Лабораторная работа №7 - Безопасность мессенджера и защита инфраструктуры #64
@@ -18,3 +18,10 @@ __pycache__
|
|||||||
node_modules
|
node_modules
|
||||||
evidence
|
evidence
|
||||||
.DS_Store
|
.DS_Store
|
||||||
|
.git
|
||||||
|
.env
|
||||||
|
.venv
|
||||||
|
__pycache__
|
||||||
|
.pytest_cache
|
||||||
|
*.pyc
|
||||||
|
evidence
|
||||||
+6
-17
@@ -11,7 +11,7 @@ SESSION_STORE=postgres
|
|||||||
CACHE_URL_FILE=/run/secrets/cache_url
|
CACHE_URL_FILE=/run/secrets/cache_url
|
||||||
API_REPLICAS=2
|
API_REPLICAS=2
|
||||||
IDEMPOTENCY_TTL_SECONDS=86400
|
IDEMPOTENCY_TTL_SECONDS=86400
|
||||||
S3_ENDPOINT=https://s3:9000
|
S3_ENDPOINT=http://s3:9000
|
||||||
S3_REGION=us-east-1
|
S3_REGION=us-east-1
|
||||||
S3_BUCKET=messenger-attachments
|
S3_BUCKET=messenger-attachments
|
||||||
S3_ACCESS_KEY_ID_FILE=/run/secrets/s3_access_key_id
|
S3_ACCESS_KEY_ID_FILE=/run/secrets/s3_access_key_id
|
||||||
@@ -23,19 +23,8 @@ WORKER_CONCURRENCY=2
|
|||||||
JOB_MAX_ATTEMPTS=5
|
JOB_MAX_ATTEMPTS=5
|
||||||
JOB_TIMEOUT_SECONDS=60
|
JOB_TIMEOUT_SECONDS=60
|
||||||
STAGING_RETENTION_SECONDS=86400
|
STAGING_RETENTION_SECONDS=86400
|
||||||
OTEL_SERVICE_NAME=messenger-api
|
RABBITMQ_USER=messenger
|
||||||
# Worker must set a distinct service.name.
|
RABBITMQ_PASSWORD=CHANGE_ME_RABBITMQ
|
||||||
OTEL_EXPORTER_OTLP_ENDPOINT=https://otel-collector:4318
|
RABBITMQ_QUEUE=image_jobs
|
||||||
OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
|
IMAGE_MAX_ATTEMPTS=5
|
||||||
OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=lab
|
GRAFANA_ADMIN_PASSWORD=replace_me
|
||||||
# TLS and OpenBao: actual paths/ports depend on your implemented trust matrix.
|
|
||||||
PUBLIC_BASE_URL=https://localhost:8443
|
|
||||||
TLS_CA_FILE=/run/secrets/ca.crt
|
|
||||||
TLS_CERT_FILE=/run/secrets/service.crt
|
|
||||||
TLS_KEY_FILE=/run/secrets/service.key
|
|
||||||
BAO_ADDR=https://openbao:8200
|
|
||||||
BAO_CACERT=/run/secrets/bao-ca.crt
|
|
||||||
# No root token here. Bootstrap operator -> short-lived service auth -> scoped token.
|
|
||||||
ARGON2_MEMORY_KIB=19456
|
|
||||||
ARGON2_ITERATIONS=2
|
|
||||||
ARGON2_PARALLELISM=1
|
|
||||||
|
|||||||
+14
@@ -30,3 +30,17 @@ coverage/
|
|||||||
.vscode/
|
.vscode/
|
||||||
# Keep small, sanitized evidence summaries in evidence/ under version control.
|
# Keep small, sanitized evidence summaries in evidence/ under version control.
|
||||||
# Inspect git diff --cached: ignore rules are not a secret scanner.
|
# Inspect git diff --cached: ignore rules are not a secret scanner.
|
||||||
|
.env
|
||||||
|
.venv/
|
||||||
|
__pycache__/
|
||||||
|
*.pyc
|
||||||
|
evidence/*.tmp
|
||||||
|
|
||||||
|
# Local certificate-rotation backups
|
||||||
|
compose.before-*-cert-rotation.yaml
|
||||||
|
|
||||||
|
# Local configuration and source backups
|
||||||
|
*.before-*
|
||||||
|
*.bak
|
||||||
|
*.backup
|
||||||
|
*.old
|
||||||
|
|||||||
+17
@@ -0,0 +1,17 @@
|
|||||||
|
FROM python:3.12-slim
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
COPY requirements.txt .
|
||||||
|
|
||||||
|
RUN pip install --no-cache-dir -r requirements.txt
|
||||||
|
|
||||||
|
COPY src/ ./src/
|
||||||
|
COPY migrations/ ./migrations/
|
||||||
|
|
||||||
|
ENV HOST=127.0.0.1
|
||||||
|
ENV PORT=8080
|
||||||
|
|
||||||
|
EXPOSE 8080
|
||||||
|
|
||||||
|
CMD ["uvicorn", "src.main:app", "--host", "127.0.0.1", "--port", "8080", "--workers", "1"]
|
||||||
@@ -1,37 +1,221 @@
|
|||||||
# Отчёт — лабораторная 7
|
# Отчёт — лабораторная 7
|
||||||
|
|
||||||
- Автор, группа: TODO
|
- Автор, группа: Матвиенко Павел, БПИ2304
|
||||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
- Целевая оценка; выбранный трек: **3 — работающий минимум; исследовательский трек не требуется**
|
||||||
- Commit/PR: TODO после публикации
|
- Commit/PR: c188a3becaf35e20ec9acc70ddf9fd5c740a3968; https://gitea.privcloud.tech/mtusi2026/mtusi2026lab7/pulls/64
|
||||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
- Использованные источники, библиотеки и инструменты: документация Python, FastAPI, Docker Compose, PostgreSQL, RabbitMQ, RustFS, Nginx, HAProxy, OpenBao, OpenTelemetry, Grafana; материалы OWASP по хранению паролей и контролю доступа.
|
||||||
|
|
||||||
## Запуск из чистого clone
|
## Запуск из чистого clone
|
||||||
|
|
||||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
Стенд реализован с использованием Docker Compose и Python 3.12. Разработка и тестирование выполнялись в Ubuntu WSL на Windows с установленным Docker Desktop.
|
||||||
|
|
||||||
|
Основные компоненты: Nginx 1.29, HAProxy 3.2, PostgreSQL 16, RabbitMQ 4.1.8, RustFS 1.0.3, OpenBao 2.7.3, OpenTelemetry Collector 0.136.0, Tempo 2.8.2, Loki 3.5.5, Prometheus 3.5.0 и Grafana 12.1.1.
|
||||||
|
|
||||||
|
Для развёртывания необходимы Docker Desktop с поддержкой Docker Compose, Python 3.9 или новее, OpenSSL и Git.
|
||||||
|
|
||||||
|
Клонирование проекта:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git clone https://gitea.privcloud.tech/allerg1q/mtusi2026lab7.git
|
||||||
|
cd mtusi2026lab7
|
||||||
|
```
|
||||||
|
|
||||||
|
Первоначальная подготовка окружения:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cp .env.example .env
|
||||||
|
```
|
||||||
|
|
||||||
|
В `.env` необходимо настроить параметры приложения и сервисов под локальный стенд. Пароли, токены и закрытые ключи не должны храниться в Git.
|
||||||
|
|
||||||
|
Для подготовки локальной PKI, сертификатов, сервисных credentials и OpenBao предусмотрены скрипты в `scripts/`:
|
||||||
|
|
||||||
|
- `bootstrap-pki.sh` — создание инфраструктуры сертификатов;
|
||||||
|
- `bootstrap-postgres-tls.sh` — TLS для PostgreSQL;
|
||||||
|
- `bootstrap-rustfs-tls.sh` — TLS для объектного хранилища;
|
||||||
|
- `bootstrap-openbao-tls.sh` и `bootstrap-openbao-client-certs.sh` — сертификаты OpenBao и клиентов;
|
||||||
|
- `bootstrap-db-credentials.py`, `bootstrap-rabbitmq-credentials.py`, `bootstrap-rustfs-credentials.py` — подготовка сервисных учётных данных;
|
||||||
|
- `bootstrap-openbao-secrets.py` — подготовка секретов;
|
||||||
|
- `issue-openbao-bootstrap.py` и `configure-openbao-cert-auth.py` — настройка служебной аутентификации OpenBao.
|
||||||
|
|
||||||
|
Приватные ключи и операторские credentials создаются и хранятся локально вне репозитория. Инициализация и распечатывание хранилища OpenBao выполняются оператором; root token и unseal keys не предоставляются приложению. Точный порядок первоначального bootstrap определяется зависимостями скриптов и должен соблюдаться перед первым запуском.
|
||||||
|
|
||||||
|
Проверка конфигурации:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose --env-file .env config --quiet
|
||||||
|
```
|
||||||
|
|
||||||
|
Сборка и запуск:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose --env-file .env up -d --build
|
||||||
|
```
|
||||||
|
|
||||||
|
Миграции базы данных выполняются отдельным сервисом `migrate`, присутствующим в Docker Compose. После запуска необходимо проверить состояние сервисов:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose ps
|
||||||
|
```
|
||||||
|
|
||||||
|
Проверка HTTPS и бизнес-API с использованием доверенного CA:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
make test BASE_URL=https://localhost:8443 CA_FILE=/absolute/path/to/ca.crt
|
||||||
|
make test-security BASE_URL=https://localhost:8443 CA_FILE=/absolute/path/to/ca.crt
|
||||||
|
```
|
||||||
|
|
||||||
|
Проверка сохранности данных:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
make test-persistence BASE_URL=https://localhost:8443 CA_FILE=/absolute/path/to/ca.crt ACTION_SCRIPT=scripts/restart.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
Проверка отказа API-реплики:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
make test-failover BASE_URL=https://localhost:8443 CA_FILE=/absolute/path/to/ca.crt ACTION_SCRIPT=scripts/stop-one.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
После failover-теста остановленную реплику необходимо восстановить вместе с её mTLS-sidecar.
|
||||||
|
|
||||||
|
Штатная остановка без удаления данных:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose stop
|
||||||
|
```
|
||||||
|
|
||||||
|
Намеренное удаление учебного стенда вместе с постоянными volumes:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose down -v
|
||||||
|
```
|
||||||
|
|
||||||
|
Последняя команда уничтожает данные Docker volumes и предназначена исключительно для осознанного сброса учебного окружения. Она не используется при обычном перезапуске.
|
||||||
|
|
||||||
## Архитектура и решения
|
## Архитектура и решения
|
||||||
|
|
||||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab6, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
В лабораторную №7 перенесены основные функции мессенджера из предыдущих лабораторных работ: пользователи, сессии, чаты, сообщения, идемпотентность запросов, вложения, миниатюры изображений и фоновая обработка задач.
|
||||||
|
|
||||||
|
Основное изменение — защита внешних и внутренних границ доверия.
|
||||||
|
|
||||||
|
Схема взаимодействия компонентов:
|
||||||
|
|
||||||
|
```text
|
||||||
|
Клиент
|
||||||
|
|
|
||||||
|
| HTTPS :8443
|
||||||
|
v
|
||||||
|
Nginx (LB)
|
||||||
|
|
|
||||||
|
| mTLS
|
||||||
|
+------> HAProxy-sidecar ------> API1
|
||||||
|
|
|
||||||
|
+------> HAProxy-sidecar ------> API2
|
||||||
|
|
|
||||||
|
+-----------+-----------+
|
||||||
|
| | |
|
||||||
|
PostgreSQL RustFS RabbitMQ
|
||||||
|
| |
|
||||||
|
Данные API Worker /
|
||||||
|
Dispatcher
|
||||||
|
|
||||||
|
API / Worker
|
||||||
|
|
|
||||||
|
+------> OpenBao (TLS, scoped credentials)
|
||||||
|
|
|
||||||
|
+------> OpenTelemetry Collector (TLS)
|
||||||
|
|
|
||||||
|
+------> Tempo (mTLS)
|
||||||
|
|
|
||||||
|
+------> Loki (HTTPS)
|
||||||
|
|
|
||||||
|
+------> Prometheus (metrics)
|
||||||
|
```
|
||||||
|
|
||||||
|
Публичная точка входа — `https://localhost:8443`. Nginx обеспечивает HTTPS и распределение запросов между двумя API-репликами. Внутреннее соединение от балансировщика защищено обязательным mTLS. HAProxy-sidecar каждой реплики использует её сетевое пространство; прямые порты API на хост не опубликованы.
|
||||||
|
|
||||||
|
Пароли пользователей хранятся с использованием Argon2id. Аутентификация основана на сессиях, пользовательская идентичность определяется сервером, а доступ к чатам и вложениям контролируется ACL. Для запросов входа предусмотрен rate limiting.
|
||||||
|
|
||||||
|
PostgreSQL выступает основным источником истины для структурированных данных приложения. RustFS хранит файлы и объекты, RabbitMQ используется для асинхронной обработки. Идемпотентность запросов и сохранение подтверждённых операций обеспечиваются механизмами приложения, перенесёнными из предыдущих лабораторных.
|
||||||
|
|
||||||
|
OpenBao используется в режиме с постоянным хранением для выдачи и контроля сервисных секретов. Доступ ограничивается сервисными политиками. Операторские credentials отделены от учётных данных приложения.
|
||||||
|
|
||||||
|
API1, API2, worker и dispatcher запускаются под UID 1000 с удалёнными Linux capabilities. Для API и worker задан лимит памяти 512 MiB, для dispatcher — 256 MiB. Контейнеры не используют privileged-режим и не подключают Docker socket.
|
||||||
|
|
||||||
|
Для наблюдаемости настроена отправка логов и трассировок через OpenTelemetry Collector. Канал Collector → Tempo защищён mTLS с клиентским сертификатом, канал Collector → Loki — HTTPS с проверкой CA и SAN.
|
||||||
|
|
||||||
|
Основные параметры приложения определяются переменными `.env`, документированными в `.env.example`. Переменные для подключения к DB, S3 и broker предусматривают использование отдельных файлов с credentials, а не размещение секретных значений в исходном коде.
|
||||||
|
|
||||||
|
Границы доверия и остаточные ограничения описаны в `contracts/trust-matrix.md`, модель угроз — в `security/THREAT_MODEL.md`.
|
||||||
|
|
||||||
## Доказательства критериев
|
## Доказательства критериев
|
||||||
|
|
||||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| Публичный smoke | make test | TODO | TODO |
|
| Проверка структуры и контракта | `make check` | PASS, код завершения 0 | `evidence/final-contract.txt` |
|
||||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
| Публичный smoke по HTTPS | `make test` с доверенным CA | PASS, полный публичный API-сценарий | `evidence/final-smoke.txt` |
|
||||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
| Проверка внешнего TLS | `make test-security` с CA | PASS, доверенный CA принимается, недоверенный отклоняется | `evidence/final-security.txt` |
|
||||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
| Обязательное mTLS LB → API | `scripts/test-mtls.sh`, отрицательные тесты | 7 PASS, 0 FAIL | `evidence/mtls-negative-tests.txt` |
|
||||||
|
| Argon2id и обоснование параметров | `scripts/benchmark_argon2.py` | Измерены три конфигурации Argon2id | `evidence/argon2-benchmark.txt` |
|
||||||
|
| Ограничение частоты входа | `scripts/test-login-rate-limit.py` | PASS, 0 FAIL | `evidence/login-rate-limit-tests.txt` |
|
||||||
|
| Разграничение доступа PostgreSQL | `scripts/test-db-acl.py` | 25 PASS, 0 FAIL | `evidence/postgres-acl-tests.txt` |
|
||||||
|
| Разграничение доступа RabbitMQ | `scripts/test-rabbitmq-acl.py` | 4 PASS, 0 FAIL | `evidence/rabbitmq-acl-tests.txt` |
|
||||||
|
| Разграничение доступа RustFS | `scripts/test-rustfs-acl.py` | 17 PASS, 0 FAIL | `evidence/rustfs-acl-tests.txt` |
|
||||||
|
| Сервисная аутентификация и политики OpenBao | Тесты `scripts/test-openbao-*` | Выполнялись проверки доступа, запрещённых операций и lifecycle credentials | `evidence/openbao-*` |
|
||||||
|
| TLS PostgreSQL | Проверка конфигурации PostgreSQL | Результаты сохранены | `evidence/postgres-tls-config.txt` |
|
||||||
|
| Collector → Tempo | Передача тестовой трассировки и негативные TLS-тесты | Трассировка получена, без сертификата и с чужим CA — отказ | Результаты проверки OTLP/mTLS |
|
||||||
|
| Collector → Loki | Передача и чтение тестового лога | PASS, проверенный HTTPS | Результаты проверки OTLP/HTTPS |
|
||||||
|
| Ограничение привилегий приложения | Аудит Docker Compose | UID 1000, `cap_drop: ALL`, лимиты памяти | `compose.yaml` |
|
||||||
|
| Persistence | `make test-persistence` | PASS, данные и сессия сохранены | `evidence/final-persistence.txt` |
|
||||||
|
| Failover | `make test-failover` | PASS, восстановление за 1,119 с | `evidence/final-failover.txt` |
|
||||||
|
|
||||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
Для внутреннего TLS отдельно проверялись отсутствие клиентского сертификата, использование недоверенного CA и успешное соединение с разрешённой идентичностью.
|
||||||
|
|
||||||
|
Измерения Argon2id на учебном стенде:
|
||||||
|
|
||||||
|
| Конфигурация | Память | t | p | Медиана |
|
||||||
|
| --- | --- | --- | --- | --- |
|
||||||
|
| Базовая | 19 MiB | 2 | 1 | 13,21 мс |
|
||||||
|
| Усиленная | 32 MiB | 3 | 1 | 46,17 мс |
|
||||||
|
| С повышенным потреблением памяти | 64 MiB | 3 | 1 | 101,44 мс |
|
||||||
|
|
||||||
|
Базовая конфигурация соответствует минимальным параметрам задания. Более высокие параметры увеличивают стоимость вычисления хеша и нагрузку на сервер при одновременных попытках входа. Выбор окончательной конфигурации должен учитывать измеренную производительность и защиту от дорогостоящего login DoS.
|
||||||
|
|
||||||
## Эксперименты и отказы
|
## Эксперименты и отказы
|
||||||
|
|
||||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
Проводились функциональные испытания HTTPS, проверка сохранности данных после перезапуска и испытание отказа одной API-реплики.
|
||||||
|
|
||||||
|
Тестирование выполнялось на локальном стенде Docker Compose в WSL. Использовались две API-реплики, PostgreSQL, RabbitMQ, RustFS и необходимые сервисы безопасности.
|
||||||
|
|
||||||
|
Для failover применялся сценарий из `tests/resilience.py`, выполняющий записи сообщений при остановке одной реплики. Испытание проверяло восстановление доступности, сохранность подтверждённых сообщений и отсутствие нарушения действующей сессии.
|
||||||
|
|
||||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| TODO | TODO | TODO | TODO |
|
| HTTPS-запрос с недоверенным CA | Отказ проверки сертификата | PASS, соединение отклонено | Не применимо |
|
||||||
|
| Подключение к mTLS без разрешённого сертификата | Отказ аутентификации | Отрицательные проверки пройдены | Не применимо |
|
||||||
|
| Перезапуск API и зависимых хранилищ | Сохранение данных и сессии | PASS, подтверждённые данные и сессия сохранились | Потеря подтверждённых данных не обнаружена |
|
||||||
|
| Остановка одной API-реплики | Продолжение работы через оставшуюся реплику | PASS, 72 успешные записи, 3 неуспешные попытки | 1,119 с до восстановления записи; потеря подтверждённых данных не обнаружена |
|
||||||
|
| Подключение к Tempo без клиентского сертификата | Отказ | `certificate required` | Не применимо |
|
||||||
|
| Подключение к Tempo с сертификатом чужого CA | Отказ | `unknown ca` | Не применимо |
|
||||||
|
| Передача логов в Loki через HTTPS | Успешная доставка и чтение | PASS, запись найдена в Loki | После повторного запроса |
|
||||||
|
|
||||||
|
В тесте отказа наблюдались две API-реплики до остановки одной из них. При переключении зафиксированы 72 успешные записи и 3 неуспешные попытки. Время восстановления составило 1,119 секунды, что меньше предусмотренного тестом предела в 10 секунд.
|
||||||
|
|
||||||
|
Проверка persistence завершилась успешно: после перезапуска PostgreSQL, RabbitMQ и RustFS, восстановления API и mTLS-sidecar подтверждённые данные и прежняя сессия сохранились.
|
||||||
|
|
||||||
|
Показатели RPS и p50/p95/p99 для отдельного нагрузочного теста не заявляются, поскольку соответствующий итоговый нагрузочный прогон и его статистика не представлены. Измерения Argon2id приведены отдельно. Результаты устойчивости относятся к одному локальному учебному стенду и не являются гарантией поведения при отказе всего хоста.
|
||||||
|
|
||||||
## Ограничения и следующие шаги
|
## Ограничения и следующие шаги
|
||||||
|
|
||||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
Полученные результаты подтверждают работоспособность публичного API через HTTPS, обязательного mTLS на внутренней границе LB → API, разграничение прав для зависимостей и сохранность данных при проверенных сценариях перезапуска и отказа одной API-реплики.
|
||||||
|
|
||||||
|
При этом тест отказа API не означает отказоустойчивость PostgreSQL, RabbitMQ, RustFS или Docker-хоста. Остановка этих компонентов может приводить к ограничению доступности отдельных операций.
|
||||||
|
|
||||||
|
Соединения Grafana → Prometheus, Grafana → Tempo и Prometheus → Collector переведены на HTTPS с использованием Lab7 CA. Проверены авторизованные запросы Grafana API, получение метрик Prometheus и доступность Tempo. Collector имеет статус UP=1. Административный интерфейс Grafana также доступен по HTTPS.
|
||||||
|
|
||||||
|
Ручная первоначальная инициализация OpenBao допускается в учебном стенде, но требует правильного хранения операторских unseal credentials. Окончательное соответствие правилам хранения секретов требует проверки всех файлов, добавляемых в Git.
|
||||||
|
|
||||||
|
Возможные дальнейшие улучшения: автоматизация восстановления после отказа, дополнительные негативные TLS-тесты, проверка административного доступа RustFS и анализ устойчивости под нагрузкой. Эти улучшения не заявляются как выполненные.
|
||||||
|
|
||||||
|
**Заключение:** реализованы основные механизмы безопасности лабораторной №7 и получены положительные результаты ключевых функциональных и отрицательных проверок. Перед окончательной сдачей необходимо завершить аудит оставшихся административных границ доверия и проверить содержимое репозитория на наличие секретов.
|
||||||
|
|||||||
+503
@@ -0,0 +1,503 @@
|
|||||||
|
services:
|
||||||
|
openbao:
|
||||||
|
image: openbao/openbao:2.7.3
|
||||||
|
command:
|
||||||
|
- server
|
||||||
|
- -config=/openbao/config/openbao.hcl
|
||||||
|
environment:
|
||||||
|
BAO_ADDR: https://127.0.0.1:8200
|
||||||
|
BAO_CACERT: /openbao/tls/ca.crt
|
||||||
|
ports:
|
||||||
|
- 127.0.0.1:8200:8200
|
||||||
|
volumes:
|
||||||
|
- openbao_data:/openbao/data
|
||||||
|
- ./security/openbao/openbao.hcl:/openbao/config/openbao.hcl:ro
|
||||||
|
- ${LAB7_PKI_DIR:?Set LAB7_PKI_DIR}/openbao.crt:/openbao/tls/openbao.crt:ro
|
||||||
|
- ${LAB7_PKI_DIR:?Set LAB7_PKI_DIR}/openbao.key:/openbao/tls/openbao.key:ro
|
||||||
|
- ${LAB7_PKI_DIR:?Set LAB7_PKI_DIR}/ca.crt:/openbao/tls/ca.crt:ro
|
||||||
|
restart: unless-stopped
|
||||||
|
prometheus:
|
||||||
|
image: prom/prometheus:v3.5.0
|
||||||
|
command:
|
||||||
|
- --config.file=/etc/prometheus/prometheus.yml
|
||||||
|
- --storage.tsdb.path=/prometheus
|
||||||
|
- --storage.tsdb.retention.time=7d
|
||||||
|
- --web.config.file=/etc/prometheus/web.yml
|
||||||
|
volumes:
|
||||||
|
- ${HOME}/.local/share/mtusi2026lab7/pki/ca.crt:/etc/prometheus/lab7-ca.crt:ro
|
||||||
|
- ./observability/prometheus.yaml:/etc/prometheus/prometheus.yml:ro
|
||||||
|
- prometheus_data:/prometheus
|
||||||
|
- ${HOME}/.local/share/mtusi2026lab7/pki/telemetry/prometheus/server.crt:/run/prometheus/server.crt:ro
|
||||||
|
- ${HOME}/.local/share/mtusi2026lab7/pki/telemetry/prometheus/server.key:/run/prometheus/server.key:ro
|
||||||
|
- ./observability/prometheus-web.yaml:/etc/prometheus/web.yml:ro
|
||||||
|
ports:
|
||||||
|
- 127.0.0.1:9090:9090
|
||||||
|
restart: unless-stopped
|
||||||
|
loki:
|
||||||
|
image: grafana/loki:3.5.5
|
||||||
|
command:
|
||||||
|
- -config.file=/etc/loki/local-config.yaml
|
||||||
|
volumes:
|
||||||
|
- /home/user/.local/share/mtusi2026lab7/pki/telemetry/loki/server.crt:/run/loki/server.crt:ro
|
||||||
|
- /home/user/.local/share/mtusi2026lab7/pki/telemetry/loki/server.key:/run/loki/server.key:ro
|
||||||
|
- ./observability/loki.yaml:/etc/loki/local-config.yaml:ro
|
||||||
|
- loki_data:/loki
|
||||||
|
user: '0'
|
||||||
|
restart: unless-stopped
|
||||||
|
tempo:
|
||||||
|
image: grafana/tempo:2.8.2
|
||||||
|
command:
|
||||||
|
- -config.file=/etc/tempo.yaml
|
||||||
|
volumes:
|
||||||
|
- ${LAB7_PKI_DIR:?Set LAB7_PKI_DIR}/telemetry-runtime/tempo/server.crt:/run/tempo/server.crt:ro
|
||||||
|
- ${LAB7_PKI_DIR:?Set LAB7_PKI_DIR}/telemetry-runtime/tempo/server.key:/run/tempo/server.key:ro
|
||||||
|
- ${LAB7_PKI_DIR:?Set LAB7_PKI_DIR}/telemetry-runtime/tempo/ca.crt:/run/tempo/ca.crt:ro
|
||||||
|
- ./observability/tempo.yaml:/etc/tempo.yaml:ro
|
||||||
|
- tempo_data:/var/tempo
|
||||||
|
user: 10001:10001
|
||||||
|
restart: unless-stopped
|
||||||
|
grafana:
|
||||||
|
image: grafana/grafana:12.1.1
|
||||||
|
environment:
|
||||||
|
GF_SECURITY_ADMIN_USER: admin
|
||||||
|
GF_SECURITY_ADMIN_PASSWORD: ${GRAFANA_ADMIN_PASSWORD:?Set GRAFANA_ADMIN_PASSWORD
|
||||||
|
in .env}
|
||||||
|
GF_USERS_ALLOW_SIGN_UP: 'false'
|
||||||
|
GF_SERVER_PROTOCOL: https
|
||||||
|
GF_SERVER_CERT_FILE: /run/grafana/server.crt
|
||||||
|
GF_SERVER_CERT_KEY: /run/grafana/server.key
|
||||||
|
GF_SERVER_ROOT_URL: https://localhost:3000/
|
||||||
|
volumes:
|
||||||
|
- grafana_data:/var/lib/grafana
|
||||||
|
- ./observability/grafana/provisioning:/etc/grafana/provisioning:ro
|
||||||
|
- ./observability/grafana/dashboards:/var/lib/grafana/dashboards:ro
|
||||||
|
- ${HOME}/.local/share/mtusi2026lab7/pki/telemetry/grafana/server.crt:/run/grafana/server.crt:ro
|
||||||
|
- ${HOME}/.local/share/mtusi2026lab7/pki/telemetry/grafana/server.key:/run/grafana/server.key:ro
|
||||||
|
ports:
|
||||||
|
- 127.0.0.1:3000:3000
|
||||||
|
depends_on:
|
||||||
|
- prometheus
|
||||||
|
- loki
|
||||||
|
- tempo
|
||||||
|
restart: unless-stopped
|
||||||
|
otel-collector:
|
||||||
|
image: otel/opentelemetry-collector-contrib:0.136.0
|
||||||
|
command:
|
||||||
|
- --config=/etc/otelcol-contrib/config.yaml
|
||||||
|
volumes:
|
||||||
|
- ${LAB7_PKI_DIR:?Set LAB7_PKI_DIR}/telemetry-runtime/otel-collector-client/client.crt:/run/telemetry/client.crt:ro
|
||||||
|
- ${LAB7_PKI_DIR:?Set LAB7_PKI_DIR}/telemetry-runtime/otel-collector-client/client.key:/run/telemetry/client.key:ro
|
||||||
|
- ${LAB7_PKI_DIR:?Set LAB7_PKI_DIR}/telemetry-runtime/otel-collector/server.crt:/run/telemetry/server.crt:ro
|
||||||
|
- ${LAB7_PKI_DIR:?Set LAB7_PKI_DIR}/telemetry-runtime/otel-collector/server.key:/run/telemetry/server.key:ro
|
||||||
|
- ${LAB7_PKI_DIR:?Set LAB7_PKI_DIR}/telemetry-runtime/otel-collector/ca.crt:/run/telemetry/ca.crt:ro
|
||||||
|
- ./observability/otel-collector.yaml:/etc/otelcol-contrib/config.yaml:ro
|
||||||
|
restart: unless-stopped
|
||||||
|
healthcheck:
|
||||||
|
test:
|
||||||
|
- CMD
|
||||||
|
- /otelcol-contrib
|
||||||
|
- components
|
||||||
|
interval: 30s
|
||||||
|
timeout: 10s
|
||||||
|
retries: 3
|
||||||
|
rabbitmq:
|
||||||
|
image: rabbitmq:4.1.8-management
|
||||||
|
hostname: rabbitmq
|
||||||
|
volumes:
|
||||||
|
- rabbitmq_data:/var/lib/rabbitmq
|
||||||
|
- ./security/rabbitmq/rabbitmq.conf:/etc/rabbitmq/rabbitmq.conf:ro
|
||||||
|
- ${LAB7_PKI_DIR:?Set LAB7_PKI_DIR}/ca.crt:/run/lab7-rabbitmq/ca.crt:ro
|
||||||
|
- ${LAB7_PKI_DIR}/rabbitmq.crt:/run/lab7-rabbitmq/rabbitmq.crt:ro
|
||||||
|
- ${LAB7_PKI_DIR}/rabbitmq-server.key:/run/lab7-rabbitmq/rabbitmq-server.key:ro
|
||||||
|
- ${LAB7_PKI_DIR:?Set LAB7_PKI_DIR}/rabbitmq-definitions.json:/run/lab7-rabbitmq/definitions.json:ro
|
||||||
|
healthcheck:
|
||||||
|
test:
|
||||||
|
- CMD
|
||||||
|
- rabbitmq-diagnostics
|
||||||
|
- -q
|
||||||
|
- ping
|
||||||
|
interval: 10s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 15
|
||||||
|
start_period: 15s
|
||||||
|
restart: unless-stopped
|
||||||
|
db:
|
||||||
|
image: postgres:16-alpine
|
||||||
|
command:
|
||||||
|
- postgres
|
||||||
|
- -c
|
||||||
|
- ssl=on
|
||||||
|
- -c
|
||||||
|
- ssl_cert_file=/etc/postgresql/tls/db.crt
|
||||||
|
- -c
|
||||||
|
- ssl_key_file=/etc/postgresql/tls/db-server.key
|
||||||
|
- -c
|
||||||
|
- ssl_min_protocol_version=TLSv1.2
|
||||||
|
- -c
|
||||||
|
- hba_file=/etc/postgresql/pg_hba.conf
|
||||||
|
environment:
|
||||||
|
POSTGRES_DB: messenger
|
||||||
|
POSTGRES_USER: messenger
|
||||||
|
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in .env}
|
||||||
|
volumes:
|
||||||
|
- postgres_data:/var/lib/postgresql/data
|
||||||
|
- ${LAB7_PKI_DIR:?Set LAB7_PKI_DIR}/db.crt:/etc/postgresql/tls/db.crt:ro
|
||||||
|
- ${LAB7_PKI_DIR}/db-server.key:/etc/postgresql/tls/db-server.key:ro
|
||||||
|
- ./security/postgres/pg_hba.conf:/etc/postgresql/pg_hba.conf:ro
|
||||||
|
healthcheck:
|
||||||
|
test:
|
||||||
|
- CMD-SHELL
|
||||||
|
- pg_isready -U messenger -d messenger
|
||||||
|
interval: 5s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 20
|
||||||
|
restart: unless-stopped
|
||||||
|
minio:
|
||||||
|
image: rustfs/rustfs:1.0.3
|
||||||
|
command:
|
||||||
|
- /data
|
||||||
|
environment:
|
||||||
|
RUSTFS_ACCESS_KEY: ${S3_ACCESS_KEY:?Set S3_ACCESS_KEY in .env}
|
||||||
|
RUSTFS_SECRET_KEY: ${S3_SECRET_KEY:?Set S3_SECRET_KEY in .env}
|
||||||
|
RUSTFS_ADDRESS: :9000
|
||||||
|
RUSTFS_TLS_PATH: /etc/rustfs/tls
|
||||||
|
volumes:
|
||||||
|
- minio_data:/data
|
||||||
|
- ${LAB7_PKI_DIR:?Set LAB7_PKI_DIR}/rustfs-tls:/etc/rustfs/tls:ro
|
||||||
|
restart: unless-stopped
|
||||||
|
s3-init:
|
||||||
|
build: .
|
||||||
|
command:
|
||||||
|
- python
|
||||||
|
- -m
|
||||||
|
- src.s3_setup
|
||||||
|
environment:
|
||||||
|
S3_ENDPOINT: https://minio:9000
|
||||||
|
AWS_CA_BUNDLE: /etc/ssl/lab7/ca.crt
|
||||||
|
S3_ACCESS_KEY: ${S3_ACCESS_KEY}
|
||||||
|
S3_SECRET_KEY: ${S3_SECRET_KEY}
|
||||||
|
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
|
||||||
|
depends_on:
|
||||||
|
minio:
|
||||||
|
condition: service_started
|
||||||
|
restart: 'no'
|
||||||
|
volumes:
|
||||||
|
- ${LAB7_PKI_DIR:?Set LAB7_PKI_DIR}/ca.crt:/etc/ssl/lab7/ca.crt:ro
|
||||||
|
migrate:
|
||||||
|
build: .
|
||||||
|
command:
|
||||||
|
- python
|
||||||
|
- -m
|
||||||
|
- src.migrate
|
||||||
|
environment:
|
||||||
|
DATABASE_URL: postgresql://messenger:${POSTGRES_PASSWORD}@db:5432/messenger?sslmode=verify-full&sslrootcert=/etc/ssl/lab7/ca.crt
|
||||||
|
depends_on:
|
||||||
|
db:
|
||||||
|
condition: service_healthy
|
||||||
|
restart: 'no'
|
||||||
|
volumes:
|
||||||
|
- ${LAB7_PKI_DIR:?Set LAB7_PKI_DIR}/ca.crt:/etc/ssl/lab7/ca.crt:ro
|
||||||
|
api1:
|
||||||
|
user: 1000:1000
|
||||||
|
cap_drop:
|
||||||
|
- ALL
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
|
mem_limit: 512m
|
||||||
|
cpus: 1.0
|
||||||
|
pids_limit: 128
|
||||||
|
build: .
|
||||||
|
command:
|
||||||
|
- python
|
||||||
|
- -m
|
||||||
|
- src.openbao_entrypoint
|
||||||
|
- --
|
||||||
|
- uvicorn
|
||||||
|
- src.main:app
|
||||||
|
- --host
|
||||||
|
- 127.0.0.1
|
||||||
|
- --port
|
||||||
|
- '8080'
|
||||||
|
- --workers
|
||||||
|
- '1'
|
||||||
|
environment:
|
||||||
|
BAO_ADDR: https://openbao:8200
|
||||||
|
BAO_CACERT: /etc/ssl/lab7/ca.crt
|
||||||
|
BAO_CERT_FILE: /run/lab7/bao/client.crt
|
||||||
|
BAO_KEY_FILE: /run/lab7/bao/client.key
|
||||||
|
BAO_CERT_NAME: lab7-api1-next
|
||||||
|
BAO_SECRET_PATH: lab7/data/api/runtime
|
||||||
|
S3_ENDPOINT: https://minio:9000
|
||||||
|
S3_BUCKET: ${S3_BUCKET}
|
||||||
|
AWS_CA_BUNDLE: /etc/ssl/lab7/ca.crt
|
||||||
|
OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:4320
|
||||||
|
OTEL_SERVICE_NAME: messenger-api
|
||||||
|
OTEL_PYTHON_FASTAPI_EXCLUDED_URLS: /health/.*
|
||||||
|
IMAGE_MAX_ATTEMPTS: ${IMAGE_MAX_ATTEMPTS:-5}
|
||||||
|
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||||
|
depends_on:
|
||||||
|
migrate:
|
||||||
|
condition: service_completed_successfully
|
||||||
|
s3-init:
|
||||||
|
condition: service_completed_successfully
|
||||||
|
healthcheck:
|
||||||
|
test:
|
||||||
|
- CMD
|
||||||
|
- python
|
||||||
|
- -c
|
||||||
|
- import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health/ready',
|
||||||
|
timeout=3)
|
||||||
|
interval: 5s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 20
|
||||||
|
stop_grace_period: 15s
|
||||||
|
restart: unless-stopped
|
||||||
|
volumes:
|
||||||
|
- ${LAB7_PKI_DIR:?Set LAB7_PKI_DIR}/ca.crt:/etc/ssl/lab7/ca.crt:ro
|
||||||
|
- ${LAB7_PKI_DIR:?Set LAB7_PKI_DIR}/ca.crt:/etc/ssl/lab7/ca.crt:ro
|
||||||
|
- type: bind
|
||||||
|
source: ${HOME}/.local/share/mtusi2026lab7/pki/openbao-clients/rotation-api1/client.crt
|
||||||
|
target: /run/lab7/bao/client.crt
|
||||||
|
read_only: true
|
||||||
|
bind:
|
||||||
|
create_host_path: false
|
||||||
|
- type: bind
|
||||||
|
source: ${HOME}/.local/share/mtusi2026lab7/pki/openbao-clients/rotation-api1/client.key
|
||||||
|
target: /run/lab7/bao/client.key
|
||||||
|
read_only: true
|
||||||
|
bind:
|
||||||
|
create_host_path: false
|
||||||
|
api2:
|
||||||
|
user: 1000:1000
|
||||||
|
cap_drop:
|
||||||
|
- ALL
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
|
mem_limit: 512m
|
||||||
|
cpus: 1.0
|
||||||
|
pids_limit: 128
|
||||||
|
build: .
|
||||||
|
command:
|
||||||
|
- python
|
||||||
|
- -m
|
||||||
|
- src.openbao_entrypoint
|
||||||
|
- --
|
||||||
|
- uvicorn
|
||||||
|
- src.main:app
|
||||||
|
- --host
|
||||||
|
- 127.0.0.1
|
||||||
|
- --port
|
||||||
|
- '8080'
|
||||||
|
- --workers
|
||||||
|
- '1'
|
||||||
|
environment:
|
||||||
|
BAO_ADDR: https://openbao:8200
|
||||||
|
BAO_CACERT: /etc/ssl/lab7/ca.crt
|
||||||
|
BAO_CERT_FILE: /run/lab7/bao/client.crt
|
||||||
|
BAO_KEY_FILE: /run/lab7/bao/client.key
|
||||||
|
BAO_CERT_NAME: lab7-api2-next
|
||||||
|
BAO_SECRET_PATH: lab7/data/api/runtime
|
||||||
|
S3_ENDPOINT: https://minio:9000
|
||||||
|
S3_BUCKET: ${S3_BUCKET}
|
||||||
|
AWS_CA_BUNDLE: /etc/ssl/lab7/ca.crt
|
||||||
|
OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:4320
|
||||||
|
OTEL_SERVICE_NAME: messenger-api
|
||||||
|
OTEL_PYTHON_FASTAPI_EXCLUDED_URLS: /health/.*
|
||||||
|
IMAGE_MAX_ATTEMPTS: ${IMAGE_MAX_ATTEMPTS:-5}
|
||||||
|
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||||
|
depends_on:
|
||||||
|
migrate:
|
||||||
|
condition: service_completed_successfully
|
||||||
|
s3-init:
|
||||||
|
condition: service_completed_successfully
|
||||||
|
healthcheck:
|
||||||
|
test:
|
||||||
|
- CMD
|
||||||
|
- python
|
||||||
|
- -c
|
||||||
|
- import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health/ready',
|
||||||
|
timeout=3)
|
||||||
|
interval: 5s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 20
|
||||||
|
stop_grace_period: 15s
|
||||||
|
restart: unless-stopped
|
||||||
|
volumes:
|
||||||
|
- ${LAB7_PKI_DIR:?Set LAB7_PKI_DIR}/ca.crt:/etc/ssl/lab7/ca.crt:ro
|
||||||
|
- ${LAB7_PKI_DIR:?Set LAB7_PKI_DIR}/ca.crt:/etc/ssl/lab7/ca.crt:ro
|
||||||
|
- type: bind
|
||||||
|
source: ${HOME}/.local/share/mtusi2026lab7/pki/openbao-clients/rotation-api2/client.crt
|
||||||
|
target: /run/lab7/bao/client.crt
|
||||||
|
read_only: true
|
||||||
|
bind:
|
||||||
|
create_host_path: false
|
||||||
|
- type: bind
|
||||||
|
source: ${HOME}/.local/share/mtusi2026lab7/pki/openbao-clients/rotation-api2/client.key
|
||||||
|
target: /run/lab7/bao/client.key
|
||||||
|
read_only: true
|
||||||
|
bind:
|
||||||
|
create_host_path: false
|
||||||
|
dispatcher:
|
||||||
|
user: 1000:1000
|
||||||
|
cap_drop:
|
||||||
|
- ALL
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
|
mem_limit: 256m
|
||||||
|
cpus: 0.5
|
||||||
|
pids_limit: 64
|
||||||
|
build: .
|
||||||
|
command:
|
||||||
|
- python
|
||||||
|
- -m
|
||||||
|
- src.dispatcher
|
||||||
|
environment:
|
||||||
|
OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:4320
|
||||||
|
OTEL_SERVICE_NAME: messenger-dispatcher
|
||||||
|
DATABASE_URL: postgresql://messenger_dispatcher:${DISPATCHER_DB_PASSWORD:?Set
|
||||||
|
DISPATCHER_DB_PASSWORD in .env}@db:5432/messenger?sslmode=verify-full&sslrootcert=/etc/ssl/lab7/ca.crt
|
||||||
|
RABBITMQ_HOST: rabbitmq
|
||||||
|
RABBITMQ_USER: messenger_publisher
|
||||||
|
RABBITMQ_PASSWORD: ${RABBITMQ_PUBLISHER_PASSWORD:?Set RABBITMQ_PUBLISHER_PASSWORD
|
||||||
|
in .env}
|
||||||
|
RABBITMQ_QUEUE: ${RABBITMQ_QUEUE:-image_jobs}
|
||||||
|
RABBITMQ_CA_FILE: /etc/ssl/lab7/ca.crt
|
||||||
|
depends_on:
|
||||||
|
rabbitmq:
|
||||||
|
condition: service_healthy
|
||||||
|
migrate:
|
||||||
|
condition: service_completed_successfully
|
||||||
|
restart: unless-stopped
|
||||||
|
stop_grace_period: 15s
|
||||||
|
volumes:
|
||||||
|
- ${LAB7_PKI_DIR:?Set LAB7_PKI_DIR}/ca.crt:/etc/ssl/lab7/ca.crt:ro
|
||||||
|
worker:
|
||||||
|
user: 1000:1000
|
||||||
|
cap_drop:
|
||||||
|
- ALL
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
|
mem_limit: 512m
|
||||||
|
cpus: 1.0
|
||||||
|
pids_limit: 128
|
||||||
|
build: .
|
||||||
|
command:
|
||||||
|
- python
|
||||||
|
- -m
|
||||||
|
- src.openbao_entrypoint
|
||||||
|
- --
|
||||||
|
- python
|
||||||
|
- -m
|
||||||
|
- src.worker
|
||||||
|
environment:
|
||||||
|
BAO_ADDR: https://openbao:8200
|
||||||
|
BAO_CACERT: /etc/ssl/lab7/ca.crt
|
||||||
|
BAO_CERT_FILE: /run/lab7/bao/client.crt
|
||||||
|
BAO_KEY_FILE: /run/lab7/bao/client.key
|
||||||
|
BAO_CERT_NAME: lab7-worker-next
|
||||||
|
BAO_SECRET_PATH: lab7/data/worker/runtime
|
||||||
|
OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:4320
|
||||||
|
OTEL_SERVICE_NAME: messenger-worker
|
||||||
|
S3_ENDPOINT: https://minio:9000
|
||||||
|
AWS_CA_BUNDLE: /etc/ssl/lab7/ca.crt
|
||||||
|
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
|
||||||
|
RABBITMQ_HOST: rabbitmq
|
||||||
|
RABBITMQ_QUEUE: ${RABBITMQ_QUEUE:-image_jobs}
|
||||||
|
IMAGE_MAX_ATTEMPTS: ${IMAGE_MAX_ATTEMPTS:-5}
|
||||||
|
RABBITMQ_CA_FILE: /etc/ssl/lab7/ca.crt
|
||||||
|
depends_on:
|
||||||
|
rabbitmq:
|
||||||
|
condition: service_healthy
|
||||||
|
migrate:
|
||||||
|
condition: service_completed_successfully
|
||||||
|
s3-init:
|
||||||
|
condition: service_completed_successfully
|
||||||
|
restart: unless-stopped
|
||||||
|
stop_grace_period: 20s
|
||||||
|
volumes:
|
||||||
|
- ${LAB7_PKI_DIR:?Set LAB7_PKI_DIR}/ca.crt:/etc/ssl/lab7/ca.crt:ro
|
||||||
|
- ${LAB7_PKI_DIR:?Set LAB7_PKI_DIR}/ca.crt:/etc/ssl/lab7/ca.crt:ro
|
||||||
|
- type: bind
|
||||||
|
source: ${HOME}/.local/share/mtusi2026lab7/pki/openbao-clients/rotation-worker/client.crt
|
||||||
|
target: /run/lab7/bao/client.crt
|
||||||
|
read_only: true
|
||||||
|
bind:
|
||||||
|
create_host_path: false
|
||||||
|
- type: bind
|
||||||
|
source: ${HOME}/.local/share/mtusi2026lab7/pki/openbao-clients/rotation-worker/client.key
|
||||||
|
target: /run/lab7/bao/client.key
|
||||||
|
read_only: true
|
||||||
|
bind:
|
||||||
|
create_host_path: false
|
||||||
|
api1-mtls:
|
||||||
|
image: haproxy:3.2-alpine
|
||||||
|
network_mode: service:api1
|
||||||
|
user: 1000:1000
|
||||||
|
entrypoint:
|
||||||
|
- haproxy
|
||||||
|
command:
|
||||||
|
- -W
|
||||||
|
- -db
|
||||||
|
- -f
|
||||||
|
- /usr/local/etc/haproxy/haproxy.cfg
|
||||||
|
cap_drop:
|
||||||
|
- ALL
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
|
volumes:
|
||||||
|
- ./security/haproxy/api1.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
||||||
|
- ${LAB7_PKI_DIR:?Set LAB7_PKI_DIR}/api1.pem:/run/lab7-pki/api1.pem:ro
|
||||||
|
- ${LAB7_PKI_DIR}/ca.crt:/run/lab7-pki/ca.crt:ro
|
||||||
|
depends_on:
|
||||||
|
api1:
|
||||||
|
condition: service_healthy
|
||||||
|
restart: unless-stopped
|
||||||
|
api2-mtls:
|
||||||
|
image: haproxy:3.2-alpine
|
||||||
|
network_mode: service:api2
|
||||||
|
user: 1000:1000
|
||||||
|
entrypoint:
|
||||||
|
- haproxy
|
||||||
|
command:
|
||||||
|
- -W
|
||||||
|
- -db
|
||||||
|
- -f
|
||||||
|
- /usr/local/etc/haproxy/haproxy.cfg
|
||||||
|
cap_drop:
|
||||||
|
- ALL
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
|
volumes:
|
||||||
|
- ./security/haproxy/api2.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
||||||
|
- ${LAB7_PKI_DIR:?Set LAB7_PKI_DIR}/api2.pem:/run/lab7-pki/api2.pem:ro
|
||||||
|
- ${LAB7_PKI_DIR}/ca.crt:/run/lab7-pki/ca.crt:ro
|
||||||
|
depends_on:
|
||||||
|
api2:
|
||||||
|
condition: service_healthy
|
||||||
|
restart: unless-stopped
|
||||||
|
nginx:
|
||||||
|
image: nginx:1.29-alpine
|
||||||
|
ports:
|
||||||
|
- 127.0.0.1:8443:443
|
||||||
|
volumes:
|
||||||
|
- ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro
|
||||||
|
- ${LAB7_PKI_DIR:?Set LAB7_PKI_DIR}/ca.crt:/run/lab7-pki/ca.crt:ro
|
||||||
|
- ${LAB7_PKI_DIR}/ingress.crt:/run/lab7-pki/ingress.crt:ro
|
||||||
|
- ${LAB7_PKI_DIR}/ingress.key:/run/lab7-pki/ingress.key:ro
|
||||||
|
- ${LAB7_PKI_DIR}/lb-client.crt:/run/lab7-pki/lb-client.crt:ro
|
||||||
|
- ${LAB7_PKI_DIR}/lb-client.key:/run/lab7-pki/lb-client.key:ro
|
||||||
|
depends_on:
|
||||||
|
api1-mtls:
|
||||||
|
condition: service_started
|
||||||
|
api2-mtls:
|
||||||
|
condition: service_started
|
||||||
|
restart: unless-stopped
|
||||||
|
volumes:
|
||||||
|
postgres_data: null
|
||||||
|
minio_data: null
|
||||||
|
rabbitmq_data: null
|
||||||
|
prometheus_data: null
|
||||||
|
loki_data: null
|
||||||
|
tempo_data: null
|
||||||
|
grafana_data: null
|
||||||
|
openbao_data: null
|
||||||
+60
-27
@@ -1,37 +1,70 @@
|
|||||||
# Матрица доверия — заполнить в решении lab7
|
# Матрица доверия — лабораторная работа №7
|
||||||
|
|
||||||
Это обязательная матрица покрытия. Для каждой строки укажите реальный порт, endpoint, CA, service identity, проверку SAN/ACL, срок жизни credentials и команду положительного/отрицательного теста. TLS шифрует и подтверждает сервер; mTLS также проверяет клиента. При доверенном CA всё равно нужно ограничивать разрешённую identity. Plaintext hop допустим только внутри закрытого локального transport/proxy boundary, без опубликованного обхода; границу и rationale нужно доказать.
|
## Общие правила
|
||||||
|
|
||||||
| Связь | Минимум на 3 | Дополнительно на 4 | Доказательство / конфиг |
|
TLS обеспечивает шифрование и проверку серверного сертификата.
|
||||||
|
mTLS дополнительно требует сертификат клиента.
|
||||||
|
Проверка CA не заменяет проверку разрешённой service identity
|
||||||
|
и применение ACL.
|
||||||
|
|
||||||
|
Основной CA стенда находится у оператора вне Git:
|
||||||
|
`~/.local/share/mtusi2026lab7/pki/ca.crt`.
|
||||||
|
|
||||||
|
| Связь | Реальный endpoint | Контроль | Доказательства и статус |
|
||||||
|---|---|---|---|
|
|---|---|---|---|
|
||||||
| Клиент → ingress/LB | TLS, CA + hostname, Bearer | Проверка expiry/revocation сессии и общего login rate limit | TODO |
|
| Клиент → Nginx | localhost:8443 | HTTPS, CA, SAN, Bearer | `final-smoke.txt`, `final-security.txt`: PASS |
|
||||||
| LB → API (все реплики) | mTLS + allowlist LB identity | Ротация leaf без обхода проверки | TODO |
|
| Nginx → API1/API2 | mTLS-sidecar каждой реплики | Клиентский сертификат, проверка identity; API:8080 не опубликован | `mtls-negative-tests.txt`: 7 PASS |
|
||||||
| API/worker → PostgreSQL | TLS verify-full + раздельные ограниченные DB roles | Ротация credentials; mTLS — допустимое усиление | TODO |
|
| API/worker → PostgreSQL | db:5432 | TLS, разделённые DB roles | `postgres-acl-tests.txt`: 25 PASS |
|
||||||
| API/worker → S3 | TLS + разные scoped credentials/prefix rights | Проверка denied prefix и ротация | TODO |
|
| API/worker → S3 | minio:9000 | TLS, scoped credentials | `rustfs-acl-tests.txt`: 17 PASS |
|
||||||
| API/worker → broker | TLS + разные producer/consumer identities и ACL | mTLS + ограничение допустимых SAN/ролей | TODO |
|
| API/worker → RabbitMQ | rabbitmq:5671 | TLS, ACL producer/consumer | `rabbitmq-acl-tests.txt`: 4 PASS |
|
||||||
| API/worker → Collector | TLS; сеть/аутентификация запрещает произвольный ingest | mTLS с раздельными identities | TODO |
|
| Приложения → Collector | otel-collector:4319/4320 | TLS, Lab7 CA, SAN | `observability/otel-collector.yaml`; приёмник настроен |
|
||||||
| Collector → telemetry backends | TLS + scoped backend credentials или mTLS | Ротация и проверка least privilege | TODO |
|
| Collector → Tempo | tempo:4317 | mTLS; клиент otel-collector-client | Успешное чтение трассировки, отказы без cert и с чужим CA |
|
||||||
| Grafana → data sources | TLS с проверкой сервера, ограниченная identity | Отрицательные проверки доступа | TODO |
|
| Collector → Loki | loki:3100/otlp | HTTPS, проверка CA и SAN | Сквозной тест записи и чтения лога: PASS |
|
||||||
| API/worker/agent → OpenBao | TLS + сервисный auth + scoped policy | Renewal/expiry/revocation | TODO |
|
| Grafana → Loki | loki:3100 | HTTPS, CA в datasource | Настроено; отдельно проверить datasource |
|
||||||
| Оператор → OpenBao/Grafana/S3 admin | TLS + authentication, доступ локальный/через защищённый канал | Разделение operator/application roles | TODO |
|
| Grafana → Prometheus | prometheus:9090 | HTTPS, Lab7 CA, проверка сертификата | PASS: datasource API, Prometheus query |
|
||||||
| API → Redis/Valkey, если используется | TLS + ACL/пароль с минимальными правами | Ротация; mTLS по возможности | TODO |
|
| Grafana → Tempo API | tempo:3200 | HTTPS, Lab7 CA, проверка сертификата | PASS: datasource API, Tempo /ready |
|
||||||
| Replication/кластерные каналы, если добавлены | TLS/mTLS либо подтверждённый шифрованный transport | Проверка заявленной модели отказа | TODO |
|
| Prometheus → Collector | otel-collector:8889 | HTTPS, Lab7 CA, проверка имени otel-collector | PASS: Collector UP=1 через Grafana/Prometheus |
|
||||||
|
| API/worker → OpenBao | openbao:8200 | TLS, scoped service auth и policy | `evidence/openbao-*` |
|
||||||
|
| Оператор → OpenBao | localhost:8200 | TLS и operator auth | `openbao-operator-security-audit.txt` |
|
||||||
|
| Оператор → Grafana | localhost:3000 | HTTPS, Lab7 CA, Basic Auth администратора | PASS: авторизованные запросы к Grafana API |
|
||||||
|
| Оператор → S3 admin | RustFS admin endpoint | TLS, отдельные административные права | Проверить фактический административный доступ |
|
||||||
|
| Redis/Valkey | N/A | Компонент отсутствует в Compose | Не используется |
|
||||||
|
| Репликация БД | N/A | Отдельный кластер PostgreSQL не заявлен | Не используется |
|
||||||
|
|
||||||
Нет выбранного компонента — отметьте N/A с причиной, а не оставляйте пустую строку. Внутренний публичный health listener, если нужен, минимален и изолирован; через него нельзя обращаться к бизнес-API без mTLS. Отдельно задокументируйте scrape/health/bootstrap каналы: они тоже не должны создавать обход.
|
## Отрицательные проверки
|
||||||
|
|
||||||
## Обязательные отрицательные проверки
|
- Внешний HTTPS: недоверенный CA отклоняется.
|
||||||
|
- LB → API: проверка отсутствующего или неправильного client certificate,
|
||||||
|
чужого CA и запрещённой identity.
|
||||||
|
- Посторонний пользователь не должен читать чужие сообщения или вложения.
|
||||||
|
- OpenBao policy запрещает неразрешённые paths и операции.
|
||||||
|
- PostgreSQL, RabbitMQ и RustFS используют разграничение прав.
|
||||||
|
- Tempo требует client certificate: без него ошибка
|
||||||
|
`certificate required`, с недоверенным CA — `unknown ca`.
|
||||||
|
- После отзыва credentials новое соединение должно получать отказ.
|
||||||
|
|
||||||
1. HTTPS с правильным CA/hostname проходит; с пустым/чужим CA и неправильным hostname — ошибка верификации, не «сервер недоступен».
|
## Credentials и эксплуатация
|
||||||
2. LB→API: без client cert, с cert чужого CA, с запрещённой identity от доверенного CA — отказ; с разрешённой LB identity — успех.
|
|
||||||
3. На 4 повторите набор для broker и Collector; ограничение на network policy не заменяет проверку identity.
|
|
||||||
4. Пользователь вне чата не читает metadata/content и не прикрепляет чужой файл; поддельный X-User-Id не меняет Bearer identity.
|
|
||||||
5. OpenBao app policy читает только свой secret/path; запись policy и чтение чужого path запрещены. Worker не получает admin credentials API/БД/S3.
|
|
||||||
6. На 4 отзовите secret/cert и дождитесь контролируемого эффекта с учётом действующих соединений, TLS resumption и cache/TTL. Покажите новое подключение, иначе тест отзыва может ничего не проверить.
|
|
||||||
|
|
||||||
## Bootstrap и эксплуатация
|
Сервисные credentials должны иметь ограниченный scope и TTL.
|
||||||
|
Точные значения TTL и разрешённые SAN необходимо сверять с
|
||||||
|
фактическими PKI/OpenBao policy и конфигурацией сервисов,
|
||||||
|
а не подставлять предполагаемые значения.
|
||||||
|
|
||||||
В репозитории только открытые конфиги, policy templates и scripts. CA private key, leaf keys, root token, unseal shares и SecretID не коммитятся, не запекаются в образ и не печатаются в отчёте. Для локального стенда оператор создаёт их вне Git и передаёт через files/secrets с ограниченными правами. Опишите, кто имеет доступ к CA/unseal, что нужно после рестарта OpenBao и как восстановить работу.
|
CA private key, leaf private keys, root token, unseal shares и
|
||||||
|
SecretID не должны коммититься, попадать в контейнерные образы
|
||||||
|
или журналы.
|
||||||
|
|
||||||
OpenBao не использует dev-mode. Выберите persistent storage и auth метод (например AppRole с короткоживущим SecretID/response wrapping, cert auth или иная обоснованная identity). Не подменяйте root token постоянной переменной BAO_TOKEN в приложении. Рабочие tokens имеют policy, TTL и renewal/re-auth сценарий. Статические KV secrets на 3 допустимы при реальном чтении через сервисную identity; динамические DB credentials — хорошее расширение, но не обязательное название технологии.
|
Persistent volumes сохраняются при штатных перезапусках.
|
||||||
|
Подтверждающие тесты:
|
||||||
|
|
||||||
Разрешённый компромисс учебного стенда: ручной operator init/unseal, если он безопасно документирован и не нужен при каждом обычном рестарте API. Автоматическое хранение всех unseal shares рядом с OpenBao без защиты не считается решённым bootstrap.
|
- `evidence/final-persistence.txt`
|
||||||
|
- `evidence/final-failover.txt`
|
||||||
|
|
||||||
|
## Незакрытые пункты
|
||||||
|
|
||||||
|
Ранее отмеченные HTTP-каналы Grafana → Prometheus,
|
||||||
|
Grafana → Tempo и Prometheus → Collector переведены на HTTPS.
|
||||||
|
Работоспособность подтверждена запросами Grafana API и
|
||||||
|
метрикой Collector UP=1. Для полного аудита остаётся
|
||||||
|
проверить остальные административные границы, включая
|
||||||
|
RustFS, и отсутствие секретов в Git.
|
||||||
|
|||||||
@@ -0,0 +1,3 @@
|
|||||||
|
baseline: memory=19456 KiB, t=2, p=1, median=13.21 ms, min=12.66 ms, max=14.40 ms
|
||||||
|
stronger: memory=32768 KiB, t=3, p=1, median=46.17 ms, min=45.01 ms, max=63.33 ms
|
||||||
|
high-memory: memory=65536 KiB, t=3, p=1, median=101.44 ms, min=97.04 ms, max=107.90 ms
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
python3 scripts/check_contract.py
|
||||||
|
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "https://localhost:8443" --ca-file "/home/user/.local/share/mtusi2026lab7/pki/ca.crt"
|
||||||
|
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
|
||||||
|
{"observed_instances_before": 2, "successful_writes": 72, "failed_attempts": 3, "first_recovery_seconds": 1.119}
|
||||||
|
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "https://localhost:8443" --ca-file "/home/user/.local/share/mtusi2026lab7/pki/ca.crt"
|
||||||
|
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
|
||||||
|
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
python3 tests/security.py --base-url "https://localhost:8443" --ca-file "/home/user/.local/share/mtusi2026lab7/pki/ca.crt"
|
||||||
|
PASS: trusted HTTPS works; untrusted CA rejected. This does NOT verify internal mTLS, OpenBao or hardening.
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
python3 tests/smoke.py --base-url "https://localhost:8443" --ca-file "/home/user/.local/share/mtusi2026lab7/pki/ca.crt"
|
||||||
|
PASS: lab7 public API scenario; infrastructure and grading evidence remain separate.
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
PASS: trusted HTTPS works; untrusted CA rejected. This does NOT verify internal mTLS, OpenBao or hardening.
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
PASS: lab7 public API scenario; infrastructure and grading evidence remain separate.
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
PASS: Trusted CA and correct hostname
|
||||||
|
curl exit code: 0
|
||||||
|
HTTP status: 200
|
||||||
|
PASS: Untrusted CA
|
||||||
|
curl exit code: 60
|
||||||
|
PASS: Wrong hostname
|
||||||
|
curl exit code: 60
|
||||||
|
PASS: HTTPS certificate verification
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
Testing rate limit with username: rl_2d31d8ed431a4b75
|
||||||
|
Attempt 1: HTTP 401, Retry-After=None
|
||||||
|
Attempt 2: HTTP 401, Retry-After=None
|
||||||
|
Attempt 3: HTTP 401, Retry-After=None
|
||||||
|
Attempt 4: HTTP 401, Retry-After=None
|
||||||
|
Attempt 5: HTTP 401, Retry-After=None
|
||||||
|
Attempt 6: HTTP 429, Retry-After=60
|
||||||
|
PASS: shared login rate limit and Retry-After
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
|
||||||
|
=== Testing api1 mTLS ===
|
||||||
|
[1] Authorized LB certificate
|
||||||
|
{"status":"ok"}
|
||||||
|
[2] No client certificate
|
||||||
|
PASS: no certificate rejected
|
||||||
|
[3] Untrusted CA certificate
|
||||||
|
PASS: rogue CA rejected
|
||||||
|
[4] Trusted CA, forbidden SAN
|
||||||
|
HTTP 403
|
||||||
|
PASS: api1 mTLS identity enforcement
|
||||||
|
|
||||||
|
=== Testing api2 mTLS ===
|
||||||
|
[1] Authorized LB certificate
|
||||||
|
{"status":"ok"}
|
||||||
|
[2] No client certificate
|
||||||
|
PASS: no certificate rejected
|
||||||
|
[3] Untrusted CA certificate
|
||||||
|
PASS: rogue CA rejected
|
||||||
|
[4] Trusted CA, forbidden SAN
|
||||||
|
HTTP 403
|
||||||
|
PASS: api2 mTLS identity enforcement
|
||||||
|
|
||||||
|
PASS: all mTLS tests passed
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
INFO: active token accessors: 1
|
||||||
|
INFO: root tokens: 1
|
||||||
|
INFO: certificate-auth tokens: 0
|
||||||
|
INFO: other tokens: 0
|
||||||
|
INFO: certificate tokens with API policy: 0
|
||||||
|
INFO: certificate tokens with worker policy: 0
|
||||||
|
INFO: certificate tokens older than 3600 seconds: 0
|
||||||
|
INFO: certificate tokens with nonpositive TTL: 0
|
||||||
|
INFO: tokens expired during audit: 0
|
||||||
|
INFO: lookup errors: 0
|
||||||
|
PASS: token accessor inventory completed
|
||||||
|
PASS: no certificate-auth tokens older than 3600 seconds found
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
PASS: runtime credentials loaded from OpenBao
|
||||||
|
PASS: rotated API1 certificate authenticated
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
PASS: Replacement identity configured
|
||||||
|
PASS: Replacement certificate configured
|
||||||
|
PASS: Replacement key configured
|
||||||
|
PASS: Certificate mounted read-only
|
||||||
|
PASS: Key mounted read-only
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
PASS: runtime credentials loaded from OpenBao
|
||||||
|
PASS: rotated API2 certificate authenticated
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
PASS: Replacement API2 identity configured
|
||||||
|
PASS: Replacement certificate configured
|
||||||
|
PASS: Replacement private key configured
|
||||||
|
PASS: Certificate mounted read-only
|
||||||
|
PASS: Private key mounted read-only
|
||||||
|
PASS: API1 rotated identity preserved
|
||||||
|
PASS: Worker identity unchanged
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
OpenBao HTTPS: https://localhost:8200/v1
|
||||||
|
TLS verification: enabled
|
||||||
|
PASS: temporary KV v2 secrets prepared
|
||||||
|
PASS: api: scoped token issued with limited TTL
|
||||||
|
PASS: api: SecretID reuse denied
|
||||||
|
PASS: worker: scoped token issued with limited TTL
|
||||||
|
PASS: worker: SecretID reuse denied
|
||||||
|
PASS: api: own secret read allowed
|
||||||
|
PASS: worker: own secret read allowed
|
||||||
|
PASS: API cannot read worker secrets
|
||||||
|
PASS: worker cannot read API secrets
|
||||||
|
PASS: api: secret modification denied
|
||||||
|
PASS: worker: secret modification denied
|
||||||
|
PASS: api: policy administration denied
|
||||||
|
PASS: worker: policy administration denied
|
||||||
|
PASS: all OpenBao AppRole ACL tests passed
|
||||||
|
OpenBao test cleanup attempted
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
=== api1 ===
|
||||||
|
PASS: certificate authentication successful
|
||||||
|
PASS: only scoped service policy assigned
|
||||||
|
PASS: own KV v2 secret readable
|
||||||
|
PASS: cross-service KV read denied
|
||||||
|
PASS: KV modification denied
|
||||||
|
PASS: temporary token revoked
|
||||||
|
=== api2 ===
|
||||||
|
PASS: certificate authentication successful
|
||||||
|
PASS: only scoped service policy assigned
|
||||||
|
PASS: own KV v2 secret readable
|
||||||
|
PASS: cross-service KV read denied
|
||||||
|
PASS: KV modification denied
|
||||||
|
PASS: temporary token revoked
|
||||||
|
=== worker ===
|
||||||
|
PASS: certificate authentication successful
|
||||||
|
PASS: only scoped service policy assigned
|
||||||
|
PASS: own KV v2 secret readable
|
||||||
|
PASS: cross-service KV read denied
|
||||||
|
PASS: KV modification denied
|
||||||
|
PASS: temporary token revoked
|
||||||
|
PASS: three certificate identities verified
|
||||||
|
PASS: scoped OpenBao certificate ACL tests completed
|
||||||
|
PASS: no secret values or tokens printed
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
=== api1 ===
|
||||||
|
PASS: certificate authentication and KV retrieval
|
||||||
|
PASS: expected number of secret fields received
|
||||||
|
PASS: no secret values printed
|
||||||
|
PASS: api1 certificate bootstrap verified
|
||||||
|
=== api2 ===
|
||||||
|
PASS: certificate authentication and KV retrieval
|
||||||
|
PASS: expected number of secret fields received
|
||||||
|
PASS: no secret values printed
|
||||||
|
PASS: api2 certificate bootstrap verified
|
||||||
|
=== worker ===
|
||||||
|
PASS: certificate authentication and KV retrieval
|
||||||
|
PASS: expected number of secret fields received
|
||||||
|
PASS: no secret values printed
|
||||||
|
PASS: worker certificate bootstrap verified
|
||||||
|
PASS: three certificate bootstrap tests completed
|
||||||
|
PASS: running application containers unchanged
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
=== api1 ===
|
||||||
|
PASS: runtime credentials loaded from OpenBao
|
||||||
|
PASS: child process received runtime credentials
|
||||||
|
PASS: api1 certificate entrypoint verified
|
||||||
|
=== api2 ===
|
||||||
|
PASS: runtime credentials loaded from OpenBao
|
||||||
|
PASS: child process received runtime credentials
|
||||||
|
PASS: api2 certificate entrypoint verified
|
||||||
|
=== worker ===
|
||||||
|
PASS: runtime credentials loaded from OpenBao
|
||||||
|
PASS: child process received runtime credentials
|
||||||
|
PASS: worker certificate entrypoint verified
|
||||||
|
PASS: three certificate entrypoint tests completed
|
||||||
|
PASS: running containers unchanged
|
||||||
|
PASS: no secret values or tokens printed
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
PASS: api1 cannot authenticate as lab7-worker
|
||||||
|
PASS: api2 cannot authenticate as lab7-api1
|
||||||
|
PASS: worker cannot authenticate as lab7-api2
|
||||||
|
PASS: all certificate identity substitutions rejected
|
||||||
|
PASS: no credentials or tokens printed
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
PASS: All replacement identities registered
|
||||||
|
PASS: Old identities absent
|
||||||
|
PASS: No unexpected certificate identities
|
||||||
|
INFO: registered identity: lab7-api1-next
|
||||||
|
INFO: registered identity: lab7-api2-next
|
||||||
|
INFO: registered identity: lab7-worker-next
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
=== api1 ===
|
||||||
|
PASS: AppRole authentication completed
|
||||||
|
PASS: runtime secrets match service credentials
|
||||||
|
PASS: scoped KV v2 secret loaded
|
||||||
|
PASS: no secret values printed
|
||||||
|
PASS: api1 bootstrap verified
|
||||||
|
PASS: consumed SecretID already absent
|
||||||
|
=== api2 ===
|
||||||
|
PASS: AppRole authentication completed
|
||||||
|
PASS: runtime secrets match service credentials
|
||||||
|
PASS: scoped KV v2 secret loaded
|
||||||
|
PASS: no secret values printed
|
||||||
|
PASS: api2 bootstrap verified
|
||||||
|
PASS: consumed SecretID already absent
|
||||||
|
=== worker ===
|
||||||
|
PASS: AppRole authentication completed
|
||||||
|
PASS: runtime secrets match service credentials
|
||||||
|
PASS: scoped KV v2 secret loaded
|
||||||
|
PASS: no secret values printed
|
||||||
|
PASS: worker bootstrap verified
|
||||||
|
PASS: consumed SecretID already absent
|
||||||
|
PASS: three independent bootstrap tests completed
|
||||||
|
PASS: temporary credential files removed
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
PASS: temporary api2 SecretID issued
|
||||||
|
PASS: runtime credentials loaded from OpenBao
|
||||||
|
PASS: child process received OpenBao secrets
|
||||||
|
PASS: api2 OpenBao entrypoint verified
|
||||||
|
PASS: consumed SecretID already absent
|
||||||
|
PASS: temporary bootstrap files removed
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
PASS: temporary API1 SecretID issued
|
||||||
|
PASS: runtime credentials loaded from OpenBao
|
||||||
|
PASS: child process received OpenBao secrets
|
||||||
|
PASS: API1 OpenBao entrypoint verified
|
||||||
|
PASS: consumed SecretID already absent
|
||||||
|
PASS: temporary bootstrap files removed
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
PASS: temporary worker SecretID issued
|
||||||
|
PASS: runtime credentials loaded from OpenBao
|
||||||
|
PASS: child process received OpenBao secrets
|
||||||
|
PASS: worker OpenBao entrypoint verified
|
||||||
|
PASS: consumed SecretID already absent
|
||||||
|
PASS: temporary bootstrap files removed
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
PASS: openbao-api1-rotation-config.txt
|
||||||
|
PASS: openbao-api1-rotation-auth.txt
|
||||||
|
PASS: openbao-api2-rotation-config.txt
|
||||||
|
PASS: openbao-api2-rotation-auth.txt
|
||||||
|
PASS: openbao-worker-rotation-config.txt
|
||||||
|
PASS: openbao-worker-rotation-auth.txt
|
||||||
|
PASS: openbao-certificate-identity-audit.txt
|
||||||
|
PASS: openbao-old-certificates-rejection.txt
|
||||||
|
PASS: openbao-retired-certificates-inventory.txt
|
||||||
|
PASS: openbao-final-rotation-audit.txt
|
||||||
|
PASS: openbao-token-lifecycle-audit.txt
|
||||||
|
PASS: openbao-token-revocation-test.txt
|
||||||
|
PASS: openbao-active-token-audit.txt
|
||||||
|
PASS: openbao-operator-security-audit.txt
|
||||||
|
PASS: https-smoke-tests.txt
|
||||||
|
PASS: OpenBao evidence inventory complete
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
PASS: api1: old files removed
|
||||||
|
PASS: api1: replacement files preserved
|
||||||
|
PASS: api1: replacement key permissions 600
|
||||||
|
PASS: api1: replacement identity configured
|
||||||
|
PASS: api1: replacement files mounted read-only
|
||||||
|
PASS: api1: running identity correct
|
||||||
|
PASS: api1: running certificate mounts correct
|
||||||
|
PASS: api2: old files removed
|
||||||
|
PASS: api2: replacement files preserved
|
||||||
|
PASS: api2: replacement key permissions 600
|
||||||
|
PASS: api2: replacement identity configured
|
||||||
|
PASS: api2: replacement files mounted read-only
|
||||||
|
PASS: api2: running identity correct
|
||||||
|
PASS: api2: running certificate mounts correct
|
||||||
|
PASS: worker: old files removed
|
||||||
|
PASS: worker: replacement files preserved
|
||||||
|
PASS: worker: replacement key permissions 600
|
||||||
|
PASS: worker: replacement identity configured
|
||||||
|
PASS: worker: replacement files mounted read-only
|
||||||
|
PASS: worker: running identity correct
|
||||||
|
PASS: worker: running certificate mounts correct
|
||||||
|
PASS: OpenBao contains exactly three replacement identities
|
||||||
|
PASS: No old certificate identities registered
|
||||||
|
PASS: final certificate rotation audit
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
PASS: old api1 certificate rejected without role name (HTTP 400)
|
||||||
|
PASS: old api2 certificate rejected without role name (HTTP 400)
|
||||||
|
PASS: old worker certificate rejected without role name (HTTP 400)
|
||||||
|
PASS: all old certificates rejected
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
PASS: Operator directory exists
|
||||||
|
PASS: Initialization file exists
|
||||||
|
PASS: Initialization file is not a symlink
|
||||||
|
PASS: Operator directory permissions 700
|
||||||
|
PASS: Initialization file permissions 600
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
PASS: api1: Old certificate exists
|
||||||
|
PASS: api1: Old private key exists
|
||||||
|
PASS: api1: Replacement certificate exists
|
||||||
|
PASS: api1: Old key permissions 600
|
||||||
|
PASS: api1: Old and new certificates differ
|
||||||
|
PASS: api2: Old certificate exists
|
||||||
|
PASS: api2: Old private key exists
|
||||||
|
PASS: api2: Replacement certificate exists
|
||||||
|
PASS: api2: Old key permissions 600
|
||||||
|
PASS: api2: Old and new certificates differ
|
||||||
|
PASS: worker: Old certificate exists
|
||||||
|
PASS: worker: Old private key exists
|
||||||
|
PASS: worker: Replacement certificate exists
|
||||||
|
PASS: worker: Old key permissions 600
|
||||||
|
PASS: worker: Old and new certificates differ
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
OpenBao endpoint: https://localhost:8200/v1
|
||||||
|
TLS verification: enabled
|
||||||
|
PASS: API replicas use matching credentials
|
||||||
|
PASS: api: correct scoped policy
|
||||||
|
PASS: api: limited token TTL
|
||||||
|
PASS: worker: correct scoped policy
|
||||||
|
PASS: worker: limited token TTL
|
||||||
|
PASS: api: runtime secrets match Compose
|
||||||
|
PASS: worker: runtime secrets match Compose
|
||||||
|
PASS: API cannot read worker runtime secrets (HTTP 403)
|
||||||
|
PASS: Worker cannot read API runtime secrets (HTTP 403)
|
||||||
|
PASS: API cannot read policy configuration (HTTP 403)
|
||||||
|
PASS: Worker cannot read policy configuration (HTTP 403)
|
||||||
|
PASS: all OpenBao runtime access tests passed
|
||||||
|
PASS: no credential values printed
|
||||||
|
PASS: temporary service token revoked
|
||||||
|
PASS: temporary service token revoked
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
PASS: lab7-api1-next: Expected policy only
|
||||||
|
PASS: lab7-api1-next: Token TTL is 1200 seconds
|
||||||
|
PASS: lab7-api1-next: Token max TTL is 3600 seconds
|
||||||
|
PASS: lab7-api1-next: Default policy disabled
|
||||||
|
PASS: lab7-api2-next: Expected policy only
|
||||||
|
PASS: lab7-api2-next: Token TTL is 1200 seconds
|
||||||
|
PASS: lab7-api2-next: Token max TTL is 3600 seconds
|
||||||
|
PASS: lab7-api2-next: Default policy disabled
|
||||||
|
PASS: lab7-worker-next: Expected policy only
|
||||||
|
PASS: lab7-worker-next: Token TTL is 1200 seconds
|
||||||
|
PASS: lab7-worker-next: Token max TTL is 3600 seconds
|
||||||
|
PASS: lab7-worker-next: Default policy disabled
|
||||||
|
PASS: token lifecycle configuration audit
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
PASS: New worker certificate authenticated
|
||||||
|
PASS: Correct worker policy
|
||||||
|
PASS: Issued TTL within 1200 seconds
|
||||||
|
PASS: Administrative token lookup succeeded
|
||||||
|
PASS: Actual TTL within 1200 seconds
|
||||||
|
PASS: Token has no root policy
|
||||||
|
PASS: Worker secret readable
|
||||||
|
PASS: API secret forbidden
|
||||||
|
PASS: Worker token cannot perform lookup-self
|
||||||
|
PASS: Token revoke-self succeeded
|
||||||
|
PASS: Revoked token no longer exists
|
||||||
|
PASS: token lifecycle and revocation test
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
PASS: runtime credentials loaded from OpenBao
|
||||||
|
PASS: rotated worker certificate authenticated
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
PASS: Replacement worker identity configured
|
||||||
|
PASS: Replacement worker certificate configured
|
||||||
|
PASS: Replacement worker private key configured
|
||||||
|
PASS: Certificate mounted read-only
|
||||||
|
PASS: Private key mounted read-only
|
||||||
|
PASS: API1 rotated identity preserved
|
||||||
|
PASS: API2 rotated identity preserved
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
|
||||||
|
================================
|
||||||
|
Testing service: api1
|
||||||
|
================================
|
||||||
|
PostgreSQL role: messenger_api
|
||||||
|
TLS encrypted: True
|
||||||
|
TLS version: TLSv1.3
|
||||||
|
PASS: allowed - read users
|
||||||
|
PASS: allowed - read sessions
|
||||||
|
PASS: allowed - read jobs
|
||||||
|
PASS: denied - read migration history
|
||||||
|
PASS: denied - create tables
|
||||||
|
PASS: all ACL tests for messenger_api
|
||||||
|
|
||||||
|
================================
|
||||||
|
Testing service: api2
|
||||||
|
================================
|
||||||
|
PostgreSQL role: messenger_api
|
||||||
|
TLS encrypted: True
|
||||||
|
TLS version: TLSv1.3
|
||||||
|
PASS: allowed - read users
|
||||||
|
PASS: allowed - read sessions
|
||||||
|
PASS: allowed - read jobs
|
||||||
|
PASS: denied - read migration history
|
||||||
|
PASS: denied - create tables
|
||||||
|
PASS: all ACL tests for messenger_api
|
||||||
|
|
||||||
|
================================
|
||||||
|
Testing service: worker
|
||||||
|
================================
|
||||||
|
PostgreSQL role: messenger_worker
|
||||||
|
TLS encrypted: True
|
||||||
|
TLS version: TLSv1.3
|
||||||
|
PASS: allowed - read jobs
|
||||||
|
PASS: allowed - read attachments
|
||||||
|
PASS: allowed - read variants
|
||||||
|
PASS: denied - read users
|
||||||
|
PASS: denied - read sessions
|
||||||
|
PASS: denied - read messages
|
||||||
|
PASS: all ACL tests for messenger_worker
|
||||||
|
|
||||||
|
================================
|
||||||
|
Testing service: dispatcher
|
||||||
|
================================
|
||||||
|
PostgreSQL role: messenger_dispatcher
|
||||||
|
TLS encrypted: True
|
||||||
|
TLS version: TLSv1.3
|
||||||
|
PASS: allowed - read jobs
|
||||||
|
PASS: denied - read users
|
||||||
|
PASS: denied - read sessions
|
||||||
|
PASS: denied - read messages
|
||||||
|
PASS: denied - read attachments
|
||||||
|
PASS: all ACL tests for messenger_dispatcher
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
on
|
||||||
|
TLSv1.2
|
||||||
|
/etc/postgresql/pg_hba.conf
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
=== Publisher ACL ===
|
||||||
|
RabbitMQ role: messenger_publisher
|
||||||
|
TLS connection: authenticated
|
||||||
|
PASS: publisher cannot consume image_jobs
|
||||||
|
PASS: RabbitMQ ACL tests for messenger_publisher
|
||||||
|
|
||||||
|
=== Consumer ACL ===
|
||||||
|
RabbitMQ role: messenger_consumer
|
||||||
|
TLS connection: authenticated
|
||||||
|
PASS: consumer cannot publish
|
||||||
|
PASS: RabbitMQ ACL tests for messenger_consumer
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
RustFS endpoint: https://minio:9000
|
||||||
|
Bucket: messenger-attachments
|
||||||
|
TLS verification: enabled
|
||||||
|
PASS: temporary test objects prepared
|
||||||
|
PASS: API can upload staging
|
||||||
|
PASS: API can read original
|
||||||
|
PASS: API can read thumbnail
|
||||||
|
PASS: API can delete staging
|
||||||
|
PASS: worker can read staging
|
||||||
|
PASS: worker can write original
|
||||||
|
PASS: worker can write thumbnail
|
||||||
|
PASS: API staging read denied
|
||||||
|
PASS: API original write denied
|
||||||
|
PASS: API thumbnail write denied
|
||||||
|
PASS: API original delete denied
|
||||||
|
PASS: worker original read denied
|
||||||
|
PASS: worker thumbnail read denied
|
||||||
|
PASS: worker staging write denied
|
||||||
|
PASS: worker staging delete denied
|
||||||
|
PASS: all RustFS IAM ACL tests passed
|
||||||
|
RustFS ACL test cleanup attempted
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS users (
|
||||||
|
id UUID PRIMARY KEY,
|
||||||
|
username VARCHAR(32) NOT NULL UNIQUE,
|
||||||
|
display_name VARCHAR(100) NOT NULL,
|
||||||
|
password_hash TEXT NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),
|
||||||
|
|
||||||
|
CONSTRAINT username_format
|
||||||
|
CHECK (username ~ '^[a-z0-9_]{3,32}$'),
|
||||||
|
CONSTRAINT display_name_length
|
||||||
|
CHECK (char_length(display_name) BETWEEN 1 AND 100),
|
||||||
|
CONSTRAINT display_name_not_blank
|
||||||
|
CHECK (length(btrim(display_name)) > 0)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS chats (
|
||||||
|
id UUID PRIMARY KEY,
|
||||||
|
title VARCHAR(100) NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),
|
||||||
|
|
||||||
|
CONSTRAINT title_not_blank
|
||||||
|
CHECK (length(btrim(title)) > 0)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS chat_members (
|
||||||
|
chat_id UUID NOT NULL
|
||||||
|
REFERENCES chats(id) ON DELETE CASCADE,
|
||||||
|
user_id UUID NOT NULL
|
||||||
|
REFERENCES users(id),
|
||||||
|
position INTEGER NOT NULL,
|
||||||
|
|
||||||
|
PRIMARY KEY (chat_id, user_id),
|
||||||
|
UNIQUE (chat_id, position)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS messages (
|
||||||
|
id UUID PRIMARY KEY,
|
||||||
|
chat_id UUID NOT NULL
|
||||||
|
REFERENCES chats(id) ON DELETE CASCADE,
|
||||||
|
sender_id UUID NOT NULL
|
||||||
|
REFERENCES users(id),
|
||||||
|
text TEXT NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),
|
||||||
|
|
||||||
|
CONSTRAINT message_length
|
||||||
|
CHECK (char_length(text) BETWEEN 1 AND 4000),
|
||||||
|
CONSTRAINT message_not_blank
|
||||||
|
CHECK (length(btrim(text)) > 0)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS sessions (
|
||||||
|
token_hash CHAR(64) PRIMARY KEY,
|
||||||
|
user_id UUID NOT NULL
|
||||||
|
REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
expires_at TIMESTAMPTZ NOT NULL,
|
||||||
|
revoked BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp()
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_chat_members_user
|
||||||
|
ON chat_members(user_id, chat_id);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_chats_order
|
||||||
|
ON chats(created_at, id);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_messages_history
|
||||||
|
ON messages(chat_id, created_at, id);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_sessions_user
|
||||||
|
ON sessions(user_id);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_sessions_expiry
|
||||||
|
ON sessions(expires_at);
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS message_idempotency (
|
||||||
|
user_id UUID NOT NULL REFERENCES users(id),
|
||||||
|
chat_id UUID NOT NULL REFERENCES chats(id),
|
||||||
|
idempotency_key VARCHAR(128) NOT NULL,
|
||||||
|
request_hash CHAR(64) NOT NULL,
|
||||||
|
message_id UUID NOT NULL REFERENCES messages(id),
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),
|
||||||
|
|
||||||
|
PRIMARY KEY (user_id, chat_id, idempotency_key)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_idempotency_created
|
||||||
|
ON message_idempotency(created_at);
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS attachments (
|
||||||
|
id UUID PRIMARY KEY,
|
||||||
|
chat_id UUID NOT NULL REFERENCES chats(id),
|
||||||
|
uploader_id UUID NOT NULL REFERENCES users(id),
|
||||||
|
filename TEXT NOT NULL,
|
||||||
|
content_type TEXT NOT NULL,
|
||||||
|
size_bytes BIGINT NOT NULL,
|
||||||
|
sha256 CHAR(64) NOT NULL,
|
||||||
|
object_key TEXT NOT NULL UNIQUE,
|
||||||
|
width INTEGER NOT NULL,
|
||||||
|
height INTEGER NOT NULL,
|
||||||
|
status TEXT NOT NULL DEFAULT 'ready',
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
|
||||||
|
CONSTRAINT attachment_size_valid
|
||||||
|
CHECK (size_bytes BETWEEN 1 AND 10485760),
|
||||||
|
|
||||||
|
CONSTRAINT attachment_dimensions_valid
|
||||||
|
CHECK (width > 0 AND height > 0),
|
||||||
|
|
||||||
|
CONSTRAINT attachment_status_valid
|
||||||
|
CHECK (status IN ('ready', 'failed'))
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_attachments_chat
|
||||||
|
ON attachments(chat_id);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS message_attachments (
|
||||||
|
message_id UUID NOT NULL REFERENCES messages(id),
|
||||||
|
attachment_id UUID NOT NULL REFERENCES attachments(id),
|
||||||
|
|
||||||
|
PRIMARY KEY (message_id, attachment_id)
|
||||||
|
);
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
|
||||||
|
-- Lab4: messages with attachments may have empty text.
|
||||||
|
-- The API checks that a message contains text or attachments.
|
||||||
|
|
||||||
|
ALTER TABLE messages
|
||||||
|
DROP CONSTRAINT IF EXISTS message_length;
|
||||||
|
|
||||||
|
ALTER TABLE messages
|
||||||
|
DROP CONSTRAINT IF EXISTS message_not_blank;
|
||||||
|
|
||||||
|
ALTER TABLE messages
|
||||||
|
ADD CONSTRAINT message_length
|
||||||
|
CHECK (char_length(text) <= 4000);
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
-- Allow asynchronous attachment states.
|
||||||
|
ALTER TABLE attachments
|
||||||
|
DROP CONSTRAINT IF EXISTS attachment_status_valid;
|
||||||
|
|
||||||
|
ALTER TABLE attachments
|
||||||
|
ADD CONSTRAINT attachment_status_valid
|
||||||
|
CHECK (
|
||||||
|
status IN (
|
||||||
|
'queued',
|
||||||
|
'processing',
|
||||||
|
'ready',
|
||||||
|
'failed'
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Staging object stored in the private S3 bucket.
|
||||||
|
ALTER TABLE attachments
|
||||||
|
ADD COLUMN IF NOT EXISTS staging_key TEXT;
|
||||||
|
|
||||||
|
-- Machine-readable final error.
|
||||||
|
ALTER TABLE attachments
|
||||||
|
ADD COLUMN IF NOT EXISTS error_code TEXT;
|
||||||
|
|
||||||
|
-- Last metadata update timestamp.
|
||||||
|
ALTER TABLE attachments
|
||||||
|
ADD COLUMN IF NOT EXISTS updated_at
|
||||||
|
TIMESTAMPTZ NOT NULL DEFAULT NOW();
|
||||||
|
|
||||||
|
-- Worker jobs and durable publication intent.
|
||||||
|
CREATE TABLE IF NOT EXISTS attachment_jobs (
|
||||||
|
id UUID PRIMARY KEY,
|
||||||
|
attachment_id UUID NOT NULL UNIQUE
|
||||||
|
REFERENCES attachments(id),
|
||||||
|
|
||||||
|
status TEXT NOT NULL DEFAULT 'queued',
|
||||||
|
attempts INTEGER NOT NULL DEFAULT 0,
|
||||||
|
max_attempts INTEGER NOT NULL DEFAULT 5,
|
||||||
|
|
||||||
|
published_at TIMESTAMPTZ,
|
||||||
|
started_at TIMESTAMPTZ,
|
||||||
|
completed_at TIMESTAMPTZ,
|
||||||
|
next_attempt_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
|
||||||
|
CONSTRAINT attachment_job_status_valid
|
||||||
|
CHECK (
|
||||||
|
status IN (
|
||||||
|
'queued',
|
||||||
|
'processing',
|
||||||
|
'ready',
|
||||||
|
'failed'
|
||||||
|
)
|
||||||
|
),
|
||||||
|
|
||||||
|
CONSTRAINT attachment_job_attempts_valid
|
||||||
|
CHECK (
|
||||||
|
attempts >= 0
|
||||||
|
AND max_attempts BETWEEN 1 AND 20
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_attachment_jobs_pending
|
||||||
|
ON attachment_jobs(status, next_attempt_at);
|
||||||
|
|
||||||
|
-- Image variants created by the worker.
|
||||||
|
CREATE TABLE IF NOT EXISTS attachment_variants (
|
||||||
|
attachment_id UUID NOT NULL
|
||||||
|
REFERENCES attachments(id),
|
||||||
|
|
||||||
|
variant_name TEXT NOT NULL,
|
||||||
|
object_key TEXT NOT NULL,
|
||||||
|
content_type TEXT NOT NULL,
|
||||||
|
size_bytes BIGINT NOT NULL,
|
||||||
|
sha256 CHAR(64) NOT NULL,
|
||||||
|
width INTEGER NOT NULL,
|
||||||
|
height INTEGER NOT NULL,
|
||||||
|
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||||
|
|
||||||
|
PRIMARY KEY (attachment_id, variant_name),
|
||||||
|
|
||||||
|
CONSTRAINT variant_name_valid
|
||||||
|
CHECK (variant_name IN ('thumbnail')),
|
||||||
|
|
||||||
|
CONSTRAINT variant_size_valid
|
||||||
|
CHECK (size_bytes > 0),
|
||||||
|
|
||||||
|
CONSTRAINT variant_dimensions_valid
|
||||||
|
CHECK (width > 0 AND height > 0)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_attachment_variants_key
|
||||||
|
ON attachment_variants(object_key);
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
|
||||||
|
-- Shared login rate limiter for both API replicas.
|
||||||
|
-- One bucket per normalized username.
|
||||||
|
-- Only SHA-256 of the bucket identity is stored.
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS login_attempt_buckets (
|
||||||
|
bucket_key TEXT PRIMARY KEY,
|
||||||
|
window_started_at TIMESTAMPTZ NOT NULL,
|
||||||
|
attempts INTEGER NOT NULL DEFAULT 0
|
||||||
|
CHECK (attempts >= 0)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS
|
||||||
|
idx_login_attempt_buckets_window
|
||||||
|
ON login_attempt_buckets (window_started_at);
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
-- Lab7 PostgreSQL least-privilege service roles.
|
||||||
|
-- Credentials are provisioned separately by the operator.
|
||||||
|
|
||||||
|
CREATE ROLE messenger_api NOLOGIN;
|
||||||
|
CREATE ROLE messenger_worker NOLOGIN;
|
||||||
|
CREATE ROLE messenger_dispatcher NOLOGIN;
|
||||||
|
|
||||||
|
-- Remove default database and schema privileges.
|
||||||
|
REVOKE ALL ON DATABASE messenger FROM PUBLIC;
|
||||||
|
REVOKE ALL ON SCHEMA public FROM PUBLIC;
|
||||||
|
|
||||||
|
GRANT CONNECT ON DATABASE messenger
|
||||||
|
TO messenger_api, messenger_worker, messenger_dispatcher;
|
||||||
|
|
||||||
|
GRANT USAGE ON SCHEMA public
|
||||||
|
TO messenger_api, messenger_worker, messenger_dispatcher;
|
||||||
|
|
||||||
|
-- API: user accounts and authentication.
|
||||||
|
GRANT SELECT, INSERT ON users TO messenger_api;
|
||||||
|
GRANT SELECT, INSERT, UPDATE ON sessions TO messenger_api;
|
||||||
|
|
||||||
|
-- API: chats and messages.
|
||||||
|
GRANT SELECT, INSERT, UPDATE ON chats TO messenger_api;
|
||||||
|
GRANT SELECT, INSERT, DELETE ON chat_members TO messenger_api;
|
||||||
|
GRANT SELECT, INSERT ON messages TO messenger_api;
|
||||||
|
GRANT SELECT, INSERT ON message_attachments TO messenger_api;
|
||||||
|
GRANT SELECT, INSERT, UPDATE ON message_idempotency TO messenger_api;
|
||||||
|
|
||||||
|
-- API: attachment metadata and asynchronous jobs.
|
||||||
|
GRANT SELECT, INSERT, UPDATE ON attachments TO messenger_api;
|
||||||
|
GRANT SELECT, INSERT, UPDATE ON attachment_jobs TO messenger_api;
|
||||||
|
GRANT SELECT ON attachment_variants TO messenger_api;
|
||||||
|
|
||||||
|
-- API: shared login rate limiter.
|
||||||
|
GRANT SELECT, INSERT, UPDATE ON login_attempt_buckets
|
||||||
|
TO messenger_api;
|
||||||
|
|
||||||
|
-- Worker: only data required for image processing.
|
||||||
|
GRANT SELECT, UPDATE ON attachment_jobs TO messenger_worker;
|
||||||
|
GRANT SELECT, UPDATE ON attachments TO messenger_worker;
|
||||||
|
GRANT SELECT, INSERT, UPDATE ON attachment_variants
|
||||||
|
TO messenger_worker;
|
||||||
|
|
||||||
|
-- Dispatcher: publication state of queued jobs.
|
||||||
|
GRANT SELECT, UPDATE ON attachment_jobs
|
||||||
|
TO messenger_dispatcher;
|
||||||
|
|
||||||
|
-- No application role receives:
|
||||||
|
-- SUPERUSER, CREATEDB, CREATEROLE, REPLICATION
|
||||||
|
-- Ownership of tables
|
||||||
|
-- CREATE on public schema
|
||||||
|
-- Access to schema_migrations
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
-- Lab7: allow API to remove expired idempotency records.
|
||||||
|
-- The send-message handler performs this cleanup.
|
||||||
|
-- No DELETE permission is granted on other tables.
|
||||||
|
|
||||||
|
GRANT DELETE ON TABLE public.message_idempotency
|
||||||
|
TO messenger_api;
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
events {
|
||||||
|
worker_connections 1024;
|
||||||
|
}
|
||||||
|
|
||||||
|
http {
|
||||||
|
resolver 127.0.0.11 valid=2s ipv6=off;
|
||||||
|
resolver_timeout 2s;
|
||||||
|
|
||||||
|
upstream messenger_api {
|
||||||
|
zone messenger_api 64k;
|
||||||
|
|
||||||
|
server api1:8443 resolve max_fails=1 fail_timeout=2s;
|
||||||
|
server api2:8443 resolve max_fails=1 fail_timeout=2s;
|
||||||
|
}
|
||||||
|
|
||||||
|
server {
|
||||||
|
listen 443 ssl;
|
||||||
|
server_name localhost;
|
||||||
|
|
||||||
|
ssl_certificate /run/lab7-pki/ingress.crt;
|
||||||
|
ssl_certificate_key /run/lab7-pki/ingress.key;
|
||||||
|
ssl_protocols TLSv1.2 TLSv1.3;
|
||||||
|
|
||||||
|
client_max_body_size 11m;
|
||||||
|
|
||||||
|
location / {
|
||||||
|
proxy_pass https://messenger_api;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
|
||||||
|
# Verify the server certificate on every API connection.
|
||||||
|
proxy_ssl_trusted_certificate /run/lab7-pki/ca.crt;
|
||||||
|
proxy_ssl_verify on;
|
||||||
|
proxy_ssl_verify_depth 2;
|
||||||
|
|
||||||
|
# Each upstream has its own DNS identity.
|
||||||
|
proxy_ssl_name messenger-api.internal;
|
||||||
|
proxy_ssl_server_name on;
|
||||||
|
|
||||||
|
# Nginx authenticates as the authorized LB.
|
||||||
|
proxy_ssl_certificate /run/lab7-pki/lb-client.crt;
|
||||||
|
proxy_ssl_certificate_key /run/lab7-pki/lb-client.key;
|
||||||
|
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto https;
|
||||||
|
|
||||||
|
proxy_connect_timeout 2s;
|
||||||
|
proxy_read_timeout 30s;
|
||||||
|
proxy_send_timeout 30s;
|
||||||
|
|
||||||
|
proxy_next_upstream error timeout http_502 http_503 http_504;
|
||||||
|
proxy_next_upstream_tries 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,245 @@
|
|||||||
|
{
|
||||||
|
"uid": "messenger-lab6",
|
||||||
|
"title": "Messenger Lab6 - Observability",
|
||||||
|
"tags": ["lab6", "messenger", "opentelemetry"],
|
||||||
|
"timezone": "browser",
|
||||||
|
"schemaVersion": 41,
|
||||||
|
"version": 1,
|
||||||
|
"refresh": "5s",
|
||||||
|
"time": {
|
||||||
|
"from": "now-30m",
|
||||||
|
"to": "now"
|
||||||
|
},
|
||||||
|
"annotations": {
|
||||||
|
"list": []
|
||||||
|
},
|
||||||
|
"templating": {
|
||||||
|
"list": []
|
||||||
|
},
|
||||||
|
"panels": [
|
||||||
|
{
|
||||||
|
"id": 1,
|
||||||
|
"title": "API - Requests per second",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 0, "y": 0, "w": 12, "h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"expr": "sum(rate(messenger_messenger_http_requests_total[2m]))",
|
||||||
|
"legendFormat": "All business requests"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "reqps",
|
||||||
|
"min": 0
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"options": {
|
||||||
|
"legend": {
|
||||||
|
"displayMode": "list",
|
||||||
|
"placement": "bottom"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 2,
|
||||||
|
"title": "API - HTTP 5xx error ratio",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 12, "y": 0, "w": 12, "h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"expr": "(100 * sum(rate(messenger_messenger_http_requests_total{http_status_class=\"5xx\"}[2m])) / clamp_min(sum(rate(messenger_messenger_http_requests_total[2m])), 0.000001)) or vector(0)",
|
||||||
|
"legendFormat": "5xx / all business requests"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "percent",
|
||||||
|
"min": 0,
|
||||||
|
"max": 100
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 3,
|
||||||
|
"title": "API - HTTP p95 duration",
|
||||||
|
"description": "OTel FastAPI duration histogram is in milliseconds; result converted to seconds.",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 0, "y": 8, "w": 12, "h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_http_server_duration_milliseconds_bucket[5m]))) / 1000",
|
||||||
|
"legendFormat": "p95 HTTP duration"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "s",
|
||||||
|
"min": 0
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 4,
|
||||||
|
"title": "Worker - Jobs by outcome",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 12, "y": 8, "w": 12, "h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"expr": "sum by (outcome) (increase(messenger_messenger_worker_jobs_processed_total[5m]))",
|
||||||
|
"legendFormat": "{{outcome}}"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "short",
|
||||||
|
"min": 0
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 5,
|
||||||
|
"title": "Worker - Processing p95 duration",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 0, "y": 16, "w": 12, "h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_messenger_worker_job_duration_seconds_bucket[5m])))",
|
||||||
|
"legendFormat": "p95 job duration"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "s",
|
||||||
|
"min": 0
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 6,
|
||||||
|
"title": "Worker - Completed job attempts",
|
||||||
|
"type": "stat",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 12, "y": 16, "w": 12, "h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"expr": "sum(messenger_messenger_worker_jobs_processed_total)",
|
||||||
|
"legendFormat": "Processing attempts"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "short",
|
||||||
|
"decimals": 0
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"options": {
|
||||||
|
"reduceOptions": {
|
||||||
|
"values": false,
|
||||||
|
"calcs": ["lastNotNull"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 7,
|
||||||
|
"title": "API - Structured logs",
|
||||||
|
"type": "logs",
|
||||||
|
"datasource": {
|
||||||
|
"type": "loki",
|
||||||
|
"uid": "loki"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 0, "y": 24, "w": 24, "h": 9
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"expr": "{service_name=\"messenger-api\"}",
|
||||||
|
"queryType": "range"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"options": {
|
||||||
|
"showTime": true,
|
||||||
|
"showLabels": true,
|
||||||
|
"showCommonLabels": false,
|
||||||
|
"enableLogDetails": true,
|
||||||
|
"wrapLogMessage": true,
|
||||||
|
"sortOrder": "Descending"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 8,
|
||||||
|
"title": "Worker - Structured logs",
|
||||||
|
"type": "logs",
|
||||||
|
"datasource": {
|
||||||
|
"type": "loki",
|
||||||
|
"uid": "loki"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 0, "y": 33, "w": 24, "h": 9
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"expr": "{service_name=\"messenger-worker\"}",
|
||||||
|
"queryType": "range"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"options": {
|
||||||
|
"showTime": true,
|
||||||
|
"showLabels": true,
|
||||||
|
"showCommonLabels": false,
|
||||||
|
"enableLogDetails": true,
|
||||||
|
"wrapLogMessage": true,
|
||||||
|
"sortOrder": "Descending"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
apiVersion: 1
|
||||||
|
|
||||||
|
providers:
|
||||||
|
- name: Messenger Lab6
|
||||||
|
orgId: 1
|
||||||
|
folder: Messenger Lab6
|
||||||
|
type: file
|
||||||
|
disableDeletion: false
|
||||||
|
editable: false
|
||||||
|
options:
|
||||||
|
path: /var/lib/grafana/dashboards
|
||||||
@@ -0,0 +1,197 @@
|
|||||||
|
apiVersion: 1
|
||||||
|
datasources:
|
||||||
|
- name: Prometheus
|
||||||
|
uid: prometheus
|
||||||
|
type: prometheus
|
||||||
|
access: proxy
|
||||||
|
url: https://prometheus:9090
|
||||||
|
isDefault: true
|
||||||
|
editable: false
|
||||||
|
jsonData:
|
||||||
|
tlsAuthWithCACert: true
|
||||||
|
tlsSkipVerify: false
|
||||||
|
secureJsonData:
|
||||||
|
tlsCACert: '-----BEGIN CERTIFICATE-----
|
||||||
|
|
||||||
|
MIIEMDCCApigAwIBAgIUDVTLymvpgcpMx4D1lOpkjNGmE+YwDQYJKoZIhvcNAQEL
|
||||||
|
|
||||||
|
BQAwHjEcMBoGA1UEAwwTTVRVU0kgTGFiNyBMb2NhbCBDQTAeFw0yNjExMjExODI3
|
||||||
|
|
||||||
|
MzlaFw0yNzExMjExODI3MzlaMB4xHDAaBgNVBAMME01UVVNJIExhYjcgTG9jYWwg
|
||||||
|
|
||||||
|
Q0EwggGiMA0GCSqGSIb3DQEBAQUAA4IBjwAwggGKAoIBgQCRZMyUu/CIiTGmasLt
|
||||||
|
|
||||||
|
wC4GazWCsDvNKojZHaws0/4WeG13gzgdKUCXs7l1PkhWIzbOa+uVChu9IUfY4mtj
|
||||||
|
|
||||||
|
Hole17SLbDj4yKit14mfdwvCRZaCgm5AuoMhulmd1DhHvRh/bwhKu7CJ1dnVlRpK
|
||||||
|
|
||||||
|
vyDJ4vbqtOa4nvGRJwAWciAejScq1C1oISQuZea/6a1DgzEHHRZhGV0SVhh+mBJI
|
||||||
|
|
||||||
|
HNugZZ6QWtV45Rdho3VouXl5zjGOtHQ2p6JBckAgfkGFG+mNA7BNQW2Xx8zIe6eK
|
||||||
|
|
||||||
|
cKLaKFPkW2ri5sPt0b7VVHiSr+vU9Smd5jJwliacCZmyqNtP1IkN7unNNx5f3Agd
|
||||||
|
|
||||||
|
HVdlbkxKIodKOGWfvqTisZQOsm0MEUFUChXsN9pQJ5IXfAoFCad9zWWZKT1CPHzA
|
||||||
|
|
||||||
|
H1iV7gDvo5TXVsmOuIEUHkECeBNdLYcdTNmgmJxrs4fMe7slvBi8wA0rNlAoRH+u
|
||||||
|
|
||||||
|
O8ggcgTMbeuovXNR4Sqb3XKluscDfD2MVknJ6v3HzxAImf0CAwEAAaNmMGQwHQYD
|
||||||
|
|
||||||
|
VR0OBBYEFMiQR7DUGXndbL0HZHpi3OK5lxSCMB8GA1UdIwQYMBaAFMiQR7DUGXnd
|
||||||
|
|
||||||
|
bL0HZHpi3OK5lxSCMBIGA1UdEwEB/wQIMAYBAf8CAQAwDgYDVR0PAQH/BAQDAgEG
|
||||||
|
|
||||||
|
MA0GCSqGSIb3DQEBCwUAA4IBgQAB9ptJKxcbPbB5L6cLpZiUM081qRnj/1FSMR2W
|
||||||
|
|
||||||
|
BcgfzZE5jBI2J3Fq1bfch919vi5/sp6DkCr4/YQbrSbPCPL34HlVfgSs2P42NKY4
|
||||||
|
|
||||||
|
FJ5uVhKZRz6IAFpKvzZf7mx6Z7BgG+3TnIJX589PgZlMotLHvZsgHnpWBq0cP202
|
||||||
|
|
||||||
|
/CRadfsUwSUXRGgJ0lehyJlNNakuc5wpNNa9+8UG0VjpidtBbU+xQFaOzq3cb2Xf
|
||||||
|
|
||||||
|
bvFb7pA7lOLTZEJiv0Bcde/AQ05GmbCHi8xIj3PkoD+D8xKBXQosZojovEc7B7HD
|
||||||
|
|
||||||
|
AdRVO3tHpX/kW6PgGc5pinqPqcvUwXNltonDJr9OrkGPIJ4ozWDjCO3pRtC3nX1H
|
||||||
|
|
||||||
|
jVoEFjmhYlknK1t5kmOGsfnOw9xy6Ci0Qa++404BsWbGYFCqIK7KurxyGxAfgsms
|
||||||
|
|
||||||
|
KC3QuJss4jjDWO5jT3yw3EUFw6A5TU+P1ixVax0OdJ4yXar5hIo0eFN+WzhMYR0q
|
||||||
|
|
||||||
|
Grh571D/oJPXICFvimxOP3dG71I=
|
||||||
|
|
||||||
|
-----END CERTIFICATE-----
|
||||||
|
|
||||||
|
'
|
||||||
|
- name: Loki
|
||||||
|
uid: loki
|
||||||
|
type: loki
|
||||||
|
access: proxy
|
||||||
|
url: https://loki:3100
|
||||||
|
editable: false
|
||||||
|
jsonData:
|
||||||
|
tlsAuthWithCACert: true
|
||||||
|
tlsSkipVerify: false
|
||||||
|
derivedFields:
|
||||||
|
- name: TraceID
|
||||||
|
matcherRegex: trace_id=([a-f0-9]{32})
|
||||||
|
datasourceUid: tempo
|
||||||
|
url: $${__value.raw}
|
||||||
|
secureJsonData:
|
||||||
|
tlsCACert: '-----BEGIN CERTIFICATE-----
|
||||||
|
|
||||||
|
MIIEMDCCApigAwIBAgIUDVTLymvpgcpMx4D1lOpkjNGmE+YwDQYJKoZIhvcNAQEL
|
||||||
|
|
||||||
|
BQAwHjEcMBoGA1UEAwwTTVRVU0kgTGFiNyBMb2NhbCBDQTAeFw0yNjExMjExODI3
|
||||||
|
|
||||||
|
MzlaFw0yNzExMjExODI3MzlaMB4xHDAaBgNVBAMME01UVVNJIExhYjcgTG9jYWwg
|
||||||
|
|
||||||
|
Q0EwggGiMA0GCSqGSIb3DQEBAQUAA4IBjwAwggGKAoIBgQCRZMyUu/CIiTGmasLt
|
||||||
|
|
||||||
|
wC4GazWCsDvNKojZHaws0/4WeG13gzgdKUCXs7l1PkhWIzbOa+uVChu9IUfY4mtj
|
||||||
|
|
||||||
|
Hole17SLbDj4yKit14mfdwvCRZaCgm5AuoMhulmd1DhHvRh/bwhKu7CJ1dnVlRpK
|
||||||
|
|
||||||
|
vyDJ4vbqtOa4nvGRJwAWciAejScq1C1oISQuZea/6a1DgzEHHRZhGV0SVhh+mBJI
|
||||||
|
|
||||||
|
HNugZZ6QWtV45Rdho3VouXl5zjGOtHQ2p6JBckAgfkGFG+mNA7BNQW2Xx8zIe6eK
|
||||||
|
|
||||||
|
cKLaKFPkW2ri5sPt0b7VVHiSr+vU9Smd5jJwliacCZmyqNtP1IkN7unNNx5f3Agd
|
||||||
|
|
||||||
|
HVdlbkxKIodKOGWfvqTisZQOsm0MEUFUChXsN9pQJ5IXfAoFCad9zWWZKT1CPHzA
|
||||||
|
|
||||||
|
H1iV7gDvo5TXVsmOuIEUHkECeBNdLYcdTNmgmJxrs4fMe7slvBi8wA0rNlAoRH+u
|
||||||
|
|
||||||
|
O8ggcgTMbeuovXNR4Sqb3XKluscDfD2MVknJ6v3HzxAImf0CAwEAAaNmMGQwHQYD
|
||||||
|
|
||||||
|
VR0OBBYEFMiQR7DUGXndbL0HZHpi3OK5lxSCMB8GA1UdIwQYMBaAFMiQR7DUGXnd
|
||||||
|
|
||||||
|
bL0HZHpi3OK5lxSCMBIGA1UdEwEB/wQIMAYBAf8CAQAwDgYDVR0PAQH/BAQDAgEG
|
||||||
|
|
||||||
|
MA0GCSqGSIb3DQEBCwUAA4IBgQAB9ptJKxcbPbB5L6cLpZiUM081qRnj/1FSMR2W
|
||||||
|
|
||||||
|
BcgfzZE5jBI2J3Fq1bfch919vi5/sp6DkCr4/YQbrSbPCPL34HlVfgSs2P42NKY4
|
||||||
|
|
||||||
|
FJ5uVhKZRz6IAFpKvzZf7mx6Z7BgG+3TnIJX589PgZlMotLHvZsgHnpWBq0cP202
|
||||||
|
|
||||||
|
/CRadfsUwSUXRGgJ0lehyJlNNakuc5wpNNa9+8UG0VjpidtBbU+xQFaOzq3cb2Xf
|
||||||
|
|
||||||
|
bvFb7pA7lOLTZEJiv0Bcde/AQ05GmbCHi8xIj3PkoD+D8xKBXQosZojovEc7B7HD
|
||||||
|
|
||||||
|
AdRVO3tHpX/kW6PgGc5pinqPqcvUwXNltonDJr9OrkGPIJ4ozWDjCO3pRtC3nX1H
|
||||||
|
|
||||||
|
jVoEFjmhYlknK1t5kmOGsfnOw9xy6Ci0Qa++404BsWbGYFCqIK7KurxyGxAfgsms
|
||||||
|
|
||||||
|
KC3QuJss4jjDWO5jT3yw3EUFw6A5TU+P1ixVax0OdJ4yXar5hIo0eFN+WzhMYR0q
|
||||||
|
|
||||||
|
Grh571D/oJPXICFvimxOP3dG71I=
|
||||||
|
|
||||||
|
-----END CERTIFICATE-----
|
||||||
|
|
||||||
|
'
|
||||||
|
- name: Tempo
|
||||||
|
uid: tempo
|
||||||
|
type: tempo
|
||||||
|
access: proxy
|
||||||
|
url: https://tempo:3200
|
||||||
|
editable: false
|
||||||
|
jsonData:
|
||||||
|
tracesToLogsV2:
|
||||||
|
datasourceUid: loki
|
||||||
|
filterByTraceID: true
|
||||||
|
filterBySpanID: false
|
||||||
|
nodeGraph:
|
||||||
|
enabled: true
|
||||||
|
tlsAuthWithCACert: true
|
||||||
|
tlsSkipVerify: false
|
||||||
|
secureJsonData:
|
||||||
|
tlsCACert: '-----BEGIN CERTIFICATE-----
|
||||||
|
|
||||||
|
MIIEMDCCApigAwIBAgIUDVTLymvpgcpMx4D1lOpkjNGmE+YwDQYJKoZIhvcNAQEL
|
||||||
|
|
||||||
|
BQAwHjEcMBoGA1UEAwwTTVRVU0kgTGFiNyBMb2NhbCBDQTAeFw0yNjExMjExODI3
|
||||||
|
|
||||||
|
MzlaFw0yNzExMjExODI3MzlaMB4xHDAaBgNVBAMME01UVVNJIExhYjcgTG9jYWwg
|
||||||
|
|
||||||
|
Q0EwggGiMA0GCSqGSIb3DQEBAQUAA4IBjwAwggGKAoIBgQCRZMyUu/CIiTGmasLt
|
||||||
|
|
||||||
|
wC4GazWCsDvNKojZHaws0/4WeG13gzgdKUCXs7l1PkhWIzbOa+uVChu9IUfY4mtj
|
||||||
|
|
||||||
|
Hole17SLbDj4yKit14mfdwvCRZaCgm5AuoMhulmd1DhHvRh/bwhKu7CJ1dnVlRpK
|
||||||
|
|
||||||
|
vyDJ4vbqtOa4nvGRJwAWciAejScq1C1oISQuZea/6a1DgzEHHRZhGV0SVhh+mBJI
|
||||||
|
|
||||||
|
HNugZZ6QWtV45Rdho3VouXl5zjGOtHQ2p6JBckAgfkGFG+mNA7BNQW2Xx8zIe6eK
|
||||||
|
|
||||||
|
cKLaKFPkW2ri5sPt0b7VVHiSr+vU9Smd5jJwliacCZmyqNtP1IkN7unNNx5f3Agd
|
||||||
|
|
||||||
|
HVdlbkxKIodKOGWfvqTisZQOsm0MEUFUChXsN9pQJ5IXfAoFCad9zWWZKT1CPHzA
|
||||||
|
|
||||||
|
H1iV7gDvo5TXVsmOuIEUHkECeBNdLYcdTNmgmJxrs4fMe7slvBi8wA0rNlAoRH+u
|
||||||
|
|
||||||
|
O8ggcgTMbeuovXNR4Sqb3XKluscDfD2MVknJ6v3HzxAImf0CAwEAAaNmMGQwHQYD
|
||||||
|
|
||||||
|
VR0OBBYEFMiQR7DUGXndbL0HZHpi3OK5lxSCMB8GA1UdIwQYMBaAFMiQR7DUGXnd
|
||||||
|
|
||||||
|
bL0HZHpi3OK5lxSCMBIGA1UdEwEB/wQIMAYBAf8CAQAwDgYDVR0PAQH/BAQDAgEG
|
||||||
|
|
||||||
|
MA0GCSqGSIb3DQEBCwUAA4IBgQAB9ptJKxcbPbB5L6cLpZiUM081qRnj/1FSMR2W
|
||||||
|
|
||||||
|
BcgfzZE5jBI2J3Fq1bfch919vi5/sp6DkCr4/YQbrSbPCPL34HlVfgSs2P42NKY4
|
||||||
|
|
||||||
|
FJ5uVhKZRz6IAFpKvzZf7mx6Z7BgG+3TnIJX589PgZlMotLHvZsgHnpWBq0cP202
|
||||||
|
|
||||||
|
/CRadfsUwSUXRGgJ0lehyJlNNakuc5wpNNa9+8UG0VjpidtBbU+xQFaOzq3cb2Xf
|
||||||
|
|
||||||
|
bvFb7pA7lOLTZEJiv0Bcde/AQ05GmbCHi8xIj3PkoD+D8xKBXQosZojovEc7B7HD
|
||||||
|
|
||||||
|
AdRVO3tHpX/kW6PgGc5pinqPqcvUwXNltonDJr9OrkGPIJ4ozWDjCO3pRtC3nX1H
|
||||||
|
|
||||||
|
jVoEFjmhYlknK1t5kmOGsfnOw9xy6Ci0Qa++404BsWbGYFCqIK7KurxyGxAfgsms
|
||||||
|
|
||||||
|
KC3QuJss4jjDWO5jT3yw3EUFw6A5TU+P1ixVax0OdJ4yXar5hIo0eFN+WzhMYR0q
|
||||||
|
|
||||||
|
Grh571D/oJPXICFvimxOP3dG71I=
|
||||||
|
|
||||||
|
-----END CERTIFICATE-----
|
||||||
|
|
||||||
|
'
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
|
||||||
|
auth_enabled: false
|
||||||
|
|
||||||
|
server:
|
||||||
|
http_listen_port: 3100
|
||||||
|
http_tls_config:
|
||||||
|
cert_file: /run/loki/server.crt
|
||||||
|
key_file: /run/loki/server.key
|
||||||
|
|
||||||
|
common:
|
||||||
|
path_prefix: /loki
|
||||||
|
replication_factor: 1
|
||||||
|
ring:
|
||||||
|
kvstore:
|
||||||
|
store: inmemory
|
||||||
|
|
||||||
|
schema_config:
|
||||||
|
configs:
|
||||||
|
- from: "2024-01-01"
|
||||||
|
store: tsdb
|
||||||
|
object_store: filesystem
|
||||||
|
schema: v13
|
||||||
|
index:
|
||||||
|
prefix: index_
|
||||||
|
period: 24h
|
||||||
|
|
||||||
|
storage_config:
|
||||||
|
filesystem:
|
||||||
|
directory: /loki/chunks
|
||||||
|
|
||||||
|
tsdb_shipper:
|
||||||
|
active_index_directory: /loki/index
|
||||||
|
cache_location: /loki/index_cache
|
||||||
|
|
||||||
|
limits_config:
|
||||||
|
allow_structured_metadata: true
|
||||||
|
|
||||||
|
analytics:
|
||||||
|
reporting_enabled: false
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
|
||||||
|
receivers:
|
||||||
|
otlp/secure:
|
||||||
|
protocols:
|
||||||
|
grpc:
|
||||||
|
endpoint: 0.0.0.0:4319
|
||||||
|
tls:
|
||||||
|
cert_file: /run/telemetry/server.crt
|
||||||
|
key_file: /run/telemetry/server.key
|
||||||
|
http:
|
||||||
|
endpoint: 0.0.0.0:4320
|
||||||
|
tls:
|
||||||
|
cert_file: /run/telemetry/server.crt
|
||||||
|
key_file: /run/telemetry/server.key
|
||||||
|
|
||||||
|
processors:
|
||||||
|
memory_limiter:
|
||||||
|
check_interval: 1s
|
||||||
|
limit_mib: 256
|
||||||
|
spike_limit_mib: 64
|
||||||
|
|
||||||
|
batch:
|
||||||
|
timeout: 5s
|
||||||
|
send_batch_size: 512
|
||||||
|
|
||||||
|
exporters:
|
||||||
|
prometheus:
|
||||||
|
endpoint: 0.0.0.0:8889
|
||||||
|
tls:
|
||||||
|
cert_file: /run/telemetry/server.crt
|
||||||
|
key_file: /run/telemetry/server.key
|
||||||
|
namespace: messenger
|
||||||
|
resource_to_telemetry_conversion:
|
||||||
|
enabled: true
|
||||||
|
|
||||||
|
otlp/tempo:
|
||||||
|
endpoint: tempo:4317
|
||||||
|
tls:
|
||||||
|
insecure: false
|
||||||
|
ca_file: /run/telemetry/ca.crt
|
||||||
|
server_name_override: tempo
|
||||||
|
cert_file: /run/telemetry/client.crt
|
||||||
|
key_file: /run/telemetry/client.key
|
||||||
|
sending_queue:
|
||||||
|
enabled: true
|
||||||
|
queue_size: 1000
|
||||||
|
retry_on_failure:
|
||||||
|
enabled: true
|
||||||
|
|
||||||
|
otlphttp/loki:
|
||||||
|
endpoint: https://loki:3100/otlp
|
||||||
|
tls:
|
||||||
|
insecure: false
|
||||||
|
ca_file: /run/telemetry/ca.crt
|
||||||
|
server_name_override: loki
|
||||||
|
sending_queue:
|
||||||
|
enabled: true
|
||||||
|
queue_size: 1000
|
||||||
|
retry_on_failure:
|
||||||
|
enabled: true
|
||||||
|
|
||||||
|
extensions:
|
||||||
|
health_check:
|
||||||
|
endpoint: 0.0.0.0:13133
|
||||||
|
|
||||||
|
service:
|
||||||
|
extensions:
|
||||||
|
- health_check
|
||||||
|
|
||||||
|
pipelines:
|
||||||
|
traces:
|
||||||
|
receivers: [otlp/secure]
|
||||||
|
processors: [memory_limiter, batch]
|
||||||
|
exporters: [otlp/tempo]
|
||||||
|
|
||||||
|
metrics:
|
||||||
|
receivers: [otlp/secure]
|
||||||
|
processors: [memory_limiter, batch]
|
||||||
|
exporters: [prometheus]
|
||||||
|
|
||||||
|
logs:
|
||||||
|
receivers: [otlp/secure]
|
||||||
|
processors: [memory_limiter, batch]
|
||||||
|
exporters: [otlphttp/loki]
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
tls_server_config:
|
||||||
|
cert_file: /run/prometheus/server.crt
|
||||||
|
key_file: /run/prometheus/server.key
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
global:
|
||||||
|
scrape_interval: 5s
|
||||||
|
evaluation_interval: 5s
|
||||||
|
|
||||||
|
scrape_configs:
|
||||||
|
- job_name: otel-collector
|
||||||
|
scheme: https
|
||||||
|
tls_config:
|
||||||
|
ca_file: /etc/prometheus/lab7-ca.crt
|
||||||
|
server_name: otel-collector
|
||||||
|
static_configs:
|
||||||
|
- targets:
|
||||||
|
- otel-collector:8889
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
server:
|
||||||
|
http_listen_port: 3200
|
||||||
|
http_tls_config:
|
||||||
|
cert_file: /run/tempo/server.crt
|
||||||
|
key_file: /run/tempo/server.key
|
||||||
|
distributor:
|
||||||
|
receivers:
|
||||||
|
otlp:
|
||||||
|
protocols:
|
||||||
|
grpc:
|
||||||
|
endpoint: 0.0.0.0:4317
|
||||||
|
tls:
|
||||||
|
cert_file: /run/tempo/server.crt
|
||||||
|
key_file: /run/tempo/server.key
|
||||||
|
client_ca_file: /run/tempo/ca.crt
|
||||||
|
min_version: '1.2'
|
||||||
|
ingester:
|
||||||
|
trace_idle_period: 10s
|
||||||
|
compactor:
|
||||||
|
compaction:
|
||||||
|
block_retention: 48h
|
||||||
|
storage:
|
||||||
|
trace:
|
||||||
|
backend: local
|
||||||
|
wal:
|
||||||
|
path: /var/tempo/wal
|
||||||
|
local:
|
||||||
|
path: /var/tempo/traces
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
fastapi==0.115.12
|
||||||
|
uvicorn==0.34.2
|
||||||
|
psycopg[binary]==3.2.6
|
||||||
|
argon2-cffi==23.1.0
|
||||||
|
boto3==1.40.70
|
||||||
|
Pillow==11.2.1
|
||||||
|
pika==1.3.2
|
||||||
|
opentelemetry-api==1.38.0
|
||||||
|
opentelemetry-sdk==1.38.0
|
||||||
|
opentelemetry-exporter-otlp-proto-http==1.38.0
|
||||||
|
opentelemetry-instrumentation-fastapi==0.59b0
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
|
||||||
|
import statistics
|
||||||
|
import time
|
||||||
|
|
||||||
|
from argon2 import PasswordHasher, Type
|
||||||
|
|
||||||
|
PASSWORD = "Lab7-Benchmark-Password-2026"
|
||||||
|
ITERATIONS = 10
|
||||||
|
|
||||||
|
CONFIGURATIONS = [
|
||||||
|
("baseline", 19456, 2, 1),
|
||||||
|
("stronger", 32768, 3, 1),
|
||||||
|
("high-memory", 65536, 3, 1),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def benchmark(name, memory, time_cost, parallelism):
|
||||||
|
hasher = PasswordHasher(
|
||||||
|
memory_cost=memory,
|
||||||
|
time_cost=time_cost,
|
||||||
|
parallelism=parallelism,
|
||||||
|
hash_len=32,
|
||||||
|
salt_len=16,
|
||||||
|
type=Type.ID,
|
||||||
|
)
|
||||||
|
|
||||||
|
samples = []
|
||||||
|
|
||||||
|
# Warm-up, excluded from measurements.
|
||||||
|
sample_hash = hasher.hash(PASSWORD)
|
||||||
|
assert hasher.verify(sample_hash, PASSWORD)
|
||||||
|
|
||||||
|
for _ in range(ITERATIONS):
|
||||||
|
start = time.perf_counter()
|
||||||
|
password_hash = hasher.hash(PASSWORD)
|
||||||
|
elapsed = (time.perf_counter() - start) * 1000
|
||||||
|
|
||||||
|
assert hasher.verify(password_hash, PASSWORD)
|
||||||
|
assert password_hash.startswith("$argon2id$")
|
||||||
|
|
||||||
|
samples.append(elapsed)
|
||||||
|
|
||||||
|
print(
|
||||||
|
f"{name}: "
|
||||||
|
f"memory={memory} KiB, "
|
||||||
|
f"t={time_cost}, "
|
||||||
|
f"p={parallelism}, "
|
||||||
|
f"median={statistics.median(samples):.2f} ms, "
|
||||||
|
f"min={min(samples):.2f} ms, "
|
||||||
|
f"max={max(samples):.2f} ms"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
for configuration in CONFIGURATIONS:
|
||||||
|
benchmark(*configuration)
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
|
||||||
|
import os
|
||||||
|
import secrets
|
||||||
|
import subprocess
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ENV_FILE = Path(".env")
|
||||||
|
|
||||||
|
ROLES = {
|
||||||
|
"messenger_api": "API_DB_PASSWORD",
|
||||||
|
"messenger_worker": "WORKER_DB_PASSWORD",
|
||||||
|
"messenger_dispatcher": "DISPATCHER_DB_PASSWORD",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
if not ENV_FILE.is_file():
|
||||||
|
raise SystemExit("ERROR: .env not found")
|
||||||
|
|
||||||
|
lines = ENV_FILE.read_text(encoding="utf-8").splitlines()
|
||||||
|
|
||||||
|
existing_keys = {
|
||||||
|
line.split("=", 1)[0]
|
||||||
|
for line in lines
|
||||||
|
if "=" in line and not line.startswith("#")
|
||||||
|
}
|
||||||
|
|
||||||
|
for env_name in ROLES.values():
|
||||||
|
if env_name in existing_keys:
|
||||||
|
raise SystemExit(
|
||||||
|
f"ERROR: {env_name} already exists. "
|
||||||
|
"Refusing to overwrite credentials."
|
||||||
|
)
|
||||||
|
|
||||||
|
# Hexadecimal passwords are easy to use in connection URIs.
|
||||||
|
passwords = {
|
||||||
|
role: secrets.token_hex(32)
|
||||||
|
for role in ROLES
|
||||||
|
}
|
||||||
|
|
||||||
|
# Passwords are sent to psql via stdin.
|
||||||
|
# They are not passed as command-line arguments.
|
||||||
|
statements = ["BEGIN;"]
|
||||||
|
|
||||||
|
for role, password in passwords.items():
|
||||||
|
statements.append(
|
||||||
|
f"ALTER ROLE {role} "
|
||||||
|
f"WITH LOGIN PASSWORD '{password}';"
|
||||||
|
)
|
||||||
|
|
||||||
|
statements.append("COMMIT;")
|
||||||
|
|
||||||
|
sql = "\n".join(statements) + "\n"
|
||||||
|
|
||||||
|
command = [
|
||||||
|
"docker", "compose", "exec", "-T",
|
||||||
|
"db",
|
||||||
|
"psql",
|
||||||
|
"-X",
|
||||||
|
"-v", "ON_ERROR_STOP=1",
|
||||||
|
"-U", "messenger",
|
||||||
|
"-d", "messenger",
|
||||||
|
"-q",
|
||||||
|
]
|
||||||
|
|
||||||
|
result = subprocess.run(
|
||||||
|
command,
|
||||||
|
input=sql,
|
||||||
|
text=True,
|
||||||
|
stdout=subprocess.PIPE,
|
||||||
|
stderr=subprocess.PIPE,
|
||||||
|
)
|
||||||
|
|
||||||
|
if result.returncode != 0:
|
||||||
|
print("ERROR: PostgreSQL role configuration failed.")
|
||||||
|
print("Check database availability and permissions.")
|
||||||
|
raise SystemExit(1)
|
||||||
|
|
||||||
|
# Update the ignored local .env only after SQL succeeds.
|
||||||
|
# No secret values are printed.
|
||||||
|
with ENV_FILE.open("a", encoding="utf-8") as file:
|
||||||
|
file.write("\n# Lab7 scoped database credentials\n")
|
||||||
|
|
||||||
|
for role, env_name in ROLES.items():
|
||||||
|
file.write(f"{env_name}={passwords[role]}\n")
|
||||||
|
|
||||||
|
os.chmod(ENV_FILE, 0o600)
|
||||||
|
|
||||||
|
print("PASS: PostgreSQL service roles enabled.")
|
||||||
|
print("PASS: Independent credentials generated.")
|
||||||
|
print("PASS: Credentials saved to ignored .env.")
|
||||||
|
print("Secret values were not displayed.")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
umask 077
|
||||||
|
|
||||||
|
BASE="$HOME/.local/share/mtusi2026lab7/pki"
|
||||||
|
DEST="$BASE/openbao-clients"
|
||||||
|
|
||||||
|
test -f "$BASE/ca.crt"
|
||||||
|
test -f "$BASE/ca.key"
|
||||||
|
|
||||||
|
mkdir -p "$DEST"
|
||||||
|
chmod 700 "$DEST"
|
||||||
|
|
||||||
|
for service in api1 api2 worker; do
|
||||||
|
cert="$DEST/${service}.crt"
|
||||||
|
key="$DEST/${service}.key"
|
||||||
|
|
||||||
|
if [[ -e "$cert" || -e "$key" ]]; then
|
||||||
|
echo "FAIL: certificate already exists for $service" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
for service in api1 api2 worker; do
|
||||||
|
name="lab7-openbao-${service}"
|
||||||
|
|
||||||
|
temp="$(mktemp -d "$DEST/.${service}.XXXXXX")"
|
||||||
|
|
||||||
|
openssl req \
|
||||||
|
-new \
|
||||||
|
-newkey rsa:3072 \
|
||||||
|
-nodes \
|
||||||
|
-keyout "$temp/client.key" \
|
||||||
|
-out "$temp/client.csr" \
|
||||||
|
-subj "/CN=$name" \
|
||||||
|
>/dev/null 2>&1
|
||||||
|
|
||||||
|
cat > "$temp/extensions.cnf" <<EOF
|
||||||
|
basicConstraints=critical,CA:FALSE
|
||||||
|
keyUsage=critical,digitalSignature
|
||||||
|
extendedKeyUsage=clientAuth
|
||||||
|
subjectKeyIdentifier=hash
|
||||||
|
EOF
|
||||||
|
|
||||||
|
serial="0x$(openssl rand -hex 16)"
|
||||||
|
|
||||||
|
openssl x509 \
|
||||||
|
-req \
|
||||||
|
-in "$temp/client.csr" \
|
||||||
|
-CA "$BASE/ca.crt" \
|
||||||
|
-CAkey "$BASE/ca.key" \
|
||||||
|
-set_serial "$serial" \
|
||||||
|
-out "$temp/client.crt" \
|
||||||
|
-days 180 \
|
||||||
|
-sha256 \
|
||||||
|
-extfile "$temp/extensions.cnf" \
|
||||||
|
>/dev/null 2>&1
|
||||||
|
|
||||||
|
chmod 600 "$temp/client.key"
|
||||||
|
chmod 644 "$temp/client.crt"
|
||||||
|
|
||||||
|
mv "$temp/client.key" "$DEST/${service}.key"
|
||||||
|
mv "$temp/client.crt" "$DEST/${service}.crt"
|
||||||
|
|
||||||
|
rm -rf -- "$temp"
|
||||||
|
|
||||||
|
echo "PASS: OpenBao client certificate issued for $service"
|
||||||
|
done
|
||||||
|
|
||||||
|
echo "PASS: three separate OpenBao client identities created"
|
||||||
@@ -0,0 +1,236 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Copy existing API/worker credentials to OpenBao KV v2."""
|
||||||
|
|
||||||
|
import hmac
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import ssl
|
||||||
|
import stat
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import urllib.error
|
||||||
|
import urllib.request
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
BASE = Path.home() / ".local/share/mtusi2026lab7"
|
||||||
|
INIT_FILE = BASE / "operator/openbao-init.json"
|
||||||
|
CA_FILE = BASE / "pki/ca.crt"
|
||||||
|
|
||||||
|
BAO_URL = "https://localhost:8200"
|
||||||
|
|
||||||
|
SECRET_FIELDS = {
|
||||||
|
"api": (
|
||||||
|
"DATABASE_URL",
|
||||||
|
"S3_ACCESS_KEY",
|
||||||
|
"S3_SECRET_KEY",
|
||||||
|
),
|
||||||
|
"worker": (
|
||||||
|
"DATABASE_URL",
|
||||||
|
"RABBITMQ_USER",
|
||||||
|
"RABBITMQ_PASSWORD",
|
||||||
|
"S3_ACCESS_KEY",
|
||||||
|
"S3_SECRET_KEY",
|
||||||
|
),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def check(condition, message):
|
||||||
|
if not condition:
|
||||||
|
raise RuntimeError(message)
|
||||||
|
print("PASS:", message)
|
||||||
|
|
||||||
|
|
||||||
|
def request(method, path, token, context, payload=None):
|
||||||
|
data = None
|
||||||
|
if payload is not None:
|
||||||
|
data = json.dumps(payload).encode("utf-8")
|
||||||
|
|
||||||
|
headers = {"X-Vault-Token": token}
|
||||||
|
|
||||||
|
if data is not None:
|
||||||
|
headers["Content-Type"] = "application/json"
|
||||||
|
|
||||||
|
req = urllib.request.Request(
|
||||||
|
BAO_URL + path,
|
||||||
|
data=data,
|
||||||
|
headers=headers,
|
||||||
|
method=method,
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(
|
||||||
|
req,
|
||||||
|
context=context,
|
||||||
|
timeout=15,
|
||||||
|
) as response:
|
||||||
|
body = response.read()
|
||||||
|
return (
|
||||||
|
response.status,
|
||||||
|
json.loads(body) if body else {},
|
||||||
|
)
|
||||||
|
|
||||||
|
except urllib.error.HTTPError as exc:
|
||||||
|
if exc.code == 404:
|
||||||
|
return 404, {}
|
||||||
|
|
||||||
|
# Do not print the response body or credentials.
|
||||||
|
raise RuntimeError(
|
||||||
|
"OpenBao request failed with HTTP {}".format(
|
||||||
|
exc.code
|
||||||
|
)
|
||||||
|
) from None
|
||||||
|
|
||||||
|
|
||||||
|
def equal_secrets(actual, expected):
|
||||||
|
if set(actual) != set(expected):
|
||||||
|
return False
|
||||||
|
|
||||||
|
return all(
|
||||||
|
isinstance(actual[key], str)
|
||||||
|
and hmac.compare_digest(actual[key], value)
|
||||||
|
for key, value in expected.items()
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
mode = stat.S_IMODE(INIT_FILE.stat().st_mode)
|
||||||
|
check(mode == 0o600, "Operator file permissions are 600")
|
||||||
|
|
||||||
|
with INIT_FILE.open(encoding="utf-8") as file:
|
||||||
|
root_token = json.load(file)["root_token"]
|
||||||
|
|
||||||
|
context = ssl.create_default_context(
|
||||||
|
cafile=str(CA_FILE)
|
||||||
|
)
|
||||||
|
|
||||||
|
result = subprocess.run(
|
||||||
|
["docker", "compose", "config", "--format", "json"],
|
||||||
|
check=True,
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
services = json.loads(result.stdout)["services"]
|
||||||
|
|
||||||
|
api1_env = services["api1"]["environment"]
|
||||||
|
api2_env = services["api2"]["environment"]
|
||||||
|
worker_env = services["worker"]["environment"]
|
||||||
|
|
||||||
|
check(
|
||||||
|
all(
|
||||||
|
api1_env.get(key) == api2_env.get(key)
|
||||||
|
for key in SECRET_FIELDS["api"]
|
||||||
|
),
|
||||||
|
"API1 and API2 credentials match",
|
||||||
|
)
|
||||||
|
|
||||||
|
environments = {
|
||||||
|
"api": api1_env,
|
||||||
|
"worker": worker_env,
|
||||||
|
}
|
||||||
|
|
||||||
|
values = {}
|
||||||
|
|
||||||
|
for role, fields in SECRET_FIELDS.items():
|
||||||
|
source = environments[role]
|
||||||
|
|
||||||
|
values[role] = {
|
||||||
|
key: source.get(key)
|
||||||
|
for key in fields
|
||||||
|
}
|
||||||
|
|
||||||
|
check(
|
||||||
|
all(
|
||||||
|
isinstance(value, str) and bool(value)
|
||||||
|
for value in values[role].values()
|
||||||
|
),
|
||||||
|
"{} credentials are configured".format(role),
|
||||||
|
)
|
||||||
|
|
||||||
|
# Check existing KV values before making changes.
|
||||||
|
existing = {}
|
||||||
|
|
||||||
|
for role in SECRET_FIELDS:
|
||||||
|
path = "/v1/lab7/data/{}/runtime".format(role)
|
||||||
|
|
||||||
|
status, response = request(
|
||||||
|
"GET",
|
||||||
|
path,
|
||||||
|
root_token,
|
||||||
|
context,
|
||||||
|
)
|
||||||
|
|
||||||
|
if status == 404:
|
||||||
|
existing[role] = False
|
||||||
|
continue
|
||||||
|
|
||||||
|
stored = response["data"]["data"]
|
||||||
|
|
||||||
|
check(
|
||||||
|
equal_secrets(stored, values[role]),
|
||||||
|
"{} existing secret matches Compose".format(role),
|
||||||
|
)
|
||||||
|
|
||||||
|
existing[role] = True
|
||||||
|
|
||||||
|
# New secrets are created only when absent.
|
||||||
|
# CAS=0 prevents accidental overwriting.
|
||||||
|
for role in SECRET_FIELDS:
|
||||||
|
if existing[role]:
|
||||||
|
print("PASS: {} secret already stored".format(role))
|
||||||
|
continue
|
||||||
|
|
||||||
|
path = "/v1/lab7/data/{}/runtime".format(role)
|
||||||
|
|
||||||
|
status, _ = request(
|
||||||
|
"POST",
|
||||||
|
path,
|
||||||
|
root_token,
|
||||||
|
context,
|
||||||
|
{
|
||||||
|
"options": {"cas": 0},
|
||||||
|
"data": values[role],
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
check(
|
||||||
|
status in (200, 204),
|
||||||
|
"{} runtime secret stored".format(role),
|
||||||
|
)
|
||||||
|
|
||||||
|
# Read back and compare without displaying values.
|
||||||
|
for role in SECRET_FIELDS:
|
||||||
|
path = "/v1/lab7/data/{}/runtime".format(role)
|
||||||
|
|
||||||
|
status, response = request(
|
||||||
|
"GET",
|
||||||
|
path,
|
||||||
|
root_token,
|
||||||
|
context,
|
||||||
|
)
|
||||||
|
|
||||||
|
check(
|
||||||
|
status == 200
|
||||||
|
and equal_secrets(
|
||||||
|
response["data"]["data"],
|
||||||
|
values[role],
|
||||||
|
),
|
||||||
|
"{} KV v2 readback verified".format(role),
|
||||||
|
)
|
||||||
|
|
||||||
|
print("PASS: OpenBao HTTPS certificate verified")
|
||||||
|
print("PASS: API and worker secrets separated")
|
||||||
|
print("PASS: no credential values printed")
|
||||||
|
print("PASS: working application configuration unchanged")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
try:
|
||||||
|
main()
|
||||||
|
except Exception as exc:
|
||||||
|
print(
|
||||||
|
"FAIL: secret bootstrap:",
|
||||||
|
type(exc).__name__,
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
raise SystemExit(1)
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -Eeuo pipefail
|
||||||
|
|
||||||
|
PKI_DIR="${LAB7_PKI_DIR:-$HOME/.local/share/mtusi2026lab7/pki}"
|
||||||
|
|
||||||
|
if [[ ! -f "$PKI_DIR/ca.crt" || ! -f "$PKI_DIR/ca.key" ]]; then
|
||||||
|
echo "FAIL: existing CA certificate or key is missing"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ -e "$PKI_DIR/openbao.crt" || -e "$PKI_DIR/openbao.key" ]]; then
|
||||||
|
echo "FAIL: OpenBao TLS files already exist; refusing to overwrite"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
umask 077
|
||||||
|
|
||||||
|
WORK_DIR="$(mktemp -d)"
|
||||||
|
trap 'rm -rf "$WORK_DIR"' EXIT
|
||||||
|
|
||||||
|
openssl genpkey \
|
||||||
|
-algorithm RSA \
|
||||||
|
-pkeyopt rsa_keygen_bits:3072 \
|
||||||
|
-out "$WORK_DIR/openbao.key" 2>/dev/null
|
||||||
|
|
||||||
|
openssl req -new -sha256 \
|
||||||
|
-key "$WORK_DIR/openbao.key" \
|
||||||
|
-subj "/CN=openbao" \
|
||||||
|
-out "$WORK_DIR/openbao.csr"
|
||||||
|
|
||||||
|
cat > "$WORK_DIR/openbao.ext" <<'EOF'
|
||||||
|
basicConstraints=critical,CA:FALSE
|
||||||
|
keyUsage=critical,digitalSignature,keyEncipherment
|
||||||
|
extendedKeyUsage=serverAuth
|
||||||
|
subjectAltName=DNS:openbao,DNS:localhost,IP:127.0.0.1
|
||||||
|
EOF
|
||||||
|
|
||||||
|
openssl x509 -req -sha256 \
|
||||||
|
-in "$WORK_DIR/openbao.csr" \
|
||||||
|
-CA "$PKI_DIR/ca.crt" \
|
||||||
|
-CAkey "$PKI_DIR/ca.key" \
|
||||||
|
-CAserial "$PKI_DIR/ca.srl" \
|
||||||
|
-CAcreateserial \
|
||||||
|
-out "$WORK_DIR/openbao.crt" \
|
||||||
|
-days 365 \
|
||||||
|
-extfile "$WORK_DIR/openbao.ext"
|
||||||
|
|
||||||
|
openssl verify \
|
||||||
|
-CAfile "$PKI_DIR/ca.crt" \
|
||||||
|
-purpose sslserver \
|
||||||
|
-verify_hostname openbao \
|
||||||
|
"$WORK_DIR/openbao.crt"
|
||||||
|
|
||||||
|
openssl verify \
|
||||||
|
-CAfile "$PKI_DIR/ca.crt" \
|
||||||
|
-purpose sslserver \
|
||||||
|
-verify_hostname localhost \
|
||||||
|
"$WORK_DIR/openbao.crt"
|
||||||
|
|
||||||
|
install -m 644 \
|
||||||
|
"$WORK_DIR/openbao.crt" \
|
||||||
|
"$PKI_DIR/openbao.crt"
|
||||||
|
|
||||||
|
# The OpenBao container runs with UID=100 and GID=1000.
|
||||||
|
sudo install -o 100 -g 1000 -m 600 \
|
||||||
|
"$WORK_DIR/openbao.key" \
|
||||||
|
"$PKI_DIR/openbao.key"
|
||||||
|
|
||||||
|
echo "PASS: OpenBao TLS certificate issued"
|
||||||
|
echo "PASS: existing CA trusted"
|
||||||
|
echo "PASS: SAN contains openbao and localhost"
|
||||||
|
echo "PASS: private key owned by UID=100 GID=1000"
|
||||||
|
echo "PASS: private key permissions are 600"
|
||||||
@@ -0,0 +1,172 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
umask 077
|
||||||
|
|
||||||
|
PKI_DIR="${LAB7_PKI_DIR:-$HOME/.local/share/mtusi2026lab7/pki}"
|
||||||
|
|
||||||
|
mkdir -p "$PKI_DIR"
|
||||||
|
chmod 700 "$PKI_DIR"
|
||||||
|
|
||||||
|
# Never overwrite an existing CA.
|
||||||
|
if [[ -e "$PKI_DIR/ca.key" || -e "$PKI_DIR/ca.crt" ]]; then
|
||||||
|
echo "ERROR: PKI already exists at $PKI_DIR"
|
||||||
|
echo "Refusing to replace existing keys."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
for tool in openssl mktemp; do
|
||||||
|
command -v "$tool" >/dev/null || {
|
||||||
|
echo "Missing tool: $tool"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
done
|
||||||
|
|
||||||
|
WORK_DIR="$(mktemp -d)"
|
||||||
|
trap 'rm -rf "$WORK_DIR"' EXIT
|
||||||
|
|
||||||
|
create_ca() {
|
||||||
|
local prefix="$1"
|
||||||
|
local common_name="$2"
|
||||||
|
|
||||||
|
openssl genpkey \
|
||||||
|
-algorithm RSA \
|
||||||
|
-pkeyopt rsa_keygen_bits:3072 \
|
||||||
|
-out "$PKI_DIR/$prefix.key" 2>/dev/null
|
||||||
|
|
||||||
|
openssl req -x509 -new -sha256 \
|
||||||
|
-days 365 \
|
||||||
|
-key "$PKI_DIR/$prefix.key" \
|
||||||
|
-out "$PKI_DIR/$prefix.crt" \
|
||||||
|
-subj "/CN=$common_name" \
|
||||||
|
-addext "basicConstraints=critical,CA:TRUE,pathlen:0" \
|
||||||
|
-addext "keyUsage=critical,keyCertSign,cRLSign"
|
||||||
|
|
||||||
|
chmod 600 "$PKI_DIR/$prefix.key"
|
||||||
|
chmod 644 "$PKI_DIR/$prefix.crt"
|
||||||
|
}
|
||||||
|
|
||||||
|
create_leaf() {
|
||||||
|
local name="$1"
|
||||||
|
local common_name="$2"
|
||||||
|
local san="$3"
|
||||||
|
local usage="$4"
|
||||||
|
local ca_prefix="${5:-ca}"
|
||||||
|
|
||||||
|
openssl genpkey \
|
||||||
|
-algorithm RSA \
|
||||||
|
-pkeyopt rsa_keygen_bits:2048 \
|
||||||
|
-out "$PKI_DIR/$name.key" 2>/dev/null
|
||||||
|
|
||||||
|
openssl req -new -sha256 \
|
||||||
|
-key "$PKI_DIR/$name.key" \
|
||||||
|
-out "$WORK_DIR/$name.csr" \
|
||||||
|
-subj "/CN=$common_name"
|
||||||
|
|
||||||
|
cat > "$WORK_DIR/$name.ext" <<EOF
|
||||||
|
basicConstraints=critical,CA:FALSE
|
||||||
|
keyUsage=critical,digitalSignature,keyEncipherment
|
||||||
|
extendedKeyUsage=$usage
|
||||||
|
subjectAltName=$san
|
||||||
|
EOF
|
||||||
|
|
||||||
|
openssl x509 -req -sha256 \
|
||||||
|
-in "$WORK_DIR/$name.csr" \
|
||||||
|
-CA "$PKI_DIR/$ca_prefix.crt" \
|
||||||
|
-CAkey "$PKI_DIR/$ca_prefix.key" \
|
||||||
|
-CAserial "$WORK_DIR/$ca_prefix.srl" \
|
||||||
|
-CAcreateserial \
|
||||||
|
-days 90 \
|
||||||
|
-out "$PKI_DIR/$name.crt" \
|
||||||
|
-extfile "$WORK_DIR/$name.ext" 2>/dev/null
|
||||||
|
|
||||||
|
chmod 600 "$PKI_DIR/$name.key"
|
||||||
|
chmod 644 "$PKI_DIR/$name.crt"
|
||||||
|
}
|
||||||
|
|
||||||
|
echo "Generating lab7 private CA..."
|
||||||
|
create_ca ca "MTUSI Lab7 Local CA"
|
||||||
|
|
||||||
|
echo "Generating HTTPS ingress certificate..."
|
||||||
|
create_leaf \
|
||||||
|
ingress \
|
||||||
|
localhost \
|
||||||
|
"DNS:localhost,IP:127.0.0.1" \
|
||||||
|
serverAuth
|
||||||
|
|
||||||
|
echo "Generating API server certificates..."
|
||||||
|
create_leaf \
|
||||||
|
api1 \
|
||||||
|
api1 \
|
||||||
|
"DNS:api1,DNS:messenger-api.internal" \
|
||||||
|
serverAuth
|
||||||
|
|
||||||
|
create_leaf \
|
||||||
|
api2 \
|
||||||
|
api2 \
|
||||||
|
"DNS:api2,DNS:messenger-api.internal" \
|
||||||
|
serverAuth
|
||||||
|
|
||||||
|
echo "Generating authorized LB client certificate..."
|
||||||
|
create_leaf \
|
||||||
|
lb-client \
|
||||||
|
lb.messenger.internal \
|
||||||
|
"DNS:lb.messenger.internal" \
|
||||||
|
clientAuth
|
||||||
|
|
||||||
|
echo "Generating unauthorized client identity..."
|
||||||
|
create_leaf \
|
||||||
|
unauthorized-client \
|
||||||
|
unauthorized.messenger.internal \
|
||||||
|
"DNS:unauthorized.messenger.internal" \
|
||||||
|
clientAuth
|
||||||
|
|
||||||
|
echo "Generating separate untrusted CA..."
|
||||||
|
create_ca rogue-ca "MTUSI Lab7 Untrusted Test CA"
|
||||||
|
|
||||||
|
create_leaf \
|
||||||
|
rogue-client \
|
||||||
|
rogue.messenger.internal \
|
||||||
|
"DNS:rogue.messenger.internal" \
|
||||||
|
clientAuth \
|
||||||
|
rogue-ca
|
||||||
|
|
||||||
|
echo "Verifying issued certificates..."
|
||||||
|
|
||||||
|
openssl verify \
|
||||||
|
-CAfile "$PKI_DIR/ca.crt" \
|
||||||
|
-purpose sslserver \
|
||||||
|
-verify_hostname localhost \
|
||||||
|
"$PKI_DIR/ingress.crt"
|
||||||
|
|
||||||
|
openssl verify \
|
||||||
|
-CAfile "$PKI_DIR/ca.crt" \
|
||||||
|
-purpose sslserver \
|
||||||
|
-verify_hostname api1 \
|
||||||
|
"$PKI_DIR/api1.crt"
|
||||||
|
|
||||||
|
openssl verify \
|
||||||
|
-CAfile "$PKI_DIR/ca.crt" \
|
||||||
|
-purpose sslserver \
|
||||||
|
-verify_hostname api2 \
|
||||||
|
"$PKI_DIR/api2.crt"
|
||||||
|
|
||||||
|
openssl verify \
|
||||||
|
-CAfile "$PKI_DIR/ca.crt" \
|
||||||
|
-purpose sslclient \
|
||||||
|
"$PKI_DIR/lb-client.crt"
|
||||||
|
|
||||||
|
openssl verify \
|
||||||
|
-CAfile "$PKI_DIR/ca.crt" \
|
||||||
|
-purpose sslclient \
|
||||||
|
"$PKI_DIR/unauthorized-client.crt"
|
||||||
|
|
||||||
|
echo
|
||||||
|
echo "PASS: local CA and TLS certificates generated."
|
||||||
|
echo "PKI directory: $PKI_DIR"
|
||||||
|
echo "CA certificate: $PKI_DIR/ca.crt"
|
||||||
|
echo
|
||||||
|
echo "IMPORTANT:"
|
||||||
|
echo "- Never commit private keys."
|
||||||
|
echo "- Keep the CA private key operator-only."
|
||||||
|
echo "- Do not copy the PKI directory into Docker images."
|
||||||
|
echo "- Unauthorized and rogue certificates are test fixtures only."
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
umask 077
|
||||||
|
|
||||||
|
PKI_DIR="${LAB7_PKI_DIR:-$HOME/.local/share/mtusi2026lab7/pki}"
|
||||||
|
|
||||||
|
if [[ ! -f "$PKI_DIR/ca.crt" || ! -f "$PKI_DIR/ca.key" ]]; then
|
||||||
|
echo "ERROR: Lab7 CA not found."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ -e "$PKI_DIR/db.key" || -e "$PKI_DIR/db.crt" ]]; then
|
||||||
|
echo "ERROR: PostgreSQL certificate already exists."
|
||||||
|
echo "Refusing to overwrite existing credentials."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
WORK_DIR="$(mktemp -d)"
|
||||||
|
trap 'rm -rf "$WORK_DIR"' EXIT
|
||||||
|
|
||||||
|
echo "Generating PostgreSQL private key..."
|
||||||
|
|
||||||
|
openssl genpkey \
|
||||||
|
-algorithm RSA \
|
||||||
|
-pkeyopt rsa_keygen_bits:2048 \
|
||||||
|
-out "$WORK_DIR/db.key" 2>/dev/null
|
||||||
|
|
||||||
|
echo "Creating certificate signing request..."
|
||||||
|
|
||||||
|
openssl req -new -sha256 \
|
||||||
|
-key "$WORK_DIR/db.key" \
|
||||||
|
-out "$WORK_DIR/db.csr" \
|
||||||
|
-subj "/CN=db"
|
||||||
|
|
||||||
|
cat > "$WORK_DIR/db.ext" <<EOF
|
||||||
|
basicConstraints=critical,CA:FALSE
|
||||||
|
keyUsage=critical,digitalSignature,keyEncipherment
|
||||||
|
extendedKeyUsage=serverAuth
|
||||||
|
subjectAltName=DNS:db
|
||||||
|
EOF
|
||||||
|
|
||||||
|
echo "Signing certificate with Lab7 CA..."
|
||||||
|
|
||||||
|
openssl x509 -req -sha256 \
|
||||||
|
-in "$WORK_DIR/db.csr" \
|
||||||
|
-CA "$PKI_DIR/ca.crt" \
|
||||||
|
-CAkey "$PKI_DIR/ca.key" \
|
||||||
|
-CAserial "$WORK_DIR/ca.srl" \
|
||||||
|
-CAcreateserial \
|
||||||
|
-days 90 \
|
||||||
|
-out "$WORK_DIR/db.crt" \
|
||||||
|
-extfile "$WORK_DIR/db.ext" 2>/dev/null
|
||||||
|
|
||||||
|
echo "Verifying CA and hostname..."
|
||||||
|
|
||||||
|
openssl verify \
|
||||||
|
-CAfile "$PKI_DIR/ca.crt" \
|
||||||
|
-purpose sslserver \
|
||||||
|
-verify_hostname db \
|
||||||
|
"$WORK_DIR/db.crt"
|
||||||
|
|
||||||
|
install -m 600 "$WORK_DIR/db.key" "$PKI_DIR/db.key"
|
||||||
|
install -m 644 "$WORK_DIR/db.crt" "$PKI_DIR/db.crt"
|
||||||
|
|
||||||
|
echo
|
||||||
|
echo "PASS: PostgreSQL TLS certificate created."
|
||||||
|
echo "SAN: DNS:db"
|
||||||
|
echo "Private key retained outside Git."
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Create separate RabbitMQ service accounts without printing passwords."""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import secrets
|
||||||
|
import subprocess
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ENV_FILE = Path(".env")
|
||||||
|
|
||||||
|
ACCOUNTS = {
|
||||||
|
"messenger_publisher": {
|
||||||
|
"env": "RABBITMQ_PUBLISHER_PASSWORD",
|
||||||
|
"configure": "^image_jobs$",
|
||||||
|
"write": r"^amq\.default$",
|
||||||
|
"read": "^$",
|
||||||
|
},
|
||||||
|
"messenger_consumer": {
|
||||||
|
"env": "RABBITMQ_CONSUMER_PASSWORD",
|
||||||
|
"configure": "^image_jobs$",
|
||||||
|
"write": "^$",
|
||||||
|
"read": "^image_jobs$",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def rabbitmqctl(*arguments, password=None):
|
||||||
|
command = [
|
||||||
|
"docker", "compose", "exec", "-T",
|
||||||
|
"rabbitmq", "rabbitmqctl",
|
||||||
|
*arguments,
|
||||||
|
]
|
||||||
|
|
||||||
|
result = subprocess.run(
|
||||||
|
command,
|
||||||
|
input=None if password is None else password + "\n",
|
||||||
|
text=True,
|
||||||
|
capture_output=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
if result.returncode != 0:
|
||||||
|
raise RuntimeError(
|
||||||
|
"RabbitMQ command failed: " + arguments[0]
|
||||||
|
)
|
||||||
|
|
||||||
|
return result.stdout
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
if not ENV_FILE.is_file():
|
||||||
|
raise SystemExit("ERROR: .env not found")
|
||||||
|
|
||||||
|
contents = ENV_FILE.read_text(encoding="utf-8")
|
||||||
|
|
||||||
|
for account in ACCOUNTS.values():
|
||||||
|
key = account["env"]
|
||||||
|
if any(
|
||||||
|
line.strip().startswith(key + "=")
|
||||||
|
for line in contents.splitlines()
|
||||||
|
):
|
||||||
|
raise SystemExit(
|
||||||
|
f"ERROR: {key} already exists in .env"
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
existing_users = rabbitmqctl("list_users")
|
||||||
|
except RuntimeError as exc:
|
||||||
|
raise SystemExit(str(exc))
|
||||||
|
|
||||||
|
for username in ACCOUNTS:
|
||||||
|
if any(
|
||||||
|
line.split("\t")[0].strip() == username
|
||||||
|
for line in existing_users.splitlines()
|
||||||
|
):
|
||||||
|
raise SystemExit(
|
||||||
|
f"ERROR: {username} already exists in RabbitMQ"
|
||||||
|
)
|
||||||
|
|
||||||
|
generated = {}
|
||||||
|
|
||||||
|
try:
|
||||||
|
for username, settings in ACCOUNTS.items():
|
||||||
|
password = secrets.token_hex(32)
|
||||||
|
|
||||||
|
rabbitmqctl(
|
||||||
|
"add_user", username,
|
||||||
|
password=password,
|
||||||
|
)
|
||||||
|
|
||||||
|
rabbitmqctl(
|
||||||
|
"set_permissions",
|
||||||
|
"-p", "/",
|
||||||
|
username,
|
||||||
|
settings["configure"],
|
||||||
|
settings["write"],
|
||||||
|
settings["read"],
|
||||||
|
)
|
||||||
|
|
||||||
|
generated[settings["env"]] = password
|
||||||
|
print(f"PASS: {username} created with scoped ACL")
|
||||||
|
|
||||||
|
except RuntimeError as exc:
|
||||||
|
print("ERROR:", exc)
|
||||||
|
print(
|
||||||
|
"RabbitMQ may contain partially created accounts. "
|
||||||
|
"Do not rerun automatically."
|
||||||
|
)
|
||||||
|
raise SystemExit(1)
|
||||||
|
|
||||||
|
with ENV_FILE.open("a", encoding="utf-8") as file:
|
||||||
|
file.write("\n# Lab7 RabbitMQ service credentials\n")
|
||||||
|
for key, password in generated.items():
|
||||||
|
file.write(f"{key}={password}\n")
|
||||||
|
|
||||||
|
os.chmod(ENV_FILE, 0o600)
|
||||||
|
|
||||||
|
print("PASS: RabbitMQ passwords stored in ignored .env")
|
||||||
|
print("PASS: No passwords printed")
|
||||||
|
print("Existing application credentials were not changed")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Generate scoped RustFS credentials in the local .env file."""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import secrets
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
ENV_FILE = Path(__file__).resolve().parent.parent / ".env"
|
||||||
|
|
||||||
|
CREDENTIALS = {
|
||||||
|
"S3_API_ACCESS_KEY": "messenger_s3_api",
|
||||||
|
"S3_API_SECRET_KEY": secrets.token_hex(32),
|
||||||
|
"S3_WORKER_ACCESS_KEY": "messenger_s3_worker",
|
||||||
|
"S3_WORKER_SECRET_KEY": secrets.token_hex(32),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
if not ENV_FILE.is_file():
|
||||||
|
raise SystemExit("FAIL: existing .env file not found")
|
||||||
|
|
||||||
|
original = ENV_FILE.read_text(encoding="utf-8")
|
||||||
|
|
||||||
|
existing = set(
|
||||||
|
re.findall(
|
||||||
|
r"^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=",
|
||||||
|
original,
|
||||||
|
flags=re.MULTILINE,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
conflicts = existing.intersection(CREDENTIALS)
|
||||||
|
|
||||||
|
if conflicts:
|
||||||
|
print("FAIL: S3 service credentials already exist")
|
||||||
|
print("Existing variable names:", ", ".join(sorted(conflicts)))
|
||||||
|
print("Refusing to overwrite existing credentials")
|
||||||
|
raise SystemExit(1)
|
||||||
|
|
||||||
|
addition = "\n# Scoped RustFS IAM credentials\n"
|
||||||
|
|
||||||
|
for name, value in CREDENTIALS.items():
|
||||||
|
addition += f"{name}={value}\n"
|
||||||
|
|
||||||
|
prefix = "" if not original or original.endswith("\n") else "\n"
|
||||||
|
|
||||||
|
with ENV_FILE.open("a", encoding="utf-8") as file:
|
||||||
|
file.write(prefix + addition)
|
||||||
|
|
||||||
|
if os.name == "posix":
|
||||||
|
ENV_FILE.chmod(0o600)
|
||||||
|
|
||||||
|
print("PASS: API IAM credentials generated")
|
||||||
|
print("PASS: worker IAM credentials generated")
|
||||||
|
print("PASS: credentials saved to local .env")
|
||||||
|
print("PASS: existing S3 root credentials preserved")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -Eeuo pipefail
|
||||||
|
|
||||||
|
PKI_DIR="${LAB7_PKI_DIR:-$HOME/.local/share/mtusi2026lab7/pki}"
|
||||||
|
TLS_DIR="$PKI_DIR/rustfs-tls"
|
||||||
|
|
||||||
|
if [[ ! -f "$PKI_DIR/ca.crt" || ! -f "$PKI_DIR/ca.key" ]]; then
|
||||||
|
echo "FAIL: existing CA certificate or key is missing"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ -e "$TLS_DIR/rustfs_cert.pem" || -e "$TLS_DIR/rustfs_key.pem" ]]; then
|
||||||
|
echo "FAIL: RustFS TLS files already exist; refusing to overwrite"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
umask 077
|
||||||
|
|
||||||
|
WORK_DIR="$(mktemp -d)"
|
||||||
|
trap 'rm -rf "$WORK_DIR"' EXIT
|
||||||
|
|
||||||
|
openssl genpkey \
|
||||||
|
-algorithm RSA \
|
||||||
|
-pkeyopt rsa_keygen_bits:3072 \
|
||||||
|
-out "$WORK_DIR/rustfs_key.pem" 2>/dev/null
|
||||||
|
|
||||||
|
openssl req -new -sha256 \
|
||||||
|
-key "$WORK_DIR/rustfs_key.pem" \
|
||||||
|
-subj "/CN=minio" \
|
||||||
|
-out "$WORK_DIR/rustfs.csr"
|
||||||
|
|
||||||
|
cat > "$WORK_DIR/rustfs.ext" <<'EOF'
|
||||||
|
basicConstraints=critical,CA:FALSE
|
||||||
|
keyUsage=critical,digitalSignature,keyEncipherment
|
||||||
|
extendedKeyUsage=serverAuth
|
||||||
|
subjectAltName=DNS:minio
|
||||||
|
EOF
|
||||||
|
|
||||||
|
openssl x509 -req -sha256 \
|
||||||
|
-in "$WORK_DIR/rustfs.csr" \
|
||||||
|
-CA "$PKI_DIR/ca.crt" \
|
||||||
|
-CAkey "$PKI_DIR/ca.key" \
|
||||||
|
-CAserial "$PKI_DIR/ca.srl" \
|
||||||
|
-CAcreateserial \
|
||||||
|
-out "$WORK_DIR/rustfs_cert.pem" \
|
||||||
|
-days 365 \
|
||||||
|
-extfile "$WORK_DIR/rustfs.ext"
|
||||||
|
|
||||||
|
openssl verify \
|
||||||
|
-CAfile "$PKI_DIR/ca.crt" \
|
||||||
|
-purpose sslserver \
|
||||||
|
-verify_hostname minio \
|
||||||
|
"$WORK_DIR/rustfs_cert.pem"
|
||||||
|
|
||||||
|
mkdir -p "$TLS_DIR"
|
||||||
|
chmod 700 "$TLS_DIR"
|
||||||
|
|
||||||
|
install -m 644 \
|
||||||
|
"$WORK_DIR/rustfs_cert.pem" \
|
||||||
|
"$TLS_DIR/rustfs_cert.pem"
|
||||||
|
|
||||||
|
install -m 600 \
|
||||||
|
"$WORK_DIR/rustfs_key.pem" \
|
||||||
|
"$TLS_DIR/rustfs_key.pem"
|
||||||
|
|
||||||
|
# RustFS inside Docker runs with UID/GID 10001.
|
||||||
|
sudo chown 10001:10001 \
|
||||||
|
"$TLS_DIR/rustfs_cert.pem" \
|
||||||
|
"$TLS_DIR/rustfs_key.pem"
|
||||||
|
|
||||||
|
chmod 750 "$TLS_DIR"
|
||||||
|
|
||||||
|
echo "PASS: RustFS certificate issued and verified"
|
||||||
|
echo "PASS: SAN DNS:minio"
|
||||||
|
echo "PASS: RustFS private key owned by UID/GID 10001"
|
||||||
|
echo "TLS directory: $TLS_DIR"
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Configure scoped certificate authentication in OpenBao."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import ssl
|
||||||
|
import sys
|
||||||
|
import urllib.error
|
||||||
|
import urllib.request
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
BASE = Path.home() / ".local/share/mtusi2026lab7"
|
||||||
|
URL = "https://localhost:8200/v1"
|
||||||
|
|
||||||
|
SERVICES = {
|
||||||
|
"api1": "messenger-api",
|
||||||
|
"api2": "messenger-api",
|
||||||
|
"worker": "messenger-worker",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def request(method, path, token, tls, payload=None):
|
||||||
|
headers = {"X-Vault-Token": token}
|
||||||
|
body = None
|
||||||
|
|
||||||
|
if payload is not None:
|
||||||
|
body = json.dumps(payload).encode("utf-8")
|
||||||
|
headers["Content-Type"] = "application/json"
|
||||||
|
|
||||||
|
req = urllib.request.Request(
|
||||||
|
URL + path,
|
||||||
|
data=body,
|
||||||
|
headers=headers,
|
||||||
|
method=method,
|
||||||
|
)
|
||||||
|
|
||||||
|
with urllib.request.urlopen(
|
||||||
|
req,
|
||||||
|
context=tls,
|
||||||
|
timeout=15,
|
||||||
|
) as response:
|
||||||
|
raw = response.read()
|
||||||
|
return json.loads(raw) if raw else {}
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
with (BASE / "operator/openbao-init.json").open(
|
||||||
|
encoding="utf-8"
|
||||||
|
) as file:
|
||||||
|
root_token = json.load(file)["root_token"]
|
||||||
|
|
||||||
|
tls = ssl.create_default_context(
|
||||||
|
cafile=str(BASE / "pki/ca.crt")
|
||||||
|
)
|
||||||
|
|
||||||
|
methods = request(
|
||||||
|
"GET",
|
||||||
|
"/sys/auth",
|
||||||
|
root_token,
|
||||||
|
tls,
|
||||||
|
)
|
||||||
|
|
||||||
|
if "cert/" not in methods:
|
||||||
|
request(
|
||||||
|
"POST",
|
||||||
|
"/sys/auth/cert",
|
||||||
|
root_token,
|
||||||
|
tls,
|
||||||
|
{"type": "cert"},
|
||||||
|
)
|
||||||
|
print("PASS: certificate auth method enabled")
|
||||||
|
elif methods["cert/"]["type"] == "cert":
|
||||||
|
print("PASS: certificate auth method already enabled")
|
||||||
|
else:
|
||||||
|
raise RuntimeError("Unexpected auth method at cert/")
|
||||||
|
|
||||||
|
for service, policy in SERVICES.items():
|
||||||
|
certificate = (
|
||||||
|
BASE
|
||||||
|
/ "pki/openbao-clients"
|
||||||
|
/ f"{service}.crt"
|
||||||
|
).read_text(encoding="ascii")
|
||||||
|
|
||||||
|
request(
|
||||||
|
"POST",
|
||||||
|
f"/auth/cert/certs/lab7-{service}",
|
||||||
|
root_token,
|
||||||
|
tls,
|
||||||
|
{
|
||||||
|
"certificate": certificate,
|
||||||
|
"display_name": f"lab7-{service}",
|
||||||
|
"token_policies": [policy],
|
||||||
|
"token_no_default_policy": True,
|
||||||
|
"token_ttl": "1200s",
|
||||||
|
"token_max_ttl": "3600s",
|
||||||
|
"token_type": "service",
|
||||||
|
"token_num_uses": 0,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
print(
|
||||||
|
f"PASS: {service} certificate registered "
|
||||||
|
f"with {policy} policy"
|
||||||
|
)
|
||||||
|
|
||||||
|
print("PASS: three scoped certificate identities configured")
|
||||||
|
print("PASS: no private keys or tokens printed")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
try:
|
||||||
|
main()
|
||||||
|
except urllib.error.HTTPError as exc:
|
||||||
|
print(
|
||||||
|
f"FAIL: OpenBao HTTP {exc.code}",
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
raise SystemExit(1)
|
||||||
|
except Exception as exc:
|
||||||
|
print(
|
||||||
|
"FAIL: certificate auth configuration:",
|
||||||
|
type(exc).__name__,
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
raise SystemExit(1)
|
||||||
@@ -0,0 +1,150 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Issue a fresh one-time OpenBao AppRole bootstrap identity."""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import ssl
|
||||||
|
import stat
|
||||||
|
import sys
|
||||||
|
import urllib.error
|
||||||
|
import urllib.request
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
BASE = Path.home() / ".local/share/mtusi2026lab7"
|
||||||
|
OPERATOR = BASE / "operator"
|
||||||
|
INIT_FILE = OPERATOR / "openbao-init.json"
|
||||||
|
|
||||||
|
SERVICES = {
|
||||||
|
"api1": "messenger-api",
|
||||||
|
"api2": "messenger-api",
|
||||||
|
"worker": "messenger-worker",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def request(method, path, token, tls, payload=None):
|
||||||
|
body = None
|
||||||
|
|
||||||
|
if payload is not None:
|
||||||
|
body = json.dumps(payload).encode("utf-8")
|
||||||
|
|
||||||
|
headers = {"X-Vault-Token": token}
|
||||||
|
|
||||||
|
if body is not None:
|
||||||
|
headers["Content-Type"] = "application/json"
|
||||||
|
|
||||||
|
req = urllib.request.Request(
|
||||||
|
"https://localhost:8200/v1" + path,
|
||||||
|
data=body,
|
||||||
|
headers=headers,
|
||||||
|
method=method,
|
||||||
|
)
|
||||||
|
|
||||||
|
with urllib.request.urlopen(
|
||||||
|
req,
|
||||||
|
context=tls,
|
||||||
|
timeout=15,
|
||||||
|
) as response:
|
||||||
|
data = response.read()
|
||||||
|
return json.loads(data) if data else {}
|
||||||
|
|
||||||
|
|
||||||
|
def write_private(path, value):
|
||||||
|
fd = os.open(
|
||||||
|
path,
|
||||||
|
os.O_WRONLY | os.O_CREAT | os.O_EXCL,
|
||||||
|
0o600,
|
||||||
|
)
|
||||||
|
|
||||||
|
with os.fdopen(fd, "w", encoding="utf-8") as file:
|
||||||
|
file.write(value + "\n")
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser(
|
||||||
|
description="Issue one-time OpenBao bootstrap credentials"
|
||||||
|
)
|
||||||
|
|
||||||
|
parser.add_argument(
|
||||||
|
"service",
|
||||||
|
choices=sorted(SERVICES),
|
||||||
|
)
|
||||||
|
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
if stat.S_IMODE(INIT_FILE.stat().st_mode) != 0o600:
|
||||||
|
raise RuntimeError("Operator file must have mode 600")
|
||||||
|
|
||||||
|
role = SERVICES[args.service]
|
||||||
|
|
||||||
|
destination = OPERATOR / "approle" / args.service
|
||||||
|
|
||||||
|
# Never overwrite credentials that may still be in use.
|
||||||
|
if destination.exists():
|
||||||
|
raise RuntimeError(
|
||||||
|
"Bootstrap directory already exists; refusing overwrite"
|
||||||
|
)
|
||||||
|
|
||||||
|
with INIT_FILE.open(encoding="utf-8") as file:
|
||||||
|
root_token = json.load(file)["root_token"]
|
||||||
|
|
||||||
|
tls = ssl.create_default_context(
|
||||||
|
cafile=str(BASE / "pki/ca.crt")
|
||||||
|
)
|
||||||
|
|
||||||
|
role_result = request(
|
||||||
|
"GET",
|
||||||
|
f"/auth/approle/role/{role}/role-id",
|
||||||
|
root_token,
|
||||||
|
tls,
|
||||||
|
)
|
||||||
|
|
||||||
|
role_id = role_result["data"]["role_id"]
|
||||||
|
|
||||||
|
secret_result = request(
|
||||||
|
"POST",
|
||||||
|
f"/auth/approle/role/{role}/secret-id",
|
||||||
|
root_token,
|
||||||
|
tls,
|
||||||
|
{},
|
||||||
|
)
|
||||||
|
|
||||||
|
secret_id = secret_result["data"]["secret_id"]
|
||||||
|
|
||||||
|
os.umask(0o077)
|
||||||
|
|
||||||
|
destination.mkdir(parents=True, mode=0o700)
|
||||||
|
|
||||||
|
try:
|
||||||
|
write_private(destination / "role-id", role_id)
|
||||||
|
write_private(destination / "secret-id", secret_id)
|
||||||
|
except Exception:
|
||||||
|
for name in ("role-id", "secret-id"):
|
||||||
|
(destination / name).unlink(missing_ok=True)
|
||||||
|
destination.rmdir()
|
||||||
|
raise
|
||||||
|
|
||||||
|
print(f"PASS: fresh bootstrap credentials issued for {args.service}")
|
||||||
|
print("PASS: separate AppRole identity used")
|
||||||
|
print("PASS: credentials stored outside Git")
|
||||||
|
print("PASS: credential files created with mode 600")
|
||||||
|
print("PASS: credential values not printed")
|
||||||
|
print("INFO: SecretID is valid for 30 minutes and one login")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
try:
|
||||||
|
main()
|
||||||
|
except urllib.error.HTTPError as exc:
|
||||||
|
print(
|
||||||
|
f"FAIL: OpenBao returned HTTP {exc.code}",
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
raise SystemExit(1)
|
||||||
|
except Exception as exc:
|
||||||
|
print(
|
||||||
|
"FAIL: bootstrap issuance:",
|
||||||
|
type(exc).__name__,
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
raise SystemExit(1)
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
umask 077
|
||||||
|
|
||||||
|
PKI_DIR="${LAB7_PKI_DIR:-$HOME/.local/share/mtusi2026lab7/pki}"
|
||||||
|
|
||||||
|
if [[ ! -f "$PKI_DIR/ca.crt" || ! -f "$PKI_DIR/ca.key" ]]; then
|
||||||
|
echo "ERROR: Existing CA not found."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
WORK_DIR="$(mktemp -d)"
|
||||||
|
trap 'rm -rf "$WORK_DIR"' EXIT
|
||||||
|
|
||||||
|
for name in api1 api2; do
|
||||||
|
echo "Reissuing certificate for $name..."
|
||||||
|
|
||||||
|
openssl genpkey \
|
||||||
|
-algorithm RSA \
|
||||||
|
-pkeyopt rsa_keygen_bits:2048 \
|
||||||
|
-out "$WORK_DIR/$name.key" 2>/dev/null
|
||||||
|
|
||||||
|
openssl req -new -sha256 \
|
||||||
|
-key "$WORK_DIR/$name.key" \
|
||||||
|
-out "$WORK_DIR/$name.csr" \
|
||||||
|
-subj "/CN=$name"
|
||||||
|
|
||||||
|
cat > "$WORK_DIR/$name.ext" <<EOF
|
||||||
|
basicConstraints=critical,CA:FALSE
|
||||||
|
keyUsage=critical,digitalSignature,keyEncipherment
|
||||||
|
extendedKeyUsage=serverAuth
|
||||||
|
subjectAltName=DNS:$name,DNS:messenger-api.internal
|
||||||
|
EOF
|
||||||
|
|
||||||
|
openssl x509 -req -sha256 \
|
||||||
|
-in "$WORK_DIR/$name.csr" \
|
||||||
|
-CA "$PKI_DIR/ca.crt" \
|
||||||
|
-CAkey "$PKI_DIR/ca.key" \
|
||||||
|
-CAcreateserial \
|
||||||
|
-days 90 \
|
||||||
|
-out "$WORK_DIR/$name.crt" \
|
||||||
|
-extfile "$WORK_DIR/$name.ext" 2>/dev/null
|
||||||
|
|
||||||
|
openssl verify \
|
||||||
|
-CAfile "$PKI_DIR/ca.crt" \
|
||||||
|
-purpose sslserver \
|
||||||
|
-verify_hostname "$name" \
|
||||||
|
"$WORK_DIR/$name.crt"
|
||||||
|
|
||||||
|
openssl verify \
|
||||||
|
-CAfile "$PKI_DIR/ca.crt" \
|
||||||
|
-purpose sslserver \
|
||||||
|
-verify_hostname messenger-api.internal \
|
||||||
|
"$WORK_DIR/$name.crt"
|
||||||
|
|
||||||
|
cat "$WORK_DIR/$name.crt" "$WORK_DIR/$name.key" \
|
||||||
|
> "$WORK_DIR/$name.pem"
|
||||||
|
|
||||||
|
# Replace only after both hostname checks have passed.
|
||||||
|
install -m 600 "$WORK_DIR/$name.key" "$PKI_DIR/$name.key"
|
||||||
|
install -m 644 "$WORK_DIR/$name.crt" "$PKI_DIR/$name.crt"
|
||||||
|
install -m 600 "$WORK_DIR/$name.pem" "$PKI_DIR/$name.pem"
|
||||||
|
|
||||||
|
done
|
||||||
|
|
||||||
|
echo
|
||||||
|
echo "PASS: API certificates reissued with shared service SAN."
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Replace previously issued OpenBao bootstrap credentials."""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import runpy
|
||||||
|
import shutil
|
||||||
|
import ssl
|
||||||
|
import stat
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import urllib.error
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
HELPERS = runpy.run_path(
|
||||||
|
str(Path(__file__).with_name("issue-openbao-bootstrap.py"))
|
||||||
|
)
|
||||||
|
|
||||||
|
BASE = HELPERS["BASE"]
|
||||||
|
OPERATOR = HELPERS["OPERATOR"]
|
||||||
|
INIT_FILE = HELPERS["INIT_FILE"]
|
||||||
|
SERVICES = HELPERS["SERVICES"]
|
||||||
|
request = HELPERS["request"]
|
||||||
|
write_private = HELPERS["write_private"]
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser(
|
||||||
|
description="Reissue existing OpenBao AppRole credentials"
|
||||||
|
)
|
||||||
|
parser.add_argument("service", choices=sorted(SERVICES))
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
role = SERVICES[args.service]
|
||||||
|
parent = OPERATOR / "approle"
|
||||||
|
destination = parent / args.service
|
||||||
|
|
||||||
|
if not destination.is_dir() or destination.is_symlink():
|
||||||
|
raise RuntimeError(
|
||||||
|
"Existing bootstrap directory required"
|
||||||
|
)
|
||||||
|
|
||||||
|
if stat.S_IMODE(INIT_FILE.stat().st_mode) != 0o600:
|
||||||
|
raise RuntimeError("Operator file must have mode 600")
|
||||||
|
|
||||||
|
old_role_file = destination / "role-id"
|
||||||
|
old_secret_file = destination / "secret-id"
|
||||||
|
|
||||||
|
for path in (old_role_file, old_secret_file):
|
||||||
|
if not path.is_file() or path.is_symlink():
|
||||||
|
raise RuntimeError("Invalid existing credential file")
|
||||||
|
|
||||||
|
old_secret_id = old_secret_file.read_text(
|
||||||
|
encoding="utf-8"
|
||||||
|
).strip()
|
||||||
|
|
||||||
|
with INIT_FILE.open(encoding="utf-8") as file:
|
||||||
|
root_token = json.load(file)["root_token"]
|
||||||
|
|
||||||
|
tls = ssl.create_default_context(
|
||||||
|
cafile=str(BASE / "pki/ca.crt")
|
||||||
|
)
|
||||||
|
|
||||||
|
role_result = request(
|
||||||
|
"GET",
|
||||||
|
f"/auth/approle/role/{role}/role-id",
|
||||||
|
root_token,
|
||||||
|
tls,
|
||||||
|
)
|
||||||
|
role_id = role_result["data"]["role_id"]
|
||||||
|
|
||||||
|
os.umask(0o077)
|
||||||
|
|
||||||
|
with tempfile.TemporaryDirectory(
|
||||||
|
prefix=f".{args.service}-new-",
|
||||||
|
dir=parent,
|
||||||
|
) as temp:
|
||||||
|
staging = Path(temp) / "credentials"
|
||||||
|
staging.mkdir(mode=0o700)
|
||||||
|
|
||||||
|
secret_result = request(
|
||||||
|
"POST",
|
||||||
|
f"/auth/approle/role/{role}/secret-id",
|
||||||
|
root_token,
|
||||||
|
tls,
|
||||||
|
{},
|
||||||
|
)
|
||||||
|
|
||||||
|
new_secret_id = secret_result["data"]["secret_id"]
|
||||||
|
|
||||||
|
try:
|
||||||
|
write_private(staging / "role-id", role_id)
|
||||||
|
write_private(staging / "secret-id", new_secret_id)
|
||||||
|
except Exception:
|
||||||
|
try:
|
||||||
|
request(
|
||||||
|
"POST",
|
||||||
|
f"/auth/approle/role/{role}/secret-id/destroy",
|
||||||
|
root_token,
|
||||||
|
tls,
|
||||||
|
{"secret_id": new_secret_id},
|
||||||
|
)
|
||||||
|
except Exception:
|
||||||
|
print(
|
||||||
|
"WARNING: unused new SecretID cleanup failed",
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
raise
|
||||||
|
|
||||||
|
backup = Path(temp) / "previous"
|
||||||
|
|
||||||
|
os.replace(destination, backup)
|
||||||
|
|
||||||
|
try:
|
||||||
|
os.replace(staging, destination)
|
||||||
|
except Exception:
|
||||||
|
os.replace(backup, destination)
|
||||||
|
raise
|
||||||
|
|
||||||
|
# The replacement is now installed.
|
||||||
|
# Revoke the previous SecretID if it is still valid.
|
||||||
|
try:
|
||||||
|
request(
|
||||||
|
"POST",
|
||||||
|
f"/auth/approle/role/{role}/secret-id/destroy",
|
||||||
|
root_token,
|
||||||
|
tls,
|
||||||
|
{"secret_id": old_secret_id},
|
||||||
|
)
|
||||||
|
except urllib.error.HTTPError as exc:
|
||||||
|
# A previously consumed SecretID may already be absent.
|
||||||
|
print(
|
||||||
|
f"INFO: previous SecretID cleanup HTTP {exc.code}"
|
||||||
|
)
|
||||||
|
|
||||||
|
shutil.rmtree(backup)
|
||||||
|
|
||||||
|
print(f"PASS: credentials reissued for {args.service}")
|
||||||
|
print("PASS: previous credential directory replaced")
|
||||||
|
print("PASS: new files stored outside Git")
|
||||||
|
print("PASS: credentials not printed")
|
||||||
|
print("INFO: new SecretID expires in 30 minutes")
|
||||||
|
print("INFO: new SecretID supports one authentication")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
try:
|
||||||
|
main()
|
||||||
|
except Exception as exc:
|
||||||
|
print(
|
||||||
|
"FAIL: reissuance:",
|
||||||
|
type(exc).__name__,
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
raise SystemExit(1)
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
|
||||||
|
echo "[1/5] Stopping API sidecars and application services"
|
||||||
|
docker compose stop \
|
||||||
|
api1-mtls api2-mtls \
|
||||||
|
api1 api2 worker dispatcher
|
||||||
|
|
||||||
|
echo "[2/5] Restarting persistent dependencies"
|
||||||
|
docker compose restart db minio rabbitmq
|
||||||
|
|
||||||
|
echo "[3/5] Waiting for PostgreSQL and RabbitMQ"
|
||||||
|
docker compose up -d --no-deps --wait db rabbitmq
|
||||||
|
|
||||||
|
echo "[4/5] Starting application services"
|
||||||
|
docker compose up -d --no-deps dispatcher worker
|
||||||
|
docker compose up -d --no-deps --wait api1 api2
|
||||||
|
|
||||||
|
echo "[5/5] Recreating mTLS sidecars"
|
||||||
|
docker compose up -d --no-deps --force-recreate \
|
||||||
|
api1-mtls api2-mtls
|
||||||
|
|
||||||
|
echo "PASS: services restarted without removing volumes"
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
|
||||||
|
if [[ -z "${TARGET_INSTANCE_ID:-}" ]]; then
|
||||||
|
echo "FAIL: TARGET_INSTANCE_ID is missing" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
for service in api1 api2; do
|
||||||
|
|
||||||
|
instance_id=$(
|
||||||
|
docker compose exec -T "$service" python -c '
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
with urllib.request.urlopen(
|
||||||
|
"http://127.0.0.1:8080/health/live",
|
||||||
|
timeout=2,
|
||||||
|
) as response:
|
||||||
|
print(response.headers.get("X-Instance-Id", ""))
|
||||||
|
' 2>/dev/null
|
||||||
|
) || continue
|
||||||
|
|
||||||
|
if [[ "$instance_id" == "$TARGET_INSTANCE_ID" ]]; then
|
||||||
|
|
||||||
|
echo "Stopping replica: $service"
|
||||||
|
|
||||||
|
docker compose stop -t 2 \
|
||||||
|
"${service}-mtls" "$service"
|
||||||
|
|
||||||
|
echo "PASS: target replica stopped"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
echo "FAIL: target API instance not found" >&2
|
||||||
|
exit 1
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
import psycopg
|
||||||
|
|
||||||
|
ROLE_TESTS = {
|
||||||
|
"messenger_api": {
|
||||||
|
"allowed": [
|
||||||
|
("read users", "SELECT id FROM public.users LIMIT 0"),
|
||||||
|
("read sessions", "SELECT * FROM public.sessions LIMIT 0"),
|
||||||
|
("read jobs", "SELECT id FROM public.attachment_jobs LIMIT 0"),
|
||||||
|
],
|
||||||
|
"denied": [
|
||||||
|
("read migration history",
|
||||||
|
"SELECT * FROM public.schema_migrations LIMIT 0"),
|
||||||
|
("create tables",
|
||||||
|
"CREATE TABLE public.lab7_acl_test (id integer)"),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
|
||||||
|
"messenger_worker": {
|
||||||
|
"allowed": [
|
||||||
|
("read jobs", "SELECT id FROM public.attachment_jobs LIMIT 0"),
|
||||||
|
("read attachments", "SELECT id FROM public.attachments LIMIT 0"),
|
||||||
|
("read variants", "SELECT * FROM public.attachment_variants LIMIT 0"),
|
||||||
|
],
|
||||||
|
"denied": [
|
||||||
|
("read users", "SELECT * FROM public.users LIMIT 0"),
|
||||||
|
("read sessions", "SELECT * FROM public.sessions LIMIT 0"),
|
||||||
|
("read messages", "SELECT * FROM public.messages LIMIT 0"),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
|
||||||
|
"messenger_dispatcher": {
|
||||||
|
"allowed": [
|
||||||
|
("read jobs", "SELECT id FROM public.attachment_jobs LIMIT 0"),
|
||||||
|
],
|
||||||
|
"denied": [
|
||||||
|
("read users", "SELECT * FROM public.users LIMIT 0"),
|
||||||
|
("read sessions", "SELECT * FROM public.sessions LIMIT 0"),
|
||||||
|
("read messages", "SELECT * FROM public.messages LIMIT 0"),
|
||||||
|
("read attachments", "SELECT * FROM public.attachments LIMIT 0"),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def run_query(conn, label, sql, should_succeed):
|
||||||
|
# Every test runs in its own transaction.
|
||||||
|
# All changes are rolled back, even if an unexpected
|
||||||
|
# permission grants the operation.
|
||||||
|
try:
|
||||||
|
with conn.transaction():
|
||||||
|
with conn.cursor() as cursor:
|
||||||
|
cursor.execute(sql)
|
||||||
|
|
||||||
|
if should_succeed:
|
||||||
|
print(f"PASS: allowed - {label}")
|
||||||
|
else:
|
||||||
|
print(f"FAIL: forbidden operation succeeded - {label}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
except psycopg.errors.InsufficientPrivilege:
|
||||||
|
if should_succeed:
|
||||||
|
print(f"FAIL: allowed operation denied - {label}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
print(f"PASS: denied - {label}")
|
||||||
|
return True
|
||||||
|
|
||||||
|
except psycopg.Error as exc:
|
||||||
|
print(f"FAIL: unexpected SQL error - {label}")
|
||||||
|
print(f"SQLSTATE: {exc.sqlstate}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
return should_succeed
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
url = os.environ["DATABASE_URL"]
|
||||||
|
|
||||||
|
if "sslmode=verify-full" not in url:
|
||||||
|
raise SystemExit("FAIL: sslmode=verify-full not configured")
|
||||||
|
|
||||||
|
passed = True
|
||||||
|
|
||||||
|
# Autocommit allows each conn.transaction() to be independent.
|
||||||
|
with psycopg.connect(url, autocommit=True) as conn:
|
||||||
|
role, encrypted, version = conn.execute("""
|
||||||
|
SELECT current_user, ssl, version
|
||||||
|
FROM pg_stat_ssl
|
||||||
|
WHERE pid = pg_backend_pid()
|
||||||
|
""").fetchone()
|
||||||
|
|
||||||
|
print(f"PostgreSQL role: {role}")
|
||||||
|
print(f"TLS encrypted: {encrypted}")
|
||||||
|
print(f"TLS version: {version}")
|
||||||
|
|
||||||
|
if not encrypted or role not in ROLE_TESTS:
|
||||||
|
raise SystemExit("FAIL: unexpected role or TLS state")
|
||||||
|
|
||||||
|
tests = ROLE_TESTS[role]
|
||||||
|
|
||||||
|
for label, sql in tests["allowed"]:
|
||||||
|
if not run_query(conn, label, sql, True):
|
||||||
|
passed = False
|
||||||
|
|
||||||
|
for label, sql in tests["denied"]:
|
||||||
|
if not run_query(conn, label, sql, False):
|
||||||
|
passed = False
|
||||||
|
|
||||||
|
if passed:
|
||||||
|
print(f"PASS: all ACL tests for {role}")
|
||||||
|
else:
|
||||||
|
print(f"FAIL: ACL tests for {role}")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,175 @@
|
|||||||
|
|
||||||
|
import base64
|
||||||
|
import json
|
||||||
|
import subprocess
|
||||||
|
import time
|
||||||
|
import urllib.error
|
||||||
|
import urllib.request
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
|
||||||
|
BASE_URL = "http://127.0.0.1:8080"
|
||||||
|
|
||||||
|
|
||||||
|
def docker(*args):
|
||||||
|
subprocess.run(
|
||||||
|
["docker", "compose", *args],
|
||||||
|
check=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def request(method, path, body=None, headers=None):
|
||||||
|
request_headers = dict(headers or {})
|
||||||
|
|
||||||
|
if isinstance(body, dict):
|
||||||
|
body = json.dumps(body).encode("utf-8")
|
||||||
|
request_headers["Content-Type"] = "application/json"
|
||||||
|
|
||||||
|
req = urllib.request.Request(
|
||||||
|
BASE_URL + path,
|
||||||
|
data=body,
|
||||||
|
headers=request_headers,
|
||||||
|
method=method,
|
||||||
|
)
|
||||||
|
|
||||||
|
started = time.monotonic()
|
||||||
|
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(req, timeout=5) as response:
|
||||||
|
response.read()
|
||||||
|
return response.status, time.monotonic() - started
|
||||||
|
|
||||||
|
except urllib.error.HTTPError as exc:
|
||||||
|
exc.read()
|
||||||
|
return exc.code, time.monotonic() - started
|
||||||
|
|
||||||
|
except (urllib.error.URLError, TimeoutError) as exc:
|
||||||
|
return type(exc).__name__, time.monotonic() - started
|
||||||
|
|
||||||
|
|
||||||
|
def login_header(username, password):
|
||||||
|
encoded = base64.b64encode(
|
||||||
|
f"{username}:{password}".encode("utf-8")
|
||||||
|
).decode("ascii")
|
||||||
|
|
||||||
|
return {
|
||||||
|
"Authorization": f"Basic {encoded}"
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def wait_for_recovery(headers):
|
||||||
|
deadline = time.monotonic() + 90
|
||||||
|
|
||||||
|
while time.monotonic() < deadline:
|
||||||
|
status, duration = request(
|
||||||
|
"POST",
|
||||||
|
"/api/v1/auth/sessions",
|
||||||
|
body=b"",
|
||||||
|
headers=headers,
|
||||||
|
)
|
||||||
|
|
||||||
|
if status == 201:
|
||||||
|
print(
|
||||||
|
f"Recovery: HTTP 201, {duration:.3f}s",
|
||||||
|
flush=True,
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
time.sleep(2)
|
||||||
|
|
||||||
|
raise RuntimeError(
|
||||||
|
"Authentication did not recover after DB restart"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
suffix = uuid.uuid4().hex[:12]
|
||||||
|
|
||||||
|
username = "lab6_db_" + suffix
|
||||||
|
password = "IncidentTest_" + suffix
|
||||||
|
|
||||||
|
status, duration = request(
|
||||||
|
"POST",
|
||||||
|
"/api/v1/users",
|
||||||
|
body={
|
||||||
|
"username": username,
|
||||||
|
"display_name": "DB incident test",
|
||||||
|
"password": password,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
if status != 201:
|
||||||
|
raise RuntimeError(
|
||||||
|
f"Cannot create test user: HTTP {status}"
|
||||||
|
)
|
||||||
|
|
||||||
|
headers = login_header(username, password)
|
||||||
|
|
||||||
|
status, _ = request(
|
||||||
|
"POST",
|
||||||
|
"/api/v1/auth/sessions",
|
||||||
|
body=b"",
|
||||||
|
headers=headers,
|
||||||
|
)
|
||||||
|
|
||||||
|
if status != 201:
|
||||||
|
raise RuntimeError(
|
||||||
|
f"Baseline login failed: HTTP {status}"
|
||||||
|
)
|
||||||
|
|
||||||
|
print("Baseline: authentication HTTP 201", flush=True)
|
||||||
|
|
||||||
|
observed_failures = 0
|
||||||
|
|
||||||
|
print("INCIDENT START: stopping PostgreSQL", flush=True)
|
||||||
|
|
||||||
|
try:
|
||||||
|
docker("stop", "db")
|
||||||
|
|
||||||
|
for attempt in range(1, 6):
|
||||||
|
status, duration = request(
|
||||||
|
"POST",
|
||||||
|
"/api/v1/auth/sessions",
|
||||||
|
body=b"",
|
||||||
|
headers=headers,
|
||||||
|
)
|
||||||
|
|
||||||
|
print(
|
||||||
|
f"Probe {attempt}: status={status}, "
|
||||||
|
f"duration={duration:.3f}s",
|
||||||
|
flush=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
if status != 201:
|
||||||
|
observed_failures += 1
|
||||||
|
|
||||||
|
time.sleep(2)
|
||||||
|
|
||||||
|
finally:
|
||||||
|
print(
|
||||||
|
"INCIDENT END: restoring PostgreSQL",
|
||||||
|
flush=True,
|
||||||
|
)
|
||||||
|
docker("up", "-d", "--wait", "db")
|
||||||
|
|
||||||
|
wait_for_recovery(headers)
|
||||||
|
|
||||||
|
print(
|
||||||
|
f"Failed requests during incident: "
|
||||||
|
f"{observed_failures}/5",
|
||||||
|
flush=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
if observed_failures == 0:
|
||||||
|
raise RuntimeError(
|
||||||
|
"The database incident did not affect requests"
|
||||||
|
)
|
||||||
|
|
||||||
|
print(
|
||||||
|
"PASS: database failure observed and recovered",
|
||||||
|
flush=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
|
||||||
|
import base64
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import urllib.error
|
||||||
|
import urllib.request
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
BASE_URL = os.getenv("BASE_URL", "https://localhost:8443").rstrip("/")
|
||||||
|
CA_FILE = os.getenv("CA_FILE")
|
||||||
|
|
||||||
|
if not CA_FILE:
|
||||||
|
sys.exit("ERROR: CA_FILE must point to a trusted CA certificate")
|
||||||
|
|
||||||
|
import ssl
|
||||||
|
|
||||||
|
SSL_CONTEXT = ssl.create_default_context(cafile=CA_FILE)
|
||||||
|
|
||||||
|
username = "rl_" + uuid.uuid4().hex[:16]
|
||||||
|
password = "Wrong-Password-For-Rate-Limit-2026"
|
||||||
|
|
||||||
|
|
||||||
|
def login():
|
||||||
|
credentials = base64.b64encode(
|
||||||
|
f"{username}:{password}".encode()
|
||||||
|
).decode()
|
||||||
|
|
||||||
|
request = urllib.request.Request(
|
||||||
|
BASE_URL + "/api/v1/auth/sessions",
|
||||||
|
data=b"",
|
||||||
|
method="POST",
|
||||||
|
headers={"Authorization": "Basic " + credentials},
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(
|
||||||
|
request,
|
||||||
|
context=SSL_CONTEXT,
|
||||||
|
timeout=10,
|
||||||
|
) as response:
|
||||||
|
return response.status, response.headers
|
||||||
|
|
||||||
|
except urllib.error.HTTPError as exc:
|
||||||
|
return exc.code, exc.headers
|
||||||
|
|
||||||
|
|
||||||
|
print("Testing rate limit with username:", username)
|
||||||
|
|
||||||
|
statuses = []
|
||||||
|
|
||||||
|
for attempt in range(1, 7):
|
||||||
|
status, headers = login()
|
||||||
|
statuses.append(status)
|
||||||
|
|
||||||
|
print(
|
||||||
|
f"Attempt {attempt}: HTTP {status}, "
|
||||||
|
f"Retry-After={headers.get('Retry-After')}"
|
||||||
|
)
|
||||||
|
|
||||||
|
if attempt <= 5:
|
||||||
|
assert status == 401, (
|
||||||
|
f"Expected HTTP 401 for attempt {attempt}, got {status}"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
assert status == 429, (
|
||||||
|
f"Expected HTTP 429 for attempt {attempt}, got {status}"
|
||||||
|
)
|
||||||
|
|
||||||
|
retry_after = headers.get("Retry-After")
|
||||||
|
|
||||||
|
assert retry_after and retry_after.isdigit(), (
|
||||||
|
"Missing or invalid Retry-After"
|
||||||
|
)
|
||||||
|
|
||||||
|
assert int(retry_after) > 0
|
||||||
|
|
||||||
|
print("PASS: shared login rate limit and Retry-After")
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
PKI_DIR="${LAB7_PKI_DIR:-$HOME/.local/share/mtusi2026lab7/pki}"
|
||||||
|
NETWORK="${COMPOSE_PROJECT_NAME:-mtusi2026lab7}_default"
|
||||||
|
|
||||||
|
for name in api1 api2; do
|
||||||
|
echo
|
||||||
|
echo "=== Testing $name mTLS ==="
|
||||||
|
|
||||||
|
run_curl() {
|
||||||
|
docker run --rm \
|
||||||
|
--network "$NETWORK" \
|
||||||
|
--user "$(id -u):$(id -g)" \
|
||||||
|
-v "$PKI_DIR:/pki:ro" \
|
||||||
|
curlimages/curl:8.16.0 \
|
||||||
|
--silent --show-error \
|
||||||
|
--max-time 10 \
|
||||||
|
--cacert /pki/ca.crt \
|
||||||
|
--resolve "$name:8443:$(docker inspect \
|
||||||
|
-f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' \
|
||||||
|
"mtusi2026lab7-$name-1")" \
|
||||||
|
"$@" \
|
||||||
|
"https://$name:8443/health/ready"
|
||||||
|
}
|
||||||
|
|
||||||
|
echo "[1] Authorized LB certificate"
|
||||||
|
response="$(run_curl \
|
||||||
|
--cert /pki/lb-client.crt \
|
||||||
|
--key /pki/lb-client.key)"
|
||||||
|
echo "$response"
|
||||||
|
[[ "$response" == *'"status":"ok"'* ]] || exit 1
|
||||||
|
|
||||||
|
echo "[2] No client certificate"
|
||||||
|
if run_curl > /dev/null 2>&1; then
|
||||||
|
echo "FAIL: connection accepted without client certificate"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo "PASS: no certificate rejected"
|
||||||
|
|
||||||
|
echo "[3] Untrusted CA certificate"
|
||||||
|
if run_curl \
|
||||||
|
--cert /pki/rogue-client.crt \
|
||||||
|
--key /pki/rogue-client.key \
|
||||||
|
> /dev/null 2>&1; then
|
||||||
|
echo "FAIL: rogue certificate accepted"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo "PASS: rogue CA rejected"
|
||||||
|
|
||||||
|
echo "[4] Trusted CA, forbidden SAN"
|
||||||
|
code="$(run_curl \
|
||||||
|
--cert /pki/unauthorized-client.crt \
|
||||||
|
--key /pki/unauthorized-client.key \
|
||||||
|
-o /dev/null -w '%{http_code}')"
|
||||||
|
|
||||||
|
echo "HTTP $code"
|
||||||
|
[[ "$code" == "403" ]] || {
|
||||||
|
echo "FAIL: expected HTTP 403"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
echo "PASS: $name mTLS identity enforcement"
|
||||||
|
done
|
||||||
|
|
||||||
|
echo
|
||||||
|
echo "PASS: all mTLS tests passed"
|
||||||
@@ -0,0 +1,251 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""OpenBao AppRole and KV v2 ACL tests for lab7."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import ssl
|
||||||
|
import stat
|
||||||
|
import uuid
|
||||||
|
import urllib.error
|
||||||
|
import urllib.request
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
BASE = Path.home() / ".local/share/mtusi2026lab7"
|
||||||
|
INIT_FILE = BASE / "operator/openbao-init.json"
|
||||||
|
URL = "https://localhost:8200/v1"
|
||||||
|
|
||||||
|
if stat.S_IMODE(INIT_FILE.stat().st_mode) != 0o600:
|
||||||
|
raise SystemExit("FAIL: operator secret file permissions")
|
||||||
|
|
||||||
|
with INIT_FILE.open(encoding="utf-8") as file:
|
||||||
|
ROOT_TOKEN = json.load(file)["root_token"]
|
||||||
|
|
||||||
|
TLS = ssl.create_default_context(
|
||||||
|
cafile=str(BASE / "pki/ca.crt")
|
||||||
|
)
|
||||||
|
|
||||||
|
TEST_ID = uuid.uuid4().hex
|
||||||
|
|
||||||
|
PATHS = {
|
||||||
|
"api": f"api/acl-test-{TEST_ID}",
|
||||||
|
"worker": f"worker/acl-test-{TEST_ID}",
|
||||||
|
}
|
||||||
|
|
||||||
|
TOKENS = []
|
||||||
|
|
||||||
|
|
||||||
|
def request(method, path, token=None, payload=None):
|
||||||
|
body = None
|
||||||
|
|
||||||
|
if payload is not None:
|
||||||
|
body = json.dumps(payload).encode("utf-8")
|
||||||
|
|
||||||
|
headers = {}
|
||||||
|
|
||||||
|
if token is not None:
|
||||||
|
headers["X-Vault-Token"] = token
|
||||||
|
|
||||||
|
if body is not None:
|
||||||
|
headers["Content-Type"] = "application/json"
|
||||||
|
|
||||||
|
req = urllib.request.Request(
|
||||||
|
URL + path,
|
||||||
|
data=body,
|
||||||
|
headers=headers,
|
||||||
|
method=method,
|
||||||
|
)
|
||||||
|
|
||||||
|
with urllib.request.urlopen(
|
||||||
|
req,
|
||||||
|
context=TLS,
|
||||||
|
timeout=15,
|
||||||
|
) as response:
|
||||||
|
raw = response.read()
|
||||||
|
|
||||||
|
return (
|
||||||
|
response.status,
|
||||||
|
json.loads(raw) if raw else {},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def passed(message):
|
||||||
|
print("PASS:", message)
|
||||||
|
|
||||||
|
|
||||||
|
def must_deny(method, path, token, payload=None):
|
||||||
|
try:
|
||||||
|
request(method, path, token, payload)
|
||||||
|
except urllib.error.HTTPError as exc:
|
||||||
|
if exc.code == 403:
|
||||||
|
return
|
||||||
|
raise AssertionError(
|
||||||
|
f"Expected HTTP 403, received {exc.code}"
|
||||||
|
) from None
|
||||||
|
|
||||||
|
raise AssertionError("Forbidden operation unexpectedly allowed")
|
||||||
|
|
||||||
|
|
||||||
|
def login(role):
|
||||||
|
name = f"messenger-{role}"
|
||||||
|
|
||||||
|
_, role_data = request(
|
||||||
|
"GET",
|
||||||
|
f"/auth/approle/role/{name}/role-id",
|
||||||
|
ROOT_TOKEN,
|
||||||
|
)
|
||||||
|
|
||||||
|
role_id = role_data["data"]["role_id"]
|
||||||
|
|
||||||
|
_, secret_data = request(
|
||||||
|
"POST",
|
||||||
|
f"/auth/approle/role/{name}/secret-id",
|
||||||
|
ROOT_TOKEN,
|
||||||
|
{},
|
||||||
|
)
|
||||||
|
|
||||||
|
secret_id = secret_data["data"]["secret_id"]
|
||||||
|
credentials = {
|
||||||
|
"role_id": role_id,
|
||||||
|
"secret_id": secret_id,
|
||||||
|
}
|
||||||
|
|
||||||
|
_, login_data = request(
|
||||||
|
"POST",
|
||||||
|
"/auth/approle/login",
|
||||||
|
payload=credentials,
|
||||||
|
)
|
||||||
|
|
||||||
|
auth = login_data["auth"]
|
||||||
|
token = auth["client_token"]
|
||||||
|
TOKENS.append(token)
|
||||||
|
|
||||||
|
assert 0 < auth["lease_duration"] <= 1200
|
||||||
|
assert name in auth["policies"]
|
||||||
|
assert "root" not in auth["policies"]
|
||||||
|
|
||||||
|
passed(f"{role}: scoped token issued with limited TTL")
|
||||||
|
|
||||||
|
# SecretID may only be used once.
|
||||||
|
try:
|
||||||
|
request(
|
||||||
|
"POST",
|
||||||
|
"/auth/approle/login",
|
||||||
|
payload=credentials,
|
||||||
|
)
|
||||||
|
except urllib.error.HTTPError as exc:
|
||||||
|
if exc.code not in (400, 403):
|
||||||
|
raise
|
||||||
|
passed(f"{role}: SecretID reuse denied")
|
||||||
|
else:
|
||||||
|
raise AssertionError("SecretID reused successfully")
|
||||||
|
|
||||||
|
return token
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
print("OpenBao HTTPS:", URL)
|
||||||
|
print("TLS verification: enabled")
|
||||||
|
|
||||||
|
# Create unique synthetic secrets using operator identity.
|
||||||
|
for role, path in PATHS.items():
|
||||||
|
request(
|
||||||
|
"POST",
|
||||||
|
"/lab7/data/" + path,
|
||||||
|
ROOT_TOKEN,
|
||||||
|
{"data": {"test_role": role}},
|
||||||
|
)
|
||||||
|
|
||||||
|
passed("temporary KV v2 secrets prepared")
|
||||||
|
|
||||||
|
api_token = login("api")
|
||||||
|
worker_token = login("worker")
|
||||||
|
|
||||||
|
# Allowed: each role reads its own path.
|
||||||
|
for role, token in (
|
||||||
|
("api", api_token),
|
||||||
|
("worker", worker_token),
|
||||||
|
):
|
||||||
|
_, result = request(
|
||||||
|
"GET",
|
||||||
|
"/lab7/data/" + PATHS[role],
|
||||||
|
token,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert result["data"]["data"]["test_role"] == role
|
||||||
|
passed(f"{role}: own secret read allowed")
|
||||||
|
|
||||||
|
# Denied: cross-role reads.
|
||||||
|
must_deny(
|
||||||
|
"GET",
|
||||||
|
"/lab7/data/" + PATHS["worker"],
|
||||||
|
api_token,
|
||||||
|
)
|
||||||
|
passed("API cannot read worker secrets")
|
||||||
|
|
||||||
|
must_deny(
|
||||||
|
"GET",
|
||||||
|
"/lab7/data/" + PATHS["api"],
|
||||||
|
worker_token,
|
||||||
|
)
|
||||||
|
passed("worker cannot read API secrets")
|
||||||
|
|
||||||
|
# Denied: updates, even within own path.
|
||||||
|
for role, token in (
|
||||||
|
("api", api_token),
|
||||||
|
("worker", worker_token),
|
||||||
|
):
|
||||||
|
must_deny(
|
||||||
|
"POST",
|
||||||
|
"/lab7/data/" + PATHS[role],
|
||||||
|
token,
|
||||||
|
{"data": {"test_role": "modified"}},
|
||||||
|
)
|
||||||
|
passed(f"{role}: secret modification denied")
|
||||||
|
|
||||||
|
# Denied: management of ACL policies.
|
||||||
|
for role, token in (
|
||||||
|
("api", api_token),
|
||||||
|
("worker", worker_token),
|
||||||
|
):
|
||||||
|
must_deny(
|
||||||
|
"GET",
|
||||||
|
"/sys/policies/acl/messenger-api",
|
||||||
|
token,
|
||||||
|
)
|
||||||
|
passed(f"{role}: policy administration denied")
|
||||||
|
|
||||||
|
print("PASS: all OpenBao AppRole ACL tests passed")
|
||||||
|
|
||||||
|
|
||||||
|
try:
|
||||||
|
main()
|
||||||
|
finally:
|
||||||
|
# Revoke only tokens created by this test.
|
||||||
|
for token in TOKENS:
|
||||||
|
try:
|
||||||
|
request(
|
||||||
|
"POST",
|
||||||
|
"/auth/token/revoke",
|
||||||
|
ROOT_TOKEN,
|
||||||
|
{"token": token},
|
||||||
|
)
|
||||||
|
except Exception as exc:
|
||||||
|
print(
|
||||||
|
"WARNING: token cleanup:",
|
||||||
|
type(exc).__name__,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Remove only the unique test secrets.
|
||||||
|
for path in PATHS.values():
|
||||||
|
try:
|
||||||
|
request(
|
||||||
|
"DELETE",
|
||||||
|
"/lab7/metadata/" + path,
|
||||||
|
ROOT_TOKEN,
|
||||||
|
)
|
||||||
|
except Exception as exc:
|
||||||
|
print(
|
||||||
|
"WARNING: KV cleanup:",
|
||||||
|
type(exc).__name__,
|
||||||
|
)
|
||||||
|
|
||||||
|
print("OpenBao test cleanup attempted")
|
||||||
@@ -0,0 +1,206 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Verify OpenBao certificate auth and least-privilege ACLs."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import ssl
|
||||||
|
import sys
|
||||||
|
import urllib.error
|
||||||
|
import urllib.request
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
BASE = Path.home() / ".local/share/mtusi2026lab7/pki"
|
||||||
|
URL = "https://localhost:8200/v1"
|
||||||
|
|
||||||
|
SERVICES = {
|
||||||
|
"api1": {
|
||||||
|
"policy": "messenger-api",
|
||||||
|
"own": "api",
|
||||||
|
"other": "worker",
|
||||||
|
},
|
||||||
|
"api2": {
|
||||||
|
"policy": "messenger-api",
|
||||||
|
"own": "api",
|
||||||
|
"other": "worker",
|
||||||
|
},
|
||||||
|
"worker": {
|
||||||
|
"policy": "messenger-worker",
|
||||||
|
"own": "worker",
|
||||||
|
"other": "api",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def request(method, path, tls, token=None, payload=None):
|
||||||
|
headers = {}
|
||||||
|
body = None
|
||||||
|
|
||||||
|
if token is not None:
|
||||||
|
headers["X-Vault-Token"] = token
|
||||||
|
|
||||||
|
if payload is not None:
|
||||||
|
body = json.dumps(payload).encode("utf-8")
|
||||||
|
headers["Content-Type"] = "application/json"
|
||||||
|
|
||||||
|
req = urllib.request.Request(
|
||||||
|
URL + path,
|
||||||
|
headers=headers,
|
||||||
|
data=body,
|
||||||
|
method=method,
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(
|
||||||
|
req,
|
||||||
|
context=tls,
|
||||||
|
timeout=15,
|
||||||
|
) as response:
|
||||||
|
raw = response.read()
|
||||||
|
result = json.loads(raw) if raw else {}
|
||||||
|
return response.status, result
|
||||||
|
|
||||||
|
except urllib.error.HTTPError as exc:
|
||||||
|
# Do not print HTTP response bodies: they may contain
|
||||||
|
# security-sensitive information.
|
||||||
|
return exc.code, {}
|
||||||
|
|
||||||
|
|
||||||
|
def verify_service(name, config):
|
||||||
|
cert = BASE / "openbao-clients" / f"{name}.crt"
|
||||||
|
key = BASE / "openbao-clients" / f"{name}.key"
|
||||||
|
|
||||||
|
tls = ssl.create_default_context(
|
||||||
|
cafile=str(BASE / "ca.crt")
|
||||||
|
)
|
||||||
|
tls.load_cert_chain(
|
||||||
|
certfile=str(cert),
|
||||||
|
keyfile=str(key),
|
||||||
|
)
|
||||||
|
|
||||||
|
print(f"=== {name} ===", flush=True)
|
||||||
|
|
||||||
|
status, result = request(
|
||||||
|
"POST",
|
||||||
|
"/auth/cert/login",
|
||||||
|
tls,
|
||||||
|
payload={"name": f"lab7-{name}"},
|
||||||
|
)
|
||||||
|
|
||||||
|
if status != 200:
|
||||||
|
raise RuntimeError(
|
||||||
|
f"{name}: certificate login HTTP {status}"
|
||||||
|
)
|
||||||
|
|
||||||
|
auth = result["auth"]
|
||||||
|
token = auth["client_token"]
|
||||||
|
|
||||||
|
print("PASS: certificate authentication successful")
|
||||||
|
|
||||||
|
try:
|
||||||
|
policies = set(auth.get("policies", []))
|
||||||
|
expected = {config["policy"]}
|
||||||
|
|
||||||
|
if policies != expected:
|
||||||
|
raise RuntimeError(
|
||||||
|
f"{name}: unexpected token policies"
|
||||||
|
)
|
||||||
|
|
||||||
|
print("PASS: only scoped service policy assigned")
|
||||||
|
|
||||||
|
own_path = (
|
||||||
|
f"/lab7/data/{config['own']}/runtime"
|
||||||
|
)
|
||||||
|
other_path = (
|
||||||
|
f"/lab7/data/{config['other']}/runtime"
|
||||||
|
)
|
||||||
|
|
||||||
|
status, result = request(
|
||||||
|
"GET",
|
||||||
|
own_path,
|
||||||
|
tls,
|
||||||
|
token=token,
|
||||||
|
)
|
||||||
|
|
||||||
|
if status != 200:
|
||||||
|
raise RuntimeError(
|
||||||
|
f"{name}: own secret read HTTP {status}"
|
||||||
|
)
|
||||||
|
|
||||||
|
secret = result.get("data", {}).get("data", {})
|
||||||
|
|
||||||
|
if not isinstance(secret, dict) or not secret:
|
||||||
|
raise RuntimeError(
|
||||||
|
f"{name}: own secret data missing"
|
||||||
|
)
|
||||||
|
|
||||||
|
print("PASS: own KV v2 secret readable")
|
||||||
|
|
||||||
|
status, _ = request(
|
||||||
|
"GET",
|
||||||
|
other_path,
|
||||||
|
tls,
|
||||||
|
token=token,
|
||||||
|
)
|
||||||
|
|
||||||
|
if status != 403:
|
||||||
|
raise RuntimeError(
|
||||||
|
f"{name}: cross-service read HTTP {status}"
|
||||||
|
)
|
||||||
|
|
||||||
|
print("PASS: cross-service KV read denied")
|
||||||
|
|
||||||
|
status, _ = request(
|
||||||
|
"POST",
|
||||||
|
own_path,
|
||||||
|
tls,
|
||||||
|
token=token,
|
||||||
|
payload={
|
||||||
|
"data": {
|
||||||
|
"acl_probe": "should-not-be-written"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
if status != 403:
|
||||||
|
raise RuntimeError(
|
||||||
|
f"{name}: unauthorized write HTTP {status}"
|
||||||
|
)
|
||||||
|
|
||||||
|
print("PASS: KV modification denied")
|
||||||
|
|
||||||
|
finally:
|
||||||
|
status, _ = request(
|
||||||
|
"POST",
|
||||||
|
"/auth/token/revoke-self",
|
||||||
|
tls,
|
||||||
|
token=token,
|
||||||
|
payload={},
|
||||||
|
)
|
||||||
|
|
||||||
|
if status not in (200, 204):
|
||||||
|
raise RuntimeError(
|
||||||
|
f"{name}: token revocation HTTP {status}"
|
||||||
|
)
|
||||||
|
|
||||||
|
print("PASS: temporary token revoked")
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
for name, config in SERVICES.items():
|
||||||
|
verify_service(name, config)
|
||||||
|
|
||||||
|
print("PASS: three certificate identities verified")
|
||||||
|
print("PASS: scoped OpenBao certificate ACL tests completed")
|
||||||
|
print("PASS: no secret values or tokens printed")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
try:
|
||||||
|
main()
|
||||||
|
except Exception as exc:
|
||||||
|
print(
|
||||||
|
"FAIL: certificate ACL test:",
|
||||||
|
type(exc).__name__,
|
||||||
|
str(exc) if isinstance(exc, RuntimeError) else "",
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
raise SystemExit(1)
|
||||||
@@ -0,0 +1,169 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Test certificate-based OpenBao bootstrap in isolated containers."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
PROJECT = Path(__file__).resolve().parent.parent
|
||||||
|
BASE = Path.home() / ".local/share/mtusi2026lab7/pki"
|
||||||
|
|
||||||
|
SERVICES = {
|
||||||
|
"api1": {
|
||||||
|
"path": "lab7/data/api/runtime",
|
||||||
|
"fields": 3,
|
||||||
|
},
|
||||||
|
"api2": {
|
||||||
|
"path": "lab7/data/api/runtime",
|
||||||
|
"fields": 3,
|
||||||
|
},
|
||||||
|
"worker": {
|
||||||
|
"path": "lab7/data/worker/runtime",
|
||||||
|
"fields": 5,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def get_network():
|
||||||
|
container = subprocess.check_output(
|
||||||
|
["docker", "compose", "ps", "-q", "openbao"],
|
||||||
|
cwd=PROJECT,
|
||||||
|
text=True,
|
||||||
|
).strip()
|
||||||
|
|
||||||
|
if not container:
|
||||||
|
raise RuntimeError("OpenBao container not running")
|
||||||
|
|
||||||
|
data = json.loads(
|
||||||
|
subprocess.check_output(
|
||||||
|
["docker", "inspect", container],
|
||||||
|
text=True,
|
||||||
|
)
|
||||||
|
)[0]
|
||||||
|
|
||||||
|
networks = data["NetworkSettings"]["Networks"]
|
||||||
|
|
||||||
|
for name in networks:
|
||||||
|
if name.endswith("_default"):
|
||||||
|
return name
|
||||||
|
|
||||||
|
raise RuntimeError("Project Docker network not found")
|
||||||
|
|
||||||
|
|
||||||
|
def test_service(service, config, network):
|
||||||
|
print(f"=== {service} ===", flush=True)
|
||||||
|
|
||||||
|
cert = BASE / "openbao-clients" / f"{service}.crt"
|
||||||
|
key = BASE / "openbao-clients" / f"{service}.key"
|
||||||
|
ca = BASE / "ca.crt"
|
||||||
|
|
||||||
|
client_module = PROJECT / "src/openbao_cert_client.py"
|
||||||
|
|
||||||
|
for path in (cert, key, ca, client_module):
|
||||||
|
if not path.is_file():
|
||||||
|
raise RuntimeError(
|
||||||
|
f"Required file missing: {path.name}"
|
||||||
|
)
|
||||||
|
|
||||||
|
test_code = (
|
||||||
|
"from src.openbao_cert_client import read_runtime_secrets\n"
|
||||||
|
"import os\n"
|
||||||
|
"secrets = read_runtime_secrets()\n"
|
||||||
|
"assert len(secrets) == int(os.environ['EXPECTED_FIELDS'])\n"
|
||||||
|
"assert all(isinstance(v, str) and v for v in secrets.values())\n"
|
||||||
|
"print('PASS: certificate authentication and KV retrieval')\n"
|
||||||
|
"print('PASS: expected number of secret fields received')\n"
|
||||||
|
"print('PASS: no secret values printed')\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
command = [
|
||||||
|
"docker", "run",
|
||||||
|
"--rm",
|
||||||
|
"--network", network,
|
||||||
|
"--mount",
|
||||||
|
(
|
||||||
|
f"type=bind,source={ca},"
|
||||||
|
"target=/etc/ssl/lab7/ca.crt,readonly"
|
||||||
|
),
|
||||||
|
"--mount",
|
||||||
|
(
|
||||||
|
f"type=bind,source={cert},"
|
||||||
|
"target=/run/lab7/bao/client.crt,readonly"
|
||||||
|
),
|
||||||
|
"--mount",
|
||||||
|
(
|
||||||
|
f"type=bind,source={key},"
|
||||||
|
"target=/run/lab7/bao/client.key,readonly"
|
||||||
|
),
|
||||||
|
"--mount",
|
||||||
|
(
|
||||||
|
f"type=bind,source={client_module},"
|
||||||
|
"target=/app/src/openbao_cert_client.py,readonly"
|
||||||
|
),
|
||||||
|
"-e", "BAO_ADDR=https://openbao:8200",
|
||||||
|
"-e", "BAO_CACERT=/etc/ssl/lab7/ca.crt",
|
||||||
|
"-e", "BAO_CERT_FILE=/run/lab7/bao/client.crt",
|
||||||
|
"-e", "BAO_KEY_FILE=/run/lab7/bao/client.key",
|
||||||
|
"-e", f"BAO_CERT_NAME=lab7-{service}",
|
||||||
|
"-e", f"BAO_SECRET_PATH={config['path']}",
|
||||||
|
"-e", f"EXPECTED_FIELDS={config['fields']}",
|
||||||
|
"--entrypoint", "python",
|
||||||
|
f"mtusi2026lab7-{service}",
|
||||||
|
"-c", test_code,
|
||||||
|
]
|
||||||
|
|
||||||
|
result = subprocess.run(
|
||||||
|
command,
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
timeout=90,
|
||||||
|
)
|
||||||
|
|
||||||
|
if result.returncode != 0:
|
||||||
|
print(
|
||||||
|
f"FAIL: {service} container test "
|
||||||
|
f"exit code {result.returncode}",
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
raise RuntimeError("Container certificate test failed")
|
||||||
|
|
||||||
|
expected_lines = (
|
||||||
|
"PASS: certificate authentication and KV retrieval",
|
||||||
|
"PASS: expected number of secret fields received",
|
||||||
|
"PASS: no secret values printed",
|
||||||
|
)
|
||||||
|
|
||||||
|
for line in expected_lines:
|
||||||
|
if line not in result.stdout:
|
||||||
|
raise RuntimeError(
|
||||||
|
f"{service}: expected test result missing"
|
||||||
|
)
|
||||||
|
print(line, flush=True)
|
||||||
|
|
||||||
|
print(
|
||||||
|
f"PASS: {service} certificate bootstrap verified",
|
||||||
|
flush=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
network = get_network()
|
||||||
|
|
||||||
|
for service, config in SERVICES.items():
|
||||||
|
test_service(service, config, network)
|
||||||
|
|
||||||
|
print("PASS: three certificate bootstrap tests completed")
|
||||||
|
print("PASS: running application containers unchanged")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
try:
|
||||||
|
main()
|
||||||
|
except Exception as exc:
|
||||||
|
print(
|
||||||
|
"FAIL: certificate bootstrap test:",
|
||||||
|
type(exc).__name__,
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
raise SystemExit(1)
|
||||||
@@ -0,0 +1,172 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Test certificate-based OpenBao entrypoint in Docker."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
PROJECT = Path(__file__).resolve().parent.parent
|
||||||
|
PKI = Path.home() / ".local/share/mtusi2026lab7/pki"
|
||||||
|
|
||||||
|
SERVICES = {
|
||||||
|
"api1": (
|
||||||
|
"lab7/data/api/runtime",
|
||||||
|
("DATABASE_URL", "S3_ACCESS_KEY", "S3_SECRET_KEY"),
|
||||||
|
),
|
||||||
|
"api2": (
|
||||||
|
"lab7/data/api/runtime",
|
||||||
|
("DATABASE_URL", "S3_ACCESS_KEY", "S3_SECRET_KEY"),
|
||||||
|
),
|
||||||
|
"worker": (
|
||||||
|
"lab7/data/worker/runtime",
|
||||||
|
(
|
||||||
|
"DATABASE_URL",
|
||||||
|
"RABBITMQ_USER",
|
||||||
|
"RABBITMQ_PASSWORD",
|
||||||
|
"S3_ACCESS_KEY",
|
||||||
|
"S3_SECRET_KEY",
|
||||||
|
),
|
||||||
|
),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def project_network():
|
||||||
|
container_id = subprocess.check_output(
|
||||||
|
["docker", "compose", "ps", "-q", "openbao"],
|
||||||
|
cwd=PROJECT,
|
||||||
|
text=True,
|
||||||
|
).strip()
|
||||||
|
|
||||||
|
if not container_id:
|
||||||
|
raise RuntimeError("OpenBao is not running")
|
||||||
|
|
||||||
|
details = json.loads(
|
||||||
|
subprocess.check_output(
|
||||||
|
["docker", "inspect", container_id],
|
||||||
|
text=True,
|
||||||
|
)
|
||||||
|
)[0]
|
||||||
|
|
||||||
|
for name in details["NetworkSettings"]["Networks"]:
|
||||||
|
if name.endswith("_default"):
|
||||||
|
return name
|
||||||
|
|
||||||
|
raise RuntimeError("Project Docker network not found")
|
||||||
|
|
||||||
|
|
||||||
|
def mount(source, target):
|
||||||
|
if not source.is_file():
|
||||||
|
raise RuntimeError(
|
||||||
|
"Required file missing: " + source.name
|
||||||
|
)
|
||||||
|
|
||||||
|
return (
|
||||||
|
f"type=bind,source={source},"
|
||||||
|
f"target={target},readonly"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def verify(service, secret_path, required, network):
|
||||||
|
print(f"=== {service} ===", flush=True)
|
||||||
|
|
||||||
|
cert = PKI / "openbao-clients" / f"{service}.crt"
|
||||||
|
key = PKI / "openbao-clients" / f"{service}.key"
|
||||||
|
|
||||||
|
child_code = (
|
||||||
|
"import os\n"
|
||||||
|
f"required = {required!r}\n"
|
||||||
|
"assert all("
|
||||||
|
"isinstance(os.environ.get(k), str) "
|
||||||
|
"and os.environ[k] for k in required"
|
||||||
|
")\n"
|
||||||
|
"print('PASS: child process received runtime credentials')\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
command = [
|
||||||
|
"docker", "run", "--rm",
|
||||||
|
"--network", network,
|
||||||
|
"--mount", mount(
|
||||||
|
PKI / "ca.crt",
|
||||||
|
"/etc/ssl/lab7/ca.crt",
|
||||||
|
),
|
||||||
|
"--mount", mount(
|
||||||
|
cert,
|
||||||
|
"/run/lab7/bao/client.crt",
|
||||||
|
),
|
||||||
|
"--mount", mount(
|
||||||
|
key,
|
||||||
|
"/run/lab7/bao/client.key",
|
||||||
|
),
|
||||||
|
"--mount", mount(
|
||||||
|
PROJECT / "src/openbao_cert_client.py",
|
||||||
|
"/app/src/openbao_cert_client.py",
|
||||||
|
),
|
||||||
|
"--mount", mount(
|
||||||
|
PROJECT / "src/openbao_entrypoint.py",
|
||||||
|
"/app/src/openbao_entrypoint.py",
|
||||||
|
),
|
||||||
|
"-e", "BAO_ADDR=https://openbao:8200",
|
||||||
|
"-e", "BAO_CACERT=/etc/ssl/lab7/ca.crt",
|
||||||
|
"-e", "BAO_CERT_FILE=/run/lab7/bao/client.crt",
|
||||||
|
"-e", "BAO_KEY_FILE=/run/lab7/bao/client.key",
|
||||||
|
"-e", f"BAO_CERT_NAME=lab7-{service}",
|
||||||
|
"-e", f"BAO_SECRET_PATH={secret_path}",
|
||||||
|
"--entrypoint", "python",
|
||||||
|
f"mtusi2026lab7-{service}",
|
||||||
|
"-m", "src.openbao_entrypoint",
|
||||||
|
"--",
|
||||||
|
"python", "-c", child_code,
|
||||||
|
]
|
||||||
|
|
||||||
|
result = subprocess.run(
|
||||||
|
command,
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
timeout=90,
|
||||||
|
)
|
||||||
|
|
||||||
|
if result.returncode != 0:
|
||||||
|
raise RuntimeError(
|
||||||
|
f"{service}: container exit code {result.returncode}"
|
||||||
|
)
|
||||||
|
|
||||||
|
expected = (
|
||||||
|
"PASS: runtime credentials loaded from OpenBao",
|
||||||
|
"PASS: child process received runtime credentials",
|
||||||
|
)
|
||||||
|
|
||||||
|
for line in expected:
|
||||||
|
if line not in result.stdout:
|
||||||
|
raise RuntimeError(
|
||||||
|
f"{service}: expected result missing"
|
||||||
|
)
|
||||||
|
print(line, flush=True)
|
||||||
|
|
||||||
|
print(
|
||||||
|
f"PASS: {service} certificate entrypoint verified",
|
||||||
|
flush=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
network = project_network()
|
||||||
|
|
||||||
|
for service, (secret_path, required) in SERVICES.items():
|
||||||
|
verify(service, secret_path, required, network)
|
||||||
|
|
||||||
|
print("PASS: three certificate entrypoint tests completed")
|
||||||
|
print("PASS: running containers unchanged")
|
||||||
|
print("PASS: no secret values or tokens printed")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
try:
|
||||||
|
main()
|
||||||
|
except Exception as exc:
|
||||||
|
print(
|
||||||
|
"FAIL: certificate entrypoint test:",
|
||||||
|
type(exc).__name__,
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
raise SystemExit(1)
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Verify OpenBao rejects mismatched certificate identities."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import ssl
|
||||||
|
import sys
|
||||||
|
import urllib.error
|
||||||
|
import urllib.request
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
PKI = Path.home() / ".local/share/mtusi2026lab7/pki"
|
||||||
|
URL = "https://localhost:8200/v1"
|
||||||
|
|
||||||
|
CASES = (
|
||||||
|
("api1", "lab7-worker"),
|
||||||
|
("api2", "lab7-api1"),
|
||||||
|
("worker", "lab7-api2"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def verify(source, claimed_identity):
|
||||||
|
tls = ssl.create_default_context(
|
||||||
|
cafile=str(PKI / "ca.crt")
|
||||||
|
)
|
||||||
|
|
||||||
|
tls.load_cert_chain(
|
||||||
|
certfile=str(
|
||||||
|
PKI / "openbao-clients" / f"{source}.crt"
|
||||||
|
),
|
||||||
|
keyfile=str(
|
||||||
|
PKI / "openbao-clients" / f"{source}.key"
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
body = json.dumps({
|
||||||
|
"name": claimed_identity,
|
||||||
|
}).encode("utf-8")
|
||||||
|
|
||||||
|
req = urllib.request.Request(
|
||||||
|
URL + "/auth/cert/login",
|
||||||
|
data=body,
|
||||||
|
headers={"Content-Type": "application/json"},
|
||||||
|
method="POST",
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(
|
||||||
|
req,
|
||||||
|
context=tls,
|
||||||
|
timeout=15,
|
||||||
|
) as response:
|
||||||
|
data = json.load(response)
|
||||||
|
|
||||||
|
except urllib.error.HTTPError as exc:
|
||||||
|
if exc.code in (400, 403):
|
||||||
|
print(
|
||||||
|
f"PASS: {source} cannot authenticate "
|
||||||
|
f"as {claimed_identity}"
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
raise RuntimeError(
|
||||||
|
f"Unexpected authentication HTTP {exc.code}"
|
||||||
|
) from None
|
||||||
|
|
||||||
|
# Defensive cleanup if an unexpected login succeeded.
|
||||||
|
token = data.get("auth", {}).get("client_token")
|
||||||
|
|
||||||
|
if token:
|
||||||
|
revoke = urllib.request.Request(
|
||||||
|
URL + "/auth/token/revoke-self",
|
||||||
|
data=b"{}",
|
||||||
|
headers={
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"X-Vault-Token": token,
|
||||||
|
},
|
||||||
|
method="POST",
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(
|
||||||
|
revoke,
|
||||||
|
context=tls,
|
||||||
|
timeout=15,
|
||||||
|
):
|
||||||
|
pass
|
||||||
|
except Exception:
|
||||||
|
print(
|
||||||
|
"WARNING: unexpected token revocation failed",
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
|
||||||
|
raise RuntimeError(
|
||||||
|
f"Certificate identity substitution accepted: {source}"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
for source, claimed_identity in CASES:
|
||||||
|
verify(source, claimed_identity)
|
||||||
|
|
||||||
|
print("PASS: all certificate identity substitutions rejected")
|
||||||
|
print("PASS: no credentials or tokens printed")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
try:
|
||||||
|
main()
|
||||||
|
except Exception as exc:
|
||||||
|
print(
|
||||||
|
"FAIL: certificate identity test:",
|
||||||
|
type(exc).__name__,
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
raise SystemExit(1)
|
||||||
@@ -0,0 +1,271 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Test OpenBao bootstrap from isolated API and worker containers."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import ssl
|
||||||
|
import stat
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import urllib.request
|
||||||
|
import urllib.error
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
BASE = Path.home() / ".local/share/mtusi2026lab7"
|
||||||
|
OPERATOR = BASE / "operator"
|
||||||
|
INIT_FILE = OPERATOR / "openbao-init.json"
|
||||||
|
PROJECT = Path.cwd()
|
||||||
|
BAO_URL = "https://localhost:8200/v1"
|
||||||
|
|
||||||
|
SERVICES = {
|
||||||
|
"api1": "messenger-api",
|
||||||
|
"api2": "messenger-api",
|
||||||
|
"worker": "messenger-worker",
|
||||||
|
}
|
||||||
|
|
||||||
|
CONTAINER_TEST = """
|
||||||
|
import hmac
|
||||||
|
import os
|
||||||
|
from src.openbao_client import read_runtime_secrets
|
||||||
|
|
||||||
|
secrets = read_runtime_secrets()
|
||||||
|
|
||||||
|
role = os.environ["BAO_SECRET_PATH"].split("/")[2]
|
||||||
|
|
||||||
|
fields = (
|
||||||
|
"DATABASE_URL",
|
||||||
|
"S3_ACCESS_KEY",
|
||||||
|
"S3_SECRET_KEY",
|
||||||
|
)
|
||||||
|
|
||||||
|
if role == "worker":
|
||||||
|
fields += (
|
||||||
|
"RABBITMQ_USER",
|
||||||
|
"RABBITMQ_PASSWORD",
|
||||||
|
)
|
||||||
|
|
||||||
|
assert set(secrets) == set(fields), "Unexpected secret fields"
|
||||||
|
|
||||||
|
for field in fields:
|
||||||
|
assert hmac.compare_digest(
|
||||||
|
secrets[field],
|
||||||
|
os.environ[field],
|
||||||
|
), "Secret mismatch: " + field
|
||||||
|
|
||||||
|
print("PASS: AppRole authentication completed")
|
||||||
|
print("PASS: runtime secrets match service credentials")
|
||||||
|
print("PASS: scoped KV v2 secret loaded")
|
||||||
|
print("PASS: no secret values printed")
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def request(method, path, token, tls, payload=None):
|
||||||
|
body = None
|
||||||
|
|
||||||
|
if payload is not None:
|
||||||
|
body = json.dumps(payload).encode("utf-8")
|
||||||
|
|
||||||
|
headers = {"X-Vault-Token": token}
|
||||||
|
|
||||||
|
if body is not None:
|
||||||
|
headers["Content-Type"] = "application/json"
|
||||||
|
|
||||||
|
req = urllib.request.Request(
|
||||||
|
BAO_URL + path,
|
||||||
|
data=body,
|
||||||
|
headers=headers,
|
||||||
|
method=method,
|
||||||
|
)
|
||||||
|
|
||||||
|
with urllib.request.urlopen(
|
||||||
|
req,
|
||||||
|
context=tls,
|
||||||
|
timeout=15,
|
||||||
|
) as response:
|
||||||
|
data = response.read()
|
||||||
|
return json.loads(data) if data else {}
|
||||||
|
|
||||||
|
|
||||||
|
def private_file(path, value):
|
||||||
|
with path.open("x", encoding="utf-8") as file:
|
||||||
|
file.write(value + "\n")
|
||||||
|
|
||||||
|
path.chmod(0o600)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
if stat.S_IMODE(INIT_FILE.stat().st_mode) != 0o600:
|
||||||
|
raise RuntimeError("Operator file must have mode 600")
|
||||||
|
|
||||||
|
with INIT_FILE.open(encoding="utf-8") as file:
|
||||||
|
root_token = json.load(file)["root_token"]
|
||||||
|
|
||||||
|
tls = ssl.create_default_context(
|
||||||
|
cafile=str(BASE / "pki/ca.crt")
|
||||||
|
)
|
||||||
|
|
||||||
|
module = PROJECT / "src/openbao_client.py"
|
||||||
|
|
||||||
|
if not module.is_file():
|
||||||
|
raise RuntimeError("OpenBao client module not found")
|
||||||
|
|
||||||
|
os.umask(0o077)
|
||||||
|
|
||||||
|
for service, role in SERVICES.items():
|
||||||
|
print("=== {} ===".format(service), flush=True)
|
||||||
|
|
||||||
|
role_response = request(
|
||||||
|
"GET",
|
||||||
|
"/auth/approle/role/{}/role-id".format(role),
|
||||||
|
root_token,
|
||||||
|
tls,
|
||||||
|
)
|
||||||
|
|
||||||
|
role_id = role_response["data"]["role_id"]
|
||||||
|
|
||||||
|
secret_response = request(
|
||||||
|
"POST",
|
||||||
|
"/auth/approle/role/{}/secret-id".format(role),
|
||||||
|
root_token,
|
||||||
|
tls,
|
||||||
|
{},
|
||||||
|
)
|
||||||
|
|
||||||
|
secret_data = secret_response["data"]
|
||||||
|
secret_id = secret_data["secret_id"]
|
||||||
|
accessor = secret_data["secret_id_accessor"]
|
||||||
|
|
||||||
|
try:
|
||||||
|
with tempfile.TemporaryDirectory(
|
||||||
|
prefix=".openbao-test-",
|
||||||
|
dir=OPERATOR,
|
||||||
|
) as temporary:
|
||||||
|
directory = Path(temporary)
|
||||||
|
|
||||||
|
private_file(directory / "role-id", role_id)
|
||||||
|
private_file(directory / "secret-id", secret_id)
|
||||||
|
|
||||||
|
command = [
|
||||||
|
"docker", "compose",
|
||||||
|
"run", "--rm", "-T", "--no-deps",
|
||||||
|
"-v",
|
||||||
|
"{}:/run/lab7/approle:ro".format(
|
||||||
|
directory
|
||||||
|
),
|
||||||
|
"-v",
|
||||||
|
"{}:/app/src/openbao_client.py:ro".format(
|
||||||
|
module
|
||||||
|
),
|
||||||
|
"-e", "BAO_ADDR=https://openbao:8200",
|
||||||
|
"-e", "BAO_CACERT=/etc/ssl/lab7/ca.crt",
|
||||||
|
"-e", "BAO_ROLE_ID_FILE=/run/lab7/approle/role-id",
|
||||||
|
"-e", "BAO_SECRET_ID_FILE=/run/lab7/approle/secret-id",
|
||||||
|
"-e",
|
||||||
|
"BAO_SECRET_PATH=lab7/data/{}/runtime".format(
|
||||||
|
"worker" if service == "worker" else "api"
|
||||||
|
),
|
||||||
|
"--entrypoint", "python",
|
||||||
|
service, "-",
|
||||||
|
]
|
||||||
|
|
||||||
|
result = subprocess.run(
|
||||||
|
command,
|
||||||
|
input=CONTAINER_TEST,
|
||||||
|
text=True,
|
||||||
|
capture_output=True,
|
||||||
|
check=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
if result.returncode != 0:
|
||||||
|
print(
|
||||||
|
"FAIL: temporary container test failed",
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
print(
|
||||||
|
"INFO: container exit code:",
|
||||||
|
result.returncode,
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
raise RuntimeError(
|
||||||
|
"{} bootstrap test failed".format(service)
|
||||||
|
)
|
||||||
|
|
||||||
|
for line in result.stdout.splitlines():
|
||||||
|
if line.startswith("PASS:"):
|
||||||
|
print(line)
|
||||||
|
|
||||||
|
print(
|
||||||
|
"PASS: {} bootstrap verified".format(service),
|
||||||
|
flush=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
finally:
|
||||||
|
# A single-use SecretID is normally removed
|
||||||
|
# automatically after successful authentication.
|
||||||
|
accessor_path = (
|
||||||
|
"/auth/approle/role/{}/secret-id-accessor".format(
|
||||||
|
role
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
request(
|
||||||
|
"POST",
|
||||||
|
accessor_path + "/lookup",
|
||||||
|
root_token,
|
||||||
|
tls,
|
||||||
|
{"secret_id_accessor": accessor},
|
||||||
|
)
|
||||||
|
|
||||||
|
except urllib.error.HTTPError as exc:
|
||||||
|
if exc.code == 404:
|
||||||
|
print(
|
||||||
|
"PASS: consumed SecretID already absent",
|
||||||
|
flush=True,
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
print(
|
||||||
|
"WARNING: SecretID lookup HTTP {}".format(
|
||||||
|
exc.code
|
||||||
|
),
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
|
||||||
|
else:
|
||||||
|
# Destroy only if the SecretID still exists.
|
||||||
|
try:
|
||||||
|
request(
|
||||||
|
"POST",
|
||||||
|
accessor_path + "/destroy",
|
||||||
|
root_token,
|
||||||
|
tls,
|
||||||
|
{"secret_id_accessor": accessor},
|
||||||
|
)
|
||||||
|
print(
|
||||||
|
"PASS: unused SecretID revoked",
|
||||||
|
flush=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
except urllib.error.HTTPError as exc:
|
||||||
|
print(
|
||||||
|
"WARNING: SecretID cleanup HTTP {}".format(
|
||||||
|
exc.code
|
||||||
|
),
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
|
||||||
|
print("PASS: three independent bootstrap tests completed")
|
||||||
|
print("PASS: temporary credential files removed")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
try:
|
||||||
|
main()
|
||||||
|
except Exception as exc:
|
||||||
|
print(
|
||||||
|
"FAIL: OpenBao bootstrap:",
|
||||||
|
type(exc).__name__,
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
raise SystemExit(1)
|
||||||
@@ -0,0 +1,241 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Test OpenBao entrypoint in an isolated API container."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import ssl
|
||||||
|
import stat
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import urllib.error
|
||||||
|
import urllib.request
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
BASE = Path.home() / ".local/share/mtusi2026lab7"
|
||||||
|
OPERATOR = BASE / "operator"
|
||||||
|
INIT_FILE = OPERATOR / "openbao-init.json"
|
||||||
|
URL = "https://localhost:8200/v1"
|
||||||
|
|
||||||
|
if len(sys.argv) != 2 or sys.argv[1] not in ("api1", "api2", "worker"):
|
||||||
|
raise SystemExit(
|
||||||
|
"Usage: python3 scripts/test-openbao-entrypoint.py "
|
||||||
|
"{api1,api2,worker}"
|
||||||
|
)
|
||||||
|
|
||||||
|
SERVICE = sys.argv[1]
|
||||||
|
|
||||||
|
ROLE = (
|
||||||
|
"messenger-worker"
|
||||||
|
if SERVICE == "worker"
|
||||||
|
else "messenger-api"
|
||||||
|
)
|
||||||
|
|
||||||
|
SECRET_PATH = (
|
||||||
|
"lab7/data/worker/runtime"
|
||||||
|
if SERVICE == "worker"
|
||||||
|
else "lab7/data/api/runtime"
|
||||||
|
)
|
||||||
|
|
||||||
|
def request(method, path, token, tls, payload=None):
|
||||||
|
body = (
|
||||||
|
json.dumps(payload).encode("utf-8")
|
||||||
|
if payload is not None else None
|
||||||
|
)
|
||||||
|
|
||||||
|
headers = {"X-Vault-Token": token}
|
||||||
|
|
||||||
|
if body is not None:
|
||||||
|
headers["Content-Type"] = "application/json"
|
||||||
|
|
||||||
|
req = urllib.request.Request(
|
||||||
|
URL + path,
|
||||||
|
data=body,
|
||||||
|
headers=headers,
|
||||||
|
method=method,
|
||||||
|
)
|
||||||
|
|
||||||
|
with urllib.request.urlopen(
|
||||||
|
req,
|
||||||
|
context=tls,
|
||||||
|
timeout=15,
|
||||||
|
) as response:
|
||||||
|
raw = response.read()
|
||||||
|
return json.loads(raw) if raw else {}
|
||||||
|
|
||||||
|
|
||||||
|
def private_file(path, value):
|
||||||
|
with path.open("x", encoding="utf-8") as file:
|
||||||
|
file.write(value + "\n")
|
||||||
|
path.chmod(0o600)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
if stat.S_IMODE(INIT_FILE.stat().st_mode) != 0o600:
|
||||||
|
raise RuntimeError("Invalid operator file permissions")
|
||||||
|
|
||||||
|
with INIT_FILE.open(encoding="utf-8") as file:
|
||||||
|
root_token = json.load(file)["root_token"]
|
||||||
|
|
||||||
|
tls = ssl.create_default_context(
|
||||||
|
cafile=str(BASE / "pki/ca.crt")
|
||||||
|
)
|
||||||
|
|
||||||
|
container_id = subprocess.check_output(
|
||||||
|
["docker", "compose", "ps", "-q", "openbao"],
|
||||||
|
text=True,
|
||||||
|
).strip()
|
||||||
|
|
||||||
|
if not container_id:
|
||||||
|
raise RuntimeError("OpenBao container not running")
|
||||||
|
|
||||||
|
inspect = json.loads(subprocess.check_output(
|
||||||
|
["docker", "inspect", container_id],
|
||||||
|
text=True,
|
||||||
|
))[0]
|
||||||
|
|
||||||
|
networks = inspect["NetworkSettings"]["Networks"]
|
||||||
|
|
||||||
|
network = next(
|
||||||
|
(name for name in networks if name.endswith("_default")),
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
|
||||||
|
if not network:
|
||||||
|
raise RuntimeError("Project Docker network not found")
|
||||||
|
|
||||||
|
role_result = request(
|
||||||
|
"GET",
|
||||||
|
f"/auth/approle/role/{ROLE}/role-id",
|
||||||
|
root_token,
|
||||||
|
tls,
|
||||||
|
)
|
||||||
|
|
||||||
|
role_id = role_result["data"]["role_id"]
|
||||||
|
|
||||||
|
secret_result = request(
|
||||||
|
"POST",
|
||||||
|
f"/auth/approle/role/{ROLE}/secret-id",
|
||||||
|
root_token,
|
||||||
|
tls,
|
||||||
|
{},
|
||||||
|
)
|
||||||
|
|
||||||
|
secret_data = secret_result["data"]
|
||||||
|
secret_id = secret_data["secret_id"]
|
||||||
|
accessor = secret_data["secret_id_accessor"]
|
||||||
|
|
||||||
|
print(
|
||||||
|
f"PASS: temporary {SERVICE} SecretID issued",
|
||||||
|
flush=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
os.umask(0o077)
|
||||||
|
|
||||||
|
with tempfile.TemporaryDirectory(
|
||||||
|
prefix=".openbao-entrypoint-",
|
||||||
|
dir=OPERATOR,
|
||||||
|
) as temporary:
|
||||||
|
directory = Path(temporary)
|
||||||
|
|
||||||
|
private_file(directory / "role-id", role_id)
|
||||||
|
private_file(directory / "secret-id", secret_id)
|
||||||
|
|
||||||
|
project = Path.cwd().resolve()
|
||||||
|
|
||||||
|
command = [
|
||||||
|
"docker", "run", "--rm",
|
||||||
|
"--network", network,
|
||||||
|
"--mount",
|
||||||
|
f"type=bind,source={directory},target=/run/lab7/approle,readonly",
|
||||||
|
"--mount",
|
||||||
|
f"type=bind,source={BASE / 'pki/ca.crt'},target=/etc/ssl/lab7/ca.crt,readonly",
|
||||||
|
"--mount",
|
||||||
|
f"type=bind,source={project / 'src/openbao_client.py'},target=/app/src/openbao_client.py,readonly",
|
||||||
|
"--mount",
|
||||||
|
f"type=bind,source={project / 'src/openbao_entrypoint.py'},target=/app/src/openbao_entrypoint.py,readonly",
|
||||||
|
"-e", "BAO_ADDR=https://openbao:8200",
|
||||||
|
"-e", "BAO_CACERT=/etc/ssl/lab7/ca.crt",
|
||||||
|
"-e", "BAO_ROLE_ID_FILE=/run/lab7/approle/role-id",
|
||||||
|
"-e", "BAO_SECRET_ID_FILE=/run/lab7/approle/secret-id",
|
||||||
|
"-e", f"BAO_SECRET_PATH={SECRET_PATH}",
|
||||||
|
"--entrypoint", "python",
|
||||||
|
f"mtusi2026lab7-{SERVICE}",
|
||||||
|
"-m", "src.openbao_entrypoint",
|
||||||
|
"--",
|
||||||
|
"python", "-c",
|
||||||
|
(
|
||||||
|
"import os; "
|
||||||
|
"required=('DATABASE_URL','S3_ACCESS_KEY','S3_SECRET_KEY'); "
|
||||||
|
"required += ('RABBITMQ_USER','RABBITMQ_PASSWORD') "
|
||||||
|
"if os.environ.get('BAO_SECRET_PATH') == "
|
||||||
|
"'lab7/data/worker/runtime' else (); "
|
||||||
|
"assert all(os.environ.get(k) for k in required); "
|
||||||
|
"print('PASS: child process received OpenBao secrets')"
|
||||||
|
),
|
||||||
|
]
|
||||||
|
|
||||||
|
result = subprocess.run(
|
||||||
|
command,
|
||||||
|
text=True,
|
||||||
|
capture_output=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
if result.returncode != 0:
|
||||||
|
print(
|
||||||
|
"FAIL: isolated entrypoint test, exit code",
|
||||||
|
result.returncode,
|
||||||
|
)
|
||||||
|
raise RuntimeError("Entrypoint test failed")
|
||||||
|
|
||||||
|
for line in result.stdout.splitlines():
|
||||||
|
if line.startswith("PASS:"):
|
||||||
|
print(line)
|
||||||
|
|
||||||
|
print(f"PASS: {SERVICE} OpenBao entrypoint verified")
|
||||||
|
|
||||||
|
finally:
|
||||||
|
# An already consumed single-use SecretID is absent.
|
||||||
|
# Revoke only if the SecretID still exists.
|
||||||
|
path = f"/auth/approle/role/{ROLE}/secret-id-accessor"
|
||||||
|
|
||||||
|
try:
|
||||||
|
request(
|
||||||
|
"POST",
|
||||||
|
path + "/lookup",
|
||||||
|
root_token,
|
||||||
|
tls,
|
||||||
|
{"secret_id_accessor": accessor},
|
||||||
|
)
|
||||||
|
except urllib.error.HTTPError as exc:
|
||||||
|
if exc.code == 404:
|
||||||
|
print("PASS: consumed SecretID already absent")
|
||||||
|
else:
|
||||||
|
print("WARNING: SecretID lookup HTTP", exc.code)
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
request(
|
||||||
|
"POST",
|
||||||
|
path + "/destroy",
|
||||||
|
root_token,
|
||||||
|
tls,
|
||||||
|
{"secret_id_accessor": accessor},
|
||||||
|
)
|
||||||
|
print("PASS: unused SecretID revoked")
|
||||||
|
except urllib.error.HTTPError as exc:
|
||||||
|
print("WARNING: SecretID cleanup HTTP", exc.code)
|
||||||
|
|
||||||
|
print("PASS: temporary bootstrap files removed")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
try:
|
||||||
|
main()
|
||||||
|
except Exception as exc:
|
||||||
|
print(
|
||||||
|
"FAIL: OpenBao entrypoint test:",
|
||||||
|
type(exc).__name__,
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
raise SystemExit(1)
|
||||||
@@ -0,0 +1,263 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Verify real runtime secrets using scoped OpenBao AppRole."""
|
||||||
|
|
||||||
|
import hmac
|
||||||
|
import json
|
||||||
|
import ssl
|
||||||
|
import stat
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import urllib.error
|
||||||
|
import urllib.request
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
BASE = Path.home() / ".local/share/mtusi2026lab7"
|
||||||
|
BAO_URL = "https://localhost:8200/v1"
|
||||||
|
INIT_FILE = BASE / "operator/openbao-init.json"
|
||||||
|
|
||||||
|
FIELDS = {
|
||||||
|
"api": (
|
||||||
|
"DATABASE_URL",
|
||||||
|
"S3_ACCESS_KEY",
|
||||||
|
"S3_SECRET_KEY",
|
||||||
|
),
|
||||||
|
"worker": (
|
||||||
|
"DATABASE_URL",
|
||||||
|
"RABBITMQ_USER",
|
||||||
|
"RABBITMQ_PASSWORD",
|
||||||
|
"S3_ACCESS_KEY",
|
||||||
|
"S3_SECRET_KEY",
|
||||||
|
),
|
||||||
|
}
|
||||||
|
|
||||||
|
TOKENS = []
|
||||||
|
|
||||||
|
TLS = ssl.create_default_context(
|
||||||
|
cafile=str(BASE / "pki/ca.crt")
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def check(condition, message):
|
||||||
|
if not condition:
|
||||||
|
raise RuntimeError(message)
|
||||||
|
|
||||||
|
print("PASS:", message)
|
||||||
|
|
||||||
|
|
||||||
|
def request(method, path, token=None, payload=None):
|
||||||
|
body = None
|
||||||
|
headers = {}
|
||||||
|
|
||||||
|
if token is not None:
|
||||||
|
headers["X-Vault-Token"] = token
|
||||||
|
|
||||||
|
if payload is not None:
|
||||||
|
body = json.dumps(payload).encode("utf-8")
|
||||||
|
headers["Content-Type"] = "application/json"
|
||||||
|
|
||||||
|
req = urllib.request.Request(
|
||||||
|
BAO_URL + path,
|
||||||
|
data=body,
|
||||||
|
headers=headers,
|
||||||
|
method=method,
|
||||||
|
)
|
||||||
|
|
||||||
|
with urllib.request.urlopen(
|
||||||
|
req,
|
||||||
|
context=TLS,
|
||||||
|
timeout=15,
|
||||||
|
) as response:
|
||||||
|
raw = response.read()
|
||||||
|
|
||||||
|
return (
|
||||||
|
response.status,
|
||||||
|
json.loads(raw) if raw else {},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def same_secrets(actual, expected):
|
||||||
|
if set(actual) != set(expected):
|
||||||
|
return False
|
||||||
|
|
||||||
|
return all(
|
||||||
|
isinstance(actual[key], str)
|
||||||
|
and hmac.compare_digest(
|
||||||
|
actual[key],
|
||||||
|
expected[key],
|
||||||
|
)
|
||||||
|
for key in expected
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def get_service_token(role, root_token):
|
||||||
|
name = "messenger-" + role
|
||||||
|
|
||||||
|
_, role_response = request(
|
||||||
|
"GET",
|
||||||
|
f"/auth/approle/role/{name}/role-id",
|
||||||
|
root_token,
|
||||||
|
)
|
||||||
|
|
||||||
|
role_id = role_response["data"]["role_id"]
|
||||||
|
|
||||||
|
_, secret_response = request(
|
||||||
|
"POST",
|
||||||
|
f"/auth/approle/role/{name}/secret-id",
|
||||||
|
root_token,
|
||||||
|
{},
|
||||||
|
)
|
||||||
|
|
||||||
|
secret_id = secret_response["data"]["secret_id"]
|
||||||
|
|
||||||
|
_, login_response = request(
|
||||||
|
"POST",
|
||||||
|
"/auth/approle/login",
|
||||||
|
payload={
|
||||||
|
"role_id": role_id,
|
||||||
|
"secret_id": secret_id,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
auth = login_response["auth"]
|
||||||
|
token = auth["client_token"]
|
||||||
|
TOKENS.append(token)
|
||||||
|
|
||||||
|
check(
|
||||||
|
name in auth["policies"]
|
||||||
|
and "root" not in auth["policies"],
|
||||||
|
f"{role}: correct scoped policy",
|
||||||
|
)
|
||||||
|
|
||||||
|
check(
|
||||||
|
0 < auth["lease_duration"] <= 1200,
|
||||||
|
f"{role}: limited token TTL",
|
||||||
|
)
|
||||||
|
|
||||||
|
return token
|
||||||
|
|
||||||
|
|
||||||
|
def must_deny(token, path, label):
|
||||||
|
try:
|
||||||
|
request("GET", path, token)
|
||||||
|
except urllib.error.HTTPError as exc:
|
||||||
|
check(
|
||||||
|
exc.code == 403,
|
||||||
|
label + " (HTTP 403)",
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
raise RuntimeError(
|
||||||
|
label + ": forbidden read unexpectedly allowed"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def main(root_token):
|
||||||
|
print("OpenBao endpoint:", BAO_URL)
|
||||||
|
print("TLS verification: enabled")
|
||||||
|
|
||||||
|
result = subprocess.run(
|
||||||
|
["docker", "compose", "config", "--format", "json"],
|
||||||
|
check=True,
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
services = json.loads(result.stdout)["services"]
|
||||||
|
|
||||||
|
expected = {
|
||||||
|
"api": {
|
||||||
|
key: services["api1"]["environment"][key]
|
||||||
|
for key in FIELDS["api"]
|
||||||
|
},
|
||||||
|
"worker": {
|
||||||
|
key: services["worker"]["environment"][key]
|
||||||
|
for key in FIELDS["worker"]
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
check(
|
||||||
|
all(
|
||||||
|
services["api1"]["environment"][key]
|
||||||
|
== services["api2"]["environment"][key]
|
||||||
|
for key in FIELDS["api"]
|
||||||
|
),
|
||||||
|
"API replicas use matching credentials",
|
||||||
|
)
|
||||||
|
|
||||||
|
api_token = get_service_token("api", root_token)
|
||||||
|
worker_token = get_service_token("worker", root_token)
|
||||||
|
|
||||||
|
for role, token in (
|
||||||
|
("api", api_token),
|
||||||
|
("worker", worker_token),
|
||||||
|
):
|
||||||
|
status, response = request(
|
||||||
|
"GET",
|
||||||
|
f"/lab7/data/{role}/runtime",
|
||||||
|
token,
|
||||||
|
)
|
||||||
|
|
||||||
|
actual = response["data"]["data"]
|
||||||
|
|
||||||
|
check(
|
||||||
|
status == 200
|
||||||
|
and same_secrets(actual, expected[role]),
|
||||||
|
f"{role}: runtime secrets match Compose",
|
||||||
|
)
|
||||||
|
|
||||||
|
must_deny(
|
||||||
|
api_token,
|
||||||
|
"/lab7/data/worker/runtime",
|
||||||
|
"API cannot read worker runtime secrets",
|
||||||
|
)
|
||||||
|
|
||||||
|
must_deny(
|
||||||
|
worker_token,
|
||||||
|
"/lab7/data/api/runtime",
|
||||||
|
"Worker cannot read API runtime secrets",
|
||||||
|
)
|
||||||
|
|
||||||
|
must_deny(
|
||||||
|
api_token,
|
||||||
|
"/sys/policies/acl/messenger-api",
|
||||||
|
"API cannot read policy configuration",
|
||||||
|
)
|
||||||
|
|
||||||
|
must_deny(
|
||||||
|
worker_token,
|
||||||
|
"/sys/policies/acl/messenger-worker",
|
||||||
|
"Worker cannot read policy configuration",
|
||||||
|
)
|
||||||
|
|
||||||
|
print("PASS: all OpenBao runtime access tests passed")
|
||||||
|
print("PASS: no credential values printed")
|
||||||
|
|
||||||
|
|
||||||
|
try:
|
||||||
|
if stat.S_IMODE(INIT_FILE.stat().st_mode) != 0o600:
|
||||||
|
raise RuntimeError("Operator file permissions must be 600")
|
||||||
|
|
||||||
|
with INIT_FILE.open(encoding="utf-8") as file:
|
||||||
|
root_token = json.load(file)["root_token"]
|
||||||
|
|
||||||
|
try:
|
||||||
|
main(root_token)
|
||||||
|
finally:
|
||||||
|
for token in TOKENS:
|
||||||
|
try:
|
||||||
|
request(
|
||||||
|
"POST",
|
||||||
|
"/auth/token/revoke",
|
||||||
|
root_token,
|
||||||
|
{"token": token},
|
||||||
|
)
|
||||||
|
print("PASS: temporary service token revoked")
|
||||||
|
except Exception:
|
||||||
|
print("WARNING: service token revocation failed")
|
||||||
|
|
||||||
|
except Exception as exc:
|
||||||
|
print(
|
||||||
|
"FAIL: OpenBao runtime test:",
|
||||||
|
type(exc).__name__,
|
||||||
|
file=sys.stderr,
|
||||||
|
)
|
||||||
|
raise SystemExit(1)
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Negative RabbitMQ ACL tests over authenticated TLS."""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
import pika
|
||||||
|
|
||||||
|
from src.queue import RABBITMQ_QUEUE, connect
|
||||||
|
|
||||||
|
|
||||||
|
def test_publisher_cannot_consume(channel):
|
||||||
|
try:
|
||||||
|
method, properties, body = channel.basic_get(
|
||||||
|
queue=RABBITMQ_QUEUE,
|
||||||
|
auto_ack=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Safety: if permissions are unexpectedly too broad,
|
||||||
|
# immediately return any received message to the queue.
|
||||||
|
if method is not None:
|
||||||
|
channel.basic_nack(
|
||||||
|
delivery_tag=method.delivery_tag,
|
||||||
|
requeue=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
print("FAIL: publisher was allowed to read queue")
|
||||||
|
return False
|
||||||
|
|
||||||
|
except pika.exceptions.ChannelClosedByBroker as exc:
|
||||||
|
if exc.reply_code == 403 and "ACCESS_REFUSED" in exc.reply_text:
|
||||||
|
print("PASS: publisher cannot consume image_jobs")
|
||||||
|
return True
|
||||||
|
|
||||||
|
print(
|
||||||
|
"FAIL: unexpected broker response:",
|
||||||
|
exc.reply_code,
|
||||||
|
exc.reply_text,
|
||||||
|
)
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def test_consumer_cannot_publish(channel):
|
||||||
|
# A unique nonexistent routing key ensures that even if
|
||||||
|
# publishing is unexpectedly permitted, no existing queue
|
||||||
|
# receives a test message.
|
||||||
|
routing_key = "lab7_acl_unroutable_" + uuid.uuid4().hex
|
||||||
|
|
||||||
|
try:
|
||||||
|
channel.basic_publish(
|
||||||
|
exchange="",
|
||||||
|
routing_key=routing_key,
|
||||||
|
body=b'{"acl_test":true}',
|
||||||
|
mandatory=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Flush asynchronous broker responses.
|
||||||
|
channel.queue_declare(
|
||||||
|
queue=RABBITMQ_QUEUE,
|
||||||
|
passive=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
print("FAIL: consumer was allowed to publish")
|
||||||
|
return False
|
||||||
|
|
||||||
|
except pika.exceptions.ChannelClosedByBroker as exc:
|
||||||
|
if exc.reply_code == 403 and "ACCESS_REFUSED" in exc.reply_text:
|
||||||
|
print("PASS: consumer cannot publish")
|
||||||
|
return True
|
||||||
|
|
||||||
|
print(
|
||||||
|
"FAIL: unexpected broker response:",
|
||||||
|
exc.reply_code,
|
||||||
|
exc.reply_text,
|
||||||
|
)
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
role = os.environ.get("RABBITMQ_USER")
|
||||||
|
|
||||||
|
connection = connect()
|
||||||
|
|
||||||
|
try:
|
||||||
|
print("RabbitMQ role:", role)
|
||||||
|
print("TLS connection: authenticated")
|
||||||
|
|
||||||
|
channel = connection.channel()
|
||||||
|
|
||||||
|
if role == "messenger_publisher":
|
||||||
|
passed = test_publisher_cannot_consume(channel)
|
||||||
|
|
||||||
|
elif role == "messenger_consumer":
|
||||||
|
passed = test_consumer_cannot_publish(channel)
|
||||||
|
|
||||||
|
else:
|
||||||
|
print("FAIL: unexpected RabbitMQ role")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
if not passed:
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
print("PASS: RabbitMQ ACL tests for", role)
|
||||||
|
|
||||||
|
finally:
|
||||||
|
if connection.is_open:
|
||||||
|
connection.close()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
|
||||||
|
sql() {
|
||||||
|
docker compose exec -T db \
|
||||||
|
psql -U messenger -d messenger -At -c "$1"
|
||||||
|
}
|
||||||
|
|
||||||
|
echo "Finding completed image job..."
|
||||||
|
|
||||||
|
JOB_ID=$(sql "
|
||||||
|
SELECT j.id
|
||||||
|
FROM attachment_jobs j
|
||||||
|
JOIN attachment_variants v
|
||||||
|
ON v.attachment_id = j.attachment_id
|
||||||
|
WHERE j.status = 'ready'
|
||||||
|
AND v.variant_name = 'thumbnail'
|
||||||
|
ORDER BY j.created_at DESC
|
||||||
|
LIMIT 1;
|
||||||
|
")
|
||||||
|
|
||||||
|
if [[ -z "$JOB_ID" ]]; then
|
||||||
|
echo "FAIL: no completed image job found"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "Job: $JOB_ID"
|
||||||
|
|
||||||
|
STATE_QUERY="
|
||||||
|
SELECT
|
||||||
|
j.status || '|' ||
|
||||||
|
j.attempts || '|' ||
|
||||||
|
v.sha256 || '|' ||
|
||||||
|
(
|
||||||
|
SELECT COUNT(*)
|
||||||
|
FROM attachment_variants
|
||||||
|
WHERE attachment_id = j.attachment_id
|
||||||
|
)
|
||||||
|
FROM attachment_jobs j
|
||||||
|
JOIN attachment_variants v
|
||||||
|
ON v.attachment_id = j.attachment_id
|
||||||
|
WHERE j.id = '$JOB_ID'
|
||||||
|
AND v.variant_name = 'thumbnail';
|
||||||
|
"
|
||||||
|
|
||||||
|
BEFORE=$(sql "$STATE_QUERY")
|
||||||
|
|
||||||
|
echo "Before: $BEFORE"
|
||||||
|
echo "Publishing the same job twice..."
|
||||||
|
|
||||||
|
docker compose run --rm --no-deps api1 \
|
||||||
|
python -c '
|
||||||
|
import sys
|
||||||
|
from src.queue import publish_job
|
||||||
|
|
||||||
|
job_id = sys.argv[1]
|
||||||
|
publish_job(job_id)
|
||||||
|
publish_job(job_id)
|
||||||
|
print("Two duplicate messages published")
|
||||||
|
' "$JOB_ID"
|
||||||
|
|
||||||
|
sleep 5
|
||||||
|
|
||||||
|
AFTER=$(sql "$STATE_QUERY")
|
||||||
|
|
||||||
|
echo "After: $AFTER"
|
||||||
|
|
||||||
|
if [[ "$BEFORE" != "$AFTER" ]]; then
|
||||||
|
echo "FAIL: completed job changed after redelivery"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "PASS: duplicate delivery did not change completed job"
|
||||||
|
echo "PASS: thumbnail checksum and variant count preserved"
|
||||||
@@ -0,0 +1,246 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Positive and negative RustFS IAM tests over verified HTTPS."""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import uuid
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import boto3
|
||||||
|
from botocore.config import Config
|
||||||
|
from botocore.exceptions import ClientError
|
||||||
|
|
||||||
|
|
||||||
|
BUCKET = os.environ["S3_BUCKET"]
|
||||||
|
ENDPOINT = os.environ["S3_ENDPOINT"]
|
||||||
|
CA_FILE = os.environ["AWS_CA_BUNDLE"]
|
||||||
|
|
||||||
|
assert ENDPOINT == "https://minio:9000"
|
||||||
|
assert Path(CA_FILE).is_file()
|
||||||
|
|
||||||
|
values = {}
|
||||||
|
|
||||||
|
for line in Path("/run/lab7/local.env").read_text(
|
||||||
|
encoding="utf-8"
|
||||||
|
).splitlines():
|
||||||
|
line = line.strip()
|
||||||
|
|
||||||
|
if not line or line.startswith("#") or "=" not in line:
|
||||||
|
continue
|
||||||
|
|
||||||
|
name, value = line.split("=", 1)
|
||||||
|
values[name.strip()] = value.strip().strip('"').strip("'")
|
||||||
|
|
||||||
|
|
||||||
|
def client(access_key, secret_key):
|
||||||
|
return boto3.client(
|
||||||
|
"s3",
|
||||||
|
endpoint_url=ENDPOINT,
|
||||||
|
aws_access_key_id=access_key,
|
||||||
|
aws_secret_access_key=secret_key,
|
||||||
|
region_name="us-east-1",
|
||||||
|
verify=CA_FILE,
|
||||||
|
config=Config(
|
||||||
|
signature_version="s3v4",
|
||||||
|
s3={"addressing_style": "path"},
|
||||||
|
connect_timeout=5,
|
||||||
|
read_timeout=10,
|
||||||
|
retries={"max_attempts": 1},
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
admin = client(
|
||||||
|
os.environ["S3_ACCESS_KEY"],
|
||||||
|
os.environ["S3_SECRET_KEY"],
|
||||||
|
)
|
||||||
|
|
||||||
|
api = client(
|
||||||
|
values["S3_API_ACCESS_KEY"],
|
||||||
|
values["S3_API_SECRET_KEY"],
|
||||||
|
)
|
||||||
|
|
||||||
|
worker = client(
|
||||||
|
values["S3_WORKER_ACCESS_KEY"],
|
||||||
|
values["S3_WORKER_SECRET_KEY"],
|
||||||
|
)
|
||||||
|
|
||||||
|
suffix = uuid.uuid4().hex
|
||||||
|
|
||||||
|
keys = {
|
||||||
|
"staging": f"staging/acl-test-{suffix}",
|
||||||
|
"original": f"originals/acl-test-{suffix}",
|
||||||
|
"thumbnail": f"thumbnails/acl-test-{suffix}.jpg",
|
||||||
|
}
|
||||||
|
|
||||||
|
payload = b"lab7-rustfs-iam-test"
|
||||||
|
|
||||||
|
|
||||||
|
def put(s3, key):
|
||||||
|
s3.put_object(
|
||||||
|
Bucket=BUCKET,
|
||||||
|
Key=key,
|
||||||
|
Body=payload,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def get(s3, key):
|
||||||
|
response = s3.get_object(
|
||||||
|
Bucket=BUCKET,
|
||||||
|
Key=key,
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
return response["Body"].read()
|
||||||
|
finally:
|
||||||
|
response["Body"].close()
|
||||||
|
|
||||||
|
|
||||||
|
def delete(s3, key):
|
||||||
|
s3.delete_object(
|
||||||
|
Bucket=BUCKET,
|
||||||
|
Key=key,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def allowed(label, operation):
|
||||||
|
operation()
|
||||||
|
print(f"PASS: {label}")
|
||||||
|
|
||||||
|
|
||||||
|
def denied(label, operation):
|
||||||
|
try:
|
||||||
|
operation()
|
||||||
|
except ClientError as exc:
|
||||||
|
error = exc.response.get("Error", {})
|
||||||
|
status = exc.response.get(
|
||||||
|
"ResponseMetadata", {}
|
||||||
|
).get("HTTPStatusCode")
|
||||||
|
|
||||||
|
code = str(error.get("Code", ""))
|
||||||
|
|
||||||
|
if status == 403 or code in (
|
||||||
|
"AccessDenied",
|
||||||
|
"AllAccessDisabled",
|
||||||
|
):
|
||||||
|
print(f"PASS: {label} denied")
|
||||||
|
return
|
||||||
|
|
||||||
|
raise AssertionError(
|
||||||
|
f"{label}: unexpected S3 error "
|
||||||
|
f"{code}, HTTP {status}"
|
||||||
|
) from exc
|
||||||
|
|
||||||
|
raise AssertionError(
|
||||||
|
f"{label}: forbidden operation was allowed"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
print("RustFS endpoint:", ENDPOINT)
|
||||||
|
print("Bucket:", BUCKET)
|
||||||
|
print("TLS verification: enabled")
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Prepare existing objects so read-denial tests
|
||||||
|
# cannot be confused with missing-object errors.
|
||||||
|
for key in keys.values():
|
||||||
|
put(admin, key)
|
||||||
|
|
||||||
|
print("PASS: temporary test objects prepared")
|
||||||
|
|
||||||
|
# API: staging upload/delete and processed-object reads.
|
||||||
|
allowed(
|
||||||
|
"API can upload staging",
|
||||||
|
lambda: put(api, keys["staging"]),
|
||||||
|
)
|
||||||
|
|
||||||
|
allowed(
|
||||||
|
"API can read original",
|
||||||
|
lambda: get(api, keys["original"]),
|
||||||
|
)
|
||||||
|
|
||||||
|
allowed(
|
||||||
|
"API can read thumbnail",
|
||||||
|
lambda: get(api, keys["thumbnail"]),
|
||||||
|
)
|
||||||
|
|
||||||
|
allowed(
|
||||||
|
"API can delete staging",
|
||||||
|
lambda: delete(api, keys["staging"]),
|
||||||
|
)
|
||||||
|
|
||||||
|
# Restore staging for the worker tests.
|
||||||
|
put(admin, keys["staging"])
|
||||||
|
|
||||||
|
# Worker: read staging, write processed objects.
|
||||||
|
allowed(
|
||||||
|
"worker can read staging",
|
||||||
|
lambda: get(worker, keys["staging"]),
|
||||||
|
)
|
||||||
|
|
||||||
|
allowed(
|
||||||
|
"worker can write original",
|
||||||
|
lambda: put(worker, keys["original"]),
|
||||||
|
)
|
||||||
|
|
||||||
|
allowed(
|
||||||
|
"worker can write thumbnail",
|
||||||
|
lambda: put(worker, keys["thumbnail"]),
|
||||||
|
)
|
||||||
|
|
||||||
|
# Negative API tests.
|
||||||
|
denied(
|
||||||
|
"API staging read",
|
||||||
|
lambda: get(api, keys["staging"]),
|
||||||
|
)
|
||||||
|
|
||||||
|
denied(
|
||||||
|
"API original write",
|
||||||
|
lambda: put(api, keys["original"]),
|
||||||
|
)
|
||||||
|
|
||||||
|
denied(
|
||||||
|
"API thumbnail write",
|
||||||
|
lambda: put(api, keys["thumbnail"]),
|
||||||
|
)
|
||||||
|
|
||||||
|
denied(
|
||||||
|
"API original delete",
|
||||||
|
lambda: delete(api, keys["original"]),
|
||||||
|
)
|
||||||
|
|
||||||
|
# Negative worker tests.
|
||||||
|
denied(
|
||||||
|
"worker original read",
|
||||||
|
lambda: get(worker, keys["original"]),
|
||||||
|
)
|
||||||
|
|
||||||
|
denied(
|
||||||
|
"worker thumbnail read",
|
||||||
|
lambda: get(worker, keys["thumbnail"]),
|
||||||
|
)
|
||||||
|
|
||||||
|
denied(
|
||||||
|
"worker staging write",
|
||||||
|
lambda: put(worker, keys["staging"]),
|
||||||
|
)
|
||||||
|
|
||||||
|
denied(
|
||||||
|
"worker staging delete",
|
||||||
|
lambda: delete(worker, keys["staging"]),
|
||||||
|
)
|
||||||
|
|
||||||
|
print("PASS: all RustFS IAM ACL tests passed")
|
||||||
|
|
||||||
|
finally:
|
||||||
|
# Root credentials are used only for test cleanup.
|
||||||
|
for key in keys.values():
|
||||||
|
try:
|
||||||
|
delete(admin, key)
|
||||||
|
except Exception:
|
||||||
|
print("WARNING: cleanup failed for", key)
|
||||||
|
|
||||||
|
print("RustFS ACL test cleanup attempted")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,154 @@
|
|||||||
|
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
import time
|
||||||
|
import urllib.parse
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
|
||||||
|
LOKI = "http://loki:3100"
|
||||||
|
TEMPO = "http://tempo:3200"
|
||||||
|
|
||||||
|
TRACE_PATTERN = re.compile(r"^[0-9a-f]{32}$")
|
||||||
|
SPAN_PATTERN = re.compile(r"^[0-9a-f]{16}$")
|
||||||
|
|
||||||
|
|
||||||
|
def get_json(url):
|
||||||
|
with urllib.request.urlopen(url, timeout=15) as response:
|
||||||
|
return json.load(response)
|
||||||
|
|
||||||
|
|
||||||
|
def find_log(service, event):
|
||||||
|
params = urllib.parse.urlencode({
|
||||||
|
"query": f'{{service_name="{service}"}}',
|
||||||
|
"start": str(time.time_ns() - 6 * 3600 * 10**9),
|
||||||
|
"end": str(time.time_ns()),
|
||||||
|
"limit": 500,
|
||||||
|
"direction": "BACKWARD",
|
||||||
|
})
|
||||||
|
|
||||||
|
payload = get_json(
|
||||||
|
f"{LOKI}/loki/api/v1/query_range?{params}"
|
||||||
|
)
|
||||||
|
|
||||||
|
streams = payload.get("data", {}).get("result", [])
|
||||||
|
|
||||||
|
for stream in streams:
|
||||||
|
labels = stream.get("stream", {})
|
||||||
|
|
||||||
|
for entry in stream.get("values", []):
|
||||||
|
if len(entry) < 2:
|
||||||
|
continue
|
||||||
|
|
||||||
|
message = entry[1]
|
||||||
|
metadata = entry[2] if len(entry) >= 3 else {}
|
||||||
|
|
||||||
|
if event not in message and (
|
||||||
|
metadata.get("event") != event
|
||||||
|
):
|
||||||
|
continue
|
||||||
|
|
||||||
|
trace_id = (
|
||||||
|
metadata.get("trace_id")
|
||||||
|
or labels.get("trace_id")
|
||||||
|
)
|
||||||
|
|
||||||
|
span_id = (
|
||||||
|
metadata.get("span_id")
|
||||||
|
or labels.get("span_id")
|
||||||
|
)
|
||||||
|
|
||||||
|
if not trace_id or not TRACE_PATTERN.fullmatch(
|
||||||
|
trace_id
|
||||||
|
):
|
||||||
|
continue
|
||||||
|
|
||||||
|
if not span_id or not SPAN_PATTERN.fullmatch(
|
||||||
|
span_id
|
||||||
|
):
|
||||||
|
continue
|
||||||
|
|
||||||
|
return {
|
||||||
|
"service": service,
|
||||||
|
"event": event,
|
||||||
|
"message": message,
|
||||||
|
"trace_id": trace_id,
|
||||||
|
"span_id": span_id,
|
||||||
|
}
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def verify_trace(log, expected_kind):
|
||||||
|
trace_id = log["trace_id"]
|
||||||
|
|
||||||
|
payload = get_json(
|
||||||
|
f"{TEMPO}/api/traces/{trace_id}"
|
||||||
|
)
|
||||||
|
|
||||||
|
batches = payload.get("batches", [])
|
||||||
|
spans = []
|
||||||
|
|
||||||
|
for batch in batches:
|
||||||
|
for scope in batch.get("scopeSpans", []):
|
||||||
|
spans.extend(scope.get("spans", []))
|
||||||
|
|
||||||
|
if not spans:
|
||||||
|
raise AssertionError(
|
||||||
|
f"No spans found for {trace_id}"
|
||||||
|
)
|
||||||
|
|
||||||
|
kinds = [str(span.get("kind", "")) for span in spans]
|
||||||
|
|
||||||
|
if not any(expected_kind in kind for kind in kinds):
|
||||||
|
raise AssertionError(
|
||||||
|
f"Expected span kind {expected_kind}; got {kinds}"
|
||||||
|
)
|
||||||
|
|
||||||
|
print(f"Service: {log['service']}")
|
||||||
|
print(f"Event: {log['event']}")
|
||||||
|
print(f"Trace ID: {trace_id}")
|
||||||
|
print(f"Span ID: {log['span_id']}")
|
||||||
|
print(f"Tempo spans: {len(spans)}")
|
||||||
|
|
||||||
|
for span in spans:
|
||||||
|
print(
|
||||||
|
" Span:",
|
||||||
|
span.get("name"),
|
||||||
|
"kind:",
|
||||||
|
span.get("kind"),
|
||||||
|
)
|
||||||
|
|
||||||
|
print("PASS: Loki log linked to Tempo trace")
|
||||||
|
print()
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
cases = [
|
||||||
|
(
|
||||||
|
"messenger-api",
|
||||||
|
"HTTP request completed",
|
||||||
|
"SERVER",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"messenger-worker",
|
||||||
|
"Image job handled",
|
||||||
|
"CONSUMER",
|
||||||
|
),
|
||||||
|
]
|
||||||
|
|
||||||
|
for service, event, kind in cases:
|
||||||
|
log = find_log(service, event)
|
||||||
|
|
||||||
|
if log is None:
|
||||||
|
raise AssertionError(
|
||||||
|
f"No correlated log found for {service}"
|
||||||
|
)
|
||||||
|
|
||||||
|
verify_trace(log, kind)
|
||||||
|
|
||||||
|
print("PASS: API and worker trace correlation")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,256 @@
|
|||||||
|
import os
|
||||||
|
import base64
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import subprocess
|
||||||
|
import time
|
||||||
|
import urllib.error
|
||||||
|
import urllib.parse
|
||||||
|
import urllib.request
|
||||||
|
import uuid
|
||||||
|
import zlib
|
||||||
|
import struct
|
||||||
|
|
||||||
|
|
||||||
|
BASE = "http://127.0.0.1:8080"
|
||||||
|
|
||||||
|
|
||||||
|
def docker(*args):
|
||||||
|
subprocess.run(
|
||||||
|
["docker", "compose", *args],
|
||||||
|
check=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def api(method, path, token=None, body=None, headers=None):
|
||||||
|
request_headers = dict(headers or {})
|
||||||
|
|
||||||
|
if token:
|
||||||
|
request_headers["Authorization"] = f"Bearer {token}"
|
||||||
|
|
||||||
|
if isinstance(body, dict):
|
||||||
|
body = json.dumps(body).encode("utf-8")
|
||||||
|
request_headers["Content-Type"] = "application/json"
|
||||||
|
|
||||||
|
request = urllib.request.Request(
|
||||||
|
BASE + path,
|
||||||
|
data=body,
|
||||||
|
headers=request_headers,
|
||||||
|
method=method,
|
||||||
|
)
|
||||||
|
|
||||||
|
with urllib.request.urlopen(request, timeout=10) as response:
|
||||||
|
data = response.read()
|
||||||
|
return (
|
||||||
|
response.status,
|
||||||
|
json.loads(data) if data and
|
||||||
|
"application/json" in response.headers.get(
|
||||||
|
"Content-Type", ""
|
||||||
|
) else data,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def png_chunk(name, data):
|
||||||
|
value = name + data
|
||||||
|
return (
|
||||||
|
struct.pack(">I", len(data))
|
||||||
|
+ value
|
||||||
|
+ struct.pack(">I", zlib.crc32(value) & 0xFFFFFFFF)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def make_png():
|
||||||
|
width, height = 320, 200
|
||||||
|
scanline = b"\x00" + bytes([220, 80, 40]) * width
|
||||||
|
|
||||||
|
return (
|
||||||
|
b"\x89PNG\r\n\x1a\n"
|
||||||
|
+ png_chunk(
|
||||||
|
b"IHDR",
|
||||||
|
struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0),
|
||||||
|
)
|
||||||
|
+ png_chunk(
|
||||||
|
b"IDAT", zlib.compress(scanline * height)
|
||||||
|
)
|
||||||
|
+ png_chunk(b"IEND", b"")
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def wait_ready():
|
||||||
|
for _ in range(90):
|
||||||
|
try:
|
||||||
|
status, data = api("GET", "/health/ready")
|
||||||
|
if status == 200 and data.get("status") == "ok":
|
||||||
|
return
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
time.sleep(1)
|
||||||
|
|
||||||
|
raise RuntimeError("API did not become ready")
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
suffix = uuid.uuid4().hex[:12]
|
||||||
|
username = "lab5_" + suffix
|
||||||
|
password = "Lab5TestPassword_" + suffix
|
||||||
|
|
||||||
|
print("Stopping worker...", flush=True)
|
||||||
|
docker("stop", "worker")
|
||||||
|
wait_ready()
|
||||||
|
|
||||||
|
status, user = api(
|
||||||
|
"POST",
|
||||||
|
"/api/v1/users",
|
||||||
|
body={
|
||||||
|
"username": username,
|
||||||
|
"display_name": "Lab5 recovery test",
|
||||||
|
"password": password,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert status == 201
|
||||||
|
|
||||||
|
credentials = base64.b64encode(
|
||||||
|
f"{username}:{password}".encode()
|
||||||
|
).decode()
|
||||||
|
|
||||||
|
status, session = api(
|
||||||
|
"POST",
|
||||||
|
"/api/v1/auth/sessions",
|
||||||
|
headers={"Authorization": f"Basic {credentials}"},
|
||||||
|
body=b"",
|
||||||
|
)
|
||||||
|
assert status == 201
|
||||||
|
token = session["token"]
|
||||||
|
|
||||||
|
status, chat = api(
|
||||||
|
"POST",
|
||||||
|
"/api/v1/chats",
|
||||||
|
token,
|
||||||
|
{
|
||||||
|
"title": "Worker recovery",
|
||||||
|
"member_ids": [user["id"]],
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert status == 201
|
||||||
|
|
||||||
|
original = make_png()
|
||||||
|
path = (
|
||||||
|
f"/api/v1/chats/{chat['id']}/attachments"
|
||||||
|
"?filename=recovery.png"
|
||||||
|
)
|
||||||
|
|
||||||
|
status, attachment = api(
|
||||||
|
"POST",
|
||||||
|
path,
|
||||||
|
token,
|
||||||
|
original,
|
||||||
|
{"Content-Type": "image/png"},
|
||||||
|
)
|
||||||
|
|
||||||
|
assert status == 202, f"Expected 202, got {status}"
|
||||||
|
assert attachment["status"] == "queued"
|
||||||
|
attachment_id = attachment["id"]
|
||||||
|
print("Upload: 202 queued", flush=True)
|
||||||
|
|
||||||
|
status, message = api(
|
||||||
|
"POST",
|
||||||
|
f"/api/v1/chats/{chat['id']}/messages",
|
||||||
|
token,
|
||||||
|
{"text": "", "attachment_ids": [attachment_id]},
|
||||||
|
{"Idempotency-Key": "recovery-" + suffix},
|
||||||
|
)
|
||||||
|
assert status == 201
|
||||||
|
assert attachment_id in message["attachment_ids"]
|
||||||
|
print("Message created while worker is stopped", flush=True)
|
||||||
|
|
||||||
|
status, metadata = api(
|
||||||
|
"GET", f"/api/v1/attachments/{attachment_id}", token
|
||||||
|
)
|
||||||
|
assert status == 200 and metadata["status"] == "queued"
|
||||||
|
|
||||||
|
print("Restarting RabbitMQ and API...", flush=True)
|
||||||
|
docker("restart", "rabbitmq")
|
||||||
|
docker("up", "-d", "--wait", "rabbitmq")
|
||||||
|
docker("restart", "api1", "api2")
|
||||||
|
wait_ready()
|
||||||
|
|
||||||
|
status, metadata = api(
|
||||||
|
"GET", f"/api/v1/attachments/{attachment_id}", token
|
||||||
|
)
|
||||||
|
assert metadata["status"] == "queued"
|
||||||
|
print("Queued attachment survived restart", flush=True)
|
||||||
|
|
||||||
|
pause_seconds = int(
|
||||||
|
os.getenv("LAB6_WORKER_PAUSE_SECONDS", "60")
|
||||||
|
)
|
||||||
|
|
||||||
|
print(
|
||||||
|
f"INCIDENT: worker stopped for {pause_seconds} seconds",
|
||||||
|
flush=True,
|
||||||
|
)
|
||||||
|
time.sleep(pause_seconds)
|
||||||
|
|
||||||
|
print("Starting worker...", flush=True)
|
||||||
|
docker("up", "-d", "worker")
|
||||||
|
|
||||||
|
deadline = time.monotonic() + 90
|
||||||
|
|
||||||
|
while time.monotonic() < deadline:
|
||||||
|
status, metadata = api(
|
||||||
|
"GET", f"/api/v1/attachments/{attachment_id}", token
|
||||||
|
)
|
||||||
|
|
||||||
|
if metadata["status"] == "ready":
|
||||||
|
break
|
||||||
|
|
||||||
|
if metadata["status"] == "failed":
|
||||||
|
raise RuntimeError(
|
||||||
|
f"Processing failed: {metadata.get('error_code')}"
|
||||||
|
)
|
||||||
|
|
||||||
|
time.sleep(1)
|
||||||
|
else:
|
||||||
|
raise RuntimeError("Attachment did not become ready")
|
||||||
|
|
||||||
|
status, downloaded = api(
|
||||||
|
"GET",
|
||||||
|
f"/api/v1/attachments/{attachment_id}/content",
|
||||||
|
token,
|
||||||
|
)
|
||||||
|
assert status == 200
|
||||||
|
assert downloaded == original
|
||||||
|
assert hashlib.sha256(downloaded).hexdigest() == (
|
||||||
|
hashlib.sha256(original).hexdigest()
|
||||||
|
)
|
||||||
|
|
||||||
|
status, thumbnail = api(
|
||||||
|
"GET",
|
||||||
|
f"/api/v1/attachments/{attachment_id}/content"
|
||||||
|
"?variant=thumbnail",
|
||||||
|
token,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert status == 200
|
||||||
|
assert thumbnail.startswith(b"\xff\xd8")
|
||||||
|
assert thumbnail.endswith(b"\xff\xd9")
|
||||||
|
|
||||||
|
variants = metadata["variants"]
|
||||||
|
assert any(
|
||||||
|
v["name"] == "thumbnail"
|
||||||
|
and v["width"] == 256
|
||||||
|
and v["height"] == 160
|
||||||
|
for v in variants
|
||||||
|
)
|
||||||
|
|
||||||
|
print("Attachment: ready", flush=True)
|
||||||
|
print("Original: SHA-256 verified", flush=True)
|
||||||
|
print("Thumbnail: JPEG 256x160 verified", flush=True)
|
||||||
|
print("PASS: durable worker recovery", flush=True)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
try:
|
||||||
|
main()
|
||||||
|
finally:
|
||||||
|
# Restore the worker even when the test fails.
|
||||||
|
docker("up", "-d", "worker")
|
||||||
@@ -1,19 +1,77 @@
|
|||||||
# Модель угроз — заполнить
|
# Модель угроз — лабораторная работа №7
|
||||||
|
|
||||||
## Активы и акторы
|
## Активы и акторы
|
||||||
|
|
||||||
TODO: пользовательские credentials/сессии, сообщения/вложения, service identities, CA/secrets, telemetry. Акторы: участник чата, посторонний пользователь, внешний клиент, скомпрометированный сервис, оператор. Опишите доступ атакующего и границы учебного стенда.
|
**Активы:** пароли и Argon2id-хеши, пользовательские сессии,
|
||||||
|
сообщения и чаты, вложения, PostgreSQL, объекты RustFS/S3,
|
||||||
|
очереди RabbitMQ, сервисные credentials OpenBao, приватные ключи
|
||||||
|
и сертификаты, логи, метрики и трассировки.
|
||||||
|
|
||||||
|
**Акторы:** участник чата, посторонний пользователь, внешний клиент,
|
||||||
|
скомпрометированный сервис и оператор стенда.
|
||||||
|
|
||||||
|
Рассматриваемый атакующий может отправлять произвольные HTTP-запросы,
|
||||||
|
подменять заголовки, предъявлять неверные TLS-сертификаты и пытаться
|
||||||
|
обращаться к данным, не разрешённым его identity. Полная компрометация
|
||||||
|
Docker host или CA private key находится за пределами базового сценария.
|
||||||
|
|
||||||
## Границы доверия
|
## Границы доверия
|
||||||
|
|
||||||
TODO: схема и ссылка на заполненную contracts/trust-matrix.md; публичные/внутренние интерфейсы, процессы, секреты и их выдача.
|
Клиент --HTTPS:8443--> Nginx
|
||||||
|
Nginx --mTLS--> HAProxy-sidecar --> API1/API2
|
||||||
|
API/worker --TLS и ACL--> PostgreSQL, RabbitMQ, RustFS
|
||||||
|
API/worker --TLS и scoped auth--> OpenBao
|
||||||
|
Приложения --TLS--> OpenTelemetry Collector
|
||||||
|
Collector --mTLS:4317--> Tempo
|
||||||
|
Collector --HTTPS:3100--> Loki
|
||||||
|
|
||||||
| Угроза и конкретный путь | Нарушаемый инвариант | Контроль | Отрицательный тест | Остаточное ограничение |
|
Внутренний plaintext между API и его sidecar допустим только в
|
||||||
|
общем закрытом сетевом пространстве контейнеров. Порты API наружу
|
||||||
|
не публикуются.
|
||||||
|
|
||||||
|
Дополнительные соединения наблюдаемости и их текущий статус
|
||||||
|
приведены в `contracts/trust-matrix.md`.
|
||||||
|
|
||||||
|
## Угрозы, контрмеры и проверки
|
||||||
|
|
||||||
|
| Угроза | Нарушаемое свойство | Контроль | Проверка | Ограничение |
|
||||||
|---|---|---|---|---|
|
|---|---|---|---|---|
|
||||||
| TODO | TODO | TODO | TODO | TODO |
|
| Посторонний клиент читает сообщения чужого чата | Конфиденциальность | Bearer identity и ACL | `tests/smoke.py` | Smoke не заменяет полный набор ACL |
|
||||||
|
| Посторонний клиент скачивает чужое вложение | Изоляция объектов | ACL чатов и вложений | `tests/smoke.py` | Дополнительные отрицательные случаи проверяются отдельно |
|
||||||
|
| Подбор пароля через частые запросы | Защита учётной записи | Argon2id и login rate limit | `scripts/test-login-rate-limit.py` | Нагрузка на CPU остаётся возможной |
|
||||||
|
| Клиент без разрешённой identity подключается к API | Изоляция внутреннего API | mTLS и проверка service identity | `scripts/test-mtls.sh`, `evidence/mtls-negative-tests.txt` | Необходима защита CA private key |
|
||||||
|
| Сервис пытается читать чужие секреты | Least privilege | OpenBao scoped policies | `evidence/openbao-approle-acl-tests.txt`, `evidence/openbao-cert-auth-acl-tests.txt` | Компрометация действующего credential |
|
||||||
|
| Сервис пытается выполнять запрещённые операции БД | Разделение прав | Ограниченные DB roles | `evidence/postgres-acl-tests.txt` | Требуется контроль выданных ролей |
|
||||||
|
| Worker пытается использовать чужие S3-права | Изоляция хранилища | Scoped credentials | `evidence/rustfs-acl-tests.txt` | Ошибки последующих изменений ACL |
|
||||||
|
| Клиент без сертификата подключается к Tempo | Защита telemetry | mTLS | Отказ `certificate required` | Общий CA не заменяет разрешённую identity |
|
||||||
|
| Клиент с недоверенным CA подключается к Tempo | Проверка доверия | Проверка client CA | Отказ `unknown ca` | Компрометация доверенного CA |
|
||||||
|
| Остановка одной API-реплики | Доступность | Балансировка и две реплики | `evidence/final-failover.txt` | Не гарантирует отказоустойчивость БД |
|
||||||
|
| Перезапуск контейнеров хранения | Сохранность данных | Persistent volumes | `evidence/final-persistence.txt` | Резервное копирование отдельно |
|
||||||
|
|
||||||
На 4 минимум 6 конкретных угроз. Не заменяйте сценарии словами «SQL injection», «безопасный Docker», «mTLS включён» без пути и проверки.
|
## Bootstrap, secrets lifecycle и инциденты
|
||||||
|
|
||||||
## Lifecycle и инциденты
|
PKI создаётся локально. CA private key и сервисные private keys
|
||||||
|
хранятся вне Git-репозитория, под контролем оператора.
|
||||||
|
Приложение не должно получать root token и unseal keys OpenBao.
|
||||||
|
|
||||||
TODO: bootstrap, expiry/renewal, revoke/rotation, компрометация identity, sealed OpenBao и восстановление. Указать владельца CA/unseal и способ защиты bootstrap credentials. Сопоставить scan findings с реальной применимостью и исправлением/остаточным риском.
|
OpenBao использует постоянное хранилище, сервисную аутентификацию
|
||||||
|
и scoped policies. Bootstrap, выдача credentials и операции
|
||||||
|
с сертификатами автоматизированы скриптами в `scripts/`.
|
||||||
|
|
||||||
|
При отзыве credential требуется проверять новое подключение,
|
||||||
|
поскольку существующее соединение может сохраняться до его закрытия.
|
||||||
|
При sealed OpenBao новые обращения к секретам могут быть недоступны;
|
||||||
|
восстановление выполняет оператор с использованием защищённых
|
||||||
|
unseal credentials.
|
||||||
|
|
||||||
|
Доказательства ACL, ротации и отзыва credentials находятся
|
||||||
|
в `evidence/openbao-*`.
|
||||||
|
|
||||||
|
## Ограничения
|
||||||
|
|
||||||
|
Подтверждена отказоустойчивость одной API-реплики, но не отказ
|
||||||
|
всего Docker host, PostgreSQL или брокера.
|
||||||
|
|
||||||
|
Незащищённые HTTP-соединения наблюдаемости перечислены в
|
||||||
|
матрице доверия и должны быть устранены либо обоснованы
|
||||||
|
проверенной закрытой границей перед сдачей.
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
global
|
||||||
|
maxconn 256
|
||||||
|
|
||||||
|
defaults
|
||||||
|
mode http
|
||||||
|
timeout connect 5s
|
||||||
|
timeout client 30s
|
||||||
|
timeout server 30s
|
||||||
|
|
||||||
|
frontend api_mtls
|
||||||
|
bind :8443 ssl crt /run/lab7-pki/api1.pem ca-file /run/lab7-pki/ca.crt verify required ssl-min-ver TLSv1.2
|
||||||
|
|
||||||
|
acl authorized_lb ssl_c_san -m str "DNS:lb.messenger.internal"
|
||||||
|
http-request deny deny_status 403 unless authorized_lb
|
||||||
|
|
||||||
|
default_backend local_api
|
||||||
|
|
||||||
|
backend local_api
|
||||||
|
server fastapi 127.0.0.1:8080 check
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user