feat: реализовать ЛР7 — TLS, mTLS, OpenBao и hardening
Skeleton contracts / contracts (pull_request) Blocked by required conditions
Skeleton contracts / contracts (pull_request) Blocked by required conditions
This commit is contained in:
@@ -18,3 +18,5 @@ __pycache__
|
||||
node_modules
|
||||
evidence
|
||||
.DS_Store
|
||||
|
||||
.local/
|
||||
|
||||
+27
-39
@@ -1,41 +1,29 @@
|
||||
# Copy to .env for your LOCAL synthetic test environment; never commit .env.
|
||||
# These are logical interface suggestions; map actual framework names in REPORT.md.
|
||||
APP_HOST=0.0.0.0
|
||||
APP_PORT=8080
|
||||
APP_ENV=lab
|
||||
SESSION_TTL_SECONDS=3600
|
||||
# Choose credentials locally. File paths contain no secret values.
|
||||
DATABASE_URL_FILE=/run/secrets/database_url
|
||||
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
|
||||
SESSION_STORE=postgres
|
||||
CACHE_URL_FILE=/run/secrets/cache_url
|
||||
API_REPLICAS=2
|
||||
IDEMPOTENCY_TTL_SECONDS=86400
|
||||
S3_ENDPOINT=https://s3:9000
|
||||
S3_REGION=us-east-1
|
||||
# Create a complete .env with python scripts/bootstrap_env.py; these are NOT defaults.
|
||||
# Do not commit .env, .local, certificates, tokens or their values.
|
||||
POSTGRES_DB=messenger
|
||||
POSTGRES_USER=lab
|
||||
POSTGRES_PASSWORD=CHANGE_ME
|
||||
DB_API_PASSWORD=CHANGE_ME
|
||||
DB_WORKER_PASSWORD=CHANGE_ME
|
||||
DB_DISPATCHER_PASSWORD=CHANGE_ME
|
||||
BROKER_ADMIN_USER=bootstrap
|
||||
BROKER_ADMIN_PASSWORD=CHANGE_ME
|
||||
BROKER_DISPATCHER_USER=dispatcher
|
||||
BROKER_DISPATCHER_PASSWORD=CHANGE_ME
|
||||
BROKER_WORKER_USER=worker
|
||||
BROKER_WORKER_PASSWORD=CHANGE_ME
|
||||
S3_BUCKET=messenger-attachments
|
||||
S3_ACCESS_KEY_ID_FILE=/run/secrets/s3_access_key_id
|
||||
S3_SECRET_ACCESS_KEY_FILE=/run/secrets/s3_secret_access_key
|
||||
MAX_UPLOAD_BYTES=10485760
|
||||
MAX_IMAGE_PIXELS=40000000
|
||||
BROKER_URL_FILE=/run/secrets/broker_url
|
||||
WORKER_CONCURRENCY=2
|
||||
JOB_MAX_ATTEMPTS=5
|
||||
S3_ADMIN_ACCESS_KEY=CHANGE_ME
|
||||
S3_ADMIN_SECRET_KEY=CHANGE_ME
|
||||
S3_API_ACCESS_KEY=CHANGE_ME
|
||||
S3_API_SECRET_KEY=CHANGE_ME
|
||||
S3_WORKER_ACCESS_KEY=CHANGE_ME
|
||||
S3_WORKER_SECRET_KEY=CHANGE_ME
|
||||
GRAFANA_ADMIN_PASSWORD=CHANGE_ME
|
||||
OTEL_ENABLED=yes
|
||||
SESSION_TTL_SECONDS=3600
|
||||
JOB_TIMEOUT_SECONDS=60
|
||||
STAGING_RETENTION_SECONDS=86400
|
||||
OTEL_SERVICE_NAME=messenger-api
|
||||
# Worker must set a distinct service.name.
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT=https://otel-collector:4318
|
||||
OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
|
||||
OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=lab
|
||||
# TLS and OpenBao: actual paths/ports depend on your implemented trust matrix.
|
||||
PUBLIC_BASE_URL=https://localhost:8443
|
||||
TLS_CA_FILE=/run/secrets/ca.crt
|
||||
TLS_CERT_FILE=/run/secrets/service.crt
|
||||
TLS_KEY_FILE=/run/secrets/service.key
|
||||
BAO_ADDR=https://openbao:8200
|
||||
BAO_CACERT=/run/secrets/bao-ca.crt
|
||||
# No root token here. Bootstrap operator -> short-lived service auth -> scoped token.
|
||||
ARGON2_MEMORY_KIB=19456
|
||||
ARGON2_ITERATIONS=2
|
||||
ARGON2_PARALLELISM=1
|
||||
JOB_MAX_ATTEMPTS=5
|
||||
REDIS_PASSWORD=CHANGE_ME
|
||||
S3_DISPATCHER_ACCESS_KEY=CHANGE_ME
|
||||
S3_DISPATCHER_SECRET_KEY=CHANGE_ME
|
||||
|
||||
@@ -30,3 +30,6 @@ coverage/
|
||||
.vscode/
|
||||
# Keep small, sanitized evidence summaries in evidence/ under version control.
|
||||
# Inspect git diff --cached: ignore rules are not a secret scanner.
|
||||
|
||||
# Generated local PKI, operator credentials, AppRole bootstrap and audit output
|
||||
.local/
|
||||
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
FROM python:3.12.16-slim-bookworm
|
||||
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1
|
||||
WORKDIR /srv
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt && groupadd --gid 999 app && useradd -m --uid 999 --gid app app
|
||||
COPY app ./app
|
||||
COPY db ./db
|
||||
USER app
|
||||
EXPOSE 8080
|
||||
CMD ["python", "-m", "app"]
|
||||
@@ -1,10 +1,10 @@
|
||||
PYTHON ?= python3
|
||||
PYTHON ?= python
|
||||
BASE_URL ?= https://localhost:8443
|
||||
CA_FILE ?=
|
||||
ACTION_SCRIPT ?=
|
||||
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
||||
|
||||
.PHONY: help check validate test load test-persistence test-failover test-security
|
||||
.PHONY: help check validate test load test-persistence test-failover test-security test-security-offline test-mtls
|
||||
|
||||
help:
|
||||
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
|
||||
@@ -31,3 +31,9 @@ test-failover:
|
||||
|
||||
test-security:
|
||||
$(PYTHON) tests/security.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
test-security-offline:
|
||||
$(PYTHON) tests/security_unit.py
|
||||
|
||||
test-mtls:
|
||||
docker compose --profile audit run --rm tls-audit
|
||||
|
||||
@@ -1,37 +1,184 @@
|
||||
# Отчёт — лабораторная 7
|
||||
# Отчёт — лабораторная работа № 7. Безопасность, mTLS и OpenBao
|
||||
|
||||
- Автор, группа: TODO
|
||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
||||
- Commit/PR: TODO после публикации
|
||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
||||
- Автор: Авзалов Артур
|
||||
- Группа: БПИ2301
|
||||
- Целевая оценка: 4 (трек на 5 не заявлен)
|
||||
- Commit/PR: указать после публикации
|
||||
- Дата проверок: 26.11.2026
|
||||
|
||||
## Запуск из чистого clone
|
||||
**База решения:** рабочая реализация ЛР6 (FastAPI x2, HAProxy, PostgreSQL, Redis, SeaweedFS, RabbitMQ, dispatcher + worker + outbox, OTel/Prometheus/Loki/Tempo/Grafana). Изменения исходного контракта API/публичных тестов не производились. **Библиотеки, инструменты и помощь ИИ:** Python, cryptography, HAProxy, OpenBao/AppRole, OpenTelemetry, Docker Compose. ChatGPT использовался при подготовке кода и документации. Приведённые результаты относятся к прогонам студента; исходные обезличенные результаты следует приложить в `evidence/`. Источники приведены в конце отчёта.
|
||||
|
||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
||||
## 1. Запуск из чистого clone
|
||||
|
||||
## Архитектура и решения
|
||||
Условия: Docker Desktop Linux Containers/Compose v2, Python 3.9+, Docker images из `compose.yaml`, cryptography из `requirements-dev.txt`. `Dockerfile` построен на Python 3.12.16 slim-bookworm (Debian 12.15); пользователь приложения UID/GID 999. Версии HAProxy 3.1.7-alpine, OpenBao 2.6.4, PostgreSQL 16.10, Redis 7.4.5, RabbitMQ 4.1.8, SeaweedFS 4.53, OTel Collector 0.123.0, Prometheus 3.2.1, Loki 3.4.2, Tempo 2.7.2, Grafana 11.6.0. Локальное время для ручных сертификатов — время оператора. Параметры аппаратного обеспечения и точные версии Docker Desktop/Windows в журнале прогонов не зафиксированы.
|
||||
|
||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab6, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
||||
Подробный [SECURITY_RUNBOOK.md](SECURITY_RUNBOOK.md). В PowerShell:
|
||||
|
||||
## Доказательства критериев
|
||||
```powershell
|
||||
python -m pip install -r requirements-dev.txt
|
||||
python scripts/bootstrap_env.py
|
||||
python scripts/bootstrap_pki.py
|
||||
New-Item -ItemType Directory -Force .local\operator | Out-Null
|
||||
docker compose --env-file .env config --quiet
|
||||
docker compose up -d openbao
|
||||
docker compose exec -T openbao bao operator init -key-shares=1 -key-threshold=1 -format=json | Set-Content -Path .local\operator\init.json -Encoding ascii
|
||||
docker compose exec openbao bao operator unseal
|
||||
docker compose --profile bootstrap run --rm --build bao-bootstrap
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||
| --- | --- | --- | --- |
|
||||
| Публичный smoke | make test | TODO | TODO |
|
||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
||||
Корневые/операторские ключи в `.local/operator`, CA key в `.local/pki`, service AppRole credentials в изолированных Docker volumes `bao_api_auth`, `bao_worker_auth`, `bao_dispatcher_auth`, рабочие operator secrets в `.env` — Docker volumes хранятся вне репозитория, файлы `.env` и каталог `.local/` должны быть исключены из Git. Перед публикацией проверить правила исключения (`git check-ignore .env .local/operator/init.json .local/pki/ca.key`) и отсутствие отслеживаемых секретов (`git ls-files -- .env .local/`). `operator init` выполняется ОДИН РАЗ при чистом томе. Рестарт OpenBao — ручной unseal сохранённым операторским ключом, не новый init. `docker compose down` сохраняет данные, `docker compose down -v` **удаляет** тома.
|
||||
|
||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
||||
После запуска дождаться готовности API через доверенный HTTPS и выполнить проверки. В PowerShell (эквивалент целей `make check`, `make test` и `make test-security` из skeleton):
|
||||
|
||||
## Эксперименты и отказы
|
||||
```powershell
|
||||
python scripts/check_contract.py
|
||||
python tests/smoke.py --base-url https://localhost:8443 --ca-file .local/pki/ca.crt
|
||||
python tests/security.py --base-url https://localhost:8443 --ca-file .local/pki/ca.crt
|
||||
```
|
||||
|
||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
||||
При наличии `make` и `python3` в PATH те же проверки можно выполнить через `make check`, `make test CA_FILE=.local/pki/ca.crt` и `make test-security CA_FILE=.local/pki/ca.crt`. Smoke проверяет готовность в начале сценария; если стенд ещё запускается, повторить после готовности сервисов.
|
||||
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||
| --- | --- | --- | --- |
|
||||
| TODO | TODO | TODO | TODO |
|
||||
Остановка без удаления учебных данных: `docker compose down`. Намеренное удаление данных: `docker compose down -v` (после этого для нового OpenBao storage требуется новый init; локальные файлы оператора остаются на диске).
|
||||
|
||||
## Ограничения и следующие шаги
|
||||
### Архитектура и границы доверия
|
||||
|
||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
||||
```text
|
||||
CLIENT (HTTPS:8443 CA verify)
|
||||
↓
|
||||
LB HAProxy -- mTLS (client SAN lab7-lb / server verify SAN api*-tls) --> API1/2 TLS sidecar
|
||||
└--> FastAPI 127.0.0.1:8080, same network namespace
|
||||
API1/2 -- native TLS SCRAM / HTTPS S3 / rediss --> PostgreSQL / SeaweedFS / Redis
|
||||
dispatcher / worker -- mTLS --> Broker-GW
|
||||
API / worker / dispatcher -- mTLS --> OTel-GW
|
||||
API / worker / dispatcher -- AppRole TLS --> OpenBao persistent file storage
|
||||
API commit (attachment + job + outbox) → dispatcher (RabbitMQ) → worker (S3 variants)
|
||||
OTel Collector -- mTLS --> Loki and Tempo; Prometheus scrapes metrics through HTTPS
|
||||
Grafana -- CA-verified HTTPS datasource --> Prometheus/Loki/Tempo; UI TLS localhost:3443
|
||||
```
|
||||
|
||||
В рамках лабораторного single-host Docker Compose PostgreSQL/S3/Rabbit/telemetry остаются одноэкземплярными и не гарантируют HA при потере хоста. Между TLS gateway и backend остается *внутренний* plaintext hop в сети с `internal: true`; эти сети не доступны извне. `api*-tls` — отдельный случай: namespace полностью общий с конкретной API, FastAPI слушает лишь loopback. `API :8080` нельзя достать из общей сети, только через gateway, проверяющий LB client cert.
|
||||
|
||||
## 2. Архитектурные решения и перенос из ЛР6
|
||||
|
||||
| Область | Перенос и новая защита |
|
||||
| --- | --- |
|
||||
| Бизнес-API и durable pipeline | Публичный OpenAPI без изменений; PostgreSQL transaction + outbox; Rabbit durable queue, publisher confirms, worker ack/lease/retry, images S3 |
|
||||
| Пользовательская auth | Salted Argon2id `m=19456 KiB (19 MiB), t=2, p=1` (см. `app/auth.py`); session 32 random bytes, Redis ключ `SHA256(token)`, TTL, logout, shared atomic 8 логинов /60s на username, 429+Retry-After, rehash-if-needed при успешном входе |
|
||||
| Клиент→LB | HTTPS 127.0.0.1:8443, локальный CA и SAN, никакого отключения проверки TLS |
|
||||
| LB→API | Mandatory mTLS на двух репликах, allowlist CA + CN + SAN + CRL, private HTTP loopback only |
|
||||
| DB/Redis/S3 | Native PG SSL verify-full + per-service DB grants; Redis TLS sidecar password; SeaweedFS HTTPS sidecar и bucket identities с отдельными паролями; auto-operator policy bootstrap |
|
||||
| Broker/OTel | Мандатный mTLS gateway + раздельные cert identities API/worker/dispatcher, RabbitMQ producer/consumer ACL |
|
||||
| Telemetry backend | OTLP Collector→Loki/Tempo mTLS с `messenger-collector` cert; Prometheus pull through CA-verified TLS; Grafana CA-verified HTTPS data sources |
|
||||
| Secrets | OpenBao non-dev with named persistent file storage, AppRole scoped `kv/data/<role>` с operator-managed SecretID, roleId, ограниченными токенами; app fail closed при unavailable/sealed Bao startup |
|
||||
| Docker | Нет privileged/socket/host network, `read_only`, no-new-privileges/cap_drop, tmpfs app and proxies, CPU/RAM/PID limits; stateful containers с выделенными named volumes |
|
||||
| Ротация | Один leaf LB+CRL в `scripts/rotate_leaf.py`, один worker S3 secret в `scripts/rotate_s3_secret.py` + reissue KV + restart services; свежие отрицательные TLS/credential probes |
|
||||
|
||||
PostgreSQL является источником истины для сообщений, метаданных вложений и outbox; содержимое файлов хранится в S3, сессии — в Redis. Транзакционная граница создания задания включает запись метаданных и outbox в PostgreSQL; доставка в RabbitMQ и обработка worker выполняются асинхронно.
|
||||
|
||||
### Аргументы для защиты
|
||||
|
||||
**Шифрование vs identity:** TLS проверяет CA + SAN сервера, mTLS дополнительно client certificate, а ACL в HAProxy сравнивает разрешённый CN/SAN: доверие к CA не означает доверия *любому* клиенту этого CA. **Защита от обхода:** HTTP FastAPI привязан к loopback внутри разделённого с TLS sidecar network namespace. **Первый секрет Bao:** ручной `init/unseal` оператора; root token только one-shot job; AppRole role/secret IDs как короткоживущие bootstrap credentials; policy ограничивает чтение. **При sealed Bao:** работающие сервисы продолжают использовать загруженные секреты, запуск нового fail-closed. **Проверка внешнего HTTPS:** клиентский `--ca-file`, не `--insecure`.
|
||||
|
||||
## 3. Результаты проверок и доказательства
|
||||
|
||||
Статусы отражают фактически описанные прогоны, а не автоматическое присвоение оценки. Где отдельный файл доказательства не указан, результат зафиксирован в данном отчёте; сырой вывод нужно приложить отдельно. Тесты, выполненные до обновления зависимостей, не считаются повторно выполненными на финальной сборке.
|
||||
|
||||
| Критерий | Команда | Ожидание | Статус | Файл доказательства / статус артефакта |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| Offline структура контракта | `python scripts/check_contract.py` | PASS | **PASS в сборочной среде**, см. `evidence/offline_validation.md` | `evidence/offline_validation.md` |
|
||||
| Offline security asserts | `python tests/security_unit.py` | PASS | **PASS в сборочной среде**, см. evidence | `evidence/offline_validation.md` |
|
||||
| Синтаксис Python | `python -m compileall -q app scripts tests` | exit 0 | **PASS в сборочной среде** | Сырой вывод не указан |
|
||||
| Docker config | `docker compose config --quiet` | exit 0 | **Стенд успешно развёрнут**; отдельный вывод config --quiet не приложен | Отдельный вывод не приложен |
|
||||
| HTTPS CA + SAN и отрицательный TLS | `python tests/security.py --base-url https://localhost:8443 --ca-file .local/pki/ca.crt` | Правильный CA → 200, пустой trust store → ошибка верификации | **PASS** до обновления зависимостей; финальный smoke с CA также PASS | Сырой вывод не указан |
|
||||
| Публичная совместимость Lab6 | `python tests/smoke.py --base-url https://localhost:8443 --ca-file .local/pki/ca.crt` | Auth, sessions, messages, attachments/worker ready | **PASS** на финальной версии | Сырой вывод не указан |
|
||||
| ACL и логин | `python tests/attachments_negative.py ...`, `python tests/security_live.py ...` | Чужая metadata 404, logout 401, 429 + Retry-After | **PASS** на финальной версии | Сырой вывод не указан |
|
||||
| Внутренний TLS identity на API обеих реплик, broker, OTLP | `docker compose --profile audit run --rm tls-audit` | no cert / foreign CA / trusted rogue denied, разрешённый accepted | **PASS**: 25 проверок на финальной версии (включая metrics-Loki и wrong SAN) | Сырой вывод не указан |
|
||||
| OpenBao scopes, чужой KV, чужой policy | `docker compose --profile audit run --rm bao-policy-audit` | Сам себе 200, чужой KV + policy write 403 | **PASS** до обновления зависимостей | Сырой вывод не указан |
|
||||
| Отзыв LB client cert | `python scripts/rotate_leaf.py` + restarts + tls-audit с previous | Старый serial denied, новый accepted | **PASS**: обе API отклонили старый сертификат, новый принят; smoke PASS | Сырой вывод не указан |
|
||||
| Отзыв рабочего S3 secret | `rotate_s3_secret.py worker` + re-bootstrap, restart + `s3-rotation-audit` | Старый 403, новый accepted | **PASS**: новый принят, старый отклонён; smoke PASS | Сырой вывод не указан |
|
||||
| Per-image scan triage | `trivy fs ...`; `trivy image ...` | Отчёт CVE + достижимость + решение | **Сканирование приложения выполнено**; остаточные риски см. раздел 6; прочие образы не сканировались | Четыре отчёта Trivy, см. раздел 6 |
|
||||
| Persistence + failover | `tests/resilience.py` with hooks or manual `stop api1` → smoke → restore | Данные и client flow сохраняются, API2 отвечает | **Ручное переключение на API2 наблюдалось** при повторе через 15 с; API2 HTTP 200 и smoke PASS. Полная persistence и отказ API2 отдельно не подтверждены | Сценарий описан в разделе 4; сырой вывод не указан |
|
||||
| Metrics/log/traces и отсутствие secret leaks | Grafana `https://localhost:3443` + grep sampled telemetry | При поиске нет test password/token/secret strings; без `chat_id` metric labels | **Частично подтверждено**: OTLP unit PASS, Grafana metrics видны; Loki/Tempo доступны по наблюдению оператора; контрольный поиск утечек требует подтверждения | Наблюдения в разделе 4; проверка утечек неполная |
|
||||
|
||||
Дополнительные проверки финального образа: `tests/idempotency_parallel.py` — PASS (две реплики, один результат записи, replay 201, конфликт 409); `tests/telemetry_unit.py` — PASS (реальный OTLP protobuf, родительские связи, histogram buckets, отсутствие синтетических маркеров имени и содержимого файла). `pip check` — No broken requirements found после обновления пакетов. Тесты до обновления зависимостей отмечены отдельно: они не заменяют полный повтор на окончательной версии. Сценарии из ЛР6 (faulted worker/broker/outbox) и полная проверка persistence не повторены. Сырые результаты следует сохранить в `evidence/`, исключив секреты. Имена файлов, не указанные в журнале прогонов, не назначены в отчёте как существующие артефакты.
|
||||
|
||||
### Соответствие критериям README
|
||||
|
||||
| Уровень / критерий | Реализация и проверка | Ограничения подтверждения |
|
||||
| --- | --- | --- |
|
||||
| 3 — HTTPS, сохранение прежнего API, Argon2id | HTTPS smoke, замер Argon2id (разделы 3–4) | Полная регрессия предыдущих лабораторных и persistence не повторены; отдельный wrong-hostname тест внешнего ingress не указан |
|
||||
| 3 — обязательное mTLS LB → обе API | TLS audit, отказ неверным identities, loopback API | Проверки описаны в разделе 3 |
|
||||
| 3 — TLS зависимостей и минимальные права | Раздельные credentials/roles, TLS sidecars, расширенный TLS audit | Полное покрытие всех каналов, bucket-prefix ACL и отдельная identity Grafana для backends не доказаны |
|
||||
| 3 — OpenBao persistent, scoped service auth | AppRole, allow/deny audit, sealed/restart сценарий | Policy audit до обновления зависимостей; полная проверка persistence всех хранилищ не выполнена |
|
||||
| 3 — контейнеры, порты, секреты | Non-root, лимиты, локальный ingress, операторские ключи вне Git | Отдельный аудит отсутствия секретов в Git, образах и всех сигналах telemetry не подтверждён |
|
||||
| 3 — ограничение входа/размера, ACL, logout/expiry | 429 и Retry-After, отрицательные тесты вложений, logout, внешний TLS | Live expiry, весь набор ACL trust matrix и отдельный oversized Content-Length не подтверждены |
|
||||
| 4 — mTLS broker и Collector | Раздельные identities; отказ доверенному, но запрещённому сертификату | TLS audit: 25 проверок; это не подтверждает каждую строку trust matrix |
|
||||
| 4 — rehash, login DoS, credentials в telemetry | Rehash предусмотрен, общий лимит, 30 итераций Argon2id | Live rehash и конкурентный login DoS не проверены; контроль утечек не завершён |
|
||||
| 4 — ротация secret и leaf, lifecycle | Отзыв LB leaf и worker S3 credential, sealed Bao, operator bootstrap | Автоматическое renewal отсутствует; реальное истечение credentials не воспроизведено; отдельная фиксация неизменности image ID при ротации не приведена |
|
||||
| 4 — hardening и scan triage | read_only, no-new-privileges, cap_drop, tmpfs, Trivy до/после | Сканирование только образа приложения; остаточные CVE ОС не скрыты |
|
||||
| 4 — threat model, ограничение worker, TLS/ACL/telemetry | Модель угроз в `security/THREAT_MODEL.md`, worker limits, TLS/ACL/OTLP tests | Число и покрытие строк threat model определяются по самому файлу; полный TLS-аудит и поиск утечек не подтверждены |
|
||||
|
||||
Целевая оценка — 4. Незакрытые доказательства указаны явно; полное выполнение всех критериев уровня 4 по имеющимся результатам не утверждается.
|
||||
|
||||
## 4. Эксперименты, сценарии отказов и измерения
|
||||
|
||||
| Воздействие | Ожидание | Реальное наблюдение после прогона |
|
||||
| --- | --- | --- |
|
||||
| Stop `api1-tls` и `api1` | LB обслуживает через API2, cert verify остаётся enabled | Первый smoke: timeout. При повторе после 15 с `/health/ready` HTTP 200, `x-instance-id: api2`; smoke PASS; API1 восстановлена. Точное время переключения не измерено; соответствие порогу ≤10 с публичного failover-теста и сохранность подтверждённых записей во время отказа не доказаны. |
|
||||
| Перезапуск OpenBao, не выполнять unseal | Старые сервисы остаются с cached secrets; новые startup не READY | Initialized=true, Sealed=true; smoke PASS; новый процесс загрузки secrets HTTP 503; после unseal Sealed=false и Secrets loaded. |
|
||||
| Worker pause/restart | Очередь / PG outbox сохраняются; lease recovery / повтор не дублирует variant metadata | При ротации S3 пересоздание было прервано, возник конфликт имени Docker; контейнер восстановлен и smoke PASS. Отдельный тест отказа worker с задачей в полёте не выполнен. |
|
||||
| Rotate LB leaf CRL | Старый cert rejected, новый accepted на новых соединениях | PASS: api1/revoked-lb и api2/revoked-lb rejected; новый LB accepted; smoke PASS. |
|
||||
| Rotate worker S3 secret | Старый ключ rejected, новый accepted, upload→ready после restart | PASS: new worker credential accepted, revoked old credential denied; smoke PASS. |
|
||||
| Overlong Content-Length + bad login | HTTP 413 и 429; sane Retry-After | Негативные проверки размера вложения PASS; общий login limiter HTTP 429 + Retry-After PASS. Отдельная проверка oversized Content-Length не подтверждена. |
|
||||
|
||||
### Argon2id и бюджет логина
|
||||
|
||||
26.11.2026 внутри API-контейнера выполнены 30 последовательных итераций hash/verify синтетического пароля (`m=19456 KiB`, `t=2`, `p=1`). Медиана hash 21,78 мс, verify 21,62 мс, максимум verify 54,12 мс. Лимит 8 попыток/60 с на username общий для реплик; при 8 проверках медианная суммарная длительность хеширования составляет примерно 173 мс, без накладных расходов HTTP/Redis/БД. Это ориентир, не гарантия CPU budget при конкурентной атаке: перебор разных username обходит ограничение на один username. Параллельный login benchmark и live rehash/expiry отдельно не подтверждены. Замер проведён до обновления базового образа. Параметры хеша не изменялись.
|
||||
|
||||
### Наблюдаемость
|
||||
|
||||
На скриншоте Grafana после финальной регрессии: throughput до ~1,37 req/s, 5xx в показанном диапазоне 0, p95 до ~240 мс, p99 до ~440 мс, job outcome=ready. Это визуальные оценки графика, не нагрузочный benchmark. Loki и Tempo содержат данные по наблюдению оператора. По фильтру тестовых строк `incorrect-password|completely_invalid` получено `No logs volume available`; необходимо подтвердить обычные записи за тот же интервал и отсутствие совпадений, прежде чем считать выборочную проверку утечек завершённой. Unit-тест проверил отсутствие синтетических S3 filename/content маркеров в OTLP, но не гарантирует отсутствие всех секретов. Точная конфигурация CPU/RAM хоста и версии Docker/Windows не записаны.
|
||||
|
||||
## 5. Hardening, жизненный цикл и ограничения
|
||||
|
||||
На внешнем хосте опубликованы только `127.0.0.1:8443` и `127.0.0.1:3443`; ни Postgres/S3/Rabbit/OpenBao/Prometheus/Loki/Tempo не имеют host port mappings. State services с persistent volumes по смыслу не всегда `read_only`; operator jobs `s3-policy`, `tls-prepare`, `db-roles` имеют исключения для записи конфигов и ролей. Worker имеет 768MiB, 1 CPU, `pids_limit=96`, image validation `MAX_PIXELS=40_000_000`, input 10MiB и timeout 60s. API имеет 384MiB и 0.75 CPU. На Docker Desktop ограничения относительны host capacity.
|
||||
|
||||
**Остаточные риски:**
|
||||
|
||||
1. У SeaweedFS identity ограничены *bucket actions*, но нет granular bucket-prefix isolation между API/worker/dispatcher; значит **полный критерий prefix ACL** не доказан. Скомпрометированный worker потенциально читает другие ключи в том же бакете. Защита доступа конечного пользователя реализована на уровне FastAPI+Postgres.
|
||||
2. Grafana↔backends использует проверяемый TLS и Docker internal network, без индивидуальной backend read-only auth. Collector→Loki/Tempo выделен отдельный write-only mTLS ingress; backend endpoints остаются в доверенной сети. Для hostile Docker-hoster нужна более сильная сегментация.
|
||||
3. OpenBao на одном томе не HA; `unseal` вручную после рестарта. AppRole SecretID 24 часа без автоматической переэмиссии/renewal; после истечения SecretID для нового запуска нужна операторская регенерация. `token_ttl=10m` действует на процесс аутентификации, приложение хранит уже полученные секреты в памяти.
|
||||
4. Локальная тестовая CA + leaf keys у оператора, без HSM/автоматической CA rotation. Локальный TLS браузера требует ручного доверия к CA; не пропускайте validation ошибки.
|
||||
5. TLS proxy↔backend допускает доверенный plaintext hop в локальной internal Docker network. От компрометации хоста/sidecar это не защищает.
|
||||
6. Временное окно отказа при restart S3, worker и sidecars, мгновенной бесшовной ротации нет. Отзыв проверяется по новому соединению.
|
||||
7. Не заявляется полная проверка всех путей TLS, всех образов, реального expiry, rehash, persistence и конкурентного login DoS. Измерения и аудиты ограничены указанными сценариями. См. разделы 3–4 и 6.
|
||||
|
||||
## 6. Сканирование зависимостей и образа: анализ применимости
|
||||
|
||||
Trivy 0.76.2, 26.11.2026, `--scanners vuln --severity HIGH,CRITICAL`, одна локальная база уязвимостей, повторные прогоны `--skip-db-update`. Объект image scan — `mtusi-lab7-app:local`, экспортированный `docker save`. Это не аудит всех инфраструктурных образов, ОС хоста или секретов. Отчёты: `evidence/trivy-dependencies-before.txt`, `evidence/trivy-dependencies.txt`, `evidence/trivy-image-before.txt`, `evidence/trivy-image-final.txt`.
|
||||
|
||||
| Сканирование | До | После |
|
||||
| --- | --- | --- |
|
||||
| requirements.txt, до/после Pillow | 41 (36 HIGH, 5 CRITICAL) | 0 |
|
||||
| Python-пакеты в образе, после Pillow / финальный | 3 HIGH (Starlette) | 0 |
|
||||
| Debian-пакеты, первый image scan / финальный | 152 (143 HIGH, 9 CRITICAL) | 102 (100 HIGH, 2 CRITICAL) |
|
||||
|
||||
Pillow 11.3.0 → 13.0.0 (включая риски обработки недоверенных изображений); FastAPI 0.115.12 → 0.165.0 и Starlette 0.46.2 → 1.10.0 (Range DoS, StaticFiles и form parsing); OTel API/SDK/exporter 1.42.1 → 1.44.0 из-за зависимости FastAPI; Python 3.12.10 → 3.12.16, Debian 12.11 → 12.15. После обновления FastAPI возникла регрессия в middleware (`_IncludedRouter` без `.path`). Поиск шаблонов маршрутов перенесён на два плоских router, встроенная telemetry FastAPI отключена в пользу собственной. Smoke, негативные вложения, security_live, idempotency_parallel, mTLS и OTLP unit на исправленной версии прошли. Итоговый image scan повторён после исправления middleware.
|
||||
|
||||
102 записи относятся к 32 различным CVE ID в отчёте; одинаковые CVE могут относиться к нескольким бинарным пакетам. Ни для одной оставшейся записи сканер не указал исправленную версию в Debian 12.15. Это не доказательство отсутствия исправлений в других дистрибутивах.
|
||||
|
||||
| Группа | Применимость и решение |
|
||||
| --- | --- |
|
||||
| SQLite, CRITICAL CVE-2025-7458 и HIGH FTS5/session | Основное хранилище PostgreSQL, не SQLite; приложение не предоставляет загрузку SQLite БД или SQL к SQLite. Прямой путь не установлен; зависимость остаётся, проверить транзитивные вызовы и обновлять базовый образ. |
|
||||
| zlib, CRITICAL CVE-2023-45853 | Trivy `will_not_fix`, уязвимая функция `zipOpenNewFileInZip4_6` относится к MiniZip, а не всему API zlib. Прямой вызов не установлен; наличие компонента/достижимость отдельно не доказаны. Не скрывать finding. |
|
||||
| zlib HIGH CVE-2026-85091 и libzstd | Возможен косвенный путь через сжатие/декодирование данных; остаточный риск, не объявлять неприменимым. Лимиты worker снижают последствия DoS, не устраняют memory corruption. |
|
||||
| Kerberos | KDC/kadmind не используются как сервисы приложения; PG использует SCRAM, mTLS — сертификаты. Прямой путь для перечисленных серверных CVE не установлен; проверить используемые транзитивные библиотеки. |
|
||||
| util-linux, libacl, PAM, systemd/udev | Нет пользовательского API mount, PAM/login или администрирования systemd; non-root, cap_drop, no-new-privileges, read-only ограничивают последствия. Остаточный риск локальной эскалации сохраняется. |
|
||||
| gzip, Perl Archive-Tar, ncurses | Не предоставляется API распаковки LZH/TAR или управления терминалом; проверка всех транзитивных путей не выполнена. Остаточный риск, следить за патчами. |
|
||||
|
||||
Решение для учебного single-host стенда: сохранить видимый отчёт с HIGH/CRITICAL, не использовать исключения сканера для искусственного нуля, обновлять базовый образ при появлении исправлений. Для production требуется отдельная проверка достижимости уязвимых функций, сканирование всех образов и согласование остаточного риска. Ноль обнаруженных HIGH/CRITICAL Python не означает ноль уязвимостей вообще.
|
||||
|
||||
## 7. Источники и документация
|
||||
|
||||
**Источники/справки:** [OWASP Password Storage](https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html), [OpenBao AppRole](https://openbao.org/docs/auth/approle/), [OpenBao policies](https://openbao.org/docs/concepts/policies/), [HAProxy SSL client cert ACL](https://www.haproxy.com/documentation/). Подробная модель угроз — [security/THREAT_MODEL.md](security/THREAT_MODEL.md), схема identity и отрицательные проверки — [contracts/trust-matrix.md](contracts/trust-matrix.md).
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
# ЛР7: операционный runbook (PowerShell + Docker Desktop)
|
||||
|
||||
> Цель — оценка **4**, унаследованная ЛР6 + добавленная модель доверия. **Не публикуйте** `.env`, `.local/`, ключи/токены, вывод команды `operator init`. Ни один тест нельзя запускать с `verify=False` / `-k`. В проекте нет готовых доверенных секретов: каждый создаётся только у оператора.
|
||||
>
|
||||
> Первый запуск: требуется Docker Desktop (Linux containers + Compose v2), Python 3.9+ и сетевой доступ Docker к pinned images. На машине автора архива Docker недоступен: сценарий ниже требуется подтвердить на стенде перед PR.
|
||||
|
||||
## 1. Чистый bootstrap (в PowerShell из корня репозитория)
|
||||
|
||||
```powershell
|
||||
python -m pip install -r requirements-dev.txt
|
||||
python scripts/bootstrap_env.py
|
||||
python scripts/bootstrap_pki.py
|
||||
New-Item -ItemType Directory -Force .local\operator | Out-Null
|
||||
docker compose --env-file .env config --quiet
|
||||
# Первый запуск OpenBao не dev и хранит состояние в named Docker volume.
|
||||
docker compose up -d openbao
|
||||
# Создание корневого токена + unseal key: файл ДЛЯ ОПЕРАТОРА; никому не пересылайте.
|
||||
docker compose exec -T openbao bao operator init -key-shares=1 -key-threshold=1 -format=json | Set-Content -Path .local\operator\init.json -Encoding ascii
|
||||
# В интерактивном терминале вводим unseal key из operator/init.json; не передаём ключ аргументом в CLI.
|
||||
docker compose exec openbao bao operator unseal
|
||||
# Отдельный одноразовый job создаёт политики и AppRole credentials в отдельных Docker named volumes, доступных только своей роли.
|
||||
docker compose --profile bootstrap run --rm --build bao-bootstrap
|
||||
# Поднимет зависимости, TLS sidecars, миграцию БД, выдачу DB/Rabbit/S3 identities.
|
||||
docker compose up -d --build
|
||||
```
|
||||
|
||||
При повторном запуске **не запускать `operator init`**! После остановки/рестарта OpenBao обычно снова `sealed`. Проверка: `docker compose exec openbao bao status` (поле Sealed), затем интерактивный `bao operator unseal`. Постоянные тома сохраняются, пока вы не используете `down -v`. При `init` в уже инициализированном хранилище будет ошибка — это ожидаемо.
|
||||
|
||||
Первые минуты контейнеры могут загружать образы и ждать миграцию. Статус: `docker compose ps -a`, не публикуя `docker compose config` с секретами. При сбое смотрите `docker compose logs --tail 60 <имя>`; не отправляйте в PR сырые логи, если они содержат секреты.
|
||||
|
||||
> Важное про Windows: `chmod` не создаёт эквивалент NTFS ACL. AppRole-файлы находятся в Linux Docker named volumes (не в Windows bind mount), а `.local` c операторскими ключами следует хранить в личном каталоге с ограниченными правами. На рабочей системе вместо ручного init — защищённый operator secret store, отдельные CA и автоматический unseal.
|
||||
|
||||
## 2. Обязательные проверки через настоящий HTTPS
|
||||
|
||||
```powershell
|
||||
# CA_FILE — публичный сертификат нашей локальной CA, не ключ. Никакого --insecure.
|
||||
python scripts/check_contract.py
|
||||
python tests/security_unit.py
|
||||
python tests/security.py --base-url https://localhost:8443 --ca-file .local/pki/ca.crt
|
||||
python tests/smoke.py --base-url https://localhost:8443 --ca-file .local/pki/ca.crt
|
||||
python tests/attachments_negative.py --base-url https://localhost:8443 --ca-file .local/pki/ca.crt
|
||||
python tests/idempotency_parallel.py --base-url https://localhost:8443 --ca-file .local/pki/ca.crt
|
||||
python tests/security_live.py --base-url https://localhost:8443 --ca-file .local/pki/ca.crt
|
||||
# Audit в Docker-сети: LB/API1/API2, Broker, OTel; no-cert, foreign CA, wrong trusted SAN, correct identity.
|
||||
docker compose --profile audit run --rm tls-audit
|
||||
docker compose --profile audit run --rm bao-policy-audit
|
||||
# Снаружи только localhost:8443 (HTTPS API) и localhost:3443 (HTTPS Grafana).
|
||||
docker compose ps
|
||||
```
|
||||
|
||||
Grafana: `https://localhost:3443`, логин `admin`, пароль в `.env` (не вставлять в отчёт), браузер предупреждает о локальной CA, пока CA не добавлена в trust store. Выберите доверие к **конкретной локальной CA**, не отключайте проверку TLS. Для Python `--ca-file` передаётся явно. При проверке внутреннего mTLS `tls-audit` сама проверяет серверный CA и SAN; запрещённые сертификаты отклоняются.
|
||||
|
||||
Если тесты из предыдущих лабораторных принимают аргументы, как указано в их `--help`, используйте те же `--base-url` и `--ca-file`. Это **фактическая проверка**, а не доказательство из одного `docker compose ps`.
|
||||
|
||||
## 3. Демонстрация OpenBao scoped policies
|
||||
|
||||
Роль API (файлы `role_id`, `secret_id` в `bao_api_auth`) читает только `kv/data/api`; worker — только `kv/data/worker`; dispatcher — только `kv/data/dispatcher`. Root-token находится только в `/operator/init.json` **одноразового** `bao-bootstrap`, его нет в `api*`/`worker`/`dispatcher` containers. Краткоживущий AppRole token: 10 мин (максимум 30 мин), SecretID: 24 ч, выдаётся в выделенном для роли read-only Docker volume. Сервисы выполняют AppRole login и читают KV по HTTPS с hostname/CA-проверкой на старте; если OpenBao недоступен или sealed, **новый запуск fail-closed** без plaintext fallback; уже работающие процессы пользуются загруженными credentials. Роль не получает весь секретный каталог. После 24 часов для нового входа переиздать SecretIDs операторским `bao-bootstrap` и перезапустить нужный сервис.
|
||||
|
||||
Для отрицательной проверки permissions можно использовать одноразовый API-token с ограниченной policy и запросы `GET /v1/kv/data/worker`, `PUT /v1/sys/policies/acl/worker`; ожидаем HTTP 403. **Не сохраняйте session token в лог/PR.** Полноценная автоматизация такого теста добавлена в `tests/bao_policy_audit.py` через одноразовый operator probe.
|
||||
|
||||
## 4. Ротация leaf без пересборки
|
||||
|
||||
```powershell
|
||||
python scripts/rotate_leaf.py
|
||||
# Загрузка нового LB-cert и CRL в HAProxy без пересборки Docker images.
|
||||
docker compose restart api1-tls api2-tls lb
|
||||
# Проверяем соединения заново и отказ по revoked old LB cert.
|
||||
docker compose --profile audit run --rm --volume "./.local/pki/previous/lb-client.crt:/run/audit-pki/old-lb-client.crt:ro" --volume "./.local/pki/previous/lb-client.key:/run/audit-pki/old-lb-client.key:ro" tls-audit
|
||||
python tests/smoke.py --base-url https://localhost:8443 --ca-file .local/pki/ca.crt
|
||||
```
|
||||
|
||||
Почему проверяем **новое** подключение: существующие TLS/HTTP соединения или TLS session resumption могли пройти аутентификацию до отзыва. CA остаётся той же, старый серийный номер заносится в CRL; новые соединения с прежним cert отклоняет mTLS proxy. `rotate_leaf.py` хранит предыдущий cert/key под `.local/pki/previous` только для отрицательной пробы. **Удалите их после проверки**.
|
||||
|
||||
## 5. Ротация рабочего S3 secret без пересборки (worker)
|
||||
|
||||
```powershell
|
||||
python scripts/rotate_s3_secret.py worker
|
||||
# Переиздать значения KV и AppRole SecretID, не трогая root keys в приложениях.
|
||||
docker compose --profile bootstrap run --rm bao-bootstrap
|
||||
# Обновить авторизованные ключи SeaweedFS, а затем перечитать конфиг S3 процессом.
|
||||
docker compose run --rm s3-policy
|
||||
# Без пересборки образов; кратковременный разрыв S3 во время рестарта допустим.
|
||||
docker compose up -d --no-deps --force-recreate s3
|
||||
docker compose up -d --no-deps --force-recreate worker
|
||||
# Положительная проверка нового ключа + отрицательная старого.
|
||||
docker compose --profile audit run --rm s3-rotation-audit
|
||||
python tests/smoke.py --base-url https://localhost:8443 --ca-file .local/pki/ca.crt
|
||||
```
|
||||
|
||||
`old-worker-s3-secret.txt` остаётся только в `.local/operator`, используется **исключительно** для проверки отзыва и удаляется оператором. В момент смены есть короткое окно отказов S3/worker; данные PG и задачи RabbitMQ переживают перезапуск. Факт восстановления фиксируется повторным smoke и READY всех задач. Полноценной автоматической zero-downtime ротации в учебной реализации нет.
|
||||
|
||||
## 6. Отказы, проверка сети, лимитов, эксплуатация
|
||||
|
||||
```powershell
|
||||
# Реплика API1 потеряна — LB перенаправляет трафик на API2.
|
||||
docker compose stop api1-tls api1
|
||||
python tests/smoke.py --base-url https://localhost:8443 --ca-file .local/pki/ca.crt
|
||||
docker compose up -d api1 api1-tls
|
||||
|
||||
# Сохраняем тома, прекращаем работу без удаления данных.
|
||||
docker compose down
|
||||
# ВАЖНО: down -v безвозвратно удаляет учебные данные Postgres/S3/Bao и не подходит для обычной остановки.
|
||||
```
|
||||
|
||||
Принципы изоляции: FastAPI слушает только `127.0.0.1:8080` в namespace API; `api*-tls` разделяют тот же namespace и публикуют 8443 только внутри Docker. LB на хосте `127.0.0.1:8443`, Grafana на `127.0.0.1:3443`; Redis/PG/S3/Rabbit/OTel/metrics/Bao не имеют host-port mappings. Backend/plaintext существуют только между gateway и зависимостью на отдельном `internal: true` Docker network; это не полноценный шифрованный hop от процесса зависимости до proxy, так что скомпрометированный сосед внутри private network всё ещё риск.
|
||||
|
||||
Worker: `cpus=1.0`, `mem_limit=768m`, `pids_limit=96`, `JOB_TIMEOUT_SECONDS=60`, обработка изолированным subprocess и cgroup; защиту от decompression bombs обеспечивает максимальное число pixels и размер изображения. Секреты не передаются HTTP API.
|
||||
|
||||
## 7. Scan и документирование доказательств
|
||||
|
||||
```powershell
|
||||
# При установленном trivy (запуск в Git Bash/WSL для .sh):
|
||||
sh scripts/scan.sh
|
||||
# Можно выполнить и напрямую в PowerShell:
|
||||
trivy fs --scanners vuln --severity HIGH,CRITICAL .
|
||||
trivy image --scanners vuln --severity HIGH,CRITICAL mtusi-lab7-app:local
|
||||
```
|
||||
|
||||
Перенесите в `REPORT.md`: конкретные test commands, PASS/FAIL, время и Windows/Docker versions, CPU/RAM, что проверено лично, что нет, и scan triage — компонент/CVE, достижимость пути, fixed-version и решение. Нет отсканированного результата — пишите «не выполнено», не «уязвимостей нет». Не копируйте `.env`, `.local`, root/role/secret IDs, содержимое S3 и запросы с Authorization в PR.
|
||||
@@ -0,0 +1,33 @@
|
||||
# ЛР7 — быстрый старт (Windows PowerShell)
|
||||
|
||||
Цель: **кандидат на 4**, построенный поверх ЛР6. Перед сдачей нужно прогнать живые тесты. Подробности: [SECURITY_RUNBOOK.md](SECURITY_RUNBOOK.md).
|
||||
|
||||
**Скопируйте эти команды из корня папки проекта:**
|
||||
|
||||
```powershell
|
||||
python -m pip install -r requirements-dev.txt
|
||||
python scripts/bootstrap_env.py
|
||||
python scripts/bootstrap_pki.py
|
||||
New-Item -ItemType Directory -Force .local\operator | Out-Null
|
||||
docker compose config --quiet
|
||||
docker compose up -d openbao
|
||||
docker compose exec -T openbao bao operator init -key-shares=1 -key-threshold=1 -format=json | Set-Content -Path .local\operator\init.json -Encoding ascii
|
||||
# Введите unseal key из .local/operator/init.json, когда CLI его запросит.
|
||||
docker compose exec openbao bao operator unseal
|
||||
docker compose --profile bootstrap run --rm --build bao-bootstrap
|
||||
# AppRole credentials хранятся в отдельных Docker named volumes, не в Windows bind mount.
|
||||
docker compose up -d --build
|
||||
docker compose ps -a
|
||||
python tests/security.py --base-url https://localhost:8443 --ca-file .local/pki/ca.crt
|
||||
python tests/smoke.py --base-url https://localhost:8443 --ca-file .local/pki/ca.crt
|
||||
python tests/attachments_negative.py --base-url https://localhost:8443 --ca-file .local/pki/ca.crt
|
||||
python tests/security_live.py --base-url https://localhost:8443 --ca-file .local/pki/ca.crt
|
||||
docker compose --profile audit run --rm tls-audit
|
||||
docker compose --profile audit run --rm bao-policy-audit
|
||||
```
|
||||
|
||||
**Важно:** `operator init` только при первом запуске пустого тома! Если уже создавали `.env` и CA — повторно не запускайте генераторы. После `docker compose down` тома сохранены. Новый `docker compose up -d` после рестарта OpenBao требует `bao operator unseal` (не `init`). Не отправляйте никому `.env`, `.local` и init.json.
|
||||
|
||||
**Что сдавать:** этот исходный код + `REPORT.md`, `security/THREAT_MODEL.md`, `contracts/trust-matrix.md`, `SECURITY_RUNBOOK.md`; в отчёте замените «ТРЕБУЕТ ЗАПУСКА» реальными PASS/FAIL и приложите безопасный вывод тестов. Отдельные критерии на 4: ротация LB leaf и S3 worker secret, scan — команды в runbook.
|
||||
|
||||
**Что показать на защите:** `https://localhost:8443` + проверка CA, оба API через HAProxy/mTLS, неправильный cert/роль не проходит, OpenBao AppRole scopes, worker/broker/collector mTLS, доступ в Grafana `https://localhost:3443`.
|
||||
@@ -0,0 +1 @@
|
||||
"""Lab 3 messenger API."""
|
||||
@@ -0,0 +1,4 @@
|
||||
import os
|
||||
import uvicorn
|
||||
if __name__ == "__main__":
|
||||
uvicorn.run("app.main:app", host=os.getenv("APP_HOST","0.0.0.0"), port=int(os.getenv("APP_PORT", "8080")), workers=1, access_log=False, timeout_graceful_shutdown=8)
|
||||
+193
@@ -0,0 +1,193 @@
|
||||
"""Messenger HTTP handlers; state lives only in PostgreSQL/Redis."""
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import uuid
|
||||
|
||||
import psycopg
|
||||
from argon2 import PasswordHasher
|
||||
from fastapi import APIRouter, Request
|
||||
|
||||
from .auth import current_user, hasher, login, logout, public_user
|
||||
from .core import APIError, invalid, iso, make_cursor, parse_limit, parse_uuid, read_cursor
|
||||
from .models import CreateChat, CreateMessage, CreateUser
|
||||
from .storage import db
|
||||
|
||||
router = APIRouter()
|
||||
KEY_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$", re.ASCII)
|
||||
|
||||
|
||||
def actor(req: Request) -> dict:
|
||||
return getattr(req.state, "actor", None) or current_user(req)
|
||||
|
||||
|
||||
def chat_detail(conn, chat: dict) -> dict:
|
||||
members = conn.execute("SELECT user_id FROM chat_members WHERE chat_id=%s ORDER BY position", (chat["id"],)).fetchall()
|
||||
return {"id": str(chat["id"]), "title": bytes(chat["title"]).decode("utf-8"), "created_at": iso(chat["created_at"]), "member_ids": [str(x["user_id"]) for x in members]}
|
||||
|
||||
|
||||
def message_detail(conn, row: dict) -> dict:
|
||||
linked = conn.execute("SELECT attachment_id FROM message_attachments WHERE message_id=%s ORDER BY position", (row["id"],)).fetchall()
|
||||
return {"id": str(row["id"]), "chat_id": str(row["chat_id"]), "sender_id": str(row["sender_id"]), "text": bytes(row["text"]).decode("utf-8"), "created_at": iso(row["created_at"]), "attachment_ids": [str(x["attachment_id"]) for x in linked]}
|
||||
|
||||
|
||||
def require_chat(conn, chat_id: str, actor_id: str) -> dict:
|
||||
row = conn.execute("SELECT c.* FROM chats c JOIN chat_members cm ON cm.chat_id=c.id WHERE c.id=%s AND cm.user_id=%s", (chat_id, actor_id)).fetchone()
|
||||
if row is None:
|
||||
raise APIError(404, "not_found", "Object not found")
|
||||
return row
|
||||
|
||||
|
||||
@router.get("/health/live")
|
||||
def live():
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.get("/health/ready")
|
||||
def ready():
|
||||
from .storage import ready as storage_ready
|
||||
if not storage_ready():
|
||||
raise APIError(503, "unavailable", "Service not ready")
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.post("/api/v1/users", status_code=201)
|
||||
def register(body: CreateUser):
|
||||
hashed = hasher.hash(body.password)
|
||||
ident = str(uuid.uuid4())
|
||||
try:
|
||||
with db() as conn:
|
||||
row = conn.execute("INSERT INTO users(id,username,display_name,password_hash) VALUES (%s,%s,%s,%s) RETURNING *", (ident, body.username, body.display_name.encode("utf-8"), hashed)).fetchone()
|
||||
return public_user(row)
|
||||
except psycopg.errors.UniqueViolation:
|
||||
raise APIError(409, "conflict", "Username already exists") from None
|
||||
|
||||
|
||||
@router.post("/api/v1/auth/sessions", status_code=201)
|
||||
def sessions(req: Request):
|
||||
return login(req)
|
||||
|
||||
|
||||
@router.delete("/api/v1/auth/sessions/current", status_code=204)
|
||||
def sessions_delete(req: Request):
|
||||
logout(req)
|
||||
return None
|
||||
|
||||
|
||||
@router.get("/api/v1/users/me")
|
||||
def users_me(req: Request):
|
||||
return actor(req)
|
||||
|
||||
|
||||
@router.post("/api/v1/chats", status_code=201)
|
||||
def chats_create(req: Request, body: CreateChat):
|
||||
ident = actor(req)["id"]
|
||||
if ident not in body.member_ids:
|
||||
raise invalid("Current user must belong to the chat")
|
||||
chat_id = str(uuid.uuid4())
|
||||
try:
|
||||
with db() as conn:
|
||||
with conn.transaction():
|
||||
# Validate all members; FK constraints are the final authority for races.
|
||||
found = conn.execute("SELECT id FROM users WHERE id = ANY(%s::uuid[])", (body.member_ids,)).fetchall()
|
||||
if len(found) != len(body.member_ids):
|
||||
raise invalid("Unknown member")
|
||||
row = conn.execute("INSERT INTO chats(id,title) VALUES (%s,%s) RETURNING *", (chat_id, body.title.encode("utf-8"))).fetchone()
|
||||
for pos, member in enumerate(body.member_ids):
|
||||
conn.execute("INSERT INTO chat_members(chat_id,user_id,position) VALUES (%s,%s,%s)", (chat_id, member, pos))
|
||||
result = chat_detail(conn, row)
|
||||
return result
|
||||
except psycopg.errors.ForeignKeyViolation:
|
||||
raise invalid("Unknown member") from None
|
||||
|
||||
|
||||
@router.get("/api/v1/chats")
|
||||
def chats_list(req: Request, limit: str | None = None, cursor: str | None = None):
|
||||
who = actor(req)["id"]
|
||||
n = parse_limit(limit)
|
||||
mark = read_cursor(cursor, "chats", who)
|
||||
with db() as conn:
|
||||
if mark:
|
||||
existing = conn.execute("SELECT 1 FROM chats c JOIN chat_members cm ON c.id=cm.chat_id WHERE c.id=%s AND c.created_at=%s AND cm.user_id=%s", (mark[1], mark[0], who)).fetchone()
|
||||
if not existing:
|
||||
raise invalid("Invalid cursor")
|
||||
rows = conn.execute("""
|
||||
SELECT c.* FROM chats c JOIN chat_members cm ON cm.chat_id=c.id
|
||||
WHERE cm.user_id=%s AND (%s::timestamptz IS NULL OR (c.created_at,c.id)>(%s::timestamptz,%s::uuid))
|
||||
ORDER BY c.created_at,c.id LIMIT %s
|
||||
""", (who, mark[0] if mark else None, mark[0] if mark else None, mark[1] if mark else None, n+1)).fetchall()
|
||||
items = [chat_detail(conn, row) for row in rows[:n]]
|
||||
more = len(rows) > n
|
||||
last = rows[n-1] if more else None
|
||||
return {"items": items, "next_cursor": make_cursor("chats", who, last["created_at"], str(last["id"])) if last else None}
|
||||
|
||||
|
||||
@router.get("/api/v1/chats/{chat_id}")
|
||||
def chats_get(req: Request, chat_id: str):
|
||||
who = actor(req)["id"]
|
||||
ident = parse_uuid(chat_id)
|
||||
with db() as conn:
|
||||
row = require_chat(conn, ident, who)
|
||||
return chat_detail(conn, row)
|
||||
|
||||
|
||||
@router.post("/api/v1/chats/{chat_id}/messages", status_code=201)
|
||||
def messages_create(req: Request, chat_id: str, body: CreateMessage):
|
||||
who = actor(req)["id"]
|
||||
ident = parse_uuid(chat_id)
|
||||
key = req.headers.get("Idempotency-Key")
|
||||
if not key or not KEY_RE.fullmatch(key):
|
||||
raise invalid("Invalid Idempotency-Key")
|
||||
# Lab3 has only text; canonical JSON avoids unstable formatting/field ordering.
|
||||
fingerprint = hashlib.sha256(json.dumps({"text": body.text, "attachment_ids": body.attachment_ids}, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode("utf-8")).hexdigest()
|
||||
lock_scope = f"{who}:POST:/api/v1/chats/{ident}/messages:{key}"
|
||||
with db() as conn:
|
||||
with conn.transaction():
|
||||
require_chat(conn, ident, who)
|
||||
# Transaction-scoped advisory lock is GLOBAL across API replicas.
|
||||
conn.execute("SELECT pg_advisory_xact_lock(hashtextextended(%s, 0))", (lock_scope,))
|
||||
previous = conn.execute("""
|
||||
SELECT idem.body_sha256, m.* FROM message_idempotency idem
|
||||
JOIN messages m ON m.id=idem.message_id
|
||||
WHERE idem.actor_id=%s AND idem.chat_id=%s AND idem.method='POST' AND idem.idem_key=%s
|
||||
""", (who, ident, key)).fetchone()
|
||||
if previous:
|
||||
if previous["body_sha256"] != fingerprint:
|
||||
raise APIError(409, "conflict", "Idempotency key used with another body")
|
||||
return message_detail(conn, previous)
|
||||
# 404 for foreign/nonexistent IDs; check BEFORE any message insert.
|
||||
if body.attachment_ids:
|
||||
owned = conn.execute("SELECT id,status FROM attachments WHERE chat_id=%s AND id=ANY(%s::uuid[])", (ident, body.attachment_ids)).fetchall()
|
||||
if len(owned) != len(body.attachment_ids):
|
||||
raise APIError(404, "not_found", "Attachment not found")
|
||||
if any(item["status"] == "failed" for item in owned):
|
||||
raise APIError(409, "conflict", "Failed attachment cannot be linked")
|
||||
message_id = str(uuid.uuid4())
|
||||
row = conn.execute("INSERT INTO messages(id,chat_id,sender_id,text) VALUES (%s,%s,%s,%s) RETURNING *", (message_id, ident, who, body.text.encode("utf-8"))).fetchone()
|
||||
for pos, attachment_id in enumerate(body.attachment_ids):
|
||||
conn.execute("INSERT INTO message_attachments(message_id,attachment_id,position) VALUES (%s,%s,%s)", (message_id, attachment_id, pos))
|
||||
conn.execute("INSERT INTO message_idempotency(actor_id,chat_id,method,idem_key,body_sha256,message_id) VALUES (%s,%s,'POST',%s,%s,%s)", (who, ident, key, fingerprint, message_id))
|
||||
return message_detail(conn, row)
|
||||
|
||||
|
||||
@router.get("/api/v1/chats/{chat_id}/messages")
|
||||
def messages_list(req: Request, chat_id: str, limit: str | None = None, cursor: str | None = None):
|
||||
who = actor(req)["id"]
|
||||
ident = parse_uuid(chat_id)
|
||||
n = parse_limit(limit)
|
||||
mark = read_cursor(cursor, "messages", ident)
|
||||
with db() as conn:
|
||||
require_chat(conn, ident, who)
|
||||
if mark:
|
||||
existing = conn.execute("SELECT 1 FROM messages WHERE id=%s AND chat_id=%s AND created_at=%s", (mark[1], ident, mark[0])).fetchone()
|
||||
if not existing:
|
||||
raise invalid("Invalid cursor")
|
||||
rows = conn.execute("""
|
||||
SELECT * FROM messages WHERE chat_id=%s
|
||||
AND (%s::timestamptz IS NULL OR (created_at,id)>(%s::timestamptz,%s::uuid))
|
||||
ORDER BY created_at,id LIMIT %s
|
||||
""", (ident, mark[0] if mark else None, mark[0] if mark else None, mark[1] if mark else None, n+1)).fetchall()
|
||||
with db() as conn:
|
||||
items = [message_detail(conn, row) for row in rows[:n]]
|
||||
last = rows[n-1] if len(rows)>n else None
|
||||
return {"items": items, "next_cursor": make_cursor("messages", ident, last["created_at"], str(last["id"])) if last else None}
|
||||
@@ -0,0 +1,240 @@
|
||||
"""Lab5 attachments: synchronous durable admission, asynchronous image pipeline.
|
||||
|
||||
202 means verified bytes were staged to private S3 and metadata + a job + an
|
||||
outbox event were committed in ONE PostgreSQL transaction. No broker availability
|
||||
is required for admission; the dispatcher replays unsent intents.
|
||||
"""
|
||||
import hashlib
|
||||
import os
|
||||
import tempfile
|
||||
import threading
|
||||
import uuid
|
||||
from contextlib import closing
|
||||
|
||||
import boto3
|
||||
from boto3.s3.transfer import TransferConfig
|
||||
from botocore.config import Config
|
||||
from botocore.exceptions import BotoCoreError, ClientError, EndpointConnectionError
|
||||
from fastapi import APIRouter, Query, Request
|
||||
from fastapi.responses import StreamingResponse
|
||||
from PIL import Image, ImageFile, UnidentifiedImageError
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
|
||||
from .auth import current_user
|
||||
from .core import APIError, invalid, iso, parse_uuid
|
||||
from .storage import db
|
||||
from . import telemetry as ot
|
||||
|
||||
router = APIRouter()
|
||||
BUCKET = os.getenv("S3_BUCKET", "messenger-attachments")
|
||||
MAX_BYTES = 10 * 1024 * 1024
|
||||
MAX_PIXELS = 40_000_000
|
||||
SPOOL_MEMORY_BYTES = 1024 * 1024
|
||||
S3_BUFFER_BYTES = 256 * 1024
|
||||
DECODE_LIMIT = threading.BoundedSemaphore(1)
|
||||
Image.MAX_IMAGE_PIXELS = MAX_PIXELS
|
||||
ImageFile.LOAD_TRUNCATED_IMAGES = False
|
||||
|
||||
|
||||
def s3_client():
|
||||
return ot.S3Tracing(boto3.client(
|
||||
"s3", endpoint_url=os.environ["S3_ENDPOINT"],
|
||||
aws_access_key_id=os.environ["S3_ACCESS_KEY"],
|
||||
aws_secret_access_key=os.environ["S3_SECRET_KEY"],
|
||||
region_name="us-east-1", use_ssl=True, verify=os.environ["TLS_CA_FILE"],
|
||||
config=Config(s3={"addressing_style": "path"}, connect_timeout=3,
|
||||
read_timeout=10, retries={"max_attempts": 1}),
|
||||
))
|
||||
|
||||
|
||||
def s3_error(exc):
|
||||
return APIError(503, "unavailable", "Object storage unavailable")
|
||||
|
||||
|
||||
def format_attachment(row, variants=()):
|
||||
return {
|
||||
"id": str(row["id"]), "chat_id": str(row["chat_id"]),
|
||||
"owner_id": str(row["owner_id"]), "filename": row["filename"],
|
||||
"content_type": row["content_type"], "size_bytes": row["size_bytes"],
|
||||
"sha256": row["sha256"], "status": row["status"],
|
||||
"variants": [{k: item[k] for k in ("name", "content_type", "size_bytes", "width", "height", "sha256")}
|
||||
for item in variants] if row["status"] == "ready" else [],
|
||||
"error_code": row["error_code"] if row["status"] == "failed" else None,
|
||||
"created_at": iso(row["created_at"]), "updated_at": iso(row["updated_at"]),
|
||||
}
|
||||
|
||||
|
||||
def require_member(conn, chat_id, user_id):
|
||||
if not conn.execute("SELECT 1 FROM chat_members WHERE chat_id=%s AND user_id=%s", (chat_id, user_id)).fetchone():
|
||||
raise APIError(404, "not_found", "Object not found")
|
||||
|
||||
|
||||
def attachment_row(conn, attachment_id, user_id):
|
||||
row = conn.execute("""
|
||||
SELECT a.* FROM attachments a
|
||||
JOIN chat_members cm ON cm.chat_id=a.chat_id
|
||||
WHERE a.id=%s AND cm.user_id=%s
|
||||
""", (attachment_id, user_id)).fetchone()
|
||||
if not row:
|
||||
raise APIError(404, "not_found", "Object not found")
|
||||
return row
|
||||
|
||||
|
||||
def validate_filename(filename: str):
|
||||
if not (1 <= len(filename) <= 255) or any(c in "/\\" or ord(c) < 32 or ord(c) == 127 for c in filename):
|
||||
raise invalid("Invalid filename")
|
||||
|
||||
|
||||
def validate_image(fileobj, mime: str):
|
||||
"""Validate MIME, magic, dimensions and complete decode; worker does the resize."""
|
||||
try:
|
||||
fileobj.seek(0)
|
||||
with Image.open(fileobj) as im:
|
||||
if im.format not in ("PNG", "JPEG"):
|
||||
raise APIError(415, "unsupported_media_type", "Unsupported image encoding")
|
||||
actual = "image/png" if im.format == "PNG" else "image/jpeg"
|
||||
if actual != mime:
|
||||
raise APIError(415, "unsupported_media_type", "Content-Type does not match image")
|
||||
if im.width * im.height > MAX_PIXELS:
|
||||
raise APIError(413, "payload_too_large", "Image dimensions too large")
|
||||
im.verify()
|
||||
fileobj.seek(0)
|
||||
with DECODE_LIMIT:
|
||||
with Image.open(fileobj) as im:
|
||||
im.load()
|
||||
except APIError:
|
||||
raise
|
||||
except (Image.DecompressionBombError, Image.DecompressionBombWarning):
|
||||
raise APIError(413, "payload_too_large", "Image dimensions too large") from None
|
||||
except (UnidentifiedImageError, OSError, ValueError, SyntaxError):
|
||||
raise APIError(415, "unsupported_media_type", "Invalid image") from None
|
||||
finally:
|
||||
fileobj.seek(0)
|
||||
|
||||
|
||||
def _admit_upload(spool, *, attachment_id, chat_id, user_id, filename, mime, size, digest):
|
||||
from .jobs import job_payload
|
||||
stage_key = f"staging/{attachment_id}/original"
|
||||
key = f"attachments/{attachment_id}/original"
|
||||
backup = f"recovery/{attachment_id}/original"
|
||||
job_id = str(uuid.uuid4())
|
||||
outbox_id = str(uuid.uuid4())
|
||||
client = s3_client()
|
||||
try:
|
||||
spool.seek(0)
|
||||
client.upload_fileobj(spool, BUCKET, stage_key,
|
||||
ExtraArgs={"ContentType": mime},
|
||||
Config=TransferConfig(use_threads=False, multipart_threshold=16*1024*1024,
|
||||
io_chunksize=S3_BUFFER_BYTES))
|
||||
except (BotoCoreError, ClientError, EndpointConnectionError, OSError) as exc:
|
||||
raise s3_error(exc) from exc
|
||||
|
||||
# Atomic DB metadata + intent. If DB commit is ambiguous, do not delete the
|
||||
# staged object: an accepted task may already exist; operator cleanup handles it.
|
||||
with db() as conn:
|
||||
with conn.transaction():
|
||||
require_member(conn, chat_id, user_id)
|
||||
# Small educational admission bound; pre-existing queued tasks remain safe.
|
||||
pending = conn.execute("SELECT count(*) AS c FROM processing_jobs WHERE status IN ('queued','processing')").fetchone()["c"]
|
||||
if pending >= int(os.getenv("JOB_BACKLOG_LIMIT", "1000")):
|
||||
raise APIError(429, "rate_limited", "Processing queue is full")
|
||||
row = conn.execute("""
|
||||
INSERT INTO attachments(id,chat_id,owner_id,object_key,backup_key,filename,
|
||||
content_type,size_bytes,sha256,status,staging_key,pipeline_version)
|
||||
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,'queued',%s,1) RETURNING *
|
||||
""", (attachment_id, chat_id, user_id, key, backup, filename, mime, size, digest, stage_key)).fetchone()
|
||||
conn.execute("""
|
||||
INSERT INTO processing_jobs(id,attachment_id,pipeline_version,status,attempt)
|
||||
VALUES (%s,%s,1,'queued',1)
|
||||
""", (job_id, attachment_id))
|
||||
payload = job_payload(job_id, attachment_id, 1, 1)
|
||||
conn.execute("""
|
||||
INSERT INTO job_outbox(id,job_id,payload) VALUES (%s,%s,%s::jsonb)
|
||||
""", (outbox_id, job_id, __import__('json').dumps(payload)))
|
||||
ot.event("upload.accepted", job_id=job_id)
|
||||
return format_attachment(row) # snapshot = queued, even if worker is very fast
|
||||
|
||||
|
||||
@router.post("/api/v1/chats/{chat_id}/attachments", status_code=202)
|
||||
async def upload_attachment(req: Request, chat_id: str, filename: str = Query(...)):
|
||||
from .api import actor, require_chat
|
||||
who = actor(req)["id"]
|
||||
chat_id = parse_uuid(chat_id)
|
||||
validate_filename(filename)
|
||||
mime = req.headers.get("content-type", "").split(";", 1)[0].strip().lower()
|
||||
if mime not in ("image/png", "image/jpeg"):
|
||||
raise APIError(415, "unsupported_media_type", "Only PNG and JPEG are supported")
|
||||
with db() as conn:
|
||||
require_chat(conn, chat_id, who)
|
||||
announced = req.headers.get("content-length")
|
||||
if announced:
|
||||
try:
|
||||
if int(announced) > MAX_BYTES:
|
||||
raise APIError(413, "payload_too_large", "Image too large")
|
||||
if int(announced) < 0:
|
||||
raise invalid("Invalid Content-Length")
|
||||
except ValueError:
|
||||
raise invalid("Invalid Content-Length") from None
|
||||
size = 0
|
||||
digest = hashlib.sha256()
|
||||
with tempfile.SpooledTemporaryFile(max_size=SPOOL_MEMORY_BYTES, mode="w+b") as spool:
|
||||
async for chunk in req.stream():
|
||||
size += len(chunk)
|
||||
if size > MAX_BYTES:
|
||||
raise APIError(413, "payload_too_large", "Image too large")
|
||||
digest.update(chunk)
|
||||
spool.write(chunk)
|
||||
if not size:
|
||||
raise APIError(415, "unsupported_media_type", "Empty image")
|
||||
await run_in_threadpool(validate_image, spool, mime)
|
||||
return await run_in_threadpool(_admit_upload, spool, attachment_id=str(uuid.uuid4()),
|
||||
chat_id=chat_id, user_id=who, filename=filename,
|
||||
mime=mime, size=size, digest=digest.hexdigest())
|
||||
|
||||
|
||||
@router.get("/api/v1/attachments/{attachment_id}")
|
||||
def get_attachment(req: Request, attachment_id: str):
|
||||
who = getattr(req.state, "actor", None) or current_user(req)
|
||||
with db() as conn:
|
||||
row = attachment_row(conn, parse_uuid(attachment_id), who["id"])
|
||||
variants = conn.execute("""
|
||||
SELECT name,content_type,size_bytes,width,height,sha256
|
||||
FROM attachment_variants WHERE attachment_id=%s AND pipeline_version=%s
|
||||
ORDER BY CASE name WHEN 'thumbnail' THEN 0 WHEN 'crop' THEN 1 ELSE 2 END
|
||||
""", (row["id"], row["pipeline_version"])).fetchall() if row["status"] == "ready" else []
|
||||
return format_attachment(row, variants)
|
||||
|
||||
|
||||
@router.get("/api/v1/attachments/{attachment_id}/content")
|
||||
def download_attachment(req: Request, attachment_id: str, variant: str = "original"):
|
||||
who = getattr(req.state, "actor", None) or current_user(req)
|
||||
with db() as conn:
|
||||
row = attachment_row(conn, parse_uuid(attachment_id), who["id"])
|
||||
if row["status"] != "ready":
|
||||
raise APIError(409, "conflict", "Attachment is not ready")
|
||||
if variant == "original":
|
||||
key, mime, size = row["object_key"], row["content_type"], row["size_bytes"]
|
||||
else:
|
||||
v = conn.execute("""
|
||||
SELECT * FROM attachment_variants
|
||||
WHERE attachment_id=%s AND pipeline_version=%s AND name=%s
|
||||
""", (row["id"], row["pipeline_version"], variant)).fetchone()
|
||||
if not v:
|
||||
raise APIError(404, "not_found", "Object not found")
|
||||
key, mime, size = v["object_key"], v["content_type"], v["size_bytes"]
|
||||
client = s3_client()
|
||||
try:
|
||||
response = client.get_object(Bucket=BUCKET, Key=key)
|
||||
except ClientError as exc:
|
||||
if exc.response.get("Error", {}).get("Code") in ("NoSuchKey", "404", "NotFound"):
|
||||
raise APIError(503, "unavailable", "Stored object missing") from exc
|
||||
raise s3_error(exc) from exc
|
||||
except BotoCoreError as exc:
|
||||
raise s3_error(exc) from exc
|
||||
|
||||
def iterator():
|
||||
with closing(response["Body"]) as body:
|
||||
while chunk := body.read(S3_BUFFER_BYTES):
|
||||
yield chunk
|
||||
|
||||
return StreamingResponse(iterator(), media_type=mime, headers={"Content-Length": str(size)})
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
"""HTTP Basic only on login; bearer sessions shared by all API replicas."""
|
||||
import base64
|
||||
import binascii
|
||||
import hashlib
|
||||
import re
|
||||
import secrets
|
||||
import uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import VerifyMismatchError, VerificationError
|
||||
from fastapi import Request
|
||||
from redis.exceptions import RedisError
|
||||
|
||||
from .core import APIError, SESSION_TTL, iso
|
||||
from .storage import cache, db
|
||||
|
||||
hasher = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1)
|
||||
PASSWORD_RE = re.compile(r"^[a-z0-9_]{3,32}$")
|
||||
|
||||
|
||||
def public_user(row: dict):
|
||||
return {"id": str(row["id"]), "username": row["username"], "display_name": bytes(row["display_name"]).decode("utf-8"), "created_at": iso(row["created_at"])}
|
||||
|
||||
|
||||
def unauthorized() -> APIError:
|
||||
return APIError(401, "unauthorized", "Unauthorized")
|
||||
|
||||
|
||||
def challenge(req: Request) -> str:
|
||||
return 'Basic realm="messenger", charset="UTF-8"' if req.url.path == "/api/v1/auth/sessions" else 'Bearer realm="messenger"'
|
||||
|
||||
|
||||
def bearer_token(req: Request) -> str:
|
||||
value = req.headers.get("Authorization", "")
|
||||
if not value.startswith("Bearer ") or len(value) <= 7 or " " in value[7:] or len(value) > 512:
|
||||
raise unauthorized()
|
||||
try:
|
||||
value[7:].encode("ascii")
|
||||
except UnicodeEncodeError:
|
||||
raise unauthorized() from None
|
||||
return value[7:]
|
||||
|
||||
|
||||
def session_key(token: str) -> str:
|
||||
return "session:" + hashlib.sha256(token.encode("ascii")).hexdigest()
|
||||
|
||||
|
||||
def current_user(req: Request) -> dict:
|
||||
token = bearer_token(req)
|
||||
try:
|
||||
raw = cache().get(session_key(token))
|
||||
except (RedisError, UnicodeError) as exc:
|
||||
raise APIError(503, "unavailable", "Session store unavailable") from exc
|
||||
if not raw:
|
||||
raise unauthorized()
|
||||
try:
|
||||
ident = str(uuid.UUID(raw))
|
||||
except (ValueError, TypeError):
|
||||
try:
|
||||
cache().delete(session_key(token))
|
||||
except RedisError as exc:
|
||||
raise APIError(503, "unavailable", "Session store unavailable") from exc
|
||||
raise unauthorized() from None
|
||||
with db() as conn:
|
||||
row = conn.execute("SELECT * FROM users WHERE id = %s", (ident,)).fetchone()
|
||||
if row is None:
|
||||
raise unauthorized()
|
||||
return public_user(row)
|
||||
|
||||
|
||||
def login(req: Request):
|
||||
auth = req.headers.get("Authorization", "")
|
||||
if not auth.startswith("Basic "):
|
||||
raise unauthorized()
|
||||
try:
|
||||
decoded = base64.b64decode(auth[6:].encode("ascii"), validate=True).decode("utf-8")
|
||||
username, password = decoded.split(":", 1)
|
||||
if not PASSWORD_RE.fullmatch(username):
|
||||
raise ValueError()
|
||||
except (ValueError, UnicodeError, binascii.Error):
|
||||
raise unauthorized() from None
|
||||
# Atomic shared token bucket across replicas; uniform 429 with Retry-After.
|
||||
digest=hashlib.sha256(username.encode('utf-8')).hexdigest()[:24]
|
||||
script="""
|
||||
local n=redis.call('INCR', KEYS[1])
|
||||
if n == 1 then redis.call('EXPIRE', KEYS[1], ARGV[1]) end
|
||||
return n
|
||||
"""
|
||||
try:
|
||||
count=int(cache().eval(script,1,'login:account:'+digest,60))
|
||||
except RedisError as exc:
|
||||
raise APIError(503,'unavailable','Session store unavailable') from exc
|
||||
if count > 8:
|
||||
raise APIError(429,'rate_limited','Too many login attempts')
|
||||
with db() as conn:
|
||||
row = conn.execute("SELECT * FROM users WHERE username=%s", (username,)).fetchone()
|
||||
if not row:
|
||||
raise unauthorized()
|
||||
try:
|
||||
hasher.verify(row["password_hash"], password)
|
||||
except (VerifyMismatchError, VerificationError):
|
||||
raise unauthorized() from None
|
||||
if hasher.check_needs_rehash(row["password_hash"]):
|
||||
with db() as conn:
|
||||
conn.execute("UPDATE users SET password_hash=%s WHERE id=%s", (hasher.hash(password),row["id"]))
|
||||
token = secrets.token_urlsafe(32)
|
||||
try:
|
||||
cache().set(session_key(token), str(row["id"]), ex=SESSION_TTL)
|
||||
except RedisError as exc:
|
||||
raise APIError(503, "unavailable", "Session store unavailable") from exc
|
||||
return {"token": token, "token_type": "Bearer", "expires_at": iso(datetime.now(timezone.utc) + timedelta(seconds=SESSION_TTL)), "user": public_user(row)}
|
||||
|
||||
|
||||
def logout(req: Request):
|
||||
current_user(req)
|
||||
try:
|
||||
cache().delete(session_key(bearer_token(req)))
|
||||
except RedisError as exc:
|
||||
raise APIError(503, "unavailable", "Session store unavailable") from exc
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
"""Configuration, HTTP errors and shared representation helpers."""
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from fastapi import Request
|
||||
|
||||
INSTANCE_ID = os.getenv("API_INSTANCE_ID", uuid.uuid4().hex[:12])
|
||||
SESSION_TTL = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
|
||||
IDEMPOTENCY_TTL = max(86400, int(os.getenv("IDEMPOTENCY_TTL_SECONDS", "86400")))
|
||||
|
||||
class APIError(Exception):
|
||||
def __init__(self, status: int, code: str, message: str):
|
||||
super().__init__(message)
|
||||
self.status = status
|
||||
self.code = code
|
||||
self.message = message
|
||||
|
||||
|
||||
def iso(value: datetime) -> str:
|
||||
return value.astimezone(timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z")
|
||||
|
||||
|
||||
def invalid(message: str = "Invalid request") -> APIError:
|
||||
return APIError(400, "invalid_request", message)
|
||||
|
||||
|
||||
def parse_uuid(value: str) -> str:
|
||||
try:
|
||||
return str(uuid.UUID(value))
|
||||
except (ValueError, TypeError, AttributeError):
|
||||
raise invalid("Invalid UUID") from None
|
||||
|
||||
|
||||
def parse_limit(raw: str | None) -> int:
|
||||
if raw is None:
|
||||
return 50
|
||||
try:
|
||||
if not raw.isascii() or not raw.isdecimal():
|
||||
raise ValueError()
|
||||
value = int(raw)
|
||||
except (ValueError, AttributeError):
|
||||
raise invalid("Invalid limit") from None
|
||||
if not 1 <= value <= 100:
|
||||
raise invalid("Invalid limit")
|
||||
return value
|
||||
|
||||
|
||||
def make_cursor(kind: str, scope: str, created: datetime, ident: str) -> str:
|
||||
b = json.dumps({"kind": kind, "scope": scope, "created_at": iso(created), "id": ident}, separators=(",", ":")).encode()
|
||||
return base64.urlsafe_b64encode(b).decode().rstrip("=")
|
||||
|
||||
|
||||
def read_cursor(raw: str | None, kind: str, scope: str):
|
||||
if raw is None:
|
||||
return None
|
||||
try:
|
||||
if not raw or len(raw) > 2048 or any(ch not in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_" for ch in raw):
|
||||
raise ValueError()
|
||||
data = json.loads(base64.b64decode(raw + "=" * (-len(raw) % 4), altchars=b"-_", validate=True))
|
||||
if not isinstance(data, dict) or data.get("kind") != kind or data.get("scope") != scope:
|
||||
raise ValueError()
|
||||
created = datetime.fromisoformat(data["created_at"].replace("Z", "+00:00"))
|
||||
if created.tzinfo is None:
|
||||
raise ValueError()
|
||||
ident = str(uuid.UUID(data["id"]))
|
||||
return created, ident
|
||||
except (ValueError, TypeError, KeyError, UnicodeError, json.JSONDecodeError):
|
||||
raise invalid("Invalid cursor") from None
|
||||
|
||||
|
||||
def request_id(req: Request) -> str:
|
||||
return getattr(req.state, "request_id", uuid.uuid4().hex)
|
||||
|
||||
|
||||
def error_body(req: Request, code: str, message: str):
|
||||
return {"error": {"code": code, "message": message, "request_id": request_id(req)}}
|
||||
@@ -0,0 +1,42 @@
|
||||
"""Operator one-shot: install narrowly scoped login roles after migrations."""
|
||||
import os
|
||||
import psycopg
|
||||
from psycopg import sql
|
||||
|
||||
# All application business tables are accessed via explicit grants;
|
||||
# only migration role can CREATE, ALTER, DROP or read pg_* administration.
|
||||
API_TABLES={'users','chats','chat_members','messages','message_attachments',
|
||||
'message_idempotency','attachments','attachment_variants','processing_jobs','job_outbox'}
|
||||
JOB_TABLES={'attachments','attachment_variants','processing_jobs','job_outbox',
|
||||
'job_replay_audit','job_fault_once'}
|
||||
|
||||
def main():
|
||||
with psycopg.connect(os.environ['DATABASE_URL'], autocommit=True) as c:
|
||||
tables={r[0] for r in c.execute("SELECT tablename FROM pg_tables WHERE schemaname='public'")}
|
||||
for role in ('api','worker','dispatcher'):
|
||||
username='messenger_'+role
|
||||
pw=os.environ['DB_'+role.upper()+'_PASSWORD']
|
||||
row=c.execute('SELECT 1 FROM pg_roles WHERE rolname=%s',(username,)).fetchone()
|
||||
if not row:
|
||||
c.execute(sql.SQL('CREATE ROLE {} LOGIN PASSWORD {}').format(sql.Identifier(username), sql.Literal(pw)))
|
||||
else:
|
||||
c.execute(sql.SQL('ALTER ROLE {} LOGIN PASSWORD {}').format(sql.Identifier(username), sql.Literal(pw)))
|
||||
c.execute(sql.SQL('GRANT CONNECT ON DATABASE {} TO {}').format(sql.Identifier(os.environ.get('POSTGRES_DB','messenger')),sql.Identifier(username)))
|
||||
c.execute(sql.SQL('GRANT USAGE ON SCHEMA public TO {}').format(sql.Identifier(username)))
|
||||
for table in sorted(tables):
|
||||
# API handles metadata and HTTP; worker updates processing statuses;
|
||||
# dispatcher works with outbox + jobs. No DDL privileges.
|
||||
mode= None
|
||||
if role=='api':
|
||||
if table in API_TABLES: mode='SELECT, INSERT, UPDATE'
|
||||
if role=='worker':
|
||||
if table in JOB_TABLES:
|
||||
mode='SELECT, INSERT, UPDATE, DELETE'
|
||||
if role=='dispatcher':
|
||||
if table in JOB_TABLES:
|
||||
mode='SELECT, INSERT, UPDATE, DELETE'
|
||||
if mode:
|
||||
c.execute(sql.SQL('GRANT '+mode+' ON TABLE {} TO {}').format(sql.Identifier(table),sql.Identifier(username)))
|
||||
c.execute(sql.SQL('GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO {}').format(sql.Identifier(username)))
|
||||
print('Role permissions synchronized (no secrets shown)')
|
||||
if __name__=='__main__': main()
|
||||
@@ -0,0 +1,124 @@
|
||||
"""Sandboxed-per-task image work. Process is killed after JOB_TIMEOUT_SECONDS.
|
||||
|
||||
Outputs only JSON variant metadata. Original bytes are copied from durable staging,
|
||||
never transformed. Pillow reopens/exif-transposes pixels for derivatives, stripping
|
||||
metadata on re-encode. No API tokens or arbitrary user paths enter this command.
|
||||
"""
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
from PIL import Image, ImageOps, UnidentifiedImageError
|
||||
from botocore.exceptions import ClientError, BotoCoreError
|
||||
|
||||
from .attachments import BUCKET, MAX_BYTES, MAX_PIXELS, s3_client
|
||||
from . import telemetry as ot
|
||||
from opentelemetry.trace import SpanKind
|
||||
|
||||
Image.MAX_IMAGE_PIXELS = MAX_PIXELS
|
||||
|
||||
|
||||
def rgb_image(src):
|
||||
orient = ImageOps.exif_transpose(src)
|
||||
orient.load()
|
||||
if orient.width * orient.height > MAX_PIXELS:
|
||||
raise ValueError("too many decoded pixels")
|
||||
# Compose transparency on white, strip EXIF/ICC and do not enlarge.
|
||||
rgba = orient.convert("RGBA")
|
||||
white = Image.new("RGBA", rgba.size, (255, 255, 255, 255))
|
||||
white.alpha_composite(rgba)
|
||||
return white.convert("RGB")
|
||||
|
||||
|
||||
def transform(raw):
|
||||
with Image.open(io.BytesIO(raw)) as image:
|
||||
if image.format not in ("PNG", "JPEG"):
|
||||
raise ValueError("invalid encoding")
|
||||
rgb = rgb_image(image)
|
||||
t = rgb.copy()
|
||||
t.thumbnail((256, 256), resample=Image.Resampling.LANCZOS)
|
||||
# Center crop fit scales up small images when needed.
|
||||
crop = ImageOps.fit(rgb, (128, 128), method=Image.Resampling.LANCZOS, centering=(0.5, 0.5))
|
||||
optim = rgb.copy()
|
||||
optim.thumbnail((1280, 1280), resample=Image.Resampling.LANCZOS)
|
||||
return [
|
||||
("thumbnail", t, "JPEG", "image/jpeg", {"quality": 85, "optimize": True}),
|
||||
("crop", crop, "JPEG", "image/jpeg", {"quality": 85, "optimize": True}),
|
||||
("optimized", optim, "WEBP", "image/webp", {"quality": 78, "method": 4}),
|
||||
]
|
||||
|
||||
|
||||
def run(attachment_id, pipeline_version):
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
|
||||
with ot.span("db.load_staging_metadata", kind=SpanKind.CLIENT, attrs={"db.system.name":"postgresql"}):
|
||||
with psycopg.connect(os.environ["DATABASE_URL"], row_factory=dict_row, connect_timeout=5) as conn:
|
||||
row = conn.execute("""
|
||||
SELECT * FROM attachments WHERE id=%s AND pipeline_version=%s
|
||||
""", (attachment_id, pipeline_version)).fetchone()
|
||||
if not row or not row["staging_key"]:
|
||||
raise ValueError("staging metadata not found")
|
||||
|
||||
client = s3_client()
|
||||
body = client.get_object(Bucket=BUCKET, Key=row["staging_key"])["Body"]
|
||||
try:
|
||||
raw = body.read(MAX_BYTES + 1)
|
||||
finally:
|
||||
body.close()
|
||||
if not raw or len(raw) > MAX_BYTES or len(raw) != row["size_bytes"]:
|
||||
raise ValueError("staging size mismatch")
|
||||
if hashlib.sha256(raw).hexdigest() != row["sha256"]:
|
||||
raise ValueError("staging checksum mismatch")
|
||||
|
||||
# Recompute every result if a prior run was interrupted. Keys are deterministic
|
||||
# for (attachment_id,pipeline_version,variant), so duplicates don't multiply objects.
|
||||
output = []
|
||||
for name, image, fmt, mime, options in transform(raw):
|
||||
buf = io.BytesIO()
|
||||
image.save(buf, format=fmt, **options)
|
||||
encoded = buf.getvalue()
|
||||
key = f"variants/{attachment_id}/v{pipeline_version}/{name}"
|
||||
client.put_object(Bucket=BUCKET, Key=key, Body=encoded, ContentType=mime)
|
||||
output.append({"name": name, "content_type": mime,
|
||||
"size_bytes": len(encoded), "sha256": hashlib.sha256(encoded).hexdigest(),
|
||||
"width": image.width, "height": image.height, "object_key": key})
|
||||
|
||||
# Only after derivatives exist, publish unchanged primary and recovery copy.
|
||||
client.copy_object(Bucket=BUCKET, Key=row["object_key"],
|
||||
CopySource={"Bucket": BUCKET, "Key": row["staging_key"]},
|
||||
MetadataDirective="REPLACE", ContentType=row["content_type"])
|
||||
client.copy_object(Bucket=BUCKET, Key=row["backup_key"],
|
||||
CopySource={"Bucket": BUCKET, "Key": row["object_key"]},
|
||||
MetadataDirective="REPLACE", ContentType=row["content_type"])
|
||||
return output
|
||||
|
||||
|
||||
def main():
|
||||
import uuid
|
||||
if len(sys.argv) != 3:
|
||||
raise SystemExit(2)
|
||||
try:
|
||||
ident = str(uuid.UUID(sys.argv[1]))
|
||||
version = int(sys.argv[2])
|
||||
if version < 1:
|
||||
raise ValueError("invalid version")
|
||||
ot.init("worker", child=True)
|
||||
with ot.span("image.transform", context=ot.extract(json.loads(os.getenv("LAB6_PARENT_CONTEXT", "{}")))):
|
||||
out = run(ident, version)
|
||||
ot.event("image.transformed")
|
||||
print(json.dumps({"variants": out}, ensure_ascii=False))
|
||||
except (ValueError, UnidentifiedImageError, Image.DecompressionBombError, Image.DecompressionBombWarning) as exc:
|
||||
print("Permanent image processing failure", file=sys.stderr)
|
||||
raise SystemExit(20) from None
|
||||
except (BotoCoreError, ClientError, OSError):
|
||||
print("Transient object storage failure", file=sys.stderr)
|
||||
raise SystemExit(30) from None
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
finally:
|
||||
ot.flush()
|
||||
+477
@@ -0,0 +1,477 @@
|
||||
"""Durable RabbitMQ delivery + PostgreSQL transactional outbox and worker leases.
|
||||
|
||||
There is no exactly-once transport guarantee. We guarantee eventual recovery of
|
||||
committed intent and idempotent DB results under at-least-once redelivery.
|
||||
Commands: `python -m app.jobs dispatch`, `worker`, `replay --id UUID`, `status`.
|
||||
"""
|
||||
import argparse
|
||||
from contextlib import contextmanager
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import random
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import threading
|
||||
from . import telemetry as ot
|
||||
from opentelemetry.trace import SpanKind, Status, StatusCode
|
||||
import uuid
|
||||
from datetime import datetime, timezone, timedelta
|
||||
|
||||
import pika
|
||||
import ssl
|
||||
import psycopg
|
||||
from pika.exceptions import AMQPError
|
||||
from psycopg.rows import dict_row
|
||||
|
||||
log = logging.getLogger("lab5.jobs")
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
||||
QUEUE = "attachment-processing.v1"
|
||||
MAX_ATTEMPTS = int(os.getenv("JOB_MAX_ATTEMPTS", "5"))
|
||||
JOB_TIMEOUT = int(os.getenv("JOB_TIMEOUT_SECONDS", "60"))
|
||||
LEASE_SECONDS = JOB_TIMEOUT + 45
|
||||
|
||||
|
||||
@contextmanager
|
||||
def connect_db():
|
||||
# No credentials, SQL text, or parameters in spans.
|
||||
with ot.dependency_span('db.job.transaction', kind=SpanKind.CLIENT, attrs={'db.system.name':'postgresql'}):
|
||||
with psycopg.connect(os.environ["DATABASE_URL"], row_factory=dict_row, connect_timeout=5, options='-c statement_timeout=5000') as conn:
|
||||
yield conn
|
||||
|
||||
|
||||
def job_payload(job_id, attachment_id, version, attempt):
|
||||
return {
|
||||
"schema_version": 1, "job_id": str(job_id), "type": "attachment.process.v1",
|
||||
"attachment_id": str(attachment_id), "pipeline_version": version,
|
||||
"attempt": attempt, "created_at": datetime.now(timezone.utc).isoformat(),
|
||||
**ot.inject(),
|
||||
}
|
||||
|
||||
|
||||
@contextmanager
|
||||
def connection():
|
||||
context=ssl.create_default_context(cafile=os.environ["TLS_CA_FILE"])
|
||||
context.load_cert_chain(os.environ["TLS_CLIENT_CERT"],os.environ["TLS_CLIENT_KEY"])
|
||||
host=os.environ["BROKER_HOST"]
|
||||
params = pika.ConnectionParameters(
|
||||
host=host, port=int(os.environ.get("BROKER_PORT","5671")),
|
||||
ssl_options=pika.SSLOptions(context,host),
|
||||
credentials=pika.PlainCredentials(os.environ["BROKER_USER"], os.environ["BROKER_PASSWORD"]),
|
||||
heartbeat=max(120, JOB_TIMEOUT + 60), blocked_connection_timeout=120,
|
||||
socket_timeout=5, connection_attempts=3, retry_delay=1)
|
||||
mq = pika.BlockingConnection(params)
|
||||
try:
|
||||
yield mq
|
||||
finally:
|
||||
try:
|
||||
if mq.is_open:
|
||||
mq.close()
|
||||
except AMQPError:
|
||||
pass
|
||||
|
||||
|
||||
def setup_channel(conn):
|
||||
ch = conn.channel()
|
||||
ch.queue_declare(queue=QUEUE, durable=True)
|
||||
return ch
|
||||
|
||||
|
||||
def queue_outbox(db, job_id, attachment_id, version, attempt, available_at=None):
|
||||
payload = job_payload(job_id, attachment_id, version, attempt)
|
||||
if not payload.get('traceparent'):
|
||||
# Lease rescue/replay has no active consumer context. Preserve the first
|
||||
# acceptance context rather than inventing a new disconnected trace.
|
||||
previous = db.execute("SELECT payload FROM job_outbox WHERE job_id=%s ORDER BY created_at,id LIMIT 1", (job_id,)).fetchone()
|
||||
if previous:
|
||||
payload.update({k: previous['payload'][k] for k in ('traceparent','tracestate') if k in previous['payload']})
|
||||
db.execute("""
|
||||
INSERT INTO job_outbox(id,job_id,payload,available_at)
|
||||
VALUES (%s,%s,%s::jsonb,COALESCE(%s,now()))
|
||||
""", (str(uuid.uuid4()), job_id, json.dumps(payload), available_at))
|
||||
|
||||
|
||||
def cleanup_abandoned_staging():
|
||||
"""Best effort cleanup of retained stages; never delete current processing work."""
|
||||
from .attachments import BUCKET, s3_client
|
||||
client = s3_client()
|
||||
retention = max(3600, int(os.getenv("STAGING_RETENTION_SECONDS", "86400")))
|
||||
with connect_db() as db:
|
||||
rows = db.execute("""
|
||||
SELECT id,staging_key FROM attachments
|
||||
WHERE staging_key IS NOT NULL AND
|
||||
((status='ready' AND updated_at < now()-interval '300 seconds') OR
|
||||
(status='failed' AND updated_at < now()-(%s*interval '1 second')))
|
||||
LIMIT 50
|
||||
""", (retention,)).fetchall()
|
||||
for row in rows:
|
||||
with connect_db() as db:
|
||||
with db.transaction():
|
||||
# Row-level lock serializes against operator replay.
|
||||
current = db.execute("SELECT status,staging_key,updated_at FROM attachments WHERE id=%s FOR UPDATE", (row["id"],)).fetchone()
|
||||
if not current or current["staging_key"] != row["staging_key"]:
|
||||
continue
|
||||
age = (datetime.now(timezone.utc) - current["updated_at"]).total_seconds()
|
||||
if not (current["status"] == "ready" and age >= 300 or current["status"] == "failed" and age >= retention):
|
||||
continue
|
||||
client.delete_object(Bucket=BUCKET, Key=row["staging_key"])
|
||||
db.execute("UPDATE attachments SET staging_key=NULL WHERE id=%s AND staging_key=%s", (row["id"], row["staging_key"]))
|
||||
# Also prune staging uploads whose DB COMMIT failed, after a long retention.
|
||||
from botocore.exceptions import ClientError
|
||||
for page in client.get_paginator("list_objects_v2").paginate(Bucket=BUCKET, Prefix="staging/"):
|
||||
for obj in page.get("Contents", []):
|
||||
if (datetime.now(timezone.utc) - obj["LastModified"]).total_seconds() < retention:
|
||||
continue
|
||||
key = obj["Key"]
|
||||
with connect_db() as db:
|
||||
with db.transaction():
|
||||
referenced = db.execute("SELECT 1 FROM attachments WHERE staging_key=%s", (key,)).fetchone()
|
||||
if not referenced:
|
||||
client.delete_object(Bucket=BUCKET, Key=key)
|
||||
|
||||
def rescue_expired_jobs(conn):
|
||||
"""Requeue leased jobs whose worker died (durably, no manual task recreation)."""
|
||||
with conn.transaction():
|
||||
rows = conn.execute("""
|
||||
SELECT j.id,j.attachment_id,j.pipeline_version,j.attempt
|
||||
FROM processing_jobs j
|
||||
WHERE j.status='processing' AND j.leased_until < now()
|
||||
FOR UPDATE SKIP LOCKED LIMIT 20
|
||||
""").fetchall()
|
||||
for row in rows:
|
||||
if row["attempt"] >= MAX_ATTEMPTS:
|
||||
conn.execute("""UPDATE processing_jobs
|
||||
SET status='failed',error_code='retry_exhausted',lease_token=NULL,leased_until=NULL,updated_at=now()
|
||||
WHERE id=%s""", (row["id"],))
|
||||
conn.execute("""UPDATE attachments SET status='failed',error_code='retry_exhausted',updated_at=now()
|
||||
WHERE id=%s""", (row["attachment_id"],))
|
||||
else:
|
||||
attempt = row["attempt"] + 1
|
||||
conn.execute("""UPDATE processing_jobs SET status='queued',attempt=%s,
|
||||
lease_token=NULL,leased_until=NULL,next_run_at=now(),updated_at=now()
|
||||
WHERE id=%s""", (attempt, row["id"]))
|
||||
conn.execute("UPDATE attachments SET status='queued',updated_at=now() WHERE id=%s", (row["attachment_id"],))
|
||||
queue_outbox(conn, row["id"], row["attachment_id"], row["pipeline_version"], attempt)
|
||||
log.warning("reclaimed timed-out job %s attempt %s", row["id"], attempt)
|
||||
|
||||
|
||||
def sample_backlog():
|
||||
# Query durable *queued* jobs, including delayed retries and unpublished outbox.
|
||||
# No broker membership scan; oldest age is wall clock since initial acceptance.
|
||||
while True:
|
||||
try:
|
||||
with psycopg.connect(os.environ['DATABASE_URL'], row_factory=dict_row, connect_timeout=3, options='-c statement_timeout=2000') as db:
|
||||
row = db.execute("SELECT count(*) AS depth, COALESCE(EXTRACT(EPOCH FROM now()-min(created_at)),0) AS age FROM processing_jobs WHERE status='queued'").fetchone()
|
||||
ot.backlog_depth, ot.backlog_age = row['depth'], float(row['age'])
|
||||
except psycopg.Error:
|
||||
ot.backlog_depth = ot.backlog_age = None
|
||||
time.sleep(3)
|
||||
|
||||
|
||||
def dispatch_loop():
|
||||
"""Publish outbox rows with publisher confirm, mark only AFTER confirm."""
|
||||
threading.Thread(target=sample_backlog, daemon=True).start()
|
||||
while True:
|
||||
try:
|
||||
with connection() as mq:
|
||||
ch = setup_channel(mq)
|
||||
ch.confirm_delivery()
|
||||
last_clean = time.monotonic()
|
||||
last_queue_sample = 0
|
||||
while True:
|
||||
# Periodic lease recovery works even if original message was consumed.
|
||||
with connect_db() as conn:
|
||||
rescue_expired_jobs(conn)
|
||||
with conn.transaction():
|
||||
rows = conn.execute("""
|
||||
SELECT id,payload FROM job_outbox
|
||||
WHERE published_at IS NULL AND available_at<=now()
|
||||
ORDER BY available_at,created_at
|
||||
FOR UPDATE SKIP LOCKED LIMIT 20
|
||||
""").fetchall()
|
||||
for row in rows:
|
||||
if os.getenv("LAB5_FAULT_BEFORE_PUBLISH") == "once":
|
||||
# Persist one-time fault before hard exit; outbox still
|
||||
# unmarked and dispatcher will publish on restart.
|
||||
with connect_db() as faultdb:
|
||||
inserted = faultdb.execute("""
|
||||
INSERT INTO job_fault_once(job_id,fault) VALUES (%s,'before_publish')
|
||||
ON CONFLICT DO NOTHING RETURNING job_id
|
||||
""", (row["payload"]["job_id"],)).fetchone()
|
||||
if inserted:
|
||||
os._exit(78)
|
||||
payload = row['payload']
|
||||
with ot.span('rabbitmq.publish', kind=SpanKind.PRODUCER, context=ot.extract(payload),
|
||||
attrs={'messaging.system':'rabbitmq','messaging.destination.name':QUEUE,'job.attempt':payload['attempt']}) as producer:
|
||||
# Propagate actual producer span, while DB retains the original intent.
|
||||
raw = json.dumps({**payload, **ot.inject()}, separators=(",", ":"))
|
||||
ch.basic_publish(exchange="", routing_key=QUEUE, body=raw.encode("utf-8"),
|
||||
mandatory=True, properties=pika.BasicProperties(content_type="application/json", delivery_mode=2))
|
||||
conn.execute("UPDATE job_outbox SET published_at=now() WHERE id=%s", (row["id"],))
|
||||
ot.event('job.published', job_id=payload['job_id'], attempt=payload['attempt'])
|
||||
if time.monotonic() - last_queue_sample > 3:
|
||||
q = ch.queue_declare(queue=QUEUE, passive=True).method
|
||||
ot.broker_ready, ot.broker_consumers = q.message_count, q.consumer_count
|
||||
last_queue_sample = time.monotonic()
|
||||
if time.monotonic() - last_clean > 60:
|
||||
try:
|
||||
cleanup_abandoned_staging()
|
||||
except Exception:
|
||||
log.warning("staging janitor failed; retry later")
|
||||
last_clean = time.monotonic()
|
||||
if not rows:
|
||||
mq.sleep(1)
|
||||
except (AMQPError, OSError, psycopg.Error) as exc:
|
||||
ot.broker_ready = ot.broker_consumers = None
|
||||
log.warning("dispatcher reconnect after %s", type(exc).__name__)
|
||||
time.sleep(2)
|
||||
|
||||
|
||||
def claim_job(db, message):
|
||||
job_id = message["job_id"]
|
||||
with db.transaction():
|
||||
job = db.execute("SELECT * FROM processing_jobs WHERE id=%s FOR UPDATE", (job_id,)).fetchone()
|
||||
if job is None or job["status"] in ("ready", "failed") or job["attempt"] != message["attempt"] or job["pipeline_version"] != message["pipeline_version"]:
|
||||
return "ignore", None
|
||||
if job["status"] == "processing":
|
||||
return "busy", None
|
||||
if job["next_run_at"] > datetime.now(timezone.utc):
|
||||
return "busy", None
|
||||
lease = str(uuid.uuid4())
|
||||
db.execute("""UPDATE processing_jobs SET status='processing',lease_token=%s,
|
||||
leased_until=now()+(%s*interval '1 second'),updated_at=now()
|
||||
WHERE id=%s""", (lease, LEASE_SECONDS, job_id))
|
||||
db.execute("UPDATE attachments SET status='processing',updated_at=now() WHERE id=%s", (job["attachment_id"],))
|
||||
return "claimed", {"job": job, "lease": lease}
|
||||
|
||||
|
||||
def publish_result(db, *, job, lease, variants):
|
||||
"""Final result is committed atomically; stale leases/versions cannot publish."""
|
||||
with db.transaction():
|
||||
current = db.execute("SELECT * FROM processing_jobs WHERE id=%s FOR UPDATE", (job["id"],)).fetchone()
|
||||
if current["status"] != "processing" or str(current["lease_token"]) != lease or current["pipeline_version"] != job["pipeline_version"]:
|
||||
log.warning("stale worker result ignored %s", job["id"])
|
||||
return False
|
||||
for v in variants:
|
||||
db.execute("""
|
||||
INSERT INTO attachment_variants(attachment_id,pipeline_version,name,object_key,content_type,size_bytes,sha256,width,height)
|
||||
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)
|
||||
ON CONFLICT(attachment_id,pipeline_version,name) DO UPDATE SET
|
||||
object_key=EXCLUDED.object_key,content_type=EXCLUDED.content_type,
|
||||
size_bytes=EXCLUDED.size_bytes,sha256=EXCLUDED.sha256,
|
||||
width=EXCLUDED.width,height=EXCLUDED.height
|
||||
""", (job["attachment_id"], job["pipeline_version"], v["name"], v["object_key"],
|
||||
v["content_type"], v["size_bytes"], v["sha256"], v["width"], v["height"]))
|
||||
db.execute("""UPDATE attachments SET status='ready',error_code=NULL,updated_at=now()
|
||||
WHERE id=%s AND pipeline_version=%s""", (job["attachment_id"], job["pipeline_version"]))
|
||||
db.execute("""UPDATE processing_jobs SET status='ready',lease_token=NULL,leased_until=NULL,
|
||||
error_code=NULL,updated_at=now() WHERE id=%s""", (job["id"],))
|
||||
return True
|
||||
|
||||
|
||||
def fail_job(db, job, lease, *, permanent=False, code="processing_failed"):
|
||||
with db.transaction():
|
||||
current = db.execute("SELECT * FROM processing_jobs WHERE id=%s FOR UPDATE", (job["id"],)).fetchone()
|
||||
if current["status"] != "processing" or str(current["lease_token"]) != lease:
|
||||
return "stale"
|
||||
if permanent or job["attempt"] >= MAX_ATTEMPTS:
|
||||
code = code if permanent else "retry_exhausted"
|
||||
db.execute("""UPDATE processing_jobs SET status='failed',error_code=%s,lease_token=NULL,
|
||||
leased_until=NULL,updated_at=now() WHERE id=%s""", (code, job["id"]))
|
||||
db.execute("UPDATE attachments SET status='failed',error_code=%s,updated_at=now() WHERE id=%s", (code, job["attachment_id"]))
|
||||
return "failed"
|
||||
else:
|
||||
attempt = job["attempt"] + 1
|
||||
delay = min(60.0, 2.0 * (2 ** (attempt - 2))) + random.uniform(0, 1.0)
|
||||
run_at = datetime.now(timezone.utc) + timedelta(seconds=delay)
|
||||
db.execute("""UPDATE processing_jobs SET status='queued',attempt=%s,next_run_at=%s,
|
||||
lease_token=NULL,leased_until=NULL,updated_at=now() WHERE id=%s""", (attempt, run_at, job["id"]))
|
||||
db.execute("UPDATE attachments SET status='queued',updated_at=now() WHERE id=%s", (job["attachment_id"],))
|
||||
queue_outbox(db, job["id"], job["attachment_id"], job["pipeline_version"], attempt, run_at)
|
||||
log.warning("job %s scheduled retry %s after %.1fs", job["id"], attempt, delay)
|
||||
return "retry"
|
||||
|
||||
|
||||
def cleanup_staging(job):
|
||||
from .attachments import BUCKET, s3_client
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
try:
|
||||
with connect_db() as conn:
|
||||
row = conn.execute("SELECT staging_key,status FROM attachments WHERE id=%s", (job["attachment_id"],)).fetchone()
|
||||
if row and row["status"] == "ready" and row["staging_key"]:
|
||||
s3_client().delete_object(Bucket=BUCKET, Key=row["staging_key"])
|
||||
with connect_db() as conn:
|
||||
conn.execute("UPDATE attachments SET staging_key=NULL WHERE id=%s AND status='ready' AND staging_key=%s",
|
||||
(job["attachment_id"], row["staging_key"]))
|
||||
except (BotoCoreError, ClientError, psycopg.Error, OSError):
|
||||
log.warning("staging cleanup deferred for %s", job["id"])
|
||||
|
||||
|
||||
def process_message(raw):
|
||||
try:
|
||||
carrier = json.loads(raw)
|
||||
if not isinstance(carrier, dict): carrier = {}
|
||||
except (ValueError, TypeError):
|
||||
carrier = {}
|
||||
with ot.span('rabbitmq.consume', kind=SpanKind.CONSUMER, context=ot.extract(carrier),
|
||||
attrs={'messaging.system':'rabbitmq','messaging.destination.name':QUEUE}) as consumer:
|
||||
return process_message_inner(raw, consumer)
|
||||
|
||||
|
||||
def process_message_inner(raw, consumer):
|
||||
try:
|
||||
msg = json.loads(raw)
|
||||
assert msg["schema_version"] == 1 and msg["type"] == "attachment.process.v1"
|
||||
uuid.UUID(msg["job_id"])
|
||||
uuid.UUID(msg["attachment_id"])
|
||||
assert type(msg["attempt"]) is int and msg["attempt"] >= 1
|
||||
except (ValueError, KeyError, AssertionError, TypeError):
|
||||
log.error("invalid internal broker message discarded")
|
||||
return "ack" # no secrets printed, does not touch DB
|
||||
with connect_db() as db:
|
||||
status, state = claim_job(db, msg)
|
||||
if status == "ignore":
|
||||
return "ack"
|
||||
if status == "busy":
|
||||
return "requeue"
|
||||
job, lease = state["job"], state["lease"]
|
||||
consumer.set_attribute('job.attempt',job['attempt'])
|
||||
consumer.set_attribute('job.id',str(job['id']))
|
||||
ot.event('job.claimed', job_id=str(job['id']), attempt=job['attempt'])
|
||||
start = time.monotonic()
|
||||
ot.worker_busy = 1
|
||||
def done(outcome):
|
||||
attrs = {'job_type':'attachment.process.v1','outcome':outcome}
|
||||
ot.count('lab_jobs',attrs)
|
||||
ot.observe('lab_job_duration',time.monotonic()-start,attrs)
|
||||
if outcome == 'retry':
|
||||
ot.count('lab_job_retries',{'job_type':'attachment.process.v1'})
|
||||
if outcome in ('retry','failed','requeue'):
|
||||
consumer.set_status(Status(StatusCode.ERROR))
|
||||
consumer.set_attribute('job.outcome',outcome)
|
||||
ot.event('job.'+outcome, level=logging.ERROR if outcome in ('failed','retry','requeue') else logging.INFO, job_id=str(job['id']), attempt=job['attempt'])
|
||||
try:
|
||||
if os.getenv('LAB6_FAULT_RETRY_ONCE') == 'once':
|
||||
with connect_db() as db:
|
||||
inserted = db.execute("INSERT INTO job_fault_once(job_id,fault) VALUES (%s,'lab6_retry') ON CONFLICT DO NOTHING RETURNING job_id", (job['id'],)).fetchone()
|
||||
if inserted:
|
||||
raise RuntimeError('injected transient retry')
|
||||
cmd = [sys.executable, "-m", "app.image_worker", str(job["attachment_id"]), str(job["pipeline_version"])]
|
||||
with ot.span('image.subprocess'):
|
||||
env = {**os.environ, 'LAB6_PARENT_CONTEXT': json.dumps(ot.inject())}
|
||||
proc = subprocess.run(cmd, capture_output=True, timeout=JOB_TIMEOUT, check=False, env=env)
|
||||
if proc.returncode != 0:
|
||||
with connect_db() as db:
|
||||
outcome = fail_job(db, job, lease, permanent=(proc.returncode == 20),
|
||||
code="invalid_image" if proc.returncode == 20 else "processing_failed")
|
||||
done(outcome)
|
||||
return "ack" # next attempt is already safely in DB outbox
|
||||
result = json.loads(proc.stdout)
|
||||
variants = result["variants"]
|
||||
if sorted(v["name"] for v in variants) != ["crop", "optimized", "thumbnail"]:
|
||||
raise ValueError("incomplete variants")
|
||||
if os.getenv("LAB5_FAULT_AFTER_S3") == "once":
|
||||
# One-time operator-only injected hard death, after all S3 writes and
|
||||
# before DB result commit/ack; SQL PK prevents endless failure loop.
|
||||
with connect_db() as db:
|
||||
with db.transaction():
|
||||
inserted = db.execute("""
|
||||
INSERT INTO job_fault_once(job_id,fault) VALUES (%s,'after_s3')
|
||||
ON CONFLICT DO NOTHING RETURNING job_id
|
||||
""", (job["id"],)).fetchone()
|
||||
if inserted:
|
||||
os._exit(77)
|
||||
with ot.span("db.publish_result", kind=SpanKind.CLIENT, attrs={"db.system.name":"postgresql"}):
|
||||
with connect_db() as db:
|
||||
ok = publish_result(db, job=job, lease=lease, variants=variants)
|
||||
if ok:
|
||||
ot.observe('lab_ready_duration',(datetime.now(timezone.utc)-job['created_at']).total_seconds(), {'job_type':'attachment.process.v1'})
|
||||
cleanup_staging(job)
|
||||
done('ready' if ok else 'stale')
|
||||
return "ack"
|
||||
except subprocess.TimeoutExpired:
|
||||
with connect_db() as db:
|
||||
outcome = fail_job(db, job, lease, code="processing_timeout")
|
||||
done(outcome)
|
||||
return "ack"
|
||||
except Exception:
|
||||
log.exception("job processing failure (internal details not sent to API)")
|
||||
# Leave lease for dispatcher recovery if even DB unavailable.
|
||||
try:
|
||||
with connect_db() as db:
|
||||
outcome = fail_job(db, job, lease)
|
||||
done(outcome)
|
||||
return "ack"
|
||||
except psycopg.Error:
|
||||
done("requeue")
|
||||
return "requeue"
|
||||
finally:
|
||||
ot.worker_busy = 0
|
||||
|
||||
|
||||
def worker_loop():
|
||||
while True:
|
||||
try:
|
||||
with connection() as mq:
|
||||
ch = setup_channel(mq)
|
||||
ch.basic_qos(prefetch_count=max(1, int(os.getenv("WORKER_PREFETCH", "1"))))
|
||||
|
||||
def callback(channel, method, props, body):
|
||||
outcome = process_message(body)
|
||||
if outcome == "ack":
|
||||
channel.basic_ack(method.delivery_tag)
|
||||
else:
|
||||
channel.basic_nack(method.delivery_tag, requeue=True)
|
||||
time.sleep(2) # prevent tight redelivery spin on an active lease
|
||||
|
||||
ch.basic_consume(queue=QUEUE, on_message_callback=callback, auto_ack=False)
|
||||
log.info("worker ready; max attempts=%d timeout=%ds", MAX_ATTEMPTS, JOB_TIMEOUT)
|
||||
ch.start_consuming()
|
||||
except (AMQPError, OSError, psycopg.Error) as exc:
|
||||
log.warning("worker reconnect after %s", type(exc).__name__)
|
||||
time.sleep(2)
|
||||
|
||||
|
||||
def replay_failed(ident):
|
||||
with connect_db() as db:
|
||||
with db.transaction():
|
||||
row = db.execute("SELECT * FROM processing_jobs WHERE attachment_id=%s FOR UPDATE", (ident,)).fetchone()
|
||||
if not row or row["status"] != "failed":
|
||||
raise RuntimeError("Only failed jobs may be explicitly replayed")
|
||||
attachment = db.execute("SELECT staging_key FROM attachments WHERE id=%s", (ident,)).fetchone()
|
||||
if not attachment or not attachment["staging_key"]:
|
||||
raise RuntimeError("Retained staging is required for replay")
|
||||
db.execute("""UPDATE processing_jobs SET status='queued',attempt=1,next_run_at=now(),
|
||||
lease_token=NULL,leased_until=NULL,error_code=NULL,updated_at=now() WHERE id=%s""", (row["id"],))
|
||||
db.execute("UPDATE attachments SET status='queued',error_code=NULL,updated_at=now() WHERE id=%s", (ident,))
|
||||
queue_outbox(db, row["id"], ident, row["pipeline_version"], 1)
|
||||
db.execute("INSERT INTO job_replay_audit(id,job_id) VALUES (%s,%s)", (str(uuid.uuid4()), row["id"]))
|
||||
print("Replayed failed job", ident)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("mode", choices=["dispatch", "worker", "replay", "status"])
|
||||
parser.add_argument("--id", help="UUID for explicit operator replay/status")
|
||||
args = parser.parse_args()
|
||||
from .secrets import load_runtime_secrets
|
||||
load_runtime_secrets(os.environ.get("BAO_ROLE"))
|
||||
if args.mode == "dispatch":
|
||||
ot.init("dispatcher")
|
||||
dispatch_loop()
|
||||
elif args.mode == "worker":
|
||||
ot.init("worker")
|
||||
worker_loop()
|
||||
elif args.mode in ("replay", "status"):
|
||||
if not args.id:
|
||||
parser.error("--id is required")
|
||||
ident = str(uuid.UUID(args.id))
|
||||
if args.mode == "replay":
|
||||
replay_failed(ident)
|
||||
else:
|
||||
with connect_db() as db:
|
||||
print(json.dumps(db.execute("SELECT status,attempt,error_code FROM processing_jobs WHERE attachment_id=%s", (ident,)).fetchone(), default=str))
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
"""FastAPI process: one stateless replica. No auto-migration on startup."""
|
||||
import logging
|
||||
import uuid
|
||||
import time
|
||||
from starlette.routing import Match
|
||||
from opentelemetry.trace import SpanKind, Status, StatusCode
|
||||
from . import telemetry as ot
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
import psycopg
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
from redis.exceptions import RedisError
|
||||
|
||||
from .api import router
|
||||
from .attachments import router as attachment_router
|
||||
from .auth import challenge, current_user
|
||||
from .core import APIError, INSTANCE_ID, error_body, invalid, request_id
|
||||
from .storage import start, stop
|
||||
|
||||
logging.basicConfig(level="INFO")
|
||||
logger = logging.getLogger("lab5")
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
from .secrets import load_runtime_secrets
|
||||
load_runtime_secrets("api")
|
||||
ot.init("api")
|
||||
start()
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
stop()
|
||||
ot.flush()
|
||||
|
||||
app = FastAPI(
|
||||
title="MTUCI Messenger Lab 7",
|
||||
docs_url=None,
|
||||
redoc_url=None,
|
||||
openapi_url=None,
|
||||
lifespan=lifespan,
|
||||
telemetry={
|
||||
"tracing": False,
|
||||
"metrics": False,
|
||||
"logs": False,
|
||||
"operation_spans": False,
|
||||
"auto_configure": False,
|
||||
},
|
||||
)
|
||||
app.include_router(router)
|
||||
app.include_router(attachment_router)
|
||||
|
||||
PROTECTED = ("/api/v1/chats", "/api/v1/attachments", "/api/v1/users/me", "/api/v1/auth/sessions/current")
|
||||
JSON_POST = ("/api/v1/users", "/api/v1/chats")
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def request_context(req: Request, call_next):
|
||||
# Match the registered template even when early authentication fails.
|
||||
route = next(
|
||||
(
|
||||
r.path
|
||||
for source in (router, attachment_router)
|
||||
for r in source.routes
|
||||
if r.matches(req.scope)[0] == Match.FULL
|
||||
),
|
||||
"unmatched",
|
||||
)
|
||||
method = req.method if req.method in ('GET','POST','DELETE','PUT','PATCH','HEAD','OPTIONS') else 'OTHER'
|
||||
attrs = {'method': method, 'route': route}
|
||||
start_at = time.monotonic()
|
||||
if route in ("/health/live", "/health/ready"):
|
||||
response = await handle_request(req, call_next)
|
||||
attrs["status_class"] = str(response.status_code//100)+"xx"
|
||||
ot.count("lab_http_requests", attrs)
|
||||
ot.observe("lab_http_duration", time.monotonic()-start_at, attrs)
|
||||
return response
|
||||
with ot.span(method+' '+route, kind=SpanKind.SERVER, attrs={'http.request.method':method,'http.route':route}) as span:
|
||||
response = await handle_request(req, call_next)
|
||||
attrs['status_class'] = str(response.status_code//100)+'xx'
|
||||
span.set_attribute('http.response.status_code', response.status_code)
|
||||
if response.status_code >= 500:
|
||||
span.set_status(Status(StatusCode.ERROR))
|
||||
ot.count('lab_http_requests', attrs)
|
||||
ot.observe('lab_http_duration', time.monotonic()-start_at, attrs)
|
||||
ot.event('http.completed', level=logging.ERROR if response.status_code >= 500 else logging.INFO,
|
||||
request_id=request_id(req), route=route, method=method, status_code=response.status_code)
|
||||
if ot.trace_id():
|
||||
response.headers['X-Trace-Id'] = ot.trace_id()
|
||||
return response
|
||||
|
||||
|
||||
async def handle_request(req: Request, call_next):
|
||||
req.state.request_id = uuid.uuid4().hex
|
||||
try:
|
||||
# Reject oversized bodies before parsing, decoding, authentication side effects.
|
||||
raw_length=req.headers.get("content-length")
|
||||
if raw_length is not None:
|
||||
try:
|
||||
length=int(raw_length)
|
||||
if length < 0: raise ValueError()
|
||||
except ValueError:
|
||||
raise APIError(400,"invalid_request","Invalid Content-Length") from None
|
||||
if length > 11 * 1024 * 1024:
|
||||
raise APIError(413,"payload_too_large","Request too large")
|
||||
path = req.url.path
|
||||
# Authenticate before parsing the request body or resource-specific fields.
|
||||
if any(path == p or path.startswith(p + "/") for p in PROTECTED):
|
||||
req.state.actor = await run_in_threadpool(current_user, req)
|
||||
if req.method == "POST" and (path in JSON_POST or (path.startswith("/api/v1/chats/") and path.endswith("/messages"))):
|
||||
if req.headers.get("content-type", "").split(";", 1)[0].strip().lower() != "application/json":
|
||||
raise APIError(415, "unsupported_media_type", "Content-Type must be application/json")
|
||||
if req.method == "POST" and path == "/api/v1/auth/sessions" and await req.body():
|
||||
raise invalid("Login body is not allowed")
|
||||
response = await call_next(req)
|
||||
except APIError as exc:
|
||||
response = api_error(req, exc)
|
||||
except (RedisError, psycopg.OperationalError, psycopg.InterfaceError):
|
||||
response = api_error(req, APIError(503, "unavailable", "Dependency unavailable"))
|
||||
except Exception:
|
||||
logger.exception("unexpected request failure id=%s", request_id(req))
|
||||
response = api_error(req, APIError(500, "internal_error", "Internal server error"))
|
||||
response.headers["X-Request-Id"] = request_id(req)
|
||||
response.headers["X-Instance-Id"] = INSTANCE_ID
|
||||
return response
|
||||
|
||||
|
||||
def api_error(req: Request, exc: APIError) -> JSONResponse:
|
||||
headers = {"WWW-Authenticate": challenge(req)} if exc.status == 401 else {}
|
||||
if exc.status == 429:
|
||||
headers["Retry-After"] = "60"
|
||||
return JSONResponse(status_code=exc.status, content=error_body(req, exc.code, exc.message), headers=headers)
|
||||
|
||||
|
||||
@app.exception_handler(APIError)
|
||||
async def api_error_handler(req: Request, exc: APIError):
|
||||
return api_error(req, exc)
|
||||
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_error_handler(req: Request, exc: RequestValidationError):
|
||||
return api_error(req, invalid())
|
||||
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def unexpected_error_handler(req: Request, exc: Exception):
|
||||
logger.exception("handler failure id=%s", request_id(req))
|
||||
if isinstance(exc, (psycopg.OperationalError, psycopg.InterfaceError, RedisError)):
|
||||
return api_error(req, APIError(503, "unavailable", "Dependency unavailable"))
|
||||
return api_error(req, APIError(500, "internal_error", "Internal server error"))
|
||||
@@ -0,0 +1,23 @@
|
||||
"""Run once before API instances; transactional and advisory-lock coordinated migrations."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import psycopg
|
||||
|
||||
MIGRATIONS = Path(__file__).resolve().parents[1] / "db" / "migrations"
|
||||
|
||||
def main():
|
||||
with psycopg.connect(os.environ["DATABASE_URL"], autocommit=False) as conn:
|
||||
with conn.transaction():
|
||||
conn.execute("SELECT pg_advisory_xact_lock(62132103)")
|
||||
conn.execute("CREATE TABLE IF NOT EXISTS schema_migrations(version TEXT PRIMARY KEY, applied_at TIMESTAMPTZ NOT NULL DEFAULT now())")
|
||||
for path in sorted(MIGRATIONS.glob("[0-9]*.sql")):
|
||||
applied = conn.execute("SELECT 1 FROM schema_migrations WHERE version=%s", (path.name,)).fetchone()
|
||||
if applied:
|
||||
continue
|
||||
conn.execute(path.read_text(encoding="utf-8"))
|
||||
conn.execute("INSERT INTO schema_migrations(version) VALUES (%s)", (path.name,))
|
||||
print("Applied", path.name, flush=True)
|
||||
print("Migrations up to date", flush=True)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,77 @@
|
||||
"""HTTP request models; all strings use Unicode code point limits."""
|
||||
import re
|
||||
import uuid
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
|
||||
|
||||
USERNAME_RE = re.compile(r"^[a-z0-9_]{3,32}$")
|
||||
|
||||
class StrictModel(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", strict=True)
|
||||
|
||||
class CreateUser(StrictModel):
|
||||
username: str
|
||||
display_name: str = Field(min_length=1, max_length=100)
|
||||
password: str = Field(min_length=12, max_length=128)
|
||||
|
||||
@field_validator("username")
|
||||
@classmethod
|
||||
def username_valid(cls, value: str) -> str:
|
||||
if not USERNAME_RE.fullmatch(value):
|
||||
raise ValueError("Invalid username")
|
||||
return value
|
||||
|
||||
@field_validator("display_name", "password")
|
||||
@classmethod
|
||||
def non_blank(cls, value: str) -> str:
|
||||
if not value.strip():
|
||||
raise ValueError("Blank value")
|
||||
value.encode("utf-8", errors="strict")
|
||||
return value
|
||||
|
||||
class CreateChat(StrictModel):
|
||||
title: str = Field(min_length=1, max_length=100)
|
||||
member_ids: list[str] = Field(min_length=1, max_length=100)
|
||||
|
||||
@field_validator("title")
|
||||
@classmethod
|
||||
def non_blank(cls, value: str) -> str:
|
||||
if not value.strip():
|
||||
raise ValueError("Blank title")
|
||||
value.encode("utf-8", errors="strict")
|
||||
return value
|
||||
|
||||
@field_validator("member_ids")
|
||||
@classmethod
|
||||
def uuid_members(cls, value: list[str]) -> list[str]:
|
||||
for member in value:
|
||||
if not isinstance(member, str) or str(uuid.UUID(member)) != member:
|
||||
raise ValueError("Invalid member UUID")
|
||||
if len(value) != len(set(value)):
|
||||
raise ValueError("Duplicate member")
|
||||
return value
|
||||
|
||||
class CreateMessage(StrictModel):
|
||||
text: str = Field(min_length=0, max_length=4000)
|
||||
attachment_ids: list[str] = Field(default_factory=list, max_length=10)
|
||||
|
||||
@field_validator("text")
|
||||
@classmethod
|
||||
def non_blank(cls, value: str) -> str:
|
||||
value.encode("utf-8", errors="strict")
|
||||
return value
|
||||
|
||||
@field_validator("attachment_ids")
|
||||
@classmethod
|
||||
def valid_attachments(cls, value: list[str]) -> list[str]:
|
||||
if len(value) != len(set(value)):
|
||||
raise ValueError("Duplicate attachment IDs")
|
||||
for item in value:
|
||||
if not isinstance(item, str) or str(uuid.UUID(item)) != item:
|
||||
raise ValueError("Invalid attachment UUID")
|
||||
return value
|
||||
|
||||
@model_validator(mode="after")
|
||||
def nonempty_message(self):
|
||||
if not self.text.strip() and not self.attachment_ids:
|
||||
raise ValueError("Empty message")
|
||||
return self
|
||||
@@ -0,0 +1,25 @@
|
||||
"""Offline image conversion tests inside the application image; no S3 or DB."""
|
||||
import io
|
||||
from PIL import Image
|
||||
from .image_worker import transform
|
||||
|
||||
|
||||
def main():
|
||||
source = Image.new('RGB',(320,200), (255,0,0))
|
||||
buf=io.BytesIO();source.save(buf,'PNG')
|
||||
result=transform(buf.getvalue())
|
||||
items={name:(img,fmt,mime,opts) for name,img,fmt,mime,opts in result}
|
||||
assert set(items)=={'thumbnail','crop','optimized'}
|
||||
assert items['thumbnail'][0].size==(256,160)
|
||||
assert items['crop'][0].size==(128,128)
|
||||
assert items['optimized'][0].size==(320,200)
|
||||
for name,(im,fmt,mime,opts) in items.items():
|
||||
data=io.BytesIO();im.save(data,format=fmt,**opts)
|
||||
with Image.open(io.BytesIO(data.getvalue())) as decoded:
|
||||
assert decoded.size==im.size
|
||||
assert decoded.format==fmt
|
||||
assert 'exif' not in decoded.info
|
||||
print('PASS: PNG 320x200 -> JPEG thumb 256x160, crop 128x128, optimized WebP, metadata stripped')
|
||||
|
||||
if __name__=='__main__':
|
||||
main()
|
||||
@@ -0,0 +1,21 @@
|
||||
"""Operator one-shot: separated broker identities and queue permissions."""
|
||||
import os, json, base64, urllib.request
|
||||
|
||||
def main():
|
||||
username=os.environ['BROKER_ADMIN_USER']
|
||||
password=os.environ['BROKER_ADMIN_PASSWORD']
|
||||
auth='Basic '+base64.b64encode((username+':'+password).encode()).decode()
|
||||
def put(path, body):
|
||||
req=urllib.request.Request('http://broker:15672/api/'+path,
|
||||
data=json.dumps(body).encode(),headers={'Authorization':auth,'Content-Type':'application/json'},method='PUT')
|
||||
with urllib.request.urlopen(req,timeout=10) as resp: resp.read()
|
||||
for role in ('DISPATCHER','WORKER'):
|
||||
user=os.environ['BROKER_'+role+'_USER']
|
||||
put('users/'+user,{'password':os.environ['BROKER_'+role+'_PASSWORD'],'tags':''})
|
||||
# AMQP queue declaration/bind/read/write needed for durable pipeline.
|
||||
# Distinct users allow individual revocation; constrained to the one job queue.
|
||||
put('permissions/%2F/'+user, {'configure':r'^attachment-processing\.v1$',
|
||||
'read':r'^attachment-processing\.v1$' if role=='WORKER' else '^$',
|
||||
'write':r'^amq\.default$' if role=='DISPATCHER' else '^$'})
|
||||
print('Broker scoped users created (credentials omitted)')
|
||||
if __name__=='__main__': main()
|
||||
@@ -0,0 +1,132 @@
|
||||
"""Lab4 grade-5 track 2: repeatable DB/S3 reconciliation.
|
||||
|
||||
Dry-run is default. Apply never drops metadata when BOTH object copies are gone:
|
||||
without a trustworthy copy or external backup, deletion would destroy evidence.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
|
||||
from .attachments import BUCKET, s3_client
|
||||
|
||||
|
||||
def inventory(client):
|
||||
result = {}
|
||||
for page in client.get_paginator("list_objects_v2").paginate(Bucket=BUCKET):
|
||||
for obj in page.get("Contents", []):
|
||||
# Only reconciliation-owned prefixes; never mutate arbitrary S3 keys.
|
||||
key = obj["Key"]
|
||||
if key.startswith(("attachments/", "recovery/")):
|
||||
result[key] = obj["LastModified"]
|
||||
return result
|
||||
|
||||
|
||||
def get_db_rows(conn):
|
||||
return conn.execute("SELECT id, object_key, backup_key, status FROM attachments").fetchall()
|
||||
|
||||
|
||||
def current_reference(conn, key):
|
||||
return conn.execute(
|
||||
"SELECT 1 FROM attachments WHERE object_key=%s OR backup_key=%s", (key, key)
|
||||
).fetchone() is not None
|
||||
|
||||
|
||||
def reconcile(*, apply=False, grace_seconds=300, now=None, client=None, connect=None):
|
||||
if grace_seconds < 300 and apply:
|
||||
raise ValueError("Apply requires >=300 s grace period to protect in-flight uploads")
|
||||
started = time.monotonic()
|
||||
now = now or datetime.now(timezone.utc)
|
||||
client = client or s3_client()
|
||||
connect = connect or (lambda: psycopg.connect(__import__('os').environ['DATABASE_URL'], row_factory=dict_row))
|
||||
objects = inventory(client)
|
||||
stats = {
|
||||
"mode": "apply" if apply else "dry-run", "grace_seconds": grace_seconds,
|
||||
"s3_keys_scanned": len(objects), "db_rows_scanned": 0,
|
||||
"orphan_keys": [], "orphan_keys_young": [],
|
||||
"missing_primary_repairable": [], "missing_backup_repairable": [],
|
||||
"missing_both_unrecoverable": [], "actions": [], "errors": [],
|
||||
}
|
||||
with connect() as conn:
|
||||
rows = get_db_rows(conn)
|
||||
stats["db_rows_scanned"] = len(rows)
|
||||
references = {key for row in rows for key in (row["object_key"], row["backup_key"])}
|
||||
for row in rows:
|
||||
if row["status"] != "ready":
|
||||
continue # queued/processing have durable staging, not final variants yet
|
||||
primary, backup = row["object_key"], row["backup_key"]
|
||||
have_primary, have_backup = primary in objects, backup in objects
|
||||
rid = str(row["id"])
|
||||
if have_primary and have_backup:
|
||||
continue
|
||||
if not have_primary and not have_backup:
|
||||
stats["missing_both_unrecoverable"].append(rid)
|
||||
continue
|
||||
dest, source, typ = (primary, backup, "missing_primary_repairable") if not have_primary else (backup, primary, "missing_backup_repairable")
|
||||
stats[typ].append(rid)
|
||||
if apply:
|
||||
# Defensive recheck. Object may have reappeared after inventory.
|
||||
try:
|
||||
client.head_object(Bucket=BUCKET, Key=dest)
|
||||
stats["actions"].append({"action": "already-restored", "key": dest})
|
||||
continue
|
||||
except ClientError as exc:
|
||||
code = exc.response.get("Error", {}).get("Code")
|
||||
if code not in ("404", "NotFound", "NoSuchKey"):
|
||||
raise
|
||||
try:
|
||||
client.copy_object(Bucket=BUCKET, Key=dest,
|
||||
CopySource={"Bucket": BUCKET, "Key": source})
|
||||
stats["actions"].append({"action": "restore", "key": dest, "from": source})
|
||||
except (BotoCoreError, ClientError) as exc:
|
||||
stats["errors"].append({"action": "restore", "key": dest, "error_type": type(exc).__name__})
|
||||
for key, modified in objects.items():
|
||||
if key in references:
|
||||
continue
|
||||
age = (now - modified).total_seconds()
|
||||
if age < grace_seconds:
|
||||
stats["orphan_keys_young"].append(key)
|
||||
continue
|
||||
stats["orphan_keys"].append(key)
|
||||
if apply:
|
||||
# Query again immediately before destructive action; never delete
|
||||
# an object now referenced by a committed metadata row.
|
||||
if current_reference(conn, key):
|
||||
stats["actions"].append({"action": "skip-now-referenced", "key": key})
|
||||
continue
|
||||
try:
|
||||
client.delete_object(Bucket=BUCKET, Key=key)
|
||||
stats["actions"].append({"action": "delete-old-orphan", "key": key})
|
||||
except (BotoCoreError, ClientError) as exc:
|
||||
stats["errors"].append({"action": "delete-old-orphan", "key": key, "error_type": type(exc).__name__})
|
||||
stats["scan_elapsed_seconds"] = round(time.monotonic() - started, 3)
|
||||
return stats
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Reconcile S3 attachments vs PostgreSQL (dry-run default)")
|
||||
parser.add_argument("--apply", action="store_true", help="Make safe changes; orphans older than 300 seconds only")
|
||||
parser.add_argument("--grace-seconds", type=int, default=300)
|
||||
parser.add_argument("--output", help="Write JSON summary (no credentials)")
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
result = reconcile(apply=args.apply, grace_seconds=args.grace_seconds)
|
||||
except Exception as exc:
|
||||
# No exception string: botocore errors may contain signed credentials/URLs.
|
||||
print(json.dumps({"status":"failed", "error_type":type(exc).__name__}), file=sys.stderr)
|
||||
raise SystemExit(2) from None
|
||||
rendered = json.dumps(result, ensure_ascii=False, indent=2)
|
||||
print(rendered)
|
||||
if args.output:
|
||||
with open(args.output, "w", encoding="utf-8") as fh:
|
||||
fh.write(rendered + "\n")
|
||||
if result["errors"] or result["missing_both_unrecoverable"]:
|
||||
raise SystemExit(1)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,36 @@
|
||||
"""Operator-only fault injection in a LOCAL TEST stack; never exposed as HTTP."""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import uuid
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
from .attachments import BUCKET, s3_client
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("action", choices=["delete-primary", "delete-backup", "create-orphan"])
|
||||
p.add_argument("--id", help="Attachment UUID for the delete actions")
|
||||
args = p.parse_args()
|
||||
if os.environ.get("LAB4_ALLOW_FAULT_INJECTION") != "yes":
|
||||
raise SystemExit("Fault injection disabled; use LAB4_ALLOW_FAULT_INJECTION=yes in isolated test")
|
||||
client = s3_client()
|
||||
if args.action == "create-orphan":
|
||||
key = f"attachments/{uuid.uuid4()}/original"
|
||||
client.put_object(Bucket=BUCKET, Key=key, Body=b"synthetic orphan")
|
||||
print(json.dumps({"fault":"orphan-created", "object_key":key}))
|
||||
return
|
||||
if not args.id:
|
||||
raise SystemExit("--id is required")
|
||||
ident = str(uuid.UUID(args.id))
|
||||
with psycopg.connect(os.environ["DATABASE_URL"], row_factory=dict_row) as conn:
|
||||
row = conn.execute("SELECT object_key,backup_key FROM attachments WHERE id=%s", (ident,)).fetchone()
|
||||
if not row:
|
||||
raise SystemExit("Attachment does not exist")
|
||||
key = row["object_key"] if args.action == "delete-primary" else row["backup_key"]
|
||||
client.delete_object(Bucket=BUCKET, Key=key)
|
||||
print(json.dumps({"fault":args.action, "object_key":key}))
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,61 @@
|
||||
"""Fast isolated tests for reconciliation safety; run in application image."""
|
||||
import uuid
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from .reconcile import reconcile
|
||||
from .attachments import BUCKET
|
||||
|
||||
NOW = datetime.now(timezone.utc)
|
||||
|
||||
class FakeConn:
|
||||
def __init__(self, rows): self.rows=rows
|
||||
def __enter__(self): return self
|
||||
def __exit__(self,*a): return False
|
||||
def execute(self, sql, args=None):
|
||||
self.sql=sql
|
||||
self.args=args
|
||||
return self
|
||||
def fetchall(self): return self.rows
|
||||
def fetchone(self):
|
||||
key=self.args[0]
|
||||
return {'id': 1} if any(key in (row['object_key'],row['backup_key']) for row in self.rows) else None
|
||||
|
||||
class FakeS3:
|
||||
def __init__(self,objects): self.objects=objects
|
||||
def get_paginator(self,op): return self
|
||||
def paginate(self,**kwargs):
|
||||
yield {'Contents':[{'Key':k,'LastModified':t} for k,t in self.objects.items()]}
|
||||
def head_object(self,**kw):
|
||||
if kw['Key'] not in self.objects:
|
||||
from botocore.exceptions import ClientError
|
||||
raise ClientError({'Error':{'Code':'404'}},'HeadObject')
|
||||
def copy_object(self,**kw):
|
||||
assert kw['CopySource']['Key'] in self.objects
|
||||
self.objects[kw['Key']]=NOW
|
||||
def delete_object(self,**kw):
|
||||
self.objects.pop(kw['Key'],None)
|
||||
|
||||
|
||||
def test():
|
||||
i=str(uuid.uuid4())
|
||||
primary=f'attachments/{i}/original';backup=f'recovery/{i}/original'
|
||||
young=f'attachments/{uuid.uuid4()}/original'
|
||||
old=f'attachments/{uuid.uuid4()}/original'
|
||||
rows=[{'id':i,'object_key':primary,'backup_key':backup,'status':'ready'}]
|
||||
fake=FakeS3({backup: NOW-timedelta(days=1),young:NOW-timedelta(seconds=10),old:NOW-timedelta(days=1)})
|
||||
kwargs={'now':NOW,'client':fake,'connect':lambda:FakeConn(rows)}
|
||||
first=reconcile(apply=False,**kwargs)
|
||||
assert first['missing_primary_repairable']==[i]
|
||||
assert old in first['orphan_keys'] and young in first['orphan_keys_young']
|
||||
assert primary not in fake.objects and old in fake.objects, 'Dry run mutated objects'
|
||||
second=reconcile(apply=True,**kwargs)
|
||||
assert primary in fake.objects and old not in fake.objects and young in fake.objects
|
||||
assert any(x['action']=='restore' for x in second['actions'])
|
||||
third=reconcile(apply=True,**kwargs)
|
||||
assert not third['actions'], 'Re-run unexpectedly mutated objects'
|
||||
assert rows[0]['object_key']==primary, 'Metadata destroyed'
|
||||
try: reconcile(apply=True, grace_seconds=0, **kwargs)
|
||||
except ValueError: pass
|
||||
else: raise AssertionError('Unsafe zero-grace apply accepted')
|
||||
print('PASS: dry-run, orphan grace, recover primary from backup, apply idempotence')
|
||||
|
||||
if __name__ == '__main__': test()
|
||||
@@ -0,0 +1,35 @@
|
||||
"""Idempotently create the private S3 bucket with bootstrap-only credentials."""
|
||||
import os
|
||||
import time
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
from botocore.exceptions import ClientError, BotoCoreError
|
||||
|
||||
|
||||
def main():
|
||||
bucket = os.environ["S3_BUCKET"]
|
||||
client = boto3.client("s3", endpoint_url=os.environ["S3_ENDPOINT"],
|
||||
aws_access_key_id=os.environ["S3_ADMIN_ACCESS_KEY"],
|
||||
aws_secret_access_key=os.environ["S3_ADMIN_SECRET_KEY"],
|
||||
region_name="us-east-1", verify=os.environ["TLS_CA_FILE"],
|
||||
config=Config(s3={"addressing_style": "path"},
|
||||
connect_timeout=2, read_timeout=4, retries={"max_attempts": 1}))
|
||||
for attempt in range(70):
|
||||
try:
|
||||
try:
|
||||
client.head_bucket(Bucket=bucket)
|
||||
except ClientError as exc:
|
||||
code = exc.response.get("Error", {}).get("Code", "")
|
||||
if code not in ("404", "NoSuchBucket", "NotFound"):
|
||||
raise
|
||||
client.create_bucket(Bucket=bucket)
|
||||
# PRIVATE: no public bucket policy, ACL or anonymous identity.
|
||||
print(f"Private bucket {bucket} ready", flush=True)
|
||||
return
|
||||
except (ClientError, BotoCoreError, OSError) as exc:
|
||||
if attempt == 69:
|
||||
raise RuntimeError("S3 bootstrap failed; inspect S3 container") from exc
|
||||
time.sleep(1)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,38 @@
|
||||
"""One-off creation of private SeaweedFS S3 identities; secrets stay in Docker volume."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def main():
|
||||
bucket = os.environ["S3_BUCKET"]
|
||||
identities = [
|
||||
{"name": "bucket-bootstrap", "credentials": [{"accessKey": os.environ["S3_ADMIN_ACCESS_KEY"],
|
||||
"secretKey": os.environ["S3_ADMIN_SECRET_KEY"]}],
|
||||
"actions": ["Admin", "Read", "Write", "List"]},
|
||||
{"name": "messenger-api", "credentials": [{"accessKey": os.environ["S3_API_ACCESS_KEY"],
|
||||
"secretKey": os.environ["S3_API_SECRET_KEY"]}],
|
||||
"actions": [f"Read:{bucket}", f"Write:{bucket}", f"List:{bucket}"]},
|
||||
{"name": "messenger-worker", "credentials": [{"accessKey": os.environ["S3_WORKER_ACCESS_KEY"],
|
||||
"secretKey": os.environ["S3_WORKER_SECRET_KEY"]}],
|
||||
"actions": [f"Read:{bucket}", f"Write:{bucket}", f"List:{bucket}"]},
|
||||
{"name": "messenger-dispatcher", "credentials": [{"accessKey": os.environ["S3_DISPATCHER_ACCESS_KEY"],
|
||||
"secretKey": os.environ["S3_DISPATCHER_SECRET_KEY"]}],
|
||||
"actions": [f"Read:{bucket}", f"Write:{bucket}", f"List:{bucket}"]},
|
||||
]
|
||||
if len({entry["credentials"][0]["accessKey"] for entry in identities}) != 4:
|
||||
raise ValueError("Admin and API credentials must differ")
|
||||
path = Path("/s3-config/config.json")
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp = path.with_suffix(".tmp")
|
||||
old_umask = os.umask(0o077)
|
||||
try:
|
||||
tmp.write_text(json.dumps({"identities": identities}, separators=(",", ":")), encoding="utf-8")
|
||||
os.chmod(tmp, 0o644) # readable by the SeaweedFS runtime UID; Docker volume stays private
|
||||
os.replace(tmp, path)
|
||||
finally:
|
||||
os.umask(old_umask)
|
||||
print("S3 identities configured (no secrets printed)", flush=True)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,40 @@
|
||||
"""Verify bucket is private at S3 boundary (not merely hidden behind HTTP API)."""
|
||||
import json
|
||||
import os
|
||||
import boto3
|
||||
from botocore import UNSIGNED
|
||||
from botocore.config import Config
|
||||
from botocore.exceptions import ClientError
|
||||
from .attachments import BUCKET, s3_client
|
||||
|
||||
|
||||
def main():
|
||||
client = s3_client()
|
||||
client.head_bucket(Bucket=BUCKET) # restricted app identity works
|
||||
unauth = boto3.client("s3", endpoint_url=os.environ["S3_ENDPOINT"],
|
||||
region_name="us-east-1", config=Config(signature_version=UNSIGNED,
|
||||
s3={"addressing_style":"path"}))
|
||||
try:
|
||||
unauth.list_objects_v2(Bucket=BUCKET, MaxKeys=1)
|
||||
except ClientError as exc:
|
||||
status = exc.response.get("ResponseMetadata", {}).get("HTTPStatusCode")
|
||||
if status not in (401,403):
|
||||
raise RuntimeError("Unexpected anonymous S3 response") from None
|
||||
else:
|
||||
raise RuntimeError("Private bucket leaked object list to anonymous caller")
|
||||
listing = client.list_objects_v2(Bucket=BUCKET, MaxKeys=1)
|
||||
keys = [entry["Key"] for entry in listing.get("Contents", [])]
|
||||
if keys:
|
||||
try:
|
||||
unauth.get_object(Bucket=BUCKET, Key=keys[0])
|
||||
except ClientError as exc:
|
||||
status = exc.response.get("ResponseMetadata", {}).get("HTTPStatusCode")
|
||||
if status not in (401, 403):
|
||||
raise RuntimeError("Unexpected anonymous object GET response") from None
|
||||
else:
|
||||
raise RuntimeError("Private S3 object downloadable anonymously")
|
||||
print(json.dumps({"private_bucket": True, "anonymous_listing": "denied",
|
||||
"anonymous_object_get": "denied" if keys else "not_tested_empty_bucket"}))
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,47 @@
|
||||
"""Fail-closed OpenBao AppRole bootstrap; token exists only in process memory.
|
||||
|
||||
Never fall back to .env, a root token, or plaintext if OpenBao is sealed.
|
||||
Credentials are fetched on startup; rotating a KV value requires a controlled
|
||||
service restart, not a Docker image rebuild. Running processes keep their last
|
||||
valid DB/S3 credentials through a temporary Bao outage.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import ssl
|
||||
from pathlib import Path
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
ALLOWED = {
|
||||
'api': {'DATABASE_URL','REDIS_URL','S3_ENDPOINT','S3_BUCKET','S3_ACCESS_KEY','S3_SECRET_KEY'},
|
||||
'worker': {'DATABASE_URL','S3_ENDPOINT','S3_BUCKET','S3_ACCESS_KEY','S3_SECRET_KEY',
|
||||
'BROKER_HOST','BROKER_PORT','BROKER_USER','BROKER_PASSWORD'},
|
||||
'dispatcher': {'DATABASE_URL','S3_ENDPOINT','S3_BUCKET','S3_ACCESS_KEY','S3_SECRET_KEY',
|
||||
'BROKER_HOST','BROKER_PORT','BROKER_USER','BROKER_PASSWORD'},
|
||||
}
|
||||
|
||||
def _json_request(url, context, payload=None, token=None):
|
||||
headers={'Accept':'application/json'}
|
||||
if payload is not None: headers['Content-Type']='application/json'
|
||||
if token: headers['X-Vault-Token']=token
|
||||
req=Request(url, data=json.dumps(payload).encode('utf-8') if payload is not None else None,
|
||||
headers=headers,method='POST' if payload is not None else 'GET')
|
||||
with urlopen(req,context=context,timeout=7) as r:
|
||||
return json.load(r)
|
||||
|
||||
def load_runtime_secrets(role=None):
|
||||
role=role or os.getenv('BAO_ROLE')
|
||||
if role not in ALLOWED: raise RuntimeError('Invalid service secret role')
|
||||
addr=os.environ.get('BAO_ADDR','https://openbao:8200').rstrip('/')
|
||||
if not addr.startswith('https://'): raise RuntimeError('OpenBao transport must be TLS')
|
||||
context=ssl.create_default_context(cafile=os.environ['TLS_CA_FILE'])
|
||||
role_id=Path(os.environ['BAO_ROLE_ID_FILE']).read_text().strip()
|
||||
secret_id=Path(os.environ['BAO_SECRET_ID_FILE']).read_text().strip()
|
||||
if not role_id or not secret_id: raise RuntimeError('Missing AppRole credentials')
|
||||
auth=_json_request(addr+'/v1/auth/approle/login',context,{'role_id':role_id,'secret_id':secret_id})
|
||||
token=auth['auth']['client_token']
|
||||
if int(auth['auth']['lease_duration'])<=0: raise RuntimeError('AppRole token must have finite TTL')
|
||||
data=_json_request(addr+'/v1/kv/data/'+role,context,token=token)['data']['data']
|
||||
if set(data)!=ALLOWED[role] or not all(isinstance(x,str) and x for x in data.values()):
|
||||
raise RuntimeError('OpenBao returned missing/extra/invalid credential fields')
|
||||
os.environ.update(data)
|
||||
return role
|
||||
@@ -0,0 +1,67 @@
|
||||
"""Shared external state: psycopg connection pool and Redis session store."""
|
||||
import os
|
||||
from contextlib import contextmanager
|
||||
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg_pool import ConnectionPool, PoolTimeout
|
||||
from redis import Redis
|
||||
from redis.exceptions import RedisError
|
||||
|
||||
from .core import APIError
|
||||
from . import telemetry as ot
|
||||
from opentelemetry.trace import SpanKind
|
||||
|
||||
pool: ConnectionPool | None = None
|
||||
redis_client: Redis | None = None
|
||||
|
||||
|
||||
def start() -> None:
|
||||
global pool, redis_client
|
||||
url = os.environ["DATABASE_URL"]
|
||||
size = int(os.getenv("DB_POOL_MAX", "8"))
|
||||
pool = ConnectionPool(conninfo=url, min_size=1, max_size=size, timeout=3, kwargs={"row_factory": dict_row, "connect_timeout": 5, "options": "-c statement_timeout=5000"}, open=False)
|
||||
pool.open(wait=True, timeout=30)
|
||||
redis_client = Redis.from_url(os.environ.get("REDIS_URL", "redis://redis:6379/0"), socket_connect_timeout=2, socket_timeout=2, decode_responses=True)
|
||||
redis_client.ping()
|
||||
|
||||
|
||||
def stop() -> None:
|
||||
global pool, redis_client
|
||||
if pool is not None:
|
||||
pool.close()
|
||||
pool = None
|
||||
if redis_client is not None:
|
||||
redis_client.close()
|
||||
redis_client = None
|
||||
|
||||
|
||||
@contextmanager
|
||||
def db():
|
||||
if pool is None:
|
||||
raise APIError(503, "unavailable", "Database unavailable")
|
||||
try:
|
||||
with ot.dependency_span("db.transaction", kind=SpanKind.CLIENT, attrs={"db.system.name":"postgresql"}):
|
||||
with pool.connection() as conn:
|
||||
yield conn
|
||||
except (psycopg.OperationalError, psycopg.InterfaceError, psycopg.errors.QueryCanceled, PoolTimeout) as exc:
|
||||
raise APIError(503, "unavailable", "Database unavailable") from exc
|
||||
|
||||
|
||||
def cache() -> Redis:
|
||||
if redis_client is None:
|
||||
raise APIError(503, "unavailable", "Session store unavailable")
|
||||
return redis_client
|
||||
|
||||
|
||||
def ready() -> bool:
|
||||
try:
|
||||
with db() as conn:
|
||||
conn.execute("SELECT 1").fetchone()
|
||||
cache().ping()
|
||||
# S3 is needed for the mandatory synchronous upload/download path.
|
||||
from .attachments import s3_client, BUCKET
|
||||
s3_client().head_bucket(Bucket=BUCKET)
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
@@ -0,0 +1,210 @@
|
||||
"""Explicit, allowlisted OTLP instrumentation; no automatic headers, SQL or bodies.
|
||||
SDK exporters run asynchronously with bounded queues; telemetry is best effort.
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
import socket
|
||||
import time
|
||||
from contextlib import contextmanager, nullcontext
|
||||
from pathlib import Path
|
||||
|
||||
from opentelemetry import metrics, trace
|
||||
from opentelemetry.trace import SpanKind, Status, StatusCode
|
||||
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
|
||||
from opentelemetry.sdk.resources import Resource
|
||||
from opentelemetry.sdk.trace import TracerProvider
|
||||
from opentelemetry.sdk.trace.export import BatchSpanProcessor
|
||||
from opentelemetry.sdk.metrics import MeterProvider
|
||||
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
|
||||
from opentelemetry.sdk.metrics.view import View, ExplicitBucketHistogramAggregation
|
||||
from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler
|
||||
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
|
||||
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
|
||||
from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
|
||||
from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
|
||||
|
||||
PROP = TraceContextTextMapPropagator()
|
||||
tracer = trace.get_tracer('messenger.lab6')
|
||||
log = logging.getLogger('messenger.telemetry')
|
||||
log.setLevel(logging.INFO)
|
||||
log.propagate = False
|
||||
providers = []
|
||||
started = False
|
||||
m = None
|
||||
instruments = {}
|
||||
worker_busy = 0
|
||||
backlog_depth = None
|
||||
backlog_age = None
|
||||
broker_ready = None
|
||||
broker_consumers = None
|
||||
QUEUE = 'attachment-processing.v1'
|
||||
BUCKETS = (0.005, .01, .025, .05, .1, .25, .5, 1, 2, 3, 5, 10, 15, 30, 60, 120, 300, 600)
|
||||
|
||||
|
||||
def init(role, *, child=False):
|
||||
global started, tracer, m
|
||||
if started or os.getenv('OTEL_ENABLED', 'no') != 'yes':
|
||||
return
|
||||
started = True
|
||||
resource = Resource.create({'service.name': 'messenger-' + role,
|
||||
'service.version': '1.6.0', 'service.instance.id': os.getenv('API_INSTANCE_ID', socket.gethostname()),
|
||||
'deployment.environment.name': 'lab'})
|
||||
base = os.getenv('OTEL_EXPORTER_OTLP_ENDPOINT', 'http://otel-collector:4318').rstrip('/')
|
||||
# OTLP TLS trust + role-specific client certificate for the Collector gateway.
|
||||
tls_kw = {}
|
||||
if base.startswith("https://"):
|
||||
tls_kw = {"certificate_file": os.environ["TLS_CA_FILE"],
|
||||
"client_certificate_file": os.environ["TLS_CLIENT_CERT"],
|
||||
"client_key_file": os.environ["TLS_CLIENT_KEY"]}
|
||||
tp = TracerProvider(resource=resource)
|
||||
tp.add_span_processor(BatchSpanProcessor(OTLPSpanExporter(endpoint=base+'/v1/traces', timeout=2, **tls_kw),
|
||||
max_queue_size=512, max_export_batch_size=64, schedule_delay_millis=500, export_timeout_millis=2000))
|
||||
trace.set_tracer_provider(tp)
|
||||
tracer = tp.get_tracer('messenger.lab6')
|
||||
lp = LoggerProvider(resource=resource)
|
||||
lp.add_log_record_processor(BatchLogRecordProcessor(OTLPLogExporter(endpoint=base+'/v1/logs', timeout=2, **tls_kw),
|
||||
max_queue_size=512, max_export_batch_size=64, schedule_delay_millis=500, export_timeout_millis=2000))
|
||||
log.addHandler(LoggingHandler(logger_provider=lp))
|
||||
providers.extend([tp, lp])
|
||||
if child:
|
||||
return
|
||||
reader = PeriodicExportingMetricReader(OTLPMetricExporter(endpoint=base+'/v1/metrics', timeout=2, **tls_kw),
|
||||
export_interval_millis=3000, export_timeout_millis=2000)
|
||||
mp = MeterProvider(resource=resource, metric_readers=[reader], views=[View(instrument_name=n,
|
||||
aggregation=ExplicitBucketHistogramAggregation(boundaries=BUCKETS)) for n in
|
||||
('lab_http_duration','lab_job_duration','lab_ready_duration')])
|
||||
metrics.set_meter_provider(mp)
|
||||
providers.append(mp)
|
||||
m = mp.get_meter('messenger.lab6')
|
||||
for name in ('lab_http_requests','lab_jobs','lab_job_retries'):
|
||||
instruments[name] = m.create_counter(name)
|
||||
for name in ('lab_http_duration','lab_job_duration','lab_ready_duration'):
|
||||
instruments[name] = m.create_histogram(name, unit='s')
|
||||
if role == 'api':
|
||||
for name, key in [('lab_db_pool_used','used'),('lab_db_pool_waiting','requests_waiting'),('lab_db_pool_capacity','pool_max')]:
|
||||
m.create_observable_gauge(name, callbacks=[lambda _, key=key: pool_stats(key)])
|
||||
if role == 'worker':
|
||||
m.create_observable_gauge('lab_worker_busy', callbacks=[lambda _: [metrics.Observation(worker_busy)]])
|
||||
m.create_observable_gauge('lab_worker_capacity', callbacks=[lambda _: [metrics.Observation(1)]])
|
||||
if role == 'dispatcher':
|
||||
m.create_observable_gauge('lab_broker_ready', callbacks=[lambda _: queue_observation(broker_ready)])
|
||||
m.create_observable_gauge('lab_broker_consumers', callbacks=[lambda _: queue_observation(broker_consumers)])
|
||||
m.create_observable_gauge('lab_queue_depth', callbacks=[lambda _: queue_observation(backlog_depth)])
|
||||
m.create_observable_gauge('lab_queue_oldest_age', unit='s', callbacks=[lambda _: queue_observation(backlog_age)])
|
||||
m.create_observable_gauge('lab_container_memory', unit='By', callbacks=[lambda _: container_observation('memory')])
|
||||
m.create_observable_gauge('lab_container_cpu_cores', callbacks=[lambda _: container_observation('cpu')])
|
||||
|
||||
|
||||
def pool_stats(key):
|
||||
from . import storage
|
||||
if storage.pool is None:
|
||||
return []
|
||||
stats = storage.pool.get_stats()
|
||||
val = stats.get('pool_size',0)-stats.get('pool_available',0) if key=='used' else stats.get(key,0)
|
||||
return [metrics.Observation(max(0,val))]
|
||||
|
||||
|
||||
def queue_observation(value):
|
||||
return [] if value is None else [metrics.Observation(value, {'queue': QUEUE})]
|
||||
|
||||
|
||||
_cpu_previous = None
|
||||
|
||||
def container_observation(kind):
|
||||
global _cpu_previous
|
||||
try:
|
||||
if kind == 'memory':
|
||||
return [metrics.Observation(int(Path('/sys/fs/cgroup/memory.current').read_text()))]
|
||||
cpu = int(dict(line.split() for line in Path('/sys/fs/cgroup/cpu.stat').read_text().splitlines())['usage_usec']) / 1e6
|
||||
now = time.monotonic()
|
||||
old = _cpu_previous
|
||||
_cpu_previous = (now,cpu)
|
||||
return [] if old is None else [metrics.Observation(max(0,(cpu-old[1])/(now-old[0])))]
|
||||
except (OSError, KeyError, ValueError):
|
||||
# cgroup v1 fallback, process tree (not full container accounting).
|
||||
import psutil
|
||||
try:
|
||||
p = psutil.Process()
|
||||
processes = [p]+p.children(recursive=True)
|
||||
if kind == 'memory':
|
||||
value = 0
|
||||
for proc in processes:
|
||||
try: value += proc.memory_info().rss
|
||||
except psutil.Error: pass
|
||||
return [metrics.Observation(value)]
|
||||
# cgroup v1 (Docker Linux) if available, CPU usage in nanoseconds.
|
||||
for path in ('/sys/fs/cgroup/cpuacct/cpuacct.usage','/sys/fs/cgroup/cpu,cpuacct/cpuacct.usage'):
|
||||
if Path(path).is_file():
|
||||
cpu = int(Path(path).read_text()) / 1e9
|
||||
now = time.monotonic()
|
||||
old = _cpu_previous
|
||||
_cpu_previous = (now,cpu)
|
||||
return [] if old is None else [metrics.Observation(max(0,(cpu-old[1])/(now-old[0])))]
|
||||
except (psutil.Error,OSError,ValueError):
|
||||
pass
|
||||
return []
|
||||
|
||||
|
||||
def count(name, attrs=None):
|
||||
if name in instruments: instruments[name].add(1, attrs or {})
|
||||
|
||||
|
||||
def observe(name, value, attrs=None):
|
||||
if name in instruments: instruments[name].record(max(0,value), attrs or {})
|
||||
|
||||
|
||||
def event(name, *, level=logging.INFO, **attrs):
|
||||
# Callers pass fixed event names and technical ID/status only, never payloads.
|
||||
if started:
|
||||
log.log(level, name, extra={'event':name, **attrs})
|
||||
|
||||
|
||||
@contextmanager
|
||||
def span(name, *, kind=SpanKind.INTERNAL, context=None, attrs=None):
|
||||
with tracer.start_as_current_span(name, kind=kind, context=context, attributes=attrs,
|
||||
record_exception=False, set_status_on_exception=False) as s:
|
||||
try:
|
||||
yield s
|
||||
except BaseException as exc:
|
||||
s.set_status(Status(StatusCode.ERROR))
|
||||
s.set_attribute('error.type', type(exc).__name__)
|
||||
event('operation.error', level=logging.ERROR, operation=name, error_type=type(exc).__name__)
|
||||
raise
|
||||
|
||||
|
||||
def inject():
|
||||
result = {}
|
||||
PROP.inject(result)
|
||||
return result
|
||||
|
||||
|
||||
def extract(carrier):
|
||||
# Ignore baggage and all unrelated fields.
|
||||
return PROP.extract({k:v for k,v in carrier.items() if k in ('traceparent','tracestate') and isinstance(v,str)})
|
||||
|
||||
|
||||
def dependency_span(name, **kwargs):
|
||||
return span(name, **kwargs) if trace_id() else nullcontext()
|
||||
|
||||
|
||||
def trace_id():
|
||||
ctx = trace.get_current_span().get_span_context()
|
||||
return f'{ctx.trace_id:032x}' if ctx.is_valid else ''
|
||||
|
||||
|
||||
def flush():
|
||||
for p in providers:
|
||||
p.force_flush(timeout_millis=2500)
|
||||
|
||||
|
||||
class S3Tracing:
|
||||
"""Only operation name is exported; bucket/key/bytes/signed URLs never exported."""
|
||||
def __init__(self, client): self.client = client
|
||||
def __getattr__(self, name):
|
||||
f = getattr(self.client,name)
|
||||
if name not in ('upload_fileobj','get_object','put_object','copy_object','delete_object','head_object','head_bucket'):
|
||||
return f
|
||||
def call(*a, **kw):
|
||||
with dependency_span('s3.'+name, kind=SpanKind.CLIENT, attrs={'storage.system':'s3'}):
|
||||
return f(*a, **kw)
|
||||
return call
|
||||
+555
@@ -0,0 +1,555 @@
|
||||
# Operator secrets/PKI are in gitignored .env/.local; AppRole credentials use private Docker volumes.
|
||||
# Bootstrap: see SECURITY_RUNBOOK.md. NO HTTP app/admin ports are published.
|
||||
x-haproxy: &haproxy
|
||||
image: haproxy:3.1.7-alpine
|
||||
security_opt: ["no-new-privileges:true"]
|
||||
cap_drop: [ALL]
|
||||
read_only: true
|
||||
tmpfs: ["/tmp:rw,noexec,nosuid,size=8m"]
|
||||
mem_limit: 128m
|
||||
cpus: 0.5
|
||||
restart: unless-stopped
|
||||
x-python: &python
|
||||
image: mtusi-lab7-app:local
|
||||
build: .
|
||||
user: "999:999"
|
||||
read_only: true
|
||||
security_opt: ["no-new-privileges:true"]
|
||||
cap_drop: [ALL]
|
||||
tmpfs: ["/tmp:rw,nosuid,size=128m"]
|
||||
pids_limit: 128
|
||||
restart: unless-stopped
|
||||
x-client-ca: &client-ca
|
||||
./.local/pki/ca.crt:/run/pki/ca.crt:ro
|
||||
|
||||
services:
|
||||
tls-prepare:
|
||||
image: busybox:1.37.0
|
||||
user: "0:0"
|
||||
command: ["sh", "-ec", "cp /source/postgres.crt /target/postgres.crt; cp /source/postgres.key /target/postgres.key; chown 999:999 /target/postgres.crt /target/postgres.key; chmod 644 /target/postgres.crt; chmod 600 /target/postgres.key"]
|
||||
volumes:
|
||||
- ./.local/pki/postgres.crt:/source/postgres.crt:ro
|
||||
- ./.local/pki/postgres.key:/source/postgres.key:ro
|
||||
- postgres_tls:/target
|
||||
network_mode: none
|
||||
restart: "no"
|
||||
postgres:
|
||||
image: postgres:16.10-bookworm
|
||||
command: ["postgres", "-c", "ssl=on", "-c", "ssl_cert_file=/run/postgres-tls/postgres.crt", "-c", "ssl_key_file=/run/postgres-tls/postgres.key", "-c", "hba_file=/etc/postgresql/pg_hba.conf", "-c", "password_encryption=scram-sha-256"]
|
||||
environment:
|
||||
POSTGRES_DB: ${POSTGRES_DB:-messenger}
|
||||
POSTGRES_USER: ${POSTGRES_USER:-lab}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Missing .env}
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
- postgres_tls:/run/postgres-tls:ro
|
||||
- ./.local/pki/ca.crt:/run/pki/ca.crt:ro
|
||||
- ./infra/postgres/pg_hba.conf:/etc/postgresql/pg_hba.conf:ro
|
||||
depends_on:
|
||||
tls-prepare: {condition: service_completed_successfully}
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "PGSSLMODE=verify-full PGSSLROOTCERT=/run/pki/ca.crt PGPASSWORD=$$POSTGRES_PASSWORD psql -h postgres -U $$POSTGRES_USER -d $$POSTGRES_DB -c 'SELECT 1' >/dev/null 2>&1"]
|
||||
interval: 4s
|
||||
timeout: 3s
|
||||
retries: 30
|
||||
mem_limit: 512m
|
||||
cpus: 1.0
|
||||
restart: unless-stopped
|
||||
networks: [storage]
|
||||
|
||||
redis:
|
||||
image: redis:7.4.5-alpine
|
||||
command: ["redis-server", "--appendonly", "yes", "--appendfsync", "always", "--save", "60", "1", "--requirepass", "${REDIS_PASSWORD:?Missing .env}"]
|
||||
volumes: ["redis_data:/data"]
|
||||
mem_limit: 256m
|
||||
cpus: 0.5
|
||||
restart: unless-stopped
|
||||
networks: [redis-private]
|
||||
redis-gw:
|
||||
<<: *haproxy
|
||||
volumes:
|
||||
- ./infra/tls/redis.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
||||
- ./.local/pki/redis-gw.pem:/run/pki/redis-gw.pem:ro
|
||||
networks: [storage, redis-private]
|
||||
|
||||
broker:
|
||||
image: rabbitmq:4.1.8-management-alpine
|
||||
hostname: lab7-broker
|
||||
environment:
|
||||
RABBITMQ_DEFAULT_USER: ${BROKER_ADMIN_USER:-bootstrap}
|
||||
RABBITMQ_DEFAULT_PASS: ${BROKER_ADMIN_PASSWORD:?Missing .env}
|
||||
volumes: ["rabbitmq_data:/var/lib/rabbitmq"]
|
||||
healthcheck:
|
||||
test: ["CMD", "rabbitmq-diagnostics", "-q", "ping"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 25
|
||||
start_period: 15s
|
||||
mem_limit: 512m
|
||||
cpus: 0.75
|
||||
restart: unless-stopped
|
||||
networks: [broker-private]
|
||||
broker-gw:
|
||||
<<: *haproxy
|
||||
volumes:
|
||||
- ./infra/tls/broker.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
||||
- ./.local/pki/broker-gw.pem:/run/pki/broker-gw.pem:ro
|
||||
- ./.local/pki/ca.crt:/run/pki/ca.crt:ro
|
||||
- ./.local/pki/ca.crl:/run/pki/ca.crl:ro
|
||||
networks: [storage, broker-private]
|
||||
broker-users:
|
||||
<<: *python
|
||||
command: ["python", "-m", "app.rabbit_bootstrap"]
|
||||
environment:
|
||||
BROKER_ADMIN_USER: ${BROKER_ADMIN_USER:-bootstrap}
|
||||
BROKER_ADMIN_PASSWORD: ${BROKER_ADMIN_PASSWORD:?Missing .env}
|
||||
BROKER_DISPATCHER_USER: ${BROKER_DISPATCHER_USER:-dispatcher}
|
||||
BROKER_DISPATCHER_PASSWORD: ${BROKER_DISPATCHER_PASSWORD:?Missing .env}
|
||||
BROKER_WORKER_USER: ${BROKER_WORKER_USER:-worker}
|
||||
BROKER_WORKER_PASSWORD: ${BROKER_WORKER_PASSWORD:?Missing .env}
|
||||
depends_on:
|
||||
broker: {condition: service_healthy}
|
||||
networks: [broker-private]
|
||||
restart: "no"
|
||||
|
||||
s3-policy:
|
||||
<<: *python
|
||||
user: "0:0" # operator-only writes SeaweedFS IAM file; no long-running root app
|
||||
read_only: false
|
||||
command: ["python", "-m", "app.s3_policy"]
|
||||
environment:
|
||||
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
|
||||
S3_ADMIN_ACCESS_KEY: ${S3_ADMIN_ACCESS_KEY:?Missing .env}
|
||||
S3_ADMIN_SECRET_KEY: ${S3_ADMIN_SECRET_KEY:?Missing .env}
|
||||
S3_API_ACCESS_KEY: ${S3_API_ACCESS_KEY:?Missing .env}
|
||||
S3_API_SECRET_KEY: ${S3_API_SECRET_KEY:?Missing .env}
|
||||
S3_WORKER_ACCESS_KEY: ${S3_WORKER_ACCESS_KEY:?Missing .env}
|
||||
S3_WORKER_SECRET_KEY: ${S3_WORKER_SECRET_KEY:?Missing .env}
|
||||
S3_DISPATCHER_ACCESS_KEY: ${S3_DISPATCHER_ACCESS_KEY:?Missing .env}
|
||||
S3_DISPATCHER_SECRET_KEY: ${S3_DISPATCHER_SECRET_KEY:?Missing .env}
|
||||
volumes: ["s3_config:/s3-config"]
|
||||
networks: [s3-private]
|
||||
restart: "no"
|
||||
s3:
|
||||
image: chrislusf/seaweedfs:4.53
|
||||
command: ["server", "-dir=/data", "-ip=s3", "-ip.bind=0.0.0.0", "-s3", "-s3.port=8333", "-s3.iam=false", "-s3.config=/s3-config/config.json"]
|
||||
volumes:
|
||||
- s3_data:/data
|
||||
- s3_config:/s3-config:ro
|
||||
- ./infra/filer.toml:/etc/seaweedfs/filer.toml:ro
|
||||
depends_on:
|
||||
s3-policy: {condition: service_completed_successfully}
|
||||
mem_limit: 640m
|
||||
cpus: 1.0
|
||||
restart: unless-stopped
|
||||
networks: [s3-private]
|
||||
s3-gw:
|
||||
<<: *haproxy
|
||||
volumes:
|
||||
- ./infra/tls/s3.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
||||
- ./.local/pki/s3-gw.pem:/run/pki/s3-gw.pem:ro
|
||||
networks: [storage, s3-private]
|
||||
s3-bootstrap:
|
||||
<<: *python
|
||||
command: ["python", "-m", "app.s3_bootstrap"]
|
||||
environment:
|
||||
S3_ENDPOINT: https://s3-gw:8334
|
||||
TLS_CA_FILE: /run/pki/ca.crt
|
||||
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
|
||||
S3_ADMIN_ACCESS_KEY: ${S3_ADMIN_ACCESS_KEY:?Missing .env}
|
||||
S3_ADMIN_SECRET_KEY: ${S3_ADMIN_SECRET_KEY:?Missing .env}
|
||||
volumes:
|
||||
- ./.local/pki/ca.crt:/run/pki/ca.crt:ro
|
||||
depends_on:
|
||||
s3: {condition: service_started}
|
||||
s3-gw: {condition: service_started}
|
||||
networks: [storage]
|
||||
restart: "no"
|
||||
|
||||
migrate:
|
||||
<<: *python
|
||||
command: ["python", "-m", "app.migrate"]
|
||||
environment:
|
||||
DATABASE_URL: postgresql://${POSTGRES_USER:-lab}:${POSTGRES_PASSWORD:?Missing .env}@postgres:5432/${POSTGRES_DB:-messenger}?sslmode=verify-full&sslrootcert=/run/pki/ca.crt
|
||||
volumes: ["./.local/pki/ca.crt:/run/pki/ca.crt:ro"]
|
||||
depends_on:
|
||||
postgres: {condition: service_healthy}
|
||||
networks: [storage]
|
||||
restart: "no"
|
||||
db-roles:
|
||||
<<: *python
|
||||
command: ["python", "-m", "app.db_roles"]
|
||||
environment:
|
||||
DATABASE_URL: postgresql://${POSTGRES_USER:-lab}:${POSTGRES_PASSWORD:?Missing .env}@postgres:5432/${POSTGRES_DB:-messenger}?sslmode=verify-full&sslrootcert=/run/pki/ca.crt
|
||||
DB_API_PASSWORD: ${DB_API_PASSWORD:?Missing .env}
|
||||
DB_WORKER_PASSWORD: ${DB_WORKER_PASSWORD:?Missing .env}
|
||||
DB_DISPATCHER_PASSWORD: ${DB_DISPATCHER_PASSWORD:?Missing .env}
|
||||
volumes: ["./.local/pki/ca.crt:/run/pki/ca.crt:ro"]
|
||||
depends_on:
|
||||
migrate: {condition: service_completed_successfully}
|
||||
networks: [storage]
|
||||
restart: "no"
|
||||
|
||||
openbao:
|
||||
image: openbao/openbao:2.6.4
|
||||
command: ["server", "-config=/bao/config.hcl"]
|
||||
environment:
|
||||
BAO_ADDR: https://openbao:8200
|
||||
BAO_CACERT: /run/pki/ca.crt
|
||||
volumes:
|
||||
- bao_data:/openbao/file
|
||||
- ./infra/openbao/config.hcl:/bao/config.hcl:ro
|
||||
- ./.local/pki/openbao.crt:/run/pki/openbao.crt:ro
|
||||
- ./.local/pki/openbao.key:/run/pki/openbao.key:ro
|
||||
- ./.local/pki/ca.crt:/run/pki/ca.crt:ro
|
||||
mem_limit: 384m
|
||||
cpus: 0.5
|
||||
restart: unless-stopped
|
||||
networks: [storage]
|
||||
|
||||
api1:
|
||||
<<: *python
|
||||
environment: &api-environment
|
||||
APP_PORT: "8080"
|
||||
APP_HOST: "127.0.0.1"
|
||||
API_INSTANCE_ID: api1
|
||||
OTEL_ENABLED: ${OTEL_ENABLED:-yes}
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-gw:4318
|
||||
TLS_CA_FILE: /run/pki/ca.crt
|
||||
TLS_CLIENT_CERT: /run/pki/client.crt
|
||||
TLS_CLIENT_KEY: /run/pki/client.key
|
||||
BAO_ADDR: https://openbao:8200
|
||||
BAO_ROLE: api
|
||||
BAO_ROLE_ID_FILE: /run/bao/role_id
|
||||
BAO_SECRET_ID_FILE: /run/bao/secret_id
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||
DB_POOL_MAX: "8"
|
||||
JOB_BACKLOG_LIMIT: "1000"
|
||||
volumes:
|
||||
- ./.local/pki/ca.crt:/run/pki/ca.crt:ro
|
||||
- ./.local/pki/api1-client.crt:/run/pki/client.crt:ro
|
||||
- ./.local/pki/api1-client.key:/run/pki/client.key:ro
|
||||
- bao_api_auth:/run/bao:ro
|
||||
depends_on: &api-dependencies
|
||||
db-roles: {condition: service_completed_successfully}
|
||||
s3-bootstrap: {condition: service_completed_successfully}
|
||||
openbao: {condition: service_started}
|
||||
redis-gw: {condition: service_started}
|
||||
otel-gw: {condition: service_started}
|
||||
healthcheck: &api-health
|
||||
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health/ready', timeout=2)"]
|
||||
interval: 4s
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
start_period: 12s
|
||||
mem_limit: 384m
|
||||
cpus: 0.75
|
||||
networks: [ingress-private, storage, otel-clients]
|
||||
api2:
|
||||
<<: *python
|
||||
environment:
|
||||
<<: *api-environment
|
||||
API_INSTANCE_ID: api2
|
||||
volumes:
|
||||
- ./.local/pki/ca.crt:/run/pki/ca.crt:ro
|
||||
- ./.local/pki/ca.crl:/run/pki/ca.crl:ro
|
||||
- ./.local/pki/api2-client.crt:/run/pki/client.crt:ro
|
||||
- ./.local/pki/api2-client.key:/run/pki/client.key:ro
|
||||
- bao_api_auth:/run/bao:ro
|
||||
depends_on: *api-dependencies
|
||||
healthcheck: *api-health
|
||||
mem_limit: 384m
|
||||
cpus: 0.75
|
||||
networks: [ingress-private, storage, otel-clients]
|
||||
api1-tls:
|
||||
<<: *haproxy
|
||||
volumes:
|
||||
- ./infra/tls/api1.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
||||
- ./.local/pki/api1-tls.pem:/run/pki/api1-tls.pem:ro
|
||||
- ./.local/pki/ca.crt:/run/pki/ca.crt:ro
|
||||
- ./.local/pki/ca.crl:/run/pki/ca.crl:ro
|
||||
depends_on: {api1: {condition: service_healthy}}
|
||||
network_mode: "service:api1"
|
||||
api2-tls:
|
||||
<<: *haproxy
|
||||
volumes:
|
||||
- ./infra/tls/api2.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
||||
- ./.local/pki/api2-tls.pem:/run/pki/api2-tls.pem:ro
|
||||
- ./.local/pki/ca.crt:/run/pki/ca.crt:ro
|
||||
- ./.local/pki/ca.crl:/run/pki/ca.crl:ro
|
||||
depends_on: {api2: {condition: service_healthy}}
|
||||
network_mode: "service:api2"
|
||||
lb:
|
||||
<<: *haproxy
|
||||
volumes:
|
||||
- ./infra/tls/ingress.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
||||
- ./.local/pki/ingress.pem:/run/pki/ingress.pem:ro
|
||||
- ./.local/pki/lb-client.pem:/run/pki/lb-client.pem:ro
|
||||
- ./.local/pki/ca.crt:/run/pki/ca.crt:ro
|
||||
ports: ["127.0.0.1:8443:8443"]
|
||||
depends_on:
|
||||
api1-tls: {condition: service_started}
|
||||
api2-tls: {condition: service_started}
|
||||
networks: [ingress-private, api-edge]
|
||||
|
||||
dispatcher:
|
||||
<<: *python
|
||||
command: ["python", "-m", "app.jobs", "dispatch"]
|
||||
environment: &worker-env
|
||||
OTEL_ENABLED: ${OTEL_ENABLED:-yes}
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-gw:4318
|
||||
TLS_CA_FILE: /run/pki/ca.crt
|
||||
TLS_CLIENT_CERT: /run/pki/client.crt
|
||||
TLS_CLIENT_KEY: /run/pki/client.key
|
||||
BAO_ADDR: https://openbao:8200
|
||||
BAO_ROLE_ID_FILE: /run/bao/role_id
|
||||
BAO_SECRET_ID_FILE: /run/bao/secret_id
|
||||
BAO_ROLE: dispatcher
|
||||
JOB_TIMEOUT_SECONDS: ${JOB_TIMEOUT_SECONDS:-60}
|
||||
JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5}
|
||||
volumes:
|
||||
- ./.local/pki/ca.crt:/run/pki/ca.crt:ro
|
||||
- ./.local/pki/dispatcher-client.crt:/run/pki/client.crt:ro
|
||||
- ./.local/pki/dispatcher-client.key:/run/pki/client.key:ro
|
||||
- bao_dispatcher_auth:/run/bao:ro
|
||||
depends_on:
|
||||
db-roles: {condition: service_completed_successfully}
|
||||
broker-users: {condition: service_completed_successfully}
|
||||
broker-gw: {condition: service_started}
|
||||
otel-gw: {condition: service_started}
|
||||
openbao: {condition: service_started}
|
||||
mem_limit: 192m
|
||||
cpus: 0.5
|
||||
networks: [storage, otel-clients]
|
||||
worker:
|
||||
<<: *python
|
||||
command: ["python", "-m", "app.jobs", "worker"]
|
||||
environment:
|
||||
<<: *worker-env
|
||||
BAO_ROLE: worker
|
||||
WORKER_PREFETCH: "1"
|
||||
LAB6_FAULT_RETRY_ONCE: ${LAB6_FAULT_RETRY_ONCE:-off}
|
||||
LAB5_FAULT_AFTER_S3: ${LAB5_FAULT_AFTER_S3:-off}
|
||||
volumes:
|
||||
- ./.local/pki/ca.crt:/run/pki/ca.crt:ro
|
||||
- ./.local/pki/worker-client.crt:/run/pki/client.crt:ro
|
||||
- ./.local/pki/worker-client.key:/run/pki/client.key:ro
|
||||
- bao_worker_auth:/run/bao:ro
|
||||
depends_on:
|
||||
db-roles: {condition: service_completed_successfully}
|
||||
broker-users: {condition: service_completed_successfully}
|
||||
s3-bootstrap: {condition: service_completed_successfully}
|
||||
broker-gw: {condition: service_started}
|
||||
otel-gw: {condition: service_started}
|
||||
openbao: {condition: service_started}
|
||||
mem_limit: 768m
|
||||
cpus: 1.0
|
||||
pids_limit: 96
|
||||
stop_grace_period: 75s
|
||||
networks: [storage, otel-clients]
|
||||
|
||||
telemetry-init:
|
||||
image: busybox:1.37.0
|
||||
user: "0:0"
|
||||
command: ["sh", "-ec", "chown 10001:10001 /tempo /loki; chown 65534:65534 /prometheus; chown 472:472 /grafana"]
|
||||
volumes: ["tempo_data:/tempo", "loki_data:/loki", "prometheus_data:/prometheus", "grafana_data:/grafana"]
|
||||
network_mode: none
|
||||
restart: "no"
|
||||
otel-gw:
|
||||
<<: *haproxy
|
||||
volumes:
|
||||
- ./infra/tls/otel.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
||||
- ./.local/pki/otel-gw.pem:/run/pki/otel-gw.pem:ro
|
||||
- ./.local/pki/ca.crt:/run/pki/ca.crt:ro
|
||||
- ./.local/pki/ca.crl:/run/pki/ca.crl:ro
|
||||
networks: [otel-clients, collector-private]
|
||||
otel-collector:
|
||||
image: otel/opentelemetry-collector-contrib:0.123.0
|
||||
command: ["--config=/etc/otelcol/config.yaml"]
|
||||
environment: {GOMEMLIMIT: 180MiB}
|
||||
volumes:
|
||||
- ./infra/otel/collector.yaml:/etc/otelcol/config.yaml:ro
|
||||
- ./.local/pki/ca.crt:/run/pki/ca.crt:ro
|
||||
- ./.local/pki/collector-client.crt:/run/pki/client.crt:ro
|
||||
- ./.local/pki/collector-client.key:/run/pki/client.key:ro
|
||||
mem_limit: 256m
|
||||
cpus: 0.75
|
||||
restart: unless-stopped
|
||||
networks: [collector-private]
|
||||
metrics-gw:
|
||||
<<: *haproxy
|
||||
volumes:
|
||||
- ./infra/tls/metrics.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
||||
- ./.local/pki/metrics-gw.pem:/run/pki/metrics-gw.pem:ro
|
||||
- ./.local/pki/ca.crt:/run/pki/ca.crt:ro
|
||||
- ./.local/pki/ca.crl:/run/pki/ca.crl:ro
|
||||
networks: [collector-private, metrics-private, dashboards]
|
||||
prometheus:
|
||||
image: prom/prometheus:v3.2.1
|
||||
command: ["--config.file=/etc/prometheus/prometheus.yml", "--storage.tsdb.path=/prometheus", "--storage.tsdb.retention.time=72h", "--storage.tsdb.retention.size=512MB"]
|
||||
volumes:
|
||||
- ./infra/otel/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml:ro
|
||||
- ./infra/otel/prometheus/alerts.yml:/etc/prometheus/alerts.yml:ro
|
||||
- ./.local/pki/ca.crt:/run/pki/ca.crt:ro
|
||||
- prometheus_data:/prometheus
|
||||
depends_on: {telemetry-init: {condition: service_completed_successfully}}
|
||||
mem_limit: 384m
|
||||
restart: unless-stopped
|
||||
networks: [metrics-private]
|
||||
loki:
|
||||
image: grafana/loki:3.4.2
|
||||
command: ["-config.file=/etc/loki/local-config.yaml"]
|
||||
volumes: ["./infra/otel/loki.yaml:/etc/loki/local-config.yaml:ro", "loki_data:/loki"]
|
||||
depends_on: {telemetry-init: {condition: service_completed_successfully}}
|
||||
mem_limit: 512m
|
||||
restart: unless-stopped
|
||||
networks: [metrics-private]
|
||||
tempo:
|
||||
image: grafana/tempo:2.7.2
|
||||
command: ["-config.file=/etc/tempo.yaml"]
|
||||
volumes: ["./infra/otel/tempo.yaml:/etc/tempo.yaml:ro", "tempo_data:/var/tempo"]
|
||||
depends_on: {telemetry-init: {condition: service_completed_successfully}}
|
||||
mem_limit: 512m
|
||||
restart: unless-stopped
|
||||
networks: [metrics-private]
|
||||
grafana:
|
||||
image: grafana/grafana:11.6.0
|
||||
environment:
|
||||
GF_SECURITY_ADMIN_USER: admin
|
||||
GF_SECURITY_ADMIN_PASSWORD: ${GRAFANA_ADMIN_PASSWORD:?Missing .env}
|
||||
GF_USERS_ALLOW_SIGN_UP: "false"
|
||||
GF_AUTH_ANONYMOUS_ENABLED: "false"
|
||||
GF_ANALYTICS_REPORTING_ENABLED: "false"
|
||||
GF_SERVER_ROOT_URL: https://localhost:3443
|
||||
SSL_CERT_FILE: /run/pki/ca.crt
|
||||
volumes:
|
||||
- grafana_data:/var/lib/grafana
|
||||
- ./.local/pki/ca.crt:/run/pki/ca.crt:ro
|
||||
- ./infra/otel/grafana/provisioning:/etc/grafana/provisioning:ro
|
||||
- ./infra/otel/grafana/dashboards:/var/lib/grafana/dashboards:ro
|
||||
depends_on: {telemetry-init: {condition: service_completed_successfully}}
|
||||
mem_limit: 384m
|
||||
restart: unless-stopped
|
||||
networks: [dashboards]
|
||||
grafana-gw:
|
||||
<<: *haproxy
|
||||
volumes:
|
||||
- ./infra/tls/grafana.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
||||
- ./.local/pki/grafana-gw.pem:/run/pki/grafana-gw.pem:ro
|
||||
ports: ["127.0.0.1:3443:3443"]
|
||||
depends_on: {grafana: {condition: service_started}}
|
||||
networks: [dashboards, grafana-edge]
|
||||
|
||||
tls-audit:
|
||||
<<: *python
|
||||
profiles: [audit]
|
||||
command: ["python", "tests/tls_matrix.py"]
|
||||
environment: {TLS_CA_FILE: /run/pki/ca.crt}
|
||||
volumes:
|
||||
- ./tests:/srv/tests:ro
|
||||
- ./.local/pki/ca.crt:/run/audit-pki/ca.crt:ro
|
||||
- ./.local/pki/lb-client.crt:/run/audit-pki/lb-client.crt:ro
|
||||
- ./.local/pki/lb-client.key:/run/audit-pki/lb-client.key:ro
|
||||
- ./.local/pki/rogue-client.crt:/run/audit-pki/rogue-client.crt:ro
|
||||
- ./.local/pki/rogue-client.key:/run/audit-pki/rogue-client.key:ro
|
||||
- ./.local/pki/foreign-client.crt:/run/audit-pki/foreign-client.crt:ro
|
||||
- ./.local/pki/foreign-client.key:/run/audit-pki/foreign-client.key:ro
|
||||
- ./.local/pki/worker-client.crt:/run/audit-pki/worker-client.crt:ro
|
||||
- ./.local/pki/worker-client.key:/run/audit-pki/worker-client.key:ro
|
||||
- ./.local/pki/collector-client.crt:/run/audit-pki/collector-client.crt:ro
|
||||
- ./.local/pki/collector-client.key:/run/audit-pki/collector-client.key:ro
|
||||
networks: [ingress-private, storage, otel-clients, collector-private]
|
||||
restart: "no"
|
||||
|
||||
bao-policy-audit:
|
||||
<<: *python
|
||||
profiles: [audit]
|
||||
command: ["python", "tests/bao_policy_audit.py"]
|
||||
volumes:
|
||||
- ./tests:/srv/tests:ro
|
||||
- ./.local/pki/ca.crt:/run/pki/ca.crt:ro
|
||||
- bao_api_auth:/role-files/api:ro
|
||||
- bao_worker_auth:/role-files/worker:ro
|
||||
- bao_dispatcher_auth:/role-files/dispatcher:ro
|
||||
networks: [storage]
|
||||
restart: "no"
|
||||
|
||||
s3-rotation-audit:
|
||||
<<: *python
|
||||
profiles: [audit]
|
||||
command: ["python", "tests/s3_rotation_audit.py"]
|
||||
environment:
|
||||
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
|
||||
S3_WORKER_ACCESS_KEY: ${S3_WORKER_ACCESS_KEY:?Missing .env}
|
||||
S3_WORKER_SECRET_KEY: ${S3_WORKER_SECRET_KEY:?Missing .env}
|
||||
volumes:
|
||||
- ./tests:/srv/tests:ro
|
||||
- ./.local/pki/ca.crt:/run/pki/ca.crt:ro
|
||||
- ./.local/operator/old-worker-s3-secret.txt:/operator/old-secret:ro
|
||||
networks: [storage]
|
||||
restart: "no"
|
||||
|
||||
bao-bootstrap:
|
||||
<<: *python
|
||||
profiles: [bootstrap]
|
||||
user: "0:0" # operator-only ephemeral job, accesses root token via operator file
|
||||
# x-python drops ALL Linux capabilities; this one-shot job must chown 0700/0600
|
||||
# Docker named-volume AppRole files for the non-root (999:999) application.
|
||||
# No extra capabilities are granted to api*, worker, or dispatcher.
|
||||
cap_add: [CHOWN, FOWNER, DAC_OVERRIDE]
|
||||
command: ["python", "scripts/bao_bootstrap.py"]
|
||||
environment:
|
||||
POSTGRES_DB: ${POSTGRES_DB:-messenger}
|
||||
DB_API_PASSWORD: ${DB_API_PASSWORD:?Missing .env}
|
||||
DB_WORKER_PASSWORD: ${DB_WORKER_PASSWORD:?Missing .env}
|
||||
DB_DISPATCHER_PASSWORD: ${DB_DISPATCHER_PASSWORD:?Missing .env}
|
||||
REDIS_PASSWORD: ${REDIS_PASSWORD:?Missing .env}
|
||||
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
|
||||
S3_API_ACCESS_KEY: ${S3_API_ACCESS_KEY:?Missing .env}
|
||||
S3_API_SECRET_KEY: ${S3_API_SECRET_KEY:?Missing .env}
|
||||
S3_WORKER_ACCESS_KEY: ${S3_WORKER_ACCESS_KEY:?Missing .env}
|
||||
S3_WORKER_SECRET_KEY: ${S3_WORKER_SECRET_KEY:?Missing .env}
|
||||
S3_DISPATCHER_ACCESS_KEY: ${S3_DISPATCHER_ACCESS_KEY:?Missing .env}
|
||||
S3_DISPATCHER_SECRET_KEY: ${S3_DISPATCHER_SECRET_KEY:?Missing .env}
|
||||
BROKER_DISPATCHER_USER: ${BROKER_DISPATCHER_USER:-dispatcher}
|
||||
BROKER_DISPATCHER_PASSWORD: ${BROKER_DISPATCHER_PASSWORD:?Missing .env}
|
||||
BROKER_WORKER_USER: ${BROKER_WORKER_USER:-worker}
|
||||
BROKER_WORKER_PASSWORD: ${BROKER_WORKER_PASSWORD:?Missing .env}
|
||||
volumes:
|
||||
- ./scripts/bao_bootstrap.py:/srv/scripts/bao_bootstrap.py:ro
|
||||
- ./infra/openbao/policies:/policies:ro
|
||||
- ./.local/operator/init.json:/operator/init.json:ro
|
||||
- bao_api_auth:/issued/api
|
||||
- bao_worker_auth:/issued/worker
|
||||
- bao_dispatcher_auth:/issued/dispatcher
|
||||
- ./.local/pki/ca.crt:/run/pki/ca.crt:ro
|
||||
networks: [storage]
|
||||
restart: "no"
|
||||
|
||||
networks:
|
||||
api-edge: {driver: bridge}
|
||||
grafana-edge: {driver: bridge}
|
||||
storage: {internal: true}
|
||||
redis-private: {internal: true}
|
||||
broker-private: {internal: true}
|
||||
s3-private: {internal: true}
|
||||
ingress-private: {internal: true}
|
||||
otel-clients: {internal: true}
|
||||
collector-private: {internal: true}
|
||||
metrics-private: {internal: true}
|
||||
dashboards: {internal: true}
|
||||
volumes:
|
||||
postgres_data:
|
||||
postgres_tls:
|
||||
redis_data:
|
||||
rabbitmq_data:
|
||||
s3_data:
|
||||
s3_config:
|
||||
bao_data:
|
||||
bao_api_auth:
|
||||
bao_worker_auth:
|
||||
bao_dispatcher_auth:
|
||||
prometheus_data:
|
||||
loki_data:
|
||||
tempo_data:
|
||||
grafana_data:
|
||||
+20
-32
@@ -1,37 +1,25 @@
|
||||
# Матрица доверия — заполнить в решении lab7
|
||||
# Матрица доверия ЛР7
|
||||
|
||||
Это обязательная матрица покрытия. Для каждой строки укажите реальный порт, endpoint, CA, service identity, проверку SAN/ACL, срок жизни credentials и команду положительного/отрицательного теста. TLS шифрует и подтверждает сервер; mTLS также проверяет клиента. При доверенном CA всё равно нужно ограничивать разрешённую identity. Plaintext hop допустим только внутри закрытого локального transport/proxy boundary, без опубликованного обхода; границу и rationale нужно доказать.
|
||||
Состояние: **реализация подготовлена; результат живого аудита заполняется после Docker-прогона**. CA — `.local/pki/ca.crt`, ECDSA P-256, действующий корень 365 дней, leaf 30 дней (обновляется оператором). SAN и роль *проверяются отдельно* от цепочки CA на mTLS gateway. Роль — identity/ACL, не только шифрование. См. [SECURITY_RUNBOOK.md](../SECURITY_RUNBOOK.md).
|
||||
|
||||
| Связь | Минимум на 3 | Дополнительно на 4 | Доказательство / конфиг |
|
||||
| Связь | Протокол, порт/граница | Identity и минимальные полномочия | Проверка отказа |
|
||||
| --- | --- | --- | --- |
|
||||
| Клиент → ingress/LB | TLS, CA + hostname, Bearer | Проверка expiry/revocation сессии и общего login rate limit | TODO |
|
||||
| LB → API (все реплики) | mTLS + allowlist LB identity | Ротация leaf без обхода проверки | TODO |
|
||||
| API/worker → PostgreSQL | TLS verify-full + раздельные ограниченные DB roles | Ротация credentials; mTLS — допустимое усиление | TODO |
|
||||
| API/worker → S3 | TLS + разные scoped credentials/prefix rights | Проверка denied prefix и ротация | TODO |
|
||||
| API/worker → broker | TLS + разные producer/consumer identities и ACL | mTLS + ограничение допустимых SAN/ролей | TODO |
|
||||
| API/worker → Collector | TLS; сеть/аутентификация запрещает произвольный ingest | mTLS с раздельными identities | TODO |
|
||||
| Collector → telemetry backends | TLS + scoped backend credentials или mTLS | Ротация и проверка least privilege | TODO |
|
||||
| Grafana → data sources | TLS с проверкой сервера, ограниченная identity | Отрицательные проверки доступа | TODO |
|
||||
| API/worker/agent → OpenBao | TLS + сервисный auth + scoped policy | Renewal/expiry/revocation | TODO |
|
||||
| Оператор → OpenBao/Grafana/S3 admin | TLS + authentication, доступ локальный/через защищённый канал | Разделение operator/application roles | TODO |
|
||||
| API → Redis/Valkey, если используется | TLS + ACL/пароль с минимальными правами | Ротация; mTLS по возможности | TODO |
|
||||
| Replication/кластерные каналы, если добавлены | TLS/mTLS либо подтверждённый шифрованный transport | Проверка заявленной модели отказа | TODO |
|
||||
| Пользователь → LB | TLS1.2+, `localhost:8443`, SAN localhost, IP 127.0.0.1, CA; Bearer hash+TTL Redis | Пользователь с bearer session; ACL чатов/вложений | `tests/security.py`, `tests/smoke.py`, `tests/security_live.py`, `tests/attachments_negative.py` |
|
||||
| LB → API1/API2 | HAProxy HTTPS mTLS `api{1,2}:8443`; серверный SAN `api{1,2}-tls` | Только клиент `lab7-lb`: CA + точный CN + SAN; CRL | `tests/tls_matrix.py`: no-cert, foreign-CA, trusted-wrong-role, correct, revoked; API HTTP на loopback, namespace shared with TLS sidecar |
|
||||
| API/worker/dispatcher → PG | PostgreSQL native `postgres:5432` TLS `sslmode=verify-full`, SAN postgres | Отдельные DB роли `messenger_api`, `_worker`, `_dispatcher`, SCRAM, table grants; DDL только оператор | SQL GRANT check / чужая таблица, `pg_hba.conf` отвергает hostnossl; см. `app/db_roles.py` |
|
||||
| API/worker/dispatcher → S3 | HTTPS `s3-gw:8334`, SAN `s3-gw`; приватный HTTP hop до `s3:8333` | Три разных AccessKey; права только на `messenger-attachments`; Admin — только bootstrap | `tests/s3_rotation_audit.py`: старый credential 403, новый работает; `tests/attachments_negative.py`; **prefix на одном bucket не разделён** |
|
||||
| Dispatcher/worker → broker | AMQPS gateway `broker-gw:5671`, SAN broker-gw, mutual cert | У worker `messenger-worker` client SAN + MQ consumer ACL; dispatcher `messenger-dispatcher` producer, разные пароли | `tests/tls_matrix.py` + `app/rabbit_bootstrap.py`, negative role/no-cert/foreign-CA |
|
||||
| API/worker/dispatcher → Collector | HTTPS OTLP `otel-gw:4318` mTLS; приватный HTTP hop до `otel-collector:4318` | SAN messenger-api1/api2/worker/dispatcher, allowlist, нет anonymous | `tests/tls_matrix.py`: wrong valid role / foreign CA / no cert / positive |
|
||||
| Collector → Loki / Tempo | `metrics-gw:3102` OTLP HTTP, `:4317` gRPC; TLS **mTLS** | Только `messenger-collector` mTLS client identity, separate cert/key, backend service SAN metrics-gw; внутренний hop до backend на `metrics-private` | TLS policy config `infra/tls/metrics.cfg`; требуется runtime negative test в расширенном аудите |
|
||||
| Prometheus → Collector | `metrics-gw:8889` и `:8888` TLS, CA+SAN verify; внутренний scrape | Prometheus только в `metrics-private`, endpoints не опубликованы | Scrape статус в Grafana/Prometheus UI (сеть/CA) |
|
||||
| Grafana → Prometheus/Loki/Tempo | TLS `metrics-gw:9091`, `3101`, `3201` | Grafana серверный Go trust CA; изолированная dashboards сеть; Grafana auth admin | Доступ к Grafana только `https://localhost:3443`; backend admin auth отсутствует (остаточный риск доверенной сети) |
|
||||
| API/worker/dispatcher → OpenBao | HTTPS `openbao:8200`, CA+SAN, private storage network | AppRole role+secretID в role-only mount; KV `read` только `kv/data/<role>`; token TTL10m max30m, SecretID24h | `tests/bao_policy_audit.py`, sealed / wrong AppRole / cross-path 403; root token только operator job |
|
||||
| API → Redis | TLS gateway `redis-gw:6380` + password; isolated hop к Redis:6379 | API Redis password через Bao, shared atomic login INCR/EXPIRE, sessions SHA256 | Login >8/min → 429 + Retry-After, logout ->401, чужие токены ->401 |
|
||||
| Оператор → OpenBao | `docker compose exec` через локальный Docker Desktop; HTTPS к OpenBao внутри контейнера | Root/unseal в `.local/operator`, только bootstrap/unseal; нет у app | Нет root/env in long-running containers; не публиковать операторские ключи |
|
||||
| Оператор → Grafana | `https://localhost:3443`, TLS, admin/pass | Только локальный хост, пароль отдельный в `.env`; публичная регистрация отключена | `docker compose ps` подтверждает localhost host-port; CA/hostname положительный/отрицательный |
|
||||
| Оператор → S3 admin | Только изолированные one-shot `s3-policy` и `s3-bootstrap` | Admin AccessKey хранится в `.env` оператора; не монтируется в API/worker | Проверка Compose environment и bucket permissions |
|
||||
| Репликация между контейнерами PG/Rabbit/S3 | N/A | Одноэкземплярные локальные stateful сервисы, без кластерного transport | Не заявляется HA stateful storage |
|
||||
|
||||
Нет выбранного компонента — отметьте N/A с причиной, а не оставляйте пустую строку. Внутренний публичный health listener, если нужен, минимален и изолирован; через него нельзя обращаться к бизнес-API без mTLS. Отдельно задокументируйте scrape/health/bootstrap каналы: они тоже не должны создавать обход.
|
||||
**Граница gateway→backend:** прозрачный proxy проверяет TLS до boundary. Последний plaintext hop физически внутри закрытой `internal: true` Docker-сети (`broker-private`, `s3-private`, `redis-private`, `collector-private`, `metrics-private`). Для production враждебного multi-tenant Docker-host это недостаточно — тогда требуются native TLS и service network policy. Дополнительные telemetry scrape/health не создают опубликованного API-port bypass: FastAPI loopback и нет host `8080`.
|
||||
|
||||
## Обязательные отрицательные проверки
|
||||
|
||||
1. HTTPS с правильным CA/hostname проходит; с пустым/чужим CA и неправильным hostname — ошибка верификации, не «сервер недоступен».
|
||||
2. LB→API: без client cert, с cert чужого CA, с запрещённой identity от доверенного CA — отказ; с разрешённой LB identity — успех.
|
||||
3. На 4 повторите набор для broker и Collector; ограничение на network policy не заменяет проверку identity.
|
||||
4. Пользователь вне чата не читает metadata/content и не прикрепляет чужой файл; поддельный X-User-Id не меняет Bearer identity.
|
||||
5. OpenBao app policy читает только свой secret/path; запись policy и чтение чужого path запрещены. Worker не получает admin credentials API/БД/S3.
|
||||
6. На 4 отзовите secret/cert и дождитесь контролируемого эффекта с учётом действующих соединений, TLS resumption и cache/TTL. Покажите новое подключение, иначе тест отзыва может ничего не проверить.
|
||||
|
||||
## Bootstrap и эксплуатация
|
||||
|
||||
В репозитории только открытые конфиги, policy templates и scripts. CA private key, leaf keys, root token, unseal shares и SecretID не коммитятся, не запекаются в образ и не печатаются в отчёте. Для локального стенда оператор создаёт их вне Git и передаёт через files/secrets с ограниченными правами. Опишите, кто имеет доступ к CA/unseal, что нужно после рестарта OpenBao и как восстановить работу.
|
||||
|
||||
OpenBao не использует dev-mode. Выберите persistent storage и auth метод (например AppRole с короткоживущим SecretID/response wrapping, cert auth или иная обоснованная identity). Не подменяйте root token постоянной переменной BAO_TOKEN в приложении. Рабочие tokens имеют policy, TTL и renewal/re-auth сценарий. Статические KV secrets на 3 допустимы при реальном чтении через сервисную identity; динамические DB credentials — хорошее расширение, но не обязательное название технологии.
|
||||
|
||||
Разрешённый компромисс учебного стенда: ручной operator init/unseal, если он безопасно документирован и не нужен при каждом обычном рестарте API. Автоматическое хранение всех unseal shares рядом с OpenBao без защиты не считается решённым bootstrap.
|
||||
**Тесты:** `docker compose --profile audit run --rm tls-audit` покрывает mTLS LB→API/broker/collector; `python tests/security.py --base-url https://localhost:8443 --ca-file .local/pki/ca.crt` проверяет внешний TLS; `tests/bao_policy_audit.py` и `s3-rotation-audit` — scoped/revoked secrets. Живые результаты нужно вписать в `REPORT.md`. Для revoked cert: `python scripts/rotate_leaf.py`, restart three HAProxy, then audit with `--volume` old leaf files (см. runbook).
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id UUID PRIMARY KEY,
|
||||
username VARCHAR(32) NOT NULL UNIQUE,
|
||||
display_name BYTEA NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),
|
||||
CONSTRAINT users_display_bytes CHECK (octet_length(display_name) BETWEEN 1 AND 400)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS chats (
|
||||
id UUID PRIMARY KEY,
|
||||
title BYTEA NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),
|
||||
CONSTRAINT chats_title_bytes CHECK (octet_length(title) BETWEEN 1 AND 400)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS chat_members (
|
||||
chat_id UUID NOT NULL REFERENCES chats(id),
|
||||
user_id UUID NOT NULL REFERENCES users(id),
|
||||
position INTEGER NOT NULL,
|
||||
PRIMARY KEY (chat_id, user_id),
|
||||
UNIQUE (chat_id, position)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_members_user ON chat_members (user_id, chat_id);
|
||||
CREATE TABLE IF NOT EXISTS messages (
|
||||
id UUID PRIMARY KEY,
|
||||
chat_id UUID NOT NULL REFERENCES chats(id),
|
||||
sender_id UUID NOT NULL,
|
||||
text BYTEA NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),
|
||||
FOREIGN KEY (chat_id, sender_id) REFERENCES chat_members(chat_id, user_id),
|
||||
CONSTRAINT messages_text_bytes CHECK (octet_length(text) BETWEEN 1 AND 16000)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_messages_chat_history ON messages (chat_id, created_at, id);
|
||||
CREATE INDEX IF NOT EXISTS idx_chats_history ON chats (created_at, id);
|
||||
@@ -0,0 +1,12 @@
|
||||
-- Same transaction creates message and idempotency receipt. Unique key arbitrates concurrent replicas.
|
||||
CREATE TABLE IF NOT EXISTS message_idempotency (
|
||||
actor_id UUID NOT NULL REFERENCES users(id),
|
||||
chat_id UUID NOT NULL REFERENCES chats(id),
|
||||
method VARCHAR(8) NOT NULL DEFAULT 'POST',
|
||||
idem_key VARCHAR(128) NOT NULL,
|
||||
body_sha256 CHAR(64) NOT NULL,
|
||||
message_id UUID NOT NULL REFERENCES messages(id),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),
|
||||
PRIMARY KEY (actor_id, chat_id, method, idem_key)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_idempotency_age ON message_idempotency (created_at);
|
||||
@@ -0,0 +1,25 @@
|
||||
ALTER TABLE messages DROP CONSTRAINT IF EXISTS messages_text_bytes;
|
||||
ALTER TABLE messages ADD CONSTRAINT messages_text_bytes CHECK (octet_length(text) BETWEEN 0 AND 16000);
|
||||
CREATE TABLE IF NOT EXISTS attachments (
|
||||
id UUID PRIMARY KEY,
|
||||
chat_id UUID NOT NULL REFERENCES chats(id),
|
||||
owner_id UUID NOT NULL REFERENCES users(id),
|
||||
object_key TEXT NOT NULL UNIQUE,
|
||||
backup_key TEXT NOT NULL UNIQUE,
|
||||
filename TEXT NOT NULL,
|
||||
content_type VARCHAR(32) NOT NULL CHECK(content_type IN ('image/png','image/jpeg')),
|
||||
size_bytes BIGINT NOT NULL CHECK(size_bytes BETWEEN 1 AND 10485760),
|
||||
sha256 CHAR(64) NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),
|
||||
FOREIGN KEY (chat_id,owner_id) REFERENCES chat_members(chat_id,user_id)
|
||||
);
|
||||
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),
|
||||
position INTEGER NOT NULL CHECK(position BETWEEN 0 AND 9),
|
||||
PRIMARY KEY (message_id, attachment_id),
|
||||
UNIQUE (message_id,position)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_message_attachments_attachment ON message_attachments(attachment_id);
|
||||
@@ -0,0 +1,58 @@
|
||||
-- Lab5: stage durably, then transact job and outbox atomically.
|
||||
ALTER TABLE attachments ADD COLUMN IF NOT EXISTS status TEXT NOT NULL DEFAULT 'ready'
|
||||
CHECK (status IN ('queued','processing','ready','failed'));
|
||||
ALTER TABLE attachments ADD COLUMN IF NOT EXISTS error_code TEXT;
|
||||
ALTER TABLE attachments ADD COLUMN IF NOT EXISTS staging_key TEXT;
|
||||
ALTER TABLE attachments ADD COLUMN IF NOT EXISTS pipeline_version INTEGER NOT NULL DEFAULT 1;
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_attachments_staging ON attachments(staging_key) WHERE staging_key IS NOT NULL;
|
||||
CREATE INDEX IF NOT EXISTS idx_attachments_status ON attachments(status);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS attachment_variants (
|
||||
attachment_id UUID NOT NULL REFERENCES attachments(id),
|
||||
pipeline_version INTEGER NOT NULL CHECK (pipeline_version >= 1),
|
||||
name TEXT NOT NULL CHECK (name IN ('thumbnail','crop','optimized')),
|
||||
object_key TEXT NOT NULL UNIQUE,
|
||||
content_type TEXT NOT NULL,
|
||||
size_bytes BIGINT NOT NULL CHECK (size_bytes > 0),
|
||||
sha256 CHAR(64) NOT NULL,
|
||||
width INTEGER NOT NULL CHECK (width > 0),
|
||||
height INTEGER NOT NULL CHECK (height > 0),
|
||||
PRIMARY KEY (attachment_id,pipeline_version,name)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS processing_jobs (
|
||||
id UUID PRIMARY KEY,
|
||||
attachment_id UUID NOT NULL UNIQUE REFERENCES attachments(id),
|
||||
pipeline_version INTEGER NOT NULL DEFAULT 1,
|
||||
status TEXT NOT NULL DEFAULT 'queued' CHECK (status IN ('queued','processing','ready','failed')),
|
||||
attempt INTEGER NOT NULL DEFAULT 1 CHECK (attempt >= 1),
|
||||
next_run_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
lease_token UUID,
|
||||
leased_until TIMESTAMPTZ,
|
||||
error_code TEXT,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_jobs_leases ON processing_jobs(status, leased_until);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS job_outbox (
|
||||
id UUID PRIMARY KEY,
|
||||
job_id UUID NOT NULL REFERENCES processing_jobs(id),
|
||||
payload JSONB NOT NULL,
|
||||
available_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
published_at TIMESTAMPTZ,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_outbox_due ON job_outbox(available_at, created_at) WHERE published_at IS NULL;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS job_replay_audit (
|
||||
id UUID PRIMARY KEY,
|
||||
job_id UUID NOT NULL REFERENCES processing_jobs(id),
|
||||
replayed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
action TEXT NOT NULL DEFAULT 'operator_replay'
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS job_fault_once (
|
||||
job_id UUID NOT NULL REFERENCES processing_jobs(id),
|
||||
fault TEXT NOT NULL,
|
||||
PRIMARY KEY (job_id,fault)
|
||||
);
|
||||
@@ -0,0 +1,18 @@
|
||||
# ЛР7: локальные проверки кандидата (без работающего Docker)
|
||||
|
||||
Сборка подготовлена 2026-11-21. Исполнялись команды именно по этому дереву исходников; runtime API/контейнеры здесь не стартовали, поскольку в окружении сборки отсутствует Docker CLI/daemon.
|
||||
|
||||
| Команда/сценарий | Фактический результат |
|
||||
| --- | --- |
|
||||
| `python3 -m compileall -q app tests scripts` | PASS (exit 0) |
|
||||
| `python3 scripts/check_contract.py` | `PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.` |
|
||||
| `python3 tests/security_unit.py` | `PASS: scoped OpenBao policies, mTLS identity ACLs, public SAN configuration` |
|
||||
| `yaml.safe_load(compose.yaml)` + проверка списка mount/ports | PASS: 34 services, оба host ports опубликованы только `127.0.0.1` (8443 HTTPS API и 3443 HTTPS Grafana), все статические bind source файлы существуют |
|
||||
| Запуск `bootstrap_env.py`, `bootstrap_pki.py`, `rotate_leaf.py` в отдельном временном каталоге | PASS: синтетическая `.env`, 18 scoped leaf сертификатов, локальный CA и CRL созданы, ключи не внесены в репозиторий |
|
||||
| `openssl verify -CAfile ca.crt ingress.crt` | `...: OK` |
|
||||
| `openssl verify -CAfile ca.crt -crl_check -CRLfile ca.crl lb-client.crt` после ротации | `...: OK` (новый cert) |
|
||||
| `openssl verify ... previous/lb-client.crt` после ротации | FAIL как **ожидаемый отрицательный** результат: старый серийный номер в CRL |
|
||||
| `openssl verify -CAfile ca.crt foreign-client.crt` | FAIL как **ожидаемый отрицательный** результат: чужой CA |
|
||||
| Парсинг SAN для server/client cert | PASS: SAN extension присутствует у всех ожидаемых ролей |
|
||||
|
||||
Не выполнены в среде сборки: `docker compose config`, HAProxy parser `haproxy -c`, OpenBao init/unseal/API, DB role grants, AMQP broker negative tests, OTel export/p99 dashboard, внешний TLS smoke, session/ACL live, restart/failover/persistence, Trivy scan. Их необходимо выполнить на Docker Desktop перед заявлением уровня 4; реальные команды собраны в [SECURITY_RUNBOOK.md](../SECURITY_RUNBOOK.md).
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,4 @@
|
||||
# Persistent SeaweedFS filer metadata for the single-node lab stack.
|
||||
[leveldb2]
|
||||
enabled = true
|
||||
dir = "/data/filerldb2"
|
||||
@@ -0,0 +1,13 @@
|
||||
ui = false
|
||||
disable_mlock = true
|
||||
storage "file" {
|
||||
path = "/openbao/file"
|
||||
}
|
||||
listener "tcp" {
|
||||
address = "0.0.0.0:8200"
|
||||
tls_disable = 0
|
||||
tls_cert_file = "/run/pki/openbao.crt"
|
||||
tls_key_file = "/run/pki/openbao.key"
|
||||
tls_min_version = "tls12"
|
||||
}
|
||||
api_addr = "https://openbao:8200"
|
||||
@@ -0,0 +1,4 @@
|
||||
# Short-lived tokens can only retrieve the credential bundle for api.
|
||||
path "kv/data/api" {
|
||||
capabilities = ["read"]
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
# Short-lived tokens can only retrieve the credential bundle for dispatcher.
|
||||
path "kv/data/dispatcher" {
|
||||
capabilities = ["read"]
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
# Short-lived tokens can only retrieve the credential bundle for worker.
|
||||
path "kv/data/worker" {
|
||||
capabilities = ["read"]
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
receivers:
|
||||
otlp:
|
||||
protocols:
|
||||
grpc:
|
||||
endpoint: 0.0.0.0:4317
|
||||
http:
|
||||
endpoint: 0.0.0.0:4318
|
||||
processors:
|
||||
memory_limiter:
|
||||
check_interval: 1s
|
||||
limit_mib: 180
|
||||
spike_limit_mib: 40
|
||||
batch:
|
||||
timeout: 1s
|
||||
send_batch_size: 128
|
||||
send_batch_max_size: 256
|
||||
exporters:
|
||||
prometheus:
|
||||
endpoint: 0.0.0.0:8889
|
||||
metric_expiration: 15s
|
||||
add_metric_suffixes: true
|
||||
resource_to_telemetry_conversion:
|
||||
enabled: true
|
||||
otlp/tempo:
|
||||
endpoint: metrics-gw:4317
|
||||
tls:
|
||||
ca_file: /run/pki/ca.crt
|
||||
cert_file: /run/pki/client.crt
|
||||
key_file: /run/pki/client.key
|
||||
timeout: 3s
|
||||
sending_queue:
|
||||
enabled: true
|
||||
num_consumers: 1
|
||||
queue_size: 64
|
||||
retry_on_failure:
|
||||
enabled: true
|
||||
initial_interval: 1s
|
||||
max_interval: 3s
|
||||
max_elapsed_time: 10s
|
||||
otlphttp/loki:
|
||||
endpoint: https://metrics-gw:3102/otlp
|
||||
tls:
|
||||
ca_file: /run/pki/ca.crt
|
||||
cert_file: /run/pki/client.crt
|
||||
key_file: /run/pki/client.key
|
||||
timeout: 3s
|
||||
sending_queue:
|
||||
enabled: true
|
||||
num_consumers: 1
|
||||
queue_size: 64
|
||||
retry_on_failure:
|
||||
enabled: true
|
||||
initial_interval: 1s
|
||||
max_interval: 3s
|
||||
max_elapsed_time: 10s
|
||||
service:
|
||||
telemetry:
|
||||
metrics:
|
||||
readers:
|
||||
- pull:
|
||||
exporter:
|
||||
prometheus:
|
||||
host: 0.0.0.0
|
||||
port: 8888
|
||||
pipelines:
|
||||
metrics:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, batch]
|
||||
exporters: [prometheus]
|
||||
logs:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, batch]
|
||||
exporters: [otlphttp/loki]
|
||||
traces:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, batch]
|
||||
exporters: [otlp/tempo]
|
||||
@@ -0,0 +1,805 @@
|
||||
{
|
||||
"uid": "lab6-messenger",
|
||||
"title": "Lab6 | Messenger observability",
|
||||
"schemaVersion": 39,
|
||||
"version": 1,
|
||||
"editable": false,
|
||||
"timezone": "browser",
|
||||
"refresh": "5s",
|
||||
"time": {
|
||||
"from": "now-15m",
|
||||
"to": "now"
|
||||
},
|
||||
"tags": [
|
||||
"lab6",
|
||||
"otel"
|
||||
],
|
||||
"panels": [
|
||||
{
|
||||
"id": 1,
|
||||
"type": "timeseries",
|
||||
"title": "Business API throughput",
|
||||
"description": "Excludes health, counts completed responses.",
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 0,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "reqps"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "sum(rate(lab_http_requests_total{route=~\"/api/.*\"}[30s]))",
|
||||
"legendFormat": "all",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"editorMode": "code"
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"expr": "sum(rate(lab_http_requests_total{route=~\"/api/.*\",status_class=\"5xx\"}[30s])) or vector(0)",
|
||||
"legendFormat": "5xx",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"editorMode": "code"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"type": "timeseries",
|
||||
"title": "Business API error ratio (5xx)",
|
||||
"description": "5xx / all business HTTP responses; threshold 5%.",
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 0,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "percentunit"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "(sum(rate(lab_http_requests_total{route=~\"/api/.*\",status_class=\"5xx\"}[30s])) or vector(0)) / clamp_min(sum(rate(lab_http_requests_total{route=~\"/api/.*\"}[30s])),0.001)",
|
||||
"legendFormat": "5xx / all",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"editorMode": "code"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"type": "timeseries",
|
||||
"title": "API latency p50/p95/p99",
|
||||
"description": "Aggregated histogram buckets across API replicas; seconds, time to response headers.",
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 8,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "s"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "histogram_quantile(0.5, sum(rate(lab_http_duration_seconds_bucket{route=~\"/api/.*\"}[30s])) by (le))",
|
||||
"legendFormat": "p50",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"editorMode": "code"
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"expr": "histogram_quantile(0.95, sum(rate(lab_http_duration_seconds_bucket{route=~\"/api/.*\"}[30s])) by (le))",
|
||||
"legendFormat": "p95",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"editorMode": "code"
|
||||
},
|
||||
{
|
||||
"refId": "C",
|
||||
"expr": "histogram_quantile(0.99, sum(rate(lab_http_duration_seconds_bucket{route=~\"/api/.*\"}[30s])) by (le))",
|
||||
"legendFormat": "p99",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"editorMode": "code"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"type": "timeseries",
|
||||
"title": "Jobs per second by outcome",
|
||||
"description": "Attempt outcomes: ready, retry, failed, stale, requeue; not exactly-once audit counts.",
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 8,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "ops"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "sum by(outcome)(rate(lab_jobs_total[30s]))",
|
||||
"legendFormat": "{{outcome}}",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"editorMode": "code"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"type": "timeseries",
|
||||
"title": "Worker processing duration",
|
||||
"description": "",
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 16,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "s"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "histogram_quantile(0.5, sum(rate(lab_job_duration_seconds_bucket[30s])) by (le))",
|
||||
"legendFormat": "p50",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"editorMode": "code"
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"expr": "histogram_quantile(0.95, sum(rate(lab_job_duration_seconds_bucket[30s])) by (le))",
|
||||
"legendFormat": "p95",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"editorMode": "code"
|
||||
},
|
||||
{
|
||||
"refId": "C",
|
||||
"expr": "histogram_quantile(0.99, sum(rate(lab_job_duration_seconds_bucket[30s])) by (le))",
|
||||
"legendFormat": "p99",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"editorMode": "code"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 6,
|
||||
"type": "timeseries",
|
||||
"title": "Time to ready",
|
||||
"description": "Acceptance to durable ready (includes queue, retry and processing).",
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 16,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "s"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "histogram_quantile(0.5, sum(rate(lab_ready_duration_seconds_bucket[30s])) by (le))",
|
||||
"legendFormat": "p50",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"editorMode": "code"
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"expr": "histogram_quantile(0.95, sum(rate(lab_ready_duration_seconds_bucket[30s])) by (le))",
|
||||
"legendFormat": "p95",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"editorMode": "code"
|
||||
},
|
||||
{
|
||||
"refId": "C",
|
||||
"expr": "histogram_quantile(0.99, sum(rate(lab_ready_duration_seconds_bucket[30s])) by (le))",
|
||||
"legendFormat": "p99",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"editorMode": "code"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 7,
|
||||
"type": "timeseries",
|
||||
"title": "Queue depth: durable backlog / RabbitMQ ready",
|
||||
"description": "DB queued includes delayed/unpublished tasks; RabbitMQ ready counts published messages waiting for delivery; neither includes busy jobs.",
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 24,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "max(lab_queue_depth)",
|
||||
"legendFormat": "DB queued",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"editorMode": "code"
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"expr": "max(lab_broker_ready)",
|
||||
"legendFormat": "broker ready",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"editorMode": "code"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 8,
|
||||
"type": "timeseries",
|
||||
"title": "Oldest queued job age",
|
||||
"description": "",
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 24,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "s"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "max(lab_queue_oldest_age_seconds)",
|
||||
"legendFormat": "age",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"editorMode": "code"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 9,
|
||||
"type": "timeseries",
|
||||
"title": "Database pool",
|
||||
"description": "",
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 32,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "lab_db_pool_used",
|
||||
"legendFormat": "used {{service_instance_id}}",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"editorMode": "code"
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"expr": "lab_db_pool_waiting",
|
||||
"legendFormat": "waiting {{service_instance_id}}",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"editorMode": "code"
|
||||
},
|
||||
{
|
||||
"refId": "C",
|
||||
"expr": "lab_db_pool_capacity",
|
||||
"legendFormat": "capacity {{service_instance_id}}",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"editorMode": "code"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 10,
|
||||
"type": "timeseries",
|
||||
"title": "Worker saturation",
|
||||
"description": "",
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 32,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "percentunit"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "sum(lab_worker_busy) / clamp_min(sum(lab_worker_capacity),1)",
|
||||
"legendFormat": "busy / capacity",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"editorMode": "code"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 11,
|
||||
"type": "timeseries",
|
||||
"title": "Container memory (or tree RSS fallback)",
|
||||
"description": "",
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 40,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "bytes"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "lab_container_memory_bytes",
|
||||
"legendFormat": "{{service_name}} / {{service_instance_id}}",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"editorMode": "code"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 12,
|
||||
"type": "timeseries",
|
||||
"title": "Container CPU",
|
||||
"description": "CPU cores: 1.0 = one logical core.",
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 40,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "lab_container_cpu_cores",
|
||||
"legendFormat": "{{service_name}} / {{service_instance_id}}",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"editorMode": "code"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 13,
|
||||
"type": "timeseries",
|
||||
"title": "Collector exporter queue",
|
||||
"description": "",
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 48,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "otelcol_exporter_queue_size",
|
||||
"legendFormat": "{{exporter}} queue",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"editorMode": "code"
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"expr": "otelcol_exporter_queue_capacity",
|
||||
"legendFormat": "{{exporter}} capacity",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"editorMode": "code"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 14,
|
||||
"type": "timeseries",
|
||||
"title": "Collector failed exports",
|
||||
"description": "",
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 48,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "ops"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "rate(otelcol_exporter_send_failed_spans[30s]) or rate(otelcol_exporter_send_failed_spans_total[30s])",
|
||||
"legendFormat": "spans {{exporter}}",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"editorMode": "code"
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"expr": "rate(otelcol_exporter_send_failed_log_records[30s]) or rate(otelcol_exporter_send_failed_log_records_total[30s])",
|
||||
"legendFormat": "logs {{exporter}}",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"editorMode": "code"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 15,
|
||||
"type": "timeseries",
|
||||
"title": "Alert state",
|
||||
"description": "",
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 56,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "ALERTS{alertname=~\"Lab.*\"}",
|
||||
"legendFormat": "{{alertname}} / {{alertstate}}",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"editorMode": "code"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 16,
|
||||
"type": "timeseries",
|
||||
"title": "SLI: successful availability (5 min)",
|
||||
"description": "1 \u2212 5xx/all business responses over 5 min; objective >= 99%. No data if no traffic.",
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 56,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "percentunit"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "1 - ((sum(increase(lab_http_requests_total{route=~\"/api/.*\",status_class=\"5xx\"}[5m])) or vector(0)) / sum(increase(lab_http_requests_total{route=~\"/api/.*\"}[5m])))",
|
||||
"legendFormat": "actual SLI",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"editorMode": "code"
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"expr": "vector(0.99)",
|
||||
"legendFormat": "SLO target 99%",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"editorMode": "code"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
apiVersion: 1
|
||||
providers:
|
||||
- name: Lab6
|
||||
orgId: 1
|
||||
folder: MTUCI
|
||||
type: file
|
||||
disableDeletion: true
|
||||
allowUiUpdates: false
|
||||
updateIntervalSeconds: 10
|
||||
options:
|
||||
path: /var/lib/grafana/dashboards
|
||||
@@ -0,0 +1,36 @@
|
||||
apiVersion: 1
|
||||
datasources:
|
||||
- name: Prometheus
|
||||
type: prometheus
|
||||
uid: prometheus
|
||||
access: proxy
|
||||
url: https://metrics-gw:9091
|
||||
isDefault: true
|
||||
editable: false
|
||||
- name: Loki
|
||||
type: loki
|
||||
uid: loki
|
||||
access: proxy
|
||||
url: https://metrics-gw:3101
|
||||
jsonData:
|
||||
derivedFields:
|
||||
- name: TraceID
|
||||
matcherType: label
|
||||
matcherRegex: trace_id
|
||||
datasourceUid: tempo
|
||||
url: '$${__value.raw}'
|
||||
- name: Tempo
|
||||
type: tempo
|
||||
uid: tempo
|
||||
access: proxy
|
||||
url: https://metrics-gw:3201
|
||||
jsonData:
|
||||
tracesToLogsV2:
|
||||
datasourceUid: loki
|
||||
spanStartTimeShift: '-2s'
|
||||
spanEndTimeShift: '2s'
|
||||
filterByTraceID: true
|
||||
filterBySpanID: false
|
||||
tags:
|
||||
- key: service.name
|
||||
value: service_name
|
||||
@@ -0,0 +1,32 @@
|
||||
auth_enabled: false
|
||||
server:
|
||||
http_listen_port: 3100
|
||||
common:
|
||||
instance_addr: 127.0.0.1
|
||||
path_prefix: /loki
|
||||
storage:
|
||||
filesystem:
|
||||
chunks_directory: /loki/chunks
|
||||
rules_directory: /loki/rules
|
||||
replication_factor: 1
|
||||
ring:
|
||||
kvstore:
|
||||
store: inmemory
|
||||
schema_config:
|
||||
configs:
|
||||
- from: 2024-01-01
|
||||
store: tsdb
|
||||
object_store: filesystem
|
||||
schema: v13
|
||||
index:
|
||||
prefix: index_
|
||||
period: 24h
|
||||
limits_config:
|
||||
allow_structured_metadata: true
|
||||
retention_period: 72h
|
||||
compactor:
|
||||
working_directory: /loki/compactor
|
||||
retention_enabled: true
|
||||
delete_request_store: filesystem
|
||||
analytics:
|
||||
reporting_enabled: false
|
||||
@@ -0,0 +1,19 @@
|
||||
groups:
|
||||
- name: messenger-lab
|
||||
rules:
|
||||
- alert: LabAPIHighErrorRate
|
||||
expr: (sum(rate(lab_http_requests_total{route=~"/api/.*",status_class="5xx"}[30s])) or vector(0)) / clamp_min(sum(rate(lab_http_requests_total{route=~"/api/.*"}[30s])), 0.001) > 0.05
|
||||
for: 9s
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: Business HTTP 5xx rate exceeds 5% over 30 seconds
|
||||
runbook: REPORT.md#инциденты-и-runbook
|
||||
- alert: LabQueueLag
|
||||
expr: max(lab_queue_oldest_age_seconds) > 15 and max(lab_queue_depth) > 0
|
||||
for: 12s
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: Oldest queued job exceeds 15 seconds (sustained 12 seconds)
|
||||
runbook: REPORT.md#инциденты-и-runbook
|
||||
@@ -0,0 +1,18 @@
|
||||
global:
|
||||
scrape_interval: 3s
|
||||
evaluation_interval: 3s
|
||||
rule_files:
|
||||
- /etc/prometheus/alerts.yml
|
||||
scrape_configs:
|
||||
- job_name: lab-otlp
|
||||
scheme: https
|
||||
tls_config:
|
||||
ca_file: /run/pki/ca.crt
|
||||
static_configs:
|
||||
- targets: ['metrics-gw:8889']
|
||||
- job_name: collector-self
|
||||
scheme: https
|
||||
tls_config:
|
||||
ca_file: /run/pki/ca.crt
|
||||
static_configs:
|
||||
- targets: ['metrics-gw:8888']
|
||||
@@ -0,0 +1,22 @@
|
||||
server:
|
||||
http_listen_port: 3200
|
||||
distributor:
|
||||
receivers:
|
||||
otlp:
|
||||
protocols:
|
||||
grpc:
|
||||
endpoint: 0.0.0.0:4317
|
||||
http:
|
||||
endpoint: 0.0.0.0:4318
|
||||
storage:
|
||||
trace:
|
||||
backend: local
|
||||
wal:
|
||||
path: /var/tempo/wal
|
||||
local:
|
||||
path: /var/tempo/blocks
|
||||
compactor:
|
||||
compaction:
|
||||
block_retention: 72h
|
||||
usage_report:
|
||||
reporting_enabled: false
|
||||
@@ -0,0 +1,2 @@
|
||||
PostgreSQL native TLS: `ssl=on` and hostnossl reject in pg_hba.conf; verify-full on clients.
|
||||
Certificates are operator generated and copied to a private mounted volume by tls-prepare.
|
||||
@@ -0,0 +1,6 @@
|
||||
# Local only for initialization/administration inside the container.
|
||||
local all all trust
|
||||
hostnossl all all 0.0.0.0/0 reject
|
||||
hostnossl all all ::/0 reject
|
||||
hostssl all all 0.0.0.0/0 scram-sha-256
|
||||
hostssl all all ::/0 scram-sha-256
|
||||
@@ -0,0 +1,15 @@
|
||||
global
|
||||
log stdout format raw local0
|
||||
defaults
|
||||
mode http
|
||||
timeout connect 2s
|
||||
timeout client 60s
|
||||
timeout server 60s
|
||||
frontend from_lb
|
||||
bind :8443 ssl crt /run/pki/api1-tls.pem ca-file /run/pki/ca.crt crl-file /run/pki/ca.crl verify required ssl-min-ver TLSv1.2
|
||||
acl trusted_identity ssl_c_s_dn(cn) -m str lab7-lb
|
||||
acl trusted_san ssl_c_san -m reg (^|,)([[:space:]]*)DNS:lab7-lb($|,)
|
||||
http-request deny deny_status 403 unless trusted_identity trusted_san
|
||||
default_backend local_api
|
||||
backend local_api
|
||||
server app 127.0.0.1:8080 check
|
||||
@@ -0,0 +1,15 @@
|
||||
global
|
||||
log stdout format raw local0
|
||||
defaults
|
||||
mode http
|
||||
timeout connect 2s
|
||||
timeout client 60s
|
||||
timeout server 60s
|
||||
frontend from_lb
|
||||
bind :8443 ssl crt /run/pki/api2-tls.pem ca-file /run/pki/ca.crt crl-file /run/pki/ca.crl verify required ssl-min-ver TLSv1.2
|
||||
acl trusted_identity ssl_c_s_dn(cn) -m str lab7-lb
|
||||
acl trusted_san ssl_c_san -m reg (^|,)([[:space:]]*)DNS:lab7-lb($|,)
|
||||
http-request deny deny_status 403 unless trusted_identity trusted_san
|
||||
default_backend local_api
|
||||
backend local_api
|
||||
server app 127.0.0.1:8080 check
|
||||
@@ -0,0 +1,17 @@
|
||||
global
|
||||
log stdout format raw local0
|
||||
defaults
|
||||
mode tcp
|
||||
timeout connect 3s
|
||||
timeout client 90s
|
||||
timeout server 90s
|
||||
frontend mqtls
|
||||
bind :5671 ssl crt /run/pki/broker-gw.pem ca-file /run/pki/ca.crt crl-file /run/pki/ca.crl verify required ssl-min-ver TLSv1.2
|
||||
acl role_ok ssl_c_s_dn(cn) -m str messenger-worker messenger-dispatcher
|
||||
acl san_worker ssl_c_san -m reg (^|,)([[:space:]]*)DNS:messenger-worker($|,)
|
||||
acl san_dispatch ssl_c_san -m reg (^|,)([[:space:]]*)DNS:messenger-dispatcher($|,)
|
||||
tcp-request content reject unless role_ok
|
||||
tcp-request content reject unless san_worker or san_dispatch
|
||||
default_backend rabbitmq
|
||||
backend rabbitmq
|
||||
server b broker:5672 check
|
||||
@@ -0,0 +1,13 @@
|
||||
global
|
||||
log stdout format raw local0
|
||||
defaults
|
||||
mode http
|
||||
timeout connect 3s
|
||||
timeout client 60s
|
||||
timeout server 60s
|
||||
frontend public_tls
|
||||
bind :3443 ssl crt /run/pki/grafana-gw.pem ssl-min-ver TLSv1.2
|
||||
http-request set-header X-Forwarded-Proto https
|
||||
default_backend grafana_internal
|
||||
backend grafana_internal
|
||||
server grafana grafana:3000 check
|
||||
@@ -0,0 +1,24 @@
|
||||
global
|
||||
log stdout format raw local0
|
||||
maxconn 1000
|
||||
defaults
|
||||
mode http
|
||||
timeout connect 3s
|
||||
timeout client 60s
|
||||
timeout server 60s
|
||||
timeout http-request 7s
|
||||
option httplog
|
||||
resolvers docker
|
||||
nameserver dns 127.0.0.11:53
|
||||
hold valid 1s
|
||||
frontend https_public
|
||||
bind :8443 ssl crt /run/pki/ingress.pem ssl-min-ver TLSv1.2
|
||||
http-request set-header X-Forwarded-Proto https
|
||||
default_backend api_cluster
|
||||
backend api_cluster
|
||||
balance roundrobin
|
||||
option httpchk GET /health/ready
|
||||
http-check expect status 200
|
||||
default-server inter 2s fall 2 rise 1 slowstart 2s
|
||||
server api1 api1:8443 ssl ca-file /run/pki/ca.crt crt /run/pki/lb-client.pem verify required verifyhost api1-tls check resolvers docker init-addr none
|
||||
server api2 api2:8443 ssl ca-file /run/pki/ca.crt crt /run/pki/lb-client.pem verify required verifyhost api2-tls check resolvers docker init-addr none
|
||||
@@ -0,0 +1,59 @@
|
||||
global
|
||||
log stdout format raw local0
|
||||
defaults
|
||||
timeout connect 3s
|
||||
timeout client 60s
|
||||
timeout server 60s
|
||||
frontend prometheus_tls
|
||||
mode http
|
||||
bind :9091 ssl crt /run/pki/metrics-gw.pem ssl-min-ver TLSv1.2
|
||||
default_backend prometheus_plain
|
||||
backend prometheus_plain
|
||||
mode http
|
||||
server prometheus prometheus:9090
|
||||
frontend loki_tls
|
||||
mode http
|
||||
bind :3101 ssl crt /run/pki/metrics-gw.pem ssl-min-ver TLSv1.2
|
||||
default_backend loki_plain
|
||||
backend loki_plain
|
||||
mode http
|
||||
server loki loki:3100
|
||||
frontend tempo_tls
|
||||
mode http
|
||||
bind :3201 ssl crt /run/pki/metrics-gw.pem ssl-min-ver TLSv1.2
|
||||
default_backend tempo_plain
|
||||
backend tempo_plain
|
||||
mode http
|
||||
server tempo tempo:3200
|
||||
frontend tempo_grpc_tls
|
||||
mode tcp
|
||||
bind :4317 ssl crt /run/pki/metrics-gw.pem ca-file /run/pki/ca.crt crl-file /run/pki/ca.crl verify required alpn h2 ssl-min-ver TLSv1.2
|
||||
acl collector_role ssl_c_s_dn(cn) -m str messenger-collector
|
||||
acl collector_san ssl_c_san -m reg (^|,)([[:space:]]*)DNS:messenger-collector($|,)
|
||||
tcp-request content reject unless collector_role collector_san
|
||||
default_backend tempo_grpc_plain
|
||||
backend tempo_grpc_plain
|
||||
mode tcp
|
||||
server tempo tempo:4317
|
||||
frontend collector_scrape_tls
|
||||
mode http
|
||||
bind :8889 ssl crt /run/pki/metrics-gw.pem ssl-min-ver TLSv1.2
|
||||
default_backend collector_scrape_plain
|
||||
backend collector_scrape_plain
|
||||
mode http
|
||||
server collector otel-collector:8889
|
||||
frontend collector_self_tls
|
||||
mode http
|
||||
bind :8888 ssl crt /run/pki/metrics-gw.pem ssl-min-ver TLSv1.2
|
||||
default_backend collector_self_plain
|
||||
backend collector_self_plain
|
||||
mode http
|
||||
server collector otel-collector:8888
|
||||
|
||||
frontend loki_ingest_mtls
|
||||
mode http
|
||||
bind :3102 ssl crt /run/pki/metrics-gw.pem ca-file /run/pki/ca.crt crl-file /run/pki/ca.crl verify required ssl-min-ver TLSv1.2
|
||||
acl collector_role ssl_c_s_dn(cn) -m str messenger-collector
|
||||
acl collector_san ssl_c_san -m reg (^|,)([[:space:]]*)DNS:messenger-collector($|,)
|
||||
http-request deny deny_status 403 unless collector_role collector_san
|
||||
default_backend loki_plain
|
||||
@@ -0,0 +1,15 @@
|
||||
global
|
||||
log stdout format raw local0
|
||||
defaults
|
||||
mode http
|
||||
timeout connect 3s
|
||||
timeout client 15s
|
||||
timeout server 15s
|
||||
frontend tls_ingest
|
||||
bind :4318 ssl crt /run/pki/otel-gw.pem ca-file /run/pki/ca.crt crl-file /run/pki/ca.crl verify required ssl-min-ver TLSv1.2
|
||||
acl identity_ok ssl_c_s_dn(cn) -m str messenger-api1 messenger-api2 messenger-worker messenger-dispatcher
|
||||
acl san_ok ssl_c_san -m reg (^|,)([[:space:]]*)DNS:messenger-(api1|api2|worker|dispatcher)($|,)
|
||||
http-request deny deny_status 403 unless identity_ok san_ok
|
||||
default_backend otlp_http
|
||||
backend otlp_http
|
||||
server collector otel-collector:4318 check
|
||||
@@ -0,0 +1,12 @@
|
||||
global
|
||||
log stdout format raw local0
|
||||
defaults
|
||||
mode tcp
|
||||
timeout connect 2s
|
||||
timeout client 90s
|
||||
timeout server 90s
|
||||
frontend redis_tls
|
||||
bind :6380 ssl crt /run/pki/redis-gw.pem ssl-min-ver TLSv1.2
|
||||
default_backend plain_redis
|
||||
backend plain_redis
|
||||
server redis redis:6379 check
|
||||
@@ -0,0 +1,12 @@
|
||||
global
|
||||
log stdout format raw local0
|
||||
defaults
|
||||
mode http
|
||||
timeout connect 3s
|
||||
timeout client 60s
|
||||
timeout server 60s
|
||||
frontend s3_https
|
||||
bind :8334 ssl crt /run/pki/s3-gw.pem ssl-min-ver TLSv1.2
|
||||
default_backend seaweed
|
||||
backend seaweed
|
||||
server s3 s3:8333 check
|
||||
@@ -1,2 +1,4 @@
|
||||
# Only for full OpenAPI/JSON Schema validation; HTTP tests use stdlib.
|
||||
openapi-spec-validator==0.7.2
|
||||
|
||||
cryptography==46.0.4
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
fastapi==0.165.0
|
||||
uvicorn==0.34.2
|
||||
pydantic==2.11.4
|
||||
psycopg[binary]==3.2.6
|
||||
psycopg-pool==3.2.6
|
||||
redis==5.2.1
|
||||
argon2-cffi==23.1.0
|
||||
|
||||
boto3==1.40.0
|
||||
Pillow==13.0.0
|
||||
pika==1.3.2
|
||||
|
||||
opentelemetry-api==1.44.0
|
||||
opentelemetry-sdk==1.44.0
|
||||
opentelemetry-exporter-otlp-proto-http==1.44.0
|
||||
psutil==7.2.2
|
||||
|
||||
PyYAML==6.0.2
|
||||
|
||||
|
||||
|
||||
starlette==1.10.0
|
||||
@@ -0,0 +1,78 @@
|
||||
"""Operator-only OpenBao policies, KV bundles, AppRole issue. Avoid printing secrets.
|
||||
|
||||
The root token is read only by this ephemeral bootstrap container. No root token
|
||||
or unseal key is ever mounted into the long-running application containers.
|
||||
"""
|
||||
import json, os, ssl
|
||||
from pathlib import Path
|
||||
from urllib.request import Request, urlopen
|
||||
from urllib.error import HTTPError
|
||||
|
||||
addr='https://openbao:8200/v1/'
|
||||
context=ssl.create_default_context(cafile='/run/pki/ca.crt')
|
||||
operator=json.loads(Path('/operator/init.json').read_text())
|
||||
token=operator['root_token']
|
||||
|
||||
def call(method,path,data=None,raw=False):
|
||||
headers={'X-Vault-Token':token}
|
||||
body=None
|
||||
if data is not None:
|
||||
body=(data if raw else json.dumps(data).encode('utf-8'))
|
||||
headers['Content-Type']='application/x-www-form-urlencoded' if raw else 'application/json'
|
||||
req=Request(addr+path,data=body,headers=headers,method=method)
|
||||
try:
|
||||
with urlopen(req,context=context,timeout=10) as r:
|
||||
content=r.read()
|
||||
return json.loads(content) if content else {}
|
||||
except HTTPError as e:
|
||||
raise RuntimeError(f'OpenBao bootstrap HTTP {e.code} for {path} (body hidden)') from None
|
||||
|
||||
def main():
|
||||
try: call('POST','sys/mounts/kv',{'type':'kv','options':{'version':'2'},'description':'App service credentials'})
|
||||
except RuntimeError:
|
||||
# Re-executing bootstrap against an existing KV mount is expected.
|
||||
mounts=call('GET','sys/mounts')
|
||||
if 'kv/' not in mounts: raise
|
||||
try: call('POST','sys/auth/approle',{'type':'approle'})
|
||||
except RuntimeError:
|
||||
methods=call('GET','sys/auth')
|
||||
if 'approle/' not in methods: raise
|
||||
root=Path('/issued');root.mkdir(parents=True,exist_ok=True)
|
||||
def create(role,values):
|
||||
policy=Path('/policies/'+role+'.hcl').read_text()
|
||||
call('PUT','sys/policies/acl/'+role,{'policy':policy})
|
||||
call('POST','kv/data/'+role,{'data':values})
|
||||
call('POST','auth/approle/role/'+role,{
|
||||
'bind_secret_id':True,'secret_id_ttl':'24h','secret_id_num_uses':0,
|
||||
'token_policies':[role],'token_ttl':'10m','token_max_ttl':'30m',
|
||||
'token_no_default_policy':True})
|
||||
role_id=call('GET','auth/approle/role/'+role+'/role-id')['data']['role_id']
|
||||
secret_id=call('POST','auth/approle/role/'+role+'/secret-id',{})['data']['secret_id']
|
||||
# Docker named volumes: own role directory, not Windows bind-mounted files.
|
||||
# Fail closed if Linux ownership cannot be applied; never chmod secrets world-readable.
|
||||
role_dir=root/role
|
||||
role_dir.mkdir(parents=True,exist_ok=True)
|
||||
os.chown(role_dir,999,999)
|
||||
os.chmod(role_dir,0o700)
|
||||
for suffix, value in (('role_id',role_id),('secret_id',secret_id)):
|
||||
path=role_dir/suffix
|
||||
path.write_text(value)
|
||||
os.chown(path,999,999)
|
||||
os.chmod(path,0o600)
|
||||
pfx='postgresql://'
|
||||
host='@postgres:5432/'+os.environ['POSTGRES_DB']+'?sslmode=verify-full&sslrootcert=/run/pki/ca.crt'
|
||||
# passwords are URL-encoded to avoid reserved characters from token_urlsafe etc.
|
||||
from urllib.parse import quote
|
||||
def db(role): return pfx+'messenger_'+role+':'+quote(os.environ['DB_'+role.upper()+'_PASSWORD'],safe='')+host
|
||||
s3_common={'S3_ENDPOINT':'https://s3-gw:8334','S3_BUCKET':os.environ['S3_BUCKET']}
|
||||
create('api', {'DATABASE_URL':db('api'),'REDIS_URL':'rediss://:'+quote(os.environ['REDIS_PASSWORD'],safe='')+'@redis-gw:6380/0?ssl_ca_certs=/run/pki/ca.crt',
|
||||
**s3_common, 'S3_ACCESS_KEY':os.environ['S3_API_ACCESS_KEY'],'S3_SECRET_KEY':os.environ['S3_API_SECRET_KEY']})
|
||||
create('worker', {'DATABASE_URL':db('worker'), **s3_common,
|
||||
'S3_ACCESS_KEY':os.environ['S3_WORKER_ACCESS_KEY'],'S3_SECRET_KEY':os.environ['S3_WORKER_SECRET_KEY'],
|
||||
'BROKER_HOST':'broker-gw','BROKER_PORT':'5671','BROKER_USER':os.environ['BROKER_WORKER_USER'],'BROKER_PASSWORD':os.environ['BROKER_WORKER_PASSWORD']})
|
||||
create('dispatcher',{'DATABASE_URL':db('dispatcher'),
|
||||
**s3_common,'S3_ACCESS_KEY':os.environ['S3_DISPATCHER_ACCESS_KEY'],'S3_SECRET_KEY':os.environ['S3_DISPATCHER_SECRET_KEY'],
|
||||
'BROKER_HOST':'broker-gw','BROKER_PORT':'5671','BROKER_USER':os.environ['BROKER_DISPATCHER_USER'],'BROKER_PASSWORD':os.environ['BROKER_DISPATCHER_PASSWORD']})
|
||||
print('OpenBao policies, bundles, AppRole identities installed (values omitted)')
|
||||
|
||||
if __name__=='__main__': main()
|
||||
@@ -0,0 +1,24 @@
|
||||
"""Create the local operator-owned synthetic secret inventory, never commit it."""
|
||||
import secrets
|
||||
from pathlib import Path
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
dest = root / '.env'
|
||||
if dest.exists():
|
||||
raise SystemExit('.env already exists; do not overwrite live secrets')
|
||||
keys = ('POSTGRES_PASSWORD', 'BROKER_ADMIN_PASSWORD', 'BROKER_DISPATCHER_PASSWORD',
|
||||
'BROKER_WORKER_PASSWORD', 'S3_ADMIN_SECRET_KEY', 'S3_API_SECRET_KEY',
|
||||
'S3_WORKER_SECRET_KEY', 'S3_DISPATCHER_SECRET_KEY', 'GRAFANA_ADMIN_PASSWORD', 'DB_API_PASSWORD',
|
||||
'DB_WORKER_PASSWORD', 'DB_DISPATCHER_PASSWORD', 'REDIS_PASSWORD')
|
||||
values = {k: secrets.token_urlsafe(32) for k in keys}
|
||||
values.update({'POSTGRES_DB': 'messenger', 'POSTGRES_USER':'lab', 'BROKER_ADMIN_USER':'bootstrap',
|
||||
'BROKER_DISPATCHER_USER':'dispatcher','BROKER_WORKER_USER':'worker',
|
||||
'S3_BUCKET':'messenger-attachments','S3_ADMIN_ACCESS_KEY':'admin-'+secrets.token_hex(8),
|
||||
'S3_API_ACCESS_KEY':'api-'+secrets.token_hex(8),'S3_WORKER_ACCESS_KEY':'worker-'+secrets.token_hex(8),
|
||||
'S3_DISPATCHER_ACCESS_KEY':'dispatcher-'+secrets.token_hex(8),
|
||||
'OTEL_ENABLED':'yes','SESSION_TTL_SECONDS':'3600','JOB_MAX_ATTEMPTS':'5', 'JOB_TIMEOUT_SECONDS':'60',
|
||||
'LAB6_FAULT_RETRY_ONCE':'off','LAB5_FAULT_AFTER_S3':'off'})
|
||||
dest.write_text('# LOCAL TEST SECRETS - DO NOT COMMIT OR PRINT\n'+''.join(f'{k}={v}\n' for k,v in values.items()),encoding='utf-8')
|
||||
try: dest.chmod(0o600)
|
||||
except OSError: pass
|
||||
print('Created .env with synthetic per-role credentials (values omitted)')
|
||||
@@ -0,0 +1,82 @@
|
||||
"""Operator-owned local training PKI. Requires cryptography; no private keys in Git."""
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
import os
|
||||
import ipaddress
|
||||
from cryptography import x509
|
||||
from cryptography.x509.oid import NameOID, ExtendedKeyUsageOID
|
||||
from cryptography.hazmat.primitives import hashes, serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import ec
|
||||
|
||||
base=Path(__file__).resolve().parents[1]/'.local/pki'
|
||||
if (base/'ca.key').exists():
|
||||
raise SystemExit('Local CA already exists. Do not silently overwrite credentials. See rotation guide.')
|
||||
base.mkdir(parents=True,exist_ok=True)
|
||||
os.chmod(base,0o700)
|
||||
def save(path, data, sensitive=False):
|
||||
path.write_bytes(data)
|
||||
if sensitive: os.chmod(path,0o600)
|
||||
def key(): return ec.generate_private_key(ec.SECP256R1())
|
||||
def name(cn): return x509.Name([x509.NameAttribute(NameOID.COMMON_NAME,cn)])
|
||||
def out_key(k): return k.private_bytes(serialization.Encoding.PEM,serialization.PrivateFormat.PKCS8,serialization.NoEncryption())
|
||||
now=datetime.now(timezone.utc)-timedelta(minutes=5)
|
||||
ca=key()
|
||||
ca_cert=(x509.CertificateBuilder().subject_name(name('Lab7 Local CA')).issuer_name(name('Lab7 Local CA'))
|
||||
.public_key(ca.public_key()).serial_number(x509.random_serial_number()).not_valid_before(now)
|
||||
.not_valid_after(now+timedelta(days=365)).add_extension(x509.BasicConstraints(ca=True,path_length=0),critical=True)
|
||||
.add_extension(x509.KeyUsage(digital_signature=True, key_encipherment=False, content_commitment=False,
|
||||
data_encipherment=False,key_agreement=False,key_cert_sign=True,crl_sign=True,
|
||||
encipher_only=False,decipher_only=False),critical=True)
|
||||
.sign(ca,hashes.SHA256()))
|
||||
ca_pem=ca_cert.public_bytes(serialization.Encoding.PEM)
|
||||
save(base/'ca.crt',ca_pem);save(base/'ca.key',out_key(ca),True)
|
||||
# Servers have DNS SANs matching the actual Docker Compose service discovery names.
|
||||
servers={'ingress':['localhost'], 'api1-tls':['api1-tls'], 'api2-tls':['api2-tls'],
|
||||
'postgres':['postgres'], 'redis-gw':['redis-gw'], 's3-gw':['s3-gw'],
|
||||
'broker-gw':['broker-gw'], 'otel-gw':['otel-gw'], 'metrics-gw':['metrics-gw'],
|
||||
'openbao':['openbao'], 'grafana-gw':['localhost']}
|
||||
clients={'lb-client':'lab7-lb','api1-client':'messenger-api1','api2-client':'messenger-api2',
|
||||
'worker-client':'messenger-worker', 'dispatcher-client':'messenger-dispatcher',
|
||||
'rogue-client':'lab7-rogue', 'collector-client':'messenger-collector'}
|
||||
for alias,domains in {**servers, **{k:[] for k in clients}}.items():
|
||||
is_client=alias in clients
|
||||
cn=clients[alias] if is_client else domains[0]
|
||||
k=key()
|
||||
sans=[x509.DNSName(cn)] if is_client else [x509.DNSName(d) for d in domains]
|
||||
if alias in ('ingress','grafana-gw'): sans += [x509.IPAddress(ipaddress.ip_address('127.0.0.1'))]
|
||||
crt=(x509.CertificateBuilder().subject_name(name(cn)).issuer_name(ca_cert.subject)
|
||||
.public_key(k.public_key()).serial_number(x509.random_serial_number()).not_valid_before(now)
|
||||
.not_valid_after(now+timedelta(days=30)).add_extension(x509.BasicConstraints(ca=False,path_length=None),critical=True)
|
||||
.add_extension(x509.SubjectAlternativeName(sans),critical=False)
|
||||
.add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.CLIENT_AUTH if is_client else ExtendedKeyUsageOID.SERVER_AUTH]),critical=False)
|
||||
.sign(ca,hashes.SHA256()))
|
||||
certificate=crt.public_bytes(serialization.Encoding.PEM)
|
||||
private=out_key(k)
|
||||
save(base/(alias+'.crt'),certificate);save(base/(alias+'.key'),private,False)
|
||||
save(base/(alias+'.pem'),certificate+private,False)
|
||||
# Empty CRL to make later revocation a normal reload rather than a new TLS design.
|
||||
revocation=(x509.CertificateRevocationListBuilder().issuer_name(ca_cert.subject)
|
||||
.last_update(datetime.now(timezone.utc)-timedelta(minutes=1))
|
||||
.next_update(datetime.now(timezone.utc)+timedelta(days=7)).sign(ca,hashes.SHA256()))
|
||||
save(base/'ca.crl',revocation.public_bytes(serialization.Encoding.PEM))
|
||||
print('Created locally trusted CA and per-service certificates under .local/pki (private keys not printed)')
|
||||
|
||||
# A different CA and its client, for the required untrusted-CA negative test.
|
||||
foreign_key=key()
|
||||
foreign_ca=(x509.CertificateBuilder().subject_name(name('Lab7 Foreign Test CA'))
|
||||
.issuer_name(name('Lab7 Foreign Test CA')).public_key(foreign_key.public_key())
|
||||
.serial_number(x509.random_serial_number()).not_valid_before(now)
|
||||
.not_valid_after(now+timedelta(days=365))
|
||||
.add_extension(x509.BasicConstraints(ca=True,path_length=0),critical=True)
|
||||
.sign(foreign_key,hashes.SHA256()))
|
||||
foreign_leaf_key=key()
|
||||
foreign_leaf=(x509.CertificateBuilder().subject_name(name('lab7-lb'))
|
||||
.issuer_name(foreign_ca.subject).public_key(foreign_leaf_key.public_key())
|
||||
.serial_number(x509.random_serial_number()).not_valid_before(now)
|
||||
.not_valid_after(now+timedelta(days=30))
|
||||
.add_extension(x509.BasicConstraints(ca=False,path_length=None),critical=True)
|
||||
.add_extension(x509.SubjectAlternativeName([x509.DNSName('lab7-lb')]),critical=False)
|
||||
.add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.CLIENT_AUTH]),critical=False)
|
||||
.sign(foreign_key,hashes.SHA256()))
|
||||
save(base/'foreign-client.crt',foreign_leaf.public_bytes(serialization.Encoding.PEM))
|
||||
save(base/'foreign-client.key',out_key(foreign_leaf_key))
|
||||
@@ -0,0 +1,19 @@
|
||||
"""Offline contract check: role-local AppRole volumes, no shared secret bind mounts."""
|
||||
from pathlib import Path
|
||||
import yaml
|
||||
|
||||
root=Path(__file__).resolve().parents[1]
|
||||
model=yaml.safe_load((root/'compose.yaml').read_text())
|
||||
services=model['services']
|
||||
assert 'user: "999:999"' in (root/'compose.yaml').read_text(), 'App containers must be non-root'
|
||||
for role, members in {'api':['api1','api2'],'worker':['worker'],'dispatcher':['dispatcher']}.items():
|
||||
vol=f'bao_{role}_auth'
|
||||
assert vol in model['volumes'], f'{vol} missing'
|
||||
for member in members:
|
||||
v=services[member]['volumes']
|
||||
assert f'{vol}:/run/bao:ro' in v, f'{member} missing private read-only AppRole mount'
|
||||
assert not any('/run/bao' in s and s!=f'{vol}:/run/bao:ro' for s in v)
|
||||
assert f'{vol}:/issued/{role}' in services['bao-bootstrap']['volumes']
|
||||
assert f'{vol}:/role-files/{role}:ro' in services['bao-policy-audit']['volumes']
|
||||
assert not any('.local/bao' in s for s in (root/'compose.yaml').read_text().splitlines())
|
||||
print('PASS: role-scoped Docker volumes, non-root apps, audit mounts, no Windows bind AppRole creds')
|
||||
@@ -0,0 +1,46 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Additional static checks (not the teacher's make check and not a live deploy)."""
|
||||
import ast,json,re
|
||||
from pathlib import Path
|
||||
import yaml
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
|
||||
def main():
|
||||
count=0
|
||||
for path in (ROOT/'app').glob('*.py'):
|
||||
tree=ast.parse(path.read_text(encoding='utf-8'))
|
||||
for n in ast.walk(tree):
|
||||
if isinstance(n,ast.Call) and isinstance(n.func,ast.Attribute) and n.func.attr=='execute' and len(n.args)>1 and isinstance(n.args[0],ast.Constant) and isinstance(n.args[0].value,str) and isinstance(n.args[1],(ast.Tuple,ast.List)):
|
||||
assert n.args[0].value.count('%s')==len(n.args[1].elts),f'SQL binding mismatch: {path.name}:{n.lineno}'
|
||||
count+=1
|
||||
compose=yaml.safe_load((ROOT/'compose.yaml').read_text())
|
||||
for name,svc in compose['services'].items():
|
||||
if 'image' in svc:assert ':' in svc['image'] and not svc['image'].endswith(':latest'),name
|
||||
for port in svc.get('ports',[]):assert port.startswith('127.0.0.1:'),name
|
||||
for mount in svc.get('volumes',[]):
|
||||
src=mount.split(':')[0]
|
||||
assert (ROOT/src).exists() if src.startswith('./') else src in compose['volumes'],f'missing mount {src}'
|
||||
for network in svc.get('networks',[]):assert network in compose['networks']
|
||||
for dep in svc.get('depends_on',{}):assert dep in compose['services']
|
||||
for p in (ROOT/'infra/otel').rglob('*'):
|
||||
if p.suffix in ('.yml','.yaml'):yaml.safe_load(p.read_text())
|
||||
services=compose['services']; assert all('telemetry' in services[s]['networks'] for s in ('api1','api2','dispatcher','worker','otel-collector','prometheus','loki','tempo','grafana'))
|
||||
for v in ('prometheus_data','loki_data','tempo_data','grafana_data'):assert v in compose['volumes']
|
||||
collector=yaml.safe_load((ROOT/'infra/otel/collector.yaml').read_text())
|
||||
for signal in ('metrics','logs','traces'):
|
||||
pipe=collector['service']['pipelines'][signal]
|
||||
assert pipe['receivers']==['otlp'] and pipe['processors']==['memory_limiter','batch']
|
||||
assert all(e in collector['exporters'] for e in pipe['exporters'])
|
||||
for exp in ('otlp/tempo','otlphttp/loki'):
|
||||
conf=collector['exporters'][exp];assert conf['sending_queue']['queue_size']==64 and conf['retry_on_failure']['max_elapsed_time']=='10s'
|
||||
dashboard=json.loads((ROOT/'infra/otel/grafana/dashboards/messenger.json').read_text())
|
||||
expressions='\n'.join(t['expr'] for p in dashboard['panels'] for t in p['targets'])
|
||||
for metric in ('lab_http_requests_total','lab_http_duration_seconds_bucket','lab_jobs_total','lab_job_duration_seconds_bucket','lab_ready_duration_seconds_bucket','lab_queue_depth','lab_queue_oldest_age_seconds','lab_broker_ready','lab_db_pool_used','lab_db_pool_waiting','lab_worker_busy','lab_worker_capacity','lab_container_cpu_cores','lab_container_memory_bytes'):
|
||||
assert metric in expressions,metric
|
||||
assert all(f'histogram_quantile({q}' in expressions for q in (.5,.95,.99))
|
||||
rules=yaml.safe_load((ROOT/'infra/otel/prometheus/alerts.yml').read_text())
|
||||
assert {x['alert'] for g in rules['groups'] for x in g['rules']}=={'LabAPIHighErrorRate','LabQueueLag'}
|
||||
assert all(x.get('for') and x['annotations'].get('runbook') for g in rules['groups'] for x in g['rules'])
|
||||
print(f'PASS: {count} literal SQL bindings; pinned Compose images, mounts and networks; 3 OTLP pipelines, dashboards and alert rules (static only)')
|
||||
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,7 @@
|
||||
@echo off
|
||||
cd /d "%~dp0.."
|
||||
docker compose stop lb api1-tls api2-tls || exit /b 1
|
||||
docker compose restart postgres redis broker s3 || exit /b 1
|
||||
docker compose up -d --no-deps --force-recreate api1 api2 || exit /b 1
|
||||
docker compose up -d --no-deps --force-recreate api1-tls api2-tls lb
|
||||
exit /b %ERRORLEVEL%
|
||||
@@ -0,0 +1,9 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
# Namespaced sidecars must be restarted together with API instances.
|
||||
# Keep persistent volumes. Do not restart OpenBao (manual unseal).
|
||||
docker compose stop lb api1-tls api2-tls
|
||||
docker compose restart postgres redis broker s3
|
||||
docker compose up -d --no-deps --force-recreate api1 api2
|
||||
docker compose up -d --no-deps --force-recreate api1-tls api2-tls lb
|
||||
@@ -0,0 +1,50 @@
|
||||
"""Operator-only, rotate LB client certificate and revoke old serial via CA CRL.
|
||||
|
||||
Does not touch the CA; creates operator-only previous/*.key for live negative test.
|
||||
After this, restart LB and both API sidecars to pick up new cert + CRL.
|
||||
"""
|
||||
from datetime import datetime,timedelta,timezone
|
||||
from pathlib import Path
|
||||
import shutil,os
|
||||
from cryptography import x509
|
||||
from cryptography.hazmat.primitives import hashes,serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import ec
|
||||
from cryptography.x509.oid import NameOID,ExtendedKeyUsageOID
|
||||
|
||||
base=Path(__file__).resolve().parents[1]/'.local/pki'
|
||||
ca=x509.load_pem_x509_certificate((base/'ca.crt').read_bytes())
|
||||
key=serialization.load_pem_private_key((base/'ca.key').read_bytes(),password=None)
|
||||
leaf=base/'lb-client.crt'
|
||||
old=x509.load_pem_x509_certificate(leaf.read_bytes())
|
||||
previous=base/'previous';previous.mkdir(mode=0o700,exist_ok=True)
|
||||
for suffix in ('crt','key'):
|
||||
shutil.copy2(base/f'lb-client.{suffix}',previous/f'lb-client.{suffix}')
|
||||
serials=[]
|
||||
crlfile=base/'ca.crl'
|
||||
if crlfile.exists():
|
||||
existing=x509.load_pem_x509_crl(crlfile.read_bytes())
|
||||
serials=[r.serial_number for r in existing]
|
||||
serials.append(old.serial_number)
|
||||
now=datetime.now(timezone.utc)
|
||||
crlb=x509.CertificateRevocationListBuilder().issuer_name(ca.subject).last_update(now-timedelta(minutes=1)).next_update(now+timedelta(days=7))
|
||||
for serial in set(serials):
|
||||
crlb=crlb.add_revoked_certificate(x509.RevokedCertificateBuilder().serial_number(serial).revocation_date(now).build())
|
||||
crl=crlb.sign(key,hashes.SHA256())
|
||||
newkey=ec.generate_private_key(ec.SECP256R1())
|
||||
name=x509.Name([x509.NameAttribute(NameOID.COMMON_NAME,'lab7-lb')])
|
||||
cert=(x509.CertificateBuilder().subject_name(name).issuer_name(ca.subject)
|
||||
.public_key(newkey.public_key()).serial_number(x509.random_serial_number())
|
||||
.not_valid_before(now-timedelta(minutes=5)).not_valid_after(now+timedelta(days=30))
|
||||
.add_extension(x509.BasicConstraints(ca=False,path_length=None),critical=True)
|
||||
.add_extension(x509.SubjectAlternativeName([x509.DNSName('lab7-lb')]),critical=False)
|
||||
.add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.CLIENT_AUTH]),critical=False)
|
||||
.sign(key,hashes.SHA256()))
|
||||
certpem=cert.public_bytes(serialization.Encoding.PEM)
|
||||
keypem=newkey.private_bytes(serialization.Encoding.PEM,serialization.PrivateFormat.PKCS8,serialization.NoEncryption())
|
||||
(base/'lb-client.crt').write_bytes(certpem)
|
||||
(base/'lb-client.key').write_bytes(keypem)
|
||||
(base/'lb-client.pem').write_bytes(certpem+keypem)
|
||||
crlfile.write_bytes(crl.public_bytes(serialization.Encoding.PEM))
|
||||
print('Rotated LB client leaf and revoked previous serial in CRL (no keys shown).')
|
||||
print('Restart: docker compose restart api1-tls api2-tls lb')
|
||||
print('Negative audit with previous cert: mount previous/lb-client.crt and .key into tls-audit.')
|
||||
@@ -0,0 +1,34 @@
|
||||
"""Operator-only rotation of one S3 service secret in .env; never prints secret material.
|
||||
|
||||
Apply with SECURITY_RUNBOOK.md sequence. No credentials are injected into a Docker image.
|
||||
"""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
import sys
|
||||
|
||||
root=Path(__file__).resolve().parents[1]
|
||||
role=(sys.argv[1] if len(sys.argv)>1 else 'worker').lower()
|
||||
if role not in ('worker','api','dispatcher'):
|
||||
raise SystemExit('Usage: python scripts/rotate_s3_secret.py [worker|api|dispatcher]')
|
||||
key='S3_'+role.upper()+'_SECRET_KEY'
|
||||
env=root/'.env'
|
||||
lines=env.read_text(encoding='utf8').splitlines(keepends=True)
|
||||
found=[i for i,line in enumerate(lines) if line.startswith(key+'=')]
|
||||
if len(found)!=1: raise SystemExit('Expected exactly one '+key+' in .env')
|
||||
idx=found[0]
|
||||
old=lines[idx].split('=',1)[1].strip()
|
||||
if not old: raise SystemExit('Old credential missing')
|
||||
secret=secrets.token_urlsafe(40)
|
||||
operator=root/'.local/operator'
|
||||
operator.mkdir(parents=True,exist_ok=True)
|
||||
old_file=operator/('old-'+role+'-s3-secret.txt')
|
||||
old_file.write_text(old,encoding='utf8')
|
||||
os.chmod(old_file,0o600)
|
||||
lines[idx]=key+'='+secret+'\n'
|
||||
replacement=env.with_suffix('.new')
|
||||
replacement.write_text(''.join(lines),encoding='utf8')
|
||||
os.chmod(replacement,0o600)
|
||||
os.replace(replacement,env)
|
||||
print('Rotated '+key+' in operator .env; previous credential held under .local/operator (never commit).')
|
||||
print('Next: re-bootstrap OpenBao, regenerate S3 policy, restart S3 and matching app role, then run s3 rotation audit.')
|
||||
@@ -0,0 +1,62 @@
|
||||
# Sample observed Docker container memory/CPU during a Lab5 workload.
|
||||
# Usage (another terminal, while attachments_concurrent.py runs):
|
||||
# powershell -ExecutionPolicy Bypass -File scripts/sample_docker_resources.ps1 -DurationSeconds 45
|
||||
param(
|
||||
[ValidateRange(5, 3600)][int]$DurationSeconds = 45,
|
||||
[ValidateRange(250, 10000)][int]$IntervalMs = 1000,
|
||||
[string]$Output = 'evidence/worker-resources.csv'
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$composeArgs = @('compose', '--env-file', '.env')
|
||||
$ids = @( & docker @composeArgs ps -q worker api1 api2 | Where-Object { $_ -and $_.Trim() } )
|
||||
if ($LASTEXITCODE -ne 0 -or $ids.Count -ne 3) {
|
||||
throw 'Expected exactly 3 running containers: worker, api1, api2'
|
||||
}
|
||||
|
||||
function Convert-ToMiB([string]$usage) {
|
||||
$first = ($usage -split ' / ')[0].Trim()
|
||||
if ($first -notmatch '^([0-9]+(?:\.[0-9]+)?)\s*(B|KiB|MiB|GiB|TiB|kB|MB|GB|TB)$') {
|
||||
throw "Unrecognized docker stats memory format: $first"
|
||||
}
|
||||
$amount = [double]::Parse($Matches[1], [Globalization.CultureInfo]::InvariantCulture)
|
||||
$factor = switch -CaseSensitive ($Matches[2]) {
|
||||
'B' { 1 / 1048576.0 }
|
||||
'KiB' { 1 / 1024.0 }
|
||||
'MiB' { 1.0 }
|
||||
'GiB' { 1024.0 }
|
||||
'TiB' { 1048576.0 }
|
||||
'kB' { 1000.0 / 1048576.0 }
|
||||
'MB' { 1000000.0 / 1048576.0 }
|
||||
'GB' { 1000000000.0 / 1048576.0 }
|
||||
'TB' { 1000000000000.0 / 1048576.0 }
|
||||
}
|
||||
return [math]::Round($amount * $factor, 3)
|
||||
}
|
||||
|
||||
$rows = [System.Collections.Generic.List[object]]::new()
|
||||
$until = (Get-Date).AddSeconds($DurationSeconds)
|
||||
Write-Host "Sampling worker/api1/api2 until $($until.ToString('HH:mm:ss'))" -ForegroundColor Cyan
|
||||
while ((Get-Date) -lt $until) {
|
||||
$raw = @( & docker stats --no-stream --format '{{json .}}' @ids )
|
||||
if ($LASTEXITCODE -ne 0) { throw 'docker stats failed' }
|
||||
foreach ($line in $raw) {
|
||||
if ([string]::IsNullOrWhiteSpace($line)) { continue }
|
||||
$item = $line | ConvertFrom-Json
|
||||
$rows.Add([PSCustomObject]@{
|
||||
time = (Get-Date).ToUniversalTime().ToString('o')
|
||||
container = $item.Name
|
||||
memory_mib = Convert-ToMiB $item.MemUsage
|
||||
cpu_percent = [double]::Parse($item.CPUPerc.TrimEnd('%'), [Globalization.CultureInfo]::InvariantCulture)
|
||||
})
|
||||
}
|
||||
Start-Sleep -Milliseconds $IntervalMs
|
||||
}
|
||||
if ($rows.Count -eq 0) { throw 'No Docker stats samples collected' }
|
||||
$folder = Split-Path -Parent $Output
|
||||
if ($folder -and !(Test-Path $folder)) { New-Item -ItemType Directory -Path $folder -Force | Out-Null }
|
||||
$rows | Export-Csv -Path $Output -NoTypeInformation -Encoding UTF8
|
||||
$rows | Group-Object container | ForEach-Object {
|
||||
$peak = ($_.Group | Measure-Object -Property memory_mib -Maximum).Maximum
|
||||
"{0}: observed max container memory {1:N2} MiB, {2} samples" -f $_.Name, $peak, $_.Count
|
||||
}
|
||||
Write-Host "Saved $Output. Observed sampled memory, NOT true peak RSS." -ForegroundColor Green
|
||||
@@ -0,0 +1,7 @@
|
||||
#!/bin/sh
|
||||
# Dependency/image vulnerability scan for operator triage; needs Trivy installed.
|
||||
set -eu
|
||||
command -v trivy >/dev/null || { echo 'Install Trivy (no claim of clean scans)' >&2; exit 2; }
|
||||
trivy fs --scanners vuln --severity HIGH,CRITICAL --exit-code 0 .
|
||||
trivy image --scanners vuln --severity HIGH,CRITICAL --exit-code 0 mtusi-lab7-app:local
|
||||
# Review every result for reachability, fixes, and risk before PR.
|
||||
@@ -0,0 +1,12 @@
|
||||
@echo off
|
||||
cd /d "%~dp0.."
|
||||
if "%TARGET_INSTANCE_ID%"=="api1" (
|
||||
docker compose stop api1-tls api1
|
||||
exit /b %ERRORLEVEL%
|
||||
)
|
||||
if "%TARGET_INSTANCE_ID%"=="api2" (
|
||||
docker compose stop api2-tls api2
|
||||
exit /b %ERRORLEVEL%
|
||||
)
|
||||
echo Unknown TARGET_INSTANCE_ID 1>&2
|
||||
exit /b 2
|
||||
@@ -0,0 +1,9 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
case "${TARGET_INSTANCE_ID:?}" in
|
||||
api1|api2)
|
||||
# Stop TLS sidecar first: it shares the API network namespace.
|
||||
docker compose stop "${TARGET_INSTANCE_ID}-tls" "$TARGET_INSTANCE_ID" ;;
|
||||
*) echo 'Unsafe or unknown instance alias' >&2; exit 2;;
|
||||
esac
|
||||
@@ -0,0 +1,14 @@
|
||||
"""Operator-facing readiness wait after container replacement."""
|
||||
import time
|
||||
import urllib.request
|
||||
for _ in range(120):
|
||||
try:
|
||||
with urllib.request.urlopen("http://localhost:8080/health/ready", timeout=2) as response:
|
||||
if response.status == 200:
|
||||
print("[restart] all services ready")
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(.5)
|
||||
else:
|
||||
raise SystemExit("[restart] health timeout")
|
||||
+21
-10
@@ -1,19 +1,30 @@
|
||||
# Модель угроз — заполнить
|
||||
# Модель угроз ЛР7 — мессенджер/изображения/наблюдаемость
|
||||
|
||||
## Активы и акторы
|
||||
|
||||
TODO: пользовательские credentials/сессии, сообщения/вложения, service identities, CA/secrets, telemetry. Акторы: участник чата, посторонний пользователь, внешний клиент, скомпрометированный сервис, оператор. Опишите доступ атакующего и границы учебного стенда.
|
||||
**Активы:** пароли пользователей, Bearer-сессии, сообщения и metadata, изображения и производные размеры, PostgreSQL, S3, RabbitMQ outbox/jobs, trace/log/metrics, service identities, CA private key, OpenBao root/unseal/AppRole SecretID. **Акторы:** участник чата; зарегистрированный посторонний; внешний клиент без токена; скомпрометированный worker или gateway; оператор с Docker/host правами. Оператор с root на Docker-хосте может читать файлы/тома — такой контроль находится за пределами модели защиты учебного стенда.
|
||||
|
||||
## Границы доверия
|
||||
**Границы:** клиент→TLS ingress; ingress→replica mTLS; services→private brokers/DB/storage/telemetry; operator→OpenBao bootstrap. Полная матрица: [contracts/trust-matrix.md](../contracts/trust-matrix.md). Публичные host ports только 127.0.0.1:8443 API и :3443 Grafana. Наличие общего CA **не** означает разрешения обращаться к любой service identity.
|
||||
|
||||
TODO: схема и ссылка на заполненную contracts/trust-matrix.md; публичные/внутренние интерфейсы, процессы, секреты и их выдача.
|
||||
|
||||
| Угроза и конкретный путь | Нарушаемый инвариант | Контроль | Отрицательный тест | Остаточное ограничение |
|
||||
| Угроза и конкретный путь | Нарушаемый инвариант | Контроль | Отрицательный тест | Остаточный риск |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| TODO | TODO | TODO | TODO | TODO |
|
||||
| 1. Клиент видит логин/токен в сети, MITM подменяет gateway | Конфиденциальность/серверная подлинность | TLS CA + SAN localhost, без fallback на HTTP | `tests/security.py` с пустым trust store → cert verify failure | Локальная CA сама защищена только оператором |
|
||||
| 2. Клиент с trusted CA но `rogue-client` пробует обойти LB прямо через `api1:8443` | Только LB может быть клиентом API | verify required, allowlist точного CN+SAN `lab7-lb`, CRL, loopback FastAPI | `tls_matrix.py` no-cert/foreign-ca/wrong-role → отказ, правильный LB → 200 | Скомпрометированный LB client key до отзыва |
|
||||
| 3. Злоумышленник выдаёт себя за worker и читает AMQP | Разделённые producer/consumer роли | broker mTLS, role-specific Rabbit permissions, user/pass | `tls_matrix.py` broker wrong/foreign/no cert, RabbitMQ permission fail | Владелец легального worker key может читать свою очередь |
|
||||
| 4. Произвольный сервис спамит/подменяет OTLP и загрязняет Grafana | Достоверность telemetry | OTLP mTLS на gateway; allowlist service SAN | `tls_matrix.py` otel-gw wrong/foreign/no cert | Внутренние authorized clients могут отправлять ложные события |
|
||||
| 5. Посторонний угадывает ID файла/чата, подменяет X-User-Id | Только участники чата получают metadata/content | Bearer session hash в Redis, ACL через join membership, 404 для чужих ID | `tests/attachments_negative.py`, `tests/security_live.py` | Риск компрометации bearer на клиентской стороне |
|
||||
| 6. Перебор пароля/дорогой Argon2id перегружает API | Доступность аутентификации | Argon2id 19 MiB,t=2,p=1, общий Redis atomic login limit 8/60s на username, 429, limit HTTP body | `tests/security_live.py` 9 неверных попыток → 429 + Retry-After | Распределённый DoS на много разных username не устранён: нужен IP/network rate limit |
|
||||
| 7. Скомпрометированный worker крадёт секреты API/Bao/root | Секреты разделены по service identity | AppRole read только `kv/data/worker`, на worker нет operator/init и api SecretID, отдельный DB/S3/broker auth | `tests/bao_policy_audit.py` forbidden read `kv/data/api`, forbidden policy write | Worker всё ещё имеет широкие права внутри общего S3 bucket, нет key-prefix policy |
|
||||
| 8. Утечка старого LB private key после ротации | Старый cert не должен дать новый доступ | CA CRL + restart mTLS proxies | `rotate_leaf.py` + new-connection audit с `old-lb-client` | TLS сессии, открытые до ротации, могут продолжать жить до завершения |
|
||||
| 9. Утечка старого S3 worker secret | Старый key должен стать недействительным | Перезапись IAM identities, выдача нового Bao KV, restart S3/worker | `s3-rotation-audit`: новый работает, прежний 403 | На время ротации возможны временные S3/worker ошибки |
|
||||
| 10. Worker распаковывает вредный/огромный upload | Доступность CPU/RAM/диска | MIME/magic/decode validation, MAX_PIXELS, 10MiB, subprocess timeout, Docker mem/cpu/pid limits | `tests/attachments_negative.py`; worker crash/retry from Lab6 | Плохой декодер может потребовать security patch; нет полноценного sandbox seccomp профиля |
|
||||
| 11. База/лог скрадывает пароли или токены | Секреты не публикуются | Argon2id salted hash, session Redis key SHA256, allowlisted telemetry attrs, отказ от raw Authorization | `tests/security_unit.py`, поиск в логах/telemetry после сценариев | Не гарантируется автоматическая редактировка всех сторонних log-exceptions |
|
||||
| 12. OpenBao sealed/restart и приложения берут plaintext fallback | Нет доступа к секретам без сервиса секретов | Non-dev persistent OpenBao, fail-closed AppRole read at service startup, нет root token in app | Restart API пока Bao sealed → без ready, unseal → восстановление | Уже работающие сервисы держат credentials в памяти; SecretID 24h требует operator refresh |
|
||||
|
||||
На 4 минимум 6 конкретных угроз. Не заменяйте сценарии словами «SQL injection», «безопасный Docker», «mTLS включён» без пути и проверки.
|
||||
## Компромиссы и lifecycle
|
||||
|
||||
## Lifecycle и инциденты
|
||||
Оператор владеет `.local/pki/ca.key`, `.local/operator/init.json` и `.env`. Закрытые leaf ключи и AppRole SecretID — отдельные volume/bind mounts на точную роль. В repository, image и traces секретов нет **по дизайну конфигурации**, фактическую очистку логов нужно проверить перед PR. `rotate_leaf.py` перевыдаёт LB leaf, отзывает серийный номер по CRL; `rotate_s3_secret.py` перевыпускает рабочий ключ, меняет OpenBao KV и SeaweedFS policy с явной проверкой старого ключа. При sealed OpenBao новые API processes не стартуют; действующие могут обслуживать запросы с локально загруженными credentials. `docker compose down` сохраняет DB/Bao/S3; `down -v` удаляет их.
|
||||
|
||||
TODO: bootstrap, expiry/renewal, revoke/rotation, компрометация identity, sealed OpenBao и восстановление. Указать владельца CA/unseal и способ защиты bootstrap credentials. Сопоставить scan findings с реальной применимостью и исправлением/остаточным риском.
|
||||
## Уязвимости образов: triage обязателен
|
||||
|
||||
Команды: `trivy fs --scanners vuln --severity HIGH,CRITICAL .` и `trivy image --scanners vuln --severity HIGH,CRITICAL mtusi-lab7-app:local`. Если scanner обнаруживает CVE, в отчёт нужно вписать package, fixed version, достижимость (например, package доступен через сеть/обработку изображений или лишь build-tool), экспозицию, принятое решение (upgrade/mitigation/accepted risk). **Скан не запускался в среде сборки этого пакета; утверждения об отсутствии CVE нет.** Используются pinned versions, но pin сам по себе не устраняет уязвимости. Secrets/token redaction надо дополнительно подтвердить live тестом Loki/Tempo.
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Concurrent Lab5 uploads (HTTP 202) and eventual processing completion.
|
||||
|
||||
Admission metrics measure upload/enqueue requests, not worker throughput.
|
||||
Completion is checked separately so an accepted-but-stuck job cannot pass.
|
||||
"""
|
||||
import argparse
|
||||
import concurrent.futures
|
||||
import json
|
||||
import statistics
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from client import Client, check, run
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--concurrency', type=int, default=10)
|
||||
parser.add_argument('--output', default='evidence/attachments-concurrent.json')
|
||||
parser.add_argument('--base-url', default='http://localhost:8080')
|
||||
parser.add_argument('--wait-seconds', type=int, default=180)
|
||||
args = parser.parse_args()
|
||||
check(args.concurrency > 0, 'concurrency must be positive')
|
||||
check(args.wait_seconds > 0, 'wait-seconds must be positive')
|
||||
|
||||
client = Client(args.base_url)
|
||||
alice, bob, eve, chat = client.bootstrap()
|
||||
source = (Path(__file__).parent / 'fixtures/sample.png').read_bytes()
|
||||
path = '/api/v1/chats/' + chat['id'] + '/attachments?filename=parallel.png'
|
||||
|
||||
def upload(_):
|
||||
cli = Client(args.base_url)
|
||||
response = cli.call('POST', path, 202, actor=alice, raw=source,
|
||||
headers={'Content-Type': 'image/png'}, schema='Attachment')
|
||||
att = response['json']
|
||||
check(att['status'] == 'queued', '202 must return a queued attachment')
|
||||
check(att['size_bytes'] == len(source), 'size mismatch')
|
||||
check(att['chat_id'] == chat['id'] and att['owner_id'] == alice['id'],
|
||||
'incorrect attachment ownership')
|
||||
return att['id'], response['elapsed']
|
||||
|
||||
started = time.monotonic()
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=args.concurrency) as pool:
|
||||
results = list(pool.map(upload, range(args.concurrency)))
|
||||
accepted_seconds = time.monotonic() - started
|
||||
ids = [att_id for att_id, _ in results]
|
||||
timings = [duration for _, duration in results]
|
||||
check(len(set(ids)) == args.concurrency, 'duplicate attachment IDs')
|
||||
|
||||
# A 202 response alone only proves acceptance, not successful processing.
|
||||
pending = set(ids)
|
||||
deadline = time.monotonic() + args.wait_seconds
|
||||
while pending and time.monotonic() < deadline:
|
||||
for att_id in list(pending):
|
||||
att = client.call('GET', '/api/v1/attachments/' + att_id,
|
||||
actor=alice, schema='Attachment')['json']
|
||||
check(att['status'] != 'failed', 'attachment reached failed: ' + att_id)
|
||||
if att['status'] == 'ready':
|
||||
variants = [v['name'] for v in att['variants']]
|
||||
check(len(variants) == 3 and set(variants) == {'thumbnail', 'crop', 'optimized'},
|
||||
'missing/duplicate image variants: ' + att_id)
|
||||
pending.remove(att_id)
|
||||
if pending:
|
||||
time.sleep(0.5)
|
||||
check(not pending, 'attachments not ready before deadline: ' + str(len(pending)))
|
||||
complete_seconds = time.monotonic() - started
|
||||
|
||||
data = {
|
||||
'concurrency': args.concurrency,
|
||||
'accepted_uploads': len(results),
|
||||
'ready_attachments': args.concurrency,
|
||||
'failed_requests': 0,
|
||||
'acceptance_elapsed_seconds': round(accepted_seconds, 3),
|
||||
'acceptance_rps': round(len(results) / accepted_seconds, 3),
|
||||
'upload_latency_p50_ms': round(statistics.median(timings) * 1000, 1),
|
||||
'upload_latency_max_ms': round(max(timings) * 1000, 1),
|
||||
'all_ready_elapsed_seconds': round(complete_seconds, 3),
|
||||
'bytes_per_file': len(source),
|
||||
'note': 'HTTP 202 = queued; readiness checked for all uploads. Capture API peak RSS separately via docker stats.',
|
||||
}
|
||||
output = Path(args.output)
|
||||
output.parent.mkdir(exist_ok=True, parents=True)
|
||||
output.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding='utf-8')
|
||||
print('PASS: %d concurrent HTTP 202 uploads -> ready, 3 variants each' % args.concurrency)
|
||||
print(json.dumps(data, ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,48 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Lab5 negative API tests with isolated synthetic users (requires live stack)."""
|
||||
from urllib.parse import quote
|
||||
import uuid
|
||||
from client import Client, arguments, run, check
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments('Lab5 negative file/ACL/security tests')
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
base = '/api/v1/chats/' + chat['id'] + '/attachments?filename='
|
||||
data = (Path(__file__).parent / 'fixtures/sample.png').read_bytes()
|
||||
c.call('POST', base+'big.png', 413, actor=alice, raw=data+b'\x00'*(10*1024*1024+1-len(data)), headers={'Content-Type':'image/png'})
|
||||
c.call('POST', base+'bad.png', 415, actor=alice, raw=b'not-an-image', headers={'Content-Type':'image/png'})
|
||||
c.call('POST', base+'fake.jpg', 415, actor=alice, raw=data, headers={'Content-Type':'image/jpeg'})
|
||||
c.call('POST', base+quote('../escape.png',safe=''), 400, actor=alice, raw=data, headers={'Content-Type':'image/png'})
|
||||
c.call('POST', base+'x.png', 404, actor=eve, raw=data, headers={'Content-Type':'image/png'})
|
||||
c.call('POST', base+'x.png', 401, raw=data, headers={'Content-Type':'image/png'})
|
||||
uploaded = c.attachment(alice,chat)[0]
|
||||
ready = c.wait_ready(alice, uploaded)
|
||||
unknown = str(uuid.uuid4())
|
||||
c.call('GET','/api/v1/attachments/'+unknown,404,actor=alice)
|
||||
c.call('GET','/api/v1/attachments/'+uploaded['id'],404,actor=eve)
|
||||
c.call('GET','/api/v1/attachments/'+uploaded['id']+'/content',404,actor=eve)
|
||||
# A ready Lab5 attachment has a downloadable thumbnail for chat members.
|
||||
# A non-member still gets 404, and an unknown variant must not resolve.
|
||||
c.call('GET','/api/v1/attachments/'+uploaded['id']+'/content?variant=thumbnail',404,actor=eve)
|
||||
c.call('GET','/api/v1/attachments/'+uploaded['id']+'/content?variant=nonexistent',404,actor=alice)
|
||||
check(any(v['name'] == 'thumbnail' for v in ready['variants']), 'missing thumbnail variant')
|
||||
thumb = c.call('GET','/api/v1/attachments/'+uploaded['id']+'/content?variant=thumbnail',200,actor=alice)
|
||||
check(thumb['headers'].get_content_type() == 'image/jpeg', 'wrong thumbnail MIME')
|
||||
other_chat = c.call('POST','/api/v1/chats',201,actor=alice,
|
||||
body={'title':'Другой чат','member_ids':[alice['id'],bob['id']]},schema='Chat')['json']
|
||||
path = '/api/v1/chats/'+other_chat['id']+'/messages'
|
||||
c.call('POST',path,404,actor=alice,
|
||||
body={'text':'cross-chat','attachment_ids':[uploaded['id']]},
|
||||
headers={'Idempotency-Key':uuid.uuid4().hex})
|
||||
c.call('POST','/api/v1/chats/'+chat['id']+'/messages',404,actor=alice,
|
||||
body={'text':'unknown','attachment_ids':[unknown]},
|
||||
headers={'Idempotency-Key':uuid.uuid4().hex})
|
||||
ok = c.message(bob,chat,'',attachments=[uploaded['id']])['json']
|
||||
check(ok['attachment_ids']==[uploaded['id']], 'valid attachment not linked')
|
||||
print('PASS: lab5 negative image, MIME, size, filename, ACL, variants and cross-chat checks')
|
||||
|
||||
if __name__=='__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Scoped role self-test executed by operator-only one-shot probe.
|
||||
Reads role IDs but never displays secret values/tokens.
|
||||
"""
|
||||
import json
|
||||
import ssl
|
||||
from pathlib import Path
|
||||
from urllib.request import Request,urlopen
|
||||
from urllib.error import HTTPError
|
||||
|
||||
ROOT='https://openbao:8200/v1/'
|
||||
TLS=ssl.create_default_context(cafile='/run/pki/ca.crt')
|
||||
|
||||
def call(method,path,payload=None,token=None):
|
||||
headers={'Content-Type':'application/json'}
|
||||
if token: headers['X-Vault-Token']=token
|
||||
req=Request(ROOT+path,headers=headers,
|
||||
data=json.dumps(payload).encode() if payload is not None else None,
|
||||
method=method)
|
||||
try:
|
||||
with urlopen(req,context=TLS,timeout=8) as resp:
|
||||
raw=resp.read()
|
||||
return resp.status,json.loads(raw) if raw else {}
|
||||
except HTTPError as e:
|
||||
return e.code,{}
|
||||
|
||||
def main():
|
||||
for role in ('api','worker','dispatcher'):
|
||||
root=Path('/role-files')/role
|
||||
id=(root/'role_id').read_text().strip()
|
||||
secret=(root/'secret_id').read_text().strip()
|
||||
status,res=call('POST','auth/approle/login',{'role_id':id,'secret_id':secret})
|
||||
assert status==200,role+' AppRole login failed'
|
||||
token=res['auth']['client_token']
|
||||
status,_=call('GET','kv/data/'+role,token=token)
|
||||
assert status==200,role+' failed own read'
|
||||
for other in ('api','worker','dispatcher'):
|
||||
if other!=role:
|
||||
status,_=call('GET','kv/data/'+other,token=token)
|
||||
assert status==403,role+' unexpectedly read '+other
|
||||
status,_=call('PUT','sys/policies/acl/api',{'policy':'path "*" { capabilities = ["sudo"] }'},token=token)
|
||||
assert status==403,role+' unexpectedly modified policies'
|
||||
print('PASS:',role,'own KV read, cross-role read denied, write policy denied')
|
||||
status,_=call('POST','auth/approle/login',{'role_id':'bad-role','secret_id':'bad-secret'})
|
||||
assert status in (400,403), 'Invalid AppRole was accepted'
|
||||
print('PASS: untrusted AppRole rejected')
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,38 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Lab3 own test: 30 requests using identical actor/chat/key/body across both replicas."""
|
||||
import concurrent.futures
|
||||
import sys
|
||||
import uuid
|
||||
from client import Client, Failure, arguments, check, run
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("Check atomic idempotency across API replicas")
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
alice, bob, _, chat = c.bootstrap()
|
||||
key = uuid.uuid4().hex
|
||||
body = {"text": "Concurrent replay " + key}
|
||||
path = f"/api/v1/chats/{chat['id']}/messages"
|
||||
|
||||
def worker(_):
|
||||
# Independent request client; one shared bearer token and idempotency key.
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
return client.call("POST", path, expected=201, actor=alice, body=body,
|
||||
headers={"Idempotency-Key": key}, schema="Message")
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=12) as executor:
|
||||
results = list(executor.map(worker, range(30)))
|
||||
ids = {result["json"]["id"] for result in results}
|
||||
instances = {result["headers"]["X-Instance-Id"] for result in results}
|
||||
check(len(ids) == 1, "parallel replay created different messages")
|
||||
check(len(instances) >= 2, "LB did not serve requests via both API replicas")
|
||||
check(all(r["json"] == results[0]["json"] for r in results), "replay returned altered result")
|
||||
c.call("POST", path, 409, actor=alice, body={"text": "different body"}, headers={"Idempotency-Key": key})
|
||||
c.call("POST", path, 201, actor=bob, body=body, headers={"Idempotency-Key": key}, schema="Message")
|
||||
history = c.call("GET", path + "?limit=100", actor=bob, schema="MessagePage")["json"]["items"]
|
||||
check(sum(x["id"] in ids for x in history) == 1, "message duplicated in history")
|
||||
print("PASS: parallel idempotency across", len(instances), "replicas; one message, replay 201, conflicting body 409")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,30 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Prevent a mismatch between SQL placeholders and parameter tuple in worker result persistence."""
|
||||
import ast
|
||||
from pathlib import Path
|
||||
import re
|
||||
|
||||
source = (Path(__file__).resolve().parents[1] / "app" / "jobs.py").read_text(encoding="utf-8")
|
||||
tree = ast.parse(source)
|
||||
fn = next(x for x in tree.body if isinstance(x, ast.FunctionDef) and x.name == "publish_result")
|
||||
matches = []
|
||||
for node in ast.walk(fn):
|
||||
if not isinstance(node, ast.Call) or not isinstance(node.func, ast.Attribute):
|
||||
continue
|
||||
if node.func.attr != "execute" or len(node.args) < 2:
|
||||
continue
|
||||
if not isinstance(node.args[0], ast.Constant) or not isinstance(node.args[0].value, str):
|
||||
continue
|
||||
sql = node.args[0].value
|
||||
if "INSERT INTO attachment_variants" not in sql:
|
||||
continue
|
||||
assert isinstance(node.args[1], ast.Tuple), "Expected literal parameters tuple"
|
||||
placeholders = sql.count("%s")
|
||||
params = len(node.args[1].elts)
|
||||
columns_match = re.search(r"INSERT INTO attachment_variants\s*\(([^)]*)\)", sql, re.I | re.S)
|
||||
assert columns_match, "Columns missing in INSERT"
|
||||
columns = len(columns_match.group(1).split(","))
|
||||
assert placeholders == columns == params, f"SQL mismatch: {columns} columns, {placeholders} placeholders, {params} parameters"
|
||||
matches.append((columns, placeholders, params))
|
||||
assert len(matches) == 1, "Expected exactly one attachment_variants INSERT"
|
||||
print("PASS: attachment_variants INSERT has 9 columns, 9 placeholders, 9 arguments")
|
||||
@@ -0,0 +1,318 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Lab6 live evidence. Only synthetic test stack; no volume removal.
|
||||
Run scenarios separately. Queries stored in evidence, no HTTP auth or payloads.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import math
|
||||
import concurrent.futures
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
from pathlib import Path
|
||||
from client import Client, Failure, check, run
|
||||
from pipeline_extended import compose, pg, scalar, wait_for
|
||||
from pipeline_resilience import verify_ready
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
PROM='http://127.0.0.1:9090'
|
||||
LOKI='http://127.0.0.1:3100'
|
||||
TEMPO='http://127.0.0.1:3200'
|
||||
GRAFANA='http://127.0.0.1:3000'
|
||||
ERR='(sum(rate(lab_http_requests_total{route=~"/api/.*",status_class="5xx"}[30s])) or vector(0)) / clamp_min(sum(rate(lab_http_requests_total{route=~"/api/.*"}[30s])),0.001)'
|
||||
LAG='max(lab_queue_oldest_age_seconds)'
|
||||
DEPTH='max(lab_queue_depth)'
|
||||
FAILED='sum(otelcol_exporter_send_failed_spans) or sum(otelcol_exporter_send_failed_spans_total) or vector(0)'
|
||||
QUEUE='max(otelcol_exporter_queue_size{exporter="otlp/tempo"}) or vector(0)'
|
||||
RSS='max(otelcol_process_memory_rss)'
|
||||
|
||||
|
||||
def get(url, params=None, *, as_json=True):
|
||||
try:
|
||||
with urllib.request.urlopen(url+('?' + urllib.parse.urlencode(params) if params else ''),timeout=8) as r:
|
||||
raw=r.read(32*1024*1024)
|
||||
return json.loads(raw) if as_json else raw.decode('utf-8',errors='replace')
|
||||
except (urllib.error.URLError,TimeoutError,ValueError) as exc:
|
||||
raise Failure('diagnostic endpoint unavailable: '+url.split('?')[0]+' ('+type(exc).__name__+')') from None
|
||||
|
||||
|
||||
def prom(expr):
|
||||
data=get(PROM+'/api/v1/query',{'query':expr})
|
||||
check(data.get('status')=='success','PromQL query failed')
|
||||
return data['data']['result']
|
||||
|
||||
|
||||
def val(expr):
|
||||
rows=prom(expr)
|
||||
return float(rows[0]['value'][1]) if rows else None
|
||||
|
||||
|
||||
def alert_state(name):
|
||||
rules=get(PROM+'/api/v1/rules')['data']['groups']
|
||||
for group in rules:
|
||||
for rule in group['rules']:
|
||||
if rule['name']==name:
|
||||
check(rule.get('health')=='ok','alert rule is not healthy: '+name)
|
||||
return rule['state']
|
||||
raise Failure('alert rule missing: '+name)
|
||||
|
||||
|
||||
def wait_alert(name,state,seconds=100):
|
||||
return wait_for(name+' '+state,lambda:alert_state(name),lambda x:x==state,seconds=seconds,interval=2)
|
||||
|
||||
|
||||
def ready():
|
||||
for url in (PROM+'/-/ready',LOKI+'/ready',TEMPO+'/ready'):
|
||||
wait_for(url,lambda:get(url,as_json=False),lambda x:bool(x),seconds=100,interval=2)
|
||||
wait_for('Grafana',lambda:get(GRAFANA+'/api/health'),lambda x:x.get('database')=='ok',seconds=100)
|
||||
wait_for('Collector scrape',lambda:val('up{job="collector-self"}'),lambda v:v==1,seconds=40)
|
||||
wait_for('OTLP metrics scrape',lambda:val('up{job="lab-otlp"}'),lambda v:v==1,seconds=40)
|
||||
|
||||
|
||||
def trace_spans(tid):
|
||||
raw=get(TEMPO+'/api/traces/'+tid)
|
||||
spans=[]
|
||||
def walk(obj):
|
||||
if isinstance(obj,dict):
|
||||
if {'spanId','traceId','name'}<=set(obj): spans.append(obj)
|
||||
else:
|
||||
for v in obj.values():walk(v)
|
||||
elif isinstance(obj,list):
|
||||
for v in obj:walk(v)
|
||||
walk(raw)
|
||||
return spans
|
||||
|
||||
|
||||
def logs(tid,service,request_id=None):
|
||||
expr='{service_name="%s"} | trace_id="%s"' % (service,tid)
|
||||
if request_id: expr+=' | request_id="%s"'%request_id
|
||||
data=get(LOKI+'/loki/api/v1/query_range',{'query':expr,'start':str(int((time.time()-900)*1e9)), 'end':str(time.time_ns()),'limit':100})
|
||||
return data['data']['result']
|
||||
|
||||
|
||||
def upload(c,alice,chat):
|
||||
raw=(ROOT/'tests/fixtures/sample.png').read_bytes()
|
||||
r=c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=sample.png',202,actor=alice,raw=raw,headers={'Content-Type':'image/png'},schema='Attachment')
|
||||
tid=r['headers'].get('X-Trace-Id','')
|
||||
check(len(tid)==32 and int(tid,16)>0,'missing active API trace ID: check SDK enablement')
|
||||
return r['json'],raw,tid,r['headers']['X-Request-Id']
|
||||
|
||||
|
||||
def span_attrs(s):
|
||||
attrs={}
|
||||
for a in s.get('attributes',[]):
|
||||
value=a.get('value',{})
|
||||
attrs[a['key']]=next(iter(value.values()),None)
|
||||
return attrs
|
||||
|
||||
|
||||
def chain_ok(spans):
|
||||
names={s['name'] for s in spans}
|
||||
required={'POST /api/v1/chats/{chat_id}/attachments','rabbitmq.publish','rabbitmq.consume','s3.upload_fileobj','s3.get_object','s3.put_object','db.publish_result'}
|
||||
if not required<=names:return False
|
||||
producers={s['spanId'] for s in spans if s['name']=='rabbitmq.publish'}
|
||||
consumers=[s for s in spans if s['name']=='rabbitmq.consume']
|
||||
outcomes={span_attrs(s).get('job.outcome') for s in consumers}
|
||||
return len(producers)>=2 and {'retry','ready'}<=outcomes and all(s.get('parentSpanId') in producers for s in consumers)
|
||||
|
||||
|
||||
def trace_retry(c):
|
||||
alice,bob,_,chat=c.bootstrap()
|
||||
compose('stop','worker')
|
||||
try:
|
||||
att,raw,tid,rid=upload(c,alice,chat)
|
||||
# Override only worker, never a public endpoint; reset in finally.
|
||||
env={**os.environ,'LAB6_FAULT_RETRY_ONCE':'once'}
|
||||
subprocess.run(['docker','compose','--env-file','.env','up','-d','--no-deps','--force-recreate','worker'],cwd=ROOT,env=env,check=True,timeout=180)
|
||||
verify_ready(c,bob,att,raw,seconds=180)
|
||||
spans=wait_for('stored retry trace',lambda:trace_spans(tid),chain_ok,seconds=100,interval=3)
|
||||
wait_for('API log joined by request/trace ID',lambda:logs(tid,'messenger-api',rid),bool,seconds=90)
|
||||
def worker_events(streams):
|
||||
return {v[1] for row in streams for v in row.get('values',[])}
|
||||
wlogs=wait_for('worker retry and ready logs',lambda:logs(tid,'messenger-worker'),lambda rows:{'job.retry','job.ready'}<=worker_events(rows),seconds=90)
|
||||
# Keep only allowlisted names/IDs, not arbitrary span values or log payloads.
|
||||
summary=[{'name':s['name'],'id':s['spanId'],'parent':s.get('parentSpanId'),'attempt':span_attrs(s).get('job.attempt'),'outcome':span_attrs(s).get('job.outcome')} for s in spans]
|
||||
result={'trace_id':tid,'request_id':rid,'spans':summary,'worker_log_streams':len(wlogs),'worker_events':sorted(worker_events(wlogs)&{'job.claimed','job.retry','job.ready','image.transformed'}),'retry_chain':True}
|
||||
print('PASS trace-retry: API/producer/consumer/S3/DB with retry, correlated logs',tid)
|
||||
return result
|
||||
finally:
|
||||
subprocess.run(['docker','compose','--env-file','.env','up','-d','--no-deps','--force-recreate','worker'],cwd=ROOT,env={**os.environ,'LAB6_FAULT_RETRY_ONCE':'off'},check=True,timeout=180)
|
||||
|
||||
|
||||
def queue_lag(c):
|
||||
alice,bob,_,chat=c.bootstrap()
|
||||
wait_alert('LabQueueLag','inactive')
|
||||
compose('stop','worker')
|
||||
try:
|
||||
att,raw,tid,rid=upload(c,alice,chat)
|
||||
t=time.monotonic()
|
||||
wait_alert('LabQueueLag','firing')
|
||||
lag=val(LAG);depth=val(DEPTH)
|
||||
check(lag is not None and lag>15 and depth>=1,'firing not supported by actual backlog metrics')
|
||||
detected=time.monotonic()-t
|
||||
print('Queue alert firing: oldest age',lag,'s, queued',depth,flush=True)
|
||||
compose('up','-d','worker')
|
||||
verify_ready(c,bob,att,raw,seconds=180)
|
||||
wait_alert('LabQueueLag','inactive',seconds=120)
|
||||
wait_for('queue drained',lambda:val(DEPTH),lambda v:v==0,seconds=60,interval=2)
|
||||
print('PASS queue-lag: firing -> ready -> resolved')
|
||||
return {'trace_id':tid,'firing_lag_seconds':lag,'firing_depth':depth,'detected_seconds':round(detected,3),'resolved_depth':val(DEPTH)}
|
||||
finally:compose('up','-d','worker')
|
||||
|
||||
|
||||
def db_error(c):
|
||||
alice,_,_,_=c.bootstrap()
|
||||
wait_alert('LabAPIHighErrorRate','inactive')
|
||||
user=compose('exec','-T','postgres','printenv','POSTGRES_USER')
|
||||
db=compose('exec','-T','postgres','printenv','POSTGRES_DB')
|
||||
# Bounded, isolated table lock. Health SELECT 1 works, authenticated business
|
||||
# read times out at statement_timeout. Never stop DB (LB would hide API 5xx).
|
||||
cmd=['docker','compose','--env-file','.env','exec','-T','postgres','psql','-X','-q','-v','ON_ERROR_STOP=1','-U',user,'-d',db,'-c','BEGIN; LOCK TABLE users IN ACCESS EXCLUSIVE MODE; SELECT pg_sleep(60); COMMIT;']
|
||||
lock=subprocess.Popen(cmd,cwd=ROOT,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
|
||||
try:
|
||||
wait_for('users lock held',lambda:scalar("SELECT count(*) FROM pg_locks WHERE relation='users'::regclass AND mode='AccessExclusiveLock' AND granted"),lambda v:int(v)>0,seconds=15)
|
||||
start=time.monotonic(); traces=[]; codes=[]
|
||||
while time.monotonic()-start < 43:
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as pool:
|
||||
def get_user(_):
|
||||
r=Client(timeout=12).call('GET','/api/v1/users/me',[200,503],actor=alice,schema='User')
|
||||
return r['status'],r['headers'].get('X-Trace-Id'),r['headers'].get('X-Request-Id')
|
||||
for code,tid,rid in pool.map(get_user,range(3)):
|
||||
codes.append(code)
|
||||
if code==503 and tid:traces.append((tid,rid))
|
||||
if traces and alert_state('LabAPIHighErrorRate')=='firing':break
|
||||
check(bool(traces),'no real HTTP 503 from DB lock')
|
||||
wait_alert('LabAPIHighErrorRate','firing',seconds=20)
|
||||
ratio=val(ERR)
|
||||
check(ratio is not None and ratio>0.05,'error ratio below threshold')
|
||||
tid,rid=traces[0]
|
||||
spans=wait_for('DB timeout trace',lambda:trace_spans(tid),lambda v:any(s['name']=='db.transaction' and span_attrs(s).get('error.type')=='QueryCanceled' for s in v),seconds=60,interval=2)
|
||||
wait_for('error log',lambda:logs(tid,'messenger-api',rid),bool,seconds=60)
|
||||
print('Error alert firing, database QueryCanceled visible; ratio',ratio,flush=True)
|
||||
finally:
|
||||
# SQL transaction has server-side 60s bound; wait for normal COMMIT.
|
||||
try:lock.wait(timeout=75)
|
||||
except subprocess.TimeoutExpired:
|
||||
lock.terminate();lock.wait(timeout=10)
|
||||
# Keep successful business traffic in the evaluation window to prove recovery.
|
||||
t=time.monotonic()
|
||||
while time.monotonic()-t<65:
|
||||
c.call('GET','/api/v1/users/me',200,actor=alice,schema='User')
|
||||
if alert_state('LabAPIHighErrorRate')=='inactive' and val(ERR) is not None and val(ERR)<=.05:break
|
||||
time.sleep(1)
|
||||
wait_alert('LabAPIHighErrorRate','inactive',seconds=40)
|
||||
print('PASS db-error: lock -> QueryCanceled/503 -> firing -> resolved')
|
||||
return {'trace_id':tid,'request_id':rid,'http_codes':codes,'firing_error_ratio':ratio,'resolved_error_ratio':val(ERR),'error_spans':[{'name':s['name'],'error_type':span_attrs(s).get('error.type')} for s in spans if span_attrs(s).get('error.type')]}
|
||||
|
||||
|
||||
def backend_down(c):
|
||||
alice,bob,_,chat=c.bootstrap()
|
||||
baseline=val(FAILED) or 0
|
||||
cid=compose('ps','-q','otel-collector')
|
||||
before=subprocess.check_output(['docker','inspect','--format','{{.RestartCount}} {{.State.OOMKilled}}',cid],text=True).strip()
|
||||
compose('stop','tempo')
|
||||
try:
|
||||
start=time.monotonic();n=0;memory=[];queues=[];failures=[]
|
||||
att,raw,tid,_=upload(c,alice,chat)
|
||||
while time.monotonic()-start<40:
|
||||
c.message(alice,chat,'telemetry-backend-offline')
|
||||
n+=1
|
||||
for expr,arr in ((RSS,memory),(QUEUE,queues),(FAILED,failures)):
|
||||
x=val(expr)
|
||||
if x is not None:arr.append(x)
|
||||
time.sleep(.3)
|
||||
verify_ready(c,bob,att,raw,seconds=180)
|
||||
check(n>0,'no successful writes during backend outage')
|
||||
check(failures and max(failures)>baseline,'no recorded exporter failure; inspect Collector internal metrics')
|
||||
check(memory and max(memory)<256*1024*1024,'Collector RSS absent or above container limit')
|
||||
check(queues and max(queues)<=64,'collector queue exceeds configured cap')
|
||||
after=subprocess.check_output(['docker','inspect','--format','{{.RestartCount}} {{.State.OOMKilled}}',cid],text=True).strip()
|
||||
check(after==before and after.endswith('false'),'Collector restarted or OOM-killed')
|
||||
print('PASS backend-down: writes and image processing persisted, telemetry failed visibly; queue/RAM bounded')
|
||||
result={'successful_messages_during_tempo_outage':n,'trace_id':tid,'max_sampled_collector_rss_bytes':max(memory),'max_export_queue':max(queues),'failed_span_counter_delta':max(failures)-baseline,'restart_state':after}
|
||||
finally:compose('up','-d','tempo')
|
||||
ready()
|
||||
# Confirm a fresh post-recovery trace can be retrieved.
|
||||
r=c.call('GET','/api/v1/users/me',200,actor=alice,schema='User')
|
||||
tid2=r['headers']['X-Trace-Id']
|
||||
wait_for('post-recovery trace',lambda:trace_spans(tid2),bool,seconds=90)
|
||||
result['recovered_trace_id']=tid2
|
||||
return result
|
||||
|
||||
|
||||
def metrics_snapshot(c):
|
||||
alice,bob,_,chat=c.bootstrap()
|
||||
att,raw,_,_=upload(c,alice,chat)
|
||||
verify_ready(c,bob,att,raw,seconds=150)
|
||||
until=time.monotonic()+12
|
||||
while time.monotonic()<until:
|
||||
c.message(alice,chat,'synthetic-metric-check')
|
||||
time.sleep(5)
|
||||
# Read the real provisioned Grafana dashboard/datasource list, without
|
||||
# printing credentials or copying the response into the evidence.
|
||||
secret=compose('exec','-T','grafana','printenv','GF_SECURITY_ADMIN_PASSWORD')
|
||||
auth=base64.b64encode(('admin:'+secret).encode()).decode()
|
||||
def grafana_json(path):
|
||||
r=urllib.request.Request(GRAFANA+path,headers={'Authorization':'Basic '+auth})
|
||||
try:
|
||||
with urllib.request.urlopen(r,timeout=8) as f:return json.load(f)
|
||||
except (urllib.error.URLError,TimeoutError,ValueError):
|
||||
raise Failure('Grafana authenticated provisioning check failed; verify admin password/volume') from None
|
||||
dashboard=grafana_json('/api/dashboards/uid/lab6-messenger')['dashboard']
|
||||
check(len(dashboard['panels'])>=15,'provisioned dashboard incomplete')
|
||||
check({'prometheus','loki','tempo'}<={d['uid'] for d in grafana_json('/api/datasources')},'provisioned datasources missing')
|
||||
queries={'api_rps':'sum(rate(lab_http_requests_total{route=~"/api/.*"}[30s]))','error_ratio':ERR,
|
||||
'p50':'histogram_quantile(0.5,sum by(le)(rate(lab_http_duration_seconds_bucket{route=~"/api/.*"}[30s])))',
|
||||
'p95':'histogram_quantile(0.95,sum by(le)(rate(lab_http_duration_seconds_bucket{route=~"/api/.*"}[30s])))',
|
||||
'p99':'histogram_quantile(0.99,sum by(le)(rate(lab_http_duration_seconds_bucket{route=~"/api/.*"}[30s])))',
|
||||
'jobs':'lab_jobs_total','job_histogram':'lab_job_duration_seconds_count','ready_histogram':'lab_ready_duration_seconds_count',
|
||||
'depth':DEPTH,'oldest':LAG,'broker_ready':'lab_broker_ready','broker_consumers':'lab_broker_consumers','pool_used':'lab_db_pool_used','pool_waiting':'lab_db_pool_waiting',
|
||||
'capacity':'lab_worker_capacity','busy':'lab_worker_busy','cpu':'lab_container_cpu_cores','memory':'lab_container_memory_bytes'}
|
||||
output={}
|
||||
for key,expr in queries.items():
|
||||
rows=wait_for('metric '+key,lambda:prom(expr),bool,seconds=45,interval=2)
|
||||
if key in ('p50','p95','p99'): check(math.isfinite(float(rows[0]['value'][1])),'percentile has no finite datapoints; repeat after active load')
|
||||
output[key]={'query':expr,'result':rows}
|
||||
forbidden={'user_id','request_id','chat_id','message_id','attachment_id','filename','job_id','trace_id','span_id'}
|
||||
for item in output.values():
|
||||
check(all(not forbidden.intersection(r.get('metric',{})) for r in item['result']),'high-cardinality metric labels')
|
||||
print('PASS metrics snapshot: all expected series present, no forbidden ID labels')
|
||||
return output
|
||||
|
||||
|
||||
def history(c):
|
||||
alice,bob,_,chat=c.bootstrap()
|
||||
att,raw,tid,rid=upload(c,alice,chat)
|
||||
verify_ready(c,bob,att,raw,seconds=150)
|
||||
wait_for('stored trace',lambda:trace_spans(tid),lambda spans:any(s['name']=='db.publish_result' for s in spans),seconds=90)
|
||||
wait_for('stored API log',lambda:logs(tid,'messenger-api',rid),bool,seconds=90)
|
||||
time.sleep(6)
|
||||
historic_time=time.time()
|
||||
expr='sum(lab_http_requests_total{route=~"/api/.*"})'
|
||||
def historic():
|
||||
rows=get(PROM+'/api/v1/query',{'query':expr,'time':str(historic_time)})['data']['result']
|
||||
return float(rows[0]['value'][1]) if rows else None
|
||||
before=historic();check(before is not None and before>0,'no historic metric')
|
||||
compose('restart','--timeout','20','prometheus','loki','tempo',timeout=180)
|
||||
ready()
|
||||
wait_for('historical trace',lambda:trace_spans(tid),lambda spans:any(s['name']=='db.publish_result' for s in spans),seconds=100)
|
||||
wait_for('historical log',lambda:logs(tid,'messenger-api',rid),bool,seconds=100)
|
||||
after=historic();check(after==before,'historic metric changed or disappeared')
|
||||
print('PASS history: saved metrics, logs and traces survive backend restart')
|
||||
return {'trace_id':tid,'historical_query_timestamp':historic_time,'metric_before':before,'metric_after':after}
|
||||
|
||||
|
||||
def main():
|
||||
p=argparse.ArgumentParser();p.add_argument('--scenario',choices=['trace-retry','queue-lag','db-error','backend-down','metrics','history'],required=True);args=p.parse_args()
|
||||
check(os.getenv('LAB6_ALLOW_FAILURE_TEST')=='yes','Set LAB6_ALLOW_FAILURE_TEST=yes on isolated synthetic stack')
|
||||
ready();c=Client(timeout=12)
|
||||
fun={'trace-retry':trace_retry,'queue-lag':queue_lag,'db-error':db_error,'backend-down':backend_down,'metrics':metrics_snapshot,'history':history}[args.scenario]
|
||||
result=fun(c)
|
||||
file=ROOT/'evidence'/('lab6-'+args.scenario+'.json');file.write_text(json.dumps({'scenario':args.scenario,'status':'PASS','result':result},indent=2,ensure_ascii=False)+'\n',encoding='utf-8')
|
||||
print('Saved',file.relative_to(ROOT))
|
||||
|
||||
if __name__=='__main__':run(main)
|
||||
@@ -0,0 +1,42 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Fast non-Docker checks for input contracts and cursor scoping."""
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from datetime import datetime, timezone
|
||||
import uuid
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from app.core import make_cursor, read_cursor, parse_limit, APIError
|
||||
from app.models import CreateUser, CreateChat, CreateMessage
|
||||
from pydantic import ValidationError
|
||||
|
||||
|
||||
def reject(fn):
|
||||
try:
|
||||
fn()
|
||||
except (APIError, ValidationError, ValueError):
|
||||
return
|
||||
raise AssertionError("Expected invalid input")
|
||||
|
||||
|
||||
def main():
|
||||
token = str(uuid.uuid4())
|
||||
dt = datetime.now(timezone.utc)
|
||||
cursor = make_cursor("messages", token, dt, str(uuid.uuid4()))
|
||||
assert read_cursor(cursor, "messages", token)[0] == dt
|
||||
reject(lambda: read_cursor(cursor, "messages", str(uuid.uuid4())))
|
||||
reject(lambda: read_cursor(cursor, "chats", token))
|
||||
assert parse_limit(None) == 50
|
||||
reject(lambda: parse_limit("0"))
|
||||
reject(lambda: parse_limit("101"))
|
||||
reject(lambda: CreateUser(username="user_name", display_name=" \t", password="Long-enough-secret"))
|
||||
reject(lambda: CreateUser(username="user_name", display_name="Test", password=" " * 3))
|
||||
assert CreateMessage(text="A\u0000B").text == "A\u0000B"
|
||||
reject(lambda: CreateMessage(text=" \t"))
|
||||
reject(lambda: CreateChat(title="title", member_ids=[token] * 2))
|
||||
reject(lambda: CreateChat(title="title", member_ids=[token] * 101))
|
||||
print("PASS: models, cursor scoping, limits, Unicode U+0000")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,233 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Additional *live* Lab5 fault tests; operator-controlled, synthetic records only.
|
||||
|
||||
broker-persistence: require a publisher-confirmed RabbitMQ message to survive
|
||||
broker restart without a running dispatcher or worker. This differs from the
|
||||
outbox-restoration tests where dispatcher publishes *after* broker recovery.
|
||||
|
||||
failed-replay: safely inject a deterministic checksum mismatch into one fresh
|
||||
synthetic attachment's DB metadata, verify permanent failure, restore the
|
||||
original hash, replay via the operator-only CLI, and verify success plus audit.
|
||||
|
||||
staging-cleanup: verify the staged S3 object is absent after ready (with a
|
||||
matching cleared staging_key in the DB).
|
||||
|
||||
No volumes are deleted. The test may stop/restart worker/dispatcher/broker;
|
||||
run only against a disposable LAB5 environment and never concurrently.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from client import Client, Failure, check, run
|
||||
from pipeline_resilience import verify_ready, wait_api
|
||||
|
||||
from pathlib import Path
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def compose(*args, expected=(0,), timeout=240):
|
||||
proc = subprocess.run(
|
||||
['docker', 'compose', '--env-file', '.env', *args], cwd=ROOT,
|
||||
capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=timeout,
|
||||
)
|
||||
if proc.returncode not in expected:
|
||||
# Don't print env vars, tokens or command stdout/stderr by default.
|
||||
raise Failure('docker compose %s failed (exit %d); inspect ps/logs' %
|
||||
(' '.join(args[:2]), proc.returncode))
|
||||
return proc.stdout.strip()
|
||||
|
||||
|
||||
def pg(sql):
|
||||
"""Read-only or deliberately scoped fault SQL; UUIDs never user-supplied here."""
|
||||
user = compose('exec', '-T', 'postgres', 'printenv', 'POSTGRES_USER').strip()
|
||||
dbname = compose('exec', '-T', 'postgres', 'printenv', 'POSTGRES_DB').strip()
|
||||
return compose('exec', '-T', 'postgres', 'psql', '-X', '-q', '-A', '-t',
|
||||
'-v', 'ON_ERROR_STOP=1', '-U', user, '-d', dbname, '-c', sql)
|
||||
|
||||
|
||||
def scalar(sql):
|
||||
return pg(sql).splitlines()[-1].strip()
|
||||
|
||||
|
||||
def wait_for(label, action, predicate, seconds=30, interval=0.5):
|
||||
deadline = time.monotonic() + seconds
|
||||
last = None
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
last = action()
|
||||
if predicate(last):
|
||||
return last
|
||||
except Failure:
|
||||
pass
|
||||
time.sleep(interval)
|
||||
raise Failure('timed out waiting for ' + label + ', last=' + str(last)[:100])
|
||||
|
||||
|
||||
def job_query(att_id, fields):
|
||||
uuid.UUID(att_id)
|
||||
return scalar('SELECT %s FROM processing_jobs WHERE attachment_id = \'%s\'' %
|
||||
(fields, att_id))
|
||||
|
||||
|
||||
def queue_ready():
|
||||
out = compose('exec', '-T', 'broker', 'rabbitmqctl', '-q', 'list_queues',
|
||||
'name', 'messages_ready', 'messages_unacknowledged')
|
||||
for line in out.splitlines():
|
||||
parts = re.split(r'\s+', line.strip())
|
||||
if parts[0] == 'attachment-processing.v1' and len(parts) >= 3:
|
||||
return int(parts[1]), int(parts[2])
|
||||
raise Failure('RabbitMQ durable queue missing')
|
||||
|
||||
|
||||
def make_upload(c):
|
||||
alice, bob, _eve, chat = c.bootstrap()
|
||||
att, original = c.attachment(alice, chat)
|
||||
check(att['status'] == 'queued', 'upload must return 202 queued')
|
||||
uuid.UUID(att['id'])
|
||||
return alice, bob, att, original
|
||||
|
||||
|
||||
def wait_staging_cleared(att_id, seconds=20):
|
||||
return wait_for('staging_key cleared after ready',
|
||||
lambda: scalar("SELECT COALESCE(staging_key,'<NULL>') FROM attachments WHERE id='%s'" % att_id),
|
||||
lambda value: value == '<NULL>', seconds=seconds)
|
||||
|
||||
|
||||
def verify_staging_absent(att_id):
|
||||
# This executes *inside* the worker container with its normal S3 credentials.
|
||||
# Never expose S3 secrets to the host or write them to evidence files.
|
||||
code = '''import sys
|
||||
from botocore.exceptions import ClientError
|
||||
from app.attachments import s3_client, BUCKET
|
||||
key='staging/'+sys.argv[1]+'/original'
|
||||
try:
|
||||
s3_client().head_object(Bucket=BUCKET,Key=key)
|
||||
except ClientError as exc:
|
||||
if exc.response.get('ResponseMetadata',{}).get('HTTPStatusCode')==404:
|
||||
print('ABSENT')
|
||||
else:
|
||||
raise
|
||||
else:
|
||||
print('STILL_PRESENT')'''
|
||||
result = compose('exec', '-T', 'worker', 'python', '-c', code, att_id)
|
||||
check(result == 'ABSENT', 'staging S3 object still present: ' + result[:70])
|
||||
|
||||
|
||||
def broker_persistence(c):
|
||||
compose('stop', 'worker')
|
||||
compose('up', '-d', 'dispatcher')
|
||||
baseline = queue_ready()[0]
|
||||
alice, _bob, att, original = make_upload(c)
|
||||
print('202 queued:', att['id'], flush=True)
|
||||
sql = "SELECT COALESCE(bool_and(published_at IS NOT NULL),false) FROM job_outbox WHERE job_id=(SELECT id FROM processing_jobs WHERE attachment_id='%s')" % att['id']
|
||||
wait_for('outbox publisher confirm', lambda: scalar(sql), lambda v: v == 't', seconds=30)
|
||||
wait_for('message in RabbitMQ ready queue', lambda: queue_ready()[0],
|
||||
lambda n: n >= baseline + 1, seconds=15)
|
||||
compose('stop', 'dispatcher')
|
||||
before = queue_ready()[0]
|
||||
check(before >= baseline + 1, 'published message disappeared before restart')
|
||||
print('Publisher confirmed; dispatcher and worker stopped; broker queue ready=%d' % before, flush=True)
|
||||
compose('restart', 'broker')
|
||||
compose('up', '-d', '--wait', 'broker')
|
||||
after = wait_for('RabbitMQ queue restoration', lambda: queue_ready()[0],
|
||||
lambda n: n >= before, seconds=40, interval=1)
|
||||
check(scalar(sql) == 't', 'outbox publish confirmation lost')
|
||||
print('Broker restarted; ready messages persisted=%d' % after, flush=True)
|
||||
# CRITICAL: do NOT restart dispatcher yet; only the restored RabbitMQ message
|
||||
# can deliver this job to the worker.
|
||||
compose('up', '-d', 'worker')
|
||||
verify_ready(c, alice, att, original, seconds=180)
|
||||
check(job_query(att['id'], 'status') == 'ready', 'job not committed ready')
|
||||
print('PASS: broker-persistence, confirmed RabbitMQ message survives broker restart without outbox republish')
|
||||
|
||||
|
||||
def failed_replay(c):
|
||||
compose('stop', 'worker', 'dispatcher')
|
||||
alice, _bob, att, original = make_upload(c)
|
||||
ident = att['id']
|
||||
original_sha = hashlib.sha256(original).hexdigest()
|
||||
check(original_sha == att['sha256'], 'fixture hash mismatch')
|
||||
check(scalar("SELECT sha256 FROM attachments WHERE id='%s'" % ident) == original_sha,
|
||||
'DB hash unexpected before controlled fault')
|
||||
fault_sha = '0' * 64 if original_sha != '0' * 64 else 'f' * 64
|
||||
changed = False
|
||||
try:
|
||||
updated = pg("UPDATE attachments SET sha256='%s' WHERE id='%s' AND status='queued' RETURNING id" %
|
||||
(fault_sha, ident))
|
||||
check(ident in updated, 'failed to inject synthetic checksum mismatch')
|
||||
changed = True
|
||||
compose('up', '-d', 'dispatcher', 'worker')
|
||||
|
||||
def get_state():
|
||||
return c.call('GET', '/api/v1/attachments/' + ident, actor=alice, schema='Attachment')['json']
|
||||
failed = wait_for('permanent failed status', get_state,
|
||||
lambda a: a['status'] == 'failed', seconds=90)
|
||||
check(failed['error_code'] == 'invalid_image',
|
||||
'expected permanent invalid_image, got ' + str(failed['error_code']))
|
||||
check(job_query(ident, 'status') == 'failed', 'processing job must fail')
|
||||
check(job_query(ident, 'attempt') == '1', 'permanent error must not retry')
|
||||
check(scalar("SELECT count(*) FROM attachment_variants WHERE attachment_id='%s'" % ident) == '0',
|
||||
'failed job created variants')
|
||||
print('Permanent invalid_image confirmed; no retry and no variant rows', flush=True)
|
||||
# Repair only the generated synthetic row before explicit operator replay.
|
||||
restored = pg("UPDATE attachments SET sha256='%s' WHERE id='%s' AND status='failed' RETURNING id" %
|
||||
(original_sha, ident))
|
||||
check(ident in restored, 'synthetic metadata could not be restored')
|
||||
changed = False
|
||||
compose('exec', '-T', 'dispatcher', 'python', '-m', 'app.jobs', 'replay', '--id', ident)
|
||||
verify_ready(c, alice, att, original, seconds=180)
|
||||
audit = scalar("SELECT count(*) FROM job_replay_audit WHERE job_id=(SELECT id FROM processing_jobs WHERE attachment_id='%s')" % ident)
|
||||
check(audit == '1', 'operator replay audit count incorrect: ' + audit)
|
||||
check(job_query(ident, 'status') == 'ready', 'replayed job not ready')
|
||||
attempt = job_query(ident, 'attempt')
|
||||
check(attempt == '1', 'replay did not reset attempt: ' + attempt)
|
||||
invalid = compose('exec', '-T', 'dispatcher', 'python', '-m', 'app.jobs',
|
||||
'replay', '--id', ident, expected=(1,))
|
||||
print('PASS: failed-replay; permanent failure → metadata repaired → replay → ready; audit=1; replay of ready rejected')
|
||||
finally:
|
||||
if changed:
|
||||
# Never leave the synthetic attachment with altered metadata.
|
||||
pg("UPDATE attachments SET sha256='%s' WHERE id='%s'" % (original_sha, ident))
|
||||
|
||||
|
||||
def staging_cleanup(c):
|
||||
compose('up', '-d', 'dispatcher', 'worker')
|
||||
alice, _bob, att, original = make_upload(c)
|
||||
verify_ready(c, alice, att, original, seconds=180)
|
||||
wait_staging_cleared(att['id'], seconds=30)
|
||||
verify_staging_absent(att['id'])
|
||||
print('PASS: staging-cleanup; ready, DB staging_key=NULL, original staging object absent in S3')
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--scenario', required=True,
|
||||
choices=['broker-persistence', 'failed-replay', 'staging-cleanup'])
|
||||
args = parser.parse_args()
|
||||
if os.getenv('LAB5_ALLOW_FAILURE_TEST') != 'yes':
|
||||
raise Failure('Set LAB5_ALLOW_FAILURE_TEST=yes; run only on your isolated Lab5 stack')
|
||||
c = Client('http://localhost:8080')
|
||||
try:
|
||||
wait_api()
|
||||
if args.scenario == 'broker-persistence':
|
||||
broker_persistence(c)
|
||||
elif args.scenario == 'failed-replay':
|
||||
failed_replay(c)
|
||||
else:
|
||||
staging_cleanup(c)
|
||||
finally:
|
||||
# Restore normal services even when an assertion fails. NO volume deletion.
|
||||
try:
|
||||
compose('up', '-d', '--wait', 'broker')
|
||||
compose('up', '-d', 'dispatcher', 'worker')
|
||||
except Failure:
|
||||
print('WARNING: inspect docker compose ps and restore dispatcher/worker manually')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,108 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Explicit operator evidence for Lab5 queue durability and failure windows.
|
||||
|
||||
Runs only on an isolated lab5 Compose stack. Never resets named volumes. The test
|
||||
preserves user/session secrets strictly in process memory and prints no tokens.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from client import Client, Failure, check, run
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def compose(*args, expected=(0,)):
|
||||
p = subprocess.run(['docker', 'compose', '--env-file', '.env', *args], cwd=ROOT,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=240)
|
||||
if p.returncode not in expected:
|
||||
raise Failure('docker compose command failed: %s (exit %s); inspect docker compose ps/logs'
|
||||
% (' '.join(args[:2]), p.returncode))
|
||||
return p
|
||||
|
||||
|
||||
def wait_api(timeout=60):
|
||||
import urllib.request
|
||||
deadline=time.monotonic()+timeout
|
||||
while time.monotonic()<deadline:
|
||||
try:
|
||||
with urllib.request.urlopen('http://localhost:8080/health/ready', timeout=2) as r:
|
||||
if r.status==200:
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(.5)
|
||||
raise Failure('API did not become ready')
|
||||
|
||||
|
||||
def make_queued(client):
|
||||
alice,bob,eve,chat=client.bootstrap()
|
||||
att,original=client.attachment(alice,chat)
|
||||
check(att['status']=='queued','202 must return queued snapshot')
|
||||
c=client.call('GET','/api/v1/attachments/'+att['id']+'/content',409,actor=alice)
|
||||
attached=client.message(alice,chat,'',attachments=[att['id']])['json']
|
||||
check(attached['attachment_ids']==[att['id']],'queued attachment cannot be linked')
|
||||
return alice,bob,att,original
|
||||
|
||||
|
||||
def verify_ready(client,actor,att,original,seconds=180):
|
||||
r=client.wait_ready(actor,att,wait_seconds=seconds)
|
||||
check(len(r['variants']) == 3, 'expected exactly three variants, no duplicate entries')
|
||||
variants={v['name']:v for v in r['variants']}
|
||||
check(set(variants)=={'thumbnail','crop','optimized'},'missing/extra variants')
|
||||
check((variants['thumbnail']['width'],variants['thumbnail']['height'])==(256,160), 'thumbnail dimensions')
|
||||
check((variants['crop']['width'],variants['crop']['height'])==(128,128), 'crop dimensions')
|
||||
raw=client.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=actor)
|
||||
check(raw['bytes']==original,'original changed across asynchronous pipeline')
|
||||
for name in ('thumbnail','crop','optimized'):
|
||||
v=variants[name]
|
||||
response=client.call('GET','/api/v1/attachments/'+att['id']+'/content?variant='+name,actor=actor)
|
||||
check(len(response['bytes'])==v['size_bytes'] and hashlib.sha256(response['bytes']).hexdigest()==v['sha256'],
|
||||
'variant checksum mismatch: '+name)
|
||||
return r
|
||||
|
||||
|
||||
def main():
|
||||
parser=argparse.ArgumentParser()
|
||||
parser.add_argument('--scenario',choices=['paused','outbox-crash','worker-crash'],required=True)
|
||||
args=parser.parse_args()
|
||||
if os.getenv('LAB5_ALLOW_FAILURE_TEST')!='yes':
|
||||
raise Failure('Set LAB5_ALLOW_FAILURE_TEST=yes in PowerShell to run destructive failure test')
|
||||
c=Client('http://localhost:8080')
|
||||
# All tests make a fresh attachment while dispatcher/worker are stopped.
|
||||
compose('stop','worker','dispatcher')
|
||||
try:
|
||||
alice,bob,att,original=make_queued(c)
|
||||
print('Created durable queued attachment',att['id'],flush=True)
|
||||
if args.scenario=='paused':
|
||||
compose('restart','api1','api2','broker')
|
||||
compose('up','-d','--wait','broker')
|
||||
wait_api()
|
||||
elif args.scenario=='outbox-crash':
|
||||
# Transaction committed, dispatcher crashes before publish.
|
||||
compose('run','--rm','-e','LAB5_FAULT_BEFORE_PUBLISH=once',
|
||||
'dispatcher',expected=(78,))
|
||||
print('Injected dispatcher exit 78 after committed outbox, before publish')
|
||||
else:
|
||||
compose('up','-d','dispatcher')
|
||||
# Fault after all S3 writes and before PostgreSQL result COMMIT and ack.
|
||||
compose('run','--rm','-e','LAB5_FAULT_AFTER_S3=once',
|
||||
'worker',expected=(77,))
|
||||
print('Injected worker exit 77 after S3 effects, before result/ack')
|
||||
compose('up','-d','dispatcher','worker')
|
||||
wait_api()
|
||||
ready=verify_ready(c,bob,att,original)
|
||||
check(ready['status']=='ready','attachment not ready')
|
||||
print('PASS:',args.scenario,'durable queued->ready; original/3 variants verified; no duplicates')
|
||||
finally:
|
||||
# Restore the normal topology even after an assertion failure.
|
||||
compose('up','-d','dispatcher','worker')
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,26 @@
|
||||
"""Operator ephemeral probe: old rotated worker S3 secret denied, new secret succeeds."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
from botocore.exceptions import ClientError
|
||||
|
||||
def client(secret):
|
||||
return boto3.client('s3',endpoint_url='https://s3-gw:8334',
|
||||
region_name='us-east-1',aws_access_key_id=os.environ['S3_WORKER_ACCESS_KEY'],
|
||||
aws_secret_access_key=secret,verify='/run/pki/ca.crt',
|
||||
config=Config(s3={'addressing_style':'path'},connect_timeout=4,read_timeout=4,retries={'max_attempts':1}))
|
||||
|
||||
def main():
|
||||
old=Path('/operator/old-secret').read_text().strip()
|
||||
current=os.environ['S3_WORKER_SECRET_KEY']
|
||||
assert old and old!=current,'Old and current secrets cannot match'
|
||||
client(current).head_bucket(Bucket=os.environ['S3_BUCKET'])
|
||||
denied=False
|
||||
try:
|
||||
client(old).head_bucket(Bucket=os.environ['S3_BUCKET'])
|
||||
except ClientError as e:
|
||||
denied=e.response.get('ResponseMetadata',{}).get('HTTPStatusCode') in (401,403)
|
||||
assert denied,'Old S3 credential unexpectedly worked or failure was not auth-related'
|
||||
print('PASS: new worker credential accepted, revoked old credential denied')
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,39 @@
|
||||
"""Black-box security controls: rate limit shared at Redis, token logout, spoofed identity, ACL.
|
||||
No secret or bearer is logged; uses the provided public HTTP client.
|
||||
"""
|
||||
import base64
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
def main():
|
||||
args=arguments('Lab7 live auth/ACL/429 checks; use verified HTTPS + CA')
|
||||
c=Client(args.base_url,args.ca_file)
|
||||
alice,bob,eve,chat=c.bootstrap()
|
||||
token=alice['token']
|
||||
response=c.call('GET','/api/v1/users/me',actor=alice,schema='User')
|
||||
check(response['json']['id']==alice['id'],'Bearer identity mismatch')
|
||||
response=c.call('GET','/api/v1/chats/'+chat['id'],404,actor=eve,
|
||||
headers={'X-User-Id':alice['id']})
|
||||
check(response['status']==404,'X-User-Id spoof changed access')
|
||||
check(c.call('DELETE','/api/v1/auth/sessions/current',204,actor=alice)['status']==204,
|
||||
'logout failed')
|
||||
check(c.call('GET','/api/v1/users/me',401,actor=alice)['status']==401,
|
||||
'revoked session still valid')
|
||||
# Use a different registered account; count is stored centrally by username hash.
|
||||
username=bob['registration']['username']
|
||||
statuses=[]
|
||||
for _ in range(10):
|
||||
basic=base64.b64encode((username+':incorrect-password').encode()).decode()
|
||||
r=c.call('POST','/api/v1/auth/sessions',expected=(401,429),
|
||||
headers={'Authorization':'Basic '+basic})
|
||||
statuses.append(r['status'])
|
||||
if r['status']==429:
|
||||
check(r['headers'].get('Retry-After')=='60','429 lacks Retry-After')
|
||||
break
|
||||
check(429 in statuses,'shared login limiter did not issue 429')
|
||||
check(c.call('GET','/api/v1/users/me',401,
|
||||
headers={'Authorization':'Bearer completely_invalid'})['status']==401,
|
||||
'invalid token accepted')
|
||||
print('PASS: trusted HTTPS+Bearer, X-User-Id spoof denied, logout revoked, shared 429, Retry-After')
|
||||
|
||||
if __name__=='__main__':run(main)
|
||||
@@ -0,0 +1,33 @@
|
||||
"""Offline tests of admission safeguards and OpenBao contracts; no Docker needed."""
|
||||
import ast
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from cryptography import x509
|
||||
|
||||
BASE=Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0,str(BASE))
|
||||
|
||||
def main():
|
||||
from app.secrets import ALLOWED
|
||||
assert ALLOWED['api'] != ALLOWED['worker']
|
||||
assert 'BROKER_PASSWORD' in ALLOWED['worker'] and 'BROKER_PASSWORD' in ALLOWED['dispatcher']
|
||||
assert 'ROOT_TOKEN' not in str(ALLOWED)
|
||||
for role in ALLOWED:
|
||||
p=(BASE/'infra/openbao/policies'/f'{role}.hcl').read_text()
|
||||
assert f'kv/data/{role}' in p and 'capabilities = ["read"]' in p
|
||||
assert all(f'kv/data/{other}' not in p for other in ALLOWED if other!=role)
|
||||
for name in ('ingress','api1','api2','broker','otel','metrics'):
|
||||
cfg=(BASE/'infra/tls'/ (name+'.cfg')).read_text()
|
||||
assert 'ssl' in cfg and 'crt ' in cfg
|
||||
for name in ('api1','api2','broker','otel'):
|
||||
cfg=(BASE/'infra/tls'/(name+'.cfg')).read_text()
|
||||
assert 'verify required' in cfg
|
||||
assert 'ssl_c_san' in cfg
|
||||
pki=BASE/'.local/pki'
|
||||
if (pki/'ca.crt').exists():
|
||||
c=x509.load_pem_x509_certificate((pki/'ingress.crt').read_bytes())
|
||||
san=c.extensions.get_extension_for_class(x509.SubjectAlternativeName).value
|
||||
assert 'localhost' in san.get_values_for_type(x509.DNSName)
|
||||
print('PASS: scoped OpenBao policies, mTLS identity ACLs, public SAN configuration')
|
||||
if __name__=='__main__': main()
|
||||
@@ -0,0 +1,62 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Real Python OTLP SDK wire-format test against a local in-process receiver.
|
||||
Requires requirements.txt (does not require Docker or external services).
|
||||
This is not a Collector/backend integration test.
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import threading
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
sys.path.insert(0,str(Path(__file__).resolve().parents[1]))
|
||||
from opentelemetry.trace import SpanKind
|
||||
from opentelemetry.proto.collector.trace.v1.trace_service_pb2 import ExportTraceServiceRequest
|
||||
from opentelemetry.proto.collector.logs.v1.logs_service_pb2 import ExportLogsServiceRequest
|
||||
from opentelemetry.proto.collector.metrics.v1.metrics_service_pb2 import ExportMetricsServiceRequest
|
||||
from app import telemetry as ot
|
||||
|
||||
received={k:[] for k in ('/v1/traces','/v1/logs','/v1/metrics')}
|
||||
class Receiver(BaseHTTPRequestHandler):
|
||||
def do_POST(self):
|
||||
data=self.rfile.read(int(self.headers['Content-Length']))
|
||||
received[self.path].append(data)
|
||||
self.send_response(200);self.send_header('Content-Type','application/x-protobuf');self.send_header('Content-Length','0');self.end_headers()
|
||||
def log_message(self,*args): pass
|
||||
|
||||
def main():
|
||||
server=ThreadingHTTPServer(('127.0.0.1',0),Receiver)
|
||||
threading.Thread(target=server.serve_forever,daemon=True).start()
|
||||
os.environ['OTEL_ENABLED']='yes'
|
||||
os.environ['OTEL_EXPORTER_OTLP_ENDPOINT']='http://127.0.0.1:'+str(server.server_port)
|
||||
ot.init('worker')
|
||||
with ot.span('POST /api/v1/chats/{chat_id}/attachments',kind=SpanKind.SERVER) as root:
|
||||
stored=ot.inject(); trace_id=ot.trace_id()
|
||||
with ot.span('rabbitmq.publish',kind=SpanKind.PRODUCER,context=ot.extract(stored)) as producer:
|
||||
sent=ot.inject()
|
||||
with ot.span('rabbitmq.consume',kind=SpanKind.CONSUMER,context=ot.extract(sent)) as consumer:
|
||||
ot.event('job.ready',job_id='synthetic-id',attempt=2)
|
||||
ot.count('lab_jobs',{'job_type':'attachment.process.v1','outcome':'ready'})
|
||||
ot.observe('lab_job_duration',2.5,{'job_type':'attachment.process.v1','outcome':'ready'})
|
||||
ot.observe('lab_ready_duration',5.0,{'job_type':'attachment.process.v1'})
|
||||
class FakeS3:
|
||||
def put_object(self,**kw): return True
|
||||
ot.S3Tracing(FakeS3()).put_object(Key='SECRET_FILENAME_SENTINEL',Body=b'SECRET_CONTENT_SENTINEL')
|
||||
ot.flush()
|
||||
for provider in reversed(ot.providers): provider.shutdown()
|
||||
server.shutdown()
|
||||
spans=[s for raw in received['/v1/traces'] for r in ExportTraceServiceRequest.FromString(raw).resource_spans for scope in r.scope_spans for s in scope.spans]
|
||||
byname={s.name:s for s in spans}
|
||||
assert byname['rabbitmq.publish'].parent_span_id==root.get_span_context().span_id.to_bytes(8,'big')
|
||||
assert byname['rabbitmq.consume'].parent_span_id==producer.get_span_context().span_id.to_bytes(8,'big')
|
||||
assert all(s.trace_id.hex()==trace_id for s in spans)
|
||||
assert 's3.put_object' in byname
|
||||
logs=[l for raw in received['/v1/logs'] for r in ExportLogsServiceRequest.FromString(raw).resource_logs for scope in r.scope_logs for l in scope.log_records]
|
||||
assert any(l.trace_id.hex()==trace_id and l.span_id==consumer.get_span_context().span_id.to_bytes(8,'big') and l.body.string_value=='job.ready' for l in logs)
|
||||
points=[m for raw in received['/v1/metrics'] for r in ExportMetricsServiceRequest.FromString(raw).resource_metrics for scope in r.scope_metrics for m in scope.metrics]
|
||||
assert any(m.name=='lab_jobs' and m.sum.data_points[0].as_int==1 for m in points)
|
||||
assert any(m.name=='lab_job_duration' and list(m.histogram.data_points[0].explicit_bounds)==list(ot.BUCKETS) for m in points)
|
||||
for raw in sum(received.values(),[]): assert b'SECRET_FILENAME_SENTINEL' not in raw and b'SECRET_CONTENT_SENTINEL' not in raw
|
||||
print('PASS: real OTLP trace/log/metric encoding, parent links, histogram buckets, safe S3 attributes')
|
||||
|
||||
if __name__=='__main__': main()
|
||||
@@ -0,0 +1,64 @@
|
||||
"""Operator-triggered negative mTLS audit, inside isolated Compose networks.
|
||||
|
||||
Tests real new TLS connections (not cached sessions); no verify=False fallback.
|
||||
Needs `docker compose --profile audit run --rm tls-audit` after services healthy.
|
||||
"""
|
||||
import socket
|
||||
import ssl
|
||||
from pathlib import Path
|
||||
|
||||
CERT_DIR=Path('/run/audit-pki')
|
||||
CA=CERT_DIR/'ca.crt'
|
||||
|
||||
def check_target(label,host,port,*,path='/',method='GET',cert=None,expected=None,server_name=None):
|
||||
ctx=ssl.create_default_context(cafile=str(CA))
|
||||
ctx.check_hostname=True
|
||||
ctx.verify_mode=ssl.CERT_REQUIRED
|
||||
if cert:
|
||||
ctx.load_cert_chain(str(CERT_DIR/(cert+'.crt')),str(CERT_DIR/(cert+'.key')))
|
||||
try:
|
||||
with socket.create_connection((host,port),timeout=6) as tcp:
|
||||
with ctx.wrap_socket(tcp,server_hostname=server_name or host) as tls:
|
||||
tls.settimeout(6)
|
||||
# Must send something; an mTLS or ACL reject can arrive after the TLS handshake.
|
||||
if method=='AMQP':
|
||||
tls.sendall(b'AMQP\x00\x00\x09\x01')
|
||||
data=tls.recv(1024)
|
||||
# RabbitMQ answers the client protocol header with an AMQP Method frame (type 1).
|
||||
allowed=bool(data) and data[0]==1
|
||||
else:
|
||||
body=b'x' if method=='POST' else b''
|
||||
req=(f'{method} {path} HTTP/1.1\r\nHost: {host}\r\n'
|
||||
f'Content-Length: {len(body)}\r\nConnection: close\r\n\r\n').encode()+body
|
||||
tls.sendall(req)
|
||||
data=tls.recv(256)
|
||||
status=data.split(b' ',2)[1] if data.startswith(b'HTTP/') else b''
|
||||
# For OTLP POST malformed bytes should reach Collector, yielding a 4xx response
|
||||
# other than an authorization 403. For HTTP health require real 200.
|
||||
allowed=(status==b'200' if method=='GET' else status in (b'400',b'415'))
|
||||
except (ssl.SSLError,OSError,ValueError,ConnectionError):
|
||||
allowed=False
|
||||
if allowed!=expected:
|
||||
raise AssertionError(f'{label}: expected {"ALLOW" if expected else "DENY"}, got {"ALLOW" if allowed else "DENY"}')
|
||||
print(f'PASS {label}: {"allowed" if allowed else "rejected"}')
|
||||
|
||||
def main():
|
||||
for api in ('api1','api2'):
|
||||
for cert,yes in ((None,False),('foreign-client',False),('rogue-client',False),('worker-client',False),('lb-client',True)):
|
||||
check_target(f'{api}/{cert or "no-cert"}',api,8443,path='/health/live',cert=cert,expected=yes,server_name=api+'-tls')
|
||||
for cert,yes in ((None,False),('foreign-client',False),('rogue-client',False),('lb-client',False),('worker-client',True)):
|
||||
check_target(f'broker-gw/{cert or "no-cert"}','broker-gw',5671,method='AMQP',cert=cert,expected=yes)
|
||||
for cert,yes in ((None,False),('foreign-client',False),('rogue-client',False),('lb-client',False),('worker-client',True)):
|
||||
check_target(f'otel-gw/{cert or "no-cert"}','otel-gw',4318,path='/v1/traces',method='POST',cert=cert,expected=yes)
|
||||
# Collector→Loki uses its own identity, not the worker/API certs.
|
||||
for cert,yes in ((None,False),('foreign-client',False),('worker-client',False),('collector-client',True)):
|
||||
check_target(f'metrics-loki/{cert or "no-cert"}','metrics-gw',3102,path='/metrics',cert=cert,expected=yes)
|
||||
# A valid certificate for the wrong server name must never validate.
|
||||
check_target('api1/wrong-server-SAN','api1',8443,path='/health/live',cert='lb-client',expected=False,server_name='wrong-api-host')
|
||||
if (CERT_DIR/'old-lb-client.crt').is_file():
|
||||
for api in ('api1','api2'):
|
||||
check_target(f'{api}/revoked-lb',api,8443,path='/health/live',
|
||||
cert='old-lb-client',expected=False,server_name=api+'-tls')
|
||||
print('PASS: mTLS identity matrix (no cert / foreign CA / wrong role / positive / wrong server SAN)')
|
||||
|
||||
if __name__=='__main__': main()
|
||||
Reference in New Issue
Block a user