This commit is contained in:
+1
-1
@@ -6,7 +6,7 @@ APP_ENV=lab
|
||||
SESSION_TTL_SECONDS=3600
|
||||
# Choose credentials locally. File paths contain no secret values.
|
||||
DATABASE_URL_FILE=/run/secrets/database_url
|
||||
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
|
||||
# Optional separate session store; Redis OR Valkey:
|
||||
SESSION_STORE=postgres
|
||||
CACHE_URL_FILE=/run/secrets/cache_url
|
||||
API_REPLICAS=2
|
||||
|
||||
+3
-3
@@ -5,15 +5,15 @@
|
||||
3. Для lab2–7 перенесите из своей предыдущей лабы только исходники, миграции, собственные тесты, Dockerfile и нужные конфигурации. Не копируйте `.git`, `.env`, credentials, volumes, `README.md`, `COURSE.md`, публичные `tests/` и `contracts/` поверх новой версии. Сначала сравните изменения API в `COURSE.md`.
|
||||
4. Реализуйте задание, добавьте свою инструкцию запуска и заполните `REPORT.md`. Публичные проверки дополняйте отдельными тестами, не ослабляйте assertions.
|
||||
5. Выполните `make check`, запустите свой стенд, затем `make test`. Выполните сценарии отказов текущей лабы. Их запуск всегда явный: scaffold сам не останавливает контейнеры.
|
||||
6. Commit и push делайте в свой fork. Откройте PR в исходный репозиторий преподавателя, заголовок: `ЛР N — Группа — Фамилия — на 3/4/5`. Выберите правильную базовую ветку и заполните шаблон.
|
||||
6. Commit и push делайте в свой fork. Откройте PR в исходный репозиторий преподавателя, заголовок: `ЛР N — Группа — Фамилия`. Выберите правильную базовую ветку и заполните шаблон.
|
||||
7. После замечаний обновляйте тот же PR. Чужие решения не переносите без указания источника и согласованных правил курса.
|
||||
|
||||
Платформа может называть PR «merge request» — процесс тот же. `.github/` содержит необязательные удобства для GitHub; проверки локально от платформы не зависят. Инициализация и публикация исходных Git-репозиториев выполняются преподавателем отдельно.
|
||||
|
||||
## Правила изменения skeleton
|
||||
|
||||
Не удаляйте обязательные endpoint, поля, рубрику и публичные проверки. Изменение контракта согласуйте отдельным комментарием/PR; обход тестов не является решением. Код приложения размещайте в `src/` либо в принятой для языка структуре. Собственные тесты — `student-tests/` или штатный каталог фреймворка. Ссылки на результаты проверки и команды запуска должны переживать clone на другой машине.
|
||||
Не удаляйте обязательные endpoint, поля, требования и публичные проверки. Изменение контракта согласуйте отдельным комментарием/PR; обход тестов не является решением. Код приложения размещайте в `app/` либо в принятой для Python структуре. Собственные тесты — `student-tests/` или штатный каталог фреймворка. Ссылки на результаты проверки и команды запуска должны переживать clone на другой машине.
|
||||
|
||||
## CI
|
||||
|
||||
Готовый GitHub workflow проверяет целостность контракта и синтаксис Python-проверок. Он **не запускает отсутствующее приложение** и **не подтверждает оценку**. Студент добавляет сборку своего приложения, запуск/готовность стенда и `make test` в отдельный job. Не используйте `pull_request_target` для запуска кода из fork, не выдавайте CI секреты или доступ к общему Docker-host.
|
||||
GitHub workflow проверяет целостность контракта и синтаксис Python; локально `make up` запускает Compose-стенд, а `make test` выполняет HTTPS smoke. CI не подтверждает выполнение всех требований безопасности. Не используйте `pull_request_target` для запуска кода из fork, не выдавайте CI секреты или доступ к общему Docker-host.
|
||||
|
||||
@@ -30,7 +30,7 @@
|
||||
2. **2 → 3:** `Idempotency-Key` обязателен для отправки сообщения; ответы API содержат `X-Instance-Id`.
|
||||
3. **4 → 5:** загрузка вложения возвращает `202` вместо `201`, состояние становится асинхронным. Клиент опрашивает метаданные. Старое текстовое сообщение остаётся валидным: `attachment_ids` по умолчанию `[]`.
|
||||
|
||||
У lab7 меняется транспорт на HTTPS, бизнес-эндпоинты остаются прежними. Внутреннее mTLS не заменяет пользовательскую сессию. Новые возможности на 4/5 добавляйте обратно совместимо, в отдельном `contracts/extensions.openapi.json` или документе; обязательный контракт сохраняйте.
|
||||
У lab7 меняется транспорт на HTTPS, бизнес-эндпоинты остаются прежними. Внутреннее mTLS не заменяет пользовательскую сессию. Для lab7 действует только обязательный набор требований из README; дополнительные уровни и исследовательские треки не задаются. Обязательный контракт сохраняйте.
|
||||
|
||||
## Общая предметная модель
|
||||
|
||||
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
FROM python:3.12.8-slim
|
||||
|
||||
ENV PYTHONDONTWRITEBYTECODE=1 \
|
||||
PYTHONUNBUFFERED=1 \
|
||||
PIP_DISABLE_PIP_VERSION_CHECK=1 \
|
||||
PIP_NO_CACHE_DIR=1
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
RUN groupadd --system --gid 10001 messenger \
|
||||
&& useradd --system --uid 10001 --gid messenger --home-dir /app messenger
|
||||
|
||||
COPY requirements.txt /app/requirements.txt
|
||||
RUN python -m pip install --no-cache-dir -r /app/requirements.txt
|
||||
|
||||
COPY app /app/app
|
||||
RUN chown -R 10001:10001 /app
|
||||
|
||||
USER 10001:10001
|
||||
EXPOSE 8443
|
||||
CMD ["python", "-m", "app.api"]
|
||||
+6
-6
@@ -1,8 +1,8 @@
|
||||
# Teaching outline, not a runnable Dockerfile. Implement your own Dockerfile.
|
||||
# 1. Choose a runtime/toolchain version and pin the base image tag/digest.
|
||||
# 2. Copy dependency manifests first; install from the language lockfile.
|
||||
# 3. Copy source and build. For compiled languages use a separate runtime stage.
|
||||
# Teaching outline, not a runnable Dockerfile. Implement your own Python image.
|
||||
# 1. Use Python 3.9+ and pin the base image tag/digest.
|
||||
# 2. Copy dependency manifests first; install pinned dependencies.
|
||||
# 3. Copy application source after installing dependencies.
|
||||
# 4. Run the HTTP process as PID 1; listen on 0.0.0.0:8080.
|
||||
# 5. Add non-root, signals and healthcheck according to the current rubric.
|
||||
# 6. Pass runtime config/secrets at startup, never COPY .env or secret files.
|
||||
# 5. Run as non-root, handle signals and configure a healthcheck.
|
||||
# 6. Pass runtime config/secrets at startup; never COPY .env or secret files.
|
||||
# This file deliberately has no FROM/CMD: selecting/implementing them is the task.
|
||||
|
||||
+8
-9
@@ -2,28 +2,29 @@
|
||||
|
||||
## Что подготовлено
|
||||
|
||||
Язык реализации не задан. README содержит накопительные уровни 3/4/5, сценарий защиты и вопросы. В каждой лабе собственная полная версия OpenAPI, поэтому fork не зависит от соседних каталогов. Публичный HTTP smoke не содержит реализации сервера; Dockerfile.example и compose.example.yaml (если есть) — задания/ориентиры, не готовый deployment.
|
||||
В каталоге есть запускаемая Python-реализация и локальный Compose-стенд. README содержит обязательные требования и команды проверки. В каждой лабе собственная полная версия OpenAPI, поэтому fork не зависит от соседних каталогов. `Dockerfile`/`compose.yaml` запускают текущий стек; файлы `*.example` служат учебными ориентирами.
|
||||
|
||||
## Перед публикацией
|
||||
|
||||
1. Выберите GitHub/GitLab и организацию, опубликуйте каждый каталог как отдельный template/skeleton repository, сообщите студентам URL и правила именования PR/MR. Эти материалы не публикуют репозитории автоматически.
|
||||
2. Задайте default branch, защиту исходных материалов и правила приёма. `.github/` уже содержит шаблон PR и CI контракта; в GitLab перенесите эквивалентные настройки, локальные Makefile-команды одинаковы.
|
||||
3. Сообщите, индивидуальная работа или командная, сроки, правила использования стороннего кода/ИИ и ресурсы демонстрационного стенда. Эти организационные решения намеренно не выдуманы в задании.
|
||||
4. Уточните ограничения площадки (например доступна ли виртуализация/несколько узлов). Для 5 предусмотрено по два трека: один можно выполнить без настоящего multi-node cloud. Универсальный проходной RPS не установлен.
|
||||
4. Уточните ограничения площадки (например доступна ли виртуализация/несколько узлов). Не заявляйте отказоустойчивость за пределами проверенной модели стенда.
|
||||
|
||||
## Что проверять
|
||||
|
||||
| Проверка | Что подтверждает | Чего не подтверждает |
|
||||
| --- | --- | --- |
|
||||
| make check | Структура файлов, JSON, локальные refs, синтаксис Python | Реализация/запуск API |
|
||||
| make check | Структура файлов, JSON, локальные refs, синтаксис Python | Запуск контейнеров и поведение API |
|
||||
| make validate | Полная OpenAPI 3.1, JSON Schema и примеры | Поведение сервера |
|
||||
| make test | Один сквозной контрактный сценарий текущей лабы | Все ошибки, persistence, HA, security |
|
||||
| test-persistence (lab2+) | Данные/прежний токен после вызова restart hook | Реальный перезапуск, если hook — no-op |
|
||||
| test-failover (lab3+) | Смена обслуживающей реплики, сохранность, retry без дубля | Несколько физических узлов, HA DB/LB |
|
||||
| test-security (lab7) | Доверенный HTTPS и отказ недоверенного CA | Внутреннее mTLS/identity/ACL/OpenBao |
|
||||
| Защита и тесты студента | Реальность инфраструктуры и критерии выбранного уровня | Неограниченная промышленная безопасность |
|
||||
| test-mtls (lab7) | Внутренний TLS handshake и URI SAN allowlist | OpenBao policy, остальные ACL и hardening |
|
||||
| Защита и тесты студента | Реальность инфраструктуры и выполнение обязательных требований | Неограниченная промышленная безопасность |
|
||||
|
||||
Проверяйте реальные контейнеры/логи процессов и данные до/после отказа: одного X-Instance-Id недостаточно. Для 4 требуются все пункты 3+4, для 5 — все пункты 3+4 и один **завершённый** трек 5. Сравнивайте подтверждённые результаты со сформулированными критериями, а не количество установленных сервисов.
|
||||
Проверяйте реальные контейнеры/логи процессов и данные до/после отказа: одного X-Instance-Id недостаточно. В lab7 проверяйте только обязательные требования из README и подтверждающие их результаты, а не количество установленных сервисов.
|
||||
|
||||
## Приём PR
|
||||
|
||||
@@ -31,8 +32,6 @@
|
||||
|
||||
Исходные README/контракт/публичные tests сохраняются, реализация переносится студентом между лабами через собственные исходники и миграции. Исправление общей спецификации публикуйте отдельным изменением, объясняя влияние на все затронутые лабораторные.
|
||||
|
||||
## Проверка этой версии skeleton
|
||||
## Проверка этой версии
|
||||
|
||||
На 2026-09-10 выполнены структурные проверки и полная валидация всех семи OpenAPI/JSON Schema, проверка локальных Markdown-ссылок/YAML и декодирование PNG fixture. HTTP-клиенты проверены на временном изолированном тестовом стенде: позитивный smoke 1–7, отрицательные варианты неправильного sender, pagination, ACL, logout, bytes и пустого API; также пути persistence/failover/load и внешнего TLS.
|
||||
|
||||
Временный стенд не включён в студенческие каталоги и не является эталонным решением. Реальное приложение, Compose, PostgreSQL/S3/broker и mTLS/OpenBao в skeleton отсутствуют: их работоспособность не заявляется. Docker CLI в среде подготовки не был доступен. Это проверка материалов и тестовых драйверов, не приёмка будущих решений студентов.
|
||||
Записывайте ниже только проверки, которые выполнены на текущем checkout. `make check`/`make validate` подтверждают целостность материалов; полноценное принятие стека требует запуска `make up`, публичного smoke и негативных TLS/identity-проверок. Не переносите сюда результаты временных стендов или предыдущего skeleton.
|
||||
|
||||
@@ -1,13 +1,30 @@
|
||||
PYTHON ?= python3
|
||||
BASE_URL ?= https://localhost:8443
|
||||
CA_FILE ?=
|
||||
CA_FILE ?= secrets/pki/ca.crt
|
||||
ACTION_SCRIPT ?=
|
||||
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
||||
COMPOSE ?= docker compose
|
||||
|
||||
.PHONY: help check validate test load test-persistence test-failover test-security
|
||||
.PHONY: help bootstrap up down logs check validate test load test-persistence test-failover test-security test-mtls
|
||||
|
||||
help:
|
||||
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
|
||||
@echo "bootstrap: create local CA/certificates and ignored secrets"
|
||||
@echo "up: provision and start the secured Compose stack"
|
||||
@echo "down: stop services without deleting persistent volumes"
|
||||
@echo "check: structure, contracts and Python syntax; validate: full OpenAPI"
|
||||
@echo "test: HTTPS smoke; test-security: trusted/untrusted CA check; test-mtls: API identity checks"
|
||||
|
||||
bootstrap:
|
||||
./scripts/bootstrap-local-stack.sh
|
||||
|
||||
up:
|
||||
./scripts/start-stack.sh
|
||||
|
||||
down:
|
||||
$(COMPOSE) down
|
||||
|
||||
logs:
|
||||
$(COMPOSE) logs --tail=100 -f
|
||||
|
||||
check:
|
||||
$(PYTHON) scripts/check_contract.py
|
||||
@@ -31,3 +48,6 @@ test-failover:
|
||||
|
||||
test-security:
|
||||
$(PYTHON) tests/security.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
test-mtls:
|
||||
$(COMPOSE) --profile test run --rm --no-deps mtls-probe
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
# Лабораторная 7. Безопасность, mTLS и OpenBao
|
||||
|
||||
Защитить работающий мессенджер на границах доверия и показать защиту отрицательными проверками: чужой доступ, неверный сертификат, недостаточные права и отзыв credentials.
|
||||
Работающий учебный мессенджер на Python с защищёнными границами доверия. Локальный Compose-стенд включает API/worker, PostgreSQL, S3, RabbitMQ, OpenBao и telemetry backends.
|
||||
|
||||
Это **skeleton**, а не готовый сервер. Здесь есть задание, контракт и публичные проверки. Реализацию приложения, Dockerfile и требуемую инфраструктуру пишет студент. Язык и framework свободные; UI не обязателен.
|
||||
Стек запускается локально из этого репозитория. Приложение использует HTTPS, mTLS LB→API, scoped AppRole secrets и TLS с проверкой CA/hostname между сервисами.
|
||||
|
||||
[Карта курса](COURSE.md) · [Процесс fork/PR](CONTRIBUTING.md) · [OpenAPI](contracts/openapi.json) · [Семантика API](contracts/README.md) · [Проверки](tests/README.md) · [Отчёт](REPORT.md) · [Примеры JSON](contracts/examples.json) · [Памятка преподавателю](MAINTAINERS.md)
|
||||
|
||||
## Откуда начинаем
|
||||
## Архитектура
|
||||
|
||||
Перенесите минимум lab6. Бизнес-API сохраняется, внешний endpoint теперь HTTPS. Новые секреты и ключи создаются для стенда, не поставляются в skeleton.
|
||||
Бизнес-контракт предыдущих обязательных лабораторных сохранён; расширения для уровней оценивания 4/5 не входят в контракт. Новые секреты и ключи генерируются только локально и не поставляются в репозитории.
|
||||
|
||||
**Архитектура:** Клиент — TLS → LB — mTLS → API; API/worker — TLS (+ клиентские cert где требуется матрицей) → зависимости; OpenBao выдаёт scoped credentials. Grafana/OTel остаются внутри доверенной сети.
|
||||
|
||||
@@ -16,11 +16,11 @@
|
||||
|
||||
1. Составьте модель угроз и contracts/trust-matrix.md: активы, акторы, границы, протокол/идентичность каждой связи и проверяемые отказы.
|
||||
2. Переведите password storage на Argon2id, настройте сессии/лимиты и проведите негативные тесты ACL/вложений.
|
||||
3. Сделайте внешний TLS и обязательное внутреннее mTLS LB→API. Для остальных связей следуйте матрице: шифрование и отдельные identities; на 4 расширяется mTLS.
|
||||
3. Сделайте внешний TLS и обязательное внутреннее mTLS LB→API. Для остальных связей следуйте матрице: шифрование и отдельные identities.
|
||||
4. Добавьте OpenBao вне dev-mode: постоянное хранение, документированный init/unseal, политики и аутентификация сервисов с ограниченным TTL. Root token и unseal keys остаются у оператора.
|
||||
5. Уберите избыточные privileges/ports, задайте лимиты, проверьте certificates/secrets lifecycle. Повторите smoke, перезапуск и отказ реплики через HTTPS без отключения проверки сертификата.
|
||||
5. Уберите избыточные privileges/ports, задайте лимиты и проверьте, что secrets не попадают в Git, образы или telemetry. Повторите smoke, перезапуск и отказ реплики через HTTPS без отключения проверки сертификата.
|
||||
|
||||
## Оценка «3»: работающий минимум
|
||||
## Обязательные требования
|
||||
|
||||
- Все предыдущие обязательные возможности работают через HTTPS с проверяемым CA и hostname/SAN. Argon2id хранит salt и параметры; базовая конфигурация не ниже 19 MiB, t=2, p=1, итоговые параметры обоснованы измерением на своём стенде.
|
||||
- LB→каждая API-реплика использует обязательное mTLS: без client certificate, с чужим CA или неверной identity соединение отклоняется; прямого обхода публичным API-портом нет. Сервер проверяет не только цепочку CA, но и разрешённую identity (SAN/роль).
|
||||
@@ -29,46 +29,28 @@
|
||||
- Контейнеры без privileged/host network/Docker socket; app и worker — non-root, без лишних capabilities, с resource limits. Наружу доступны только нужный TLS ingress и локальные административные интерфейсы. Secret values/ключи не попадают в Git, образы или telemetry.
|
||||
- Есть ограничение частоты входа с 429/Retry-After, ограничение размера запросов, тесты доступа постороннего, logout/expiry и проверка недоверенного TLS. Публичный smoke по HTTPS проходит; сертификаты создаются локально через документированный bootstrap.
|
||||
|
||||
## Оценка «4»: уровень стажёра/джуна
|
||||
|
||||
Весь уровень 3 **и все** пункты ниже:
|
||||
|
||||
- mTLS дополнительно защищает API/worker→broker и API/worker→OTel Collector, с разными service identities. Доказано, что чужой, но подписанный тем же CA сертификат не даёт лишние права. Для нестандартного broker допускается sidecar с эквивалентной проверкой.
|
||||
- Пароли/сессионные token hashes и ошибки не раскрывают credentials; есть rehash старого password hash при успешном входе и измеренный бюджет защиты от дорогостоящего login DoS. Rate limit общий для реплик.
|
||||
- Показаны ротация одного рабочего secret и одного leaf certificate без пересборки образов, отзыв старой identity и ограниченное поведение при expiry/sealed OpenBao. Описаны bootstrap trust и renewal, в приложение не встроен постоянный секрет «для получения секретов».
|
||||
- Добавлены read_only/no-new-privileges/drop capabilities и отдельные tmpfs там, где это совместимо; исключения для stateful сервисов объяснены. Есть dependency/image scan с разбором применимости, а не только скриншот количества CVE.
|
||||
- Модель угроз связывает минимум 6 конкретных угроз с контролями и воспроизводимыми отрицательными тестами. Upload-worker ограничен по CPU/RAM/времени; TLS-аудит проверяет всю заявленную матрицу, ACL и отсутствие утечек в telemetry.
|
||||
|
||||
## Оценка «5»: исследование и доказанный результат
|
||||
|
||||
Весь уровень 4 **и один законченный трек на выбор**. Приведите гипотезу, повторяемую методику, результаты и ограничения.
|
||||
|
||||
**Трек 1. Компрометация worker.** На изолированном стенде смоделируйте получение прав worker: покажите, какие bucket-prefix, queue и DB-операции доступны, а какие запрещены. Отзовите identity, ротируйте связанный secret, восстановите обработку и докажите сохранность задач. Сопоставьте последствия до/после least privilege.
|
||||
|
||||
**Трек 2. Жизненный цикл PKI/secrets.** Автоматизируйте выдачу короткоживущих cert/credentials, renewal и безопасный rollover CA/leaf. Проведите тест истечения/отзыва под нагрузкой, измерьте ошибки и восстановление; покажите отсутствие fallback на plaintext/проверку сертификата off. Обоснуйте хранение CA, bootstrap и аудит.
|
||||
|
||||
## Как начать и проверить
|
||||
|
||||
```sh
|
||||
# Работает прямо в skeleton, Python 3.9+; приложение не запускается:
|
||||
make check
|
||||
|
||||
# После реализации запустите свой сервер/стенд по REPORT.md.
|
||||
# По умолчанию тест использует https://localhost:8443.
|
||||
# Docker Engine/Desktop с Compose v2, OpenSSL и Python 3
|
||||
make bootstrap
|
||||
make up
|
||||
make test
|
||||
make test-security
|
||||
```
|
||||
|
||||
`.env.example`, `compose.example.yaml` и `contracts/infrastructure.json` описывают настройки и роли компонентов. **compose.example.yaml — список ролей с пустым services, не запускаемый стенд.** Реализуйте свой `compose.yaml`/`stack.yaml`, закрепите версии образов, заполните локальный `.env` и опишите bootstrap/миграции. Все зависимости поднимаются из этого репозитория; ссылка «у меня БД уже установлена» не заменяет воспроизводимость.
|
||||
`make bootstrap` создаёт локальные CA/сертификаты и случайные секреты в игнорируемом Git каталоге `secrets/` и файле `.env`. Не публикуйте их и не используйте локальный CA вне учебного стенда. `make up` поднимает зависимости, создаёт scoped credentials в OpenBao и запускает API/worker; публичный адрес — `https://localhost:8443`. Путь к CA по умолчанию — `secrets/pki/ca.crt`.
|
||||
|
||||
```sh
|
||||
# Compose-вариант после реализации:
|
||||
docker compose --env-file .env config --quiet
|
||||
docker compose --env-file .env up -d --build
|
||||
# Дождитесь /health/ready; затем make test.
|
||||
# Для Swarm укажите эквивалентные build/push/deploy-команды в REPORT.md.
|
||||
make check
|
||||
make validate
|
||||
make down # останавливает сервисы, сохраняет volumes
|
||||
make logs # журналы текущего стенда
|
||||
```
|
||||
|
||||
Для HTTPS передайте публичный CA: `make test CA_FILE=/absolute/path/to/ca.crt`. CA certificate можно распространять; private keys создаются локально. `make test-security` проверяет только внешний TLS trust; внутренние отрицательные тесты реализуйте по [trust matrix](contracts/trust-matrix.md).
|
||||
`compose.yaml` и `Dockerfile` — запускаемая конфигурация. `compose.example.yaml` оставлен как учебная схема ролей, а не для запуска. Административные интерфейсы не опубликованы; ingress привязан только к loopback. `make down` не удаляет постоянные данные. Для нового чистого стенда используйте отдельное имя проекта/volume и удаляйте только осознанно выбранные данные вручную.
|
||||
|
||||
Для другого адреса CA задайте явно: `make test CA_FILE=/absolute/path/to/ca.crt`. `make test-security` проверяет доверенное HTTPS-соединение и отказ для недоверенного CA; внутреннее mTLS также проверяется при подключении к API без сертификата, с недоверенным CA и с неверной identity.
|
||||
|
||||
|
||||
Примеры запросов доступны в `examples/requests.http`, примеры JSON — в `contracts/examples.json`. Для полной проверки схемы (по желанию локально; CI делает её автоматически):
|
||||
@@ -79,21 +61,20 @@ python3 -m venv .venv
|
||||
make validate PYTHON=.venv/bin/python
|
||||
```
|
||||
|
||||
Smoke не выставляет оценку автоматически. Проверку сохранности/отказов запускайте явно по [tests/README.md](tests/README.md), остальные доказательства приведите в отчёте.
|
||||
Smoke проверяет публичный API-контракт. Проверки сохранности/отказов описаны в [tests/README.md](tests/README.md), измерения Argon2id и результаты проверок фиксируйте в отчёте.
|
||||
|
||||
## Сценарий защиты
|
||||
|
||||
1. Развернуть стенд по инструкции оператора, локально создать secrets/CA; выполнить make test BASE_URL=https://localhost:8443 CA_FILE=<путь-к-CA>.
|
||||
2. Запустить make test-security: внешний endpoint обязан отклонять недоверенный CA; затем авторизованный HTTPS smoke и тесты ACL/logout.
|
||||
3. Скрипт студента доказывает внутреннее mTLS: нет сертификата / чужой CA / неверная identity при доверенном CA → отказ; правильная identity → успех. TLS proxy без проверки client identity не засчитывается.
|
||||
2. Запустить make test-security: внешний endpoint обязан отклонять недоверенный CA; затем авторизованный HTTPS smoke и негативные проверки 429/Retry-After, размера запроса, ACL, logout и expiry.
|
||||
3. Проверьте внутреннее mTLS: нет сертификата / чужой CA / неверная identity при доверенном CA → отказ; правильная identity → успех. TLS proxy без проверки client identity не засчитывается.
|
||||
4. Показать OpenBao policy allow/deny, отсутствие root credential в app, перезапуск с сохранением данных и последовательный отказ API-реплик.
|
||||
5. Для 4: ротация/expiry и вся расширенная матрица; для 5: повторяемый сценарий компрометации или PKI lifecycle.
|
||||
|
||||
## Что должно быть в PR
|
||||
|
||||
Threat model, заполненная trust matrix, TLS/mTLS конфигурации, OpenBao policies и bootstrap/rotation scripts без secrets, scan triage и отрицательные тесты.
|
||||
Threat model, заполненная trust matrix, TLS/mTLS конфигурации, OpenBao policies, документированный локальный bootstrap сертификатов и отрицательные тесты. Секреты и приватные ключи не включать.
|
||||
|
||||
Заполните `REPORT.md` и [шаблон PR](.github/pull_request_template.md), укажите целевую оценку/трек. Не меняйте обязательный контракт и публичные tests ради зелёного результата. Сохраняйте возможности предыдущих лабораторных в пределах [объявленных переходов](COURSE.md).
|
||||
Заполните `REPORT.md` и [шаблон PR](.github/pull_request_template.md). Не меняйте обязательный контракт и публичные tests ради зелёного результата. Сохраняйте возможности предыдущих лабораторных в пределах [объявленных переходов](COURSE.md).
|
||||
|
||||
## Вопросы на защите
|
||||
|
||||
|
||||
@@ -1,10 +1,21 @@
|
||||
# Отчёт — лабораторная 7
|
||||
|
||||
- Автор, группа: TODO
|
||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
||||
- Commit/PR: TODO после публикации
|
||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
||||
|
||||
## Проверка обязательных требований
|
||||
|
||||
| Требование README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||
| --- | --- | --- | --- |
|
||||
| Argon2id и измерение параметров | TODO | TODO | TODO |
|
||||
| HTTPS и обязательное mTLS LB→API | TODO | TODO | TODO |
|
||||
| TLS для остальных связей и матрица identities/прав | TODO | TODO | TODO |
|
||||
| OpenBao, persistent storage и scoped policies | TODO | TODO | TODO |
|
||||
| Ограничения контейнеров, портов и ресурсов; отсутствие утечки secrets | TODO | TODO | TODO |
|
||||
| Rate limit, размер запроса, ACL, logout/expiry и недоверенный TLS | TODO | TODO | TODO |
|
||||
| Публичный smoke по HTTPS | make test | TODO | TODO |
|
||||
|
||||
## Запуск из чистого clone
|
||||
|
||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
||||
@@ -13,20 +24,9 @@ TODO: версии runtime/образов, prerequisites, команды соз
|
||||
|
||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab6, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
||||
|
||||
## Доказательства критериев
|
||||
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||
| --- | --- | --- | --- |
|
||||
| Публичный smoke | make test | TODO | TODO |
|
||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
||||
|
||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
||||
|
||||
## Эксперименты и отказы
|
||||
|
||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
||||
TODO: для измерения Argon2id укажите hardware/лимиты, версию библиотеки, выбранные параметры, длительность и повторы. Для проверок отказов укажите воздействие, ожидаемое и наблюдаемое поведение. Не сохраняйте tokens или секреты.
|
||||
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||
| --- | --- | --- | --- |
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
"""Messenger lab7 application package."""
|
||||
+808
@@ -0,0 +1,808 @@
|
||||
import asyncio
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import secrets
|
||||
import ssl
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import PurePosixPath
|
||||
|
||||
import asyncpg
|
||||
import boto3
|
||||
import pika
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import VerifyMismatchError
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.responses import JSONResponse, Response
|
||||
from PIL import Image
|
||||
|
||||
from .config import load_settings, env
|
||||
from .db import migrate, pg_ssl
|
||||
from .vault import login
|
||||
from .telemetry import configure
|
||||
|
||||
settings = load_settings("api")
|
||||
tracer = configure("messenger-api", settings.instance_id,
|
||||
settings.otlp_endpoint, settings.otlp_verify)
|
||||
vault = None
|
||||
|
||||
try:
|
||||
vault = login(settings, "api")
|
||||
vault_secrets = vault["secrets"]
|
||||
settings = settings.__class__(
|
||||
**{**settings.__dict__,
|
||||
"database_url": vault_secrets["database_url"],
|
||||
"broker_url": vault_secrets["broker_url"],
|
||||
"s3_access_key": vault_secrets["s3_access_key"],
|
||||
"s3_secret_key": vault_secrets["s3_secret_key"]}
|
||||
)
|
||||
except Exception as exc:
|
||||
if env("APP_ENV") == "lab" and env("ALLOW_INSECURE_LOCAL_DEV") == "1":
|
||||
raise
|
||||
raise
|
||||
|
||||
ph = PasswordHasher(
|
||||
memory_cost=settings.argon_memory,
|
||||
time_cost=settings.argon_iterations,
|
||||
parallelism=settings.argon_parallelism,
|
||||
)
|
||||
|
||||
app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)
|
||||
pool = None
|
||||
instances = {}
|
||||
rate_state = {}
|
||||
logger = logging.getLogger("messenger-api")
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def rate_limit_middleware(req: Request, call_next):
|
||||
if req.url.path.startswith("/health/"):
|
||||
return await call_next(req)
|
||||
now = time.monotonic()
|
||||
key = req.client.host if req.client else "unknown"
|
||||
bucket = rate_state.setdefault(key, [])
|
||||
bucket[:] = [stamp for stamp in bucket if now - stamp < 60]
|
||||
if len(bucket) >= 120:
|
||||
rid = request_id(req)
|
||||
return JSONResponse(
|
||||
{"error": {"code": "rate_limited", "message": "Слишком много запросов", "request_id": rid}},
|
||||
status_code=429,
|
||||
headers={"Retry-After": "60", "X-Request-Id": rid, "X-Instance-Id": settings.instance_id},
|
||||
)
|
||||
bucket.append(now)
|
||||
return await call_next(req)
|
||||
|
||||
|
||||
def utcnow():
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def rfc3339(value):
|
||||
if value.tzinfo is None:
|
||||
value = value.replace(tzinfo=timezone.utc)
|
||||
return value.astimezone(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")
|
||||
|
||||
|
||||
def error(code, message, status, request_id, headers=None):
|
||||
h = {"X-Request-Id": request_id}
|
||||
if headers:
|
||||
h.update(headers)
|
||||
return JSONResponse({"error": {"code": code, "message": message, "request_id": request_id}},
|
||||
status_code=status, headers=h)
|
||||
|
||||
|
||||
def request_id(req):
|
||||
return (
|
||||
getattr(req.state, "request_id", None)
|
||||
or req.headers.get("X-Request-Id")
|
||||
or uuid.uuid4().hex
|
||||
)
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def request_middleware(req: Request, call_next):
|
||||
rid = request_id(req)
|
||||
req.state.request_id = rid
|
||||
start = time.monotonic()
|
||||
try:
|
||||
response = await call_next(req)
|
||||
except Exception as exc:
|
||||
route_template = req.url.path
|
||||
route_template = re.sub(
|
||||
r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-"
|
||||
r"[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}",
|
||||
"{id}", route_template,
|
||||
)
|
||||
logger.error("request_failed_safe", extra={
|
||||
"event": "request_failed",
|
||||
"request_id": rid,
|
||||
"method": req.method,
|
||||
"route_template": route_template,
|
||||
"error_type": type(exc).__name__,
|
||||
})
|
||||
response = error("internal_error", "Внутренняя ошибка сервера", 500, rid)
|
||||
response.headers["X-Request-Id"] = rid
|
||||
response.headers["X-Instance-Id"] = settings.instance_id
|
||||
return response
|
||||
|
||||
|
||||
def bearer(req):
|
||||
auth = req.headers.get("Authorization", "")
|
||||
if not auth.lower().startswith("bearer ") or len(auth.strip()) <= 7:
|
||||
return None
|
||||
return auth.split(None, 1)[1].strip()
|
||||
|
||||
|
||||
async def auth_user(req):
|
||||
token = bearer(req)
|
||||
if not token:
|
||||
return None
|
||||
async with pool.acquire() as con:
|
||||
row = await con.fetchrow(
|
||||
"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=$1 AND s.expires_at>$2",
|
||||
token, utcnow(),
|
||||
)
|
||||
if not row:
|
||||
return None
|
||||
return row
|
||||
|
||||
|
||||
async def auth_or_error(req):
|
||||
user = await auth_user(req)
|
||||
rid = request_id(req)
|
||||
if not user:
|
||||
return None, error("unauthorized", "Требуется действительная сессия", 401, rid,
|
||||
{"WWW-Authenticate": 'Bearer realm="messenger"'})
|
||||
return user, None
|
||||
|
||||
|
||||
def user_json(row):
|
||||
return {"id": str(row["id"]), "username": row["username"], "display_name": row["display_name"],
|
||||
"created_at": rfc3339(row["created_at"])}
|
||||
|
||||
|
||||
def chat_json(row, member_ids):
|
||||
return {"id": str(row["id"]), "title": row["title"], "member_ids": [str(x) for x in member_ids],
|
||||
"created_at": rfc3339(row["created_at"])}
|
||||
|
||||
|
||||
def is_blank(value):
|
||||
return not isinstance(value, str) or not value.strip()
|
||||
|
||||
|
||||
def valid_uuid(value):
|
||||
try:
|
||||
return str(uuid.UUID(value))
|
||||
except (ValueError, AttributeError, TypeError):
|
||||
return None
|
||||
|
||||
|
||||
@app.on_event("startup")
|
||||
async def startup():
|
||||
global pool
|
||||
ca = env("PG_CACERT", env("TLS_CA_FILE"))
|
||||
ssl_context = pg_ssl(settings.database_url, ca)
|
||||
pool = await asyncpg.create_pool(settings.database_url, ssl=ssl_context, min_size=1, max_size=10)
|
||||
await migrate(pool)
|
||||
|
||||
|
||||
@app.on_event("shutdown")
|
||||
async def shutdown():
|
||||
if pool:
|
||||
await pool.close()
|
||||
|
||||
|
||||
@app.get("/health/live")
|
||||
async def live(request: Request):
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@app.get("/health/ready")
|
||||
async def ready(request: Request):
|
||||
rid = request_id(request)
|
||||
try:
|
||||
async with pool.acquire() as con:
|
||||
await con.fetchval("SELECT 1")
|
||||
await asyncio.to_thread(s3_client().head_bucket, Bucket=settings.s3_bucket)
|
||||
await asyncio.to_thread(check_broker)
|
||||
return {"status": "ok"}
|
||||
except Exception:
|
||||
return error("unavailable", "Сервис временно недоступен", 503, rid)
|
||||
|
||||
|
||||
@app.post("/api/v1/users")
|
||||
async def create_user(request: Request):
|
||||
rid = request_id(request)
|
||||
try:
|
||||
body = await request.json()
|
||||
except Exception:
|
||||
return error("invalid_request", "Некорректный JSON", 400, rid)
|
||||
if not isinstance(body, dict) or set(body) != {"username", "display_name", "password"}:
|
||||
return error("invalid_request", "Неверные поля запроса", 400, rid)
|
||||
username = body["username"]
|
||||
display = body["display_name"]
|
||||
password = body["password"]
|
||||
if not isinstance(username, str) or not re.fullmatch(r"[a-z0-9_]{3,32}", username):
|
||||
return error("invalid_request", "Неверное имя пользователя", 400, rid)
|
||||
if not isinstance(display, str) or is_blank(display) or len(display) > 100:
|
||||
return error("invalid_request", "Неверное отображаемое имя", 400, rid)
|
||||
if not isinstance(password, str) or not 12 <= len(password) <= 128:
|
||||
return error("invalid_request", "Неверный пароль", 400, rid)
|
||||
password_hash = ph.hash(password)
|
||||
uid = uuid.uuid4()
|
||||
now = utcnow()
|
||||
try:
|
||||
async with pool.acquire() as con:
|
||||
row = await con.fetchrow(
|
||||
"INSERT INTO users(id,username,display_name,password_hash,created_at) "
|
||||
"VALUES($1,$2,$3,$4,$5) RETURNING id,username,display_name,created_at",
|
||||
uid, username, display, password_hash, now,
|
||||
)
|
||||
except asyncpg.UniqueViolationError:
|
||||
return error("conflict", "Имя пользователя уже занято", 409, rid)
|
||||
return JSONResponse(user_json(row), status_code=201)
|
||||
|
||||
|
||||
@app.post("/api/v1/auth/sessions")
|
||||
async def login_session(request: Request):
|
||||
rid = request_id(request)
|
||||
if await request.body():
|
||||
return error("invalid_request", "Basic аутентификация не принимает JSON body", 400, rid)
|
||||
auth = request.headers.get("Authorization", "")
|
||||
if not auth.startswith("Basic ") or len(auth) == 6:
|
||||
return error("unauthorized", "Неверные учетные данные", 401, rid,
|
||||
{"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'})
|
||||
try:
|
||||
raw = base64.b64decode(auth[6:].strip(), validate=True).decode("utf-8")
|
||||
username, password = raw.split(":", 1)
|
||||
except Exception:
|
||||
return error("unauthorized", "Неверные учетные данные", 401, rid,
|
||||
{"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'})
|
||||
if not re.fullmatch(r"[a-z0-9_]{3,32}", username) or not 12 <= len(password) <= 128:
|
||||
return error("unauthorized", "Неверные учетные данные", 401, rid,
|
||||
{"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'})
|
||||
async with pool.acquire() as con:
|
||||
row = await con.fetchrow("SELECT id,username,display_name,created_at,password_hash FROM users WHERE username=$1", username)
|
||||
if not row:
|
||||
return error("unauthorized", "Неверные учетные данные", 401, rid,
|
||||
{"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'})
|
||||
try:
|
||||
ph.verify(row["password_hash"], password)
|
||||
except VerifyMismatchError:
|
||||
return error("unauthorized", "Неверные учетные данные", 401, rid,
|
||||
{"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'})
|
||||
token = secrets.token_urlsafe(32)
|
||||
expires = utcnow() + timedelta(seconds=settings.session_ttl)
|
||||
async with pool.acquire() as con:
|
||||
await con.execute("INSERT INTO sessions(token,user_id,expires_at) VALUES($1,$2,$3)",
|
||||
token, row["id"], expires)
|
||||
return JSONResponse({"token": token, "token_type": "Bearer", "expires_at": rfc3339(expires),
|
||||
"user": user_json(row)}, status_code=201)
|
||||
|
||||
|
||||
@app.delete("/api/v1/auth/sessions/current")
|
||||
async def logout(request: Request):
|
||||
rid = request_id(request)
|
||||
user, denied = await auth_or_error(request)
|
||||
if denied:
|
||||
return denied
|
||||
token = bearer(request)
|
||||
async with pool.acquire() as con:
|
||||
deleted = await con.fetchval("DELETE FROM sessions WHERE token=$1 AND expires_at>$2 RETURNING token",
|
||||
token, utcnow())
|
||||
if not deleted:
|
||||
return error("unauthorized", "Сессия недействительна", 401, rid,
|
||||
{"WWW-Authenticate": 'Bearer realm="messenger"'})
|
||||
return Response(status_code=204)
|
||||
|
||||
|
||||
@app.get("/api/v1/users/me")
|
||||
async def users_me(request: Request):
|
||||
rid = request_id(request)
|
||||
user, denied = await auth_or_error(request)
|
||||
if denied:
|
||||
return denied
|
||||
return user_json(user)
|
||||
|
||||
|
||||
async def member_check(con, chat_id, user_id):
|
||||
return await con.fetchval(
|
||||
"SELECT 1 FROM chat_members WHERE chat_id=$1 AND user_id=$2",
|
||||
chat_id, user_id,
|
||||
)
|
||||
|
||||
|
||||
@app.post("/api/v1/chats")
|
||||
async def create_chat(request: Request):
|
||||
rid = request_id(request)
|
||||
user, denied = await auth_or_error(request)
|
||||
if denied:
|
||||
return denied
|
||||
try:
|
||||
body = await request.json()
|
||||
except Exception:
|
||||
return error("invalid_request", "Некорректный JSON", 400, rid)
|
||||
if not isinstance(body, dict) or set(body) != {"title", "member_ids"}:
|
||||
return error("invalid_request", "Неверные поля запроса", 400, rid)
|
||||
title = body["title"]
|
||||
ids = body["member_ids"]
|
||||
if not isinstance(title, str) or is_blank(title) or len(title) > 100:
|
||||
return error("invalid_request", "Неверный title", 400, rid)
|
||||
if not isinstance(ids, list) or not 1 <= len(ids) <= 100:
|
||||
return error("invalid_request", "Неверный member_ids", 400, rid)
|
||||
normalized = []
|
||||
for value in ids:
|
||||
uid = valid_uuid(value) if isinstance(value, str) else None
|
||||
if not uid:
|
||||
return error("invalid_request", "Неверный UUID участника", 400, rid)
|
||||
normalized.append(uuid.UUID(uid))
|
||||
if len(set(normalized)) != len(normalized):
|
||||
return error("invalid_request", "Дубликаты участников", 400, rid)
|
||||
if user["id"] not in normalized:
|
||||
return error("invalid_request", "Создатель должен быть участником", 400, rid)
|
||||
cid = uuid.uuid4()
|
||||
now = utcnow()
|
||||
async with pool.acquire() as con:
|
||||
async with con.transaction():
|
||||
found = await con.fetchval("SELECT COUNT(*) FROM users WHERE id=ANY($1::uuid[])", normalized)
|
||||
if found != len(normalized):
|
||||
return error("invalid_request", "Неизвестный участник", 400, rid)
|
||||
row = await con.fetchrow(
|
||||
"INSERT INTO chats(id,title,created_at) VALUES($1,$2,$3) "
|
||||
"RETURNING id,title,created_at", cid, title, now,
|
||||
)
|
||||
await con.executemany(
|
||||
"INSERT INTO chat_members(chat_id,user_id) VALUES($1,$2)",
|
||||
[(cid, uid) for uid in normalized],
|
||||
)
|
||||
return JSONResponse(chat_json(row, normalized), status_code=201)
|
||||
|
||||
|
||||
@app.get("/api/v1/chats")
|
||||
async def list_chats(request: Request):
|
||||
rid = request_id(request)
|
||||
user, denied = await auth_or_error(request)
|
||||
if denied:
|
||||
return denied
|
||||
try:
|
||||
limit = int(request.query_params.get("limit", "50"))
|
||||
except (ValueError, TypeError):
|
||||
return error("invalid_request", "Неверный limit", 400, rid)
|
||||
if not 1 <= limit <= 100:
|
||||
return error("invalid_request", "Неверный limit", 400, rid)
|
||||
async with pool.acquire() as con:
|
||||
rows = await con.fetch(
|
||||
"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=$1 "
|
||||
"ORDER BY c.created_at,c.id LIMIT $2",
|
||||
user["id"], limit,
|
||||
)
|
||||
items = []
|
||||
for row in rows:
|
||||
member_rows = await con.fetch("SELECT user_id FROM chat_members WHERE chat_id=$1 ORDER BY user_id", row["id"])
|
||||
items.append(chat_json(row, [x["user_id"] for x in member_rows]))
|
||||
return {"items": items, "next_cursor": None}
|
||||
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}")
|
||||
async def get_chat(chat_id: str, request: Request):
|
||||
rid = request_id(request)
|
||||
user, denied = await auth_or_error(request)
|
||||
if denied:
|
||||
return denied
|
||||
cid = valid_uuid(chat_id)
|
||||
if not cid:
|
||||
return error("invalid_request", "Неверный UUID чата", 400, rid)
|
||||
async with pool.acquire() as con:
|
||||
if not await member_check(con, uuid.UUID(cid), user["id"]):
|
||||
return error("not_found", "Объект не найден", 404, rid)
|
||||
row = await con.fetchrow("SELECT id,title,created_at FROM chats WHERE id=$1", uuid.UUID(cid))
|
||||
member_rows = await con.fetch("SELECT user_id FROM chat_members WHERE chat_id=$1 ORDER BY user_id", uuid.UUID(cid))
|
||||
return chat_json(row, [x["user_id"] for x in member_rows])
|
||||
|
||||
|
||||
def encode_cursor(chat_id, created, message_id):
|
||||
timestamp = (
|
||||
created.astimezone(timezone.utc)
|
||||
.isoformat(timespec="microseconds")
|
||||
.replace("+00:00", "Z")
|
||||
)
|
||||
payload = json.dumps(
|
||||
{"chat": chat_id, "t": timestamp, "id": message_id},
|
||||
separators=(",", ":"),
|
||||
).encode()
|
||||
return base64.urlsafe_b64encode(payload).decode().rstrip("=")
|
||||
|
||||
|
||||
def decode_cursor(cursor, chat_id):
|
||||
try:
|
||||
padding = "=" * (-len(cursor) % 4)
|
||||
payload = json.loads(base64.urlsafe_b64decode(cursor + padding))
|
||||
if payload.get("chat") != chat_id or set(payload) != {"chat", "t", "id"}:
|
||||
return None
|
||||
timestamp = datetime.fromisoformat(payload["t"].replace("Z", "+00:00"))
|
||||
mid = valid_uuid(payload["id"])
|
||||
if not mid:
|
||||
return None
|
||||
return timestamp, uuid.UUID(mid)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}/messages")
|
||||
async def history(chat_id: str, request: Request):
|
||||
rid = request_id(request)
|
||||
user, denied = await auth_or_error(request)
|
||||
if denied:
|
||||
return denied
|
||||
cid = valid_uuid(chat_id)
|
||||
if not cid:
|
||||
return error("invalid_request", "Неверный UUID чата", 400, rid)
|
||||
try:
|
||||
limit = int(request.query_params.get("limit", "50"))
|
||||
except (ValueError, TypeError):
|
||||
return error("invalid_request", "Неверный limit", 400, rid)
|
||||
if not 1 <= limit <= 100:
|
||||
return error("invalid_request", "Неверный limit", 400, rid)
|
||||
cursor = request.query_params.get("cursor")
|
||||
after = decode_cursor(cursor, cid) if cursor else None
|
||||
if cursor and after is None:
|
||||
return error("invalid_request", "Неверный cursor", 400, rid)
|
||||
async with pool.acquire() as con:
|
||||
if not await member_check(con, uuid.UUID(cid), user["id"]):
|
||||
return error("not_found", "Объект не найден", 404, rid)
|
||||
if after:
|
||||
rows = await con.fetch(
|
||||
"SELECT * FROM messages WHERE chat_id=$1 "
|
||||
"AND (created_at,id) > ($2,$3) "
|
||||
"ORDER BY created_at,id LIMIT $4",
|
||||
uuid.UUID(cid), after[0], after[1], limit + 1,
|
||||
)
|
||||
else:
|
||||
rows = await con.fetch(
|
||||
"SELECT * FROM messages WHERE chat_id=$1 "
|
||||
"ORDER BY created_at,id LIMIT $2",
|
||||
uuid.UUID(cid), limit + 1,
|
||||
)
|
||||
items = []
|
||||
for row in rows[:limit]:
|
||||
aids = await con.fetch(
|
||||
"SELECT attachment_id FROM message_attachments WHERE message_id=$1 ORDER BY attachment_id",
|
||||
row["id"],
|
||||
)
|
||||
items.append({
|
||||
"id": str(row["id"]), "chat_id": str(row["chat_id"]),
|
||||
"sender_id": str(row["sender_id"]), "text": row["text"],
|
||||
"created_at": rfc3339(row["created_at"]),
|
||||
"attachment_ids": [str(x["attachment_id"]) for x in aids],
|
||||
})
|
||||
next_cursor = None
|
||||
if len(rows) > limit:
|
||||
last = rows[limit - 1]
|
||||
next_cursor = encode_cursor(cid, last["created_at"], str(last["id"]))
|
||||
return {"items": items, "next_cursor": next_cursor}
|
||||
|
||||
|
||||
def canonical_body(body):
|
||||
text = body.get("text")
|
||||
attachments = body.get("attachment_ids", [])
|
||||
return {"text": text, "attachment_ids": sorted(attachments)}
|
||||
|
||||
|
||||
def s3_client():
|
||||
return boto3.client(
|
||||
"s3",
|
||||
endpoint_url=settings.s3_endpoint,
|
||||
region_name=settings.s3_region,
|
||||
aws_access_key_id=settings.s3_access_key,
|
||||
aws_secret_access_key=settings.s3_secret_key,
|
||||
verify=settings.s3_verify,
|
||||
)
|
||||
|
||||
|
||||
def check_broker():
|
||||
params = pika.URLParameters(settings.broker_url)
|
||||
if settings.broker_url.startswith("amqps://"):
|
||||
ssl_context = ssl.create_default_context(cafile=settings.broker_verify)
|
||||
ssl_context.check_hostname = True
|
||||
ssl_context.verify_mode = ssl.CERT_REQUIRED
|
||||
params.ssl_options = pika.SSLOptions(ssl_context)
|
||||
connection = pika.BlockingConnection(params)
|
||||
connection.close()
|
||||
|
||||
|
||||
def publish_job(payload):
|
||||
params = pika.URLParameters(settings.broker_url)
|
||||
if settings.broker_url.startswith("amqps://"):
|
||||
ssl_context = ssl.create_default_context(cafile=settings.broker_verify)
|
||||
ssl_context.check_hostname = True
|
||||
ssl_context.verify_mode = ssl.CERT_REQUIRED
|
||||
params.ssl_options = pika.SSLOptions(ssl_context)
|
||||
connection = pika.BlockingConnection(params)
|
||||
channel = connection.channel()
|
||||
channel.queue_declare(queue="attachment.jobs", durable=True)
|
||||
channel.confirm_delivery()
|
||||
channel.basic_publish(
|
||||
exchange="", routing_key="attachment.jobs",
|
||||
body=json.dumps(payload, separators=(",", ":")).encode("utf-8"),
|
||||
properties=pika.BasicProperties(delivery_mode=2),
|
||||
mandatory=True,
|
||||
)
|
||||
connection.close()
|
||||
|
||||
|
||||
@app.post("/api/v1/chats/{chat_id}/messages")
|
||||
async def create_message(chat_id: str, request: Request):
|
||||
rid = request_id(request)
|
||||
user, denied = await auth_or_error(request)
|
||||
if denied:
|
||||
return denied
|
||||
cid = valid_uuid(chat_id)
|
||||
if not cid:
|
||||
return error("invalid_request", "Неверный UUID чата", 400, rid)
|
||||
key = request.headers.get("Idempotency-Key")
|
||||
if not key or not re.fullmatch(r"[A-Za-z0-9._:-]{1,128}", key):
|
||||
return error("invalid_request", "Неверный Idempotency-Key", 400, rid)
|
||||
try:
|
||||
body = await request.json()
|
||||
except Exception:
|
||||
return error("invalid_request", "Некорректный JSON", 400, rid)
|
||||
if not isinstance(body, dict) or set(body) - {"text", "attachment_ids"}:
|
||||
return error("invalid_request", "Неверные поля запроса", 400, rid)
|
||||
if set(body) == set() or "text" not in body or not isinstance(body["text"], str):
|
||||
return error("invalid_request", "Неверный текст сообщения", 400, rid)
|
||||
text = body["text"]
|
||||
aids = body.get("attachment_ids", [])
|
||||
if not isinstance(aids, list) or len(aids) > 10 or len(set(aids)) != len(aids):
|
||||
return error("invalid_request", "Неверный attachment_ids", 400, rid)
|
||||
normalized_aids = []
|
||||
for value in aids:
|
||||
aid = valid_uuid(value) if isinstance(value, str) else None
|
||||
if not aid:
|
||||
return error("invalid_request", "Неверный UUID вложения", 400, rid)
|
||||
normalized_aids.append(uuid.UUID(aid))
|
||||
if len(text) > 4000:
|
||||
return error("invalid_request", "Текст сообщения слишком длинный", 400, rid)
|
||||
if is_blank(text) and not normalized_aids:
|
||||
return error("invalid_request", "Пустое сообщение", 400, rid)
|
||||
canonical = canonical_body({"text": text, "attachment_ids": [str(x) for x in normalized_aids]})
|
||||
body_hash = hashlib.sha256(json.dumps(canonical, ensure_ascii=False, sort_keys=True).encode()).hexdigest()
|
||||
path = "/api/v1/chats/" + cid + "/messages"
|
||||
|
||||
async with pool.acquire() as con:
|
||||
if not await member_check(con, uuid.UUID(cid), user["id"]):
|
||||
return error("not_found", "Объект не найден", 404, rid)
|
||||
async with con.transaction():
|
||||
await con.fetchval(
|
||||
"SELECT pg_advisory_xact_lock(hashtext($1), hashtext($2))",
|
||||
str(user["id"]), cid + ":" + key,
|
||||
)
|
||||
prior = await con.fetchrow(
|
||||
"SELECT body_hash,response_json FROM idempotency "
|
||||
"WHERE user_id=$1 AND method='POST' AND path=$2 AND key=$3 "
|
||||
"AND created_at>$4",
|
||||
user["id"], path, key, utcnow() - timedelta(hours=24),
|
||||
)
|
||||
if prior:
|
||||
if prior["body_hash"] != body_hash:
|
||||
return error("conflict", "Ключ используется для другого сообщения", 409, rid)
|
||||
return JSONResponse(
|
||||
json.loads(prior["response_json"]),
|
||||
status_code=201,
|
||||
)
|
||||
|
||||
for aid in normalized_aids:
|
||||
att = await con.fetchrow(
|
||||
"SELECT chat_id,status FROM attachments WHERE id=$1", aid,
|
||||
)
|
||||
if not att or att["chat_id"] != uuid.UUID(cid):
|
||||
return error("not_found", "Вложение не найдено", 404, rid)
|
||||
if att["status"] == "failed":
|
||||
return error("conflict", "Вложение ещё или не готово", 409, rid)
|
||||
|
||||
mid = uuid.uuid4()
|
||||
now = utcnow()
|
||||
now = now.replace(microsecond=(now.microsecond // 1000) * 1000)
|
||||
row = await con.fetchrow(
|
||||
"INSERT INTO messages(id,chat_id,sender_id,text,created_at) "
|
||||
"VALUES($1,$2,$3,$4,$5) RETURNING id,chat_id,sender_id,text,created_at",
|
||||
mid, uuid.UUID(cid), user["id"], text, now,
|
||||
)
|
||||
await con.executemany(
|
||||
"INSERT INTO message_attachments(message_id,attachment_id) VALUES($1,$2)",
|
||||
[(mid, aid) for aid in normalized_aids],
|
||||
)
|
||||
response_data = {
|
||||
"id": str(row["id"]), "chat_id": str(row["chat_id"]),
|
||||
"sender_id": str(row["sender_id"]), "text": row["text"],
|
||||
"created_at": rfc3339(row["created_at"]),
|
||||
"attachment_ids": [str(x) for x in normalized_aids],
|
||||
}
|
||||
inserted = await con.fetchval(
|
||||
"INSERT INTO idempotency(user_id,method,path,key,body_hash,status,response_json,created_at) "
|
||||
"VALUES($1,'POST',$2,$3,$4,201,$5,$6) "
|
||||
"ON CONFLICT(user_id,method,path,key) DO NOTHING RETURNING key",
|
||||
user["id"], path, key, body_hash, json.dumps(response_data), now,
|
||||
)
|
||||
if not inserted:
|
||||
prior = await con.fetchrow(
|
||||
"SELECT body_hash,response_json FROM idempotency "
|
||||
"WHERE user_id=$1 AND method='POST' AND path=$2 AND key=$3",
|
||||
user["id"], path, key,
|
||||
)
|
||||
if prior and prior["body_hash"] == body_hash:
|
||||
return JSONResponse(prior["response_json"], status_code=201)
|
||||
message = {
|
||||
"id": str(row["id"]), "chat_id": str(row["chat_id"]),
|
||||
"sender_id": str(row["sender_id"]), "text": row["text"],
|
||||
"created_at": rfc3339(row["created_at"]),
|
||||
"attachment_ids": [str(x) for x in normalized_aids],
|
||||
}
|
||||
return JSONResponse(message, status_code=201)
|
||||
|
||||
|
||||
@app.post("/api/v1/chats/{chat_id}/attachments")
|
||||
async def upload_attachment(chat_id: str, request: Request):
|
||||
rid = request_id(request)
|
||||
user, denied = await auth_or_error(request)
|
||||
if denied:
|
||||
return denied
|
||||
cid = valid_uuid(chat_id)
|
||||
if not cid:
|
||||
return error("invalid_request", "Неверный UUID чата", 400, rid)
|
||||
filename = request.query_params.get("filename")
|
||||
if not filename or len(filename) > 255 or is_blank(filename):
|
||||
return error("invalid_request", "Неверное имя файла", 400, rid)
|
||||
if any(ch in filename for ch in ('/', '\\', '\x00')) or any(ord(ch) < 32 for ch in filename):
|
||||
return error("invalid_request", "Недопустимое имя файла", 400, rid)
|
||||
media_type = request.headers.get("Content-Type", "").split(";", 1)[0].strip().lower()
|
||||
if media_type not in ("image/png", "image/jpeg"):
|
||||
return error("unsupported_media_type", "Допустимые форматы — PNG или JPEG", 415, rid)
|
||||
data = await request.body()
|
||||
if len(data) > settings.max_upload:
|
||||
return error("payload_too_large", "Файл превышает допустимый размер", 413, rid)
|
||||
if len(data) == 0:
|
||||
return error("unsupported_media_type", "Повреждённое изображение", 415, rid)
|
||||
try:
|
||||
from io import BytesIO
|
||||
with Image.open(BytesIO(data)) as image:
|
||||
image.verify()
|
||||
with Image.open(BytesIO(data)) as image:
|
||||
image_format = image.format
|
||||
width, height = image.size
|
||||
if width * height > settings.max_pixels:
|
||||
return error("payload_too_large", "Изображение содержит слишком много пикселей", 413, rid)
|
||||
except Exception:
|
||||
return error("unsupported_media_type", "Повреждённое или неподдерживаемое изображение", 415, rid)
|
||||
detected = "image/png" if image_format == "PNG" else "image/jpeg" if image_format == "JPEG" else None
|
||||
if detected != media_type:
|
||||
return error("unsupported_media_type", "Содержимое не соответствует MIME типу", 415, rid)
|
||||
|
||||
async with pool.acquire() as con:
|
||||
if not await member_check(con, uuid.UUID(cid), user["id"]):
|
||||
return error("not_found", "Объект не найден", 404, rid)
|
||||
|
||||
aid = uuid.uuid4()
|
||||
sha = hashlib.sha256(data).hexdigest()
|
||||
staging_key = f"staging/{aid}/{sha}"
|
||||
now = utcnow()
|
||||
try:
|
||||
await asyncio.to_thread(
|
||||
s3_client().put_object,
|
||||
Bucket=settings.s3_bucket,
|
||||
Key=staging_key,
|
||||
Body=data,
|
||||
ContentType=detected,
|
||||
)
|
||||
async with pool.acquire() as con:
|
||||
await con.execute(
|
||||
"INSERT INTO attachments(id,chat_id,owner_id,filename,content_type,size_bytes,"
|
||||
"sha256,staging_key,status,created_at,updated_at) "
|
||||
"VALUES($1,$2,$3,$4,$5,$6,$7,$8,'queued',$9,$9)",
|
||||
aid, uuid.UUID(cid), user["id"], filename, detected, len(data),
|
||||
sha, staging_key, now,
|
||||
)
|
||||
job = {
|
||||
"schema_version": 1,
|
||||
"job_id": str(uuid.uuid4()),
|
||||
"type": "attachment.process.v1",
|
||||
"attachment_id": str(aid),
|
||||
"pipeline_version": 1,
|
||||
"attempt": 1,
|
||||
"created_at": rfc3339(now),
|
||||
}
|
||||
await asyncio.to_thread(publish_job, job)
|
||||
except Exception:
|
||||
return error("unavailable", "Хранилище временно недоступно", 503, rid)
|
||||
|
||||
return JSONResponse({
|
||||
"id": str(aid), "chat_id": cid, "owner_id": str(user["id"]),
|
||||
"filename": filename, "content_type": detected, "size_bytes": len(data),
|
||||
"sha256": sha, "status": "queued", "variants": [], "error_code": None,
|
||||
"created_at": rfc3339(now), "updated_at": rfc3339(now),
|
||||
}, status_code=202)
|
||||
|
||||
|
||||
async def attachment_row(req, aid):
|
||||
user, denied = await auth_or_error(req)
|
||||
if denied:
|
||||
return None, denied
|
||||
rid = request_id(req)
|
||||
async with pool.acquire() as con:
|
||||
row = await con.fetchrow("SELECT * FROM attachments WHERE id=$1", aid)
|
||||
if not row:
|
||||
return None, error("not_found", "Объект не найден", 404, rid)
|
||||
if not await member_check(con, row["chat_id"], user["id"]):
|
||||
return None, error("not_found", "Объект не найден", 404, rid)
|
||||
return row, None
|
||||
|
||||
|
||||
def attachment_json(row, variants):
|
||||
return {
|
||||
"id": str(row["id"]), "chat_id": str(row["chat_id"]), "owner_id": str(row["owner_id"]),
|
||||
"filename": row["filename"], "content_type": row["content_type"],
|
||||
"size_bytes": row["size_bytes"], "sha256": row["sha256"],
|
||||
"status": row["status"], "variants": variants, "error_code": row["error_code"],
|
||||
"created_at": rfc3339(row["created_at"]), "updated_at": rfc3339(row["updated_at"]),
|
||||
}
|
||||
|
||||
|
||||
@app.get("/api/v1/attachments/{attachment_id}")
|
||||
async def get_attachment(attachment_id: str, request: Request):
|
||||
rid = request_id(request)
|
||||
aid = valid_uuid(attachment_id)
|
||||
if not aid:
|
||||
return error("invalid_request", "Неверный UUID вложения", 400, rid)
|
||||
row, denied = await attachment_row(request, uuid.UUID(aid))
|
||||
if denied:
|
||||
return denied
|
||||
async with pool.acquire() as con:
|
||||
variant_rows = await con.fetch(
|
||||
"SELECT name,content_type,size_bytes,width,height,sha256 "
|
||||
"FROM attachment_variants WHERE attachment_id=$1 ORDER BY name", row["id"],
|
||||
)
|
||||
variants = [dict(v) for v in variant_rows]
|
||||
return attachment_json(row, variants)
|
||||
|
||||
|
||||
@app.get("/api/v1/attachments/{attachment_id}/content")
|
||||
async def attachment_content(attachment_id: str, request: Request):
|
||||
rid = request_id(request)
|
||||
aid = valid_uuid(attachment_id)
|
||||
if not aid:
|
||||
return error("invalid_request", "Неверный UUID вложения", 400, rid)
|
||||
row, denied = await attachment_row(request, uuid.UUID(aid))
|
||||
if denied:
|
||||
return denied
|
||||
variant = request.query_params.get("variant", "original")
|
||||
if row["status"] in ("queued", "processing"):
|
||||
return error("conflict", "Вложение ещё не готово", 409, rid)
|
||||
if row["status"] == "failed":
|
||||
return error("conflict", "Вложение обработано с ошибкой", 409, rid)
|
||||
try:
|
||||
if variant == "original":
|
||||
key = row["final_key"] or row["staging_key"]
|
||||
content_type = row["content_type"]
|
||||
else:
|
||||
if variant != "thumbnail":
|
||||
return error("not_found", "Вариант не найден", 404, rid)
|
||||
async with pool.acquire() as con:
|
||||
v = await con.fetchrow(
|
||||
"SELECT object_key,content_type FROM attachment_variants "
|
||||
"WHERE attachment_id=$1 AND name='thumbnail'", row["id"],
|
||||
)
|
||||
if not v:
|
||||
return error("not_found", "Вариант не найден", 404, rid)
|
||||
key = v["object_key"]
|
||||
content_type = v["content_type"]
|
||||
obj = await asyncio.to_thread(s3_client().get_object, Bucket=settings.s3_bucket, Key=key)
|
||||
data = await asyncio.to_thread(obj["Body"].read)
|
||||
except Exception:
|
||||
return error("unavailable", "Хранилище временно недоступно", 503, rid)
|
||||
return Response(content=data, media_type=content_type,
|
||||
headers={"Content-Length": str(len(data))})
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
import os
|
||||
import secrets
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
|
||||
def env(name: str, default: Optional[str] = None, required: bool = False) -> Optional[str]:
|
||||
value = os.getenv(name, default)
|
||||
if required and not value:
|
||||
raise RuntimeError(f"required environment variable {name} is not set")
|
||||
return value
|
||||
|
||||
|
||||
def secret_file(name: str) -> str:
|
||||
path = env(name, required=True)
|
||||
try:
|
||||
return Path(path).read_text(encoding="utf-8").strip()
|
||||
except OSError as exc:
|
||||
raise RuntimeError(f"unable to read secret file {name}") from exc
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Settings:
|
||||
database_url: str
|
||||
session_ttl: int
|
||||
idempotency_ttl: int
|
||||
s3_endpoint: str
|
||||
s3_region: str
|
||||
s3_bucket: str
|
||||
s3_access_key: str
|
||||
s3_secret_key: str
|
||||
s3_verify: str
|
||||
broker_url: str
|
||||
broker_verify: str
|
||||
bao_addr: str
|
||||
bao_cacert: str
|
||||
bao_role_id: str
|
||||
bao_secret_id: str
|
||||
bao_api_secret_path: str
|
||||
bao_worker_secret_path: str
|
||||
tls_cert: str
|
||||
tls_key: str
|
||||
tls_ca: str
|
||||
tls_client_sans: tuple[str, ...]
|
||||
argon_memory: int
|
||||
argon_iterations: int
|
||||
argon_parallelism: int
|
||||
otlp_endpoint: Optional[str]
|
||||
otlp_verify: Optional[str]
|
||||
max_upload: int
|
||||
max_pixels: int
|
||||
job_attempts: int
|
||||
job_timeout: int
|
||||
instance_id: str
|
||||
|
||||
|
||||
def load_settings(role: str) -> Settings:
|
||||
if role not in ("api", "worker"):
|
||||
raise RuntimeError("role must be api or worker")
|
||||
|
||||
argon_memory = int(env("ARGON2_MEMORY_KIB", "19456"))
|
||||
argon_iterations = int(env("ARGON2_ITERATIONS", "2"))
|
||||
argon_parallelism = int(env("ARGON2_PARALLELISM", "1"))
|
||||
if argon_memory < 19456 or argon_iterations < 2 or argon_parallelism < 1:
|
||||
raise RuntimeError("Argon2id parameters are below the mandatory minimum")
|
||||
|
||||
database_url = env("DATABASE_URL")
|
||||
if not database_url and env("DATABASE_URL_FILE"):
|
||||
database_url = secret_file("DATABASE_URL_FILE")
|
||||
broker_url = env("BROKER_URL")
|
||||
if not broker_url and env("BROKER_URL_FILE"):
|
||||
broker_url = secret_file("BROKER_URL_FILE")
|
||||
|
||||
s3_access = env("S3_ACCESS_KEY_ID")
|
||||
if not s3_access and env("S3_ACCESS_KEY_ID_FILE"):
|
||||
s3_access = secret_file("S3_ACCESS_KEY_ID_FILE")
|
||||
s3_secret = env("S3_SECRET_ACCESS_KEY")
|
||||
if not s3_secret and env("S3_SECRET_ACCESS_KEY_FILE"):
|
||||
s3_secret = secret_file("S3_SECRET_ACCESS_KEY_FILE")
|
||||
|
||||
if role == "api":
|
||||
bao_role = env("BAO_API_ROLE_ID") or (
|
||||
secret_file("BAO_API_ROLE_ID_FILE") if env("BAO_API_ROLE_ID_FILE") else ""
|
||||
)
|
||||
bao_secret = env("BAO_API_SECRET_ID") or (
|
||||
secret_file("BAO_API_SECRET_ID_FILE") if env("BAO_API_SECRET_ID_FILE") else ""
|
||||
)
|
||||
else:
|
||||
bao_role = env("BAO_WORKER_ROLE_ID") or (
|
||||
secret_file("BAO_WORKER_ROLE_ID_FILE") if env("BAO_WORKER_ROLE_ID_FILE") else ""
|
||||
)
|
||||
bao_secret = env("BAO_WORKER_SECRET_ID") or (
|
||||
secret_file("BAO_WORKER_SECRET_ID_FILE") if env("BAO_WORKER_SECRET_ID_FILE") else ""
|
||||
)
|
||||
|
||||
return Settings(
|
||||
database_url=database_url,
|
||||
session_ttl=int(env("SESSION_TTL_SECONDS", "3600")),
|
||||
idempotency_ttl=int(env("IDEMPOTENCY_TTL_SECONDS", "86400")),
|
||||
s3_endpoint=env("S3_ENDPOINT", "https://s3:9000"),
|
||||
s3_region=env("S3_REGION", "us-east-1"),
|
||||
s3_bucket=env("S3_BUCKET", "messenger-attachments"),
|
||||
s3_access_key=s3_access or "",
|
||||
s3_secret_key=s3_secret or "",
|
||||
s3_verify=env("S3_CACERT", env("TLS_CA_FILE", "/run/secrets/ca.crt")),
|
||||
broker_url=broker_url or "",
|
||||
broker_verify=env("RABBITMQ_CACERT", env("TLS_CA_FILE", "/run/secrets/ca.crt")),
|
||||
bao_addr=env("BAO_ADDR", ""),
|
||||
bao_cacert=env("BAO_CACERT", ""),
|
||||
bao_role_id=bao_role or "",
|
||||
bao_secret_id=bao_secret or "",
|
||||
bao_api_secret_path=env("BAO_API_SECRET_PATH", env("API_BAO_SECRET_PATH", "secret/data/messenger/api")),
|
||||
bao_worker_secret_path=env("BAO_WORKER_SECRET_PATH", env("WORKER_BAO_SECRET_PATH", "secret/data/messenger/worker")),
|
||||
tls_cert=env("TLS_CERT_FILE", ""),
|
||||
tls_key=env("TLS_KEY_FILE", ""),
|
||||
tls_ca=env("TLS_CA_FILE", ""),
|
||||
tls_client_sans=tuple(
|
||||
x.strip() for x in env(
|
||||
"TLS_ALLOWED_CLIENT_SANS",
|
||||
"URI:spiffe://lab7/role/load-balancer",
|
||||
).split(",") if x.strip()
|
||||
),
|
||||
argon_memory=argon_memory,
|
||||
argon_iterations=argon_iterations,
|
||||
argon_parallelism=argon_parallelism,
|
||||
otlp_endpoint=env("OTEL_EXPORTER_OTLP_ENDPOINT"),
|
||||
otlp_verify=env("OTEL_EXPORTER_TLS_CA", env("TLS_CA_FILE")),
|
||||
max_upload=int(env("MAX_UPLOAD_BYTES", "10485760")),
|
||||
max_pixels=int(env("MAX_IMAGE_PIXELS", "40000000")),
|
||||
job_attempts=int(env("JOB_MAX_ATTEMPTS", "5")),
|
||||
job_timeout=int(env("JOB_TIMEOUT_SECONDS", "60")),
|
||||
instance_id=env("INSTANCE_ID", secrets.token_urlsafe(12)),
|
||||
)
|
||||
@@ -0,0 +1,82 @@
|
||||
import ssl
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import asyncpg
|
||||
|
||||
SCHEMA = """
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id UUID PRIMARY KEY, username TEXT UNIQUE NOT NULL, display_name TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS sessions (
|
||||
token TEXT PRIMARY KEY, user_id UUID NOT NULL REFERENCES users(id),
|
||||
expires_at TIMESTAMPTZ NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS chats (
|
||||
id UUID PRIMARY KEY, title TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS chat_members (
|
||||
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||
user_id UUID NOT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
PRIMARY KEY(chat_id,user_id)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS messages (
|
||||
id UUID PRIMARY KEY, chat_id UUID NOT NULL REFERENCES chats(id),
|
||||
sender_id UUID NOT NULL REFERENCES users(id), text TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS message_attachments (
|
||||
message_id UUID NOT NULL REFERENCES messages(id) ON DELETE CASCADE,
|
||||
attachment_id UUID NOT NULL, PRIMARY KEY(message_id,attachment_id)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS attachments (
|
||||
id UUID PRIMARY KEY, chat_id UUID NOT NULL REFERENCES chats(id),
|
||||
owner_id UUID NOT NULL REFERENCES users(id), filename TEXT NOT NULL,
|
||||
content_type TEXT NOT NULL, size_bytes INTEGER NOT NULL, sha256 TEXT NOT NULL,
|
||||
staging_key TEXT NOT NULL, final_key TEXT,
|
||||
status TEXT NOT NULL, error_code TEXT, created_at TIMESTAMPTZ NOT NULL,
|
||||
updated_at TIMESTAMPTZ NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS attachment_variants (
|
||||
attachment_id UUID NOT NULL REFERENCES attachments(id) ON DELETE CASCADE,
|
||||
name TEXT NOT NULL, content_type TEXT NOT NULL, size_bytes INTEGER NOT NULL,
|
||||
width INTEGER NOT NULL, height INTEGER NOT NULL, sha256 TEXT NOT NULL,
|
||||
object_key TEXT NOT NULL, PRIMARY KEY(attachment_id,name)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS idempotency (
|
||||
user_id UUID NOT NULL, method TEXT NOT NULL, path TEXT NOT NULL, key TEXT NOT NULL,
|
||||
body_hash TEXT NOT NULL, status INTEGER NOT NULL, response_json JSONB NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL,
|
||||
PRIMARY KEY(user_id,method,path,key)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_sessions_expiry ON sessions(expires_at);
|
||||
CREATE INDEX IF NOT EXISTS idx_messages_chat_time ON messages(chat_id,created_at,id);
|
||||
CREATE INDEX IF NOT EXISTS idx_chats_time ON chats(created_at,id);
|
||||
CREATE INDEX IF NOT EXISTS idx_attachments_status ON attachments(status);
|
||||
"""
|
||||
|
||||
SCHEMA = SCHEMA.replace("user_id UUID NOT NOT NULL", "user_id UUID NOT NULL")
|
||||
|
||||
|
||||
def pg_ssl(database_url: str, ca_path: str) -> ssl.SSLContext:
|
||||
context = ssl.create_default_context(cafile=ca_path)
|
||||
context.check_hostname = True
|
||||
context.verify_mode = ssl.CERT_REQUIRED
|
||||
return context
|
||||
|
||||
|
||||
async def connect(database_url: str, ca_path: str):
|
||||
return await asyncpg.connect(database_url, ssl=pg_ssl(database_url, ca_path))
|
||||
|
||||
|
||||
async def migrate(pool):
|
||||
async with pool.acquire() as con:
|
||||
async with con.transaction():
|
||||
await con.execute("SELECT pg_advisory_xact_lock($1)", 721548103)
|
||||
await con.execute(SCHEMA)
|
||||
await con.execute(
|
||||
"GRANT SELECT, UPDATE ON attachments TO messenger_worker"
|
||||
)
|
||||
await con.execute(
|
||||
"GRANT SELECT, INSERT, UPDATE ON attachment_variants TO messenger_worker"
|
||||
)
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
"""HTTPS/mTLS entrypoint for the API process."""
|
||||
import asyncio
|
||||
import ssl
|
||||
from urllib.parse import unquote
|
||||
import h11
|
||||
import uvicorn
|
||||
from uvicorn.protocols.http.h11_impl import H11Protocol, RequestResponseCycle
|
||||
from uvicorn.protocols.http.flow_control import HIGH_WATER_LIMIT
|
||||
|
||||
from cryptography import x509
|
||||
from cryptography.x509.oid import ExtensionOID
|
||||
|
||||
from .api import app
|
||||
from .config import load_settings
|
||||
from .tls import normalize_allowed_sans, peer_uri_identites
|
||||
from .tls import API_SERVER_DNS_SAN, LB_URI_SAN
|
||||
|
||||
|
||||
def make_server_context(settings) -> ssl.SSLContext:
|
||||
if not settings.tls_cert or not settings.tls_key or not settings.tls_ca:
|
||||
raise RuntimeError("TLS_CERT_FILE, TLS_KEY_FILE and TLS_CA_FILE are required for lab7")
|
||||
|
||||
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||
context.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||
context.load_cert_chain(settings.tls_cert, settings.tls_key)
|
||||
try:
|
||||
cert = x509.load_pem_x509_certificate(open(settings.tls_cert, "rb").read())
|
||||
san = cert.extensions.get_extension_for_oid(ExtensionOID.SUBJECT_ALTERNATIVE_NAME).value
|
||||
if API_SERVER_DNS_SAN not in san.get_values_for_type(x509.DNSName):
|
||||
raise RuntimeError("API server certificate must contain DNS SAN api")
|
||||
except (OSError, x509.ExtensionNotFound) as exc:
|
||||
raise RuntimeError("valid API TLS certificate/SAN is required") from exc
|
||||
context.load_verify_locations(cafile=settings.tls_ca)
|
||||
context.verify_mode = ssl.CERT_REQUIRED
|
||||
|
||||
return context
|
||||
|
||||
|
||||
async def identity_rejected_app(scope, receive, send):
|
||||
body = b'{"error":{"code":"unauthorized","message":"TLS client identity rejected","request_id":"tls-identity"}}'
|
||||
await send({"type": "http.response.start", "status": 401,
|
||||
"headers": [(b"content-type", b"application/json"),
|
||||
(b"content-length", str(len(body)).encode("ascii"))]})
|
||||
await send({"type": "http.response.body", "body": body})
|
||||
|
||||
|
||||
class AllowlistH11Protocol(H11Protocol):
|
||||
allowed_uri_identity = LB_URI_SAN
|
||||
|
||||
def handle_events(self) -> None:
|
||||
while True:
|
||||
try:
|
||||
event = self.conn.next_event()
|
||||
except h11.RemoteProtocolError:
|
||||
self.logger.warning("Invalid HTTP request received")
|
||||
self.send_400_response("Invalid HTTP request received.")
|
||||
return
|
||||
|
||||
if event is h11.NEED_DATA:
|
||||
break
|
||||
if event is h11.PAUSED:
|
||||
self.flow.pause_reading()
|
||||
break
|
||||
if isinstance(event, h11.Request):
|
||||
self.headers = [(key.lower(), value) for key, value in event.headers]
|
||||
raw_path, _, query_string = event.target.partition(b"?")
|
||||
ssl_object = self.transport.get_extra_info("ssl_object")
|
||||
peer = peer_uri_identites(ssl_object)
|
||||
allowed_from_env = getattr(self.config, "_tls_allowed_client_sans", ())
|
||||
allowed = normalize_allowed_sans(allowed_from_env) or {self.allowed_uri_identity}
|
||||
identity_allowed = bool(peer & allowed)
|
||||
|
||||
self.scope = {
|
||||
"type": "http",
|
||||
"asgi": {"version": self.config.asgi_version, "spec_version": "2.3"},
|
||||
"http_version": event.http_version.decode("ascii"),
|
||||
"server": self.server,
|
||||
"client": self.client,
|
||||
"scheme": self.scheme,
|
||||
"method": event.method.decode("ascii"),
|
||||
"root_path": self.root_path,
|
||||
"path": unquote(raw_path.decode("ascii")),
|
||||
"raw_path": raw_path,
|
||||
"query_string": query_string,
|
||||
"headers": self.headers,
|
||||
"state": self.app_state.copy(),
|
||||
"transport": self.transport,
|
||||
}
|
||||
app = identity_rejected_app if not identity_allowed else self.app
|
||||
if self.limit_concurrency is not None and len(self.connections) >= self.limit_concurrency:
|
||||
app = __import__("uvicorn.protocols.http.h11_impl", fromlist=["service_unavailable"]).service_unavailable
|
||||
self.cycle = RequestResponseCycle(
|
||||
scope=self.scope,
|
||||
conn=self.conn,
|
||||
transport=self.transport,
|
||||
flow=self.flow,
|
||||
logger=self.logger,
|
||||
access_logger=self.access_logger,
|
||||
access_log=self.access_log,
|
||||
default_headers=self.server_state.default_headers,
|
||||
message_event=asyncio.Event(),
|
||||
on_response=self.on_response_complete,
|
||||
)
|
||||
task = self.loop.create_task(self.cycle.run_asgi(app))
|
||||
task.add_done_callback(self.tasks.discard)
|
||||
self.tasks.add(task)
|
||||
elif isinstance(event, h11.Data):
|
||||
if self.conn.our_state is h11.DONE:
|
||||
continue
|
||||
self.cycle.body += event.data
|
||||
if len(self.cycle.body) > HIGH_WATER_LIMIT:
|
||||
self.flow.pause_reading()
|
||||
self.cycle.message_event.set()
|
||||
elif isinstance(event, h11.EndOfMessage):
|
||||
if self.conn.our_state is h11.DONE:
|
||||
self.transport.resume_reading()
|
||||
self.conn.start_next_cycle()
|
||||
continue
|
||||
self.cycle.more_body = False
|
||||
self.cycle.message_event.set()
|
||||
|
||||
|
||||
def main():
|
||||
settings = load_settings("api")
|
||||
context = make_server_context(settings)
|
||||
from os import environ
|
||||
config = uvicorn.Config(
|
||||
app,
|
||||
host=environ.get("APP_HOST", "0.0.0.0"),
|
||||
port=int(environ.get("APP_PORT", "8443")),
|
||||
log_level=environ.get("UVICORN_LOG_LEVEL", "info"),
|
||||
http="h11",
|
||||
ssl_keyfile=settings.tls_key,
|
||||
ssl_certfile=settings.tls_cert,
|
||||
ssl_ca_certs=settings.tls_ca,
|
||||
ssl_cert_reqs=ssl.CERT_REQUIRED,
|
||||
)
|
||||
config.load()
|
||||
config.ssl = context
|
||||
config.http_protocol_class = AllowlistH11Protocol
|
||||
config._tls_allowed_client_sans = settings.tls_client_sans
|
||||
server = uvicorn.Server(config)
|
||||
asyncio.run(server.serve())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,35 @@
|
||||
import os
|
||||
from opentelemetry.sdk.resources import Resource
|
||||
from opentelemetry.sdk.trace import TracerProvider
|
||||
from opentelemetry.sdk.trace.export import BatchSpanProcessor
|
||||
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
|
||||
from opentelemetry.sdk.metrics import MeterProvider
|
||||
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
|
||||
from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
|
||||
|
||||
|
||||
def configure(service_name: str, instance_id: str, endpoint: str | None, ca_file: str | None):
|
||||
if not endpoint:
|
||||
return None
|
||||
resource = Resource.create({
|
||||
"service.name": service_name,
|
||||
"service.version": "1.7.0",
|
||||
"service.instance.id": instance_id,
|
||||
"deployment.environment.name": "lab",
|
||||
})
|
||||
exporter_headers = None
|
||||
kwargs = {"certificate_file": ca_file} if ca_file and os.path.isfile(ca_file) else {}
|
||||
tracer_provider = TracerProvider(resource=resource)
|
||||
tracer_provider.add_span_processor(
|
||||
BatchSpanProcessor(OTLPSpanExporter(endpoint=endpoint.rstrip("/") + "/v1/traces",
|
||||
headers=exporter_headers, **kwargs))
|
||||
)
|
||||
metric_reader = PeriodicExportingMetricReader(
|
||||
OTLPMetricExporter(endpoint=endpoint.rstrip("/") + "/v1/metrics",
|
||||
headers=exporter_headers, **kwargs)
|
||||
)
|
||||
meter_provider = MeterProvider(resource=resource, metric_readers=[metric_reader])
|
||||
from opentelemetry import trace, metrics
|
||||
trace.set_tracer_provider(tracer_provider)
|
||||
metrics.set_meter_provider(meter_provider)
|
||||
return trace.get_tracer(service_name)
|
||||
@@ -0,0 +1,71 @@
|
||||
import unittest
|
||||
import os
|
||||
import tempfile
|
||||
|
||||
from app.tls import (
|
||||
API_SERVER_DNS_SAN,
|
||||
LB_URI_SAN,
|
||||
normalize_allowed_sans,
|
||||
peer_uri_identites,
|
||||
)
|
||||
from app.config import load_settings
|
||||
|
||||
|
||||
class FakeSslObject:
|
||||
def getpeercert(self, binary_form=False):
|
||||
return {"subjectAltName": (
|
||||
("URI", "spiffe://lab7/role/load-balancer"),
|
||||
("DNS", "not-a-uri"),
|
||||
)}
|
||||
|
||||
|
||||
class TlsSanTests(unittest.TestCase):
|
||||
def test_local_api_and_lb_identities_are_exact(self):
|
||||
self.assertEqual(API_SERVER_DNS_SAN, "api")
|
||||
self.assertEqual(LB_URI_SAN, "URI:spiffe://lab7/role/load-balancer")
|
||||
|
||||
def test_allowlist_accepts_exact_spiffe_uri(self):
|
||||
peer = peer_uri_identites(FakeSslObject())
|
||||
allowed = normalize_allowed_sans(["spiffe://lab7/role/load-balancer"])
|
||||
self.assertIn("URI:spiffe://lab7/role/load-balancer", peer)
|
||||
self.assertTrue(peer & allowed)
|
||||
|
||||
def test_allowlist_rejects_different_uri(self):
|
||||
peer = peer_uri_identites(FakeSslObject())
|
||||
allowed = normalize_allowed_sans(["URI:spiffe://lab7/role/other"])
|
||||
self.assertFalse(peer & allowed)
|
||||
|
||||
|
||||
class ConfigIntegrationTests(unittest.TestCase):
|
||||
def test_scoped_bao_files_instance_and_otel_ca(self):
|
||||
with tempfile.NamedTemporaryFile(mode="w", delete=False) as role, tempfile.NamedTemporaryFile(mode="w", delete=False) as secret:
|
||||
role.write("api-role-id")
|
||||
secret.write("api-secret-id")
|
||||
role_path, secret_path = role.name, secret.name
|
||||
try:
|
||||
os.environ["BAO_API_ROLE_ID_FILE"] = role_path
|
||||
os.environ["BAO_API_SECRET_ID_FILE"] = secret_path
|
||||
os.environ["BAO_API_SECRET_PATH"] = "secret/data/messenger/api"
|
||||
os.environ["BAO_ADDR"] = "https://openbao:8200"
|
||||
os.environ["BAO_CACERT"] = "/run/secrets/bao-ca.crt"
|
||||
os.environ["INSTANCE_ID"] = "api-01"
|
||||
os.environ["OTEL_EXPORTER_TLS_CA"] = "/run/secrets/otel-ca.crt"
|
||||
os.environ["DATABASE_URL"] = "postgresql://api:pass@postgres/db"
|
||||
settings = load_settings("api")
|
||||
self.assertEqual(settings.bao_role_id, "api-role-id")
|
||||
self.assertEqual(settings.bao_secret_id, "api-secret-id")
|
||||
self.assertEqual(settings.bao_api_secret_path, "secret/data/messenger/api")
|
||||
self.assertEqual(settings.instance_id, "api-01")
|
||||
self.assertEqual(settings.otlp_verify, "/run/secrets/otel-ca.crt")
|
||||
finally:
|
||||
os.unlink(role_path)
|
||||
os.unlink(secret_path)
|
||||
for key in (
|
||||
"BAO_API_ROLE_ID_FILE", "BAO_API_SECRET_ID_FILE", "BAO_API_SECRET_PATH",
|
||||
"BAO_ADDR", "BAO_CACERT", "INSTANCE_ID", "OTEL_EXPORTER_TLS_CA", "DATABASE_URL",
|
||||
):
|
||||
os.environ.pop(key, None)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
import ssl
|
||||
|
||||
API_SERVER_DNS_SAN = "api"
|
||||
LB_URI_SAN = "URI:spiffe://lab7/role/load-balancer"
|
||||
|
||||
|
||||
def peer_uri_identites(ssl_object) -> set[str]:
|
||||
"""Read URI SANs from the TLS socket peer certificate."""
|
||||
if ssl_object is None:
|
||||
return set()
|
||||
try:
|
||||
cert = ssl_object.getpeercert(binary_form=False)
|
||||
except (AttributeError, ssl.SSLError):
|
||||
return set()
|
||||
if not isinstance(cert, dict):
|
||||
return set()
|
||||
return {
|
||||
"URI:" + value
|
||||
for kind, value in cert.get("subjectAltName", ())
|
||||
if kind == "URI"
|
||||
}
|
||||
|
||||
|
||||
def normalize_allowed_sans(values) -> set[str]:
|
||||
normalized = set()
|
||||
for value in values:
|
||||
value = value.strip()
|
||||
if not value:
|
||||
continue
|
||||
normalized.add(value if value.startswith("URI:") else "URI:" + value)
|
||||
return normalized
|
||||
@@ -0,0 +1,51 @@
|
||||
import json
|
||||
import ssl
|
||||
from pathlib import Path
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
from .config import Settings
|
||||
|
||||
|
||||
def _post_json(url: str, payload: dict, ca: str) -> dict:
|
||||
context = ssl.create_default_context(cafile=ca)
|
||||
req = Request(url, data=json.dumps(payload).encode("utf-8"),
|
||||
headers={"Content-Type": "application/json"}, method="POST")
|
||||
with urlopen(req, context=context, timeout=10) as response:
|
||||
return json.loads(response.read())
|
||||
|
||||
|
||||
def login(settings: Settings, role: str) -> dict:
|
||||
"""Authenticate via the role-scoped AppRole and fetch only that role's KV path."""
|
||||
if not settings.bao_addr or not settings.bao_cacert:
|
||||
raise RuntimeError("OpenBao address and TLS CA are required")
|
||||
if not settings.bao_role_id or not settings.bao_secret_id:
|
||||
raise RuntimeError("OpenBao AppRole role_id and secret_id are required")
|
||||
ca = settings.bao_cacert
|
||||
if not Path(ca).is_file():
|
||||
raise RuntimeError("OpenBao TLS CA file is unavailable")
|
||||
login = _post_json(
|
||||
settings.bao_addr.rstrip("/") + "/v1/auth/approle/login",
|
||||
{"role_id": settings.bao_role_id, "secret_id": settings.bao_secret_id},
|
||||
ca,
|
||||
)
|
||||
token = login.get("auth", {}).get("client_token")
|
||||
if not token:
|
||||
raise RuntimeError("OpenBao AppRole authentication did not return a scoped token")
|
||||
path = settings.bao_api_secret_path if role == "api" else settings.bao_worker_secret_path
|
||||
context = ssl.create_default_context(cafile=ca)
|
||||
req = Request(settings.bao_addr.rstrip("/") + "/v1/" + path.lstrip("v1/"),
|
||||
headers={"X-Vault-Token": token})
|
||||
with urlopen(req, context=context, timeout=10) as response:
|
||||
envelope = json.loads(response.read())
|
||||
data = envelope.get("data", {})
|
||||
secrets = data.get("data", data)
|
||||
if not isinstance(secrets, dict):
|
||||
raise RuntimeError("OpenBao returned an invalid scoped secret envelope")
|
||||
if role == "api":
|
||||
required = ("database_url", "broker_url", "s3_access_key", "s3_secret_key")
|
||||
else:
|
||||
required = ("database_url", "broker_url", "s3_access_key", "s3_secret_key")
|
||||
missing = [key for key in required if not secrets.get(key)]
|
||||
if missing:
|
||||
raise RuntimeError("OpenBao scoped secret path is missing required credentials")
|
||||
return {"token": token, "secrets": secrets}
|
||||
+232
@@ -0,0 +1,232 @@
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import ssl
|
||||
import sys
|
||||
import uuid
|
||||
from io import BytesIO
|
||||
|
||||
import asyncpg
|
||||
import boto3
|
||||
import pika
|
||||
from PIL import Image, ImageOps
|
||||
|
||||
from .config import load_settings, env
|
||||
from .db import pg_ssl
|
||||
from .vault import login
|
||||
|
||||
settings = load_settings("worker")
|
||||
try:
|
||||
vault = login(settings, "worker")
|
||||
except Exception as exc:
|
||||
logger = logging.getLogger("messenger-worker")
|
||||
logger.error("worker_startup_secret_auth_failed", extra={
|
||||
"event": "worker_startup_secret_auth_failed",
|
||||
"error_type": type(exc).__name__,
|
||||
})
|
||||
raise RuntimeError("worker OpenBao AppRole authentication unavailable") from None
|
||||
secrets = vault["secrets"]
|
||||
settings = settings.__class__(**{**settings.__dict__,
|
||||
"database_url": secrets["database_url"],
|
||||
"broker_url": secrets["broker_url"],
|
||||
"s3_access_key": secrets["s3_access_key"],
|
||||
"s3_secret_key": secrets["s3_secret_key"],
|
||||
})
|
||||
|
||||
|
||||
logger = logging.getLogger("messenger-worker")
|
||||
|
||||
|
||||
async def pool():
|
||||
ca = env("PG_CACERT", env("TLS_CA_FILE"))
|
||||
pool = await asyncpg.create_pool(settings.database_url, ssl=pg_ssl(settings.database_url, ca),
|
||||
min_size=1, max_size=5)
|
||||
return pool
|
||||
|
||||
|
||||
def s3():
|
||||
return boto3.client(
|
||||
"s3",
|
||||
endpoint_url=settings.s3_endpoint,
|
||||
region_name=settings.s3_region,
|
||||
aws_access_key_id=settings.s3_access_key,
|
||||
aws_secret_access_key=settings.s3_secret_key,
|
||||
verify=settings.s3_verify,
|
||||
)
|
||||
|
||||
|
||||
async def process_attachment(pool, attachment_id):
|
||||
async with pool.acquire() as con:
|
||||
row = await con.fetchrow("SELECT * FROM attachments WHERE id=$1", attachment_id)
|
||||
if not row:
|
||||
return "missing"
|
||||
if row["status"] == "ready":
|
||||
return "ready"
|
||||
await con.execute(
|
||||
"UPDATE attachments SET status='processing',updated_at=NOW() WHERE id=$1",
|
||||
attachment_id,
|
||||
)
|
||||
|
||||
client = s3()
|
||||
original = await asyncio.to_thread(
|
||||
client.get_object, Bucket=settings.s3_bucket, Key=row["staging_key"]
|
||||
)
|
||||
data = await asyncio.to_thread(original["Body"].read)
|
||||
|
||||
try:
|
||||
with Image.open(BytesIO(data)) as source:
|
||||
source.load()
|
||||
image = ImageOps.exif_transpose(source)
|
||||
if image.mode in ("RGBA", "LA") or "transparency" in image.info:
|
||||
alpha = image.convert("RGBA")
|
||||
white = Image.new("RGBA", alpha.size, (255, 255, 255, 255))
|
||||
white.alpha_composite(alpha)
|
||||
image = white.convert("RGB")
|
||||
else:
|
||||
image = image.convert("RGB")
|
||||
width, height = image.size
|
||||
if width >= 1 and height >= 1:
|
||||
scale = min(256 / width, 256 / height, 1.0)
|
||||
tw = max(1, int(width * scale))
|
||||
th = max(1, int(height * scale))
|
||||
thumbnail = image.resize((tw, th), Image.Resampling.LANCZOS)
|
||||
else:
|
||||
raise ValueError("invalid image dimensions")
|
||||
output = BytesIO()
|
||||
thumbnail.save(output, format="JPEG", quality=85, optimize=True)
|
||||
thumb = output.getvalue()
|
||||
except Exception as exc:
|
||||
logger.error("attachment_processing_failed_safe", extra={
|
||||
"event": "attachment_processing_failed",
|
||||
"attachment_id": str(attachment_id),
|
||||
"error_type": type(exc).__name__,
|
||||
})
|
||||
async with pool.acquire() as con:
|
||||
await con.execute(
|
||||
"UPDATE attachments SET status='failed',error_code='invalid_image',"
|
||||
"updated_at=NOW() WHERE id=$1", attachment_id,
|
||||
)
|
||||
return "failed"
|
||||
|
||||
final_key = f"attachments/{attachment_id}/original"
|
||||
thumb_key = f"attachments/{attachment_id}/thumbnail"
|
||||
try:
|
||||
await asyncio.to_thread(
|
||||
client.put_object, Bucket=settings.s3_bucket, Key=final_key,
|
||||
Body=data, ContentType=row["content_type"],
|
||||
)
|
||||
await asyncio.to_thread(
|
||||
client.put_object, Bucket=settings.s3_bucket, Key=thumb_key,
|
||||
Body=thumb, ContentType="image/jpeg",
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.error("attachment_publish_failed_safe", extra={
|
||||
"event": "attachment_publish_failed",
|
||||
"attachment_id": str(attachment_id),
|
||||
"error_type": type(exc).__name__,
|
||||
})
|
||||
async with pool.acquire() as con:
|
||||
await con.execute(
|
||||
"UPDATE attachments SET status='failed',error_code='processing_failed',"
|
||||
"updated_at=NOW() WHERE id=$1", attachment_id,
|
||||
)
|
||||
return "failed"
|
||||
|
||||
thumb_sha = hashlib.sha256(thumb).hexdigest()
|
||||
async with pool.acquire() as con:
|
||||
async with con.transaction():
|
||||
await con.execute(
|
||||
"INSERT INTO attachment_variants"
|
||||
"(attachment_id,name,content_type,size_bytes,width,height,sha256,object_key)"
|
||||
" VALUES($1,'thumbnail','image/jpeg',$2,$3,$4,$5,$6)"
|
||||
" ON CONFLICT (attachment_id,name) DO UPDATE SET "
|
||||
"size_bytes=EXCLUDED.size_bytes,width=EXCLUDED.width,height=EXCLUDED.height,"
|
||||
"sha256=EXCLUDED.sha256,object_key=EXCLUDED.object_key",
|
||||
attachment_id, len(thumb), tw, th, thumb_sha, thumb_key,
|
||||
)
|
||||
await con.execute(
|
||||
"UPDATE attachments SET status='ready',error_code=NULL,final_key=$1,"
|
||||
"updated_at=NOW() WHERE id=$2",
|
||||
final_key, attachment_id,
|
||||
)
|
||||
return "ready"
|
||||
|
||||
|
||||
async def fail_retry_exhausted(pool, attachment_id):
|
||||
async with pool.acquire() as con:
|
||||
await con.execute(
|
||||
"UPDATE attachments SET status='failed',error_code='retry_exhausted',"
|
||||
"updated_at=NOW() WHERE id=$1",
|
||||
attachment_id,
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
loop = asyncio.new_event_loop()
|
||||
asyncio.set_event_loop(loop)
|
||||
db_pool = loop.run_until_complete(pool())
|
||||
|
||||
params = pika.URLParameters(settings.broker_url)
|
||||
if settings.broker_url.startswith("amqps://"):
|
||||
ssl_context = ssl.create_default_context(cafile=settings.broker_verify)
|
||||
ssl_context.check_hostname = True
|
||||
ssl_context.verify_mode = ssl.CERT_REQUIRED
|
||||
params.ssl_options = pika.SSLOptions(ssl_context)
|
||||
connection = pika.BlockingConnection(params)
|
||||
channel = connection.channel()
|
||||
channel.queue_declare(queue="attachment.jobs", durable=True)
|
||||
channel.basic_qos(prefetch_count=settings.job_attempts)
|
||||
channel.confirm_delivery()
|
||||
|
||||
def on_message(ch, method, properties, body):
|
||||
job = None
|
||||
try:
|
||||
job = json.loads(body)
|
||||
if set(job) - {"schema_version","job_id","type","attachment_id","pipeline_version","attempt","created_at","traceparent","tracestate"}:
|
||||
raise ValueError("invalid job")
|
||||
if job.get("schema_version") != 1 or job.get("type") != "attachment.process.v1":
|
||||
raise ValueError("invalid job")
|
||||
import uuid
|
||||
uuid.UUID(job["job_id"])
|
||||
aid = uuid.UUID(job["attachment_id"])
|
||||
outcome = loop.run_until_complete(process_attachment(db_pool, aid))
|
||||
if outcome in ("ready", "missing", "failed"):
|
||||
ch.basic_ack(delivery_tag=method.delivery_tag)
|
||||
else:
|
||||
ch.basic_nack(delivery_tag=method.delivery_tag, requeue=True)
|
||||
except Exception as exc:
|
||||
logger.error("worker_job_failed_safe", extra={
|
||||
"event": "worker_job_failed",
|
||||
"job_id": job.get("job_id") if isinstance(job, dict) else None,
|
||||
"attachment_id": job.get("attachment_id") if isinstance(job, dict) else None,
|
||||
"error_type": type(exc).__name__,
|
||||
})
|
||||
attempt = int(job.get("attempt", 1)) if isinstance(job, dict) else 1
|
||||
if attempt >= settings.job_attempts:
|
||||
try:
|
||||
aid = uuid.UUID(job["attachment_id"])
|
||||
loop.run_until_complete(fail_retry_exhausted(db_pool, aid))
|
||||
except Exception as exc:
|
||||
logger.error("retry_exhausted_update_failed_safe", extra={
|
||||
"event": "retry_exhausted_update_failed",
|
||||
"attachment_id": job.get("attachment_id") if isinstance(job, dict) else None,
|
||||
"error_type": type(exc).__name__,
|
||||
})
|
||||
ch.basic_ack(delivery_tag=method.delivery_tag)
|
||||
else:
|
||||
next_job = dict(job)
|
||||
next_job["attempt"] = attempt + 1
|
||||
ch.basic_publish(
|
||||
exchange="", routing_key="attachment.jobs",
|
||||
body=json.dumps(next_job, separators=(",", ":")).encode("utf-8"),
|
||||
properties=pika.BasicProperties(delivery_mode=2),
|
||||
)
|
||||
ch.basic_ack(delivery_tag=method.delivery_tag)
|
||||
|
||||
channel.basic_consume(queue="attachment.jobs", on_message_callback=on_message)
|
||||
channel.start_consuming()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+514
@@ -0,0 +1,514 @@
|
||||
name: mtusi-lab7
|
||||
|
||||
x-service-hardening: &service-hardening
|
||||
cap_drop: [ALL]
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
init: true
|
||||
restart: unless-stopped
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "1.0"
|
||||
memory: 768M
|
||||
|
||||
services:
|
||||
certs-init:
|
||||
image: alpine:3.21.3
|
||||
entrypoint: ["/bin/sh", "/bootstrap/copy-runtime-certs.sh"]
|
||||
read_only: true
|
||||
cap_drop: [ALL]
|
||||
cap_add: [CHOWN]
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
volumes:
|
||||
- ./secrets/runtime-pki:/source:ro
|
||||
- ./secrets/pki:/source-test-pki:ro
|
||||
- ./secrets:/source-secrets:ro
|
||||
- ./infra/copy-runtime-certs.sh:/bootstrap/copy-runtime-certs.sh:ro
|
||||
- ingress-certs:/certs/ingress
|
||||
- api-certs:/certs/api
|
||||
- worker-certs:/certs/worker
|
||||
- postgres-certs:/certs/postgres
|
||||
- postgres-secrets:/certs/postgres-secrets
|
||||
- s3-certs:/certs/s3
|
||||
- mc-ca:/certs/mc-ca
|
||||
- rabbit-certs:/certs/rabbit
|
||||
- openbao-certs:/certs/openbao
|
||||
- collector-certs:/certs/collector
|
||||
- prometheus-certs:/certs/prometheus
|
||||
- loki-certs:/certs/loki
|
||||
- tempo-certs:/certs/tempo
|
||||
- grafana-certs:/certs/grafana
|
||||
- mtls-test-certs:/certs/mtls-test
|
||||
networks: []
|
||||
restart: "no"
|
||||
|
||||
postgres:
|
||||
image: postgres:16.6-alpine
|
||||
<<: *service-hardening
|
||||
environment:
|
||||
POSTGRES_DB: ${POSTGRES_DB:?run make bootstrap first}
|
||||
POSTGRES_USER: ${POSTGRES_USER:?run make bootstrap first}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?run make bootstrap first}
|
||||
POSTGRES_INITDB_ARGS: --auth-host=scram-sha-256
|
||||
command:
|
||||
- postgres
|
||||
- -c
|
||||
- ssl=on
|
||||
- -c
|
||||
- ssl_cert_file=/run/certs/server.crt
|
||||
- -c
|
||||
- ssl_key_file=/run/certs/server.key
|
||||
- -c
|
||||
- ssl_ca_file=/run/certs/ca.crt
|
||||
- -c
|
||||
- hba_file=/etc/postgresql/pg_hba.conf
|
||||
volumes:
|
||||
- postgres-data:/var/lib/postgresql/data
|
||||
- ./infra/postgres/pg_hba.conf:/etc/postgresql/pg_hba.conf:ro
|
||||
- postgres-certs:/run/certs:ro
|
||||
- postgres-secrets:/run/secrets:ro
|
||||
tmpfs:
|
||||
- /tmp
|
||||
- /run/postgresql
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U \"$${POSTGRES_USER}\" -d \"$${POSTGRES_DB}\""]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
networks: [services]
|
||||
cap_drop: [ALL]
|
||||
cap_add: [CHOWN, DAC_OVERRIDE, FOWNER, SETGID, SETUID]
|
||||
read_only: true
|
||||
depends_on:
|
||||
certs-init:
|
||||
condition: service_completed_successfully
|
||||
|
||||
s3:
|
||||
image: bitnamilegacy/minio:2024.12.18-debian-12-r0@sha256:cce234b4381a169d80836584d966bb5c82365e5f7f0becfcf2d1cf8c57be754b
|
||||
<<: *service-hardening
|
||||
environment:
|
||||
MINIO_ROOT_USER: ${MINIO_ROOT_USER:?run make bootstrap first}
|
||||
MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD:?run make bootstrap first}
|
||||
MINIO_PROMETHEUS_AUTH_TYPE: public
|
||||
MINIO_SCHEME: https
|
||||
MINIO_SERVER_URL: https://s3:9000
|
||||
MINIO_CLIENT_CONF_DIR: /tmp
|
||||
volumes:
|
||||
- s3-data:/bitnami/minio
|
||||
- s3-certs:/certs:ro
|
||||
networks: [services]
|
||||
cap_drop: [ALL]
|
||||
read_only: true
|
||||
tmpfs:
|
||||
- /tmp
|
||||
- /opt/bitnami/minio/tmp
|
||||
depends_on:
|
||||
certs-init:
|
||||
condition: service_completed_successfully
|
||||
|
||||
s3-provisioner:
|
||||
image: bitnamilegacy/minio-client:latest@sha256:00dcc4e58ada0df45bb7d9ee435af98295f96c27c3c68292ce78ec700a87b511
|
||||
entrypoint: ["/bin/sh", "/bootstrap/provision.sh"]
|
||||
environment:
|
||||
MINIO_ROOT_USER: ${MINIO_ROOT_USER:?run make bootstrap first}
|
||||
MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD:?run make bootstrap first}
|
||||
S3_API_ACCESS_KEY: ${S3_API_ACCESS_KEY:?run make bootstrap first}
|
||||
S3_API_SECRET_KEY: ${S3_API_SECRET_KEY:?run make bootstrap first}
|
||||
S3_WORKER_ACCESS_KEY: ${S3_WORKER_ACCESS_KEY:?run make bootstrap first}
|
||||
S3_WORKER_SECRET_KEY: ${S3_WORKER_SECRET_KEY:?run make bootstrap first}
|
||||
MINIO_CLIENT_CONF_DIR: /tmp
|
||||
volumes:
|
||||
- ./infra/s3/provision.sh:/bootstrap/provision.sh:ro
|
||||
- ./infra/s3/policy-api.json:/bootstrap/policy-api.json:ro
|
||||
- ./infra/s3/policy-worker.json:/bootstrap/policy-worker.json:ro
|
||||
- mc-ca:/tmp/certs/CAs:ro
|
||||
cap_drop: [ALL]
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
read_only: true
|
||||
tmpfs:
|
||||
- /tmp
|
||||
networks: [services]
|
||||
depends_on:
|
||||
s3:
|
||||
condition: service_started
|
||||
restart: "no"
|
||||
|
||||
mtls-probe:
|
||||
image: python:3.12.8-slim
|
||||
profiles: [test]
|
||||
entrypoint: ["python", "/tests/internal_mtls.py"]
|
||||
user: "10001:10001"
|
||||
cap_drop: [ALL]
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
read_only: true
|
||||
volumes:
|
||||
- ./tests/internal_mtls.py:/tests/internal_mtls.py:ro
|
||||
- mtls-test-certs:/run/pki:ro
|
||||
networks: [services]
|
||||
restart: "no"
|
||||
|
||||
rabbitmq:
|
||||
image: rabbitmq:4.0-management-alpine
|
||||
<<: *service-hardening
|
||||
user: "100:101"
|
||||
hostname: rabbitmq
|
||||
environment:
|
||||
RABBITMQ_DEFAULT_USER: ${RABBITMQ_DEFAULT_USER:?run make bootstrap first}
|
||||
RABBITMQ_DEFAULT_PASS: ${RABBITMQ_DEFAULT_PASS:?run make bootstrap first}
|
||||
RABBITMQ_DEFAULT_VHOST: messenger
|
||||
volumes:
|
||||
- rabbit-data:/var/lib/rabbitmq
|
||||
- ./infra/rabbitmq/rabbitmq.conf:/etc/rabbitmq/rabbitmq.conf:ro
|
||||
- rabbit-certs:/run/pki:ro
|
||||
healthcheck:
|
||||
test: ["CMD", "rabbitmq-diagnostics", "-q", "ping"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 20
|
||||
networks: [services]
|
||||
depends_on:
|
||||
certs-init:
|
||||
condition: service_completed_successfully
|
||||
|
||||
openbao:
|
||||
image: openbao/openbao:2.1.0
|
||||
<<: *service-hardening
|
||||
command: ["server", "-config=/openbao/config.hcl"]
|
||||
environment:
|
||||
BAO_ADDR: https://openbao:8200
|
||||
BAO_CACERT: /run/pki/ca.crt
|
||||
volumes:
|
||||
- openbao-data:/openbao/file
|
||||
- ./infra/openbao/config.hcl:/openbao/config.hcl:ro
|
||||
- openbao-certs:/run/pki:ro
|
||||
networks: [services]
|
||||
cap_add: [SETGID, SETUID]
|
||||
depends_on:
|
||||
certs-init:
|
||||
condition: service_completed_successfully
|
||||
|
||||
openbao-provisioner:
|
||||
image: python:3.12.8-slim
|
||||
command: ["python", "/bootstrap/provision.py"]
|
||||
environment:
|
||||
OPENBAO_ADDR: https://openbao:8200
|
||||
OPENBAO_CACERT: /run/certs/ca.crt
|
||||
POSTGRES_API_PASSWORD: ${POSTGRES_API_PASSWORD:?run make bootstrap first}
|
||||
POSTGRES_WORKER_PASSWORD: ${POSTGRES_WORKER_PASSWORD:?run make bootstrap first}
|
||||
RABBITMQ_API_PASSWORD: ${RABBITMQ_API_PASSWORD:?run make bootstrap first}
|
||||
RABBITMQ_WORKER_PASSWORD: ${RABBITMQ_WORKER_PASSWORD:?run make bootstrap first}
|
||||
S3_API_ACCESS_KEY: ${S3_API_ACCESS_KEY:?run make bootstrap first}
|
||||
S3_API_SECRET_KEY: ${S3_API_SECRET_KEY:?run make bootstrap first}
|
||||
S3_WORKER_ACCESS_KEY: ${S3_WORKER_ACCESS_KEY:?run make bootstrap first}
|
||||
S3_WORKER_SECRET_KEY: ${S3_WORKER_SECRET_KEY:?run make bootstrap first}
|
||||
volumes:
|
||||
- ./infra/openbao/provision.py:/bootstrap/provision.py:ro
|
||||
- ./secrets/openbao-operator.json:/run/operator/openbao-operator.json:ro
|
||||
- ./secrets/approle:/output/approle
|
||||
- openbao-certs:/run/certs:ro
|
||||
read_only: true
|
||||
tmpfs:
|
||||
- /tmp
|
||||
networks: [services]
|
||||
depends_on:
|
||||
openbao:
|
||||
condition: service_started
|
||||
|
||||
api-1:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
<<: *service-hardening
|
||||
user: "10001:10001"
|
||||
cap_drop: [ALL]
|
||||
command: ["python", "-m", "app.server"]
|
||||
environment: &api-environment
|
||||
APP_HOST: 0.0.0.0
|
||||
APP_PORT: "8443"
|
||||
TLS_CERT_FILE: /run/certs/server.crt
|
||||
TLS_KEY_FILE: /run/certs/server.key
|
||||
TLS_CA_FILE: /run/certs/ca.crt
|
||||
TLS_ALLOWED_CLIENT_SANS: URI:spiffe://lab7/role/load-balancer
|
||||
BAO_ADDR: https://openbao:8200
|
||||
BAO_CACERT: /run/certs/ca.crt
|
||||
BAO_API_ROLE_ID_FILE: /run/bao-auth/role_id
|
||||
BAO_API_SECRET_ID_FILE: /run/bao-auth/secret_id
|
||||
BAO_API_SECRET_PATH: secret/data/messenger/api
|
||||
PG_CACERT: /run/certs/ca.crt
|
||||
S3_CACERT: /run/certs/ca.crt
|
||||
RABBITMQ_CACERT: /run/certs/ca.crt
|
||||
S3_ENDPOINT: https://s3:9000
|
||||
S3_BUCKET: messenger-attachments
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:4318
|
||||
OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf
|
||||
OTEL_EXPORTER_TLS_CA: /run/certs/ca.crt
|
||||
OTEL_EXPORTER_OTLP_CERTIFICATE: /run/certs/ca.crt
|
||||
OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: /run/certs/client.crt
|
||||
OTEL_EXPORTER_OTLP_CLIENT_KEY: /run/certs/client.key
|
||||
APP_ENV: lab
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||
ARGON2_MEMORY_KIB: ${ARGON2_MEMORY_KIB:-19456}
|
||||
ARGON2_ITERATIONS: ${ARGON2_ITERATIONS:-2}
|
||||
ARGON2_PARALLELISM: ${ARGON2_PARALLELISM:-1}
|
||||
MAX_UPLOAD_BYTES: "10485760"
|
||||
MAX_IMAGE_PIXELS: "40000000"
|
||||
INSTANCE_ID: api-1
|
||||
volumes:
|
||||
- api-certs:/run/certs:ro
|
||||
- ./secrets/approle/api:/run/bao-auth:ro
|
||||
read_only: true
|
||||
tmpfs:
|
||||
- /tmp
|
||||
networks: [services]
|
||||
healthcheck:
|
||||
test: ["CMD", "python", "-c", "import socket; socket.create_connection(('127.0.0.1',8443),timeout=2).close()"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
rabbitmq:
|
||||
condition: service_healthy
|
||||
openbao:
|
||||
condition: service_started
|
||||
s3-provisioner:
|
||||
condition: service_completed_successfully
|
||||
|
||||
api-2:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
<<: *service-hardening
|
||||
user: "10001:10001"
|
||||
cap_drop: [ALL]
|
||||
command: ["python", "-m", "app.server"]
|
||||
environment:
|
||||
<<: *api-environment
|
||||
INSTANCE_ID: api-2
|
||||
volumes:
|
||||
- api-certs:/run/certs:ro
|
||||
- ./secrets/approle/api:/run/bao-auth:ro
|
||||
read_only: true
|
||||
tmpfs:
|
||||
- /tmp
|
||||
networks: [services]
|
||||
healthcheck:
|
||||
test: ["CMD", "python", "-c", "import socket; socket.create_connection(('127.0.0.1',8443),timeout=2).close()"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
rabbitmq:
|
||||
condition: service_healthy
|
||||
openbao:
|
||||
condition: service_started
|
||||
s3-provisioner:
|
||||
condition: service_completed_successfully
|
||||
|
||||
worker:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
<<: *service-hardening
|
||||
user: "10001:10001"
|
||||
cap_drop: [ALL]
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "0.5"
|
||||
memory: 512M
|
||||
command: ["python", "-m", "app.worker"]
|
||||
environment:
|
||||
APP_ROLE: worker
|
||||
BAO_ADDR: https://openbao:8200
|
||||
BAO_CACERT: /run/certs/ca.crt
|
||||
BAO_WORKER_ROLE_ID_FILE: /run/bao-auth/role_id
|
||||
BAO_WORKER_SECRET_ID_FILE: /run/bao-auth/secret_id
|
||||
BAO_WORKER_SECRET_PATH: secret/data/messenger/worker
|
||||
TLS_CA_FILE: /run/certs/ca.crt
|
||||
PG_CACERT: /run/certs/ca.crt
|
||||
S3_CACERT: /run/certs/ca.crt
|
||||
RABBITMQ_CACERT: /run/certs/ca.crt
|
||||
S3_ENDPOINT: https://s3:9000
|
||||
S3_BUCKET: messenger-attachments
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:4318
|
||||
OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf
|
||||
OTEL_EXPORTER_TLS_CA: /run/certs/ca.crt
|
||||
OTEL_EXPORTER_OTLP_CERTIFICATE: /run/certs/ca.crt
|
||||
OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: /run/certs/client.crt
|
||||
OTEL_EXPORTER_OTLP_CLIENT_KEY: /run/certs/client.key
|
||||
APP_ENV: lab
|
||||
INSTANCE_ID: worker
|
||||
volumes:
|
||||
- worker-certs:/run/certs:ro
|
||||
- ./secrets/approle/worker:/run/bao-auth:ro
|
||||
read_only: true
|
||||
tmpfs:
|
||||
- /tmp
|
||||
networks: [services]
|
||||
depends_on:
|
||||
api-1:
|
||||
condition: service_healthy
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
rabbitmq:
|
||||
condition: service_healthy
|
||||
openbao:
|
||||
condition: service_started
|
||||
s3-provisioner:
|
||||
condition: service_completed_successfully
|
||||
|
||||
nginx:
|
||||
image: nginx:1.27-alpine
|
||||
<<: *service-hardening
|
||||
user: "101:101"
|
||||
tmpfs:
|
||||
- /var/cache/nginx:mode=1777
|
||||
- /var/run:mode=1777
|
||||
- /tmp
|
||||
ports:
|
||||
- "127.0.0.1:8443:8443"
|
||||
volumes:
|
||||
- ./infra/nginx.conf:/etc/nginx/nginx.conf:ro
|
||||
- ingress-certs:/run/pki:ro
|
||||
- grafana-certs:/run/grafana-certs:ro
|
||||
networks: [services, telemetry, host-ingress]
|
||||
depends_on:
|
||||
api-1:
|
||||
condition: service_healthy
|
||||
api-2:
|
||||
condition: service_healthy
|
||||
grafana:
|
||||
condition: service_started
|
||||
|
||||
otel-collector:
|
||||
image: otel/opentelemetry-collector-contrib:0.120.0
|
||||
<<: *service-hardening
|
||||
command: ["--config=/etc/otelcol-contrib/config.yaml"]
|
||||
volumes:
|
||||
- ./infra/otel/collector.yaml:/etc/otelcol-contrib/config.yaml:ro
|
||||
- collector-certs:/run/certs:ro
|
||||
networks: [services, telemetry]
|
||||
depends_on:
|
||||
certs-init:
|
||||
condition: service_completed_successfully
|
||||
prometheus:
|
||||
condition: service_started
|
||||
loki:
|
||||
condition: service_started
|
||||
tempo:
|
||||
condition: service_started
|
||||
|
||||
prometheus:
|
||||
image: prom/prometheus:v2.55.1
|
||||
<<: *service-hardening
|
||||
command:
|
||||
- --config.file=/etc/prometheus/prometheus.yml
|
||||
- --storage.tsdb.path=/prometheus
|
||||
- --web.config.file=/etc/prometheus/web.yml
|
||||
- --web.enable-remote-write-receiver
|
||||
volumes:
|
||||
- ./infra/otel/prometheus.yaml:/etc/prometheus/prometheus.yml:ro
|
||||
- ./infra/otel/prometheus-web.yaml:/etc/prometheus/web.yml:ro
|
||||
- prometheus-certs:/run/certs:ro
|
||||
- prometheus-data:/prometheus
|
||||
networks: [telemetry]
|
||||
depends_on:
|
||||
certs-init:
|
||||
condition: service_completed_successfully
|
||||
|
||||
loki:
|
||||
image: grafana/loki:3.3.2
|
||||
<<: *service-hardening
|
||||
command: ["-config.file=/etc/loki/config.yaml"]
|
||||
volumes:
|
||||
- ./infra/otel/loki.yaml:/etc/loki/config.yaml:ro
|
||||
- loki-certs:/run/certs:ro
|
||||
- loki-data:/loki
|
||||
networks: [telemetry]
|
||||
depends_on:
|
||||
certs-init:
|
||||
condition: service_completed_successfully
|
||||
|
||||
tempo:
|
||||
image: grafana/tempo:2.7.1
|
||||
<<: *service-hardening
|
||||
command: ["-config.file=/etc/tempo/config.yaml"]
|
||||
volumes:
|
||||
- ./infra/otel/tempo.yaml:/etc/tempo/config.yaml:ro
|
||||
- tempo-certs:/run/certs:ro
|
||||
- tempo-data:/var/tempo
|
||||
networks: [telemetry]
|
||||
depends_on:
|
||||
certs-init:
|
||||
condition: service_completed_successfully
|
||||
|
||||
grafana:
|
||||
image: grafana/grafana:11.4.0
|
||||
<<: *service-hardening
|
||||
environment:
|
||||
GF_SERVER_PROTOCOL: https
|
||||
GF_SERVER_HTTP_PORT: "3000"
|
||||
GF_SERVER_CERT_FILE: /run/certs/server.crt
|
||||
GF_SERVER_CERT_KEY: /run/certs/server.key
|
||||
GF_SERVER_ROOT_URL: https://localhost:8443/grafana/
|
||||
GF_SERVER_SERVE_FROM_SUB_PATH: "true"
|
||||
GF_SECURITY_ADMIN_USER: ${GRAFANA_ADMIN_USER:?run make bootstrap first}
|
||||
GF_SECURITY_ADMIN_PASSWORD: ${GRAFANA_ADMIN_PASSWORD:?run make bootstrap first}
|
||||
GF_USERS_ALLOW_SIGN_UP: "false"
|
||||
volumes:
|
||||
- grafana-certs:/run/certs:ro
|
||||
- grafana-data:/var/lib/grafana
|
||||
- ./infra/otel/grafana-datasources.yaml:/etc/grafana/provisioning/datasources/datasources.yaml:ro
|
||||
- ./infra/otel/grafana-dashboards.yaml:/etc/grafana/provisioning/dashboards/dashboards.yaml:ro
|
||||
- ./infra/otel/dashboards:/var/lib/grafana/dashboards:ro
|
||||
networks: [telemetry]
|
||||
depends_on:
|
||||
prometheus:
|
||||
condition: service_started
|
||||
loki:
|
||||
condition: service_started
|
||||
tempo:
|
||||
condition: service_started
|
||||
certs-init:
|
||||
condition: service_completed_successfully
|
||||
|
||||
networks:
|
||||
services:
|
||||
internal: true
|
||||
telemetry:
|
||||
internal: true
|
||||
host-ingress:
|
||||
internal: false
|
||||
|
||||
volumes:
|
||||
postgres-data:
|
||||
s3-data:
|
||||
rabbit-data:
|
||||
openbao-data:
|
||||
prometheus-data:
|
||||
loki-data:
|
||||
tempo-data:
|
||||
grafana-data:
|
||||
ingress-certs:
|
||||
api-certs:
|
||||
worker-certs:
|
||||
postgres-certs:
|
||||
s3-certs:
|
||||
rabbit-certs:
|
||||
openbao-certs:
|
||||
collector-certs:
|
||||
prometheus-certs:
|
||||
loki-certs:
|
||||
tempo-certs:
|
||||
grafana-certs:
|
||||
mc-ca:
|
||||
postgres-secrets:
|
||||
mtls-test-certs:
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
# Семантика API
|
||||
|
||||
Этот текст дополняет [openapi.json](openapi.json). Обязательный API соответствует уровню 3 текущей лабораторной. Факультативный crop или rate limiting не становятся обязательными только из-за наличия допустимого имени варианта или кода ошибки в схеме.
|
||||
Этот текст дополняет [openapi.json](openapi.json). Для lab7 обязателен весь набор требований из README. Rate limiting также обязателен: ответы `429 rate_limited` содержат `Retry-After` в секундах. Имена дополнительных кодов ошибок в схеме не требуют реализовать факультативную причину их выдачи.
|
||||
|
||||
## Формат и ошибки
|
||||
|
||||
@@ -56,6 +56,6 @@ Basic — это кодирование, не шифрование. HTTP lab1–
|
||||
|
||||
До 202 все байты приняты в **устойчивый staging**, а намерение обработать файл надёжно сохранено. HTTP-передача клиента не исчезает и не становится мгновенной. Staging — приватный S3-prefix либо общий persistent volume, доступный worker; локальная память/API ephemeral disk не подходит. Worker асинхронно переносит/публикует оригинал в конечный S3-prefix и создаёт варианты; если staging уже в S3, опишите эту границу честно.
|
||||
|
||||
Обязательный thumbnail: JPEG, изображение вписано в 256×256 с сохранением пропорций, без увеличения маленьких исходников, EXIF orientation применяется; alpha компонуется на белый. Размеры округляются вниз, минимум 1 px. Fixture 320×200 должен дать 256×160. Статус ready ставится после сохранения оригинала и thumbnail. Crop на 4: JPEG, центрированный квадрат 128×128 (для маленьких исходников допускается увеличение). Optimized на 4: WebP, вписан в 1280×1280 без увеличения, параметры качества и удаления EXIF документируются; не обещайте уменьшение каждого маленького файла.
|
||||
Обязательный thumbnail: JPEG, изображение вписано в 256×256 с сохранением пропорций, без увеличения маленьких исходников, EXIF orientation применяется; alpha компонуется на белый. Размеры округляются вниз, минимум 1 px. Fixture 320×200 должен дать 256×160. Статус ready ставится после сохранения оригинала и thumbnail.
|
||||
|
||||
Допустимые состояния и события описаны в `jobs.schema.json` и `attachment-states.md`. Доставка — at least once; обработка идемпотентна, повторы не размножают варианты. Финальные ошибки наблюдаемы, бесконечный немой retry недопустим. Обязательный smoke ждёт ready до 60 секунд; это бюджет локального smoke для одного файла при свободном worker, не универсальный production SLA. В очередь идут ссылки/ID, не бинарное содержимое.
|
||||
|
||||
@@ -7,14 +7,13 @@
|
||||
| нет → queued | Принимаем upload; только после durable handoff отвечаем 202 | Полный проверенный оригинал в staging, метаданные, намерение обработки |
|
||||
| queued → processing | Worker захватил/арендовал работу | Попытка, lease/deadline или эквивалентная защита |
|
||||
| processing → queued | Временная ошибка и остались попытки | Причина без секретов, время следующей попытки |
|
||||
| processing → ready | Все обязательные объекты записаны и результат атомарно опубликован | Оригинал, thumbnail (на 4 ещё crop/optimized), метаданные/checksums |
|
||||
| processing → ready | Все обязательные объекты записаны и результат атомарно опубликован | Оригинал, thumbnail, метаданные/checksums |
|
||||
| processing → failed | Ошибка постоянная или попытки исчерпаны | error_code и запись, доступная оператору |
|
||||
| processing → queued | Истёк lease после смерти worker | Восстановленная работа, без дублирования эффектов |
|
||||
| failed → queued | Явный операторский replay, доступен на 4 | Audit, новая попытка, прежний логический эффект защищён от дубля |
|
||||
|
||||
Повторная доставка уже ready-задачи — no-op с ack после проверки завершённого эффекта. Конкурентные попытки не перезаписывают более новый pipeline_version. Основной курс использует pipeline_version=1; версионирование нескольких pipeline — трек 5. Заявляйте готовность только когда все обещанные уровнем варианты доступны. Нельзя откатывать ready в processing из-за старого дубля.
|
||||
Повторная доставка уже ready-задачи — no-op с ack после проверки завершённого эффекта. Конкурентные попытки не перезаписывают результат. Используется pipeline_version=1. Заявляйте готовность только когда оригинал, thumbnail и метаданные доступны. Нельзя откатывать ready в processing из-за старого дубля.
|
||||
|
||||
**Окна отказа для защиты:** после staging до записи задания; после COMMIT до publish; после publish до confirm; после записи S3 до COMMIT результата; после COMMIT результата до ack. На 3 покажите сохранность успешно принятой работы и повторную доставку; на 4 автоматическое восстановление разрыва DB/broker (outbox/эквивалент) и зависшего processing.
|
||||
**Окна отказа для защиты:** после staging до записи задания; после COMMIT до publish; после publish до confirm; после записи S3 до COMMIT результата; после COMMIT результата до ack. Покажите сохранность успешно принятой работы и безопасную повторную доставку.
|
||||
|
||||
Staging не удаляется до безопасной публикации результатов. Неуспешные/непривязанные исходники имеют документированный retention и cleanup; он не удаляет текущую работу. Broker принимает только ID/служебные данные, не произвольный URL для скачивания и не путь из клиентского filename. Worker берёт доверенные storage metadata из БД.
|
||||
|
||||
|
||||
@@ -77,13 +77,6 @@
|
||||
"service_scoped_policies": true
|
||||
}
|
||||
],
|
||||
"optional_components": [
|
||||
{
|
||||
"role": "redis_or_valkey",
|
||||
"required_for_lab2_grade4": true,
|
||||
"note": "Choose one; if only store of sessions, configure durable persistence."
|
||||
}
|
||||
],
|
||||
"rules": [
|
||||
"Choose Compose or Swarm for lab3+; do not need both.",
|
||||
"Never publish internal API replica ports in bypass of LB from lab3.",
|
||||
|
||||
@@ -2,18 +2,14 @@
|
||||
|
||||
Ниже логические сигналы. Допустимы стандартные semantic conventions выбранного SDK и их native metric names: зафиксируйте соответствие в `REPORT.md`, dashboard обязан ссылаться на реально существующие имена/единицы. Переименование SDK не повод дублировать одну метрику двумя инструментами. Версии SDK, semantic conventions, Collector distribution и backend закрепляются в решении.
|
||||
|
||||
| Сигнал | Минимальные поля/измерения | Уровень |
|
||||
| --- | --- | --- |
|
||||
| HTTP requests | method, route template, status class; counter | 3 |
|
||||
| HTTP duration | histogram в секундах или документированное преобразование из ms | 3 |
|
||||
| Jobs processed / failed | job type, outcome, counter | 3 |
|
||||
| Job processing duration | job type, outcome, histogram | 3 |
|
||||
| API и worker logs | timestamp, severity, service.name, event, trace_id, span_id при активном span | 3 |
|
||||
| API и worker traces | реальные server/consumer spans, duration, outcome; не искусственный статический trace | 3 |
|
||||
| Queue depth / oldest job age | queue name, количество / секунды | 4 |
|
||||
| Pool/saturation | DB pool used/waiting, worker busy/capacity, process/container CPU/RAM | 4 |
|
||||
| Сквозная связь upload → publish → consume → S3/DB | W3C traceparent/tracestate; parent-child или link по выбранной семантике | 4 |
|
||||
| End-to-end time to ready | от durable acceptance до публикации ready, histogram | 4 |
|
||||
| Сигнал | Минимальные поля/измерения |
|
||||
| --- | --- |
|
||||
| HTTP requests | method, route template, status class; counter |
|
||||
| HTTP duration | histogram в секундах или документированное преобразование из ms |
|
||||
| Jobs processed / failed | job type, outcome, counter |
|
||||
| Job processing duration | job type, outcome, histogram |
|
||||
| API и worker logs | timestamp, severity, service.name, event, trace_id, span_id при активном span |
|
||||
| API и worker traces | реальные server/consumer spans, duration, outcome; не искусственный статический trace |
|
||||
|
||||
Resource attributes: `service.name` (messenger-api / messenger-worker), `service.version`, `service.instance.id`, `deployment.environment.name=lab`. Список имён может отличаться, если явно сопоставлен. `X-Request-Id` коррелирует HTTP-ошибку с логом; trace_id — не замена всех request IDs.
|
||||
|
||||
@@ -21,8 +17,4 @@ Resource attributes: `service.name` (messenger-api / messenger-worker), `service
|
||||
|
||||
Для HTTP error ratio заранее определите numerator/denominator: например 5xx/все бизнес-запросы, исключая health; не смешивайте неверный пароль клиента с отказом БД. p95 агрегируется из histogram buckets всех нужных реплик, а не средних p95. Границы buckets должны соответствовать ожидаемым задержкам. Backlog — не queue processing latency.
|
||||
|
||||
В Git находятся Collector config, backend configs, datasources/dashboard provisioning, dashboard JSON и на 4 alert rules. У alerts есть условие, окно, порог, `for` при необходимости, описание и локальный runbook. Отправка сообщений в почту/мессенджер не требуется.
|
||||
|
||||
Минимальные контролируемые инциденты для 4: (1) остановить worker и увидеть рост возраста задач; (2) сделать DB медленной/недоступной и отличить её от медленного HTTP handler по trace/метрикам. После восстановления backlog уменьшается, alerts resolved. Третий сценарий — недоступность backend telemetry: SDK/Collector ограничивают RAM/очередь, API сохраняет работу, потери telemetry считаются и объясняются.
|
||||
|
||||
Collector — получатель/обработчик/экспортёр, не долговременная БД. Grafana — интерфейс и запросы к источникам. Логи можно отправлять OTLP в совместимый backend; не закладывайте удалённый/устаревший exporter без проверки текущей сборки. См. [Collector configuration](https://opentelemetry.io/docs/collector/configuration/), [Trace Context](https://www.w3.org/TR/trace-context/) и [histograms](https://prometheus.io/docs/practices/histograms/).
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
"info": {
|
||||
"title": "MTUSI Messenger — лабораторная 7",
|
||||
"version": "1.7.0",
|
||||
"description": "Нормативный минимум на 3. Семантика: contracts/README.md. Расширения на 4/5 не должны менять этот API. Наличие кода ошибки в схеме не требует реализовать факультативную причину его выдачи."
|
||||
"description": "Обязательный контракт лабораторной 7. Семантика: contracts/README.md. Наличие кода ошибки в схеме не требует реализовать факультативную причину его выдачи."
|
||||
},
|
||||
"servers": [
|
||||
{
|
||||
@@ -2937,9 +2937,7 @@
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"original",
|
||||
"thumbnail",
|
||||
"crop",
|
||||
"optimized"
|
||||
"thumbnail"
|
||||
],
|
||||
"default": "original"
|
||||
}
|
||||
@@ -3385,9 +3383,7 @@
|
||||
"name": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"thumbnail",
|
||||
"crop",
|
||||
"optimized"
|
||||
"thumbnail"
|
||||
]
|
||||
},
|
||||
"content_type": {
|
||||
|
||||
+17
-18
@@ -2,20 +2,20 @@
|
||||
|
||||
Это обязательная матрица покрытия. Для каждой строки укажите реальный порт, endpoint, CA, service identity, проверку SAN/ACL, срок жизни credentials и команду положительного/отрицательного теста. TLS шифрует и подтверждает сервер; mTLS также проверяет клиента. При доверенном CA всё равно нужно ограничивать разрешённую identity. Plaintext hop допустим только внутри закрытого локального transport/proxy boundary, без опубликованного обхода; границу и rationale нужно доказать.
|
||||
|
||||
| Связь | Минимум на 3 | Дополнительно на 4 | Доказательство / конфиг |
|
||||
| --- | --- | --- | --- |
|
||||
| Клиент → ingress/LB | TLS, CA + hostname, Bearer | Проверка expiry/revocation сессии и общего login rate limit | TODO |
|
||||
| LB → API (все реплики) | mTLS + allowlist LB identity | Ротация leaf без обхода проверки | TODO |
|
||||
| API/worker → PostgreSQL | TLS verify-full + раздельные ограниченные DB roles | Ротация credentials; mTLS — допустимое усиление | TODO |
|
||||
| API/worker → S3 | TLS + разные scoped credentials/prefix rights | Проверка denied prefix и ротация | TODO |
|
||||
| API/worker → broker | TLS + разные producer/consumer identities и ACL | mTLS + ограничение допустимых SAN/ролей | TODO |
|
||||
| API/worker → Collector | TLS; сеть/аутентификация запрещает произвольный ingest | mTLS с раздельными identities | TODO |
|
||||
| Collector → telemetry backends | TLS + scoped backend credentials или mTLS | Ротация и проверка least privilege | TODO |
|
||||
| Grafana → data sources | TLS с проверкой сервера, ограниченная identity | Отрицательные проверки доступа | TODO |
|
||||
| API/worker/agent → OpenBao | TLS + сервисный auth + scoped policy | Renewal/expiry/revocation | TODO |
|
||||
| Оператор → OpenBao/Grafana/S3 admin | TLS + authentication, доступ локальный/через защищённый канал | Разделение operator/application roles | TODO |
|
||||
| API → Redis/Valkey, если используется | TLS + ACL/пароль с минимальными правами | Ротация; mTLS по возможности | TODO |
|
||||
| Replication/кластерные каналы, если добавлены | TLS/mTLS либо подтверждённый шифрованный transport | Проверка заявленной модели отказа | TODO |
|
||||
| Связь | Обязательное требование | Доказательство / конфиг |
|
||||
| --- | --- | --- |
|
||||
| Клиент → ingress/LB | TLS, проверка CA и hostname, Bearer | TODO |
|
||||
| LB → API (все реплики) | mTLS и allowlist LB identity | TODO |
|
||||
| API/worker → PostgreSQL | TLS с проверкой сервера, раздельные ограниченные DB roles | TODO |
|
||||
| API/worker → S3 | TLS с проверкой сервера, scoped credentials/prefix rights | TODO |
|
||||
| API/worker → broker | TLS с проверкой сервера, раздельные identities; API публикует в `attachment.jobs` через `amq.default`, worker читает очередь и публикует retries через `amq.default` | TODO |
|
||||
| API/worker → Collector | TLS с проверкой сервера и ограничением допустимых отправителей | TODO |
|
||||
| Collector → telemetry backends | TLS с проверкой сервера и ограниченными credentials | TODO |
|
||||
| Grafana → data sources | TLS с проверкой сервера и ограниченной identity | TODO |
|
||||
| API/worker → OpenBao | TLS, service authentication и scoped policy | TODO |
|
||||
| Оператор → OpenBao/Grafana/S3 admin | TLS + authentication, доступ локальный/через защищённый канал | TODO |
|
||||
| API → Redis/Valkey, если используется | TLS + ACL/пароль с минимальными правами | TODO |
|
||||
| Replication/кластерные каналы, если используются | TLS с проверкой сервера и client identity, где это поддерживается | TODO |
|
||||
|
||||
Нет выбранного компонента — отметьте N/A с причиной, а не оставляйте пустую строку. Внутренний публичный health listener, если нужен, минимален и изолирован; через него нельзя обращаться к бизнес-API без mTLS. Отдельно задокументируйте scrape/health/bootstrap каналы: они тоже не должны создавать обход.
|
||||
|
||||
@@ -23,10 +23,9 @@
|
||||
|
||||
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. Покажите новое подключение, иначе тест отзыва может ничего не проверить.
|
||||
3. Пользователь вне чата не читает metadata/content и не прикрепляет чужой файл; поддельный X-User-Id не меняет Bearer identity.
|
||||
4. OpenBao app policy читает только свой secret/path; запись policy и чтение чужого path запрещены. Worker не получает admin credentials API/БД/S3.
|
||||
5. Зафиксируйте 429/Retry-After при превышении лимита, отказ для запроса выше допустимого размера, logout/expiry и проверку TLS с недоверенным CA.
|
||||
|
||||
## Bootstrap и эксплуатация
|
||||
|
||||
|
||||
Executable
+75
@@ -0,0 +1,75 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
for directory in /certs/ingress /certs/api /certs/worker /certs/postgres \
|
||||
/certs/postgres-secrets /certs/s3 /certs/mc-ca /certs/mtls-test \
|
||||
/certs/rabbit /certs/openbao /certs/collector /certs/prometheus \
|
||||
/certs/loki /certs/tempo /certs/grafana; do
|
||||
find "$directory" -type f -exec chown 0:0 {} \;
|
||||
find "$directory" -type f -exec chmod 0644 {} \;
|
||||
find "$directory" -type d -exec chmod 0755 {} \;
|
||||
done
|
||||
|
||||
copy_server() {
|
||||
name=$1
|
||||
target=$2
|
||||
mkdir -p "$target"
|
||||
cp "/source/$name/ca.crt" "$target/ca.crt"
|
||||
cp "/source/$name/server.crt" "$target/server.crt"
|
||||
cp "/source/$name/server.key" "$target/server.key"
|
||||
}
|
||||
|
||||
for name in ingress api postgres s3 rabbit openbao collector prometheus loki tempo grafana; do
|
||||
copy_server "$name" "/certs/$name"
|
||||
done
|
||||
|
||||
cp /source/ingress/client.crt /certs/ingress/client.crt
|
||||
cp /source/ingress/client.key /certs/ingress/client.key
|
||||
cp /source/api/client.crt /certs/api/client.crt
|
||||
cp /source/api/client.key /certs/api/client.key
|
||||
cp /source/worker/client.crt /certs/worker/client.crt
|
||||
cp /source/worker/client.key /certs/worker/client.key
|
||||
cp /source/worker/ca.crt /certs/worker/ca.crt
|
||||
|
||||
mkdir -p /certs/s3/CAs
|
||||
cp /certs/s3/server.crt /certs/s3/public.crt
|
||||
cp /certs/s3/server.key /certs/s3/private.key
|
||||
cp /certs/s3/ca.crt /certs/s3/CAs/ca.crt
|
||||
chmod 0755 /certs/s3/CAs
|
||||
mkdir -p /certs/mc-ca
|
||||
cp /certs/s3/ca.crt /certs/mc-ca/ca.crt
|
||||
mkdir -p /certs/mtls-test
|
||||
cp /source-test-pki/ca.crt /certs/mtls-test/ca.crt
|
||||
cp /source-test-pki/lb-client.crt /certs/mtls-test/lb-client.crt
|
||||
cp /source-test-pki/lb-client.key /certs/mtls-test/lb-client.key
|
||||
cp /source-test-pki/worker-client.crt /certs/mtls-test/worker-client.crt
|
||||
cp /source-test-pki/worker-client.key /certs/mtls-test/worker-client.key
|
||||
cp /source-test-pki/foreign-ca.crt /certs/mtls-test/foreign-ca.crt
|
||||
cp /source-test-pki/foreign-client.crt /certs/mtls-test/foreign-client.crt
|
||||
cp /source-test-pki/foreign-client.key /certs/mtls-test/foreign-client.key
|
||||
cp /source-secrets/api_db_password /certs/postgres-secrets/api_db_password
|
||||
cp /source-secrets/worker_db_password /certs/postgres-secrets/worker_db_password
|
||||
|
||||
for directory in /certs/ingress /certs/api /certs/worker /certs/postgres \
|
||||
/certs/postgres-secrets /certs/s3 /certs/mc-ca /certs/mtls-test \
|
||||
/certs/rabbit /certs/openbao /certs/collector /certs/prometheus \
|
||||
/certs/loki /certs/tempo /certs/grafana; do
|
||||
find "$directory" -type f -exec chmod 0444 {} \;
|
||||
find "$directory" -type d -exec chmod 0555 {} \;
|
||||
done
|
||||
|
||||
chmod 0400 /certs/s3/server.key /certs/s3/private.key
|
||||
chown 1001:1001 /certs/s3/server.key /certs/s3/private.key
|
||||
chmod 0400 /certs/api/server.key /certs/api/client.key
|
||||
chown 10001:10001 /certs/api/server.key /certs/api/client.key
|
||||
chmod 0400 /certs/worker/client.key
|
||||
chown 10001:10001 /certs/worker/client.key
|
||||
chmod 0400 /certs/mtls-test/lb-client.key \
|
||||
/certs/mtls-test/worker-client.key /certs/mtls-test/foreign-client.key
|
||||
chown 10001:10001 /certs/mtls-test/lb-client.key \
|
||||
/certs/mtls-test/worker-client.key /certs/mtls-test/foreign-client.key
|
||||
chmod 0600 /certs/postgres/server.key
|
||||
chown 70:70 /certs/postgres/server.key
|
||||
|
||||
chmod 0400 /certs/postgres-secrets/api_db_password /certs/postgres-secrets/worker_db_password
|
||||
chown 70:70 /certs/postgres-secrets/api_db_password /certs/postgres-secrets/worker_db_password
|
||||
@@ -0,0 +1,60 @@
|
||||
events {}
|
||||
|
||||
http {
|
||||
upstream messenger_api {
|
||||
least_conn;
|
||||
server api-1:8443 max_fails=3 fail_timeout=5s;
|
||||
server api-2:8443 max_fails=3 fail_timeout=5s;
|
||||
keepalive 16;
|
||||
}
|
||||
|
||||
server {
|
||||
listen 8443 ssl;
|
||||
server_name localhost;
|
||||
|
||||
ssl_certificate /run/pki/server.crt;
|
||||
ssl_certificate_key /run/pki/server.key;
|
||||
ssl_protocols TLSv1.2 TLSv1.3;
|
||||
ssl_session_tickets off;
|
||||
ssl_session_cache shared:TLS:10m;
|
||||
|
||||
client_max_body_size 11m;
|
||||
client_body_timeout 15s;
|
||||
send_timeout 30s;
|
||||
|
||||
location = /grafana {
|
||||
return 308 /grafana/;
|
||||
}
|
||||
|
||||
location /grafana/ {
|
||||
proxy_pass https://grafana:3000;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Forwarded-Proto https;
|
||||
proxy_set_header X-Forwarded-Prefix /grafana;
|
||||
|
||||
proxy_ssl_server_name on;
|
||||
proxy_ssl_name grafana;
|
||||
proxy_ssl_verify on;
|
||||
proxy_ssl_verify_depth 2;
|
||||
proxy_ssl_trusted_certificate /run/grafana-certs/ca.crt;
|
||||
}
|
||||
|
||||
location / {
|
||||
proxy_pass https://messenger_api;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Connection "";
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Forwarded-Proto https;
|
||||
proxy_set_header X-Forwarded-For $remote_addr;
|
||||
|
||||
proxy_ssl_server_name on;
|
||||
proxy_ssl_name api;
|
||||
proxy_ssl_verify on;
|
||||
proxy_ssl_verify_depth 2;
|
||||
proxy_ssl_trusted_certificate /run/pki/ca.crt;
|
||||
proxy_ssl_certificate /run/pki/client.crt;
|
||||
proxy_ssl_certificate_key /run/pki/client.key;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
# OpenBao — реализовать конфигурацию и политики
|
||||
|
||||
Добавьте non-dev конфигурацию listener/storage/TLS, API/worker policies, bootstrap и rotation scripts. Credentials и unseal material создаются локально; здесь нет готового root token или private key.
|
||||
Добавьте non-dev конфигурацию listener/storage/TLS, API/worker policies и документированный bootstrap. Credentials и unseal material создаются локально; здесь нет готового root token или private key.
|
||||
|
||||
Решение должно показать реальную сервисную аутентификацию и получение нужного secret по ограниченной policy; просто работающий контейнер OpenBao не засчитывается. На 3 статический KV secret допустим. На 4 покажите expiry/renewal/rotation и allow/deny. Путь KV v2 data/metadata и ACL должен соответствовать фактическому mount; не копируйте широкое `path "*"` для приложения.
|
||||
Решение должно показать реальную сервисную аутентификацию и получение нужного secret по ограниченной policy; просто работающий контейнер OpenBao не засчитывается. Статический KV secret допустим. Путь KV v2 data/metadata и ACL должен соответствовать фактическому mount; не копируйте широкое `path "*"` для приложения.
|
||||
|
||||
Документируйте шаги оператора init/unseal и восстановление после restart. Скрипт не должен печатать tokens/shares или хранить их в Git. См. contracts/trust-matrix.md и REPORT.md.
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
ui = false
|
||||
listener "tcp" {
|
||||
address = "0.0.0.0:8200"
|
||||
cluster_address = "0.0.0.0:8201"
|
||||
tls_disable = false
|
||||
tls_cert_file = "/run/pki/server.crt"
|
||||
tls_key_file = "/run/pki/server.key"
|
||||
tls_min_version = "tls12"
|
||||
}
|
||||
|
||||
storage "raft" {
|
||||
path = "/openbao/file"
|
||||
node_id = "lab7-openbao-1"
|
||||
}
|
||||
|
||||
api_addr = "https://openbao:8200"
|
||||
cluster_addr = "https://openbao:8201"
|
||||
@@ -0,0 +1,168 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Operator-only OpenBao bootstrap; this container is never used by the app."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import ssl
|
||||
import sys
|
||||
import time
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
ADDRESS = os.environ.get("OPENBAO_ADDR", "https://openbao:8200").rstrip("/")
|
||||
CA_FILE = os.environ.get("OPENBAO_CACERT", "/run/certs/ca.crt")
|
||||
OPERATOR_FILE = Path("/run/operator/openbao-operator.json")
|
||||
APPROLE_DIR = Path("/output/approle")
|
||||
|
||||
|
||||
class BaoClient:
|
||||
def __init__(self, token=None):
|
||||
self.token = token
|
||||
self.context = ssl.create_default_context(cafile=CA_FILE)
|
||||
self.context.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||
|
||||
def request(self, method, path, body=None, allow_status=()):
|
||||
data = json.dumps(body).encode("utf-8") if body is not None else None
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if self.token:
|
||||
headers["X-Vault-Token"] = self.token
|
||||
request = Request(ADDRESS + "/v1/" + path.lstrip("/"), data=data, headers=headers, method=method)
|
||||
try:
|
||||
with urlopen(request, context=self.context, timeout=10) as response:
|
||||
payload = response.read()
|
||||
return json.loads(payload) if payload else {}
|
||||
except HTTPError as exc:
|
||||
if exc.code in allow_status:
|
||||
return {}
|
||||
raise RuntimeError(f"OpenBao API rejected {method} {path} (HTTP {exc.code})") from None
|
||||
except URLError as exc:
|
||||
raise RuntimeError(f"OpenBao TLS connection failed ({type(exc.reason).__name__})") from None
|
||||
|
||||
|
||||
def wait_for_openbao(client):
|
||||
for _ in range(60):
|
||||
try:
|
||||
client.request("GET", "sys/health", allow_status=(501, 503, 530))
|
||||
return
|
||||
except RuntimeError:
|
||||
time.sleep(2)
|
||||
raise RuntimeError("OpenBao did not become reachable over verified TLS")
|
||||
|
||||
|
||||
def create_role(client, name, policy, secret_path, secret_values):
|
||||
policy_text = f'path "{secret_path}" {{ capabilities = ["read"] }}\n'
|
||||
client.request("PUT", f"sys/policies/acl/{policy}", {"policy": policy_text})
|
||||
|
||||
role_path = f"auth/approle/role/{name}"
|
||||
client.request(
|
||||
"POST",
|
||||
role_path,
|
||||
{
|
||||
"token_policies": [policy],
|
||||
"token_ttl": "1h",
|
||||
"token_max_ttl": "4h",
|
||||
"secret_id_ttl": "720h",
|
||||
"secret_id_num_uses": 0,
|
||||
"bind_secret_id": True,
|
||||
},
|
||||
)
|
||||
role_id = client.request("GET", role_path + "/role-id")["data"]["role_id"]
|
||||
secret_id = client.request("POST", role_path + "/secret-id", {})["data"]["secret_id"]
|
||||
client.request(
|
||||
"POST",
|
||||
secret_path,
|
||||
{"data": secret_values},
|
||||
)
|
||||
|
||||
target = APPROLE_DIR / name.removeprefix("messenger-")
|
||||
target.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
os.chown(target, 10001, 10001)
|
||||
target.chmod(0o500)
|
||||
for filename, value in (("role_id", role_id), ("secret_id", secret_id)):
|
||||
file_path = target / filename
|
||||
file_path.write_text(value + "\n", encoding="utf-8")
|
||||
os.chown(file_path, 10001, 10001)
|
||||
file_path.chmod(0o400)
|
||||
|
||||
|
||||
def main():
|
||||
if not Path(CA_FILE).is_file() or not OPERATOR_FILE.is_file():
|
||||
raise RuntimeError("OpenBao CA or operator bootstrap material is missing")
|
||||
material = json.loads(OPERATOR_FILE.read_text(encoding="utf-8"))
|
||||
key = material["unseal_keys_b64"][0]
|
||||
root_token = material["root_token"]
|
||||
anonymous = BaoClient()
|
||||
wait_for_openbao(anonymous)
|
||||
anonymous.request("POST", "sys/unseal", {"key": key})
|
||||
|
||||
client = BaoClient(root_token)
|
||||
health = client.request("GET", "sys/health", allow_status=(501, 503, 530))
|
||||
if health.get("sealed") or not health.get("initialized"):
|
||||
raise RuntimeError("OpenBao did not reach initialized, unsealed state")
|
||||
|
||||
mounts = client.request("GET", "sys/mounts")
|
||||
if "secret/" not in mounts:
|
||||
client.request(
|
||||
"POST",
|
||||
"sys/mounts/secret",
|
||||
{"type": "kv", "options": {"version": "2"}},
|
||||
)
|
||||
else:
|
||||
options = mounts["secret/"].get("options", {})
|
||||
if options.get("version") != "2":
|
||||
raise RuntimeError("OpenBao secret/ mount exists but is not KV v2")
|
||||
|
||||
auth = client.request("GET", "sys/auth")
|
||||
if "approle/" not in auth:
|
||||
client.request("POST", "sys/auth/approle", {"type": "approle"})
|
||||
|
||||
api_values = {
|
||||
"database_url": (
|
||||
"postgresql://messenger_api:"
|
||||
+ os.environ["POSTGRES_API_PASSWORD"]
|
||||
+ "@postgres:5432/messenger"
|
||||
),
|
||||
"broker_url": (
|
||||
"amqps://messenger_api:"
|
||||
+ os.environ["RABBITMQ_API_PASSWORD"]
|
||||
+ "@rabbitmq:5671/messenger"
|
||||
),
|
||||
"s3_access_key": os.environ["S3_API_ACCESS_KEY"],
|
||||
"s3_secret_key": os.environ["S3_API_SECRET_KEY"],
|
||||
}
|
||||
worker_values = {
|
||||
"database_url": (
|
||||
"postgresql://messenger_worker:"
|
||||
+ os.environ["POSTGRES_WORKER_PASSWORD"]
|
||||
+ "@postgres:5432/messenger"
|
||||
),
|
||||
"broker_url": (
|
||||
"amqps://messenger_worker:"
|
||||
+ os.environ["RABBITMQ_WORKER_PASSWORD"]
|
||||
+ "@rabbitmq:5671/messenger"
|
||||
),
|
||||
"s3_access_key": os.environ["S3_WORKER_ACCESS_KEY"],
|
||||
"s3_secret_key": os.environ["S3_WORKER_SECRET_KEY"],
|
||||
}
|
||||
create_role(
|
||||
client,
|
||||
"messenger-api",
|
||||
"messenger-api",
|
||||
"secret/data/messenger/api",
|
||||
api_values,
|
||||
)
|
||||
create_role(
|
||||
client,
|
||||
"messenger-worker",
|
||||
"messenger-worker",
|
||||
"secret/data/messenger/worker",
|
||||
worker_values,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except (KeyError, OSError, ValueError, RuntimeError) as exc:
|
||||
print(f"ERROR: {exc}", file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
@@ -1,7 +1,7 @@
|
||||
# Конфигурация наблюдаемости — реализовать
|
||||
|
||||
Добавьте `collector.yaml` с OTLP receivers, processors и exporters выбранной версии Collector. Укажите явные bind endpoints, внутренние сети, memory limits/batch и поведение при backpressure по уровню. Сопоставьте все три pipeline с реально развёрнутыми backend.
|
||||
Добавьте `collector.yaml` с OTLP receivers, processors и exporters выбранной версии Collector. Укажите явные bind endpoints, внутренние сети, memory limits/batch и поведение при backpressure. Сопоставьте все три pipeline с реально развёрнутыми backend.
|
||||
|
||||
Добавьте конфигурации storage, Grafana provisioning/datasources, provisioning/dashboards и импортируемые dashboard JSON. На 4 — alert rules и runbooks. Пустой dashboard или debug exporter, который только печатает данные в stdout, не заменяют хранилища/доказательства из `contracts/observability.md`.
|
||||
Добавьте конфигурации storage, Grafana provisioning/datasources, provisioning/dashboards и импортируемые dashboard JSON. Пустой dashboard или debug exporter, который только печатает данные в stdout, не заменяют хранилища/доказательства из `contracts/observability.md`.
|
||||
|
||||
Не публикуйте OTLP/metrics/административные ports в общую сеть без необходимости. В lab7 реализуйте TLS/mTLS по trust matrix; экспорт Authorization и message bodies запрещён.
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
extensions:
|
||||
health_check:
|
||||
endpoint: 0.0.0.0:13133
|
||||
tls:
|
||||
cert_file: /run/certs/server.crt
|
||||
key_file: /run/certs/server.key
|
||||
client_ca_file: /run/certs/ca.crt
|
||||
|
||||
receivers:
|
||||
otlp:
|
||||
protocols:
|
||||
grpc:
|
||||
endpoint: 0.0.0.0:4317
|
||||
tls:
|
||||
cert_file: /run/certs/server.crt
|
||||
key_file: /run/certs/server.key
|
||||
client_ca_file: /run/certs/ca.crt
|
||||
http:
|
||||
endpoint: 0.0.0.0:4318
|
||||
tls:
|
||||
cert_file: /run/certs/server.crt
|
||||
key_file: /run/certs/server.key
|
||||
client_ca_file: /run/certs/ca.crt
|
||||
|
||||
processors:
|
||||
memory_limiter:
|
||||
check_interval: 1s
|
||||
limit_mib: 256
|
||||
spike_limit_mib: 64
|
||||
batch:
|
||||
send_batch_size: 512
|
||||
timeout: 5s
|
||||
|
||||
exporters:
|
||||
otlp/tempo:
|
||||
endpoint: tempo:4317
|
||||
tls:
|
||||
ca_file: /run/certs/ca.crt
|
||||
otlphttp/loki:
|
||||
endpoint: https://loki:3100/otlp
|
||||
tls:
|
||||
ca_file: /run/certs/ca.crt
|
||||
prometheusremotewrite:
|
||||
endpoint: https://prometheus:9090/api/v1/write
|
||||
tls:
|
||||
ca_file: /run/certs/ca.crt
|
||||
|
||||
service:
|
||||
extensions: [health_check]
|
||||
pipelines:
|
||||
traces:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, batch]
|
||||
exporters: [otlp/tempo]
|
||||
metrics:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, batch]
|
||||
exporters: [prometheusremotewrite]
|
||||
logs:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, batch]
|
||||
exporters: [otlphttp/loki]
|
||||
@@ -0,0 +1,68 @@
|
||||
{
|
||||
"id": null,
|
||||
"uid": "lab7-stack-health",
|
||||
"title": "Lab 7 stack health",
|
||||
"tags": ["lab7"],
|
||||
"timezone": "browser",
|
||||
"schemaVersion": 39,
|
||||
"version": 1,
|
||||
"refresh": "30s",
|
||||
"time": {
|
||||
"from": "now-1h",
|
||||
"to": "now"
|
||||
},
|
||||
"panels": [
|
||||
{
|
||||
"id": 1,
|
||||
"type": "stat",
|
||||
"title": "Prometheus targets up",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prom-lab7"
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "sum(up)",
|
||||
"instant": true
|
||||
}
|
||||
],
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 0,
|
||||
"y": 0
|
||||
},
|
||||
"options": {
|
||||
"reduceOptions": {
|
||||
"values": false,
|
||||
"calcs": ["lastNotNull"],
|
||||
"fields": ""
|
||||
},
|
||||
"orientation": "auto",
|
||||
"textMode": "auto",
|
||||
"colorMode": "value",
|
||||
"graphMode": "area",
|
||||
"justifyMode": "auto"
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"thresholds": {
|
||||
"mode": "absolute",
|
||||
"steps": [
|
||||
{
|
||||
"color": "red",
|
||||
"value": null
|
||||
},
|
||||
{
|
||||
"color": "green",
|
||||
"value": 1
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
apiVersion: 1
|
||||
providers:
|
||||
- name: lab7
|
||||
orgId: 1
|
||||
folder: Lab 7
|
||||
type: file
|
||||
disableDeletion: true
|
||||
editable: false
|
||||
options:
|
||||
path: /var/lib/grafana/dashboards
|
||||
@@ -0,0 +1,39 @@
|
||||
apiVersion: 1
|
||||
datasources:
|
||||
- name: Prometheus
|
||||
uid: prom-lab7
|
||||
type: prometheus
|
||||
access: proxy
|
||||
url: https://prometheus:9090
|
||||
isDefault: true
|
||||
editable: false
|
||||
jsonData:
|
||||
tlsAuthWithCACert: true
|
||||
tlsSkipVerify: false
|
||||
serverName: prometheus
|
||||
secureJsonData:
|
||||
tlsCACert: "$__file{/run/certs/ca.crt}"
|
||||
- name: Loki
|
||||
uid: loki-lab7
|
||||
type: loki
|
||||
access: proxy
|
||||
url: https://loki:3100
|
||||
editable: false
|
||||
jsonData:
|
||||
tlsAuthWithCACert: true
|
||||
tlsSkipVerify: false
|
||||
serverName: loki
|
||||
secureJsonData:
|
||||
tlsCACert: "$__file{/run/certs/ca.crt}"
|
||||
- name: Tempo
|
||||
uid: tempo-lab7
|
||||
type: tempo
|
||||
access: proxy
|
||||
url: https://tempo:3200
|
||||
editable: false
|
||||
jsonData:
|
||||
tlsAuthWithCACert: true
|
||||
tlsSkipVerify: false
|
||||
serverName: tempo
|
||||
secureJsonData:
|
||||
tlsCACert: "$__file{/run/certs/ca.crt}"
|
||||
@@ -0,0 +1,39 @@
|
||||
auth_enabled: false
|
||||
|
||||
server:
|
||||
http_listen_address: 0.0.0.0
|
||||
http_listen_port: 3100
|
||||
http_tls_config:
|
||||
cert_file: /run/certs/server.crt
|
||||
key_file: /run/certs/server.key
|
||||
grpc_listen_port: 9096
|
||||
grpc_tls_config:
|
||||
cert_file: /run/certs/server.crt
|
||||
key_file: /run/certs/server.key
|
||||
|
||||
common:
|
||||
path_prefix: /loki
|
||||
replication_factor: 1
|
||||
ring:
|
||||
kvstore:
|
||||
store: inmemory
|
||||
storage:
|
||||
filesystem:
|
||||
chunks_directory: /loki/chunks
|
||||
rules_directory: /loki/rules
|
||||
|
||||
schema_config:
|
||||
configs:
|
||||
- from: 2024-01-01
|
||||
store: tsdb
|
||||
object_store: filesystem
|
||||
schema: v13
|
||||
index:
|
||||
prefix: index_
|
||||
period: 24h
|
||||
|
||||
limits_config:
|
||||
allow_structured_metadata: true
|
||||
|
||||
analytics:
|
||||
reporting_enabled: false
|
||||
@@ -0,0 +1,3 @@
|
||||
tls_server_config:
|
||||
cert_file: /run/certs/server.crt
|
||||
key_file: /run/certs/server.key
|
||||
@@ -0,0 +1,13 @@
|
||||
global:
|
||||
scrape_interval: 15s
|
||||
evaluation_interval: 15s
|
||||
|
||||
scrape_configs:
|
||||
- job_name: prometheus
|
||||
scheme: https
|
||||
static_configs:
|
||||
- targets: ["prometheus:9090"]
|
||||
tls_config:
|
||||
ca_file: /run/certs/ca.crt
|
||||
server_name: prometheus
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
server:
|
||||
http_listen_port: 3200
|
||||
http_tls_config:
|
||||
cert_file: /run/certs/server.crt
|
||||
key_file: /run/certs/server.key
|
||||
|
||||
distributor:
|
||||
receivers:
|
||||
otlp:
|
||||
protocols:
|
||||
grpc:
|
||||
endpoint: 0.0.0.0:4317
|
||||
tls:
|
||||
cert_file: /run/certs/server.crt
|
||||
key_file: /run/certs/server.key
|
||||
http:
|
||||
endpoint: 0.0.0.0:4318
|
||||
tls:
|
||||
cert_file: /run/certs/server.crt
|
||||
key_file: /run/certs/server.key
|
||||
|
||||
ingester:
|
||||
max_block_duration: 5m
|
||||
trace_idle_period: 10s
|
||||
|
||||
compactor:
|
||||
compaction:
|
||||
block_retention: 24h
|
||||
|
||||
storage:
|
||||
trace:
|
||||
backend: local
|
||||
wal:
|
||||
path: /var/tempo/wal
|
||||
local:
|
||||
path: /var/tempo/blocks
|
||||
@@ -0,0 +1,3 @@
|
||||
local all all scram-sha-256
|
||||
hostssl all all all scram-sha-256
|
||||
hostnossl all all all reject
|
||||
@@ -0,0 +1,12 @@
|
||||
SELECT format('CREATE ROLE messenger_api LOGIN PASSWORD %L', :'api_password')
|
||||
WHERE NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'messenger_api')
|
||||
\gexec
|
||||
SELECT format('ALTER ROLE messenger_api LOGIN PASSWORD %L', :'api_password')
|
||||
\gexec
|
||||
SELECT format('CREATE ROLE messenger_worker LOGIN PASSWORD %L', :'worker_password')
|
||||
WHERE NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'messenger_worker')
|
||||
\gexec
|
||||
SELECT format('ALTER ROLE messenger_worker LOGIN PASSWORD %L', :'worker_password')
|
||||
\gexec
|
||||
GRANT CONNECT ON DATABASE messenger TO messenger_api, messenger_worker;
|
||||
GRANT CREATE ON SCHEMA public TO messenger_api;
|
||||
Executable
+30
@@ -0,0 +1,30 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/../.." && pwd)
|
||||
set -a
|
||||
. "$ROOT/.env"
|
||||
set +a
|
||||
|
||||
compose() {
|
||||
docker compose exec -T rabbitmq rabbitmqctl "$@"
|
||||
}
|
||||
|
||||
ensure_user() {
|
||||
username=$1
|
||||
password=$2
|
||||
if compose list_users | awk 'NR > 1 { print $1 }' | grep -Fxq "$username"; then
|
||||
compose change_password "$username" "$password" >/dev/null
|
||||
else
|
||||
compose add_user "$username" "$password" >/dev/null
|
||||
fi
|
||||
compose set_user_tags "$username" >/dev/null
|
||||
}
|
||||
|
||||
ensure_user messenger_api "$RABBITMQ_API_PASSWORD"
|
||||
compose set_permissions -p messenger messenger_api '^attachment\.jobs$' '^attachment\.jobs$' '^$' >/dev/null
|
||||
|
||||
ensure_user messenger_worker "$RABBITMQ_WORKER_PASSWORD"
|
||||
compose set_permissions -p messenger messenger_worker '^attachment\.jobs$' '^attachment\.jobs$' '^attachment\.jobs$' >/dev/null
|
||||
|
||||
printf '%s\n' "RabbitMQ API/worker credentials provisioned with vhost-scoped permissions."
|
||||
@@ -0,0 +1,20 @@
|
||||
listeners.tcp = none
|
||||
listeners.ssl.default = 5671
|
||||
ssl_options.certfile = /run/pki/server.crt
|
||||
ssl_options.keyfile = /run/pki/server.key
|
||||
ssl_options.cacertfile = /run/pki/ca.crt
|
||||
ssl_options.verify = verify_peer
|
||||
ssl_options.fail_if_no_peer_cert = false
|
||||
ssl_options.versions.1 = tlsv1.2
|
||||
ssl_options.versions.2 = tlsv1.3
|
||||
loopback_users.guest = true
|
||||
management.tcp.ip = 127.0.0.1
|
||||
prometheus.tcp.ip = 127.0.0.1
|
||||
management.ssl.port = 15671
|
||||
management.ssl.certfile = /run/pki/server.crt
|
||||
management.ssl.keyfile = /run/pki/server.key
|
||||
management.ssl.cacertfile = /run/pki/ca.crt
|
||||
management.ssl.verify = verify_peer
|
||||
management.ssl.fail_if_no_peer_cert = false
|
||||
management.ssl.versions.1 = tlsv1.2
|
||||
management.ssl.versions.2 = tlsv1.3
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["s3:ListBucket"],
|
||||
"Resource": ["arn:aws:s3:::messenger-attachments"]
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["s3:GetObject", "s3:PutObject"],
|
||||
"Resource": ["arn:aws:s3:::messenger-attachments/staging/*", "arn:aws:s3:::messenger-attachments/attachments/*"]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["s3:GetObject"],
|
||||
"Resource": ["arn:aws:s3:::messenger-attachments/staging/*"]
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["s3:PutObject"],
|
||||
"Resource": ["arn:aws:s3:::messenger-attachments/attachments/*"]
|
||||
}
|
||||
]
|
||||
}
|
||||
Executable
+39
@@ -0,0 +1,39 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
mc() {
|
||||
/opt/bitnami/minio-client/bin/mc --config-dir "$MINIO_CLIENT_CONF_DIR" "$@"
|
||||
}
|
||||
|
||||
ready=0
|
||||
attempt=0
|
||||
while [ "$attempt" -lt 60 ]; do
|
||||
if mc alias set local https://s3:9000 "$MINIO_ROOT_USER" "$MINIO_ROOT_PASSWORD" \
|
||||
>/dev/null 2>&1 && mc ready local >/dev/null 2>&1; then
|
||||
ready=1
|
||||
break
|
||||
fi
|
||||
attempt=$((attempt + 1))
|
||||
sleep 2
|
||||
done
|
||||
[ "$ready" -eq 1 ] || {
|
||||
printf '%s\n' "S3 did not become ready over verified TLS" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
mc mb --ignore-existing local/messenger-attachments
|
||||
mc anonymous set none local/messenger-attachments
|
||||
if ! mc admin policy info local messenger-api >/dev/null 2>&1; then
|
||||
mc admin policy create local messenger-api /bootstrap/policy-api.json
|
||||
fi
|
||||
if ! mc admin policy info local messenger-worker >/dev/null 2>&1; then
|
||||
mc admin policy create local messenger-worker /bootstrap/policy-worker.json
|
||||
fi
|
||||
if ! mc admin user info local "$S3_API_ACCESS_KEY" >/dev/null 2>&1; then
|
||||
mc admin user add local "$S3_API_ACCESS_KEY" "$S3_API_SECRET_KEY" >/dev/null
|
||||
fi
|
||||
mc admin policy attach local messenger-api --user "$S3_API_ACCESS_KEY" >/dev/null
|
||||
if ! mc admin user info local "$S3_WORKER_ACCESS_KEY" >/dev/null 2>&1; then
|
||||
mc admin user add local "$S3_WORKER_ACCESS_KEY" "$S3_WORKER_SECRET_KEY" >/dev/null
|
||||
fi
|
||||
mc admin policy attach local messenger-worker --user "$S3_WORKER_ACCESS_KEY" >/dev/null
|
||||
@@ -3,6 +3,6 @@
|
||||
"title": "Безопасность, mTLS и OpenBao",
|
||||
"contract_version": "1.7.0",
|
||||
"default_base_url": "https://localhost:8443",
|
||||
"grading": "3; 4 includes 3; 5 includes 4 plus one completed research track",
|
||||
"scaffold_has_application": false
|
||||
"grading": "mandatory requirements only; no extended grade tracks",
|
||||
"scaffold_has_application": true
|
||||
}
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
# Python 3.12 runtime dependencies
|
||||
fastapi==0.115.6
|
||||
uvicorn==0.34.0
|
||||
asyncpg==0.30.0
|
||||
argon2-cffi==23.1.0
|
||||
boto3==1.35.90
|
||||
pika==1.3.2
|
||||
Pillow==11.0.0
|
||||
cryptography==44.0.0
|
||||
opentelemetry-api==1.29.0
|
||||
opentelemetry-sdk==1.29.0
|
||||
opentelemetry-exporter-otlp-proto-http==1.29.0
|
||||
Executable
+111
@@ -0,0 +1,111 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
PKI_DIR="$ROOT/secrets/pki"
|
||||
umask 077
|
||||
|
||||
if [ -e "$PKI_DIR" ] && [ -n "$(find "$PKI_DIR" -mindepth 1 -maxdepth 1 -print -quit)" ]; then
|
||||
printf '%s\n' "Refusing to overwrite existing PKI in $PKI_DIR" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
mkdir -p "$PKI_DIR"
|
||||
chmod 700 "$ROOT/secrets" "$PKI_DIR"
|
||||
|
||||
openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:3072 -out "$PKI_DIR/ca.key"
|
||||
openssl req -x509 -new -key "$PKI_DIR/ca.key" -sha256 -days 3650 \
|
||||
-subj "/CN=MTUSI Lab 7 Local CA" \
|
||||
-addext "basicConstraints=critical,CA:TRUE,pathlen:0" \
|
||||
-addext "keyUsage=critical,keyCertSign,cRLSign" \
|
||||
-out "$PKI_DIR/ca.crt"
|
||||
|
||||
issue_cert() {
|
||||
name=$1
|
||||
common_name=$2
|
||||
dns_names=$3
|
||||
ip_names=$4
|
||||
uri_name=$5
|
||||
usage=$6
|
||||
key="$PKI_DIR/$name.key"
|
||||
csr="$PKI_DIR/$name.csr"
|
||||
cert="$PKI_DIR/$name.crt"
|
||||
ext="$PKI_DIR/$name.ext"
|
||||
|
||||
openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -out "$key"
|
||||
openssl req -new -key "$key" -subj "/CN=$common_name" -out "$csr"
|
||||
{
|
||||
printf '%s\n' '[v3_req]' 'basicConstraints=critical,CA:FALSE'
|
||||
printf '%s\n' 'keyUsage=critical,digitalSignature,keyEncipherment'
|
||||
printf 'extendedKeyUsage=%s\n' "$usage"
|
||||
printf '%s\n' 'subjectAltName=@alt_names' '[alt_names]'
|
||||
index=1
|
||||
old_ifs=$IFS
|
||||
IFS=,
|
||||
for dns in $dns_names; do
|
||||
[ -n "$dns" ] || continue
|
||||
printf 'DNS.%s=%s\n' "$index" "$dns"
|
||||
index=$((index + 1))
|
||||
done
|
||||
IFS=$old_ifs
|
||||
index=1
|
||||
IFS=,
|
||||
for ip in $ip_names; do
|
||||
[ -n "$ip" ] || continue
|
||||
printf 'IP.%s=%s\n' "$index" "$ip"
|
||||
index=$((index + 1))
|
||||
done
|
||||
IFS=$old_ifs
|
||||
if [ -n "$uri_name" ]; then
|
||||
printf 'URI.1=%s\n' "$uri_name"
|
||||
fi
|
||||
} > "$ext"
|
||||
openssl x509 -req -in "$csr" -CA "$PKI_DIR/ca.crt" -CAkey "$PKI_DIR/ca.key" \
|
||||
-CAcreateserial -out "$cert" -days 397 -sha256 -extfile "$ext" -extensions v3_req
|
||||
rm -f "$csr" "$ext"
|
||||
chmod 600 "$key"
|
||||
chmod 644 "$cert"
|
||||
}
|
||||
|
||||
issue_cert ingress localhost localhost,ingress 127.0.0.1 "" serverAuth
|
||||
issue_cert lb-client load-balancer "" "" spiffe://lab7/role/load-balancer clientAuth
|
||||
issue_cert api-server api api "" spiffe://lab7/role/api serverAuth,clientAuth
|
||||
issue_cert api-client api-service "" "" spiffe://lab7/role/api clientAuth
|
||||
issue_cert worker-client worker-service "" "" spiffe://lab7/role/worker clientAuth
|
||||
issue_cert postgres-server postgres postgres "" "" serverAuth
|
||||
issue_cert s3-server s3 s3 "" "" serverAuth
|
||||
issue_cert rabbit-server rabbitmq rabbitmq "" "" serverAuth
|
||||
issue_cert openbao-server openbao openbao "" "" serverAuth
|
||||
issue_cert collector-server otel-collector otel-collector "" "" serverAuth
|
||||
issue_cert prometheus-server prometheus prometheus "" "" serverAuth
|
||||
issue_cert loki-server loki loki "" "" serverAuth
|
||||
issue_cert tempo-server tempo tempo "" "" serverAuth
|
||||
issue_cert grafana-server grafana grafana "" "" serverAuth
|
||||
|
||||
prepare_runtime_cert() {
|
||||
service=$1
|
||||
certificate=$2
|
||||
mkdir -p "$ROOT/secrets/runtime-pki/$service"
|
||||
cp "$PKI_DIR/ca.crt" "$ROOT/secrets/runtime-pki/$service/ca.crt"
|
||||
cp "$PKI_DIR/$certificate.crt" "$ROOT/secrets/runtime-pki/$service/server.crt"
|
||||
cp "$PKI_DIR/$certificate.key" "$ROOT/secrets/runtime-pki/$service/server.key"
|
||||
}
|
||||
|
||||
prepare_runtime_cert ingress ingress
|
||||
for service in api postgres s3 rabbit openbao collector prometheus loki tempo grafana; do
|
||||
prepare_runtime_cert "$service" "$service-server"
|
||||
done
|
||||
cp "$PKI_DIR/lb-client.crt" "$ROOT/secrets/runtime-pki/ingress/client.crt"
|
||||
cp "$PKI_DIR/lb-client.key" "$ROOT/secrets/runtime-pki/ingress/client.key"
|
||||
cp "$PKI_DIR/api-client.crt" "$ROOT/secrets/runtime-pki/api/client.crt"
|
||||
cp "$PKI_DIR/api-client.key" "$ROOT/secrets/runtime-pki/api/client.key"
|
||||
mkdir -p "$ROOT/secrets/runtime-pki/worker"
|
||||
cp "$PKI_DIR/ca.crt" "$ROOT/secrets/runtime-pki/worker/ca.crt"
|
||||
cp "$PKI_DIR/worker-client.crt" "$ROOT/secrets/runtime-pki/worker/client.crt"
|
||||
cp "$PKI_DIR/worker-client.key" "$ROOT/secrets/runtime-pki/worker/client.key"
|
||||
|
||||
rm -f "$PKI_DIR/ca.srl"
|
||||
"$ROOT/scripts/bootstrap-untrusted-client.sh"
|
||||
printf 'Created local CA and service certificates in %s\n' "$PKI_DIR"
|
||||
printf 'Prepared service-specific runtime certificates in %s\n' "$ROOT/secrets/runtime-pki"
|
||||
printf 'Keep all private keys out of Git and do not reuse this CA outside the local lab.\n'
|
||||
Executable
+66
@@ -0,0 +1,66 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
SECRETS_DIR="$ROOT/secrets"
|
||||
ENV_FILE="$ROOT/.env"
|
||||
umask 077
|
||||
|
||||
mkdir -p "$SECRETS_DIR"
|
||||
chmod 700 "$SECRETS_DIR"
|
||||
|
||||
if [ -e "$ENV_FILE" ]; then
|
||||
printf '%s\n' "Refusing to overwrite existing local secrets: $ENV_FILE" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
random_secret() {
|
||||
openssl rand -hex 32
|
||||
}
|
||||
|
||||
POSTGRES_PASSWORD=$(random_secret)
|
||||
POSTGRES_API_PASSWORD=$(random_secret)
|
||||
POSTGRES_WORKER_PASSWORD=$(random_secret)
|
||||
MINIO_ROOT_PASSWORD=$(random_secret)
|
||||
S3_API_ACCESS_KEY=$(openssl rand -hex 16)
|
||||
S3_API_SECRET_KEY=$(random_secret)
|
||||
S3_WORKER_ACCESS_KEY=$(openssl rand -hex 16)
|
||||
S3_WORKER_SECRET_KEY=$(random_secret)
|
||||
RABBITMQ_DEFAULT_PASSWORD=$(random_secret)
|
||||
RABBITMQ_API_PASSWORD=$(random_secret)
|
||||
RABBITMQ_WORKER_PASSWORD=$(random_secret)
|
||||
GRAFANA_ADMIN_PASSWORD=$(random_secret)
|
||||
|
||||
cat > "$ENV_FILE" <<EOF
|
||||
POSTGRES_DB=messenger
|
||||
POSTGRES_USER=postgres
|
||||
POSTGRES_PASSWORD=$POSTGRES_PASSWORD
|
||||
POSTGRES_API_PASSWORD=$POSTGRES_API_PASSWORD
|
||||
POSTGRES_WORKER_PASSWORD=$POSTGRES_WORKER_PASSWORD
|
||||
MINIO_ROOT_USER=lab7operator
|
||||
MINIO_ROOT_PASSWORD=$MINIO_ROOT_PASSWORD
|
||||
S3_API_ACCESS_KEY=$S3_API_ACCESS_KEY
|
||||
S3_API_SECRET_KEY=$S3_API_SECRET_KEY
|
||||
S3_WORKER_ACCESS_KEY=$S3_WORKER_ACCESS_KEY
|
||||
S3_WORKER_SECRET_KEY=$S3_WORKER_SECRET_KEY
|
||||
RABBITMQ_DEFAULT_USER=lab7operator
|
||||
RABBITMQ_DEFAULT_PASS=$RABBITMQ_DEFAULT_PASSWORD
|
||||
RABBITMQ_API_PASSWORD=$RABBITMQ_API_PASSWORD
|
||||
RABBITMQ_WORKER_PASSWORD=$RABBITMQ_WORKER_PASSWORD
|
||||
GRAFANA_ADMIN_USER=operator
|
||||
GRAFANA_ADMIN_PASSWORD=$GRAFANA_ADMIN_PASSWORD
|
||||
EOF
|
||||
chmod 600 "$ENV_FILE"
|
||||
|
||||
for pair in \
|
||||
"api_db_password:$POSTGRES_API_PASSWORD" \
|
||||
"worker_db_password:$POSTGRES_WORKER_PASSWORD"
|
||||
do
|
||||
name=${pair%%:*}
|
||||
value=${pair#*:}
|
||||
printf '%s' "$value" > "$SECRETS_DIR/$name"
|
||||
chmod 600 "$SECRETS_DIR/$name"
|
||||
done
|
||||
|
||||
printf 'Created non-overwriting local runtime secrets: %s\n' "$ENV_FILE"
|
||||
printf 'Do not print or commit .env; only the one-shot provisioners receive its credentials.\n'
|
||||
Executable
+44
@@ -0,0 +1,44 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
PKI_DIR="$ROOT/secrets/pki"
|
||||
RUNTIME_PKI="$ROOT/secrets/runtime-pki"
|
||||
|
||||
if [ ! -f "$PKI_DIR/ca.crt" ]; then
|
||||
"$ROOT/scripts/bootstrap-local-pki.sh"
|
||||
elif [ ! -f "$RUNTIME_PKI/ingress/server.crt" ]; then
|
||||
for certificate in ingress api-server api-client worker-client postgres-server \
|
||||
s3-server rabbit-server openbao-server collector-server prometheus-server \
|
||||
loki-server tempo-server grafana-server; do
|
||||
if [ ! -f "$PKI_DIR/$certificate.crt" ] || [ ! -f "$PKI_DIR/$certificate.key" ]; then
|
||||
printf 'Existing local PKI is incomplete: %s\n' "$PKI_DIR/$certificate" >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
mkdir -p "$RUNTIME_PKI"
|
||||
for service in ingress api postgres s3 rabbit openbao collector prometheus loki tempo grafana; do
|
||||
certificate="$service-server"
|
||||
[ "$service" != ingress ] || certificate=ingress
|
||||
mkdir -p "$RUNTIME_PKI/$service"
|
||||
cp "$PKI_DIR/ca.crt" "$RUNTIME_PKI/$service/ca.crt"
|
||||
cp "$PKI_DIR/$certificate.crt" "$RUNTIME_PKI/$service/server.crt"
|
||||
cp "$PKI_DIR/$certificate.key" "$RUNTIME_PKI/$service/server.key"
|
||||
done
|
||||
cp "$PKI_DIR/lb-client.crt" "$RUNTIME_PKI/ingress/client.crt"
|
||||
cp "$PKI_DIR/lb-client.key" "$RUNTIME_PKI/ingress/client.key"
|
||||
cp "$PKI_DIR/api-client.crt" "$RUNTIME_PKI/api/client.crt"
|
||||
cp "$PKI_DIR/api-client.key" "$RUNTIME_PKI/api/client.key"
|
||||
mkdir -p "$RUNTIME_PKI/worker"
|
||||
cp "$PKI_DIR/ca.crt" "$RUNTIME_PKI/worker/ca.crt"
|
||||
cp "$PKI_DIR/worker-client.crt" "$RUNTIME_PKI/worker/client.crt"
|
||||
cp "$PKI_DIR/worker-client.key" "$RUNTIME_PKI/worker/client.key"
|
||||
chmod 600 "$RUNTIME_PKI"/*/*.key
|
||||
fi
|
||||
|
||||
if [ ! -f "$ROOT/.env" ]; then
|
||||
"$ROOT/scripts/bootstrap-local-secrets.sh"
|
||||
fi
|
||||
|
||||
"$ROOT/scripts/bootstrap-untrusted-client.sh"
|
||||
printf 'Local PKI and stack secrets are ready. Next run: make up\n'
|
||||
Executable
+44
@@ -0,0 +1,44 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
PKI_DIR="$ROOT/secrets/pki"
|
||||
umask 077
|
||||
|
||||
if [ -f "$PKI_DIR/foreign-client.crt" ] && [ -f "$PKI_DIR/foreign-client.key" ] \
|
||||
&& [ -f "$PKI_DIR/foreign-ca.crt" ]; then
|
||||
exit 0
|
||||
fi
|
||||
if [ -e "$PKI_DIR/foreign-client.crt" ] || [ -e "$PKI_DIR/foreign-client.key" ] \
|
||||
|| [ -e "$PKI_DIR/foreign-ca.crt" ]; then
|
||||
printf '%s\n' "Incomplete foreign test identity in $PKI_DIR; inspect it before repair." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -out "$PKI_DIR/foreign-ca.key"
|
||||
openssl req -x509 -new -key "$PKI_DIR/foreign-ca.key" -sha256 -days 365 \
|
||||
-subj "/CN=MTUSI Lab 7 Untrusted Test CA" \
|
||||
-addext "basicConstraints=critical,CA:TRUE,pathlen:0" \
|
||||
-addext "keyUsage=critical,keyCertSign,cRLSign" \
|
||||
-out "$PKI_DIR/foreign-ca.crt"
|
||||
openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 \
|
||||
-out "$PKI_DIR/foreign-client.key"
|
||||
openssl req -new -key "$PKI_DIR/foreign-client.key" \
|
||||
-subj "/CN=untrusted-load-balancer" -out "$PKI_DIR/foreign-client.csr"
|
||||
cat > "$PKI_DIR/foreign-client.ext" <<'EOF'
|
||||
[v3_req]
|
||||
basicConstraints=critical,CA:FALSE
|
||||
keyUsage=critical,digitalSignature,keyEncipherment
|
||||
extendedKeyUsage=clientAuth
|
||||
subjectAltName=URI:spiffe://lab7/role/load-balancer
|
||||
EOF
|
||||
openssl x509 -req -in "$PKI_DIR/foreign-client.csr" \
|
||||
-CA "$PKI_DIR/foreign-ca.crt" -CAkey "$PKI_DIR/foreign-ca.key" \
|
||||
-CAcreateserial -out "$PKI_DIR/foreign-client.crt" -days 90 -sha256 \
|
||||
-extfile "$PKI_DIR/foreign-client.ext" -extensions v3_req
|
||||
|
||||
rm -f "$PKI_DIR/foreign-ca.key" "$PKI_DIR/foreign-ca.srl" \
|
||||
"$PKI_DIR/foreign-client.csr" "$PKI_DIR/foreign-client.ext"
|
||||
chmod 600 "$PKI_DIR/foreign-client.key"
|
||||
chmod 644 "$PKI_DIR/foreign-client.crt" "$PKI_DIR/foreign-ca.crt"
|
||||
printf '%s\n' "Created local untrusted client identity for negative mTLS testing."
|
||||
@@ -40,7 +40,13 @@ def main():
|
||||
assert 'X-Instance-Id' in response['headers']
|
||||
assert ('/api/v1/auth/sessions' in spec['paths']) == (lab>=2)
|
||||
assert ('/api/v1/attachments/{attachment_id}' in spec['paths']) == (lab>=4)
|
||||
for file in list((ROOT/'tests').glob('*.py'))+list((ROOT/'scripts').glob('*.py')):
|
||||
python_files = (
|
||||
list((ROOT/'tests').glob('*.py'))
|
||||
+ list((ROOT/'scripts').glob('*.py'))
|
||||
+ list((ROOT/'app').glob('*.py'))
|
||||
+ list((ROOT/'infra/openbao').glob('*.py'))
|
||||
)
|
||||
for file in python_files:
|
||||
ast.parse(file.read_text(),filename=str(file))
|
||||
for file in ROOT.rglob('*.json'):
|
||||
if any(part in {'.git','.venv','node_modules','vendor','output'} for part in file.parts):
|
||||
@@ -48,7 +54,7 @@ def main():
|
||||
json.loads(file.read_text())
|
||||
for required in ('README.md','COURSE.md','CONTRIBUTING.md','REPORT.md','contracts/README.md','tests/smoke.py','tests/README.md'):
|
||||
assert (ROOT/required).is_file(), 'missing '+required
|
||||
print('PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.')
|
||||
print('PASS: offline structure, local refs, JSON and Python syntax; runtime requires Compose.')
|
||||
|
||||
if __name__=='__main__':
|
||||
main()
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Initialize and provision the local persistent OpenBao instance."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
OPERATOR_FILE = ROOT / "secrets" / "openbao-operator.json"
|
||||
|
||||
|
||||
def main() -> int:
|
||||
if not (ROOT / ".env").is_file():
|
||||
raise RuntimeError("local secrets are missing; run make bootstrap first")
|
||||
if not OPERATOR_FILE.exists():
|
||||
result = subprocess.run(
|
||||
[
|
||||
"docker", "compose", "exec", "-T", "openbao", "bao", "operator",
|
||||
"init", "-key-shares=1", "-key-threshold=1", "-format=json",
|
||||
],
|
||||
cwd=ROOT,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
if result.returncode:
|
||||
raise RuntimeError(
|
||||
"OpenBao initialization failed. If the persistent volume was already initialized, "
|
||||
"restore the operator recovery material instead of reinitializing it."
|
||||
)
|
||||
material = json.loads(result.stdout)
|
||||
if not material.get("root_token") or not material.get("unseal_keys_b64"):
|
||||
raise RuntimeError("OpenBao initialization returned incomplete operator material")
|
||||
OPERATOR_FILE.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
fd = os.open(OPERATOR_FILE, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
||||
with os.fdopen(fd, "w", encoding="utf-8") as output:
|
||||
json.dump(material, output)
|
||||
output.write("\n")
|
||||
else:
|
||||
material = json.loads(OPERATOR_FILE.read_text(encoding="utf-8"))
|
||||
|
||||
if not material.get("root_token") or not material.get("unseal_keys_b64"):
|
||||
raise RuntimeError("local OpenBao operator file is incomplete")
|
||||
|
||||
result = subprocess.run(
|
||||
["docker", "compose", "run", "--rm", "--no-deps", "openbao-provisioner"],
|
||||
cwd=ROOT,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
check=False,
|
||||
)
|
||||
if result.returncode:
|
||||
raise RuntimeError(
|
||||
"OpenBao provisioning failed. Inspect service readiness and local operator state; "
|
||||
"secret values and tokens were not printed."
|
||||
)
|
||||
print("OpenBao is unsealed; scoped API/worker AppRoles and secrets are provisioned.")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
raise SystemExit(main())
|
||||
except (OSError, ValueError, RuntimeError) as exc:
|
||||
print(f"ERROR: {exc}", file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
Executable
+33
@@ -0,0 +1,33 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
set -a
|
||||
. "$ROOT/.env"
|
||||
set +a
|
||||
|
||||
attempt=0
|
||||
ready=0
|
||||
while [ "$attempt" -lt 60 ]; do
|
||||
if docker compose exec -T postgres \
|
||||
pg_isready -U "$POSTGRES_USER" -d "$POSTGRES_DB" >/dev/null 2>&1; then
|
||||
ready=1
|
||||
break
|
||||
fi
|
||||
attempt=$((attempt + 1))
|
||||
sleep 2
|
||||
done
|
||||
[ "$ready" -eq 1 ] || {
|
||||
printf '%s\n' "PostgreSQL did not become ready" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
{
|
||||
printf '%s\n' "\\set api_password '$POSTGRES_API_PASSWORD'"
|
||||
printf '%s\n' "\\set worker_password '$POSTGRES_WORKER_PASSWORD'"
|
||||
cat "$ROOT/infra/postgres/roles.sql"
|
||||
} | docker compose exec -T -e "PGPASSWORD=$POSTGRES_PASSWORD" postgres \
|
||||
psql --host=/var/run/postgresql --username "$POSTGRES_USER" \
|
||||
--dbname "$POSTGRES_DB" --set=ON_ERROR_STOP=1
|
||||
|
||||
printf '%s\n' "PostgreSQL API/worker roles provisioned with separate credentials."
|
||||
Executable
+44
@@ -0,0 +1,44 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
set -a
|
||||
. "$ROOT/.env"
|
||||
set +a
|
||||
|
||||
attempt=0
|
||||
ready=0
|
||||
while [ "$attempt" -lt 60 ]; do
|
||||
if docker compose exec -T rabbitmq rabbitmq-diagnostics -q ping >/dev/null 2>&1; then
|
||||
ready=1
|
||||
break
|
||||
fi
|
||||
attempt=$((attempt + 1))
|
||||
sleep 2
|
||||
done
|
||||
[ "$ready" -eq 1 ] || {
|
||||
printf '%s\n' "RabbitMQ did not become ready" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
compose() {
|
||||
docker compose exec -T rabbitmq rabbitmqctl "$@"
|
||||
}
|
||||
|
||||
ensure_user() {
|
||||
username=$1
|
||||
password=$2
|
||||
if compose list_users | awk 'NR > 1 { print $1 }' | grep -Fxq "$username"; then
|
||||
compose change_password "$username" "$password" >/dev/null
|
||||
else
|
||||
compose add_user "$username" "$password" >/dev/null
|
||||
fi
|
||||
}
|
||||
|
||||
ensure_user messenger_api "$RABBITMQ_API_PASSWORD"
|
||||
compose set_permissions -p messenger messenger_api '^attachment\.jobs$' '^amq\.default$' '^$' >/dev/null
|
||||
|
||||
ensure_user messenger_worker "$RABBITMQ_WORKER_PASSWORD"
|
||||
compose set_permissions -p messenger messenger_worker '^attachment\.jobs$' '^amq\.default$' '^attachment\.jobs$' >/dev/null
|
||||
|
||||
printf '%s\n' "RabbitMQ API/worker credentials provisioned with vhost-scoped permissions."
|
||||
Executable
+19
@@ -0,0 +1,19 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$ROOT"
|
||||
|
||||
if [ ! -f .env ] || [ ! -f secrets/pki/ca.crt ]; then
|
||||
scripts/bootstrap-local-stack.sh
|
||||
fi
|
||||
|
||||
docker compose up -d certs-init postgres s3 rabbitmq openbao
|
||||
scripts/provision-db.sh
|
||||
docker compose run --rm --no-deps s3-provisioner
|
||||
scripts/provision-rabbitmq.sh
|
||||
python3 scripts/initialize-openbao.py
|
||||
docker compose up -d --build
|
||||
|
||||
printf '%s\n' "Stack started. Public endpoint: https://localhost:8443"
|
||||
printf '%s\n' "Use CA_FILE=secrets/pki/ca.crt make test and make test-security."
|
||||
@@ -20,4 +20,4 @@ for path in (root/'contracts').glob('*.schema.json'):
|
||||
Draft202012Validator.check_schema(schema)
|
||||
for example in schema.get('examples',[]):
|
||||
Draft202012Validator(schema).validate(example)
|
||||
print('PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.')
|
||||
print('PASS: full OpenAPI 3.1 and JSON Schema validation.')
|
||||
|
||||
@@ -12,8 +12,8 @@ TODO: схема и ссылка на заполненную contracts/trust-mat
|
||||
| --- | --- | --- | --- | --- |
|
||||
| TODO | TODO | TODO | TODO | TODO |
|
||||
|
||||
На 4 минимум 6 конкретных угроз. Не заменяйте сценарии словами «SQL injection», «безопасный Docker», «mTLS включён» без пути и проверки.
|
||||
Опишите конкретные угрозы и воспроизводимые отрицательные проверки. Не заменяйте сценарии словами «SQL injection», «безопасный Docker», «mTLS включён» без пути и проверки.
|
||||
|
||||
## Lifecycle и инциденты
|
||||
|
||||
TODO: bootstrap, expiry/renewal, revoke/rotation, компрометация identity, sealed OpenBao и восстановление. Указать владельца CA/unseal и способ защиты bootstrap credentials. Сопоставить scan findings с реальной применимостью и исправлением/остаточным риском.
|
||||
TODO: локальный certificate bootstrap, компрометация identity, sealed OpenBao и восстановление. Указать владельца CA/unseal и способ защиты bootstrap credentials.
|
||||
|
||||
+4
-4
@@ -4,9 +4,9 @@ Python **3.9+**, стандартная библиотека. Сервер уж
|
||||
|
||||
```sh
|
||||
make check
|
||||
make test BASE_URL=http://localhost:8080
|
||||
make test BASE_URL=https://localhost:8443 CA_FILE=/absolute/path/to/ca.crt
|
||||
# без make:
|
||||
python3 tests/smoke.py --base-url http://localhost:8080
|
||||
python3 tests/smoke.py --base-url https://localhost:8443 --ca-file /absolute/path/to/ca.crt
|
||||
```
|
||||
|
||||
`smoke.py` выполняет **один сквозной сценарий**, автоматически выбирая профиль из `lab.json`: health → три пользователя → вход с lab2 → чат → сообщения → пагинация → ошибки доступа → идемпотентность с lab3 → файл с lab4 → thumbnail с lab5 → logout. Он проверяет JSON по используемому подмножеству схемы, коды/headers, Unicode, SHA-256 оригинала и фактические JPEG-размеры thumbnail. Это публичный минимум, не полный fuzz/security/load suite.
|
||||
@@ -50,8 +50,8 @@ 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
|
||||
```
|
||||
|
||||
Все скрипты принимают `--ca-file`/`CA_FILE` и проверяют серверный сертификат и hostname. `--insecure` отсутствует. TLS-тест сначала проверяет рабочее доверенное соединение, затем намеренно пустой trust store и именно ошибку проверки сертификата; network timeout не засчитывается как правильный отказ. **Внутреннее mTLS, identity/authorization, OpenBao policy и hardening проверяют отдельные тесты студента** по trust matrix. Клиентский сертификат внешнему учебному REST-клиенту не требуется: mTLS находится на внутренних связях.
|
||||
Все скрипты принимают `--ca-file`/`CA_FILE` и проверяют серверный сертификат и hostname. `--insecure` отсутствует. TLS-тест сначала проверяет рабочее доверенное соединение, затем намеренно пустой trust store и именно ошибку проверки сертификата; network timeout не засчитывается как правильный отказ. `make test-mtls` подключается к API из закрытой Compose-сети и проверяет четыре случая: без сертификата, сертификат от чужого CA, доверенный сертификат с неверной URI identity и разрешённый сертификат LB. Клиентский сертификат внешнему учебному REST-клиенту не требуется: mTLS находится на внутренних связях. OpenBao policy и остальные проверки hardening выполняются отдельно по trust matrix.
|
||||
|
||||
## Что ещё остаётся доказать
|
||||
|
||||
Smoke не доказывает persistence, число реальных контейнеров, durability брокера, outbox, отсутствие утечек/уязвимостей, полноту telemetry или выполнение уровня 4/5. Конкурентные/нагрузочные/негативные проверки своего решения добавляйте отдельно. Список защиты текущей лабы находится в README.md. Проверки рассчитаны на localhost-стенд, не на production.
|
||||
Smoke не доказывает persistence, число реальных контейнеров, durability брокера, outbox, отсутствие утечек/уязвимостей или полноту telemetry. Другие обязательные проверки решения описаны в README.md. Проверки рассчитаны на localhost-стенд, не на production.
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Verify the API's client-certificate and URI SAN allowlist on the TLS socket."""
|
||||
import socket
|
||||
import ssl
|
||||
import sys
|
||||
|
||||
CA = "/run/pki/ca.crt"
|
||||
API_HOST = "api-1"
|
||||
API_TLS_NAME = "api"
|
||||
API_PORT = 8443
|
||||
|
||||
|
||||
def request(certificate=None, key=None, trust=CA):
|
||||
context = ssl.create_default_context(cafile=trust)
|
||||
context.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||
if certificate:
|
||||
context.load_cert_chain(certificate, key)
|
||||
raw_socket = socket.create_connection((API_HOST, API_PORT), timeout=5)
|
||||
with raw_socket:
|
||||
with context.wrap_socket(raw_socket, server_hostname=API_TLS_NAME) as tls:
|
||||
tls.sendall(
|
||||
b"GET /health/live HTTP/1.1\r\n"
|
||||
b"Host: api\r\n"
|
||||
b"Connection: close\r\n\r\n"
|
||||
)
|
||||
response = bytearray()
|
||||
while True:
|
||||
chunk = tls.recv(4096)
|
||||
if not chunk:
|
||||
break
|
||||
response.extend(chunk)
|
||||
status_line = bytes(response).split(b"\r\n", 1)[0]
|
||||
if not status_line:
|
||||
raise ConnectionError("server closed connection before returning HTTP")
|
||||
return int(status_line.split()[1])
|
||||
|
||||
|
||||
def must_fail_handshake(label, certificate=None, key=None, trust=CA):
|
||||
try:
|
||||
request(certificate, key, trust)
|
||||
except (ssl.SSLError, ConnectionError, OSError):
|
||||
print(f"PASS: {label} rejected before receiving an HTTP response")
|
||||
return
|
||||
raise AssertionError(f"{label} unexpectedly completed TLS handshake")
|
||||
|
||||
|
||||
def main():
|
||||
must_fail_handshake("missing client certificate")
|
||||
must_fail_handshake(
|
||||
"client certificate from an untrusted CA",
|
||||
"/run/pki/foreign-client.crt",
|
||||
"/run/pki/foreign-client.key",
|
||||
)
|
||||
wrong_identity_status = request(
|
||||
"/run/pki/worker-client.crt", "/run/pki/worker-client.key"
|
||||
)
|
||||
if wrong_identity_status != 401:
|
||||
raise AssertionError(
|
||||
f"trusted but unauthorized SAN returned HTTP {wrong_identity_status}, expected 401"
|
||||
)
|
||||
print("PASS: trusted client certificate with wrong URI SAN rejected by API")
|
||||
|
||||
allowed_status = request("/run/pki/lb-client.crt", "/run/pki/lb-client.key")
|
||||
if allowed_status != 200:
|
||||
raise AssertionError(
|
||||
f"allowlisted load-balancer identity returned HTTP {allowed_status}, expected 200"
|
||||
)
|
||||
print("PASS: allowlisted load-balancer URI SAN accepted")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except (AssertionError, OSError, ssl.SSLError, ValueError) as exc:
|
||||
print(f"FAIL: {exc}", file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
+1
-1
@@ -76,7 +76,7 @@ def main():
|
||||
c.call('DELETE','/api/v1/auth/sessions/current',204,actor=alice)
|
||||
c.call('GET','/api/v1/users/me',401,actor=alice)
|
||||
c.call('DELETE','/api/v1/auth/sessions/current',401,actor=alice)
|
||||
print('PASS: lab%d public API scenario; infrastructure and grading evidence remain separate.' % LAB)
|
||||
print('PASS: lab%d public API scenario.' % LAB)
|
||||
|
||||
if __name__=='__main__':
|
||||
run(main)
|
||||
|
||||
Reference in New Issue
Block a user