diff --git a/.dockerignore b/.dockerignore index bc16e55..036eee9 100644 --- a/.dockerignore +++ b/.dockerignore @@ -18,3 +18,10 @@ __pycache__ node_modules evidence .DS_Store +.git +.env +.venv +__pycache__ +.pytest_cache +*.pyc +evidence \ No newline at end of file diff --git a/.env.example b/.env.example index 2e9f054..25b2273 100644 --- a/.env.example +++ b/.env.example @@ -11,7 +11,7 @@ SESSION_STORE=postgres CACHE_URL_FILE=/run/secrets/cache_url API_REPLICAS=2 IDEMPOTENCY_TTL_SECONDS=86400 -S3_ENDPOINT=https://s3:9000 +S3_ENDPOINT=http://s3:9000 S3_REGION=us-east-1 S3_BUCKET=messenger-attachments S3_ACCESS_KEY_ID_FILE=/run/secrets/s3_access_key_id @@ -23,19 +23,8 @@ WORKER_CONCURRENCY=2 JOB_MAX_ATTEMPTS=5 JOB_TIMEOUT_SECONDS=60 STAGING_RETENTION_SECONDS=86400 -OTEL_SERVICE_NAME=messenger-api -# Worker must set a distinct service.name. -OTEL_EXPORTER_OTLP_ENDPOINT=https://otel-collector:4318 -OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf -OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=lab -# TLS and OpenBao: actual paths/ports depend on your implemented trust matrix. -PUBLIC_BASE_URL=https://localhost:8443 -TLS_CA_FILE=/run/secrets/ca.crt -TLS_CERT_FILE=/run/secrets/service.crt -TLS_KEY_FILE=/run/secrets/service.key -BAO_ADDR=https://openbao:8200 -BAO_CACERT=/run/secrets/bao-ca.crt -# No root token here. Bootstrap operator -> short-lived service auth -> scoped token. -ARGON2_MEMORY_KIB=19456 -ARGON2_ITERATIONS=2 -ARGON2_PARALLELISM=1 +RABBITMQ_USER=messenger +RABBITMQ_PASSWORD=CHANGE_ME_RABBITMQ +RABBITMQ_QUEUE=image_jobs +IMAGE_MAX_ATTEMPTS=5 +GRAFANA_ADMIN_PASSWORD=replace_me diff --git a/.gitignore b/.gitignore index b5a7189..99dd0e9 100644 --- a/.gitignore +++ b/.gitignore @@ -30,3 +30,17 @@ coverage/ .vscode/ # Keep small, sanitized evidence summaries in evidence/ under version control. # Inspect git diff --cached: ignore rules are not a secret scanner. +.env +.venv/ +__pycache__/ +*.pyc +evidence/*.tmp + +# Local certificate-rotation backups +compose.before-*-cert-rotation.yaml + +# Local configuration and source backups +*.before-* +*.bak +*.backup +*.old diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..14c621c --- /dev/null +++ b/Dockerfile @@ -0,0 +1,17 @@ +FROM python:3.12-slim + +WORKDIR /app + +COPY requirements.txt . + +RUN pip install --no-cache-dir -r requirements.txt + +COPY src/ ./src/ +COPY migrations/ ./migrations/ + +ENV HOST=127.0.0.1 +ENV PORT=8080 + +EXPOSE 8080 + +CMD ["uvicorn", "src.main:app", "--host", "127.0.0.1", "--port", "8080", "--workers", "1"] diff --git a/REPORT.md b/REPORT.md index 9801db4..56f52d9 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,37 +1,221 @@ # Отчёт — лабораторная 7 -- Автор, группа: TODO -- Целевая оценка; выбранный трек 5, если нужен: TODO -- Commit/PR: TODO после публикации -- Использованные источники, библиотеки и помощь ИИ: TODO +- Автор, группа: Матвиенко Павел, БПИ2304 +- Целевая оценка; выбранный трек: **3 — работающий минимум; исследовательский трек не требуется** +- Commit/PR: +- Использованные источники, библиотеки и инструменты: документация Python, FastAPI, Docker Compose, PostgreSQL, RabbitMQ, RustFS, Nginx, HAProxy, OpenBao, OpenTelemetry, Grafana; материалы OWASP по хранению паролей и контролю доступа. ## Запуск из чистого clone -TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. +Стенд реализован с использованием Docker Compose и Python 3.12. Разработка и тестирование выполнялись в Ubuntu WSL на Windows с установленным Docker Desktop. + +Основные компоненты: Nginx 1.29, HAProxy 3.2, PostgreSQL 16, RabbitMQ 4.1.8, RustFS 1.0.3, OpenBao 2.7.3, OpenTelemetry Collector 0.136.0, Tempo 2.8.2, Loki 3.5.5, Prometheus 3.5.0 и Grafana 12.1.1. + +Для развёртывания необходимы Docker Desktop с поддержкой Docker Compose, Python 3.9 или новее, OpenSSL и Git. + +Клонирование проекта: + +```bash +git clone https://gitea.privcloud.tech/allerg1q/mtusi2026lab7.git +cd mtusi2026lab7 +``` + +Первоначальная подготовка окружения: + +```bash +cp .env.example .env +``` + +В `.env` необходимо настроить параметры приложения и сервисов под локальный стенд. Пароли, токены и закрытые ключи не должны храниться в Git. + +Для подготовки локальной PKI, сертификатов, сервисных credentials и OpenBao предусмотрены скрипты в `scripts/`: + +- `bootstrap-pki.sh` — создание инфраструктуры сертификатов; +- `bootstrap-postgres-tls.sh` — TLS для PostgreSQL; +- `bootstrap-rustfs-tls.sh` — TLS для объектного хранилища; +- `bootstrap-openbao-tls.sh` и `bootstrap-openbao-client-certs.sh` — сертификаты OpenBao и клиентов; +- `bootstrap-db-credentials.py`, `bootstrap-rabbitmq-credentials.py`, `bootstrap-rustfs-credentials.py` — подготовка сервисных учётных данных; +- `bootstrap-openbao-secrets.py` — подготовка секретов; +- `issue-openbao-bootstrap.py` и `configure-openbao-cert-auth.py` — настройка служебной аутентификации OpenBao. + +Приватные ключи и операторские credentials создаются и хранятся локально вне репозитория. Инициализация и распечатывание хранилища OpenBao выполняются оператором; root token и unseal keys не предоставляются приложению. Точный порядок первоначального bootstrap определяется зависимостями скриптов и должен соблюдаться перед первым запуском. + +Проверка конфигурации: + +```bash +docker compose --env-file .env config --quiet +``` + +Сборка и запуск: + +```bash +docker compose --env-file .env up -d --build +``` + +Миграции базы данных выполняются отдельным сервисом `migrate`, присутствующим в Docker Compose. После запуска необходимо проверить состояние сервисов: + +```bash +docker compose ps +``` + +Проверка HTTPS и бизнес-API с использованием доверенного CA: + +```bash +make test BASE_URL=https://localhost:8443 CA_FILE=/absolute/path/to/ca.crt +make test-security BASE_URL=https://localhost:8443 CA_FILE=/absolute/path/to/ca.crt +``` + +Проверка сохранности данных: + +```bash +make test-persistence BASE_URL=https://localhost:8443 CA_FILE=/absolute/path/to/ca.crt ACTION_SCRIPT=scripts/restart.sh +``` + +Проверка отказа API-реплики: + +```bash +make test-failover BASE_URL=https://localhost:8443 CA_FILE=/absolute/path/to/ca.crt ACTION_SCRIPT=scripts/stop-one.sh +``` + +После failover-теста остановленную реплику необходимо восстановить вместе с её mTLS-sidecar. + +Штатная остановка без удаления данных: + +```bash +docker compose stop +``` + +Намеренное удаление учебного стенда вместе с постоянными volumes: + +```bash +docker compose down -v +``` + +Последняя команда уничтожает данные Docker volumes и предназначена исключительно для осознанного сброса учебного окружения. Она не используется при обычном перезапуске. ## Архитектура и решения -TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab6, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. +В лабораторную №7 перенесены основные функции мессенджера из предыдущих лабораторных работ: пользователи, сессии, чаты, сообщения, идемпотентность запросов, вложения, миниатюры изображений и фоновая обработка задач. + +Основное изменение — защита внешних и внутренних границ доверия. + +Схема взаимодействия компонентов: + +```text +Клиент + | + | HTTPS :8443 + v +Nginx (LB) + | + | mTLS + +------> HAProxy-sidecar ------> API1 + | + +------> HAProxy-sidecar ------> API2 + | + +-----------+-----------+ + | | | + PostgreSQL RustFS RabbitMQ + | | + Данные API Worker / + Dispatcher + +API / Worker + | + +------> OpenBao (TLS, scoped credentials) + | + +------> OpenTelemetry Collector (TLS) + | + +------> Tempo (mTLS) + | + +------> Loki (HTTPS) + | + +------> Prometheus (metrics) +``` + +Публичная точка входа — `https://localhost:8443`. Nginx обеспечивает HTTPS и распределение запросов между двумя API-репликами. Внутреннее соединение от балансировщика защищено обязательным mTLS. HAProxy-sidecar каждой реплики использует её сетевое пространство; прямые порты API на хост не опубликованы. + +Пароли пользователей хранятся с использованием Argon2id. Аутентификация основана на сессиях, пользовательская идентичность определяется сервером, а доступ к чатам и вложениям контролируется ACL. Для запросов входа предусмотрен rate limiting. + +PostgreSQL выступает основным источником истины для структурированных данных приложения. RustFS хранит файлы и объекты, RabbitMQ используется для асинхронной обработки. Идемпотентность запросов и сохранение подтверждённых операций обеспечиваются механизмами приложения, перенесёнными из предыдущих лабораторных. + +OpenBao используется в режиме с постоянным хранением для выдачи и контроля сервисных секретов. Доступ ограничивается сервисными политиками. Операторские credentials отделены от учётных данных приложения. + +API1, API2, worker и dispatcher запускаются под UID 1000 с удалёнными Linux capabilities. Для API и worker задан лимит памяти 512 MiB, для dispatcher — 256 MiB. Контейнеры не используют privileged-режим и не подключают Docker socket. + +Для наблюдаемости настроена отправка логов и трассировок через OpenTelemetry Collector. Канал Collector → Tempo защищён mTLS с клиентским сертификатом, канал Collector → Loki — HTTPS с проверкой CA и SAN. + +Основные параметры приложения определяются переменными `.env`, документированными в `.env.example`. Переменные для подключения к DB, S3 и broker предусматривают использование отдельных файлов с credentials, а не размещение секретных значений в исходном коде. + +Границы доверия и остаточные ограничения описаны в `contracts/trust-matrix.md`, модель угроз — в `security/THREAT_MODEL.md`. ## Доказательства критериев | Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | | --- | --- | --- | --- | -| Публичный smoke | make test | TODO | TODO | -| Остальные пункты уровня 3 | TODO | TODO | TODO | -| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | -| Выбранный трек 5, если заявлен | TODO | TODO | TODO | +| Проверка структуры и контракта | `make check` | PASS, код завершения 0 | `evidence/final-contract.txt` | +| Публичный smoke по HTTPS | `make test` с доверенным CA | PASS, полный публичный API-сценарий | `evidence/final-smoke.txt` | +| Проверка внешнего TLS | `make test-security` с CA | PASS, доверенный CA принимается, недоверенный отклоняется | `evidence/final-security.txt` | +| Обязательное mTLS LB → API | `scripts/test-mtls.sh`, отрицательные тесты | 7 PASS, 0 FAIL | `evidence/mtls-negative-tests.txt` | +| Argon2id и обоснование параметров | `scripts/benchmark_argon2.py` | Измерены три конфигурации Argon2id | `evidence/argon2-benchmark.txt` | +| Ограничение частоты входа | `scripts/test-login-rate-limit.py` | PASS, 0 FAIL | `evidence/login-rate-limit-tests.txt` | +| Разграничение доступа PostgreSQL | `scripts/test-db-acl.py` | 25 PASS, 0 FAIL | `evidence/postgres-acl-tests.txt` | +| Разграничение доступа RabbitMQ | `scripts/test-rabbitmq-acl.py` | 4 PASS, 0 FAIL | `evidence/rabbitmq-acl-tests.txt` | +| Разграничение доступа RustFS | `scripts/test-rustfs-acl.py` | 17 PASS, 0 FAIL | `evidence/rustfs-acl-tests.txt` | +| Сервисная аутентификация и политики OpenBao | Тесты `scripts/test-openbao-*` | Выполнялись проверки доступа, запрещённых операций и lifecycle credentials | `evidence/openbao-*` | +| TLS PostgreSQL | Проверка конфигурации PostgreSQL | Результаты сохранены | `evidence/postgres-tls-config.txt` | +| Collector → Tempo | Передача тестовой трассировки и негативные TLS-тесты | Трассировка получена, без сертификата и с чужим CA — отказ | Результаты проверки OTLP/mTLS | +| Collector → Loki | Передача и чтение тестового лога | PASS, проверенный HTTPS | Результаты проверки OTLP/HTTPS | +| Ограничение привилегий приложения | Аудит Docker Compose | UID 1000, `cap_drop: ALL`, лимиты памяти | `compose.yaml` | +| Persistence | `make test-persistence` | PASS, данные и сессия сохранены | `evidence/final-persistence.txt` | +| Failover | `make test-failover` | PASS, восстановление за 1,119 с | `evidence/final-failover.txt` | -TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. +Для внутреннего TLS отдельно проверялись отсутствие клиентского сертификата, использование недоверенного CA и успешное соединение с разрешённой идентичностью. + +Измерения Argon2id на учебном стенде: + +| Конфигурация | Память | t | p | Медиана | +| --- | --- | --- | --- | --- | +| Базовая | 19 MiB | 2 | 1 | 13,21 мс | +| Усиленная | 32 MiB | 3 | 1 | 46,17 мс | +| С повышенным потреблением памяти | 64 MiB | 3 | 1 | 101,44 мс | + +Базовая конфигурация соответствует минимальным параметрам задания. Более высокие параметры увеличивают стоимость вычисления хеша и нагрузку на сервер при одновременных попытках входа. Выбор окончательной конфигурации должен учитывать измеренную производительность и защиту от дорогостоящего login DoS. ## Эксперименты и отказы -TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. +Проводились функциональные испытания HTTPS, проверка сохранности данных после перезапуска и испытание отказа одной API-реплики. + +Тестирование выполнялось на локальном стенде Docker Compose в WSL. Использовались две API-реплики, PostgreSQL, RabbitMQ, RustFS и необходимые сервисы безопасности. + +Для failover применялся сценарий из `tests/resilience.py`, выполняющий записи сообщений при остановке одной реплики. Испытание проверяло восстановление доступности, сохранность подтверждённых сообщений и отсутствие нарушения действующей сессии. | Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | | --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | +| HTTPS-запрос с недоверенным CA | Отказ проверки сертификата | PASS, соединение отклонено | Не применимо | +| Подключение к mTLS без разрешённого сертификата | Отказ аутентификации | Отрицательные проверки пройдены | Не применимо | +| Перезапуск API и зависимых хранилищ | Сохранение данных и сессии | PASS, подтверждённые данные и сессия сохранились | Потеря подтверждённых данных не обнаружена | +| Остановка одной API-реплики | Продолжение работы через оставшуюся реплику | PASS, 72 успешные записи, 3 неуспешные попытки | 1,119 с до восстановления записи; потеря подтверждённых данных не обнаружена | +| Подключение к Tempo без клиентского сертификата | Отказ | `certificate required` | Не применимо | +| Подключение к Tempo с сертификатом чужого CA | Отказ | `unknown ca` | Не применимо | +| Передача логов в Loki через HTTPS | Успешная доставка и чтение | PASS, запись найдена в Loki | После повторного запроса | + +В тесте отказа наблюдались две API-реплики до остановки одной из них. При переключении зафиксированы 72 успешные записи и 3 неуспешные попытки. Время восстановления составило 1,119 секунды, что меньше предусмотренного тестом предела в 10 секунд. + +Проверка persistence завершилась успешно: после перезапуска PostgreSQL, RabbitMQ и RustFS, восстановления API и mTLS-sidecar подтверждённые данные и прежняя сессия сохранились. + +Показатели RPS и p50/p95/p99 для отдельного нагрузочного теста не заявляются, поскольку соответствующий итоговый нагрузочный прогон и его статистика не представлены. Измерения Argon2id приведены отдельно. Результаты устойчивости относятся к одному локальному учебному стенду и не являются гарантией поведения при отказе всего хоста. ## Ограничения и следующие шаги -TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. +Полученные результаты подтверждают работоспособность публичного API через HTTPS, обязательного mTLS на внутренней границе LB → API, разграничение прав для зависимостей и сохранность данных при проверенных сценариях перезапуска и отказа одной API-реплики. + +При этом тест отказа API не означает отказоустойчивость PostgreSQL, RabbitMQ, RustFS или Docker-хоста. Остановка этих компонентов может приводить к ограничению доступности отдельных операций. + +Соединения Grafana → Prometheus, Grafana → Tempo и Prometheus → Collector переведены на HTTPS с использованием Lab7 CA. Проверены авторизованные запросы Grafana API, получение метрик Prometheus и доступность Tempo. Collector имеет статус UP=1. Административный интерфейс Grafana также доступен по HTTPS. + +Ручная первоначальная инициализация OpenBao допускается в учебном стенде, но требует правильного хранения операторских unseal credentials. Окончательное соответствие правилам хранения секретов требует проверки всех файлов, добавляемых в Git. + +Возможные дальнейшие улучшения: автоматизация восстановления после отказа, дополнительные негативные TLS-тесты, проверка административного доступа RustFS и анализ устойчивости под нагрузкой. Эти улучшения не заявляются как выполненные. + +**Заключение:** реализованы основные механизмы безопасности лабораторной №7 и получены положительные результаты ключевых функциональных и отрицательных проверок. Перед окончательной сдачей необходимо завершить аудит оставшихся административных границ доверия и проверить содержимое репозитория на наличие секретов. diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 0000000..daf9a22 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,503 @@ +services: + openbao: + image: openbao/openbao:2.7.3 + command: + - server + - -config=/openbao/config/openbao.hcl + environment: + BAO_ADDR: https://127.0.0.1:8200 + BAO_CACERT: /openbao/tls/ca.crt + ports: + - 127.0.0.1:8200:8200 + volumes: + - openbao_data:/openbao/data + - ./security/openbao/openbao.hcl:/openbao/config/openbao.hcl:ro + - ${LAB7_PKI_DIR:?Set LAB7_PKI_DIR}/openbao.crt:/openbao/tls/openbao.crt:ro + - ${LAB7_PKI_DIR:?Set LAB7_PKI_DIR}/openbao.key:/openbao/tls/openbao.key:ro + - ${LAB7_PKI_DIR:?Set LAB7_PKI_DIR}/ca.crt:/openbao/tls/ca.crt:ro + restart: unless-stopped + prometheus: + image: prom/prometheus:v3.5.0 + command: + - --config.file=/etc/prometheus/prometheus.yml + - --storage.tsdb.path=/prometheus + - --storage.tsdb.retention.time=7d + - --web.config.file=/etc/prometheus/web.yml + volumes: + - ${HOME}/.local/share/mtusi2026lab7/pki/ca.crt:/etc/prometheus/lab7-ca.crt:ro + - ./observability/prometheus.yaml:/etc/prometheus/prometheus.yml:ro + - prometheus_data:/prometheus + - ${HOME}/.local/share/mtusi2026lab7/pki/telemetry/prometheus/server.crt:/run/prometheus/server.crt:ro + - ${HOME}/.local/share/mtusi2026lab7/pki/telemetry/prometheus/server.key:/run/prometheus/server.key:ro + - ./observability/prometheus-web.yaml:/etc/prometheus/web.yml:ro + ports: + - 127.0.0.1:9090:9090 + restart: unless-stopped + loki: + image: grafana/loki:3.5.5 + command: + - -config.file=/etc/loki/local-config.yaml + volumes: + - /home/user/.local/share/mtusi2026lab7/pki/telemetry/loki/server.crt:/run/loki/server.crt:ro + - /home/user/.local/share/mtusi2026lab7/pki/telemetry/loki/server.key:/run/loki/server.key:ro + - ./observability/loki.yaml:/etc/loki/local-config.yaml:ro + - loki_data:/loki + user: '0' + restart: unless-stopped + tempo: + image: grafana/tempo:2.8.2 + command: + - -config.file=/etc/tempo.yaml + volumes: + - ${LAB7_PKI_DIR:?Set LAB7_PKI_DIR}/telemetry-runtime/tempo/server.crt:/run/tempo/server.crt:ro + - ${LAB7_PKI_DIR:?Set LAB7_PKI_DIR}/telemetry-runtime/tempo/server.key:/run/tempo/server.key:ro + - ${LAB7_PKI_DIR:?Set LAB7_PKI_DIR}/telemetry-runtime/tempo/ca.crt:/run/tempo/ca.crt:ro + - ./observability/tempo.yaml:/etc/tempo.yaml:ro + - tempo_data:/var/tempo + user: 10001:10001 + restart: unless-stopped + grafana: + image: grafana/grafana:12.1.1 + environment: + GF_SECURITY_ADMIN_USER: admin + GF_SECURITY_ADMIN_PASSWORD: ${GRAFANA_ADMIN_PASSWORD:?Set GRAFANA_ADMIN_PASSWORD + in .env} + GF_USERS_ALLOW_SIGN_UP: 'false' + GF_SERVER_PROTOCOL: https + GF_SERVER_CERT_FILE: /run/grafana/server.crt + GF_SERVER_CERT_KEY: /run/grafana/server.key + GF_SERVER_ROOT_URL: https://localhost:3000/ + volumes: + - grafana_data:/var/lib/grafana + - ./observability/grafana/provisioning:/etc/grafana/provisioning:ro + - ./observability/grafana/dashboards:/var/lib/grafana/dashboards:ro + - ${HOME}/.local/share/mtusi2026lab7/pki/telemetry/grafana/server.crt:/run/grafana/server.crt:ro + - ${HOME}/.local/share/mtusi2026lab7/pki/telemetry/grafana/server.key:/run/grafana/server.key:ro + ports: + - 127.0.0.1:3000:3000 + depends_on: + - prometheus + - loki + - tempo + restart: unless-stopped + otel-collector: + image: otel/opentelemetry-collector-contrib:0.136.0 + command: + - --config=/etc/otelcol-contrib/config.yaml + volumes: + - ${LAB7_PKI_DIR:?Set LAB7_PKI_DIR}/telemetry-runtime/otel-collector-client/client.crt:/run/telemetry/client.crt:ro + - ${LAB7_PKI_DIR:?Set LAB7_PKI_DIR}/telemetry-runtime/otel-collector-client/client.key:/run/telemetry/client.key:ro + - ${LAB7_PKI_DIR:?Set LAB7_PKI_DIR}/telemetry-runtime/otel-collector/server.crt:/run/telemetry/server.crt:ro + - ${LAB7_PKI_DIR:?Set LAB7_PKI_DIR}/telemetry-runtime/otel-collector/server.key:/run/telemetry/server.key:ro + - ${LAB7_PKI_DIR:?Set LAB7_PKI_DIR}/telemetry-runtime/otel-collector/ca.crt:/run/telemetry/ca.crt:ro + - ./observability/otel-collector.yaml:/etc/otelcol-contrib/config.yaml:ro + restart: unless-stopped + healthcheck: + test: + - CMD + - /otelcol-contrib + - components + interval: 30s + timeout: 10s + retries: 3 + rabbitmq: + image: rabbitmq:4.1.8-management + hostname: rabbitmq + volumes: + - rabbitmq_data:/var/lib/rabbitmq + - ./security/rabbitmq/rabbitmq.conf:/etc/rabbitmq/rabbitmq.conf:ro + - ${LAB7_PKI_DIR:?Set LAB7_PKI_DIR}/ca.crt:/run/lab7-rabbitmq/ca.crt:ro + - ${LAB7_PKI_DIR}/rabbitmq.crt:/run/lab7-rabbitmq/rabbitmq.crt:ro + - ${LAB7_PKI_DIR}/rabbitmq-server.key:/run/lab7-rabbitmq/rabbitmq-server.key:ro + - ${LAB7_PKI_DIR:?Set LAB7_PKI_DIR}/rabbitmq-definitions.json:/run/lab7-rabbitmq/definitions.json:ro + healthcheck: + test: + - CMD + - rabbitmq-diagnostics + - -q + - ping + interval: 10s + timeout: 5s + retries: 15 + start_period: 15s + restart: unless-stopped + db: + image: postgres:16-alpine + command: + - postgres + - -c + - ssl=on + - -c + - ssl_cert_file=/etc/postgresql/tls/db.crt + - -c + - ssl_key_file=/etc/postgresql/tls/db-server.key + - -c + - ssl_min_protocol_version=TLSv1.2 + - -c + - hba_file=/etc/postgresql/pg_hba.conf + environment: + POSTGRES_DB: messenger + POSTGRES_USER: messenger + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env} + volumes: + - postgres_data:/var/lib/postgresql/data + - ${LAB7_PKI_DIR:?Set LAB7_PKI_DIR}/db.crt:/etc/postgresql/tls/db.crt:ro + - ${LAB7_PKI_DIR}/db-server.key:/etc/postgresql/tls/db-server.key:ro + - ./security/postgres/pg_hba.conf:/etc/postgresql/pg_hba.conf:ro + healthcheck: + test: + - CMD-SHELL + - pg_isready -U messenger -d messenger + interval: 5s + timeout: 3s + retries: 20 + restart: unless-stopped + minio: + image: rustfs/rustfs:1.0.3 + command: + - /data + environment: + RUSTFS_ACCESS_KEY: ${S3_ACCESS_KEY:?Set S3_ACCESS_KEY in .env} + RUSTFS_SECRET_KEY: ${S3_SECRET_KEY:?Set S3_SECRET_KEY in .env} + RUSTFS_ADDRESS: :9000 + RUSTFS_TLS_PATH: /etc/rustfs/tls + volumes: + - minio_data:/data + - ${LAB7_PKI_DIR:?Set LAB7_PKI_DIR}/rustfs-tls:/etc/rustfs/tls:ro + restart: unless-stopped + s3-init: + build: . + command: + - python + - -m + - src.s3_setup + environment: + S3_ENDPOINT: https://minio:9000 + AWS_CA_BUNDLE: /etc/ssl/lab7/ca.crt + S3_ACCESS_KEY: ${S3_ACCESS_KEY} + S3_SECRET_KEY: ${S3_SECRET_KEY} + S3_BUCKET: ${S3_BUCKET:-messenger-attachments} + depends_on: + minio: + condition: service_started + restart: 'no' + volumes: + - ${LAB7_PKI_DIR:?Set LAB7_PKI_DIR}/ca.crt:/etc/ssl/lab7/ca.crt:ro + migrate: + build: . + command: + - python + - -m + - src.migrate + environment: + DATABASE_URL: postgresql://messenger:${POSTGRES_PASSWORD}@db:5432/messenger?sslmode=verify-full&sslrootcert=/etc/ssl/lab7/ca.crt + depends_on: + db: + condition: service_healthy + restart: 'no' + volumes: + - ${LAB7_PKI_DIR:?Set LAB7_PKI_DIR}/ca.crt:/etc/ssl/lab7/ca.crt:ro + api1: + user: 1000:1000 + cap_drop: + - ALL + security_opt: + - no-new-privileges:true + mem_limit: 512m + cpus: 1.0 + pids_limit: 128 + build: . + command: + - python + - -m + - src.openbao_entrypoint + - -- + - uvicorn + - src.main:app + - --host + - 127.0.0.1 + - --port + - '8080' + - --workers + - '1' + environment: + BAO_ADDR: https://openbao:8200 + BAO_CACERT: /etc/ssl/lab7/ca.crt + BAO_CERT_FILE: /run/lab7/bao/client.crt + BAO_KEY_FILE: /run/lab7/bao/client.key + BAO_CERT_NAME: lab7-api1-next + BAO_SECRET_PATH: lab7/data/api/runtime + S3_ENDPOINT: https://minio:9000 + S3_BUCKET: ${S3_BUCKET} + AWS_CA_BUNDLE: /etc/ssl/lab7/ca.crt + OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:4320 + OTEL_SERVICE_NAME: messenger-api + OTEL_PYTHON_FASTAPI_EXCLUDED_URLS: /health/.* + IMAGE_MAX_ATTEMPTS: ${IMAGE_MAX_ATTEMPTS:-5} + SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} + depends_on: + migrate: + condition: service_completed_successfully + s3-init: + condition: service_completed_successfully + healthcheck: + test: + - CMD + - python + - -c + - import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health/ready', + timeout=3) + interval: 5s + timeout: 3s + retries: 20 + stop_grace_period: 15s + restart: unless-stopped + volumes: + - ${LAB7_PKI_DIR:?Set LAB7_PKI_DIR}/ca.crt:/etc/ssl/lab7/ca.crt:ro + - ${LAB7_PKI_DIR:?Set LAB7_PKI_DIR}/ca.crt:/etc/ssl/lab7/ca.crt:ro + - type: bind + source: ${HOME}/.local/share/mtusi2026lab7/pki/openbao-clients/rotation-api1/client.crt + target: /run/lab7/bao/client.crt + read_only: true + bind: + create_host_path: false + - type: bind + source: ${HOME}/.local/share/mtusi2026lab7/pki/openbao-clients/rotation-api1/client.key + target: /run/lab7/bao/client.key + read_only: true + bind: + create_host_path: false + api2: + user: 1000:1000 + cap_drop: + - ALL + security_opt: + - no-new-privileges:true + mem_limit: 512m + cpus: 1.0 + pids_limit: 128 + build: . + command: + - python + - -m + - src.openbao_entrypoint + - -- + - uvicorn + - src.main:app + - --host + - 127.0.0.1 + - --port + - '8080' + - --workers + - '1' + environment: + BAO_ADDR: https://openbao:8200 + BAO_CACERT: /etc/ssl/lab7/ca.crt + BAO_CERT_FILE: /run/lab7/bao/client.crt + BAO_KEY_FILE: /run/lab7/bao/client.key + BAO_CERT_NAME: lab7-api2-next + BAO_SECRET_PATH: lab7/data/api/runtime + S3_ENDPOINT: https://minio:9000 + S3_BUCKET: ${S3_BUCKET} + AWS_CA_BUNDLE: /etc/ssl/lab7/ca.crt + OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:4320 + OTEL_SERVICE_NAME: messenger-api + OTEL_PYTHON_FASTAPI_EXCLUDED_URLS: /health/.* + IMAGE_MAX_ATTEMPTS: ${IMAGE_MAX_ATTEMPTS:-5} + SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} + depends_on: + migrate: + condition: service_completed_successfully + s3-init: + condition: service_completed_successfully + healthcheck: + test: + - CMD + - python + - -c + - import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health/ready', + timeout=3) + interval: 5s + timeout: 3s + retries: 20 + stop_grace_period: 15s + restart: unless-stopped + volumes: + - ${LAB7_PKI_DIR:?Set LAB7_PKI_DIR}/ca.crt:/etc/ssl/lab7/ca.crt:ro + - ${LAB7_PKI_DIR:?Set LAB7_PKI_DIR}/ca.crt:/etc/ssl/lab7/ca.crt:ro + - type: bind + source: ${HOME}/.local/share/mtusi2026lab7/pki/openbao-clients/rotation-api2/client.crt + target: /run/lab7/bao/client.crt + read_only: true + bind: + create_host_path: false + - type: bind + source: ${HOME}/.local/share/mtusi2026lab7/pki/openbao-clients/rotation-api2/client.key + target: /run/lab7/bao/client.key + read_only: true + bind: + create_host_path: false + dispatcher: + user: 1000:1000 + cap_drop: + - ALL + security_opt: + - no-new-privileges:true + mem_limit: 256m + cpus: 0.5 + pids_limit: 64 + build: . + command: + - python + - -m + - src.dispatcher + environment: + OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:4320 + OTEL_SERVICE_NAME: messenger-dispatcher + DATABASE_URL: postgresql://messenger_dispatcher:${DISPATCHER_DB_PASSWORD:?Set + DISPATCHER_DB_PASSWORD in .env}@db:5432/messenger?sslmode=verify-full&sslrootcert=/etc/ssl/lab7/ca.crt + RABBITMQ_HOST: rabbitmq + RABBITMQ_USER: messenger_publisher + RABBITMQ_PASSWORD: ${RABBITMQ_PUBLISHER_PASSWORD:?Set RABBITMQ_PUBLISHER_PASSWORD + in .env} + RABBITMQ_QUEUE: ${RABBITMQ_QUEUE:-image_jobs} + RABBITMQ_CA_FILE: /etc/ssl/lab7/ca.crt + depends_on: + rabbitmq: + condition: service_healthy + migrate: + condition: service_completed_successfully + restart: unless-stopped + stop_grace_period: 15s + volumes: + - ${LAB7_PKI_DIR:?Set LAB7_PKI_DIR}/ca.crt:/etc/ssl/lab7/ca.crt:ro + worker: + user: 1000:1000 + cap_drop: + - ALL + security_opt: + - no-new-privileges:true + mem_limit: 512m + cpus: 1.0 + pids_limit: 128 + build: . + command: + - python + - -m + - src.openbao_entrypoint + - -- + - python + - -m + - src.worker + environment: + BAO_ADDR: https://openbao:8200 + BAO_CACERT: /etc/ssl/lab7/ca.crt + BAO_CERT_FILE: /run/lab7/bao/client.crt + BAO_KEY_FILE: /run/lab7/bao/client.key + BAO_CERT_NAME: lab7-worker-next + BAO_SECRET_PATH: lab7/data/worker/runtime + OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:4320 + OTEL_SERVICE_NAME: messenger-worker + S3_ENDPOINT: https://minio:9000 + AWS_CA_BUNDLE: /etc/ssl/lab7/ca.crt + S3_BUCKET: ${S3_BUCKET:-messenger-attachments} + RABBITMQ_HOST: rabbitmq + RABBITMQ_QUEUE: ${RABBITMQ_QUEUE:-image_jobs} + IMAGE_MAX_ATTEMPTS: ${IMAGE_MAX_ATTEMPTS:-5} + RABBITMQ_CA_FILE: /etc/ssl/lab7/ca.crt + depends_on: + rabbitmq: + condition: service_healthy + migrate: + condition: service_completed_successfully + s3-init: + condition: service_completed_successfully + restart: unless-stopped + stop_grace_period: 20s + volumes: + - ${LAB7_PKI_DIR:?Set LAB7_PKI_DIR}/ca.crt:/etc/ssl/lab7/ca.crt:ro + - ${LAB7_PKI_DIR:?Set LAB7_PKI_DIR}/ca.crt:/etc/ssl/lab7/ca.crt:ro + - type: bind + source: ${HOME}/.local/share/mtusi2026lab7/pki/openbao-clients/rotation-worker/client.crt + target: /run/lab7/bao/client.crt + read_only: true + bind: + create_host_path: false + - type: bind + source: ${HOME}/.local/share/mtusi2026lab7/pki/openbao-clients/rotation-worker/client.key + target: /run/lab7/bao/client.key + read_only: true + bind: + create_host_path: false + api1-mtls: + image: haproxy:3.2-alpine + network_mode: service:api1 + user: 1000:1000 + entrypoint: + - haproxy + command: + - -W + - -db + - -f + - /usr/local/etc/haproxy/haproxy.cfg + cap_drop: + - ALL + security_opt: + - no-new-privileges:true + volumes: + - ./security/haproxy/api1.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro + - ${LAB7_PKI_DIR:?Set LAB7_PKI_DIR}/api1.pem:/run/lab7-pki/api1.pem:ro + - ${LAB7_PKI_DIR}/ca.crt:/run/lab7-pki/ca.crt:ro + depends_on: + api1: + condition: service_healthy + restart: unless-stopped + api2-mtls: + image: haproxy:3.2-alpine + network_mode: service:api2 + user: 1000:1000 + entrypoint: + - haproxy + command: + - -W + - -db + - -f + - /usr/local/etc/haproxy/haproxy.cfg + cap_drop: + - ALL + security_opt: + - no-new-privileges:true + volumes: + - ./security/haproxy/api2.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro + - ${LAB7_PKI_DIR:?Set LAB7_PKI_DIR}/api2.pem:/run/lab7-pki/api2.pem:ro + - ${LAB7_PKI_DIR}/ca.crt:/run/lab7-pki/ca.crt:ro + depends_on: + api2: + condition: service_healthy + restart: unless-stopped + nginx: + image: nginx:1.29-alpine + ports: + - 127.0.0.1:8443:443 + volumes: + - ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro + - ${LAB7_PKI_DIR:?Set LAB7_PKI_DIR}/ca.crt:/run/lab7-pki/ca.crt:ro + - ${LAB7_PKI_DIR}/ingress.crt:/run/lab7-pki/ingress.crt:ro + - ${LAB7_PKI_DIR}/ingress.key:/run/lab7-pki/ingress.key:ro + - ${LAB7_PKI_DIR}/lb-client.crt:/run/lab7-pki/lb-client.crt:ro + - ${LAB7_PKI_DIR}/lb-client.key:/run/lab7-pki/lb-client.key:ro + depends_on: + api1-mtls: + condition: service_started + api2-mtls: + condition: service_started + restart: unless-stopped +volumes: + postgres_data: null + minio_data: null + rabbitmq_data: null + prometheus_data: null + loki_data: null + tempo_data: null + grafana_data: null + openbao_data: null diff --git a/contracts/trust-matrix.md b/contracts/trust-matrix.md index 0c2a977..e0aaf08 100644 --- a/contracts/trust-matrix.md +++ b/contracts/trust-matrix.md @@ -1,37 +1,70 @@ -# Матрица доверия — заполнить в решении lab7 +# Матрица доверия — лабораторная работа №7 -Это обязательная матрица покрытия. Для каждой строки укажите реальный порт, endpoint, CA, service identity, проверку SAN/ACL, срок жизни credentials и команду положительного/отрицательного теста. TLS шифрует и подтверждает сервер; mTLS также проверяет клиента. При доверенном CA всё равно нужно ограничивать разрешённую identity. Plaintext hop допустим только внутри закрытого локального transport/proxy boundary, без опубликованного обхода; границу и rationale нужно доказать. +## Общие правила -| Связь | Минимум на 3 | Дополнительно на 4 | Доказательство / конфиг | -| --- | --- | --- | --- | -| Клиент → ingress/LB | TLS, CA + hostname, Bearer | Проверка expiry/revocation сессии и общего login rate limit | TODO | -| LB → API (все реплики) | mTLS + allowlist LB identity | Ротация leaf без обхода проверки | TODO | -| API/worker → PostgreSQL | TLS verify-full + раздельные ограниченные DB roles | Ротация credentials; mTLS — допустимое усиление | TODO | -| API/worker → S3 | TLS + разные scoped credentials/prefix rights | Проверка denied prefix и ротация | TODO | -| API/worker → broker | TLS + разные producer/consumer identities и ACL | mTLS + ограничение допустимых SAN/ролей | TODO | -| API/worker → Collector | TLS; сеть/аутентификация запрещает произвольный ingest | mTLS с раздельными identities | TODO | -| Collector → telemetry backends | TLS + scoped backend credentials или mTLS | Ротация и проверка least privilege | TODO | -| Grafana → data sources | TLS с проверкой сервера, ограниченная identity | Отрицательные проверки доступа | TODO | -| API/worker/agent → OpenBao | TLS + сервисный auth + scoped policy | Renewal/expiry/revocation | TODO | -| Оператор → OpenBao/Grafana/S3 admin | TLS + authentication, доступ локальный/через защищённый канал | Разделение operator/application roles | TODO | -| API → Redis/Valkey, если используется | TLS + ACL/пароль с минимальными правами | Ротация; mTLS по возможности | TODO | -| Replication/кластерные каналы, если добавлены | TLS/mTLS либо подтверждённый шифрованный transport | Проверка заявленной модели отказа | TODO | +TLS обеспечивает шифрование и проверку серверного сертификата. +mTLS дополнительно требует сертификат клиента. +Проверка CA не заменяет проверку разрешённой service identity +и применение ACL. -Нет выбранного компонента — отметьте N/A с причиной, а не оставляйте пустую строку. Внутренний публичный health listener, если нужен, минимален и изолирован; через него нельзя обращаться к бизнес-API без mTLS. Отдельно задокументируйте scrape/health/bootstrap каналы: они тоже не должны создавать обход. +Основной CA стенда находится у оператора вне Git: +`~/.local/share/mtusi2026lab7/pki/ca.crt`. -## Обязательные отрицательные проверки +| Связь | Реальный endpoint | Контроль | Доказательства и статус | +|---|---|---|---| +| Клиент → Nginx | localhost:8443 | HTTPS, CA, SAN, Bearer | `final-smoke.txt`, `final-security.txt`: PASS | +| Nginx → API1/API2 | mTLS-sidecar каждой реплики | Клиентский сертификат, проверка identity; API:8080 не опубликован | `mtls-negative-tests.txt`: 7 PASS | +| API/worker → PostgreSQL | db:5432 | TLS, разделённые DB roles | `postgres-acl-tests.txt`: 25 PASS | +| API/worker → S3 | minio:9000 | TLS, scoped credentials | `rustfs-acl-tests.txt`: 17 PASS | +| API/worker → RabbitMQ | rabbitmq:5671 | TLS, ACL producer/consumer | `rabbitmq-acl-tests.txt`: 4 PASS | +| Приложения → Collector | otel-collector:4319/4320 | TLS, Lab7 CA, SAN | `observability/otel-collector.yaml`; приёмник настроен | +| Collector → Tempo | tempo:4317 | mTLS; клиент otel-collector-client | Успешное чтение трассировки, отказы без cert и с чужим CA | +| Collector → Loki | loki:3100/otlp | HTTPS, проверка CA и SAN | Сквозной тест записи и чтения лога: PASS | +| Grafana → Loki | loki:3100 | HTTPS, CA в datasource | Настроено; отдельно проверить datasource | +| Grafana → Prometheus | prometheus:9090 | HTTPS, Lab7 CA, проверка сертификата | PASS: datasource API, Prometheus query | +| Grafana → Tempo API | tempo:3200 | HTTPS, Lab7 CA, проверка сертификата | PASS: datasource API, Tempo /ready | +| Prometheus → Collector | otel-collector:8889 | HTTPS, Lab7 CA, проверка имени otel-collector | PASS: Collector UP=1 через Grafana/Prometheus | +| API/worker → OpenBao | openbao:8200 | TLS, scoped service auth и policy | `evidence/openbao-*` | +| Оператор → OpenBao | localhost:8200 | TLS и operator auth | `openbao-operator-security-audit.txt` | +| Оператор → Grafana | localhost:3000 | HTTPS, Lab7 CA, Basic Auth администратора | PASS: авторизованные запросы к Grafana API | +| Оператор → S3 admin | RustFS admin endpoint | TLS, отдельные административные права | Проверить фактический административный доступ | +| Redis/Valkey | N/A | Компонент отсутствует в Compose | Не используется | +| Репликация БД | N/A | Отдельный кластер PostgreSQL не заявлен | Не используется | -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 и эксплуатация +- Внешний HTTPS: недоверенный CA отклоняется. +- LB → API: проверка отсутствующего или неправильного client certificate, + чужого CA и запрещённой identity. +- Посторонний пользователь не должен читать чужие сообщения или вложения. +- OpenBao policy запрещает неразрешённые paths и операции. +- PostgreSQL, RabbitMQ и RustFS используют разграничение прав. +- Tempo требует client certificate: без него ошибка + `certificate required`, с недоверенным CA — `unknown ca`. +- После отзыва credentials новое соединение должно получать отказ. -В репозитории только открытые конфиги, policy templates и scripts. CA private key, leaf keys, root token, unseal shares и SecretID не коммитятся, не запекаются в образ и не печатаются в отчёте. Для локального стенда оператор создаёт их вне Git и передаёт через files/secrets с ограниченными правами. Опишите, кто имеет доступ к CA/unseal, что нужно после рестарта OpenBao и как восстановить работу. +## Credentials и эксплуатация -OpenBao не использует dev-mode. Выберите persistent storage и auth метод (например AppRole с короткоживущим SecretID/response wrapping, cert auth или иная обоснованная identity). Не подменяйте root token постоянной переменной BAO_TOKEN в приложении. Рабочие tokens имеют policy, TTL и renewal/re-auth сценарий. Статические KV secrets на 3 допустимы при реальном чтении через сервисную identity; динамические DB credentials — хорошее расширение, но не обязательное название технологии. +Сервисные credentials должны иметь ограниченный scope и TTL. +Точные значения TTL и разрешённые SAN необходимо сверять с +фактическими PKI/OpenBao policy и конфигурацией сервисов, +а не подставлять предполагаемые значения. -Разрешённый компромисс учебного стенда: ручной operator init/unseal, если он безопасно документирован и не нужен при каждом обычном рестарте API. Автоматическое хранение всех unseal shares рядом с OpenBao без защиты не считается решённым bootstrap. +CA private key, leaf private keys, root token, unseal shares и +SecretID не должны коммититься, попадать в контейнерные образы +или журналы. + +Persistent volumes сохраняются при штатных перезапусках. +Подтверждающие тесты: + +- `evidence/final-persistence.txt` +- `evidence/final-failover.txt` + +## Незакрытые пункты + +Ранее отмеченные HTTP-каналы Grafana → Prometheus, +Grafana → Tempo и Prometheus → Collector переведены на HTTPS. +Работоспособность подтверждена запросами Grafana API и +метрикой Collector UP=1. Для полного аудита остаётся +проверить остальные административные границы, включая +RustFS, и отсутствие секретов в Git. diff --git a/evidence/argon2-benchmark.txt b/evidence/argon2-benchmark.txt new file mode 100644 index 0000000..dccdf55 --- /dev/null +++ b/evidence/argon2-benchmark.txt @@ -0,0 +1,3 @@ +baseline: memory=19456 KiB, t=2, p=1, median=13.21 ms, min=12.66 ms, max=14.40 ms +stronger: memory=32768 KiB, t=3, p=1, median=46.17 ms, min=45.01 ms, max=63.33 ms +high-memory: memory=65536 KiB, t=3, p=1, median=101.44 ms, min=97.04 ms, max=107.90 ms diff --git a/evidence/final-contract.txt b/evidence/final-contract.txt new file mode 100644 index 0000000..9a55330 --- /dev/null +++ b/evidence/final-contract.txt @@ -0,0 +1,2 @@ +python3 scripts/check_contract.py +PASS: offline skeleton structure, local refs and Python syntax; application NOT tested. diff --git a/evidence/final-failover.txt b/evidence/final-failover.txt new file mode 100644 index 0000000..d478f03 --- /dev/null +++ b/evidence/final-failover.txt @@ -0,0 +1,4 @@ +python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "https://localhost:8443" --ca-file "/home/user/.local/share/mtusi2026lab7/pki/ca.crt" +Executing explicit failover hook; hook output suppressed to avoid leaking secrets. +{"observed_instances_before": 2, "successful_writes": 72, "failed_attempts": 3, "first_recovery_seconds": 1.119} +PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence. diff --git a/evidence/final-persistence.txt b/evidence/final-persistence.txt new file mode 100644 index 0000000..d0ada58 --- /dev/null +++ b/evidence/final-persistence.txt @@ -0,0 +1,3 @@ +python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "https://localhost:8443" --ca-file "/home/user/.local/share/mtusi2026lab7/pki/ca.crt" +Executing explicit persistence hook; hook output suppressed to avoid leaking secrets. +PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence. diff --git a/evidence/final-security.txt b/evidence/final-security.txt new file mode 100644 index 0000000..acd2600 --- /dev/null +++ b/evidence/final-security.txt @@ -0,0 +1,2 @@ +python3 tests/security.py --base-url "https://localhost:8443" --ca-file "/home/user/.local/share/mtusi2026lab7/pki/ca.crt" +PASS: trusted HTTPS works; untrusted CA rejected. This does NOT verify internal mTLS, OpenBao or hardening. diff --git a/evidence/final-smoke.txt b/evidence/final-smoke.txt new file mode 100644 index 0000000..9d32888 --- /dev/null +++ b/evidence/final-smoke.txt @@ -0,0 +1,2 @@ +python3 tests/smoke.py --base-url "https://localhost:8443" --ca-file "/home/user/.local/share/mtusi2026lab7/pki/ca.crt" +PASS: lab7 public API scenario; infrastructure and grading evidence remain separate. diff --git a/evidence/https-security-tests.txt b/evidence/https-security-tests.txt new file mode 100644 index 0000000..ff2e222 --- /dev/null +++ b/evidence/https-security-tests.txt @@ -0,0 +1 @@ +PASS: trusted HTTPS works; untrusted CA rejected. This does NOT verify internal mTLS, OpenBao or hardening. diff --git a/evidence/https-smoke-tests.txt b/evidence/https-smoke-tests.txt new file mode 100644 index 0000000..b484213 --- /dev/null +++ b/evidence/https-smoke-tests.txt @@ -0,0 +1 @@ +PASS: lab7 public API scenario; infrastructure and grading evidence remain separate. diff --git a/evidence/https-tls-tests.txt b/evidence/https-tls-tests.txt new file mode 100644 index 0000000..6bf2c6a --- /dev/null +++ b/evidence/https-tls-tests.txt @@ -0,0 +1,8 @@ +PASS: Trusted CA and correct hostname + curl exit code: 0 + HTTP status: 200 +PASS: Untrusted CA + curl exit code: 60 +PASS: Wrong hostname + curl exit code: 60 +PASS: HTTPS certificate verification diff --git a/evidence/login-rate-limit-tests.txt b/evidence/login-rate-limit-tests.txt new file mode 100644 index 0000000..58e5c40 --- /dev/null +++ b/evidence/login-rate-limit-tests.txt @@ -0,0 +1,8 @@ +Testing rate limit with username: rl_2d31d8ed431a4b75 +Attempt 1: HTTP 401, Retry-After=None +Attempt 2: HTTP 401, Retry-After=None +Attempt 3: HTTP 401, Retry-After=None +Attempt 4: HTTP 401, Retry-After=None +Attempt 5: HTTP 401, Retry-After=None +Attempt 6: HTTP 429, Retry-After=60 +PASS: shared login rate limit and Retry-After diff --git a/evidence/mtls-negative-tests.txt b/evidence/mtls-negative-tests.txt new file mode 100644 index 0000000..4fc6768 --- /dev/null +++ b/evidence/mtls-negative-tests.txt @@ -0,0 +1,24 @@ + +=== Testing api1 mTLS === +[1] Authorized LB certificate +{"status":"ok"} +[2] No client certificate +PASS: no certificate rejected +[3] Untrusted CA certificate +PASS: rogue CA rejected +[4] Trusted CA, forbidden SAN +HTTP 403 +PASS: api1 mTLS identity enforcement + +=== Testing api2 mTLS === +[1] Authorized LB certificate +{"status":"ok"} +[2] No client certificate +PASS: no certificate rejected +[3] Untrusted CA certificate +PASS: rogue CA rejected +[4] Trusted CA, forbidden SAN +HTTP 403 +PASS: api2 mTLS identity enforcement + +PASS: all mTLS tests passed diff --git a/evidence/openbao-active-token-audit.txt b/evidence/openbao-active-token-audit.txt new file mode 100644 index 0000000..546f578 --- /dev/null +++ b/evidence/openbao-active-token-audit.txt @@ -0,0 +1,12 @@ +INFO: active token accessors: 1 +INFO: root tokens: 1 +INFO: certificate-auth tokens: 0 +INFO: other tokens: 0 +INFO: certificate tokens with API policy: 0 +INFO: certificate tokens with worker policy: 0 +INFO: certificate tokens older than 3600 seconds: 0 +INFO: certificate tokens with nonpositive TTL: 0 +INFO: tokens expired during audit: 0 +INFO: lookup errors: 0 +PASS: token accessor inventory completed +PASS: no certificate-auth tokens older than 3600 seconds found diff --git a/evidence/openbao-api1-rotation-auth.txt b/evidence/openbao-api1-rotation-auth.txt new file mode 100644 index 0000000..7befc52 --- /dev/null +++ b/evidence/openbao-api1-rotation-auth.txt @@ -0,0 +1,2 @@ +PASS: runtime credentials loaded from OpenBao +PASS: rotated API1 certificate authenticated diff --git a/evidence/openbao-api1-rotation-config.txt b/evidence/openbao-api1-rotation-config.txt new file mode 100644 index 0000000..96b730b --- /dev/null +++ b/evidence/openbao-api1-rotation-config.txt @@ -0,0 +1,5 @@ +PASS: Replacement identity configured +PASS: Replacement certificate configured +PASS: Replacement key configured +PASS: Certificate mounted read-only +PASS: Key mounted read-only diff --git a/evidence/openbao-api2-rotation-auth.txt b/evidence/openbao-api2-rotation-auth.txt new file mode 100644 index 0000000..fe85829 --- /dev/null +++ b/evidence/openbao-api2-rotation-auth.txt @@ -0,0 +1,2 @@ +PASS: runtime credentials loaded from OpenBao +PASS: rotated API2 certificate authenticated diff --git a/evidence/openbao-api2-rotation-config.txt b/evidence/openbao-api2-rotation-config.txt new file mode 100644 index 0000000..1dad6fd --- /dev/null +++ b/evidence/openbao-api2-rotation-config.txt @@ -0,0 +1,7 @@ +PASS: Replacement API2 identity configured +PASS: Replacement certificate configured +PASS: Replacement private key configured +PASS: Certificate mounted read-only +PASS: Private key mounted read-only +PASS: API1 rotated identity preserved +PASS: Worker identity unchanged diff --git a/evidence/openbao-approle-acl-tests.txt b/evidence/openbao-approle-acl-tests.txt new file mode 100644 index 0000000..f91a431 --- /dev/null +++ b/evidence/openbao-approle-acl-tests.txt @@ -0,0 +1,17 @@ +OpenBao HTTPS: https://localhost:8200/v1 +TLS verification: enabled +PASS: temporary KV v2 secrets prepared +PASS: api: scoped token issued with limited TTL +PASS: api: SecretID reuse denied +PASS: worker: scoped token issued with limited TTL +PASS: worker: SecretID reuse denied +PASS: api: own secret read allowed +PASS: worker: own secret read allowed +PASS: API cannot read worker secrets +PASS: worker cannot read API secrets +PASS: api: secret modification denied +PASS: worker: secret modification denied +PASS: api: policy administration denied +PASS: worker: policy administration denied +PASS: all OpenBao AppRole ACL tests passed +OpenBao test cleanup attempted diff --git a/evidence/openbao-cert-auth-acl-tests.txt b/evidence/openbao-cert-auth-acl-tests.txt new file mode 100644 index 0000000..0ec0f6c --- /dev/null +++ b/evidence/openbao-cert-auth-acl-tests.txt @@ -0,0 +1,24 @@ +=== api1 === +PASS: certificate authentication successful +PASS: only scoped service policy assigned +PASS: own KV v2 secret readable +PASS: cross-service KV read denied +PASS: KV modification denied +PASS: temporary token revoked +=== api2 === +PASS: certificate authentication successful +PASS: only scoped service policy assigned +PASS: own KV v2 secret readable +PASS: cross-service KV read denied +PASS: KV modification denied +PASS: temporary token revoked +=== worker === +PASS: certificate authentication successful +PASS: only scoped service policy assigned +PASS: own KV v2 secret readable +PASS: cross-service KV read denied +PASS: KV modification denied +PASS: temporary token revoked +PASS: three certificate identities verified +PASS: scoped OpenBao certificate ACL tests completed +PASS: no secret values or tokens printed diff --git a/evidence/openbao-cert-client-tests.txt b/evidence/openbao-cert-client-tests.txt new file mode 100644 index 0000000..7016fc8 --- /dev/null +++ b/evidence/openbao-cert-client-tests.txt @@ -0,0 +1,17 @@ +=== api1 === +PASS: certificate authentication and KV retrieval +PASS: expected number of secret fields received +PASS: no secret values printed +PASS: api1 certificate bootstrap verified +=== api2 === +PASS: certificate authentication and KV retrieval +PASS: expected number of secret fields received +PASS: no secret values printed +PASS: api2 certificate bootstrap verified +=== worker === +PASS: certificate authentication and KV retrieval +PASS: expected number of secret fields received +PASS: no secret values printed +PASS: worker certificate bootstrap verified +PASS: three certificate bootstrap tests completed +PASS: running application containers unchanged diff --git a/evidence/openbao-cert-entrypoint-tests.txt b/evidence/openbao-cert-entrypoint-tests.txt new file mode 100644 index 0000000..1312142 --- /dev/null +++ b/evidence/openbao-cert-entrypoint-tests.txt @@ -0,0 +1,15 @@ +=== api1 === +PASS: runtime credentials loaded from OpenBao +PASS: child process received runtime credentials +PASS: api1 certificate entrypoint verified +=== api2 === +PASS: runtime credentials loaded from OpenBao +PASS: child process received runtime credentials +PASS: api2 certificate entrypoint verified +=== worker === +PASS: runtime credentials loaded from OpenBao +PASS: child process received runtime credentials +PASS: worker certificate entrypoint verified +PASS: three certificate entrypoint tests completed +PASS: running containers unchanged +PASS: no secret values or tokens printed diff --git a/evidence/openbao-cert-identity-tests.txt b/evidence/openbao-cert-identity-tests.txt new file mode 100644 index 0000000..00c7d52 --- /dev/null +++ b/evidence/openbao-cert-identity-tests.txt @@ -0,0 +1,5 @@ +PASS: api1 cannot authenticate as lab7-worker +PASS: api2 cannot authenticate as lab7-api1 +PASS: worker cannot authenticate as lab7-api2 +PASS: all certificate identity substitutions rejected +PASS: no credentials or tokens printed diff --git a/evidence/openbao-certificate-identity-audit.txt b/evidence/openbao-certificate-identity-audit.txt new file mode 100644 index 0000000..0d81e21 --- /dev/null +++ b/evidence/openbao-certificate-identity-audit.txt @@ -0,0 +1,6 @@ +PASS: All replacement identities registered +PASS: Old identities absent +PASS: No unexpected certificate identities +INFO: registered identity: lab7-api1-next +INFO: registered identity: lab7-api2-next +INFO: registered identity: lab7-worker-next diff --git a/evidence/openbao-client-bootstrap-tests.txt b/evidence/openbao-client-bootstrap-tests.txt new file mode 100644 index 0000000..9641ecf --- /dev/null +++ b/evidence/openbao-client-bootstrap-tests.txt @@ -0,0 +1,23 @@ +=== api1 === +PASS: AppRole authentication completed +PASS: runtime secrets match service credentials +PASS: scoped KV v2 secret loaded +PASS: no secret values printed +PASS: api1 bootstrap verified +PASS: consumed SecretID already absent +=== api2 === +PASS: AppRole authentication completed +PASS: runtime secrets match service credentials +PASS: scoped KV v2 secret loaded +PASS: no secret values printed +PASS: api2 bootstrap verified +PASS: consumed SecretID already absent +=== worker === +PASS: AppRole authentication completed +PASS: runtime secrets match service credentials +PASS: scoped KV v2 secret loaded +PASS: no secret values printed +PASS: worker bootstrap verified +PASS: consumed SecretID already absent +PASS: three independent bootstrap tests completed +PASS: temporary credential files removed diff --git a/evidence/openbao-entrypoint-api2-tests.txt b/evidence/openbao-entrypoint-api2-tests.txt new file mode 100644 index 0000000..df5ac8a --- /dev/null +++ b/evidence/openbao-entrypoint-api2-tests.txt @@ -0,0 +1,6 @@ +PASS: temporary api2 SecretID issued +PASS: runtime credentials loaded from OpenBao +PASS: child process received OpenBao secrets +PASS: api2 OpenBao entrypoint verified +PASS: consumed SecretID already absent +PASS: temporary bootstrap files removed diff --git a/evidence/openbao-entrypoint-tests.txt b/evidence/openbao-entrypoint-tests.txt new file mode 100644 index 0000000..92e8e25 --- /dev/null +++ b/evidence/openbao-entrypoint-tests.txt @@ -0,0 +1,6 @@ +PASS: temporary API1 SecretID issued +PASS: runtime credentials loaded from OpenBao +PASS: child process received OpenBao secrets +PASS: API1 OpenBao entrypoint verified +PASS: consumed SecretID already absent +PASS: temporary bootstrap files removed diff --git a/evidence/openbao-entrypoint-worker-tests.txt b/evidence/openbao-entrypoint-worker-tests.txt new file mode 100644 index 0000000..4d2397b --- /dev/null +++ b/evidence/openbao-entrypoint-worker-tests.txt @@ -0,0 +1,6 @@ +PASS: temporary worker SecretID issued +PASS: runtime credentials loaded from OpenBao +PASS: child process received OpenBao secrets +PASS: worker OpenBao entrypoint verified +PASS: consumed SecretID already absent +PASS: temporary bootstrap files removed diff --git a/evidence/openbao-final-evidence-check.txt b/evidence/openbao-final-evidence-check.txt new file mode 100644 index 0000000..72089a4 --- /dev/null +++ b/evidence/openbao-final-evidence-check.txt @@ -0,0 +1,16 @@ +PASS: openbao-api1-rotation-config.txt +PASS: openbao-api1-rotation-auth.txt +PASS: openbao-api2-rotation-config.txt +PASS: openbao-api2-rotation-auth.txt +PASS: openbao-worker-rotation-config.txt +PASS: openbao-worker-rotation-auth.txt +PASS: openbao-certificate-identity-audit.txt +PASS: openbao-old-certificates-rejection.txt +PASS: openbao-retired-certificates-inventory.txt +PASS: openbao-final-rotation-audit.txt +PASS: openbao-token-lifecycle-audit.txt +PASS: openbao-token-revocation-test.txt +PASS: openbao-active-token-audit.txt +PASS: openbao-operator-security-audit.txt +PASS: https-smoke-tests.txt +PASS: OpenBao evidence inventory complete diff --git a/evidence/openbao-final-rotation-audit.txt b/evidence/openbao-final-rotation-audit.txt new file mode 100644 index 0000000..fe97bf8 --- /dev/null +++ b/evidence/openbao-final-rotation-audit.txt @@ -0,0 +1,24 @@ +PASS: api1: old files removed +PASS: api1: replacement files preserved +PASS: api1: replacement key permissions 600 +PASS: api1: replacement identity configured +PASS: api1: replacement files mounted read-only +PASS: api1: running identity correct +PASS: api1: running certificate mounts correct +PASS: api2: old files removed +PASS: api2: replacement files preserved +PASS: api2: replacement key permissions 600 +PASS: api2: replacement identity configured +PASS: api2: replacement files mounted read-only +PASS: api2: running identity correct +PASS: api2: running certificate mounts correct +PASS: worker: old files removed +PASS: worker: replacement files preserved +PASS: worker: replacement key permissions 600 +PASS: worker: replacement identity configured +PASS: worker: replacement files mounted read-only +PASS: worker: running identity correct +PASS: worker: running certificate mounts correct +PASS: OpenBao contains exactly three replacement identities +PASS: No old certificate identities registered +PASS: final certificate rotation audit diff --git a/evidence/openbao-old-certificates-rejection.txt b/evidence/openbao-old-certificates-rejection.txt new file mode 100644 index 0000000..4cb7a0b --- /dev/null +++ b/evidence/openbao-old-certificates-rejection.txt @@ -0,0 +1,4 @@ +PASS: old api1 certificate rejected without role name (HTTP 400) +PASS: old api2 certificate rejected without role name (HTTP 400) +PASS: old worker certificate rejected without role name (HTTP 400) +PASS: all old certificates rejected diff --git a/evidence/openbao-operator-security-audit.txt b/evidence/openbao-operator-security-audit.txt new file mode 100644 index 0000000..5a0fd1e --- /dev/null +++ b/evidence/openbao-operator-security-audit.txt @@ -0,0 +1,5 @@ +PASS: Operator directory exists +PASS: Initialization file exists +PASS: Initialization file is not a symlink +PASS: Operator directory permissions 700 +PASS: Initialization file permissions 600 diff --git a/evidence/openbao-retired-certificates-inventory.txt b/evidence/openbao-retired-certificates-inventory.txt new file mode 100644 index 0000000..1b913c7 --- /dev/null +++ b/evidence/openbao-retired-certificates-inventory.txt @@ -0,0 +1,15 @@ +PASS: api1: Old certificate exists +PASS: api1: Old private key exists +PASS: api1: Replacement certificate exists +PASS: api1: Old key permissions 600 +PASS: api1: Old and new certificates differ +PASS: api2: Old certificate exists +PASS: api2: Old private key exists +PASS: api2: Replacement certificate exists +PASS: api2: Old key permissions 600 +PASS: api2: Old and new certificates differ +PASS: worker: Old certificate exists +PASS: worker: Old private key exists +PASS: worker: Replacement certificate exists +PASS: worker: Old key permissions 600 +PASS: worker: Old and new certificates differ diff --git a/evidence/openbao-runtime-acl-tests.txt b/evidence/openbao-runtime-acl-tests.txt new file mode 100644 index 0000000..9d8f94e --- /dev/null +++ b/evidence/openbao-runtime-acl-tests.txt @@ -0,0 +1,17 @@ +OpenBao endpoint: https://localhost:8200/v1 +TLS verification: enabled +PASS: API replicas use matching credentials +PASS: api: correct scoped policy +PASS: api: limited token TTL +PASS: worker: correct scoped policy +PASS: worker: limited token TTL +PASS: api: runtime secrets match Compose +PASS: worker: runtime secrets match Compose +PASS: API cannot read worker runtime secrets (HTTP 403) +PASS: Worker cannot read API runtime secrets (HTTP 403) +PASS: API cannot read policy configuration (HTTP 403) +PASS: Worker cannot read policy configuration (HTTP 403) +PASS: all OpenBao runtime access tests passed +PASS: no credential values printed +PASS: temporary service token revoked +PASS: temporary service token revoked diff --git a/evidence/openbao-token-lifecycle-audit.txt b/evidence/openbao-token-lifecycle-audit.txt new file mode 100644 index 0000000..ee45a2b --- /dev/null +++ b/evidence/openbao-token-lifecycle-audit.txt @@ -0,0 +1,13 @@ +PASS: lab7-api1-next: Expected policy only +PASS: lab7-api1-next: Token TTL is 1200 seconds +PASS: lab7-api1-next: Token max TTL is 3600 seconds +PASS: lab7-api1-next: Default policy disabled +PASS: lab7-api2-next: Expected policy only +PASS: lab7-api2-next: Token TTL is 1200 seconds +PASS: lab7-api2-next: Token max TTL is 3600 seconds +PASS: lab7-api2-next: Default policy disabled +PASS: lab7-worker-next: Expected policy only +PASS: lab7-worker-next: Token TTL is 1200 seconds +PASS: lab7-worker-next: Token max TTL is 3600 seconds +PASS: lab7-worker-next: Default policy disabled +PASS: token lifecycle configuration audit diff --git a/evidence/openbao-token-revocation-test.txt b/evidence/openbao-token-revocation-test.txt new file mode 100644 index 0000000..200c9d5 --- /dev/null +++ b/evidence/openbao-token-revocation-test.txt @@ -0,0 +1,12 @@ +PASS: New worker certificate authenticated +PASS: Correct worker policy +PASS: Issued TTL within 1200 seconds +PASS: Administrative token lookup succeeded +PASS: Actual TTL within 1200 seconds +PASS: Token has no root policy +PASS: Worker secret readable +PASS: API secret forbidden +PASS: Worker token cannot perform lookup-self +PASS: Token revoke-self succeeded +PASS: Revoked token no longer exists +PASS: token lifecycle and revocation test diff --git a/evidence/openbao-worker-rotation-auth.txt b/evidence/openbao-worker-rotation-auth.txt new file mode 100644 index 0000000..ce3d68a --- /dev/null +++ b/evidence/openbao-worker-rotation-auth.txt @@ -0,0 +1,2 @@ +PASS: runtime credentials loaded from OpenBao +PASS: rotated worker certificate authenticated diff --git a/evidence/openbao-worker-rotation-config.txt b/evidence/openbao-worker-rotation-config.txt new file mode 100644 index 0000000..3a16992 --- /dev/null +++ b/evidence/openbao-worker-rotation-config.txt @@ -0,0 +1,7 @@ +PASS: Replacement worker identity configured +PASS: Replacement worker certificate configured +PASS: Replacement worker private key configured +PASS: Certificate mounted read-only +PASS: Private key mounted read-only +PASS: API1 rotated identity preserved +PASS: API2 rotated identity preserved diff --git a/evidence/postgres-acl-tests.txt b/evidence/postgres-acl-tests.txt new file mode 100644 index 0000000..274a946 --- /dev/null +++ b/evidence/postgres-acl-tests.txt @@ -0,0 +1,53 @@ + +================================ +Testing service: api1 +================================ +PostgreSQL role: messenger_api +TLS encrypted: True +TLS version: TLSv1.3 +PASS: allowed - read users +PASS: allowed - read sessions +PASS: allowed - read jobs +PASS: denied - read migration history +PASS: denied - create tables +PASS: all ACL tests for messenger_api + +================================ +Testing service: api2 +================================ +PostgreSQL role: messenger_api +TLS encrypted: True +TLS version: TLSv1.3 +PASS: allowed - read users +PASS: allowed - read sessions +PASS: allowed - read jobs +PASS: denied - read migration history +PASS: denied - create tables +PASS: all ACL tests for messenger_api + +================================ +Testing service: worker +================================ +PostgreSQL role: messenger_worker +TLS encrypted: True +TLS version: TLSv1.3 +PASS: allowed - read jobs +PASS: allowed - read attachments +PASS: allowed - read variants +PASS: denied - read users +PASS: denied - read sessions +PASS: denied - read messages +PASS: all ACL tests for messenger_worker + +================================ +Testing service: dispatcher +================================ +PostgreSQL role: messenger_dispatcher +TLS encrypted: True +TLS version: TLSv1.3 +PASS: allowed - read jobs +PASS: denied - read users +PASS: denied - read sessions +PASS: denied - read messages +PASS: denied - read attachments +PASS: all ACL tests for messenger_dispatcher diff --git a/evidence/postgres-tls-config.txt b/evidence/postgres-tls-config.txt new file mode 100644 index 0000000..9f42d91 --- /dev/null +++ b/evidence/postgres-tls-config.txt @@ -0,0 +1,3 @@ +on +TLSv1.2 +/etc/postgresql/pg_hba.conf diff --git a/evidence/rabbitmq-acl-tests.txt b/evidence/rabbitmq-acl-tests.txt new file mode 100644 index 0000000..1283d25 --- /dev/null +++ b/evidence/rabbitmq-acl-tests.txt @@ -0,0 +1,11 @@ +=== Publisher ACL === +RabbitMQ role: messenger_publisher +TLS connection: authenticated +PASS: publisher cannot consume image_jobs +PASS: RabbitMQ ACL tests for messenger_publisher + +=== Consumer ACL === +RabbitMQ role: messenger_consumer +TLS connection: authenticated +PASS: consumer cannot publish +PASS: RabbitMQ ACL tests for messenger_consumer diff --git a/evidence/rustfs-acl-tests.txt b/evidence/rustfs-acl-tests.txt new file mode 100644 index 0000000..6d2c08b --- /dev/null +++ b/evidence/rustfs-acl-tests.txt @@ -0,0 +1,21 @@ +RustFS endpoint: https://minio:9000 +Bucket: messenger-attachments +TLS verification: enabled +PASS: temporary test objects prepared +PASS: API can upload staging +PASS: API can read original +PASS: API can read thumbnail +PASS: API can delete staging +PASS: worker can read staging +PASS: worker can write original +PASS: worker can write thumbnail +PASS: API staging read denied +PASS: API original write denied +PASS: API thumbnail write denied +PASS: API original delete denied +PASS: worker original read denied +PASS: worker thumbnail read denied +PASS: worker staging write denied +PASS: worker staging delete denied +PASS: all RustFS IAM ACL tests passed +RustFS ACL test cleanup attempted diff --git a/migrations/001_initial.sql b/migrations/001_initial.sql new file mode 100644 index 0000000..0e4d523 --- /dev/null +++ b/migrations/001_initial.sql @@ -0,0 +1,74 @@ + +CREATE TABLE IF NOT EXISTS users ( + id UUID PRIMARY KEY, + username VARCHAR(32) NOT NULL UNIQUE, + display_name VARCHAR(100) NOT NULL, + password_hash TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), + + CONSTRAINT username_format + CHECK (username ~ '^[a-z0-9_]{3,32}$'), + CONSTRAINT display_name_length + CHECK (char_length(display_name) BETWEEN 1 AND 100), + CONSTRAINT display_name_not_blank + CHECK (length(btrim(display_name)) > 0) +); + +CREATE TABLE IF NOT EXISTS chats ( + id UUID PRIMARY KEY, + title VARCHAR(100) NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), + + CONSTRAINT title_not_blank + CHECK (length(btrim(title)) > 0) +); + +CREATE TABLE IF NOT EXISTS chat_members ( + chat_id UUID NOT NULL + REFERENCES chats(id) ON DELETE CASCADE, + user_id UUID NOT NULL + REFERENCES users(id), + position INTEGER NOT NULL, + + PRIMARY KEY (chat_id, user_id), + UNIQUE (chat_id, position) +); + +CREATE TABLE IF NOT EXISTS messages ( + id UUID PRIMARY KEY, + chat_id UUID NOT NULL + REFERENCES chats(id) ON DELETE CASCADE, + sender_id UUID NOT NULL + REFERENCES users(id), + text TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), + + CONSTRAINT message_length + CHECK (char_length(text) BETWEEN 1 AND 4000), + CONSTRAINT message_not_blank + CHECK (length(btrim(text)) > 0) +); + +CREATE TABLE IF NOT EXISTS sessions ( + token_hash CHAR(64) PRIMARY KEY, + user_id UUID NOT NULL + REFERENCES users(id) ON DELETE CASCADE, + expires_at TIMESTAMPTZ NOT NULL, + revoked BOOLEAN NOT NULL DEFAULT FALSE, + created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp() +); + +CREATE INDEX IF NOT EXISTS idx_chat_members_user + ON chat_members(user_id, chat_id); + +CREATE INDEX IF NOT EXISTS idx_chats_order + ON chats(created_at, id); + +CREATE INDEX IF NOT EXISTS idx_messages_history + ON messages(chat_id, created_at, id); + +CREATE INDEX IF NOT EXISTS idx_sessions_user + ON sessions(user_id); + +CREATE INDEX IF NOT EXISTS idx_sessions_expiry + ON sessions(expires_at); diff --git a/migrations/002_idempotency.sql b/migrations/002_idempotency.sql new file mode 100644 index 0000000..663c6b6 --- /dev/null +++ b/migrations/002_idempotency.sql @@ -0,0 +1,14 @@ + +CREATE TABLE IF NOT EXISTS message_idempotency ( + user_id UUID NOT NULL REFERENCES users(id), + chat_id UUID NOT NULL REFERENCES chats(id), + idempotency_key VARCHAR(128) NOT NULL, + request_hash CHAR(64) NOT NULL, + message_id UUID NOT NULL REFERENCES messages(id), + created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), + + PRIMARY KEY (user_id, chat_id, idempotency_key) +); + +CREATE INDEX IF NOT EXISTS idx_idempotency_created +ON message_idempotency(created_at); diff --git a/migrations/003_attachments.sql b/migrations/003_attachments.sql new file mode 100644 index 0000000..49e9f33 --- /dev/null +++ b/migrations/003_attachments.sql @@ -0,0 +1,34 @@ + +CREATE TABLE IF NOT EXISTS attachments ( + id UUID PRIMARY KEY, + chat_id UUID NOT NULL REFERENCES chats(id), + uploader_id UUID NOT NULL REFERENCES users(id), + filename TEXT NOT NULL, + content_type TEXT NOT NULL, + size_bytes BIGINT NOT NULL, + sha256 CHAR(64) NOT NULL, + object_key TEXT NOT NULL UNIQUE, + width INTEGER NOT NULL, + height INTEGER NOT NULL, + status TEXT NOT NULL DEFAULT 'ready', + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + + CONSTRAINT attachment_size_valid + CHECK (size_bytes BETWEEN 1 AND 10485760), + + CONSTRAINT attachment_dimensions_valid + CHECK (width > 0 AND height > 0), + + CONSTRAINT attachment_status_valid + CHECK (status IN ('ready', 'failed')) +); + +CREATE INDEX IF NOT EXISTS idx_attachments_chat +ON attachments(chat_id); + +CREATE TABLE IF NOT EXISTS message_attachments ( + message_id UUID NOT NULL REFERENCES messages(id), + attachment_id UUID NOT NULL REFERENCES attachments(id), + + PRIMARY KEY (message_id, attachment_id) +); diff --git a/migrations/004_allow_empty_message_text.sql b/migrations/004_allow_empty_message_text.sql new file mode 100644 index 0000000..9b72153 --- /dev/null +++ b/migrations/004_allow_empty_message_text.sql @@ -0,0 +1,13 @@ + +-- Lab4: messages with attachments may have empty text. +-- The API checks that a message contains text or attachments. + +ALTER TABLE messages +DROP CONSTRAINT IF EXISTS message_length; + +ALTER TABLE messages +DROP CONSTRAINT IF EXISTS message_not_blank; + +ALTER TABLE messages +ADD CONSTRAINT message_length +CHECK (char_length(text) <= 4000); diff --git a/migrations/005_async_jobs.sql b/migrations/005_async_jobs.sql new file mode 100644 index 0000000..9417b50 --- /dev/null +++ b/migrations/005_async_jobs.sql @@ -0,0 +1,95 @@ +-- Allow asynchronous attachment states. +ALTER TABLE attachments +DROP CONSTRAINT IF EXISTS attachment_status_valid; + +ALTER TABLE attachments +ADD CONSTRAINT attachment_status_valid +CHECK ( + status IN ( + 'queued', + 'processing', + 'ready', + 'failed' + ) +); + +-- Staging object stored in the private S3 bucket. +ALTER TABLE attachments +ADD COLUMN IF NOT EXISTS staging_key TEXT; + +-- Machine-readable final error. +ALTER TABLE attachments +ADD COLUMN IF NOT EXISTS error_code TEXT; + +-- Last metadata update timestamp. +ALTER TABLE attachments +ADD COLUMN IF NOT EXISTS updated_at +TIMESTAMPTZ NOT NULL DEFAULT NOW(); + +-- Worker jobs and durable publication intent. +CREATE TABLE IF NOT EXISTS attachment_jobs ( + id UUID PRIMARY KEY, + attachment_id UUID NOT NULL UNIQUE + REFERENCES attachments(id), + + status TEXT NOT NULL DEFAULT 'queued', + attempts INTEGER NOT NULL DEFAULT 0, + max_attempts INTEGER NOT NULL DEFAULT 5, + + published_at TIMESTAMPTZ, + started_at TIMESTAMPTZ, + completed_at TIMESTAMPTZ, + next_attempt_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + + CONSTRAINT attachment_job_status_valid + CHECK ( + status IN ( + 'queued', + 'processing', + 'ready', + 'failed' + ) + ), + + CONSTRAINT attachment_job_attempts_valid + CHECK ( + attempts >= 0 + AND max_attempts BETWEEN 1 AND 20 + ) +); + +CREATE INDEX IF NOT EXISTS idx_attachment_jobs_pending +ON attachment_jobs(status, next_attempt_at); + +-- Image variants created by the worker. +CREATE TABLE IF NOT EXISTS attachment_variants ( + attachment_id UUID NOT NULL + REFERENCES attachments(id), + + variant_name TEXT NOT NULL, + object_key TEXT NOT NULL, + content_type TEXT NOT NULL, + size_bytes BIGINT NOT NULL, + sha256 CHAR(64) NOT NULL, + width INTEGER NOT NULL, + height INTEGER NOT NULL, + + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + + PRIMARY KEY (attachment_id, variant_name), + + CONSTRAINT variant_name_valid + CHECK (variant_name IN ('thumbnail')), + + CONSTRAINT variant_size_valid + CHECK (size_bytes > 0), + + CONSTRAINT variant_dimensions_valid + CHECK (width > 0 AND height > 0) +); + +CREATE UNIQUE INDEX IF NOT EXISTS idx_attachment_variants_key +ON attachment_variants(object_key); diff --git a/migrations/006_login_rate_limit.sql b/migrations/006_login_rate_limit.sql new file mode 100644 index 0000000..aaf8bc2 --- /dev/null +++ b/migrations/006_login_rate_limit.sql @@ -0,0 +1,15 @@ + +-- Shared login rate limiter for both API replicas. +-- One bucket per normalized username. +-- Only SHA-256 of the bucket identity is stored. + +CREATE TABLE IF NOT EXISTS login_attempt_buckets ( + bucket_key TEXT PRIMARY KEY, + window_started_at TIMESTAMPTZ NOT NULL, + attempts INTEGER NOT NULL DEFAULT 0 + CHECK (attempts >= 0) +); + +CREATE INDEX IF NOT EXISTS + idx_login_attempt_buckets_window +ON login_attempt_buckets (window_started_at); diff --git a/migrations/007_db_roles.sql b/migrations/007_db_roles.sql new file mode 100644 index 0000000..c95184b --- /dev/null +++ b/migrations/007_db_roles.sql @@ -0,0 +1,52 @@ +-- Lab7 PostgreSQL least-privilege service roles. +-- Credentials are provisioned separately by the operator. + +CREATE ROLE messenger_api NOLOGIN; +CREATE ROLE messenger_worker NOLOGIN; +CREATE ROLE messenger_dispatcher NOLOGIN; + +-- Remove default database and schema privileges. +REVOKE ALL ON DATABASE messenger FROM PUBLIC; +REVOKE ALL ON SCHEMA public FROM PUBLIC; + +GRANT CONNECT ON DATABASE messenger +TO messenger_api, messenger_worker, messenger_dispatcher; + +GRANT USAGE ON SCHEMA public +TO messenger_api, messenger_worker, messenger_dispatcher; + +-- API: user accounts and authentication. +GRANT SELECT, INSERT ON users TO messenger_api; +GRANT SELECT, INSERT, UPDATE ON sessions TO messenger_api; + +-- API: chats and messages. +GRANT SELECT, INSERT, UPDATE ON chats TO messenger_api; +GRANT SELECT, INSERT, DELETE ON chat_members TO messenger_api; +GRANT SELECT, INSERT ON messages TO messenger_api; +GRANT SELECT, INSERT ON message_attachments TO messenger_api; +GRANT SELECT, INSERT, UPDATE ON message_idempotency TO messenger_api; + +-- API: attachment metadata and asynchronous jobs. +GRANT SELECT, INSERT, UPDATE ON attachments TO messenger_api; +GRANT SELECT, INSERT, UPDATE ON attachment_jobs TO messenger_api; +GRANT SELECT ON attachment_variants TO messenger_api; + +-- API: shared login rate limiter. +GRANT SELECT, INSERT, UPDATE ON login_attempt_buckets +TO messenger_api; + +-- Worker: only data required for image processing. +GRANT SELECT, UPDATE ON attachment_jobs TO messenger_worker; +GRANT SELECT, UPDATE ON attachments TO messenger_worker; +GRANT SELECT, INSERT, UPDATE ON attachment_variants +TO messenger_worker; + +-- Dispatcher: publication state of queued jobs. +GRANT SELECT, UPDATE ON attachment_jobs +TO messenger_dispatcher; + +-- No application role receives: +-- SUPERUSER, CREATEDB, CREATEROLE, REPLICATION +-- Ownership of tables +-- CREATE on public schema +-- Access to schema_migrations diff --git a/migrations/008_api_idempotency_delete.sql b/migrations/008_api_idempotency_delete.sql new file mode 100644 index 0000000..fc1c14e --- /dev/null +++ b/migrations/008_api_idempotency_delete.sql @@ -0,0 +1,6 @@ +-- Lab7: allow API to remove expired idempotency records. +-- The send-message handler performs this cleanup. +-- No DELETE permission is granted on other tables. + +GRANT DELETE ON TABLE public.message_idempotency +TO messenger_api; diff --git a/nginx/nginx.conf b/nginx/nginx.conf new file mode 100644 index 0000000..0c63fa7 --- /dev/null +++ b/nginx/nginx.conf @@ -0,0 +1,56 @@ +events { + worker_connections 1024; +} + +http { + resolver 127.0.0.11 valid=2s ipv6=off; + resolver_timeout 2s; + + upstream messenger_api { + zone messenger_api 64k; + + server api1:8443 resolve max_fails=1 fail_timeout=2s; + server api2:8443 resolve max_fails=1 fail_timeout=2s; + } + + server { + listen 443 ssl; + server_name localhost; + + ssl_certificate /run/lab7-pki/ingress.crt; + ssl_certificate_key /run/lab7-pki/ingress.key; + ssl_protocols TLSv1.2 TLSv1.3; + + client_max_body_size 11m; + + location / { + proxy_pass https://messenger_api; + proxy_http_version 1.1; + + # Verify the server certificate on every API connection. + proxy_ssl_trusted_certificate /run/lab7-pki/ca.crt; + proxy_ssl_verify on; + proxy_ssl_verify_depth 2; + + # Each upstream has its own DNS identity. + proxy_ssl_name messenger-api.internal; + proxy_ssl_server_name on; + + # Nginx authenticates as the authorized LB. + proxy_ssl_certificate /run/lab7-pki/lb-client.crt; + proxy_ssl_certificate_key /run/lab7-pki/lb-client.key; + + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto https; + + proxy_connect_timeout 2s; + proxy_read_timeout 30s; + proxy_send_timeout 30s; + + proxy_next_upstream error timeout http_502 http_503 http_504; + proxy_next_upstream_tries 2; + } + } +} diff --git a/observability/grafana/dashboards/messenger-lab6.json b/observability/grafana/dashboards/messenger-lab6.json new file mode 100644 index 0000000..296727a --- /dev/null +++ b/observability/grafana/dashboards/messenger-lab6.json @@ -0,0 +1,245 @@ +{ + "uid": "messenger-lab6", + "title": "Messenger Lab6 - Observability", + "tags": ["lab6", "messenger", "opentelemetry"], + "timezone": "browser", + "schemaVersion": 41, + "version": 1, + "refresh": "5s", + "time": { + "from": "now-30m", + "to": "now" + }, + "annotations": { + "list": [] + }, + "templating": { + "list": [] + }, + "panels": [ + { + "id": 1, + "title": "API - Requests per second", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 0, "y": 0, "w": 12, "h": 8 + }, + "targets": [ + { + "refId": "A", + "expr": "sum(rate(messenger_messenger_http_requests_total[2m]))", + "legendFormat": "All business requests" + } + ], + "fieldConfig": { + "defaults": { + "unit": "reqps", + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom" + } + } + }, + { + "id": 2, + "title": "API - HTTP 5xx error ratio", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 12, "y": 0, "w": 12, "h": 8 + }, + "targets": [ + { + "refId": "A", + "expr": "(100 * sum(rate(messenger_messenger_http_requests_total{http_status_class=\"5xx\"}[2m])) / clamp_min(sum(rate(messenger_messenger_http_requests_total[2m])), 0.000001)) or vector(0)", + "legendFormat": "5xx / all business requests" + } + ], + "fieldConfig": { + "defaults": { + "unit": "percent", + "min": 0, + "max": 100 + }, + "overrides": [] + } + }, + { + "id": 3, + "title": "API - HTTP p95 duration", + "description": "OTel FastAPI duration histogram is in milliseconds; result converted to seconds.", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 0, "y": 8, "w": 12, "h": 8 + }, + "targets": [ + { + "refId": "A", + "expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_http_server_duration_milliseconds_bucket[5m]))) / 1000", + "legendFormat": "p95 HTTP duration" + } + ], + "fieldConfig": { + "defaults": { + "unit": "s", + "min": 0 + }, + "overrides": [] + } + }, + { + "id": 4, + "title": "Worker - Jobs by outcome", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 12, "y": 8, "w": 12, "h": 8 + }, + "targets": [ + { + "refId": "A", + "expr": "sum by (outcome) (increase(messenger_messenger_worker_jobs_processed_total[5m]))", + "legendFormat": "{{outcome}}" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "min": 0 + }, + "overrides": [] + } + }, + { + "id": 5, + "title": "Worker - Processing p95 duration", + "type": "timeseries", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 0, "y": 16, "w": 12, "h": 8 + }, + "targets": [ + { + "refId": "A", + "expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_messenger_worker_job_duration_seconds_bucket[5m])))", + "legendFormat": "p95 job duration" + } + ], + "fieldConfig": { + "defaults": { + "unit": "s", + "min": 0 + }, + "overrides": [] + } + }, + { + "id": 6, + "title": "Worker - Completed job attempts", + "type": "stat", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "gridPos": { + "x": 12, "y": 16, "w": 12, "h": 8 + }, + "targets": [ + { + "refId": "A", + "expr": "sum(messenger_messenger_worker_jobs_processed_total)", + "legendFormat": "Processing attempts" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "decimals": 0 + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "values": false, + "calcs": ["lastNotNull"] + } + } + }, + { + "id": 7, + "title": "API - Structured logs", + "type": "logs", + "datasource": { + "type": "loki", + "uid": "loki" + }, + "gridPos": { + "x": 0, "y": 24, "w": 24, "h": 9 + }, + "targets": [ + { + "refId": "A", + "expr": "{service_name=\"messenger-api\"}", + "queryType": "range" + } + ], + "options": { + "showTime": true, + "showLabels": true, + "showCommonLabels": false, + "enableLogDetails": true, + "wrapLogMessage": true, + "sortOrder": "Descending" + } + }, + { + "id": 8, + "title": "Worker - Structured logs", + "type": "logs", + "datasource": { + "type": "loki", + "uid": "loki" + }, + "gridPos": { + "x": 0, "y": 33, "w": 24, "h": 9 + }, + "targets": [ + { + "refId": "A", + "expr": "{service_name=\"messenger-worker\"}", + "queryType": "range" + } + ], + "options": { + "showTime": true, + "showLabels": true, + "showCommonLabels": false, + "enableLogDetails": true, + "wrapLogMessage": true, + "sortOrder": "Descending" + } + } + ] +} diff --git a/observability/grafana/provisioning/dashboards/dashboard.yaml b/observability/grafana/provisioning/dashboards/dashboard.yaml new file mode 100644 index 0000000..2a29efd --- /dev/null +++ b/observability/grafana/provisioning/dashboards/dashboard.yaml @@ -0,0 +1,11 @@ +apiVersion: 1 + +providers: + - name: Messenger Lab6 + orgId: 1 + folder: Messenger Lab6 + type: file + disableDeletion: false + editable: false + options: + path: /var/lib/grafana/dashboards diff --git a/observability/grafana/provisioning/datasources/datasources.yaml b/observability/grafana/provisioning/datasources/datasources.yaml new file mode 100644 index 0000000..a255799 --- /dev/null +++ b/observability/grafana/provisioning/datasources/datasources.yaml @@ -0,0 +1,197 @@ +apiVersion: 1 +datasources: +- name: Prometheus + uid: prometheus + type: prometheus + access: proxy + url: https://prometheus:9090 + isDefault: true + editable: false + jsonData: + tlsAuthWithCACert: true + tlsSkipVerify: false + secureJsonData: + tlsCACert: '-----BEGIN CERTIFICATE----- + + MIIEMDCCApigAwIBAgIUDVTLymvpgcpMx4D1lOpkjNGmE+YwDQYJKoZIhvcNAQEL + + BQAwHjEcMBoGA1UEAwwTTVRVU0kgTGFiNyBMb2NhbCBDQTAeFw0yNjExMjExODI3 + + MzlaFw0yNzExMjExODI3MzlaMB4xHDAaBgNVBAMME01UVVNJIExhYjcgTG9jYWwg + + Q0EwggGiMA0GCSqGSIb3DQEBAQUAA4IBjwAwggGKAoIBgQCRZMyUu/CIiTGmasLt + + wC4GazWCsDvNKojZHaws0/4WeG13gzgdKUCXs7l1PkhWIzbOa+uVChu9IUfY4mtj + + Hole17SLbDj4yKit14mfdwvCRZaCgm5AuoMhulmd1DhHvRh/bwhKu7CJ1dnVlRpK + + vyDJ4vbqtOa4nvGRJwAWciAejScq1C1oISQuZea/6a1DgzEHHRZhGV0SVhh+mBJI + + HNugZZ6QWtV45Rdho3VouXl5zjGOtHQ2p6JBckAgfkGFG+mNA7BNQW2Xx8zIe6eK + + cKLaKFPkW2ri5sPt0b7VVHiSr+vU9Smd5jJwliacCZmyqNtP1IkN7unNNx5f3Agd + + HVdlbkxKIodKOGWfvqTisZQOsm0MEUFUChXsN9pQJ5IXfAoFCad9zWWZKT1CPHzA + + H1iV7gDvo5TXVsmOuIEUHkECeBNdLYcdTNmgmJxrs4fMe7slvBi8wA0rNlAoRH+u + + O8ggcgTMbeuovXNR4Sqb3XKluscDfD2MVknJ6v3HzxAImf0CAwEAAaNmMGQwHQYD + + VR0OBBYEFMiQR7DUGXndbL0HZHpi3OK5lxSCMB8GA1UdIwQYMBaAFMiQR7DUGXnd + + bL0HZHpi3OK5lxSCMBIGA1UdEwEB/wQIMAYBAf8CAQAwDgYDVR0PAQH/BAQDAgEG + + MA0GCSqGSIb3DQEBCwUAA4IBgQAB9ptJKxcbPbB5L6cLpZiUM081qRnj/1FSMR2W + + BcgfzZE5jBI2J3Fq1bfch919vi5/sp6DkCr4/YQbrSbPCPL34HlVfgSs2P42NKY4 + + FJ5uVhKZRz6IAFpKvzZf7mx6Z7BgG+3TnIJX589PgZlMotLHvZsgHnpWBq0cP202 + + /CRadfsUwSUXRGgJ0lehyJlNNakuc5wpNNa9+8UG0VjpidtBbU+xQFaOzq3cb2Xf + + bvFb7pA7lOLTZEJiv0Bcde/AQ05GmbCHi8xIj3PkoD+D8xKBXQosZojovEc7B7HD + + AdRVO3tHpX/kW6PgGc5pinqPqcvUwXNltonDJr9OrkGPIJ4ozWDjCO3pRtC3nX1H + + jVoEFjmhYlknK1t5kmOGsfnOw9xy6Ci0Qa++404BsWbGYFCqIK7KurxyGxAfgsms + + KC3QuJss4jjDWO5jT3yw3EUFw6A5TU+P1ixVax0OdJ4yXar5hIo0eFN+WzhMYR0q + + Grh571D/oJPXICFvimxOP3dG71I= + + -----END CERTIFICATE----- + + ' +- name: Loki + uid: loki + type: loki + access: proxy + url: https://loki:3100 + editable: false + jsonData: + tlsAuthWithCACert: true + tlsSkipVerify: false + derivedFields: + - name: TraceID + matcherRegex: trace_id=([a-f0-9]{32}) + datasourceUid: tempo + url: $${__value.raw} + secureJsonData: + tlsCACert: '-----BEGIN CERTIFICATE----- + + MIIEMDCCApigAwIBAgIUDVTLymvpgcpMx4D1lOpkjNGmE+YwDQYJKoZIhvcNAQEL + + BQAwHjEcMBoGA1UEAwwTTVRVU0kgTGFiNyBMb2NhbCBDQTAeFw0yNjExMjExODI3 + + MzlaFw0yNzExMjExODI3MzlaMB4xHDAaBgNVBAMME01UVVNJIExhYjcgTG9jYWwg + + Q0EwggGiMA0GCSqGSIb3DQEBAQUAA4IBjwAwggGKAoIBgQCRZMyUu/CIiTGmasLt + + wC4GazWCsDvNKojZHaws0/4WeG13gzgdKUCXs7l1PkhWIzbOa+uVChu9IUfY4mtj + + Hole17SLbDj4yKit14mfdwvCRZaCgm5AuoMhulmd1DhHvRh/bwhKu7CJ1dnVlRpK + + vyDJ4vbqtOa4nvGRJwAWciAejScq1C1oISQuZea/6a1DgzEHHRZhGV0SVhh+mBJI + + HNugZZ6QWtV45Rdho3VouXl5zjGOtHQ2p6JBckAgfkGFG+mNA7BNQW2Xx8zIe6eK + + cKLaKFPkW2ri5sPt0b7VVHiSr+vU9Smd5jJwliacCZmyqNtP1IkN7unNNx5f3Agd + + HVdlbkxKIodKOGWfvqTisZQOsm0MEUFUChXsN9pQJ5IXfAoFCad9zWWZKT1CPHzA + + H1iV7gDvo5TXVsmOuIEUHkECeBNdLYcdTNmgmJxrs4fMe7slvBi8wA0rNlAoRH+u + + O8ggcgTMbeuovXNR4Sqb3XKluscDfD2MVknJ6v3HzxAImf0CAwEAAaNmMGQwHQYD + + VR0OBBYEFMiQR7DUGXndbL0HZHpi3OK5lxSCMB8GA1UdIwQYMBaAFMiQR7DUGXnd + + bL0HZHpi3OK5lxSCMBIGA1UdEwEB/wQIMAYBAf8CAQAwDgYDVR0PAQH/BAQDAgEG + + MA0GCSqGSIb3DQEBCwUAA4IBgQAB9ptJKxcbPbB5L6cLpZiUM081qRnj/1FSMR2W + + BcgfzZE5jBI2J3Fq1bfch919vi5/sp6DkCr4/YQbrSbPCPL34HlVfgSs2P42NKY4 + + FJ5uVhKZRz6IAFpKvzZf7mx6Z7BgG+3TnIJX589PgZlMotLHvZsgHnpWBq0cP202 + + /CRadfsUwSUXRGgJ0lehyJlNNakuc5wpNNa9+8UG0VjpidtBbU+xQFaOzq3cb2Xf + + bvFb7pA7lOLTZEJiv0Bcde/AQ05GmbCHi8xIj3PkoD+D8xKBXQosZojovEc7B7HD + + AdRVO3tHpX/kW6PgGc5pinqPqcvUwXNltonDJr9OrkGPIJ4ozWDjCO3pRtC3nX1H + + jVoEFjmhYlknK1t5kmOGsfnOw9xy6Ci0Qa++404BsWbGYFCqIK7KurxyGxAfgsms + + KC3QuJss4jjDWO5jT3yw3EUFw6A5TU+P1ixVax0OdJ4yXar5hIo0eFN+WzhMYR0q + + Grh571D/oJPXICFvimxOP3dG71I= + + -----END CERTIFICATE----- + + ' +- name: Tempo + uid: tempo + type: tempo + access: proxy + url: https://tempo:3200 + editable: false + jsonData: + tracesToLogsV2: + datasourceUid: loki + filterByTraceID: true + filterBySpanID: false + nodeGraph: + enabled: true + tlsAuthWithCACert: true + tlsSkipVerify: false + secureJsonData: + tlsCACert: '-----BEGIN CERTIFICATE----- + + MIIEMDCCApigAwIBAgIUDVTLymvpgcpMx4D1lOpkjNGmE+YwDQYJKoZIhvcNAQEL + + BQAwHjEcMBoGA1UEAwwTTVRVU0kgTGFiNyBMb2NhbCBDQTAeFw0yNjExMjExODI3 + + MzlaFw0yNzExMjExODI3MzlaMB4xHDAaBgNVBAMME01UVVNJIExhYjcgTG9jYWwg + + Q0EwggGiMA0GCSqGSIb3DQEBAQUAA4IBjwAwggGKAoIBgQCRZMyUu/CIiTGmasLt + + wC4GazWCsDvNKojZHaws0/4WeG13gzgdKUCXs7l1PkhWIzbOa+uVChu9IUfY4mtj + + Hole17SLbDj4yKit14mfdwvCRZaCgm5AuoMhulmd1DhHvRh/bwhKu7CJ1dnVlRpK + + vyDJ4vbqtOa4nvGRJwAWciAejScq1C1oISQuZea/6a1DgzEHHRZhGV0SVhh+mBJI + + HNugZZ6QWtV45Rdho3VouXl5zjGOtHQ2p6JBckAgfkGFG+mNA7BNQW2Xx8zIe6eK + + cKLaKFPkW2ri5sPt0b7VVHiSr+vU9Smd5jJwliacCZmyqNtP1IkN7unNNx5f3Agd + + HVdlbkxKIodKOGWfvqTisZQOsm0MEUFUChXsN9pQJ5IXfAoFCad9zWWZKT1CPHzA + + H1iV7gDvo5TXVsmOuIEUHkECeBNdLYcdTNmgmJxrs4fMe7slvBi8wA0rNlAoRH+u + + O8ggcgTMbeuovXNR4Sqb3XKluscDfD2MVknJ6v3HzxAImf0CAwEAAaNmMGQwHQYD + + VR0OBBYEFMiQR7DUGXndbL0HZHpi3OK5lxSCMB8GA1UdIwQYMBaAFMiQR7DUGXnd + + bL0HZHpi3OK5lxSCMBIGA1UdEwEB/wQIMAYBAf8CAQAwDgYDVR0PAQH/BAQDAgEG + + MA0GCSqGSIb3DQEBCwUAA4IBgQAB9ptJKxcbPbB5L6cLpZiUM081qRnj/1FSMR2W + + BcgfzZE5jBI2J3Fq1bfch919vi5/sp6DkCr4/YQbrSbPCPL34HlVfgSs2P42NKY4 + + FJ5uVhKZRz6IAFpKvzZf7mx6Z7BgG+3TnIJX589PgZlMotLHvZsgHnpWBq0cP202 + + /CRadfsUwSUXRGgJ0lehyJlNNakuc5wpNNa9+8UG0VjpidtBbU+xQFaOzq3cb2Xf + + bvFb7pA7lOLTZEJiv0Bcde/AQ05GmbCHi8xIj3PkoD+D8xKBXQosZojovEc7B7HD + + AdRVO3tHpX/kW6PgGc5pinqPqcvUwXNltonDJr9OrkGPIJ4ozWDjCO3pRtC3nX1H + + jVoEFjmhYlknK1t5kmOGsfnOw9xy6Ci0Qa++404BsWbGYFCqIK7KurxyGxAfgsms + + KC3QuJss4jjDWO5jT3yw3EUFw6A5TU+P1ixVax0OdJ4yXar5hIo0eFN+WzhMYR0q + + Grh571D/oJPXICFvimxOP3dG71I= + + -----END CERTIFICATE----- + + ' diff --git a/observability/loki.yaml b/observability/loki.yaml new file mode 100644 index 0000000..423f59f --- /dev/null +++ b/observability/loki.yaml @@ -0,0 +1,39 @@ + +auth_enabled: false + +server: + http_listen_port: 3100 + http_tls_config: + cert_file: /run/loki/server.crt + key_file: /run/loki/server.key + +common: + path_prefix: /loki + replication_factor: 1 + ring: + kvstore: + store: inmemory + +schema_config: + configs: + - from: "2024-01-01" + store: tsdb + object_store: filesystem + schema: v13 + index: + prefix: index_ + period: 24h + +storage_config: + filesystem: + directory: /loki/chunks + + tsdb_shipper: + active_index_directory: /loki/index + cache_location: /loki/index_cache + +limits_config: + allow_structured_metadata: true + +analytics: + reporting_enabled: false diff --git a/observability/otel-collector.yaml b/observability/otel-collector.yaml new file mode 100644 index 0000000..e5df8a7 --- /dev/null +++ b/observability/otel-collector.yaml @@ -0,0 +1,84 @@ + +receivers: + otlp/secure: + protocols: + grpc: + endpoint: 0.0.0.0:4319 + tls: + cert_file: /run/telemetry/server.crt + key_file: /run/telemetry/server.key + http: + endpoint: 0.0.0.0:4320 + tls: + cert_file: /run/telemetry/server.crt + key_file: /run/telemetry/server.key + +processors: + memory_limiter: + check_interval: 1s + limit_mib: 256 + spike_limit_mib: 64 + + batch: + timeout: 5s + send_batch_size: 512 + +exporters: + prometheus: + endpoint: 0.0.0.0:8889 + tls: + cert_file: /run/telemetry/server.crt + key_file: /run/telemetry/server.key + namespace: messenger + resource_to_telemetry_conversion: + enabled: true + + otlp/tempo: + endpoint: tempo:4317 + tls: + insecure: false + ca_file: /run/telemetry/ca.crt + server_name_override: tempo + cert_file: /run/telemetry/client.crt + key_file: /run/telemetry/client.key + sending_queue: + enabled: true + queue_size: 1000 + retry_on_failure: + enabled: true + + otlphttp/loki: + endpoint: https://loki:3100/otlp + tls: + insecure: false + ca_file: /run/telemetry/ca.crt + server_name_override: loki + sending_queue: + enabled: true + queue_size: 1000 + retry_on_failure: + enabled: true + +extensions: + health_check: + endpoint: 0.0.0.0:13133 + +service: + extensions: + - health_check + + pipelines: + traces: + receivers: [otlp/secure] + processors: [memory_limiter, batch] + exporters: [otlp/tempo] + + metrics: + receivers: [otlp/secure] + processors: [memory_limiter, batch] + exporters: [prometheus] + + logs: + receivers: [otlp/secure] + processors: [memory_limiter, batch] + exporters: [otlphttp/loki] diff --git a/observability/prometheus-web.yaml b/observability/prometheus-web.yaml new file mode 100644 index 0000000..e384fa8 --- /dev/null +++ b/observability/prometheus-web.yaml @@ -0,0 +1,3 @@ +tls_server_config: + cert_file: /run/prometheus/server.crt + key_file: /run/prometheus/server.key diff --git a/observability/prometheus.yaml b/observability/prometheus.yaml new file mode 100644 index 0000000..3dc7272 --- /dev/null +++ b/observability/prometheus.yaml @@ -0,0 +1,13 @@ +global: + scrape_interval: 5s + evaluation_interval: 5s + +scrape_configs: + - job_name: otel-collector + scheme: https + tls_config: + ca_file: /etc/prometheus/lab7-ca.crt + server_name: otel-collector + static_configs: + - targets: + - otel-collector:8889 diff --git a/observability/tempo.yaml b/observability/tempo.yaml new file mode 100644 index 0000000..0f23e5a --- /dev/null +++ b/observability/tempo.yaml @@ -0,0 +1,28 @@ +server: + http_listen_port: 3200 + http_tls_config: + cert_file: /run/tempo/server.crt + key_file: /run/tempo/server.key +distributor: + receivers: + otlp: + protocols: + grpc: + endpoint: 0.0.0.0:4317 + tls: + cert_file: /run/tempo/server.crt + key_file: /run/tempo/server.key + client_ca_file: /run/tempo/ca.crt + min_version: '1.2' +ingester: + trace_idle_period: 10s +compactor: + compaction: + block_retention: 48h +storage: + trace: + backend: local + wal: + path: /var/tempo/wal + local: + path: /var/tempo/traces diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..d767a6f --- /dev/null +++ b/requirements.txt @@ -0,0 +1,11 @@ +fastapi==0.115.12 +uvicorn==0.34.2 +psycopg[binary]==3.2.6 +argon2-cffi==23.1.0 +boto3==1.40.70 +Pillow==11.2.1 +pika==1.3.2 +opentelemetry-api==1.38.0 +opentelemetry-sdk==1.38.0 +opentelemetry-exporter-otlp-proto-http==1.38.0 +opentelemetry-instrumentation-fastapi==0.59b0 diff --git a/scripts/benchmark_argon2.py b/scripts/benchmark_argon2.py new file mode 100644 index 0000000..068e0c5 --- /dev/null +++ b/scripts/benchmark_argon2.py @@ -0,0 +1,56 @@ + +import statistics +import time + +from argon2 import PasswordHasher, Type + +PASSWORD = "Lab7-Benchmark-Password-2026" +ITERATIONS = 10 + +CONFIGURATIONS = [ + ("baseline", 19456, 2, 1), + ("stronger", 32768, 3, 1), + ("high-memory", 65536, 3, 1), +] + + +def benchmark(name, memory, time_cost, parallelism): + hasher = PasswordHasher( + memory_cost=memory, + time_cost=time_cost, + parallelism=parallelism, + hash_len=32, + salt_len=16, + type=Type.ID, + ) + + samples = [] + + # Warm-up, excluded from measurements. + sample_hash = hasher.hash(PASSWORD) + assert hasher.verify(sample_hash, PASSWORD) + + for _ in range(ITERATIONS): + start = time.perf_counter() + password_hash = hasher.hash(PASSWORD) + elapsed = (time.perf_counter() - start) * 1000 + + assert hasher.verify(password_hash, PASSWORD) + assert password_hash.startswith("$argon2id$") + + samples.append(elapsed) + + print( + f"{name}: " + f"memory={memory} KiB, " + f"t={time_cost}, " + f"p={parallelism}, " + f"median={statistics.median(samples):.2f} ms, " + f"min={min(samples):.2f} ms, " + f"max={max(samples):.2f} ms" + ) + + +if __name__ == "__main__": + for configuration in CONFIGURATIONS: + benchmark(*configuration) diff --git a/scripts/bootstrap-db-credentials.py b/scripts/bootstrap-db-credentials.py new file mode 100644 index 0000000..bd27251 --- /dev/null +++ b/scripts/bootstrap-db-credentials.py @@ -0,0 +1,97 @@ +#!/usr/bin/env python3 + +import os +import secrets +import subprocess +from pathlib import Path + +ENV_FILE = Path(".env") + +ROLES = { + "messenger_api": "API_DB_PASSWORD", + "messenger_worker": "WORKER_DB_PASSWORD", + "messenger_dispatcher": "DISPATCHER_DB_PASSWORD", +} + + +def main(): + if not ENV_FILE.is_file(): + raise SystemExit("ERROR: .env not found") + + lines = ENV_FILE.read_text(encoding="utf-8").splitlines() + + existing_keys = { + line.split("=", 1)[0] + for line in lines + if "=" in line and not line.startswith("#") + } + + for env_name in ROLES.values(): + if env_name in existing_keys: + raise SystemExit( + f"ERROR: {env_name} already exists. " + "Refusing to overwrite credentials." + ) + + # Hexadecimal passwords are easy to use in connection URIs. + passwords = { + role: secrets.token_hex(32) + for role in ROLES + } + + # Passwords are sent to psql via stdin. + # They are not passed as command-line arguments. + statements = ["BEGIN;"] + + for role, password in passwords.items(): + statements.append( + f"ALTER ROLE {role} " + f"WITH LOGIN PASSWORD '{password}';" + ) + + statements.append("COMMIT;") + + sql = "\n".join(statements) + "\n" + + command = [ + "docker", "compose", "exec", "-T", + "db", + "psql", + "-X", + "-v", "ON_ERROR_STOP=1", + "-U", "messenger", + "-d", "messenger", + "-q", + ] + + result = subprocess.run( + command, + input=sql, + text=True, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + ) + + if result.returncode != 0: + print("ERROR: PostgreSQL role configuration failed.") + print("Check database availability and permissions.") + raise SystemExit(1) + + # Update the ignored local .env only after SQL succeeds. + # No secret values are printed. + with ENV_FILE.open("a", encoding="utf-8") as file: + file.write("\n# Lab7 scoped database credentials\n") + + for role, env_name in ROLES.items(): + file.write(f"{env_name}={passwords[role]}\n") + + os.chmod(ENV_FILE, 0o600) + + print("PASS: PostgreSQL service roles enabled.") + print("PASS: Independent credentials generated.") + print("PASS: Credentials saved to ignored .env.") + print("Secret values were not displayed.") + + +if __name__ == "__main__": + main() diff --git a/scripts/bootstrap-openbao-client-certs.sh b/scripts/bootstrap-openbao-client-certs.sh new file mode 100644 index 0000000..9453765 --- /dev/null +++ b/scripts/bootstrap-openbao-client-certs.sh @@ -0,0 +1,71 @@ +#!/usr/bin/env bash +set -euo pipefail + +umask 077 + +BASE="$HOME/.local/share/mtusi2026lab7/pki" +DEST="$BASE/openbao-clients" + +test -f "$BASE/ca.crt" +test -f "$BASE/ca.key" + +mkdir -p "$DEST" +chmod 700 "$DEST" + +for service in api1 api2 worker; do + cert="$DEST/${service}.crt" + key="$DEST/${service}.key" + + if [[ -e "$cert" || -e "$key" ]]; then + echo "FAIL: certificate already exists for $service" >&2 + exit 1 + fi +done + +for service in api1 api2 worker; do + name="lab7-openbao-${service}" + + temp="$(mktemp -d "$DEST/.${service}.XXXXXX")" + + openssl req \ + -new \ + -newkey rsa:3072 \ + -nodes \ + -keyout "$temp/client.key" \ + -out "$temp/client.csr" \ + -subj "/CN=$name" \ + >/dev/null 2>&1 + + cat > "$temp/extensions.cnf" </dev/null 2>&1 + + chmod 600 "$temp/client.key" + chmod 644 "$temp/client.crt" + + mv "$temp/client.key" "$DEST/${service}.key" + mv "$temp/client.crt" "$DEST/${service}.crt" + + rm -rf -- "$temp" + + echo "PASS: OpenBao client certificate issued for $service" +done + +echo "PASS: three separate OpenBao client identities created" diff --git a/scripts/bootstrap-openbao-secrets.py b/scripts/bootstrap-openbao-secrets.py new file mode 100644 index 0000000..c72a441 --- /dev/null +++ b/scripts/bootstrap-openbao-secrets.py @@ -0,0 +1,236 @@ +#!/usr/bin/env python3 +"""Copy existing API/worker credentials to OpenBao KV v2.""" + +import hmac +import json +import os +import ssl +import stat +import subprocess +import sys +import urllib.error +import urllib.request +from pathlib import Path + +BASE = Path.home() / ".local/share/mtusi2026lab7" +INIT_FILE = BASE / "operator/openbao-init.json" +CA_FILE = BASE / "pki/ca.crt" + +BAO_URL = "https://localhost:8200" + +SECRET_FIELDS = { + "api": ( + "DATABASE_URL", + "S3_ACCESS_KEY", + "S3_SECRET_KEY", + ), + "worker": ( + "DATABASE_URL", + "RABBITMQ_USER", + "RABBITMQ_PASSWORD", + "S3_ACCESS_KEY", + "S3_SECRET_KEY", + ), +} + + +def check(condition, message): + if not condition: + raise RuntimeError(message) + print("PASS:", message) + + +def request(method, path, token, context, payload=None): + data = None + if payload is not None: + data = json.dumps(payload).encode("utf-8") + + headers = {"X-Vault-Token": token} + + if data is not None: + headers["Content-Type"] = "application/json" + + req = urllib.request.Request( + BAO_URL + path, + data=data, + headers=headers, + method=method, + ) + + try: + with urllib.request.urlopen( + req, + context=context, + timeout=15, + ) as response: + body = response.read() + return ( + response.status, + json.loads(body) if body else {}, + ) + + except urllib.error.HTTPError as exc: + if exc.code == 404: + return 404, {} + + # Do not print the response body or credentials. + raise RuntimeError( + "OpenBao request failed with HTTP {}".format( + exc.code + ) + ) from None + + +def equal_secrets(actual, expected): + if set(actual) != set(expected): + return False + + return all( + isinstance(actual[key], str) + and hmac.compare_digest(actual[key], value) + for key, value in expected.items() + ) + + +def main(): + mode = stat.S_IMODE(INIT_FILE.stat().st_mode) + check(mode == 0o600, "Operator file permissions are 600") + + with INIT_FILE.open(encoding="utf-8") as file: + root_token = json.load(file)["root_token"] + + context = ssl.create_default_context( + cafile=str(CA_FILE) + ) + + result = subprocess.run( + ["docker", "compose", "config", "--format", "json"], + check=True, + capture_output=True, + text=True, + ) + + services = json.loads(result.stdout)["services"] + + api1_env = services["api1"]["environment"] + api2_env = services["api2"]["environment"] + worker_env = services["worker"]["environment"] + + check( + all( + api1_env.get(key) == api2_env.get(key) + for key in SECRET_FIELDS["api"] + ), + "API1 and API2 credentials match", + ) + + environments = { + "api": api1_env, + "worker": worker_env, + } + + values = {} + + for role, fields in SECRET_FIELDS.items(): + source = environments[role] + + values[role] = { + key: source.get(key) + for key in fields + } + + check( + all( + isinstance(value, str) and bool(value) + for value in values[role].values() + ), + "{} credentials are configured".format(role), + ) + + # Check existing KV values before making changes. + existing = {} + + for role in SECRET_FIELDS: + path = "/v1/lab7/data/{}/runtime".format(role) + + status, response = request( + "GET", + path, + root_token, + context, + ) + + if status == 404: + existing[role] = False + continue + + stored = response["data"]["data"] + + check( + equal_secrets(stored, values[role]), + "{} existing secret matches Compose".format(role), + ) + + existing[role] = True + + # New secrets are created only when absent. + # CAS=0 prevents accidental overwriting. + for role in SECRET_FIELDS: + if existing[role]: + print("PASS: {} secret already stored".format(role)) + continue + + path = "/v1/lab7/data/{}/runtime".format(role) + + status, _ = request( + "POST", + path, + root_token, + context, + { + "options": {"cas": 0}, + "data": values[role], + }, + ) + + check( + status in (200, 204), + "{} runtime secret stored".format(role), + ) + + # Read back and compare without displaying values. + for role in SECRET_FIELDS: + path = "/v1/lab7/data/{}/runtime".format(role) + + status, response = request( + "GET", + path, + root_token, + context, + ) + + check( + status == 200 + and equal_secrets( + response["data"]["data"], + values[role], + ), + "{} KV v2 readback verified".format(role), + ) + + print("PASS: OpenBao HTTPS certificate verified") + print("PASS: API and worker secrets separated") + print("PASS: no credential values printed") + print("PASS: working application configuration unchanged") + + +if __name__ == "__main__": + try: + main() + except Exception as exc: + print( + "FAIL: secret bootstrap:", + type(exc).__name__, + file=sys.stderr, + ) + raise SystemExit(1) diff --git a/scripts/bootstrap-openbao-tls.sh b/scripts/bootstrap-openbao-tls.sh new file mode 100644 index 0000000..db07840 --- /dev/null +++ b/scripts/bootstrap-openbao-tls.sh @@ -0,0 +1,73 @@ +#!/usr/bin/env bash +set -Eeuo pipefail + +PKI_DIR="${LAB7_PKI_DIR:-$HOME/.local/share/mtusi2026lab7/pki}" + +if [[ ! -f "$PKI_DIR/ca.crt" || ! -f "$PKI_DIR/ca.key" ]]; then + echo "FAIL: existing CA certificate or key is missing" + exit 1 +fi + +if [[ -e "$PKI_DIR/openbao.crt" || -e "$PKI_DIR/openbao.key" ]]; then + echo "FAIL: OpenBao TLS files already exist; refusing to overwrite" + exit 1 +fi + +umask 077 + +WORK_DIR="$(mktemp -d)" +trap 'rm -rf "$WORK_DIR"' EXIT + +openssl genpkey \ + -algorithm RSA \ + -pkeyopt rsa_keygen_bits:3072 \ + -out "$WORK_DIR/openbao.key" 2>/dev/null + +openssl req -new -sha256 \ + -key "$WORK_DIR/openbao.key" \ + -subj "/CN=openbao" \ + -out "$WORK_DIR/openbao.csr" + +cat > "$WORK_DIR/openbao.ext" <<'EOF' +basicConstraints=critical,CA:FALSE +keyUsage=critical,digitalSignature,keyEncipherment +extendedKeyUsage=serverAuth +subjectAltName=DNS:openbao,DNS:localhost,IP:127.0.0.1 +EOF + +openssl x509 -req -sha256 \ + -in "$WORK_DIR/openbao.csr" \ + -CA "$PKI_DIR/ca.crt" \ + -CAkey "$PKI_DIR/ca.key" \ + -CAserial "$PKI_DIR/ca.srl" \ + -CAcreateserial \ + -out "$WORK_DIR/openbao.crt" \ + -days 365 \ + -extfile "$WORK_DIR/openbao.ext" + +openssl verify \ + -CAfile "$PKI_DIR/ca.crt" \ + -purpose sslserver \ + -verify_hostname openbao \ + "$WORK_DIR/openbao.crt" + +openssl verify \ + -CAfile "$PKI_DIR/ca.crt" \ + -purpose sslserver \ + -verify_hostname localhost \ + "$WORK_DIR/openbao.crt" + +install -m 644 \ + "$WORK_DIR/openbao.crt" \ + "$PKI_DIR/openbao.crt" + +# The OpenBao container runs with UID=100 and GID=1000. +sudo install -o 100 -g 1000 -m 600 \ + "$WORK_DIR/openbao.key" \ + "$PKI_DIR/openbao.key" + +echo "PASS: OpenBao TLS certificate issued" +echo "PASS: existing CA trusted" +echo "PASS: SAN contains openbao and localhost" +echo "PASS: private key owned by UID=100 GID=1000" +echo "PASS: private key permissions are 600" diff --git a/scripts/bootstrap-pki.sh b/scripts/bootstrap-pki.sh new file mode 100644 index 0000000..821a011 --- /dev/null +++ b/scripts/bootstrap-pki.sh @@ -0,0 +1,172 @@ +#!/usr/bin/env bash +set -euo pipefail +umask 077 + +PKI_DIR="${LAB7_PKI_DIR:-$HOME/.local/share/mtusi2026lab7/pki}" + +mkdir -p "$PKI_DIR" +chmod 700 "$PKI_DIR" + +# Never overwrite an existing CA. +if [[ -e "$PKI_DIR/ca.key" || -e "$PKI_DIR/ca.crt" ]]; then + echo "ERROR: PKI already exists at $PKI_DIR" + echo "Refusing to replace existing keys." + exit 1 +fi + +for tool in openssl mktemp; do + command -v "$tool" >/dev/null || { + echo "Missing tool: $tool" + exit 1 + } +done + +WORK_DIR="$(mktemp -d)" +trap 'rm -rf "$WORK_DIR"' EXIT + +create_ca() { + local prefix="$1" + local common_name="$2" + + openssl genpkey \ + -algorithm RSA \ + -pkeyopt rsa_keygen_bits:3072 \ + -out "$PKI_DIR/$prefix.key" 2>/dev/null + + openssl req -x509 -new -sha256 \ + -days 365 \ + -key "$PKI_DIR/$prefix.key" \ + -out "$PKI_DIR/$prefix.crt" \ + -subj "/CN=$common_name" \ + -addext "basicConstraints=critical,CA:TRUE,pathlen:0" \ + -addext "keyUsage=critical,keyCertSign,cRLSign" + + chmod 600 "$PKI_DIR/$prefix.key" + chmod 644 "$PKI_DIR/$prefix.crt" +} + +create_leaf() { + local name="$1" + local common_name="$2" + local san="$3" + local usage="$4" + local ca_prefix="${5:-ca}" + + openssl genpkey \ + -algorithm RSA \ + -pkeyopt rsa_keygen_bits:2048 \ + -out "$PKI_DIR/$name.key" 2>/dev/null + + openssl req -new -sha256 \ + -key "$PKI_DIR/$name.key" \ + -out "$WORK_DIR/$name.csr" \ + -subj "/CN=$common_name" + + cat > "$WORK_DIR/$name.ext" </dev/null + + chmod 600 "$PKI_DIR/$name.key" + chmod 644 "$PKI_DIR/$name.crt" +} + +echo "Generating lab7 private CA..." +create_ca ca "MTUSI Lab7 Local CA" + +echo "Generating HTTPS ingress certificate..." +create_leaf \ + ingress \ + localhost \ + "DNS:localhost,IP:127.0.0.1" \ + serverAuth + +echo "Generating API server certificates..." +create_leaf \ + api1 \ + api1 \ + "DNS:api1,DNS:messenger-api.internal" \ + serverAuth + +create_leaf \ + api2 \ + api2 \ + "DNS:api2,DNS:messenger-api.internal" \ + serverAuth + +echo "Generating authorized LB client certificate..." +create_leaf \ + lb-client \ + lb.messenger.internal \ + "DNS:lb.messenger.internal" \ + clientAuth + +echo "Generating unauthorized client identity..." +create_leaf \ + unauthorized-client \ + unauthorized.messenger.internal \ + "DNS:unauthorized.messenger.internal" \ + clientAuth + +echo "Generating separate untrusted CA..." +create_ca rogue-ca "MTUSI Lab7 Untrusted Test CA" + +create_leaf \ + rogue-client \ + rogue.messenger.internal \ + "DNS:rogue.messenger.internal" \ + clientAuth \ + rogue-ca + +echo "Verifying issued certificates..." + +openssl verify \ + -CAfile "$PKI_DIR/ca.crt" \ + -purpose sslserver \ + -verify_hostname localhost \ + "$PKI_DIR/ingress.crt" + +openssl verify \ + -CAfile "$PKI_DIR/ca.crt" \ + -purpose sslserver \ + -verify_hostname api1 \ + "$PKI_DIR/api1.crt" + +openssl verify \ + -CAfile "$PKI_DIR/ca.crt" \ + -purpose sslserver \ + -verify_hostname api2 \ + "$PKI_DIR/api2.crt" + +openssl verify \ + -CAfile "$PKI_DIR/ca.crt" \ + -purpose sslclient \ + "$PKI_DIR/lb-client.crt" + +openssl verify \ + -CAfile "$PKI_DIR/ca.crt" \ + -purpose sslclient \ + "$PKI_DIR/unauthorized-client.crt" + +echo +echo "PASS: local CA and TLS certificates generated." +echo "PKI directory: $PKI_DIR" +echo "CA certificate: $PKI_DIR/ca.crt" +echo +echo "IMPORTANT:" +echo "- Never commit private keys." +echo "- Keep the CA private key operator-only." +echo "- Do not copy the PKI directory into Docker images." +echo "- Unauthorized and rogue certificates are test fixtures only." diff --git a/scripts/bootstrap-postgres-tls.sh b/scripts/bootstrap-postgres-tls.sh new file mode 100644 index 0000000..fbb1581 --- /dev/null +++ b/scripts/bootstrap-postgres-tls.sh @@ -0,0 +1,68 @@ +#!/usr/bin/env bash +set -euo pipefail +umask 077 + +PKI_DIR="${LAB7_PKI_DIR:-$HOME/.local/share/mtusi2026lab7/pki}" + +if [[ ! -f "$PKI_DIR/ca.crt" || ! -f "$PKI_DIR/ca.key" ]]; then + echo "ERROR: Lab7 CA not found." + exit 1 +fi + +if [[ -e "$PKI_DIR/db.key" || -e "$PKI_DIR/db.crt" ]]; then + echo "ERROR: PostgreSQL certificate already exists." + echo "Refusing to overwrite existing credentials." + exit 1 +fi + +WORK_DIR="$(mktemp -d)" +trap 'rm -rf "$WORK_DIR"' EXIT + +echo "Generating PostgreSQL private key..." + +openssl genpkey \ + -algorithm RSA \ + -pkeyopt rsa_keygen_bits:2048 \ + -out "$WORK_DIR/db.key" 2>/dev/null + +echo "Creating certificate signing request..." + +openssl req -new -sha256 \ + -key "$WORK_DIR/db.key" \ + -out "$WORK_DIR/db.csr" \ + -subj "/CN=db" + +cat > "$WORK_DIR/db.ext" </dev/null + +echo "Verifying CA and hostname..." + +openssl verify \ + -CAfile "$PKI_DIR/ca.crt" \ + -purpose sslserver \ + -verify_hostname db \ + "$WORK_DIR/db.crt" + +install -m 600 "$WORK_DIR/db.key" "$PKI_DIR/db.key" +install -m 644 "$WORK_DIR/db.crt" "$PKI_DIR/db.crt" + +echo +echo "PASS: PostgreSQL TLS certificate created." +echo "SAN: DNS:db" +echo "Private key retained outside Git." diff --git a/scripts/bootstrap-rabbitmq-credentials.py b/scripts/bootstrap-rabbitmq-credentials.py new file mode 100644 index 0000000..a6ecd30 --- /dev/null +++ b/scripts/bootstrap-rabbitmq-credentials.py @@ -0,0 +1,123 @@ +#!/usr/bin/env python3 +"""Create separate RabbitMQ service accounts without printing passwords.""" + +import os +import secrets +import subprocess +from pathlib import Path + +ENV_FILE = Path(".env") + +ACCOUNTS = { + "messenger_publisher": { + "env": "RABBITMQ_PUBLISHER_PASSWORD", + "configure": "^image_jobs$", + "write": r"^amq\.default$", + "read": "^$", + }, + "messenger_consumer": { + "env": "RABBITMQ_CONSUMER_PASSWORD", + "configure": "^image_jobs$", + "write": "^$", + "read": "^image_jobs$", + }, +} + + +def rabbitmqctl(*arguments, password=None): + command = [ + "docker", "compose", "exec", "-T", + "rabbitmq", "rabbitmqctl", + *arguments, + ] + + result = subprocess.run( + command, + input=None if password is None else password + "\n", + text=True, + capture_output=True, + ) + + if result.returncode != 0: + raise RuntimeError( + "RabbitMQ command failed: " + arguments[0] + ) + + return result.stdout + + +def main(): + if not ENV_FILE.is_file(): + raise SystemExit("ERROR: .env not found") + + contents = ENV_FILE.read_text(encoding="utf-8") + + for account in ACCOUNTS.values(): + key = account["env"] + if any( + line.strip().startswith(key + "=") + for line in contents.splitlines() + ): + raise SystemExit( + f"ERROR: {key} already exists in .env" + ) + + try: + existing_users = rabbitmqctl("list_users") + except RuntimeError as exc: + raise SystemExit(str(exc)) + + for username in ACCOUNTS: + if any( + line.split("\t")[0].strip() == username + for line in existing_users.splitlines() + ): + raise SystemExit( + f"ERROR: {username} already exists in RabbitMQ" + ) + + generated = {} + + try: + for username, settings in ACCOUNTS.items(): + password = secrets.token_hex(32) + + rabbitmqctl( + "add_user", username, + password=password, + ) + + rabbitmqctl( + "set_permissions", + "-p", "/", + username, + settings["configure"], + settings["write"], + settings["read"], + ) + + generated[settings["env"]] = password + print(f"PASS: {username} created with scoped ACL") + + except RuntimeError as exc: + print("ERROR:", exc) + print( + "RabbitMQ may contain partially created accounts. " + "Do not rerun automatically." + ) + raise SystemExit(1) + + with ENV_FILE.open("a", encoding="utf-8") as file: + file.write("\n# Lab7 RabbitMQ service credentials\n") + for key, password in generated.items(): + file.write(f"{key}={password}\n") + + os.chmod(ENV_FILE, 0o600) + + print("PASS: RabbitMQ passwords stored in ignored .env") + print("PASS: No passwords printed") + print("Existing application credentials were not changed") + + +if __name__ == "__main__": + main() diff --git a/scripts/bootstrap-rustfs-credentials.py b/scripts/bootstrap-rustfs-credentials.py new file mode 100644 index 0000000..df1e058 --- /dev/null +++ b/scripts/bootstrap-rustfs-credentials.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python3 +"""Generate scoped RustFS credentials in the local .env file.""" + +import os +import re +import secrets +from pathlib import Path + + +ENV_FILE = Path(__file__).resolve().parent.parent / ".env" + +CREDENTIALS = { + "S3_API_ACCESS_KEY": "messenger_s3_api", + "S3_API_SECRET_KEY": secrets.token_hex(32), + "S3_WORKER_ACCESS_KEY": "messenger_s3_worker", + "S3_WORKER_SECRET_KEY": secrets.token_hex(32), +} + + +def main(): + if not ENV_FILE.is_file(): + raise SystemExit("FAIL: existing .env file not found") + + original = ENV_FILE.read_text(encoding="utf-8") + + existing = set( + re.findall( + r"^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=", + original, + flags=re.MULTILINE, + ) + ) + + conflicts = existing.intersection(CREDENTIALS) + + if conflicts: + print("FAIL: S3 service credentials already exist") + print("Existing variable names:", ", ".join(sorted(conflicts))) + print("Refusing to overwrite existing credentials") + raise SystemExit(1) + + addition = "\n# Scoped RustFS IAM credentials\n" + + for name, value in CREDENTIALS.items(): + addition += f"{name}={value}\n" + + prefix = "" if not original or original.endswith("\n") else "\n" + + with ENV_FILE.open("a", encoding="utf-8") as file: + file.write(prefix + addition) + + if os.name == "posix": + ENV_FILE.chmod(0o600) + + print("PASS: API IAM credentials generated") + print("PASS: worker IAM credentials generated") + print("PASS: credentials saved to local .env") + print("PASS: existing S3 root credentials preserved") + + +if __name__ == "__main__": + main() diff --git a/scripts/bootstrap-rustfs-tls.sh b/scripts/bootstrap-rustfs-tls.sh new file mode 100644 index 0000000..7349152 --- /dev/null +++ b/scripts/bootstrap-rustfs-tls.sh @@ -0,0 +1,76 @@ +#!/usr/bin/env bash +set -Eeuo pipefail + +PKI_DIR="${LAB7_PKI_DIR:-$HOME/.local/share/mtusi2026lab7/pki}" +TLS_DIR="$PKI_DIR/rustfs-tls" + +if [[ ! -f "$PKI_DIR/ca.crt" || ! -f "$PKI_DIR/ca.key" ]]; then + echo "FAIL: existing CA certificate or key is missing" + exit 1 +fi + +if [[ -e "$TLS_DIR/rustfs_cert.pem" || -e "$TLS_DIR/rustfs_key.pem" ]]; then + echo "FAIL: RustFS TLS files already exist; refusing to overwrite" + exit 1 +fi + +umask 077 + +WORK_DIR="$(mktemp -d)" +trap 'rm -rf "$WORK_DIR"' EXIT + +openssl genpkey \ + -algorithm RSA \ + -pkeyopt rsa_keygen_bits:3072 \ + -out "$WORK_DIR/rustfs_key.pem" 2>/dev/null + +openssl req -new -sha256 \ + -key "$WORK_DIR/rustfs_key.pem" \ + -subj "/CN=minio" \ + -out "$WORK_DIR/rustfs.csr" + +cat > "$WORK_DIR/rustfs.ext" <<'EOF' +basicConstraints=critical,CA:FALSE +keyUsage=critical,digitalSignature,keyEncipherment +extendedKeyUsage=serverAuth +subjectAltName=DNS:minio +EOF + +openssl x509 -req -sha256 \ + -in "$WORK_DIR/rustfs.csr" \ + -CA "$PKI_DIR/ca.crt" \ + -CAkey "$PKI_DIR/ca.key" \ + -CAserial "$PKI_DIR/ca.srl" \ + -CAcreateserial \ + -out "$WORK_DIR/rustfs_cert.pem" \ + -days 365 \ + -extfile "$WORK_DIR/rustfs.ext" + +openssl verify \ + -CAfile "$PKI_DIR/ca.crt" \ + -purpose sslserver \ + -verify_hostname minio \ + "$WORK_DIR/rustfs_cert.pem" + +mkdir -p "$TLS_DIR" +chmod 700 "$TLS_DIR" + +install -m 644 \ + "$WORK_DIR/rustfs_cert.pem" \ + "$TLS_DIR/rustfs_cert.pem" + +install -m 600 \ + "$WORK_DIR/rustfs_key.pem" \ + "$TLS_DIR/rustfs_key.pem" + +# RustFS inside Docker runs with UID/GID 10001. +sudo chown 10001:10001 \ + "$TLS_DIR/rustfs_cert.pem" \ + "$TLS_DIR/rustfs_key.pem" + +chmod 750 "$TLS_DIR" + +echo "PASS: RustFS certificate issued and verified" +echo "PASS: SAN DNS:minio" +echo "PASS: RustFS private key owned by UID/GID 10001" +echo "TLS directory: $TLS_DIR" diff --git a/scripts/configure-openbao-cert-auth.py b/scripts/configure-openbao-cert-auth.py new file mode 100644 index 0000000..902a4d8 --- /dev/null +++ b/scripts/configure-openbao-cert-auth.py @@ -0,0 +1,124 @@ +#!/usr/bin/env python3 +"""Configure scoped certificate authentication in OpenBao.""" + +import json +import ssl +import sys +import urllib.error +import urllib.request +from pathlib import Path + +BASE = Path.home() / ".local/share/mtusi2026lab7" +URL = "https://localhost:8200/v1" + +SERVICES = { + "api1": "messenger-api", + "api2": "messenger-api", + "worker": "messenger-worker", +} + + +def request(method, path, token, tls, payload=None): + headers = {"X-Vault-Token": token} + body = None + + if payload is not None: + body = json.dumps(payload).encode("utf-8") + headers["Content-Type"] = "application/json" + + req = urllib.request.Request( + URL + path, + data=body, + headers=headers, + method=method, + ) + + with urllib.request.urlopen( + req, + context=tls, + timeout=15, + ) as response: + raw = response.read() + return json.loads(raw) if raw else {} + + +def main(): + with (BASE / "operator/openbao-init.json").open( + encoding="utf-8" + ) as file: + root_token = json.load(file)["root_token"] + + tls = ssl.create_default_context( + cafile=str(BASE / "pki/ca.crt") + ) + + methods = request( + "GET", + "/sys/auth", + root_token, + tls, + ) + + if "cert/" not in methods: + request( + "POST", + "/sys/auth/cert", + root_token, + tls, + {"type": "cert"}, + ) + print("PASS: certificate auth method enabled") + elif methods["cert/"]["type"] == "cert": + print("PASS: certificate auth method already enabled") + else: + raise RuntimeError("Unexpected auth method at cert/") + + for service, policy in SERVICES.items(): + certificate = ( + BASE + / "pki/openbao-clients" + / f"{service}.crt" + ).read_text(encoding="ascii") + + request( + "POST", + f"/auth/cert/certs/lab7-{service}", + root_token, + tls, + { + "certificate": certificate, + "display_name": f"lab7-{service}", + "token_policies": [policy], + "token_no_default_policy": True, + "token_ttl": "1200s", + "token_max_ttl": "3600s", + "token_type": "service", + "token_num_uses": 0, + }, + ) + + print( + f"PASS: {service} certificate registered " + f"with {policy} policy" + ) + + print("PASS: three scoped certificate identities configured") + print("PASS: no private keys or tokens printed") + + +if __name__ == "__main__": + try: + main() + except urllib.error.HTTPError as exc: + print( + f"FAIL: OpenBao HTTP {exc.code}", + file=sys.stderr, + ) + raise SystemExit(1) + except Exception as exc: + print( + "FAIL: certificate auth configuration:", + type(exc).__name__, + file=sys.stderr, + ) + raise SystemExit(1) diff --git a/scripts/issue-openbao-bootstrap.py b/scripts/issue-openbao-bootstrap.py new file mode 100644 index 0000000..87295ba --- /dev/null +++ b/scripts/issue-openbao-bootstrap.py @@ -0,0 +1,150 @@ +#!/usr/bin/env python3 +"""Issue a fresh one-time OpenBao AppRole bootstrap identity.""" + +import argparse +import json +import os +import ssl +import stat +import sys +import urllib.error +import urllib.request +from pathlib import Path + +BASE = Path.home() / ".local/share/mtusi2026lab7" +OPERATOR = BASE / "operator" +INIT_FILE = OPERATOR / "openbao-init.json" + +SERVICES = { + "api1": "messenger-api", + "api2": "messenger-api", + "worker": "messenger-worker", +} + + +def request(method, path, token, tls, payload=None): + body = None + + if payload is not None: + body = json.dumps(payload).encode("utf-8") + + headers = {"X-Vault-Token": token} + + if body is not None: + headers["Content-Type"] = "application/json" + + req = urllib.request.Request( + "https://localhost:8200/v1" + path, + data=body, + headers=headers, + method=method, + ) + + with urllib.request.urlopen( + req, + context=tls, + timeout=15, + ) as response: + data = response.read() + return json.loads(data) if data else {} + + +def write_private(path, value): + fd = os.open( + path, + os.O_WRONLY | os.O_CREAT | os.O_EXCL, + 0o600, + ) + + with os.fdopen(fd, "w", encoding="utf-8") as file: + file.write(value + "\n") + + +def main(): + parser = argparse.ArgumentParser( + description="Issue one-time OpenBao bootstrap credentials" + ) + + parser.add_argument( + "service", + choices=sorted(SERVICES), + ) + + args = parser.parse_args() + + if stat.S_IMODE(INIT_FILE.stat().st_mode) != 0o600: + raise RuntimeError("Operator file must have mode 600") + + role = SERVICES[args.service] + + destination = OPERATOR / "approle" / args.service + + # Never overwrite credentials that may still be in use. + if destination.exists(): + raise RuntimeError( + "Bootstrap directory already exists; refusing overwrite" + ) + + with INIT_FILE.open(encoding="utf-8") as file: + root_token = json.load(file)["root_token"] + + tls = ssl.create_default_context( + cafile=str(BASE / "pki/ca.crt") + ) + + role_result = request( + "GET", + f"/auth/approle/role/{role}/role-id", + root_token, + tls, + ) + + role_id = role_result["data"]["role_id"] + + secret_result = request( + "POST", + f"/auth/approle/role/{role}/secret-id", + root_token, + tls, + {}, + ) + + secret_id = secret_result["data"]["secret_id"] + + os.umask(0o077) + + destination.mkdir(parents=True, mode=0o700) + + try: + write_private(destination / "role-id", role_id) + write_private(destination / "secret-id", secret_id) + except Exception: + for name in ("role-id", "secret-id"): + (destination / name).unlink(missing_ok=True) + destination.rmdir() + raise + + print(f"PASS: fresh bootstrap credentials issued for {args.service}") + print("PASS: separate AppRole identity used") + print("PASS: credentials stored outside Git") + print("PASS: credential files created with mode 600") + print("PASS: credential values not printed") + print("INFO: SecretID is valid for 30 minutes and one login") + + +if __name__ == "__main__": + try: + main() + except urllib.error.HTTPError as exc: + print( + f"FAIL: OpenBao returned HTTP {exc.code}", + file=sys.stderr, + ) + raise SystemExit(1) + except Exception as exc: + print( + "FAIL: bootstrap issuance:", + type(exc).__name__, + file=sys.stderr, + ) + raise SystemExit(1) diff --git a/scripts/reissue-api-certs.sh b/scripts/reissue-api-certs.sh new file mode 100644 index 0000000..f0bda8c --- /dev/null +++ b/scripts/reissue-api-certs.sh @@ -0,0 +1,67 @@ +#!/usr/bin/env bash +set -euo pipefail +umask 077 + +PKI_DIR="${LAB7_PKI_DIR:-$HOME/.local/share/mtusi2026lab7/pki}" + +if [[ ! -f "$PKI_DIR/ca.crt" || ! -f "$PKI_DIR/ca.key" ]]; then + echo "ERROR: Existing CA not found." + exit 1 +fi + +WORK_DIR="$(mktemp -d)" +trap 'rm -rf "$WORK_DIR"' EXIT + +for name in api1 api2; do + echo "Reissuing certificate for $name..." + + openssl genpkey \ + -algorithm RSA \ + -pkeyopt rsa_keygen_bits:2048 \ + -out "$WORK_DIR/$name.key" 2>/dev/null + + openssl req -new -sha256 \ + -key "$WORK_DIR/$name.key" \ + -out "$WORK_DIR/$name.csr" \ + -subj "/CN=$name" + + cat > "$WORK_DIR/$name.ext" </dev/null + + openssl verify \ + -CAfile "$PKI_DIR/ca.crt" \ + -purpose sslserver \ + -verify_hostname "$name" \ + "$WORK_DIR/$name.crt" + + openssl verify \ + -CAfile "$PKI_DIR/ca.crt" \ + -purpose sslserver \ + -verify_hostname messenger-api.internal \ + "$WORK_DIR/$name.crt" + + cat "$WORK_DIR/$name.crt" "$WORK_DIR/$name.key" \ + > "$WORK_DIR/$name.pem" + + # Replace only after both hostname checks have passed. + install -m 600 "$WORK_DIR/$name.key" "$PKI_DIR/$name.key" + install -m 644 "$WORK_DIR/$name.crt" "$PKI_DIR/$name.crt" + install -m 600 "$WORK_DIR/$name.pem" "$PKI_DIR/$name.pem" + +done + +echo +echo "PASS: API certificates reissued with shared service SAN." diff --git a/scripts/reissue-openbao-bootstrap.py b/scripts/reissue-openbao-bootstrap.py new file mode 100644 index 0000000..6195300 --- /dev/null +++ b/scripts/reissue-openbao-bootstrap.py @@ -0,0 +1,156 @@ +#!/usr/bin/env python3 +"""Replace previously issued OpenBao bootstrap credentials.""" + +import argparse +import json +import os +import runpy +import shutil +import ssl +import stat +import sys +import tempfile +import urllib.error +from pathlib import Path + +HELPERS = runpy.run_path( + str(Path(__file__).with_name("issue-openbao-bootstrap.py")) +) + +BASE = HELPERS["BASE"] +OPERATOR = HELPERS["OPERATOR"] +INIT_FILE = HELPERS["INIT_FILE"] +SERVICES = HELPERS["SERVICES"] +request = HELPERS["request"] +write_private = HELPERS["write_private"] + + +def main(): + parser = argparse.ArgumentParser( + description="Reissue existing OpenBao AppRole credentials" + ) + parser.add_argument("service", choices=sorted(SERVICES)) + args = parser.parse_args() + + role = SERVICES[args.service] + parent = OPERATOR / "approle" + destination = parent / args.service + + if not destination.is_dir() or destination.is_symlink(): + raise RuntimeError( + "Existing bootstrap directory required" + ) + + if stat.S_IMODE(INIT_FILE.stat().st_mode) != 0o600: + raise RuntimeError("Operator file must have mode 600") + + old_role_file = destination / "role-id" + old_secret_file = destination / "secret-id" + + for path in (old_role_file, old_secret_file): + if not path.is_file() or path.is_symlink(): + raise RuntimeError("Invalid existing credential file") + + old_secret_id = old_secret_file.read_text( + encoding="utf-8" + ).strip() + + with INIT_FILE.open(encoding="utf-8") as file: + root_token = json.load(file)["root_token"] + + tls = ssl.create_default_context( + cafile=str(BASE / "pki/ca.crt") + ) + + role_result = request( + "GET", + f"/auth/approle/role/{role}/role-id", + root_token, + tls, + ) + role_id = role_result["data"]["role_id"] + + os.umask(0o077) + + with tempfile.TemporaryDirectory( + prefix=f".{args.service}-new-", + dir=parent, + ) as temp: + staging = Path(temp) / "credentials" + staging.mkdir(mode=0o700) + + secret_result = request( + "POST", + f"/auth/approle/role/{role}/secret-id", + root_token, + tls, + {}, + ) + + new_secret_id = secret_result["data"]["secret_id"] + + try: + write_private(staging / "role-id", role_id) + write_private(staging / "secret-id", new_secret_id) + except Exception: + try: + request( + "POST", + f"/auth/approle/role/{role}/secret-id/destroy", + root_token, + tls, + {"secret_id": new_secret_id}, + ) + except Exception: + print( + "WARNING: unused new SecretID cleanup failed", + file=sys.stderr, + ) + raise + + backup = Path(temp) / "previous" + + os.replace(destination, backup) + + try: + os.replace(staging, destination) + except Exception: + os.replace(backup, destination) + raise + + # The replacement is now installed. + # Revoke the previous SecretID if it is still valid. + try: + request( + "POST", + f"/auth/approle/role/{role}/secret-id/destroy", + root_token, + tls, + {"secret_id": old_secret_id}, + ) + except urllib.error.HTTPError as exc: + # A previously consumed SecretID may already be absent. + print( + f"INFO: previous SecretID cleanup HTTP {exc.code}" + ) + + shutil.rmtree(backup) + + print(f"PASS: credentials reissued for {args.service}") + print("PASS: previous credential directory replaced") + print("PASS: new files stored outside Git") + print("PASS: credentials not printed") + print("INFO: new SecretID expires in 30 minutes") + print("INFO: new SecretID supports one authentication") + + +if __name__ == "__main__": + try: + main() + except Exception as exc: + print( + "FAIL: reissuance:", + type(exc).__name__, + file=sys.stderr, + ) + raise SystemExit(1) diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100644 index 0000000..ef399c6 --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,25 @@ +#!/usr/bin/env bash +set -euo pipefail + +cd "$(dirname "$0")/.." + +echo "[1/5] Stopping API sidecars and application services" +docker compose stop \ + api1-mtls api2-mtls \ + api1 api2 worker dispatcher + +echo "[2/5] Restarting persistent dependencies" +docker compose restart db minio rabbitmq + +echo "[3/5] Waiting for PostgreSQL and RabbitMQ" +docker compose up -d --no-deps --wait db rabbitmq + +echo "[4/5] Starting application services" +docker compose up -d --no-deps dispatcher worker +docker compose up -d --no-deps --wait api1 api2 + +echo "[5/5] Recreating mTLS sidecars" +docker compose up -d --no-deps --force-recreate \ + api1-mtls api2-mtls + +echo "PASS: services restarted without removing volumes" diff --git a/scripts/stop-one.sh b/scripts/stop-one.sh new file mode 100644 index 0000000..148d4d5 --- /dev/null +++ b/scripts/stop-one.sh @@ -0,0 +1,38 @@ +#!/usr/bin/env bash +set -euo pipefail + +cd "$(dirname "$0")/.." + +if [[ -z "${TARGET_INSTANCE_ID:-}" ]]; then + echo "FAIL: TARGET_INSTANCE_ID is missing" >&2 + exit 1 +fi + +for service in api1 api2; do + + instance_id=$( + docker compose exec -T "$service" python -c ' +import urllib.request + +with urllib.request.urlopen( + "http://127.0.0.1:8080/health/live", + timeout=2, +) as response: + print(response.headers.get("X-Instance-Id", "")) +' 2>/dev/null + ) || continue + + if [[ "$instance_id" == "$TARGET_INSTANCE_ID" ]]; then + + echo "Stopping replica: $service" + + docker compose stop -t 2 \ + "${service}-mtls" "$service" + + echo "PASS: target replica stopped" + exit 0 + fi +done + +echo "FAIL: target API instance not found" >&2 +exit 1 diff --git a/scripts/test-db-acl.py b/scripts/test-db-acl.py new file mode 100644 index 0000000..64a2a8f --- /dev/null +++ b/scripts/test-db-acl.py @@ -0,0 +1,122 @@ +#!/usr/bin/env python3 + +import os +import sys + +import psycopg + +ROLE_TESTS = { + "messenger_api": { + "allowed": [ + ("read users", "SELECT id FROM public.users LIMIT 0"), + ("read sessions", "SELECT * FROM public.sessions LIMIT 0"), + ("read jobs", "SELECT id FROM public.attachment_jobs LIMIT 0"), + ], + "denied": [ + ("read migration history", + "SELECT * FROM public.schema_migrations LIMIT 0"), + ("create tables", + "CREATE TABLE public.lab7_acl_test (id integer)"), + ], + }, + + "messenger_worker": { + "allowed": [ + ("read jobs", "SELECT id FROM public.attachment_jobs LIMIT 0"), + ("read attachments", "SELECT id FROM public.attachments LIMIT 0"), + ("read variants", "SELECT * FROM public.attachment_variants LIMIT 0"), + ], + "denied": [ + ("read users", "SELECT * FROM public.users LIMIT 0"), + ("read sessions", "SELECT * FROM public.sessions LIMIT 0"), + ("read messages", "SELECT * FROM public.messages LIMIT 0"), + ], + }, + + "messenger_dispatcher": { + "allowed": [ + ("read jobs", "SELECT id FROM public.attachment_jobs LIMIT 0"), + ], + "denied": [ + ("read users", "SELECT * FROM public.users LIMIT 0"), + ("read sessions", "SELECT * FROM public.sessions LIMIT 0"), + ("read messages", "SELECT * FROM public.messages LIMIT 0"), + ("read attachments", "SELECT * FROM public.attachments LIMIT 0"), + ], + }, +} + + +def run_query(conn, label, sql, should_succeed): + # Every test runs in its own transaction. + # All changes are rolled back, even if an unexpected + # permission grants the operation. + try: + with conn.transaction(): + with conn.cursor() as cursor: + cursor.execute(sql) + + if should_succeed: + print(f"PASS: allowed - {label}") + else: + print(f"FAIL: forbidden operation succeeded - {label}") + return False + + except psycopg.errors.InsufficientPrivilege: + if should_succeed: + print(f"FAIL: allowed operation denied - {label}") + return False + + print(f"PASS: denied - {label}") + return True + + except psycopg.Error as exc: + print(f"FAIL: unexpected SQL error - {label}") + print(f"SQLSTATE: {exc.sqlstate}") + return False + + return should_succeed + + +def main(): + url = os.environ["DATABASE_URL"] + + if "sslmode=verify-full" not in url: + raise SystemExit("FAIL: sslmode=verify-full not configured") + + passed = True + + # Autocommit allows each conn.transaction() to be independent. + with psycopg.connect(url, autocommit=True) as conn: + role, encrypted, version = conn.execute(""" + SELECT current_user, ssl, version + FROM pg_stat_ssl + WHERE pid = pg_backend_pid() + """).fetchone() + + print(f"PostgreSQL role: {role}") + print(f"TLS encrypted: {encrypted}") + print(f"TLS version: {version}") + + if not encrypted or role not in ROLE_TESTS: + raise SystemExit("FAIL: unexpected role or TLS state") + + tests = ROLE_TESTS[role] + + for label, sql in tests["allowed"]: + if not run_query(conn, label, sql, True): + passed = False + + for label, sql in tests["denied"]: + if not run_query(conn, label, sql, False): + passed = False + + if passed: + print(f"PASS: all ACL tests for {role}") + else: + print(f"FAIL: ACL tests for {role}") + sys.exit(1) + + +if __name__ == "__main__": + main() diff --git a/scripts/test-db-incident.py b/scripts/test-db-incident.py new file mode 100644 index 0000000..8a16533 --- /dev/null +++ b/scripts/test-db-incident.py @@ -0,0 +1,175 @@ + +import base64 +import json +import subprocess +import time +import urllib.error +import urllib.request +import uuid + + +BASE_URL = "http://127.0.0.1:8080" + + +def docker(*args): + subprocess.run( + ["docker", "compose", *args], + check=True, + ) + + +def request(method, path, body=None, headers=None): + request_headers = dict(headers or {}) + + if isinstance(body, dict): + body = json.dumps(body).encode("utf-8") + request_headers["Content-Type"] = "application/json" + + req = urllib.request.Request( + BASE_URL + path, + data=body, + headers=request_headers, + method=method, + ) + + started = time.monotonic() + + try: + with urllib.request.urlopen(req, timeout=5) as response: + response.read() + return response.status, time.monotonic() - started + + except urllib.error.HTTPError as exc: + exc.read() + return exc.code, time.monotonic() - started + + except (urllib.error.URLError, TimeoutError) as exc: + return type(exc).__name__, time.monotonic() - started + + +def login_header(username, password): + encoded = base64.b64encode( + f"{username}:{password}".encode("utf-8") + ).decode("ascii") + + return { + "Authorization": f"Basic {encoded}" + } + + +def wait_for_recovery(headers): + deadline = time.monotonic() + 90 + + while time.monotonic() < deadline: + status, duration = request( + "POST", + "/api/v1/auth/sessions", + body=b"", + headers=headers, + ) + + if status == 201: + print( + f"Recovery: HTTP 201, {duration:.3f}s", + flush=True, + ) + return + + time.sleep(2) + + raise RuntimeError( + "Authentication did not recover after DB restart" + ) + + +def main(): + suffix = uuid.uuid4().hex[:12] + + username = "lab6_db_" + suffix + password = "IncidentTest_" + suffix + + status, duration = request( + "POST", + "/api/v1/users", + body={ + "username": username, + "display_name": "DB incident test", + "password": password, + }, + ) + + if status != 201: + raise RuntimeError( + f"Cannot create test user: HTTP {status}" + ) + + headers = login_header(username, password) + + status, _ = request( + "POST", + "/api/v1/auth/sessions", + body=b"", + headers=headers, + ) + + if status != 201: + raise RuntimeError( + f"Baseline login failed: HTTP {status}" + ) + + print("Baseline: authentication HTTP 201", flush=True) + + observed_failures = 0 + + print("INCIDENT START: stopping PostgreSQL", flush=True) + + try: + docker("stop", "db") + + for attempt in range(1, 6): + status, duration = request( + "POST", + "/api/v1/auth/sessions", + body=b"", + headers=headers, + ) + + print( + f"Probe {attempt}: status={status}, " + f"duration={duration:.3f}s", + flush=True, + ) + + if status != 201: + observed_failures += 1 + + time.sleep(2) + + finally: + print( + "INCIDENT END: restoring PostgreSQL", + flush=True, + ) + docker("up", "-d", "--wait", "db") + + wait_for_recovery(headers) + + print( + f"Failed requests during incident: " + f"{observed_failures}/5", + flush=True, + ) + + if observed_failures == 0: + raise RuntimeError( + "The database incident did not affect requests" + ) + + print( + "PASS: database failure observed and recovered", + flush=True, + ) + + +if __name__ == "__main__": + main() diff --git a/scripts/test-login-rate-limit.py b/scripts/test-login-rate-limit.py new file mode 100644 index 0000000..8989199 --- /dev/null +++ b/scripts/test-login-rate-limit.py @@ -0,0 +1,77 @@ + +import base64 +import os +import sys +import urllib.error +import urllib.request +import uuid + +BASE_URL = os.getenv("BASE_URL", "https://localhost:8443").rstrip("/") +CA_FILE = os.getenv("CA_FILE") + +if not CA_FILE: + sys.exit("ERROR: CA_FILE must point to a trusted CA certificate") + +import ssl + +SSL_CONTEXT = ssl.create_default_context(cafile=CA_FILE) + +username = "rl_" + uuid.uuid4().hex[:16] +password = "Wrong-Password-For-Rate-Limit-2026" + + +def login(): + credentials = base64.b64encode( + f"{username}:{password}".encode() + ).decode() + + request = urllib.request.Request( + BASE_URL + "/api/v1/auth/sessions", + data=b"", + method="POST", + headers={"Authorization": "Basic " + credentials}, + ) + + try: + with urllib.request.urlopen( + request, + context=SSL_CONTEXT, + timeout=10, + ) as response: + return response.status, response.headers + + except urllib.error.HTTPError as exc: + return exc.code, exc.headers + + +print("Testing rate limit with username:", username) + +statuses = [] + +for attempt in range(1, 7): + status, headers = login() + statuses.append(status) + + print( + f"Attempt {attempt}: HTTP {status}, " + f"Retry-After={headers.get('Retry-After')}" + ) + + if attempt <= 5: + assert status == 401, ( + f"Expected HTTP 401 for attempt {attempt}, got {status}" + ) + else: + assert status == 429, ( + f"Expected HTTP 429 for attempt {attempt}, got {status}" + ) + + retry_after = headers.get("Retry-After") + + assert retry_after and retry_after.isdigit(), ( + "Missing or invalid Retry-After" + ) + + assert int(retry_after) > 0 + +print("PASS: shared login rate limit and Retry-After") diff --git a/scripts/test-mtls.sh b/scripts/test-mtls.sh new file mode 100644 index 0000000..91678f9 --- /dev/null +++ b/scripts/test-mtls.sh @@ -0,0 +1,67 @@ +#!/usr/bin/env bash +set -euo pipefail + +PKI_DIR="${LAB7_PKI_DIR:-$HOME/.local/share/mtusi2026lab7/pki}" +NETWORK="${COMPOSE_PROJECT_NAME:-mtusi2026lab7}_default" + +for name in api1 api2; do + echo + echo "=== Testing $name mTLS ===" + + run_curl() { + docker run --rm \ + --network "$NETWORK" \ + --user "$(id -u):$(id -g)" \ + -v "$PKI_DIR:/pki:ro" \ + curlimages/curl:8.16.0 \ + --silent --show-error \ + --max-time 10 \ + --cacert /pki/ca.crt \ + --resolve "$name:8443:$(docker inspect \ + -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' \ + "mtusi2026lab7-$name-1")" \ + "$@" \ + "https://$name:8443/health/ready" + } + + echo "[1] Authorized LB certificate" + response="$(run_curl \ + --cert /pki/lb-client.crt \ + --key /pki/lb-client.key)" + echo "$response" + [[ "$response" == *'"status":"ok"'* ]] || exit 1 + + echo "[2] No client certificate" + if run_curl > /dev/null 2>&1; then + echo "FAIL: connection accepted without client certificate" + exit 1 + fi + echo "PASS: no certificate rejected" + + echo "[3] Untrusted CA certificate" + if run_curl \ + --cert /pki/rogue-client.crt \ + --key /pki/rogue-client.key \ + > /dev/null 2>&1; then + echo "FAIL: rogue certificate accepted" + exit 1 + fi + echo "PASS: rogue CA rejected" + + echo "[4] Trusted CA, forbidden SAN" + code="$(run_curl \ + --cert /pki/unauthorized-client.crt \ + --key /pki/unauthorized-client.key \ + -o /dev/null -w '%{http_code}')" + + echo "HTTP $code" + [[ "$code" == "403" ]] || { + echo "FAIL: expected HTTP 403" + exit 1 + } + + echo "PASS: $name mTLS identity enforcement" +done + +echo +echo "PASS: all mTLS tests passed" diff --git a/scripts/test-openbao-approle.py b/scripts/test-openbao-approle.py new file mode 100644 index 0000000..b529521 --- /dev/null +++ b/scripts/test-openbao-approle.py @@ -0,0 +1,251 @@ +#!/usr/bin/env python3 +"""OpenBao AppRole and KV v2 ACL tests for lab7.""" + +import json +import ssl +import stat +import uuid +import urllib.error +import urllib.request +from pathlib import Path + +BASE = Path.home() / ".local/share/mtusi2026lab7" +INIT_FILE = BASE / "operator/openbao-init.json" +URL = "https://localhost:8200/v1" + +if stat.S_IMODE(INIT_FILE.stat().st_mode) != 0o600: + raise SystemExit("FAIL: operator secret file permissions") + +with INIT_FILE.open(encoding="utf-8") as file: + ROOT_TOKEN = json.load(file)["root_token"] + +TLS = ssl.create_default_context( + cafile=str(BASE / "pki/ca.crt") +) + +TEST_ID = uuid.uuid4().hex + +PATHS = { + "api": f"api/acl-test-{TEST_ID}", + "worker": f"worker/acl-test-{TEST_ID}", +} + +TOKENS = [] + + +def request(method, path, token=None, payload=None): + body = None + + if payload is not None: + body = json.dumps(payload).encode("utf-8") + + headers = {} + + if token is not None: + headers["X-Vault-Token"] = token + + if body is not None: + headers["Content-Type"] = "application/json" + + req = urllib.request.Request( + URL + path, + data=body, + headers=headers, + method=method, + ) + + with urllib.request.urlopen( + req, + context=TLS, + timeout=15, + ) as response: + raw = response.read() + + return ( + response.status, + json.loads(raw) if raw else {}, + ) + + +def passed(message): + print("PASS:", message) + + +def must_deny(method, path, token, payload=None): + try: + request(method, path, token, payload) + except urllib.error.HTTPError as exc: + if exc.code == 403: + return + raise AssertionError( + f"Expected HTTP 403, received {exc.code}" + ) from None + + raise AssertionError("Forbidden operation unexpectedly allowed") + + +def login(role): + name = f"messenger-{role}" + + _, role_data = request( + "GET", + f"/auth/approle/role/{name}/role-id", + ROOT_TOKEN, + ) + + role_id = role_data["data"]["role_id"] + + _, secret_data = request( + "POST", + f"/auth/approle/role/{name}/secret-id", + ROOT_TOKEN, + {}, + ) + + secret_id = secret_data["data"]["secret_id"] + credentials = { + "role_id": role_id, + "secret_id": secret_id, + } + + _, login_data = request( + "POST", + "/auth/approle/login", + payload=credentials, + ) + + auth = login_data["auth"] + token = auth["client_token"] + TOKENS.append(token) + + assert 0 < auth["lease_duration"] <= 1200 + assert name in auth["policies"] + assert "root" not in auth["policies"] + + passed(f"{role}: scoped token issued with limited TTL") + + # SecretID may only be used once. + try: + request( + "POST", + "/auth/approle/login", + payload=credentials, + ) + except urllib.error.HTTPError as exc: + if exc.code not in (400, 403): + raise + passed(f"{role}: SecretID reuse denied") + else: + raise AssertionError("SecretID reused successfully") + + return token + + +def main(): + print("OpenBao HTTPS:", URL) + print("TLS verification: enabled") + + # Create unique synthetic secrets using operator identity. + for role, path in PATHS.items(): + request( + "POST", + "/lab7/data/" + path, + ROOT_TOKEN, + {"data": {"test_role": role}}, + ) + + passed("temporary KV v2 secrets prepared") + + api_token = login("api") + worker_token = login("worker") + + # Allowed: each role reads its own path. + for role, token in ( + ("api", api_token), + ("worker", worker_token), + ): + _, result = request( + "GET", + "/lab7/data/" + PATHS[role], + token, + ) + + assert result["data"]["data"]["test_role"] == role + passed(f"{role}: own secret read allowed") + + # Denied: cross-role reads. + must_deny( + "GET", + "/lab7/data/" + PATHS["worker"], + api_token, + ) + passed("API cannot read worker secrets") + + must_deny( + "GET", + "/lab7/data/" + PATHS["api"], + worker_token, + ) + passed("worker cannot read API secrets") + + # Denied: updates, even within own path. + for role, token in ( + ("api", api_token), + ("worker", worker_token), + ): + must_deny( + "POST", + "/lab7/data/" + PATHS[role], + token, + {"data": {"test_role": "modified"}}, + ) + passed(f"{role}: secret modification denied") + + # Denied: management of ACL policies. + for role, token in ( + ("api", api_token), + ("worker", worker_token), + ): + must_deny( + "GET", + "/sys/policies/acl/messenger-api", + token, + ) + passed(f"{role}: policy administration denied") + + print("PASS: all OpenBao AppRole ACL tests passed") + + +try: + main() +finally: + # Revoke only tokens created by this test. + for token in TOKENS: + try: + request( + "POST", + "/auth/token/revoke", + ROOT_TOKEN, + {"token": token}, + ) + except Exception as exc: + print( + "WARNING: token cleanup:", + type(exc).__name__, + ) + + # Remove only the unique test secrets. + for path in PATHS.values(): + try: + request( + "DELETE", + "/lab7/metadata/" + path, + ROOT_TOKEN, + ) + except Exception as exc: + print( + "WARNING: KV cleanup:", + type(exc).__name__, + ) + + print("OpenBao test cleanup attempted") diff --git a/scripts/test-openbao-cert-auth.py b/scripts/test-openbao-cert-auth.py new file mode 100644 index 0000000..94e3d46 --- /dev/null +++ b/scripts/test-openbao-cert-auth.py @@ -0,0 +1,206 @@ +#!/usr/bin/env python3 +"""Verify OpenBao certificate auth and least-privilege ACLs.""" + +import json +import ssl +import sys +import urllib.error +import urllib.request +from pathlib import Path + +BASE = Path.home() / ".local/share/mtusi2026lab7/pki" +URL = "https://localhost:8200/v1" + +SERVICES = { + "api1": { + "policy": "messenger-api", + "own": "api", + "other": "worker", + }, + "api2": { + "policy": "messenger-api", + "own": "api", + "other": "worker", + }, + "worker": { + "policy": "messenger-worker", + "own": "worker", + "other": "api", + }, +} + + +def request(method, path, tls, token=None, payload=None): + headers = {} + body = None + + if token is not None: + headers["X-Vault-Token"] = token + + if payload is not None: + body = json.dumps(payload).encode("utf-8") + headers["Content-Type"] = "application/json" + + req = urllib.request.Request( + URL + path, + headers=headers, + data=body, + method=method, + ) + + try: + with urllib.request.urlopen( + req, + context=tls, + timeout=15, + ) as response: + raw = response.read() + result = json.loads(raw) if raw else {} + return response.status, result + + except urllib.error.HTTPError as exc: + # Do not print HTTP response bodies: they may contain + # security-sensitive information. + return exc.code, {} + + +def verify_service(name, config): + cert = BASE / "openbao-clients" / f"{name}.crt" + key = BASE / "openbao-clients" / f"{name}.key" + + tls = ssl.create_default_context( + cafile=str(BASE / "ca.crt") + ) + tls.load_cert_chain( + certfile=str(cert), + keyfile=str(key), + ) + + print(f"=== {name} ===", flush=True) + + status, result = request( + "POST", + "/auth/cert/login", + tls, + payload={"name": f"lab7-{name}"}, + ) + + if status != 200: + raise RuntimeError( + f"{name}: certificate login HTTP {status}" + ) + + auth = result["auth"] + token = auth["client_token"] + + print("PASS: certificate authentication successful") + + try: + policies = set(auth.get("policies", [])) + expected = {config["policy"]} + + if policies != expected: + raise RuntimeError( + f"{name}: unexpected token policies" + ) + + print("PASS: only scoped service policy assigned") + + own_path = ( + f"/lab7/data/{config['own']}/runtime" + ) + other_path = ( + f"/lab7/data/{config['other']}/runtime" + ) + + status, result = request( + "GET", + own_path, + tls, + token=token, + ) + + if status != 200: + raise RuntimeError( + f"{name}: own secret read HTTP {status}" + ) + + secret = result.get("data", {}).get("data", {}) + + if not isinstance(secret, dict) or not secret: + raise RuntimeError( + f"{name}: own secret data missing" + ) + + print("PASS: own KV v2 secret readable") + + status, _ = request( + "GET", + other_path, + tls, + token=token, + ) + + if status != 403: + raise RuntimeError( + f"{name}: cross-service read HTTP {status}" + ) + + print("PASS: cross-service KV read denied") + + status, _ = request( + "POST", + own_path, + tls, + token=token, + payload={ + "data": { + "acl_probe": "should-not-be-written" + } + }, + ) + + if status != 403: + raise RuntimeError( + f"{name}: unauthorized write HTTP {status}" + ) + + print("PASS: KV modification denied") + + finally: + status, _ = request( + "POST", + "/auth/token/revoke-self", + tls, + token=token, + payload={}, + ) + + if status not in (200, 204): + raise RuntimeError( + f"{name}: token revocation HTTP {status}" + ) + + print("PASS: temporary token revoked") + + +def main(): + for name, config in SERVICES.items(): + verify_service(name, config) + + print("PASS: three certificate identities verified") + print("PASS: scoped OpenBao certificate ACL tests completed") + print("PASS: no secret values or tokens printed") + + +if __name__ == "__main__": + try: + main() + except Exception as exc: + print( + "FAIL: certificate ACL test:", + type(exc).__name__, + str(exc) if isinstance(exc, RuntimeError) else "", + file=sys.stderr, + ) + raise SystemExit(1) diff --git a/scripts/test-openbao-cert-client.py b/scripts/test-openbao-cert-client.py new file mode 100644 index 0000000..1528f0d --- /dev/null +++ b/scripts/test-openbao-cert-client.py @@ -0,0 +1,169 @@ +#!/usr/bin/env python3 +"""Test certificate-based OpenBao bootstrap in isolated containers.""" + +import json +import subprocess +import sys +from pathlib import Path + +PROJECT = Path(__file__).resolve().parent.parent +BASE = Path.home() / ".local/share/mtusi2026lab7/pki" + +SERVICES = { + "api1": { + "path": "lab7/data/api/runtime", + "fields": 3, + }, + "api2": { + "path": "lab7/data/api/runtime", + "fields": 3, + }, + "worker": { + "path": "lab7/data/worker/runtime", + "fields": 5, + }, +} + + +def get_network(): + container = subprocess.check_output( + ["docker", "compose", "ps", "-q", "openbao"], + cwd=PROJECT, + text=True, + ).strip() + + if not container: + raise RuntimeError("OpenBao container not running") + + data = json.loads( + subprocess.check_output( + ["docker", "inspect", container], + text=True, + ) + )[0] + + networks = data["NetworkSettings"]["Networks"] + + for name in networks: + if name.endswith("_default"): + return name + + raise RuntimeError("Project Docker network not found") + + +def test_service(service, config, network): + print(f"=== {service} ===", flush=True) + + cert = BASE / "openbao-clients" / f"{service}.crt" + key = BASE / "openbao-clients" / f"{service}.key" + ca = BASE / "ca.crt" + + client_module = PROJECT / "src/openbao_cert_client.py" + + for path in (cert, key, ca, client_module): + if not path.is_file(): + raise RuntimeError( + f"Required file missing: {path.name}" + ) + + test_code = ( + "from src.openbao_cert_client import read_runtime_secrets\n" + "import os\n" + "secrets = read_runtime_secrets()\n" + "assert len(secrets) == int(os.environ['EXPECTED_FIELDS'])\n" + "assert all(isinstance(v, str) and v for v in secrets.values())\n" + "print('PASS: certificate authentication and KV retrieval')\n" + "print('PASS: expected number of secret fields received')\n" + "print('PASS: no secret values printed')\n" + ) + + command = [ + "docker", "run", + "--rm", + "--network", network, + "--mount", + ( + f"type=bind,source={ca}," + "target=/etc/ssl/lab7/ca.crt,readonly" + ), + "--mount", + ( + f"type=bind,source={cert}," + "target=/run/lab7/bao/client.crt,readonly" + ), + "--mount", + ( + f"type=bind,source={key}," + "target=/run/lab7/bao/client.key,readonly" + ), + "--mount", + ( + f"type=bind,source={client_module}," + "target=/app/src/openbao_cert_client.py,readonly" + ), + "-e", "BAO_ADDR=https://openbao:8200", + "-e", "BAO_CACERT=/etc/ssl/lab7/ca.crt", + "-e", "BAO_CERT_FILE=/run/lab7/bao/client.crt", + "-e", "BAO_KEY_FILE=/run/lab7/bao/client.key", + "-e", f"BAO_CERT_NAME=lab7-{service}", + "-e", f"BAO_SECRET_PATH={config['path']}", + "-e", f"EXPECTED_FIELDS={config['fields']}", + "--entrypoint", "python", + f"mtusi2026lab7-{service}", + "-c", test_code, + ] + + result = subprocess.run( + command, + capture_output=True, + text=True, + timeout=90, + ) + + if result.returncode != 0: + print( + f"FAIL: {service} container test " + f"exit code {result.returncode}", + file=sys.stderr, + ) + raise RuntimeError("Container certificate test failed") + + expected_lines = ( + "PASS: certificate authentication and KV retrieval", + "PASS: expected number of secret fields received", + "PASS: no secret values printed", + ) + + for line in expected_lines: + if line not in result.stdout: + raise RuntimeError( + f"{service}: expected test result missing" + ) + print(line, flush=True) + + print( + f"PASS: {service} certificate bootstrap verified", + flush=True, + ) + + +def main(): + network = get_network() + + for service, config in SERVICES.items(): + test_service(service, config, network) + + print("PASS: three certificate bootstrap tests completed") + print("PASS: running application containers unchanged") + + +if __name__ == "__main__": + try: + main() + except Exception as exc: + print( + "FAIL: certificate bootstrap test:", + type(exc).__name__, + file=sys.stderr, + ) + raise SystemExit(1) diff --git a/scripts/test-openbao-cert-entrypoint.py b/scripts/test-openbao-cert-entrypoint.py new file mode 100644 index 0000000..b8128fa --- /dev/null +++ b/scripts/test-openbao-cert-entrypoint.py @@ -0,0 +1,172 @@ +#!/usr/bin/env python3 +"""Test certificate-based OpenBao entrypoint in Docker.""" + +import json +import subprocess +import sys +from pathlib import Path + +PROJECT = Path(__file__).resolve().parent.parent +PKI = Path.home() / ".local/share/mtusi2026lab7/pki" + +SERVICES = { + "api1": ( + "lab7/data/api/runtime", + ("DATABASE_URL", "S3_ACCESS_KEY", "S3_SECRET_KEY"), + ), + "api2": ( + "lab7/data/api/runtime", + ("DATABASE_URL", "S3_ACCESS_KEY", "S3_SECRET_KEY"), + ), + "worker": ( + "lab7/data/worker/runtime", + ( + "DATABASE_URL", + "RABBITMQ_USER", + "RABBITMQ_PASSWORD", + "S3_ACCESS_KEY", + "S3_SECRET_KEY", + ), + ), +} + + +def project_network(): + container_id = subprocess.check_output( + ["docker", "compose", "ps", "-q", "openbao"], + cwd=PROJECT, + text=True, + ).strip() + + if not container_id: + raise RuntimeError("OpenBao is not running") + + details = json.loads( + subprocess.check_output( + ["docker", "inspect", container_id], + text=True, + ) + )[0] + + for name in details["NetworkSettings"]["Networks"]: + if name.endswith("_default"): + return name + + raise RuntimeError("Project Docker network not found") + + +def mount(source, target): + if not source.is_file(): + raise RuntimeError( + "Required file missing: " + source.name + ) + + return ( + f"type=bind,source={source}," + f"target={target},readonly" + ) + + +def verify(service, secret_path, required, network): + print(f"=== {service} ===", flush=True) + + cert = PKI / "openbao-clients" / f"{service}.crt" + key = PKI / "openbao-clients" / f"{service}.key" + + child_code = ( + "import os\n" + f"required = {required!r}\n" + "assert all(" + "isinstance(os.environ.get(k), str) " + "and os.environ[k] for k in required" + ")\n" + "print('PASS: child process received runtime credentials')\n" + ) + + command = [ + "docker", "run", "--rm", + "--network", network, + "--mount", mount( + PKI / "ca.crt", + "/etc/ssl/lab7/ca.crt", + ), + "--mount", mount( + cert, + "/run/lab7/bao/client.crt", + ), + "--mount", mount( + key, + "/run/lab7/bao/client.key", + ), + "--mount", mount( + PROJECT / "src/openbao_cert_client.py", + "/app/src/openbao_cert_client.py", + ), + "--mount", mount( + PROJECT / "src/openbao_entrypoint.py", + "/app/src/openbao_entrypoint.py", + ), + "-e", "BAO_ADDR=https://openbao:8200", + "-e", "BAO_CACERT=/etc/ssl/lab7/ca.crt", + "-e", "BAO_CERT_FILE=/run/lab7/bao/client.crt", + "-e", "BAO_KEY_FILE=/run/lab7/bao/client.key", + "-e", f"BAO_CERT_NAME=lab7-{service}", + "-e", f"BAO_SECRET_PATH={secret_path}", + "--entrypoint", "python", + f"mtusi2026lab7-{service}", + "-m", "src.openbao_entrypoint", + "--", + "python", "-c", child_code, + ] + + result = subprocess.run( + command, + capture_output=True, + text=True, + timeout=90, + ) + + if result.returncode != 0: + raise RuntimeError( + f"{service}: container exit code {result.returncode}" + ) + + expected = ( + "PASS: runtime credentials loaded from OpenBao", + "PASS: child process received runtime credentials", + ) + + for line in expected: + if line not in result.stdout: + raise RuntimeError( + f"{service}: expected result missing" + ) + print(line, flush=True) + + print( + f"PASS: {service} certificate entrypoint verified", + flush=True, + ) + + +def main(): + network = project_network() + + for service, (secret_path, required) in SERVICES.items(): + verify(service, secret_path, required, network) + + print("PASS: three certificate entrypoint tests completed") + print("PASS: running containers unchanged") + print("PASS: no secret values or tokens printed") + + +if __name__ == "__main__": + try: + main() + except Exception as exc: + print( + "FAIL: certificate entrypoint test:", + type(exc).__name__, + file=sys.stderr, + ) + raise SystemExit(1) diff --git a/scripts/test-openbao-cert-identity.py b/scripts/test-openbao-cert-identity.py new file mode 100644 index 0000000..9d2fa49 --- /dev/null +++ b/scripts/test-openbao-cert-identity.py @@ -0,0 +1,115 @@ +#!/usr/bin/env python3 +"""Verify OpenBao rejects mismatched certificate identities.""" + +import json +import ssl +import sys +import urllib.error +import urllib.request +from pathlib import Path + +PKI = Path.home() / ".local/share/mtusi2026lab7/pki" +URL = "https://localhost:8200/v1" + +CASES = ( + ("api1", "lab7-worker"), + ("api2", "lab7-api1"), + ("worker", "lab7-api2"), +) + + +def verify(source, claimed_identity): + tls = ssl.create_default_context( + cafile=str(PKI / "ca.crt") + ) + + tls.load_cert_chain( + certfile=str( + PKI / "openbao-clients" / f"{source}.crt" + ), + keyfile=str( + PKI / "openbao-clients" / f"{source}.key" + ), + ) + + body = json.dumps({ + "name": claimed_identity, + }).encode("utf-8") + + req = urllib.request.Request( + URL + "/auth/cert/login", + data=body, + headers={"Content-Type": "application/json"}, + method="POST", + ) + + try: + with urllib.request.urlopen( + req, + context=tls, + timeout=15, + ) as response: + data = json.load(response) + + except urllib.error.HTTPError as exc: + if exc.code in (400, 403): + print( + f"PASS: {source} cannot authenticate " + f"as {claimed_identity}" + ) + return + + raise RuntimeError( + f"Unexpected authentication HTTP {exc.code}" + ) from None + + # Defensive cleanup if an unexpected login succeeded. + token = data.get("auth", {}).get("client_token") + + if token: + revoke = urllib.request.Request( + URL + "/auth/token/revoke-self", + data=b"{}", + headers={ + "Content-Type": "application/json", + "X-Vault-Token": token, + }, + method="POST", + ) + + try: + with urllib.request.urlopen( + revoke, + context=tls, + timeout=15, + ): + pass + except Exception: + print( + "WARNING: unexpected token revocation failed", + file=sys.stderr, + ) + + raise RuntimeError( + f"Certificate identity substitution accepted: {source}" + ) + + +def main(): + for source, claimed_identity in CASES: + verify(source, claimed_identity) + + print("PASS: all certificate identity substitutions rejected") + print("PASS: no credentials or tokens printed") + + +if __name__ == "__main__": + try: + main() + except Exception as exc: + print( + "FAIL: certificate identity test:", + type(exc).__name__, + file=sys.stderr, + ) + raise SystemExit(1) diff --git a/scripts/test-openbao-client-bootstrap.py b/scripts/test-openbao-client-bootstrap.py new file mode 100644 index 0000000..4e4c1d4 --- /dev/null +++ b/scripts/test-openbao-client-bootstrap.py @@ -0,0 +1,271 @@ +#!/usr/bin/env python3 +"""Test OpenBao bootstrap from isolated API and worker containers.""" + +import json +import os +import ssl +import stat +import subprocess +import sys +import tempfile +import urllib.request +import urllib.error +from pathlib import Path + +BASE = Path.home() / ".local/share/mtusi2026lab7" +OPERATOR = BASE / "operator" +INIT_FILE = OPERATOR / "openbao-init.json" +PROJECT = Path.cwd() +BAO_URL = "https://localhost:8200/v1" + +SERVICES = { + "api1": "messenger-api", + "api2": "messenger-api", + "worker": "messenger-worker", +} + +CONTAINER_TEST = """ +import hmac +import os +from src.openbao_client import read_runtime_secrets + +secrets = read_runtime_secrets() + +role = os.environ["BAO_SECRET_PATH"].split("/")[2] + +fields = ( + "DATABASE_URL", + "S3_ACCESS_KEY", + "S3_SECRET_KEY", +) + +if role == "worker": + fields += ( + "RABBITMQ_USER", + "RABBITMQ_PASSWORD", + ) + +assert set(secrets) == set(fields), "Unexpected secret fields" + +for field in fields: + assert hmac.compare_digest( + secrets[field], + os.environ[field], + ), "Secret mismatch: " + field + +print("PASS: AppRole authentication completed") +print("PASS: runtime secrets match service credentials") +print("PASS: scoped KV v2 secret loaded") +print("PASS: no secret values printed") +""" + + +def request(method, path, token, tls, payload=None): + body = None + + if payload is not None: + body = json.dumps(payload).encode("utf-8") + + headers = {"X-Vault-Token": token} + + if body is not None: + headers["Content-Type"] = "application/json" + + req = urllib.request.Request( + BAO_URL + path, + data=body, + headers=headers, + method=method, + ) + + with urllib.request.urlopen( + req, + context=tls, + timeout=15, + ) as response: + data = response.read() + return json.loads(data) if data else {} + + +def private_file(path, value): + with path.open("x", encoding="utf-8") as file: + file.write(value + "\n") + + path.chmod(0o600) + + +def main(): + if stat.S_IMODE(INIT_FILE.stat().st_mode) != 0o600: + raise RuntimeError("Operator file must have mode 600") + + with INIT_FILE.open(encoding="utf-8") as file: + root_token = json.load(file)["root_token"] + + tls = ssl.create_default_context( + cafile=str(BASE / "pki/ca.crt") + ) + + module = PROJECT / "src/openbao_client.py" + + if not module.is_file(): + raise RuntimeError("OpenBao client module not found") + + os.umask(0o077) + + for service, role in SERVICES.items(): + print("=== {} ===".format(service), flush=True) + + role_response = request( + "GET", + "/auth/approle/role/{}/role-id".format(role), + root_token, + tls, + ) + + role_id = role_response["data"]["role_id"] + + secret_response = request( + "POST", + "/auth/approle/role/{}/secret-id".format(role), + root_token, + tls, + {}, + ) + + secret_data = secret_response["data"] + secret_id = secret_data["secret_id"] + accessor = secret_data["secret_id_accessor"] + + try: + with tempfile.TemporaryDirectory( + prefix=".openbao-test-", + dir=OPERATOR, + ) as temporary: + directory = Path(temporary) + + private_file(directory / "role-id", role_id) + private_file(directory / "secret-id", secret_id) + + command = [ + "docker", "compose", + "run", "--rm", "-T", "--no-deps", + "-v", + "{}:/run/lab7/approle:ro".format( + directory + ), + "-v", + "{}:/app/src/openbao_client.py:ro".format( + module + ), + "-e", "BAO_ADDR=https://openbao:8200", + "-e", "BAO_CACERT=/etc/ssl/lab7/ca.crt", + "-e", "BAO_ROLE_ID_FILE=/run/lab7/approle/role-id", + "-e", "BAO_SECRET_ID_FILE=/run/lab7/approle/secret-id", + "-e", + "BAO_SECRET_PATH=lab7/data/{}/runtime".format( + "worker" if service == "worker" else "api" + ), + "--entrypoint", "python", + service, "-", + ] + + result = subprocess.run( + command, + input=CONTAINER_TEST, + text=True, + capture_output=True, + check=False, + ) + + if result.returncode != 0: + print( + "FAIL: temporary container test failed", + file=sys.stderr, + ) + print( + "INFO: container exit code:", + result.returncode, + file=sys.stderr, + ) + raise RuntimeError( + "{} bootstrap test failed".format(service) + ) + + for line in result.stdout.splitlines(): + if line.startswith("PASS:"): + print(line) + + print( + "PASS: {} bootstrap verified".format(service), + flush=True, + ) + + finally: + # A single-use SecretID is normally removed + # automatically after successful authentication. + accessor_path = ( + "/auth/approle/role/{}/secret-id-accessor".format( + role + ) + ) + + try: + request( + "POST", + accessor_path + "/lookup", + root_token, + tls, + {"secret_id_accessor": accessor}, + ) + + except urllib.error.HTTPError as exc: + if exc.code == 404: + print( + "PASS: consumed SecretID already absent", + flush=True, + ) + else: + print( + "WARNING: SecretID lookup HTTP {}".format( + exc.code + ), + file=sys.stderr, + ) + + else: + # Destroy only if the SecretID still exists. + try: + request( + "POST", + accessor_path + "/destroy", + root_token, + tls, + {"secret_id_accessor": accessor}, + ) + print( + "PASS: unused SecretID revoked", + flush=True, + ) + + except urllib.error.HTTPError as exc: + print( + "WARNING: SecretID cleanup HTTP {}".format( + exc.code + ), + file=sys.stderr, + ) + + print("PASS: three independent bootstrap tests completed") + print("PASS: temporary credential files removed") + + +if __name__ == "__main__": + try: + main() + except Exception as exc: + print( + "FAIL: OpenBao bootstrap:", + type(exc).__name__, + file=sys.stderr, + ) + raise SystemExit(1) diff --git a/scripts/test-openbao-entrypoint.py b/scripts/test-openbao-entrypoint.py new file mode 100644 index 0000000..22281ac --- /dev/null +++ b/scripts/test-openbao-entrypoint.py @@ -0,0 +1,241 @@ +#!/usr/bin/env python3 +"""Test OpenBao entrypoint in an isolated API container.""" + +import json +import os +import ssl +import stat +import subprocess +import sys +import tempfile +import urllib.error +import urllib.request +from pathlib import Path + +BASE = Path.home() / ".local/share/mtusi2026lab7" +OPERATOR = BASE / "operator" +INIT_FILE = OPERATOR / "openbao-init.json" +URL = "https://localhost:8200/v1" + +if len(sys.argv) != 2 or sys.argv[1] not in ("api1", "api2", "worker"): + raise SystemExit( + "Usage: python3 scripts/test-openbao-entrypoint.py " + "{api1,api2,worker}" + ) + +SERVICE = sys.argv[1] + +ROLE = ( + "messenger-worker" + if SERVICE == "worker" + else "messenger-api" +) + +SECRET_PATH = ( + "lab7/data/worker/runtime" + if SERVICE == "worker" + else "lab7/data/api/runtime" +) + +def request(method, path, token, tls, payload=None): + body = ( + json.dumps(payload).encode("utf-8") + if payload is not None else None + ) + + headers = {"X-Vault-Token": token} + + if body is not None: + headers["Content-Type"] = "application/json" + + req = urllib.request.Request( + URL + path, + data=body, + headers=headers, + method=method, + ) + + with urllib.request.urlopen( + req, + context=tls, + timeout=15, + ) as response: + raw = response.read() + return json.loads(raw) if raw else {} + + +def private_file(path, value): + with path.open("x", encoding="utf-8") as file: + file.write(value + "\n") + path.chmod(0o600) + + +def main(): + if stat.S_IMODE(INIT_FILE.stat().st_mode) != 0o600: + raise RuntimeError("Invalid operator file permissions") + + with INIT_FILE.open(encoding="utf-8") as file: + root_token = json.load(file)["root_token"] + + tls = ssl.create_default_context( + cafile=str(BASE / "pki/ca.crt") + ) + + container_id = subprocess.check_output( + ["docker", "compose", "ps", "-q", "openbao"], + text=True, + ).strip() + + if not container_id: + raise RuntimeError("OpenBao container not running") + + inspect = json.loads(subprocess.check_output( + ["docker", "inspect", container_id], + text=True, + ))[0] + + networks = inspect["NetworkSettings"]["Networks"] + + network = next( + (name for name in networks if name.endswith("_default")), + None, + ) + + if not network: + raise RuntimeError("Project Docker network not found") + + role_result = request( + "GET", + f"/auth/approle/role/{ROLE}/role-id", + root_token, + tls, + ) + + role_id = role_result["data"]["role_id"] + + secret_result = request( + "POST", + f"/auth/approle/role/{ROLE}/secret-id", + root_token, + tls, + {}, + ) + + secret_data = secret_result["data"] + secret_id = secret_data["secret_id"] + accessor = secret_data["secret_id_accessor"] + + print( + f"PASS: temporary {SERVICE} SecretID issued", + flush=True, + ) + + try: + os.umask(0o077) + + with tempfile.TemporaryDirectory( + prefix=".openbao-entrypoint-", + dir=OPERATOR, + ) as temporary: + directory = Path(temporary) + + private_file(directory / "role-id", role_id) + private_file(directory / "secret-id", secret_id) + + project = Path.cwd().resolve() + + command = [ + "docker", "run", "--rm", + "--network", network, + "--mount", + f"type=bind,source={directory},target=/run/lab7/approle,readonly", + "--mount", + f"type=bind,source={BASE / 'pki/ca.crt'},target=/etc/ssl/lab7/ca.crt,readonly", + "--mount", + f"type=bind,source={project / 'src/openbao_client.py'},target=/app/src/openbao_client.py,readonly", + "--mount", + f"type=bind,source={project / 'src/openbao_entrypoint.py'},target=/app/src/openbao_entrypoint.py,readonly", + "-e", "BAO_ADDR=https://openbao:8200", + "-e", "BAO_CACERT=/etc/ssl/lab7/ca.crt", + "-e", "BAO_ROLE_ID_FILE=/run/lab7/approle/role-id", + "-e", "BAO_SECRET_ID_FILE=/run/lab7/approle/secret-id", + "-e", f"BAO_SECRET_PATH={SECRET_PATH}", + "--entrypoint", "python", + f"mtusi2026lab7-{SERVICE}", + "-m", "src.openbao_entrypoint", + "--", + "python", "-c", + ( + "import os; " + "required=('DATABASE_URL','S3_ACCESS_KEY','S3_SECRET_KEY'); " + "required += ('RABBITMQ_USER','RABBITMQ_PASSWORD') " + "if os.environ.get('BAO_SECRET_PATH') == " + "'lab7/data/worker/runtime' else (); " + "assert all(os.environ.get(k) for k in required); " + "print('PASS: child process received OpenBao secrets')" + ), + ] + + result = subprocess.run( + command, + text=True, + capture_output=True, + ) + + if result.returncode != 0: + print( + "FAIL: isolated entrypoint test, exit code", + result.returncode, + ) + raise RuntimeError("Entrypoint test failed") + + for line in result.stdout.splitlines(): + if line.startswith("PASS:"): + print(line) + + print(f"PASS: {SERVICE} OpenBao entrypoint verified") + + finally: + # An already consumed single-use SecretID is absent. + # Revoke only if the SecretID still exists. + path = f"/auth/approle/role/{ROLE}/secret-id-accessor" + + try: + request( + "POST", + path + "/lookup", + root_token, + tls, + {"secret_id_accessor": accessor}, + ) + except urllib.error.HTTPError as exc: + if exc.code == 404: + print("PASS: consumed SecretID already absent") + else: + print("WARNING: SecretID lookup HTTP", exc.code) + else: + try: + request( + "POST", + path + "/destroy", + root_token, + tls, + {"secret_id_accessor": accessor}, + ) + print("PASS: unused SecretID revoked") + except urllib.error.HTTPError as exc: + print("WARNING: SecretID cleanup HTTP", exc.code) + + print("PASS: temporary bootstrap files removed") + + +if __name__ == "__main__": + try: + main() + except Exception as exc: + print( + "FAIL: OpenBao entrypoint test:", + type(exc).__name__, + file=sys.stderr, + ) + raise SystemExit(1) diff --git a/scripts/test-openbao-runtime.py b/scripts/test-openbao-runtime.py new file mode 100644 index 0000000..acea99b --- /dev/null +++ b/scripts/test-openbao-runtime.py @@ -0,0 +1,263 @@ +#!/usr/bin/env python3 +"""Verify real runtime secrets using scoped OpenBao AppRole.""" + +import hmac +import json +import ssl +import stat +import subprocess +import sys +import urllib.error +import urllib.request +from pathlib import Path + +BASE = Path.home() / ".local/share/mtusi2026lab7" +BAO_URL = "https://localhost:8200/v1" +INIT_FILE = BASE / "operator/openbao-init.json" + +FIELDS = { + "api": ( + "DATABASE_URL", + "S3_ACCESS_KEY", + "S3_SECRET_KEY", + ), + "worker": ( + "DATABASE_URL", + "RABBITMQ_USER", + "RABBITMQ_PASSWORD", + "S3_ACCESS_KEY", + "S3_SECRET_KEY", + ), +} + +TOKENS = [] + +TLS = ssl.create_default_context( + cafile=str(BASE / "pki/ca.crt") +) + + +def check(condition, message): + if not condition: + raise RuntimeError(message) + + print("PASS:", message) + + +def request(method, path, token=None, payload=None): + body = None + headers = {} + + if token is not None: + headers["X-Vault-Token"] = token + + if payload is not None: + body = json.dumps(payload).encode("utf-8") + headers["Content-Type"] = "application/json" + + req = urllib.request.Request( + BAO_URL + path, + data=body, + headers=headers, + method=method, + ) + + with urllib.request.urlopen( + req, + context=TLS, + timeout=15, + ) as response: + raw = response.read() + + return ( + response.status, + json.loads(raw) if raw else {}, + ) + + +def same_secrets(actual, expected): + if set(actual) != set(expected): + return False + + return all( + isinstance(actual[key], str) + and hmac.compare_digest( + actual[key], + expected[key], + ) + for key in expected + ) + + +def get_service_token(role, root_token): + name = "messenger-" + role + + _, role_response = request( + "GET", + f"/auth/approle/role/{name}/role-id", + root_token, + ) + + role_id = role_response["data"]["role_id"] + + _, secret_response = request( + "POST", + f"/auth/approle/role/{name}/secret-id", + root_token, + {}, + ) + + secret_id = secret_response["data"]["secret_id"] + + _, login_response = request( + "POST", + "/auth/approle/login", + payload={ + "role_id": role_id, + "secret_id": secret_id, + }, + ) + + auth = login_response["auth"] + token = auth["client_token"] + TOKENS.append(token) + + check( + name in auth["policies"] + and "root" not in auth["policies"], + f"{role}: correct scoped policy", + ) + + check( + 0 < auth["lease_duration"] <= 1200, + f"{role}: limited token TTL", + ) + + return token + + +def must_deny(token, path, label): + try: + request("GET", path, token) + except urllib.error.HTTPError as exc: + check( + exc.code == 403, + label + " (HTTP 403)", + ) + else: + raise RuntimeError( + label + ": forbidden read unexpectedly allowed" + ) + + +def main(root_token): + print("OpenBao endpoint:", BAO_URL) + print("TLS verification: enabled") + + result = subprocess.run( + ["docker", "compose", "config", "--format", "json"], + check=True, + capture_output=True, + text=True, + ) + + services = json.loads(result.stdout)["services"] + + expected = { + "api": { + key: services["api1"]["environment"][key] + for key in FIELDS["api"] + }, + "worker": { + key: services["worker"]["environment"][key] + for key in FIELDS["worker"] + }, + } + + check( + all( + services["api1"]["environment"][key] + == services["api2"]["environment"][key] + for key in FIELDS["api"] + ), + "API replicas use matching credentials", + ) + + api_token = get_service_token("api", root_token) + worker_token = get_service_token("worker", root_token) + + for role, token in ( + ("api", api_token), + ("worker", worker_token), + ): + status, response = request( + "GET", + f"/lab7/data/{role}/runtime", + token, + ) + + actual = response["data"]["data"] + + check( + status == 200 + and same_secrets(actual, expected[role]), + f"{role}: runtime secrets match Compose", + ) + + must_deny( + api_token, + "/lab7/data/worker/runtime", + "API cannot read worker runtime secrets", + ) + + must_deny( + worker_token, + "/lab7/data/api/runtime", + "Worker cannot read API runtime secrets", + ) + + must_deny( + api_token, + "/sys/policies/acl/messenger-api", + "API cannot read policy configuration", + ) + + must_deny( + worker_token, + "/sys/policies/acl/messenger-worker", + "Worker cannot read policy configuration", + ) + + print("PASS: all OpenBao runtime access tests passed") + print("PASS: no credential values printed") + + +try: + if stat.S_IMODE(INIT_FILE.stat().st_mode) != 0o600: + raise RuntimeError("Operator file permissions must be 600") + + with INIT_FILE.open(encoding="utf-8") as file: + root_token = json.load(file)["root_token"] + + try: + main(root_token) + finally: + for token in TOKENS: + try: + request( + "POST", + "/auth/token/revoke", + root_token, + {"token": token}, + ) + print("PASS: temporary service token revoked") + except Exception: + print("WARNING: service token revocation failed") + +except Exception as exc: + print( + "FAIL: OpenBao runtime test:", + type(exc).__name__, + file=sys.stderr, + ) + raise SystemExit(1) diff --git a/scripts/test-rabbitmq-acl.py b/scripts/test-rabbitmq-acl.py new file mode 100644 index 0000000..bd9dbc1 --- /dev/null +++ b/scripts/test-rabbitmq-acl.py @@ -0,0 +1,112 @@ +#!/usr/bin/env python3 +"""Negative RabbitMQ ACL tests over authenticated TLS.""" + +import os +import sys +import uuid + +import pika + +from src.queue import RABBITMQ_QUEUE, connect + + +def test_publisher_cannot_consume(channel): + try: + method, properties, body = channel.basic_get( + queue=RABBITMQ_QUEUE, + auto_ack=False, + ) + + # Safety: if permissions are unexpectedly too broad, + # immediately return any received message to the queue. + if method is not None: + channel.basic_nack( + delivery_tag=method.delivery_tag, + requeue=True, + ) + + print("FAIL: publisher was allowed to read queue") + return False + + except pika.exceptions.ChannelClosedByBroker as exc: + if exc.reply_code == 403 and "ACCESS_REFUSED" in exc.reply_text: + print("PASS: publisher cannot consume image_jobs") + return True + + print( + "FAIL: unexpected broker response:", + exc.reply_code, + exc.reply_text, + ) + return False + + +def test_consumer_cannot_publish(channel): + # A unique nonexistent routing key ensures that even if + # publishing is unexpectedly permitted, no existing queue + # receives a test message. + routing_key = "lab7_acl_unroutable_" + uuid.uuid4().hex + + try: + channel.basic_publish( + exchange="", + routing_key=routing_key, + body=b'{"acl_test":true}', + mandatory=False, + ) + + # Flush asynchronous broker responses. + channel.queue_declare( + queue=RABBITMQ_QUEUE, + passive=True, + ) + + print("FAIL: consumer was allowed to publish") + return False + + except pika.exceptions.ChannelClosedByBroker as exc: + if exc.reply_code == 403 and "ACCESS_REFUSED" in exc.reply_text: + print("PASS: consumer cannot publish") + return True + + print( + "FAIL: unexpected broker response:", + exc.reply_code, + exc.reply_text, + ) + return False + + +def main(): + role = os.environ.get("RABBITMQ_USER") + + connection = connect() + + try: + print("RabbitMQ role:", role) + print("TLS connection: authenticated") + + channel = connection.channel() + + if role == "messenger_publisher": + passed = test_publisher_cannot_consume(channel) + + elif role == "messenger_consumer": + passed = test_consumer_cannot_publish(channel) + + else: + print("FAIL: unexpected RabbitMQ role") + sys.exit(1) + + if not passed: + sys.exit(1) + + print("PASS: RabbitMQ ACL tests for", role) + + finally: + if connection.is_open: + connection.close() + + +if __name__ == "__main__": + main() diff --git a/scripts/test-redelivery.sh b/scripts/test-redelivery.sh new file mode 100644 index 0000000..c02c0c8 --- /dev/null +++ b/scripts/test-redelivery.sh @@ -0,0 +1,77 @@ + +#!/usr/bin/env bash +set -euo pipefail + +cd "$(dirname "$0")/.." + +sql() { + docker compose exec -T db \ + psql -U messenger -d messenger -At -c "$1" +} + +echo "Finding completed image job..." + +JOB_ID=$(sql " + SELECT j.id + FROM attachment_jobs j + JOIN attachment_variants v + ON v.attachment_id = j.attachment_id + WHERE j.status = 'ready' + AND v.variant_name = 'thumbnail' + ORDER BY j.created_at DESC + LIMIT 1; +") + +if [[ -z "$JOB_ID" ]]; then + echo "FAIL: no completed image job found" + exit 1 +fi + +echo "Job: $JOB_ID" + +STATE_QUERY=" + SELECT + j.status || '|' || + j.attempts || '|' || + v.sha256 || '|' || + ( + SELECT COUNT(*) + FROM attachment_variants + WHERE attachment_id = j.attachment_id + ) + FROM attachment_jobs j + JOIN attachment_variants v + ON v.attachment_id = j.attachment_id + WHERE j.id = '$JOB_ID' + AND v.variant_name = 'thumbnail'; +" + +BEFORE=$(sql "$STATE_QUERY") + +echo "Before: $BEFORE" +echo "Publishing the same job twice..." + +docker compose run --rm --no-deps api1 \ + python -c ' +import sys +from src.queue import publish_job + +job_id = sys.argv[1] +publish_job(job_id) +publish_job(job_id) +print("Two duplicate messages published") +' "$JOB_ID" + +sleep 5 + +AFTER=$(sql "$STATE_QUERY") + +echo "After: $AFTER" + +if [[ "$BEFORE" != "$AFTER" ]]; then + echo "FAIL: completed job changed after redelivery" + exit 1 +fi + +echo "PASS: duplicate delivery did not change completed job" +echo "PASS: thumbnail checksum and variant count preserved" diff --git a/scripts/test-rustfs-acl.py b/scripts/test-rustfs-acl.py new file mode 100644 index 0000000..f021b0d --- /dev/null +++ b/scripts/test-rustfs-acl.py @@ -0,0 +1,246 @@ +#!/usr/bin/env python3 +"""Positive and negative RustFS IAM tests over verified HTTPS.""" + +import os +import uuid +from pathlib import Path + +import boto3 +from botocore.config import Config +from botocore.exceptions import ClientError + + +BUCKET = os.environ["S3_BUCKET"] +ENDPOINT = os.environ["S3_ENDPOINT"] +CA_FILE = os.environ["AWS_CA_BUNDLE"] + +assert ENDPOINT == "https://minio:9000" +assert Path(CA_FILE).is_file() + +values = {} + +for line in Path("/run/lab7/local.env").read_text( + encoding="utf-8" +).splitlines(): + line = line.strip() + + if not line or line.startswith("#") or "=" not in line: + continue + + name, value = line.split("=", 1) + values[name.strip()] = value.strip().strip('"').strip("'") + + +def client(access_key, secret_key): + return boto3.client( + "s3", + endpoint_url=ENDPOINT, + aws_access_key_id=access_key, + aws_secret_access_key=secret_key, + region_name="us-east-1", + verify=CA_FILE, + config=Config( + signature_version="s3v4", + s3={"addressing_style": "path"}, + connect_timeout=5, + read_timeout=10, + retries={"max_attempts": 1}, + ), + ) + + +admin = client( + os.environ["S3_ACCESS_KEY"], + os.environ["S3_SECRET_KEY"], +) + +api = client( + values["S3_API_ACCESS_KEY"], + values["S3_API_SECRET_KEY"], +) + +worker = client( + values["S3_WORKER_ACCESS_KEY"], + values["S3_WORKER_SECRET_KEY"], +) + +suffix = uuid.uuid4().hex + +keys = { + "staging": f"staging/acl-test-{suffix}", + "original": f"originals/acl-test-{suffix}", + "thumbnail": f"thumbnails/acl-test-{suffix}.jpg", +} + +payload = b"lab7-rustfs-iam-test" + + +def put(s3, key): + s3.put_object( + Bucket=BUCKET, + Key=key, + Body=payload, + ) + + +def get(s3, key): + response = s3.get_object( + Bucket=BUCKET, + Key=key, + ) + try: + return response["Body"].read() + finally: + response["Body"].close() + + +def delete(s3, key): + s3.delete_object( + Bucket=BUCKET, + Key=key, + ) + + +def allowed(label, operation): + operation() + print(f"PASS: {label}") + + +def denied(label, operation): + try: + operation() + except ClientError as exc: + error = exc.response.get("Error", {}) + status = exc.response.get( + "ResponseMetadata", {} + ).get("HTTPStatusCode") + + code = str(error.get("Code", "")) + + if status == 403 or code in ( + "AccessDenied", + "AllAccessDisabled", + ): + print(f"PASS: {label} denied") + return + + raise AssertionError( + f"{label}: unexpected S3 error " + f"{code}, HTTP {status}" + ) from exc + + raise AssertionError( + f"{label}: forbidden operation was allowed" + ) + + +def main(): + print("RustFS endpoint:", ENDPOINT) + print("Bucket:", BUCKET) + print("TLS verification: enabled") + + try: + # Prepare existing objects so read-denial tests + # cannot be confused with missing-object errors. + for key in keys.values(): + put(admin, key) + + print("PASS: temporary test objects prepared") + + # API: staging upload/delete and processed-object reads. + allowed( + "API can upload staging", + lambda: put(api, keys["staging"]), + ) + + allowed( + "API can read original", + lambda: get(api, keys["original"]), + ) + + allowed( + "API can read thumbnail", + lambda: get(api, keys["thumbnail"]), + ) + + allowed( + "API can delete staging", + lambda: delete(api, keys["staging"]), + ) + + # Restore staging for the worker tests. + put(admin, keys["staging"]) + + # Worker: read staging, write processed objects. + allowed( + "worker can read staging", + lambda: get(worker, keys["staging"]), + ) + + allowed( + "worker can write original", + lambda: put(worker, keys["original"]), + ) + + allowed( + "worker can write thumbnail", + lambda: put(worker, keys["thumbnail"]), + ) + + # Negative API tests. + denied( + "API staging read", + lambda: get(api, keys["staging"]), + ) + + denied( + "API original write", + lambda: put(api, keys["original"]), + ) + + denied( + "API thumbnail write", + lambda: put(api, keys["thumbnail"]), + ) + + denied( + "API original delete", + lambda: delete(api, keys["original"]), + ) + + # Negative worker tests. + denied( + "worker original read", + lambda: get(worker, keys["original"]), + ) + + denied( + "worker thumbnail read", + lambda: get(worker, keys["thumbnail"]), + ) + + denied( + "worker staging write", + lambda: put(worker, keys["staging"]), + ) + + denied( + "worker staging delete", + lambda: delete(worker, keys["staging"]), + ) + + print("PASS: all RustFS IAM ACL tests passed") + + finally: + # Root credentials are used only for test cleanup. + for key in keys.values(): + try: + delete(admin, key) + except Exception: + print("WARNING: cleanup failed for", key) + + print("RustFS ACL test cleanup attempted") + + +if __name__ == "__main__": + main() diff --git a/scripts/test-trace-correlation.py b/scripts/test-trace-correlation.py new file mode 100644 index 0000000..723cd0c --- /dev/null +++ b/scripts/test-trace-correlation.py @@ -0,0 +1,154 @@ + +import json +import re +import time +import urllib.parse +import urllib.request + + +LOKI = "http://loki:3100" +TEMPO = "http://tempo:3200" + +TRACE_PATTERN = re.compile(r"^[0-9a-f]{32}$") +SPAN_PATTERN = re.compile(r"^[0-9a-f]{16}$") + + +def get_json(url): + with urllib.request.urlopen(url, timeout=15) as response: + return json.load(response) + + +def find_log(service, event): + params = urllib.parse.urlencode({ + "query": f'{{service_name="{service}"}}', + "start": str(time.time_ns() - 6 * 3600 * 10**9), + "end": str(time.time_ns()), + "limit": 500, + "direction": "BACKWARD", + }) + + payload = get_json( + f"{LOKI}/loki/api/v1/query_range?{params}" + ) + + streams = payload.get("data", {}).get("result", []) + + for stream in streams: + labels = stream.get("stream", {}) + + for entry in stream.get("values", []): + if len(entry) < 2: + continue + + message = entry[1] + metadata = entry[2] if len(entry) >= 3 else {} + + if event not in message and ( + metadata.get("event") != event + ): + continue + + trace_id = ( + metadata.get("trace_id") + or labels.get("trace_id") + ) + + span_id = ( + metadata.get("span_id") + or labels.get("span_id") + ) + + if not trace_id or not TRACE_PATTERN.fullmatch( + trace_id + ): + continue + + if not span_id or not SPAN_PATTERN.fullmatch( + span_id + ): + continue + + return { + "service": service, + "event": event, + "message": message, + "trace_id": trace_id, + "span_id": span_id, + } + + return None + + +def verify_trace(log, expected_kind): + trace_id = log["trace_id"] + + payload = get_json( + f"{TEMPO}/api/traces/{trace_id}" + ) + + batches = payload.get("batches", []) + spans = [] + + for batch in batches: + for scope in batch.get("scopeSpans", []): + spans.extend(scope.get("spans", [])) + + if not spans: + raise AssertionError( + f"No spans found for {trace_id}" + ) + + kinds = [str(span.get("kind", "")) for span in spans] + + if not any(expected_kind in kind for kind in kinds): + raise AssertionError( + f"Expected span kind {expected_kind}; got {kinds}" + ) + + print(f"Service: {log['service']}") + print(f"Event: {log['event']}") + print(f"Trace ID: {trace_id}") + print(f"Span ID: {log['span_id']}") + print(f"Tempo spans: {len(spans)}") + + for span in spans: + print( + " Span:", + span.get("name"), + "kind:", + span.get("kind"), + ) + + print("PASS: Loki log linked to Tempo trace") + print() + + +def main(): + cases = [ + ( + "messenger-api", + "HTTP request completed", + "SERVER", + ), + ( + "messenger-worker", + "Image job handled", + "CONSUMER", + ), + ] + + for service, event, kind in cases: + log = find_log(service, event) + + if log is None: + raise AssertionError( + f"No correlated log found for {service}" + ) + + verify_trace(log, kind) + + print("PASS: API and worker trace correlation") + + +if __name__ == "__main__": + main() diff --git a/scripts/test-worker-recovery.py b/scripts/test-worker-recovery.py new file mode 100644 index 0000000..4d920f6 --- /dev/null +++ b/scripts/test-worker-recovery.py @@ -0,0 +1,256 @@ +import os +import base64 +import hashlib +import json +import subprocess +import time +import urllib.error +import urllib.parse +import urllib.request +import uuid +import zlib +import struct + + +BASE = "http://127.0.0.1:8080" + + +def docker(*args): + subprocess.run( + ["docker", "compose", *args], + check=True, + ) + + +def api(method, path, token=None, body=None, headers=None): + request_headers = dict(headers or {}) + + if token: + request_headers["Authorization"] = f"Bearer {token}" + + if isinstance(body, dict): + body = json.dumps(body).encode("utf-8") + request_headers["Content-Type"] = "application/json" + + request = urllib.request.Request( + BASE + path, + data=body, + headers=request_headers, + method=method, + ) + + with urllib.request.urlopen(request, timeout=10) as response: + data = response.read() + return ( + response.status, + json.loads(data) if data and + "application/json" in response.headers.get( + "Content-Type", "" + ) else data, + ) + + +def png_chunk(name, data): + value = name + data + return ( + struct.pack(">I", len(data)) + + value + + struct.pack(">I", zlib.crc32(value) & 0xFFFFFFFF) + ) + + +def make_png(): + width, height = 320, 200 + scanline = b"\x00" + bytes([220, 80, 40]) * width + + return ( + b"\x89PNG\r\n\x1a\n" + + png_chunk( + b"IHDR", + struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0), + ) + + png_chunk( + b"IDAT", zlib.compress(scanline * height) + ) + + png_chunk(b"IEND", b"") + ) + + +def wait_ready(): + for _ in range(90): + try: + status, data = api("GET", "/health/ready") + if status == 200 and data.get("status") == "ok": + return + except Exception: + pass + time.sleep(1) + + raise RuntimeError("API did not become ready") + + +def main(): + suffix = uuid.uuid4().hex[:12] + username = "lab5_" + suffix + password = "Lab5TestPassword_" + suffix + + print("Stopping worker...", flush=True) + docker("stop", "worker") + wait_ready() + + status, user = api( + "POST", + "/api/v1/users", + body={ + "username": username, + "display_name": "Lab5 recovery test", + "password": password, + }, + ) + assert status == 201 + + credentials = base64.b64encode( + f"{username}:{password}".encode() + ).decode() + + status, session = api( + "POST", + "/api/v1/auth/sessions", + headers={"Authorization": f"Basic {credentials}"}, + body=b"", + ) + assert status == 201 + token = session["token"] + + status, chat = api( + "POST", + "/api/v1/chats", + token, + { + "title": "Worker recovery", + "member_ids": [user["id"]], + }, + ) + assert status == 201 + + original = make_png() + path = ( + f"/api/v1/chats/{chat['id']}/attachments" + "?filename=recovery.png" + ) + + status, attachment = api( + "POST", + path, + token, + original, + {"Content-Type": "image/png"}, + ) + + assert status == 202, f"Expected 202, got {status}" + assert attachment["status"] == "queued" + attachment_id = attachment["id"] + print("Upload: 202 queued", flush=True) + + status, message = api( + "POST", + f"/api/v1/chats/{chat['id']}/messages", + token, + {"text": "", "attachment_ids": [attachment_id]}, + {"Idempotency-Key": "recovery-" + suffix}, + ) + assert status == 201 + assert attachment_id in message["attachment_ids"] + print("Message created while worker is stopped", flush=True) + + status, metadata = api( + "GET", f"/api/v1/attachments/{attachment_id}", token + ) + assert status == 200 and metadata["status"] == "queued" + + print("Restarting RabbitMQ and API...", flush=True) + docker("restart", "rabbitmq") + docker("up", "-d", "--wait", "rabbitmq") + docker("restart", "api1", "api2") + wait_ready() + + status, metadata = api( + "GET", f"/api/v1/attachments/{attachment_id}", token + ) + assert metadata["status"] == "queued" + print("Queued attachment survived restart", flush=True) + + pause_seconds = int( + os.getenv("LAB6_WORKER_PAUSE_SECONDS", "60") + ) + + print( + f"INCIDENT: worker stopped for {pause_seconds} seconds", + flush=True, + ) + time.sleep(pause_seconds) + + print("Starting worker...", flush=True) + docker("up", "-d", "worker") + + deadline = time.monotonic() + 90 + + while time.monotonic() < deadline: + status, metadata = api( + "GET", f"/api/v1/attachments/{attachment_id}", token + ) + + if metadata["status"] == "ready": + break + + if metadata["status"] == "failed": + raise RuntimeError( + f"Processing failed: {metadata.get('error_code')}" + ) + + time.sleep(1) + else: + raise RuntimeError("Attachment did not become ready") + + status, downloaded = api( + "GET", + f"/api/v1/attachments/{attachment_id}/content", + token, + ) + assert status == 200 + assert downloaded == original + assert hashlib.sha256(downloaded).hexdigest() == ( + hashlib.sha256(original).hexdigest() + ) + + status, thumbnail = api( + "GET", + f"/api/v1/attachments/{attachment_id}/content" + "?variant=thumbnail", + token, + ) + + assert status == 200 + assert thumbnail.startswith(b"\xff\xd8") + assert thumbnail.endswith(b"\xff\xd9") + + variants = metadata["variants"] + assert any( + v["name"] == "thumbnail" + and v["width"] == 256 + and v["height"] == 160 + for v in variants + ) + + print("Attachment: ready", flush=True) + print("Original: SHA-256 verified", flush=True) + print("Thumbnail: JPEG 256x160 verified", flush=True) + print("PASS: durable worker recovery", flush=True) + + +if __name__ == "__main__": + try: + main() + finally: + # Restore the worker even when the test fails. + docker("up", "-d", "worker") diff --git a/security/THREAT_MODEL.md b/security/THREAT_MODEL.md index 31da287..939d8f0 100644 --- a/security/THREAT_MODEL.md +++ b/security/THREAT_MODEL.md @@ -1,19 +1,77 @@ -# Модель угроз — заполнить +# Модель угроз — лабораторная работа №7 ## Активы и акторы -TODO: пользовательские credentials/сессии, сообщения/вложения, service identities, CA/secrets, telemetry. Акторы: участник чата, посторонний пользователь, внешний клиент, скомпрометированный сервис, оператор. Опишите доступ атакующего и границы учебного стенда. +**Активы:** пароли и Argon2id-хеши, пользовательские сессии, +сообщения и чаты, вложения, PostgreSQL, объекты RustFS/S3, +очереди RabbitMQ, сервисные credentials OpenBao, приватные ключи +и сертификаты, логи, метрики и трассировки. + +**Акторы:** участник чата, посторонний пользователь, внешний клиент, +скомпрометированный сервис и оператор стенда. + +Рассматриваемый атакующий может отправлять произвольные HTTP-запросы, +подменять заголовки, предъявлять неверные TLS-сертификаты и пытаться +обращаться к данным, не разрешённым его identity. Полная компрометация +Docker host или CA private key находится за пределами базового сценария. ## Границы доверия -TODO: схема и ссылка на заполненную contracts/trust-matrix.md; публичные/внутренние интерфейсы, процессы, секреты и их выдача. +Клиент --HTTPS:8443--> Nginx +Nginx --mTLS--> HAProxy-sidecar --> API1/API2 +API/worker --TLS и ACL--> PostgreSQL, RabbitMQ, RustFS +API/worker --TLS и scoped auth--> OpenBao +Приложения --TLS--> OpenTelemetry Collector +Collector --mTLS:4317--> Tempo +Collector --HTTPS:3100--> Loki -| Угроза и конкретный путь | Нарушаемый инвариант | Контроль | Отрицательный тест | Остаточное ограничение | -| --- | --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | TODO | +Внутренний plaintext между API и его sidecar допустим только в +общем закрытом сетевом пространстве контейнеров. Порты API наружу +не публикуются. -На 4 минимум 6 конкретных угроз. Не заменяйте сценарии словами «SQL injection», «безопасный Docker», «mTLS включён» без пути и проверки. +Дополнительные соединения наблюдаемости и их текущий статус +приведены в `contracts/trust-matrix.md`. -## Lifecycle и инциденты +## Угрозы, контрмеры и проверки -TODO: bootstrap, expiry/renewal, revoke/rotation, компрометация identity, sealed OpenBao и восстановление. Указать владельца CA/unseal и способ защиты bootstrap credentials. Сопоставить scan findings с реальной применимостью и исправлением/остаточным риском. +| Угроза | Нарушаемое свойство | Контроль | Проверка | Ограничение | +|---|---|---|---|---| +| Посторонний клиент читает сообщения чужого чата | Конфиденциальность | Bearer identity и ACL | `tests/smoke.py` | Smoke не заменяет полный набор ACL | +| Посторонний клиент скачивает чужое вложение | Изоляция объектов | ACL чатов и вложений | `tests/smoke.py` | Дополнительные отрицательные случаи проверяются отдельно | +| Подбор пароля через частые запросы | Защита учётной записи | Argon2id и login rate limit | `scripts/test-login-rate-limit.py` | Нагрузка на CPU остаётся возможной | +| Клиент без разрешённой identity подключается к API | Изоляция внутреннего API | mTLS и проверка service identity | `scripts/test-mtls.sh`, `evidence/mtls-negative-tests.txt` | Необходима защита CA private key | +| Сервис пытается читать чужие секреты | Least privilege | OpenBao scoped policies | `evidence/openbao-approle-acl-tests.txt`, `evidence/openbao-cert-auth-acl-tests.txt` | Компрометация действующего credential | +| Сервис пытается выполнять запрещённые операции БД | Разделение прав | Ограниченные DB roles | `evidence/postgres-acl-tests.txt` | Требуется контроль выданных ролей | +| Worker пытается использовать чужие S3-права | Изоляция хранилища | Scoped credentials | `evidence/rustfs-acl-tests.txt` | Ошибки последующих изменений ACL | +| Клиент без сертификата подключается к Tempo | Защита telemetry | mTLS | Отказ `certificate required` | Общий CA не заменяет разрешённую identity | +| Клиент с недоверенным CA подключается к Tempo | Проверка доверия | Проверка client CA | Отказ `unknown ca` | Компрометация доверенного CA | +| Остановка одной API-реплики | Доступность | Балансировка и две реплики | `evidence/final-failover.txt` | Не гарантирует отказоустойчивость БД | +| Перезапуск контейнеров хранения | Сохранность данных | Persistent volumes | `evidence/final-persistence.txt` | Резервное копирование отдельно | + +## Bootstrap, secrets lifecycle и инциденты + +PKI создаётся локально. CA private key и сервисные private keys +хранятся вне Git-репозитория, под контролем оператора. +Приложение не должно получать root token и unseal keys OpenBao. + +OpenBao использует постоянное хранилище, сервисную аутентификацию +и scoped policies. Bootstrap, выдача credentials и операции +с сертификатами автоматизированы скриптами в `scripts/`. + +При отзыве credential требуется проверять новое подключение, +поскольку существующее соединение может сохраняться до его закрытия. +При sealed OpenBao новые обращения к секретам могут быть недоступны; +восстановление выполняет оператор с использованием защищённых +unseal credentials. + +Доказательства ACL, ротации и отзыва credentials находятся +в `evidence/openbao-*`. + +## Ограничения + +Подтверждена отказоустойчивость одной API-реплики, но не отказ +всего Docker host, PostgreSQL или брокера. + +Незащищённые HTTP-соединения наблюдаемости перечислены в +матрице доверия и должны быть устранены либо обоснованы +проверенной закрытой границей перед сдачей. diff --git a/security/haproxy/api1.cfg b/security/haproxy/api1.cfg new file mode 100644 index 0000000..b8d6de8 --- /dev/null +++ b/security/haproxy/api1.cfg @@ -0,0 +1,19 @@ +global + maxconn 256 + +defaults + mode http + timeout connect 5s + timeout client 30s + timeout server 30s + +frontend api_mtls + bind :8443 ssl crt /run/lab7-pki/api1.pem ca-file /run/lab7-pki/ca.crt verify required ssl-min-ver TLSv1.2 + + acl authorized_lb ssl_c_san -m str "DNS:lb.messenger.internal" + http-request deny deny_status 403 unless authorized_lb + + default_backend local_api + +backend local_api + server fastapi 127.0.0.1:8080 check diff --git a/security/haproxy/api2.cfg b/security/haproxy/api2.cfg new file mode 100644 index 0000000..e3529dc --- /dev/null +++ b/security/haproxy/api2.cfg @@ -0,0 +1,19 @@ +global + maxconn 256 + +defaults + mode http + timeout connect 5s + timeout client 30s + timeout server 30s + +frontend api_mtls + bind :8443 ssl crt /run/lab7-pki/api2.pem ca-file /run/lab7-pki/ca.crt verify required ssl-min-ver TLSv1.2 + + acl authorized_lb ssl_c_san -m str "DNS:lb.messenger.internal" + http-request deny deny_status 403 unless authorized_lb + + default_backend local_api + +backend local_api + server fastapi 127.0.0.1:8080 check diff --git a/security/openbao/api-policy.hcl b/security/openbao/api-policy.hcl new file mode 100644 index 0000000..57cd6fc --- /dev/null +++ b/security/openbao/api-policy.hcl @@ -0,0 +1,10 @@ +# Lab7 API: read only its own application secrets. +# No write, delete, list, or administrator capabilities. + +path "lab7/data/api/*" { + capabilities = ["read"] +} + +path "auth/token/revoke-self" { + capabilities = ["update"] +} \ No newline at end of file diff --git a/security/openbao/openbao.hcl b/security/openbao/openbao.hcl new file mode 100644 index 0000000..ae2ac36 --- /dev/null +++ b/security/openbao/openbao.hcl @@ -0,0 +1,24 @@ +# OpenBao production-style configuration for lab7. +# Persistent Raft storage, HTTPS, manual operator unseal. + +ui = false + +api_addr = "https://openbao:8200" +cluster_addr = "https://openbao:8201" + +disable_mlock = true + +storage "raft" { + path = "/openbao/data" + node_id = "lab7-openbao-1" +} + +listener "tcp" { + address = "0.0.0.0:8200" + cluster_address = "0.0.0.0:8201" + + tls_disable = false + tls_cert_file = "/openbao/tls/openbao.crt" + tls_key_file = "/openbao/tls/openbao.key" + tls_min_version = "tls12" +} diff --git a/security/openbao/worker-policy.hcl b/security/openbao/worker-policy.hcl new file mode 100644 index 0000000..7d9246b --- /dev/null +++ b/security/openbao/worker-policy.hcl @@ -0,0 +1,10 @@ +# Lab7 worker: read only its own application secrets. +# No write, delete, list, or administrator capabilities. + +path "lab7/data/worker/*" { + capabilities = ["read"] +} + +path "auth/token/revoke-self" { + capabilities = ["update"] +} \ No newline at end of file diff --git a/security/postgres/pg_hba.conf b/security/postgres/pg_hba.conf new file mode 100644 index 0000000..7244863 --- /dev/null +++ b/security/postgres/pg_hba.conf @@ -0,0 +1,13 @@ +# PostgreSQL authentication rules for MTUSI Lab7. +# +# Local Unix socket is accessible only inside the DB container. +# This rule preserves local maintenance during the TLS transition. +local all all trust + +# Explicitly reject all unencrypted TCP connections. +hostnossl all all 0.0.0.0/0 reject +hostnossl all all ::/0 reject + +# Require TLS and password authentication for TCP clients. +hostssl all all 0.0.0.0/0 scram-sha-256 +hostssl all all ::/0 scram-sha-256 diff --git a/security/rabbitmq/rabbitmq.conf b/security/rabbitmq/rabbitmq.conf new file mode 100644 index 0000000..7cbdee1 --- /dev/null +++ b/security/rabbitmq/rabbitmq.conf @@ -0,0 +1,23 @@ +# Lab7 - RabbitMQ TLS +# Transitional configuration: both AMQP and AMQPS. +# Plaintext listener will be disabled after client migration. + +listeners.tcp = none +listeners.ssl.default = 5671 + +ssl_options.cacertfile = /run/lab7-rabbitmq/ca.crt +ssl_options.certfile = /run/lab7-rabbitmq/rabbitmq.crt +ssl_options.keyfile = /run/lab7-rabbitmq/rabbitmq-server.key + +# TLS 1.2 or newer. +ssl_options.versions.1 = tlsv1.3 +ssl_options.versions.2 = tlsv1.2 + +# Clients authenticate with RabbitMQ username/password. +# A client certificate is not required in this configuration. +ssl_options.verify = verify_none +ssl_options.fail_if_no_peer_cert = false + +# Import RabbitMQ users, permissions and queue definitions. +definitions.import_backend = local_filesystem +definitions.local.path = /run/lab7-rabbitmq/definitions.json \ No newline at end of file diff --git a/security/rustfs/api-policy.json b/security/rustfs/api-policy.json new file mode 100644 index 0000000..04f80eb --- /dev/null +++ b/security/rustfs/api-policy.json @@ -0,0 +1,25 @@ +{ + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "UploadAndCleanupStaging", + "Effect": "Allow", + "Action": [ + "s3:PutObject", + "s3:DeleteObject" + ], + "Resource": "arn:aws:s3:::messenger-attachments/staging/*" + }, + { + "Sid": "ReadProcessedAttachments", + "Effect": "Allow", + "Action": [ + "s3:GetObject" + ], + "Resource": [ + "arn:aws:s3:::messenger-attachments/originals/*", + "arn:aws:s3:::messenger-attachments/thumbnails/*" + ] + } + ] +} diff --git a/security/rustfs/worker-policy.json b/security/rustfs/worker-policy.json new file mode 100644 index 0000000..d19534e --- /dev/null +++ b/security/rustfs/worker-policy.json @@ -0,0 +1,24 @@ +{ + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "ReadStagingObjects", + "Effect": "Allow", + "Action": [ + "s3:GetObject" + ], + "Resource": "arn:aws:s3:::messenger-attachments/staging/*" + }, + { + "Sid": "WriteProcessedAttachments", + "Effect": "Allow", + "Action": [ + "s3:PutObject" + ], + "Resource": [ + "arn:aws:s3:::messenger-attachments/originals/*", + "arn:aws:s3:::messenger-attachments/thumbnails/*" + ] + } + ] +} diff --git a/src/__init__.py b/src/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/api_observability.py b/src/api_observability.py new file mode 100644 index 0000000..25eb529 --- /dev/null +++ b/src/api_observability.py @@ -0,0 +1,127 @@ + +import time +import uuid + +from fastapi import Request +from opentelemetry import trace +from opentelemetry.instrumentation.fastapi import ( + FastAPIInstrumentor, +) +from starlette.middleware.base import BaseHTTPMiddleware + +from src.telemetry import setup_telemetry + + +def configure_api_observability(app): + tracer, meter, logger = setup_telemetry( + "messenger-api" + ) + + request_counter = meter.create_counter( + name="messenger_http_requests", + unit="{request}", + description="Completed business HTTP requests", + ) + + class ObservabilityMiddleware(BaseHTTPMiddleware): + async def dispatch(self, request: Request, call_next): + # Health checks should not distort business RPS. + if request.url.path.startswith("/health/"): + return await call_next(request) + + + request_id = uuid.uuid4().hex + started = time.monotonic() + status_code = 500 + + try: + response = await call_next(request) + status_code = response.status_code + + # Preserve the request ID produced by the existing + # API error handler. It must match the JSON body. + existing_id = response.headers.get("X-Request-Id") + + if existing_id: + request_id = existing_id + else: + response.headers["X-Request-Id"] = request_id + + return response + + + finally: + duration = time.monotonic() - started + + # FastAPI provides a route template after routing. + route = request.scope.get("route") + + if route is not None: + route_template = getattr( + route, "path", None + ) + else: + route_template = None + + # Do not use raw paths or dynamic IDs as labels. + if not route_template: + route_template = "unmatched" + + method = request.method + + if method not in ( + "GET", "POST", "PUT", + "PATCH", "DELETE", "HEAD", "OPTIONS" + ): + method = "OTHER" + + status_class = f"{status_code // 100}xx" + + attributes = { + "http.request.method": method, + "http.route": route_template, + "http.status_class": status_class, + } + + request_counter.add( + 1, + attributes=attributes, + ) + + # The span is created by FastAPIInstrumentor. + span = trace.get_current_span() + + if span.is_recording(): + span.set_attribute( + "messenger.request_id", + request_id, + ) + span.set_attribute( + "messenger.status_class", + status_class, + ) + + # No Authorization header, body, filename, + # chat ID, user ID or raw URL in telemetry. + logger.info( + "HTTP request completed", + extra={ + "event": "http_request_completed", + "request_id": request_id, + "http_method": method, + "http_route": route_template, + "status_code": status_code, + "duration_ms": round( + duration * 1000, 3 + ), + }, + ) + + # Add our middleware first so it executes within + # the span created by the OTel ASGI middleware. + app.add_middleware(ObservabilityMiddleware) + + FastAPIInstrumentor.instrument_app( + app, + excluded_urls=r".*/health/.*", + ) diff --git a/src/attachments.py b/src/attachments.py new file mode 100644 index 0000000..59652d2 --- /dev/null +++ b/src/attachments.py @@ -0,0 +1,108 @@ + +import io +import re +import uuid +import hashlib + +from PIL import Image, UnidentifiedImageError + + +MAX_BYTES = 10 * 1024 * 1024 +MAX_PIXELS = 40_000_000 + + +def valid_filename(filename): + if not isinstance(filename, str): + return False + + if not 1 <= len(filename) <= 255: + return False + + if filename.strip() == "": + return False + + if "/" in filename or "\\" in filename: + return False + + if any(ord(ch) < 32 or ord(ch) == 127 for ch in filename): + return False + + return True + + +def inspect_image(data, declared_mime): + if len(data) > MAX_BYTES: + raise ValueError("too_large") + + if not data: + raise ValueError("invalid_image") + + if declared_mime not in ("image/png", "image/jpeg"): + raise ValueError("invalid_image") + + try: + with Image.open(io.BytesIO(data)) as image: + image_format = image.format + + width, height = image.size + + if width * height > MAX_PIXELS: + raise ValueError("too_many_pixels") + + if image_format not in ("PNG", "JPEG"): + raise ValueError("invalid_image") + + actual_mime = ( + "image/png" + if image_format == "PNG" + else "image/jpeg" + ) + + if declared_mime != actual_mime: + raise ValueError("invalid_image") + + image.verify() + + except Image.DecompressionBombError: + raise ValueError("too_many_pixels") + except ( + UnidentifiedImageError, + OSError, + SyntaxError, + EOFError, + ): + raise ValueError("invalid_image") + + return { + "content_type": actual_mime, + "width": width, + "height": height, + "size_bytes": len(data), + "sha256": hashlib.sha256(data).hexdigest(), + } + +def attachment_json(row, variants=None): + from datetime import timezone + + def timestamp(value): + return value.astimezone(timezone.utc).isoformat( + timespec="microseconds" + ).replace("+00:00", "Z") + + return { + "id": str(row["id"]), + "chat_id": str(row["chat_id"]), + "owner_id": str(row["uploader_id"]), + "filename": row["filename"], + "content_type": row["content_type"], + "size_bytes": row["size_bytes"], + "sha256": row["sha256"], + "status": row["status"], + "variants": variants if variants is not None else [], + "error_code": row["error_code"], + "created_at": timestamp(row["created_at"]), + "updated_at": timestamp(row["updated_at"]), + } + +def object_key(): + return f"originals/{uuid.uuid4()}" diff --git a/src/dispatcher.py b/src/dispatcher.py new file mode 100644 index 0000000..31c8cf3 --- /dev/null +++ b/src/dispatcher.py @@ -0,0 +1,84 @@ + +import logging +import os +import time + +import psycopg +from psycopg.rows import dict_row + +from src.queue import publish_job + + +logging.basicConfig( + level=logging.INFO, + format="%(asctime)s %(levelname)s %(message)s", +) + +logger = logging.getLogger("image-dispatcher") + +DATABASE_URL = os.environ["DATABASE_URL"] + + +def dispatch_one(): + with psycopg.connect( + DATABASE_URL, + row_factory=dict_row, + ) as conn: + + # Only publish due, unpublished jobs. + # The row lock also prevents two dispatchers + # from selecting the same job simultaneously. + job = conn.execute( + """ + SELECT id + FROM attachment_jobs + WHERE status = 'queued' + AND published_at IS NULL + AND next_attempt_at <= NOW() + ORDER BY created_at, id + LIMIT 1 + FOR UPDATE SKIP LOCKED + """, + ).fetchone() + + if job is None: + return False + + job_id = str(job["id"]) + + # RabbitMQ publisher confirms are enabled. + # An exception rolls back this DB transaction. + publish_job(job_id) + + conn.execute( + """ + UPDATE attachment_jobs + SET published_at = NOW(), + updated_at = NOW() + WHERE id = %s + """, + (job_id,), + ) + + logger.info("Published job %s", job_id) + + return True + + +def main(): + logger.info("Dispatcher started") + + while True: + try: + if not dispatch_one(): + time.sleep(1) + + except Exception: + logger.exception( + "Dispatch failed; retrying" + ) + time.sleep(3) + + +if __name__ == "__main__": + main() diff --git a/src/main.py b/src/main.py new file mode 100644 index 0000000..2b075ba --- /dev/null +++ b/src/main.py @@ -0,0 +1,1382 @@ + +import base64 +import hashlib +import io +import json +import os +import re +import secrets +import uuid + +from src.api_observability import configure_api_observability + +from datetime import datetime, timedelta, timezone + +import psycopg +from psycopg.rows import dict_row +from psycopg.errors import UniqueViolation + +from argon2 import PasswordHasher, Type +from argon2.exceptions import ( + VerifyMismatchError, + VerificationError, + InvalidHashError, +) + +from fastapi import FastAPI, Request +from fastapi.responses import JSONResponse, Response +from fastapi.exceptions import RequestValidationError +from starlette.exceptions import HTTPException as StarletteHTTPException + +import boto3 +from botocore.config import Config +from botocore.exceptions import BotoCoreError, ClientError +from PIL import Image, UnidentifiedImageError + +app = FastAPI(title="MTUSI Messenger Lab5") + +INSTANCE_ID = str(uuid.uuid4()) + +DATABASE_URL = os.environ["DATABASE_URL"] +SESSION_TTL_SECONDS = int(os.getenv("SESSION_TTL_SECONDS", "3600")) + +IMAGE_MAX_ATTEMPTS = int(os.getenv("IMAGE_MAX_ATTEMPTS", "5")) +S3_BUCKET = os.environ["S3_BUCKET"] +MAX_IMAGE_BYTES = 10 * 1024 * 1024 +MAX_IMAGE_PIXELS = 40_000_000 + +s3 = boto3.client( + "s3", + endpoint_url=os.environ["S3_ENDPOINT"], + aws_access_key_id=os.environ["S3_ACCESS_KEY"], + aws_secret_access_key=os.environ["S3_SECRET_KEY"], + region_name="us-east-1", + config=Config( + signature_version="s3v4", + s3={"addressing_style": "path"}, + connect_timeout=3, + read_timeout=10, + retries={"max_attempts": 1}, + ), +) + +# Argon2id password hashing. +# 32768 KiB = 32 MiB. +# Selected from local benchmark: median 47.82 ms. +password_hasher = PasswordHasher( + time_cost=3, + memory_cost=32768, + parallelism=1, + hash_len=32, + salt_len=16, + type=Type.ID, +) + + +# ---------- Helpers ---------- + +class ApiError(Exception): + def __init__(self, status, code, message, headers=None): + self.status = status + self.code = code + self.message = message + self.headers = headers or {} + + +def fail(status, code, message, headers=None): + raise ApiError(status, code, message, headers) + + +def db(): + return psycopg.connect(DATABASE_URL, row_factory=dict_row) + + +def utc_string(value): + return value.astimezone(timezone.utc).isoformat( + timespec="microseconds" + ).replace("+00:00", "Z") + + +def user_json(row): + return { + "id": str(row["id"]), + "username": row["username"], + "display_name": row["display_name"], + "created_at": utc_string(row["created_at"]), + } + + + +def message_json(row, conn=None): + attachment_ids = [] + + if conn is not None: + attachments = conn.execute( + """ + SELECT attachment_id + FROM message_attachments + WHERE message_id = %s + ORDER BY attachment_id + """, + (row["id"],), + ).fetchall() + + attachment_ids = [ + str(item["attachment_id"]) + for item in attachments + ] + + return { + "id": str(row["id"]), + "chat_id": str(row["chat_id"]), + "sender_id": str(row["sender_id"]), + "text": row["text"], + "attachment_ids": attachment_ids, + "created_at": utc_string(row["created_at"]), + } + + + +def chat_json(conn, row): + members = conn.execute( + """ + SELECT user_id FROM chat_members + WHERE chat_id = %s + ORDER BY position + """, + (row["id"],) + ).fetchall() + + return { + "id": str(row["id"]), + "title": row["title"], + "member_ids": [str(m["user_id"]) for m in members], + "created_at": utc_string(row["created_at"]), + } + + +def valid_uuid(value): + if not isinstance(value, str): + return False + try: + return str(uuid.UUID(value)) == value + except ValueError: + return False + + +def valid_text(value, maximum): + return ( + isinstance(value, str) + and 1 <= len(value) <= maximum + and bool(value.strip()) + ) + + +def validate_limit(request): + value = request.query_params.get("limit", "50") + + if not re.fullmatch(r"[0-9]+", value): + fail(400, "invalid_request", "Invalid limit") + + number = int(value) + + if not 1 <= number <= 100: + fail(400, "invalid_request", "Invalid limit") + + return number + + +def make_cursor(resource, row): + payload = { + "resource": resource, + "created_at": utc_string(row["created_at"]), + "id": str(row["id"]), + } + + raw = json.dumps(payload).encode("utf-8") + + return base64.urlsafe_b64encode(raw).decode().rstrip("=") + + +def read_cursor(cursor, resource): + if not isinstance(cursor, str) or not cursor: + fail(400, "invalid_request", "Invalid cursor") + + try: + raw = base64.urlsafe_b64decode( + cursor + "=" * (-len(cursor) % 4) + ) + value = json.loads(raw) + + if value["resource"] != resource: + raise ValueError() + + if not valid_uuid(value["id"]): + raise ValueError() + + timestamp = datetime.fromisoformat( + value["created_at"].replace("Z", "+00:00") + ) + + if timestamp.tzinfo is None: + raise ValueError() + + return timestamp, value["id"] + + except (ValueError, KeyError, TypeError, UnicodeDecodeError): + fail(400, "invalid_request", "Invalid cursor") + + +async def json_body(request, required, allowed): + content_type = request.headers.get("content-type", "") + media_type = content_type.split(";")[0].strip().lower() + + if media_type != "application/json": + fail(415, "unsupported_media_type", "Expected JSON") + + try: + data = await request.json() + except Exception: + fail(400, "invalid_request", "Invalid JSON") + + if not isinstance(data, dict): + fail(400, "invalid_request", "Expected JSON object") + + if not set(required).issubset(data): + fail(400, "invalid_request", "Missing fields") + + if not set(data).issubset(allowed): + fail(400, "invalid_request", "Unexpected fields") + + return data + + +def unauthorized(kind="Bearer"): + if kind == "Basic": + header = 'Basic realm="messenger", charset="UTF-8"' + else: + header = 'Bearer realm="messenger"' + + fail( + 401, + "unauthorized", + "Authentication required", + {"WWW-Authenticate": header}, + ) + + +def current_user(request): + authorization = request.headers.get("Authorization", "") + + if not authorization.startswith("Bearer "): + unauthorized() + + token = authorization[7:] + + if not token: + unauthorized() + + token_hash = hashlib.sha256(token.encode()).hexdigest() + + with db() as conn: + row = conn.execute( + """ + SELECT u.id, u.username, u.display_name, u.created_at + FROM sessions s + JOIN users u ON u.id = s.user_id + WHERE s.token_hash = %s + AND s.revoked = FALSE + AND s.expires_at > clock_timestamp() + """, + (token_hash,) + ).fetchone() + + if row is None: + unauthorized() + + return row + + +def accessible_chat(conn, chat_id, user_id): + if not valid_uuid(chat_id): + fail(400, "invalid_request", "Invalid chat ID") + + row = conn.execute( + """ + SELECT c.id, c.title, c.created_at + FROM chats c + JOIN chat_members m ON m.chat_id = c.id + WHERE c.id = %s AND m.user_id = %s + """, + (chat_id, user_id) + ).fetchone() + + if row is None: + fail(404, "not_found", "Chat not found") + + return row + + +# ---------- Request IDs and errors ---------- + +def error_response(request, status, code, message, headers=None): + request_id = request.state.request_id + + response_headers = { + "X-Request-Id": request_id, + **(headers or {}), + } + + return JSONResponse( + status_code=status, + content={ + "error": { + "code": code, + "message": message, + "request_id": request_id, + } + }, + headers=response_headers, + ) + + +@app.middleware("http") +async def add_request_id(request, call_next): + request.state.request_id = str(uuid.uuid4()) + + try: + response = await call_next(request) + except psycopg.OperationalError: + response = error_response( + request, 503, "unavailable", "Database unavailable" + ) + except Exception: + response = error_response( + request, 500, "internal_error", "Internal server error" + ) + + response.headers["X-Request-Id"] = request.state.request_id + response.headers["X-Instance-Id"] = INSTANCE_ID + return response + + +@app.exception_handler(ApiError) +async def api_error_handler(request, exc): + return error_response( + request, exc.status, exc.code, exc.message, exc.headers + ) + + +@app.exception_handler(StarletteHTTPException) +async def http_error_handler(request, exc): + return error_response( + request, exc.status_code, + "not_found" if exc.status_code == 404 else "invalid_request", + "Resource not found" if exc.status_code == 404 else "Invalid request", + ) + + +@app.exception_handler(RequestValidationError) +async def validation_error_handler(request, exc): + return error_response( + request, 400, "invalid_request", "Invalid request" + ) + + +# ---------- Health ---------- + +@app.get("/health/live") +def health_live(): + return {"status": "ok"} + + +@app.get("/health/ready") +def health_ready(): + try: + with db() as conn: + conn.execute("SELECT 1") + + # Use an object-level permission instead of + # requiring bucket-wide ListBucket access. + health_key = f"originals/health-{uuid.uuid4().hex}" + + try: + s3.head_object( + Bucket=S3_BUCKET, + Key=health_key, + ) + + except ClientError as exc: + status = exc.response.get( + "ResponseMetadata", {} + ).get("HTTPStatusCode") + + # A missing object is expected: the storage + # endpoint is reachable and authenticated. + if status != 404: + raise + + return {"status": "ok"} + + except ( + psycopg.Error, + BotoCoreError, + ClientError, + OSError, + ): + fail( + 503, + "unavailable", + "Storage unavailable", + ) + +# ---------- Users ---------- + +@app.post("/api/v1/users", status_code=201) +async def create_user(request: Request): + data = await json_body( + request, + required=["username", "display_name", "password"], + allowed=["username", "display_name", "password"], + ) + + username = data["username"] + display_name = data["display_name"] + password = data["password"] + + if ( + not isinstance(username, str) + or not re.fullmatch(r"[a-z0-9_]{3,32}", username) + or not valid_text(display_name, 100) + or not isinstance(password, str) + or not 12 <= len(password) <= 128 + ): + fail(400, "invalid_request", "Invalid user fields") + + password_hash = password_hasher.hash(password) + user_id = str(uuid.uuid4()) + + try: + with db() as conn: + row = conn.execute( + """ + INSERT INTO users + (id, username, display_name, password_hash) + VALUES (%s, %s, %s, %s) + RETURNING id, username, display_name, created_at + """, + (user_id, username, display_name, password_hash) + ).fetchone() + + return user_json(row) + + except UniqueViolation: + fail(409, "conflict", "Username already exists") + + +@app.get("/api/v1/users/me") +def get_me(request: Request): + return user_json(current_user(request)) + + +# ---------- Login rate limiting ---------- + +LOGIN_RATE_LIMIT_ATTEMPTS = 5 +LOGIN_RATE_LIMIT_WINDOW_SECONDS = 60 + + +def check_login_rate_limit(username: str) -> None: + """ + Shared, atomic fixed-window limiter. + + All API replicas use the same PostgreSQL table. + The user is counted before checking whether the + account exists, so the limiter does not reveal + account existence. + """ + normalized_username = username.lower() + + bucket_key = hashlib.sha256( + f"login:{normalized_username}".encode("utf-8") + ).hexdigest() + + with db() as conn: + row = conn.execute( + """ + INSERT INTO login_attempt_buckets ( + bucket_key, + window_started_at, + attempts + ) + VALUES (%s, NOW(), 1) + + ON CONFLICT (bucket_key) + DO UPDATE SET + attempts = CASE + WHEN login_attempt_buckets.window_started_at + <= NOW() - INTERVAL '60 seconds' + THEN 1 + ELSE login_attempt_buckets.attempts + 1 + END, + + window_started_at = CASE + WHEN login_attempt_buckets.window_started_at + <= NOW() - INTERVAL '60 seconds' + THEN NOW() + ELSE login_attempt_buckets.window_started_at + END + + RETURNING + attempts, + GREATEST( + 1, + CEIL( + EXTRACT( + EPOCH FROM ( + window_started_at + + INTERVAL '60 seconds' + - NOW() + ) + ) + )::INTEGER + ) AS retry_after + """, + (bucket_key,), + ).fetchone() + + if row["attempts"] > LOGIN_RATE_LIMIT_ATTEMPTS: + fail( + 429, + "rate_limited", + "Too many login attempts. Try again later.", + headers={ + "Retry-After": str(row["retry_after"]) + }, + ) + + +# ---------- Sessions ---------- + +@app.post("/api/v1/auth/sessions", status_code=201) +async def create_session(request: Request): + authorization = request.headers.get("Authorization", "") + + if not authorization.startswith("Basic "): + unauthorized("Basic") + + try: + encoded = authorization[6:] + decoded = base64.b64decode(encoded, validate=True).decode("utf-8") + + if ":" not in decoded: + raise ValueError() + + username, password = decoded.split(":", 1) + + except (ValueError, UnicodeDecodeError): + unauthorized("Basic") + + if not re.fullmatch(r"[a-z0-9_]{3,32}", username): + unauthorized("Basic") + + # Applied before user lookup and password verification. + # Shared across all API replicas via PostgreSQL. + check_login_rate_limit(username) + + with db() as conn: + row = conn.execute( + "SELECT * FROM users WHERE username = %s", + (username,) + ).fetchone() + + if row is None: + unauthorized("Basic") + + try: + password_hasher.verify(row["password_hash"], password) + except (VerifyMismatchError, VerificationError, InvalidHashError): + unauthorized("Basic") + + token = secrets.token_urlsafe(32) + token_hash = hashlib.sha256(token.encode()).hexdigest() + + expires_at = datetime.now(timezone.utc) + timedelta( + seconds=SESSION_TTL_SECONDS + ) + + with db() as conn: + conn.execute( + """ + INSERT INTO sessions (token_hash, user_id, expires_at) + VALUES (%s, %s, %s) + """, + (token_hash, row["id"], expires_at) + ) + + return { + "token": token, + "token_type": "Bearer", + "expires_at": utc_string(expires_at), + "user": user_json(row), + } + + +@app.delete("/api/v1/auth/sessions/current", status_code=204) +def logout(request: Request): + current_user(request) + + token = request.headers["Authorization"][7:] + token_hash = hashlib.sha256(token.encode()).hexdigest() + + with db() as conn: + conn.execute( + "UPDATE sessions SET revoked = TRUE WHERE token_hash = %s", + (token_hash,) + ) + + return Response(status_code=204) + + +# ---------- Chats ---------- + +@app.post("/api/v1/chats", status_code=201) +async def create_chat(request: Request): + actor = current_user(request) + + data = await json_body( + request, + required=["title", "member_ids"], + allowed=["title", "member_ids"], + ) + + title = data["title"] + member_ids = data["member_ids"] + + if not valid_text(title, 100): + fail(400, "invalid_request", "Invalid title") + + if ( + not isinstance(member_ids, list) + or not 1 <= len(member_ids) <= 100 + or not all(valid_uuid(x) for x in member_ids) + or len(member_ids) != len(set(member_ids)) + or str(actor["id"]) not in member_ids + ): + fail(400, "invalid_request", "Invalid members") + + chat_id = str(uuid.uuid4()) + + with db() as conn: + # All operations use one transaction. + existing = conn.execute( + """ + SELECT id FROM users + WHERE id = ANY(%s::uuid[]) + """, + (member_ids,) + ).fetchall() + + if len(existing) != len(member_ids): + fail(400, "invalid_request", "Unknown member") + + row = conn.execute( + """ + INSERT INTO chats (id, title) + VALUES (%s, %s) + RETURNING id, title, created_at + """, + (chat_id, title) + ).fetchone() + + for position, member_id in enumerate(member_ids): + conn.execute( + """ + INSERT INTO chat_members (chat_id, user_id, position) + VALUES (%s, %s, %s) + """, + (chat_id, member_id, position) + ) + + result = chat_json(conn, row) + + return result + + +@app.get("/api/v1/chats") +def list_chats(request: Request): + actor = current_user(request) + limit = validate_limit(request) + cursor = request.query_params.get("cursor") + + resource = "chats:" + str(actor["id"]) + + with db() as conn: + if cursor is None: + rows = conn.execute( + """ + SELECT c.id, c.title, c.created_at + FROM chats c + JOIN chat_members m ON m.chat_id = c.id + WHERE m.user_id = %s + ORDER BY c.created_at, c.id + LIMIT %s + """, + (actor["id"], limit + 1) + ).fetchall() + else: + timestamp, last_id = read_cursor(cursor, resource) + + rows = conn.execute( + """ + SELECT c.id, c.title, c.created_at + FROM chats c + JOIN chat_members m ON m.chat_id = c.id + WHERE m.user_id = %s + AND (c.created_at, c.id) > (%s, %s) + ORDER BY c.created_at, c.id + LIMIT %s + """, + (actor["id"], timestamp, last_id, limit + 1) + ).fetchall() + + has_more = len(rows) > limit + page = rows[:limit] + + items = [chat_json(conn, row) for row in page] + + next_cursor = ( + make_cursor(resource, page[-1]) + if has_more else None + ) + + return {"items": items, "next_cursor": next_cursor} + + +@app.get("/api/v1/chats/{chat_id}") +def get_chat(chat_id: str, request: Request): + actor = current_user(request) + + with db() as conn: + row = accessible_chat(conn, chat_id, actor["id"]) + result = chat_json(conn, row) + + return result + + +# ---------- Attachments ---------- + +from src.attachments import ( + MAX_BYTES, + valid_filename, + inspect_image, + attachment_json, + object_key, +) + + +def attachment_for_user(conn, attachment_id, user_id): + if not valid_uuid(attachment_id): + fail(400, "invalid_request", "Invalid attachment ID") + + row = conn.execute( + """ + SELECT a.* + FROM attachments a + JOIN chat_members cm + ON cm.chat_id = a.chat_id + WHERE a.id = %s + AND cm.user_id = %s + """, + (attachment_id, user_id), + ).fetchone() + + if row is None: + fail(404, "not_found", "Attachment not found") + + return row + + +@app.post( + "/api/v1/chats/{chat_id}/attachments", + status_code=202, +) +async def upload_attachment(chat_id: str, request: Request): + actor = current_user(request) + + with db() as conn: + accessible_chat(conn, chat_id, actor["id"]) + + filename = request.query_params.get("filename") + + if not valid_filename(filename): + fail(400, "invalid_request", "Invalid filename") + + content_type = request.headers.get( + "content-type", "" + ).split(";")[0].strip().lower() + + if content_type not in ("image/png", "image/jpeg"): + fail( + 415, + "unsupported_media_type", + "Expected PNG or JPEG", + ) + + content_length = request.headers.get("content-length") + + if content_length is not None: + try: + declared_size = int(content_length) + except ValueError: + fail( + 400, + "invalid_request", + "Invalid Content-Length", + ) + + if declared_size > MAX_BYTES: + fail( + 413, + "payload_too_large", + "Image exceeds 10 MiB", + ) + + # Receive the HTTP body with a strict byte limit. + data = bytearray() + + async for chunk in request.stream(): + if len(data) + len(chunk) > MAX_BYTES: + fail( + 413, + "payload_too_large", + "Image exceeds 10 MiB", + ) + + data.extend(chunk) + + data = bytes(data) + + try: + metadata = inspect_image(data, content_type) + except ValueError as exc: + if str(exc) in ("too_large", "too_many_pixels"): + fail( + 413, + "payload_too_large", + "Image exceeds limits", + ) + + fail( + 415, + "unsupported_media_type", + "Invalid PNG or JPEG", + ) + + attachment_id = str(uuid.uuid4()) + job_id = str(uuid.uuid4()) + + # Server-generated keys, independent of filename. + staging_key = f"staging/{attachment_id}" + original_key = f"originals/{attachment_id}" + + # First persist the accepted original in shared S3. + try: + s3.put_object( + Bucket=S3_BUCKET, + Key=staging_key, + Body=data, + ContentType=metadata["content_type"], + ) + except (BotoCoreError, ClientError, OSError): + fail( + 503, + "unavailable", + "Storage unavailable", + ) + + try: + with db() as conn: + accessible_chat(conn, chat_id, actor["id"]) + + row = conn.execute( + """ + INSERT INTO attachments + ( + id, + chat_id, + uploader_id, + filename, + content_type, + size_bytes, + sha256, + object_key, + staging_key, + width, + height, + status, + error_code + ) + VALUES ( + %s, %s, %s, %s, %s, + %s, %s, %s, %s, %s, + %s, 'queued', NULL + ) + RETURNING * + """, + ( + attachment_id, + chat_id, + actor["id"], + filename, + metadata["content_type"], + metadata["size_bytes"], + metadata["sha256"], + original_key, + staging_key, + metadata["width"], + metadata["height"], + ), + ).fetchone() + + # Durable job record in the same DB transaction. + conn.execute( + """ + INSERT INTO attachment_jobs + ( + id, + attachment_id, + status, + attempts, + max_attempts, + next_attempt_at + ) + VALUES ( + %s, %s, 'queued', + 0, %s, NOW() + ) + """, + ( + job_id, + attachment_id, + IMAGE_MAX_ATTEMPTS, + ), + ) + + except Exception: + # The database transaction was not confirmed. + # Try to clean up the unreferenced staging object. + try: + s3.delete_object( + Bucket=S3_BUCKET, + Key=staging_key, + ) + except Exception: + pass + + raise + + # Do not perform resizing or require the worker here. + # The dispatcher will publish this durable DB job. + return attachment_json(row) + + + +@app.get("/api/v1/attachments/{attachment_id}") +def get_attachment(attachment_id: str, request: Request): + actor = current_user(request) + + with db() as conn: + row = attachment_for_user( + conn, attachment_id, actor["id"] + ) + + variant_rows = conn.execute( + """ + SELECT variant_name, content_type, + size_bytes, sha256, width, height + FROM attachment_variants + WHERE attachment_id = %s + ORDER BY variant_name + """, + (attachment_id,), + ).fetchall() + + variants = [ + { + "name": v["variant_name"], + "content_type": v["content_type"], + "size_bytes": v["size_bytes"], + "sha256": v["sha256"], + "width": v["width"], + "height": v["height"], + } + for v in variant_rows + ] + + return attachment_json(row, variants) + + + + +@app.get("/api/v1/attachments/{attachment_id}/content") +def download_attachment( + attachment_id: str, + request: Request, +): + actor = current_user(request) + + variant = request.query_params.get( + "variant", "original" + ) + + with db() as conn: + row = attachment_for_user( + conn, attachment_id, actor["id"] + ) + + if row["status"] != "ready": + fail( + 409, + "conflict", + "Attachment is not ready", + ) + + if variant == "original": + key = row["object_key"] + content_type = row["content_type"] + expected_size = row["size_bytes"] + expected_sha256 = row["sha256"] + + elif variant == "thumbnail": + variant_row = conn.execute( + """ + SELECT object_key, content_type, + size_bytes, sha256 + FROM attachment_variants + WHERE attachment_id = %s + AND variant_name = 'thumbnail' + """, + (attachment_id,), + ).fetchone() + + if variant_row is None: + fail( + 404, + "not_found", + "Variant not found", + ) + + key = variant_row["object_key"] + content_type = variant_row["content_type"] + expected_size = variant_row["size_bytes"] + expected_sha256 = variant_row["sha256"] + + else: + fail( + 404, + "not_found", + "Variant not found", + ) + + try: + result = s3.get_object( + Bucket=S3_BUCKET, + Key=key, + ) + + body_stream = result["Body"] + + try: + data = body_stream.read(MAX_BYTES + 1) + finally: + body_stream.close() + + except (BotoCoreError, ClientError, OSError): + fail( + 503, + "unavailable", + "Storage unavailable", + ) + + if ( + len(data) != expected_size + or hashlib.sha256(data).hexdigest() + != expected_sha256 + ): + fail( + 503, + "unavailable", + "Stored object is unavailable", + ) + + return Response( + content=data, + media_type=content_type, + headers={ + "Cache-Control": "private, no-store", + "X-Content-Type-Options": "nosniff", + }, + ) + +def get_idempotency_key(request): + key = request.headers.get("Idempotency-Key") + + if ( + key is None + or not re.fullmatch(r"[A-Za-z0-9._:-]{1,128}", key) + ): + fail( + 400, + "invalid_request", + "Invalid or missing Idempotency-Key" + ) + + return key + + +def request_fingerprint(data): + normalized = { + "text": data["text"], + "attachment_ids": data.get("attachment_ids", []), + } + + encoded = json.dumps( + normalized, + ensure_ascii=False, + sort_keys=True, + separators=(",", ":"), + ).encode("utf-8") + + return hashlib.sha256(encoded).hexdigest() + + + +def idempotency_lock_id(user_id, chat_id, key): + scope = f"{user_id}:{chat_id}:{key}" + + digest = hashlib.sha256( + scope.encode("utf-8") + ).digest() + + return int.from_bytes( + digest[:8], + byteorder="big", + signed=True + ) + + +# ---------- Messages ---------- + + + +@app.post("/api/v1/chats/{chat_id}/messages", status_code=201) +async def send_message(chat_id: str, request: Request): + actor = current_user(request) + + data = await json_body( + request, + required=["text"], + allowed=["text", "attachment_ids"], + ) + + message_text = data["text"] + attachment_ids = data.get("attachment_ids", []) + + if ( + not isinstance(message_text, str) + or len(message_text) > 4000 + ): + fail(400, "invalid_request", "Invalid message text") + + if ( + not isinstance(attachment_ids, list) + or len(attachment_ids) > 10 + or not all(valid_uuid(x) for x in attachment_ids) + or len(attachment_ids) != len(set(attachment_ids)) + ): + fail(400, "invalid_request", "Invalid attachment_ids") + + if not message_text.strip() and not attachment_ids: + fail(400, "invalid_request", "Empty message") + + key = get_idempotency_key(request) + fingerprint = request_fingerprint(data) + user_id = actor["id"] + + with db() as conn: + accessible_chat(conn, chat_id, user_id) + + lock_id = idempotency_lock_id( + user_id, chat_id, key + ) + + conn.execute( + "SELECT pg_advisory_xact_lock(%s)", + (lock_id,), + ) + + conn.execute( + """ + DELETE FROM message_idempotency + WHERE user_id = %s + AND chat_id = %s + AND idempotency_key = %s + AND created_at < + clock_timestamp() - INTERVAL '24 hours' + """, + (user_id, chat_id, key), + ) + + previous = conn.execute( + """ + SELECT i.request_hash, m.* + FROM message_idempotency i + JOIN messages m ON m.id = i.message_id + WHERE i.user_id = %s + AND i.chat_id = %s + AND i.idempotency_key = %s + """, + (user_id, chat_id, key), + ).fetchone() + + if previous is not None: + if previous["request_hash"] != fingerprint: + fail( + 409, + "conflict", + "Idempotency-Key already used " + "with different content", + ) + + return message_json(previous, conn) + + for attachment_id in attachment_ids: + attachment = conn.execute( + """ + SELECT id, status + FROM attachments + WHERE id = %s + AND chat_id = %s + FOR KEY SHARE + """, + (attachment_id, chat_id), + ).fetchone() + + if attachment is None: + fail( + 404, + "not_found", + "Attachment not found", + ) + + if attachment["status"] == "failed": + fail( + 409, + "conflict", + "Attachment processing failed", + ) + + if attachment["status"] not in ( + "queued", + "processing", + "ready", + ): + fail( + 409, + "conflict", + "Invalid attachment status", + ) + + message_id = str(uuid.uuid4()) + + row = conn.execute( + """ + INSERT INTO messages + (id, chat_id, sender_id, text) + VALUES (%s, %s, %s, %s) + RETURNING id, chat_id, sender_id, + text, created_at + """, + (message_id, chat_id, user_id, message_text), + ).fetchone() + + for attachment_id in attachment_ids: + conn.execute( + """ + INSERT INTO message_attachments + (message_id, attachment_id) + VALUES (%s, %s) + """, + (message_id, attachment_id), + ) + + conn.execute( + """ + INSERT INTO message_idempotency + ( + user_id, chat_id, idempotency_key, + request_hash, message_id + ) + VALUES (%s, %s, %s, %s, %s) + """, + ( + user_id, chat_id, key, + fingerprint, message_id, + ), + ) + + return message_json(row, conn) + + + +@app.get("/api/v1/chats/{chat_id}/messages") +def list_messages(chat_id: str, request: Request): + actor = current_user(request) + limit = validate_limit(request) + cursor = request.query_params.get("cursor") + + resource = "messages:" + chat_id + + with db() as conn: + accessible_chat(conn, chat_id, actor["id"]) + + if cursor is None: + rows = conn.execute( + """ + SELECT id, chat_id, sender_id, text, created_at + FROM messages + WHERE chat_id = %s + ORDER BY created_at, id + LIMIT %s + """, + (chat_id, limit + 1) + ).fetchall() + else: + timestamp, last_id = read_cursor(cursor, resource) + + rows = conn.execute( + """ + SELECT id, chat_id, sender_id, text, created_at + FROM messages + WHERE chat_id = %s + AND (created_at, id) > (%s, %s) + ORDER BY created_at, id + LIMIT %s + """, + (chat_id, timestamp, last_id, limit + 1) + ).fetchall() + + has_more = len(rows) > limit + page = rows[:limit] + + next_cursor = ( + make_cursor(resource, page[-1]) + if has_more else None + ) + + items = [message_json(row, conn) for row in page] + + return {"items": items, "next_cursor": next_cursor} + +# Initialize observability after route registration. +configure_api_observability(app) \ No newline at end of file diff --git a/src/migrate.py b/src/migrate.py new file mode 100644 index 0000000..c13aa99 --- /dev/null +++ b/src/migrate.py @@ -0,0 +1,53 @@ + +import os +from pathlib import Path + +import psycopg + + +DATABASE_URL = os.environ["DATABASE_URL"] +MIGRATIONS_DIR = Path(__file__).resolve().parent.parent / "migrations" + + +def run_migrations(): + with psycopg.connect(DATABASE_URL) as conn: + with conn.cursor() as cur: + # Prevent simultaneous migration runs. + cur.execute("SELECT pg_advisory_xact_lock(2026002)") + + cur.execute(""" + CREATE TABLE IF NOT EXISTS schema_migrations ( + version TEXT PRIMARY KEY, + applied_at TIMESTAMPTZ NOT NULL + DEFAULT clock_timestamp() + ) + """) + + for file in sorted(MIGRATIONS_DIR.glob("*.sql")): + cur.execute( + "SELECT 1 FROM schema_migrations WHERE version = %s", + (file.name,) + ) + + if cur.fetchone(): + print(f"Already applied: {file.name}") + continue + + sql = file.read_text(encoding="utf-8") + + for statement in sql.split(";"): + if statement.strip(): + cur.execute(statement) + + cur.execute( + "INSERT INTO schema_migrations (version) VALUES (%s)", + (file.name,) + ) + + print(f"Applied migration: {file.name}") + + print("Migrations completed") + + +if __name__ == "__main__": + run_migrations() diff --git a/src/openbao_cert_client.py b/src/openbao_cert_client.py new file mode 100644 index 0000000..add3b02 --- /dev/null +++ b/src/openbao_cert_client.py @@ -0,0 +1,149 @@ +"""Read OpenBao runtime secrets using client certificate authentication.""" + +import json +import os +import ssl +import urllib.request +from pathlib import Path +from urllib.parse import quote + +class CertificateBootstrapError(Exception): + """OpenBao certificate bootstrap failed.""" + +SERVICE_PATHS = { + "lab7-api1": "lab7/data/api/runtime", + "lab7-api1-next": "lab7/data/api/runtime", + "lab7-api2": "lab7/data/api/runtime", + "lab7-api2-next": "lab7/data/api/runtime", + "lab7-worker": "lab7/data/worker/runtime", + "lab7-worker-next": "lab7/data/worker/runtime", +} + +def _request(method, url, tls, token=None, payload=None): + headers = {} + body = None + + if token is not None: + headers["X-Vault-Token"] = token + + if payload is not None: + body = json.dumps(payload).encode("utf-8") + headers["Content-Type"] = "application/json" + + request = urllib.request.Request( + url, + headers=headers, + data=body, + method=method, + ) + + with urllib.request.urlopen( + request, + context=tls, + timeout=15, + ) as response: + raw = response.read() + return json.loads(raw) if raw else {} + + +def read_runtime_secrets(): + """Authenticate with a certificate and read scoped KV v2 data.""" + + address = os.environ.get("BAO_ADDR", "") + ca_file = os.environ.get("BAO_CACERT", "") + cert_file = os.environ.get("BAO_CERT_FILE", "") + key_file = os.environ.get("BAO_KEY_FILE", "") + cert_name = os.environ.get("BAO_CERT_NAME", "") + secret_path = os.environ.get("BAO_SECRET_PATH", "") + + if not address.startswith("https://"): + raise CertificateBootstrapError( + "HTTPS OpenBao address required" + ) + + if any( + not value + for value in ( + ca_file, + cert_file, + key_file, + cert_name, + secret_path, + ) + ): + raise CertificateBootstrapError( + "Certificate bootstrap configuration incomplete" + ) + + if SERVICE_PATHS.get(cert_name) != secret_path: + raise CertificateBootstrapError( + "Certificate identity and secret path mismatch" + ) + + for filename in (ca_file, cert_file, key_file): + if not Path(filename).is_file(): + raise CertificateBootstrapError( + "Required TLS credential file unavailable" + ) + + try: + tls = ssl.create_default_context(cafile=ca_file) + tls.load_cert_chain( + certfile=cert_file, + keyfile=key_file, + ) + + base_url = address.rstrip("/") + "/v1" + + login_result = _request( + "POST", + base_url + "/auth/cert/login", + tls, + payload={"name": cert_name}, + ) + + auth = login_result["auth"] + token = auth["client_token"] + + except Exception as exc: + raise CertificateBootstrapError( + "Certificate authentication failed" + ) from exc + + try: + result = _request( + "GET", + base_url + "/" + quote( + secret_path, + safe="/", + ), + tls, + token=token, + ) + + secrets = result["data"]["data"] + + if not isinstance(secrets, dict) or not secrets: + raise ValueError("Invalid KV v2 response") + + return secrets + + except Exception as exc: + raise CertificateBootstrapError( + "Runtime secret retrieval failed" + ) from exc + + finally: + # The service token is no longer needed after KV retrieval. + try: + _request( + "POST", + base_url + "/auth/token/revoke-self", + tls, + token=token, + payload={}, + ) + except Exception: + # A failed revocation does not change the ACL or TTL. + # The token remains bounded by its configured lifetime. + pass diff --git a/src/openbao_client.py b/src/openbao_client.py new file mode 100644 index 0000000..45bdb3c --- /dev/null +++ b/src/openbao_client.py @@ -0,0 +1,159 @@ +"""OpenBao HTTPS AppRole and KV v2 client.""" + +import json +import os +import ssl +import urllib.error +import urllib.request +from pathlib import Path + + +class OpenBaoError(RuntimeError): + """OpenBao authentication or secrets access failed.""" + + +def _read_credential(path): + if not path: + raise OpenBaoError("AppRole credential file is not configured") + + try: + value = Path(path).read_text(encoding="utf-8").strip() + except OSError as exc: + raise OpenBaoError( + "AppRole credential file cannot be read" + ) from exc + + if not value: + raise OpenBaoError("AppRole credential file is empty") + + return value + + +def _request(method, url, context, token=None, payload=None): + headers = {"Accept": "application/json"} + body = None + + if token is not None: + headers["X-Vault-Token"] = token + + if payload is not None: + body = json.dumps(payload).encode("utf-8") + headers["Content-Type"] = "application/json" + + request = urllib.request.Request( + url, + data=body, + headers=headers, + method=method, + ) + + try: + with urllib.request.urlopen( + request, + context=context, + timeout=10, + ) as response: + data = response.read() + + return json.loads(data) if data else {} + + except urllib.error.HTTPError as exc: + # Do not expose response bodies, tokens or credentials. + raise OpenBaoError( + "OpenBao returned HTTP {}".format(exc.code) + ) from None + + except ( + urllib.error.URLError, + TimeoutError, + OSError, + ): + raise OpenBaoError( + "OpenBao connection or TLS verification failed" + ) from None + + +def read_runtime_secrets(): + """Authenticate with AppRole and read a scoped KV v2 secret.""" + + address = os.environ.get("BAO_ADDR", "") + ca_file = os.environ.get("BAO_CACERT", "") + role_file = os.environ.get("BAO_ROLE_ID_FILE", "") + secret_file = os.environ.get("BAO_SECRET_ID_FILE", "") + secret_path = os.environ.get("BAO_SECRET_PATH", "") + + if not address.startswith("https://"): + raise OpenBaoError("OpenBao HTTPS address is required") + + if not ca_file: + raise OpenBaoError("OpenBao CA file is required") + + if not secret_path or not secret_path.startswith("lab7/data/"): + raise OpenBaoError("Invalid OpenBao secret path") + + # Separate bootstrap credentials from application secrets. + role_id = _read_credential(role_file) + secret_id = _read_credential(secret_file) + + try: + context = ssl.create_default_context(cafile=ca_file) + except (OSError, ssl.SSLError): + raise OpenBaoError("OpenBao CA configuration is invalid") from None + + base_url = address.rstrip("/") + "/v1" + + login = _request( + "POST", + base_url + "/auth/approle/login", + context, + payload={ + "role_id": role_id, + "secret_id": secret_id, + }, + ) + + try: + auth = login["auth"] + token = auth["client_token"] + + if not token or auth["lease_duration"] <= 0: + raise ValueError("invalid token") + except (KeyError, TypeError, ValueError): + raise OpenBaoError("Invalid AppRole login response") from None + + try: + result = _request( + "GET", + base_url + "/" + secret_path, + context, + token=token, + ) + + secrets = result["data"]["data"] + + if not isinstance(secrets, dict) or not secrets: + raise OpenBaoError("OpenBao returned empty secrets") + + if not all( + isinstance(value, str) and bool(value) + for value in secrets.values() + ): + raise OpenBaoError("OpenBao returned invalid secret values") + + return secrets + + except (KeyError, TypeError): + raise OpenBaoError("Invalid KV v2 response") from None + + finally: + # The short-lived token is no longer needed after readback. + # Revoke it when possible; its TTL also limits exposure. + try: + _request( + "POST", + base_url + "/auth/token/revoke-self", + context, + token=token, + ) + except OpenBaoError: + pass diff --git a/src/openbao_entrypoint.py b/src/openbao_entrypoint.py new file mode 100644 index 0000000..89fe32c --- /dev/null +++ b/src/openbao_entrypoint.py @@ -0,0 +1,87 @@ +"""Start an application with runtime secrets loaded from OpenBao.""" + +import os +import sys + +from src.openbao_cert_client import ( + CertificateBootstrapError, + read_runtime_secrets, +) + + +REQUIRED_FIELDS = { + "lab7/data/api/runtime": { + "DATABASE_URL", + "S3_ACCESS_KEY", + "S3_SECRET_KEY", + }, + "lab7/data/worker/runtime": { + "DATABASE_URL", + "RABBITMQ_USER", + "RABBITMQ_PASSWORD", + "S3_ACCESS_KEY", + "S3_SECRET_KEY", + }, +} + + +def main(): + if len(sys.argv) < 2: + raise SystemExit("FAIL: application command is missing") + + command = sys.argv[1:] + + if command[0] == "--": + command = command[1:] + + if not command: + raise SystemExit("FAIL: application command is missing") + + secret_path = os.environ.get("BAO_SECRET_PATH", "") + + required = REQUIRED_FIELDS.get(secret_path) + + if required is None: + raise SystemExit("FAIL: unexpected OpenBao secret path") + + try: + secrets = read_runtime_secrets() + + except CertificateBootstrapError: + print( + "FAIL: OpenBao runtime bootstrap unavailable", + file=sys.stderr, + ) + raise SystemExit(1) + + if set(secrets) != required: + print( + "FAIL: invalid OpenBao runtime secret fields", + file=sys.stderr, + ) + raise SystemExit(1) + + if not all( + isinstance(value, str) and bool(value) + for value in secrets.values() + ): + print( + "FAIL: invalid OpenBao runtime secret values", + file=sys.stderr, + ) + raise SystemExit(1) + + # Replace existing values rather than using them as fallback. + os.environ.update(secrets) + + print( + "PASS: runtime credentials loaded from OpenBao", + flush=True, + ) + + # Replace the bootstrap process with the application. + os.execvp(command[0], command) + + +if __name__ == "__main__": + main() diff --git a/src/queue.py b/src/queue.py new file mode 100644 index 0000000..22d03d6 --- /dev/null +++ b/src/queue.py @@ -0,0 +1,111 @@ + +import json +import os +import ssl +import uuid + +import pika + + +RABBITMQ_HOST = os.getenv("RABBITMQ_HOST", "rabbitmq") +RABBITMQ_USER = os.environ["RABBITMQ_USER"] +RABBITMQ_PASSWORD = os.environ["RABBITMQ_PASSWORD"] +RABBITMQ_QUEUE = os.getenv( + "RABBITMQ_QUEUE", + "image_jobs", +) + +RABBITMQ_CA_FILE = os.getenv( + "RABBITMQ_CA_FILE", + "/etc/ssl/lab7/ca.crt", +) + + +def connect(): + # Validate the broker certificate and its DNS name. + # Do not fall back to an unencrypted connection. + context = ssl.create_default_context( + cafile=RABBITMQ_CA_FILE, + ) + context.minimum_version = ssl.TLSVersion.TLSv1_2 + context.verify_mode = ssl.CERT_REQUIRED + context.check_hostname = True + + credentials = pika.PlainCredentials( + RABBITMQ_USER, + RABBITMQ_PASSWORD, + ) + + parameters = pika.ConnectionParameters( + host=RABBITMQ_HOST, + port=5671, + virtual_host="/", + credentials=credentials, + ssl_options=pika.SSLOptions( + context, + server_hostname=RABBITMQ_HOST, + ), + heartbeat=30, + blocked_connection_timeout=15, + connection_attempts=3, + retry_delay=2, + socket_timeout=5, + stack_timeout=15, + ) + + return pika.BlockingConnection(parameters) + + +def declare_queue(channel): + channel.queue_declare( + queue=RABBITMQ_QUEUE, + durable=True, + arguments={ + "x-queue-type": "quorum", + }, + ) + + +def publish_job(job_id): + connection = connect() + + try: + channel = connection.channel() + declare_queue(channel) + + # Wait for confirmation from RabbitMQ. + channel.confirm_delivery() + + payload = json.dumps({ + "job_id": str(uuid.UUID(str(job_id))), + }).encode("utf-8") + + channel.basic_publish( + exchange="", + routing_key=RABBITMQ_QUEUE, + body=payload, + properties=pika.BasicProperties( + delivery_mode=2, + content_type="application/json", + message_id=str(job_id), + ), + mandatory=True, + ) + + finally: + if connection.is_open: + connection.close() + + +def parse_job(body): + payload = json.loads(body) + + if not isinstance(payload, dict): + raise ValueError("Invalid job payload") + + job_id = payload.get("job_id") + + if not isinstance(job_id, str): + raise ValueError("Missing job_id") + + return str(uuid.UUID(job_id)) diff --git a/src/s3_setup.py b/src/s3_setup.py new file mode 100644 index 0000000..7798af6 --- /dev/null +++ b/src/s3_setup.py @@ -0,0 +1,60 @@ + +import os +import time + +import boto3 +from botocore.config import Config +from botocore.exceptions import ClientError + + +def main(): + bucket = os.environ["S3_BUCKET"] + + client = boto3.client( + "s3", + endpoint_url=os.environ["S3_ENDPOINT"], + aws_access_key_id=os.environ["S3_ACCESS_KEY"], + aws_secret_access_key=os.environ["S3_SECRET_KEY"], + region_name="us-east-1", + config=Config( + signature_version="s3v4", + s3={"addressing_style": "path"}, + ), + ) + + for attempt in range(30): + try: + client.head_bucket(Bucket=bucket) + print(f"Bucket already exists: {bucket}", flush=True) + break + + except ClientError as exc: + code = exc.response["Error"]["Code"] + + if code in ("404", "NoSuchBucket"): + try: + client.create_bucket(Bucket=bucket) + print(f"Bucket created: {bucket}", flush=True) + break + except Exception as create_error: + print( + f"Waiting for S3: {create_error}", + flush=True, + ) + else: + print(f"Waiting for S3: {exc}", flush=True) + + except Exception as exc: + print(f"Waiting for S3: {exc}", flush=True) + + if attempt == 29: + raise RuntimeError("Cannot initialize S3 bucket") + + time.sleep(2) + + # No public bucket policy is configured. + print(f"Private S3 bucket is ready: {bucket}", flush=True) + + +if __name__ == "__main__": + main() diff --git a/src/telemetry.py b/src/telemetry.py new file mode 100644 index 0000000..4d4838c --- /dev/null +++ b/src/telemetry.py @@ -0,0 +1,182 @@ + +import logging +import os +import socket + +from opentelemetry import metrics, trace +from opentelemetry._logs import set_logger_provider +from opentelemetry.exporter.otlp.proto.http._log_exporter import ( + OTLPLogExporter, +) +from opentelemetry.exporter.otlp.proto.http.metric_exporter import ( + OTLPMetricExporter, +) +from opentelemetry.exporter.otlp.proto.http.trace_exporter import ( + OTLPSpanExporter, +) +from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler +from opentelemetry.sdk._logs.export import ( + BatchLogRecordProcessor, +) +from opentelemetry.sdk.metrics import MeterProvider +from opentelemetry.sdk.metrics.export import ( + PeriodicExportingMetricReader, +) +from opentelemetry.sdk.resources import Resource +from opentelemetry.sdk.trace import TracerProvider +from opentelemetry.sdk.trace.export import ( + BatchSpanProcessor, +) + + +SERVICE_VERSION = "lab6-1.0" +ENVIRONMENT = "lab" + +OTLP_ENDPOINT = os.getenv( + "OTEL_EXPORTER_OTLP_ENDPOINT", + "http://otel-collector:4318", +).rstrip("/") + +OTLP_CA_FILE = os.getenv( + "OTEL_EXPORTER_OTLP_CERTIFICATE", + "/etc/ssl/lab7/ca.crt", +) + +OTLP_TLS_VERIFY = ( + OTLP_CA_FILE + if OTLP_ENDPOINT.startswith("https://") + else None +) + + +class TraceContextFilter(logging.Filter): + def filter(self, record): + context = trace.get_current_span().get_span_context() + + if context.is_valid: + record.trace_id = format( + context.trace_id, "032x" + ) + record.span_id = format( + context.span_id, "016x" + ) + else: + record.trace_id = "-" + record.span_id = "-" + + return True + + +def setup_telemetry(service_name): + """ + Initialize OTLP traces, metrics and logs. + + Do not record request bodies, Authorization + headers, message text or image bytes. + """ + + resource = Resource.create( + { + "service.name": service_name, + "service.version": SERVICE_VERSION, + "service.instance.id": os.getenv( + "HOSTNAME", + socket.gethostname(), + ), + "deployment.environment.name": ENVIRONMENT, + } + ) + + # Distributed traces -> Collector -> Tempo + tracer_provider = TracerProvider(resource=resource) + + trace_exporter = OTLPSpanExporter( + endpoint=f"{OTLP_ENDPOINT}/v1/traces", + timeout=3, + certificate_file=OTLP_TLS_VERIFY, + ) + + tracer_provider.add_span_processor( + BatchSpanProcessor( + trace_exporter, + max_queue_size=1024, + ) + ) + + trace.set_tracer_provider(tracer_provider) + + # Metrics -> Collector -> Prometheus + metric_exporter = OTLPMetricExporter( + endpoint=f"{OTLP_ENDPOINT}/v1/metrics", + timeout=3, + certificate_file=OTLP_TLS_VERIFY, + ) + + metric_reader = PeriodicExportingMetricReader( + metric_exporter, + export_interval_millis=5000, + export_timeout_millis=3000, + ) + + meter_provider = MeterProvider( + resource=resource, + metric_readers=[metric_reader], + ) + + metrics.set_meter_provider(meter_provider) + + # Structured logs -> Collector -> Loki + logger_provider = LoggerProvider(resource=resource) + + log_exporter = OTLPLogExporter( + endpoint=f"{OTLP_ENDPOINT}/v1/logs", + timeout=3, + certificate_file=OTLP_TLS_VERIFY, + ) + + logger_provider.add_log_record_processor( + BatchLogRecordProcessor( + log_exporter, + max_queue_size=1024, + ) + ) + + set_logger_provider(logger_provider) + + # Dedicated application logger. + # We intentionally do not forward arbitrary + # library logs or sensitive request data. + logger = logging.getLogger("messenger.telemetry") + logger.setLevel(logging.INFO) + logger.propagate = False + + for handler in list(logger.handlers): + logger.removeHandler(handler) + + context_filter = TraceContextFilter() + + console_handler = logging.StreamHandler() + console_handler.addFilter(context_filter) + console_handler.setFormatter( + logging.Formatter( + "%(asctime)s %(levelname)s " + "event=%(event)s " + "trace_id=%(trace_id)s " + "span_id=%(span_id)s " + "%(message)s" + ) + ) + + logger.addHandler(console_handler) + + otlp_handler = LoggingHandler( + level=logging.INFO, + logger_provider=logger_provider, + ) + otlp_handler.addFilter(context_filter) + logger.addHandler(otlp_handler) + + tracer = trace.get_tracer(service_name, SERVICE_VERSION) + meter = metrics.get_meter(service_name, SERVICE_VERSION) + + return tracer, meter, logger diff --git a/src/worker.py b/src/worker.py new file mode 100644 index 0000000..5bde427 --- /dev/null +++ b/src/worker.py @@ -0,0 +1,576 @@ + +import hashlib +import io +import logging +import os +import time + +import boto3 +import pika +import psycopg +from opentelemetry.trace import SpanKind, Status, StatusCode +from src.telemetry import setup_telemetry +from botocore.config import Config +from PIL import Image, ImageOps +from psycopg.rows import dict_row + +from src.queue import ( + RABBITMQ_QUEUE, + connect, + declare_queue, + parse_job, +) + + +logging.basicConfig( + level=logging.INFO, + format="%(asctime)s %(levelname)s %(message)s", +) + +logger = logging.getLogger("image-worker") + +worker_tracer, worker_meter, worker_logger = setup_telemetry( + "messenger-worker" +) + +jobs_processed = worker_meter.create_counter( + name="messenger_worker_jobs_processed", + unit="{job}", + description="Image processing job attempts by outcome", +) + +job_duration = worker_meter.create_histogram( + name="messenger_worker_job_duration", + unit="s", + description="Image processing duration in seconds", +) + +DATABASE_URL = os.environ["DATABASE_URL"] +S3_BUCKET = os.environ["S3_BUCKET"] +MAX_BYTES = 10 * 1024 * 1024 + +s3 = boto3.client( + "s3", + endpoint_url=os.environ["S3_ENDPOINT"], + aws_access_key_id=os.environ["S3_ACCESS_KEY"], + aws_secret_access_key=os.environ["S3_SECRET_KEY"], + region_name="us-east-1", + config=Config( + signature_version="s3v4", + s3={"addressing_style": "path"}, + connect_timeout=3, + read_timeout=15, + retries={"max_attempts": 1}, + ), +) + + +class InvalidImage(Exception): + pass + + +def make_thumbnail(original): + try: + with Image.open(io.BytesIO(original)) as image: + if image.format not in ("PNG", "JPEG"): + raise InvalidImage("Unsupported image") + + if image.width * image.height > 40_000_000: + raise InvalidImage("Too many pixels") + + image = ImageOps.exif_transpose(image) + image.thumbnail( + (256, 256), + Image.Resampling.LANCZOS, + ) + + # JPEG does not support transparency. + rgba = image.convert("RGBA") + + background = Image.new( + "RGB", + rgba.size, + (255, 255, 255), + ) + + background.paste( + rgba, + mask=rgba.getchannel("A"), + ) + + output = io.BytesIO() + + background.save( + output, + format="JPEG", + quality=85, + optimize=True, + ) + + return ( + output.getvalue(), + background.width, + background.height, + ) + + except (OSError, SyntaxError, EOFError) as exc: + raise InvalidImage("Invalid image") from exc + + +def get_staging_object(key): + response = s3.get_object( + Bucket=S3_BUCKET, + Key=key, + ) + + stream = response["Body"] + + try: + data = stream.read(MAX_BYTES + 1) + finally: + stream.close() + + if not data or len(data) > MAX_BYTES: + raise InvalidImage("Invalid staging size") + + return data + + +def process_job(job_id): + """ + Use a PostgreSQL row lock to prevent concurrent + processing of the same logical job. + + The transaction commits before RabbitMQ ACK. + """ + + with psycopg.connect( + DATABASE_URL, + row_factory=dict_row, + ) as conn: + + job = conn.execute( + """ + SELECT j.*, a.staging_key, + a.object_key, a.sha256, + a.size_bytes, a.status AS attachment_status + FROM attachment_jobs j + JOIN attachments a + ON a.id = j.attachment_id + WHERE j.id = %s + FOR UPDATE OF j, a + """, + (job_id,), + ).fetchone() + + if job is None: + logger.info("Unknown job %s, ignoring", job_id) + return + + if job["status"] == "ready": + logger.info("Job %s already completed", job_id) + return + + if job["status"] == "failed": + logger.info("Job %s already failed", job_id) + return + + if job["next_attempt_at"] is not None: + from datetime import datetime, timezone + + if job["next_attempt_at"] > datetime.now(timezone.utc): + logger.info("Job %s is not due yet", job_id) + return + + attempts = job["attempts"] + 1 + + if attempts > job["max_attempts"]: + conn.execute( + """ + UPDATE attachment_jobs + SET status = 'failed', + completed_at = NOW(), + updated_at = NOW() + WHERE id = %s + """, + (job_id,), + ) + + conn.execute( + """ + UPDATE attachments + SET status = 'failed', + error_code = 'processing_failed', + updated_at = NOW() + WHERE id = %s + """, + (job["attachment_id"],), + ) + + return + + conn.execute( + """ + UPDATE attachment_jobs + SET status = 'processing', + attempts = %s, + started_at = NOW(), + updated_at = NOW() + WHERE id = %s + """, + (attempts, job_id), + ) + + conn.execute( + """ + UPDATE attachments + SET status = 'processing', + updated_at = NOW() + WHERE id = %s + """, + (job["attachment_id"],), + ) + + try: + original = get_staging_object( + job["staging_key"] + ) + + if ( + len(original) != job["size_bytes"] + or hashlib.sha256(original).hexdigest() + != job["sha256"] + ): + raise InvalidImage("Staging checksum mismatch") + + thumbnail, width, height = make_thumbnail( + original + ) + + attachment_id = str(job["attachment_id"]) + + # Stable keys make duplicate delivery safe. + original_key = job["object_key"] + thumb_key = ( + f"thumbnails/{attachment_id}.jpg" + ) + + s3.put_object( + Bucket=S3_BUCKET, + Key=original_key, + Body=original, + ContentType="image/png" + if original[:8] == b"\x89PNG\r\n\x1a\n" + else "image/jpeg", + ) + + s3.put_object( + Bucket=S3_BUCKET, + Key=thumb_key, + Body=thumbnail, + ContentType="image/jpeg", + ) + + thumb_sha256 = hashlib.sha256( + thumbnail + ).hexdigest() + + conn.execute( + """ + INSERT INTO attachment_variants + ( + attachment_id, + variant_name, + object_key, + content_type, + size_bytes, + sha256, + width, + height + ) + VALUES ( + %s, 'thumbnail', %s, 'image/jpeg', + %s, %s, %s, %s + ) + ON CONFLICT ( + attachment_id, variant_name + ) + DO UPDATE SET + object_key = EXCLUDED.object_key, + size_bytes = EXCLUDED.size_bytes, + sha256 = EXCLUDED.sha256, + width = EXCLUDED.width, + height = EXCLUDED.height + """, + ( + job["attachment_id"], + thumb_key, + len(thumbnail), + thumb_sha256, + width, + height, + ), + ) + + conn.execute( + """ + UPDATE attachments + SET status = 'ready', + error_code = NULL, + updated_at = NOW() + WHERE id = %s + """, + (job["attachment_id"],), + ) + + conn.execute( + """ + UPDATE attachment_jobs + SET status = 'ready', + completed_at = NOW(), + updated_at = NOW() + WHERE id = %s + """, + (job_id,), + ) + + logger.info( + "Job %s ready, thumbnail %sx%s", + job_id, + width, + height, + ) + + except Exception as exc: + logger.exception( + "Processing failed for job %s: %s", + job_id, + type(exc).__name__, + ) + + if ( + attempts >= job["max_attempts"] + or isinstance(exc, InvalidImage) + ): + conn.execute( + """ + UPDATE attachment_jobs + SET status = 'failed', + completed_at = NOW(), + updated_at = NOW() + WHERE id = %s + """, + (job_id,), + ) + + conn.execute( + """ + UPDATE attachments + SET status = 'failed', + error_code = 'processing_failed', + updated_at = NOW() + WHERE id = %s + """, + (job["attachment_id"],), + ) + + else: + conn.execute( + """ + UPDATE attachment_jobs + SET status = 'queued', + next_attempt_at = + NOW() + INTERVAL '5 seconds', + published_at = NULL, + updated_at = NOW() + WHERE id = %s + """, + (job_id,), + ) + + conn.execute( + """ + UPDATE attachments + SET status = 'queued', + updated_at = NOW() + WHERE id = %s + """, + (job["attachment_id"],), + ) + + +def get_job_status(job_id): + with psycopg.connect(DATABASE_URL) as conn: + row = conn.execute( + """ + SELECT status + FROM attachment_jobs + WHERE id = %s + """, + (job_id,), + ).fetchone() + + return row[0] if row else None + + +def on_message(channel, method, properties, body): + try: + job_id = parse_job(body) + except (ValueError, TypeError, KeyError): + logger.warning("Invalid queue message") + channel.basic_ack( + delivery_tag=method.delivery_tag + ) + return + + attributes = { + "messaging.system": "rabbitmq", + "messaging.destination.name": RABBITMQ_QUEUE, + "messaging.operation.name": "process", + "messenger.job_type": "image_thumbnail", + } + + # A real consumer span around the actual job processing. + with worker_tracer.start_as_current_span( + "image_job.process", + kind=SpanKind.CONSUMER, + attributes=attributes, + ) as span: + + started = time.monotonic() + + try: + previous_status = get_job_status(job_id) + + process_job(job_id) + + current_status = get_job_status(job_id) + duration = time.monotonic() - started + + if previous_status in ("ready", "failed"): + outcome = "duplicate" + + elif current_status == "ready": + outcome = "success" + + elif current_status == "failed": + outcome = "failed" + + elif current_status == "queued": + outcome = "retry" + + else: + outcome = "ignored" + + span.set_attribute( + "messenger.job.outcome", + outcome, + ) + + if outcome == "failed": + span.set_status( + Status(StatusCode.ERROR) + ) + + # Count actual processing attempts, not + # duplicate deliveries of completed jobs. + if outcome in ("success", "failed", "retry"): + metric_attributes = { + "job_type": "image_thumbnail", + "outcome": outcome, + } + + jobs_processed.add( + 1, + attributes=metric_attributes, + ) + + job_duration.record( + duration, + attributes=metric_attributes, + ) + + worker_logger.info( + "Image job handled", + extra={ + "event": "image_job_handled", + "job_type": "image_thumbnail", + "outcome": outcome, + "duration_seconds": round(duration, 4), + }, + ) + + # ACK after process_job has committed the + # PostgreSQL transaction. + channel.basic_ack( + delivery_tag=method.delivery_tag + ) + + except Exception as exc: + span.record_exception(exc) + span.set_status(Status(StatusCode.ERROR)) + + worker_logger.error( + "Image job processing interrupted", + extra={ + "event": "image_job_interrupted", + "job_type": "image_thumbnail", + "error_type": type(exc).__name__, + }, + ) + + logger.exception( + "Unexpected failure for job %s", + job_id, + ) + + channel.basic_nack( + delivery_tag=method.delivery_tag, + requeue=True, + ) + + time.sleep(2) + + + +def main(): + while True: + try: + connection = connect() + channel = connection.channel() + + declare_queue(channel) + + channel.basic_qos( + prefetch_count=1 + ) + + channel.basic_consume( + queue=RABBITMQ_QUEUE, + on_message_callback=on_message, + auto_ack=False, + ) + + logger.info( + "Worker listening on %s", + RABBITMQ_QUEUE, + ) + + channel.start_consuming() + + except Exception: + logger.exception( + "Worker disconnected, reconnecting" + ) + time.sleep(3) + + finally: + if ( + "connection" in locals() + and connection.is_open + ): + connection.close() + + +if __name__ == "__main__": + main()