forked from mtusi2026/mtusi2026lab7
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
03cc1b5e06 | ||
|
|
912a874f00 |
+14
@@ -0,0 +1,14 @@
|
|||||||
|
FROM python:3.12.11-slim-bookworm
|
||||||
|
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 PIP_DISABLE_PIP_VERSION_CHECK=1
|
||||||
|
WORKDIR /app
|
||||||
|
RUN groupadd -g 10001 app && useradd -u 10001 -g 10001 -M -s /usr/sbin/nologin app
|
||||||
|
COPY requirements.txt ./requirements.txt
|
||||||
|
RUN python -m pip install --no-cache-dir -r requirements.txt
|
||||||
|
COPY src ./src
|
||||||
|
COPY migrations ./migrations
|
||||||
|
COPY scripts ./scripts
|
||||||
|
USER 10001:10001
|
||||||
|
EXPOSE 8443
|
||||||
|
STOPSIGNAL SIGTERM
|
||||||
|
# No secret, key or certificate is baked into the image: they are mounted at run time (/run/pki, /run/approle).
|
||||||
|
CMD ["python", "-m", "src.server"]
|
||||||
@@ -1,13 +1,14 @@
|
|||||||
PYTHON ?= python3
|
PYTHON ?= python3
|
||||||
BASE_URL ?= https://localhost:8443
|
BASE_URL ?= https://localhost:8443
|
||||||
CA_FILE ?=
|
CA_FILE ?= $(CURDIR)/secrets/pki/ca/ca.crt
|
||||||
ACTION_SCRIPT ?=
|
ACTION_SCRIPT ?=
|
||||||
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
||||||
|
|
||||||
.PHONY: help check validate test load test-persistence test-failover test-security
|
.PHONY: help check validate up down test load test-persistence test-failover test-security test-tls test-acl test-compromise incident scan
|
||||||
|
|
||||||
help:
|
help:
|
||||||
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
|
@echo "up: bootstrap PKI/secrets + OpenBao + stack; down: stop (volumes kept); test/load/test-persistence/test-failover/test-security: public checks"
|
||||||
|
@echo "test-tls: whole trust matrix; test-acl: ACL/rate-limit/leaks; test-compromise: track 1 probes; incident: track 1 recovery; scan: dependency+image scan"
|
||||||
|
|
||||||
check:
|
check:
|
||||||
$(PYTHON) scripts/check_contract.py
|
$(PYTHON) scripts/check_contract.py
|
||||||
@@ -15,6 +16,12 @@ check:
|
|||||||
validate:
|
validate:
|
||||||
$(PYTHON) scripts/validate_openapi.py
|
$(PYTHON) scripts/validate_openapi.py
|
||||||
|
|
||||||
|
up:
|
||||||
|
sh scripts/up.sh
|
||||||
|
|
||||||
|
down:
|
||||||
|
docker compose stop
|
||||||
|
|
||||||
test:
|
test:
|
||||||
$(PYTHON) tests/smoke.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
$(PYTHON) tests/smoke.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||||
|
|
||||||
@@ -22,12 +29,29 @@ load:
|
|||||||
$(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
$(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||||
|
|
||||||
test-persistence:
|
test-persistence:
|
||||||
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2)
|
$(PYTHON) tests/resilience.py --mode persistence --action-script "$(or $(ACTION_SCRIPT),scripts/restart.sh)" --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||||
$(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
|
|
||||||
|
|
||||||
test-failover:
|
test-failover:
|
||||||
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable stop-one hook"; exit 2)
|
$(PYTHON) tests/resilience.py --mode failover --action-script "$(or $(ACTION_SCRIPT),scripts/stop-one.sh)" --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||||
$(PYTHON) tests/resilience.py --mode failover --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
|
|
||||||
|
|
||||||
test-security:
|
test-security:
|
||||||
$(PYTHON) tests/security.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
$(PYTHON) tests/security.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||||
|
|
||||||
|
test-tls:
|
||||||
|
sh security-tests/run_in_net.sh tls_audit.py
|
||||||
|
|
||||||
|
test-acl:
|
||||||
|
$(PYTHON) security-tests/acl_leak.py $(TLS_ARGS) --grafana-password-file secrets/ops/grafana_admin_password
|
||||||
|
|
||||||
|
test-compromise:
|
||||||
|
sh security-tests/run_in_net.sh worker_compromise.py --profile after > evidence/worker-compromise-after.json
|
||||||
|
sh security-tests/run_in_net.sh worker_compromise.py --profile before > evidence/worker-compromise-before.json
|
||||||
|
|
||||||
|
incident:
|
||||||
|
docker compose stop worker
|
||||||
|
$(PYTHON) security-tests/jobs_integrity.py submit --n 10 $(TLS_ARGS)
|
||||||
|
sh scripts/incident_worker.sh
|
||||||
|
cd "$$PWD" && $(PYTHON) security-tests/jobs_integrity.py verify $(TLS_ARGS)
|
||||||
|
|
||||||
|
scan:
|
||||||
|
sh scripts/scan.sh
|
||||||
|
|||||||
+131
@@ -0,0 +1,131 @@
|
|||||||
|
# Отчёт - лабораторная 7
|
||||||
|
|
||||||
|
- Автор, группа: Алексей Миронов, БВТ2302
|
||||||
|
- Целевая оценка; выбранный трек 5, если нужен: 5, трек 1 («Компрометация worker»)
|
||||||
|
- Commit/PR: 912a874 lab 7 openbao/ https://gitea.privcloud.tech/mtusi2026/mtusi2026lab7/pulls/36
|
||||||
|
- Использованные источники, библиотеки и помощь ИИ: OWASP Password Storage / File Upload, документация OpenBao (AppRole, policies), Kafka SSL/ACL, Docker security; библиотеки argon2-cffi, redis-py, psycopg, confluent-kafka, boto3, uvicorn. Использовалась помощь ИИ.
|
||||||
|
|
||||||
|
## Запуск из чистого clone
|
||||||
|
|
||||||
|
Prerequisites: Docker Engine + Compose v2, Python 3.9+ и `openssl` на хосте. Версии образов закреплены в `compose.yaml` (python 3.12.11, postgres 17.6, redis 7.4.2, silo/MinIO RELEASE.2026-10-15, apache/kafka 3.9.0, openbao 2.4.1, otel-collector-contrib 0.131.0, prometheus 3.5.0, loki 3.5.3, tempo 2.8.2, grafana 12.1.1, haproxy 3.2.5).
|
||||||
|
|
||||||
|
```sh
|
||||||
|
make check && make validate # офлайн-проверки skeleton и OpenAPI (перед запуском стенда)
|
||||||
|
make up # bootstrap.sh (CA, leaf-сертификаты, пароли, Redis ACL) -> openbao -> init/unseal/bootstrap -> SecretID -> весь стек
|
||||||
|
# дождаться https://localhost:8443/health/ready
|
||||||
|
make test CA_FILE=$PWD/secrets/pki/ca/ca.crt
|
||||||
|
make test-security
|
||||||
|
make test-tls # вся trust matrix (внутри сети backend)
|
||||||
|
make test-acl # ACL, X-User-Id, logout, 413, 429, canary в логах и Loki
|
||||||
|
make test-persistence # scripts/restart.sh (перезапуск ВСЕХ stores + unseal)
|
||||||
|
make test-failover # scripts/stop-one.sh (останавливает одну реплику API)
|
||||||
|
make test-compromise # трек 1: пробы до/после least privilege -> evidence/worker-compromise-*.json
|
||||||
|
make incident # трек 1: компрометация -> отзыв -> ротация -> восстановление -> проверка заданий
|
||||||
|
make scan # pip-audit + trivy
|
||||||
|
```
|
||||||
|
|
||||||
|
**Действия оператора.** (1) Один раз `scripts/bao_init.sh` (вызывается из `make up`): 3 доли ключа, порог 2, доли и root token пишутся в `./secrets/operator` (0600) и никуда не печатаются. (2) После каждого рестарта OpenBao - `scripts/bao_unseal.sh` (его делает `restart.sh`). (3) SecretID живёт 24 ч: `scripts/bao_secret_id.sh all`. Секреты и ключи не попадают в Git (`secrets/` в `.gitignore`), образ и отчёт.
|
||||||
|
|
||||||
|
**Остановка:** `make down` (`docker compose stop`, тома сохраняются). **Намеренное удаление учебных данных:** `docker compose down -v && rm -rf secrets`.
|
||||||
|
|
||||||
|
## Архитектура и решения
|
||||||
|
|
||||||
|
```
|
||||||
|
Клиент ─TLS(CA,localhost)-> HAProxy:8443 ─mTLS(SAN lb)-> API ×2 :8443
|
||||||
|
API ─TLS verify-full-> PostgreSQL (роль api) ─TLS+ACL-> Redis (сессии, rate limit) ─TLS-> S3 (svc-api)
|
||||||
|
dispatcher ─outbox(PostgreSQL)-> Kafka(mTLS, producer ACL) -> worker (consumer ACL) ─-> S3 (svc-worker), PostgreSQL (роль worker)
|
||||||
|
api/worker/dispatcher ─mTLS(workload CA)-> OTel Collector ─mTLS-> Prometheus | Loki | Tempo ←mTLS─ Grafana (https://127.0.0.1:3000)
|
||||||
|
api/worker/dispatcher/sweeper ─TLS + AppRole-> OpenBao (file storage, sealed при старте)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Kafka:** слушатель брокера назван `INTERNAL` (протокол SSL, `ssl.client.auth=required`, PEM-хранилища): образ `apache/kafka` для слушателя с именем `SSL://` требует Confluent-переменные (`*_FILENAME`, `*_CREDENTIALS`) и PKCS12; с другим именем эти проверки не применяются, а защита (mTLS + ACL по CN) та же.
|
||||||
|
|
||||||
|
**Источник истины:** PostgreSQL (пользователи, чаты, сообщения, задания, outbox); сессии - Redis с AOF; файлы - S3; доставка заданий - outbox -> Kafka (at-least-once, ack после COMMIT результата).
|
||||||
|
|
||||||
|
**Перенесено из lab6 без изменений логики:** бизнес-API, идемпотентность, вложения, outbox/dispatcher/worker, lease/retry, sweeper, observability (collector, дашборд, alert rules, runbooks). **Изменено в lab7:** внешний HTTPS и mTLS LB->API (`src/server.py`, `infra/haproxy.cfg`); TLS/mTLS на всех связях; OpenBao + AppRole (`src/vault.py`, `infra/openbao/`); раздельные роли БД/S3/Kafka/Redis; Argon2id с rehash и общий rate limit (`src/main.py`); hardening контейнеров; скрипты PKI/ротации/инцидента; тесты `security-tests/`.
|
||||||
|
|
||||||
|
Соответствие `.env.example`: `APP_PORT` -> публикуемый порт LB; `ARGON2_*` -> параметры хеша; `BAO_ADDR` -> адрес OpenBao; `S3_ENDPOINT`, `OTEL_EXPORTER_OTLP_*`, `TLS_*_FILE` заданы в `compose.yaml`; `*_FILE` с секретами заменены монтированием файлов из `./secrets` и чтением из OpenBao.
|
||||||
|
|
||||||
|
Роль -> сервис -> health -> volume -> сеть/порт -> доставка credentials:
|
||||||
|
|
||||||
|
| Роль | Сервис | Health | Volume | Сеть/порт | Credentials |
|
||||||
|
| --- | --- | --- | --- | --- | --- |
|
||||||
|
| ingress | load_balancer | `haproxy -c` | - | 127.0.0.1:8443 | cert `lb-public`, клиентский cert `lb` |
|
||||||
|
| api (×2) | api | TCP 8443 | - | backend, не публикуется | cert `api`, AppRole `api` |
|
||||||
|
| db | postgres | pg_isready | postgres_data | backend | пароль владельца только в `migrate`; роли из OpenBao |
|
||||||
|
| sessions | redis | redis-cli PING (ACL `health`) | redis_data | backend | ACL-пользователь `api` |
|
||||||
|
| s3 | s3 | - (ждёт `s3_init`) | s3_data | backend | `svc-*` ключи, root только `s3`/`s3_init` |
|
||||||
|
| broker | kafka (+kafka_init) | broker-api-versions | kafka_data | backend | CN-принципалы + ACL |
|
||||||
|
| worker/dispatcher/sweeper | worker, dispatcher, s3_sweeper | - | - | backend | cert + AppRole |
|
||||||
|
| secrets | openbao | `bao status` (sealed допустим) | bao_data | backend | AppRole/policies |
|
||||||
|
| telemetry | otel-collector, prometheus, loki, tempo, grafana | provisioning в Git | *_data | backend; Grafana 127.0.0.1:3000 | mTLS |
|
||||||
|
|
||||||
|
Bootstrap-операции (идемпотентны): схема и роли - сервис `migrate`; bucket и S3-пользователи - `s3_init`; топик и ACL - `kafka_init`; KV/AppRole/policies - `bao_bootstrap.sh`.
|
||||||
|
|
||||||
|
## Доказательства критериев
|
||||||
|
|
||||||
|
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| Публичный smoke | `make test` | PASS: lab7 public API scenario | evidence/evidence.txt |
|
||||||
|
| Внешний TLS, чужой CA отклонён | `make test-security` | PASS: trusted HTTPS works; untrusted CA rejected | evidence/evidence.txt |
|
||||||
|
| Argon2id, параметры ≥ 19 MiB/t=2/p=1, обоснованы измерением | `docker compose run --rm --entrypoint python migrate scripts/argon2_bench.py --runs 20` | m=19 MiB, t=2, p=1: медиана 83 мс, p95 94 мс, ≈12 логинов/с на слот; для сравнения m=46 MiB, t=1: 211 мс (p95 400 мс), m=64 MiB, t=3, p=4 (параметры lab6): 609 мс (p95 811 мс) | evidence/evidence.txt |
|
||||||
|
| LB->API mTLS + allowlist identity | `make test-tls` (блок api) | `lb` принят (200); без сертификата, чужой CA, `outsider` (тот же CA), `worker` - отказ; клиент, не доверяющий CA сервера, - SSLCertVerificationError | evidence/evidence.txt |
|
||||||
|
| TLS на остальных связях | `make test-tls` | 38/38 проб как ожидается: postgres/redis/s3/openbao/prometheus/loki/tempo - чужой CA отклоняется, plaintext отклоняется | evidence/evidence.txt |
|
||||||
|
| OpenBao не dev, persistent, policy allow/deny | `make test-compromise` (bao-блок), `make test-persistence` | свой путь `kv/data/worker` - allowed; `kv/data/api` и запись sys-policy - denied; persistence PASS (OpenBao перезапущен и разблокирован `restart.sh`) | evidence/worker-compromise-after.json, evidence/evidence.txt |
|
||||||
|
| Контейнеры: без privileged/host network/socket, non-root, лимиты | `docker inspect` по всем запущенным контейнерам (16), `compose.yaml` | у всех `Privileged=false`, сеть - только сети проекта (`mtusi-lab7_*`, host network нет), `CapDrop=[ALL]`, `SecurityOpt=[no-new-privileges:true]`; пользователь 10001:10001 везде, кроме postgres (стартует от root только для chown ключа, затем понижает права - исключение объяснено); `docker.sock`, `privileged`, `network_mode: host` в `compose.yaml` отсутствуют; лимиты `cpus`/`mem_limit`/`pids_limit` заданы | evidence/evidence.txt |
|
||||||
|
| 429/Retry-After, 413, ACL, logout | `make test-acl` | ALL PASS: чужой пользователь получает 404 на метаданные, сообщения и вложения чужого чата; подделанный `X-User-Id` игнорируется (404), без Bearer - 401; logout 204 и токен после него 401; JSON > 64 KiB -> 413; пароль и токен canary-пользователя отсутствуют в логах контейнеров и в Loki; после 10 неверных попыток подряд - 429 с `Retry-After: 59` | evidence/evidence.txt |
|
||||||
|
| Restart и отказ реплики через HTTPS | `make test-persistence`, `make test-failover` | persistence PASS; failover PASS: 2 реплики, 100 успешных записей, 1 неудачная попытка, первое восстановление за 2.785 с | evidence/evidence.txt |
|
||||||
|
| **4:** mTLS broker и Collector, чужой cert того же CA не получает прав | `make test-tls` (блоки kafka, collector) | Kafka: `dispatcher` пишет (OK); `worker`, `api` и `outsider` (CA-signed) - `AUTHORIZATION_FAILED`; Collector: принимает `api`/`worker`/`dispatcher`, отклоняет `outsider`/`grafana`/`lb` (тот же root CA) и клиента без сертификата | evidence/evidence.txt |
|
||||||
|
| **4:** rehash старого хеша | вход пользователя со старым хешем (lab6) -> `SELECT left(password_hash,30)` через `psql` | - | evidence/rehash.txt |
|
||||||
|
| **4:** ротация secret и leaf без пересборки, отзыв | `make incident` (внутри: `rotate_secret.sh db-worker`, `rotate_secret.sh s3-worker`, `pki.sh leaf worker`, `revoke_identity.sh worker`) | выполнено без пересборки образов: ротированы пароль роли БД и S3-секрет worker, перевыпущен сертификат `worker` (workload CA, 14 д), AppRole отозван; на новых подключениях старые SecretID, пароль и S3-секрет отклоняются, новые работают (6/6) | evidence/revoked-creds.txt, evidence/evidence.txt |
|
||||||
|
| **4:** sealed/expiry OpenBao | `docker compose restart openbao`, `docker compose restart worker`, `bao_unseal.sh`, `bao_secret_id.sh all`, повторный рестарт worker | после перезапуска OpenBao `/health/ready` продолжал отвечать `{"status":"ok"}` (API уже держит секреты в памяти и не зависит от OpenBao при работе); после `bao_unseal.sh` и выдачи нового SecretID worker перезапущен и работает (Up); SecretID с TTL 24 ч, токен 10 мин и отзывается после чтения - expiry и отзыв проверены в `make incident` | evidence/evidence.txt, evidence/revoked-creds.txt |
|
||||||
|
| **4:** read_only/no-new-privileges/cap_drop, tmpfs | `docker inspect` (`ReadonlyRootfs`), `compose.yaml` | `ReadonlyRootfs=true` у api (×2), worker, dispatcher, s3_sweeper, load_balancer, otel-collector, redis (с отдельными tmpfs для `/tmp`); `false` только у stateful-сервисов с записью в том: postgres, kafka, s3, openbao, prometheus, loki, tempo, grafana - исключения объяснены в комментариях `compose.yaml`; `no-new-privileges` и `cap_drop: ALL` - у всех | evidence/evidence.txt |
|
||||||
|
| **4:** dependency/image scan с применимостью | `make scan` | pip-audit: 89 находок в 3 пакетах; trivy (HIGH/CRITICAL, только с доступным исправлением) по 5 образам; разбор - в разделе «Scan triage» | evidence/pip-audit.txt, evidence/trivy-*.txt |
|
||||||
|
| **4:** ≥ 6 угроз с тестами | `security/THREAT_MODEL.md` (9 угроз, у каждой контроль и отрицательный тест) | см. строки выше | security/THREAT_MODEL.md |
|
||||||
|
| **Трек 1:** до/после least privilege | `make test-compromise` | after: 19/19 проб соответствуют least privilege; before (модель lab6): из 11 запретных проб 10 разрешены | evidence/worker-compromise-before.json, evidence/worker-compromise-after.json |
|
||||||
|
| **Трек 1:** отзыв, ротация, восстановление, сохранность заданий | `make incident` | старые SecretID, пароль роли БД и S3-секрет отклоняются на новых подключениях, новые работают (6/6); 10/10 заданий `ready`, lost=0; инцидент 23:25:35Z–23:27:08Z (93 с) | evidence/incident-start.txt, evidence/incident-end.txt, evidence/revoked-creds.txt, evidence/evidence.txt |
|
||||||
|
|
||||||
|
## Эксперименты и отказы (трек 1)
|
||||||
|
|
||||||
|
**Гипотеза.** При наличии у атакующего всех credentials worker (AppRole-материал, пароль роли БД, ключ S3, сертификат Kafka) он ограничен: в БД - состояние заданий и статусы вложений; в S3 - чтение `staging/*` и запись `attachments/*`; в Kafka - чтение своей группы; запрещены `users`, `messages`, DDL, `DELETE`, листинг bucket, чтение готовых вложений, запись в `staging/` и в топик, чужие пути OpenBao, доступ к API. В lab6 (общие креды, PLAINTEXT Kafka) всё перечисленное разрешено.
|
||||||
|
|
||||||
|
**Методика.** `security-tests/worker_compromise.py` выполняет одинаковый список из 19 проб в двух профилях: `after` - идентичность worker этого стенда (получена через настоящий AppRole login), `before` - модель lab6: владелец БД, root S3, административный Kafka-сертификат. Результат - JSON, значения секретов не выводятся. Восстановление: `incident_worker.sh`. Сохранность заданий: `jobs_integrity.py` (N=10 загрузок при остановленном worker, после инцидента все 10 должны стать `ready`, потерь 0).
|
||||||
|
|
||||||
|
Бюджет защиты логина (измерено на этом стенде): один Argon2id-хеш (19 MiB, t=2, p=1) ≈ 83 мс, слотов `ARGON2_CONCURRENCY=2` на реплику ⇒ около 24 проверок/с на реплику (≈48/с на две реплики) при лимите 30 попыток/мин на IP и 10 ошибок/мин на логин; параметры lab6 (64 MiB, t=3, p=4) на том же стенде в ≈7 раз медленнее (609 мс).
|
||||||
|
|
||||||
|
Окружение/лимиты/версии: см. `compose.yaml`; стенд запускался на Windows + WSL2 (Docker Compose), прогон 2026-11-22; hardware (CPU/RAM) - -; нагрузочный профиль для этих проверок не применялся (проверки функциональные: 1 прогон каждой, повторы и p50/p95/p99 - -).
|
||||||
|
|
||||||
|
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| Пробы с credentials worker (after) | 19/19 соответствуют ожиданию | 19/19: БД - только состояние заданий и статусы вложений (users, messages, DELETE, DDL - denied); S3 - GET staging и PUT attachments (GET attachments, PUT staging, DELETE, List - denied); Kafka - consume своей группы (produce и чужая группа - denied); OpenBao - только свой путь; API по сертификату worker - denied | - |
|
||||||
|
| Те же пробы (before, модель lab6) | запрещённые операции разрешены | 16 проб (OpenBao-пробы в этом профиле не применимы): все 5 «разрешённых» работают; из 11 «запретных» 10 разрешены (чтение `users`/`messages`, DELETE, DDL, чтение/удаление `attachments`, запись `staging`, List, produce в Kafka, чужая группа), отклонён только доступ к API по сертификату worker | - |
|
||||||
|
| Отзыв AppRole worker + ротация DB/S3 (`incident_worker.sh`, шаг 6) | на НОВЫХ подключениях старый SecretID, пароль роли и S3-секрет отклоняются, новые работают (6/6 проб) | 6/6: старый SecretID - rejected, пароль роли БД - rejected, S3-секрет - rejected; новые credentials - accepted | входит в 93 с инцидента (следующая строка) |
|
||||||
|
| `incident_worker.sh` при 10 заданиях в очереди | 10/10 `ready`, потерь 0 | 10/10 `ready`, lost=0 (worker был остановлен на время постановки заданий) | 93 с от остановки worker до запуска с новыми credentials (23:25:35Z–23:27:08Z); потеря данных 0 |
|
||||||
|
| Остановка API-реплики | запросы идут на оставшуюся | 100 успешных записей, 1 неудачная попытка в момент остановки | 2.785 с до первого успешного ответа |
|
||||||
|
| OpenBao sealed + рестарт worker | запущенные сервисы продолжают работать; новый старт сервиса требует OpenBao | `/health/ready` = 200 после рестарта OpenBao; worker после unseal и нового SecretID - `Up` | - |
|
||||||
|
|
||||||
|
## Scan triage
|
||||||
|
|
||||||
|
Прогон `make scan` от 2026-11-22: `pip-audit -r requirements.txt` и `trivy image --severity HIGH,CRITICAL --ignore-unfixed` (то есть показаны только находки, для которых исправление существует). Подробные списки - в evidence/. Итоги: pip-audit - 89 находок в 3 пакетах; trivy - app 147 в ОС (HIGH 138, CRITICAL 9) + 44 в Python-пакетах (HIGH 39, CRITICAL 5); haproxy 29 (CRITICAL 3); openbao 29 в ОС (CRITICAL 2) + 72 в бинарнике `bao` (CRITICAL 7); postgres 34 (CRITICAL 2) + 26 в `gosu` (CRITICAL 1); redis 24 (CRITICAL 2) + 60 в `gosu` (CRITICAL 4). Находки сгруппированы по компоненту и пути, по которому уязвимость достижима в этом стенде.
|
||||||
|
|
||||||
|
| Находка | Компонент | Применимость в этом стенде | Решение |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| Pillow 11.3.0: десятки CVE/PYSEC, исправления в 12.x–13.0.0 (pip-audit, trivy) | worker (и api при `imgproc`) | Применимо: Pillow декодирует загружаемые пользователем изображения. Смягчение: размер ≤ 10 MiB, ≤ 40 Mpx до декодирования, декодирование в дочернем процессе с RLIMIT_AS/CPU и таймаутом, `read_only`, `cap_drop: ALL`, `mem_limit`, non-root | Принято на время лабы с компенсирующими мерами; план: обновить Pillow до версии ≥ 13.0.0 из pip-audit и повторить `make test` и `make scan` |
|
||||||
|
| Starlette 0.47.3 (PYSEC, исправления вплоть до 1.3.1) | api | Применимо частично: фреймворк обрабатывает HTTP-запросы, но к API есть прямой доступ только у LB (mTLS + allowlist SAN), тело JSON ограничено 64 KiB, лимит запросов в Redis | Принято; план: обновить связку FastAPI/Starlette после проверки совместимости (Starlette закреплён версией FastAPI) |
|
||||||
|
| opentelemetry-api 1.45.1 (исправление 1.45.2) | api, worker, dispatcher | Низкая: библиотека телеметрии, не обрабатывает внешний ввод | Обновить до 1.45.2 (patch-версия) |
|
||||||
|
| CVE-2026-31789 (openssl/libssl, CRITICAL) во всех пяти образах; исправленные версии пакетов существуют | api, haproxy, openbao, postgres, redis | Применимо в части TLS: библиотека используется TLS-слушателями. Смягчение: сеть `backend` internal, mTLS/ACL/пароли на всех связях, опубликованы только 127.0.0.1:8443 и 127.0.0.1:3000 | Обновить базовые образы до патч-версий с исправленным openssl и повторить сканирование |
|
||||||
|
| Образ приложения (Debian 12): 147 находок ОС (apt, util-linux, krb5, gnutls, sqlite, perl-base и др.) | api, worker, dispatcher, sweeper | Большинство пакетов не вызывается кодом приложения (нет apt/perl/krb5 в пути запроса); контейнеры non-root, `read_only`, `cap_drop: ALL`, `no-new-privileges` | Принято; план: пересобрать на актуальном патч-релизе `python:3.12-slim` |
|
||||||
|
| OpenBao 2.4.1: зависимости бинарника `bao` (pgx, grpc, go-jose, stdlib, docker и др.) и сам openbao | openbao | Порт 8200 не публикуется (сеть `backend` internal), TLS, доступ только по токену AppRole с политикой на один путь; движок баз данных (pgx) не включён - используются только `kv` и `approle` | Принято на время лабы; перед использованием вне лабы обновить образ OpenBao до версии с исправлениями |
|
||||||
|
| `gosu` (Go stdlib) в образах postgres и redis | postgres, redis | Низкая: `gosu` выполняется только при старте контейнера для смены пользователя и не слушает сеть; redis запускается сразу пользователем 10001 (`user:`), `gosu` не вызывается | Принято |
|
||||||
|
| haproxy: Alpine (musl, zlib, pcre2 - CRITICAL CVE-2025-58050) | load_balancer | Ограниченно: в `haproxy.cfg` нет regex-ACL (pcre2 не используется для сопоставления); порт публикуется только на 127.0.0.1 | Обновить тег образа на версию с исправленными библиотеками |
|
||||||
|
|
||||||
|
## Ограничения и следующие шаги
|
||||||
|
|
||||||
|
- Один хост и по одному экземпляру stateful-сервисов; репликации нет.
|
||||||
|
- Отзыв сертификатов (CRL/OCSP) не реализован: украденный сертификат `worker` остаётся рабочим для чтения очереди и OTLP до истечения (14 дней) или смены CA; смягчение - consumer-only ACL, ротация `pki.sh leaf worker`, экстренная замена CN в ACL.
|
||||||
|
- Prometheus/Loki/Tempo проверяют клиента только по CA (SAN-фильтр недоступен); ограничение - internal-сеть.
|
||||||
|
- Ключи сертификатов смонтированы файлами в `./secrets` (каталог 0700, файлы 0644 для чтения контейнерами с другим uid) - упрощение учебного стенда.
|
||||||
|
- Unseal-ключ передаётся аргументом `bao operator unseal` (виден в списке процессов оператора на время вызова); для production - ввод с TTY или отдельные хранители.
|
||||||
|
- `disable_mlock=true`: контейнер без `IPC_LOCK`; swap на хосте должен быть отключён.
|
||||||
|
- OpenBao использует `file` storage (один узел); для HA - Raft.
|
||||||
|
- Rate limit - fixed window; блокирует и владельца логина на окно при переборе.
|
||||||
+530
@@ -0,0 +1,530 @@
|
|||||||
|
# Lab 7: lab 6 stack + TLS/mTLS everywhere, OpenBao (non-dev), least privilege, hardened containers.
|
||||||
|
name: mtusi-lab7
|
||||||
|
|
||||||
|
x-hardened: &hardened # every container: no privilege escalation, all capabilities dropped (stateful exceptions are explicit below)
|
||||||
|
security_opt: ["no-new-privileges:true"]
|
||||||
|
cap_drop: ["ALL"]
|
||||||
|
pids_limit: 256
|
||||||
|
|
||||||
|
x-otel-env: &otel-env # SDK -> Collector over mTLS with the service's own identity (OTEL_* variables are read by the SDK itself)
|
||||||
|
OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:4318
|
||||||
|
OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf
|
||||||
|
OTEL_EXPORTER_OTLP_CERTIFICATE: /run/pki/ca.crt
|
||||||
|
OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: /run/pki/tls.crt
|
||||||
|
OTEL_EXPORTER_OTLP_CLIENT_KEY: /run/pki/tls.key
|
||||||
|
OTEL_RESOURCE_ATTRIBUTES: deployment.environment.name=lab
|
||||||
|
SERVICE_VERSION: "1.7.0"
|
||||||
|
|
||||||
|
x-pg-env: &pg-env # libpq reads these: TLS verify-full against our CA; password is injected from OpenBao at start
|
||||||
|
PGHOST: postgres
|
||||||
|
PGPORT: "5432"
|
||||||
|
PGDATABASE: ${POSTGRES_DB:-messenger}
|
||||||
|
PGSSLMODE: verify-full
|
||||||
|
PGSSLROOTCERT: /run/pki/ca.crt
|
||||||
|
|
||||||
|
x-app-env: &app-env
|
||||||
|
TLS_CA_FILE: /run/pki/ca.crt
|
||||||
|
TLS_CERT_FILE: /run/pki/tls.crt
|
||||||
|
TLS_KEY_FILE: /run/pki/tls.key
|
||||||
|
BAO_ADDR: ${BAO_ADDR:-https://openbao:8200}
|
||||||
|
BAO_CACERT: /run/pki/ca.crt
|
||||||
|
S3_ENDPOINT: https://s3:9000
|
||||||
|
S3_REGION: ${S3_REGION:-us-east-1}
|
||||||
|
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
|
||||||
|
|
||||||
|
services:
|
||||||
|
init_perms: # one-shot: named volumes are root-owned on first use; give them to the unprivileged uid
|
||||||
|
image: alpine:3.20.3
|
||||||
|
user: "0:0"
|
||||||
|
command: ["sh", "-c", "chown -R 10001:10001 /v/redis /v/s3 /v/kafka /v/prom /v/loki /v/tempo /v/grafana /v/bao"]
|
||||||
|
volumes: [redis_data:/v/redis, s3_data:/v/s3, kafka_data:/v/kafka, prometheus_data:/v/prom, loki_data:/v/loki, tempo_data:/v/tempo, grafana_data:/v/grafana, bao_data:/v/bao]
|
||||||
|
security_opt: ["no-new-privileges:true"]
|
||||||
|
cap_drop: ["ALL"]
|
||||||
|
cap_add: ["CHOWN", "DAC_OVERRIDE", "FOWNER"]
|
||||||
|
network_mode: none
|
||||||
|
restart: "no"
|
||||||
|
|
||||||
|
openbao:
|
||||||
|
<<: *hardened
|
||||||
|
image: openbao/openbao:2.4.1
|
||||||
|
user: "10001:10001"
|
||||||
|
command: ["bao", "server", "-config=/openbao/config/openbao.hcl"] # NOT -dev: sealed at start, persistent file storage
|
||||||
|
volumes:
|
||||||
|
- ./infra/openbao/openbao.hcl:/openbao/config/openbao.hcl:ro
|
||||||
|
- ./secrets/pki/openbao:/run/pki:ro
|
||||||
|
- bao_data:/openbao/data
|
||||||
|
networks: [backend] # no published port: the operator uses `docker compose exec`
|
||||||
|
depends_on: {init_perms: {condition: service_completed_successfully}}
|
||||||
|
healthcheck: # healthy = process up and TLS works (sealed is fine: exit code 2)
|
||||||
|
test: ["CMD-SHELL", "bao status -address=https://127.0.0.1:8200 -ca-cert=/run/pki/ca.crt >/dev/null 2>&1; [ $$? -ne 1 ]"]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 20
|
||||||
|
cpus: 0.5
|
||||||
|
mem_limit: 256m
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
postgres: # exception: starts as root to chown the key, then drops to postgres; minimal capabilities; writable data volume
|
||||||
|
image: postgres:17.6-alpine
|
||||||
|
entrypoint: ["/bin/sh", "/entrypoint.sh"]
|
||||||
|
environment:
|
||||||
|
POSTGRES_DB: ${POSTGRES_DB:-messenger}
|
||||||
|
POSTGRES_USER: ${POSTGRES_USER:-messenger}
|
||||||
|
POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password
|
||||||
|
volumes:
|
||||||
|
- postgres_data:/var/lib/postgresql/data
|
||||||
|
- ./infra/postgres/entrypoint.sh:/entrypoint.sh:ro
|
||||||
|
- ./infra/postgres/pg_hba.conf:/etc/postgresql/pg_hba.conf:ro
|
||||||
|
- ./secrets/pki/postgres:/pki:ro
|
||||||
|
- ./secrets/ops/postgres_password:/run/secrets/postgres_password:ro
|
||||||
|
tmpfs: ["/tls:mode=0700", "/run/postgresql", "/tmp"]
|
||||||
|
security_opt: ["no-new-privileges:true"]
|
||||||
|
cap_drop: ["ALL"]
|
||||||
|
cap_add: ["CHOWN", "SETUID", "SETGID", "DAC_OVERRIDE", "FOWNER"]
|
||||||
|
networks: [backend]
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 20
|
||||||
|
cpus: 1.0
|
||||||
|
mem_limit: 768m
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
redis:
|
||||||
|
<<: *hardened
|
||||||
|
image: redis:7.4.2-alpine
|
||||||
|
user: "10001:10001"
|
||||||
|
command: ["redis-server", "/etc/redis/redis.conf"]
|
||||||
|
read_only: true
|
||||||
|
tmpfs: ["/tmp"]
|
||||||
|
volumes:
|
||||||
|
- redis_data:/data
|
||||||
|
- ./infra/redis/redis.conf:/etc/redis/redis.conf:ro
|
||||||
|
- ./secrets/ops/redis_users.acl:/acl/users.acl:ro
|
||||||
|
- ./secrets/pki/redis:/pki:ro
|
||||||
|
- ./secrets/ops/redis_health_password:/run/secrets/redis_health_password:ro
|
||||||
|
networks: [backend]
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "REDISCLI_AUTH=\"$$(cat /run/secrets/redis_health_password)\" redis-cli --tls --cacert /pki/ca.crt --user health ping | grep -q PONG"]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 20
|
||||||
|
cpus: 0.25
|
||||||
|
mem_limit: 256m
|
||||||
|
depends_on: {init_perms: {condition: service_completed_successfully}}
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
s3: # exception: stateful store with a writable data volume (rootfs not read-only)
|
||||||
|
<<: *hardened
|
||||||
|
image: pgsty/silo:RELEASE.2026-10-15T00-00-00Z
|
||||||
|
user: "10001:10001"
|
||||||
|
command: ["server", "/data", "--address", ":9000", "--certs-dir", "/certs"]
|
||||||
|
environment:
|
||||||
|
MINIO_ROOT_USER_FILE: /run/secrets/s3_root_user
|
||||||
|
MINIO_ROOT_PASSWORD_FILE: /run/secrets/s3_root_password
|
||||||
|
MINIO_BROWSER: "off"
|
||||||
|
volumes:
|
||||||
|
- s3_data:/data
|
||||||
|
- ./secrets/pki/s3/tls.crt:/certs/public.crt:ro
|
||||||
|
- ./secrets/pki/s3/tls.key:/certs/private.key:ro
|
||||||
|
- ./secrets/pki/s3/ca.crt:/certs/CAs/ca.crt:ro
|
||||||
|
- ./secrets/ops/s3_root_user:/run/secrets/s3_root_user:ro
|
||||||
|
- ./secrets/ops/s3_root_password:/run/secrets/s3_root_password:ro
|
||||||
|
networks: [backend]
|
||||||
|
depends_on: {init_perms: {condition: service_completed_successfully}}
|
||||||
|
cpus: 1.0
|
||||||
|
mem_limit: 512m
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
s3_init:
|
||||||
|
<<: *hardened
|
||||||
|
image: pgsty/silo:RELEASE.2026-10-15T00-00-00Z
|
||||||
|
user: "10001:10001"
|
||||||
|
entrypoint: ["/bin/sh", "/infra/s3-init.sh"]
|
||||||
|
environment:
|
||||||
|
S3_ENDPOINT: https://s3:9000
|
||||||
|
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
|
||||||
|
SSL_CERT_FILE: /pki/ca.crt # mc trusts only our CA
|
||||||
|
HOME: /tmp
|
||||||
|
tmpfs: ["/tmp"]
|
||||||
|
volumes:
|
||||||
|
- ./infra/s3-init.sh:/infra/s3-init.sh:ro
|
||||||
|
- ./secrets/pki/ca/ca.crt:/pki/ca.crt:ro
|
||||||
|
- ./secrets/ops/s3_root_user:/run/secrets/s3_root_user:ro
|
||||||
|
- ./secrets/ops/s3_root_password:/run/secrets/s3_root_password:ro
|
||||||
|
- ./secrets/ops/s3_api_secret:/run/secrets/s3_api_secret:ro
|
||||||
|
- ./secrets/ops/s3_worker_secret:/run/secrets/s3_worker_secret:ro
|
||||||
|
- ./secrets/ops/s3_sweeper_secret:/run/secrets/s3_sweeper_secret:ro
|
||||||
|
networks: [backend]
|
||||||
|
depends_on: {s3: {condition: service_started}}
|
||||||
|
restart: "no"
|
||||||
|
|
||||||
|
kafka: # exception: stateful broker (writable log dir and generated config)
|
||||||
|
security_opt: ["no-new-privileges:true"]
|
||||||
|
cap_drop: ["ALL"]
|
||||||
|
image: apache/kafka:3.9.0
|
||||||
|
user: "10001:10001"
|
||||||
|
environment:
|
||||||
|
KAFKA_NODE_ID: "1"
|
||||||
|
KAFKA_PROCESS_ROLES: broker,controller
|
||||||
|
KAFKA_LISTENERS: INTERNAL://:9092,CONTROLLER://:9093
|
||||||
|
KAFKA_ADVERTISED_LISTENERS: INTERNAL://kafka:9092
|
||||||
|
KAFKA_CONTROLLER_LISTENER_NAMES: CONTROLLER
|
||||||
|
KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: CONTROLLER:SSL,INTERNAL:SSL
|
||||||
|
KAFKA_CONTROLLER_QUORUM_VOTERS: 1@kafka:9093
|
||||||
|
KAFKA_INTER_BROKER_LISTENER_NAME: INTERNAL
|
||||||
|
KAFKA_SSL_KEYSTORE_TYPE: PEM
|
||||||
|
KAFKA_SSL_KEYSTORE_LOCATION: /pki/keystore.pem
|
||||||
|
KAFKA_SSL_TRUSTSTORE_TYPE: PEM
|
||||||
|
KAFKA_SSL_TRUSTSTORE_LOCATION: /pki/ca.crt
|
||||||
|
|
||||||
|
KAFKA_SSL_CLIENT_AUTH: required # mTLS on every listener
|
||||||
|
KAFKA_SSL_PRINCIPAL_MAPPING_RULES: "RULE:^CN=([^,]+).*$$/$$1/,DEFAULT"
|
||||||
|
KAFKA_AUTHORIZER_CLASS_NAME: org.apache.kafka.metadata.authorizer.StandardAuthorizer
|
||||||
|
KAFKA_SUPER_USERS: User:kafka;User:kafka-admin
|
||||||
|
KAFKA_ALLOW_EVERYONE_IF_NO_ACL_FOUND: "false"
|
||||||
|
KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: "1"
|
||||||
|
KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: "1"
|
||||||
|
KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: "1"
|
||||||
|
KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: "0"
|
||||||
|
KAFKA_AUTO_CREATE_TOPICS_ENABLE: "false"
|
||||||
|
KAFKA_LOG_DIRS: /var/lib/kafka/data
|
||||||
|
KAFKA_HEAP_OPTS: "-Xms256m -Xmx512m"
|
||||||
|
tmpfs: ["/opt/kafka/config:uid=10001,gid=10001", "/opt/kafka/logs:uid=10001,gid=10001"]
|
||||||
|
volumes:
|
||||||
|
- kafka_data:/var/lib/kafka/data
|
||||||
|
- ./secrets/pki/kafka:/pki:ro
|
||||||
|
- ./infra/kafka/client.properties:/client.properties:ro
|
||||||
|
networks: [backend]
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "KAFKA_HEAP_OPTS='-Xmx128m' /opt/kafka/bin/kafka-broker-api-versions.sh --bootstrap-server kafka:9092 --command-config /client.properties >/dev/null 2>&1"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 25s
|
||||||
|
retries: 40
|
||||||
|
start_period: 45s
|
||||||
|
cpus: 2.0
|
||||||
|
mem_limit: 2g
|
||||||
|
depends_on: {init_perms: {condition: service_completed_successfully}}
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
kafka_init:
|
||||||
|
<<: *hardened
|
||||||
|
image: apache/kafka:3.9.0
|
||||||
|
user: "10001:10001"
|
||||||
|
entrypoint: ["/bin/sh", "/init.sh"]
|
||||||
|
environment: {JOBS_TOPIC: "${JOBS_TOPIC:-attachment-jobs}"}
|
||||||
|
tmpfs: ["/opt/kafka/logs:uid=10001,gid=10001"]
|
||||||
|
volumes:
|
||||||
|
- ./infra/kafka/init.sh:/init.sh:ro
|
||||||
|
- ./infra/kafka/client.properties:/client.properties:ro
|
||||||
|
- ./secrets/pki/kafka-admin:/pki:ro
|
||||||
|
networks: [backend]
|
||||||
|
depends_on: {kafka: {condition: service_healthy}}
|
||||||
|
restart: "no"
|
||||||
|
|
||||||
|
migrate: # one-shot owner job: schema + least-privilege roles; the only container that knows the DB owner password
|
||||||
|
<<: *hardened
|
||||||
|
build: .
|
||||||
|
image: mtusi-lab7-app:1.0.0
|
||||||
|
user: "10001:10001"
|
||||||
|
command: ["sh", "-c", "PGPASSWORD=\"$$(cat /run/secrets/postgres_password)\" python scripts/migrate.py && PGPASSWORD=\"$$(cat /run/secrets/postgres_password)\" python scripts/db_roles.py $${DB_ROLES_ARGS}"]
|
||||||
|
environment:
|
||||||
|
<<: *pg-env
|
||||||
|
PGUSER: ${POSTGRES_USER:-messenger}
|
||||||
|
PGSSLROOTCERT: /pki/ca.crt
|
||||||
|
OPS_SECRETS_DIR: /run/secrets
|
||||||
|
DB_ROLES_ARGS: ${DB_ROLES_ARGS:-}
|
||||||
|
read_only: true
|
||||||
|
tmpfs: ["/tmp"]
|
||||||
|
volumes:
|
||||||
|
- ./secrets/pki/ca/ca.crt:/pki/ca.crt:ro
|
||||||
|
- ./secrets/ops/postgres_password:/run/secrets/postgres_password:ro
|
||||||
|
- ./secrets/ops/db_api_password:/run/secrets/db_api_password:ro
|
||||||
|
- ./secrets/ops/db_worker_password:/run/secrets/db_worker_password:ro
|
||||||
|
- ./secrets/ops/db_dispatcher_password:/run/secrets/db_dispatcher_password:ro
|
||||||
|
- ./secrets/ops/db_sweeper_password:/run/secrets/db_sweeper_password:ro
|
||||||
|
networks: [backend]
|
||||||
|
depends_on: {postgres: {condition: service_healthy}}
|
||||||
|
restart: "no"
|
||||||
|
cpus: 0.5
|
||||||
|
mem_limit: 384m
|
||||||
|
|
||||||
|
api:
|
||||||
|
<<: *hardened
|
||||||
|
build: .
|
||||||
|
image: mtusi-lab7-app:1.0.0
|
||||||
|
user: "10001:10001"
|
||||||
|
environment:
|
||||||
|
<<: [*pg-env, *app-env, *otel-env]
|
||||||
|
PGUSER: messenger_api
|
||||||
|
APP_HOST: 0.0.0.0
|
||||||
|
APP_PORT: "8443"
|
||||||
|
ALLOWED_CLIENT_SANS: ${ALLOWED_CLIENT_SANS:-lb}
|
||||||
|
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||||
|
DB_POOL_MIN_SIZE: ${DB_POOL_MIN_SIZE:-1}
|
||||||
|
DB_POOL_MAX_SIZE: ${DB_POOL_MAX_SIZE:-10}
|
||||||
|
DB_POOL_TIMEOUT_SECONDS: ${DB_POOL_TIMEOUT_SECONDS:-5}
|
||||||
|
MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-10485760}
|
||||||
|
MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000}
|
||||||
|
IMAGE_DECODE_CONCURRENCY: ${IMAGE_DECODE_CONCURRENCY:-1}
|
||||||
|
JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5}
|
||||||
|
ARGON2_MEMORY_KIB: ${ARGON2_MEMORY_KIB:-19456}
|
||||||
|
ARGON2_ITERATIONS: ${ARGON2_ITERATIONS:-2}
|
||||||
|
ARGON2_PARALLELISM: ${ARGON2_PARALLELISM:-1}
|
||||||
|
ARGON2_CONCURRENCY: ${ARGON2_CONCURRENCY:-2}
|
||||||
|
LOGIN_IP_LIMIT: ${LOGIN_IP_LIMIT:-30}
|
||||||
|
LOGIN_USER_FAIL_LIMIT: ${LOGIN_USER_FAIL_LIMIT:-10}
|
||||||
|
RATE_WINDOW_SECONDS: ${RATE_WINDOW_SECONDS:-60}
|
||||||
|
deploy: {replicas: 2}
|
||||||
|
expose: ["8443"] # reachable only inside the backend network, and only with the LB client identity
|
||||||
|
read_only: true
|
||||||
|
tmpfs: ["/tmp:size=128m,mode=1777"]
|
||||||
|
volumes:
|
||||||
|
- ./secrets/pki/api:/run/pki:ro
|
||||||
|
- ./secrets/approle/api:/run/approle:ro
|
||||||
|
networks: [backend]
|
||||||
|
depends_on:
|
||||||
|
migrate: {condition: service_completed_successfully}
|
||||||
|
redis: {condition: service_healthy}
|
||||||
|
openbao: {condition: service_healthy}
|
||||||
|
s3_init: {condition: service_completed_successfully}
|
||||||
|
healthcheck: # TCP only: an HTTPS probe would be (correctly) refused by the identity allowlist
|
||||||
|
test: ["CMD", "python", "-c", "import socket; socket.create_connection(('127.0.0.1', 8443), 2)"]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 10
|
||||||
|
start_period: 40s
|
||||||
|
stop_grace_period: 15s
|
||||||
|
cpus: 1.0
|
||||||
|
mem_limit: 512m
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
worker:
|
||||||
|
<<: *hardened
|
||||||
|
build: .
|
||||||
|
image: mtusi-lab7-app:1.0.0
|
||||||
|
user: "10001:10001"
|
||||||
|
command: ["python", "-m", "src.worker"]
|
||||||
|
environment:
|
||||||
|
<<: [*pg-env, *app-env, *otel-env]
|
||||||
|
PGUSER: messenger_worker
|
||||||
|
KAFKA_BOOTSTRAP_SERVERS: kafka:9092
|
||||||
|
JOBS_TOPIC: ${JOBS_TOPIC:-attachment-jobs}
|
||||||
|
JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5}
|
||||||
|
JOB_TIMEOUT_SECONDS: ${JOB_TIMEOUT_SECONDS:-60}
|
||||||
|
LEASE_GRACE_SECONDS: ${LEASE_GRACE_SECONDS:-15}
|
||||||
|
JOB_BACKOFF_BASE_SECONDS: ${JOB_BACKOFF_BASE_SECONDS:-2}
|
||||||
|
JOB_BACKOFF_CAP_SECONDS: ${JOB_BACKOFF_CAP_SECONDS:-60}
|
||||||
|
WORKER_CONCURRENCY: ${WORKER_CONCURRENCY:-2}
|
||||||
|
IMG_MEMORY_MB: ${IMG_MEMORY_MB:-1024}
|
||||||
|
MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000}
|
||||||
|
FAULT_WORKER_EXIT_AFTER_S3: ${FAULT_WORKER_EXIT_AFTER_S3:-0}
|
||||||
|
read_only: true
|
||||||
|
tmpfs: ["/tmp:size=512m,mode=1777"]
|
||||||
|
volumes:
|
||||||
|
- ./secrets/pki/worker:/run/pki:ro
|
||||||
|
- ./secrets/approle/worker:/run/approle:ro
|
||||||
|
networks: [backend]
|
||||||
|
depends_on:
|
||||||
|
migrate: {condition: service_completed_successfully}
|
||||||
|
kafka_init: {condition: service_completed_successfully}
|
||||||
|
s3_init: {condition: service_completed_successfully}
|
||||||
|
openbao: {condition: service_healthy}
|
||||||
|
stop_grace_period: 30s
|
||||||
|
cpus: 1.0 # upload-worker budget: CPU, RAM (also RLIMIT_AS in the child) and JOB_TIMEOUT_SECONDS
|
||||||
|
mem_limit: 1g
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
dispatcher:
|
||||||
|
<<: *hardened
|
||||||
|
build: .
|
||||||
|
image: mtusi-lab7-app:1.0.0
|
||||||
|
user: "10001:10001"
|
||||||
|
command: ["python", "-m", "src.dispatcher"]
|
||||||
|
environment:
|
||||||
|
<<: [*pg-env, *app-env, *otel-env]
|
||||||
|
PGUSER: messenger_dispatcher
|
||||||
|
KAFKA_BOOTSTRAP_SERVERS: kafka:9092
|
||||||
|
JOBS_TOPIC: ${JOBS_TOPIC:-attachment-jobs}
|
||||||
|
JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5}
|
||||||
|
JOB_TIMEOUT_SECONDS: ${JOB_TIMEOUT_SECONDS:-60}
|
||||||
|
LEASE_GRACE_SECONDS: ${LEASE_GRACE_SECONDS:-15}
|
||||||
|
JOB_BACKOFF_BASE_SECONDS: ${JOB_BACKOFF_BASE_SECONDS:-2}
|
||||||
|
JOB_BACKOFF_CAP_SECONDS: ${JOB_BACKOFF_CAP_SECONDS:-60}
|
||||||
|
FAULT_DISPATCHER_EXIT_BEFORE_PUBLISH: ${FAULT_DISPATCHER_EXIT_BEFORE_PUBLISH:-0}
|
||||||
|
read_only: true
|
||||||
|
tmpfs: ["/tmp"]
|
||||||
|
volumes:
|
||||||
|
- ./secrets/pki/dispatcher:/run/pki:ro
|
||||||
|
- ./secrets/approle/dispatcher:/run/approle:ro
|
||||||
|
networks: [backend]
|
||||||
|
depends_on:
|
||||||
|
migrate: {condition: service_completed_successfully}
|
||||||
|
kafka_init: {condition: service_completed_successfully}
|
||||||
|
openbao: {condition: service_healthy}
|
||||||
|
cpus: 0.25
|
||||||
|
mem_limit: 192m
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
s3_sweeper:
|
||||||
|
<<: *hardened
|
||||||
|
build: .
|
||||||
|
image: mtusi-lab7-app:1.0.0
|
||||||
|
user: "10001:10001"
|
||||||
|
command: ["python", "scripts/s3_sweep.py", "--loop", "--apply"]
|
||||||
|
environment:
|
||||||
|
<<: [*pg-env, *app-env]
|
||||||
|
PGUSER: messenger_sweeper
|
||||||
|
SWEEP_GRACE_SECONDS: ${SWEEP_GRACE_SECONDS:-3600}
|
||||||
|
SWEEP_INTERVAL_SECONDS: ${SWEEP_INTERVAL_SECONDS:-600}
|
||||||
|
STAGING_RETENTION_SECONDS: ${STAGING_RETENTION_SECONDS:-86400}
|
||||||
|
read_only: true
|
||||||
|
tmpfs: ["/tmp"]
|
||||||
|
volumes:
|
||||||
|
- ./secrets/pki/sweeper:/run/pki:ro
|
||||||
|
- ./secrets/approle/sweeper:/run/approle:ro
|
||||||
|
networks: [backend]
|
||||||
|
depends_on:
|
||||||
|
migrate: {condition: service_completed_successfully}
|
||||||
|
s3_init: {condition: service_completed_successfully}
|
||||||
|
openbao: {condition: service_healthy}
|
||||||
|
cpus: 0.25
|
||||||
|
mem_limit: 128m
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
otel-collector:
|
||||||
|
<<: *hardened
|
||||||
|
image: otel/opentelemetry-collector-contrib:0.131.0
|
||||||
|
user: "10001:10001"
|
||||||
|
command: ["--config=/etc/otelcol/collector.yaml"]
|
||||||
|
read_only: true
|
||||||
|
volumes:
|
||||||
|
- ./infra/otel/collector.yaml:/etc/otelcol/collector.yaml:ro
|
||||||
|
- ./secrets/pki/otel-collector:/pki:ro
|
||||||
|
- ./secrets/pki/ca/workload-ca.crt:/ca/workload-ca.crt:ro
|
||||||
|
networks: [backend]
|
||||||
|
cpus: 0.5
|
||||||
|
mem_limit: 256m
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
prometheus: # exception: writable TSDB volume
|
||||||
|
<<: *hardened
|
||||||
|
image: prom/prometheus:v3.5.0
|
||||||
|
user: "10001:10001"
|
||||||
|
command:
|
||||||
|
- --config.file=/etc/prometheus/prometheus.yml
|
||||||
|
- --web.config.file=/etc/prometheus/web.yml
|
||||||
|
- --storage.tsdb.path=/prometheus
|
||||||
|
- --storage.tsdb.retention.time=30d
|
||||||
|
- --web.enable-remote-write-receiver
|
||||||
|
volumes:
|
||||||
|
- ./infra/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml:ro
|
||||||
|
- ./infra/prometheus/web.yml:/etc/prometheus/web.yml:ro
|
||||||
|
- ./infra/prometheus/alerts.yml:/etc/prometheus/alerts.yml:ro
|
||||||
|
- ./secrets/pki/prometheus:/pki:ro
|
||||||
|
- prometheus_data:/prometheus
|
||||||
|
networks: [backend]
|
||||||
|
depends_on: {init_perms: {condition: service_completed_successfully}}
|
||||||
|
cpus: 0.5
|
||||||
|
mem_limit: 512m
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
loki: # exception: writable chunk store
|
||||||
|
<<: *hardened
|
||||||
|
image: grafana/loki:3.5.3
|
||||||
|
user: "10001:10001"
|
||||||
|
command: ["-config.file=/etc/loki/loki.yaml"]
|
||||||
|
volumes:
|
||||||
|
- ./infra/loki/loki.yaml:/etc/loki/loki.yaml:ro
|
||||||
|
- ./secrets/pki/loki:/pki:ro
|
||||||
|
- loki_data:/loki
|
||||||
|
networks: [backend]
|
||||||
|
depends_on: {init_perms: {condition: service_completed_successfully}}
|
||||||
|
cpus: 0.5
|
||||||
|
mem_limit: 512m
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
tempo: # exception: writable WAL/blocks; no longer runs as root (lab 6 used user 0)
|
||||||
|
<<: *hardened
|
||||||
|
image: grafana/tempo:2.8.2
|
||||||
|
user: "10001:10001"
|
||||||
|
command: ["-config.file=/etc/tempo/tempo.yaml"]
|
||||||
|
volumes:
|
||||||
|
- ./infra/tempo/tempo.yaml:/etc/tempo/tempo.yaml:ro
|
||||||
|
- ./secrets/pki/tempo:/pki:ro
|
||||||
|
- tempo_data:/var/tempo
|
||||||
|
networks: [backend]
|
||||||
|
depends_on: {init_perms: {condition: service_completed_successfully}}
|
||||||
|
cpus: 0.5
|
||||||
|
mem_limit: 512m
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
grafana: # exception: writable state volume; HTTPS, loopback-only port
|
||||||
|
<<: *hardened
|
||||||
|
image: grafana/grafana:12.1.1
|
||||||
|
user: "10001:10001"
|
||||||
|
environment:
|
||||||
|
GF_SECURITY_ADMIN_USER: ${GRAFANA_ADMIN_USER:-admin}
|
||||||
|
GF_SECURITY_ADMIN_PASSWORD__FILE: /run/secrets/grafana_admin_password
|
||||||
|
GF_SERVER_PROTOCOL: https
|
||||||
|
GF_SERVER_CERT_FILE: /pki/tls.crt
|
||||||
|
GF_SERVER_CERT_KEY: /pki/tls.key
|
||||||
|
GF_USERS_ALLOW_SIGN_UP: "false"
|
||||||
|
GF_ANALYTICS_REPORTING_ENABLED: "false"
|
||||||
|
GF_ANALYTICS_CHECK_FOR_UPDATES: "false"
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:${GRAFANA_PORT:-3000}:3000"
|
||||||
|
volumes:
|
||||||
|
- ./infra/grafana/provisioning:/etc/grafana/provisioning:ro
|
||||||
|
- ./infra/grafana/dashboards:/var/lib/grafana/dashboards:ro
|
||||||
|
- ./secrets/pki/grafana:/pki:ro
|
||||||
|
- ./secrets/ops/grafana_admin_password:/run/secrets/grafana_admin_password:ro
|
||||||
|
- grafana_data:/var/lib/grafana
|
||||||
|
tmpfs: ["/tmp"]
|
||||||
|
networks: [frontend, backend]
|
||||||
|
depends_on: [prometheus, loki, tempo]
|
||||||
|
cpus: 0.5
|
||||||
|
mem_limit: 512m
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
load_balancer:
|
||||||
|
<<: *hardened
|
||||||
|
image: haproxy:3.2.5-alpine
|
||||||
|
user: "10001:10001"
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:${APP_PORT:-8443}:8443"
|
||||||
|
read_only: true
|
||||||
|
tmpfs: ["/tmp"]
|
||||||
|
volumes:
|
||||||
|
- ./infra/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
||||||
|
- ./secrets/pki/lb-public:/pki/lb-public:ro
|
||||||
|
- ./secrets/pki/lb:/pki/lb:ro
|
||||||
|
networks: [frontend, backend]
|
||||||
|
depends_on:
|
||||||
|
api: {condition: service_healthy}
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "haproxy", "-c", "-f", "/usr/local/etc/haproxy/haproxy.cfg"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 3
|
||||||
|
cpus: 0.5
|
||||||
|
mem_limit: 128m
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
networks:
|
||||||
|
frontend: {driver: bridge}
|
||||||
|
backend:
|
||||||
|
driver: bridge
|
||||||
|
internal: true # no route to/from the host or the internet
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
postgres_data:
|
||||||
|
redis_data:
|
||||||
|
s3_data:
|
||||||
|
kafka_data:
|
||||||
|
bao_data:
|
||||||
|
prometheus_data:
|
||||||
|
loki_data:
|
||||||
|
tempo_data:
|
||||||
|
grafana_data:
|
||||||
@@ -0,0 +1,270 @@
|
|||||||
|
thereal_alyoname@DESKTOP-8Q26HPT:/mnt/c/Users/User/Desktop/MTUCI/4_course/highload_apps/lab7/mtusi2026lab7-fork$
|
||||||
|
make check
|
||||||
|
python3 scripts/check_contract.py
|
||||||
|
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||||
|
thereal_alyoname@DESKTOP-8Q26HPT:/mnt/c/Users/User/Desktop/MTUCI/4_course/highload_apps/lab7/mtusi2026lab7-fork$
|
||||||
|
make validate
|
||||||
|
python3 scripts/validate_openapi.py
|
||||||
|
PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.
|
||||||
|
thereal_alyoname@DESKTOP-8Q26HPT:/mnt/c/Users/User/Desktop/MTUCI/4_course/highload_apps/lab7/mtusi2026lab7-fork$
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
thereal_alyoname@DESKTOP-8Q26HPT:/mnt/c/Users/User/Desktop/MTUCI/4_course/highload_apps/lab7/mtusi2026lab7-fork$
|
||||||
|
make up
|
||||||
|
sh scripts/up.sh
|
||||||
|
bootstrap done (PKI, passwords, Redis ACL). Next: scripts/up.sh
|
||||||
|
[+] Running 8/8
|
||||||
|
✔ openbao Pulled 13.8s
|
||||||
|
[+] Running 6/7
|
||||||
|
[+] Running 9/9i-lab7_backend Created 0.2s
|
||||||
|
✔ Network mtusi-lab7_backend Created 0.2s
|
||||||
|
✔ Volume "mtusi-lab7_grafana_data" Created 0.1s
|
||||||
|
[+] Running 9/10-lab7_bao_data" Created 0.0s
|
||||||
|
✔ Network mtusi-lab7_backend Created 0.2s
|
||||||
|
✔ Volume "mtusi-lab7_grafana_data" Created 0.1s
|
||||||
|
✔ Volume "mtusi-lab7_bao_data" Created 0.0s
|
||||||
|
[+] Running 9/10-lab7_redis_data" Created 0.0s
|
||||||
|
✔ Network mtusi-lab7_backend Created 0.2s
|
||||||
|
✔ Volume "mtusi-lab7_grafana_data" Created 0.1s
|
||||||
|
✔ Volume "mtusi-lab7_bao_data"
|
||||||
|
|
||||||
|
|
||||||
|
thereal_alyoname@DESKTOP-8Q26HPT:/mnt/c/Users/User/Desktop/MTUCI/4_course/highload_apps/lab7/mtusi2026lab7-fork$
|
||||||
|
curl --cacert secrets/pki/ca/ca.crt https://localhost:8443/health/ready
|
||||||
|
{"status":"ok"}thereal_alyoname@DESKTOP-8Q26HPT:/mnt/c/Users/User/Desktop/MTUCI/4_course/highload_apps/lab7/mtusi2026lab7-fork$
|
||||||
|
|
||||||
|
|
||||||
|
thereal_alyoname@DESKTOP-8Q26HPT:/mnt/c/Users/User/Desktop/MTUCI/4_course/highload_apps/lab7/mtusi2026lab7-fork$ make test
|
||||||
|
python3 tests/smoke.py --base-url "https://localhost:8443" --ca-file "/mnt/c/Users/User/Desktop/MTUCI/4_course/highload_apps/lab7/mtusi2026lab7-fork/secrets/pki/ca/ca.crt"
|
||||||
|
PASS: lab7 public API scenario; infrastructure and grading evidence remain separate.
|
||||||
|
thereal_alyoname@DESKTOP-8Q26HPT:/mnt/c/Users/User/Desktop/MTUCI/4_course/highload_apps/lab7/mtusi2026lab7-fork$
|
||||||
|
|
||||||
|
|
||||||
|
thereal_alyoname@DESKTOP-8Q26HPT:/mnt/c/Users/User/Desktop/MTUCI/4_course/highload_apps/lab7/mtusi2026lab7-fork$
|
||||||
|
make test-security
|
||||||
|
python3 tests/security.py --base-url "https://localhost:8443" --ca-file "/mnt/c/Users/User/Desktop/MTUCI/4_course/highload_apps/lab7/mtusi2026lab7-fork/secrets/pki/ca/ca.crt"
|
||||||
|
PASS: trusted HTTPS works; untrusted CA rejected. This does NOT verify internal mTLS, OpenBao or hardening.
|
||||||
|
thereal_alyoname@DESKTOP-8Q26HPT:/mnt/c/Users/User/Desktop/MTUCI/4_course/highload_apps/lab7/mtusi2026lab7-fork$
|
||||||
|
|
||||||
|
|
||||||
|
thereal_alyoname@DESKTOP-8Q26HPT:/mnt/c/Users/User/Desktop/MTUCI/4_course/highload_apps/lab7/mtusi2026lab7-fork$
|
||||||
|
make test-tls
|
||||||
|
sh security-tests/run_in_net.sh tls_audit.py
|
||||||
|
PASS api: lb identity accepted: HTTP/1.1 200 OK
|
||||||
|
PASS api: no client cert refused: EmptyReply
|
||||||
|
PASS api: foreign-CA cert refused: EmptyReply
|
||||||
|
PASS api: same-CA, wrong identity (outsider) refused: EmptyReply
|
||||||
|
PASS api: worker identity refused: EmptyReply
|
||||||
|
PASS api: client distrusting server CA fails verification: SSLCertVerificationError
|
||||||
|
PASS collector: api identity accepted: HTTP/1.1 404 Not Found
|
||||||
|
PASS collector: worker identity accepted: HTTP/1.1 404 Not Found
|
||||||
|
PASS collector: dispatcher identity accepted: HTTP/1.1 404 Not Found
|
||||||
|
PASS collector: outsider (same root CA, not a workload) refused: SSLError
|
||||||
|
PASS collector: grafana (same root CA, not a workload) refused: SSLError
|
||||||
|
PASS collector: lb (same root CA, not a workload) refused: SSLError
|
||||||
|
PASS collector: no client cert refused: SSLError
|
||||||
|
PASS collector: plaintext refused: TLS_ONLY
|
||||||
|
PASS kafka: dispatcher may produce: OK
|
||||||
|
%0|1795386387.764|FATAL|rdkafka#producer-2| [thrd:main]: Fatal error: Broker: Cluster authorization failed: Failed to acquire idempotence PID from broker ssl://kafka:9092/1: Broker: Cluster authorization failed
|
||||||
|
%4|1795386387.764|TERMINATE|rdkafka#producer-2| [thrd:app]: Producer terminating with 1 message (11 bytes) still in queue or transit: use flush() to wait for outstanding message delivery
|
||||||
|
PASS kafka: worker may NOT produce: KafkaError{FATAL,code=CLUSTER_AUTHORIZATION_FAILED,val=31,str="Failed to acquire idempotence PID from broker ssl://kafka:9092/1: Broker: Cluster authorization failed"}
|
||||||
|
PASS kafka: CA-signed outsider may NOT produce: KafkaError{code=TOPIC_AUTHORIZATION_FAILED,val=29,str="Broker: Topic authorization failed"}
|
||||||
|
PASS kafka: api identity may NOT produce: KafkaError{code=TOPIC_AUTHORIZATION_FAILED,val=29,str="Broker: Topic authorization failed"}
|
||||||
|
PASS kafka: plaintext refused: NoHTTP
|
||||||
|
PASS postgres: foreign CA -> verification error: SSLCertVerificationError
|
||||||
|
PASS redis: foreign CA -> verification error: SSLCertVerificationError
|
||||||
|
PASS s3: foreign CA -> verification error: SSLCertVerificationError
|
||||||
|
PASS openbao: foreign CA -> verification error: SSLCertVerificationError
|
||||||
|
PASS prometheus: foreign CA -> verification error: SSLCertVerificationError
|
||||||
|
PASS loki: foreign CA -> verification error: SSLCertVerificationError
|
||||||
|
PASS tempo: foreign CA -> verification error: SSLCertVerificationError
|
||||||
|
PASS prometheus: no client cert refused (mTLS): SSLError
|
||||||
|
PASS prometheus: client cert accepted: HTTP/1.1 302 Found
|
||||||
|
PASS loki: no client cert refused (mTLS): SSLError
|
||||||
|
PASS loki: client cert accepted: HTTP/1.1 404 Not Found
|
||||||
|
PASS tempo: no client cert refused (mTLS): SSLError
|
||||||
|
PASS tempo: client cert accepted: HTTP/1.1 404 Not Found
|
||||||
|
PASS s3: TLS with verification works: HTTP/1.1 200 OK
|
||||||
|
PASS openbao: TLS with verification works: HTTP/1.1 200 OK
|
||||||
|
PASS redis: plaintext refused: ConnectionResetError
|
||||||
|
PASS s3: plaintext refused: TLS_ONLY
|
||||||
|
PASS openbao: plaintext refused: TLS_ONLY
|
||||||
|
PASS postgres: sslmode=disable refused (pg_hba reject): OperationalError
|
||||||
|
|
||||||
|
38/38 probes as expected
|
||||||
|
thereal_alyoname@DESKTOP-8Q26HPT:/mnt/c/Users/User/Desktop/MTUCI/4_course/highload_apps/lab7/mtusi2026lab7-fork$
|
||||||
|
|
||||||
|
thereal_alyoname@DESKTOP-8Q26HPT:/mnt/c/Users/User/Desktop/MTUCI/4_course/highload_apps/lab7/mtusi2026lab7-fork$
|
||||||
|
make test-acl
|
||||||
|
python3 security-tests/acl_leak.py --ca-file "/mnt/c/Users/User/Desktop/MTUCI/4_course/highload_apps/lab7/mtusi2026lab7-fork/secrets/pki/ca/ca.crt" --grafana-password-file secrets/ops/grafana_admin_password
|
||||||
|
PASS outsider cannot read chat metadata (404)
|
||||||
|
PASS outsider cannot read messages (404)
|
||||||
|
PASS outsider cannot attach a file to a foreign chat (404)
|
||||||
|
PASS forged X-User-Id does not change the Bearer identity (404)
|
||||||
|
PASS X-User-Id alone gives no access (401)
|
||||||
|
PASS logout returns 204 (204)
|
||||||
|
PASS token is dead after logout (401)
|
||||||
|
PASS JSON body over 64 KiB -> 413 (413)
|
||||||
|
PASS canary user registered (201)
|
||||||
|
PASS canary login (201)
|
||||||
|
PASS password and token absent from container logs
|
||||||
|
PASS password and token absent from Loki
|
||||||
|
PASS login: 429 after repeated failures, Retry-After present ([401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 429, 429, 429, 429] retry=59)
|
||||||
|
|
||||||
|
ALL PASS
|
||||||
|
thereal_alyoname@DESKTOP-8Q26HPT:/mnt/c/Users/User/Desktop/MTUCI/4_course/highload_apps/lab7/mtusi2026lab7-fork$
|
||||||
|
|
||||||
|
thereal_alyoname@DESKTOP-8Q26HPT:/mnt/c/Users/User/Desktop/MTUCI/4_course/highload_apps/lab7/mtusi2026lab7-fork$ docker compose run --rm --entrypoint python migrate scripts/argon2_bench.py --runs 20
|
||||||
|
[+] Creating 1/1
|
||||||
|
✔ Container mtusi-lab7-postgres-1 Running 0.0s
|
||||||
|
m=19 MiB t=2 p=1: median 83 ms, p95 94 ms, max logins/s per slot 12.0
|
||||||
|
m=46 MiB t=1 p=1: median 211 ms, p95 400 ms, max logins/s per slot 4.7
|
||||||
|
m=64 MiB t=3 p=4: median 609 ms, p95 811 ms, max logins/s per slot 1.6
|
||||||
|
thereal_alyoname@DESKTOP-8Q26HPT:/mnt/c/Users/User/Desktop/MTUCI/4_course/highload_apps/lab7/mtusi2026lab7-fork$
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
thereal_alyoname@DESKTOP-8Q26HPT:/mnt/c/Users/User/Desktop/MTUCI/4_course/highload_apps/lab7/mtusi2026lab7-fork$
|
||||||
|
make test-persistence
|
||||||
|
python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "https://localhost:8443" --ca-file "/mnt/c/Users/User/Desktop/MTUCI/4_course/highload_apps/lab7/mtusi2026lab7-fork/secrets/pki/ca/ca.crt"
|
||||||
|
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
|
||||||
|
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||||
|
thereal_alyoname@DESKTOP-8Q26HPT:/mnt/c/Users/User/Desktop/MTUCI/4_course/highload_apps/lab7/mtusi2026lab7-fork$
|
||||||
|
|
||||||
|
|
||||||
|
thereal_alyoname@DESKTOP-8Q26HPT:/mnt/c/Users/User/Desktop/MTUCI/4_course/highload_apps/lab7/mtusi2026lab7-fork$
|
||||||
|
make test-failover
|
||||||
|
python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "https://localhost:8443" --ca-file "/mnt/c/Users/User/Desktop/MTUCI/4_course/highload_apps/lab7/mtusi2026lab7-fork/secrets/pki/ca/ca.crt"
|
||||||
|
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
|
||||||
|
{"observed_instances_before": 2, "successful_writes": 100, "failed_attempts": 1, "first_recovery_seconds": 2.785}
|
||||||
|
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||||
|
thereal_alyoname@DESKTOP-8Q26HPT:/mnt/c/Users/User/Desktop/MTUCI/4_course/highload_apps/lab7/mtusi2026lab7-fork$
|
||||||
|
|
||||||
|
|
||||||
|
thereal_alyoname@DESKTOP-8Q26HPT:/mnt/c/Users/User/Desktop/MTUCI/4_course/highload_apps/lab7/mtusi2026lab7-fork$
|
||||||
|
make test-compromise
|
||||||
|
sh security-tests/run_in_net.sh worker_compromise.py --profile after > evidence/worker-compromise-after.json
|
||||||
|
%5|1795386798.420|PARTCNT|rdkafka#producer-2| [thrd:ssl://kafka:9092/1]: Topic attachment-jobs partition count changed from 3 to 0
|
||||||
|
PASS: every probe matches the least-privilege expectation
|
||||||
|
sh security-tests/run_in_net.sh worker_compromise.py --profile before > evidence/worker-compromise-before.json
|
||||||
|
thereal_alyoname@DESKTOP-8Q26HPT:/mnt/c/Users/User/Desktop/MTUCI/4_course/highload_apps/lab7/mtusi2026lab7-fork$
|
||||||
|
|
||||||
|
|
||||||
|
thereal_alyoname@DESKTOP-8Q26HPT:/mnt/c/Users/User/Desktop/MTUCI/4_course/highload_apps/lab7/mtusi2026lab7-fork$
|
||||||
|
make incident
|
||||||
|
docker compose stop worker
|
||||||
|
[+] Stopping 0/1
|
||||||
|
[+] Stopping 0/1si-lab7-worker-1 Stopping 0.1s
|
||||||
|
[+] Stopping 0/1si-lab7-worker-1 Stopping 0.2s
|
||||||
|
[+] Stopping 0/1si-lab7-worker-1 Stopping 0.3s
|
||||||
|
[+] Stopping 0/1si-lab7-worker-1 Stopping 0.4s
|
||||||
|
[+] Stopping 0/1si-lab7-worker-1 Stopping 0.5s
|
||||||
|
[+] Stopping 0/1si-lab7-worker-1 Stopping 0.6s
|
||||||
|
[+] Stopping 0/1si-lab7-worker-1 Stopping 0.7s
|
||||||
|
[+] Stopping 0/1si-lab7-worker-1 Stopping 0.8s
|
||||||
|
[+] Stopping 0/1si-lab7-worker-1 Stopping 0.9s
|
||||||
|
[+] Stopping 1/1si-lab7-worker-1 Stopping 1.0s
|
||||||
|
✔ Container mtusi-lab7-worker-1 Stopped 1.1s
|
||||||
|
python3 security-tests/jobs_integrity.py submit --n 10 --ca-file "/mnt/c/Users/User/Desktop/MTUCI/4_course/highload_apps/lab7/mtusi2026lab7-fork/secrets/pki/ca/ca.crt"
|
||||||
|
submitted 10 jobs; they stay queued while the worker is stopped
|
||||||
|
sh scripts/incident_worker.sh
|
||||||
|
[+] Stopping 1/1
|
||||||
|
✔ Container mtusi-lab7-worker-1 Stopped 0.0s
|
||||||
|
identity worker revoked (SecretIDs destroyed, login tokens revoked)
|
||||||
|
[+] Creating 1/1
|
||||||
|
✔ Container mtusi-lab7-postgres-1 Running0.0s
|
||||||
|
[+] Restarting 1/1
|
||||||
|
✔ Container mtusi-lab7-worker-1 Started0.5s 4s
|
||||||
|
rotated db-worker; old value is dead in the store, new value lives in OpenBao only; worker restarted
|
||||||
|
[+] Creating 2/2
|
||||||
|
✔ Container mtusi-lab7-init_perms-1 Created0.0s
|
||||||
|
✔ Container mtusi-lab7-s3-1 Running0.0s
|
||||||
|
[+] Running 1/1
|
||||||
|
✔ Container mtusi-lab7-init_perms-1 Exited1.4s
|
||||||
|
[+] Restarting 1/1
|
||||||
|
✔ Container mtusi-lab7-worker-1 Started30.8s 7s
|
||||||
|
rotated s3-worker; old value is dead in the store, new value lives in OpenBao only; worker restarted
|
||||||
|
issued worker (workload CA, 14 d)
|
||||||
|
secret_id issued for worker
|
||||||
|
[+] Running 1/1
|
||||||
|
✔ Container mtusi-lab7-worker-1 Running 0.0s
|
||||||
|
PASS OpenBao: login with OLD SecretID: rejected (expected rejected)
|
||||||
|
PASS PostgreSQL: new connection with OLD role password: rejected (expected rejected)
|
||||||
|
PASS S3: new request with OLD svc-worker secret: rejected (expected rejected)
|
||||||
|
PASS OpenBao: login with NEW SecretID: accepted (expected accepted)
|
||||||
|
PASS PostgreSQL: new connection with NEW role password: accepted (expected accepted)
|
||||||
|
PASS S3: new request with NEW svc-worker secret: accepted (expected accepted)
|
||||||
|
|
||||||
|
6/6 probes as expected
|
||||||
|
worker recovered; old credentials are dead on new connections (evidence/revoked-creds.txt)
|
||||||
|
also run: security-tests/run_in_net.sh worker_compromise.py --profile after
|
||||||
|
cd "$PWD" && python3 security-tests/jobs_integrity.py verify --ca-file "/mnt/c/Users/User/Desktop/MTUCI/4_course/highload_apps/lab7/mtusi2026lab7-fork/secrets/pki/ca/ca.crt"
|
||||||
|
10/10 attachments ready; lost=0
|
||||||
|
thereal_alyoname@DESKTOP-8Q26HPT:/mnt/c/Users/User/Desktop/MTUCI/4_course/highload_apps/lab7/mtusi2026lab7-fork$
|
||||||
|
|
||||||
|
|
||||||
|
thereal_alyoname@DESKTOP-8Q26HPT:/mnt/c/Users/User/Desktop/MTUCI/4_course/highload_apps/lab7/mtusi2026lab7-fork$
|
||||||
|
for c in $(docker compose ps -q); do docker inspect --format '{{.Name}} priv={{.HostConfig.Privileged}} net={{.HostConfig.NetworkMode}} ro={{.HostConfig.ReadonlyRootfs}} user={{.Config.User}} capdrop={{.HostConfig.CapDrop}} secopt={{.HostConfig.SecurityOpt}}' $c; done
|
||||||
|
/mtusi-lab7-api-1 priv=false net=mtusi-lab7_backend ro=true user=10001:10001 capdrop=[ALL] secopt=[no-new-privileges:true]
|
||||||
|
/mtusi-lab7-api-2 priv=false net=mtusi-lab7_backend ro=true user=10001:10001 capdrop=[ALL] secopt=[no-new-privileges:true]
|
||||||
|
/mtusi-lab7-dispatcher-1 priv=false net=mtusi-lab7_backend ro=true user=10001:10001 capdrop=[ALL] secopt=[no-new-privileges:true]
|
||||||
|
/mtusi-lab7-grafana-1 priv=false net=mtusi-lab7_backend ro=false user=10001:10001 capdrop=[ALL] secopt=[no-new-privileges:true]
|
||||||
|
/mtusi-lab7-kafka-1 priv=false net=mtusi-lab7_backend ro=false user=10001:10001 capdrop=[ALL] secopt=[no-new-privileges:true]
|
||||||
|
/mtusi-lab7-load_balancer-1 priv=false net=mtusi-lab7_backend ro=true user=10001:10001 capdrop=[ALL] secopt=[no-new-privileges:true]
|
||||||
|
/mtusi-lab7-loki-1 priv=false net=mtusi-lab7_backend ro=false user=10001:10001 capdrop=[ALL] secopt=[no-new-privileges:true]
|
||||||
|
/mtusi-lab7-openbao-1 priv=false net=mtusi-lab7_backend ro=false user=10001:10001 capdrop=[ALL] secopt=[no-new-privileges:true]
|
||||||
|
/mtusi-lab7-otel-collector-1 priv=false net=mtusi-lab7_backend ro=true user=10001:10001 capdrop=[ALL] secopt=[no-new-privileges:true]
|
||||||
|
/mtusi-lab7-postgres-1 priv=false net=mtusi-lab7_backend ro=false user= capdrop=[ALL] secopt=[no-new-privileges:true]
|
||||||
|
/mtusi-lab7-prometheus-1 priv=false net=mtusi-lab7_backend ro=false user=10001:10001 capdrop=[ALL] secopt=[no-new-privileges:true]
|
||||||
|
/mtusi-lab7-redis-1 priv=false net=mtusi-lab7_backend ro=true user=10001:10001 capdrop=[ALL] secopt=[no-new-privileges:true]
|
||||||
|
/mtusi-lab7-s3-1 priv=false net=mtusi-lab7_backend ro=false user=10001:10001 capdrop=[ALL] secopt=[no-new-privileges:true]
|
||||||
|
/mtusi-lab7-s3_sweeper-1 priv=false net=mtusi-lab7_backend ro=true user=10001:10001 capdrop=[ALL] secopt=[no-new-privileges:true]
|
||||||
|
/mtusi-lab7-tempo-1 priv=false net=mtusi-lab7_backend ro=false user=10001:10001 capdrop=[ALL] secopt=[no-new-privileges:true]
|
||||||
|
/mtusi-lab7-worker-1 priv=false net=mtusi-lab7_backend ro=true user=10001:10001 capdrop=[ALL] secopt=[no-new-privileges:true]
|
||||||
|
thereal_alyoname@DESKTOP-8Q26HPT:/mnt/c/Users/User/Desktop/MTUCI/4_course/highload_apps/lab7/mtusi2026lab7-fork$
|
||||||
|
docker compose restart openbao
|
||||||
|
sleep 15
|
||||||
|
docker compose restart worker
|
||||||
|
sleep 20
|
||||||
|
docker compose logs worker --tail 8
|
||||||
|
curl --cacert secrets/pki/ca/ca.crt https://localhost:8443/health/ready
|
||||||
|
sh scripts/bao_unseal.sh
|
||||||
|
sh scripts/bao_secret_id.sh all
|
||||||
|
docker compose restart worker
|
||||||
|
sleep 30
|
||||||
|
docker compose ps worker
|
||||||
|
[+] Restarting 1/1
|
||||||
|
✔ Container mtusi-lab7-openbao-1 Started 0.6s
|
||||||
|
[+] Restarting 1/1
|
||||||
|
✔ Container mtusi-lab7-worker-1 Started 1.1s
|
||||||
|
worker-1 | {"timestamp": "2026-11-23T11:14:55.994Z", "severity": "INFO", "service.name": "messenger-worker", "event": "worker_started", "message": "worker 84aa576470e6 started, concurrency=2, max_attempts=5, lease=75s"}
|
||||||
|
{"status":"ok"}OpenBao unsealed
|
||||||
|
secret_id issued for api
|
||||||
|
secret_id issued for worker
|
||||||
|
secret_id issued for dispatcher
|
||||||
|
secret_id issued for sweeper
|
||||||
|
[+] Restarting 1/1
|
||||||
|
✔ Container mtusi-lab7-worker-1 Started 0.7s
|
||||||
|
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||||
|
mtusi-lab7-worker-1 mtusi-lab7-app:1.0.0 "python -m src.worker" worker 16 minutes ago Up 30 seconds
|
||||||
|
thereal_alyoname@DESKTOP-8Q26HPT:/mnt/c/Users/User/Desktop/MTUCI/4_course/highload_apps/lab7/mtusi2026lab7-fork$
|
||||||
|
|
||||||
|
thereal_alyoname@DESKTOP-8Q26HPT:/mnt/c/Users/User/Desktop/MTUCI/4_course/highload_apps/lab7/mtusi2026la
|
||||||
|
b7-fork$ m
|
||||||
|
ake scan
|
||||||
|
sh scripts/scan.sh
|
||||||
|
Scanning mtusi-lab7-app:1.0.0 ...
|
||||||
|
PASS: mtusi-lab7-app:1.0.0; report saved to evidence/trivy-mtusi-lab7-app_1.0.0.txt
|
||||||
|
Scanning openbao/openbao:2.4.1 ...
|
||||||
|
PASS: openbao/openbao:2.4.1; report saved to evidence/trivy-openbao_openbao_2.4.1.txt
|
||||||
|
Scanning redis:7.4.2-alpine ...
|
||||||
|
PASS: redis:7.4.2-alpine; report saved to evidence/trivy-redis_7.4.2-alpine.txt
|
||||||
|
Scanning postgres:17.6-alpine ...
|
||||||
|
PASS: postgres:17.6-alpine; report saved to evidence/trivy-postgres_17.6-alpine.txt
|
||||||
|
Scanning haproxy:3.2.5-alpine ...
|
||||||
|
PASS: haproxy:3.2.5-alpine; report saved to evidence/trivy-haproxy_3.2.5-alpine.txt
|
||||||
|
scan finished: evidence/pip-audit.txt, evidence/trivy-*.txt
|
||||||
|
thereal_alyoname@DESKTOP-8Q26HPT:/mnt/c/Users/User/Desktop/MTUCI/4_course/highload_apps/lab7/mtusi2026lab7-fork$
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
2026-11-22T23:27:08Z
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
2026-11-22T23:25:35Z
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager, possibly rendering your system unusable. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv. Use the --root-user-action option if you know what you are doing and want to suppress this warning.
|
||||||
|
|
||||||
|
[notice] A new release of pip is available: 25.0.1 -> 26.3
|
||||||
|
[notice] To update, run: pip install --upgrade pip
|
||||||
|
Found 89 known vulnerabilities in 3 packages
|
||||||
|
Name Version ID Fix Versions
|
||||||
|
----------------- ------- ------------------- ------------
|
||||||
|
pillow 11.3.0 PYSEC-2026-2249 12.1.1
|
||||||
|
pillow 11.3.0 PYSEC-2026-2250 12.2.0
|
||||||
|
pillow 11.3.0 PYSEC-2026-165 12.2.0
|
||||||
|
pillow 11.3.0 PYSEC-2026-2251 12.2.0
|
||||||
|
pillow 11.3.0 PYSEC-2026-2874 12.2.0
|
||||||
|
pillow 11.3.0 PYSEC-2026-2252 12.2.0
|
||||||
|
pillow 11.3.0 PYSEC-2026-165 12.2.0
|
||||||
|
pillow 11.3.0 PYSEC-2026-2250 12.2.0
|
||||||
|
pillow 11.3.0 PYSEC-2026-2253 12.3.0
|
||||||
|
pillow 11.3.0 PYSEC-2026-2251 12.2.0
|
||||||
|
pillow 11.3.0 PYSEC-2026-2255 12.3.0
|
||||||
|
pillow 11.3.0 PYSEC-2026-2257 12.3.0
|
||||||
|
pillow 11.3.0 PYSEC-2026-2256 12.3.0
|
||||||
|
pillow 11.3.0 PYSEC-2026-2254 12.3.0
|
||||||
|
pillow 11.3.0 PYSEC-2026-2252 12.2.0
|
||||||
|
pillow 11.3.0 PYSEC-2026-2249 12.1.1
|
||||||
|
pillow 11.3.0 PYSEC-2026-2874 12.2.0
|
||||||
|
pillow 11.3.0 PYSEC-2026-3453 12.3.0
|
||||||
|
pillow 11.3.0 PYSEC-2026-3451 12.3.0
|
||||||
|
pillow 11.3.0 PYSEC-2026-3493 12.3.0
|
||||||
|
pillow 11.3.0 PYSEC-2026-2254 12.3.0
|
||||||
|
pillow 11.3.0 PYSEC-2026-2253 12.3.0
|
||||||
|
pillow 11.3.0 PYSEC-2026-2256 12.3.0
|
||||||
|
pillow 11.3.0 PYSEC-2026-2255 12.3.0
|
||||||
|
pillow 11.3.0 PYSEC-2026-3454 12.3.0
|
||||||
|
pillow 11.3.0 PYSEC-2026-3451 12.3.0
|
||||||
|
pillow 11.3.0 PYSEC-2026-3494 12.3.0
|
||||||
|
pillow 11.3.0 PYSEC-2026-3495 12.3.0
|
||||||
|
pillow 11.3.0 PYSEC-2026-3496 12.3.0
|
||||||
|
pillow 11.3.0 PYSEC-2026-3453 12.3.0
|
||||||
|
pillow 11.3.0 PYSEC-2026-3454 12.3.0
|
||||||
|
pillow 11.3.0 PYSEC-2026-3495 12.3.0
|
||||||
|
pillow 11.3.0 PYSEC-2026-3496 12.3.0
|
||||||
|
pillow 11.3.0 PYSEC-2026-3494 12.3.0
|
||||||
|
pillow 11.3.0 PYSEC-2026-3493 12.3.0
|
||||||
|
pillow 11.3.0 PYSEC-2026-4327 13.0.0
|
||||||
|
pillow 11.3.0 PYSEC-2026-4328 13.0.0
|
||||||
|
pillow 11.3.0 PYSEC-2026-4326 13.0.0
|
||||||
|
pillow 11.3.0 PYSEC-2026-4339 13.0.0
|
||||||
|
pillow 11.3.0 PYSEC-2026-4340 13.0.0
|
||||||
|
pillow 11.3.0 PYSEC-2026-4343 13.0.0
|
||||||
|
pillow 11.3.0 PYSEC-2026-4334 13.0.0
|
||||||
|
pillow 11.3.0 PYSEC-2026-4337 13.0.0
|
||||||
|
pillow 11.3.0 PYSEC-2026-4341 13.0.0
|
||||||
|
pillow 11.3.0 PYSEC-2026-4330 13.0.0
|
||||||
|
pillow 11.3.0 PYSEC-2026-4338 13.0.0
|
||||||
|
pillow 11.3.0 PYSEC-2026-4335 13.0.0
|
||||||
|
pillow 11.3.0 PYSEC-2026-4336 13.0.0
|
||||||
|
pillow 11.3.0 PYSEC-2026-4331 13.0.0
|
||||||
|
pillow 11.3.0 PYSEC-2026-4332 13.0.0
|
||||||
|
pillow 11.3.0 PYSEC-2026-4329 13.0.0
|
||||||
|
pillow 11.3.0 PYSEC-2026-4342 13.0.0
|
||||||
|
pillow 11.3.0 PYSEC-2026-4363 13.0.0
|
||||||
|
pillow 11.3.0 CVE-2026-112895 13.0.0
|
||||||
|
pillow 11.3.0 CVE-2026-112400 13.0.0
|
||||||
|
pillow 11.3.0 CVE-2026-112897 13.0.0
|
||||||
|
pillow 11.3.0 CVE-2026-112395 13.0.0
|
||||||
|
pillow 11.3.0 CVE-2026-112404 13.0.0
|
||||||
|
pillow 11.3.0 CVE-2026-112899 13.0.0
|
||||||
|
pillow 11.3.0 CVE-2026-112900 13.0.0
|
||||||
|
pillow 11.3.0 CVE-2026-112893 13.0.0
|
||||||
|
pillow 11.3.0 CVE-2026-112891 13.0.0
|
||||||
|
pillow 11.3.0 CVE-2026-112390 13.0.0
|
||||||
|
pillow 11.3.0 CVE-2026-112401 13.0.0
|
||||||
|
pillow 11.3.0 CVE-2026-112391 13.0.0
|
||||||
|
pillow 11.3.0 CVE-2026-112894 13.0.0
|
||||||
|
pillow 11.3.0 CVE-2026-112406 13.0.0
|
||||||
|
pillow 11.3.0 CVE-2026-112399 13.0.0
|
||||||
|
pillow 11.3.0 CVE-2026-112892 13.0.0
|
||||||
|
pillow 11.3.0 CVE-2026-112393 13.0.0
|
||||||
|
pillow 11.3.0 CVE-2026-96638 13.0.0
|
||||||
|
pillow 11.3.0 CVE-2026-96640 13.0.0
|
||||||
|
pillow 11.3.0 CVE-2026-96778 13.0.0
|
||||||
|
pillow 11.3.0 GHSA-78g4-xqwv-q3g8 13.0.0
|
||||||
|
pillow 11.3.0 CVE-2026-128067 13.0.0
|
||||||
|
pillow 11.3.0 CVE-2026-128066 13.0.0
|
||||||
|
opentelemetry-api 1.45.1 CVE-2026-126360 1.45.2
|
||||||
|
starlette 0.47.3 PYSEC-2026-1942 0.49.1
|
||||||
|
starlette 0.47.3 PYSEC-2026-161 1.0.1
|
||||||
|
starlette 0.47.3 PYSEC-2026-161 1.0.1
|
||||||
|
starlette 0.47.3 PYSEC-2026-2281 1.1.0
|
||||||
|
starlette 0.47.3 PYSEC-2026-2280 1.1.0
|
||||||
|
starlette 0.47.3 PYSEC-2026-249 1.3.1
|
||||||
|
starlette 0.47.3 PYSEC-2026-248 1.3.0
|
||||||
|
starlette 0.47.3 PYSEC-2026-249 1.3.1
|
||||||
|
starlette 0.47.3 PYSEC-2026-248 1.3.0
|
||||||
|
starlette 0.47.3 PYSEC-2026-1942 0.49.1
|
||||||
|
starlette 0.47.3 PYSEC-2026-2281 1.1.0
|
||||||
|
starlette 0.47.3 PYSEC-2026-2280 1.1.0
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
PASS OpenBao: login with OLD SecretID: rejected (expected rejected)
|
||||||
|
PASS PostgreSQL: new connection with OLD role password: rejected (expected rejected)
|
||||||
|
PASS S3: new request with OLD svc-worker secret: rejected (expected rejected)
|
||||||
|
PASS OpenBao: login with NEW SecretID: accepted (expected accepted)
|
||||||
|
PASS PostgreSQL: new connection with NEW role password: accepted (expected accepted)
|
||||||
|
PASS S3: new request with NEW svc-worker secret: accepted (expected accepted)
|
||||||
|
|
||||||
|
6/6 probes as expected
|
||||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,100 @@
|
|||||||
|
{
|
||||||
|
"profile": "after",
|
||||||
|
"probes": [
|
||||||
|
{
|
||||||
|
"probe": "db: SELECT attachment_jobs (job state)",
|
||||||
|
"expected_after": "allowed",
|
||||||
|
"observed": "allowed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"probe": "db: UPDATE attachments (status)",
|
||||||
|
"expected_after": "allowed",
|
||||||
|
"observed": "allowed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"probe": "db: SELECT users.password_hash",
|
||||||
|
"expected_after": "denied",
|
||||||
|
"observed": "denied"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"probe": "db: SELECT messages (content)",
|
||||||
|
"expected_after": "denied",
|
||||||
|
"observed": "denied"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"probe": "db: DELETE FROM attachment_jobs",
|
||||||
|
"expected_after": "denied",
|
||||||
|
"observed": "denied"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"probe": "db: CREATE TABLE / DDL",
|
||||||
|
"expected_after": "denied",
|
||||||
|
"observed": "denied"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"probe": "s3: GET staging/*",
|
||||||
|
"expected_after": "allowed",
|
||||||
|
"observed": "allowed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"probe": "s3: GET attachments/* (finished files)",
|
||||||
|
"expected_after": "denied",
|
||||||
|
"observed": "denied"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"probe": "s3: PUT attachments/*",
|
||||||
|
"expected_after": "allowed",
|
||||||
|
"observed": "allowed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"probe": "s3: DELETE attachments/*",
|
||||||
|
"expected_after": "denied",
|
||||||
|
"observed": "denied"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"probe": "s3: PUT staging/* (forge input)",
|
||||||
|
"expected_after": "denied",
|
||||||
|
"observed": "denied"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"probe": "s3: ListBucket",
|
||||||
|
"expected_after": "denied",
|
||||||
|
"observed": "denied"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"probe": "kafka: consume jobs topic, own group",
|
||||||
|
"expected_after": "allowed",
|
||||||
|
"observed": "allowed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"probe": "kafka: produce to jobs topic (forge jobs)",
|
||||||
|
"expected_after": "denied",
|
||||||
|
"observed": "denied"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"probe": "kafka: consume with another group",
|
||||||
|
"expected_after": "denied",
|
||||||
|
"observed": "denied"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"probe": "bao: read kv/data/worker (own secret)",
|
||||||
|
"expected_after": "allowed",
|
||||||
|
"observed": "allowed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"probe": "bao: read kv/data/api",
|
||||||
|
"expected_after": "denied",
|
||||||
|
"observed": "denied"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"probe": "bao: write sys policy",
|
||||||
|
"expected_after": "denied",
|
||||||
|
"observed": "denied"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"probe": "api: connect to api:8443 with worker certificate",
|
||||||
|
"expected_after": "denied",
|
||||||
|
"observed": "denied"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
{
|
||||||
|
"profile": "before",
|
||||||
|
"probes": [
|
||||||
|
{
|
||||||
|
"probe": "db: SELECT attachment_jobs (job state)",
|
||||||
|
"expected_after": "allowed",
|
||||||
|
"observed": "allowed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"probe": "db: UPDATE attachments (status)",
|
||||||
|
"expected_after": "allowed",
|
||||||
|
"observed": "allowed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"probe": "db: SELECT users.password_hash",
|
||||||
|
"expected_after": "denied",
|
||||||
|
"observed": "allowed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"probe": "db: SELECT messages (content)",
|
||||||
|
"expected_after": "denied",
|
||||||
|
"observed": "allowed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"probe": "db: DELETE FROM attachment_jobs",
|
||||||
|
"expected_after": "denied",
|
||||||
|
"observed": "allowed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"probe": "db: CREATE TABLE / DDL",
|
||||||
|
"expected_after": "denied",
|
||||||
|
"observed": "allowed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"probe": "s3: GET staging/*",
|
||||||
|
"expected_after": "allowed",
|
||||||
|
"observed": "allowed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"probe": "s3: GET attachments/* (finished files)",
|
||||||
|
"expected_after": "denied",
|
||||||
|
"observed": "allowed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"probe": "s3: PUT attachments/*",
|
||||||
|
"expected_after": "allowed",
|
||||||
|
"observed": "allowed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"probe": "s3: DELETE attachments/*",
|
||||||
|
"expected_after": "denied",
|
||||||
|
"observed": "allowed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"probe": "s3: PUT staging/* (forge input)",
|
||||||
|
"expected_after": "denied",
|
||||||
|
"observed": "allowed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"probe": "s3: ListBucket",
|
||||||
|
"expected_after": "denied",
|
||||||
|
"observed": "allowed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"probe": "kafka: consume jobs topic, own group",
|
||||||
|
"expected_after": "allowed",
|
||||||
|
"observed": "allowed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"probe": "kafka: produce to jobs topic (forge jobs)",
|
||||||
|
"expected_after": "denied",
|
||||||
|
"observed": "allowed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"probe": "kafka: consume with another group",
|
||||||
|
"expected_after": "denied",
|
||||||
|
"observed": "allowed"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"probe": "api: connect to api:8443 with worker certificate",
|
||||||
|
"expected_after": "denied",
|
||||||
|
"observed": "denied"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,670 @@
|
|||||||
|
{
|
||||||
|
"uid": "messenger-observability",
|
||||||
|
"title": "Messenger: observability (lab 6)",
|
||||||
|
"tags": [
|
||||||
|
"messenger",
|
||||||
|
"lab6"
|
||||||
|
],
|
||||||
|
"timezone": "browser",
|
||||||
|
"schemaVersion": 39,
|
||||||
|
"version": 1,
|
||||||
|
"refresh": "10s",
|
||||||
|
"time": {
|
||||||
|
"from": "now-30m",
|
||||||
|
"to": "now"
|
||||||
|
},
|
||||||
|
"editable": false,
|
||||||
|
"panels": [
|
||||||
|
{
|
||||||
|
"id": 1,
|
||||||
|
"type": "stat",
|
||||||
|
"title": "API availability SLI (SLO 99 % / 30 d)",
|
||||||
|
"description": "SLI = 1 - 5xx / all business requests (health excluded; 4xx are client errors). Window = dashboard time range (set 30d to read the SLO). Query: 1 - sum(increase(http_server_request_duration_seconds_count{5xx}[$__range])) / sum(increase(..._count[$__range])).",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 0,
|
||||||
|
"y": 0,
|
||||||
|
"w": 8,
|
||||||
|
"h": 4
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"expr": "1 - (sum(increase(http_server_request_duration_seconds_count{service_name=\"messenger-api\",http_response_status_class=\"5xx\"}[$__range])) / sum(increase(http_server_request_duration_seconds_count{service_name=\"messenger-api\"}[$__range])))",
|
||||||
|
"legendFormat": "availability"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "percentunit",
|
||||||
|
"min": 0.9,
|
||||||
|
"max": 1,
|
||||||
|
"decimals": 3,
|
||||||
|
"thresholds": {
|
||||||
|
"mode": "absolute",
|
||||||
|
"steps": [
|
||||||
|
{
|
||||||
|
"color": "red",
|
||||||
|
"value": null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"color": "green",
|
||||||
|
"value": 0.99
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"options": {
|
||||||
|
"colorMode": "background",
|
||||||
|
"reduceOptions": {
|
||||||
|
"calcs": [
|
||||||
|
"lastNotNull"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 2,
|
||||||
|
"type": "timeseries",
|
||||||
|
"title": "Alert state (pending / firing)",
|
||||||
|
"description": "ALERTS{} series written by Prometheus rule evaluation: shows pending -> firing -> gone (resolved).",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 8,
|
||||||
|
"y": 0,
|
||||||
|
"w": 16,
|
||||||
|
"h": 4
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"expr": "sum by (alertname, alertstate) (ALERTS)",
|
||||||
|
"legendFormat": "{{alertname}} {{alertstate}}"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "short"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"options": {}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 3,
|
||||||
|
"type": "timeseries",
|
||||||
|
"title": "API RPS by route",
|
||||||
|
"description": "Query: sum by (http_route)(rate(http_server_request_duration_seconds_count[1m])). Unit: requests/s. Route is a TEMPLATE, never a real UUID.",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 0,
|
||||||
|
"y": 4,
|
||||||
|
"w": 8,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"expr": "sum by (http_route) (rate(http_server_request_duration_seconds_count{service_name=\"messenger-api\"}[1m]))",
|
||||||
|
"legendFormat": "{{http_route}}"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "reqps"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"options": {}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 4,
|
||||||
|
"type": "timeseries",
|
||||||
|
"title": "API 5xx error ratio",
|
||||||
|
"description": "numerator = 5xx business requests, denominator = all business requests (health excluded). Unit: ratio 0..1.",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 8,
|
||||||
|
"y": 4,
|
||||||
|
"w": 8,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"expr": "sum(rate(http_server_request_duration_seconds_count{service_name=\"messenger-api\",http_response_status_class=\"5xx\"}[2m])) / sum(rate(http_server_request_duration_seconds_count{service_name=\"messenger-api\"}[2m]))",
|
||||||
|
"legendFormat": "5xx / all"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "percentunit",
|
||||||
|
"min": 0
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"options": {}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 5,
|
||||||
|
"type": "timeseries",
|
||||||
|
"title": "API latency p50 / p95 / p99",
|
||||||
|
"description": "histogram_quantile(q, sum by (le)(rate(http_server_request_duration_seconds_bucket[2m]))): buckets of ALL replicas are summed first. Averages of per-replica percentiles are mathematically wrong. Unit: seconds.",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 16,
|
||||||
|
"y": 4,
|
||||||
|
"w": 8,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"expr": "histogram_quantile(0.5, sum by (le) (rate(http_server_request_duration_seconds_bucket{service_name=\"messenger-api\"}[2m])))",
|
||||||
|
"legendFormat": "p50"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"refId": "B",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"expr": "histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket{service_name=\"messenger-api\"}[2m])))",
|
||||||
|
"legendFormat": "p95"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"refId": "C",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"expr": "histogram_quantile(0.99, sum by (le) (rate(http_server_request_duration_seconds_bucket{service_name=\"messenger-api\"}[2m])))",
|
||||||
|
"legendFormat": "p99"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "s"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"options": {}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 6,
|
||||||
|
"type": "timeseries",
|
||||||
|
"title": "Jobs by outcome",
|
||||||
|
"description": "Counter of finished attempts: success | retry | failed | lost | noop | error. Unit: attempts/s.",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 0,
|
||||||
|
"y": 12,
|
||||||
|
"w": 8,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"expr": "sum by (outcome) (rate(messenger_jobs_processed_total[1m]))",
|
||||||
|
"legendFormat": "{{outcome}}"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "ops"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"options": {}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 7,
|
||||||
|
"type": "timeseries",
|
||||||
|
"title": "Worker job duration p50 / p95 / p99",
|
||||||
|
"description": "Processing time of one attempt (claim -> outcome). Does NOT include waiting in the queue (that is queue age). Unit: seconds.",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 8,
|
||||||
|
"y": 12,
|
||||||
|
"w": 8,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"expr": "histogram_quantile(0.5, sum by (le) (rate(messenger_job_duration_seconds_bucket{}[2m])))",
|
||||||
|
"legendFormat": "p50"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"refId": "B",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_job_duration_seconds_bucket{}[2m])))",
|
||||||
|
"legendFormat": "p95"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"refId": "C",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_job_duration_seconds_bucket{}[2m])))",
|
||||||
|
"legendFormat": "p99"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "s"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"options": {}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 8,
|
||||||
|
"type": "timeseries",
|
||||||
|
"title": "Time to ready p50 / p95 / p99",
|
||||||
|
"description": "End-to-end: durable acceptance (job row) -> ready commit, incl. backlog, retries and backoff. Unit: seconds.",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 16,
|
||||||
|
"y": 12,
|
||||||
|
"w": 8,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"expr": "histogram_quantile(0.5, sum by (le) (rate(messenger_job_time_to_ready_seconds_bucket{}[5m])))",
|
||||||
|
"legendFormat": "p50"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"refId": "B",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_job_time_to_ready_seconds_bucket{}[5m])))",
|
||||||
|
"legendFormat": "p95"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"refId": "C",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_job_time_to_ready_seconds_bucket{}[5m])))",
|
||||||
|
"legendFormat": "p99"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "s"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"options": {}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 9,
|
||||||
|
"type": "timeseries",
|
||||||
|
"title": "Queue depth",
|
||||||
|
"description": "Jobs with status=queued whose backoff has elapsed (waiting for a worker). Computed by the dispatcher from PostgreSQL. Unit: jobs.",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 0,
|
||||||
|
"y": 20,
|
||||||
|
"w": 6,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"expr": "max by (queue_name) (messenger_queue_depth)",
|
||||||
|
"legendFormat": "{{queue_name}}"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "short"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"options": {}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 10,
|
||||||
|
"type": "timeseries",
|
||||||
|
"title": "Oldest waiting job age",
|
||||||
|
"description": "now - min(next_attempt_at) over due queued jobs; 0 when empty. Alert QueueLagGrowing: > 30 s for 1 m. Unit: seconds.",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 6,
|
||||||
|
"y": 20,
|
||||||
|
"w": 6,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"expr": "max by (queue_name) (messenger_queue_oldest_job_age_seconds)",
|
||||||
|
"legendFormat": "{{queue_name}}"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "s"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"options": {}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 11,
|
||||||
|
"type": "timeseries",
|
||||||
|
"title": "Worker busy vs capacity",
|
||||||
|
"description": "busy = jobs handled right now, capacity = WORKER_CONCURRENCY. Saturation = busy / capacity. Unit: jobs.",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 12,
|
||||||
|
"y": 20,
|
||||||
|
"w": 6,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"expr": "sum(messenger_worker_busy)",
|
||||||
|
"legendFormat": "busy"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"refId": "B",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"expr": "sum(messenger_worker_capacity)",
|
||||||
|
"legendFormat": "capacity"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "short"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"options": {}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 12,
|
||||||
|
"type": "timeseries",
|
||||||
|
"title": "DB pool used / waiting (API)",
|
||||||
|
"description": "psycopg_pool stats: connections checked out, requests waiting for a connection. waiting > 0 = pool saturation. Unit: connections / requests.",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 18,
|
||||||
|
"y": 20,
|
||||||
|
"w": 6,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"expr": "sum by (service_instance_id) (messenger_db_pool_used)",
|
||||||
|
"legendFormat": "used {{service_instance_id}}"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"refId": "B",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"expr": "sum(messenger_db_pool_waiting)",
|
||||||
|
"legendFormat": "waiting (all)"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "short"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"options": {}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 13,
|
||||||
|
"type": "timeseries",
|
||||||
|
"title": "CPU by service (cores)",
|
||||||
|
"description": "rate of process CPU seconds (user+system) of the main process. Unit: CPU cores.",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 0,
|
||||||
|
"y": 28,
|
||||||
|
"w": 8,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"expr": "sum by (service_name) (rate(process_cpu_time_seconds_total[1m]))",
|
||||||
|
"legendFormat": "{{service_name}}"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "short"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"options": {}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 14,
|
||||||
|
"type": "timeseries",
|
||||||
|
"title": "Memory (RSS) by service",
|
||||||
|
"description": "Resident set size of the main process. Unit: bytes.",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 8,
|
||||||
|
"y": 28,
|
||||||
|
"w": 8,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"expr": "sum by (service_name, service_instance_id) (process_memory_usage_bytes)",
|
||||||
|
"legendFormat": "{{service_name}} {{service_instance_id}}"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "bytes"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"options": {}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 15,
|
||||||
|
"type": "timeseries",
|
||||||
|
"title": "Telemetry loss in the Collector",
|
||||||
|
"description": "Failed exporter sends and memory_limiter refusals (spans / metric points / log records per second). Non-zero while a backend is down: telemetry is lost, the API is not affected.",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 16,
|
||||||
|
"y": 28,
|
||||||
|
"w": 8,
|
||||||
|
"h": 8
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"expr": "sum by (__name__) (rate({__name__=~\"otelcol_(exporter_send_failed|processor_refused)_.*_total\",job=\"otel-collector\"}[1m]))",
|
||||||
|
"legendFormat": "{{__name__}}"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "short"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"options": {}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 16,
|
||||||
|
"type": "logs",
|
||||||
|
"title": "Warnings and errors (all services)",
|
||||||
|
"description": "Loki (OTLP). Click trace_id to open the trace in Tempo. Filter one trace: {service_name=~\"messenger-.+\"} | trace_id=\"<id>\".",
|
||||||
|
"datasource": {
|
||||||
|
"type": "loki",
|
||||||
|
"uid": "loki"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"x": 0,
|
||||||
|
"y": 36,
|
||||||
|
"w": 24,
|
||||||
|
"h": 10
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"datasource": {
|
||||||
|
"type": "loki",
|
||||||
|
"uid": "loki"
|
||||||
|
},
|
||||||
|
"expr": "{service_name=~\"messenger-.+\"} | detected_level=~\"WARN|ERROR|CRITICAL\"",
|
||||||
|
"legendFormat": ""
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "short"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"options": {
|
||||||
|
"showTime": true,
|
||||||
|
"wrapLogMessage": true,
|
||||||
|
"enableLogDetails": true,
|
||||||
|
"sortOrder": "Descending"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"templating": {
|
||||||
|
"list": []
|
||||||
|
},
|
||||||
|
"annotations": {
|
||||||
|
"list": []
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
apiVersion: 1
|
||||||
|
providers:
|
||||||
|
- name: messenger
|
||||||
|
type: file
|
||||||
|
disableDeletion: true
|
||||||
|
allowUiUpdates: false
|
||||||
|
updateIntervalSeconds: 30
|
||||||
|
options:
|
||||||
|
path: /var/lib/grafana/dashboards
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
apiVersion: 1
|
||||||
|
# Grafana -> data sources: TLS with server verification (CA + serverName) and the grafana client identity (mTLS).
|
||||||
|
datasources:
|
||||||
|
- name: Prometheus
|
||||||
|
uid: prometheus
|
||||||
|
type: prometheus
|
||||||
|
access: proxy
|
||||||
|
url: https://prometheus:9090
|
||||||
|
isDefault: true
|
||||||
|
jsonData: {timeInterval: 15s, tlsAuth: true, tlsAuthWithCACert: true, serverName: prometheus}
|
||||||
|
secureJsonData: {tlsCACert: "$__file{/pki/ca.crt}", tlsClientCert: "$__file{/pki/tls.crt}", tlsClientKey: "$__file{/pki/tls.key}"}
|
||||||
|
- name: Loki
|
||||||
|
uid: loki
|
||||||
|
type: loki
|
||||||
|
access: proxy
|
||||||
|
url: https://loki:3100
|
||||||
|
jsonData: {tlsAuth: true, tlsAuthWithCACert: true, serverName: loki}
|
||||||
|
secureJsonData: {tlsCACert: "$__file{/pki/ca.crt}", tlsClientCert: "$__file{/pki/tls.crt}", tlsClientKey: "$__file{/pki/tls.key}"}
|
||||||
|
- name: Tempo
|
||||||
|
uid: tempo
|
||||||
|
type: tempo
|
||||||
|
access: proxy
|
||||||
|
url: https://tempo:3200
|
||||||
|
jsonData: {tlsAuth: true, tlsAuthWithCACert: true, serverName: tempo}
|
||||||
|
secureJsonData: {tlsCACert: "$__file{/pki/ca.crt}", tlsClientCert: "$__file{/pki/tls.crt}", tlsClientKey: "$__file{/pki/tls.key}"}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
# Lab 7 ingress: TLS (public CA, hostname localhost) from clients, mTLS to every API replica.
|
||||||
|
global
|
||||||
|
log stdout format raw local0
|
||||||
|
maxconn 1024
|
||||||
|
ssl-default-bind-options ssl-min-ver TLSv1.2
|
||||||
|
ssl-default-server-options ssl-min-ver TLSv1.2
|
||||||
|
|
||||||
|
defaults
|
||||||
|
log global
|
||||||
|
mode http
|
||||||
|
option httplog
|
||||||
|
option http-keep-alive
|
||||||
|
timeout connect 2s
|
||||||
|
timeout client 30s
|
||||||
|
timeout server 30s
|
||||||
|
timeout check 2s
|
||||||
|
timeout http-request 10s # slow-header (Slowloris) protection
|
||||||
|
|
||||||
|
resolvers docker
|
||||||
|
nameserver docker-dns 127.0.0.11:53
|
||||||
|
resolve_retries 3
|
||||||
|
timeout resolve 1s
|
||||||
|
timeout retry 1s
|
||||||
|
hold valid 2s
|
||||||
|
hold obsolete 2s
|
||||||
|
|
||||||
|
frontend public_https
|
||||||
|
bind :8443 ssl crt /pki/lb-public/keystore.pem
|
||||||
|
http-request set-header X-Real-IP %[src] # overwritten here: the API trusts it for rate limiting (only this LB may connect)
|
||||||
|
http-response set-header Strict-Transport-Security "max-age=31536000"
|
||||||
|
default_backend api_replicas
|
||||||
|
|
||||||
|
backend api_replicas
|
||||||
|
balance roundrobin
|
||||||
|
option httpchk
|
||||||
|
http-check send meth GET uri /health/ready
|
||||||
|
http-check expect status 200
|
||||||
|
# mTLS to the replica: verify the API certificate (CA + hostname "api"), present the LB identity (CN/SAN "lb").
|
||||||
|
default-server inter 1s fall 2 rise 1 ssl verify required ca-file /pki/lb/ca.crt verifyhost api sni str(api) crt /pki/lb/keystore.pem check
|
||||||
|
server-template api 10 api:8443 resolvers docker init-addr libc,none
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
# Admin/health client config used INSIDE the kafka and kafka_init containers (identity = the mounted /pki/keystore.pem).
|
||||||
|
security.protocol=SSL
|
||||||
|
ssl.keystore.type=PEM
|
||||||
|
ssl.keystore.location=/pki/keystore.pem
|
||||||
|
ssl.truststore.type=PEM
|
||||||
|
ssl.truststore.location=/pki/ca.crt
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# Idempotent broker topology + ACLs. Principals are certificate CNs (ssl.principal.mapping.rules).
|
||||||
|
# dispatcher = producer only, worker = consumer of the jobs topic and of its own group only. Anybody else (even with a CA-signed cert) is denied.
|
||||||
|
set -eu
|
||||||
|
K=/opt/kafka/bin; B="--bootstrap-server kafka:9092 --command-config /client.properties"
|
||||||
|
$K/kafka-topics.sh $B --create --if-not-exists --topic "$JOBS_TOPIC" --partitions 3 --replication-factor 1 --config min.insync.replicas=1 --config retention.ms=604800000
|
||||||
|
$K/kafka-acls.sh $B --add --allow-principal User:dispatcher --producer --idempotent --topic "$JOBS_TOPIC"
|
||||||
|
$K/kafka-acls.sh $B --add --allow-principal User:worker --consumer --topic "$JOBS_TOPIC" --group attachment-workers
|
||||||
|
$K/kafka-acls.sh $B --list
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
auth_enabled: false
|
||||||
|
server:
|
||||||
|
http_listen_port: 3100
|
||||||
|
grpc_listen_port: 9096
|
||||||
|
grpc_listen_address: 127.0.0.1 # in-process traffic only (single binary); not reachable from the network
|
||||||
|
http_tls_config:
|
||||||
|
cert_file: /pki/tls.crt
|
||||||
|
key_file: /pki/tls.key
|
||||||
|
client_ca_file: /pki/ca.crt
|
||||||
|
client_auth_type: RequireAndVerifyClientCert
|
||||||
|
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
|
||||||
|
ingestion_rate_mb: 8
|
||||||
|
ingestion_burst_size_mb: 16
|
||||||
|
analytics: {reporting_enabled: false}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
# Non-dev OpenBao: TLS listener, persistent file storage on a named volume, sealed after every restart.
|
||||||
|
ui = false
|
||||||
|
disable_mlock = true # container without IPC_LOCK; swap is disabled on the lab host (see REPORT)
|
||||||
|
api_addr = "https://openbao:8200"
|
||||||
|
|
||||||
|
storage "file" {
|
||||||
|
path = "/openbao/data"
|
||||||
|
}
|
||||||
|
|
||||||
|
listener "tcp" {
|
||||||
|
address = "0.0.0.0:8200"
|
||||||
|
tls_cert_file = "/run/pki/tls.crt"
|
||||||
|
tls_key_file = "/run/pki/tls.key"
|
||||||
|
tls_min_version = "tls12"
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
# Policy "api": read exactly one KV v2 secret. No list, no metadata, no write, no sys/*, no other service paths.
|
||||||
|
path "kv/data/api" {
|
||||||
|
capabilities = ["read"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
# Policy "dispatcher": read exactly one KV v2 secret. No list, no metadata, no write, no sys/*, no other service paths.
|
||||||
|
path "kv/data/dispatcher" {
|
||||||
|
capabilities = ["read"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
# Policy "sweeper": read exactly one KV v2 secret. No list, no metadata, no write, no sys/*, no other service paths.
|
||||||
|
path "kv/data/sweeper" {
|
||||||
|
capabilities = ["read"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
# Policy "worker": read exactly one KV v2 secret. No list, no metadata, no write, no sys/*, no other service paths.
|
||||||
|
path "kv/data/worker" {
|
||||||
|
capabilities = ["read"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
# OpenTelemetry Collector (contrib 0.131.0), lab 7: OTLP/HTTP is mTLS-only and accepts ONLY identities issued by the "workload CA"
|
||||||
|
# (api, worker, dispatcher). A certificate signed by the root CA with another identity (grafana, lb, outsider) has no chain to that
|
||||||
|
# trust anchor and is rejected in the handshake. Exporters to the backends use TLS with server verification + the collector client cert.
|
||||||
|
extensions:
|
||||||
|
health_check:
|
||||||
|
endpoint: 0.0.0.0:13133 # liveness only, no telemetry data; inside the internal backend network, never published
|
||||||
|
|
||||||
|
receivers:
|
||||||
|
otlp:
|
||||||
|
protocols:
|
||||||
|
http:
|
||||||
|
endpoint: 0.0.0.0:4318
|
||||||
|
tls:
|
||||||
|
cert_file: /pki/tls.crt
|
||||||
|
key_file: /pki/tls.key
|
||||||
|
client_ca_file: /ca/workload-ca.crt # trust anchor = workload CA only (not the root CA)
|
||||||
|
min_version: "1.2"
|
||||||
|
|
||||||
|
processors:
|
||||||
|
memory_limiter: {check_interval: 1s, limit_mib: 192, spike_limit_mib: 48}
|
||||||
|
batch: {timeout: 2s, send_batch_size: 512, send_batch_max_size: 1024}
|
||||||
|
attributes/no_secrets: # defence in depth: never forward credentials even if an SDK attached them
|
||||||
|
actions:
|
||||||
|
- {key: http.request.header.authorization, action: delete}
|
||||||
|
- {key: http.request.header.cookie, action: delete}
|
||||||
|
- {key: password, action: delete}
|
||||||
|
|
||||||
|
exporters:
|
||||||
|
prometheusremotewrite:
|
||||||
|
endpoint: https://prometheus:9090/api/v1/write
|
||||||
|
timeout: 5s
|
||||||
|
tls: {ca_file: /pki/ca.crt, cert_file: /pki/tls.crt, key_file: /pki/tls.key}
|
||||||
|
resource_to_telemetry_conversion: {enabled: true}
|
||||||
|
retry_on_failure: {enabled: true, initial_interval: 1s, max_interval: 10s, max_elapsed_time: 30s}
|
||||||
|
remote_write_queue: {enabled: true, queue_size: 200, num_consumers: 2}
|
||||||
|
otlphttp/loki:
|
||||||
|
endpoint: https://loki:3100/otlp
|
||||||
|
timeout: 5s
|
||||||
|
tls: {ca_file: /pki/ca.crt, cert_file: /pki/tls.crt, key_file: /pki/tls.key}
|
||||||
|
retry_on_failure: {enabled: true, initial_interval: 1s, max_interval: 10s, max_elapsed_time: 30s}
|
||||||
|
sending_queue: {enabled: true, num_consumers: 2, queue_size: 200}
|
||||||
|
otlp/tempo:
|
||||||
|
endpoint: tempo:4317
|
||||||
|
timeout: 5s
|
||||||
|
tls: {ca_file: /pki/ca.crt, cert_file: /pki/tls.crt, key_file: /pki/tls.key}
|
||||||
|
retry_on_failure: {enabled: true, initial_interval: 1s, max_interval: 10s, max_elapsed_time: 30s}
|
||||||
|
sending_queue: {enabled: true, num_consumers: 2, queue_size: 200}
|
||||||
|
|
||||||
|
service:
|
||||||
|
extensions: [health_check]
|
||||||
|
pipelines:
|
||||||
|
metrics: {receivers: [otlp], processors: [memory_limiter, attributes/no_secrets, batch], exporters: [prometheusremotewrite]}
|
||||||
|
logs: {receivers: [otlp], processors: [memory_limiter, attributes/no_secrets, batch], exporters: [otlphttp/loki]}
|
||||||
|
traces: {receivers: [otlp], processors: [memory_limiter, attributes/no_secrets, batch], exporters: [otlp/tempo]}
|
||||||
|
telemetry:
|
||||||
|
logs: {level: info}
|
||||||
|
metrics:
|
||||||
|
level: normal
|
||||||
|
readers:
|
||||||
|
- pull:
|
||||||
|
exporter:
|
||||||
|
prometheus: {host: 0.0.0.0, port: 8888} # Collector self-metrics only; plain HTTP, internal network, no credentials/data
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# PostgreSQL refuses a key that is not owned by the server user with mode 0600: copy the mounted key into a private tmpfs first.
|
||||||
|
set -eu
|
||||||
|
install -d -m 700 -o postgres -g postgres /tls
|
||||||
|
install -m 644 -o postgres -g postgres /pki/tls.crt /tls/server.crt
|
||||||
|
install -m 600 -o postgres -g postgres /pki/tls.key /tls/server.key
|
||||||
|
install -m 644 -o postgres -g postgres /pki/ca.crt /tls/ca.crt
|
||||||
|
exec docker-entrypoint.sh postgres -c ssl=on -c ssl_cert_file=/tls/server.crt -c ssl_key_file=/tls/server.key \
|
||||||
|
-c ssl_ca_file=/tls/ca.crt -c ssl_min_protocol_version=TLSv1.2 -c hba_file=/etc/postgresql/pg_hba.conf -c password_encryption=scram-sha-256
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
# Lab 7: TLS + SCRAM only. Plain-text TCP connections are rejected. The unix socket exists only inside the container (operator docker exec).
|
||||||
|
local all all trust
|
||||||
|
hostssl all all 0.0.0.0/0 scram-sha-256
|
||||||
|
host all all 0.0.0.0/0 reject
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
groups:
|
||||||
|
- name: messenger-slo
|
||||||
|
rules:
|
||||||
|
# SLI (availability): 1 - 5xx / all BUSINESS requests (health excluded; 4xx such as a wrong password are NOT errors).
|
||||||
|
# SLO: 99 % over a rolling 30 days (error budget 1 %). Alert = fast symptom: >5 % 5xx for 1 m with real traffic.
|
||||||
|
- alert: HighApiErrorRate
|
||||||
|
expr: |
|
||||||
|
(
|
||||||
|
sum(rate(http_server_request_duration_seconds_count{service_name="messenger-api",http_response_status_class="5xx"}[2m]))
|
||||||
|
/
|
||||||
|
sum(rate(http_server_request_duration_seconds_count{service_name="messenger-api"}[2m]))
|
||||||
|
) > 0.05
|
||||||
|
and
|
||||||
|
sum(rate(http_server_request_duration_seconds_count{service_name="messenger-api"}[2m])) > 0.2
|
||||||
|
for: 1m
|
||||||
|
labels:
|
||||||
|
severity: page
|
||||||
|
annotations:
|
||||||
|
summary: "API 5xx ratio above 5 % (2m window)"
|
||||||
|
description: "More than 5 % of business requests end with 5xx for 1 minute. Runbook: runbooks/high-error-rate.md"
|
||||||
|
runbook: runbooks/high-error-rate.md
|
||||||
|
# Queue lag: the oldest due job waits for a worker longer than 30 s for 1 m (worker stopped / too slow / broker problem).
|
||||||
|
# Backlog (age of waiting jobs) is NOT processing latency: processing time is messenger_job_duration_seconds.
|
||||||
|
- alert: QueueLagGrowing
|
||||||
|
expr: max(messenger_queue_oldest_job_age_seconds{queue_name="attachment-jobs"}) > 30
|
||||||
|
for: 1m
|
||||||
|
labels:
|
||||||
|
severity: page
|
||||||
|
annotations:
|
||||||
|
summary: "Oldest waiting job is older than 30 s"
|
||||||
|
description: "Jobs wait for a worker. Check messenger_worker_busy/capacity, messenger_queue_depth and the worker logs. Runbook: runbooks/queue-lag.md"
|
||||||
|
runbook: runbooks/queue-lag.md
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
global:
|
||||||
|
scrape_interval: 15s
|
||||||
|
evaluation_interval: 15s
|
||||||
|
rule_files:
|
||||||
|
- /etc/prometheus/alerts.yml
|
||||||
|
scrape_configs:
|
||||||
|
# App metrics arrive by remote write (push, mTLS). Only the Collector self-metrics (plain, internal) and Prometheus itself (TLS) are scraped.
|
||||||
|
- job_name: otel-collector
|
||||||
|
static_configs:
|
||||||
|
- targets: ["otel-collector:8888"]
|
||||||
|
- job_name: prometheus
|
||||||
|
scheme: https
|
||||||
|
tls_config: {ca_file: /pki/ca.crt, cert_file: /pki/tls.crt, key_file: /pki/tls.key, server_name: prometheus}
|
||||||
|
static_configs:
|
||||||
|
- targets: ["prometheus:9090"]
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
# Prometheus web TLS: mTLS - only clients with a certificate from our CA (collector remote-write, grafana, self-scrape).
|
||||||
|
tls_server_config:
|
||||||
|
cert_file: /pki/tls.crt
|
||||||
|
key_file: /pki/tls.key
|
||||||
|
client_ca_file: /pki/ca.crt
|
||||||
|
client_auth_type: RequireAndVerifyClientCert
|
||||||
|
min_version: TLS12
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
# Lab 7: TLS only (plain port disabled); ACL users come from users.acl (hashed passwords, `default` user off).
|
||||||
|
port 0
|
||||||
|
tls-port 6379
|
||||||
|
tls-cert-file /pki/tls.crt
|
||||||
|
tls-key-file /pki/tls.key
|
||||||
|
tls-ca-cert-file /pki/ca.crt
|
||||||
|
tls-auth-clients no
|
||||||
|
tls-protocols "TLSv1.2 TLSv1.3"
|
||||||
|
aclfile /acl/users.acl
|
||||||
|
appendonly yes
|
||||||
|
appendfsync everysec
|
||||||
|
dir /data
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# Idempotent bootstrap: private bucket + THREE scoped S3 users (api, worker, sweeper). Runs with the S3 root credentials, then exits.
|
||||||
|
# api : write/delete staging/*, read attachments/* (accepts uploads, serves downloads)
|
||||||
|
# worker : read/delete staging/*, write attachments/* (cannot read finished attachments, cannot write staging, cannot list)
|
||||||
|
# sweeper: list bucket, read/delete staging/* and attachments/* (no PutObject)
|
||||||
|
set -eu
|
||||||
|
: "${S3_ENDPOINT:?}" "${S3_BUCKET:?}"
|
||||||
|
RU="$(cat /run/secrets/s3_root_user)"; RP="$(cat /run/secrets/s3_root_password)"
|
||||||
|
i=0
|
||||||
|
until mc alias set local "$S3_ENDPOINT" "$RU" "$RP" >/dev/null 2>&1; do
|
||||||
|
i=$((i+1)); [ "$i" -lt 60 ] || { echo "S3 not reachable over TLS" >&2; exit 1; }; sleep 1
|
||||||
|
done
|
||||||
|
mc mb --ignore-existing "local/$S3_BUCKET"
|
||||||
|
mc anonymous set none "local/$S3_BUCKET"
|
||||||
|
printf ok | mc pipe "local/$S3_BUCKET/attachments/.ready"
|
||||||
|
B="arn:aws:s3:::$S3_BUCKET"
|
||||||
|
cat > /tmp/p-api.json <<P
|
||||||
|
{"Version":"2012-10-17","Statement":[
|
||||||
|
{"Effect":"Allow","Action":["s3:PutObject","s3:DeleteObject","s3:AbortMultipartUpload","s3:ListMultipartUploadParts"],"Resource":["$B/staging/*"]},
|
||||||
|
{"Effect":"Allow","Action":["s3:GetObject"],"Resource":["$B/attachments/*"]}]}
|
||||||
|
P
|
||||||
|
cat > /tmp/p-worker.json <<P
|
||||||
|
{"Version":"2012-10-17","Statement":[
|
||||||
|
{"Effect":"Allow","Action":["s3:GetObject","s3:DeleteObject"],"Resource":["$B/staging/*"]},
|
||||||
|
{"Effect":"Allow","Action":["s3:PutObject","s3:AbortMultipartUpload","s3:ListMultipartUploadParts"],"Resource":["$B/attachments/*"]}]}
|
||||||
|
P
|
||||||
|
cat > /tmp/p-sweeper.json <<P
|
||||||
|
{"Version":"2012-10-17","Statement":[
|
||||||
|
{"Effect":"Allow","Action":["s3:ListBucket","s3:GetBucketLocation"],"Resource":["$B"]},
|
||||||
|
{"Effect":"Allow","Action":["s3:GetObject","s3:DeleteObject"],"Resource":["$B/attachments/*","$B/staging/*"]}]}
|
||||||
|
P
|
||||||
|
for r in api worker sweeper; do
|
||||||
|
key="svc-$r"; [ "$key" != "$RU" ] || { echo "service key must differ from root" >&2; exit 1; }
|
||||||
|
mc admin policy remove local "messenger-$r" --force >/dev/null 2>&1 || true
|
||||||
|
mc admin policy create local "messenger-$r" "/tmp/p-$r.json"
|
||||||
|
mc admin user add local "$key" "$(cat /run/secrets/s3_${r}_secret)" # idempotent: re-running = secret rotation
|
||||||
|
out=$(mc admin policy attach local "messenger-$r" --user "$key" 2>&1) || { echo "$out" | grep -qi already || { echo "$out" >&2; exit 1; }; }
|
||||||
|
done
|
||||||
|
echo "PASS: bucket $S3_BUCKET private; users svc-api, svc-worker, svc-sweeper with separate policies"
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
stream_over_http_enabled: true
|
||||||
|
server:
|
||||||
|
http_listen_port: 3200
|
||||||
|
grpc_listen_address: 127.0.0.1 # internal gRPC (querier/ingester inside the single binary) is loopback only
|
||||||
|
http_tls_config:
|
||||||
|
cert_file: /pki/tls.crt
|
||||||
|
key_file: /pki/tls.key
|
||||||
|
client_ca_file: /pki/ca.crt
|
||||||
|
client_auth_type: RequireAndVerifyClientCert
|
||||||
|
distributor:
|
||||||
|
receivers:
|
||||||
|
otlp:
|
||||||
|
protocols:
|
||||||
|
grpc:
|
||||||
|
endpoint: 0.0.0.0:4317
|
||||||
|
tls:
|
||||||
|
cert_file: /pki/tls.crt
|
||||||
|
key_file: /pki/tls.key
|
||||||
|
client_ca_file: /pki/ca.crt # collector -> tempo is mTLS
|
||||||
|
ingester: {max_block_duration: 5m}
|
||||||
|
storage:
|
||||||
|
trace:
|
||||||
|
backend: local
|
||||||
|
wal: {path: /var/tempo/wal}
|
||||||
|
local: {path: /var/tempo/blocks}
|
||||||
|
usage_report: {reporting_enabled: false}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
CREATE TABLE IF NOT EXISTS users (
|
||||||
|
id UUID PRIMARY KEY,
|
||||||
|
username VARCHAR(32) NOT NULL UNIQUE,
|
||||||
|
display_name VARCHAR(100) NOT NULL,
|
||||||
|
password_hash TEXT NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9_]{3,32}$'),
|
||||||
|
CONSTRAINT users_display_name_nonblank CHECK (length(btrim(display_name)) > 0)
|
||||||
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS chats (
|
||||||
|
id UUID PRIMARY KEY,
|
||||||
|
title VARCHAR(100) NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
CONSTRAINT chats_title_nonblank CHECK (length(btrim(title)) > 0)
|
||||||
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS chat_members (
|
||||||
|
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||||
|
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
position INTEGER NOT NULL DEFAULT 0,
|
||||||
|
PRIMARY KEY (chat_id, user_id)
|
||||||
|
);
|
||||||
|
ALTER TABLE chat_members ADD COLUMN IF NOT EXISTS position INTEGER NOT NULL DEFAULT 0;
|
||||||
|
CREATE INDEX IF NOT EXISTS chat_members_user_chat_idx 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) ON DELETE CASCADE,
|
||||||
|
sender_id UUID NOT NULL REFERENCES users(id),
|
||||||
|
text VARCHAR(4000) NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
CONSTRAINT messages_text_nonblank CHECK (length(btrim(text)) > 0)
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS messages_chat_created_id_idx ON messages(chat_id, created_at, id);
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
CREATE TABLE IF NOT EXISTS idempotency_records (
|
||||||
|
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||||
|
idempotency_key VARCHAR(128) NOT NULL,
|
||||||
|
request_hash CHAR(64) NOT NULL,
|
||||||
|
response_body JSONB NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
PRIMARY KEY (user_id, chat_id, idempotency_key),
|
||||||
|
CONSTRAINT idempotency_key_format CHECK (idempotency_key ~ '^[A-Za-z0-9._:-]{1,128}$')
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idempotency_records_created_at_idx ON idempotency_records(created_at);
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
CREATE TABLE IF NOT EXISTS attachments (
|
||||||
|
id UUID PRIMARY KEY,
|
||||||
|
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||||
|
owner_id UUID NOT NULL REFERENCES users(id),
|
||||||
|
filename VARCHAR(255) NOT NULL,
|
||||||
|
content_type TEXT NOT NULL,
|
||||||
|
size_bytes BIGINT NOT NULL,
|
||||||
|
sha256 CHAR(64) NOT NULL,
|
||||||
|
s3_key TEXT NOT NULL UNIQUE,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
CONSTRAINT attachments_filename_nonblank CHECK (length(btrim(filename)) > 0),
|
||||||
|
CONSTRAINT attachments_content_type CHECK (content_type IN ('image/png', 'image/jpeg')),
|
||||||
|
CONSTRAINT attachments_size CHECK (size_bytes BETWEEN 1 AND 10485760),
|
||||||
|
CONSTRAINT attachments_sha256 CHECK (sha256 ~ '^[a-f0-9]{64}$')
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS attachments_chat_idx ON attachments(chat_id);
|
||||||
|
CREATE TABLE IF NOT EXISTS message_attachments (
|
||||||
|
message_id UUID NOT NULL REFERENCES messages(id) ON DELETE CASCADE,
|
||||||
|
attachment_id UUID NOT NULL REFERENCES attachments(id),
|
||||||
|
position INTEGER NOT NULL,
|
||||||
|
PRIMARY KEY (message_id, attachment_id)
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS message_attachments_attachment_idx ON message_attachments(attachment_id);
|
||||||
|
ALTER TABLE messages DROP CONSTRAINT IF EXISTS messages_text_nonblank;
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
ALTER TABLE attachments ADD COLUMN IF NOT EXISTS status TEXT NOT NULL DEFAULT 'ready';
|
||||||
|
ALTER TABLE attachments ADD COLUMN IF NOT EXISTS error_code TEXT;
|
||||||
|
ALTER TABLE attachments ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT now();
|
||||||
|
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;
|
||||||
|
ALTER TABLE attachments DROP CONSTRAINT IF EXISTS attachments_status;
|
||||||
|
ALTER TABLE attachments ADD CONSTRAINT attachments_status CHECK (status IN ('queued', 'processing', 'ready', 'failed'));
|
||||||
|
CREATE INDEX IF NOT EXISTS attachments_staging_idx ON attachments(staging_key) WHERE staging_key IS NOT NULL;
|
||||||
|
CREATE TABLE IF NOT EXISTS attachment_variants (
|
||||||
|
attachment_id UUID NOT NULL REFERENCES attachments(id) ON DELETE CASCADE,
|
||||||
|
pipeline_version INTEGER NOT NULL,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
s3_key TEXT NOT NULL,
|
||||||
|
content_type TEXT NOT NULL,
|
||||||
|
size_bytes BIGINT NOT NULL,
|
||||||
|
width INTEGER NOT NULL,
|
||||||
|
height INTEGER NOT NULL,
|
||||||
|
sha256 CHAR(64) NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
PRIMARY KEY (attachment_id, pipeline_version, name),
|
||||||
|
CONSTRAINT variants_name CHECK (name IN ('thumbnail', 'crop', 'optimized'))
|
||||||
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS attachment_jobs (
|
||||||
|
job_id UUID PRIMARY KEY,
|
||||||
|
attachment_id UUID NOT NULL REFERENCES attachments(id) ON DELETE CASCADE,
|
||||||
|
pipeline_version INTEGER NOT NULL DEFAULT 1,
|
||||||
|
status TEXT NOT NULL,
|
||||||
|
attempt INTEGER NOT NULL DEFAULT 0,
|
||||||
|
max_attempts INTEGER NOT NULL,
|
||||||
|
next_attempt_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
lease_until TIMESTAMPTZ,
|
||||||
|
worker_id TEXT,
|
||||||
|
error_code TEXT,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
CONSTRAINT jobs_status CHECK (status IN ('queued', 'processing', 'ready', 'failed')),
|
||||||
|
CONSTRAINT jobs_effect_key UNIQUE (attachment_id, pipeline_version)
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS attachment_jobs_status_idx ON attachment_jobs(status, lease_until);
|
||||||
|
CREATE TABLE IF NOT EXISTS job_events (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
job_id UUID NOT NULL REFERENCES attachment_jobs(job_id) ON DELETE CASCADE,
|
||||||
|
at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
event TEXT NOT NULL,
|
||||||
|
detail TEXT
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS job_events_job_idx ON job_events(job_id, id);
|
||||||
|
CREATE TABLE IF NOT EXISTS outbox (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
job_id UUID NOT NULL REFERENCES attachment_jobs(job_id) ON DELETE CASCADE,
|
||||||
|
topic TEXT NOT NULL,
|
||||||
|
msg_key TEXT NOT NULL,
|
||||||
|
payload JSONB NOT NULL,
|
||||||
|
available_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||||
|
published_at TIMESTAMPTZ
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS outbox_pending_idx ON outbox(available_at, id) WHERE published_at IS NULL;
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
fastapi==0.116.1
|
||||||
|
uvicorn[standard]==0.35.0
|
||||||
|
psycopg[pool,binary]==3.2.9
|
||||||
|
argon2-cffi==25.1.0
|
||||||
|
redis==6.4.0
|
||||||
|
boto3==1.40.20
|
||||||
|
Pillow==11.3.0
|
||||||
|
confluent-kafka==2.10.1
|
||||||
|
opentelemetry-api==1.45.1
|
||||||
|
opentelemetry-sdk==1.45.1
|
||||||
|
opentelemetry-exporter-otlp-proto-http==1.45.1
|
||||||
|
opentelemetry-instrumentation-fastapi==0.66b1
|
||||||
|
opentelemetry-instrumentation-psycopg==0.66b1
|
||||||
|
opentelemetry-instrumentation-botocore==0.66b1
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
# Runbook: HighApiErrorRate (5xx > 5 % за 2 мин, держится 1 мин)
|
||||||
|
|
||||||
|
**Что значит.** Доля 5xx среди бизнес-запросов API выше 5 %. 4xx (неверный пароль, чужой чат) сюда не входят.
|
||||||
|
|
||||||
|
1. Grafana → дашборд *Messenger: observability* → панели *API 5xx error ratio* и *API RPS by route*: какие маршруты и какая реплика (`service_instance_id`).
|
||||||
|
2. Панель *DB pool used / waiting*: `waiting > 0` и `used = max` — упёрлись в пул/медленную БД. Нули — проблема не в пуле.
|
||||||
|
3. Логи: Explore → Loki → `{service_name="messenger-api"} | event=~"db_error|db_pool_timeout|s3_error|session_store_error|unhandled_exception"`. Поле `event` сразу называет зависимость; `reason` — тип исключения.
|
||||||
|
4. Трасса: из строки лога по `trace_id` (Derived field *Open trace*) открыть трассу. Смотреть **длинный дочерний span**:
|
||||||
|
- длинный `INSERT/SELECT` (psycopg span) → медленная/заблокированная БД (статус ERROR после `statement_timeout`);
|
||||||
|
- длинный `S3.PutObject` → хранилище объектов;
|
||||||
|
- пустое время между спанами внутри server span → медленный Python-код handler'а, а не зависимость.
|
||||||
|
5. Подтвердить на стороне БД: `docker compose exec postgres psql -U messenger -c "select pid,state,wait_event_type,left(query,60) from pg_stat_activity where state<>'idle'"`.
|
||||||
|
6. Устранить причину (снять блокировку, восстановить зависимость). Алерт перейдёт в *resolved*, когда окно 2 мин очистится от ошибок.
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
# Runbook: QueueLagGrowing (самая старая ожидающая job > 30 с, держится 1 мин)
|
||||||
|
|
||||||
|
**Что значит.** Задачи ждут worker'а: backlog растёт. Это не время обработки (оно в `messenger_job_duration_seconds`).
|
||||||
|
|
||||||
|
1. Панели *Queue depth* и *Oldest waiting job age*: растут оба — worker'ы не разбирают очередь.
|
||||||
|
2. Панель *Worker busy vs capacity*: серия `busy` отсутствует/0 при росте очереди → worker остановлен или не подключён к Kafka; `busy = capacity` → worker перегружен (медленные задачи, см. *Worker job duration p95*).
|
||||||
|
3. `docker compose ps worker dispatcher kafka` и логи: `{service_name="messenger-worker"} | event=~"worker_started|job_attempt_failed|job_lease_lost"`.
|
||||||
|
4. Если растёт `retry`/`failed` в панели *Jobs by outcome* → причина в логе `job_attempt_failed` (`reason`), трасса задачи: `{service_name="messenger-worker"} | event="job_attempt_failed"` → `trace_id` → span `job.pipeline`/`s3.*`.
|
||||||
|
5. Если очередь растёт, а worker жив и свободен → проверить dispatcher (`event="outbox_publish_unconfirmed"`) и Kafka: сообщения не доходят до топика.
|
||||||
|
6. Устранить причину (`docker compose up -d worker`). Backlog уменьшается, алерт переходит в *resolved*.
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Measure Argon2id cost on THIS stand and derive the login-DoS budget. Usage (inside the app image or any venv with argon2-cffi):
|
||||||
|
python scripts/argon2_bench.py [--runs 20]
|
||||||
|
Budget = concurrency limit (ARGON2_CONCURRENCY per replica) x single-hash time: with c slots one replica can verify at most c / t logins per second;
|
||||||
|
the shared Redis rate limit (30 attempts/min/IP, 10 failures/min/user) keeps the attacker far below that."""
|
||||||
|
import argparse, statistics, time
|
||||||
|
from argon2 import PasswordHasher, Type
|
||||||
|
|
||||||
|
ap = argparse.ArgumentParser(); ap.add_argument("--runs", type=int, default=20); a = ap.parse_args()
|
||||||
|
for m, t, p in ((19456, 2, 1), (47104, 1, 1), (65536, 3, 4)):
|
||||||
|
ph = PasswordHasher(time_cost=t, memory_cost=m, parallelism=p, type=Type.ID)
|
||||||
|
h = ph.hash("benchmark-password"); xs = []
|
||||||
|
for _ in range(a.runs):
|
||||||
|
s = time.perf_counter(); ph.verify(h, "benchmark-password"); xs.append(time.perf_counter() - s)
|
||||||
|
xs.sort()
|
||||||
|
print(f"m={m//1024} MiB t={t} p={p}: median {statistics.median(xs)*1000:.0f} ms, p95 {xs[int(.95*len(xs))-1]*1000:.0f} ms, max logins/s per slot {1/statistics.median(xs):.1f}")
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# Operator step (idempotent): KV v2 mount, AppRole auth, one policy + one role per service, initial secrets from ./secrets/ops.
|
||||||
|
# AppRole: token_ttl 10m / max 30m, SecretID TTL 24h (re-issued by scripts/bao_secret_id.sh). RoleID is not a secret.
|
||||||
|
set -eu
|
||||||
|
cd "$(dirname "$0")/.."; . scripts/bao_lib.sh; load_root
|
||||||
|
baoc secrets list -format=json | grep -q "\"kv/\"" || baoc secrets enable -path=kv -version=2 kv >/dev/null
|
||||||
|
baoc auth list -format=json | grep -q "\"approle/\"" || baoc auth enable approle >/dev/null
|
||||||
|
for r in api worker dispatcher sweeper; do
|
||||||
|
baoc policy write "$r" - < "infra/openbao/policies/$r.hcl" >/dev/null
|
||||||
|
baoc write "auth/approle/role/$r" token_policies="$r" token_ttl=10m token_max_ttl=30m secret_id_ttl=24h secret_id_num_uses=0 >/dev/null
|
||||||
|
mkdir -p "$S/approle/$r"
|
||||||
|
baoc read -field=role_id "auth/approle/role/$r/role-id" > "$S/approle/$r/role_id"
|
||||||
|
chmod 644 "$S/approle/$r/role_id"
|
||||||
|
done
|
||||||
|
O="$S/ops"
|
||||||
|
python3 - "$O" <<"PY" | while IFS=" " read -r path json; do printf "%s" "$json" | baoc kv put "kv/$path" - >/dev/null; done
|
||||||
|
import json, sys
|
||||||
|
o = sys.argv[1]; r = lambda n: open(f"{o}/{n}").read().strip()
|
||||||
|
data = {
|
||||||
|
"api": {"db_password": r("db_api_password"), "redis_password": r("redis_api_password"), "s3_access_key": "svc-api", "s3_secret_key": r("s3_api_secret")},
|
||||||
|
"worker": {"db_password": r("db_worker_password"), "s3_access_key": "svc-worker", "s3_secret_key": r("s3_worker_secret")},
|
||||||
|
"dispatcher": {"db_password": r("db_dispatcher_password")},
|
||||||
|
"sweeper": {"db_password": r("db_sweeper_password"), "s3_access_key": "svc-sweeper", "s3_secret_key": r("s3_sweeper_secret")},
|
||||||
|
}
|
||||||
|
for p, d in data.items(): print(p + "\t" + json.dumps(d))
|
||||||
|
PY
|
||||||
|
echo "OpenBao bootstrapped: kv/, approle, policies and roles for api worker dispatcher sweeper"
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# ONE-TIME operator step: initialise OpenBao (3 key shares, threshold 2). Shares and root token go to ./secrets/operator
|
||||||
|
# as separate 0600 files: the operator is expected to move shares to different custodians. Nothing is printed.
|
||||||
|
set -eu
|
||||||
|
cd "$(dirname "$0")/.."; . scripts/bao_lib.sh
|
||||||
|
umask 077; mkdir -p "$OPD"
|
||||||
|
if baoc status -format=json 2>/dev/null | grep -q "\"initialized\": true"; then echo "OpenBao already initialised"; exit 0; fi
|
||||||
|
baoc operator init -key-shares=3 -key-threshold=2 -format=json > "$OPD/init.json"
|
||||||
|
python3 - "$OPD" <<"PY"
|
||||||
|
import json, os, sys
|
||||||
|
d = sys.argv[1]; j = json.load(open(d + "/init.json"))
|
||||||
|
for i, k in enumerate(j["unseal_keys_b64"], 1):
|
||||||
|
open(f"{d}/unseal-{i}", "w").write(k)
|
||||||
|
open(d + "/root_token", "w").write(j["root_token"])
|
||||||
|
os.remove(d + "/init.json")
|
||||||
|
PY
|
||||||
|
echo "initialised: unseal-1..3 and root_token written to $OPD (keep them OUT of Git and OUT of the stand)"
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# Shared helpers for operator scripts. The root token lives only in ./secrets/operator (0600, outside Git, outside any image/volume).
|
||||||
|
S="${SECRETS_DIR:-secrets}"; OPD="$S/operator"
|
||||||
|
# baoc <args...>: run the bao CLI. BAO_LOCAL=1 uses a host binary; default is `docker compose exec` into the openbao container.
|
||||||
|
baoc() {
|
||||||
|
if [ -n "${BAO_LOCAL:-}" ]; then
|
||||||
|
BAO_ADDR="${BAO_LOCAL_ADDR:-https://localhost:8200}" BAO_CACERT="$S/pki/ca/ca.crt" BAO_TOKEN="${BAO_TOKEN_VALUE:-}" "${BAO_BIN:-bao}" "$@"
|
||||||
|
else
|
||||||
|
docker compose exec -T -e BAO_ADDR=https://openbao:8200 -e BAO_CACERT=/run/pki/ca.crt -e BAO_TOKEN="${BAO_TOKEN_VALUE:-}" openbao bao "$@"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
load_root() { [ -f "$OPD/root_token" ] || { echo "no operator root token: run scripts/bao_init.sh" >&2; exit 1; }; BAO_TOKEN_VALUE="$(cat "$OPD/root_token")"; }
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# Issue a fresh short-lived SecretID (24 h) into ./secrets/approle/<role>/secret_id. Usage: bao_secret_id.sh <role|all>
|
||||||
|
set -eu
|
||||||
|
cd "$(dirname "$0")/.."; . scripts/bao_lib.sh; load_root
|
||||||
|
roles="${1:-all}"; [ "$roles" = all ] && roles="api worker dispatcher sweeper"
|
||||||
|
for r in $roles; do
|
||||||
|
mkdir -p "$S/approle/$r"
|
||||||
|
baoc write -f -field=secret_id "auth/approle/role/$r/secret-id" > "$S/approle/$r/secret_id.new"
|
||||||
|
chmod 644 "$S/approle/$r/secret_id.new"; mv -f "$S/approle/$r/secret_id.new" "$S/approle/$r/secret_id"
|
||||||
|
echo "secret_id issued for $r"
|
||||||
|
done
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# Operator step after EVERY OpenBao restart (the vault starts sealed). Needs any 2 of the 3 shares.
|
||||||
|
set -eu
|
||||||
|
cd "$(dirname "$0")/.."; . scripts/bao_lib.sh
|
||||||
|
for i in 1 2 3; do
|
||||||
|
baoc status -format=json 2>/dev/null | grep -q "\"sealed\": false" && { echo "OpenBao unsealed"; exit 0; }
|
||||||
|
[ -f "$OPD/unseal-$i" ] && baoc operator unseal "$(cat "$OPD/unseal-$i")" >/dev/null
|
||||||
|
done
|
||||||
|
baoc status -format=json 2>/dev/null | grep -q "\"sealed\": false" && echo "OpenBao unsealed" || { echo "still sealed: need 2 shares" >&2; exit 1; }
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# Operator bootstrap, idempotent, nothing printed: local PKI, random service passwords, Redis ACL file, .env. All under ./secrets (0700, ignored by Git).
|
||||||
|
set -eu
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
S="${SECRETS_DIR:-secrets}"; O="$S/ops"
|
||||||
|
umask 077; mkdir -p "$O"; chmod 700 "$S"
|
||||||
|
gen() { [ -s "$O/$1" ] || { openssl rand -base64 36 | tr -d '/+=\n' | cut -c1-32 > "$O/$1"; }; }
|
||||||
|
for n in postgres_password db_api_password db_worker_password db_dispatcher_password db_sweeper_password \
|
||||||
|
redis_api_password redis_health_password s3_root_password s3_api_secret s3_worker_secret s3_sweeper_secret grafana_admin_password kafka_ssl_password; do gen "$n"; done
|
||||||
|
sh scripts/pki.sh init
|
||||||
|
[ -s "$O/s3_root_user" ] || printf 'root-%s' "$(openssl rand -hex 4)" > "$O/s3_root_user"
|
||||||
|
h() { printf %s "$(cat "$O/$1")" | sha256sum | cut -d' ' -f1; }
|
||||||
|
cat > "$O/redis_users.acl" <<ACL
|
||||||
|
user default off
|
||||||
|
user api on #$(h redis_api_password) ~session:* ~rl:* resetchannels -@all +get +set +setex +del +incr +incrby +expire +ttl +ping +multi +exec +client|setinfo
|
||||||
|
user health on #$(h redis_health_password) resetkeys resetchannels -@all +ping
|
||||||
|
ACL
|
||||||
|
chmod 644 "$O"/* # ./secrets is 0700: only the operator can enter; containers run as other uids and mount single files read-only
|
||||||
|
[ -f .env ] || { cp .env.example .env; }
|
||||||
|
echo "bootstrap done (PKI, passwords, Redis ACL). Next: scripts/up.sh"
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Lab 7: separate least-privilege PostgreSQL roles (idempotent; run by the one-shot `migrate` service as the owner role, after migrations).
|
||||||
|
|
||||||
|
Passwords are read from the operator files mounted at /run/secrets (the same values the operator loaded into OpenBao).
|
||||||
|
python scripts/db_roles.py create/update roles, grants and passwords
|
||||||
|
python scripts/db_roles.py --terminate ROLE additionally kill live sessions of ROLE (credential rotation / revocation)
|
||||||
|
The API role has no DDL, the worker cannot touch users/messages/sessions, the dispatcher cannot touch attachments metadata beyond job state.
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
|
||||||
|
import psycopg
|
||||||
|
from psycopg import sql
|
||||||
|
|
||||||
|
SECRETS = os.getenv("OPS_SECRETS_DIR", "/run/secrets")
|
||||||
|
# role -> {table: privileges}. Anything not listed is denied (public schema CREATE is revoked, PUBLIC has no table rights).
|
||||||
|
GRANTS = {
|
||||||
|
"messenger_api": {
|
||||||
|
"users": "SELECT, INSERT, UPDATE", "chats": "SELECT, INSERT", "chat_members": "SELECT, INSERT", "messages": "SELECT, INSERT",
|
||||||
|
"idempotency_records": "SELECT, INSERT, DELETE", "attachments": "SELECT, INSERT, UPDATE", "message_attachments": "SELECT, INSERT",
|
||||||
|
"attachment_variants": "SELECT", "attachment_jobs": "SELECT, INSERT", "job_events": "SELECT, INSERT", "outbox": "SELECT, INSERT",
|
||||||
|
},
|
||||||
|
"messenger_worker": {
|
||||||
|
"attachment_jobs": "SELECT, UPDATE", "attachments": "SELECT, UPDATE", "attachment_variants": "SELECT, INSERT",
|
||||||
|
"job_events": "INSERT", "outbox": "INSERT",
|
||||||
|
},
|
||||||
|
"messenger_dispatcher": {
|
||||||
|
"outbox": "SELECT, INSERT, UPDATE", "attachment_jobs": "SELECT, UPDATE", "attachments": "SELECT, UPDATE", "job_events": "INSERT",
|
||||||
|
},
|
||||||
|
"messenger_sweeper": {"attachments": "SELECT, UPDATE"},
|
||||||
|
}
|
||||||
|
PASSWORD_FILES = {"messenger_api": "db_api_password", "messenger_worker": "db_worker_password",
|
||||||
|
"messenger_dispatcher": "db_dispatcher_password", "messenger_sweeper": "db_sweeper_password"}
|
||||||
|
SEQUENCES = {"messenger_api": ["job_events_id_seq", "outbox_id_seq"], "messenger_worker": ["job_events_id_seq", "outbox_id_seq"],
|
||||||
|
"messenger_dispatcher": ["job_events_id_seq", "outbox_id_seq"], "messenger_sweeper": []}
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
terminate = sys.argv[sys.argv.index("--terminate") + 1] if "--terminate" in sys.argv else None
|
||||||
|
last = None
|
||||||
|
for _ in range(30):
|
||||||
|
try:
|
||||||
|
conn = psycopg.connect(connect_timeout=3, autocommit=True)
|
||||||
|
break
|
||||||
|
except psycopg.Error as exc:
|
||||||
|
last = exc
|
||||||
|
time.sleep(1)
|
||||||
|
else:
|
||||||
|
raise SystemExit(f"db_roles: database unavailable: {type(last).__name__}")
|
||||||
|
with conn:
|
||||||
|
db = os.environ["PGDATABASE"]
|
||||||
|
conn.execute(sql.SQL("REVOKE ALL ON DATABASE {} FROM PUBLIC").format(sql.Identifier(db)))
|
||||||
|
conn.execute("REVOKE CREATE ON SCHEMA public FROM PUBLIC")
|
||||||
|
conn.execute("REVOKE ALL ON ALL TABLES IN SCHEMA public FROM PUBLIC")
|
||||||
|
for role, tables in GRANTS.items():
|
||||||
|
password = open(os.path.join(SECRETS, PASSWORD_FILES[role]), encoding="utf-8").read().strip()
|
||||||
|
if conn.execute("SELECT 1 FROM pg_roles WHERE rolname=%s", (role,)).fetchone() is None:
|
||||||
|
conn.execute(sql.SQL("CREATE ROLE {} LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT CONNECTION LIMIT 40").format(sql.Identifier(role)))
|
||||||
|
conn.execute(sql.SQL("ALTER ROLE {} PASSWORD {}").format(sql.Identifier(role), sql.Literal(password)))
|
||||||
|
conn.execute(sql.SQL("GRANT CONNECT ON DATABASE {} TO {}").format(sql.Identifier(db), sql.Identifier(role)))
|
||||||
|
conn.execute(sql.SQL("GRANT USAGE ON SCHEMA public TO {}").format(sql.Identifier(role)))
|
||||||
|
conn.execute(sql.SQL("REVOKE ALL ON ALL TABLES IN SCHEMA public FROM {}").format(sql.Identifier(role)))
|
||||||
|
for table, privs in tables.items():
|
||||||
|
conn.execute(sql.SQL("GRANT {} ON {} TO {}").format(sql.SQL(privs), sql.Identifier(table), sql.Identifier(role)))
|
||||||
|
for seq in SEQUENCES[role]:
|
||||||
|
conn.execute(sql.SQL("GRANT USAGE ON SEQUENCE {} TO {}").format(sql.Identifier(seq), sql.Identifier(role)))
|
||||||
|
print(f"role {role}: {len(tables)} tables granted", flush=True)
|
||||||
|
if terminate:
|
||||||
|
n = conn.execute("SELECT count(pg_terminate_backend(pid)) FROM pg_stat_activity WHERE usename=%s", (terminate,)).fetchone()[0]
|
||||||
|
print(f"terminated {n} sessions of {terminate}", flush=True)
|
||||||
|
print("PASS: database roles ready", flush=True)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# Track 1 incident response for a compromised worker (isolated lab stand). Order matters:
|
||||||
|
# 0 keep the OLD credentials (only to prove later that they are dead) 1 stop the worker (jobs stay in Kafka/PostgreSQL)
|
||||||
|
# 2 revoke AppRole 3 rotate DB + S3 secrets (live sessions killed) 4 new worker certificate 5 fresh SecretID, start worker
|
||||||
|
# 6 NEW connections with the old credentials must fail, with the new ones must work (security-tests/revoked_creds.py)
|
||||||
|
set -eu
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
S="${SECRETS_DIR:-secrets}"; OLD="$S/incident-old"
|
||||||
|
mkdir -p evidence; rm -rf "$OLD"; umask 077; mkdir -p "$OLD"; umask 022
|
||||||
|
cp "$S/approle/worker/secret_id" "$OLD/secret_id"
|
||||||
|
cp "$S/ops/db_worker_password" "$OLD/db_password"
|
||||||
|
cp "$S/ops/s3_worker_secret" "$OLD/s3_secret"
|
||||||
|
chmod 644 "$OLD"/*
|
||||||
|
date -u +%FT%TZ > evidence/incident-start.txt
|
||||||
|
docker compose stop worker
|
||||||
|
sh scripts/revoke_identity.sh worker
|
||||||
|
sh scripts/rotate_secret.sh db-worker
|
||||||
|
sh scripts/rotate_secret.sh s3-worker
|
||||||
|
sh scripts/pki.sh leaf worker
|
||||||
|
sh scripts/bao_secret_id.sh worker
|
||||||
|
docker compose up -d --no-deps worker
|
||||||
|
date -u +%FT%TZ > evidence/incident-end.txt
|
||||||
|
# step 6: fresh connections, public CA only; the saved old secrets are removed afterwards (also on failure)
|
||||||
|
rc=0
|
||||||
|
docker run --rm --network mtusi-lab7_backend --user 10001:10001 --read-only --cap-drop ALL --security-opt no-new-privileges:true \
|
||||||
|
-v "$PWD/security-tests:/t:ro" -v "$PWD/$S/pki/ca:/pki/ca:ro" -v "$PWD/$OLD:/old:ro" -v "$PWD/$S/approle/worker:/approle:ro" \
|
||||||
|
--entrypoint python mtusi-lab7-app:1.0.0 /t/revoked_creds.py | tee evidence/revoked-creds.txt || rc=$?
|
||||||
|
rm -rf "$OLD"
|
||||||
|
[ "$rc" -eq 0 ] || { echo "revocation check FAILED" >&2; exit "$rc"; }
|
||||||
|
echo "worker recovered; old credentials are dead on new connections (evidence/revoked-creds.txt)"
|
||||||
|
echo "also run: security-tests/run_in_net.sh worker_compromise.py --profile after"
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Apply SQL migrations once, before any API replica is started."""
|
||||||
|
from pathlib import Path
|
||||||
|
import os
|
||||||
|
import time
|
||||||
|
import psycopg
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
CONNINFO = os.getenv("DATABASE_URL", "")
|
||||||
|
|
||||||
|
def main():
|
||||||
|
last_error = None
|
||||||
|
for _ in range(30):
|
||||||
|
try:
|
||||||
|
with psycopg.connect(CONNINFO, connect_timeout=3) as conn:
|
||||||
|
conn.execute("CREATE TABLE IF NOT EXISTS schema_migrations (version TEXT PRIMARY KEY, applied_at TIMESTAMPTZ NOT NULL DEFAULT now())")
|
||||||
|
conn.commit()
|
||||||
|
for path in sorted((ROOT / "migrations").glob("*.sql")):
|
||||||
|
version = path.name
|
||||||
|
if conn.execute("SELECT 1 FROM schema_migrations WHERE version=%s", (version,)).fetchone():
|
||||||
|
continue
|
||||||
|
sql = path.read_text(encoding="utf-8")
|
||||||
|
with conn.transaction():
|
||||||
|
for statement in sql.split(";"):
|
||||||
|
if statement.strip():
|
||||||
|
conn.execute(statement)
|
||||||
|
conn.execute("INSERT INTO schema_migrations(version) VALUES (%s)", (version,))
|
||||||
|
print(f"APPLIED {version}", flush=True)
|
||||||
|
print("PASS: migrations complete", flush=True)
|
||||||
|
return
|
||||||
|
except Exception as exc:
|
||||||
|
last_error = exc
|
||||||
|
time.sleep(1)
|
||||||
|
raise SystemExit(f"Migration failed after retries: {type(last_error).__name__}")
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# Local PKI for the lab stand. Operator-run, outside Git: everything is written under ./secrets (ignored by Git).
|
||||||
|
# scripts/pki.sh init create root CA, workload CA and all leaf identities (idempotent: existing files are kept)
|
||||||
|
# scripts/pki.sh leaf <name> re-issue ONE leaf with a NEW key (rotation, no image rebuild); the old file is replaced atomically
|
||||||
|
# Identity model: root CA signs infrastructure leaves; intermediate "workload CA" signs application identities (api, worker, dispatcher, sweeper).
|
||||||
|
set -eu
|
||||||
|
umask 022
|
||||||
|
S="${SECRETS_DIR:-secrets}"; PKI="$S/pki"; CA="$PKI/ca"
|
||||||
|
INFRA_DAYS="${INFRA_DAYS:-90}"; WORKLOAD_DAYS="${WORKLOAD_DAYS:-14}"
|
||||||
|
|
||||||
|
mkca() {
|
||||||
|
[ -f "$CA/ca.crt" ] && return 0
|
||||||
|
mkdir -p "$CA"
|
||||||
|
openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -days 3650 -subj "/CN=mtusi-lab7-root-ca" \
|
||||||
|
-addext "basicConstraints=critical,CA:TRUE" -addext "keyUsage=critical,keyCertSign,cRLSign" -keyout "$CA/ca.key" -out "$CA/ca.crt" 2>/dev/null
|
||||||
|
chmod 600 "$CA/ca.key"
|
||||||
|
}
|
||||||
|
mkworkloadca() {
|
||||||
|
[ -f "$CA/workload-ca.crt" ] && return 0
|
||||||
|
openssl req -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -subj "/CN=mtusi-lab7-workload-ca" -keyout "$CA/workload-ca.key" -out "$CA/workload-ca.csr" 2>/dev/null
|
||||||
|
printf "basicConstraints=critical,CA:TRUE,pathlen:0\nkeyUsage=critical,keyCertSign,cRLSign\n" > "$CA/wl.ext"
|
||||||
|
openssl x509 -req -in "$CA/workload-ca.csr" -CA "$CA/ca.crt" -CAkey "$CA/ca.key" -set_serial "0x$(openssl rand -hex 8)" -days 1825 -extfile "$CA/wl.ext" -out "$CA/workload-ca.crt" 2>/dev/null
|
||||||
|
chmod 600 "$CA/workload-ca.key"
|
||||||
|
}
|
||||||
|
# issue <name> <root|workload> <subjectAltName list> <days>
|
||||||
|
issue() {
|
||||||
|
name="$1"; signer="$2"; sans="$3"; days="$4"; d="$PKI/$name"; tmp="$PKI/.tmp-$name"
|
||||||
|
rm -rf "$tmp"; mkdir -p "$tmp"
|
||||||
|
openssl req -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -subj "/CN=$name" -keyout "$tmp/tls.key" -out "$tmp/tls.csr" 2>/dev/null
|
||||||
|
printf "basicConstraints=CA:FALSE\nkeyUsage=critical,digitalSignature\nextendedKeyUsage=serverAuth,clientAuth\nsubjectAltName=%s\n" "$sans" > "$tmp/ext"
|
||||||
|
if [ "$signer" = workload ]; then ca=workload-ca; else ca=ca; fi
|
||||||
|
openssl x509 -req -in "$tmp/tls.csr" -CA "$CA/$ca.crt" -CAkey "$CA/$ca.key" -set_serial "0x$(openssl rand -hex 8)" -days "$days" -extfile "$tmp/ext" -out "$tmp/leaf.crt" 2>/dev/null
|
||||||
|
if [ "$signer" = workload ]; then cat "$tmp/leaf.crt" "$CA/workload-ca.crt" > "$tmp/tls.crt"; else cp "$tmp/leaf.crt" "$tmp/tls.crt"; fi
|
||||||
|
cp "$CA/ca.crt" "$tmp/ca.crt"
|
||||||
|
cat "$tmp/tls.key" "$tmp/tls.crt" > "$tmp/keystore.pem" # key first: HAProxy "crt" and Kafka PEM keystore format
|
||||||
|
openssl pkcs12 -export -in "$tmp/tls.crt" -inkey "$tmp/tls.key" -out "$tmp/keystore.p12" -passout "file:$S/ops/kafka_ssl_password" 2>/dev/null
|
||||||
|
openssl pkcs12 -export -nokeys -in "$CA/ca.crt" -out "$tmp/truststore.p12" -passout "file:$S/ops/kafka_ssl_password" 2>/dev/null
|
||||||
|
rm -f "$tmp/tls.csr" "$tmp/ext" "$tmp/leaf.crt"
|
||||||
|
chmod 644 "$tmp"/* # ./secrets itself is 0700; containers run as other uids
|
||||||
|
mkdir -p "$d"; mv -f "$tmp"/* "$d"/; rmdir "$tmp"
|
||||||
|
echo "issued $name ($signer CA, $days d)"
|
||||||
|
}
|
||||||
|
spec() { # name signer SANs -- the single source of truth for identities
|
||||||
|
cat <<EOF2
|
||||||
|
lb-public root DNS:localhost,IP:127.0.0.1
|
||||||
|
lb root DNS:lb
|
||||||
|
postgres root DNS:postgres
|
||||||
|
redis root DNS:redis
|
||||||
|
s3 root DNS:s3,DNS:localhost
|
||||||
|
kafka root DNS:kafka
|
||||||
|
kafka-admin root DNS:kafka-admin
|
||||||
|
otel-collector root DNS:otel-collector
|
||||||
|
prometheus root DNS:prometheus
|
||||||
|
loki root DNS:loki
|
||||||
|
tempo root DNS:tempo
|
||||||
|
grafana root DNS:grafana,DNS:localhost,IP:127.0.0.1
|
||||||
|
openbao root DNS:openbao,DNS:localhost,IP:127.0.0.1
|
||||||
|
api workload DNS:api
|
||||||
|
worker workload DNS:worker
|
||||||
|
dispatcher workload DNS:dispatcher
|
||||||
|
sweeper workload DNS:sweeper
|
||||||
|
EOF2
|
||||||
|
}
|
||||||
|
days_for() { if [ "$1" = workload ]; then echo "$WORKLOAD_DAYS"; else echo "$INFRA_DAYS"; fi; }
|
||||||
|
|
||||||
|
case "${1:-}" in
|
||||||
|
init)
|
||||||
|
umask 077; mkdir -p "$S" "$PKI"; umask 022; chmod 700 "$S"
|
||||||
|
mkca; mkworkloadca
|
||||||
|
spec | while read -r n s sans; do [ -f "$PKI/$n/tls.crt" ] || issue "$n" "$s" "$sans" "$(days_for "$s")"; done
|
||||||
|
# Negative-test identities (never mounted into the stand): same root CA but not allowed; and a foreign CA.
|
||||||
|
[ -f "$PKI/outsider/tls.crt" ] || issue outsider root DNS:outsider "$INFRA_DAYS"
|
||||||
|
if [ ! -f "$PKI/rogue/tls.crt" ]; then
|
||||||
|
mkdir -p "$PKI/rogue"
|
||||||
|
openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -days 30 -subj "/CN=rogue-ca" -keyout "$PKI/rogue/rogue-ca.key" -out "$PKI/rogue/rogue-ca.crt" 2>/dev/null
|
||||||
|
openssl req -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -subj "/CN=lb" -keyout "$PKI/rogue/tls.key" -out "$PKI/rogue/tls.csr" 2>/dev/null
|
||||||
|
printf "subjectAltName=DNS:lb\nextendedKeyUsage=clientAuth\n" > "$PKI/rogue/ext"
|
||||||
|
openssl x509 -req -in "$PKI/rogue/tls.csr" -CA "$PKI/rogue/rogue-ca.crt" -CAkey "$PKI/rogue/rogue-ca.key" -CAcreateserial -days 30 -extfile "$PKI/rogue/ext" -out "$PKI/rogue/tls.crt" 2>/dev/null
|
||||||
|
fi ;;
|
||||||
|
leaf)
|
||||||
|
n="${2:?usage: pki.sh leaf <name>}"
|
||||||
|
line="$(spec | awk -v n="$n" "\$1==n")"; [ -n "$line" ] || { echo "unknown identity $n" >&2; exit 1; }
|
||||||
|
set -- $line; issue "$1" "$2" "$3" "$(days_for "$2")" ;;
|
||||||
|
*) echo "usage: pki.sh init | leaf <name>" >&2; exit 2 ;;
|
||||||
|
esac
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Operator tool: failed-job registry and SAFE explicit replay (lab5, level 4).
|
||||||
|
|
||||||
|
docker compose exec worker python scripts/replay_failed.py --list
|
||||||
|
docker compose exec worker python scripts/replay_failed.py --job-id <uuid> --reason "ticket-123"
|
||||||
|
|
||||||
|
Replay never executes a duplicate of a successful job: it requires status=failed, that the staging source still exists,
|
||||||
|
and that the effect (all variants of the pipeline version) is NOT already present. Everything happens in ONE transaction
|
||||||
|
(state change + audit event + outbox row), so the new attempt is delivered by the normal dispatcher path.
|
||||||
|
"""
|
||||||
|
import argparse
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
import psycopg
|
||||||
|
|
||||||
|
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
|
from src import jobs # noqa: E402
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
p = argparse.ArgumentParser()
|
||||||
|
p.add_argument("--list", action="store_true")
|
||||||
|
p.add_argument("--job-id")
|
||||||
|
p.add_argument("--reason", default="operator replay")
|
||||||
|
a = p.parse_args()
|
||||||
|
with psycopg.connect(connect_timeout=5) as conn:
|
||||||
|
if a.list or not a.job_id:
|
||||||
|
for r in conn.execute("SELECT job_id, attachment_id, error_code, attempt, updated_at FROM attachment_jobs WHERE status='failed' ORDER BY updated_at"):
|
||||||
|
print(*r, sep="\t")
|
||||||
|
return 0
|
||||||
|
row = conn.execute("SELECT j.status, j.attachment_id, j.pipeline_version, a.staging_key FROM attachment_jobs j "
|
||||||
|
"JOIN attachments a ON a.id=j.attachment_id WHERE j.job_id=%s FOR UPDATE OF j", (a.job_id,)).fetchone()
|
||||||
|
if row is None:
|
||||||
|
print("REFUSED: unknown job"); return 1
|
||||||
|
status, att_id, pv, staging_key = row
|
||||||
|
if status != "failed":
|
||||||
|
print(f"REFUSED: job is {status}, only failed jobs can be replayed"); return 1
|
||||||
|
done = conn.execute("SELECT count(*) FROM attachment_variants WHERE attachment_id=%s AND pipeline_version=%s", (att_id, pv)).fetchone()[0]
|
||||||
|
if done >= len(jobs.VARIANT_ORDER):
|
||||||
|
print("REFUSED: the effect already exists (all variants present)"); return 1
|
||||||
|
if not staging_key:
|
||||||
|
print("REFUSED: staging source expired (retention), upload the file again"); return 1
|
||||||
|
conn.execute("UPDATE attachment_jobs SET status='queued', attempt=0, error_code=NULL, lease_until=NULL, next_attempt_at=now(), updated_at=now() WHERE job_id=%s", (a.job_id,))
|
||||||
|
conn.execute("UPDATE attachments SET status='queued', error_code=NULL, updated_at=now() WHERE id=%s", (att_id,))
|
||||||
|
jobs.add_event(conn, a.job_id, "replay", a.reason[:200])
|
||||||
|
jobs.enqueue(conn, a.job_id, att_id, pv, 1)
|
||||||
|
print(f"REPLAYED job={a.job_id} attachment={att_id}")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# Restart hook (tests/resilience.py --mode persistence): restarts ALL stores with their volumes (nothing is removed), then re-unseals OpenBao,
|
||||||
|
# refreshes the 24 h SecretIDs and restarts the services that fetch secrets.
|
||||||
|
set -eu
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
docker compose restart postgres redis s3 kafka openbao prometheus loki tempo
|
||||||
|
sh scripts/bao_unseal.sh
|
||||||
|
sh scripts/bao_secret_id.sh all >/dev/null
|
||||||
|
docker compose restart api dispatcher worker s3_sweeper otel-collector grafana
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# Revoke an AppRole identity (stolen RoleID/SecretID/tokens become useless). Usage: revoke_identity.sh <role>
|
||||||
|
# Destroys every SecretID of the role and revokes all tokens issued through AppRole login (apps only hold a token for milliseconds at start).
|
||||||
|
set -eu
|
||||||
|
cd "$(dirname "$0")/.."; . scripts/bao_lib.sh; load_root
|
||||||
|
r="${1:?role}"
|
||||||
|
for acc in $(baoc list -format=json "auth/approle/role/$r/secret-id" 2>/dev/null | python3 -c "import sys,json; print(' '.join(json.load(sys.stdin)))" 2>/dev/null || true); do
|
||||||
|
baoc write "auth/approle/role/$r/secret-id-accessor/destroy" secret_id_accessor="$acc" >/dev/null
|
||||||
|
done
|
||||||
|
baoc lease revoke -prefix auth/approle/login >/dev/null 2>&1 || true
|
||||||
|
echo "identity $r revoked (SecretIDs destroyed, login tokens revoked)"
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# Rotate ONE working secret without rebuilding images. Usage: rotate_secret.sh db-<api|worker|dispatcher|sweeper> | s3-<api|worker|sweeper>
|
||||||
|
# 1) new random value in ./secrets/ops 2) apply to the store (ALTER ROLE / mc admin user add) and kill old sessions 3) OpenBao KV 4) restart the consumer.
|
||||||
|
set -eu
|
||||||
|
cd "$(dirname "$0")/.."; . scripts/bao_lib.sh; load_root
|
||||||
|
t="${1:?usage: rotate_secret.sh db-worker|s3-worker|...}"; kind="${t%%-*}"; role="${t#*-}"
|
||||||
|
new="$(openssl rand -base64 36 | tr -d '/+=\n' | cut -c1-32)"
|
||||||
|
case "$kind" in
|
||||||
|
db) f="$S/ops/db_${role}_password"; field=db_password ;;
|
||||||
|
s3) f="$S/ops/s3_${role}_secret"; field=s3_secret_key ;;
|
||||||
|
*) echo "unknown target" >&2; exit 2 ;;
|
||||||
|
esac
|
||||||
|
umask 022; printf %s "$new" > "$f"
|
||||||
|
if [ "$kind" = db ]; then DB_ROLES_ARGS="--terminate messenger_$role" docker compose run --rm -e DB_ROLES_ARGS migrate >/dev/null
|
||||||
|
else docker compose run --rm s3_init >/dev/null; fi
|
||||||
|
baoc kv patch "kv/$role" "$field=$new" >/dev/null
|
||||||
|
sh scripts/bao_secret_id.sh "$role" >/dev/null
|
||||||
|
svc="$role"; [ "$role" = sweeper ] && svc=s3_sweeper
|
||||||
|
docker compose restart "$svc" >/dev/null
|
||||||
|
echo "rotated $t; old value is dead in the store, new value lives in OpenBao only; $svc restarted"
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Orphan sweeper (lab5): staging/ and attachments/ cleanup, retention of failed staging (see run_once).
|
||||||
|
|
||||||
|
Safety: only objects older than --grace-seconds are candidates (default 3600, far above the few seconds between
|
||||||
|
PUT and COMMIT), and the DB is re-checked immediately before each delete. Default mode is --dry-run.
|
||||||
|
"""
|
||||||
|
import argparse, os, sys, time
|
||||||
|
from pathlib import Path
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
import boto3, psycopg
|
||||||
|
from botocore.config import Config
|
||||||
|
|
||||||
|
def run_once(s3, conn, bucket, grace, apply, retention):
|
||||||
|
"""Lab5 cleanup rules (documented in REPORT.md):
|
||||||
|
1) staging/<k> without any attachments.staging_key row older than grace = orphan of a crash between PUT and COMMIT -> delete
|
||||||
|
(staging of ready attachments is deleted by the worker and its staging_key set to NULL, so a leftover is also an orphan);
|
||||||
|
2) attachments/<id>/... whose attachment row no longer exists -> delete;
|
||||||
|
3) staging of FAILED attachments older than retention -> delete object and NULL staging_key (replay is then impossible).
|
||||||
|
Current work (queued/processing, or failed within retention) is never touched; the DB is re-checked right before each delete."""
|
||||||
|
now = datetime.now(timezone.utc)
|
||||||
|
seen = old = orphans = deleted = 0
|
||||||
|
for prefix in ("staging/", "attachments/"):
|
||||||
|
for page in s3.get_paginator("list_objects_v2").paginate(Bucket=bucket, Prefix=prefix):
|
||||||
|
for obj in page.get("Contents", []):
|
||||||
|
seen += 1
|
||||||
|
key = obj["Key"]
|
||||||
|
if key == "attachments/.ready" or (now - obj["LastModified"]).total_seconds() < grace:
|
||||||
|
continue # fresh: may still be between PUT and COMMIT
|
||||||
|
old += 1
|
||||||
|
if prefix == "staging/":
|
||||||
|
referenced = lambda: conn.execute("SELECT 1 FROM attachments WHERE staging_key=%s", (key,)).fetchone()
|
||||||
|
else:
|
||||||
|
att = key.split("/")[1] if key.count("/") >= 2 else ""
|
||||||
|
referenced = lambda: conn.execute("SELECT 1 FROM attachments WHERE id::text=%s", (att,)).fetchone()
|
||||||
|
if referenced():
|
||||||
|
continue
|
||||||
|
orphans += 1
|
||||||
|
print(("DELETE " if apply else "WOULD-DELETE ") + key, flush=True)
|
||||||
|
if apply and not referenced():
|
||||||
|
s3.delete_object(Bucket=bucket, Key=key); deleted += 1
|
||||||
|
expired = conn.execute("SELECT id, staging_key FROM attachments WHERE status='failed' AND staging_key IS NOT NULL "
|
||||||
|
"AND updated_at < now() - make_interval(secs=>%s)", (retention,)).fetchall()
|
||||||
|
for att_id, skey in expired:
|
||||||
|
print(("EXPIRE-STAGING " if apply else "WOULD-EXPIRE-STAGING ") + skey, flush=True)
|
||||||
|
if apply:
|
||||||
|
s3.delete_object(Bucket=bucket, Key=skey)
|
||||||
|
conn.execute("UPDATE attachments SET staging_key=NULL WHERE id=%s", (att_id,))
|
||||||
|
deleted += 1
|
||||||
|
print(f"sweep: seen={seen} older_than_grace={old} orphans={orphans} failed_expired={len(expired)} deleted={deleted} apply={apply}", flush=True)
|
||||||
|
return orphans, deleted
|
||||||
|
|
||||||
|
def main():
|
||||||
|
p = argparse.ArgumentParser()
|
||||||
|
p.add_argument("--apply", action="store_true", help="really delete (default: dry-run)")
|
||||||
|
p.add_argument("--grace-seconds", type=int, default=int(os.getenv("SWEEP_GRACE_SECONDS", "3600")))
|
||||||
|
p.add_argument("--loop", action="store_true"); p.add_argument("--interval", type=int, default=int(os.getenv("SWEEP_INTERVAL_SECONDS", "600")))
|
||||||
|
p.add_argument("--retention-seconds", type=int, default=int(os.getenv("STAGING_RETENTION_SECONDS", "86400")))
|
||||||
|
a = p.parse_args()
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||||
|
from src import vault
|
||||||
|
vault.load_into_env("sweeper") # lab 7: DB role messenger_sweeper + S3 key svc-sweeper from OpenBao
|
||||||
|
if a.grace_seconds < 0: sys.exit("grace must be >= 0")
|
||||||
|
s3 = boto3.client("s3", endpoint_url=os.environ["S3_ENDPOINT"], region_name=os.getenv("S3_REGION", "us-east-1"),
|
||||||
|
aws_access_key_id=os.environ["S3_ACCESS_KEY_ID"], aws_secret_access_key=os.environ["S3_SECRET_ACCESS_KEY"], verify=os.getenv("TLS_CA_FILE", "/run/pki/ca.crt"),
|
||||||
|
config=Config(signature_version="s3v4", s3={"addressing_style": "path"}, connect_timeout=3, read_timeout=15, retries={"max_attempts": 2}))
|
||||||
|
bucket = os.environ["S3_BUCKET"]
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
with psycopg.connect(connect_timeout=5, autocommit=True) as conn:
|
||||||
|
run_once(s3, conn, bucket, a.grace_seconds, a.apply, a.retention_seconds)
|
||||||
|
except Exception as exc: # keep looping through outages
|
||||||
|
print("sweep failed:", type(exc).__name__, flush=True)
|
||||||
|
if not a.loop: raise
|
||||||
|
if not a.loop: return
|
||||||
|
time.sleep(a.interval)
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# Dependency + image scan (results go to evidence/; triage by applicability is written in REPORT.md).
|
||||||
|
set -eu
|
||||||
|
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
mkdir -p evidence
|
||||||
|
|
||||||
|
# pip-audit: non-zero exit is expected when vulnerabilities are found.
|
||||||
|
docker run --rm \
|
||||||
|
-v "$PWD/requirements.txt:/r.txt:ro" \
|
||||||
|
python:3.12.11-slim-bookworm \
|
||||||
|
sh -c "pip install -q pip-audit && pip-audit -r /r.txt" \
|
||||||
|
> evidence/pip-audit.txt 2>&1 || true
|
||||||
|
|
||||||
|
# Trivy: preserve complete reports, including findings without fixes.
|
||||||
|
scan_failed=0
|
||||||
|
|
||||||
|
for img in \
|
||||||
|
mtusi-lab7-app:1.0.0 \
|
||||||
|
openbao/openbao:2.4.1 \
|
||||||
|
redis:7.4.2-alpine \
|
||||||
|
postgres:17.6-alpine \
|
||||||
|
haproxy:3.2.5-alpine
|
||||||
|
do
|
||||||
|
out="evidence/trivy-$(echo "$img" | tr '/:' '__').txt"
|
||||||
|
|
||||||
|
echo "Scanning $img ..."
|
||||||
|
|
||||||
|
if docker run --rm \
|
||||||
|
-v /var/run/docker.sock:/var/run/docker.sock:ro \
|
||||||
|
aquasec/trivy:0.58.1 image \
|
||||||
|
--severity HIGH,CRITICAL \
|
||||||
|
"$img" > "$out" 2>&1
|
||||||
|
then
|
||||||
|
echo "PASS: $img; report saved to $out"
|
||||||
|
else
|
||||||
|
rc=$?
|
||||||
|
echo "ERROR: Trivy failed for $img (exit code $rc); see $out" >&2
|
||||||
|
scan_failed=1
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
if [ "$scan_failed" -ne 0 ]; then
|
||||||
|
echo "Scan failed for one or more images" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "scan finished: evidence/pip-audit.txt, evidence/trivy-*.txt"
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
: "${TARGET_INSTANCE_ID:?TARGET_INSTANCE_ID must be supplied by tests/resilience.py}"
|
||||||
|
found=""
|
||||||
|
for id in $(docker compose ps -q api); do
|
||||||
|
host=$(docker inspect --format '{{.Config.Hostname}}' "$id")
|
||||||
|
if [ "$host" = "$TARGET_INSTANCE_ID" ]; then
|
||||||
|
found="$id"
|
||||||
|
break
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
if [ -z "$found" ]; then
|
||||||
|
echo "No running API container matches TARGET_INSTANCE_ID" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
# Stop exactly one API replica and intentionally leave it stopped for the failover check.
|
||||||
|
docker stop --time 10 "$found" >/dev/null
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# Operator: first start or start after a full stop. OpenBao is started first, initialised once, unsealed, filled; then the rest.
|
||||||
|
set -eu
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
sh scripts/bootstrap.sh
|
||||||
|
docker compose --env-file .env config --quiet
|
||||||
|
docker compose --env-file .env up -d --build init_perms openbao
|
||||||
|
i=0; until [ "$(docker inspect -f '{{.State.Health.Status}}' "$(docker compose ps -q openbao)")" = healthy ]; do i=$((i+1)); [ $i -lt 60 ] || exit 1; sleep 1; done
|
||||||
|
sh scripts/bao_init.sh
|
||||||
|
sh scripts/bao_unseal.sh
|
||||||
|
sh scripts/bao_bootstrap.sh
|
||||||
|
sh scripts/bao_secret_id.sh all
|
||||||
|
docker compose --env-file .env up -d --build
|
||||||
|
echo "stack started; wait for https://localhost:8443/health/ready, then: make test CA_FILE=\$PWD/secrets/pki/ca/ca.crt"
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Lab 7 negative application tests through the public HTTPS endpoint (stdlib + tests/client.py helper).
|
||||||
|
|
||||||
|
Covers: outsider cannot read chat metadata/content or attach a foreign file; forged X-User-Id does not change the Bearer identity;
|
||||||
|
logout revokes the token; login rate limit (429 + Retry-After) shared by replicas; oversized JSON -> 413; canary password/token
|
||||||
|
never appear in container logs or in Loki (queried through the Grafana datasource proxy).
|
||||||
|
Usage: python3 security-tests/acl_leak.py --ca-file secrets/pki/ca/ca.crt [--grafana-password-file secrets/ops/grafana_admin_password]
|
||||||
|
"""
|
||||||
|
import argparse
|
||||||
|
import base64
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import ssl
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import urllib.error
|
||||||
|
import urllib.parse
|
||||||
|
import urllib.request
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "tests"))
|
||||||
|
from client import Client # noqa: E402
|
||||||
|
|
||||||
|
FAILS = []
|
||||||
|
PNG = open(os.path.join(os.path.dirname(__file__), "..", "tests", "fixtures", "sample.png"), "rb").read()
|
||||||
|
|
||||||
|
|
||||||
|
def ok(name, cond, detail=""):
|
||||||
|
print(("PASS " if cond else "FAIL ") + name + (f" ({detail})" if detail else ""))
|
||||||
|
if not cond:
|
||||||
|
FAILS.append(name)
|
||||||
|
|
||||||
|
|
||||||
|
def raw(base, ca, method, path, headers=None, body=None):
|
||||||
|
req = urllib.request.Request(base + path, data=body, headers=headers or {}, method=method)
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(req, context=ssl.create_default_context(cafile=ca), timeout=15) as r:
|
||||||
|
return r.status, {k.lower(): v for k, v in r.headers.items()}, r.read() # header names are case-insensitive (uvicorn sends them lower-case)
|
||||||
|
except urllib.error.HTTPError as e:
|
||||||
|
return e.code, {k.lower(): v for k, v in e.headers.items()}, e.read()
|
||||||
|
|
||||||
|
|
||||||
|
def basic(u, p):
|
||||||
|
return {"Authorization": "Basic " + base64.b64encode(f"{u}:{p}".encode()).decode()}
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
ap = argparse.ArgumentParser()
|
||||||
|
ap.add_argument("--base-url", default="https://localhost:8443"); ap.add_argument("--ca-file", required=True)
|
||||||
|
ap.add_argument("--grafana-password-file")
|
||||||
|
a = ap.parse_args()
|
||||||
|
c = Client(a.base_url, a.ca_file)
|
||||||
|
alice, bob, eve, chat = c.bootstrap()
|
||||||
|
path = "/api/v1/chats/" + chat["id"]
|
||||||
|
# 1. outsider (eve) and identity forgery
|
||||||
|
s, _, _ = raw(a.base_url, a.ca_file, "GET", path, {"Authorization": "Bearer " + eve["token"]}); ok("outsider cannot read chat metadata", s == 404, s)
|
||||||
|
s, _, _ = raw(a.base_url, a.ca_file, "GET", path + "/messages", {"Authorization": "Bearer " + eve["token"]}); ok("outsider cannot read messages", s == 404, s)
|
||||||
|
s, _, _ = raw(a.base_url, a.ca_file, "POST", path + "/attachments?filename=x.png", {"Authorization": "Bearer " + eve["token"], "Content-Type": "image/png"}, PNG)
|
||||||
|
ok("outsider cannot attach a file to a foreign chat", s == 404, s)
|
||||||
|
s, _, _ = raw(a.base_url, a.ca_file, "GET", path, {"Authorization": "Bearer " + eve["token"], "X-User-Id": alice["id"]}); ok("forged X-User-Id does not change the Bearer identity", s == 404, s)
|
||||||
|
s, _, _ = raw(a.base_url, a.ca_file, "GET", "/api/v1/users/me", {"X-User-Id": alice["id"]}); ok("X-User-Id alone gives no access", s == 401, s)
|
||||||
|
# 2. logout revokes
|
||||||
|
s, _, _ = raw(a.base_url, a.ca_file, "DELETE", "/api/v1/auth/sessions/current", {"Authorization": "Bearer " + eve["token"]}); ok("logout returns 204", s == 204, s)
|
||||||
|
s, _, _ = raw(a.base_url, a.ca_file, "GET", "/api/v1/users/me", {"Authorization": "Bearer " + eve["token"]}); ok("token is dead after logout", s == 401, s)
|
||||||
|
# 3. oversized JSON
|
||||||
|
big = json.dumps({"text": "x" * 70000}).encode()
|
||||||
|
s, _, b = raw(a.base_url, a.ca_file, "POST", path + "/messages", {"Authorization": "Bearer " + alice["token"], "Content-Type": "application/json", "Idempotency-Key": uuid.uuid4().hex}, big)
|
||||||
|
ok("JSON body over 64 KiB -> 413", s == 413, s)
|
||||||
|
# 4. canary credentials must never reach logs/telemetry
|
||||||
|
canary_user, canary_pw = "canary" + uuid.uuid4().hex[:8], "CANARY-pw-" + uuid.uuid4().hex
|
||||||
|
reg = json.dumps({"username": canary_user, "display_name": "Canary", "password": canary_pw}).encode()
|
||||||
|
s, _, _ = raw(a.base_url, a.ca_file, "POST", "/api/v1/users", {"Content-Type": "application/json"}, reg); ok("canary user registered", s == 201, s)
|
||||||
|
s, _, b = raw(a.base_url, a.ca_file, "POST", "/api/v1/auth/sessions", basic(canary_user, canary_pw)); ok("canary login", s == 201, s)
|
||||||
|
canary_token = json.loads(b)["token"]
|
||||||
|
s, _, _ = raw(a.base_url, a.ca_file, "POST", "/api/v1/auth/sessions", basic(canary_user, canary_pw + "x"))
|
||||||
|
logs = subprocess.run(["docker", "compose", "logs", "--no-color", "--since", "10m"], capture_output=True, text=True).stdout
|
||||||
|
ok("password and token absent from container logs", canary_pw not in logs and canary_token not in logs)
|
||||||
|
if a.grafana_password_file:
|
||||||
|
pw = open(a.grafana_password_file).read().strip()
|
||||||
|
q = urllib.parse.quote('{service_name=~".+"} |~ "CANARY-pw|' + canary_token[:12] + '"')
|
||||||
|
url = "https://localhost:3000/api/datasources/proxy/uid/loki/loki/api/v1/query_range?limit=5&since=15m&query=" + q
|
||||||
|
req = urllib.request.Request(url, headers={"Authorization": "Basic " + base64.b64encode(f"admin:{pw}".encode()).decode()})
|
||||||
|
data = json.load(urllib.request.urlopen(req, context=ssl.create_default_context(cafile=a.ca_file), timeout=15))
|
||||||
|
ok("password and token absent from Loki", data["data"]["result"] == [], len(data["data"]["result"]))
|
||||||
|
# 5. login rate limit: shared counter, 429 + Retry-After (run last: it locks the throw-away username for one window)
|
||||||
|
victim = "rl" + uuid.uuid4().hex[:10]
|
||||||
|
statuses, retry = [], None
|
||||||
|
for _ in range(14):
|
||||||
|
s, h, _ = raw(a.base_url, a.ca_file, "POST", "/api/v1/auth/sessions", basic(victim, "wrong-password-123"))
|
||||||
|
statuses.append(s)
|
||||||
|
if s == 429:
|
||||||
|
retry = h.get("retry-after")
|
||||||
|
ok("login: 429 after repeated failures, Retry-After present", 429 in statuses and retry is not None and int(retry) >= 1, f"{statuses} retry={retry}")
|
||||||
|
print("\n" + ("ALL PASS" if not FAILS else "FAILED: " + "; ".join(FAILS)))
|
||||||
|
sys.exit(1 if FAILS else 0)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Track 1 proof of job durability. Host side, public HTTPS API only, uses the unchanged skeleton test client.
|
||||||
|
|
||||||
|
jobs_integrity.py submit --n 10 register users, upload N images while the worker is STOPPED, remember their ids in evidence/jobs-ids.json
|
||||||
|
jobs_integrity.py verify after the incident script restarted the worker: every attachment must become `ready` (lost = 0)
|
||||||
|
"""
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
|
||||||
|
ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")
|
||||||
|
sys.path.insert(0, os.path.join(ROOT, "tests"))
|
||||||
|
from client import Client # noqa: E402
|
||||||
|
|
||||||
|
IDS = os.path.join(ROOT, "evidence", "jobs-ids.json")
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
ap = argparse.ArgumentParser()
|
||||||
|
ap.add_argument("mode", choices=["submit", "verify"])
|
||||||
|
ap.add_argument("--n", type=int, default=10)
|
||||||
|
ap.add_argument("--base-url", default="https://localhost:8443")
|
||||||
|
ap.add_argument("--ca-file", required=True)
|
||||||
|
ap.add_argument("--wait", type=int, default=180)
|
||||||
|
a = ap.parse_args()
|
||||||
|
c = Client(a.base_url, a.ca_file)
|
||||||
|
if a.mode == "submit":
|
||||||
|
alice, bob, eve, chat = c.bootstrap()
|
||||||
|
ids = []
|
||||||
|
for _ in range(a.n):
|
||||||
|
att, _content = c.attachment(alice, chat) # 202 + status "queued" are asserted by the client
|
||||||
|
ids.append(att["id"])
|
||||||
|
os.makedirs(os.path.dirname(IDS), exist_ok=True)
|
||||||
|
json.dump({"ids": ids, "actor": {"id": alice["id"], "token": alice["token"]}}, open(IDS, "w"))
|
||||||
|
print(f"submitted {len(ids)} jobs; they stay queued while the worker is stopped")
|
||||||
|
return
|
||||||
|
data = json.load(open(IDS))
|
||||||
|
actor, pending, ready = data["actor"], list(data["ids"]), set()
|
||||||
|
deadline = time.monotonic() + a.wait
|
||||||
|
while pending and time.monotonic() < deadline:
|
||||||
|
for att_id in list(pending):
|
||||||
|
res = c.call("GET", "/api/v1/attachments/" + att_id, actor=actor, schema="Attachment")
|
||||||
|
if not res.get("json") or "status" not in res["json"]:
|
||||||
|
continue
|
||||||
|
st = res["json"]["status"]
|
||||||
|
|
||||||
|
if st == "failed":
|
||||||
|
print(f"attachment {att_id} FAILED")
|
||||||
|
sys.exit(1)
|
||||||
|
if st == "ready":
|
||||||
|
ready.add(att_id)
|
||||||
|
pending.remove(att_id)
|
||||||
|
if pending:
|
||||||
|
time.sleep(2)
|
||||||
|
total = len(data["ids"])
|
||||||
|
print(f"{len(ready)}/{total} attachments ready; lost={total - len(ready)}")
|
||||||
|
if len(ready) == total:
|
||||||
|
os.remove(IDS)
|
||||||
|
sys.exit(0)
|
||||||
|
|
||||||
|
print(f"IDs preserved for retry: {IDS}", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Lab 7, track 1: proof that REVOKED worker credentials are dead on NEW connections, and the rotated ones work.
|
||||||
|
|
||||||
|
Runs inside the backend network (called by scripts/incident_worker.sh).
|
||||||
|
Mounts: /pki (public CA at /pki/ca/ca.crt), /old (the worker secrets saved BEFORE the incident: secret_id, db_password, s3_secret),
|
||||||
|
/approle (the NEW role_id + secret_id issued after the incident).
|
||||||
|
Every probe opens a fresh TCP/TLS connection / performs a fresh login: an already open session or a cached token would prove nothing.
|
||||||
|
No secret value is printed. Exit code 0 only if all 6 probes behave as expected.
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
import ssl
|
||||||
|
import sys
|
||||||
|
import urllib.error
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
CA = "/pki/ca/ca.crt"
|
||||||
|
RESULTS = []
|
||||||
|
|
||||||
|
|
||||||
|
def rd(path):
|
||||||
|
return open(path, encoding="utf-8").read().strip()
|
||||||
|
|
||||||
|
|
||||||
|
def bao_login(role_id, secret_id):
|
||||||
|
req = urllib.request.Request("https://openbao:8200/v1/auth/approle/login", method="POST",
|
||||||
|
data=json.dumps({"role_id": role_id, "secret_id": secret_id}).encode())
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(req, timeout=5, context=ssl.create_default_context(cafile=CA)) as r:
|
||||||
|
return r.status, json.loads(r.read())["auth"]["client_token"]
|
||||||
|
except urllib.error.HTTPError as exc:
|
||||||
|
return exc.code, None
|
||||||
|
|
||||||
|
|
||||||
|
def bao_kv(token):
|
||||||
|
req = urllib.request.Request("https://openbao:8200/v1/kv/data/worker", headers={"X-Vault-Token": token})
|
||||||
|
with urllib.request.urlopen(req, timeout=5, context=ssl.create_default_context(cafile=CA)) as r:
|
||||||
|
return json.loads(r.read())["data"]["data"]
|
||||||
|
|
||||||
|
|
||||||
|
def db_connect(password):
|
||||||
|
import psycopg
|
||||||
|
try:
|
||||||
|
with psycopg.connect(host="postgres", dbname="messenger", user="messenger_worker", password=password, sslmode="verify-full",
|
||||||
|
sslrootcert=CA, connect_timeout=5) as conn:
|
||||||
|
conn.execute("SELECT 1 FROM attachment_jobs LIMIT 1")
|
||||||
|
return "connected"
|
||||||
|
except psycopg.OperationalError as exc:
|
||||||
|
return "rejected" if "password authentication failed" in str(exc) else "error:" + type(exc).__name__
|
||||||
|
|
||||||
|
|
||||||
|
def s3_call(key, secret):
|
||||||
|
import boto3
|
||||||
|
from botocore.config import Config
|
||||||
|
from botocore.exceptions import ClientError
|
||||||
|
s3 = boto3.client("s3", endpoint_url="https://s3:9000", region_name="us-east-1", aws_access_key_id=key, aws_secret_access_key=secret, verify=CA,
|
||||||
|
config=Config(signature_version="s3v4", s3={"addressing_style": "path"}, retries={"max_attempts": 1}, connect_timeout=3))
|
||||||
|
try:
|
||||||
|
s3.get_object(Bucket="messenger-attachments", Key="staging/revocation-probe")
|
||||||
|
return "accepted"
|
||||||
|
except ClientError as exc:
|
||||||
|
code = exc.response["Error"]["Code"]
|
||||||
|
if code in ("NoSuchKey", "404"):
|
||||||
|
return "accepted" # authenticated and authorised; the object simply does not exist
|
||||||
|
return "rejected" if code in ("SignatureDoesNotMatch", "InvalidAccessKeyId", "AccessDenied", "403") else "error:" + code
|
||||||
|
|
||||||
|
|
||||||
|
def expect(name, got, want):
|
||||||
|
ok = got == want
|
||||||
|
RESULTS.append(ok)
|
||||||
|
print(("PASS " if ok else "FAIL ") + f"{name}: {got} (expected {want})")
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
role_id = rd("/approle/role_id")
|
||||||
|
# old material (saved before the incident) -> must be dead on a NEW connection
|
||||||
|
status, _ = bao_login(role_id, rd("/old/secret_id"))
|
||||||
|
expect("OpenBao: login with OLD SecretID", "rejected" if status in (400, 403) else f"HTTP {status}", "rejected")
|
||||||
|
expect("PostgreSQL: new connection with OLD role password", db_connect(rd("/old/db_password")), "rejected")
|
||||||
|
expect("S3: new request with OLD svc-worker secret", s3_call("svc-worker", rd("/old/s3_secret")), "rejected")
|
||||||
|
# new material -> must work, otherwise "rejected" above could simply mean "everything is down"
|
||||||
|
status, token = bao_login(role_id, rd("/approle/secret_id"))
|
||||||
|
expect("OpenBao: login with NEW SecretID", "accepted" if status == 200 else f"HTTP {status}", "accepted")
|
||||||
|
if token:
|
||||||
|
kv = bao_kv(token)
|
||||||
|
expect("PostgreSQL: new connection with NEW role password", "accepted" if db_connect(kv["db_password"]) == "connected" else "rejected", "accepted")
|
||||||
|
expect("S3: new request with NEW svc-worker secret", s3_call(kv["s3_access_key"], kv["s3_secret_key"]), "accepted")
|
||||||
|
else:
|
||||||
|
expect("PostgreSQL: new connection with NEW role password", "skipped (no token)", "accepted")
|
||||||
|
expect("S3: new request with NEW svc-worker secret", "skipped (no token)", "accepted")
|
||||||
|
print(f"\n{sum(RESULTS)}/{len(RESULTS)} probes as expected")
|
||||||
|
sys.exit(0 if all(RESULTS) else 1)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# Run a security test script INSIDE the backend network using the application image (all client libraries present).
|
||||||
|
# Usage: security-tests/run_in_net.sh <script.py> [args]. ./secrets/pki is mounted read-only (operator test only, never part of the stand).
|
||||||
|
set -eu
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
script="$1"; shift
|
||||||
|
exec docker run --rm --network mtusi-lab7_backend --user 10001:10001 --read-only --cap-drop ALL --security-opt no-new-privileges:true \
|
||||||
|
-v "$PWD/security-tests:/t:ro" -v "$PWD/secrets/pki:/pki:ro" -v "$PWD/secrets/approle/worker:/approle:ro" -v "$PWD/secrets/ops:/ops:ro" \
|
||||||
|
-e BAO_ADDR=https://openbao:8200 -e BAO_CACERT=/pki/ca/ca.crt --entrypoint python mtusi-lab7-app:1.0.0 "/t/$script" "$@"
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Lab 7 TLS audit of the whole trust matrix. Runs INSIDE the backend network (see security-tests/run_in_net.sh) with ./secrets/pki mounted at /pki.
|
||||||
|
|
||||||
|
Every row is a positive or a negative probe; "rejected" means: handshake/ACL/auth error, never "server unavailable".
|
||||||
|
Exit code 0 only if every probe behaved as expected.
|
||||||
|
"""
|
||||||
|
import socket
|
||||||
|
import ssl
|
||||||
|
import sys
|
||||||
|
|
||||||
|
P = "/pki"
|
||||||
|
CA = f"{P}/ca/ca.crt"
|
||||||
|
RESULTS = []
|
||||||
|
|
||||||
|
|
||||||
|
def ctx(ca=CA, cert=None, check=True):
|
||||||
|
c = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
|
||||||
|
if ca:
|
||||||
|
c.load_verify_locations(ca)
|
||||||
|
c.check_hostname = check
|
||||||
|
c.verify_mode = ssl.CERT_REQUIRED
|
||||||
|
if cert:
|
||||||
|
c.load_cert_chain(f"{P}/{cert}/tls.crt", f"{P}/{cert}/tls.key")
|
||||||
|
return c
|
||||||
|
|
||||||
|
|
||||||
|
def tls_get(host, port, path="/", c=None, sni=None):
|
||||||
|
"""returns the HTTP status line, or the exception class name when the connection is refused/reset/verification fails."""
|
||||||
|
try:
|
||||||
|
with socket.create_connection((host, port), timeout=5) as raw:
|
||||||
|
with (c or ctx()).wrap_socket(raw, server_hostname=sni or host) as s:
|
||||||
|
s.sendall(f"GET {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n".encode())
|
||||||
|
data = s.recv(200)
|
||||||
|
return data.split(b"\r\n")[0].decode() if data else "EmptyReply" # TLS 1.3: a refused client cert shows up here
|
||||||
|
except (ssl.SSLError, OSError) as exc:
|
||||||
|
return type(exc).__name__
|
||||||
|
|
||||||
|
|
||||||
|
def plain(host, port):
|
||||||
|
"""Plain-text probe. A TLS-only server may still answer with 'HTTP/1.x 400 ... HTTPS server': that is a REFUSAL, not an accepted plaintext request."""
|
||||||
|
try:
|
||||||
|
with socket.create_connection((host, port), timeout=3) as s:
|
||||||
|
s.sendall(b"GET / HTTP/1.0\r\n\r\n")
|
||||||
|
data = s.recv(300)
|
||||||
|
if not data:
|
||||||
|
return "Closed"
|
||||||
|
if not data.startswith(b"HTTP"):
|
||||||
|
return "NoHTTP"
|
||||||
|
return "TLS_ONLY" if (b"HTTPS" in data or data.split(b"\r\n")[0].split(b" ")[1:2] == [b"400"]) else "ANSWERED"
|
||||||
|
except OSError as exc:
|
||||||
|
return type(exc).__name__
|
||||||
|
|
||||||
|
|
||||||
|
def expect(name, got, ok):
|
||||||
|
RESULTS.append((name, got, ok))
|
||||||
|
print(("PASS " if ok else "FAIL ") + f"{name}: {got}")
|
||||||
|
|
||||||
|
|
||||||
|
def accepted(r):
|
||||||
|
"""The server completed TLS and answered with any HTTP status (2xx/3xx/4xx/5xx)."""
|
||||||
|
return r.startswith("HTTP/1.") and r.split(" ")[1][:1] in "2345"
|
||||||
|
|
||||||
|
|
||||||
|
def refused(r):
|
||||||
|
"""A real refusal (handshake/verify error, reset, empty reply). DNS failures and timeouts mean 'service not reachable' and must NOT count as refusal."""
|
||||||
|
return not accepted(r) and r not in ("gaierror", "TimeoutError", "timeout")
|
||||||
|
|
||||||
|
|
||||||
|
def kafka_produce(cert):
|
||||||
|
from confluent_kafka import KafkaException, Producer
|
||||||
|
errors = []
|
||||||
|
p = Producer({"bootstrap.servers": "kafka:9092", "security.protocol": "SSL", "ssl.ca.location": CA,
|
||||||
|
"ssl.certificate.location": f"{P}/{cert}/tls.crt", "ssl.key.location": f"{P}/{cert}/tls.key",
|
||||||
|
"message.timeout.ms": 8000, "enable.idempotence": True})
|
||||||
|
try:
|
||||||
|
p.produce("attachment-jobs", b"audit-probe", on_delivery=lambda e, m: errors.append(str(e) if e else "OK"))
|
||||||
|
p.flush(10)
|
||||||
|
except KafkaException as exc: # idempotent producer: denied IdempotentWrite on the cluster surfaces here (also an authorization refusal)
|
||||||
|
return str(exc)
|
||||||
|
return errors[0] if errors else "NoDelivery"
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
# 1. LB -> API (mTLS + identity allowlist)
|
||||||
|
r = tls_get("api", 8443, "/health/live", ctx(cert="lb"), sni="api"); expect("api: lb identity accepted", r, accepted(r))
|
||||||
|
r = tls_get("api", 8443, "/health/live", sni="api"); expect("api: no client cert refused", r, refused(r))
|
||||||
|
r = tls_get("api", 8443, "/health/live", ctx(cert="rogue", ca=CA), sni="api"); expect("api: foreign-CA cert refused", r, refused(r))
|
||||||
|
r = tls_get("api", 8443, "/health/live", ctx(cert="outsider"), sni="api"); expect("api: same-CA, wrong identity (outsider) refused", r, refused(r))
|
||||||
|
r = tls_get("api", 8443, "/health/live", ctx(cert="worker"), sni="api"); expect("api: worker identity refused", r, refused(r))
|
||||||
|
r = tls_get("api", 8443, "/health/live", ctx(ca="/pki/rogue/rogue-ca.crt", cert="lb"), sni="api"); expect("api: client distrusting server CA fails verification", r, r == "SSLCertVerificationError")
|
||||||
|
# 2. Collector (mTLS, workload CA only)
|
||||||
|
for who in ("api", "worker", "dispatcher"):
|
||||||
|
r = tls_get("otel-collector", 4318, "/", ctx(cert=who)); expect(f"collector: {who} identity accepted", r, accepted(r))
|
||||||
|
for who in ("outsider", "grafana", "lb"):
|
||||||
|
r = tls_get("otel-collector", 4318, "/", ctx(cert=who)); expect(f"collector: {who} (same root CA, not a workload) refused", r, refused(r))
|
||||||
|
r = tls_get("otel-collector", 4318, "/"); expect("collector: no client cert refused", r, refused(r))
|
||||||
|
expect("collector: plaintext refused", plain("otel-collector", 4318), plain("otel-collector", 4318) != "ANSWERED")
|
||||||
|
# 3. Kafka (mTLS + ACL by CN)
|
||||||
|
r = kafka_produce("dispatcher"); expect("kafka: dispatcher may produce", r, r == "OK")
|
||||||
|
r = kafka_produce("worker"); expect("kafka: worker may NOT produce", r, "AUTHORIZATION" in r.upper())
|
||||||
|
r = kafka_produce("outsider"); expect("kafka: CA-signed outsider may NOT produce", r, "AUTHORIZATION" in r.upper())
|
||||||
|
r = kafka_produce("api"); expect("kafka: api identity may NOT produce", r, "AUTHORIZATION" in r.upper())
|
||||||
|
expect("kafka: plaintext refused", plain("kafka", 9092), plain("kafka", 9092) != "ANSWERED")
|
||||||
|
# 4. Stores and backends: TLS only, server verified
|
||||||
|
for host, port in (("postgres", 5432), ("redis", 6379), ("s3", 9000), ("openbao", 8200), ("prometheus", 9090), ("loki", 3100), ("tempo", 3200)):
|
||||||
|
r = tls_get(host, port, "/", ctx(ca="/pki/rogue/rogue-ca.crt")); expect(f"{host}: foreign CA -> verification error", r, r == "SSLCertVerificationError" or r.startswith("SSL"))
|
||||||
|
for host, port in (("prometheus", 9090), ("loki", 3100), ("tempo", 3200)):
|
||||||
|
r = tls_get(host, port, "/ready"); expect(f"{host}: no client cert refused (mTLS)", r, refused(r))
|
||||||
|
r = tls_get(host, port, "/", ctx(cert="grafana")); expect(f"{host}: client cert accepted", r, accepted(r))
|
||||||
|
r = tls_get("s3", 9000, "/minio/health/live"); expect("s3: TLS with verification works", r, accepted(r))
|
||||||
|
r = tls_get("openbao", 8200, "/v1/sys/health"); expect("openbao: TLS with verification works", r, accepted(r))
|
||||||
|
for host, port in (("redis", 6379), ("s3", 9000), ("openbao", 8200)):
|
||||||
|
expect(f"{host}: plaintext refused", plain(host, port), plain(host, port) != "ANSWERED")
|
||||||
|
try:
|
||||||
|
import psycopg
|
||||||
|
psycopg.connect(host="postgres", user="messenger_api", password="x", dbname="messenger", sslmode="disable", connect_timeout=3)
|
||||||
|
expect("postgres: sslmode=disable refused", "connected", False)
|
||||||
|
except Exception as exc:
|
||||||
|
expect("postgres: sslmode=disable refused (pg_hba reject)", type(exc).__name__, "pg_hba" in str(exc) or "SSL" in str(exc).upper())
|
||||||
|
bad = [n for n, _, ok in RESULTS if not ok]
|
||||||
|
print(f"\n{len(RESULTS) - len(bad)}/{len(RESULTS)} probes as expected")
|
||||||
|
sys.exit(1 if bad else 0)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,154 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Lab 7, research track 1: attacker holds the worker's credentials. What can they do?
|
||||||
|
|
||||||
|
--profile after the worker identity of this stand: DB role messenger_worker, S3 key svc-worker, Kafka cert CN=worker, AppRole "worker"
|
||||||
|
--profile before model of the lab 6 flat trust: one over-privileged credential set shared by everything (DB owner, S3 root, Kafka admin identity)
|
||||||
|
|
||||||
|
Runs inside the backend network (security-tests/run_in_net.sh worker_compromise.py --profile after --out /t/../evidence/x.json is not
|
||||||
|
writable: results are printed as JSON on stdout; redirect on the host). No secret value is printed.
|
||||||
|
Hypothesis: with least privilege the compromised worker can only touch job state, staging reads and attachments writes; everything else is denied.
|
||||||
|
"""
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import socket
|
||||||
|
import ssl
|
||||||
|
import sys
|
||||||
|
import urllib.error
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
P = "/pki"
|
||||||
|
CA = f"{P}/ca/ca.crt"
|
||||||
|
OPS = "/ops"
|
||||||
|
|
||||||
|
|
||||||
|
def rd(path):
|
||||||
|
return open(path, encoding="utf-8").read().strip()
|
||||||
|
|
||||||
|
|
||||||
|
def classify_db(sql, user, password):
|
||||||
|
import psycopg
|
||||||
|
try:
|
||||||
|
with psycopg.connect(host="postgres", dbname="messenger", user=user, password=password, sslmode="verify-full", sslrootcert=CA,
|
||||||
|
connect_timeout=5, autocommit=True) as conn:
|
||||||
|
conn.execute(sql)
|
||||||
|
return "allowed"
|
||||||
|
except psycopg.errors.InsufficientPrivilege:
|
||||||
|
return "denied"
|
||||||
|
except psycopg.Error as exc:
|
||||||
|
return "error:" + type(exc).__name__
|
||||||
|
|
||||||
|
|
||||||
|
def classify_s3(op, key, secret):
|
||||||
|
import boto3
|
||||||
|
from botocore.config import Config
|
||||||
|
from botocore.exceptions import ClientError
|
||||||
|
s3 = boto3.client("s3", endpoint_url="https://s3:9000", region_name="us-east-1", aws_access_key_id=key, aws_secret_access_key=secret,
|
||||||
|
verify=CA, config=Config(signature_version="s3v4", s3={"addressing_style": "path"}, retries={"max_attempts": 1}, connect_timeout=3))
|
||||||
|
b = "messenger-attachments"
|
||||||
|
try:
|
||||||
|
{"get": lambda k: s3.get_object(Bucket=b, Key=k), "put": lambda k: s3.put_object(Bucket=b, Key=k, Body=b"probe"),
|
||||||
|
"delete": lambda k: s3.delete_object(Bucket=b, Key=k), "list": lambda k: s3.list_objects_v2(Bucket=b, MaxKeys=1)}[op](key_of[op])
|
||||||
|
return "allowed"
|
||||||
|
except ClientError as exc:
|
||||||
|
code = exc.response["Error"]["Code"]
|
||||||
|
return "allowed" if code in ("NoSuchKey", "404") else ("denied" if code in ("AccessDenied", "403") else "error:" + code)
|
||||||
|
|
||||||
|
|
||||||
|
key_of = {}
|
||||||
|
|
||||||
|
|
||||||
|
def kafka(identity, action):
|
||||||
|
from confluent_kafka import Consumer, Producer
|
||||||
|
base = {"bootstrap.servers": "kafka:9092", "security.protocol": "SSL", "ssl.ca.location": CA,
|
||||||
|
"ssl.certificate.location": f"{P}/{identity}/tls.crt", "ssl.key.location": f"{P}/{identity}/tls.key"}
|
||||||
|
if action == "produce":
|
||||||
|
out = []
|
||||||
|
p = Producer({**base, "message.timeout.ms": 8000})
|
||||||
|
p.produce("attachment-jobs", b"compromise-probe", on_delivery=lambda e, m: out.append(str(e) if e else "OK"))
|
||||||
|
p.flush(10)
|
||||||
|
return "allowed" if out and out[0] == "OK" else ("denied" if out and "AUTHORIZATION" in out[0].upper() else "error:" + (out[0] if out else "none"))
|
||||||
|
group = "attachment-workers" if action == "consume_own_group" else "attacker-group"
|
||||||
|
errs = []
|
||||||
|
c = Consumer({**base, "group.id": group, "enable.auto.commit": False, "auto.offset.reset": "latest", "error_cb": lambda e: errs.append(str(e))})
|
||||||
|
c.subscribe(["attachment-jobs"])
|
||||||
|
for _ in range(6):
|
||||||
|
m = c.poll(1.0)
|
||||||
|
if m is not None and m.error():
|
||||||
|
errs.append(str(m.error()))
|
||||||
|
c.close()
|
||||||
|
text = " ".join(errs).upper()
|
||||||
|
return "denied" if "AUTHORIZATION" in text else "allowed"
|
||||||
|
|
||||||
|
|
||||||
|
def bao(method, path, token=None, body=None):
|
||||||
|
ctx = ssl.create_default_context(cafile=CA)
|
||||||
|
req = urllib.request.Request("https://openbao:8200/v1/" + path, method=method, data=json.dumps(body).encode() if body is not None else None)
|
||||||
|
if token:
|
||||||
|
req.add_header("X-Vault-Token", token)
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(req, timeout=5, context=ctx) as r:
|
||||||
|
return r.status, json.loads(r.read() or b"{}")
|
||||||
|
except urllib.error.HTTPError as exc:
|
||||||
|
return exc.code, {}
|
||||||
|
|
||||||
|
|
||||||
|
def tls_status(host, port, cert):
|
||||||
|
c = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
|
||||||
|
c.load_verify_locations(CA)
|
||||||
|
c.load_cert_chain(f"{P}/{cert}/tls.crt", f"{P}/{cert}/tls.key")
|
||||||
|
try:
|
||||||
|
with socket.create_connection((host, port), timeout=5) as raw, c.wrap_socket(raw, server_hostname=host) as s:
|
||||||
|
s.sendall(b"GET /health/live HTTP/1.1\r\nHost: api\r\nConnection: close\r\n\r\n")
|
||||||
|
return "allowed" if s.recv(16).startswith(b"HTTP") else "denied"
|
||||||
|
except (ssl.SSLError, OSError):
|
||||||
|
return "denied"
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
ap = argparse.ArgumentParser()
|
||||||
|
ap.add_argument("--profile", choices=["after", "before"], required=True)
|
||||||
|
a = ap.parse_args()
|
||||||
|
after = a.profile == "after"
|
||||||
|
if after: # the attacker logs in with the stolen AppRole material exactly like the worker does
|
||||||
|
_, login = bao("POST", "auth/approle/login", body={"role_id": rd("/approle/role_id"), "secret_id": rd("/approle/secret_id")})
|
||||||
|
token = login["auth"]["client_token"]
|
||||||
|
_, kv = bao("GET", "kv/data/worker", token)
|
||||||
|
db_user, db_pw, s3k, s3s, kid = "messenger_worker", kv["data"]["data"]["db_password"], kv["data"]["data"]["s3_access_key"], kv["data"]["data"]["s3_secret_key"], "worker"
|
||||||
|
else:
|
||||||
|
token = None
|
||||||
|
db_user, db_pw, s3k, s3s, kid = "messenger", rd(f"{OPS}/postgres_password"), rd(f"{OPS}/s3_root_user"), rd(f"{OPS}/s3_root_password"), "kafka-admin"
|
||||||
|
r = {}
|
||||||
|
r["db: SELECT attachment_jobs (job state)"] = ("allowed", classify_db("SELECT 1 FROM attachment_jobs LIMIT 1", db_user, db_pw))
|
||||||
|
r["db: UPDATE attachments (status)"] = ("allowed", classify_db("UPDATE attachments SET status=status WHERE false", db_user, db_pw))
|
||||||
|
r["db: SELECT users.password_hash"] = ("denied", classify_db("SELECT password_hash FROM users LIMIT 1", db_user, db_pw))
|
||||||
|
r["db: SELECT messages (content)"] = ("denied", classify_db("SELECT text FROM messages LIMIT 1", db_user, db_pw))
|
||||||
|
r["db: DELETE FROM attachment_jobs"] = ("denied", classify_db("DELETE FROM attachment_jobs WHERE false", db_user, db_pw))
|
||||||
|
r["db: CREATE TABLE / DDL"] = ("denied", classify_db("CREATE TABLE attacker_probe(x int)", db_user, db_pw))
|
||||||
|
key_of.update({"get": "staging/probe-none", "put": "attachments/probe-worker.txt", "delete": "attachments/probe-worker.txt", "list": ""})
|
||||||
|
r["s3: GET staging/*"] = ("allowed", classify_s3("get", s3k, s3s))
|
||||||
|
key_of["get"] = "attachments/probe-none"
|
||||||
|
r["s3: GET attachments/* (finished files)"] = ("denied", classify_s3("get", s3k, s3s))
|
||||||
|
r["s3: PUT attachments/*"] = ("allowed", classify_s3("put", s3k, s3s))
|
||||||
|
r["s3: DELETE attachments/*"] = ("denied", classify_s3("delete", s3k, s3s))
|
||||||
|
key_of["put"] = "staging/probe-worker.txt"
|
||||||
|
r["s3: PUT staging/* (forge input)"] = ("denied", classify_s3("put", s3k, s3s))
|
||||||
|
r["s3: ListBucket"] = ("denied", classify_s3("list", s3k, s3s))
|
||||||
|
r["kafka: consume jobs topic, own group"] = ("allowed", kafka(kid, "consume_own_group"))
|
||||||
|
r["kafka: produce to jobs topic (forge jobs)"] = ("denied", kafka(kid, "produce"))
|
||||||
|
r["kafka: consume with another group"] = ("denied", kafka(kid, "consume_other_group"))
|
||||||
|
if after:
|
||||||
|
r["bao: read kv/data/worker (own secret)"] = ("allowed", "allowed" if bao("GET", "kv/data/worker", token)[0] == 200 else "denied")
|
||||||
|
r["bao: read kv/data/api"] = ("denied", "allowed" if bao("GET", "kv/data/api", token)[0] == 200 else "denied")
|
||||||
|
r["bao: write sys policy"] = ("denied", "allowed" if bao("PUT", "sys/policies/acl/evil", token, {"policy": 'path "*" {capabilities=["sudo"]}'})[0] in (200, 204) else "denied")
|
||||||
|
r["api: connect to api:8443 with worker certificate"] = ("denied", tls_status("api", 8443, "worker"))
|
||||||
|
out = {"profile": a.profile, "probes": [{"probe": k, "expected_after": e, "observed": o} for k, (e, o) in r.items()]}
|
||||||
|
print(json.dumps(out, indent=1, ensure_ascii=False))
|
||||||
|
if after:
|
||||||
|
bad = [k for k, (e, o) in r.items() if e != o]
|
||||||
|
print("MISMATCH: " + "; ".join(bad) if bad else "PASS: every probe matches the least-privilege expectation", file=sys.stderr)
|
||||||
|
sys.exit(1 if bad else 0)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,141 @@
|
|||||||
|
"""Lab 6 dispatcher (lab 5 + OpenTelemetry): transactional-outbox relay + lease reaper + queue gauges.
|
||||||
|
|
||||||
|
* relay : outbox rows (committed together with the state change) -> Kafka (acks=all, idempotent producer, delivery report)
|
||||||
|
* reaper : processing job with an expired lease (worker died) -> queued again (or failed when attempts are exhausted)
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import psycopg
|
||||||
|
from confluent_kafka import Producer
|
||||||
|
from opentelemetry import metrics, trace
|
||||||
|
from opentelemetry.propagate import extract, inject
|
||||||
|
from opentelemetry.trace import SpanKind, Status, StatusCode
|
||||||
|
|
||||||
|
from . import jobs, telemetry, vault
|
||||||
|
|
||||||
|
# Lab 7: dispatcher = DB role messenger_dispatcher + Kafka producer identity; no S3, no Redis credentials.
|
||||||
|
vault.load_into_env("dispatcher")
|
||||||
|
|
||||||
|
telemetry.init("messenger-dispatcher", instrument=("psycopg",))
|
||||||
|
log = logging.getLogger("dispatcher")
|
||||||
|
TRACER = telemetry.tracer()
|
||||||
|
|
||||||
|
# ---- Lab 6: queue gauges are computed HERE (not in the worker) so they stay visible when the worker is stopped. ----
|
||||||
|
QUEUE_SAMPLE_SECONDS = 5.0
|
||||||
|
_queue = {"depth": 0.0, "oldest": 0.0, "at": None}
|
||||||
|
|
||||||
|
|
||||||
|
def _queue_gauge(key: str):
|
||||||
|
def callback(_options):
|
||||||
|
at = _queue["at"]
|
||||||
|
if at is not None and time.monotonic() - at < 30: # stale (DB down) => no observation instead of a fake value
|
||||||
|
yield metrics.Observation(_queue[key], {"queue.name": jobs.JOBS_TOPIC})
|
||||||
|
return callback
|
||||||
|
|
||||||
|
|
||||||
|
telemetry.meter().create_observable_gauge("messenger.queue.depth", callbacks=[_queue_gauge("depth")], unit="{job}",
|
||||||
|
description="Jobs waiting for a worker: status=queued and due (backoff elapsed)")
|
||||||
|
telemetry.meter().create_observable_gauge("messenger.queue.oldest_job_age", callbacks=[_queue_gauge("oldest")], unit="s",
|
||||||
|
description="Age of the oldest waiting job (now - time it became due); 0 if the queue is empty")
|
||||||
|
telemetry.register_process_metrics()
|
||||||
|
|
||||||
|
|
||||||
|
def sample_queue(conn) -> None:
|
||||||
|
depth, oldest = conn.execute(
|
||||||
|
"SELECT count(*), COALESCE(EXTRACT(EPOCH FROM (now() - min(next_attempt_at))), 0) "
|
||||||
|
"FROM attachment_jobs WHERE status='queued' AND next_attempt_at <= now()").fetchone()
|
||||||
|
_queue.update(depth=float(depth), oldest=max(0.0, float(oldest)), at=time.monotonic())
|
||||||
|
POLL_SECONDS = float(os.getenv("DISPATCH_POLL_SECONDS", "1"))
|
||||||
|
BATCH = int(os.getenv("OUTBOX_BATCH", "100"))
|
||||||
|
FAULT_FLAG = Path("/tmp/dispatcher_fault_done")
|
||||||
|
FAULT_EXIT_BEFORE_PUBLISH = os.getenv("FAULT_DISPATCHER_EXIT_BEFORE_PUBLISH", "0") == "1" # test hook: crash between COMMIT and publish
|
||||||
|
|
||||||
|
|
||||||
|
def relay(conn, producer: Producer) -> int:
|
||||||
|
with conn.transaction():
|
||||||
|
rows = conn.execute("SELECT id, topic, msg_key, payload::text FROM outbox WHERE published_at IS NULL AND available_at <= now() "
|
||||||
|
"ORDER BY id LIMIT %s FOR UPDATE SKIP LOCKED", (BATCH,)).fetchall()
|
||||||
|
if not rows:
|
||||||
|
return 0
|
||||||
|
if FAULT_EXIT_BEFORE_PUBLISH and not FAULT_FLAG.exists():
|
||||||
|
FAULT_FLAG.touch()
|
||||||
|
log.error("FAULT: exiting after reading the outbox, before publishing (COMMIT happened, publish did not)")
|
||||||
|
os._exit(137)
|
||||||
|
delivered, errors = set(), {}
|
||||||
|
|
||||||
|
for oid, topic, key, payload in rows:
|
||||||
|
msg = json.loads(payload)
|
||||||
|
# PRODUCER span: child of the span that wrote the outbox row (API upload / worker retry); the payload then
|
||||||
|
# carries THIS span's traceparent, so the worker's CONSUMER span becomes its child.
|
||||||
|
span = TRACER.start_span(f"{topic} publish", context=extract(msg), kind=SpanKind.PRODUCER,
|
||||||
|
attributes={"messaging.system": "kafka", "messaging.destination.name": topic,
|
||||||
|
"messaging.operation.type": "publish", "job.id": msg.get("job_id", ""),
|
||||||
|
"job.attempt": msg.get("attempt", 0)})
|
||||||
|
with trace.use_span(span, end_on_exit=False):
|
||||||
|
inject(msg)
|
||||||
|
|
||||||
|
def cb(err, _m, oid=oid, span=span):
|
||||||
|
if err:
|
||||||
|
errors[oid] = str(err)
|
||||||
|
span.set_status(Status(StatusCode.ERROR, "delivery not confirmed"))
|
||||||
|
else:
|
||||||
|
delivered.add(oid) # publisher confirm arrives here
|
||||||
|
span.end()
|
||||||
|
producer.produce(topic, key=key.encode(), value=json.dumps(msg).encode(), on_delivery=cb)
|
||||||
|
producer.flush(15)
|
||||||
|
if delivered:
|
||||||
|
conn.execute("UPDATE outbox SET published_at=now() WHERE id = ANY(%s)", (list(delivered),))
|
||||||
|
if errors:
|
||||||
|
telemetry.log_event(log, logging.WARNING, "outbox_publish_unconfirmed", f"{len(errors)} outbox rows not confirmed by the broker, will retry", count=len(errors))
|
||||||
|
return len(delivered)
|
||||||
|
|
||||||
|
|
||||||
|
def reap(conn) -> int:
|
||||||
|
n = 0
|
||||||
|
with conn.transaction():
|
||||||
|
for job_id, att_id, attempt, max_attempts, pv in conn.execute(
|
||||||
|
"SELECT job_id, attachment_id, attempt, max_attempts, pipeline_version FROM attachment_jobs "
|
||||||
|
"WHERE status='processing' AND lease_until < now() FOR UPDATE SKIP LOCKED").fetchall():
|
||||||
|
if attempt >= max_attempts:
|
||||||
|
jobs.fail_job(conn, job_id, att_id, "retry_exhausted", attempt)
|
||||||
|
else:
|
||||||
|
conn.execute("UPDATE attachment_jobs SET status='queued', lease_until=NULL, next_attempt_at=now(), updated_at=now() WHERE job_id=%s", (job_id,))
|
||||||
|
conn.execute("UPDATE attachments SET status='queued', updated_at=now() WHERE id=%s", (att_id,))
|
||||||
|
jobs.add_event(conn, job_id, "lease_expired", f"attempt={attempt}")
|
||||||
|
jobs.enqueue(conn, job_id, att_id, pv, attempt + 1)
|
||||||
|
n += 1
|
||||||
|
return n
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
producer = Producer({**jobs.kafka_ssl(), "bootstrap.servers": jobs.KAFKA_BOOTSTRAP, "acks": "all", "enable.idempotence": True,
|
||||||
|
"message.timeout.ms": 15000, "linger.ms": 5})
|
||||||
|
telemetry.log_event(log, logging.INFO, "dispatcher_started", f"dispatcher started (poll={POLL_SECONDS:.1f}s)")
|
||||||
|
last_sample = 0.0
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
with psycopg.connect(connect_timeout=5, autocommit=True, options="-c statement_timeout=20000") as conn:
|
||||||
|
while True:
|
||||||
|
done = reap(conn)
|
||||||
|
sent = relay(conn, producer)
|
||||||
|
if done or sent:
|
||||||
|
telemetry.log_event(log, logging.INFO, "dispatcher_cycle", f"reaped={done} published={sent}", count=sent)
|
||||||
|
if time.monotonic() - last_sample >= QUEUE_SAMPLE_SECONDS:
|
||||||
|
sample_queue(conn)
|
||||||
|
last_sample = time.monotonic()
|
||||||
|
if not sent:
|
||||||
|
time.sleep(POLL_SECONDS)
|
||||||
|
except psycopg.Error as exc:
|
||||||
|
log.warning("database unavailable: %s", type(exc).__name__); time.sleep(2)
|
||||||
|
except Exception as exc:
|
||||||
|
log.warning("dispatcher iteration failed: %s", type(exc).__name__); time.sleep(2)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
"""Image pipeline v1. Runs in a CHILD process with hard CPU/address-space limits (called by worker.py).
|
||||||
|
|
||||||
|
python -m src.imgproc <input-file> <output-dir>
|
||||||
|
|
||||||
|
Writes thumbnail.jpg, crop.jpg, optimized.webp and prints JSON metadata on stdout.
|
||||||
|
Exit codes: 0 ok, 2 invalid image, 3 too many pixels, 4 out of memory, other = unexpected (treated as transient).
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import resource
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from PIL import Image, ImageOps
|
||||||
|
|
||||||
|
MAX_IMAGE_PIXELS = int(os.getenv("MAX_IMAGE_PIXELS", "40000000"))
|
||||||
|
THUMB_BOX, CROP_SIZE, OPT_BOX = 256, 128, 1280
|
||||||
|
JPEG_QUALITY, WEBP_QUALITY = 85, 80 # documented in REPORT.md
|
||||||
|
EXIT_INVALID, EXIT_TOO_LARGE, EXIT_OOM = 2, 3, 4
|
||||||
|
|
||||||
|
|
||||||
|
def fit_box(w: int, h: int, box: int) -> tuple[int, int]:
|
||||||
|
"""Fit (w,h) into box x box, keep aspect ratio, never upscale, floor, min 1 px. Integer math: 320x200 -> 256x160."""
|
||||||
|
if w <= box and h <= box:
|
||||||
|
return w, h
|
||||||
|
if w >= h:
|
||||||
|
return box, max(1, h * box // w)
|
||||||
|
return max(1, w * box // h), box
|
||||||
|
|
||||||
|
|
||||||
|
def flatten_on_white(img: Image.Image) -> Image.Image:
|
||||||
|
"""RGB image; any alpha is composited on white (JPEG has no alpha)."""
|
||||||
|
if img.mode in ("RGBA", "LA") or (img.mode == "P" and "transparency" in img.info):
|
||||||
|
rgba = img.convert("RGBA")
|
||||||
|
bg = Image.new("RGB", rgba.size, (255, 255, 255))
|
||||||
|
bg.paste(rgba, mask=rgba.getchannel("A"))
|
||||||
|
return bg
|
||||||
|
return img.convert("RGB")
|
||||||
|
|
||||||
|
|
||||||
|
def save(img: Image.Image, path: Path, fmt: str, **opts) -> dict:
|
||||||
|
img.save(path, fmt, **opts) # no exif=/icc_profile= passed => metadata is stripped
|
||||||
|
data = path.read_bytes()
|
||||||
|
return {"size_bytes": len(data), "width": img.width, "height": img.height, "sha256": hashlib.sha256(data).hexdigest()}
|
||||||
|
|
||||||
|
|
||||||
|
def process(src: Path, out: Path) -> dict:
|
||||||
|
with Image.open(src) as img:
|
||||||
|
if img.format not in ("PNG", "JPEG"):
|
||||||
|
raise ValueError("unsupported format")
|
||||||
|
if img.width < 1 or img.height < 1:
|
||||||
|
raise ValueError("empty image")
|
||||||
|
if img.width * img.height > MAX_IMAGE_PIXELS: # decided from the header, before any pixel buffer exists
|
||||||
|
raise OverflowError("too many pixels")
|
||||||
|
img.load()
|
||||||
|
base = ImageOps.exif_transpose(img) # apply EXIF orientation once; result has no orientation tag
|
||||||
|
base.load()
|
||||||
|
result = {}
|
||||||
|
# thumbnail: JPEG, fit 256x256, no upscale, alpha -> white
|
||||||
|
flat = flatten_on_white(base)
|
||||||
|
t = flat.resize(fit_box(*flat.size, THUMB_BOX), Image.LANCZOS) if fit_box(*flat.size, THUMB_BOX) != flat.size else flat
|
||||||
|
result["thumbnail"] = {"content_type": "image/jpeg", **save(t, out / "thumbnail.jpg", "JPEG", quality=JPEG_QUALITY, optimize=True)}
|
||||||
|
# crop: JPEG, centered square 128x128 (small sources may be upscaled)
|
||||||
|
c = ImageOps.fit(flat, (CROP_SIZE, CROP_SIZE), Image.LANCZOS, centering=(0.5, 0.5))
|
||||||
|
result["crop"] = {"content_type": "image/jpeg", **save(c, out / "crop.jpg", "JPEG", quality=JPEG_QUALITY, optimize=True)}
|
||||||
|
# optimized: WebP, fit 1280x1280, no upscale, keeps alpha, lossy q=80, no EXIF/ICC
|
||||||
|
o = base if base.mode in ("RGB", "RGBA") else (base.convert("RGBA") if "A" in base.getbands() or base.mode == "P" else base.convert("RGB"))
|
||||||
|
size = fit_box(*o.size, OPT_BOX)
|
||||||
|
if size != o.size:
|
||||||
|
o = o.resize(size, Image.LANCZOS)
|
||||||
|
result["optimized"] = {"content_type": "image/webp", **save(o, out / "optimized.webp", "WEBP", quality=WEBP_QUALITY, method=4)}
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
mem_mb, cpu_s = int(os.getenv("IMG_MEMORY_MB", "1024")), int(os.getenv("IMG_CPU_SECONDS", "60"))
|
||||||
|
resource.setrlimit(resource.RLIMIT_AS, (mem_mb * 1024 * 1024, mem_mb * 1024 * 1024))
|
||||||
|
resource.setrlimit(resource.RLIMIT_CPU, (cpu_s, cpu_s + 5))
|
||||||
|
Image.MAX_IMAGE_PIXELS = MAX_IMAGE_PIXELS
|
||||||
|
try:
|
||||||
|
print(json.dumps(process(Path(sys.argv[1]), Path(sys.argv[2]))))
|
||||||
|
return 0
|
||||||
|
except OverflowError:
|
||||||
|
return EXIT_TOO_LARGE
|
||||||
|
except Image.DecompressionBombError:
|
||||||
|
return EXIT_TOO_LARGE
|
||||||
|
except MemoryError:
|
||||||
|
return EXIT_OOM
|
||||||
|
except (ValueError, OSError, SyntaxError, Image.UnidentifiedImageError):
|
||||||
|
return EXIT_INVALID
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
+96
@@ -0,0 +1,96 @@
|
|||||||
|
"""Shared constants and helpers for the API, the worker and the dispatcher (lab 5)."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import random
|
||||||
|
import uuid
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
import boto3
|
||||||
|
from botocore.config import Config as BotoConfig
|
||||||
|
from opentelemetry import trace
|
||||||
|
from opentelemetry.propagate import inject
|
||||||
|
|
||||||
|
KAFKA_BOOTSTRAP = os.getenv("KAFKA_BOOTSTRAP_SERVERS", "kafka:9092")
|
||||||
|
TLS_CA_FILE = os.getenv("TLS_CA_FILE", "/run/pki/ca.crt")
|
||||||
|
|
||||||
|
|
||||||
|
def kafka_ssl() -> dict:
|
||||||
|
"""Lab 7: mTLS to the broker. The certificate CN is the Kafka principal (dispatcher = producer, worker = consumer); ACLs decide the rights."""
|
||||||
|
return {"security.protocol": "SSL", "ssl.ca.location": TLS_CA_FILE,
|
||||||
|
"ssl.certificate.location": os.getenv("TLS_CERT_FILE", "/run/pki/tls.crt"), "ssl.key.location": os.getenv("TLS_KEY_FILE", "/run/pki/tls.key"),
|
||||||
|
"ssl.endpoint.identification.algorithm": "https"}
|
||||||
|
JOBS_TOPIC = os.getenv("JOBS_TOPIC", "attachment-jobs")
|
||||||
|
PIPELINE_VERSION = 1
|
||||||
|
JOB_TYPE = "attachment.process.v1"
|
||||||
|
|
||||||
|
JOB_MAX_ATTEMPTS = int(os.getenv("JOB_MAX_ATTEMPTS", "5"))
|
||||||
|
JOB_TIMEOUT_SECONDS = int(os.getenv("JOB_TIMEOUT_SECONDS", "60"))
|
||||||
|
LEASE_GRACE_SECONDS = int(os.getenv("LEASE_GRACE_SECONDS", "15"))
|
||||||
|
LEASE_SECONDS = JOB_TIMEOUT_SECONDS + LEASE_GRACE_SECONDS # lease > hard job timeout: a live worker never loses it
|
||||||
|
BACKOFF_BASE_SECONDS = float(os.getenv("JOB_BACKOFF_BASE_SECONDS", "2"))
|
||||||
|
BACKOFF_CAP_SECONDS = float(os.getenv("JOB_BACKOFF_CAP_SECONDS", "60"))
|
||||||
|
|
||||||
|
S3_ENDPOINT = os.getenv("S3_ENDPOINT", "https://s3:9000")
|
||||||
|
S3_REGION = os.getenv("S3_REGION", "us-east-1")
|
||||||
|
S3_BUCKET = os.getenv("S3_BUCKET", "messenger-attachments")
|
||||||
|
STAGING_PREFIX = "staging/"
|
||||||
|
FINAL_PREFIX = "attachments/"
|
||||||
|
|
||||||
|
VARIANT_ORDER = ("thumbnail", "crop", "optimized")
|
||||||
|
|
||||||
|
|
||||||
|
def final_key(attachment_id, pipeline_version: int, name: str) -> str:
|
||||||
|
"""Deterministic key: the effect key (attachment_id, pipeline_version, variant) maps 1:1 to an S3 object."""
|
||||||
|
return f"{FINAL_PREFIX}{attachment_id}/v{pipeline_version}/{name}"
|
||||||
|
|
||||||
|
|
||||||
|
def make_s3():
|
||||||
|
return boto3.client(
|
||||||
|
"s3", endpoint_url=S3_ENDPOINT, region_name=S3_REGION, verify=TLS_CA_FILE,
|
||||||
|
aws_access_key_id=os.getenv("S3_ACCESS_KEY_ID", ""), aws_secret_access_key=os.getenv("S3_SECRET_ACCESS_KEY", ""),
|
||||||
|
config=BotoConfig(signature_version="s3v4", s3={"addressing_style": "path"}, connect_timeout=2, read_timeout=20,
|
||||||
|
retries={"max_attempts": 2, "mode": "standard"},
|
||||||
|
request_checksum_calculation="when_required", response_checksum_validation="when_required"))
|
||||||
|
|
||||||
|
|
||||||
|
def backoff_seconds(attempt: int) -> float:
|
||||||
|
"""Exponential backoff with 'equal jitter': delay in [d/2, d], d = min(cap, base * 2^(attempt-1))."""
|
||||||
|
d = min(BACKOFF_CAP_SECONDS, BACKOFF_BASE_SECONDS * (2 ** max(0, attempt - 1)))
|
||||||
|
return random.uniform(d / 2, d)
|
||||||
|
|
||||||
|
|
||||||
|
def iso_now() -> str:
|
||||||
|
return datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z")
|
||||||
|
|
||||||
|
|
||||||
|
def add_event(conn, job_id, event: str, detail: str | None = None) -> None:
|
||||||
|
conn.execute("INSERT INTO job_events(job_id,event,detail) VALUES (%s,%s,%s)", (job_id, event, detail))
|
||||||
|
|
||||||
|
|
||||||
|
def enqueue(conn, job_id, attachment_id, pipeline_version: int, attempt: int, delay_seconds: float = 0.0) -> None:
|
||||||
|
"""Record the intent to publish a job message in the SAME transaction as the state change (transactional outbox).
|
||||||
|
|
||||||
|
The message carries only IDs (jobs.schema.json): no bytes, no credentials, no URLs.
|
||||||
|
Lab 6: the W3C trace context of the CURRENT span is stored in the payload (traceparent/tracestate), so the causal
|
||||||
|
link survives the outbox -> dispatcher -> Kafka -> worker hops (and the retry loop: worker -> enqueue -> ...).
|
||||||
|
"""
|
||||||
|
payload = {"schema_version": 1, "job_id": str(job_id), "type": JOB_TYPE, "attachment_id": str(attachment_id),
|
||||||
|
"pipeline_version": pipeline_version, "attempt": attempt, "created_at": iso_now()}
|
||||||
|
with trace.get_tracer("messenger").start_as_current_span(
|
||||||
|
"outbox.enqueue", attributes={"messaging.system": "kafka", "messaging.destination.name": JOBS_TOPIC, "job.attempt": attempt}):
|
||||||
|
inject(payload) # adds "traceparent" (+ "tracestate" when present): carrier = the JSON payload itself
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO outbox(job_id,topic,msg_key,payload,available_at) VALUES (%s,%s,%s,%s::jsonb, now() + make_interval(secs => %s))",
|
||||||
|
(job_id, JOBS_TOPIC, str(attachment_id), json.dumps(payload), delay_seconds))
|
||||||
|
|
||||||
|
|
||||||
|
def new_job_id() -> uuid.UUID:
|
||||||
|
return uuid.uuid4()
|
||||||
|
|
||||||
|
|
||||||
|
def fail_job(conn, job_id, att_id, code: str, attempt: int) -> None:
|
||||||
|
conn.execute("UPDATE attachment_jobs SET status='failed', error_code=%s, lease_until=NULL, updated_at=now() WHERE job_id=%s", (code, job_id))
|
||||||
|
conn.execute("UPDATE attachments SET status='failed', error_code=%s, updated_at=now() WHERE id=%s", (code, att_id))
|
||||||
|
add_event(conn, job_id, "failed", code)
|
||||||
+869
@@ -0,0 +1,869 @@
|
|||||||
|
"""Lab 7 REST API: lab 6 business API + TLS/mTLS, OpenBao secrets, Argon2id (rehash), shared login rate limit, request size limits."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import anyio
|
||||||
|
import anyio.to_thread
|
||||||
|
import base64
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import secrets
|
||||||
|
import socket
|
||||||
|
import tempfile
|
||||||
|
import time
|
||||||
|
import unicodedata
|
||||||
|
import uuid
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
from urllib.parse import quote
|
||||||
|
|
||||||
|
import psycopg
|
||||||
|
from psycopg_pool import ConnectionPool, PoolTimeout
|
||||||
|
import anyio
|
||||||
|
import boto3
|
||||||
|
import redis
|
||||||
|
from botocore.config import Config as BotoConfig
|
||||||
|
from botocore.exceptions import BotoCoreError, ClientError
|
||||||
|
from PIL import Image
|
||||||
|
from redis.exceptions import RedisError
|
||||||
|
from argon2 import PasswordHasher, Type
|
||||||
|
from argon2.exceptions import InvalidHashError, VerificationError, VerifyMismatchError
|
||||||
|
from fastapi import FastAPI, Request
|
||||||
|
from fastapi.exceptions import RequestValidationError
|
||||||
|
from fastapi.responses import JSONResponse, Response, StreamingResponse
|
||||||
|
from starlette.concurrency import iterate_in_threadpool, run_in_threadpool
|
||||||
|
from starlette.requests import ClientDisconnect
|
||||||
|
from pydantic import BaseModel, ConfigDict, Field, ValidationError
|
||||||
|
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||||
|
|
||||||
|
from opentelemetry import metrics, trace
|
||||||
|
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
|
||||||
|
|
||||||
|
from . import jobs, telemetry, vault
|
||||||
|
|
||||||
|
# Lab 7: secrets (PGPASSWORD, Redis password, S3 keys) come from OpenBao BEFORE any client below is created.
|
||||||
|
vault.load_into_env("api")
|
||||||
|
TLS_CA_FILE = os.getenv("TLS_CA_FILE", "/run/pki/ca.crt")
|
||||||
|
|
||||||
|
# Lab 6: JSON logs on stdout + OTLP (traces, metrics, logs) to the Collector. psycopg/botocore spans are automatic.
|
||||||
|
telemetry.init("messenger-api", instrument=("psycopg", "botocore"))
|
||||||
|
log = logging.getLogger("messenger")
|
||||||
|
DATABASE_URL = os.getenv("DATABASE_URL", "")
|
||||||
|
INSTANCE_ID = os.getenv("INSTANCE_ID") or socket.gethostname()
|
||||||
|
IDEMPOTENCY_KEY_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
|
||||||
|
SESSION_TTL_SECONDS = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
|
||||||
|
if SESSION_TTL_SECONDS < 1:
|
||||||
|
raise RuntimeError("SESSION_TTL_SECONDS must be positive")
|
||||||
|
# Redis uses its connection pool; session keys contain only a hash of the opaque token.
|
||||||
|
# Lab 7: TLS with server verification (CA + hostname) and a dedicated least-privilege ACL user (keys session:* and rl:* only).
|
||||||
|
session_store = redis.Redis(host=os.getenv("REDIS_HOST", "redis"), port=6379, db=0, username="api", password=os.environ["REDIS_PASSWORD"], ssl=True,
|
||||||
|
ssl_ca_certs=TLS_CA_FILE, ssl_cert_reqs="required", ssl_check_hostname=True,
|
||||||
|
decode_responses=True, socket_connect_timeout=3, socket_timeout=3, health_check_interval=30)
|
||||||
|
DB_POOL_MIN_SIZE = int(os.getenv("DB_POOL_MIN_SIZE", "1"))
|
||||||
|
DB_POOL_MAX_SIZE = int(os.getenv("DB_POOL_MAX_SIZE", "10"))
|
||||||
|
DB_POOL_TIMEOUT_SECONDS = float(os.getenv("DB_POOL_TIMEOUT_SECONDS", "5"))
|
||||||
|
if DB_POOL_MIN_SIZE < 1 or DB_POOL_MAX_SIZE < DB_POOL_MIN_SIZE:
|
||||||
|
raise RuntimeError("Invalid PostgreSQL pool size configuration")
|
||||||
|
# Every pooled connection gets bounded connect/query/idle-transaction timeouts.
|
||||||
|
db_pool = ConnectionPool(
|
||||||
|
conninfo=DATABASE_URL,
|
||||||
|
min_size=DB_POOL_MIN_SIZE,
|
||||||
|
max_size=DB_POOL_MAX_SIZE,
|
||||||
|
timeout=DB_POOL_TIMEOUT_SECONDS,
|
||||||
|
kwargs={
|
||||||
|
"connect_timeout": 5,
|
||||||
|
"options": "-c statement_timeout=5000 -c idle_in_transaction_session_timeout=10000",
|
||||||
|
},
|
||||||
|
open=False,
|
||||||
|
name="messenger-postgres",
|
||||||
|
)
|
||||||
|
|
||||||
|
# ---- Lab 4: S3 / attachment limits (names follow .env.example of the lab) ----
|
||||||
|
S3_ENDPOINT = os.getenv("S3_ENDPOINT", "https://s3:9000")
|
||||||
|
S3_REGION = os.getenv("S3_REGION", "us-east-1")
|
||||||
|
S3_BUCKET = os.getenv("S3_BUCKET", "messenger-attachments")
|
||||||
|
S3_ACCESS_KEY_ID = os.getenv("S3_ACCESS_KEY_ID", "")
|
||||||
|
S3_SECRET_ACCESS_KEY = os.getenv("S3_SECRET_ACCESS_KEY", "")
|
||||||
|
S3_KEY_PREFIX = "attachments/"
|
||||||
|
STAGING_PREFIX = jobs.STAGING_PREFIX # lab5: durable staging (private S3 prefix) for bytes accepted but not yet processed
|
||||||
|
MAX_UPLOAD_BYTES = int(os.getenv("MAX_UPLOAD_BYTES", "10485760"))
|
||||||
|
MAX_IMAGE_PIXELS = int(os.getenv("MAX_IMAGE_PIXELS", "40000000"))
|
||||||
|
UPLOAD_IDLE_TIMEOUT_SECONDS = float(os.getenv("UPLOAD_IDLE_TIMEOUT_SECONDS", "10"))
|
||||||
|
UPLOAD_TOTAL_TIMEOUT_SECONDS = float(os.getenv("UPLOAD_TOTAL_TIMEOUT_SECONDS", "60"))
|
||||||
|
IMAGE_DECODE_CONCURRENCY = int(os.getenv("IMAGE_DECODE_CONCURRENCY", "1"))
|
||||||
|
SPOOL_MEMORY_BYTES = 1024 * 1024 # larger bodies roll over to an anonymous temp file, never to RAM
|
||||||
|
CHUNK_BYTES = 64 * 1024
|
||||||
|
# Pillow's own bomb guard is a second line of defence behind the explicit check below.
|
||||||
|
Image.MAX_IMAGE_PIXELS = MAX_IMAGE_PIXELS
|
||||||
|
# Credentials are the restricted application user created by s3_init, never the MinIO root user.
|
||||||
|
_s3_common = dict(endpoint_url=S3_ENDPOINT, region_name=S3_REGION, aws_access_key_id=S3_ACCESS_KEY_ID, aws_secret_access_key=S3_SECRET_ACCESS_KEY, verify=TLS_CA_FILE)
|
||||||
|
s3 = boto3.client("s3", **_s3_common, config=BotoConfig(
|
||||||
|
signature_version="s3v4", s3={"addressing_style": "path"}, connect_timeout=2, read_timeout=20,
|
||||||
|
retries={"max_attempts": 2, "mode": "standard"}, max_pool_connections=32,
|
||||||
|
request_checksum_calculation="when_required", response_checksum_validation="when_required"))
|
||||||
|
# Readiness probe client: one attempt and tight timeouts so HAProxy's 2 s check never hangs on it.
|
||||||
|
s3_probe = boto3.client("s3", **_s3_common, config=BotoConfig(
|
||||||
|
signature_version="s3v4", s3={"addressing_style": "path"}, connect_timeout=1, read_timeout=1,
|
||||||
|
retries={"max_attempts": 1}, request_checksum_calculation="when_required", response_checksum_validation="when_required"))
|
||||||
|
decode_limiter = anyio.CapacityLimiter(IMAGE_DECODE_CONCURRENCY)
|
||||||
|
IMAGE_TYPES = {"PNG": "image/png", "JPEG": "image/jpeg"}
|
||||||
|
USERNAME_RE = re.compile(r"^[a-z0-9_]{3,32}$")
|
||||||
|
# Lab 7: Argon2id with explicit parameters (OWASP minimum 19 MiB, t=2, p=1); parameters are stored inside every hash.
|
||||||
|
ARGON2_MEMORY_KIB = int(os.getenv("ARGON2_MEMORY_KIB", "19456"))
|
||||||
|
ARGON2_ITERATIONS = int(os.getenv("ARGON2_ITERATIONS", "2"))
|
||||||
|
ARGON2_PARALLELISM = int(os.getenv("ARGON2_PARALLELISM", "1"))
|
||||||
|
PASSWORDS = PasswordHasher(time_cost=ARGON2_ITERATIONS, memory_cost=ARGON2_MEMORY_KIB, parallelism=ARGON2_PARALLELISM, type=Type.ID)
|
||||||
|
DUMMY_HASH = PASSWORDS.hash("dummy-password-for-timing-equalisation") # verified for unknown users: same cost as a real login
|
||||||
|
# Login DoS budget: at most N concurrent Argon2 operations per replica (N x ~19 MiB RAM, N cores); extra requests queue or hit the rate limit.
|
||||||
|
HASH_LIMITER = anyio.CapacityLimiter(int(os.getenv("ARGON2_CONCURRENCY", "2")))
|
||||||
|
MAX_JSON_BYTES = int(os.getenv("MAX_JSON_BYTES", "65536"))
|
||||||
|
# Shared (Redis) fixed-window limits: identical counters for every API replica.
|
||||||
|
LOGIN_IP_LIMIT = int(os.getenv("LOGIN_IP_LIMIT", "30")) # attempts per source IP per window
|
||||||
|
LOGIN_USER_FAIL_LIMIT = int(os.getenv("LOGIN_USER_FAIL_LIMIT", "10")) # failed attempts per username per window
|
||||||
|
REGISTER_IP_LIMIT = int(os.getenv("REGISTER_IP_LIMIT", "30"))
|
||||||
|
RATE_WINDOW_SECONDS = int(os.getenv("RATE_WINDOW_SECONDS", "60"))
|
||||||
|
|
||||||
|
class ApiError(Exception):
|
||||||
|
def __init__(self, status: int, code: str, message: str, headers: dict[str, str] | None = None):
|
||||||
|
self.status, self.code, self.message, self.headers = status, code, message, headers or {}
|
||||||
|
|
||||||
|
def fail(status: int, code: str, message: str, headers: dict[str, str] | None = None):
|
||||||
|
raise ApiError(status, code, message, headers)
|
||||||
|
|
||||||
|
class StrictModel(BaseModel):
|
||||||
|
model_config = ConfigDict(extra="forbid", strict=True)
|
||||||
|
|
||||||
|
class RegisterBody(StrictModel):
|
||||||
|
username: str
|
||||||
|
display_name: str
|
||||||
|
password: str
|
||||||
|
|
||||||
|
class ChatBody(StrictModel):
|
||||||
|
title: str
|
||||||
|
member_ids: list[str] = Field(min_length=1, max_length=100)
|
||||||
|
|
||||||
|
class MessageBody(StrictModel):
|
||||||
|
text: str
|
||||||
|
attachment_ids: list[str] = Field(default_factory=list, max_length=10)
|
||||||
|
|
||||||
|
app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)
|
||||||
|
|
||||||
|
# ---- Lab 6: HTTP metrics (names/units: REPORT.md). Labels are LOW cardinality: method, route TEMPLATE, status class. ----
|
||||||
|
HTTP_DURATION = telemetry.meter().create_histogram(
|
||||||
|
"http.server.request.duration", unit="s", description="Server-side duration of business HTTP requests (health excluded)",
|
||||||
|
explicit_bucket_boundaries_advisory=[0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60])
|
||||||
|
KNOWN_METHODS = {"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"}
|
||||||
|
|
||||||
|
def observe_http(request: Request, status: int, started: float) -> None:
|
||||||
|
if request.url.path.startswith("/health/"):
|
||||||
|
return # error ratio denominator = business requests, health probes are excluded
|
||||||
|
route = getattr(request.scope.get("route"), "path", None) or "unmatched" # "/api/v1/chats/{chat_id}/messages", never a real UUID
|
||||||
|
HTTP_DURATION.record(time.perf_counter() - started, {
|
||||||
|
"http.request.method": request.method if request.method in KNOWN_METHODS else "OTHER",
|
||||||
|
"http.route": route, "http.response.status_class": f"{status // 100}xx"})
|
||||||
|
|
||||||
|
def _pool_gauge(field: str):
|
||||||
|
def callback(_options):
|
||||||
|
stats = db_pool.get_stats()
|
||||||
|
value = stats["pool_size"] - stats["pool_available"] if field == "used" else stats[field]
|
||||||
|
yield metrics.Observation(value, {"pool.name": "messenger-postgres"})
|
||||||
|
return callback
|
||||||
|
|
||||||
|
for _name, _field, _desc in (("messenger.db.pool.used", "used", "Connections checked out of the pool"),
|
||||||
|
("messenger.db.pool.waiting", "requests_waiting", "Requests waiting for a free pooled connection")):
|
||||||
|
telemetry.meter().create_observable_gauge(_name, callbacks=[_pool_gauge(_field)], unit="{connection}", description=_desc)
|
||||||
|
telemetry.register_process_metrics()
|
||||||
|
|
||||||
|
@app.middleware("http")
|
||||||
|
async def request_id_middleware(request: Request, call_next):
|
||||||
|
request.state.request_id = uuid.uuid4().hex
|
||||||
|
started = time.perf_counter()
|
||||||
|
# X-Request-Id <-> trace: the id is stored on the server span; logs carry both request_id and trace_id.
|
||||||
|
trace.get_current_span().set_attribute("messenger.request_id", request.state.request_id)
|
||||||
|
try:
|
||||||
|
response = await call_next(request)
|
||||||
|
except Exception as exc:
|
||||||
|
telemetry.log_event(log, logging.ERROR, "unhandled_exception", "Unhandled API exception", request_id=request.state.request_id, reason=type(exc).__name__)
|
||||||
|
response = JSONResponse(status_code=500, content={"error": {"code": "internal_error", "message": "Internal server error", "request_id": request.state.request_id}})
|
||||||
|
response.headers["X-Request-Id"] = request.state.request_id
|
||||||
|
response.headers["X-Instance-Id"] = INSTANCE_ID
|
||||||
|
observe_http(request, response.status_code, started)
|
||||||
|
return response
|
||||||
|
|
||||||
|
# Added LAST => outermost middleware: the server span is active inside request_id_middleware. No metrics from the instrumentor:
|
||||||
|
# our own histogram above is the only HTTP metric (no duplicate instruments). Health probes produce no spans.
|
||||||
|
FastAPIInstrumentor.instrument_app(app, excluded_urls="/health/(live|ready)", meter_provider=metrics.NoOpMeterProvider())
|
||||||
|
|
||||||
|
def error_response(status: int, code: str, message: str, request_id: str, headers: dict[str, str] | None = None):
|
||||||
|
return JSONResponse(status_code=status, content={"error": {"code": code, "message": message, "request_id": request_id}}, headers=headers or {})
|
||||||
|
|
||||||
|
@app.exception_handler(ApiError)
|
||||||
|
async def api_error_handler(request: Request, exc: ApiError):
|
||||||
|
return error_response(exc.status, exc.code, exc.message, request.state.request_id, exc.headers)
|
||||||
|
|
||||||
|
@app.exception_handler(PoolTimeout)
|
||||||
|
async def database_pool_timeout_handler(request: Request, exc: PoolTimeout):
|
||||||
|
telemetry.log_event(log, logging.WARNING, "db_pool_timeout", "Database connection pool timed out", request_id=request.state.request_id)
|
||||||
|
return error_response(503, "unavailable", "Required storage is unavailable", request.state.request_id)
|
||||||
|
|
||||||
|
@app.exception_handler(psycopg.Error)
|
||||||
|
async def database_error_handler(request: Request, exc: psycopg.Error):
|
||||||
|
telemetry.log_event(log, logging.WARNING, "db_error", "Database operation failed", request_id=request.state.request_id, reason=type(exc).__name__)
|
||||||
|
return error_response(503, "unavailable", "Required storage is unavailable", request.state.request_id)
|
||||||
|
|
||||||
|
@app.exception_handler(RedisError)
|
||||||
|
async def redis_error_handler(request: Request, exc: RedisError):
|
||||||
|
telemetry.log_event(log, logging.WARNING, "session_store_error", "Session store operation failed", request_id=request.state.request_id)
|
||||||
|
return error_response(503, "unavailable", "Required storage is unavailable", request.state.request_id)
|
||||||
|
|
||||||
|
@app.exception_handler(BotoCoreError)
|
||||||
|
async def s3_core_error_handler(request: Request, exc: BotoCoreError):
|
||||||
|
telemetry.log_event(log, logging.WARNING, "s3_error", "Object storage failure", request_id=request.state.request_id, reason=type(exc).__name__)
|
||||||
|
return error_response(503, "unavailable", "Required storage is unavailable", request.state.request_id)
|
||||||
|
|
||||||
|
@app.exception_handler(ClientError)
|
||||||
|
async def s3_client_error_handler(request: Request, exc: ClientError):
|
||||||
|
telemetry.log_event(log, logging.WARNING, "s3_error", "Object storage error", request_id=request.state.request_id, reason=str(exc.response.get("Error", {}).get("Code")))
|
||||||
|
return error_response(503, "unavailable", "Required storage is unavailable", request.state.request_id)
|
||||||
|
|
||||||
|
@app.exception_handler(RequestValidationError)
|
||||||
|
async def validation_error_handler(request: Request, exc: RequestValidationError):
|
||||||
|
return error_response(400, "invalid_request", "Invalid request", request.state.request_id)
|
||||||
|
|
||||||
|
@app.exception_handler(StarletteHTTPException)
|
||||||
|
async def http_error_handler(request: Request, exc: StarletteHTTPException):
|
||||||
|
status = exc.status_code
|
||||||
|
code = "not_found" if status == 404 else "invalid_request"
|
||||||
|
message = "Object not found" if status == 404 else "Invalid request"
|
||||||
|
headers = dict(exc.headers or {})
|
||||||
|
return error_response(status, code, message, request.state.request_id, headers)
|
||||||
|
|
||||||
|
def db():
|
||||||
|
"""Borrow a bounded pooled connection; context exit commits/rolls back and returns it."""
|
||||||
|
return db_pool.connection(timeout=DB_POOL_TIMEOUT_SECONDS)
|
||||||
|
|
||||||
|
@app.on_event("startup")
|
||||||
|
def startup():
|
||||||
|
# Migrations run once in the dedicated `migrate` service before API replicas.
|
||||||
|
db_pool.open(wait=False)
|
||||||
|
last_error = None
|
||||||
|
for _ in range(30):
|
||||||
|
try:
|
||||||
|
with db() as conn:
|
||||||
|
conn.execute("SELECT 1")
|
||||||
|
conn.execute("SELECT 1 FROM idempotency_records LIMIT 0")
|
||||||
|
conn.execute("SELECT 1 FROM outbox LIMIT 0")
|
||||||
|
session_store.ping()
|
||||||
|
s3.head_object(Bucket=S3_BUCKET, Key=S3_KEY_PREFIX + ".ready")
|
||||||
|
telemetry.log_event(log, logging.INFO, "api_ready", f"PostgreSQL, Redis and S3 bucket are ready; instance={INSTANCE_ID}")
|
||||||
|
return
|
||||||
|
except Exception as exc:
|
||||||
|
last_error = exc
|
||||||
|
time.sleep(1)
|
||||||
|
raise RuntimeError("PostgreSQL schema, Redis or S3 bucket unavailable during startup") from last_error
|
||||||
|
|
||||||
|
@app.on_event("shutdown")
|
||||||
|
def shutdown():
|
||||||
|
session_store.close()
|
||||||
|
db_pool.close()
|
||||||
|
|
||||||
|
def now_utc() -> datetime:
|
||||||
|
return datetime.now(timezone.utc)
|
||||||
|
|
||||||
|
def iso(value: datetime) -> str:
|
||||||
|
return value.astimezone(timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z")
|
||||||
|
|
||||||
|
def user_dict(row: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
return {"id": str(row["id"]), "username": row["username"], "display_name": row["display_name"], "created_at": iso(row["created_at"])}
|
||||||
|
|
||||||
|
def chat_dict(row: dict[str, Any], member_ids: list[str]) -> dict[str, Any]:
|
||||||
|
return {"id": str(row["id"]), "title": row["title"], "member_ids": member_ids, "created_at": iso(row["created_at"])}
|
||||||
|
|
||||||
|
def message_dict(row: dict[str, Any], attachment_ids: list[str] | None = None) -> dict[str, Any]:
|
||||||
|
return {"id": str(row["id"]), "chat_id": str(row["chat_id"]), "sender_id": str(row["sender_id"]), "text": row["text"], "created_at": iso(row["created_at"]), "attachment_ids": attachment_ids or []}
|
||||||
|
|
||||||
|
def validate_unicode(value: str, label: str) -> str:
|
||||||
|
"""Reject unpaired UTF-16 surrogates before sending text to PostgreSQL/KDF."""
|
||||||
|
try:
|
||||||
|
value.encode("utf-8")
|
||||||
|
except UnicodeEncodeError:
|
||||||
|
fail(400, "invalid_request", "Invalid Unicode in " + label)
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def parse_uuid(value: str, label: str = "UUID") -> uuid.UUID:
|
||||||
|
try:
|
||||||
|
# Keep the canonical UUID representation used by the Lab 1 API.
|
||||||
|
if not isinstance(value, str) or len(value) != 36:
|
||||||
|
raise ValueError("non-canonical UUID")
|
||||||
|
parsed = uuid.UUID(value)
|
||||||
|
if str(parsed) != value:
|
||||||
|
raise ValueError("non-canonical UUID")
|
||||||
|
return parsed
|
||||||
|
except (ValueError, TypeError, AttributeError):
|
||||||
|
fail(400, "invalid_request", "Invalid " + label)
|
||||||
|
|
||||||
|
def validate_body_type(request: Request):
|
||||||
|
content_type = request.headers.get("content-type", "").split(";", 1)[0].strip().lower()
|
||||||
|
if content_type != "application/json":
|
||||||
|
fail(415, "unsupported_media_type", "Content-Type must be application/json")
|
||||||
|
|
||||||
|
async def parse_body(request: Request, model):
|
||||||
|
validate_body_type(request)
|
||||||
|
try:
|
||||||
|
raw = await request.body()
|
||||||
|
if len(raw) > MAX_JSON_BYTES:
|
||||||
|
fail(413, "payload_too_large", "JSON body is too large")
|
||||||
|
data = json.loads(raw.decode("utf-8"))
|
||||||
|
return model.model_validate(data)
|
||||||
|
except (UnicodeDecodeError, json.JSONDecodeError, ValidationError, TypeError):
|
||||||
|
fail(400, "invalid_request", "Invalid JSON request body")
|
||||||
|
|
||||||
|
def challenge(scheme: str) -> dict[str, str]:
|
||||||
|
if scheme == "Basic":
|
||||||
|
return {"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'}
|
||||||
|
return {"WWW-Authenticate": 'Bearer realm="messenger"'}
|
||||||
|
|
||||||
|
def current_user(request: Request) -> dict[str, Any]:
|
||||||
|
auth = request.headers.get("authorization", "")
|
||||||
|
if not auth.startswith("Bearer ") or not auth[7:].strip():
|
||||||
|
fail(401, "unauthorized", "Valid Bearer session required", challenge("Bearer"))
|
||||||
|
token_hash = hashlib.sha256(auth[7:].strip().encode("utf-8")).hexdigest()
|
||||||
|
session_json = session_store.get("session:" + token_hash)
|
||||||
|
if session_json is None:
|
||||||
|
fail(401, "unauthorized", "Valid Bearer session required", challenge("Bearer"))
|
||||||
|
try:
|
||||||
|
session = json.loads(session_json)
|
||||||
|
user_id = uuid.UUID(session["user_id"])
|
||||||
|
expires_at = datetime.fromisoformat(session["expires_at"].replace("Z", "+00:00"))
|
||||||
|
except (ValueError, KeyError, TypeError, json.JSONDecodeError):
|
||||||
|
# Corrupt session data is invalidated instead of trusted.
|
||||||
|
session_store.delete("session:" + token_hash)
|
||||||
|
fail(401, "unauthorized", "Valid Bearer session required", challenge("Bearer"))
|
||||||
|
if expires_at <= now_utc():
|
||||||
|
session_store.delete("session:" + token_hash)
|
||||||
|
fail(401, "unauthorized", "Valid Bearer session required", challenge("Bearer"))
|
||||||
|
with db() as conn:
|
||||||
|
row = conn.execute("SELECT id,username,display_name,created_at FROM users WHERE id=%s", (user_id,)).fetchone()
|
||||||
|
if row is None:
|
||||||
|
session_store.delete("session:" + token_hash)
|
||||||
|
fail(401, "unauthorized", "Valid Bearer session required", challenge("Bearer"))
|
||||||
|
return {"id": row[0], "username": row[1], "display_name": row[2], "created_at": row[3], "expires_at": expires_at, "user": {"id": str(row[0]), "username": row[1], "display_name": row[2], "created_at": iso(row[3])}, "token_hash": token_hash}
|
||||||
|
|
||||||
|
def ensure_member(actor_id: uuid.UUID, chat_id: uuid.UUID):
|
||||||
|
with db() as conn:
|
||||||
|
row = conn.execute("SELECT 1 FROM chats c JOIN chat_members m ON m.chat_id=c.id WHERE c.id=%s AND m.user_id=%s", (chat_id, actor_id)).fetchone()
|
||||||
|
if row is None:
|
||||||
|
fail(404, "not_found", "Object not found")
|
||||||
|
|
||||||
|
def parse_page_args(limit: int | None, cursor: str | None, resource: str):
|
||||||
|
actual_limit = 50 if limit is None else limit
|
||||||
|
if isinstance(actual_limit, bool) or actual_limit < 1 or actual_limit > 100:
|
||||||
|
fail(400, "invalid_request", "limit must be an integer from 1 to 100")
|
||||||
|
after = None
|
||||||
|
if cursor is not None:
|
||||||
|
if not cursor:
|
||||||
|
fail(400, "invalid_request", "Invalid cursor")
|
||||||
|
try:
|
||||||
|
decoded = base64.urlsafe_b64decode(cursor + "=" * (-len(cursor) % 4)).decode("utf-8")
|
||||||
|
obj = json.loads(decoded)
|
||||||
|
if obj.get("resource") != resource:
|
||||||
|
fail(400, "invalid_request", "Cursor belongs to another resource")
|
||||||
|
after = (datetime.fromisoformat(obj["created_at"].replace("Z", "+00:00")), uuid.UUID(obj["id"]))
|
||||||
|
except ApiError:
|
||||||
|
raise
|
||||||
|
except Exception:
|
||||||
|
fail(400, "invalid_request", "Invalid cursor")
|
||||||
|
return actual_limit, after
|
||||||
|
|
||||||
|
def make_cursor(resource: str, created_at: datetime, item_id: uuid.UUID) -> str:
|
||||||
|
raw = json.dumps({"resource": resource, "created_at": iso(created_at), "id": str(item_id)}, separators=(",", ":")).encode()
|
||||||
|
return base64.urlsafe_b64encode(raw).decode().rstrip("=")
|
||||||
|
|
||||||
|
def json_rows(cursor, query: str, params=()):
|
||||||
|
with db() as conn:
|
||||||
|
cur = conn.execute(query, params)
|
||||||
|
names = [d.name for d in cur.description]
|
||||||
|
return [dict(zip(names, row)) for row in cur.fetchall()]
|
||||||
|
|
||||||
|
@app.get("/health/live")
|
||||||
|
def live():
|
||||||
|
return {"status": "ok"}
|
||||||
|
|
||||||
|
@app.get("/health/ready")
|
||||||
|
def ready():
|
||||||
|
try:
|
||||||
|
with db() as conn:
|
||||||
|
conn.execute("SELECT 1")
|
||||||
|
session_store.ping()
|
||||||
|
s3_probe.head_object(Bucket=S3_BUCKET, Key=S3_KEY_PREFIX + ".ready") # S3 is critical: uploads/downloads are part of the mandatory path
|
||||||
|
return {"status": "ok"}
|
||||||
|
except (psycopg.Error, PoolTimeout, RedisError, BotoCoreError, ClientError):
|
||||||
|
fail(503, "unavailable", "Required storage is unavailable")
|
||||||
|
|
||||||
|
def client_ip(request: Request) -> str:
|
||||||
|
"""The LB (the only allowed mTLS client) overwrites X-Real-IP with the TCP source address; the client cannot forge it."""
|
||||||
|
return request.headers.get("x-real-ip", "unknown")[:45]
|
||||||
|
|
||||||
|
def hit(key: str, window: int) -> tuple[int, int]:
|
||||||
|
"""Increment a shared Redis counter; returns (count, seconds_left). INCR + EXPIRE NX in one MULTI/EXEC."""
|
||||||
|
pipe = session_store.pipeline(transaction=True)
|
||||||
|
pipe.incr(key); pipe.expire(key, window, nx=True); pipe.ttl(key)
|
||||||
|
count, _, ttl = pipe.execute()
|
||||||
|
return int(count), max(int(ttl), 1)
|
||||||
|
|
||||||
|
def too_many(retry_after: int):
|
||||||
|
fail(429, "rate_limited", "Too many requests", {"Retry-After": str(retry_after)})
|
||||||
|
|
||||||
|
@app.post("/api/v1/users", status_code=201)
|
||||||
|
async def register(request: Request):
|
||||||
|
body = await parse_body(request, RegisterBody)
|
||||||
|
if not USERNAME_RE.fullmatch(body.username):
|
||||||
|
fail(400, "invalid_request", "Invalid username")
|
||||||
|
validate_unicode(body.display_name, "display_name")
|
||||||
|
validate_unicode(body.password, "password")
|
||||||
|
if not body.display_name.strip() or len(body.display_name) > 100:
|
||||||
|
fail(400, "invalid_request", "Invalid display_name")
|
||||||
|
if not 12 <= len(body.password) <= 128:
|
||||||
|
fail(400, "invalid_request", "Password must contain 12 to 128 Unicode code points")
|
||||||
|
count, ttl = hit("rl:reg:ip:" + client_ip(request), RATE_WINDOW_SECONDS)
|
||||||
|
if count > REGISTER_IP_LIMIT:
|
||||||
|
too_many(ttl)
|
||||||
|
user_id = uuid.uuid4()
|
||||||
|
password_hash = await anyio.to_thread.run_sync(PASSWORDS.hash, body.password, limiter=HASH_LIMITER)
|
||||||
|
try:
|
||||||
|
with db() as conn:
|
||||||
|
row = conn.execute("INSERT INTO users(id,username,display_name,password_hash) VALUES (%s,%s,%s,%s) RETURNING id,username,display_name,created_at", (user_id, body.username, body.display_name, password_hash)).fetchone()
|
||||||
|
except psycopg.errors.UniqueViolation:
|
||||||
|
fail(409, "conflict", "Username already exists")
|
||||||
|
return user_dict(dict(zip(("id", "username", "display_name", "created_at"), row)))
|
||||||
|
|
||||||
|
@app.get("/api/v1/users/me")
|
||||||
|
def me(request: Request):
|
||||||
|
return current_user(request)["user"]
|
||||||
|
|
||||||
|
@app.post("/api/v1/auth/sessions", status_code=201)
|
||||||
|
async def create_session(request: Request):
|
||||||
|
if await request.body():
|
||||||
|
fail(400, "invalid_request", "Session creation does not accept a request body")
|
||||||
|
auth = request.headers.get("authorization", "")
|
||||||
|
if not auth[:6].lower() == "basic ":
|
||||||
|
fail(401, "unauthorized", "Valid Basic credentials required", challenge("Basic"))
|
||||||
|
try:
|
||||||
|
decoded = base64.b64decode(auth[6:], validate=True).decode("utf-8")
|
||||||
|
username, password = decoded.split(":", 1)
|
||||||
|
except Exception:
|
||||||
|
fail(401, "unauthorized", "Invalid credentials", challenge("Basic"))
|
||||||
|
try:
|
||||||
|
validate_unicode(password, "password")
|
||||||
|
except ApiError:
|
||||||
|
fail(401, "unauthorized", "Invalid credentials", challenge("Basic"))
|
||||||
|
if not password or len(password) < 12 or len(password) > 128:
|
||||||
|
fail(401, "unauthorized", "Invalid credentials", challenge("Basic"))
|
||||||
|
# Lab 7: shared rate limit BEFORE any expensive work. Per-IP: every attempt; per-username: failed attempts only.
|
||||||
|
ip_count, ip_ttl = hit("rl:login:ip:" + client_ip(request), RATE_WINDOW_SECONDS)
|
||||||
|
if ip_count > LOGIN_IP_LIMIT:
|
||||||
|
too_many(ip_ttl)
|
||||||
|
user_key = "rl:login:user:" + hashlib.sha256(username.encode("utf-8")).hexdigest()[:32] # no raw username in Redis keys
|
||||||
|
failed = session_store.get(user_key)
|
||||||
|
if failed is not None and int(failed) >= LOGIN_USER_FAIL_LIMIT:
|
||||||
|
too_many(max(session_store.ttl(user_key), 1))
|
||||||
|
with db() as conn:
|
||||||
|
row = conn.execute("SELECT id,username,display_name,password_hash,created_at FROM users WHERE username=%s", (username,)).fetchone()
|
||||||
|
stored_hash = row[3] if row is not None else DUMMY_HASH # unknown user costs the same Argon2 time: no enumeration by timing
|
||||||
|
try:
|
||||||
|
await anyio.to_thread.run_sync(PASSWORDS.verify, stored_hash, password, limiter=HASH_LIMITER)
|
||||||
|
verified = row is not None
|
||||||
|
except (VerifyMismatchError, VerificationError, InvalidHashError):
|
||||||
|
verified = False
|
||||||
|
if not verified:
|
||||||
|
count, ttl = hit(user_key, RATE_WINDOW_SECONDS)
|
||||||
|
if count > LOGIN_USER_FAIL_LIMIT:
|
||||||
|
too_many(ttl)
|
||||||
|
fail(401, "unauthorized", "Invalid credentials", challenge("Basic"))
|
||||||
|
session_store.delete(user_key)
|
||||||
|
# Lab 7: transparent upgrade of old hashes (lab 6 used library defaults m=64 MiB,t=3,p=4) to the current parameters.
|
||||||
|
if PASSWORDS.check_needs_rehash(row[3]):
|
||||||
|
new_hash = await anyio.to_thread.run_sync(PASSWORDS.hash, password, limiter=HASH_LIMITER)
|
||||||
|
with db() as conn:
|
||||||
|
conn.execute("UPDATE users SET password_hash=%s WHERE id=%s AND password_hash=%s", (new_hash, row[0], row[3]))
|
||||||
|
token = secrets.token_urlsafe(32)
|
||||||
|
token_hash = hashlib.sha256(token.encode()).hexdigest()
|
||||||
|
expires_at = now_utc() + timedelta(seconds=SESSION_TTL_SECONDS)
|
||||||
|
session_json = json.dumps({"user_id": str(row[0]), "expires_at": iso(expires_at)}, separators=(",", ":"))
|
||||||
|
# Redis TTL enforces expiry; AOF + named volume make active sessions survive stack restarts.
|
||||||
|
session_store.setex("session:" + token_hash, SESSION_TTL_SECONDS, session_json)
|
||||||
|
user = user_dict({"id": row[0], "username": row[1], "display_name": row[2], "created_at": row[4]})
|
||||||
|
return {"token": token, "token_type": "Bearer", "expires_at": iso(expires_at), "user": user}
|
||||||
|
|
||||||
|
@app.delete("/api/v1/auth/sessions/current", status_code=204)
|
||||||
|
def revoke_session(request: Request):
|
||||||
|
actor = current_user(request)
|
||||||
|
session_store.delete("session:" + actor["token_hash"])
|
||||||
|
return Response(status_code=204)
|
||||||
|
|
||||||
|
@app.post("/api/v1/chats", status_code=201)
|
||||||
|
async def create_chat(request: Request):
|
||||||
|
actor = current_user(request)
|
||||||
|
body = await parse_body(request, ChatBody)
|
||||||
|
validate_unicode(body.title, "title")
|
||||||
|
if not body.title.strip() or len(body.title) > 100:
|
||||||
|
fail(400, "invalid_request", "Invalid title")
|
||||||
|
ids = [parse_uuid(value, "member UUID") for value in body.member_ids]
|
||||||
|
if len(ids) != len(set(ids)) or actor["id"] not in ids:
|
||||||
|
fail(400, "invalid_request", "Members must be unique and include the caller")
|
||||||
|
chat_id = uuid.uuid4()
|
||||||
|
try:
|
||||||
|
with db() as conn:
|
||||||
|
existing = conn.execute("SELECT id FROM users WHERE id = ANY(%s)", (ids,)).fetchall()
|
||||||
|
if len(existing) != len(ids):
|
||||||
|
fail(400, "invalid_request", "Unknown chat member")
|
||||||
|
row = conn.execute("INSERT INTO chats(id,title) VALUES (%s,%s) RETURNING id,title,created_at", (chat_id, body.title)).fetchone()
|
||||||
|
# psycopg 3: executemany exists on cursors, not on Connection (fix of a latent lab3 bug)
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.executemany("INSERT INTO chat_members(chat_id,user_id,position) VALUES (%s,%s,%s)", [(chat_id, uid, position) for position, uid in enumerate(ids)])
|
||||||
|
except psycopg.errors.ForeignKeyViolation:
|
||||||
|
fail(400, "invalid_request", "Unknown chat member")
|
||||||
|
return chat_dict({"id": row[0], "title": row[1], "created_at": row[2]}, [str(x) for x in ids])
|
||||||
|
|
||||||
|
@app.get("/api/v1/chats")
|
||||||
|
def list_chats(request: Request, limit: int | None = None, cursor: str | None = None):
|
||||||
|
actor = current_user(request)
|
||||||
|
chat_list_resource = "chats:" + str(actor["id"])
|
||||||
|
actual_limit, after = parse_page_args(limit, cursor, chat_list_resource)
|
||||||
|
params: list[Any] = [actor["id"]]
|
||||||
|
where = "m.user_id=%s"
|
||||||
|
if after:
|
||||||
|
where += " AND (c.created_at,c.id)>(%s,%s)"
|
||||||
|
params.extend(after)
|
||||||
|
params.append(actual_limit + 1)
|
||||||
|
rows = json_rows(None, f"SELECT c.id,c.title,c.created_at FROM chats c JOIN chat_members m ON m.chat_id=c.id WHERE {where} ORDER BY c.created_at,c.id LIMIT %s", tuple(params))
|
||||||
|
more = len(rows) > actual_limit
|
||||||
|
rows = rows[:actual_limit]
|
||||||
|
items = []
|
||||||
|
for row in rows:
|
||||||
|
members = json_rows(None, "SELECT user_id FROM chat_members WHERE chat_id=%s ORDER BY position,user_id", (row["id"],))
|
||||||
|
items.append(chat_dict(row, [str(m["user_id"]) for m in members]))
|
||||||
|
next_cursor = make_cursor(chat_list_resource, rows[-1]["created_at"], rows[-1]["id"]) if more and rows else None
|
||||||
|
return {"items": items, "next_cursor": next_cursor}
|
||||||
|
|
||||||
|
@app.get("/api/v1/chats/{chat_id}")
|
||||||
|
def get_chat(chat_id: str, request: Request):
|
||||||
|
actor = current_user(request)
|
||||||
|
parsed = parse_uuid(chat_id, "chat UUID")
|
||||||
|
ensure_member(actor["id"], parsed)
|
||||||
|
rows = json_rows(None, "SELECT id,title,created_at FROM chats WHERE id=%s", (parsed,))
|
||||||
|
members = json_rows(None, "SELECT user_id FROM chat_members WHERE chat_id=%s ORDER BY position,user_id", (parsed,))
|
||||||
|
return chat_dict(rows[0], [str(m["user_id"]) for m in members])
|
||||||
|
|
||||||
|
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
|
||||||
|
async def create_message(chat_id: str, request: Request):
|
||||||
|
actor = current_user(request)
|
||||||
|
parsed_chat = parse_uuid(chat_id, "chat UUID")
|
||||||
|
ensure_member(actor["id"], parsed_chat)
|
||||||
|
body = await parse_body(request, MessageBody)
|
||||||
|
validate_unicode(body.text, "text")
|
||||||
|
attachment_ids = [parse_uuid(value, "attachment UUID") for value in body.attachment_ids]
|
||||||
|
if len(attachment_ids) != len(set(attachment_ids)):
|
||||||
|
fail(400, "invalid_request", "attachment_ids must be unique")
|
||||||
|
if len(body.text) > 4000 or (not body.text.strip() and not attachment_ids):
|
||||||
|
fail(400, "invalid_request", "Message needs 1 to 4000 non-whitespace code points of text or at least one attachment")
|
||||||
|
|
||||||
|
key = request.headers.get("Idempotency-Key", "")
|
||||||
|
if not IDEMPOTENCY_KEY_RE.fullmatch(key):
|
||||||
|
fail(400, "invalid_request", "Idempotency-Key must contain 1 to 128 ASCII letters, digits, '.', '_', ':', or '-'")
|
||||||
|
|
||||||
|
# Hash semantic JSON rather than raw bytes, so insignificant JSON formatting does not matter.
|
||||||
|
# attachment_ids is part of the hash only when non-empty: absent == [] and lab3 records stay valid.
|
||||||
|
canonical = {"text": body.text}
|
||||||
|
if attachment_ids:
|
||||||
|
canonical["attachment_ids"] = [str(x) for x in attachment_ids]
|
||||||
|
canonical_body = json.dumps(canonical, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
|
||||||
|
request_hash = hashlib.sha256(canonical_body.encode("utf-8")).hexdigest()
|
||||||
|
scope = f"{actor['id']}|POST|/api/v1/chats/{parsed_chat}/messages|{key}"
|
||||||
|
|
||||||
|
# The advisory transaction lock serializes the same key across every API replica.
|
||||||
|
# Message and idempotency result are committed atomically in the same PostgreSQL transaction.
|
||||||
|
with db() as conn:
|
||||||
|
conn.execute("SELECT pg_advisory_xact_lock(hashtextextended(%s, 0))", (scope,))
|
||||||
|
existing = conn.execute(
|
||||||
|
"SELECT request_hash, response_body FROM idempotency_records "
|
||||||
|
"WHERE user_id=%s AND chat_id=%s AND idempotency_key=%s AND created_at >= now() - interval '24 hours'",
|
||||||
|
(actor["id"], parsed_chat, key),
|
||||||
|
).fetchone()
|
||||||
|
if existing is not None:
|
||||||
|
if existing[0] != request_hash:
|
||||||
|
fail(409, "conflict", "Idempotency-Key was already used with a different request body")
|
||||||
|
replay = dict(existing[1])
|
||||||
|
replay.setdefault("attachment_ids", [])
|
||||||
|
return JSONResponse(status_code=201, content=replay)
|
||||||
|
|
||||||
|
# Keys are guaranteed for 24 hours; expired records may be replaced by a new attempt.
|
||||||
|
conn.execute(
|
||||||
|
"DELETE FROM idempotency_records WHERE user_id=%s AND chat_id=%s AND idempotency_key=%s AND created_at < now() - interval '24 hours'",
|
||||||
|
(actor["id"], parsed_chat, key),
|
||||||
|
)
|
||||||
|
if attachment_ids:
|
||||||
|
# Foreign, unknown and other-chat attachments are indistinguishable: all -> 404.
|
||||||
|
found = conn.execute("SELECT count(*) FROM attachments WHERE id = ANY(%s) AND chat_id=%s", (attachment_ids, parsed_chat)).fetchone()[0]
|
||||||
|
if found != len(attachment_ids):
|
||||||
|
fail(404, "not_found", "Object not found")
|
||||||
|
# lab5: queued/processing attachments may be attached, failed ones may not
|
||||||
|
if conn.execute("SELECT 1 FROM attachments WHERE id = ANY(%s) AND status='failed' LIMIT 1", (attachment_ids,)).fetchone():
|
||||||
|
fail(409, "conflict", "Attachment processing failed")
|
||||||
|
row = conn.execute(
|
||||||
|
"INSERT INTO messages(id,chat_id,sender_id,text) VALUES (%s,%s,%s,%s) "
|
||||||
|
"RETURNING id,chat_id,sender_id,text,created_at",
|
||||||
|
(uuid.uuid4(), parsed_chat, actor["id"], body.text),
|
||||||
|
).fetchone()
|
||||||
|
result = message_dict(dict(zip(("id", "chat_id", "sender_id", "text", "created_at"), row)), [str(x) for x in attachment_ids])
|
||||||
|
if attachment_ids:
|
||||||
|
with conn.cursor() as cur:
|
||||||
|
cur.executemany("INSERT INTO message_attachments(message_id,attachment_id,position) VALUES (%s,%s,%s)", [(row[0], aid, i) for i, aid in enumerate(attachment_ids)])
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO idempotency_records(user_id,chat_id,idempotency_key,request_hash,response_body) "
|
||||||
|
"VALUES (%s,%s,%s,%s,%s::jsonb)",
|
||||||
|
(actor["id"], parsed_chat, key, request_hash, json.dumps(result, ensure_ascii=False)),
|
||||||
|
)
|
||||||
|
return result
|
||||||
|
|
||||||
|
@app.get("/api/v1/chats/{chat_id}/messages")
|
||||||
|
def list_messages(chat_id: str, request: Request, limit: int | None = None, cursor: str | None = None):
|
||||||
|
actor = current_user(request)
|
||||||
|
parsed_chat = parse_uuid(chat_id, "chat UUID")
|
||||||
|
ensure_member(actor["id"], parsed_chat)
|
||||||
|
actual_limit, after = parse_page_args(limit, cursor, "messages:" + str(parsed_chat))
|
||||||
|
params: list[Any] = [parsed_chat]
|
||||||
|
where = "chat_id=%s"
|
||||||
|
if after:
|
||||||
|
where += " AND (created_at,id)>(%s,%s)"
|
||||||
|
params.extend(after)
|
||||||
|
params.append(actual_limit + 1)
|
||||||
|
rows = json_rows(None, f"SELECT id,chat_id,sender_id,text,created_at FROM messages WHERE {where} ORDER BY created_at,id LIMIT %s", tuple(params))
|
||||||
|
more = len(rows) > actual_limit
|
||||||
|
rows = rows[:actual_limit]
|
||||||
|
links: dict[Any, list[str]] = {}
|
||||||
|
if rows:
|
||||||
|
link_rows = json_rows(None, "SELECT message_id, attachment_id FROM message_attachments WHERE message_id = ANY(%s) ORDER BY message_id, position", ([r["id"] for r in rows],))
|
||||||
|
for link in link_rows:
|
||||||
|
links.setdefault(link["message_id"], []).append(str(link["attachment_id"]))
|
||||||
|
items = [message_dict(row, links.get(row["id"])) for row in rows]
|
||||||
|
next_cursor = make_cursor("messages:" + str(parsed_chat), rows[-1]["created_at"], rows[-1]["id"]) if more and rows else None
|
||||||
|
return {"items": items, "next_cursor": next_cursor}
|
||||||
|
|
||||||
|
# ======================= Lab 4: attachments =======================
|
||||||
|
|
||||||
|
def attachment_dict(row: dict[str, Any], variants: list[dict[str, Any]] | None = None) -> dict[str, Any]:
|
||||||
|
return {"id": str(row["id"]), "chat_id": str(row["chat_id"]), "owner_id": str(row["owner_id"]), "filename": row["filename"],
|
||||||
|
"content_type": row["content_type"], "size_bytes": row["size_bytes"], "sha256": row["sha256"], "status": row["status"],
|
||||||
|
"variants": variants or [], "error_code": row["error_code"] if row["status"] == "failed" else None,
|
||||||
|
"created_at": iso(row["created_at"]), "updated_at": iso(row["updated_at"])}
|
||||||
|
|
||||||
|
def validate_filename(values: list[str]) -> str:
|
||||||
|
"""filename is display-only: it never reaches a path or an S3 key, but dangerous values are still rejected."""
|
||||||
|
if len(values) != 1:
|
||||||
|
fail(400, "invalid_request", "Exactly one filename query parameter is required")
|
||||||
|
name = values[0]
|
||||||
|
validate_unicode(name, "filename")
|
||||||
|
if not 1 <= len(name) <= 255 or not name.strip() or name in (".", ".."):
|
||||||
|
fail(400, "invalid_request", "Invalid filename")
|
||||||
|
if "/" in name or "\\" in name or any(unicodedata.category(ch) == "Cc" for ch in name):
|
||||||
|
fail(400, "invalid_request", "Invalid filename")
|
||||||
|
return name
|
||||||
|
|
||||||
|
def sniff_image_type(head: bytes) -> str | None:
|
||||||
|
if head.startswith(b"\x89PNG\r\n\x1a\n"):
|
||||||
|
return "image/png"
|
||||||
|
if head.startswith(b"\xff\xd8\xff"):
|
||||||
|
return "image/jpeg"
|
||||||
|
return None
|
||||||
|
|
||||||
|
async def read_body_to_spool(request: Request, declared: str):
|
||||||
|
"""Stream the request body into a bounded spool while hashing; abort as soon as a limit is broken.
|
||||||
|
|
||||||
|
RAM per upload stays ~1 MiB: bodies above SPOOL_MEMORY_BYTES roll over to an anonymous (already unlinked) temp file.
|
||||||
|
"""
|
||||||
|
spool = tempfile.SpooledTemporaryFile(max_size=SPOOL_MEMORY_BYTES)
|
||||||
|
digest, total, head = hashlib.sha256(), 0, b""
|
||||||
|
try:
|
||||||
|
iterator = request.stream().__aiter__()
|
||||||
|
with anyio.fail_after(UPLOAD_TOTAL_TIMEOUT_SECONDS):
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
chunk = await asyncio.wait_for(iterator.__anext__(), UPLOAD_IDLE_TIMEOUT_SECONDS)
|
||||||
|
except StopAsyncIteration:
|
||||||
|
break
|
||||||
|
if not chunk:
|
||||||
|
continue
|
||||||
|
total += len(chunk)
|
||||||
|
if total > MAX_UPLOAD_BYTES:
|
||||||
|
fail(413, "payload_too_large", "Attachment exceeds the size limit")
|
||||||
|
if len(head) < 8:
|
||||||
|
head += chunk[: 8 - len(head)]
|
||||||
|
if len(head) >= 8 and sniff_image_type(head) != declared:
|
||||||
|
fail(415, "unsupported_media_type", "Content does not match the declared image type")
|
||||||
|
digest.update(chunk)
|
||||||
|
spool.write(chunk)
|
||||||
|
except ApiError:
|
||||||
|
spool.close()
|
||||||
|
raise
|
||||||
|
except (TimeoutError, asyncio.TimeoutError):
|
||||||
|
spool.close()
|
||||||
|
fail(400, "invalid_request", "Upload timed out")
|
||||||
|
except BaseException: # ClientDisconnect, cancellation: nothing was written to S3 yet
|
||||||
|
spool.close()
|
||||||
|
raise
|
||||||
|
if total == 0 or sniff_image_type(head) != declared:
|
||||||
|
spool.close()
|
||||||
|
fail(415, "unsupported_media_type", "Content is not a supported image")
|
||||||
|
return spool, total, digest.hexdigest()
|
||||||
|
|
||||||
|
def decode_image_checked(spool, declared: str) -> None:
|
||||||
|
"""Runs in a worker thread: header -> pixel limit -> full decode. Raises ApiError for every user mistake."""
|
||||||
|
try:
|
||||||
|
spool.seek(0)
|
||||||
|
with Image.open(spool) as img:
|
||||||
|
if IMAGE_TYPES.get(img.format or "") != declared:
|
||||||
|
fail(415, "unsupported_media_type", "Content does not match the declared image type")
|
||||||
|
width, height = img.size
|
||||||
|
if width < 1 or height < 1:
|
||||||
|
fail(415, "unsupported_media_type", "Corrupt image")
|
||||||
|
if width * height > MAX_IMAGE_PIXELS: # decided from the header, before any pixel buffer exists
|
||||||
|
fail(413, "payload_too_large", "Image has too many pixels")
|
||||||
|
img.load() # full decode detects truncated/corrupt data
|
||||||
|
except ApiError:
|
||||||
|
raise
|
||||||
|
except Image.DecompressionBombError:
|
||||||
|
fail(413, "payload_too_large", "Image has too many pixels")
|
||||||
|
except MemoryError:
|
||||||
|
fail(503, "unavailable", "Temporarily unable to process the image")
|
||||||
|
except Exception: # Pillow raises OSError/SyntaxError/ValueError/struct.error/... for corrupt input
|
||||||
|
fail(415, "unsupported_media_type", "Corrupt or unsupported image")
|
||||||
|
finally:
|
||||||
|
spool.seek(0)
|
||||||
|
|
||||||
|
def s3_put(key: str, spool, size: int, content_type: str) -> None:
|
||||||
|
spool.seek(0)
|
||||||
|
s3.put_object(Bucket=S3_BUCKET, Key=key, Body=spool, ContentLength=size, ContentType=content_type)
|
||||||
|
|
||||||
|
def s3_delete_quietly(key: str) -> None:
|
||||||
|
try:
|
||||||
|
s3.delete_object(Bucket=S3_BUCKET, Key=key)
|
||||||
|
except Exception:
|
||||||
|
# The periodic sweeper (scripts/s3_sweep.py) removes it after the grace period.
|
||||||
|
log.warning("Compensation delete failed; orphan left for sweeper key=%s", key)
|
||||||
|
|
||||||
|
async def compensate(key: str) -> None:
|
||||||
|
with anyio.CancelScope(shield=True):
|
||||||
|
await run_in_threadpool(s3_delete_quietly, key)
|
||||||
|
|
||||||
|
@app.post("/api/v1/chats/{chat_id}/attachments", status_code=202)
|
||||||
|
async def upload_attachment(chat_id: str, request: Request):
|
||||||
|
actor = current_user(request)
|
||||||
|
parsed_chat = parse_uuid(chat_id, "chat UUID")
|
||||||
|
ensure_member(actor["id"], parsed_chat)
|
||||||
|
filename = validate_filename(request.query_params.getlist("filename"))
|
||||||
|
declared = request.headers.get("content-type", "").split(";", 1)[0].strip().lower()
|
||||||
|
if declared not in ("image/png", "image/jpeg"):
|
||||||
|
fail(415, "unsupported_media_type", "Content-Type must be image/png or image/jpeg")
|
||||||
|
length = request.headers.get("content-length")
|
||||||
|
if length is not None:
|
||||||
|
if not length.isascii() or not length.isdigit():
|
||||||
|
fail(400, "invalid_request", "Invalid Content-Length")
|
||||||
|
if int(length) > MAX_UPLOAD_BYTES: # reject before reading a single body byte
|
||||||
|
fail(413, "payload_too_large", "Attachment exceeds the size limit")
|
||||||
|
spool, size, sha256 = await read_body_to_spool(request, declared)
|
||||||
|
key = STAGING_PREFIX + secrets.token_hex(16) # server-chosen random STAGING key, unrelated to filename or attachment id
|
||||||
|
try:
|
||||||
|
await anyio.to_thread.run_sync(decode_image_checked, spool, declared, limiter=decode_limiter)
|
||||||
|
await run_in_threadpool(s3_put, key, spool, size, declared)
|
||||||
|
except ApiError: # user error found by validation, before any S3 write
|
||||||
|
spool.close()
|
||||||
|
raise
|
||||||
|
except BaseException:
|
||||||
|
spool.close()
|
||||||
|
await compensate(key) # a PUT whose reply was lost may still have stored the object
|
||||||
|
raise
|
||||||
|
spool.close()
|
||||||
|
attachment_id, job_id = uuid.uuid4(), uuid.uuid4()
|
||||||
|
final_original = jobs.final_key(attachment_id, jobs.PIPELINE_VERSION, "original")
|
||||||
|
try:
|
||||||
|
# ONE transaction: metadata + job + outbox row. 202 is returned only after this COMMIT (durable handoff).
|
||||||
|
with db() as conn:
|
||||||
|
row = conn.execute(
|
||||||
|
"INSERT INTO attachments(id,chat_id,owner_id,filename,content_type,size_bytes,sha256,s3_key,staging_key,status,pipeline_version) "
|
||||||
|
"VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,'queued',%s) "
|
||||||
|
"RETURNING id,chat_id,owner_id,filename,content_type,size_bytes,sha256,status,error_code,created_at,updated_at",
|
||||||
|
(attachment_id, parsed_chat, actor["id"], filename, declared, size, sha256, final_original, key, jobs.PIPELINE_VERSION)).fetchone()
|
||||||
|
conn.execute("INSERT INTO attachment_jobs(job_id,attachment_id,pipeline_version,status,max_attempts) VALUES (%s,%s,%s,'queued',%s)",
|
||||||
|
(job_id, attachment_id, jobs.PIPELINE_VERSION, jobs.JOB_MAX_ATTEMPTS))
|
||||||
|
jobs.add_event(conn, job_id, "accepted")
|
||||||
|
jobs.enqueue(conn, job_id, attachment_id, jobs.PIPELINE_VERSION, 1)
|
||||||
|
except BaseException:
|
||||||
|
await compensate(key) # staging PUT succeeded but the COMMIT did not: remove the unaccounted object
|
||||||
|
raise
|
||||||
|
telemetry.log_event(log, logging.INFO, "attachment_accepted", "Attachment accepted, job queued", job_id=str(job_id), attachment_id=str(attachment_id))
|
||||||
|
cols = ("id", "chat_id", "owner_id", "filename", "content_type", "size_bytes", "sha256", "status", "error_code", "created_at", "updated_at")
|
||||||
|
return JSONResponse(status_code=202, content=attachment_dict(dict(zip(cols, row))))
|
||||||
|
|
||||||
|
ATT_COLS = ("id", "chat_id", "owner_id", "filename", "content_type", "size_bytes", "sha256", "s3_key", "status", "error_code", "created_at", "updated_at")
|
||||||
|
|
||||||
|
def load_attachment(attachment_id: str, request: Request) -> dict[str, Any]:
|
||||||
|
actor = current_user(request)
|
||||||
|
parsed = parse_uuid(attachment_id, "attachment UUID")
|
||||||
|
rows = json_rows(None, "SELECT a.id,a.chat_id,a.owner_id,a.filename,a.content_type,a.size_bytes,a.sha256,a.s3_key,a.status,a.error_code,a.created_at,a.updated_at "
|
||||||
|
"FROM attachments a JOIN chat_members m ON m.chat_id=a.chat_id WHERE a.id=%s AND m.user_id=%s", (parsed, actor["id"]))
|
||||||
|
if not rows:
|
||||||
|
fail(404, "not_found", "Object not found")
|
||||||
|
return rows[0]
|
||||||
|
|
||||||
|
def variant_rows(attachment_id, pipeline_version: int = jobs.PIPELINE_VERSION) -> list[dict[str, Any]]:
|
||||||
|
rows = json_rows(None, "SELECT name,s3_key,content_type,size_bytes,width,height,sha256 FROM attachment_variants WHERE attachment_id=%s AND pipeline_version=%s", (attachment_id, pipeline_version))
|
||||||
|
return sorted(rows, key=lambda r: jobs.VARIANT_ORDER.index(r["name"]))
|
||||||
|
|
||||||
|
@app.get("/api/v1/attachments/{attachment_id}")
|
||||||
|
def get_attachment(attachment_id: str, request: Request):
|
||||||
|
row = load_attachment(attachment_id, request)
|
||||||
|
variants = []
|
||||||
|
if row["status"] == "ready": # variants are published only together with ready (one COMMIT in the worker)
|
||||||
|
variants = [{k: v[k] for k in ("name", "content_type", "size_bytes", "width", "height", "sha256")} for v in variant_rows(row["id"])]
|
||||||
|
return attachment_dict(row, variants)
|
||||||
|
|
||||||
|
@app.get("/api/v1/attachments/{attachment_id}/content")
|
||||||
|
def download_attachment(attachment_id: str, request: Request, variant: str = "original"):
|
||||||
|
row = load_attachment(attachment_id, request)
|
||||||
|
if variant != "original" and variant not in jobs.VARIANT_ORDER:
|
||||||
|
fail(400, "invalid_request", "Unknown variant")
|
||||||
|
if row["status"] != "ready":
|
||||||
|
fail(409, "conflict", "Attachment is not ready") # queued, processing and failed: no content
|
||||||
|
key, content_type, size = row["s3_key"], row["content_type"], row["size_bytes"]
|
||||||
|
if variant != "original":
|
||||||
|
found = [v for v in variant_rows(row["id"]) if v["name"] == variant]
|
||||||
|
if not found:
|
||||||
|
fail(404, "not_found", "Object not found")
|
||||||
|
key, content_type, size = found[0]["s3_key"], found[0]["content_type"], found[0]["size_bytes"]
|
||||||
|
try:
|
||||||
|
obj = s3.get_object(Bucket=S3_BUCKET, Key=key)
|
||||||
|
except ClientError as exc:
|
||||||
|
if exc.response.get("Error", {}).get("Code") in ("NoSuchKey", "404"):
|
||||||
|
log.error("INTEGRITY: metadata without object attachment=%s variant=%s", row["id"], variant)
|
||||||
|
fail(500, "internal_error", "Internal server error")
|
||||||
|
raise
|
||||||
|
body = obj["Body"]
|
||||||
|
async def stream():
|
||||||
|
try:
|
||||||
|
async for chunk in iterate_in_threadpool(body.iter_chunks(CHUNK_BYTES)):
|
||||||
|
yield chunk
|
||||||
|
finally:
|
||||||
|
body.close()
|
||||||
|
headers = {"Content-Length": str(size), "X-Content-Type-Options": "nosniff", "Cache-Control": "private, no-store",
|
||||||
|
"Content-Disposition": "inline; filename*=UTF-8''" + quote(row["filename"], safe="")}
|
||||||
|
return StreamingResponse(stream(), media_type=content_type, headers=headers)
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
import uvicorn
|
||||||
|
uvicorn.run("main:app", host=os.getenv("APP_HOST", "0.0.0.0"), port=int(os.getenv("APP_PORT", "8080")), timeout_graceful_shutdown=5)
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
"""Lab 7 API entrypoint: uvicorn with mandatory mTLS and a client-identity allowlist.
|
||||||
|
|
||||||
|
The CA check (ssl.CERT_REQUIRED) only proves "signed by our CA". Every service and the operator-issued
|
||||||
|
"outsider" certificate pass it, so the identity (SAN) is checked here, right after the handshake and
|
||||||
|
before a single HTTP byte is parsed. Not allowed => the connection is closed.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import ssl
|
||||||
|
|
||||||
|
import uvicorn
|
||||||
|
from uvicorn.protocols.http.h11_impl import H11Protocol
|
||||||
|
|
||||||
|
log = logging.getLogger("messenger.tls")
|
||||||
|
ALLOWED_SANS = {s.strip().lower() for s in os.getenv("ALLOWED_CLIENT_SANS", "lb").split(",") if s.strip()}
|
||||||
|
|
||||||
|
|
||||||
|
class AllowListProtocol(H11Protocol):
|
||||||
|
"""asyncio calls connection_made only after the TLS handshake finished, so getpeercert() is the verified certificate."""
|
||||||
|
_accepted = False
|
||||||
|
|
||||||
|
def connection_made(self, transport):
|
||||||
|
ssl_obj = transport.get_extra_info("ssl_object")
|
||||||
|
cert = ssl_obj.getpeercert() if ssl_obj else None
|
||||||
|
sans = {v.lower() for k, v in (cert or {}).get("subjectAltName", ()) if k == "DNS"}
|
||||||
|
if not sans & ALLOWED_SANS:
|
||||||
|
log.warning("mTLS identity rejected: %s", sorted(sans) or "no SAN")
|
||||||
|
transport.close()
|
||||||
|
return
|
||||||
|
self._accepted = True
|
||||||
|
super().connection_made(transport)
|
||||||
|
|
||||||
|
def connection_lost(self, exc):
|
||||||
|
if self._accepted:
|
||||||
|
super().connection_lost(exc)
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
config = uvicorn.Config(
|
||||||
|
os.getenv("APP", "src.main:app"), host=os.getenv("APP_HOST", "0.0.0.0"), port=int(os.getenv("APP_PORT", "8443")),
|
||||||
|
ssl_certfile=os.environ["TLS_CERT_FILE"], ssl_keyfile=os.environ["TLS_KEY_FILE"],
|
||||||
|
ssl_ca_certs=os.environ["TLS_CA_FILE"], ssl_cert_reqs=ssl.CERT_REQUIRED,
|
||||||
|
http=AllowListProtocol, proxy_headers=False, server_header=False, timeout_graceful_shutdown=10, access_log=False)
|
||||||
|
uvicorn.Server(config).run()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,145 @@
|
|||||||
|
"""Lab 6: one OpenTelemetry bootstrap shared by the API, the worker and the dispatcher.
|
||||||
|
|
||||||
|
* traces -> BatchSpanProcessor -> OTLP/HTTP -> Collector -> Tempo
|
||||||
|
* metrics -> PeriodicExportingMetricReader -> OTLP/HTTP -> Collector -> Prometheus (remote write)
|
||||||
|
* logs -> stdout (JSON) + BatchLogRecordProcessor -> OTLP/HTTP -> Collector -> Loki
|
||||||
|
|
||||||
|
Telemetry is best effort: every queue is bounded and exporters have short timeouts, so a dead Collector or
|
||||||
|
backend can only cost telemetry (dropped batches), never an API response or a job.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import socket
|
||||||
|
import sys
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
from opentelemetry import metrics, trace
|
||||||
|
from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
|
||||||
|
from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
|
||||||
|
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
|
||||||
|
from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler
|
||||||
|
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
|
||||||
|
from opentelemetry.sdk.metrics import MeterProvider
|
||||||
|
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
|
||||||
|
from opentelemetry.sdk.resources import Resource
|
||||||
|
from opentelemetry.sdk.trace import TracerProvider
|
||||||
|
from opentelemetry.sdk.trace.export import BatchSpanProcessor
|
||||||
|
|
||||||
|
SERVICE_NAME = "unknown"
|
||||||
|
EXPORT_TIMEOUT_S = 3 # a dead Collector must not block the exporter thread for long
|
||||||
|
METRIC_INTERVAL_MS = 10_000
|
||||||
|
# Technical (synthetic) identifiers allowed in logs/traces; never in metric labels, never bodies/tokens/URLs.
|
||||||
|
LOG_FIELDS = ("job_id", "attachment_id", "attempt", "request_id", "outcome", "reason", "topic", "count")
|
||||||
|
|
||||||
|
|
||||||
|
class _EventFilter(logging.Filter):
|
||||||
|
"""Every record gets an `event` (contract: logs have `event`); explicit extra={"event": ...} wins."""
|
||||||
|
|
||||||
|
def filter(self, record: logging.LogRecord) -> bool:
|
||||||
|
if not hasattr(record, "event"):
|
||||||
|
record.event = record.name
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
class _NoOtelSelfLogs(logging.Filter):
|
||||||
|
"""Exporter errors are logged by the opentelemetry package itself: never feed them back into the OTLP handler."""
|
||||||
|
|
||||||
|
def filter(self, record: logging.LogRecord) -> bool:
|
||||||
|
return not record.name.startswith(("opentelemetry", "urllib3"))
|
||||||
|
|
||||||
|
|
||||||
|
class JsonFormatter(logging.Formatter):
|
||||||
|
def format(self, record: logging.LogRecord) -> str:
|
||||||
|
ctx = trace.get_current_span().get_span_context()
|
||||||
|
doc = {
|
||||||
|
"timestamp": datetime.fromtimestamp(record.created, timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z"),
|
||||||
|
"severity": record.levelname,
|
||||||
|
"service.name": SERVICE_NAME,
|
||||||
|
"event": getattr(record, "event", record.name),
|
||||||
|
"message": record.getMessage(),
|
||||||
|
}
|
||||||
|
if ctx.is_valid:
|
||||||
|
doc["trace_id"] = format(ctx.trace_id, "032x")
|
||||||
|
doc["span_id"] = format(ctx.span_id, "016x")
|
||||||
|
for field in LOG_FIELDS:
|
||||||
|
if hasattr(record, field):
|
||||||
|
doc[field] = getattr(record, field)
|
||||||
|
if record.exc_info and record.exc_info[0]:
|
||||||
|
doc["exception.type"] = record.exc_info[0].__name__ # type only: no stack trace, no SQL, no values
|
||||||
|
return json.dumps(doc, ensure_ascii=False)
|
||||||
|
|
||||||
|
|
||||||
|
def log_event(logger: logging.Logger, level: int, event: str, message: str, **fields) -> None:
|
||||||
|
"""Structured log: `event` + whitelisted technical fields; trace_id/span_id come from the active span."""
|
||||||
|
logger.log(level, message, extra={"event": event, **fields})
|
||||||
|
|
||||||
|
|
||||||
|
def init(service_name: str, instrument: tuple[str, ...] = ()) -> None:
|
||||||
|
"""Configure providers once per process. `instrument` selects auto-instrumentation libraries."""
|
||||||
|
global SERVICE_NAME
|
||||||
|
SERVICE_NAME = service_name
|
||||||
|
instance = os.getenv("INSTANCE_ID") or socket.gethostname()
|
||||||
|
resource = Resource.create({
|
||||||
|
"service.name": service_name,
|
||||||
|
"service.version": os.getenv("SERVICE_VERSION", "1.6.0"),
|
||||||
|
"service.instance.id": instance,
|
||||||
|
"deployment.environment.name": os.getenv("DEPLOYMENT_ENVIRONMENT", "lab"),
|
||||||
|
})
|
||||||
|
|
||||||
|
tracer_provider = TracerProvider(resource=resource)
|
||||||
|
tracer_provider.add_span_processor(BatchSpanProcessor(
|
||||||
|
OTLPSpanExporter(timeout=EXPORT_TIMEOUT_S),
|
||||||
|
max_queue_size=2048, max_export_batch_size=512, schedule_delay_millis=2000, export_timeout_millis=EXPORT_TIMEOUT_S * 1000))
|
||||||
|
trace.set_tracer_provider(tracer_provider)
|
||||||
|
|
||||||
|
reader = PeriodicExportingMetricReader(
|
||||||
|
OTLPMetricExporter(timeout=EXPORT_TIMEOUT_S), export_interval_millis=METRIC_INTERVAL_MS, export_timeout_millis=5000)
|
||||||
|
metrics.set_meter_provider(MeterProvider(resource=resource, metric_readers=[reader]))
|
||||||
|
|
||||||
|
logger_provider = LoggerProvider(resource=resource)
|
||||||
|
logger_provider.add_log_record_processor(BatchLogRecordProcessor(
|
||||||
|
OTLPLogExporter(timeout=EXPORT_TIMEOUT_S),
|
||||||
|
max_queue_size=2048, max_export_batch_size=512, schedule_delay_millis=2000, export_timeout_millis=EXPORT_TIMEOUT_S * 1000))
|
||||||
|
|
||||||
|
otlp_handler = LoggingHandler(level=logging.NOTSET, logger_provider=logger_provider)
|
||||||
|
otlp_handler.addFilter(_NoOtelSelfLogs())
|
||||||
|
otlp_handler.addFilter(_EventFilter())
|
||||||
|
stdout_handler = logging.StreamHandler(sys.stdout)
|
||||||
|
stdout_handler.setFormatter(JsonFormatter())
|
||||||
|
stdout_handler.addFilter(_EventFilter())
|
||||||
|
root = logging.getLogger()
|
||||||
|
root.handlers[:] = [stdout_handler, otlp_handler]
|
||||||
|
root.setLevel(os.getenv("LOG_LEVEL", "INFO"))
|
||||||
|
|
||||||
|
if "psycopg" in instrument:
|
||||||
|
from opentelemetry.instrumentation.psycopg import PsycopgInstrumentor
|
||||||
|
PsycopgInstrumentor().instrument()
|
||||||
|
if "botocore" in instrument:
|
||||||
|
from opentelemetry.instrumentation.botocore import BotocoreInstrumentor
|
||||||
|
BotocoreInstrumentor().instrument()
|
||||||
|
# Redis is deliberately NOT auto-instrumented: session keys are derived from the session token.
|
||||||
|
|
||||||
|
|
||||||
|
def tracer(name: str = "messenger") -> trace.Tracer:
|
||||||
|
return trace.get_tracer(name)
|
||||||
|
|
||||||
|
|
||||||
|
def meter(name: str = "messenger") -> metrics.Meter:
|
||||||
|
return metrics.get_meter(name)
|
||||||
|
|
||||||
|
|
||||||
|
def _rss_bytes() -> int:
|
||||||
|
with open("/proc/self/statm") as f:
|
||||||
|
return int(f.read().split()[1]) * os.sysconf("SC_PAGE_SIZE")
|
||||||
|
|
||||||
|
|
||||||
|
def register_process_metrics() -> None:
|
||||||
|
"""Process CPU/RAM of this container's main process (own gauges: no psutil dependency)."""
|
||||||
|
m = meter()
|
||||||
|
m.create_observable_counter("process.cpu.time", callbacks=[lambda _o: [metrics.Observation(sum(os.times()[:2]))]],
|
||||||
|
unit="s", description="CPU seconds (user+system) used by this process")
|
||||||
|
m.create_observable_gauge("process.memory.usage", callbacks=[lambda _o: [metrics.Observation(_rss_bytes())]],
|
||||||
|
unit="By", description="Resident set size of this process")
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
"""Secrets for api/worker/dispatcher/sweeper from OpenBao (AppRole -> short-lived scoped token -> one KV v2 secret).
|
||||||
|
|
||||||
|
Bootstrap trust: the only things on disk are the PUBLIC CA, the RoleID (not a secret) and a SecretID with a 24 h TTL that the
|
||||||
|
operator issues into /run/approle. The service logs in, reads exactly one path allowed by its policy, revokes its own token and
|
||||||
|
keeps the values only in process memory / environment. No root token, no unseal key, no long-lived token is ever present.
|
||||||
|
Sealed/unreachable OpenBao at start => bounded retries, then exit (compose restarts the container); a running process is not affected.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import ssl
|
||||||
|
import time
|
||||||
|
import urllib.error
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
BAO_ADDR = os.getenv("BAO_ADDR", "https://openbao:8200").rstrip("/")
|
||||||
|
BAO_CACERT = os.getenv("BAO_CACERT", "/run/pki/ca.crt")
|
||||||
|
APPROLE_DIR = os.getenv("APPROLE_DIR", "/run/approle")
|
||||||
|
# secret field in OpenBao -> environment variable consumed by the unchanged lab 6 code (psycopg reads PGPASSWORD itself).
|
||||||
|
ENV_MAP = {
|
||||||
|
"api": {"db_password": "PGPASSWORD", "redis_password": "REDIS_PASSWORD", "s3_access_key": "S3_ACCESS_KEY_ID", "s3_secret_key": "S3_SECRET_ACCESS_KEY"},
|
||||||
|
"worker": {"db_password": "PGPASSWORD", "s3_access_key": "S3_ACCESS_KEY_ID", "s3_secret_key": "S3_SECRET_ACCESS_KEY"},
|
||||||
|
"dispatcher": {"db_password": "PGPASSWORD"},
|
||||||
|
"sweeper": {"db_password": "PGPASSWORD", "s3_access_key": "S3_ACCESS_KEY_ID", "s3_secret_key": "S3_SECRET_ACCESS_KEY"},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class VaultError(RuntimeError):
|
||||||
|
"""Message never contains secret values or tokens."""
|
||||||
|
|
||||||
|
|
||||||
|
def _call(method: str, path: str, body: dict | None = None, token: str | None = None) -> dict:
|
||||||
|
ctx = ssl.create_default_context(cafile=BAO_CACERT) # CA + hostname (SAN) verification, never disabled
|
||||||
|
data = json.dumps(body).encode() if body is not None else None
|
||||||
|
req = urllib.request.Request(f"{BAO_ADDR}/v1/{path}", data=data, method=method)
|
||||||
|
if token:
|
||||||
|
req.add_header("X-Vault-Token", token)
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(req, timeout=5, context=ctx) as resp:
|
||||||
|
raw = resp.read()
|
||||||
|
except urllib.error.HTTPError as exc:
|
||||||
|
raise VaultError(f"OpenBao {method} {path}: HTTP {exc.code}") from None
|
||||||
|
except (urllib.error.URLError, OSError) as exc:
|
||||||
|
raise VaultError(f"OpenBao unreachable: {type(exc).__name__}") from None
|
||||||
|
return json.loads(raw) if raw else {}
|
||||||
|
|
||||||
|
|
||||||
|
def _read(name: str) -> str:
|
||||||
|
with open(os.path.join(APPROLE_DIR, name), encoding="utf-8") as fh:
|
||||||
|
return fh.read().strip()
|
||||||
|
|
||||||
|
|
||||||
|
def fetch(role: str) -> dict[str, str]:
|
||||||
|
"""One login -> one read -> token revoked. Raises VaultError if sealed, SecretID expired/destroyed, or policy denies."""
|
||||||
|
login = _call("POST", "auth/approle/login", {"role_id": _read("role_id"), "secret_id": _read("secret_id")})
|
||||||
|
token = login["auth"]["client_token"]
|
||||||
|
try:
|
||||||
|
return _call("GET", f"kv/data/{role}", token=token)["data"]["data"]
|
||||||
|
finally:
|
||||||
|
try:
|
||||||
|
_call("POST", "auth/token/revoke-self", token=token)
|
||||||
|
except VaultError:
|
||||||
|
pass # the token expires by TTL anyway
|
||||||
|
|
||||||
|
|
||||||
|
def load_into_env(role: str, attempts: int = 30, delay: float = 2.0) -> None:
|
||||||
|
last = None
|
||||||
|
for _ in range(attempts):
|
||||||
|
try:
|
||||||
|
secret = fetch(role)
|
||||||
|
for field, env in ENV_MAP[role].items():
|
||||||
|
os.environ[env] = secret[field]
|
||||||
|
return
|
||||||
|
except (VaultError, KeyError, OSError) as exc:
|
||||||
|
last = exc
|
||||||
|
time.sleep(delay)
|
||||||
|
raise SystemExit(f"cannot obtain secrets for {role} from OpenBao: {last}")
|
||||||
+297
@@ -0,0 +1,297 @@
|
|||||||
|
"""Lab 6 worker (lab 5 + OpenTelemetry): Kafka consumer -> claim (lease) in PostgreSQL -> staging -> pipeline -> final S3 + COMMIT -> offset commit.
|
||||||
|
|
||||||
|
PostgreSQL is the source of truth for job state; Kafka is the at-least-once transport. The Kafka offset is committed
|
||||||
|
only AFTER the durable effect (final objects + COMMIT of the result) or after a durable decision (retry scheduled / failed).
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import signal
|
||||||
|
import socket
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
import uuid
|
||||||
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import psycopg
|
||||||
|
from botocore.exceptions import BotoCoreError, ClientError
|
||||||
|
from boto3.s3.transfer import TransferConfig
|
||||||
|
from confluent_kafka import Consumer, TopicPartition
|
||||||
|
from opentelemetry import metrics, trace
|
||||||
|
from opentelemetry.propagate import extract
|
||||||
|
from opentelemetry.trace import SpanKind, Status, StatusCode
|
||||||
|
|
||||||
|
from . import jobs, telemetry, vault
|
||||||
|
|
||||||
|
# Lab 7: the worker identity gets ONLY its own secret (DB role messenger_worker, S3 key svc-worker); never api/admin credentials.
|
||||||
|
vault.load_into_env("worker")
|
||||||
|
|
||||||
|
telemetry.init("messenger-worker", instrument=("psycopg", "botocore"))
|
||||||
|
log = logging.getLogger("worker")
|
||||||
|
TRACER = telemetry.tracer()
|
||||||
|
NO_THREADS = TransferConfig(use_threads=False) # s3transfer threads would lose the trace context: keep transfers in the job thread
|
||||||
|
WORKER_ID = os.getenv("INSTANCE_ID") or socket.gethostname()
|
||||||
|
CONCURRENCY = int(os.getenv("WORKER_CONCURRENCY", "2"))
|
||||||
|
FAULT_EXIT_AFTER_S3 = os.getenv("FAULT_WORKER_EXIT_AFTER_S3", "0") == "1" # test hook: crash after the S3 write, before COMMIT/ack
|
||||||
|
IMG_MEMORY_MB = os.getenv("IMG_MEMORY_MB", "1024")
|
||||||
|
CODE_BY_EXIT = {2: "invalid_image", 3: "image_too_large", 4: "image_too_complex"} # permanent errors of imgproc
|
||||||
|
STOP = False
|
||||||
|
|
||||||
|
# ---- Lab 6 metrics. Labels: job.type + outcome only (never job_id / attachment_id). ----
|
||||||
|
_M = telemetry.meter()
|
||||||
|
JOBS_PROCESSED = _M.create_counter("messenger.jobs.processed", unit="{job}", description="Finished job attempts by outcome: success|retry|failed|lost|noop|error")
|
||||||
|
JOB_DURATION = _M.create_histogram("messenger.job.duration", unit="s", description="Worker processing time of one attempt (claim -> outcome), backlog wait excluded",
|
||||||
|
explicit_bucket_boundaries_advisory=[0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60, 120])
|
||||||
|
TIME_TO_READY = _M.create_histogram("messenger.job.time_to_ready", unit="s", description="End-to-end: durable acceptance (job row created) -> ready committed",
|
||||||
|
explicit_bucket_boundaries_advisory=[0.5, 1, 2, 5, 10, 15, 30, 60, 120, 300, 600, 1800])
|
||||||
|
_busy, _busy_lock = 0, threading.Lock()
|
||||||
|
_M.create_observable_gauge("messenger.worker.busy", callbacks=[lambda _o: [metrics.Observation(_busy)]], unit="{job}", description="Jobs being handled right now")
|
||||||
|
_M.create_observable_gauge("messenger.worker.capacity", callbacks=[lambda _o: [metrics.Observation(CONCURRENCY)]], unit="{job}", description="WORKER_CONCURRENCY")
|
||||||
|
telemetry.register_process_metrics()
|
||||||
|
|
||||||
|
|
||||||
|
class Permanent(Exception):
|
||||||
|
def __init__(self, code: str):
|
||||||
|
super().__init__(code)
|
||||||
|
self.code = code
|
||||||
|
|
||||||
|
|
||||||
|
class Transient(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def connect():
|
||||||
|
return psycopg.connect(connect_timeout=5, options="-c statement_timeout=10000")
|
||||||
|
|
||||||
|
|
||||||
|
def parse_job(raw: bytes) -> dict | None:
|
||||||
|
"""Validate against jobs.schema.json (the subset that matters). Poison messages are logged and skipped."""
|
||||||
|
try:
|
||||||
|
m = json.loads(raw)
|
||||||
|
assert m["schema_version"] == 1 and m["type"] == jobs.JOB_TYPE
|
||||||
|
uuid.UUID(m["job_id"]); uuid.UUID(m["attachment_id"])
|
||||||
|
assert isinstance(m["pipeline_version"], int) and m["pipeline_version"] >= 1
|
||||||
|
return m
|
||||||
|
except Exception:
|
||||||
|
telemetry.log_event(log, logging.ERROR, "job_poison_skipped", f"poison message skipped (schema violation), size={len(raw)}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def claim(msg: dict) -> dict | None:
|
||||||
|
"""queued -> processing with a lease. Returns None when this delivery must be a no-op (ack)."""
|
||||||
|
with connect() as conn:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT status, attempt, max_attempts, attachment_id, pipeline_version, "
|
||||||
|
"(next_attempt_at <= now()) AS due, (lease_until IS NOT NULL AND lease_until < now()) AS lease_expired "
|
||||||
|
"FROM attachment_jobs WHERE job_id=%s FOR UPDATE", (msg["job_id"],)).fetchone()
|
||||||
|
if row is None:
|
||||||
|
telemetry.log_event(log, logging.WARNING, "job_unknown", "job unknown, skipped", job_id=msg["job_id"]); return None
|
||||||
|
status, attempt, max_attempts, att_id, pv, due, expired = row
|
||||||
|
if pv != msg["pipeline_version"]:
|
||||||
|
return None # stale job of another pipeline version never overwrites the newer one
|
||||||
|
if status in ("ready", "failed"):
|
||||||
|
telemetry.log_event(log, logging.INFO, "job_duplicate_noop", f"job already {status}: duplicate delivery is a no-op", job_id=msg["job_id"]); return None
|
||||||
|
if status == "queued" and not due:
|
||||||
|
return None # early duplicate: the delayed outbox row will deliver it later
|
||||||
|
if status == "processing" and not expired:
|
||||||
|
telemetry.log_event(log, logging.INFO, "job_leased_skip", "job is leased by another worker: skip", job_id=msg["job_id"]); return None
|
||||||
|
if attempt >= max_attempts: # lease expired and no attempts left
|
||||||
|
jobs.fail_job(conn, msg["job_id"], att_id, "retry_exhausted", attempt)
|
||||||
|
return None
|
||||||
|
attempt += 1
|
||||||
|
conn.execute("UPDATE attachment_jobs SET status='processing', attempt=%s, worker_id=%s, "
|
||||||
|
"lease_until=now()+make_interval(secs=>%s), updated_at=now() WHERE job_id=%s",
|
||||||
|
(attempt, WORKER_ID, jobs.LEASE_SECONDS, msg["job_id"]))
|
||||||
|
conn.execute("UPDATE attachments SET status='processing', updated_at=now() WHERE id=%s", (att_id,))
|
||||||
|
jobs.add_event(conn, msg["job_id"], "claimed", f"attempt={attempt} worker={WORKER_ID}")
|
||||||
|
telemetry.log_event(log, logging.INFO, "job_claimed", "job claimed", job_id=msg["job_id"], attempt=attempt)
|
||||||
|
a = conn.execute("SELECT sha256, staging_key, s3_key, content_type, filename FROM attachments WHERE id=%s", (att_id,)).fetchone()
|
||||||
|
return {"job_id": msg["job_id"], "attachment_id": att_id, "pv": pv, "attempt": attempt, "max_attempts": max_attempts,
|
||||||
|
"sha256": a[0].strip(), "staging_key": a[1], "original_key": a[2], "content_type": a[3]}
|
||||||
|
|
||||||
|
|
||||||
|
def run_pipeline(s3, c: dict) -> dict:
|
||||||
|
"""Download staging -> verify -> child process with limits -> idempotent PUTs of deterministic keys."""
|
||||||
|
if not c["staging_key"]:
|
||||||
|
raise Permanent("staging_missing")
|
||||||
|
with tempfile.TemporaryDirectory(prefix="job-") as tmp:
|
||||||
|
src, out = Path(tmp) / "in.bin", Path(tmp) / "out"
|
||||||
|
out.mkdir()
|
||||||
|
try:
|
||||||
|
with TRACER.start_as_current_span("s3.download_staging"):
|
||||||
|
s3.download_file(jobs.S3_BUCKET, c["staging_key"], str(src), Config=NO_THREADS)
|
||||||
|
except ClientError as e:
|
||||||
|
if e.response.get("Error", {}).get("Code") in ("NoSuchKey", "404"):
|
||||||
|
raise Permanent("staging_missing")
|
||||||
|
raise
|
||||||
|
if hashlib.sha256(src.read_bytes()).hexdigest() != c["sha256"]:
|
||||||
|
raise Permanent("integrity_error") # bytes differ from what the API accepted
|
||||||
|
try:
|
||||||
|
with TRACER.start_as_current_span("imgproc.run"):
|
||||||
|
r = subprocess.run([sys.executable, "-m", "src.imgproc", str(src), str(out)], capture_output=True, text=True,
|
||||||
|
timeout=jobs.JOB_TIMEOUT_SECONDS, env={"PATH": os.environ.get("PATH", ""), "IMG_MEMORY_MB": IMG_MEMORY_MB,
|
||||||
|
"IMG_CPU_SECONDS": str(jobs.JOB_TIMEOUT_SECONDS),
|
||||||
|
"MAX_IMAGE_PIXELS": os.getenv("MAX_IMAGE_PIXELS", "40000000")}) # no secrets in the child
|
||||||
|
except subprocess.TimeoutExpired:
|
||||||
|
raise Transient("job timeout") # child is killed by subprocess.run
|
||||||
|
if r.returncode in CODE_BY_EXIT:
|
||||||
|
raise Permanent(CODE_BY_EXIT[r.returncode])
|
||||||
|
if r.returncode != 0:
|
||||||
|
raise Transient(f"imgproc exit {r.returncode}")
|
||||||
|
meta = json.loads(r.stdout)
|
||||||
|
files = {"thumbnail": "thumbnail.jpg", "crop": "crop.jpg", "optimized": "optimized.webp"}
|
||||||
|
# 1) original into the final prefix (same key every time => repeated PUT is harmless)
|
||||||
|
with TRACER.start_as_current_span("s3.upload_final"):
|
||||||
|
s3.upload_file(str(src), jobs.S3_BUCKET, c["original_key"], ExtraArgs={"ContentType": c["content_type"]}, Config=NO_THREADS)
|
||||||
|
# 2) variants
|
||||||
|
for name in jobs.VARIANT_ORDER:
|
||||||
|
key = jobs.final_key(c["attachment_id"], c["pv"], name)
|
||||||
|
s3.upload_file(str(out / files[name]), jobs.S3_BUCKET, key, ExtraArgs={"ContentType": meta[name]["content_type"]}, Config=NO_THREADS)
|
||||||
|
meta[name]["s3_key"] = key
|
||||||
|
return meta
|
||||||
|
|
||||||
|
|
||||||
|
def commit_ready(c: dict, meta: dict) -> bool:
|
||||||
|
"""Atomically publish the result. False if this attempt no longer owns the job (lease lost to a newer attempt)."""
|
||||||
|
with connect() as conn:
|
||||||
|
row = conn.execute("SELECT status, attempt FROM attachment_jobs WHERE job_id=%s FOR UPDATE", (c["job_id"],)).fetchone()
|
||||||
|
if row is None or row[0] != "processing" or row[1] != c["attempt"]:
|
||||||
|
telemetry.log_event(log, logging.WARNING, "job_lease_lost", "attempt lost ownership, result not committed", job_id=c["job_id"], attempt=c["attempt"]); return False
|
||||||
|
for name in jobs.VARIANT_ORDER:
|
||||||
|
v = meta[name]
|
||||||
|
conn.execute("INSERT INTO attachment_variants(attachment_id,pipeline_version,name,s3_key,content_type,size_bytes,width,height,sha256) "
|
||||||
|
"VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s) ON CONFLICT (attachment_id,pipeline_version,name) DO NOTHING",
|
||||||
|
(c["attachment_id"], c["pv"], name, v["s3_key"], v["content_type"], v["size_bytes"], v["width"], v["height"], v["sha256"]))
|
||||||
|
waited = conn.execute("UPDATE attachment_jobs SET status='ready', error_code=NULL, lease_until=NULL, updated_at=now() WHERE job_id=%s "
|
||||||
|
"RETURNING EXTRACT(EPOCH FROM (now() - created_at))", (c["job_id"],)).fetchone()[0]
|
||||||
|
TIME_TO_READY.record(float(waited), {"job.type": jobs.JOB_TYPE})
|
||||||
|
conn.execute("UPDATE attachments SET status='ready', error_code=NULL, staging_key=NULL, updated_at=now() WHERE id=%s", (c["attachment_id"],))
|
||||||
|
jobs.add_event(conn, c["job_id"], "ready", f"attempt={c['attempt']}")
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def record_failure(c: dict, exc: Exception) -> None:
|
||||||
|
"""Permanent -> failed in the PostgreSQL registry. Transient -> queued with backoff+jitter (delayed outbox row) or failed when attempts are exhausted."""
|
||||||
|
with connect() as conn:
|
||||||
|
row = conn.execute("SELECT status, attempt FROM attachment_jobs WHERE job_id=%s FOR UPDATE", (c["job_id"],)).fetchone()
|
||||||
|
if row is None or row[0] != "processing" or row[1] != c["attempt"]:
|
||||||
|
return
|
||||||
|
if isinstance(exc, Permanent):
|
||||||
|
jobs.fail_job(conn, c["job_id"], c["attachment_id"], exc.code, c["attempt"])
|
||||||
|
elif c["attempt"] >= c["max_attempts"]:
|
||||||
|
jobs.fail_job(conn, c["job_id"], c["attachment_id"], "retry_exhausted", c["attempt"])
|
||||||
|
else:
|
||||||
|
delay = jobs.backoff_seconds(c["attempt"])
|
||||||
|
conn.execute("UPDATE attachment_jobs SET status='queued', lease_until=NULL, next_attempt_at=now()+make_interval(secs=>%s), "
|
||||||
|
"error_code=NULL, updated_at=now() WHERE job_id=%s", (delay, c["job_id"]))
|
||||||
|
conn.execute("UPDATE attachments SET status='queued', updated_at=now() WHERE id=%s", (c["attachment_id"],))
|
||||||
|
jobs.add_event(conn, c["job_id"], "retry_scheduled", f"attempt={c['attempt']} delay={delay:.1f}s reason={type(exc).__name__}")
|
||||||
|
jobs.enqueue(conn, c["job_id"], c["attachment_id"], c["pv"], c["attempt"] + 1, delay_seconds=delay)
|
||||||
|
|
||||||
|
|
||||||
|
def _process(s3, msg: dict, span) -> str:
|
||||||
|
"""The lab 5 job logic, now with stage spans. Returns the outcome label used by metrics and the consumer span."""
|
||||||
|
with TRACER.start_as_current_span("job.claim"):
|
||||||
|
c = claim(msg)
|
||||||
|
if c is None:
|
||||||
|
return "noop"
|
||||||
|
span.set_attribute("job.attempt", c["attempt"])
|
||||||
|
try:
|
||||||
|
with TRACER.start_as_current_span("job.pipeline"):
|
||||||
|
meta = run_pipeline(s3, c)
|
||||||
|
if FAULT_EXIT_AFTER_S3 and c["attempt"] == 1:
|
||||||
|
log.error("FAULT: exiting after S3 write, before COMMIT and offset commit")
|
||||||
|
os._exit(137)
|
||||||
|
with TRACER.start_as_current_span("job.commit_ready"):
|
||||||
|
committed = commit_ready(c, meta)
|
||||||
|
if not committed:
|
||||||
|
return "lost"
|
||||||
|
telemetry.log_event(log, logging.INFO, "job_ready", "job ready", job_id=c["job_id"], attempt=c["attempt"], outcome="success")
|
||||||
|
try:
|
||||||
|
s3.delete_object(Bucket=jobs.S3_BUCKET, Key=c["staging_key"]) # staging cleanup after the safe COMMIT
|
||||||
|
except Exception:
|
||||||
|
log.warning("staging cleanup failed; sweeper will remove it")
|
||||||
|
return "success"
|
||||||
|
except (Permanent, Transient, ClientError, BotoCoreError, OSError, json.JSONDecodeError) as exc:
|
||||||
|
final = isinstance(exc, Permanent) or c["attempt"] >= c["max_attempts"]
|
||||||
|
outcome = "failed" if final else "retry"
|
||||||
|
span.record_exception(exc, attributes={"exception.escaped": False})
|
||||||
|
telemetry.log_event(log, logging.WARNING, "job_attempt_failed", f"job attempt failed: {type(exc).__name__}",
|
||||||
|
job_id=c["job_id"], attempt=c["attempt"], outcome=outcome, reason=getattr(exc, "code", type(exc).__name__))
|
||||||
|
with TRACER.start_as_current_span("job.record_failure"):
|
||||||
|
record_failure(c, exc)
|
||||||
|
return outcome
|
||||||
|
|
||||||
|
|
||||||
|
def handle(s3, raw: bytes) -> None:
|
||||||
|
global _busy
|
||||||
|
msg = parse_job(raw)
|
||||||
|
if msg is None:
|
||||||
|
return
|
||||||
|
# W3C trace context travels in the message: this CONSUMER span is a child of the dispatcher's PRODUCER span.
|
||||||
|
with TRACER.start_as_current_span(
|
||||||
|
f"{jobs.JOBS_TOPIC} process", context=extract(msg), kind=SpanKind.CONSUMER,
|
||||||
|
attributes={"messaging.system": "kafka", "messaging.destination.name": jobs.JOBS_TOPIC, "messaging.operation.type": "process",
|
||||||
|
"job.type": jobs.JOB_TYPE, "job.id": msg["job_id"], "attachment.id": msg["attachment_id"], "job.attempt": msg.get("attempt", 0)}) as span:
|
||||||
|
started, outcome = time.perf_counter(), "error"
|
||||||
|
with _busy_lock:
|
||||||
|
_busy += 1
|
||||||
|
try:
|
||||||
|
outcome = _process(s3, msg, span)
|
||||||
|
finally: # unexpected exception: outcome stays "error", the exception propagates (process exits)
|
||||||
|
with _busy_lock:
|
||||||
|
_busy -= 1
|
||||||
|
attrs = {"job.type": jobs.JOB_TYPE, "outcome": outcome}
|
||||||
|
JOBS_PROCESSED.add(1, attrs)
|
||||||
|
if outcome != "noop":
|
||||||
|
JOB_DURATION.record(time.perf_counter() - started, attrs)
|
||||||
|
span.set_attribute("job.outcome", outcome)
|
||||||
|
if outcome in ("retry", "failed", "lost", "error"):
|
||||||
|
span.set_status(Status(StatusCode.ERROR, outcome))
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
def request_stop(*_):
|
||||||
|
global STOP
|
||||||
|
STOP = True
|
||||||
|
signal.signal(signal.SIGTERM, request_stop)
|
||||||
|
signal.signal(signal.SIGINT, request_stop)
|
||||||
|
s3 = jobs.make_s3()
|
||||||
|
consumer = Consumer({
|
||||||
|
**jobs.kafka_ssl(), "bootstrap.servers": jobs.KAFKA_BOOTSTRAP, "group.id": "attachment-workers",
|
||||||
|
"enable.auto.commit": False, "auto.offset.reset": "earliest", "isolation.level": "read_committed",
|
||||||
|
"max.poll.interval.ms": 600000, "session.timeout.ms": 30000,
|
||||||
|
"queued.max.messages.kbytes": 1024, "fetch.max.bytes": 1048576, # bounded client-side prefetch
|
||||||
|
})
|
||||||
|
consumer.subscribe([jobs.JOBS_TOPIC])
|
||||||
|
telemetry.log_event(log, logging.INFO, "worker_started", f"worker {WORKER_ID} started, concurrency={CONCURRENCY}, max_attempts={jobs.JOB_MAX_ATTEMPTS}, lease={jobs.LEASE_SECONDS}s")
|
||||||
|
with ThreadPoolExecutor(max_workers=CONCURRENCY) as pool:
|
||||||
|
while not STOP:
|
||||||
|
msgs = consumer.consume(num_messages=CONCURRENCY, timeout=1.0) # at most CONCURRENCY jobs in flight
|
||||||
|
batch = []
|
||||||
|
for m in msgs:
|
||||||
|
if m.error():
|
||||||
|
log.warning("kafka error: %s", m.error()); continue
|
||||||
|
batch.append(m)
|
||||||
|
if not batch:
|
||||||
|
continue
|
||||||
|
futures = [pool.submit(handle, s3, m.value()) for m in batch]
|
||||||
|
for f in futures:
|
||||||
|
f.result() # unexpected exception => process exits, offsets stay uncommitted, Kafka redelivers
|
||||||
|
# ACK boundary: commit the highest processed offset+1 per partition, only after every job of the batch is durable
|
||||||
|
top = {}
|
||||||
|
for m in batch:
|
||||||
|
top[(m.topic(), m.partition())] = max(top.get((m.topic(), m.partition()), -1), m.offset() + 1)
|
||||||
|
consumer.commit(offsets=[TopicPartition(t, p, o) for (t, p), o in top.items()], asynchronous=False)
|
||||||
|
consumer.close()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
Reference in New Issue
Block a user