ЛР 7 — БВТ2301 — Козырев — на 3 #8
@@ -30,6 +30,9 @@ OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
|
||||
OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=lab
|
||||
# TLS and OpenBao: actual paths/ports depend on your implemented trust matrix.
|
||||
PUBLIC_BASE_URL=https://localhost:8443
|
||||
PUBLIC_HTTPS_PORT=8443
|
||||
BAO_HOST_PORT=18200
|
||||
GRAFANA_HOST_PORT=3000
|
||||
TLS_CA_FILE=/run/secrets/ca.crt
|
||||
TLS_CERT_FILE=/run/secrets/service.crt
|
||||
TLS_KEY_FILE=/run/secrets/service.key
|
||||
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
FROM python:3.12.12-slim
|
||||
|
||||
ENV PYTHONDONTWRITEBYTECODE=1 \
|
||||
PYTHONUNBUFFERED=1
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
RUN pip install --no-cache-dir uv==0.11.28
|
||||
|
||||
COPY pyproject.toml uv.lock ./
|
||||
RUN uv sync --frozen --no-dev --no-install-project
|
||||
|
||||
COPY src ./src
|
||||
COPY migrations ./migrations
|
||||
|
||||
USER 65534:65534
|
||||
|
||||
EXPOSE 8080
|
||||
|
||||
HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \
|
||||
CMD ["/app/.venv/bin/python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health/ready', timeout=2).read()"]
|
||||
|
||||
CMD ["/app/.venv/bin/python", "-m", "src.main"]
|
||||
@@ -1,37 +1,88 @@
|
||||
# Отчёт — лабораторная 7
|
||||
|
||||
- Автор, группа: TODO
|
||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
||||
- Commit/PR: TODO после публикации
|
||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
||||
- Автор: Kozyrev, группа BVT2301.
|
||||
- Целевая оценка: 3.
|
||||
- База: собственная lab6, commit `7fe48e3`; исходники, конфигурация и тесты перенесены без пользовательских данных и секретов.
|
||||
- Использована помощь Codex. Документация: [OpenBao certificate auth](https://openbao.org/docs/auth/cert/), [OpenBao configuration](https://openbao.org/docs/configuration/), [RabbitMQ access control](https://www.rabbitmq.com/docs/access-control/); остальные источники — в README задания.
|
||||
|
||||
## Запуск из чистого clone
|
||||
|
||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
||||
Нужны Docker с Compose, Python 3.9+ для операторских и публичных скриптов и OpenSSL. Порты по умолчанию: HTTPS API `127.0.0.1:8443`, OpenBao `127.0.0.1:18200`, Grafana `127.0.0.1:3000`. Если порт занят, измените `PUBLIC_HTTPS_PORT`, `BAO_HOST_PORT` или `GRAFANA_HOST_PORT` в `.env`; для операторского скрипта при изменённом порте OpenBao задайте `BAO_OPERATOR_ADDR=https://localhost:<порт>`.
|
||||
|
||||
## Архитектура и решения
|
||||
Чистый запуск проверен на Docker Desktop для macOS. После генерации secrets выполните `scripts/prepare-secret-access.py`: каталог остаётся 0700, отдельно монтируемые файлы получают 0640 и группу оператора; её GID записывается в `.env` как `LAB_SECRET_GID` и добавляется контейнерам через `group_add`. CA key и operator JSON остаются 0600 и не монтируются приложениям. После повторной генерации secrets повторите этот шаг. Это учитывает [ограничение Compose для file secrets](https://docs.docker.com/reference/compose-file/services/#secrets): uid/gid/mode не переназначаются для bind-mounted файлов. Полный запуск на отдельном Linux-хосте пока не проверен. Переменные в `.env.example` являются подсказками задания: сетевые адреса контейнеров и пути секретов фактически заданы в `compose.yaml`.
|
||||
|
||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab6, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
||||
```sh
|
||||
cp .env.example .env
|
||||
python3 scripts/init-secrets.py
|
||||
sh scripts/bootstrap-pki.sh
|
||||
sh scripts/bootstrap-internal-pki.sh
|
||||
python3 scripts/prepare-secret-access.py
|
||||
docker compose --env-file .env up -d openbao
|
||||
# Дождаться ответа статуса, затем один раз инициализировать:
|
||||
python3 scripts/openbao-operator.py status
|
||||
python3 scripts/openbao-operator.py init
|
||||
python3 scripts/openbao-operator.py unseal
|
||||
python3 scripts/openbao-provision.py
|
||||
docker compose --env-file .env up -d --build
|
||||
make test CA_FILE="$PWD/secrets/ca.crt"
|
||||
make test-security CA_FILE="$PWD/secrets/ca.crt"
|
||||
```
|
||||
|
||||
## Доказательства критериев
|
||||
При обычном перезапуске OpenBao остаётся sealed: оператор выполняет `python3 scripts/openbao-operator.py unseal`. Повторно выполнять `init` нельзя: его результат хранится в `secrets/openbao-operator.json` с локальными правами 0600. Файл содержит root token и unseal shares, не передаётся приложениям и требует защищённого резервного копирования оператором. Хранение всех shares на одной учебной машине — ограничение стенда, не схема разделения полномочий. Если OpenBao недоступен или sealed, новый процесс API/worker не получает секреты и не запускается; уже запущенный процесс использует полученные при старте рабочие credentials. Secret values, CA key и ключи сервисов не коммитятся и не копируются в образ.
|
||||
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||
| --- | --- | --- | --- |
|
||||
| Публичный smoke | make test | TODO | TODO |
|
||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
||||
Для безопасной остановки без удаления данных: `docker compose --env-file .env down`. Команда намеренного уничтожения **всех томов данного Compose-проекта**, включая OpenBao и данные сообщений: `docker compose --env-file .env down -v`; запускать только когда учебные данные больше не нужны. При новом OpenBao после удаления его тома старые operator credentials нужно отдельно архивировать и провести новую инициализацию.
|
||||
|
||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
||||
## Архитектура
|
||||
|
||||
## Эксперименты и отказы
|
||||
Клиент → HTTPS HAProxy → mTLS-прокси каждой API-реплики → loopback API. PostgreSQL принимает только TLS-соединения; роли API, worker, outbox и reconcile раздельны. S3 принимает TLS и имеет разные bucket-scoped credentials API, worker и reconcile; прокси ограничивает запись по префиксам, внутренние интерфейсы SeaweedFS доступны только в его сетевом пространстве. RabbitMQ принимает AMQPS через TCP-прокси, служебные порты ограничены loopback, а API, worker и outbox имеют отдельные роли и ограничения на очереди. PostgreSQL хранит пользователей, сессии, сообщения и метаданные; S3 — файлы; RabbitMQ — устойчивую очередь, outbox обеспечивает повторную публикацию.
|
||||
|
||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
||||
OpenBao использует persistent file storage вне dev-mode. API и worker аутентифицируются отдельными сертификатами, получают часовой token с policy только на свой KV path и считывают нужные секреты при старте. Миграция, S3 bootstrap и DB provisioning используют отдельные операторские credentials. OTel, Grafana и хранилища сигналов общаются через TLS-прокси с проверкой сертификатов сервисных ролей. Локальные plaintext hops прокси ограничены loopback внутри соответствующего сетевого пространства. Подробности и ограничения — в [матрице доверия](contracts/trust-matrix.md).
|
||||
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||
| --- | --- | --- | --- |
|
||||
| TODO | TODO | TODO | TODO |
|
||||
Сервисные leaf certificates действуют 90 дней, локальный CA — 365 дней. Автоматический renewal и ротация не реализованы. Локальный CA не предназначен для внешнего production-развёртывания.
|
||||
|
||||
## Ограничения и следующие шаги
|
||||
## Проверки
|
||||
|
||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
||||
Публичные проверки используют HTTPS и CA certificate. Для стенда с нестандартным портом передайте `BASE_URL=https://localhost:<порт>`; для тестов с `docker compose` задайте `COMPOSE_FILE`, если используются дополнительные Compose-файлы.
|
||||
|
||||
| Сценарий | Команда или проверка | Результат локального запуска |
|
||||
| --- | --- | --- |
|
||||
| Структура | `make check` | PASS |
|
||||
| Чистый запуск | Команды из раздела запуска в отдельном временном Compose-проекте | PASS: новая инициализация OpenBao, пустые тома, HTTPS smoke, mTLS и S3 ACL; `evidence/lab7-clean-start.json` |
|
||||
| Публичный сценарий | `make test CA_FILE="$PWD/secrets/ca.crt"` | PASS через HTTPS, в том числе загрузка и thumbnail |
|
||||
| Внешний TLS | `make test-security CA_FILE="$PWD/secrets/ca.crt"` | PASS: недоверенный CA отклонён |
|
||||
| Внутренний mTLS | `sh scripts/test-internal-mtls.sh` | PASS на обеих репликах: без cert, чужой CA и неправильная роль отклонены; прямой порт API недоступен |
|
||||
| PostgreSQL TLS | `docker compose exec -T api-a /app/.venv/bin/python - < student-tests/postgres_tls.py` | PASS: TLS, отказ plaintext и недоверенного CA |
|
||||
| TLS зависимостей | `docker compose exec -T api-a /app/.venv/bin/python - < student-tests/dependency_tls.py` | PASS: проверка CA S3, broker, OpenBao; закрыты внутренние порты и S3 POST |
|
||||
| Политики OpenBao | `docker compose exec -T api-a /app/.venv/bin/python - < student-tests/openbao_policy.py` и аналогично `worker` | PASS: свой path разрешён, чужой path и запись policy запрещены |
|
||||
| Права DB/broker | `docker compose exec -T api-a /app/.venv/bin/python - < student-tests/service_permissions.py` и аналогично `worker` | PASS: отказ лишних операций |
|
||||
| S3 prefix ACL | `docker compose exec -T api-a /app/.venv/bin/python - < student-tests/s3_prefix_permissions.py` и аналогично `worker` | PASS: запись в staging разрешена; запись API в originals и worker в bootstrap отклонена |
|
||||
| Collector | `docker compose exec -T api-a /app/.venv/bin/python - < student-tests/telemetry_tls.py` | PASS: разрешённый publisher проходит; без cert и с чужой ролью отказ |
|
||||
| Observability | `python3 student-tests/observability_tls.py` | PASS: Grafana запрашивает данные Prometheus, Loki и Tempo через TLS; `GRAFANA_URL` меняет адрес |
|
||||
| ACL и expiry | `python3 student-tests/lab7_security.py --base-url https://localhost:8443 --ca-file "$PWD/secrets/ca.crt"` | PASS: чужое вложение, hostname и истечение синтетической сессии |
|
||||
| Лимиты | `python3 student-tests/lab7_limits.py` в окружении зависимостей приложения | PASS: лимит запросов и 429/Retry-After |
|
||||
| Сохранность | `python3 student-tests/persistence_evidence.py` с `BASE_URL` и `CA_FILE` | PASS: данные, вложение и прежняя сессия сохранились; время запуска хранилищ и API до/после записано в `evidence/lab7-persistence.json` |
|
||||
| Отказ API | `make test-failover ACTION_SCRIPT=scripts/stop-one.sh CA_FILE="$PWD/secrets/ca.crt"` | PASS отдельно для обеих реплик и повторно для API-A после финальной S3 ACL; `evidence/lab7-failover.json`. После теста остановленную реплику нужно восстановить |
|
||||
|
||||
Локальные запуски использовали порты API `18443` и Grafana `13000` через временный Compose override из-за занятых портов. Для failover первой реплики за 15 секунд было 92 подтверждённых записи, 2 неуспешные попытки, восстановление записи через 5,910 с; для второй — 111, 1 и 2,887 с соответственно. Это результаты отдельных запусков публичного closed-loop сценария, а не показатели максимальной производительности. Raw-вывод отдельных запусков не сохранён.
|
||||
|
||||
Argon2id настроен на `m=19456 KiB`, `t=2`, `p=1`. Один запуск `docker compose exec -T api-a /app/.venv/bin/python - < scripts/benchmark-argon2.py` выполнил по 10 последовательных хеширований и проверок: медианы 11,84 и 11,27 мс. Контейнер API ограничен 0,5 CPU и 512 MiB; Docker сообщил 10 CPU и 10 416 644 096 байт памяти. Параметры соответствуют минимуму задания, а замер показывает задержку одной операции на этом стенде; выбор не исследован при параллельной нагрузке и не является оценкой устойчивости к DoS.
|
||||
|
||||
`docker inspect` показал для API и worker пользователя `65534:65534`, `privileged=false` и `cap_drop=[ALL]`; лимиты API — 0,5 CPU/512 MiB, worker — 2 CPU/4 GiB. Конфигурация остальных сервисов также содержит CPU и memory limits. Повторная проверка `python3 student-tests/runtime_hardening.py` подтверждает ограничения фактически работающих контейнеров. `student-tests/ingress_redaction.py` проверяет отсутствие синтетических секретов в access-логах; `student-tests/telemetry_unit.py` — фильтрацию полей OTLP. Это не исчерпывающий аудит всех каналов утечки.
|
||||
|
||||
## Ограничения
|
||||
|
||||
Rate limit локален каждой API-реплике: 60 попыток за 60 секунд на процесс и может затрагивать добросовестных клиентов. S3-прокси поддерживает только SigV4 и запрещает экранированные и неоднозначные пути и POST; проверки ACL ограничены заявленными сценариями. Токены и секреты OpenBao читаются при запуске, автоматическая ротация и renewal не реализованы. Поведение при потере одного хоста и отказ отдельных хранилищ не исследованы. Один узел PostgreSQL, RabbitMQ, S3 и OpenBao не образует отказоустойчивый кластер.
|
||||
|
||||
Для SeaweedFS опубликовано [сообщение о обходе bucket policy через POST Object](https://github.com/seaweedfs/seaweedfs/security/advisories/GHSA-qmx6-fpcw-q3xg), в котором указаны затронутые версии до 4.45 включительно и отсутствие исправленной версии на дату публикации. Стенд использует 4.17. В приложении POST Object не нужен; прокси запрещает HTTP POST, что проверяет `student-tests/dependency_tls.py`. Это ограничение конкретного пути, а не утверждение об устранении всех уязвимостей SeaweedFS.
|
||||
|
||||
Не проверены все возможные пути утечки секретов в телеметрию и все сценарии отказа зависимостей. Оценка не подтверждается одним smoke-тестом.
|
||||
|
||||
## Повторный строгий аудит
|
||||
|
||||
Обнаружена и воспроизведена запись синтетического секрета из query string в stdout HAProxy. `infra/haproxy.cfg` теперь пишет только статус, размер, backend/server и код завершения; URL и заголовки исключены. Регрессия: `BASE_URL=https://localhost:18443 python3 student-tests/ingress_redaction.py`. Проверка касается этих access-логов, а не всех потенциальных каналов утечки.
|
||||
|
||||
Добавлены подготовка прав файлов secrets для non-root контейнеров и зависимость outbox/reconcile от успешного `db-provision`, чтобы запуск не опережал выдачу прав БД. S3-прокси явно отклоняет повторные Authorization; в проверенном исходном сценарии обход ACL не воспроизвёлся (403), поэтому это усиление, а не подтверждённая уязвимость.
|
||||
|
||||
Повторные проверки сохранены в [evidence/lab7-strict-audit.json](evidence/lab7-strict-audit.json): HTTPS smoke, внешний TLS, mTLS обеих реплик, ACL/expiry/hostname, scoped policies и права API/worker, TLS зависимостей, лимиты, OTLP redaction и доступ Grafana к трём источникам. Linux DAC проверен в одноразовом контейнере на синтетических файлах (`student-tests/secret_file_permissions.py`), без утверждения о полном развёртывании на отдельном Linux-хосте.
|
||||
|
||||
После исправлений повторно прошёл persistence с фактическими временами рестарта (`evidence/lab7-persistence.json`). Повторный последовательный failover и восстановление API-A/API-B фиксируются отдельно в `evidence/lab7-failover-audit.json`. Публичные тесты и контракт не изменялись.
|
||||
|
||||
+671
@@ -0,0 +1,671 @@
|
||||
x-api: &api
|
||||
group_add: ["${LAB_SECRET_GID:-65534}"]
|
||||
build:
|
||||
context: .
|
||||
cap_drop: [ALL]
|
||||
security_opt: [no-new-privileges:true]
|
||||
command: ["/app/.venv/bin/python", "-m", "src.bao_entrypoint", "/app/.venv/bin/python", "-m", "src.main"]
|
||||
environment:
|
||||
APP_HOST: 127.0.0.1
|
||||
APP_PORT: 8080
|
||||
APP_ENV: lab
|
||||
OTEL_ENABLED: "1"
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:4318
|
||||
OTEL_EXPORTER_OTLP_CERTIFICATE: /run/secrets/ca_cert
|
||||
OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: /run/secrets/otel_api_cert
|
||||
OTEL_EXPORTER_OTLP_CLIENT_KEY: /run/secrets/otel_api_cert
|
||||
DATABASE_CA_FILE: /run/secrets/ca_cert
|
||||
BROKER_CA_FILE: /run/secrets/ca_cert
|
||||
BAO_ADDR: https://openbao:8200
|
||||
BAO_CACERT: /run/secrets/ca_cert
|
||||
BAO_CLIENT_CERT: /run/secrets/bao_api_cert
|
||||
BAO_SERVICE_ROLE: api
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||
IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400}
|
||||
S3_ENDPOINT: https://s3:8333
|
||||
AWS_CA_BUNDLE: /run/secrets/ca_cert
|
||||
S3_BUCKET: messenger-attachments
|
||||
MAX_UPLOAD_BYTES: "10485760"
|
||||
MAX_IMAGE_PIXELS: "40000000"
|
||||
UPLOAD_CONCURRENCY: "1"
|
||||
UPLOAD_TIMEOUT_SECONDS: "30"
|
||||
UPLOAD_FAULT_AFTER_S3_PUT: ${UPLOAD_FAULT_AFTER_S3_PUT:-0}
|
||||
OUTBOX_FAULT_AFTER_COMMIT: ${OUTBOX_FAULT_AFTER_COMMIT:-0}
|
||||
MAX_PENDING_JOBS: ${MAX_PENDING_JOBS:-100}
|
||||
secrets:
|
||||
- ca_cert
|
||||
- bao_api_cert
|
||||
- otel_api_cert
|
||||
depends_on:
|
||||
openbao:
|
||||
condition: service_started
|
||||
s3-init:
|
||||
condition: service_completed_successfully
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
db-provision:
|
||||
condition: service_completed_successfully
|
||||
broker:
|
||||
condition: service_healthy
|
||||
broker-tcp:
|
||||
condition: service_started
|
||||
stop_grace_period: 10s
|
||||
healthcheck:
|
||||
test: ["CMD", "/app/.venv/bin/python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health/ready', timeout=2).read()"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 12
|
||||
start_period: 10s
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "0.50"
|
||||
memory: 512M
|
||||
|
||||
services:
|
||||
openbao:
|
||||
group_add: ["${LAB_SECRET_GID:-65534}"]
|
||||
image: openbao/openbao:2.3.2
|
||||
user: "0:0"
|
||||
entrypoint: ["bao"]
|
||||
command: ["server", "-config=/bao/config/openbao.hcl"]
|
||||
environment:
|
||||
BAO_ADDR: https://openbao:8200
|
||||
BAO_CACERT: /run/secrets/ca.crt
|
||||
ports:
|
||||
- "127.0.0.1:${BAO_HOST_PORT:-18200}:8200"
|
||||
volumes:
|
||||
- ./infra/openbao/openbao.hcl:/bao/config/openbao.hcl:ro
|
||||
- ./secrets/openbao.pem:/run/secrets/openbao.pem:ro
|
||||
- ./secrets/ca.crt:/run/secrets/ca.crt:ro
|
||||
- openbao_data:/bao/file
|
||||
cap_drop: [ALL]
|
||||
security_opt: [no-new-privileges:true]
|
||||
mem_limit: 256m
|
||||
cpus: "0.50"
|
||||
|
||||
broker:
|
||||
group_add: ["${LAB_SECRET_GID:-65534}"]
|
||||
image: rabbitmq:4.1.2-alpine
|
||||
hostname: broker
|
||||
extra_hosts: ["broker:127.0.0.1"]
|
||||
environment:
|
||||
RABBITMQ_DEFAULT_USER: messenger
|
||||
RABBITMQ_SERVER_ADDITIONAL_ERL_ARGS: "-kernel inet_dist_use_interface {127,0,0,1}"
|
||||
ERL_EPMD_ADDRESS: 127.0.0.1
|
||||
entrypoint: ["/bin/sh", "/usr/local/bin/rabbitmq-secret-entrypoint.sh"]
|
||||
command: ["rabbitmq-server"]
|
||||
secrets:
|
||||
- rabbitmq_password
|
||||
- broker_tls
|
||||
- broker_api_password_hash
|
||||
- broker_worker_password_hash
|
||||
- broker_outbox_password_hash
|
||||
volumes:
|
||||
- rabbitmq_data:/var/lib/rabbitmq
|
||||
- ./infra/rabbitmq-secret-entrypoint.sh:/usr/local/bin/rabbitmq-secret-entrypoint.sh:ro
|
||||
- ./infra/rabbitmq.conf:/etc/rabbitmq/rabbitmq.conf:ro
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "test -f /tmp/rabbitmq-tls/provisioned && rabbitmq-diagnostics -q ping"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
start_period: 10s
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "0.50"
|
||||
memory: 256M
|
||||
|
||||
broker-tcp:
|
||||
group_add: ["${LAB_SECRET_GID:-65534}"]
|
||||
image: haproxy:3.0.11-alpine
|
||||
network_mode: service:broker
|
||||
depends_on:
|
||||
broker:
|
||||
condition: service_healthy
|
||||
volumes:
|
||||
- ./infra/broker-tcp.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
||||
restart: unless-stopped
|
||||
mem_limit: 128m
|
||||
cpus: "0.25"
|
||||
|
||||
s3:
|
||||
group_add: ["${LAB_SECRET_GID:-65534}"]
|
||||
image: chrislusf/seaweedfs:4.17@sha256:186de7ef977a20343ee9a5544073f081976a29e2d29ecf8379891e7bf177fbe9
|
||||
command: ["server", "-dir=/data", "-ip=127.0.0.1", "-ip.bind=127.0.0.1", "-s3", "-s3.port=18333", "-s3.config=/run/secrets/s3_config", "-s3.cert.file=/run/secrets/s3_tls", "-s3.key.file=/run/secrets/s3_tls", "-master.volumeSizeLimitMB=128", "-volume.max=64", "-s3.port.iceberg=0", "-filer.exposeDirectoryData=false"]
|
||||
secrets:
|
||||
- s3_config
|
||||
- s3_tls
|
||||
volumes:
|
||||
- s3_data:/data
|
||||
- ./infra/filer.toml:/etc/seaweedfs/filer.toml:ro
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:9333/cluster/status"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
start_period: 15s
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "1.0"
|
||||
memory: 512M
|
||||
|
||||
s3-tcp:
|
||||
group_add: ["${LAB_SECRET_GID:-65534}"]
|
||||
image: haproxy:3.0.11-alpine
|
||||
network_mode: service:s3
|
||||
depends_on:
|
||||
s3:
|
||||
condition: service_healthy
|
||||
volumes:
|
||||
- ./infra/s3-tcp.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
||||
- ./secrets/s3.pem:/run/secrets/server.pem:ro
|
||||
- ./secrets/ca.crt:/run/secrets/ca.crt:ro
|
||||
- ./secrets/s3_admin_acl:/run/secrets/admin_acl:ro
|
||||
- ./secrets/s3_api_acl:/run/secrets/api_acl:ro
|
||||
- ./secrets/s3_worker_acl:/run/secrets/worker_acl:ro
|
||||
- ./secrets/s3_reconcile_acl:/run/secrets/reconcile_acl:ro
|
||||
restart: unless-stopped
|
||||
mem_limit: 128m
|
||||
cpus: "0.25"
|
||||
|
||||
s3-init:
|
||||
group_add: ["${LAB_SECRET_GID:-65534}"]
|
||||
build:
|
||||
context: .
|
||||
command: ["/app/.venv/bin/python", "-m", "src.bootstrap_s3"]
|
||||
environment:
|
||||
S3_ENDPOINT: https://s3:8333
|
||||
AWS_CA_BUNDLE: /run/secrets/ca_cert
|
||||
S3_BUCKET: messenger-attachments
|
||||
S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_admin_key
|
||||
S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_admin_secret
|
||||
secrets:
|
||||
- ca_cert
|
||||
- s3_admin_key
|
||||
- s3_admin_secret
|
||||
depends_on:
|
||||
s3-tcp:
|
||||
condition: service_started
|
||||
restart: "no"
|
||||
mem_limit: 256m
|
||||
cpus: "0.50"
|
||||
|
||||
postgres:
|
||||
group_add: ["${LAB_SECRET_GID:-65534}"]
|
||||
image: postgres:17.6-alpine
|
||||
entrypoint: ["/bin/sh", "/usr/local/bin/postgres-tls-entrypoint.sh"]
|
||||
command: ["postgres", "-c", "track_commit_timestamp=on", "-c", "ssl=on", "-c", "ssl_cert_file=/tmp/postgres-tls/server.pem", "-c", "ssl_key_file=/tmp/postgres-tls/server.pem", "-c", "hba_file=/etc/postgresql/pg_hba.conf"]
|
||||
environment:
|
||||
POSTGRES_DB: messenger
|
||||
POSTGRES_USER: messenger
|
||||
POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password
|
||||
secrets:
|
||||
- postgres_password
|
||||
- postgres_tls
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
- ./infra/postgres-tls-entrypoint.sh:/usr/local/bin/postgres-tls-entrypoint.sh:ro
|
||||
- ./infra/postgres-pg_hba.conf:/etc/postgresql/pg_hba.conf:ro
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U messenger -d messenger"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 12
|
||||
start_period: 5s
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "0.75"
|
||||
memory: 512M
|
||||
|
||||
migrate:
|
||||
group_add: ["${LAB_SECRET_GID:-65534}"]
|
||||
build:
|
||||
context: .
|
||||
command: ["/app/.venv/bin/python", "-m", "src.migrate"]
|
||||
environment:
|
||||
DATABASE_URL_FILE: /run/secrets/database_url
|
||||
DATABASE_CA_FILE: /run/secrets/ca_cert
|
||||
CURSOR_SECRET_FILE: /run/secrets/cursor_secret
|
||||
secrets:
|
||||
- ca_cert
|
||||
- database_url
|
||||
- cursor_secret
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
restart: "no"
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "0.25"
|
||||
memory: 128M
|
||||
|
||||
db-provision:
|
||||
group_add: ["${LAB_SECRET_GID:-65534}"]
|
||||
build:
|
||||
context: .
|
||||
command: ["/app/.venv/bin/python", "-m", "src.provision_db_roles"]
|
||||
secrets:
|
||||
- database_url
|
||||
- database_api_password
|
||||
- database_worker_password
|
||||
- database_outbox_password
|
||||
- database_reconcile_password
|
||||
- ca_cert
|
||||
depends_on:
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
restart: "no"
|
||||
mem_limit: 128m
|
||||
cpus: "0.25"
|
||||
|
||||
reconcile:
|
||||
group_add: ["${LAB_SECRET_GID:-65534}"]
|
||||
healthcheck:
|
||||
disable: true
|
||||
build:
|
||||
context: .
|
||||
entrypoint: ["/app/.venv/bin/python", "-m", "src.reconcile"]
|
||||
command: ["--apply", "--loop"]
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
DATABASE_URL_FILE: /run/secrets/database_reconcile_url
|
||||
DATABASE_CA_FILE: /run/secrets/ca_cert
|
||||
CURSOR_SECRET_FILE: /run/secrets/cursor_secret
|
||||
S3_ENDPOINT: https://s3:8333
|
||||
AWS_CA_BUNDLE: /run/secrets/ca_cert
|
||||
S3_BUCKET: messenger-attachments
|
||||
S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_reconcile_access_key_id
|
||||
S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_reconcile_secret_access_key
|
||||
STAGING_RETENTION_SECONDS: ${STAGING_RETENTION_SECONDS:-86400}
|
||||
secrets:
|
||||
- ca_cert
|
||||
- database_reconcile_url
|
||||
- cursor_secret
|
||||
- s3_reconcile_access_key_id
|
||||
- s3_reconcile_secret_access_key
|
||||
depends_on:
|
||||
db-provision:
|
||||
condition: service_completed_successfully
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
s3:
|
||||
condition: service_healthy
|
||||
s3-tcp:
|
||||
condition: service_started
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "0.25"
|
||||
memory: 128M
|
||||
|
||||
api-a:
|
||||
<<: *api
|
||||
|
||||
api-b:
|
||||
<<: *api
|
||||
|
||||
api-a-tls:
|
||||
group_add: ["${LAB_SECRET_GID:-65534}"]
|
||||
image: haproxy:3.0.11-alpine
|
||||
network_mode: service:api-a
|
||||
depends_on:
|
||||
api-a:
|
||||
condition: service_healthy
|
||||
volumes:
|
||||
- ./infra/api-tls.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
||||
- ./secrets/api-a.pem:/run/secrets/api.pem:ro
|
||||
- ./secrets/ca.crt:/run/secrets/ca.crt:ro
|
||||
restart: unless-stopped
|
||||
mem_limit: 128m
|
||||
cpus: "0.25"
|
||||
|
||||
api-b-tls:
|
||||
group_add: ["${LAB_SECRET_GID:-65534}"]
|
||||
image: haproxy:3.0.11-alpine
|
||||
network_mode: service:api-b
|
||||
depends_on:
|
||||
api-b:
|
||||
condition: service_healthy
|
||||
volumes:
|
||||
- ./infra/api-tls.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
||||
- ./secrets/api-b.pem:/run/secrets/api.pem:ro
|
||||
- ./secrets/ca.crt:/run/secrets/ca.crt:ro
|
||||
restart: unless-stopped
|
||||
mem_limit: 128m
|
||||
cpus: "0.25"
|
||||
|
||||
worker:
|
||||
group_add: ["${LAB_SECRET_GID:-65534}"]
|
||||
restart: unless-stopped
|
||||
cap_drop: [ALL]
|
||||
security_opt: [no-new-privileges:true]
|
||||
healthcheck:
|
||||
test: ["CMD", "/app/.venv/bin/python", "-c", "import time,pathlib; assert time.time()-float(pathlib.Path('/tmp/worker-heartbeat').read_text()) < 15"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 3
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "2.0"
|
||||
memory: 4G
|
||||
build:
|
||||
context: .
|
||||
command: ["/app/.venv/bin/python", "-m", "src.bao_entrypoint", "/app/.venv/bin/python", "-m", "src.worker"]
|
||||
environment:
|
||||
APP_ENV: lab
|
||||
OTEL_ENABLED: "1"
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:4318
|
||||
OTEL_EXPORTER_OTLP_CERTIFICATE: /run/secrets/ca_cert
|
||||
OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: /run/secrets/otel_worker_cert
|
||||
OTEL_EXPORTER_OTLP_CLIENT_KEY: /run/secrets/otel_worker_cert
|
||||
DATABASE_CA_FILE: /run/secrets/ca_cert
|
||||
BROKER_CA_FILE: /run/secrets/ca_cert
|
||||
BAO_ADDR: https://openbao:8200
|
||||
BAO_CACERT: /run/secrets/ca_cert
|
||||
BAO_CLIENT_CERT: /run/secrets/bao_worker_cert
|
||||
BAO_SERVICE_ROLE: worker
|
||||
S3_ENDPOINT: https://s3:8333
|
||||
AWS_CA_BUNDLE: /run/secrets/ca_cert
|
||||
S3_BUCKET: messenger-attachments
|
||||
WORKER_CONCURRENCY: ${WORKER_CONCURRENCY:-2}
|
||||
WORKER_FAULT_AFTER_S3_PUT: ${WORKER_FAULT_AFTER_S3_PUT:-0}
|
||||
RENDER_MEMORY_MB: ${RENDER_MEMORY_MB:-768}
|
||||
WORKER_PREFETCH: ${WORKER_PREFETCH:-2}
|
||||
JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5}
|
||||
JOB_TIMEOUT_SECONDS: ${JOB_TIMEOUT_SECONDS:-60}
|
||||
STAGING_RETENTION_SECONDS: ${STAGING_RETENTION_SECONDS:-86400}
|
||||
secrets:
|
||||
- ca_cert
|
||||
- bao_worker_cert
|
||||
- otel_worker_cert
|
||||
depends_on:
|
||||
openbao:
|
||||
condition: service_started
|
||||
db-provision:
|
||||
condition: service_completed_successfully
|
||||
s3-init:
|
||||
condition: service_completed_successfully
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
broker:
|
||||
condition: service_healthy
|
||||
broker-tcp:
|
||||
condition: service_started
|
||||
stop_grace_period: 30s
|
||||
|
||||
outbox:
|
||||
group_add: ["${LAB_SECRET_GID:-65534}"]
|
||||
mem_limit: 256m
|
||||
cpus: "0.50"
|
||||
cap_drop: [ALL]
|
||||
security_opt: [no-new-privileges:true]
|
||||
healthcheck:
|
||||
disable: true
|
||||
build:
|
||||
context: .
|
||||
command: ["/app/.venv/bin/python", "-m", "src.outbox"]
|
||||
environment:
|
||||
APP_ENV: lab
|
||||
OTEL_ENABLED: "1"
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:4318
|
||||
OTEL_EXPORTER_OTLP_CERTIFICATE: /run/secrets/ca_cert
|
||||
OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: /run/secrets/otel_outbox_cert
|
||||
OTEL_EXPORTER_OTLP_CLIENT_KEY: /run/secrets/otel_outbox_cert
|
||||
DATABASE_URL_FILE: /run/secrets/database_outbox_url
|
||||
DATABASE_CA_FILE: /run/secrets/ca_cert
|
||||
CURSOR_SECRET_FILE: /run/secrets/cursor_secret
|
||||
BROKER_URL_FILE: /run/secrets/broker_outbox_url
|
||||
BROKER_CA_FILE: /run/secrets/ca_cert
|
||||
OUTBOX_DISPATCH_INTERVAL_SECONDS: "1"
|
||||
JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5}
|
||||
secrets:
|
||||
- ca_cert
|
||||
- database_outbox_url
|
||||
- cursor_secret
|
||||
- broker_outbox_url
|
||||
- otel_outbox_cert
|
||||
depends_on:
|
||||
db-provision:
|
||||
condition: service_completed_successfully
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
broker:
|
||||
condition: service_healthy
|
||||
broker-tcp:
|
||||
condition: service_started
|
||||
restart: unless-stopped
|
||||
|
||||
load_balancer:
|
||||
group_add: ["${LAB_SECRET_GID:-65534}"]
|
||||
image: haproxy:3.0.11-alpine
|
||||
ports:
|
||||
- "127.0.0.1:${PUBLIC_HTTPS_PORT:-8443}:8443"
|
||||
volumes:
|
||||
- ./infra/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
||||
- ./secrets/ingress.pem:/run/secrets/ingress.pem:ro
|
||||
- ./secrets/lb.pem:/run/secrets/lb.pem:ro
|
||||
- ./secrets/ca.crt:/run/secrets/ca.crt:ro
|
||||
depends_on:
|
||||
api-a:
|
||||
condition: service_healthy
|
||||
api-b:
|
||||
condition: service_healthy
|
||||
api-a-tls:
|
||||
condition: service_started
|
||||
api-b-tls:
|
||||
condition: service_started
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "wget -q -O /dev/null http://127.0.0.1:8404/health/ready"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 12
|
||||
start_period: 5s
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: "0.25"
|
||||
memory: 128M
|
||||
|
||||
otel-collector:
|
||||
group_add: ["${LAB_SECRET_GID:-65534}"]
|
||||
image: otel/opentelemetry-collector-contrib:0.120.0
|
||||
command: ["--config=/etc/otelcol/config.yaml"]
|
||||
volumes:
|
||||
- ./infra/otel/collector.yaml:/etc/otelcol/config.yaml:ro
|
||||
secrets: [ca_cert, telemetry_collector_cert]
|
||||
mem_limit: 256m
|
||||
cpus: "0.50"
|
||||
restart: unless-stopped
|
||||
otel-tls:
|
||||
group_add: ["${LAB_SECRET_GID:-65534}"]
|
||||
image: haproxy:3.0.11-alpine
|
||||
network_mode: service:otel-collector
|
||||
depends_on: [otel-collector]
|
||||
volumes:
|
||||
- ./infra/otel-tls.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
||||
- ./secrets/otel-collector.pem:/run/secrets/server.pem:ro
|
||||
- ./secrets/ca.crt:/run/secrets/ca.crt:ro
|
||||
restart: unless-stopped
|
||||
mem_limit: 128m
|
||||
cpus: "0.25"
|
||||
prometheus:
|
||||
group_add: ["${LAB_SECRET_GID:-65534}"]
|
||||
image: prom/prometheus:v3.2.1
|
||||
mem_limit: 512m
|
||||
cpus: "0.50"
|
||||
command: ["--config.file=/etc/prometheus/prometheus.yaml", "--web.listen-address=127.0.0.1:19090", "--storage.tsdb.path=/prometheus", "--storage.tsdb.retention.time=7d"]
|
||||
secrets: [ca_cert, telemetry_prometheus_cert]
|
||||
volumes:
|
||||
- ./infra/prometheus/prometheus.yaml:/etc/prometheus/prometheus.yaml:ro
|
||||
- ./infra/prometheus/alerts.yaml:/etc/prometheus/alerts.yaml:ro
|
||||
- prometheus_data:/prometheus
|
||||
restart: unless-stopped
|
||||
prometheus-tls:
|
||||
group_add: ["${LAB_SECRET_GID:-65534}"]
|
||||
image: haproxy:3.0.11-alpine
|
||||
network_mode: service:prometheus
|
||||
depends_on: [prometheus]
|
||||
volumes:
|
||||
- ./infra/prometheus-tls.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
||||
- ./secrets/prometheus.pem:/run/secrets/server.pem:ro
|
||||
- ./secrets/ca.crt:/run/secrets/ca.crt:ro
|
||||
restart: unless-stopped
|
||||
mem_limit: 128m
|
||||
cpus: "0.25"
|
||||
loki:
|
||||
group_add: ["${LAB_SECRET_GID:-65534}"]
|
||||
image: grafana/loki:3.4.2
|
||||
mem_limit: 512m
|
||||
cpus: "0.50"
|
||||
command: ["-config.file=/etc/loki/loki.yaml"]
|
||||
volumes:
|
||||
- ./infra/loki/loki.yaml:/etc/loki/loki.yaml:ro
|
||||
- loki_data:/loki
|
||||
restart: unless-stopped
|
||||
loki-tls:
|
||||
group_add: ["${LAB_SECRET_GID:-65534}"]
|
||||
image: haproxy:3.0.11-alpine
|
||||
network_mode: service:loki
|
||||
depends_on: [loki]
|
||||
volumes:
|
||||
- ./infra/loki-tls.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
||||
- ./secrets/loki.pem:/run/secrets/server.pem:ro
|
||||
- ./secrets/ca.crt:/run/secrets/ca.crt:ro
|
||||
restart: unless-stopped
|
||||
mem_limit: 128m
|
||||
cpus: "0.25"
|
||||
tempo:
|
||||
group_add: ["${LAB_SECRET_GID:-65534}"]
|
||||
image: grafana/tempo:2.7.1
|
||||
mem_limit: 512m
|
||||
cpus: "0.50"
|
||||
command: ["-config.file=/etc/tempo/tempo.yaml"]
|
||||
volumes:
|
||||
- ./infra/tempo/tempo.yaml:/etc/tempo/tempo.yaml:ro
|
||||
- tempo_data:/var/tempo
|
||||
restart: unless-stopped
|
||||
tempo-tls:
|
||||
group_add: ["${LAB_SECRET_GID:-65534}"]
|
||||
image: haproxy:3.0.11-alpine
|
||||
network_mode: service:tempo
|
||||
depends_on: [tempo]
|
||||
volumes:
|
||||
- ./infra/tempo-tls.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
||||
- ./secrets/tempo.pem:/run/secrets/server.pem:ro
|
||||
- ./secrets/ca.crt:/run/secrets/ca.crt:ro
|
||||
restart: unless-stopped
|
||||
mem_limit: 128m
|
||||
cpus: "0.25"
|
||||
grafana:
|
||||
group_add: ["${LAB_SECRET_GID:-65534}"]
|
||||
image: grafana/grafana:11.5.2
|
||||
mem_limit: 512m
|
||||
cpus: "0.50"
|
||||
ports: ["127.0.0.1:${GRAFANA_HOST_PORT:-3000}:3000"]
|
||||
environment:
|
||||
GF_SECURITY_ADMIN_USER: admin
|
||||
GF_SECURITY_ADMIN_PASSWORD__FILE: /run/secrets/grafana_password
|
||||
GF_USERS_ALLOW_SIGN_UP: "false"
|
||||
GF_SERVER_PROTOCOL: https
|
||||
GF_SERVER_CERT_FILE: /run/secrets/grafana_tls
|
||||
GF_SERVER_CERT_KEY: /run/secrets/grafana_tls
|
||||
entrypoint: ["/bin/sh", "/etc/grafana/lab-entrypoint.sh"]
|
||||
secrets: [grafana_password, grafana_tls, ca_cert, telemetry_grafana_cert]
|
||||
volumes:
|
||||
- grafana_data:/var/lib/grafana
|
||||
- ./infra/grafana/provisioning:/etc/grafana/provisioning:ro
|
||||
- ./infra/grafana/dashboards:/var/lib/grafana/dashboards:ro
|
||||
- ./infra/grafana-entrypoint.sh:/etc/grafana/lab-entrypoint.sh:ro
|
||||
restart: unless-stopped
|
||||
|
||||
secrets:
|
||||
database_outbox_password:
|
||||
file: ./secrets/database_outbox_password
|
||||
database_reconcile_password:
|
||||
file: ./secrets/database_reconcile_password
|
||||
database_outbox_url:
|
||||
file: ./secrets/database_outbox_url
|
||||
database_reconcile_url:
|
||||
file: ./secrets/database_reconcile_url
|
||||
s3_reconcile_access_key_id:
|
||||
file: ./secrets/s3_reconcile_access_key_id
|
||||
s3_reconcile_secret_access_key:
|
||||
file: ./secrets/s3_reconcile_secret_access_key
|
||||
telemetry_grafana_cert:
|
||||
file: ./secrets/telemetry-grafana.pem
|
||||
telemetry_collector_cert:
|
||||
file: ./secrets/telemetry-collector.pem
|
||||
telemetry_prometheus_cert:
|
||||
file: ./secrets/telemetry-prometheus.pem
|
||||
grafana_tls:
|
||||
file: ./secrets/grafana.pem
|
||||
otel_api_cert:
|
||||
file: ./secrets/otel-api.pem
|
||||
otel_worker_cert:
|
||||
file: ./secrets/otel-worker.pem
|
||||
otel_outbox_cert:
|
||||
file: ./secrets/otel-outbox.pem
|
||||
database_api_password:
|
||||
file: ./secrets/database_api_password
|
||||
database_worker_password:
|
||||
file: ./secrets/database_worker_password
|
||||
broker_api_password_hash:
|
||||
file: ./secrets/broker_api_password_hash
|
||||
broker_worker_password_hash:
|
||||
file: ./secrets/broker_worker_password_hash
|
||||
broker_outbox_password_hash:
|
||||
file: ./secrets/broker_outbox_password_hash
|
||||
broker_outbox_url:
|
||||
file: ./secrets/broker_outbox_url
|
||||
broker_tls:
|
||||
file: ./secrets/broker.pem
|
||||
broker_tls_url:
|
||||
file: ./secrets/broker_tls_url
|
||||
s3_tls:
|
||||
file: ./secrets/s3.pem
|
||||
bao_api_cert:
|
||||
file: ./secrets/bao-api.pem
|
||||
bao_worker_cert:
|
||||
file: ./secrets/bao-worker.pem
|
||||
ca_cert:
|
||||
file: ./secrets/ca.crt
|
||||
postgres_tls:
|
||||
file: ./secrets/postgres.pem
|
||||
grafana_password:
|
||||
file: ./secrets/grafana_password
|
||||
s3_config:
|
||||
file: ./secrets/s3.json
|
||||
s3_admin_key:
|
||||
file: ./secrets/s3_admin_key
|
||||
s3_admin_secret:
|
||||
file: ./secrets/s3_admin_secret
|
||||
s3_access_key_id:
|
||||
file: ./secrets/s3_access_key_id
|
||||
s3_secret_access_key:
|
||||
file: ./secrets/s3_secret_access_key
|
||||
postgres_password:
|
||||
file: ./secrets/postgres_password
|
||||
database_url:
|
||||
file: ./secrets/database_url
|
||||
cursor_secret:
|
||||
file: ./secrets/cursor_secret
|
||||
rabbitmq_password:
|
||||
file: ./secrets/rabbitmq_password
|
||||
broker_url:
|
||||
file: ./secrets/broker_url
|
||||
|
||||
volumes:
|
||||
openbao_data:
|
||||
prometheus_data:
|
||||
loki_data:
|
||||
tempo_data:
|
||||
grafana_data:
|
||||
s3_data:
|
||||
postgres_data:
|
||||
rabbitmq_data:
|
||||
+12
-12
@@ -4,18 +4,18 @@
|
||||
|
||||
| Связь | Минимум на 3 | Дополнительно на 4 | Доказательство / конфиг |
|
||||
| --- | --- | --- | --- |
|
||||
| Клиент → ingress/LB | TLS, CA + hostname, Bearer | Проверка expiry/revocation сессии и общего login rate limit | TODO |
|
||||
| LB → API (все реплики) | mTLS + allowlist LB identity | Ротация leaf без обхода проверки | TODO |
|
||||
| API/worker → PostgreSQL | TLS verify-full + раздельные ограниченные DB roles | Ротация credentials; mTLS — допустимое усиление | TODO |
|
||||
| API/worker → S3 | TLS + разные scoped credentials/prefix rights | Проверка denied prefix и ротация | TODO |
|
||||
| API/worker → broker | TLS + разные producer/consumer identities и ACL | mTLS + ограничение допустимых SAN/ролей | TODO |
|
||||
| API/worker → Collector | TLS; сеть/аутентификация запрещает произвольный ingest | mTLS с раздельными identities | TODO |
|
||||
| Collector → telemetry backends | TLS + scoped backend credentials или mTLS | Ротация и проверка least privilege | TODO |
|
||||
| Grafana → data sources | TLS с проверкой сервера, ограниченная identity | Отрицательные проверки доступа | TODO |
|
||||
| API/worker/agent → OpenBao | TLS + сервисный auth + scoped policy | Renewal/expiry/revocation | TODO |
|
||||
| Оператор → OpenBao/Grafana/S3 admin | TLS + authentication, доступ локальный/через защищённый канал | Разделение operator/application roles | TODO |
|
||||
| API → Redis/Valkey, если используется | TLS + ACL/пароль с минимальными правами | Ротация; mTLS по возможности | TODO |
|
||||
| Replication/кластерные каналы, если добавлены | TLS/mTLS либо подтверждённый шифрованный transport | Проверка заявленной модели отказа | TODO |
|
||||
| Клиент → ingress/LB | TLS, CA + hostname, Bearer | Проверка expiry/revocation сессии и общего login rate limit | `https://localhost:8443` (порт настраивается), DNS/IP SAN `localhost`/`127.0.0.1`, CA `secrets/ca.crt`; `make test-security`, `student-tests/lab7_security.py`; session TTL по умолчанию 3600 с. |
|
||||
| LB → API (все реплики) | mTLS + allowlist LB identity | Ротация leaf без обхода проверки | `infra/api-tls.cfg`, `infra/haproxy.cfg`; TCP 8444, TLS-прокси каждой реплики проверяет CA и роль `CN=lb, OU=load-balancer`, LB проверяет DNS identity `api-a`/`api-b`; `sh scripts/test-internal-mtls.sh`. Сертификаты на 90 дней, renewal пока ручной. API порт 8080 доступен только через loopback в сетевом пространстве реплики. |
|
||||
| API/worker → PostgreSQL | TLS verify-full + раздельные ограниченные DB roles | Ротация credentials; mTLS — допустимое усиление | TCP 5432, server DNS `postgres`, CA `/run/secrets/ca_cert`; роли `messenger_api` и `messenger_worker`, права в `src/provision_db_roles.py`. Plaintext отклоняется `infra/postgres-pg_hba.conf`. Проверки `student-tests/postgres_tls.py`, `student-tests/service_permissions.py`. Пароли статические до ротации оператором. |
|
||||
| API/worker → S3 | TLS + разные scoped credentials/prefix rights | Проверка denied prefix и ротация | `https://s3:8333`, CA `/run/secrets/ca_cert`, server DNS `s3`; отдельные ключи API/worker ограничены bucket `messenger-attachments`. Прокси по SigV4 identity разрешает API писать только в `staging/`, worker — в `staging/`, `originals/`, `variants/`; backend проверяет подпись. Прокси проверяет TLS на обоих соединениях, filer/master loopback-only. Тест `student-tests/s3_prefix_permissions.py`; срок статических ключей не ограничен. |
|
||||
| API/worker → broker | TLS + разные producer/consumer identities и ACL | mTLS + ограничение допустимых SAN/ролей | `amqps://broker:5671`, CA `/run/secrets/ca_cert`, DNS `broker`; TCP-прокси передаёт TLS к loopback 15671. Erlang distribution, EPMD и metrics listener привязаны к loopback. Отдельные роли `messenger_api`, `messenger_worker`, `messenger_outbox` и ограничения очередей в `infra/rabbitmq-secret-entrypoint.sh`. Проверки `student-tests/service_permissions.py` и `student-tests/dependency_tls.py`; пароли статические до ротации. |
|
||||
| API/worker → Collector | TLS; сеть/аутентификация запрещает произвольный ingest | mTLS с раздельными identities | `https://otel-collector:4318`, отдельные сертификаты API/worker/outbox с OU `telemetry-publisher`, CA и server DNS проверяются клиентом; `infra/otel-tls.cfg`, `student-tests/telemetry_tls.py`. Сертификаты на 90 дней. |
|
||||
| Collector → telemetry backends | TLS + scoped backend credentials или mTLS | Ротация и проверка least privilege | Loki TCP 3100 и Tempo TCP 4317: проверка server DNS/CA, клиентская роль `telemetry-writer`; Prometheus получает метрики через TLS на Collector 8888/8889 с ролью `telemetry-scraper`. TLS завершается локальными sidecar; `infra/*-tls.cfg`, `student-tests/observability_tls.py`. Сертификаты на 90 дней. |
|
||||
| Grafana → data sources | TLS с проверкой сервера, ограниченная identity | Отрицательные проверки доступа | `https://prometheus:9090`, `https://loki:3100`, `https://tempo:3200`; CA, DNS и клиентская роль `telemetry-reader`; datasource provisioning и `student-tests/observability_tls.py`. Сертификат на 90 дней. |
|
||||
| API/worker/agent → OpenBao | TLS + сервисный auth + scoped policy | Renewal/expiry/revocation | `https://openbao:8200`, CA и DNS `openbao`, отдельные клиентские cert auth identities и политики `lab/data/api`, `lab/data/worker`; срок service token 1 час, сертификаты 90 дней; `student-tests/openbao_policy.py`. Secret values считываются при старте. |
|
||||
| Оператор → OpenBao/Grafana/S3 admin | TLS + authentication, доступ локальный/через защищённый канал | Разделение operator/application roles | OpenBao `https://localhost:18200`, Grafana `https://localhost:3000`, порты привязаны к loopback. Операторские ключи/пароль хранятся в `secrets/`; S3 bootstrap работает только во внутренней сети с отдельным admin credential. |
|
||||
| API → Redis/Valkey, если используется | TLS + ACL/пароль с минимальными правами | Ротация; mTLS по возможности | N/A: сессии хранятся в PostgreSQL. |
|
||||
| Replication/кластерные каналы, если добавлены | TLS/mTLS либо подтверждённый шифрованный transport | Проверка заявленной модели отказа | Кластеры или репликация хранилищ не настроены. Встроенные локальные процессы SeaweedFS и Loki/Tempo не являются проверкой отказа хоста. |
|
||||
|
||||
Нет выбранного компонента — отметьте N/A с причиной, а не оставляйте пустую строку. Внутренний публичный health listener, если нужен, минимален и изолирован; через него нельзя обращаться к бизнес-API без mTLS. Отдельно задокументируйте scrape/health/bootstrap каналы: они тоже не должны создавать обход.
|
||||
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
# Наблюдаемость и проверка lab6
|
||||
|
||||
## Сигналы и назначение
|
||||
|
||||
API, worker и outbox отправляют OTLP/HTTP в Collector. Prometheus хранит метрики, Loki — логи, Tempo — трассы, Grafana предоставляет запросы и dashboard. Данные хранятся в именованных volumes, retention для Prometheus/Loki/Tempo — 7 дней. Grafana доступна на `http://localhost:3000`, пользователь `admin`, пароль находится в локальном `secrets/grafana_password`. Provisioning импортирует источники и dashboard `Messenger — observability`.
|
||||
|
||||
Сохраняются только выбранные поля логов; трассы не содержат SQL, аргументов запросов, заголовков авторизации, имён файлов и тел. Метрики не размечаются ID пользователей, чатов и вложений. В экспортируемых логах доступен `request_id`, а `trace_id`/`span_id` передаются полями OTLP. В Explore Loki запрос `{service_name="messenger-api"}` находит события API, `{service_name="messenger-worker"}` — worker; в метаданных события доступны ID трассы. По ним можно перейти в Tempo. Локальные stdout-логи содержат JSON с теми же trace/span ID для событий телеметрии.
|
||||
|
||||
При upload текущий W3C trace context сохраняется в `attachment_jobs` одной транзакцией с outbox. Dispatcher извлекает его и публикует сообщение с дочерним producer span и AMQP headers; worker извлекает контекст и создаёт consumer span. Повторная публикация и retry используют сохранённый контекст исходной загрузки. Каждая попытка имеет собственные spans; они являются потомками исходной транзакции загрузки. Baggage не переносится. Контекст — технические данные, не содержимое изображения.
|
||||
|
||||
Dashboard использует счётчики и гистограммы с единицами секунд: p50/p95/p99 HTTP вычисляются через `histogram_quantile` по сумме buckets, не по среднему перцентилей. `messenger_job_ready_duration_seconds` измеряет разность commit публикации ready и commit принятия задания из `attachment_slo` (миграция 009). Оба момента берутся из PostgreSQL; часы worker не участвуют. Гистограмма записывается после успешного commit: аварийное завершение worker между commit и записью метрики может потерять этот histogram sample; DB-когорта SLO при этом сохраняется. Queue depth и age — число и возраст самого старого задания в состоянии queued из PostgreSQL, включая ожидающие retry; это не длина очереди RabbitMQ. Данные обновляет outbox. DB pool отражает пул каждой API-реплики; число ожидающих читается из внутренней очереди asyncpg 0.31.0 и зависит от этой версии. Worker busy/capacity — число занятых executor threads и их лимит; повторная доставка без нового результата имеет outcome `skipped`, успешный commit — `success`, ошибка — `failed`. CPU и RSS — процессы API/worker/outbox, без дочерних процессов render. Queue-метрики имеют label `queue="attachment.process.v1"`. `messenger_queue_sample_time_seconds` показывает время последнего успешного обновления; `MessengerQueueTelemetryStale` сигнализирует об устаревании/отсутствии ряда.
|
||||
|
||||
SLI: доля ответов 5xx среди всех HTTP бизнес-запросов API, исключая health. Целевой SLO: не менее 99% запросов без 5xx за скользящие 24 часа; ошибки балансировщика, которые не дошли до API, SLI не учитывает. Целевое значение выбрано для учебного стенда, а не по измеренным требованиям пользователей. Второй SLO и расчёт burn-rate описаны в [runbook](slo-runbook.md); его DB-счётчики учитывают и невыполненные в срок задания. Alert `MessengerHighErrorRate` срабатывает при >5% за минуту в течение 10 секунд; это оперативный порог, не burn-rate alert. `MessengerQueueLag` срабатывает при возрасте queued >30 секунд в течение 15 секунд. Состояния доступны в Prometheus через Grafana Explore или локальный API Prometheus внутри контейнера.
|
||||
|
||||
Collector использует memory limiter 192 MiB, batch до 1024 записей, очереди экспортёров по 128 batches и retry до 60 секунд; лимит контейнера 256 MiB. SDK использует ограниченные очереди spans/logs по 2048 и timeout экспорта 2 секунды. При долгом отказе хранилища возможна потеря телеметрии; это не должно блокировать бизнес-обработку. Наблюдайте внутренние метрики `otelcol_exporter_queue_size`, `otelcol_exporter_send_failed_spans_total`, `otelcol_exporter_enqueue_failed_spans_total`, `otelcol_exporter_send_failed_log_records_total` и `otelcol_receiver_refused_*`. Очереди не сохраняются после перезапуска Collector.
|
||||
|
||||
## Проверки на локальном учебном стенде
|
||||
|
||||
Приведённые сценарии воспроизведены на локальном стенде; зафиксированные результаты и ограничения — в `evidence/observability.md`. Повторный запуск создаёт новые синтетические данные.
|
||||
|
||||
1. Выполните `python3 scripts/init-secrets.py`, `docker compose up -d --build`, дождитесь readiness и запустите `make test`. В Grafana найдите событие API и worker, раскройте trace_id, проверьте дерево upload → DB/outbox → producer → consumer → S3/DB и убедитесь, что содержимое/credentials не попали в telemetry. Для повторной попытки используйте имеющийся fault injection worker и проверьте новую попытку в том же trace.
|
||||
2. Очередь: `docker compose stop worker`, затем `python3 student-tests/queue_incident.py`. Смотрите queue age и alert; после перехода в firing выполните `docker compose start worker`, дождитесь уменьшения backlog и resolved. Время и скриншоты/запросы сохраните в evidence.
|
||||
3. DB: начните `python3 tests/load.py --duration 180 --concurrency 8 --output evidence/db-incident-load.json`; после завершения bootstrap в отдельном терминале выполните `docker compose exec -T postgres psql -U messenger -d messenger -c "BEGIN; LOCK TABLE users IN ACCESS EXCLUSIVE MODE; SELECT pg_sleep(90); COMMIT;"`. Наблюдайте задержку `postgres.user_for_token`, ошибки и alert; после окончания блокировки проверьте восстановление и resolved. Тест работает с синтетическими данными и намеренно мешает запросам.
|
||||
4. Отказ telemetry backend: `docker compose stop tempo`, затем `make test` и контролируемая нагрузка; сравните `docker stats --no-stream`, queue size и failed exports до/во время отказа. Восстановите `docker compose start tempo` и проверьте восстановление экспорта. Длительный отказ может привести к потере traces; измерьте её, а не предполагайте отсутствие потерь.
|
||||
|
||||
Для каждого сценария фиксируйте UTC-время воздействия, исходный профиль нагрузки, запросы метрик, firing/resolved, trace/log и результат после восстановления. `docker compose down` сохраняет volumes; не используйте `down -v`, если нужны сохранённые наблюдения.
|
||||
@@ -0,0 +1,36 @@
|
||||
# Проверка по критериям README
|
||||
|
||||
Проверялись [README](../README.md), [контракт наблюдаемости](../contracts/observability.md), исходный [REPORT](../REPORT.md), код и локальный Docker-стенд. Автоматический smoke не выставляет оценку за наблюдаемость.
|
||||
|
||||
## Итог по уровням
|
||||
|
||||
- **3: подтверждён после исправлений.** [Короткие проверки](../evidence/review-checks.json), [публичные persistence/failover](../evidence/review-resilience.json), [коррелированные логи API/worker и trace](../evidence/review-retry-trace.json).
|
||||
- **4: подтверждён в проверенном локальном стенде.** [Разбор инцидентов и отказа Tempo](../evidence/review-observability.md), [QueueLag/ready](../evidence/slo-ready-incident.json), [проверка retry-дерева](../evidence/review-retry-summary.json), [сохранность trace после рестарта Tempo](../evidence/review-tempo-persistence.json).
|
||||
- **5: техническая часть трека 2 проверена, полный зачёт не подтверждён.** [Повторные измерения](../evidence/slo-track.md) и runbook есть; независимый диагноз другого студента не задокументирован. Итоговая подтверждённая оценка этой проверки — **4**.
|
||||
|
||||
## Исправления
|
||||
|
||||
| Уровень | Найденная ошибка | Исправление и проверка |
|
||||
| --- | --- | --- |
|
||||
| 3 | Allowlist применялся только к stdout; OTLP LoggingHandler получал произвольные extra и exception | Фильтр до обоих handlers; тест реального SDK log exporter с секретом в extra и exception — [telemetry_unit.py](../student-tests/telemetry_unit.py) |
|
||||
| 3 | Произвольные HTTP method могли создавать новые metric labels | Стандартные методы и `_OTHER`; шаблон маршрута сохранён — [main.py](../src/main.py), [telemetry.py](../src/telemetry.py) |
|
||||
| 3 | Повторная доставка без нового результата считалась успешной job | Отдельный исход `skipped`; `success` только после commit ready — [worker.py](../src/worker.py), [pipeline_critical.py](../student-tests/pipeline_critical.py) |
|
||||
| 4 | Исключение publish оставляло producer span без ERROR | ERROR без экспорта текста исключения; regression test — [broker.py](../src/broker.py), [telemetry_unit.py](../student-tests/telemetry_unit.py) |
|
||||
| 4 | Histogram ready начинался до durable acceptance и использовал часы worker | Оба конца — commit timestamps PostgreSQL; [миграция 009](../migrations/009_slo_commits.sql), [изолированный интеграционный тест](../student-tests/slo_commit_integration.py) |
|
||||
| 4 | Queue gauge не имел queue name и мог незаметно устареть | Label queue, timestamp последнего обновления и stale/absent alert; [telemetry.py](../src/telemetry.py), [правила](../infra/prometheus/alerts.yaml) |
|
||||
| 4 | Потери Tempo приписывались накопленным счётчикам без baseline | Повторяемый опыт с baseline, дельтами, ID Collector и замерами памяти — [tempo_outage.py](../student-tests/tempo_outage.py) |
|
||||
| 5 | Ready SLO зависел от изменяемых status/updated_at | Отдельная зрелая когорта с однократно зафиксированным bad; retry/replay не меняют результат — [postgres.py](../src/storage/postgres.py) |
|
||||
| 5 | Старые временные результаты использовались при расхождении UTC/monotonic | Старые отсчёты сохранены в [pre-review](../evidence/pre-review/slo-analysis.json); анализатор выявил расхождение 83,075 с и пометил их непригодными для elapsed-time выводов; причина не установлена |
|
||||
| 5 | При исключении сценарий мог зависнуть, ожидая бесконечные клиентские потоки | STOP устанавливается до выхода из ThreadPoolExecutor, включая исключения — [slo_incidents.py](../student-tests/slo_incidents.py) |
|
||||
|
||||
Дополнительный прогон выявил дефект теста очереди: требовалось одновременное firing Fast и QueueLag, хотя их окна различаются. Кроме того, выбирался первый metric series старого outbox после пересоздания. [Неудачный прогон](../evidence/pre-review/ready-scenario-failed.json) сохранён; сценарий теперь проверяет наблюдение обоих сигналов и снятие каждого, а абсолютные DB-счётчики читает через max по экземплярам (они представляют одну БД).
|
||||
|
||||
## Ограничения, которые нельзя скрыть оценкой
|
||||
|
||||
- Прохождение runbook другим студентом не подтверждено. Подготовлен [протокол независимой проверки](slo-runbook.md#проверка-другим-студентом); собственная проверка не заменяет внешнюю.
|
||||
- 99%/24 часа — учебная цель; короткий опыт не доказывает выполнение суточного SLO. Baseline оценивает наблюдавшиеся ложные тревоги только за этот интервал.
|
||||
- Старые задания до миграции 009 не имеют восстановимых commit timestamps и исключены из новой когорты. Исторические Prometheus-ряды до миграции нельзя смешивать с новой методикой для доказательства SLO.
|
||||
- PostgreSQL не хранит commit timestamps бессрочно. Outbox сохраняет их в таблицу; если потерял источник до материализации, unknown alert показывает неполноту данных. При перезапуске экспортёра `increase` может не учесть события в разрыве наблюдения.
|
||||
- Histogram sample может потеряться при crash после commit ready; durable DB-когорта сохраняется. Collector с ограниченной очередью также может терять spans. Это не «нулевые потери».
|
||||
|
||||
Источник границ commit timestamps: [PostgreSQL 17](https://www.postgresql.org/docs/17/functions-info.html#FUNCTIONS-COMMIT-TIMESTAMP). Источник критериев оценки — локальные README и contracts, ссылки выше.
|
||||
@@ -0,0 +1,45 @@
|
||||
# Runbook: расход бюджета SLO
|
||||
|
||||
Используйте только учебный стенд с синтетическими данными. Grafana: `http://localhost:3000`, имя `admin`, пароль в `secrets/grafana_password`. На dashboard `Messenger — observability` находятся панели API/ready SLI и burn rates. В Explore выберите Prometheus; логи и traces доступны через Loki и Tempo. Правила — [alerts.yaml](../infra/prometheus/alerts.yaml).
|
||||
|
||||
## Что означает сигнал
|
||||
|
||||
Два учебных SLO на скользящие 24 часа: 99% бизнес-запросов API без 5xx и 99% принятых вложений становятся ready не позднее чем через 30 секунд после commit принятия задания. API исключает health и ошибки LB до попадания в приложение; 4xx остаются в знаменателе. Для готовности учтены только задания, достигшие 30-секундного возраста: неготовые, failed и завершённые позднее срока считаются плохими. Счётчики вычисляет outbox по PostgreSQL, поэтому при его недоступности данные не обновляются; события между последним scrape старого процесса и первым scrape нового могут не попасть в расчёт `increase`. Миграция 009 добавляет `attachment_slo`: моменты acceptance и первого ready берутся из commit timestamps PostgreSQL и сохраняются outbox. Результат зрелой когорты фиксируется один раз; retry/replay не меняют историю. Старые задания до миграции исключены, поскольку восстановить точные времена их приёма нельзя. `track_commit_timestamp=on` задан в Compose. PostgreSQL удаляет старые commit timestamps при vacuum; outbox материализует их раз в цикл. Если не успел, растёт `messenger_slo_unknown`, срабатывает `MessengerReadyTimestampUnknown`: неизвестные события нельзя считать доказательством выполнения SLO. Источник: [PostgreSQL 17, commit timestamps](https://www.postgresql.org/docs/17/functions-info.html#FUNCTIONS-COMMIT-TIMESTAMP). Порог 30 секунд — половина 60-секундного бюджета smoke-теста для одного файла при свободном worker; это учебная цель, не измеренное требование пользователей. Цель 99% также выбрана для демонстрации, а не выведена из пользовательского исследования.
|
||||
|
||||
Error budget каждого SLO — `1 − 0,99 = 0,01`. Burn rate — доля плохих событий за окно / 0,01. Приближение расхода бюджета `burn × окно / 24 часа` предполагает стабильную интенсивность событий; при сильно меняющейся нагрузке бюджет, выраженный в доле событий за 24 часа, расходуется иначе. Значение 1 означает, что при сохранении текущей доли плохих событий все допустимые ошибки будут израсходованы за период SLO.
|
||||
|
||||
- Fast: одновременно 1 минута и 20 секунд выше `28,8 × 0,01 = 28,8%`; в коротком окне не менее 5 событий. При постоянной интенсивности это `28,8 × 1 / 1440 = 0,02`, то есть 2% суточного бюджета за минуту.
|
||||
- Slow: одновременно 5 минут и 1 минута выше `14,4 × 0,01 = 14,4%`; в коротком окне не менее 5 событий. При постоянной интенсивности это `14,4 × 5 / 1440 = 0,05`, то есть 5% бюджета за пять минут.
|
||||
|
||||
В окне недостаточно событий — alert молчит; отсутствие ряда не является доказательством здоровья. Короткие окна и пороги выбраны для воспроизводимого лабораторного опыта, не являются рекомендацией для production. Источник метода multiwindow/multi-burn-rate и ограничений: [Google SRE Workbook](https://sre.google/workbook/alerting-on-slos/). Гистограмма: [Prometheus histograms](https://prometheus.io/docs/practices/histograms/).
|
||||
|
||||
## API burn
|
||||
|
||||
1. Убедитесь в наличии запросов: `sum(rate(messenger_http_requests_total{route!~"/health/.*"}[1m]))`. Отсутствие запросов требует отдельной проверки LB/readiness, а не вывода об отсутствии ошибок.
|
||||
2. Сравните на dashboard 20s/1m/5m и долю 5xx по маршрутам: `sum by(route) (rate(messenger_http_requests_total{status_class="5xx"}[1m]))`. Если burn high, перейдите в Loki: `{service_name="messenger-api"} | status="503"`. Ограничьте диапазон временем alert.
|
||||
3. Откройте trace из metadata лога в Tempo. Если `postgres.user_for_token` или другая DB-операция занимает большую часть HTTP span, проверьте подключение к PostgreSQL и блокировки (`pg_locks`, `pg_stat_activity`); не печатайте параметры SQL или credentials. Если вместо этого длителен S3 span — проверьте S3 и сеть. Проверьте также pool used/waiting.
|
||||
4. Устраните причину в рамках полномочий: в учебном опыте дождитесь окончания контролируемой блокировки. Проверьте уменьшение error ratio, отсутствие активного burn alert и успешный `make test`. Сообщение об устранении возможно после короткого окна; долгая часть условия может ещё некоторое время оставаться выше порога.
|
||||
|
||||
## Ready burn / очередь
|
||||
|
||||
1. Сначала убедитесь, что `MessengerQueueTelemetryStale` и `MessengerReadyTimestampUnknown` не firing. Проверьте `sum(increase(messenger_slo_ready_eligible_total{service_name="messenger-outbox"}[1m]))`, p95 ready и исходы jobs. Счётчик `messenger_slo_ready_bad_total` включает задания, нарушившие срок. Отсутствие событий не делает SLI хорошим: проверьте `messenger_queue_depth{service_name="messenger-outbox"}` и `messenger_queue_age_seconds{service_name="messenger-outbox"}`.
|
||||
2. В Loki откройте `{service_name="messenger-worker"}`, найдите событие и trace ID. В Tempo проверьте цепочку upload → producer → consumer → S3/DB; посмотрите busy/capacity и состояние broker/worker через `docker compose ps`.
|
||||
3. В учебном опыте запустите остановленный worker, наблюдайте уменьшение глубины/возраста и новые ready. Проверьте resolved и метаданные вложений. Не удаляйте volumes и не запускайте replay вслепую.
|
||||
|
||||
## Повторение экспериментов
|
||||
|
||||
`python3 student-tests/slo_incidents.py` создаёт синтетические данные, ведёт три клиента и выполняет краткую и длительную блокировку таблицы `users`. Скрипт пишет временные отметки и наблюдения в [evidence/slo-incidents.json](../evidence/slo-incidents.json), не сохраняет tokens; опрашивает alert примерно каждые 5 секунд. `python3 student-tests/slo_analyze.py` строит сводку, включая срабатывания уже после завершения воздействия. Тест намеренно ухудшает локальный API и занимает несколько минут. Первая отметка воздействия — момент, когда скрипт увидел granted `AccessExclusiveLock`; окончание — возврат команды транзакции, поэтому обе оценки имеют задержку наблюдения. Анализатор сравнивает приращения UTC и монотонных часов и сохраняет максимальный фактический интервал опроса. Если `timing_quality.valid_for_elapsed_time_claims=false`, опыт повторяют; причину расхождения часов по этим данным установить нельзя. Аварийное прерывание клиентской команды может оставить server-side `pg_sleep` до окончания заданного ограниченного времени; проверьте состояние блокировки.
|
||||
|
||||
`python3 student-tests/slo_ready_incident.py` проверяет отсутствие незавершённых заданий, останавливает worker, принимает восемь синтетических файлов и восстанавливает worker в `finally`. До запуска убедитесь, что API и worker свободны. Результат — [evidence/slo-ready-incident.json](../evidence/slo-ready-incident.json). Снятие alerts при малом количестве новых событий может означать недостаток событий в коротком окне, а не доказательство выполнения 24-часового SLO.
|
||||
|
||||
Проверка правил без стенда и в ускоренном времени:
|
||||
|
||||
```sh
|
||||
docker run --rm -v "$PWD:/workspace:ro" --entrypoint promtool prom/prometheus:v3.2.1 test rules /workspace/student-tests/burn_rules.test.yaml
|
||||
```
|
||||
|
||||
В runbook зафиксируйте фазу, UTC начала/окончания, первый firing и первое наблюдение после исчезновения alert. Первый и последний интервалы ограничены частотой опроса, а отсутствие ложного firing в одном baseline не оценивает долгосрочный false-positive rate.
|
||||
|
||||
## Проверка другим студентом
|
||||
|
||||
Проверяющий не получает команду инъекции заранее. Автор запускает один из двух ограниченных сценариев; проверяющий получает время и имя alert, затем проходит шаги выше. В отдельный протокол записывают: имя проверяющего, UTC, запрос PromQL/LogQL, trace ID, медленный span или отсутствие consumer, диагноз, действие восстановления и свидетельство resolved. Совпадение диагноза с инъекцией проверяют после записи. Пока такого заполненного протокола нет, независимое прохождение runbook не подтверждено.
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"date": "2026-11-07",
|
||||
"environment": "Docker Desktop on local machine; separate temporary Compose project",
|
||||
"procedure": "Generated new local secrets and CA, initialized and unsealed a new OpenBao, created fresh PostgreSQL, RabbitMQ and S3 volumes, and started the Compose stack.",
|
||||
"checks": {
|
||||
"public_https_smoke": "PASS",
|
||||
"external_tls_untrusted_ca": "PASS",
|
||||
"internal_mtls_both_api_replicas": "PASS",
|
||||
"api_and_worker_s3_prefix_acl": "PASS"
|
||||
},
|
||||
"note": "Two initial RabbitMQ bootstrap races were corrected before the final successful clean run. The final run included S3 prefix ACL. Temporary test data were isolated from the main project and removed."
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"results": [
|
||||
{
|
||||
"stopped": [
|
||||
"api-a"
|
||||
],
|
||||
"status": "PASS",
|
||||
"output": "python3 tests/resilience.py --mode failover --action-script \"scripts/stop-one.sh\" --base-url \"https://localhost:18443\" --ca-file \"/Users/garfieldmk/Desktop/study/highLoad/mtusi2026lab7/secrets/ca.crt\"\nExecuting explicit failover hook; hook output suppressed to avoid leaking secrets.\n{\"observed_instances_before\": 2, \"successful_writes\": 90, \"failed_attempts\": 2, \"first_recovery_seconds\": 2.58}\nPASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.\n"
|
||||
},
|
||||
{
|
||||
"stopped": [
|
||||
"api-b"
|
||||
],
|
||||
"status": "PASS",
|
||||
"output": "python3 tests/resilience.py --mode failover --action-script \"scripts/stop-one.sh\" --base-url \"https://localhost:18443\" --ca-file \"/Users/garfieldmk/Desktop/study/highLoad/mtusi2026lab7/secrets/ca.crt\"\nExecuting explicit failover hook; hook output suppressed to avoid leaking secrets.\n{\"observed_instances_before\": 2, \"successful_writes\": 108, \"failed_attempts\": 1, \"first_recovery_seconds\": 2.573}\nPASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.\n"
|
||||
}
|
||||
],
|
||||
"both_replicas_tested": true
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"date": "2026-11-07",
|
||||
"scenario": "tests/resilience.py failover; separate runs stopping each API replica",
|
||||
"transport": "HTTPS with the local CA",
|
||||
"runs": [
|
||||
{"stopped_service": "api-a", "observed_instances_before": 2, "successful_writes": 92, "failed_attempts": 2, "first_recovery_seconds": 5.91, "status": "PASS"},
|
||||
{"stopped_service": "api-b", "observed_instances_before": 2, "successful_writes": 111, "failed_attempts": 1, "first_recovery_seconds": 2.887, "status": "PASS"},
|
||||
{"stopped_service": "api-a", "observed_instances_before": 2, "successful_writes": 91, "failed_attempts": 2, "first_recovery_seconds": 4.784, "status": "PASS", "configuration": "after S3 prefix ACL"}
|
||||
],
|
||||
"note": "Closed-loop public test; first two runs preceded the final S3 prefix ACL. Results are not a throughput benchmark."
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
{
|
||||
"status": "PASS",
|
||||
"command": "make test-persistence ACTION_SCRIPT=scripts/restart.sh",
|
||||
"services": {
|
||||
"postgres": {
|
||||
"before": "2026-11-07T18:37:40.342662055Z",
|
||||
"after": "2026-11-07T18:40:29.165485675Z"
|
||||
},
|
||||
"s3": {
|
||||
"before": "2026-11-07T18:37:40.258400055Z",
|
||||
"after": "2026-11-07T18:40:32.078899093Z"
|
||||
},
|
||||
"broker": {
|
||||
"before": "2026-11-07T18:37:40.181643097Z",
|
||||
"after": "2026-11-07T18:40:30.133283175Z"
|
||||
},
|
||||
"openbao": {
|
||||
"before": "2026-11-07T18:37:25.793975132Z",
|
||||
"after": "2026-11-07T18:40:29.375343008Z"
|
||||
},
|
||||
"prometheus": {
|
||||
"before": "2026-11-07T18:37:40.556532722Z",
|
||||
"after": "2026-11-07T18:40:29.121133508Z"
|
||||
},
|
||||
"loki": {
|
||||
"before": "2026-11-07T18:37:40.63945868Z",
|
||||
"after": "2026-11-07T18:40:30.996157426Z"
|
||||
},
|
||||
"tempo": {
|
||||
"before": "2026-11-07T18:37:40.724841472Z",
|
||||
"after": "2026-11-07T18:40:30.060878259Z"
|
||||
},
|
||||
"api-a": {
|
||||
"before": "2026-11-07T18:39:11.623110833Z",
|
||||
"after": "2026-11-07T18:40:53.924133089Z"
|
||||
},
|
||||
"api-b": {
|
||||
"before": "2026-11-07T18:39:11.708902667Z",
|
||||
"after": "2026-11-07T18:40:53.958697422Z"
|
||||
}
|
||||
},
|
||||
"test_output": "python3 tests/resilience.py --mode persistence --action-script \"scripts/restart.sh\" --base-url \"https://localhost:18443\" --ca-file \"/Users/garfieldmk/Desktop/study/highLoad/mtusi2026lab7/secrets/ca.crt\"\nExecuting explicit persistence hook; hook output suppressed to avoid leaking secrets.\nPASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence."
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
{
|
||||
"time": "2026-11-07T18:39:57.470382+00:00",
|
||||
"results": [
|
||||
{
|
||||
"test": "structure",
|
||||
"command": [
|
||||
"make",
|
||||
"check"
|
||||
],
|
||||
"status": "PASS",
|
||||
"output": "python3 scripts/check_contract.py\nPASS: offline skeleton structure, local refs and Python syntax; application NOT tested.\n"
|
||||
},
|
||||
{
|
||||
"test": "smoke",
|
||||
"command": [
|
||||
"make",
|
||||
"test"
|
||||
],
|
||||
"status": "PASS",
|
||||
"output": "python3 tests/smoke.py --base-url \"https://localhost:18443\" --ca-file \"/Users/garfieldmk/Desktop/study/highLoad/mtusi2026lab7/secrets/ca.crt\"\nPASS: lab7 public API scenario; infrastructure and grading evidence remain separate.\n"
|
||||
},
|
||||
{
|
||||
"test": "external TLS",
|
||||
"command": [
|
||||
"make",
|
||||
"test-security"
|
||||
],
|
||||
"status": "PASS",
|
||||
"output": "python3 tests/security.py --base-url \"https://localhost:18443\" --ca-file \"/Users/garfieldmk/Desktop/study/highLoad/mtusi2026lab7/secrets/ca.crt\"\nPASS: trusted HTTPS works; untrusted CA rejected. This does NOT verify internal mTLS, OpenBao or hardening.\n"
|
||||
},
|
||||
{
|
||||
"test": "mTLS",
|
||||
"command": [
|
||||
"sh",
|
||||
"scripts/test-internal-mtls.sh"
|
||||
],
|
||||
"status": "PASS",
|
||||
"output": "PASS api-a: valid identity accepted; no cert, foreign CA and wrong role rejected; direct API closed\nPASS api-b: valid identity accepted; no cert, foreign CA and wrong role rejected; direct API closed\n"
|
||||
},
|
||||
{
|
||||
"test": "access log redaction",
|
||||
"command": [
|
||||
"python3",
|
||||
"student-tests/ingress_redaction.py"
|
||||
],
|
||||
"status": "PASS",
|
||||
"output": "PASS: ingress/API access records present; query, path and header markers absent\n"
|
||||
},
|
||||
{
|
||||
"test": "ACL expiry hostname",
|
||||
"command": [
|
||||
"python3",
|
||||
"student-tests/lab7_security.py",
|
||||
"--base-url",
|
||||
"https://localhost:18443",
|
||||
"--ca-file",
|
||||
"/Users/garfieldmk/Desktop/study/highLoad/mtusi2026lab7/secrets/ca.crt"
|
||||
],
|
||||
"status": "PASS",
|
||||
"output": "PASS: wrong hostname rejected; cross-chat attachment denied; expired session rejected\n"
|
||||
},
|
||||
{
|
||||
"test": "api-a openbao_policy",
|
||||
"command": [
|
||||
"docker",
|
||||
"compose",
|
||||
"exec",
|
||||
"-T",
|
||||
"api-a",
|
||||
"/app/.venv/bin/python",
|
||||
"-"
|
||||
],
|
||||
"status": "PASS",
|
||||
"output": "PASS api: own path allowed; other path and policy write denied\n"
|
||||
},
|
||||
{
|
||||
"test": "api-a service_permissions",
|
||||
"command": [
|
||||
"docker",
|
||||
"compose",
|
||||
"exec",
|
||||
"-T",
|
||||
"api-a",
|
||||
"/app/.venv/bin/python",
|
||||
"-"
|
||||
],
|
||||
"status": "PASS",
|
||||
"output": "PASS api: DB identity and denied privilege; broker denied unauthorized operation\n"
|
||||
},
|
||||
{
|
||||
"test": "api-a s3_prefix_permissions",
|
||||
"command": [
|
||||
"docker",
|
||||
"compose",
|
||||
"exec",
|
||||
"-T",
|
||||
"api-a",
|
||||
"/app/.venv/bin/python",
|
||||
"-"
|
||||
],
|
||||
"status": "PASS",
|
||||
"output": "PASS api: allowed staging write; forbidden prefix denied\nPASS api: duplicate Authorization denied\n"
|
||||
},
|
||||
{
|
||||
"test": "worker openbao_policy",
|
||||
"command": [
|
||||
"docker",
|
||||
"compose",
|
||||
"exec",
|
||||
"-T",
|
||||
"worker",
|
||||
"/app/.venv/bin/python",
|
||||
"-"
|
||||
],
|
||||
"status": "PASS",
|
||||
"output": "PASS worker: own path allowed; other path and policy write denied\n"
|
||||
},
|
||||
{
|
||||
"test": "worker service_permissions",
|
||||
"command": [
|
||||
"docker",
|
||||
"compose",
|
||||
"exec",
|
||||
"-T",
|
||||
"worker",
|
||||
"/app/.venv/bin/python",
|
||||
"-"
|
||||
],
|
||||
"status": "PASS",
|
||||
"output": "PASS worker: DB identity and denied privilege; broker denied unauthorized operation\n"
|
||||
},
|
||||
{
|
||||
"test": "worker s3_prefix_permissions",
|
||||
"command": [
|
||||
"docker",
|
||||
"compose",
|
||||
"exec",
|
||||
"-T",
|
||||
"worker",
|
||||
"/app/.venv/bin/python",
|
||||
"-"
|
||||
],
|
||||
"status": "PASS",
|
||||
"output": "PASS worker: allowed staging write; forbidden prefix denied\nPASS worker: duplicate Authorization denied\n"
|
||||
},
|
||||
{
|
||||
"test": "postgres_tls",
|
||||
"command": [
|
||||
"docker",
|
||||
"compose",
|
||||
"exec",
|
||||
"-T",
|
||||
"api-a",
|
||||
"/app/.venv/bin/python",
|
||||
"-"
|
||||
],
|
||||
"status": "PASS",
|
||||
"output": "PASS: PostgreSQL TLS verified, plaintext and untrusted CA rejected\n"
|
||||
},
|
||||
{
|
||||
"test": "dependency_tls",
|
||||
"command": [
|
||||
"docker",
|
||||
"compose",
|
||||
"exec",
|
||||
"-T",
|
||||
"api-a",
|
||||
"/app/.venv/bin/python",
|
||||
"-"
|
||||
],
|
||||
"status": "PASS",
|
||||
"output": "PASS s3: verified TLS; untrusted CA rejected\nPASS broker: verified TLS; untrusted CA rejected\nPASS openbao: verified TLS; untrusted CA rejected\nPASS: S3 internal and broker plaintext ports are closed\nPASS: S3 proxy blocks POST\n"
|
||||
},
|
||||
{
|
||||
"test": "telemetry_tls",
|
||||
"command": [
|
||||
"docker",
|
||||
"compose",
|
||||
"exec",
|
||||
"-T",
|
||||
"api-a",
|
||||
"/app/.venv/bin/python",
|
||||
"-"
|
||||
],
|
||||
"status": "PASS",
|
||||
"output": "PASS: Collector publisher accepted; no cert and wrong role rejected; local listener closed\n"
|
||||
},
|
||||
{
|
||||
"test": "lab7_limits",
|
||||
"command": [
|
||||
"docker",
|
||||
"compose",
|
||||
"exec",
|
||||
"-T",
|
||||
"api-a",
|
||||
"/app/.venv/bin/python",
|
||||
"-"
|
||||
],
|
||||
"status": "PASS",
|
||||
"output": "{\"timestamp\": \"2026-11-07T18:39:56.443007+00:00\", \"severity\": \"INFO\", \"service.name\": \"messenger-api\", \"event\": \"http.request\", \"trace_id\": \"ed16f2869c1055cfa8eba8a2c8ddcc26\", \"span_id\": \"3322ff50bd52d312\", \"request_id\": \"791140e4-e019-4902-8943-715409df0a3a\", \"method\": \"POST\", \"route\": \"unmatched\", \"status\": 413}\n.{\"timestamp\": \"2026-11-07T18:39:56.447785+00:00\", \"severity\": \"INFO\", \"service.name\": \"messenger-api\", \"event\": \"http.request\", \"trace_id\": \"8ee51e4ac84311da20f7e9bf76cd8dbc\", \"span_id\": \"5d24a10e81cf49e1\", \"request_id\": \"b009f765-9103-4510-b4a8-452388d746c1\", \"method\": \"POST\", \"route\": \"/api/v1/auth/sessions\", \"status\": 401}\n{\"timestamp\": \"2026-11-07T18:39:56.448485+00:00\", \"severity\": \"INFO\", \"service.name\": \"messenger-api\", \"event\": \"http.request\", \"trace_id\": \"7cf78e312d771b81e3296f8d0f396c72\", \"span_id\": \"76966e6c01b4dedf\", \"request_id\": \"1f2dc31e-17be-433b-b6eb-12a3d548b7cf\", \"method\": \"POST\", \"route\": \"/api/v1/auth/sessions\", \"status\": 429}\n.{\"timestamp\": \"2026-11-07T18:39:56.449173+00:00\", \"severity\": \"INFO\", \"service.name\": \"messenger-api\", \"event\": \"http.request\", \"trace_id\": \"efbb722e22211c38bd5772aab61a12a4\", \"span_id\": \"4d9aa2c1437a6693\", \"request_id\": \"c4a1c350-7dc3-456e-8415-5d0df3644b33\", \"method\": \"POST\", \"route\": \"/api/v1/auth/sessions\", \"status\": 401}\n..\n----------------------------------------------------------------------\nRan 4 tests in 0.026s\n\nOK\n"
|
||||
},
|
||||
{
|
||||
"test": "telemetry_unit",
|
||||
"command": [
|
||||
"docker",
|
||||
"compose",
|
||||
"exec",
|
||||
"-T",
|
||||
"api-a",
|
||||
"/app/.venv/bin/python",
|
||||
"-"
|
||||
],
|
||||
"status": "PASS",
|
||||
"output": "......\n----------------------------------------------------------------------\nRan 6 tests in 0.091s\n\nOK\n"
|
||||
},
|
||||
{
|
||||
"test": "observability",
|
||||
"command": [
|
||||
"python3",
|
||||
"student-tests/observability_tls.py"
|
||||
],
|
||||
"status": "PASS",
|
||||
"output": "PASS: Grafana connected to prometheus; data present\nPASS: Grafana connected to loki; data present\nPASS: Grafana connected to tempo; data present\n"
|
||||
}
|
||||
],
|
||||
"additional_checks": {
|
||||
"linux_synthetic_DAC": "PASS: student-tests/secret_file_permissions.py, disposable Linux container; not a full native Linux deployment",
|
||||
"runtime_hardening": "PASS: student-tests/runtime_hardening.py",
|
||||
"validate": "PASS: make validate",
|
||||
"credential_scan": "PASS: current tracked files compared to local generated credentials and private-key markers; Git history and image layers not scanned"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
global
|
||||
log stdout format raw local0
|
||||
|
||||
defaults
|
||||
mode http
|
||||
log global
|
||||
timeout connect 2s
|
||||
timeout client 30s
|
||||
timeout server 30s
|
||||
|
||||
frontend internal_mtls
|
||||
bind :8444 ssl crt /run/secrets/api.pem ca-file /run/secrets/ca.crt verify required ssl-min-ver TLSv1.2
|
||||
http-request deny unless { ssl_c_s_dn(OU) -m str load-balancer } { ssl_c_s_dn(CN) -m str lb }
|
||||
default_backend local_api
|
||||
|
||||
backend local_api
|
||||
server app 127.0.0.1:8080
|
||||
@@ -0,0 +1,10 @@
|
||||
defaults
|
||||
mode tcp
|
||||
timeout connect 2s
|
||||
timeout client 60s
|
||||
timeout server 60s
|
||||
frontend broker_tls
|
||||
bind :5671
|
||||
default_backend broker_local
|
||||
backend broker_local
|
||||
server broker 127.0.0.1:15671 check
|
||||
@@ -0,0 +1,3 @@
|
||||
[leveldb2]
|
||||
enabled = true
|
||||
dir = "/data/filer"
|
||||
@@ -0,0 +1,7 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
LAB_CA="$(cat /run/secrets/ca_cert)"
|
||||
export LAB_CA
|
||||
LAB_CLIENT_PEM="$(cat /run/secrets/telemetry_grafana_cert)"
|
||||
export LAB_CLIENT_PEM
|
||||
exec /run.sh
|
||||
@@ -0,0 +1,543 @@
|
||||
{
|
||||
"uid": "messenger-lab6",
|
||||
"title": "Messenger — observability",
|
||||
"schemaVersion": 39,
|
||||
"version": 1,
|
||||
"refresh": "10s",
|
||||
"time": {
|
||||
"from": "now-30m",
|
||||
"to": "now"
|
||||
},
|
||||
"panels": [
|
||||
{
|
||||
"id": 1,
|
||||
"title": "API RPS",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 0,
|
||||
"y": 0
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "reqps"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "sum(rate(messenger_http_requests_total{route!~\"/health/.*\"}[1m]))",
|
||||
"legendFormat": "{{service_name}} {{outcome}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"title": "API error ratio",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 12,
|
||||
"y": 0
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "percentunit"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "(sum(rate(messenger_http_requests_total{status_class=\"5xx\",route!~\"/health/.*\"}[1m])) or vector(0)) / clamp_min(sum(rate(messenger_http_requests_total{route!~\"/health/.*\"}[1m])),0.001) and sum(increase(messenger_http_requests_total{route!~\"/health/.*\"}[1m])) > 0",
|
||||
"legendFormat": "{{service_name}} {{outcome}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"title": "API latency p50 / p95 / p99",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 0,
|
||||
"y": 8
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "s"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "histogram_quantile(0.5, sum by (le) (rate(messenger_http_duration_seconds_bucket{route!~\"/health/.*\"}[5m])))",
|
||||
"legendFormat": "p50"
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_http_duration_seconds_bucket{route!~\"/health/.*\"}[5m])))",
|
||||
"legendFormat": "p95"
|
||||
},
|
||||
{
|
||||
"refId": "C",
|
||||
"expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_http_duration_seconds_bucket{route!~\"/health/.*\"}[5m])))",
|
||||
"legendFormat": "p99"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"title": "Jobs by outcome",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 12,
|
||||
"y": 8
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "ops"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "sum by (outcome) (rate(messenger_jobs_total[1m]))",
|
||||
"legendFormat": "{{service_name}} {{outcome}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"title": "Job duration p95",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 0,
|
||||
"y": 16
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "s"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_job_duration_seconds_bucket[5m])))",
|
||||
"legendFormat": "{{service_name}} {{outcome}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 6,
|
||||
"title": "Acceptance to ready p95",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 12,
|
||||
"y": 16
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "s"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_job_ready_duration_seconds_bucket[5m])))",
|
||||
"legendFormat": "{{service_name}} {{outcome}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 7,
|
||||
"title": "Queued jobs",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 0,
|
||||
"y": 24
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "max(messenger_queue_depth{service_name=\"messenger-outbox\"})",
|
||||
"legendFormat": "{{service_name}} {{outcome}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 8,
|
||||
"title": "Oldest queued age",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 12,
|
||||
"y": 24
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "s"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "max(messenger_queue_age_seconds{service_name=\"messenger-outbox\"})",
|
||||
"legendFormat": "{{service_name}} {{outcome}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 9,
|
||||
"title": "DB pool used / capacity / waiting",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 0,
|
||||
"y": 32
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "messenger_pool_used{service_name=\"messenger-api\"}",
|
||||
"legendFormat": "used"
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"expr": "messenger_pool_capacity{service_name=\"messenger-api\"}",
|
||||
"legendFormat": "capacity"
|
||||
},
|
||||
{
|
||||
"refId": "C",
|
||||
"expr": "messenger_pool_waiting{service_name=\"messenger-api\"}",
|
||||
"legendFormat": "waiting"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 10,
|
||||
"title": "Worker busy / capacity",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 12,
|
||||
"y": 32
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "messenger_worker_busy{service_name=\"messenger-worker\"}",
|
||||
"legendFormat": "busy"
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"expr": "messenger_worker_capacity{service_name=\"messenger-worker\"}",
|
||||
"legendFormat": "capacity"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 11,
|
||||
"title": "Process CPU",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 0,
|
||||
"y": 40
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "percentunit"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "sum by (service_name, service_instance_id) (rate(messenger_process_cpu_seconds_total[1m]))",
|
||||
"legendFormat": "{{service_name}} {{outcome}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 12,
|
||||
"title": "Process resident memory",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 12,
|
||||
"y": 40
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "bytes"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "messenger_process_memory_bytes",
|
||||
"legendFormat": "{{service_name}} {{outcome}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 13,
|
||||
"title": "Collector failed / dropped spans per second",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 0,
|
||||
"y": 48
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "ops"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "sum by (exporter) (rate(otelcol_exporter_send_failed_spans_total[1m]))",
|
||||
"legendFormat": "send failed {{exporter}}"
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"expr": "sum by (exporter) (rate(otelcol_exporter_enqueue_failed_spans_total[1m]))",
|
||||
"legendFormat": "queue full {{exporter}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 14,
|
||||
"title": "API SLI: successful ratio over 24h",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 12,
|
||||
"y": 48
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "percentunit",
|
||||
"min": 0,
|
||||
"max": 1
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "1 - (sum(increase(messenger_http_requests_total{status_class=\"5xx\",route!~\"/health/.*\"}[24h])) or vector(0)) / clamp_min(sum(increase(messenger_http_requests_total{route!~\"/health/.*\"}[24h])),1) and sum(increase(messenger_http_requests_total{route!~\"/health/.*\"}[24h])) > 0",
|
||||
"legendFormat": "SLI"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 15,
|
||||
"title": "API SLO burn rate (budget 1%)",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 0,
|
||||
"y": 56
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "(((sum(increase(messenger_http_requests_total{status_class=\"5xx\",route!~\"/health/.*\"}[20s])) or vector(0)) / clamp_min(sum(increase(messenger_http_requests_total{route!~\"/health/.*\"}[20s])), 1)) / 0.01) and sum(increase(messenger_http_requests_total{route!~\"/health/.*\"}[20s])) > 0",
|
||||
"legendFormat": "burn 20s"
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"expr": "(((sum(increase(messenger_http_requests_total{status_class=\"5xx\",route!~\"/health/.*\"}[1m])) or vector(0)) / clamp_min(sum(increase(messenger_http_requests_total{route!~\"/health/.*\"}[1m])), 1)) / 0.01) and sum(increase(messenger_http_requests_total{route!~\"/health/.*\"}[1m])) > 0",
|
||||
"legendFormat": "burn 1m"
|
||||
},
|
||||
{
|
||||
"refId": "C",
|
||||
"expr": "(((sum(increase(messenger_http_requests_total{status_class=\"5xx\",route!~\"/health/.*\"}[5m])) or vector(0)) / clamp_min(sum(increase(messenger_http_requests_total{route!~\"/health/.*\"}[5m])), 1)) / 0.01) and sum(increase(messenger_http_requests_total{route!~\"/health/.*\"}[5m])) > 0",
|
||||
"legendFormat": "burn 5m"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 16,
|
||||
"title": "READY SLO burn rate (budget 1%)",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 12,
|
||||
"y": 56
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "(((sum(increase(messenger_slo_ready_bad_total{service_name=\"messenger-outbox\"}[20s])) or vector(0)) / clamp_min(sum(increase(messenger_slo_ready_eligible_total{service_name=\"messenger-outbox\"}[20s])), 1)) / 0.01) and sum(increase(messenger_slo_ready_eligible_total{service_name=\"messenger-outbox\"}[20s])) > 0",
|
||||
"legendFormat": "burn 20s"
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"expr": "(((sum(increase(messenger_slo_ready_bad_total{service_name=\"messenger-outbox\"}[1m])) or vector(0)) / clamp_min(sum(increase(messenger_slo_ready_eligible_total{service_name=\"messenger-outbox\"}[1m])), 1)) / 0.01) and sum(increase(messenger_slo_ready_eligible_total{service_name=\"messenger-outbox\"}[1m])) > 0",
|
||||
"legendFormat": "burn 1m"
|
||||
},
|
||||
{
|
||||
"refId": "C",
|
||||
"expr": "(((sum(increase(messenger_slo_ready_bad_total{service_name=\"messenger-outbox\"}[5m])) or vector(0)) / clamp_min(sum(increase(messenger_slo_ready_eligible_total{service_name=\"messenger-outbox\"}[5m])), 1)) / 0.01) and sum(increase(messenger_slo_ready_eligible_total{service_name=\"messenger-outbox\"}[5m])) > 0",
|
||||
"legendFormat": "burn 5m"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 17,
|
||||
"title": "Accepted jobs ready within 30 s — 24h (matured cohort)",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 0,
|
||||
"y": 64
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "percentunit",
|
||||
"min": 0,
|
||||
"max": 1
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "1 - ((sum(increase(messenger_slo_ready_bad_total{service_name=\"messenger-outbox\"}[24h])) or vector(0)) / clamp_min(sum(increase(messenger_slo_ready_eligible_total{service_name=\"messenger-outbox\"}[24h])), 1)) and sum(increase(messenger_slo_ready_eligible_total{service_name=\"messenger-outbox\"}[24h])) > 0",
|
||||
"legendFormat": "ready SLI"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
apiVersion: 1
|
||||
providers:
|
||||
- name: messenger
|
||||
orgId: 1
|
||||
folder: Messenger
|
||||
type: file
|
||||
disableDeletion: false
|
||||
options: {path: /var/lib/grafana/dashboards}
|
||||
@@ -0,0 +1,32 @@
|
||||
apiVersion: 1
|
||||
datasources:
|
||||
- name: Prometheus
|
||||
uid: prometheus
|
||||
type: prometheus
|
||||
access: proxy
|
||||
url: https://prometheus:9090
|
||||
jsonData: {tlsAuthWithCACert: true, tlsAuth: true}
|
||||
secureJsonData: {tlsCACert: '$LAB_CA', tlsClientCert: '$LAB_CLIENT_PEM', tlsClientKey: '$LAB_CLIENT_PEM'}
|
||||
isDefault: true
|
||||
- name: Loki
|
||||
uid: loki
|
||||
type: loki
|
||||
access: proxy
|
||||
url: https://loki:3100
|
||||
jsonData:
|
||||
tlsAuthWithCACert: true
|
||||
tlsAuth: true
|
||||
derivedFields:
|
||||
- name: TraceID
|
||||
matcherType: label
|
||||
matcherRegex: '^trace_?id$'
|
||||
url: '$${__value.raw}'
|
||||
datasourceUid: tempo
|
||||
secureJsonData: {tlsCACert: '$LAB_CA', tlsClientCert: '$LAB_CLIENT_PEM', tlsClientKey: '$LAB_CLIENT_PEM'}
|
||||
- name: Tempo
|
||||
uid: tempo
|
||||
type: tempo
|
||||
access: proxy
|
||||
url: https://tempo:3200
|
||||
jsonData: {tlsAuthWithCACert: true, tlsAuth: true}
|
||||
secureJsonData: {tlsCACert: '$LAB_CA', tlsClientCert: '$LAB_CLIENT_PEM', tlsClientKey: '$LAB_CLIENT_PEM'}
|
||||
@@ -0,0 +1,41 @@
|
||||
global
|
||||
log stdout format raw local0
|
||||
|
||||
defaults
|
||||
mode http
|
||||
log global
|
||||
# Never log raw URLs, query strings, headers or request bodies.
|
||||
log-format "ingress status=%ST bytes=%B backend=%b server=%s termination=%tsc"
|
||||
option forwardfor
|
||||
timeout connect 1s
|
||||
timeout client 30s
|
||||
timeout server 10s
|
||||
timeout check 2s
|
||||
retries 2
|
||||
|
||||
resolvers docker
|
||||
nameserver dns 127.0.0.11:53
|
||||
resolve_retries 3
|
||||
timeout resolve 1s
|
||||
timeout retry 1s
|
||||
hold valid 2s
|
||||
hold obsolete 2s
|
||||
|
||||
frontend https
|
||||
bind :8443 ssl crt /run/secrets/ingress.pem ssl-min-ver TLSv1.2
|
||||
default_backend api
|
||||
|
||||
frontend container_health
|
||||
bind 127.0.0.1:8404
|
||||
http-request deny unless { path -i /health/ready } { method GET }
|
||||
default_backend api
|
||||
|
||||
backend api
|
||||
balance roundrobin
|
||||
option httpchk
|
||||
http-check send meth GET uri /health/ready ver HTTP/1.1 hdr Host localhost
|
||||
http-check expect status 200
|
||||
default-server check inter 2s fall 1 rise 2 resolvers docker resolve-prefer ipv4 init-addr libc,none
|
||||
server api-a api-a:8444 ssl verify required ca-file /run/secrets/ca.crt crt /run/secrets/lb.pem verifyhost api-a
|
||||
server api-b api-b:8444 ssl verify required ca-file /run/secrets/ca.crt crt /run/secrets/lb.pem verifyhost api-b
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
defaults
|
||||
mode tcp
|
||||
timeout connect 2s
|
||||
timeout client 30s
|
||||
timeout server 30s
|
||||
frontend https
|
||||
bind :3100 ssl crt /run/secrets/server.pem ca-file /run/secrets/ca.crt verify required ssl-min-ver TLSv1.2
|
||||
tcp-request content reject unless { ssl_c_s_dn(OU) -m str telemetry-reader telemetry-writer }
|
||||
default_backend local
|
||||
backend local
|
||||
server loki 127.0.0.1:13100
|
||||
@@ -0,0 +1,18 @@
|
||||
auth_enabled: false
|
||||
server: {http_listen_address: "127.0.0.1", http_listen_port: 13100, grpc_listen_address: "127.0.0.1"}
|
||||
common:
|
||||
instance_addr: 127.0.0.1
|
||||
path_prefix: /loki
|
||||
replication_factor: 1
|
||||
ring: {kvstore: {store: inmemory}}
|
||||
schema_config:
|
||||
configs:
|
||||
- from: '2024-01-01'
|
||||
store: tsdb
|
||||
object_store: filesystem
|
||||
schema: v13
|
||||
index: {prefix: index_, period: 24h}
|
||||
storage_config:
|
||||
filesystem: {directory: /loki/chunks}
|
||||
limits_config: {allow_structured_metadata: true, retention_period: 168h}
|
||||
compactor: {working_directory: /loki/compactor, retention_enabled: true, delete_request_store: filesystem}
|
||||
@@ -0,0 +1,15 @@
|
||||
ui = false
|
||||
disable_mlock = true
|
||||
api_addr = "https://openbao:8200"
|
||||
|
||||
storage "file" {
|
||||
path = "/bao/file"
|
||||
}
|
||||
|
||||
listener "tcp" {
|
||||
address = "0.0.0.0:8200"
|
||||
tls_cert_file = "/run/secrets/openbao.pem"
|
||||
tls_key_file = "/run/secrets/openbao.pem"
|
||||
tls_client_ca_file = "/run/secrets/ca.crt"
|
||||
tls_min_version = "tls12"
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
defaults
|
||||
mode tcp
|
||||
timeout connect 2s
|
||||
timeout client 30s
|
||||
timeout server 30s
|
||||
|
||||
frontend ingest
|
||||
bind :4318 ssl crt /run/secrets/server.pem ca-file /run/secrets/ca.crt verify required ssl-min-ver TLSv1.2
|
||||
tcp-request content reject unless { ssl_c_s_dn(OU) -m str telemetry-publisher }
|
||||
default_backend ingest_local
|
||||
backend ingest_local
|
||||
server collector 127.0.0.1:14318
|
||||
|
||||
frontend metrics
|
||||
bind :8889 ssl crt /run/secrets/server.pem ca-file /run/secrets/ca.crt verify required ssl-min-ver TLSv1.2
|
||||
tcp-request content reject unless { ssl_c_s_dn(OU) -m str telemetry-scraper }
|
||||
default_backend metrics_local
|
||||
backend metrics_local
|
||||
server collector 127.0.0.1:18889
|
||||
|
||||
frontend internal_metrics
|
||||
bind :8888 ssl crt /run/secrets/server.pem ca-file /run/secrets/ca.crt verify required ssl-min-ver TLSv1.2
|
||||
tcp-request content reject unless { ssl_c_s_dn(OU) -m str telemetry-scraper }
|
||||
default_backend internal_metrics_local
|
||||
backend internal_metrics_local
|
||||
server collector 127.0.0.1:18888
|
||||
@@ -0,0 +1,32 @@
|
||||
receivers:
|
||||
otlp:
|
||||
protocols:
|
||||
http: {endpoint: "127.0.0.1:14318"}
|
||||
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}
|
||||
exporters:
|
||||
prometheus:
|
||||
endpoint: "127.0.0.1:18889"
|
||||
resource_to_telemetry_conversion: {enabled: true}
|
||||
otlp/tempo:
|
||||
endpoint: tempo:4317
|
||||
tls: {ca_file: /run/secrets/ca_cert, cert_file: /run/secrets/telemetry_collector_cert, key_file: /run/secrets/telemetry_collector_cert, server_name_override: tempo}
|
||||
sending_queue: {enabled: true, queue_size: 128, num_consumers: 2}
|
||||
retry_on_failure: {enabled: true, initial_interval: 1s, max_interval: 10s, max_elapsed_time: 60s}
|
||||
otlphttp/loki:
|
||||
endpoint: https://loki:3100/otlp
|
||||
tls: {ca_file: /run/secrets/ca_cert, cert_file: /run/secrets/telemetry_collector_cert, key_file: /run/secrets/telemetry_collector_cert}
|
||||
sending_queue: {enabled: true, queue_size: 128, num_consumers: 2}
|
||||
retry_on_failure: {enabled: true, initial_interval: 1s, max_interval: 10s, max_elapsed_time: 60s}
|
||||
service:
|
||||
telemetry:
|
||||
metrics:
|
||||
readers:
|
||||
- pull:
|
||||
exporter:
|
||||
prometheus: {host: 127.0.0.1, port: 18888}
|
||||
pipelines:
|
||||
metrics: {receivers: [otlp], processors: [memory_limiter, batch], exporters: [prometheus]}
|
||||
traces: {receivers: [otlp], processors: [memory_limiter, batch], exporters: [otlp/tempo]}
|
||||
logs: {receivers: [otlp], processors: [memory_limiter, batch], exporters: [otlphttp/loki]}
|
||||
@@ -0,0 +1,4 @@
|
||||
# Local maintenance stays inside the database container. Network clients must use TLS.
|
||||
local all all trust
|
||||
hostssl all all all scram-sha-256
|
||||
hostnossl all all all reject
|
||||
@@ -0,0 +1,6 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
# PostgreSQL requires its key to be owned by the postgres user and mode 0600.
|
||||
install -d -o postgres -g postgres -m 0700 /tmp/postgres-tls
|
||||
install -o postgres -g postgres -m 0600 /run/secrets/postgres_tls /tmp/postgres-tls/server.pem
|
||||
exec /usr/local/bin/docker-entrypoint.sh "$@"
|
||||
@@ -0,0 +1,11 @@
|
||||
defaults
|
||||
mode tcp
|
||||
timeout connect 2s
|
||||
timeout client 30s
|
||||
timeout server 30s
|
||||
frontend https
|
||||
bind :9090 ssl crt /run/secrets/server.pem ca-file /run/secrets/ca.crt verify required ssl-min-ver TLSv1.2
|
||||
tcp-request content reject unless { ssl_c_s_dn(OU) -m str telemetry-reader }
|
||||
default_backend local
|
||||
backend local
|
||||
server prometheus 127.0.0.1:19090
|
||||
@@ -0,0 +1,39 @@
|
||||
groups:
|
||||
- name: messenger
|
||||
rules:
|
||||
- alert: MessengerQueueTelemetryStale
|
||||
expr: time() - max(messenger_queue_sample_time_seconds{service_name="messenger-outbox"}) > 20 or sum(absent(messenger_queue_sample_time_seconds{service_name="messenger-outbox"}))
|
||||
for: 15s
|
||||
labels: {severity: warning}
|
||||
annotations: {summary: 'Queue and ready SLO telemetry is stale', runbook: 'See docs/slo-runbook.md; check outbox and DB before interpreting ready SLO.'}
|
||||
- alert: MessengerReadyTimestampUnknown
|
||||
expr: max(messenger_slo_unknown{service_name="messenger-outbox"}) > 0
|
||||
for: 15s
|
||||
labels: {severity: warning}
|
||||
annotations: {summary: 'Ready SLO commit timestamps unavailable', runbook: 'Check track_commit_timestamp and outbox; unknown events are not proof of SLO compliance.'}
|
||||
- alert: MessengerHighErrorRate
|
||||
expr: (sum(rate(messenger_http_requests_total{status_class="5xx",route!~"/health/.*"}[1m])) or vector(0)) / clamp_min(sum(rate(messenger_http_requests_total{route!~"/health/.*"}[1m])), 0.001) > 0.05
|
||||
for: 10s
|
||||
labels: {severity: warning}
|
||||
annotations: {summary: 'API 5xx ratio exceeds 5%', runbook: 'Inspect API latency, traces and dependency spans; check DB readiness.'}
|
||||
- alert: MessengerQueueLag
|
||||
expr: max(messenger_queue_age_seconds{service_name="messenger-outbox"}) > 30
|
||||
for: 15s
|
||||
labels: {severity: warning}
|
||||
annotations: {summary: 'Oldest queued job exceeds 30 seconds', runbook: 'Check worker health, busy/capacity, broker and consumer traces.'}
|
||||
- alert: MessengerApiBurnFast
|
||||
expr: '((sum(increase(messenger_http_requests_total{status_class="5xx",route!~"/health/.*"}[1m])) or vector(0)) / clamp_min(sum(increase(messenger_http_requests_total{route!~"/health/.*"}[1m])), 1)) > 28.8 * 0.01 and ((sum(increase(messenger_http_requests_total{status_class="5xx",route!~"/health/.*"}[20s])) or vector(0)) / clamp_min(sum(increase(messenger_http_requests_total{route!~"/health/.*"}[20s])), 1)) > 28.8 * 0.01 and sum(increase(messenger_http_requests_total{route!~"/health/.*"}[20s])) >= 5'
|
||||
labels: {severity: critical, slo: api, burn: fast}
|
||||
annotations: {summary: 'api SLO fast burn', runbook: 'See docs/slo-runbook.md'}
|
||||
- alert: MessengerApiBurnSlow
|
||||
expr: '((sum(increase(messenger_http_requests_total{status_class="5xx",route!~"/health/.*"}[5m])) or vector(0)) / clamp_min(sum(increase(messenger_http_requests_total{route!~"/health/.*"}[5m])), 1)) > 14.4 * 0.01 and ((sum(increase(messenger_http_requests_total{status_class="5xx",route!~"/health/.*"}[1m])) or vector(0)) / clamp_min(sum(increase(messenger_http_requests_total{route!~"/health/.*"}[1m])), 1)) > 14.4 * 0.01 and sum(increase(messenger_http_requests_total{route!~"/health/.*"}[1m])) >= 5'
|
||||
labels: {severity: warning, slo: api, burn: slow}
|
||||
annotations: {summary: 'api SLO slow burn', runbook: 'See docs/slo-runbook.md'}
|
||||
- alert: MessengerReadyBurnFast
|
||||
expr: '((sum(increase(messenger_slo_ready_bad_total{service_name="messenger-outbox"}[1m])) or vector(0)) / clamp_min(sum(increase(messenger_slo_ready_eligible_total{service_name="messenger-outbox"}[1m])), 1)) > 28.8 * 0.01 and ((sum(increase(messenger_slo_ready_bad_total{service_name="messenger-outbox"}[20s])) or vector(0)) / clamp_min(sum(increase(messenger_slo_ready_eligible_total{service_name="messenger-outbox"}[20s])), 1)) > 28.8 * 0.01 and sum(increase(messenger_slo_ready_eligible_total{service_name="messenger-outbox"}[20s])) >= 5'
|
||||
labels: {severity: critical, slo: ready, burn: fast}
|
||||
annotations: {summary: 'ready SLO fast burn', runbook: 'See docs/slo-runbook.md'}
|
||||
- alert: MessengerReadyBurnSlow
|
||||
expr: '((sum(increase(messenger_slo_ready_bad_total{service_name="messenger-outbox"}[5m])) or vector(0)) / clamp_min(sum(increase(messenger_slo_ready_eligible_total{service_name="messenger-outbox"}[5m])), 1)) > 14.4 * 0.01 and ((sum(increase(messenger_slo_ready_bad_total{service_name="messenger-outbox"}[1m])) or vector(0)) / clamp_min(sum(increase(messenger_slo_ready_eligible_total{service_name="messenger-outbox"}[1m])), 1)) > 14.4 * 0.01 and sum(increase(messenger_slo_ready_eligible_total{service_name="messenger-outbox"}[1m])) >= 5'
|
||||
labels: {severity: warning, slo: ready, burn: slow}
|
||||
annotations: {summary: 'ready SLO slow burn', runbook: 'See docs/slo-runbook.md'}
|
||||
@@ -0,0 +1,11 @@
|
||||
global: {scrape_interval: 5s, evaluation_interval: 5s}
|
||||
rule_files: ['/etc/prometheus/alerts.yaml']
|
||||
scrape_configs:
|
||||
- job_name: collector
|
||||
scheme: https
|
||||
tls_config: {ca_file: /run/secrets/ca_cert, cert_file: /run/secrets/telemetry_prometheus_cert, key_file: /run/secrets/telemetry_prometheus_cert, server_name: otel-collector}
|
||||
static_configs: [{targets: ['otel-collector:8889']}]
|
||||
- job_name: collector-internal
|
||||
scheme: https
|
||||
tls_config: {ca_file: /run/secrets/ca_cert, cert_file: /run/secrets/telemetry_prometheus_cert, key_file: /run/secrets/telemetry_prometheus_cert, server_name: otel-collector}
|
||||
static_configs: [{targets: ['otel-collector:8888']}]
|
||||
@@ -0,0 +1,37 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
# RabbitMQ 4 no longer supports *_FILE. Keep the password in a Docker
|
||||
# secret and export it only inside the running container, never in Compose.
|
||||
RABBITMQ_DEFAULT_PASS="$(cat /run/secrets/rabbitmq_password)"
|
||||
if [ -z "$RABBITMQ_DEFAULT_PASS" ]; then
|
||||
echo "RabbitMQ password secret must not be empty" >&2
|
||||
exit 1
|
||||
fi
|
||||
export RABBITMQ_DEFAULT_PASS
|
||||
install -d -o rabbitmq -g rabbitmq -m 0700 /tmp/rabbitmq-tls
|
||||
rm -f /tmp/rabbitmq-tls/provisioned
|
||||
install -o rabbitmq -g rabbitmq -m 0600 /run/secrets/broker_tls /tmp/rabbitmq-tls/server.pem
|
||||
(
|
||||
set -e
|
||||
# Let the server create its own Erlang cookie before starting CLI tools.
|
||||
until [ -s /var/lib/rabbitmq/.erlang.cookie ]; do sleep 1; done
|
||||
until rabbitmqctl -q await_startup >/dev/null 2>&1; do sleep 2; done
|
||||
for role in api worker outbox; do
|
||||
user="messenger_$role"
|
||||
if ! rabbitmqctl -q list_users | cut -f1 | grep -Fxq "$user"; then
|
||||
if ! rabbitmqctl -q add_user "$user" "$(cat "/run/secrets/broker_${role}_password_hash")" --pre-hashed-password >/dev/null 2>&1; then
|
||||
echo 'RabbitMQ user provisioning failed' >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
case "$role" in
|
||||
api) write='^$'; read='^$' ;;
|
||||
worker) write='^amq\.default$'; read='^attachment\.process\.v1$' ;;
|
||||
outbox) write='^amq\.default$'; read='^$' ;;
|
||||
esac
|
||||
rabbitmqctl -q set_permissions -p / "$user" '^attachment\.process\.v1(\.dlq)?$' "$write" "$read"
|
||||
done
|
||||
touch /tmp/rabbitmq-tls/provisioned
|
||||
) &
|
||||
exec /usr/local/bin/docker-entrypoint.sh "$@"
|
||||
@@ -0,0 +1,7 @@
|
||||
listeners.tcp = none
|
||||
listeners.ssl.1 = 127.0.0.1:15671
|
||||
prometheus.tcp.ip = 127.0.0.1
|
||||
ssl_options.certfile = /tmp/rabbitmq-tls/server.pem
|
||||
ssl_options.keyfile = /tmp/rabbitmq-tls/server.pem
|
||||
ssl_options.verify = verify_none
|
||||
ssl_options.fail_if_no_peer_cert = false
|
||||
@@ -0,0 +1,26 @@
|
||||
defaults
|
||||
mode http
|
||||
timeout connect 2s
|
||||
timeout client 30s
|
||||
timeout server 30s
|
||||
frontend s3_tls
|
||||
bind :8333 ssl crt /run/secrets/server.pem ssl-min-ver TLSv1.2
|
||||
# Multipart form POST is not used by this application; deny it at the boundary.
|
||||
http-request deny if { method POST }
|
||||
# Reject repeated Authorization fields; commas inside SigV4 are valid.
|
||||
http-request deny unless { req.fhdr_cnt(Authorization) eq 1 }
|
||||
# Only the four locally provisioned SigV4 identities may use this endpoint.
|
||||
acl admin_auth req.hdr(Authorization) -m reg -f /run/secrets/admin_acl
|
||||
acl api_auth req.hdr(Authorization) -m reg -f /run/secrets/api_acl
|
||||
acl worker_auth req.hdr(Authorization) -m reg -f /run/secrets/worker_acl
|
||||
acl reconcile_auth req.hdr(Authorization) -m reg -f /run/secrets/reconcile_acl
|
||||
http-request deny unless admin_auth or api_auth or worker_auth or reconcile_auth
|
||||
# Application-generated keys contain no escapes or dot segments. Reject
|
||||
# ambiguous paths so the prefix checks and the backend see the same path.
|
||||
http-request deny if { path -m sub % } or { path -m sub /../ } or { path -m sub /./ } or { path -m sub // } or { path_end /.. } or { path_end /. }
|
||||
http-request deny if api_auth { method PUT DELETE } !{ path_beg /messenger-attachments/staging/ }
|
||||
http-request deny if worker_auth { method PUT DELETE } !{ path_beg /messenger-attachments/staging/ /messenger-attachments/originals/ /messenger-attachments/variants/ }
|
||||
http-request deny if reconcile_auth { method PUT DELETE } !{ path_beg /messenger-attachments/staging/ /messenger-attachments/originals/ /messenger-attachments/variants/ }
|
||||
default_backend s3_local
|
||||
backend s3_local
|
||||
server s3 127.0.0.1:18333 ssl verify required ca-file /run/secrets/ca.crt verifyhost s3 check
|
||||
@@ -0,0 +1,17 @@
|
||||
defaults
|
||||
mode tcp
|
||||
timeout connect 2s
|
||||
timeout client 30s
|
||||
timeout server 30s
|
||||
frontend http_tls
|
||||
bind :3200 ssl crt /run/secrets/server.pem ca-file /run/secrets/ca.crt verify required ssl-min-ver TLSv1.2
|
||||
tcp-request content reject unless { ssl_c_s_dn(OU) -m str telemetry-reader }
|
||||
default_backend http_local
|
||||
backend http_local
|
||||
server tempo 127.0.0.1:13200
|
||||
frontend grpc_tls
|
||||
bind :4317 ssl crt /run/secrets/server.pem ca-file /run/secrets/ca.crt verify required ssl-min-ver TLSv1.2 alpn h2
|
||||
tcp-request content reject unless { ssl_c_s_dn(OU) -m str telemetry-writer }
|
||||
default_backend grpc_local
|
||||
backend grpc_local
|
||||
server tempo 127.0.0.1:14317
|
||||
@@ -0,0 +1,15 @@
|
||||
server: {http_listen_address: "127.0.0.1", http_listen_port: 13200, grpc_listen_address: "127.0.0.1"}
|
||||
distributor:
|
||||
receivers:
|
||||
otlp:
|
||||
protocols:
|
||||
grpc: {endpoint: "127.0.0.1:14317"}
|
||||
ingester:
|
||||
trace_idle_period: 10s
|
||||
lifecycler: {address: "127.0.0.1"}
|
||||
compactor: {compaction: {block_retention: 168h}}
|
||||
storage:
|
||||
trace:
|
||||
backend: local
|
||||
wal: {path: /var/tempo/wal}
|
||||
local: {path: /var/tempo/blocks}
|
||||
@@ -0,0 +1,37 @@
|
||||
CREATE TABLE users (
|
||||
id uuid PRIMARY KEY,
|
||||
username varchar(32) NOT NULL UNIQUE CHECK (username ~ '^[a-z0-9_]{3,32}$'),
|
||||
display_name varchar(100) NOT NULL CHECK (char_length(btrim(display_name)) > 0),
|
||||
password_hash text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE chats (
|
||||
id uuid PRIMARY KEY,
|
||||
title varchar(100) NOT NULL CHECK (char_length(btrim(title)) > 0),
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE chat_members (
|
||||
chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||
user_id uuid NOT NULL REFERENCES users(id) ON DELETE RESTRICT,
|
||||
PRIMARY KEY (chat_id, user_id)
|
||||
);
|
||||
CREATE INDEX chat_members_user_chat_idx ON chat_members (user_id, chat_id);
|
||||
|
||||
CREATE TABLE messages (
|
||||
id uuid PRIMARY KEY,
|
||||
chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||
sender_id uuid NOT NULL REFERENCES users(id) ON DELETE RESTRICT,
|
||||
text varchar(4000) NOT NULL CHECK (char_length(btrim(text)) > 0),
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX messages_chat_created_id_idx ON messages (chat_id, created_at, id);
|
||||
|
||||
CREATE TABLE sessions (
|
||||
token_hash char(64) PRIMARY KEY,
|
||||
user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
expires_at timestamptz NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX sessions_expiry_idx ON sessions (expires_at);
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE chats ADD COLUMN history_version bigint NOT NULL DEFAULT 0;
|
||||
@@ -0,0 +1,12 @@
|
||||
CREATE TABLE idempotency_records (
|
||||
user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
method varchar(8) NOT NULL,
|
||||
path text NOT NULL,
|
||||
idempotency_key varchar(128) NOT NULL,
|
||||
request_hash char(64) NOT NULL,
|
||||
message_id uuid REFERENCES messages(id) ON DELETE RESTRICT,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (user_id, method, path, idempotency_key)
|
||||
);
|
||||
|
||||
CREATE INDEX idempotency_records_created_at_idx ON idempotency_records (created_at);
|
||||
@@ -0,0 +1,18 @@
|
||||
CREATE TABLE attachments (
|
||||
id uuid PRIMARY KEY,
|
||||
chat_id uuid NOT NULL REFERENCES chats(id),
|
||||
owner_id uuid NOT NULL REFERENCES users(id),
|
||||
filename varchar(255) NOT NULL,
|
||||
content_type text NOT NULL CHECK (content_type IN ('image/png', 'image/jpeg')),
|
||||
size_bytes integer NOT NULL CHECK (size_bytes BETWEEN 1 AND 10485760),
|
||||
sha256 char(64) NOT NULL,
|
||||
object_key text NOT NULL UNIQUE,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
UNIQUE (id, chat_id)
|
||||
);
|
||||
ALTER TABLE messages DROP CONSTRAINT messages_text_check;
|
||||
ALTER TABLE messages ADD COLUMN attachment_ids uuid[] NOT NULL DEFAULT '{}';
|
||||
ALTER TABLE messages ADD CONSTRAINT messages_content_check
|
||||
CHECK (char_length(btrim(text)) > 0 OR cardinality(attachment_ids) > 0);
|
||||
CREATE INDEX attachments_chat_idx ON attachments(chat_id);
|
||||
@@ -0,0 +1,34 @@
|
||||
ALTER TABLE attachments
|
||||
RENAME COLUMN object_key TO staging_key;
|
||||
ALTER TABLE attachments
|
||||
ADD COLUMN original_key text,
|
||||
ADD COLUMN status text NOT NULL DEFAULT 'queued'
|
||||
CHECK (status IN ('queued', 'processing', 'ready', 'failed')),
|
||||
ADD COLUMN error_code text,
|
||||
ADD COLUMN pipeline_version integer NOT NULL DEFAULT 1,
|
||||
ADD COLUMN processing_started_at timestamptz;
|
||||
|
||||
CREATE TABLE attachment_variants (
|
||||
attachment_id uuid NOT NULL REFERENCES attachments(id) ON DELETE CASCADE,
|
||||
pipeline_version integer NOT NULL,
|
||||
name text NOT NULL CHECK (name IN ('thumbnail', 'crop', 'optimized')),
|
||||
object_key text NOT NULL UNIQUE,
|
||||
content_type text NOT NULL,
|
||||
size_bytes integer NOT NULL CHECK (size_bytes > 0),
|
||||
width integer NOT NULL CHECK (width > 0),
|
||||
height integer NOT NULL CHECK (height > 0),
|
||||
sha256 char(64) NOT NULL,
|
||||
PRIMARY KEY (attachment_id, pipeline_version, name)
|
||||
);
|
||||
|
||||
CREATE TABLE attachment_jobs (
|
||||
job_id uuid PRIMARY KEY,
|
||||
attachment_id uuid NOT NULL UNIQUE REFERENCES attachments(id) ON DELETE CASCADE,
|
||||
pipeline_version integer NOT NULL DEFAULT 1,
|
||||
attempt integer NOT NULL DEFAULT 1 CHECK (attempt >= 1),
|
||||
status text NOT NULL DEFAULT 'queued' CHECK (status IN ('queued', 'processing', 'ready', 'failed')),
|
||||
last_error text,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX attachment_jobs_status_idx ON attachment_jobs(status, updated_at);
|
||||
@@ -0,0 +1,17 @@
|
||||
ALTER TABLE attachment_jobs
|
||||
ADD COLUMN next_attempt_at timestamptz NOT NULL DEFAULT now(),
|
||||
ADD COLUMN lease_until timestamptz,
|
||||
ADD COLUMN replayed_at timestamptz;
|
||||
CREATE INDEX attachment_jobs_due_idx ON attachment_jobs(status, next_attempt_at);
|
||||
CREATE INDEX attachment_jobs_lease_idx ON attachment_jobs(status, lease_until);
|
||||
|
||||
CREATE TABLE attachment_outbox (
|
||||
id uuid PRIMARY KEY,
|
||||
job_id uuid NOT NULL REFERENCES attachment_jobs(job_id) ON DELETE CASCADE,
|
||||
payload jsonb NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
published_at timestamptz,
|
||||
attempts integer NOT NULL DEFAULT 0,
|
||||
UNIQUE (job_id, published_at)
|
||||
);
|
||||
CREATE INDEX attachment_outbox_pending_idx ON attachment_outbox(created_at) WHERE published_at IS NULL;
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE attachment_jobs ADD COLUMN first_started_at timestamptz;
|
||||
@@ -0,0 +1,2 @@
|
||||
-- Context is technical metadata, never user content. Retained across retry/outbox recreation.
|
||||
ALTER TABLE attachment_jobs ADD COLUMN trace_context jsonb NOT NULL DEFAULT '{}'::jsonb;
|
||||
@@ -0,0 +1,11 @@
|
||||
-- A separate immutable cohort: replay and job cleanup must not rewrite SLO history.
|
||||
-- Existing jobs have no recoverable acceptance commit and are deliberately not backfilled.
|
||||
CREATE TABLE attachment_slo (
|
||||
attachment_id uuid PRIMARY KEY,
|
||||
accepted_xid xid NOT NULL DEFAULT pg_current_xact_id()::xid,
|
||||
ready_xid xid,
|
||||
accepted_at timestamptz,
|
||||
ready_at timestamptz,
|
||||
bad boolean
|
||||
);
|
||||
CREATE INDEX attachment_slo_unresolved_idx ON attachment_slo(accepted_at) WHERE bad IS NULL;
|
||||
@@ -0,0 +1,17 @@
|
||||
[project]
|
||||
name = "mtusi2026lab6"
|
||||
version = "1.6.0"
|
||||
description = "MTUSI high-load messenger, laboratory 6"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.12"
|
||||
dependencies = [
|
||||
"argon2-cffi==25.1.0",
|
||||
"asyncpg==0.31.0",
|
||||
"boto3==1.43.115",
|
||||
"fastapi==0.141.1",
|
||||
"pillow==13.0.0",
|
||||
"pika==1.3.2",
|
||||
"uvicorn==0.40.0",
|
||||
"opentelemetry-sdk==1.36.0",
|
||||
"opentelemetry-exporter-otlp-proto-http==1.36.0",
|
||||
]
|
||||
@@ -0,0 +1,70 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Sequential lab3-5 verification; capture actual output and exit status, fail fast."""
|
||||
from datetime import datetime, timezone
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
DESTINATION = ROOT / "evidence/audit"
|
||||
CHECKS = [
|
||||
("contracts", ["make", "check", "validate", "PYTHON=.venv/bin/python"]),
|
||||
("compose", ["docker", "compose", "config", "--quiet"]),
|
||||
("smoke", ["make", "test"]),
|
||||
("attachments", ["make", "test-attachments"]),
|
||||
("idempotency", [sys.executable, "student-tests/idempotency_concurrency.py"]),
|
||||
("regressions", [sys.executable, "student-tests/review_regressions.py"]),
|
||||
("private-bucket", ["make", "test-private"]),
|
||||
("s3-permissions", ["make", "test-s3-permissions"]),
|
||||
("bootstrap", ["docker", "compose", "run", "--rm", "--no-deps", "s3-init"]),
|
||||
("upload-failover", ["make", "test-upload-failover"]),
|
||||
("public-failover", ["make", "test-failover", "ACTION_SCRIPT=scripts/stop-one.sh"]),
|
||||
("restore-replicas", ["docker", "compose", "up", "-d", "--wait", "api-a", "api-b", "load_balancer"]),
|
||||
("s3-outage", ["make", "test-s3-outage"]),
|
||||
("persistence", [sys.executable, "scripts/verify-persistence.py"]),
|
||||
("reconcile", ["make", "test-reconcile"]),
|
||||
("reconcile-audit", ["make", "test-reconcile-audit"]),
|
||||
("upload-memory", ["make", "test-upload-memory"]),
|
||||
("reconcile-benchmark", ["make", "test-reconcile-benchmark"]),
|
||||
("final-smoke", ["make", "test"]),
|
||||
("environment", [sys.executable, "scripts/record-environment.py"]),
|
||||
]
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--resume-from', choices=[name for name, _ in CHECKS])
|
||||
args = parser.parse_args()
|
||||
DESTINATION.mkdir(parents=True, exist_ok=True)
|
||||
results = []
|
||||
checks = CHECKS
|
||||
if args.resume_from:
|
||||
offset = [name for name, _ in CHECKS].index(args.resume_from)
|
||||
previous = json.loads((DESTINATION / 'results.json').read_text())['checks']
|
||||
results = previous[:offset]
|
||||
if [item['name'] for item in results] != [name for name, _ in CHECKS[:offset]] or any(item['exit_code'] for item in results):
|
||||
parser.error('resume requires successful evidence for every earlier step')
|
||||
checks = CHECKS[offset:]
|
||||
for name, command in checks:
|
||||
print(f"RUN {name}", flush=True)
|
||||
started = time.monotonic()
|
||||
with (DESTINATION / f"{name}.txt").open("w") as stream:
|
||||
result = subprocess.run(command, cwd=ROOT, stdout=stream, stderr=subprocess.STDOUT)
|
||||
results.append({"name": name, "command": command, "exit_code": result.returncode,
|
||||
"seconds": round(time.monotonic() - started, 3)})
|
||||
(DESTINATION / "results.json").write_text(json.dumps({
|
||||
"recorded_at_utc": datetime.now(timezone.utc).isoformat(),
|
||||
"checks": results, "complete": len(results) == len(CHECKS),
|
||||
}, indent=2) + "\n")
|
||||
print(f"{'PASS' if result.returncode == 0 else 'FAIL'} {name}: exit={result.returncode}", flush=True)
|
||||
if result.returncode:
|
||||
print((DESTINATION / f"{name}.txt").read_text()[-8000:], flush=True)
|
||||
return result.returncode
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,25 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Measure local Argon2id hashing and verification without recording secrets."""
|
||||
from statistics import median
|
||||
from time import perf_counter
|
||||
|
||||
from argon2 import PasswordHasher
|
||||
|
||||
|
||||
def main():
|
||||
hasher = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1)
|
||||
password = "synthetic-benchmark-password"
|
||||
hashes, verifications = [], []
|
||||
for _ in range(10):
|
||||
started = perf_counter()
|
||||
encoded = hasher.hash(password)
|
||||
hashes.append((perf_counter() - started) * 1000)
|
||||
started = perf_counter()
|
||||
assert hasher.verify(encoded, password)
|
||||
verifications.append((perf_counter() - started) * 1000)
|
||||
print("Argon2id m=19456 KiB, t=2, p=1; samples=10")
|
||||
print(f"hash median={median(hashes):.2f} ms; verify median={median(verifications):.2f} ms")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,49 @@
|
||||
#!/bin/sh
|
||||
# Issue separate internal API server identities and a load-balancer client role.
|
||||
set -eu
|
||||
umask 077
|
||||
cd "$(dirname "$0")/.."
|
||||
test -s secrets/ca.key && test -s secrets/ca.crt || { echo 'Run bootstrap-pki.sh first' >&2; exit 1; }
|
||||
work=$(mktemp -d "${TMPDIR:-/tmp}/lab7-mtls.XXXXXXXX")
|
||||
trap 'rm -rf "$work"' EXIT HUP INT TERM
|
||||
issue() {
|
||||
name=$1; usage=$2; subject=$3; san=$4
|
||||
if [ -s "secrets/$name.pem" ]; then return; fi
|
||||
if [ -e "secrets/$name.pem" ]; then echo "Incomplete $name.pem" >&2; exit 1; fi
|
||||
cat > "$work/ext" <<EOF
|
||||
basicConstraints=critical,CA:FALSE
|
||||
keyUsage=critical,digitalSignature,keyEncipherment
|
||||
extendedKeyUsage=$usage
|
||||
subjectAltName=DNS:$san
|
||||
subjectKeyIdentifier=hash
|
||||
authorityKeyIdentifier=keyid,issuer
|
||||
EOF
|
||||
openssl req -new -newkey rsa:2048 -nodes -sha256 -subj "$subject" \
|
||||
-keyout "$work/$name.key" -out "$work/$name.csr" 2>/dev/null
|
||||
openssl x509 -req -in "$work/$name.csr" -CA secrets/ca.crt -CAkey secrets/ca.key \
|
||||
-set_serial "0x$(openssl rand -hex 16)" -days 90 -sha256 -extfile "$work/ext" \
|
||||
-out "$work/$name.crt" 2>/dev/null
|
||||
openssl verify -CAfile secrets/ca.crt "$work/$name.crt" >/dev/null
|
||||
cat "$work/$name.crt" "$work/$name.key" > "secrets/$name.pem"
|
||||
}
|
||||
issue api-a serverAuth '/CN=api-a' api-a
|
||||
issue api-b serverAuth '/CN=api-b' api-b
|
||||
issue lb clientAuth '/CN=lb/OU=load-balancer' lb
|
||||
issue openbao serverAuth '/CN=openbao' 'openbao,DNS:localhost,IP:127.0.0.1'
|
||||
issue bao-api clientAuth '/CN=bao-api/OU=api' bao-api
|
||||
issue bao-worker clientAuth '/CN=bao-worker/OU=worker' bao-worker
|
||||
issue postgres serverAuth '/CN=postgres' postgres
|
||||
issue s3 serverAuth '/CN=s3' s3
|
||||
issue broker serverAuth '/CN=broker' broker
|
||||
issue otel-collector serverAuth '/CN=otel-collector' otel-collector
|
||||
issue otel-api clientAuth '/CN=otel-api/OU=telemetry-publisher' otel-api
|
||||
issue otel-worker clientAuth '/CN=otel-worker/OU=telemetry-publisher' otel-worker
|
||||
issue otel-outbox clientAuth '/CN=otel-outbox/OU=telemetry-publisher' otel-outbox
|
||||
issue tempo serverAuth '/CN=tempo' tempo
|
||||
issue loki serverAuth '/CN=loki' loki
|
||||
issue prometheus serverAuth '/CN=prometheus' prometheus
|
||||
issue grafana serverAuth '/CN=localhost' 'localhost,IP:127.0.0.1'
|
||||
issue telemetry-grafana clientAuth '/CN=grafana/OU=telemetry-reader' grafana
|
||||
issue telemetry-collector clientAuth '/CN=collector/OU=telemetry-writer' collector
|
||||
issue telemetry-prometheus clientAuth '/CN=prometheus/OU=telemetry-scraper' prometheus
|
||||
echo 'Local internal identities ready.'
|
||||
@@ -0,0 +1,38 @@
|
||||
#!/bin/sh
|
||||
# Local-only CA and ingress certificate. Never commit the generated secrets.
|
||||
set -eu
|
||||
umask 077
|
||||
cd "$(dirname "$0")/.."
|
||||
mkdir -p secrets
|
||||
if [ -e secrets/ca.key ] || [ -e secrets/ca.crt ] || [ -e secrets/ingress.pem ]; then
|
||||
if [ -s secrets/ca.key ] && [ -s secrets/ca.crt ] && [ -s secrets/ingress.pem ]; then
|
||||
echo 'Local PKI already exists; preserving it.'
|
||||
exit 0
|
||||
fi
|
||||
echo 'Incomplete PKI in secrets/: inspect it before retrying.' >&2
|
||||
exit 1
|
||||
fi
|
||||
work=$(mktemp -d "${TMPDIR:-/tmp}/lab7-pki.XXXXXXXX")
|
||||
trap 'rm -rf "$work"' EXIT HUP INT TERM
|
||||
cat > "$work/extensions.cnf" <<'EOF'
|
||||
basicConstraints=critical,CA:FALSE
|
||||
keyUsage=critical,digitalSignature,keyEncipherment
|
||||
extendedKeyUsage=serverAuth
|
||||
subjectAltName=DNS:localhost,IP:127.0.0.1
|
||||
subjectKeyIdentifier=hash
|
||||
authorityKeyIdentifier=keyid,issuer
|
||||
EOF
|
||||
openssl req -x509 -newkey rsa:3072 -nodes -sha256 -days 365 \
|
||||
-subj '/CN=Lab7 local CA' -addext 'basicConstraints=critical,CA:TRUE' \
|
||||
-addext 'keyUsage=critical,keyCertSign,cRLSign' -addext 'subjectKeyIdentifier=hash' \
|
||||
-keyout "$work/ca.key" -out "$work/ca.crt" 2>/dev/null
|
||||
openssl req -new -newkey rsa:2048 -nodes -sha256 -subj '/CN=localhost' \
|
||||
-keyout "$work/ingress.key" -out "$work/ingress.csr" 2>/dev/null
|
||||
openssl x509 -req -in "$work/ingress.csr" -CA "$work/ca.crt" -CAkey "$work/ca.key" \
|
||||
-CAcreateserial -days 90 -sha256 -extfile "$work/extensions.cnf" -out "$work/ingress.crt" 2>/dev/null
|
||||
openssl verify -CAfile "$work/ca.crt" "$work/ingress.crt" >/dev/null
|
||||
cat "$work/ingress.crt" "$work/ingress.key" > "$work/ingress.pem"
|
||||
cp "$work/ca.key" secrets/ca.key
|
||||
cp "$work/ca.crt" secrets/ca.crt
|
||||
cp "$work/ingress.pem" secrets/ingress.pem
|
||||
echo 'Local ingress PKI generated in secrets/.'
|
||||
@@ -0,0 +1,64 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Create local credentials without printing or overwriting existing values."""
|
||||
import json
|
||||
import base64
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
|
||||
root = Path(__file__).resolve().parents[1] / "secrets"
|
||||
root.mkdir(mode=0o700, exist_ok=True)
|
||||
root.chmod(0o700)
|
||||
|
||||
|
||||
def write(name, value):
|
||||
path = root / name
|
||||
if path.exists():
|
||||
return path.read_text().strip()
|
||||
with path.open("x") as stream:
|
||||
path.chmod(0o600)
|
||||
stream.write(value + "\n")
|
||||
return value
|
||||
|
||||
|
||||
write("grafana_password", secrets.token_urlsafe(24))
|
||||
password = write("postgres_password", secrets.token_hex(32))
|
||||
write("database_url", f"postgresql://messenger:{password}@postgres:5432/messenger")
|
||||
for role in ("api", "worker", "outbox", "reconcile"):
|
||||
role_password = write(f"database_{role}_password", secrets.token_hex(32))
|
||||
write(f"database_{role}_url", f"postgresql://messenger_{role}:{role_password}@postgres:5432/messenger")
|
||||
write("cursor_secret", secrets.token_hex(32))
|
||||
admin_key = write("s3_admin_key", secrets.token_hex(16))
|
||||
admin_secret = write("s3_admin_secret", secrets.token_hex(32))
|
||||
app_key = write("s3_access_key_id", secrets.token_hex(16))
|
||||
app_secret = write("s3_secret_access_key", secrets.token_hex(32))
|
||||
worker_key = write("s3_worker_access_key_id", secrets.token_hex(16))
|
||||
worker_secret = write("s3_worker_secret_access_key", secrets.token_hex(32))
|
||||
reconcile_key = write("s3_reconcile_access_key_id", secrets.token_hex(16))
|
||||
reconcile_secret = write("s3_reconcile_secret_access_key", secrets.token_hex(32))
|
||||
for role, key in (("admin", admin_key), ("api", app_key), ("worker", worker_key), ("reconcile", reconcile_key)):
|
||||
# Used by the S3 proxy to select a write-prefix policy; the gateway still
|
||||
# verifies the complete SigV4 signature before accepting a request.
|
||||
write(f"s3_{role}_acl", "^AWS4-HMAC-SHA256[[:space:]]+Credential=" + key + "/")
|
||||
rabbitmq_password = write("rabbitmq_password", secrets.token_urlsafe(32))
|
||||
write("broker_url", f"amqp://messenger:{rabbitmq_password}@broker:5672/%2F")
|
||||
write("broker_tls_url", f"amqps://messenger:{rabbitmq_password}@broker:5671/%2F")
|
||||
for role in ("api", "worker", "outbox"):
|
||||
role_password = write(f"broker_{role}_password", secrets.token_hex(32))
|
||||
write(f"broker_{role}_url", f"amqps://messenger_{role}:{role_password}@broker:5671/%2F")
|
||||
salt = secrets.token_bytes(4)
|
||||
digest = base64.b64encode(salt + hashlib.sha256(salt + role_password.encode()).digest()).decode()
|
||||
write(f"broker_{role}_password_hash", digest)
|
||||
config_path = root / "s3.json"
|
||||
config_path.write_text(json.dumps({"identities": [
|
||||
{"name": "bootstrap", "credentials": [{"accessKey": admin_key, "secretKey": admin_secret}],
|
||||
"actions": ["Admin", "Read", "Write", "List", "Tagging"]},
|
||||
{"name": "api", "credentials": [{"accessKey": app_key, "secretKey": app_secret}],
|
||||
"actions": ["Read:messenger-attachments", "Write:messenger-attachments", "List:messenger-attachments"]},
|
||||
{"name": "worker", "credentials": [{"accessKey": worker_key, "secretKey": worker_secret}],
|
||||
"actions": ["Read:messenger-attachments", "Write:messenger-attachments", "List:messenger-attachments"]},
|
||||
{"name": "reconcile", "credentials": [{"accessKey": reconcile_key, "secretKey": reconcile_secret}],
|
||||
"actions": ["Read:messenger-attachments", "Write:messenger-attachments", "List:messenger-attachments"]},
|
||||
]}, indent=2) + "\n")
|
||||
config_path.chmod(0o600)
|
||||
print("Local secrets ready; existing values preserved.")
|
||||
@@ -0,0 +1,57 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Initialize/unseal the local OpenBao as operator without printing credentials."""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import ssl
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
DATA = ROOT / 'secrets' / 'openbao-operator.json'
|
||||
BASE = os.environ.get('BAO_OPERATOR_ADDR', 'https://localhost:18200').rstrip('/')
|
||||
TLS = ssl.create_default_context(cafile=str(ROOT / 'secrets' / 'ca.crt'))
|
||||
|
||||
|
||||
def request(path, body=None):
|
||||
data = None if body is None else json.dumps(body).encode()
|
||||
req = urllib.request.Request(BASE + '/v1/' + path, data=data,
|
||||
headers={'Content-Type': 'application/json'},
|
||||
method='GET' if body is None else 'PUT')
|
||||
with urllib.request.urlopen(req, context=TLS, timeout=10) as response:
|
||||
return json.load(response)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('action', choices=['init', 'unseal', 'status'])
|
||||
args = parser.parse_args()
|
||||
if args.action == 'init':
|
||||
if DATA.exists():
|
||||
raise SystemExit('Operator credentials file exists; refusing to overwrite it.')
|
||||
if request('sys/init')['initialized']:
|
||||
raise SystemExit('OpenBao is already initialized. Recover operator credentials; do not reinitialize.')
|
||||
fd = os.open(DATA, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
||||
with os.fdopen(fd, 'w') as stream:
|
||||
result = request('sys/init', {'secret_shares': 3, 'secret_threshold': 2})
|
||||
json.dump(result, stream)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
print('Initialized. Operator credentials stored locally in secrets/openbao-operator.json; protect and back them up.')
|
||||
elif args.action == 'unseal':
|
||||
data = json.loads(DATA.read_text())
|
||||
for key in data['keys_base64'][:2]:
|
||||
state = request('sys/unseal', {'key': key})
|
||||
if not state['sealed']:
|
||||
break
|
||||
if state['sealed']:
|
||||
raise SystemExit('OpenBao remains sealed.')
|
||||
print('OpenBao unsealed.')
|
||||
else:
|
||||
state = request('sys/seal-status')
|
||||
print('initialized=' + str(state['initialized']) + ' sealed=' + str(state['sealed']))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,54 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Operator provisions certificate auth and scoped KV v2 paths; no credentials printed."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import ssl
|
||||
import subprocess
|
||||
import urllib.request
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SECRETS = ROOT / 'secrets'
|
||||
BASE = os.environ.get('BAO_OPERATOR_ADDR', 'https://localhost:18200').rstrip('/')
|
||||
TLS = ssl.create_default_context(cafile=str(SECRETS / 'ca.crt'))
|
||||
TOKEN = json.loads((SECRETS / 'openbao-operator.json').read_text())['root_token']
|
||||
|
||||
|
||||
def call(path, body=None):
|
||||
data = None if body is None else json.dumps(body).encode()
|
||||
request = urllib.request.Request(BASE + '/v1/' + path, data=data,
|
||||
headers={'Content-Type': 'application/json', 'X-Vault-Token': TOKEN},
|
||||
method='GET' if body is None else 'POST')
|
||||
with urllib.request.urlopen(request, context=TLS, timeout=10) as response:
|
||||
payload = response.read()
|
||||
return json.loads(payload) if payload else {}
|
||||
|
||||
|
||||
def main():
|
||||
if 'cert/' not in call('sys/auth')['data']:
|
||||
call('sys/auth/cert', {'type': 'cert'})
|
||||
if 'lab/' not in call('sys/mounts')['data']:
|
||||
call('sys/mounts/lab', {'type': 'kv', 'options': {'version': '2'}})
|
||||
files = {'DATABASE_URL': 'database_api_url', 'CURSOR_SECRET': 'cursor_secret',
|
||||
'S3_ACCESS_KEY_ID': 's3_access_key_id', 'S3_SECRET_ACCESS_KEY': 's3_secret_access_key',
|
||||
'BROKER_URL': 'broker_api_url'}
|
||||
for role in ('api', 'worker'):
|
||||
role_files = dict(files)
|
||||
if role == 'worker':
|
||||
role_files.update(DATABASE_URL='database_worker_url',
|
||||
S3_ACCESS_KEY_ID='s3_worker_access_key_id',
|
||||
S3_SECRET_ACCESS_KEY='s3_worker_secret_access_key',
|
||||
BROKER_URL='broker_worker_url')
|
||||
values = {name: (SECRETS / file).read_text().strip() for name, file in role_files.items()}
|
||||
policy = f'path "lab/data/{role}" {{ capabilities = ["read"] }}'
|
||||
call('sys/policies/acl/' + role, {'policy': policy})
|
||||
certificate = subprocess.check_output(['openssl', 'x509', '-in', str(SECRETS / ('bao-' + role + '.pem'))], text=True)
|
||||
call('auth/cert/certs/' + role, {'certificate': certificate, 'token_policies': [role],
|
||||
'token_ttl': '1h', 'token_max_ttl': '1h',
|
||||
'token_no_default_policy': True})
|
||||
call('lab/data/' + role, {'data': values})
|
||||
print('Scoped API and worker policies, certificate identities and secret paths configured.')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,39 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Give containers group-read access only to individually mounted secret files.
|
||||
|
||||
The host directory stays owner-only; CA and operator credentials stay 0600.
|
||||
Compose bind-mounted file secrets preserve host ownership on Linux.
|
||||
"""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
secret_dir = ROOT / 'secrets'
|
||||
if secret_dir.is_symlink():
|
||||
raise SystemExit('secrets directory must not be a symlink')
|
||||
secret_dir.chmod(0o700)
|
||||
compose = (ROOT / 'compose.yaml').read_text()
|
||||
names = set(re.findall(r'\./secrets/([A-Za-z0-9_.-]+)', compose))
|
||||
gid = os.getgid()
|
||||
for name in sorted(names):
|
||||
path = secret_dir / name
|
||||
if path.is_symlink() or not path.is_file():
|
||||
raise SystemExit('Missing or unsafe mounted secret: ' + name)
|
||||
os.chown(path, -1, gid)
|
||||
path.chmod(0o640)
|
||||
for name in ('ca.key', 'openbao-operator.json'):
|
||||
path = secret_dir / name
|
||||
if path.is_symlink():
|
||||
raise SystemExit('Operator credential must not be a symlink')
|
||||
if path.exists():
|
||||
path.chmod(0o600)
|
||||
env = ROOT / '.env'
|
||||
if env.is_symlink():
|
||||
raise SystemExit('.env must not be a symlink')
|
||||
text = env.read_text() if env.exists() else (ROOT / '.env.example').read_text()
|
||||
text = re.sub(r'^LAB_SECRET_GID=.*\n?', '', text, flags=re.M)
|
||||
with env.open('w') as stream:
|
||||
env.chmod(0o600)
|
||||
stream.write(text.rstrip() + '\nLAB_SECRET_GID=' + str(gid) + '\n')
|
||||
print('Mounted secrets: group-readable; host directory: 0700; operator files: 0600.')
|
||||
@@ -0,0 +1,44 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Sanitized environment and source fingerprint for local test evidence."""
|
||||
from datetime import datetime, timezone
|
||||
from hashlib import sha256
|
||||
import json
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import subprocess
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def command(*args):
|
||||
return subprocess.check_output(args, cwd=root, text=True).strip()
|
||||
|
||||
|
||||
paths = [root / name for name in ('Dockerfile', 'compose.yaml', 'pyproject.toml', 'uv.lock', 'Makefile')]
|
||||
for directory in ('src', 'migrations', 'infra', 'scripts', 'student-tests'):
|
||||
paths.extend(path for path in (root / directory).rglob('*')
|
||||
if path.is_file() and '__pycache__' not in path.parts)
|
||||
report = {
|
||||
'recorded_at_utc': datetime.now(timezone.utc).isoformat(),
|
||||
'base_commit': command('git', 'rev-parse', 'HEAD'),
|
||||
'branch': command('git', 'branch', '--show-current'),
|
||||
'note': 'Results apply to this working tree, not only the base commit. Per-profile load settings are recorded in real-c*-p*-s*.json.',
|
||||
'host': platform.platform(),
|
||||
'docker': json.loads(command('docker', 'info', '--format',
|
||||
'{"server":"{{.ServerVersion}}","cpus":{{.NCPU}},"memory_bytes":{{.MemTotal}}}')),
|
||||
'compose_version': command('docker', 'compose', 'version', '--short'),
|
||||
'sources_sha256': {str(path.relative_to(root)): sha256(path.read_bytes()).hexdigest() for path in sorted(paths)},
|
||||
'services': {},
|
||||
}
|
||||
for service in ('postgres', 's3', 'broker', 'worker', 'outbox', 'reconcile', 'api-a', 'api-b', 'load_balancer'):
|
||||
container = command('docker', 'compose', 'ps', '-q', service)
|
||||
info = json.loads(command('docker', 'inspect', container))[0]
|
||||
report['services'][service] = {
|
||||
'image': info['Config']['Image'], 'image_id': info['Image'],
|
||||
'state': info['State']['Status'], 'health': info['State'].get('Health', {}).get('Status'),
|
||||
'memory_limit_bytes': info['HostConfig']['Memory'],
|
||||
'nano_cpus_limit': info['HostConfig']['NanoCpus'],
|
||||
'volumes': [mount['Name'] for mount in info['Mounts'] if mount['Type'] == 'volume'],
|
||||
}
|
||||
(root / 'evidence/environment.json').write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n')
|
||||
print('PASS: sanitized environment and source hashes saved')
|
||||
Executable
+21
@@ -0,0 +1,21 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
# Deliberately preserves named volumes and test data.
|
||||
docker compose restart postgres s3 broker openbao prometheus loki tempo grafana otel-collector
|
||||
attempt=0
|
||||
until python3 scripts/openbao-operator.py unseal; do
|
||||
attempt=$((attempt + 1))
|
||||
[ "$attempt" -lt 30 ] || exit 1
|
||||
sleep 1
|
||||
done
|
||||
docker compose up -d --wait postgres s3 broker
|
||||
docker compose up -d --no-deps --force-recreate broker-tcp
|
||||
docker compose up -d --no-deps --force-recreate s3-tcp
|
||||
docker compose run --rm --no-deps s3-init
|
||||
docker compose up -d --no-deps --force-recreate otel-tls prometheus-tls loki-tls tempo-tls
|
||||
docker compose restart worker outbox reconcile api-a api-b
|
||||
docker compose up -d --no-deps --force-recreate api-a-tls api-b-tls
|
||||
docker compose restart load_balancer
|
||||
docker compose up -d --wait worker outbox reconcile api-a api-b load_balancer
|
||||
@@ -0,0 +1,31 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run real, sequential Docker profiles; restore normal settings on exit."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def main():
|
||||
try:
|
||||
for workers in (1, 2, 4):
|
||||
env = dict(os.environ, WORKER_CONCURRENCY=str(workers),
|
||||
WORKER_PREFETCH=str(workers), MAX_PENDING_JOBS='32')
|
||||
subprocess.run(['docker', 'compose', 'up', '-d', '--no-deps', '--wait',
|
||||
'worker', 'api-a', 'api-b'], cwd=ROOT, env=env, check=True)
|
||||
for size in (512, 2400):
|
||||
subprocess.run([sys.executable, 'scripts/track1.py',
|
||||
'--run-name', f'real-c{workers}-p{workers}-s{size}',
|
||||
'--workers', str(workers), '--prefetch', str(workers),
|
||||
'--max-pending', '32', '--images', '160',
|
||||
'--concurrency', '16', '--size', str(size),
|
||||
'--require-backpressure'], cwd=ROOT, check=True)
|
||||
finally:
|
||||
subprocess.run(['docker', 'compose', 'up', '-d', '--no-deps', '--wait',
|
||||
'worker', 'api-a', 'api-b'], cwd=ROOT, check=True)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Executable
+18
@@ -0,0 +1,18 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
for service in api-a api-b; do
|
||||
container="$(docker compose ps -q "$service")"
|
||||
[ -n "$container" ] || continue
|
||||
hostname="$(docker inspect --format '{{.Config.Hostname}}' "$container")"
|
||||
if [ "$hostname" = "$TARGET_INSTANCE_ID" ]; then
|
||||
docker compose stop "$service"
|
||||
exit 0
|
||||
fi
|
||||
done
|
||||
|
||||
printf '%s\n' 'TARGET_INSTANCE_ID does not match a running API replica' >&2
|
||||
exit 2
|
||||
@@ -0,0 +1,29 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
umask 077
|
||||
cd "$(dirname "$0")/.."
|
||||
test -s secrets/ca.key && test -s secrets/lb.pem || { echo 'Bootstrap PKI first' >&2; exit 1; }
|
||||
work=$(mktemp -d "${TMPDIR:-/tmp}/lab7-mtls-test.XXXXXXXX")
|
||||
trap 'rm -rf "$work"' EXIT HUP INT TERM
|
||||
cat > "$work/ext" <<'EOF'
|
||||
basicConstraints=critical,CA:FALSE
|
||||
keyUsage=critical,digitalSignature,keyEncipherment
|
||||
extendedKeyUsage=clientAuth
|
||||
subjectKeyIdentifier=hash
|
||||
authorityKeyIdentifier=keyid,issuer
|
||||
EOF
|
||||
openssl req -new -newkey rsa:2048 -nodes -subj '/CN=lb/OU=worker' \
|
||||
-keyout "$work/wrong.key" -out "$work/wrong.csr" 2>/dev/null
|
||||
openssl x509 -req -in "$work/wrong.csr" -CA secrets/ca.crt -CAkey secrets/ca.key \
|
||||
-set_serial "0x$(openssl rand -hex 16)" -days 1 -extfile "$work/ext" -out "$work/wrong.crt" 2>/dev/null
|
||||
cat "$work/wrong.crt" "$work/wrong.key" > "$work/wrong-role.pem"
|
||||
openssl req -x509 -newkey rsa:2048 -nodes -days 1 -subj '/CN=foreign' \
|
||||
-keyout "$work/foreign.key" -out "$work/foreign.crt" 2>/dev/null
|
||||
cat "$work/foreign.crt" "$work/foreign.key" > "$work/foreign.pem"
|
||||
docker run --rm --network "${COMPOSE_PROJECT_NAME:-$(basename "$PWD")}_default" --user 0 \
|
||||
-v "$PWD/secrets/ca.crt:/certs/ca.crt:ro" \
|
||||
-v "$PWD/secrets/lb.pem:/certs/lb.pem:ro" \
|
||||
-v "$work/wrong-role.pem:/certs/wrong-role.pem:ro" \
|
||||
-v "$work/foreign.pem:/certs/foreign.pem:ro" \
|
||||
-v "$PWD/student-tests/mtls_probe.py:/probe.py:ro" \
|
||||
"${COMPOSE_PROJECT_NAME:-$(basename "$PWD")}-api-a" /app/.venv/bin/python /probe.py
|
||||
Executable
+217
@@ -0,0 +1,217 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Closed-loop upload burst with concurrent readiness observations and drain proof."""
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
from io import BytesIO
|
||||
import json
|
||||
import math
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, Failure, arguments, check, run
|
||||
|
||||
|
||||
def percentile(values, point):
|
||||
values = sorted(values)
|
||||
return round(values[max(0, math.ceil(len(values) * point) - 1)] * 1000, 3) if values else None
|
||||
|
||||
|
||||
def command_json(*args):
|
||||
result = subprocess.run(args, cwd=ROOT, text=True, capture_output=True, timeout=20)
|
||||
if result.returncode:
|
||||
raise Failure("metrics command failed: " + args[0])
|
||||
try:
|
||||
return json.loads(result.stdout)
|
||||
except ValueError:
|
||||
raise Failure("metrics command returned invalid JSON") from None
|
||||
|
||||
|
||||
def metrics(chat_id):
|
||||
return command_json("docker", "compose", "exec", "-T", "worker",
|
||||
"/app/.venv/bin/python", "-m", "src.pipeline_metrics", chat_id)
|
||||
|
||||
|
||||
def broker_depth():
|
||||
rows = command_json("docker", "compose", "exec", "-T", "broker",
|
||||
"rabbitmqctl", "list_queues", "name", "messages_ready",
|
||||
"messages_unacknowledged", "--formatter", "json")
|
||||
return next(row for row in rows if row["name"] == "attachment.process.v1")
|
||||
|
||||
|
||||
def container_info(service):
|
||||
result = subprocess.run(['docker', 'compose', 'ps', '-q', service], cwd=ROOT,
|
||||
capture_output=True, text=True, timeout=10, check=True)
|
||||
ids = result.stdout.split()
|
||||
check(len(ids) == 1, 'expected exactly one container: ' + service)
|
||||
return command_json('docker', 'inspect', ids[0])[0]
|
||||
|
||||
|
||||
def main():
|
||||
def configure(p):
|
||||
p.add_argument("--run-name", required=True)
|
||||
p.add_argument("--workers", type=int, required=True)
|
||||
p.add_argument("--prefetch", type=int, required=True)
|
||||
p.add_argument("--max-pending", type=int, required=True)
|
||||
p.add_argument("--images", type=int, default=40)
|
||||
p.add_argument("--concurrency", type=int, default=8)
|
||||
p.add_argument("--size", type=int, default=1600)
|
||||
p.add_argument("--max-ready-seconds", type=float, default=180)
|
||||
p.add_argument("--require-backpressure", action="store_true")
|
||||
p.add_argument("--output")
|
||||
args = arguments(__doc__, configure)
|
||||
check(1 <= args.images <= 1000 and 1 <= args.concurrency <= 128, "invalid workload")
|
||||
check(1 <= args.size <= 6000 and 0 < args.max_ready_seconds <= 3600, "invalid size/deadline")
|
||||
check(args.workers > 0 and args.prefetch > 0 and args.max_pending > 0, "invalid profile")
|
||||
from PIL import Image
|
||||
# Reproducible, nonuniform synthetic image; no real personal data.
|
||||
row = bytes(v for x in range(args.size) for v in ((x * 13) % 256, (x * 37) % 256, (x * 71) % 256))
|
||||
image = Image.frombytes("RGB", (args.size, args.size), row * args.size)
|
||||
stream = BytesIO()
|
||||
image.save(stream, "PNG")
|
||||
data = stream.getvalue()
|
||||
client = Client(args.base_url, args.ca_file, timeout=30)
|
||||
alice, bob, _, chat = client.bootstrap()
|
||||
baseline = metrics(chat["id"])
|
||||
check(baseline["concurrency"] == args.workers and baseline["prefetch"] == args.prefetch,
|
||||
"worker settings do not match requested profile")
|
||||
check(baseline["pending"] == 0, "use an idle isolated stack")
|
||||
for service in ("api-a", "api-b"):
|
||||
env = dict(item.split('=', 1) for item in container_info(service)['Config']['Env'])
|
||||
check(int(env['MAX_PENDING_JOBS']) == args.max_pending,
|
||||
'running API MAX_PENDING_JOBS does not match profile')
|
||||
resources = container_info('worker')['HostConfig']
|
||||
path = "/api/v1/chats/" + chat["id"] + "/attachments?filename=track1.png"
|
||||
pending, records, samples, errors = {}, [], [], []
|
||||
lock, finished = threading.Lock(), threading.Event()
|
||||
started = time.monotonic()
|
||||
def observe():
|
||||
local = Client(args.base_url, args.ca_file, timeout=5)
|
||||
while not finished.wait(.1):
|
||||
with lock:
|
||||
batch = list(pending.items())
|
||||
for key, record in batch:
|
||||
if finished.is_set():
|
||||
break
|
||||
try:
|
||||
att = local.call("GET", "/api/v1/attachments/" + key, actor=bob, schema="Attachment")["json"]
|
||||
if att["status"] in ("ready", "failed"):
|
||||
with lock:
|
||||
record["terminal"] = att["status"]
|
||||
record["terminal_at"] = time.monotonic()
|
||||
pending.pop(key, None)
|
||||
except Failure:
|
||||
continue
|
||||
def sample():
|
||||
while not finished.is_set():
|
||||
try:
|
||||
sample = metrics(chat["id"])
|
||||
sample["queue"] = broker_depth()
|
||||
sample["seconds"] = time.monotonic() - started
|
||||
with lock:
|
||||
samples.append(sample)
|
||||
except (Failure, OSError, subprocess.TimeoutExpired) as exc:
|
||||
with lock:
|
||||
errors.append(type(exc).__name__)
|
||||
if finished.wait(1):
|
||||
break
|
||||
observer = threading.Thread(target=observe, daemon=True)
|
||||
sampler = threading.Thread(target=sample, daemon=True)
|
||||
observer.start()
|
||||
sampler.start()
|
||||
def upload(index):
|
||||
local = Client(args.base_url, args.ca_file, timeout=30)
|
||||
before = time.monotonic()
|
||||
try:
|
||||
response = local.call("POST", path, (202, 429), actor=alice, raw=data,
|
||||
headers={"Content-Type": "image/png"}, schema="Attachment")
|
||||
received = time.monotonic()
|
||||
record = {"index": index, "status": response["status"], "upload_seconds": received - before}
|
||||
if response["status"] == 202:
|
||||
record.update(id=response["json"]["id"], accepted_at=received)
|
||||
with lock:
|
||||
records.append(record)
|
||||
if response["status"] == 202:
|
||||
pending[record["id"]] = record
|
||||
except Failure:
|
||||
with lock:
|
||||
records.append({"index": index, "status": "transport_or_http_error"})
|
||||
try:
|
||||
with ThreadPoolExecutor(max_workers=args.concurrency) as pool:
|
||||
list(pool.map(upload, range(args.images)))
|
||||
upload_finished = time.monotonic()
|
||||
deadline = upload_finished + args.max_ready_seconds
|
||||
while time.monotonic() < deadline:
|
||||
with lock:
|
||||
empty = not pending
|
||||
if empty:
|
||||
break
|
||||
time.sleep(.1)
|
||||
finally:
|
||||
measured_end = time.monotonic()
|
||||
finished.set()
|
||||
observer.join(timeout=10)
|
||||
sampler.join(timeout=45)
|
||||
elapsed = measured_end - started
|
||||
final = metrics(chat["id"])
|
||||
queue = broker_depth()
|
||||
for _ in range(20):
|
||||
if queue["messages_ready"] == 0 and queue["messages_unacknowledged"] == 0:
|
||||
break
|
||||
time.sleep(.25)
|
||||
queue = broker_depth()
|
||||
accepted = [r for r in records if r["status"] == 202]
|
||||
ready = [r for r in accepted if r.get("terminal") == "ready"]
|
||||
latencies = [r["terminal_at"] - r["accepted_at"] for r in ready]
|
||||
waits = [r["queue_wait_seconds"] for r in final["jobs"] if r["queue_wait_seconds"] is not None]
|
||||
drained = (bool(accepted) and len(ready) == len(accepted) and final["pending"] == 0
|
||||
and queue["messages_ready"] == 0 and queue["messages_unacknowledged"] == 0)
|
||||
recovery = False
|
||||
if drained:
|
||||
try:
|
||||
att, _ = client.attachment(alice, chat)
|
||||
client.wait_ready(bob, att, wait_seconds=args.max_ready_seconds)
|
||||
recovery = True
|
||||
except Failure:
|
||||
pass
|
||||
rejected = sum(r["status"] == 429 for r in records)
|
||||
report = {
|
||||
"run_name": args.run_name,
|
||||
"settings": {"workers": baseline["concurrency"], "prefetch": baseline["prefetch"],
|
||||
"max_pending": args.max_pending,
|
||||
"worker_limits": {key: resources[key] for key in ('Memory', 'NanoCpus')}},
|
||||
"workload": {"images": args.images, "concurrency": args.concurrency,
|
||||
"size": args.size, "bytes": len(data), "type": "closed-loop burst"},
|
||||
"results": {"accepted": len(accepted), "rejected_429": rejected, "ready": len(ready),
|
||||
"failed": sum(r.get("terminal") == "failed" for r in accepted),
|
||||
"timed_out": len(pending), "elapsed_seconds": elapsed,
|
||||
"ready_per_second": len(ready) / elapsed,
|
||||
"ready_latency_ms": {str(p): percentile(latencies, p) for p in (.5, .95, .99)},
|
||||
"queue_wait_ms": {str(p): percentile(waits, p) for p in (.5, .95, .99)},
|
||||
"max_sampled_rss_bytes": max((s["rss_bytes"] for s in samples), default=None),
|
||||
"max_sampled_pending": max((s["pending"] for s in samples), default=None),
|
||||
"sample_count": len(samples),
|
||||
"drained": drained, "recovery_upload_ready": recovery},
|
||||
"records": [{k: v for k, v in r.items() if k not in ("accepted_at", "terminal_at")} |
|
||||
({"ready_seconds": r["terminal_at"] - r["accepted_at"]} if "terminal_at" in r else {})
|
||||
for r in records],
|
||||
"samples": samples, "metric_errors": errors,
|
||||
"limitations": "Closed-loop; ready time is polling upper bound. RSS is sum of worker/container processes, shared pages may be counted twice. Sampling may miss peaks. Queue wait is first claim minus durable job creation.",
|
||||
}
|
||||
target = Path(args.output or ROOT / "evidence" / (args.run_name + ".json"))
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_text(json.dumps(report, indent=2) + "\n")
|
||||
print(json.dumps(report["results"], indent=2))
|
||||
check(not errors and bool(samples), "incomplete metrics; result saved but not valid evidence")
|
||||
check(all(s['pending'] <= args.max_pending for s in samples), "admission limit exceeded")
|
||||
check(all(r["status"] in (202, 429) for r in records), "unexpected HTTP/transport failures")
|
||||
check(drained and recovery, "pipeline did not drain/recover; see saved result")
|
||||
if args.require_backpressure:
|
||||
check(rejected > 0, "backpressure was not observed")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,27 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Public persistence test plus proof of actual container restarts."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def snapshot():
|
||||
result = {}
|
||||
for service in ('postgres', 's3', 'api-a', 'api-b', 'load_balancer'):
|
||||
container = subprocess.check_output(['docker', 'compose', 'ps', '-q', service], cwd=ROOT, text=True).strip()
|
||||
started = subprocess.check_output(['docker', 'inspect', '--format', '{{.State.StartedAt}}', container], text=True).strip()
|
||||
result[service] = {'container': container[:12], 'started_at': started}
|
||||
return result
|
||||
|
||||
|
||||
before = snapshot()
|
||||
print('Before:', json.dumps(before, sort_keys=True), flush=True)
|
||||
subprocess.run([sys.executable, 'tests/resilience.py', '--mode', 'persistence',
|
||||
'--action-script', 'scripts/restart.sh'], cwd=ROOT, check=True)
|
||||
after = snapshot()
|
||||
print('After:', json.dumps(after, sort_keys=True), flush=True)
|
||||
assert all(before[key]['started_at'] != after[key]['started_at'] for key in before)
|
||||
print('PASS: PostgreSQL, S3, both API replicas and LB actually restarted; volumes preserved')
|
||||
@@ -0,0 +1,48 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Sequential public tests with safe container-state evidence; no credentials."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def states():
|
||||
ids = subprocess.check_output(['docker', 'compose', 'ps', '-aq'], text=True).split()
|
||||
rows = json.loads(subprocess.check_output(['docker', 'inspect', *ids], text=True))
|
||||
return {r['Config']['Labels']['com.docker.compose.service']:
|
||||
{'id': r['Id'][:12], 'started_at': r['State']['StartedAt'], 'status': r['State']['Status']}
|
||||
for r in rows}
|
||||
|
||||
|
||||
def main():
|
||||
results, stopped = [], set()
|
||||
try:
|
||||
for mode in ['persistence'] + ['failover'] * 6:
|
||||
before = states()
|
||||
hook = 'restart' if mode == 'persistence' else 'stop-one'
|
||||
result = subprocess.run([sys.executable, 'tests/resilience.py', '--mode', mode,
|
||||
'--action-script', 'scripts/' + hook + '.sh'],
|
||||
text=True, capture_output=True, timeout=200)
|
||||
after = states()
|
||||
results.append(dict(mode=mode, returncode=result.returncode,
|
||||
output=result.stdout + result.stderr, before=before, after=after))
|
||||
(ROOT / 'evidence/resilience.json').write_text(json.dumps(results, indent=2) + '\n')
|
||||
print(result.stdout + result.stderr, flush=True)
|
||||
assert result.returncode == 0, 'public resilience failed'
|
||||
if mode == 'persistence':
|
||||
for service in ('postgres', 's3', 'broker', 'worker', 'outbox', 'api-a', 'api-b'):
|
||||
assert before[service]['started_at'] != after[service]['started_at'], service
|
||||
else:
|
||||
stopped.update(s for s in ('api-a', 'api-b') if after[s]['status'] == 'exited')
|
||||
subprocess.run(['docker', 'compose', 'up', '-d', '--no-deps', '--wait', 'api-a', 'api-b'], check=True)
|
||||
if len(stopped) == 2:
|
||||
break
|
||||
assert len(stopped) == 2, 'did not exercise both API replicas'
|
||||
finally:
|
||||
subprocess.run(['docker', 'compose', 'up', '-d', '--no-deps', '--wait', 'api-a', 'api-b'], check=True)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -1,19 +1,28 @@
|
||||
# Модель угроз — заполнить
|
||||
# Модель угроз — лабораторная 7
|
||||
|
||||
Статус проверок и оставшиеся ограничения приведены в [отчёте](../REPORT.md); полная проверка всех каналов ещё не завершена.
|
||||
|
||||
## Активы и акторы
|
||||
|
||||
TODO: пользовательские credentials/сессии, сообщения/вложения, service identities, CA/secrets, telemetry. Акторы: участник чата, посторонний пользователь, внешний клиент, скомпрометированный сервис, оператор. Опишите доступ атакующего и границы учебного стенда.
|
||||
Активы: пароли и сессии, сообщения и вложения, ключи CA и сервисные credentials, метаданные и telemetry. Акторы: участник чата, посторонний зарегистрированный пользователь, внешний клиент, скомпрометированный сервис и оператор. Внешний клиент может отправлять произвольные запросы к ingress; пользователь может менять заголовки и идентификаторы в запросах. Компрометация хоста и оператора не рассматривается как выдерживаемый отказ.
|
||||
|
||||
## Границы доверия
|
||||
|
||||
TODO: схема и ссылка на заполненную contracts/trust-matrix.md; публичные/внутренние интерфейсы, процессы, секреты и их выдача.
|
||||
Границы: клиент → ingress, ingress → API, приложения → хранилища и брокер, приложения → Collector, компоненты → OpenBao, оператор → административные интерфейсы. Конкретные endpoint, identity и проверки перечислены в [матрице доверия](../contracts/trust-matrix.md).
|
||||
|
||||
| Угроза и конкретный путь | Нарушаемый инвариант | Контроль | Отрицательный тест | Остаточное ограничение |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| TODO | TODO | TODO | TODO | TODO |
|
||||
| Посторонний пользователь подставляет ID чужого вложения | Доступ только участникам чата | Проверка Bearer и членства для metadata/content и сообщений | Авторизованным посторонним запросить оба endpoint и приложить чужой ID | Не защищает от компрометации участника |
|
||||
| Клиент подменяет заголовок X-User-Id | Идентичность определяется сессией | Игнорировать клиентский X-User-Id | Передать заголовок с ID другого пользователя и проверить отказ | Украденный Bearer остаётся действителен до expiry/logout |
|
||||
| Клиент соединяется с поддельным ingress | Клиент не передаёт секреты чужому серверу | TLS и проверка CA/hostname | Соединение с чужим CA и неверным hostname отклоняется | Компрометированный доверенный CA вне заявленной защиты |
|
||||
| Сервис с чужой identity подключается напрямую к API | Только LB вызывает внутренний API | mTLS и проверка разрешённой identity | `sh scripts/test-internal-mtls.sh`: без сертификата, чужой CA, доверенный CA с неверной identity — отказ | Отзыв и ротация identity под нагрузкой не проверены |
|
||||
| Скомпрометированный worker читает чужой секрет | Каждому сервису доступен только нужный набор секретов | Отдельная identity и scoped policy OpenBao | Запросить разрешённый и чужой путь, попробовать изменить policy | Из разрешённых worker данных возможна утечка |
|
||||
| Автоматические попытки входа перегружают KDF | Вход ограничен по частоте | Лимит попыток с 429 и Retry-After | Превысить лимит и проверить ответ, затем дождаться окна | Текущий лимит локален процессу и общий для всех клиентов |
|
||||
| Загрузка чрезмерного файла исчерпывает память или диск | Размер и число пикселей ограничены | Потоковый лимит и проверка изображения | Отправить файл свыше лимита и изображение со слишком большим числом пикселей | Лимиты контейнеров проверяются `student-tests/runtime_hardening.py`; устойчивость под произвольной нагрузкой не доказана |
|
||||
| Клиент передаёт секрет в URL, который попадает в access-log | Секреты не сохраняются в наблюдаемости | Ingress пишет только статус, размер и служебные поля; API пишет шаблон маршрута | `student-tests/ingress_redaction.py`: маркеры в path/query/headers отсутствуют в реальных логах | Тест не доказывает отсутствие всех каналов утечки |
|
||||
|
||||
На 4 минимум 6 конкретных угроз. Не заменяйте сценарии словами «SQL injection», «безопасный Docker», «mTLS включён» без пути и проверки.
|
||||
|
||||
## Lifecycle и инциденты
|
||||
|
||||
TODO: bootstrap, expiry/renewal, revoke/rotation, компрометация identity, sealed OpenBao и восстановление. Указать владельца CA/unseal и способ защиты bootstrap credentials. Сопоставить scan findings с реальной применимостью и исправлением/остаточным риском.
|
||||
Владелец CA и unseal — оператор стенда; bootstrap и поведение при sealed OpenBao описаны в [отчёте](../REPORT.md). Сертификаты действуют 90 дней, CA — 365 дней; автоматический renewal и отзыв не реализованы. Сканирование и разбор результатов не проводились.
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
import asyncio
|
||||
from hashlib import sha256
|
||||
import os
|
||||
from tempfile import TemporaryFile
|
||||
import unicodedata
|
||||
from uuid import UUID, uuid4
|
||||
import warnings
|
||||
|
||||
from fastapi import APIRouter, Depends, Query, Request, Response
|
||||
from PIL import Image, UnidentifiedImageError
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
from starlette.requests import ClientDisconnect
|
||||
|
||||
from .errors import ApiError
|
||||
from .models import Attachment
|
||||
from .routes import get_current_user, get_store
|
||||
from .storage.postgres import PostgresStore
|
||||
|
||||
router = APIRouter()
|
||||
Image.MAX_IMAGE_PIXELS = 40000000
|
||||
warnings.filterwarnings("error", category=Image.DecompressionBombWarning)
|
||||
|
||||
|
||||
def inspect_image(file, content_type, max_pixels):
|
||||
try:
|
||||
file.seek(0)
|
||||
with Image.open(file, formats=("PNG", "JPEG")) as image:
|
||||
if image.width * image.height > max_pixels:
|
||||
raise ApiError(413, "payload_too_large", "Слишком много пикселей")
|
||||
actual = {"PNG": "image/png", "JPEG": "image/jpeg"}[image.format]
|
||||
if actual != content_type or getattr(image, "n_frames", 1) != 1:
|
||||
raise ApiError(415, "unsupported_media_type", "Нужен обычный PNG или JPEG")
|
||||
image.verify()
|
||||
# verify checks PNG CRC; load also catches truncated pixel streams/JPEGs.
|
||||
file.seek(0)
|
||||
with Image.open(file, formats=("PNG", "JPEG")) as image:
|
||||
image.load()
|
||||
except (Image.DecompressionBombError, Image.DecompressionBombWarning) as error:
|
||||
raise ApiError(413, "payload_too_large", "Слишком много пикселей") from error
|
||||
except (UnidentifiedImageError, OSError, ValueError, SyntaxError) as error:
|
||||
raise ApiError(415, "unsupported_media_type", "Повреждённое изображение") from error
|
||||
file.seek(0)
|
||||
|
||||
|
||||
@router.post("/api/v1/chats/{chat_id}/attachments", response_model=Attachment, status_code=202)
|
||||
async def upload(chat_id: UUID, request: Request, filename: str = Query(...),
|
||||
user: dict = Depends(get_current_user), store: PostgresStore = Depends(get_store)):
|
||||
await store.get_chat_for_member(chat_id, user["id"])
|
||||
if (not 1 <= len(filename) <= 255 or not filename.strip() or
|
||||
any(c in "/\\" or unicodedata.category(c) in {"Cc", "Cs"} for c in filename)):
|
||||
raise ApiError(400, "invalid_request", "Некорректное имя файла")
|
||||
content_type = request.headers.get("content-type", "").lower()
|
||||
if content_type not in {"image/png", "image/jpeg"}:
|
||||
raise ApiError(415, "unsupported_media_type", "Нужен PNG или JPEG")
|
||||
s3 = request.app.state.s3
|
||||
limit = s3.settings.max_bytes
|
||||
if "content-length" in request.headers:
|
||||
try:
|
||||
length = int(request.headers["content-length"])
|
||||
if length < 0:
|
||||
raise ValueError()
|
||||
except ValueError:
|
||||
raise ApiError(400, "invalid_request", "Некорректная длина") from None
|
||||
if length > limit:
|
||||
raise ApiError(413, "payload_too_large", "Файл больше лимита")
|
||||
try:
|
||||
timeout = int(os.environ.get("UPLOAD_TIMEOUT_SECONDS", "30"))
|
||||
if not 1 <= timeout <= 120:
|
||||
raise ApiError(503, "unavailable", "Некорректный лимит времени загрузки")
|
||||
async with asyncio.timeout(timeout):
|
||||
async with request.app.state.upload_slot:
|
||||
# Temporary scratch space only; deleted on every exit, never used for downloads.
|
||||
with TemporaryFile() as file:
|
||||
size = 0
|
||||
digest = sha256()
|
||||
async for chunk in request.stream():
|
||||
size += len(chunk)
|
||||
if size > limit:
|
||||
raise ApiError(413, "payload_too_large", "Файл больше лимита")
|
||||
digest.update(chunk)
|
||||
await run_in_threadpool(file.write, chunk)
|
||||
await run_in_threadpool(inspect_image, file, content_type, s3.settings.max_pixels)
|
||||
attachment_id, job_id = uuid4(), uuid4()
|
||||
key = f"staging/{attachment_id}/original"
|
||||
async with store.attachment_transaction() as connection:
|
||||
try:
|
||||
max_pending = int(os.environ.get("MAX_PENDING_JOBS", "100"))
|
||||
except ValueError as error:
|
||||
raise ApiError(503, "unavailable", "Некорректный лимит очереди") from error
|
||||
if max_pending < 1:
|
||||
raise ApiError(503, "unavailable", "Некорректный лимит очереди")
|
||||
await store.ensure_attachment_queue_capacity(connection, max_pending)
|
||||
await s3.put(key, file, size, content_type)
|
||||
if os.environ.get("UPLOAD_FAULT_AFTER_S3_PUT") == "1":
|
||||
raise ApiError(503, "unavailable", "Инъецирован отказ после S3 PUT")
|
||||
attachment = await store.create_attachment(
|
||||
attachment_id, chat_id, user["id"], filename, content_type,
|
||||
size, digest.hexdigest(), key, job_id, connection=connection,
|
||||
)
|
||||
# Fault-injection for level-4 proof: durable outbox must recover this commit.
|
||||
if os.environ.get("OUTBOX_FAULT_AFTER_COMMIT") == "1":
|
||||
os._exit(70)
|
||||
attachment["variants"] = []
|
||||
return attachment
|
||||
except ClientDisconnect:
|
||||
raise ApiError(400, "invalid_request", "Загрузка прервана") from None
|
||||
except TimeoutError:
|
||||
raise ApiError(503, "unavailable", "Время загрузки истекло") from None
|
||||
|
||||
|
||||
@router.get("/api/v1/attachments/{attachment_id}", response_model=Attachment)
|
||||
async def metadata(attachment_id: UUID, user: dict = Depends(get_current_user),
|
||||
store: PostgresStore = Depends(get_store)):
|
||||
return await store.attachment_for_member(attachment_id, user["id"])
|
||||
|
||||
|
||||
@router.get("/api/v1/attachments/{attachment_id}/content")
|
||||
async def download(attachment_id: UUID, request: Request,
|
||||
variant: str = Query("original", pattern="^(original|thumbnail|crop|optimized)$"),
|
||||
user: dict = Depends(get_current_user), store: PostgresStore = Depends(get_store)):
|
||||
attachment = await store.attachment_for_member(attachment_id, user["id"])
|
||||
if attachment["status"] != "ready":
|
||||
raise ApiError(409, "conflict", "Вложение ещё не готово")
|
||||
if variant == "original":
|
||||
data = await request.app.state.s3.download(attachment)
|
||||
content_type = attachment["content_type"]
|
||||
else:
|
||||
matching = [item for item in attachment["variants"] if item["name"] == variant]
|
||||
if not matching:
|
||||
raise ApiError(404, "not_found", "Вариант не найден")
|
||||
item = matching[0]
|
||||
object_key = await store.pool.fetchval(
|
||||
'SELECT object_key FROM attachment_variants WHERE attachment_id=$1 AND pipeline_version=$2 AND name=$3',
|
||||
attachment_id, attachment['pipeline_version'], variant,
|
||||
)
|
||||
data = await request.app.state.s3.download_key(
|
||||
object_key, item["size_bytes"], item["sha256"]
|
||||
)
|
||||
content_type = item["content_type"]
|
||||
return Response(data, media_type=content_type,
|
||||
headers={"X-Content-Type-Options": "nosniff", "Cache-Control": "private, no-store"})
|
||||
@@ -0,0 +1,37 @@
|
||||
"""Obtain scoped service configuration using a certificate identity in OpenBao."""
|
||||
import json
|
||||
import os
|
||||
import ssl
|
||||
import sys
|
||||
import urllib.request
|
||||
|
||||
|
||||
def main():
|
||||
role = os.environ['BAO_SERVICE_ROLE']
|
||||
if role not in {'api', 'worker'}:
|
||||
raise ValueError('unsupported service identity')
|
||||
base = os.environ.get('BAO_ADDR', 'https://openbao:8200').rstrip('/')
|
||||
context = ssl.create_default_context(cafile=os.environ['BAO_CACERT'])
|
||||
context.load_cert_chain(os.environ['BAO_CLIENT_CERT'])
|
||||
login = urllib.request.Request(base + '/v1/auth/cert/login',
|
||||
data=json.dumps({'name': role}).encode(),
|
||||
headers={'Content-Type': 'application/json'}, method='POST')
|
||||
with urllib.request.urlopen(login, context=context, timeout=5) as response:
|
||||
token = json.load(response)['auth']['client_token']
|
||||
request = urllib.request.Request(base + '/v1/lab/data/' + role,
|
||||
headers={'X-Vault-Token': token})
|
||||
with urllib.request.urlopen(request, context=context, timeout=5) as response:
|
||||
values = json.load(response)['data']['data']
|
||||
allowed = {'DATABASE_URL', 'CURSOR_SECRET', 'S3_ACCESS_KEY_ID', 'S3_SECRET_ACCESS_KEY', 'BROKER_URL'}
|
||||
if set(values) != allowed or not all(isinstance(v, str) and v for v in values.values()):
|
||||
raise ValueError('invalid service configuration from OpenBao')
|
||||
for key, value in values.items():
|
||||
os.environ.pop(key + '_FILE', None)
|
||||
os.environ[key] = value
|
||||
if len(sys.argv) < 2:
|
||||
raise SystemExit('missing command')
|
||||
os.execv(sys.argv[1], sys.argv[1:])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,51 @@
|
||||
"""Idempotent private bucket bootstrap; executed with separate admin credentials."""
|
||||
import time
|
||||
from uuid import uuid4
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
from .storage.s3 import S3Settings, S3Store
|
||||
|
||||
|
||||
def main():
|
||||
store = S3Store(S3Settings.load())
|
||||
try:
|
||||
for attempt in range(60):
|
||||
try:
|
||||
store.client.list_buckets()
|
||||
break
|
||||
except (BotoCoreError, ClientError):
|
||||
if attempt == 59:
|
||||
raise RuntimeError("S3 startup timed out") from None
|
||||
time.sleep(1)
|
||||
bucket = store.settings.bucket
|
||||
try:
|
||||
store.client.head_bucket(Bucket=bucket)
|
||||
except ClientError as error:
|
||||
if str(error.response["Error"]["Code"]) not in {"404", "NoSuchBucket", "NotFound"}:
|
||||
raise
|
||||
store.client.create_bucket(Bucket=bucket)
|
||||
# No anonymous identity; revoke any previously configured public grants/policy.
|
||||
store.client.put_bucket_acl(Bucket=bucket, ACL="private")
|
||||
try:
|
||||
store.client.delete_bucket_policy(Bucket=bucket)
|
||||
except ClientError as error:
|
||||
if error.response["Error"]["Code"] != "NoSuchBucketPolicy":
|
||||
raise
|
||||
# The master health endpoint can become available before a volume accepts
|
||||
# writes after a restart. Verify the actual data path before APIs start.
|
||||
probe_key = f"_bootstrap/write-probe-{uuid4()}"
|
||||
for attempt in range(30):
|
||||
try:
|
||||
store.client.put_object(Bucket=bucket, Key=probe_key, Body=b"ready")
|
||||
store.client.delete_object(Bucket=bucket, Key=probe_key)
|
||||
break
|
||||
except (BotoCoreError, ClientError):
|
||||
if attempt == 29:
|
||||
raise RuntimeError("S3 write path startup timed out") from None
|
||||
time.sleep(1)
|
||||
print("PASS: private S3 bucket ready")
|
||||
finally:
|
||||
store.client.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,97 @@
|
||||
"""Small durable RabbitMQ adapter; broker messages contain no attachment bytes."""
|
||||
import json
|
||||
import os
|
||||
import ssl
|
||||
from pathlib import Path
|
||||
|
||||
import pika
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
|
||||
from .errors import ApiError
|
||||
from . import telemetry as tel
|
||||
|
||||
QUEUE = "attachment.process.v1"
|
||||
DLQ = "attachment.process.v1.dlq"
|
||||
|
||||
|
||||
def broker_url() -> str:
|
||||
path = os.environ.get("BROKER_URL_FILE")
|
||||
value = Path(path).read_text(encoding="utf-8").strip() if path else os.environ.get("BROKER_URL", "")
|
||||
if not value.startswith("amqps://"):
|
||||
raise ValueError("BROKER_URL или BROKER_URL_FILE должен содержать AMQPS URL")
|
||||
return value
|
||||
|
||||
|
||||
def _connection() -> pika.BlockingConnection:
|
||||
url = broker_url()
|
||||
parameters = pika.URLParameters(url)
|
||||
ca_file = os.environ.get("BROKER_CA_FILE")
|
||||
if not ca_file:
|
||||
raise ValueError("BROKER_CA_FILE is required for verified broker TLS")
|
||||
parameters.ssl_options = pika.SSLOptions(ssl.create_default_context(cafile=ca_file), parameters.host)
|
||||
connection = pika.BlockingConnection(parameters)
|
||||
channel = connection.channel()
|
||||
channel.queue_declare(queue=QUEUE, durable=True)
|
||||
channel.queue_declare(queue=DLQ, durable=True)
|
||||
return connection
|
||||
|
||||
|
||||
def _publish(payload: dict, headers: dict | None = None) -> None:
|
||||
connection = _connection()
|
||||
try:
|
||||
channel = connection.channel()
|
||||
channel.confirm_delivery()
|
||||
channel.basic_publish(
|
||||
exchange="", routing_key=QUEUE,
|
||||
body=json.dumps(payload, separators=(",", ":")).encode("utf-8"),
|
||||
properties=pika.BasicProperties(delivery_mode=pika.DeliveryMode.Persistent, content_type="application/json", headers=headers),
|
||||
mandatory=True,
|
||||
)
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
|
||||
async def publish(payload: dict, context=None) -> None:
|
||||
try:
|
||||
with tel.tracer.start_as_current_span("attachment.publish", context=tel.extract(context), kind=tel.SpanKind.PRODUCER, record_exception=False, set_status_on_exception=False) as span:
|
||||
span.set_attribute("messaging.retry.attempt", int(payload.get("attempt", 1)))
|
||||
try:
|
||||
await run_in_threadpool(_publish, payload, tel.carrier())
|
||||
except Exception:
|
||||
span.set_status(tel.Status(tel.StatusCode.ERROR))
|
||||
raise
|
||||
except (pika.exceptions.AMQPError, OSError, ValueError) as error:
|
||||
raise ApiError(503, "unavailable", "Брокер недоступен") from error
|
||||
|
||||
|
||||
async def publish_dlq(payload: dict) -> None:
|
||||
payload = {**payload, "failure": payload.get('failure', 'retry_exhausted')}
|
||||
try:
|
||||
await run_in_threadpool(_publish_to, DLQ, payload)
|
||||
except (pika.exceptions.AMQPError, OSError, ValueError) as error:
|
||||
raise RuntimeError("DLQ is unavailable") from error
|
||||
|
||||
|
||||
def _publish_to(queue: str, payload: dict) -> None:
|
||||
connection = _connection()
|
||||
try:
|
||||
channel = connection.channel()
|
||||
channel.confirm_delivery()
|
||||
channel.basic_publish(
|
||||
exchange="", routing_key=queue, body=json.dumps(payload, separators=(",", ":")).encode("utf-8"),
|
||||
properties=pika.BasicProperties(delivery_mode=pika.DeliveryMode.Persistent, content_type="application/json"),
|
||||
mandatory=True,
|
||||
)
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
|
||||
async def ready() -> None:
|
||||
connection = None
|
||||
try:
|
||||
connection = await run_in_threadpool(_connection)
|
||||
except (pika.exceptions.AMQPError, OSError, ValueError) as error:
|
||||
raise ApiError(503, "unavailable", "Брокер недоступен") from error
|
||||
finally:
|
||||
if connection is not None:
|
||||
await run_in_threadpool(connection.close)
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
from dataclasses import dataclass
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
_CONFIGURATION_KEYS = {
|
||||
"APP_HOST",
|
||||
"APP_PORT",
|
||||
"APP_ENV",
|
||||
"DATABASE_URL",
|
||||
"DATABASE_URL_FILE",
|
||||
"SESSION_TTL_SECONDS",
|
||||
"IDEMPOTENCY_TTL_SECONDS",
|
||||
"INSTANCE_ID",
|
||||
"CURSOR_SECRET",
|
||||
"CURSOR_SECRET_FILE",
|
||||
"S3_ENDPOINT", "S3_REGION", "S3_BUCKET",
|
||||
"S3_ACCESS_KEY_ID", "S3_ACCESS_KEY_ID_FILE",
|
||||
"S3_SECRET_ACCESS_KEY", "S3_SECRET_ACCESS_KEY_FILE",
|
||||
"BROKER_URL", "BROKER_URL_FILE",
|
||||
"MAX_UPLOAD_BYTES", "MAX_IMAGE_PIXELS",
|
||||
"UPLOAD_CONCURRENCY", "UPLOAD_TIMEOUT_SECONDS", "UPLOAD_FAULT_AFTER_S3_PUT",
|
||||
"WORKER_CONCURRENCY", "JOB_MAX_ATTEMPTS", "JOB_TIMEOUT_SECONDS", "STAGING_RETENTION_SECONDS",
|
||||
"WORKER_PREFETCH", "MAX_PENDING_JOBS", "RENDER_MEMORY_MB",
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Settings:
|
||||
"""Проверенная конфигурация запуска HTTP-сервера."""
|
||||
|
||||
host: str
|
||||
port: int
|
||||
environment: str
|
||||
database_url: str
|
||||
session_ttl_seconds: int
|
||||
idempotency_ttl_seconds: int
|
||||
instance_id: str
|
||||
cursor_secret: bytes
|
||||
|
||||
|
||||
def load_settings(env_file: Path = ROOT / ".env") -> Settings:
|
||||
"""Читает разрешённые ключи .env, не заменяя явно переданное окружение."""
|
||||
|
||||
if env_file.is_file():
|
||||
for raw_line in env_file.read_text(encoding="utf-8").splitlines():
|
||||
line = raw_line.strip()
|
||||
if not line or line.startswith("#"):
|
||||
continue
|
||||
key, separator, value = line.partition("=")
|
||||
if not separator or key not in _CONFIGURATION_KEYS:
|
||||
continue
|
||||
value = value.strip()
|
||||
if len(value) >= 2 and value[0] == value[-1] and value[0] in {"'", '"'}:
|
||||
value = value[1:-1]
|
||||
os.environ.setdefault(key, value)
|
||||
|
||||
def value(name: str, default: str = "") -> str:
|
||||
return os.environ.get(name, default).strip()
|
||||
|
||||
def number(name: str, default: int) -> int:
|
||||
try:
|
||||
result = int(value(name, str(default)))
|
||||
except ValueError as error:
|
||||
raise ValueError(f"{name} должен быть целым числом") from error
|
||||
if result < 1:
|
||||
raise ValueError(f"{name} должен быть положительным")
|
||||
return result
|
||||
|
||||
def url(name: str, file_name: str, prefixes: tuple[str, ...]) -> str:
|
||||
result = value(name)
|
||||
path = value(file_name)
|
||||
if path:
|
||||
try:
|
||||
result = Path(path).read_text(encoding="utf-8").strip()
|
||||
except OSError as error:
|
||||
raise ValueError(f"{file_name} недоступен") from error
|
||||
if result and not result.startswith(prefixes):
|
||||
raise ValueError(f"{name} содержит неверный URL")
|
||||
return result
|
||||
|
||||
def secret(name: str, file_name: str) -> bytes:
|
||||
result = value(name)
|
||||
path = value(file_name)
|
||||
if path:
|
||||
try:
|
||||
result = Path(path).read_text(encoding="utf-8").strip()
|
||||
except OSError as error:
|
||||
raise ValueError(f"{file_name} недоступен") from error
|
||||
encoded = result.encode("utf-8")
|
||||
if len(encoded) < 32:
|
||||
raise ValueError(f"{name} должен содержать не менее 32 байт")
|
||||
return encoded
|
||||
|
||||
host = value("APP_HOST", "0.0.0.0")
|
||||
environment = value("APP_ENV", "lab")
|
||||
if not host:
|
||||
raise ValueError("APP_HOST не может быть пустым")
|
||||
if not environment:
|
||||
raise ValueError("APP_ENV не может быть пустым")
|
||||
port = number("APP_PORT", 8080)
|
||||
if port > 65535:
|
||||
raise ValueError("APP_PORT должен находиться в диапазоне 1..65535")
|
||||
database_url = url(
|
||||
"DATABASE_URL", "DATABASE_URL_FILE", ("postgresql://", "postgres://")
|
||||
)
|
||||
if not database_url:
|
||||
raise ValueError("Нужен PostgreSQL DATABASE_URL или DATABASE_URL_FILE")
|
||||
instance_id = value("INSTANCE_ID") or os.uname().nodename
|
||||
if not instance_id:
|
||||
raise ValueError("INSTANCE_ID не может быть пустым")
|
||||
idempotency_ttl_seconds = number("IDEMPOTENCY_TTL_SECONDS", 86400)
|
||||
if idempotency_ttl_seconds < 86400:
|
||||
raise ValueError("IDEMPOTENCY_TTL_SECONDS должен быть не менее 86400")
|
||||
return Settings(
|
||||
host=host,
|
||||
port=port,
|
||||
environment=environment,
|
||||
database_url=database_url,
|
||||
session_ttl_seconds=number("SESSION_TTL_SECONDS", 3600),
|
||||
idempotency_ttl_seconds=idempotency_ttl_seconds,
|
||||
instance_id=instance_id,
|
||||
cursor_secret=secret("CURSOR_SECRET", "CURSOR_SECRET_FILE"),
|
||||
)
|
||||
@@ -0,0 +1,81 @@
|
||||
import base64
|
||||
from datetime import UTC, datetime
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
from uuid import UUID
|
||||
|
||||
|
||||
_secret: bytes | None = None
|
||||
|
||||
|
||||
class CursorError(ValueError):
|
||||
"""Недопустимый, повреждённый или применённый не к тому ресурсу курсор."""
|
||||
|
||||
|
||||
def configure_secret(secret: bytes) -> None:
|
||||
"""Устанавливает общий для всех реплик ключ подписи курсоров."""
|
||||
global _secret
|
||||
if len(secret) < 32:
|
||||
raise ValueError("cursor secret must contain at least 32 bytes")
|
||||
_secret = secret
|
||||
|
||||
|
||||
def signing_secret() -> bytes:
|
||||
if _secret is None:
|
||||
raise RuntimeError("cursor secret has not been configured")
|
||||
return _secret
|
||||
|
||||
|
||||
def _encode_bytes(value: bytes) -> str:
|
||||
return base64.urlsafe_b64encode(value).decode().rstrip("=")
|
||||
|
||||
|
||||
def _decode_bytes(value: str) -> bytes:
|
||||
try:
|
||||
return base64.urlsafe_b64decode(value + "=" * (-len(value) % 4))
|
||||
except (ValueError, UnicodeEncodeError) as error:
|
||||
raise CursorError from error
|
||||
|
||||
|
||||
def encode_cursor(scope: str, created_at: datetime, item_id: str) -> str:
|
||||
payload = json.dumps(
|
||||
{
|
||||
"scope": scope,
|
||||
"created_at": created_at.astimezone(UTC)
|
||||
.isoformat()
|
||||
.replace("+00:00", "Z"),
|
||||
"id": item_id,
|
||||
},
|
||||
separators=(",", ":"),
|
||||
sort_keys=True,
|
||||
).encode()
|
||||
signature = hmac.new(signing_secret(), payload, hashlib.sha256).digest()
|
||||
return _encode_bytes(payload) + "." + _encode_bytes(signature)
|
||||
|
||||
|
||||
def decode_cursor(cursor: str, expected_scope: str) -> tuple[datetime, str]:
|
||||
try:
|
||||
encoded_payload, encoded_signature = cursor.split(".")
|
||||
payload = _decode_bytes(encoded_payload)
|
||||
signature = _decode_bytes(encoded_signature)
|
||||
except ValueError as error:
|
||||
raise CursorError from error
|
||||
|
||||
expected_signature = hmac.new(signing_secret(), payload, hashlib.sha256).digest()
|
||||
if not hmac.compare_digest(signature, expected_signature):
|
||||
raise CursorError
|
||||
|
||||
try:
|
||||
data = json.loads(payload)
|
||||
if set(data) != {"scope", "created_at", "id"}:
|
||||
raise CursorError
|
||||
if data["scope"] != expected_scope:
|
||||
raise CursorError
|
||||
item_id = str(UUID(data["id"]))
|
||||
created_at = datetime.fromisoformat(data["created_at"].replace("Z", "+00:00"))
|
||||
if created_at.tzinfo is None:
|
||||
raise CursorError
|
||||
return created_at.astimezone(UTC), item_id
|
||||
except (TypeError, ValueError, KeyError) as error:
|
||||
raise CursorError from error
|
||||
@@ -0,0 +1,12 @@
|
||||
"""Ошибки, которые преобразуются в контрактные HTTP-ответы."""
|
||||
|
||||
|
||||
class ApiError(Exception):
|
||||
|
||||
def __init__(
|
||||
self, status_code: int, code: str, message: str, headers: dict[str, str] | None = None
|
||||
) -> None:
|
||||
self.status_code = status_code
|
||||
self.code = code
|
||||
self.message = message
|
||||
self.headers = headers or {}
|
||||
@@ -0,0 +1,23 @@
|
||||
"""Bounded per-process login attempt limit, using a monotonic clock."""
|
||||
import math
|
||||
import time
|
||||
from collections import deque
|
||||
|
||||
|
||||
class LoginLimiter:
|
||||
def __init__(self, attempts: int = 60, window_seconds: int = 60, clock=time.monotonic):
|
||||
if attempts < 1 or window_seconds < 1:
|
||||
raise ValueError("login limit must be positive")
|
||||
self.attempts = attempts
|
||||
self.window_seconds = window_seconds
|
||||
self.clock = clock
|
||||
self.timestamps = deque()
|
||||
|
||||
def retry_after(self) -> int:
|
||||
now = self.clock()
|
||||
while self.timestamps and self.timestamps[0] <= now - self.window_seconds:
|
||||
self.timestamps.popleft()
|
||||
if len(self.timestamps) >= self.attempts:
|
||||
return max(1, math.ceil(self.timestamps[0] + self.window_seconds - now))
|
||||
self.timestamps.append(now)
|
||||
return 0
|
||||
+207
@@ -0,0 +1,207 @@
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
from contextlib import asynccontextmanager
|
||||
from uuid import uuid4
|
||||
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
import uvicorn
|
||||
from starlette.responses import JSONResponse, Response
|
||||
from starlette.exceptions import HTTPException
|
||||
|
||||
from .errors import ApiError
|
||||
from .cursor import configure_secret
|
||||
from .models import ErrorDetails, ErrorResponse
|
||||
from .config import load_settings
|
||||
from .routes import router
|
||||
from .attachments import router as attachment_router
|
||||
from .storage.s3 import S3Settings, S3Store
|
||||
from .storage.postgres import PostgresStore
|
||||
from . import telemetry as tel
|
||||
from .login_limit import LoginLimiter
|
||||
|
||||
tel.setup("messenger-api")
|
||||
|
||||
|
||||
def logger(name: str) -> logging.Logger:
|
||||
result = logging.getLogger(name)
|
||||
if result.handlers:
|
||||
return result
|
||||
handler = logging.StreamHandler(sys.stdout)
|
||||
handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(name)s %(message)s"))
|
||||
result.addHandler(handler)
|
||||
result.setLevel(logging.INFO)
|
||||
result.propagate = False
|
||||
return result
|
||||
|
||||
|
||||
access_logger = logger("messenger.access")
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(application: FastAPI):
|
||||
settings = load_settings()
|
||||
configure_secret(settings.cursor_secret)
|
||||
store = PostgresStore(settings.database_url)
|
||||
await store.connect()
|
||||
application.state.store = store
|
||||
application.state.settings = settings
|
||||
application.state.login_limiter = LoginLimiter()
|
||||
application.state.s3 = S3Store(S3Settings.load())
|
||||
concurrency = int(os.environ.get("UPLOAD_CONCURRENCY", "1"))
|
||||
if not 1 <= concurrency <= 8:
|
||||
raise ValueError("UPLOAD_CONCURRENCY must be 1..8")
|
||||
application.state.upload_slot = asyncio.Semaphore(concurrency)
|
||||
application.state.accepting_requests = True
|
||||
async def sample_pool():
|
||||
while True:
|
||||
pool = store.pool
|
||||
tel.state.update(pool_used=pool.get_size()-pool.get_idle_size(), pool_capacity=pool.get_max_size(), pool_waiting=len(pool._queue._getters))
|
||||
await asyncio.sleep(1)
|
||||
sampler = asyncio.create_task(sample_pool())
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
sampler.cancel()
|
||||
try:
|
||||
await sampler
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
application.state.accepting_requests = False
|
||||
application.state.s3.client.close()
|
||||
await store.close()
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
title="MTUSI Messenger",
|
||||
version="1.7.0",
|
||||
redoc_url=None,
|
||||
lifespan=lifespan,
|
||||
)
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def add_request_id(request: Request, call_next) -> Response:
|
||||
"""Добавляет ID запроса и пишет безопасную строку access-лога."""
|
||||
|
||||
request.state.request_id = str(uuid4())
|
||||
started_at = time.monotonic()
|
||||
status_code = 500
|
||||
with tel.tracer.start_as_current_span("HTTP request", context=tel.extract(dict(request.headers)), kind=tel.SpanKind.SERVER, record_exception=False, set_status_on_exception=False) as span:
|
||||
try:
|
||||
upload = request.method == "POST" and re.fullmatch(r"/api/v1/chats/[^/]+/attachments", request.url.path)
|
||||
if request.method in {"POST", "PUT", "PATCH"} and not upload:
|
||||
# Buffer only bounded non-upload bodies; upload has its own streaming limit.
|
||||
chunks = []
|
||||
size = 0
|
||||
async for chunk in request.stream():
|
||||
size += len(chunk)
|
||||
if size > 65536:
|
||||
response = error_response(request, 413, "payload_too_large", "Тело запроса слишком велико")
|
||||
break
|
||||
chunks.append(chunk)
|
||||
else:
|
||||
request._body = b"".join(chunks)
|
||||
response = await call_next(request)
|
||||
else:
|
||||
response = await call_next(request)
|
||||
status_code = response.status_code
|
||||
response.headers["X-Request-Id"] = request.state.request_id
|
||||
response.headers["X-Instance-Id"] = request.app.state.settings.instance_id
|
||||
return response
|
||||
finally:
|
||||
route = getattr(request.scope.get("route"), "path", "unmatched")
|
||||
method = tel.http_method(request.method)
|
||||
attrs = {"method": method, "route": route, "status_class": f"{status_code // 100}xx"}
|
||||
span.update_name(f"{method} {route}")
|
||||
span.set_attributes({"http.request.method": method, "http.route": route, "http.response.status_code": status_code})
|
||||
if status_code >= 500:
|
||||
span.set_status(tel.Status(tel.StatusCode.ERROR))
|
||||
tel.http_requests.add(1, attrs)
|
||||
tel.http_duration.record(time.monotonic() - started_at, attrs)
|
||||
tel.log.info("http.request", extra={"request_id": request.state.request_id, "method": method, "route": route, "status": status_code})
|
||||
|
||||
|
||||
def error_response(
|
||||
request: Request, status_code: int, code: str, message: str, headers: dict[str, str] | None = None
|
||||
) -> JSONResponse:
|
||||
request_id = request.state.request_id
|
||||
body = ErrorResponse(
|
||||
error=ErrorDetails(code=code, message=message, request_id=request_id)
|
||||
)
|
||||
# Неожиданная ошибка обрабатывается за пределами HTTP-middleware.
|
||||
# Поэтому её ответ тоже должен сам получить заголовок из контракта.
|
||||
return JSONResponse(
|
||||
status_code=status_code,
|
||||
content=body.model_dump(),
|
||||
headers={
|
||||
"X-Request-Id": request_id,
|
||||
"X-Instance-Id": request.app.state.settings.instance_id,
|
||||
**(headers or {}),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@app.exception_handler(ApiError)
|
||||
async def handle_api_error(request: Request, error: ApiError) -> JSONResponse:
|
||||
"""Преобразует контролируемую ошибку API в стандартный JSON-ответ."""
|
||||
|
||||
return error_response(request, error.status_code, error.code, error.message, error.headers)
|
||||
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def handle_validation_error(
|
||||
request: Request, error: RequestValidationError
|
||||
) -> JSONResponse:
|
||||
"""Преобразует ошибки JSON и Pydantic в обязательный ответ 400."""
|
||||
|
||||
return error_response(request, 400, "invalid_request", "Некорректный запрос")
|
||||
|
||||
|
||||
@app.exception_handler(HTTPException)
|
||||
async def handle_http_error(request: Request, error: HTTPException) -> JSONResponse:
|
||||
"""Включает ошибки декодирования тела, возникающие до Pydantic."""
|
||||
codes = {
|
||||
400: "invalid_request",
|
||||
401: "unauthorized",
|
||||
403: "forbidden",
|
||||
404: "not_found",
|
||||
405: "method_not_allowed",
|
||||
503: "unavailable",
|
||||
}
|
||||
code = codes.get(error.status_code, "internal_error")
|
||||
return error_response(
|
||||
request, error.status_code, code,
|
||||
"Некорректный запрос" if error.status_code < 500 else "Ошибка сервера",
|
||||
error.headers,
|
||||
)
|
||||
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def handle_unexpected_error(request: Request, error: Exception) -> JSONResponse:
|
||||
"""Не раскрывает внутренние детали при непредвиденной ошибке приложения."""
|
||||
|
||||
return error_response(request, 500, "internal_error", "Внутренняя ошибка сервера")
|
||||
|
||||
|
||||
app.include_router(router)
|
||||
app.include_router(attachment_router)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
settings = load_settings()
|
||||
uvicorn.run(
|
||||
app,
|
||||
host=settings.host,
|
||||
port=settings.port,
|
||||
access_log=False,
|
||||
timeout_graceful_shutdown=8,
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,18 @@
|
||||
import asyncio
|
||||
|
||||
from .config import load_settings
|
||||
from .storage.postgres import PostgresStore
|
||||
|
||||
|
||||
async def run() -> None:
|
||||
settings = load_settings()
|
||||
store = PostgresStore(settings.database_url)
|
||||
await store.connect()
|
||||
try:
|
||||
await store.migrate()
|
||||
finally:
|
||||
await store.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(run())
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
from datetime import datetime
|
||||
from uuid import UUID
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
|
||||
|
||||
class CreateUserRequest(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", strict=True)
|
||||
|
||||
username: str = Field(min_length=3, max_length=32, pattern=r"^[a-z0-9_]{3,32}$")
|
||||
display_name: str = Field(min_length=1, max_length=100)
|
||||
password: str = Field(min_length=12, max_length=128)
|
||||
|
||||
@field_validator("display_name")
|
||||
@classmethod
|
||||
def display_name_must_not_be_whitespace(cls, value: str) -> str:
|
||||
"""Не допускает обязательное имя, состоящее только из пробелов."""
|
||||
|
||||
if not value.strip():
|
||||
raise ValueError("display_name не может состоять только из пробелов")
|
||||
return value
|
||||
|
||||
|
||||
class CreateChatRequest(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
title: str = Field(min_length=1, max_length=100)
|
||||
member_ids: list[UUID] = Field(min_length=1, max_length=100)
|
||||
|
||||
@field_validator("title")
|
||||
@classmethod
|
||||
def title_must_not_be_whitespace(cls, value: str) -> str:
|
||||
"""Не допускает обязательное название, состоящее только из пробелов."""
|
||||
|
||||
if not value.strip():
|
||||
raise ValueError("title не может состоять только из пробелов")
|
||||
return value
|
||||
|
||||
|
||||
class ChatPageResponse(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
items: list["Chat"]
|
||||
next_cursor: str | None
|
||||
|
||||
|
||||
class CreateMessageRequest(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", strict=True)
|
||||
|
||||
text: str = Field(max_length=4000)
|
||||
attachment_ids: list[str] = Field(default_factory=list, max_length=10)
|
||||
|
||||
@field_validator("attachment_ids")
|
||||
@classmethod
|
||||
def valid_ids(cls, values: list[str]) -> list[str]:
|
||||
normalized = [str(UUID(value)) for value in values]
|
||||
if len(normalized) != len(set(normalized)):
|
||||
raise ValueError("Повторяющиеся attachment_ids")
|
||||
return normalized
|
||||
|
||||
@model_validator(mode="after")
|
||||
def has_content(self):
|
||||
if not self.text.strip() and not self.attachment_ids:
|
||||
raise ValueError("Сообщение без содержимого")
|
||||
return self
|
||||
|
||||
|
||||
class MessagePageResponse(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
items: list["Message"]
|
||||
next_cursor: str | None
|
||||
|
||||
|
||||
class ErrorDetails(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
code: str
|
||||
message: str
|
||||
request_id: str
|
||||
|
||||
|
||||
class ErrorResponse(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
error: ErrorDetails
|
||||
|
||||
|
||||
class User(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
id: UUID
|
||||
username: str
|
||||
display_name: str
|
||||
created_at: datetime
|
||||
|
||||
|
||||
class Chat(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
id: UUID
|
||||
title: str
|
||||
member_ids: list[UUID]
|
||||
created_at: datetime
|
||||
|
||||
|
||||
class Message(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
id: UUID
|
||||
chat_id: UUID
|
||||
sender_id: UUID
|
||||
text: str
|
||||
attachment_ids: list[UUID] = Field(default_factory=list)
|
||||
created_at: datetime
|
||||
|
||||
|
||||
class Session(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
token: str = Field(min_length=32)
|
||||
token_type: str = "Bearer"
|
||||
expires_at: datetime
|
||||
user: User
|
||||
|
||||
|
||||
class Attachment(BaseModel):
|
||||
model_config = ConfigDict(extra="ignore")
|
||||
|
||||
id: UUID
|
||||
chat_id: UUID
|
||||
owner_id: UUID
|
||||
filename: str
|
||||
content_type: str
|
||||
size_bytes: int
|
||||
sha256: str
|
||||
status: str
|
||||
variants: list["Variant"] = Field(default_factory=list)
|
||||
error_code: str | None = None
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
|
||||
class Variant(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
name: str
|
||||
content_type: str
|
||||
size_bytes: int
|
||||
width: int
|
||||
height: int
|
||||
sha256: str
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Transactional-outbox dispatcher; safe to run as one or more replicas."""
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
import json
|
||||
import time
|
||||
|
||||
from .broker import publish
|
||||
from .config import load_settings
|
||||
from .storage.postgres import PostgresStore
|
||||
from . import telemetry as tel
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s outbox %(message)s")
|
||||
|
||||
|
||||
async def run() -> None:
|
||||
tel.setup("messenger-outbox")
|
||||
settings = load_settings()
|
||||
store = PostgresStore(settings.database_url)
|
||||
await store.connect()
|
||||
interval = max(0.1, float(os.environ.get("OUTBOX_DISPATCH_INTERVAL_SECONDS", "1")))
|
||||
try:
|
||||
while True:
|
||||
try:
|
||||
await store.schedule_due_jobs(int(os.environ.get('JOB_MAX_ATTEMPTS', '5')))
|
||||
for event in await store.due_outbox_events():
|
||||
context = event['trace_context']
|
||||
await publish(event["payload"], json.loads(context) if isinstance(context, str) else context)
|
||||
await store.mark_outbox_published(event["id"])
|
||||
except Exception:
|
||||
logging.exception("outbox dispatch failed; durable event remains pending")
|
||||
try:
|
||||
queue = await store.pool.fetchrow("SELECT count(*) AS depth, COALESCE(EXTRACT(EPOCH FROM now()-min(created_at)), 0)::float8 AS age FROM attachment_jobs WHERE status='queued'")
|
||||
slo = await store.sample_ready_slo()
|
||||
tel.state.update(queue_depth=queue['depth'], queue_age=queue['age'],
|
||||
slo_ready_eligible=slo['eligible'], slo_ready_bad=slo['bad'],
|
||||
slo_unknown=slo['unknown'], queue_sample_time=time.time())
|
||||
except Exception:
|
||||
logging.warning("queue telemetry unavailable")
|
||||
await asyncio.sleep(interval)
|
||||
finally:
|
||||
await store.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(run())
|
||||
@@ -0,0 +1,37 @@
|
||||
"""Operator-only metrics for one synthetic chat; never exposes credentials."""
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
from uuid import UUID
|
||||
from .config import load_settings
|
||||
from .storage.postgres import PostgresStore
|
||||
|
||||
|
||||
async def main(chat):
|
||||
store = PostgresStore(load_settings().database_url)
|
||||
await store.connect()
|
||||
try:
|
||||
rows = await store.pool.fetch('SELECT a.id, a.status, extract(epoch from (j.first_started_at-j.created_at))::float8 AS queue_wait_seconds FROM attachments a JOIN attachment_jobs j ON j.attachment_id=a.id WHERE a.chat_id=$1', chat)
|
||||
jobs = [dict(row, id=str(row['id'])) for row in rows]
|
||||
pending = await store.pool.fetchval("SELECT count(*) FROM attachment_jobs WHERE status IN ('queued','processing')")
|
||||
finally:
|
||||
await store.close()
|
||||
rss = 0
|
||||
for path in Path('/proc').glob('[0-9]*/status'):
|
||||
try:
|
||||
if int(path.parent.name) == os.getpid():
|
||||
continue
|
||||
for line in path.read_text().splitlines():
|
||||
if line.startswith('VmRSS:'):
|
||||
rss += int(line.split()[1]) * 1024
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
print(json.dumps({'jobs': jobs, 'pending': pending, 'rss_bytes': rss,
|
||||
'concurrency': int(os.environ['WORKER_CONCURRENCY']),
|
||||
'prefetch': int(os.environ['WORKER_PREFETCH'])}))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main(UUID(sys.argv[1])))
|
||||
@@ -0,0 +1,41 @@
|
||||
"""Create limited application roles after migrations using operator DB credentials."""
|
||||
import asyncio
|
||||
from pathlib import Path
|
||||
import re
|
||||
import ssl
|
||||
import asyncpg
|
||||
|
||||
|
||||
async def main():
|
||||
secret = lambda name: Path('/run/secrets/' + name).read_text().strip()
|
||||
connection = await asyncpg.connect(secret('database_url'),
|
||||
ssl=ssl.create_default_context(cafile='/run/secrets/ca_cert'))
|
||||
try:
|
||||
for role in ('api', 'worker', 'outbox', 'reconcile'):
|
||||
user = 'messenger_' + role
|
||||
password = secret('database_' + role + '_password')
|
||||
if not re.fullmatch(r'[0-9a-f]{64}', password):
|
||||
raise ValueError('invalid generated password')
|
||||
exists = await connection.fetchval('SELECT 1 FROM pg_roles WHERE rolname=$1', user)
|
||||
if not exists:
|
||||
await connection.execute(f'CREATE ROLE {user} LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION PASSWORD \'{password}\'')
|
||||
await connection.execute(f'GRANT USAGE ON SCHEMA public TO {user}')
|
||||
await connection.execute('REVOKE CREATE ON SCHEMA public FROM PUBLIC')
|
||||
await connection.execute('GRANT SELECT, INSERT ON users, chats, chat_members, messages TO messenger_api')
|
||||
await connection.execute('GRANT SELECT, INSERT, DELETE ON sessions TO messenger_api')
|
||||
await connection.execute('GRANT SELECT, INSERT, UPDATE, DELETE ON idempotency_records TO messenger_api')
|
||||
await connection.execute('GRANT SELECT, INSERT, UPDATE ON attachments, attachment_jobs TO messenger_api')
|
||||
await connection.execute('GRANT SELECT ON attachment_variants TO messenger_api')
|
||||
await connection.execute('GRANT INSERT ON attachment_outbox, attachment_slo TO messenger_api')
|
||||
await connection.execute('GRANT SELECT, UPDATE ON attachments, attachment_jobs, attachment_slo TO messenger_worker')
|
||||
await connection.execute('GRANT SELECT, INSERT, UPDATE ON attachment_variants TO messenger_worker')
|
||||
await connection.execute('GRANT SELECT, UPDATE ON attachments, attachment_jobs, attachment_slo TO messenger_outbox')
|
||||
await connection.execute('GRANT SELECT, INSERT, UPDATE ON attachment_outbox TO messenger_outbox')
|
||||
await connection.execute('GRANT SELECT ON attachments, attachment_variants TO messenger_reconcile')
|
||||
print('Database API and worker roles configured.')
|
||||
finally:
|
||||
await connection.close()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
asyncio.run(main())
|
||||
@@ -0,0 +1,104 @@
|
||||
"""Safely reconcile attachment metadata and original S3 objects.
|
||||
|
||||
The command is dry-run by default. It only deletes unreferenced objects older
|
||||
than a configured grace period; missing objects are reported and never cause a
|
||||
metadata delete. That keeps a delayed PostgreSQL commit and active attachment
|
||||
records safe from a maintenance run.
|
||||
"""
|
||||
import argparse
|
||||
import asyncio
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import json
|
||||
import os
|
||||
from time import perf_counter
|
||||
|
||||
from .config import load_settings
|
||||
from .storage.postgres import PostgresStore
|
||||
from .storage.s3 import S3Settings, S3Store
|
||||
|
||||
|
||||
async def run(args) -> dict:
|
||||
settings = load_settings()
|
||||
db = PostgresStore(settings.database_url)
|
||||
s3 = S3Store(S3Settings.load())
|
||||
try:
|
||||
await db.connect()
|
||||
async with db.attachment_transaction(maintenance=True):
|
||||
return await scan(args, db, s3)
|
||||
finally:
|
||||
s3.client.close()
|
||||
await db.close()
|
||||
|
||||
|
||||
async def scan(args, db, s3) -> dict:
|
||||
# Age is measured at scan start, not after a potentially slow inventory.
|
||||
cutoff = datetime.now(timezone.utc) - timedelta(seconds=args.grace_seconds)
|
||||
started = perf_counter()
|
||||
objects, s3_pages = {}, 0
|
||||
for prefix in ('staging/', 'originals/', 'variants/'):
|
||||
entries, pages = await s3.list_with_pages(prefix)
|
||||
objects.update(entries)
|
||||
s3_pages += pages
|
||||
listed_at = perf_counter()
|
||||
metadata = await db.attachment_keys()
|
||||
metadata_at = perf_counter()
|
||||
orphan = sorted(key for key, modified in objects.items()
|
||||
if key not in metadata and modified <= cutoff)
|
||||
fresh = sorted(key for key, modified in objects.items()
|
||||
if key not in metadata and modified > cutoff)
|
||||
missing = sorted({str(attachment_id): key for key, attachment_id in metadata.items()
|
||||
if key not in objects}.items())
|
||||
deleted = []
|
||||
selected = set(args.object_key) if args.object_key else None
|
||||
if args.apply:
|
||||
for key in orphan:
|
||||
if selected is not None and key not in selected:
|
||||
continue
|
||||
await s3.delete(key)
|
||||
deleted.append(key)
|
||||
finished = perf_counter()
|
||||
return {
|
||||
"mode": "apply" if args.apply else "dry-run",
|
||||
"grace_seconds": args.grace_seconds,
|
||||
"s3_objects": len(objects),
|
||||
"metadata_rows": len(metadata),
|
||||
"orphan_candidates": orphan,
|
||||
"fresh_unreferenced": fresh,
|
||||
"missing_objects": [{"attachment_id": item[0], "object_key": item[1]} for item in missing],
|
||||
"deleted": deleted,
|
||||
"selected_keys": sorted(selected) if selected is not None else None,
|
||||
"scan_metrics": {
|
||||
"s3_list_pages": s3_pages,
|
||||
"s3_list_seconds": round(listed_at - started, 6),
|
||||
"postgres_metadata_seconds": round(metadata_at - listed_at, 6),
|
||||
"total_seconds": round(finished - started, 6),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--apply", action="store_true", help="delete only aged orphan objects")
|
||||
parser.add_argument("--grace-seconds", type=int, default=int(os.environ.get('STAGING_RETENTION_SECONDS', '86400')))
|
||||
parser.add_argument('--loop', action='store_true')
|
||||
parser.add_argument("--object-key", action="append", default=[],
|
||||
help="restrict apply to these exact keys; repeatable, inventory stays complete")
|
||||
args = parser.parse_args()
|
||||
if not 0 <= args.grace_seconds <= 7 * 24 * 3600:
|
||||
parser.error("--grace-seconds must be 0..604800")
|
||||
if any(not key.startswith(('originals/', 'staging/', 'variants/')) for key in args.object_key):
|
||||
parser.error('unsupported object prefix')
|
||||
if args.loop:
|
||||
import time
|
||||
while True:
|
||||
try:
|
||||
print(json.dumps(asyncio.run(run(args)), ensure_ascii=False, sort_keys=True))
|
||||
except Exception:
|
||||
print('cleanup deferred: dependency unavailable', flush=True)
|
||||
time.sleep(60)
|
||||
else:
|
||||
print(json.dumps(asyncio.run(run(args)), ensure_ascii=False, sort_keys=True))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,27 @@
|
||||
"""Isolated image renderer. Parent enforces wall time and kills this process."""
|
||||
import os
|
||||
import pickle
|
||||
import sys
|
||||
|
||||
|
||||
def main():
|
||||
if sys.platform == 'linux':
|
||||
import resource
|
||||
limit = int(os.environ.get('RENDER_MEMORY_MB', '768')) * 1024 * 1024
|
||||
resource.setrlimit(resource.RLIMIT_AS, (limit, limit))
|
||||
from .worker import variants
|
||||
from PIL import UnidentifiedImageError, Image
|
||||
try:
|
||||
data = sys.stdin.buffer.read(10485761)
|
||||
if len(data) > 10485760:
|
||||
raise ValueError('bytes limit')
|
||||
result = variants(data, int(os.environ.get('MAX_IMAGE_PIXELS', '40000000')))
|
||||
pickle.dump(result, sys.stdout.buffer)
|
||||
except MemoryError:
|
||||
sys.exit(21)
|
||||
except (ValueError, OSError, SyntaxError, UnidentifiedImageError, Image.DecompressionBombError):
|
||||
sys.exit(20)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,24 @@
|
||||
"""Operator-only safe replay for a failed attachment job."""
|
||||
import argparse
|
||||
import asyncio
|
||||
from uuid import UUID
|
||||
|
||||
from .config import load_settings
|
||||
from .storage.postgres import PostgresStore
|
||||
|
||||
|
||||
async def run(attachment_id: UUID) -> None:
|
||||
store = PostgresStore(load_settings().database_url)
|
||||
await store.connect()
|
||||
try:
|
||||
if not await store.replay_failed_attachment(attachment_id):
|
||||
raise SystemExit("attachment is not in failed state")
|
||||
finally:
|
||||
await store.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("attachment_id", type=UUID)
|
||||
args = parser.parse_args()
|
||||
asyncio.run(run(args.attachment_id))
|
||||
+188
@@ -0,0 +1,188 @@
|
||||
import base64
|
||||
import re
|
||||
from datetime import datetime
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import APIRouter, Depends, Header, Query, Request, Response
|
||||
|
||||
from .cursor import CursorError, decode_cursor, encode_cursor
|
||||
from .errors import ApiError
|
||||
from .storage.postgres import PostgresStore
|
||||
from .broker import ready as broker_ready
|
||||
from .models import (
|
||||
Chat,
|
||||
ChatPageResponse,
|
||||
CreateChatRequest,
|
||||
CreateMessageRequest,
|
||||
CreateUserRequest,
|
||||
Message,
|
||||
MessagePageResponse,
|
||||
Session,
|
||||
User,
|
||||
)
|
||||
|
||||
router = APIRouter()
|
||||
BEARER_CHALLENGE = {"WWW-Authenticate": 'Bearer realm="messenger"'}
|
||||
BASIC_CHALLENGE = {"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'}
|
||||
IDEMPOTENCY_KEY = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
|
||||
|
||||
def get_store(request: Request) -> PostgresStore:
|
||||
return request.app.state.store
|
||||
|
||||
|
||||
async def get_current_user(
|
||||
authorization: str | None = Header(default=None),
|
||||
store: PostgresStore = Depends(get_store),
|
||||
) -> dict:
|
||||
if authorization is None or not authorization.startswith("Bearer "):
|
||||
raise ApiError(401, "unauthorized", "Требуется Bearer-сессия", BEARER_CHALLENGE)
|
||||
token = authorization[7:]
|
||||
if not token or not token.isascii() or token.strip() != token:
|
||||
raise ApiError(401, "unauthorized", "Требуется Bearer-сессия", BEARER_CHALLENGE)
|
||||
user = await store.user_for_token(token)
|
||||
if user is None:
|
||||
raise ApiError(401, "unauthorized", "Недействительная сессия", BEARER_CHALLENGE)
|
||||
return user
|
||||
|
||||
def parse_basic(authorization: str | None) -> tuple[str, str]:
|
||||
if authorization is None or not authorization.startswith("Basic "):
|
||||
raise ApiError(401, "unauthorized", "Неверные учётные данные", BASIC_CHALLENGE)
|
||||
try:
|
||||
decoded = base64.b64decode(authorization[6:], validate=True)
|
||||
username_bytes, password_bytes = decoded.split(b":", 1)
|
||||
username = username_bytes.decode("ascii")
|
||||
password = password_bytes.decode("utf-8")
|
||||
except (UnicodeDecodeError, ValueError) as error:
|
||||
raise ApiError(401, "unauthorized", "Неверные учётные данные", BASIC_CHALLENGE) from error
|
||||
if not username or not (12 <= len(password) <= 128):
|
||||
raise ApiError(401, "unauthorized", "Неверные учётные данные", BASIC_CHALLENGE)
|
||||
return username, password
|
||||
|
||||
|
||||
def cursor_position(cursor: str | None, scope: str) -> tuple[datetime, UUID] | None:
|
||||
if cursor is None:
|
||||
return None
|
||||
try:
|
||||
created_at, item_id = decode_cursor(cursor, scope)
|
||||
return created_at, UUID(item_id)
|
||||
except (CursorError, ValueError) as error:
|
||||
raise ApiError(400, "invalid_request", "Некорректный cursor") from error
|
||||
|
||||
|
||||
def next_page_cursor(rows: list[dict], limit: int, scope: str) -> str | None:
|
||||
if len(rows) <= limit:
|
||||
return None
|
||||
last = rows[limit - 1]
|
||||
return encode_cursor(scope, last["created_at"], str(last["id"]))
|
||||
|
||||
@router.get("/health/live")
|
||||
async def liveness() -> dict[str, str]:
|
||||
return {"status": "ok"}
|
||||
|
||||
@router.get("/health/ready")
|
||||
async def readiness(request: Request, store: PostgresStore = Depends(get_store)) -> dict[str, str]:
|
||||
if not request.app.state.accepting_requests:
|
||||
raise ApiError(503, "unavailable", "API завершает работу")
|
||||
await store.ready()
|
||||
await request.app.state.s3.ready()
|
||||
await broker_ready()
|
||||
return {"status": "ok"}
|
||||
|
||||
@router.post("/api/v1/users", response_model=User, status_code=201)
|
||||
async def register_user(
|
||||
payload: CreateUserRequest, store: PostgresStore = Depends(get_store)
|
||||
) -> dict:
|
||||
return await store.create_user(payload.username, payload.display_name, payload.password)
|
||||
|
||||
@router.post("/api/v1/auth/sessions", response_model=Session, status_code=201)
|
||||
async def create_session(
|
||||
request: Request,
|
||||
authorization: str | None = Header(default=None),
|
||||
store: PostgresStore = Depends(get_store),
|
||||
) -> dict:
|
||||
retry_after = request.app.state.login_limiter.retry_after()
|
||||
if retry_after:
|
||||
raise ApiError(429, "rate_limited", "Слишком много попыток входа", {"Retry-After": str(retry_after)})
|
||||
if await request.body():
|
||||
raise ApiError(400, "invalid_request", "Тело запроса не требуется")
|
||||
username, password = parse_basic(authorization)
|
||||
user = await store.authenticate(username, password)
|
||||
if user is None:
|
||||
raise ApiError(401, "unauthorized", "Неверные учётные данные", BASIC_CHALLENGE)
|
||||
return await store.create_session(user, request.app.state.settings.session_ttl_seconds)
|
||||
|
||||
@router.delete("/api/v1/auth/sessions/current", status_code=204)
|
||||
async def revoke_session(
|
||||
authorization: str | None = Header(default=None),
|
||||
store: PostgresStore = Depends(get_store),
|
||||
user: dict = Depends(get_current_user),
|
||||
) -> Response:
|
||||
del user
|
||||
await store.revoke_session(authorization[7:])
|
||||
return Response(status_code=204)
|
||||
|
||||
@router.get("/api/v1/users/me", response_model=User)
|
||||
async def current_user(user: dict = Depends(get_current_user)) -> dict:
|
||||
return user
|
||||
|
||||
@router.post("/api/v1/chats", response_model=Chat, status_code=201)
|
||||
async def create_chat(
|
||||
payload: CreateChatRequest,
|
||||
user: dict = Depends(get_current_user),
|
||||
store: PostgresStore = Depends(get_store),
|
||||
) -> dict:
|
||||
return await store.create_chat(user["id"], payload.title, payload.member_ids)
|
||||
|
||||
@router.get("/api/v1/chats", response_model=ChatPageResponse)
|
||||
async def list_chats(
|
||||
user: dict = Depends(get_current_user),
|
||||
store: PostgresStore = Depends(get_store),
|
||||
limit: int = Query(default=50, ge=1, le=100),
|
||||
cursor: str | None = Query(default=None, min_length=1),
|
||||
) -> ChatPageResponse:
|
||||
scope = "chats:" + str(user["id"])
|
||||
rows = await store.list_chats_for_member(user["id"], cursor_position(cursor, scope), limit)
|
||||
page = rows[:limit]
|
||||
return ChatPageResponse(items=page, next_cursor=next_page_cursor(rows, limit, scope))
|
||||
|
||||
@router.get("/api/v1/chats/{chat_id}", response_model=Chat)
|
||||
async def get_chat(
|
||||
chat_id: UUID,
|
||||
user: dict = Depends(get_current_user),
|
||||
store: PostgresStore = Depends(get_store),
|
||||
) -> dict:
|
||||
return await store.get_chat_for_member(chat_id, user["id"])
|
||||
|
||||
@router.post("/api/v1/chats/{chat_id}/messages", response_model=Message, status_code=201)
|
||||
async def create_message(
|
||||
chat_id: UUID,
|
||||
payload: CreateMessageRequest,
|
||||
request: Request,
|
||||
idempotency_key: str | None = Header(default=None, alias="Idempotency-Key"),
|
||||
user: dict = Depends(get_current_user),
|
||||
store: PostgresStore = Depends(get_store),
|
||||
) -> dict:
|
||||
if idempotency_key is None or IDEMPOTENCY_KEY.fullmatch(idempotency_key) is None:
|
||||
raise ApiError(400, "invalid_request", "Некорректный Idempotency-Key")
|
||||
return await store.create_message_idempotent(
|
||||
chat_id,
|
||||
user["id"],
|
||||
payload.text,
|
||||
idempotency_key,
|
||||
request.app.state.settings.idempotency_ttl_seconds,
|
||||
[UUID(value) for value in payload.attachment_ids],
|
||||
)
|
||||
|
||||
@router.get("/api/v1/chats/{chat_id}/messages", response_model=MessagePageResponse)
|
||||
async def list_messages(
|
||||
chat_id: UUID,
|
||||
user: dict = Depends(get_current_user),
|
||||
store: PostgresStore = Depends(get_store),
|
||||
limit: int = Query(default=50, ge=1, le=100),
|
||||
cursor: str | None = Query(default=None, min_length=1),
|
||||
) -> MessagePageResponse:
|
||||
scope = "messages:" + str(chat_id)
|
||||
after = cursor_position(cursor, scope)
|
||||
rows = await store.list_messages_for_member(chat_id, user["id"], after, limit)
|
||||
page = rows[:limit]
|
||||
return MessagePageResponse(items=page, next_cursor=next_page_cursor(rows, limit, scope))
|
||||
@@ -0,0 +1,2 @@
|
||||
"""Слой in-memory хранения для приложения первой лабораторной работы."""
|
||||
"""Persistent storage adapters."""
|
||||
@@ -0,0 +1,600 @@
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from contextlib import asynccontextmanager
|
||||
from hashlib import sha256
|
||||
import json
|
||||
import os
|
||||
import ssl
|
||||
from pathlib import Path
|
||||
from secrets import token_urlsafe
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
import asyncpg
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import InvalidHashError, VerificationError
|
||||
|
||||
from ..errors import ApiError
|
||||
from .. import telemetry as tel
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
MIGRATIONS = ROOT / "migrations"
|
||||
PASSWORD_HASHER = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1)
|
||||
DB_ERRORS = (asyncpg.PostgresError, asyncpg.InterfaceError, OSError, TimeoutError)
|
||||
|
||||
|
||||
class PostgresStore:
|
||||
def __init__(self, database_url: str) -> None:
|
||||
self._database_url = database_url
|
||||
self._pool: asyncpg.Pool | None = None
|
||||
|
||||
async def connect(self) -> None:
|
||||
try:
|
||||
ca_file = os.environ.get("DATABASE_CA_FILE")
|
||||
if not ca_file:
|
||||
raise ValueError("DATABASE_CA_FILE is required for verified PostgreSQL TLS")
|
||||
tls = ssl.create_default_context(cafile=ca_file)
|
||||
self._pool = await asyncpg.create_pool(
|
||||
self._database_url, min_size=1, max_size=10, command_timeout=5, ssl=tls
|
||||
)
|
||||
except DB_ERRORS as error:
|
||||
raise RuntimeError("PostgreSQL is unavailable") from error
|
||||
|
||||
async def close(self) -> None:
|
||||
if self._pool is not None:
|
||||
await self._pool.close()
|
||||
|
||||
@property
|
||||
def pool(self) -> asyncpg.Pool:
|
||||
if self._pool is None:
|
||||
raise RuntimeError("PostgreSQL pool has not been initialized")
|
||||
return self._pool
|
||||
|
||||
async def migrate(self) -> None:
|
||||
async with self.pool.acquire() as connection:
|
||||
await connection.execute(
|
||||
"CREATE TABLE IF NOT EXISTS schema_migrations (version text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now())"
|
||||
)
|
||||
for migration in sorted(MIGRATIONS.glob("*.sql")):
|
||||
applied = await connection.fetchval(
|
||||
"SELECT 1 FROM schema_migrations WHERE version = $1", migration.name
|
||||
)
|
||||
if applied:
|
||||
continue
|
||||
async with connection.transaction():
|
||||
await connection.execute(migration.read_text(encoding="utf-8"))
|
||||
await connection.execute(
|
||||
"INSERT INTO schema_migrations (version) VALUES ($1)", migration.name
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _user(row: asyncpg.Record) -> dict:
|
||||
return {
|
||||
"id": row["id"],
|
||||
"username": row["username"],
|
||||
"display_name": row["display_name"],
|
||||
"created_at": row["created_at"],
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _chat(row: asyncpg.Record) -> dict:
|
||||
return {
|
||||
"id": row["id"],
|
||||
"title": row["title"],
|
||||
"member_ids": row["member_ids"],
|
||||
"created_at": row["created_at"],
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _message(row: asyncpg.Record) -> dict:
|
||||
return {
|
||||
"id": row["id"],
|
||||
"chat_id": row["chat_id"],
|
||||
"sender_id": row["sender_id"],
|
||||
"text": row["text"],
|
||||
"attachment_ids": row["attachment_ids"],
|
||||
"created_at": row["created_at"],
|
||||
}
|
||||
|
||||
async def ready(self) -> None:
|
||||
try:
|
||||
await self.pool.fetchval("SELECT 1")
|
||||
except DB_ERRORS as error:
|
||||
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
|
||||
|
||||
async def create_user(self, username: str, display_name: str, password: str) -> dict:
|
||||
try:
|
||||
row = await self.pool.fetchrow(
|
||||
"INSERT INTO users (id, username, display_name, password_hash) VALUES ($1, $2, $3, $4) RETURNING id, username, display_name, created_at",
|
||||
uuid4(),
|
||||
username,
|
||||
display_name,
|
||||
PASSWORD_HASHER.hash(password),
|
||||
)
|
||||
except asyncpg.UniqueViolationError as error:
|
||||
raise ApiError(409, "conflict", "Username уже занят") from error
|
||||
except DB_ERRORS as error:
|
||||
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
|
||||
return self._user(row)
|
||||
|
||||
async def authenticate(self, username: str, password: str) -> dict | None:
|
||||
try:
|
||||
row = await self.pool.fetchrow(
|
||||
"SELECT id, username, display_name, created_at, password_hash FROM users WHERE username = $1",
|
||||
username,
|
||||
)
|
||||
except DB_ERRORS as error:
|
||||
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
|
||||
if row is None:
|
||||
return None
|
||||
try:
|
||||
valid = PASSWORD_HASHER.verify(row["password_hash"], password)
|
||||
except (InvalidHashError, VerificationError):
|
||||
valid = False
|
||||
return self._user(row) if valid else None
|
||||
|
||||
async def create_session(self, user: dict, ttl_seconds: int) -> dict:
|
||||
token = token_urlsafe(32)
|
||||
token_hash = sha256(token.encode("ascii")).hexdigest()
|
||||
try:
|
||||
row = await self.pool.fetchrow(
|
||||
"INSERT INTO sessions (token_hash, user_id, expires_at) VALUES ($1, $2, now() + $3 * interval '1 second') RETURNING expires_at",
|
||||
token_hash,
|
||||
user["id"],
|
||||
ttl_seconds,
|
||||
)
|
||||
except DB_ERRORS as error:
|
||||
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
|
||||
return {"token": token, "token_type": "Bearer", "expires_at": row["expires_at"], "user": user}
|
||||
|
||||
async def user_for_token(self, token: str) -> dict | None:
|
||||
if not token.isascii():
|
||||
return None
|
||||
token_hash = sha256(token.encode("ascii")).hexdigest()
|
||||
try:
|
||||
row = await self.pool.fetchrow(
|
||||
"SELECT u.id, u.username, u.display_name, u.created_at FROM sessions s JOIN users u ON u.id = s.user_id WHERE s.token_hash = $1 AND s.expires_at > now()",
|
||||
token_hash,
|
||||
)
|
||||
except DB_ERRORS as error:
|
||||
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
|
||||
return self._user(row) if row else None
|
||||
|
||||
async def revoke_session(self, token: str) -> None:
|
||||
try:
|
||||
await self.pool.execute(
|
||||
"DELETE FROM sessions WHERE token_hash = $1", sha256(token.encode("ascii")).hexdigest()
|
||||
)
|
||||
except DB_ERRORS as error:
|
||||
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
|
||||
|
||||
async def create_chat(self, creator_id: UUID, title: str, member_ids: list[UUID]) -> dict:
|
||||
if len(member_ids) != len(set(member_ids)) or creator_id not in member_ids:
|
||||
raise ApiError(400, "invalid_request", "Некорректный список участников")
|
||||
try:
|
||||
async with self.pool.acquire() as connection, connection.transaction():
|
||||
existing = await connection.fetchval(
|
||||
"SELECT count(*) FROM users WHERE id = ANY($1::uuid[])", member_ids
|
||||
)
|
||||
if existing != len(member_ids):
|
||||
raise ApiError(400, "invalid_request", "Один или несколько участников не существуют")
|
||||
row = await connection.fetchrow(
|
||||
"INSERT INTO chats (id, title) VALUES ($1, $2) RETURNING id, title, created_at",
|
||||
uuid4(),
|
||||
title,
|
||||
)
|
||||
await connection.executemany(
|
||||
"INSERT INTO chat_members (chat_id, user_id) VALUES ($1, $2)",
|
||||
[(row["id"], member_id) for member_id in member_ids],
|
||||
)
|
||||
except DB_ERRORS as error:
|
||||
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
|
||||
return {
|
||||
"id": row["id"],
|
||||
"title": row["title"],
|
||||
"member_ids": member_ids,
|
||||
"created_at": row["created_at"],
|
||||
}
|
||||
|
||||
async def get_chat_for_member(self, chat_id: UUID, user_id: UUID) -> dict:
|
||||
try:
|
||||
row = await self.pool.fetchrow(
|
||||
"SELECT c.id, c.title, c.created_at, array_agg(cm_all.user_id ORDER BY cm_all.user_id) AS member_ids FROM chats c JOIN chat_members mine ON mine.chat_id = c.id AND mine.user_id = $2 JOIN chat_members cm_all ON cm_all.chat_id = c.id WHERE c.id = $1 GROUP BY c.id",
|
||||
chat_id,
|
||||
user_id,
|
||||
)
|
||||
except DB_ERRORS as error:
|
||||
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
|
||||
if row is None:
|
||||
raise ApiError(404, "not_found", "Чат не найден")
|
||||
return self._chat(row)
|
||||
|
||||
async def list_chats_for_member(
|
||||
self, user_id: UUID, after: tuple[datetime, UUID] | None, limit: int
|
||||
) -> list[dict]:
|
||||
query = "SELECT c.id, c.title, c.created_at, array_agg(cm_all.user_id ORDER BY cm_all.user_id) AS member_ids FROM chats c JOIN chat_members mine ON mine.chat_id = c.id AND mine.user_id = $1 JOIN chat_members cm_all ON cm_all.chat_id = c.id"
|
||||
args: list = [user_id]
|
||||
if after is not None:
|
||||
query += " WHERE (c.created_at, c.id) > ($2, $3)"
|
||||
args.extend(after)
|
||||
query += " GROUP BY c.id ORDER BY c.created_at, c.id LIMIT $" + str(len(args) + 1)
|
||||
args.append(limit + 1)
|
||||
try:
|
||||
rows = await self.pool.fetch(query, *args)
|
||||
except DB_ERRORS as error:
|
||||
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
|
||||
return [self._chat(row) for row in rows]
|
||||
|
||||
async def create_message_idempotent(
|
||||
self, chat_id: UUID, sender_id: UUID, text: str, idempotency_key: str, ttl_seconds: int, attachment_ids: list[UUID] | None = None
|
||||
) -> dict:
|
||||
"""Создаёт сообщение и фиксирует результат retry в одной транзакции."""
|
||||
path = f"/api/v1/chats/{chat_id}/messages"
|
||||
attachment_ids = attachment_ids or []
|
||||
# Preserve hashes of text-only requests already accepted by lab3.
|
||||
canonical = {"text": text}
|
||||
if attachment_ids:
|
||||
canonical["attachment_ids"] = [str(value) for value in attachment_ids]
|
||||
request_hash = sha256(
|
||||
json.dumps(canonical, ensure_ascii=False, separators=(",", ":"), sort_keys=True).encode("utf-8")
|
||||
).hexdigest()
|
||||
try:
|
||||
async with self.pool.acquire() as connection, connection.transaction():
|
||||
member = await connection.fetchval(
|
||||
"SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2", chat_id, sender_id
|
||||
)
|
||||
if member is None:
|
||||
raise ApiError(404, "not_found", "Чат не найден")
|
||||
await connection.execute(
|
||||
"DELETE FROM idempotency_records WHERE created_at <= now() - $1 * interval '1 second'", ttl_seconds
|
||||
)
|
||||
if attachment_ids:
|
||||
count = await connection.fetchval(
|
||||
"SELECT count(*) FROM attachments WHERE chat_id = $1 AND id = ANY($2::uuid[])",
|
||||
chat_id, attachment_ids,
|
||||
)
|
||||
if count != len(attachment_ids):
|
||||
raise ApiError(404, "not_found", "Вложение не найдено")
|
||||
failed = await connection.fetchval(
|
||||
"SELECT 1 FROM attachments WHERE id=ANY($1::uuid[]) AND status='failed' LIMIT 1", attachment_ids
|
||||
)
|
||||
if failed:
|
||||
raise ApiError(409, 'conflict', 'Вложение завершилось ошибкой')
|
||||
claimed = await connection.fetchrow(
|
||||
"INSERT INTO idempotency_records (user_id, method, path, idempotency_key, request_hash) "
|
||||
"VALUES ($1, 'POST', $2, $3, $4) ON CONFLICT DO NOTHING RETURNING message_id",
|
||||
sender_id, path, idempotency_key, request_hash,
|
||||
)
|
||||
if claimed is None:
|
||||
recorded = await connection.fetchrow(
|
||||
"SELECT request_hash, message_id FROM idempotency_records "
|
||||
"WHERE user_id = $1 AND method = 'POST' AND path = $2 AND idempotency_key = $3 FOR UPDATE",
|
||||
sender_id, path, idempotency_key,
|
||||
)
|
||||
if recorded is None:
|
||||
raise ApiError(503, "unavailable", "Не удалось получить результат идемпотентного запроса")
|
||||
if recorded["request_hash"] != request_hash:
|
||||
raise ApiError(409, "conflict", "Idempotency-Key использован с другим телом")
|
||||
if recorded["message_id"] is None:
|
||||
raise ApiError(503, "unavailable", "Не удалось получить результат идемпотентного запроса")
|
||||
row = await connection.fetchrow(
|
||||
"SELECT id, chat_id, sender_id, text, attachment_ids, created_at FROM messages WHERE id = $1", recorded["message_id"]
|
||||
)
|
||||
if row is None:
|
||||
raise ApiError(503, "unavailable", "Не удалось получить сохранённое сообщение")
|
||||
return self._message(row)
|
||||
row = await connection.fetchrow(
|
||||
"INSERT INTO messages (id, chat_id, sender_id, text, attachment_ids) VALUES ($1, $2, $3, $4, $5) "
|
||||
"RETURNING id, chat_id, sender_id, text, attachment_ids, created_at",
|
||||
uuid4(), chat_id, sender_id, text, attachment_ids,
|
||||
)
|
||||
await connection.execute(
|
||||
"UPDATE idempotency_records SET message_id = $1 WHERE user_id = $2 AND method = 'POST' "
|
||||
"AND path = $3 AND idempotency_key = $4",
|
||||
row["id"], sender_id, path, idempotency_key,
|
||||
)
|
||||
except DB_ERRORS as error:
|
||||
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
|
||||
return self._message(row)
|
||||
|
||||
async def list_messages_for_member(
|
||||
self, chat_id: UUID, user_id: UUID, after: tuple[datetime, UUID] | None, limit: int
|
||||
) -> list[dict]:
|
||||
await self.get_chat_for_member(chat_id, user_id)
|
||||
query = "SELECT id, chat_id, sender_id, text, attachment_ids, created_at FROM messages WHERE chat_id = $1"
|
||||
args: list = [chat_id]
|
||||
if after is not None:
|
||||
query += " AND (created_at, id) > ($2, $3)"
|
||||
args.extend(after)
|
||||
query += " ORDER BY created_at, id LIMIT $" + str(len(args) + 1)
|
||||
args.append(limit + 1)
|
||||
try:
|
||||
rows = await self.pool.fetch(query, *args)
|
||||
except DB_ERRORS as error:
|
||||
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
|
||||
return [self._message(row) for row in rows]
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def attachment_transaction(self, *, maintenance=False):
|
||||
"""Shared writer / exclusive reconciler lock across all API replicas.
|
||||
|
||||
Writers hold the transaction from before PUT through metadata COMMIT.
|
||||
Maintenance holds the exclusive lock through inventory and deletion.
|
||||
All attachment writers must participate in this protocol.
|
||||
"""
|
||||
try:
|
||||
with tel.tracer.start_as_current_span("postgres.attachment_transaction", kind=tel.SpanKind.CLIENT, record_exception=False, set_status_on_exception=False) as span:
|
||||
try:
|
||||
async with self.pool.acquire() as connection, connection.transaction():
|
||||
await connection.execute("SET LOCAL lock_timeout = '5s'")
|
||||
lock = "pg_advisory_xact_lock" if maintenance else "pg_advisory_xact_lock_shared"
|
||||
await connection.execute(f"SELECT {lock}(41004, 1)")
|
||||
yield connection
|
||||
except Exception:
|
||||
span.set_status(tel.Status(tel.StatusCode.ERROR))
|
||||
raise
|
||||
except DB_ERRORS as error:
|
||||
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
|
||||
|
||||
async def create_attachment(self, attachment_id, chat_id, owner_id, filename,
|
||||
content_type, size_bytes, digest, staging_key, job_id, *, connection=None) -> dict:
|
||||
try:
|
||||
row = await (connection or self.pool).fetchrow(
|
||||
"INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256, staging_key) "
|
||||
"VALUES ($1,$2,$3,$4,$5,$6,$7,$8) RETURNING *",
|
||||
attachment_id, chat_id, owner_id, filename, content_type, size_bytes, digest, staging_key,
|
||||
)
|
||||
await (connection or self.pool).execute(
|
||||
"INSERT INTO attachment_jobs (job_id, attachment_id, trace_context) VALUES ($1, $2, $3::jsonb)", job_id, attachment_id, json.dumps(tel.carrier())
|
||||
)
|
||||
await (connection or self.pool).execute(
|
||||
"INSERT INTO attachment_slo (attachment_id) VALUES ($1)", attachment_id
|
||||
)
|
||||
payload = {
|
||||
"schema_version": 1, "job_id": str(job_id), "type": "attachment.process.v1",
|
||||
"attachment_id": str(attachment_id), "pipeline_version": 1, "attempt": 1,
|
||||
"created_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
|
||||
}
|
||||
await (connection or self.pool).execute(
|
||||
"INSERT INTO attachment_outbox (id, job_id, payload) VALUES ($1, $2, $3::jsonb)",
|
||||
uuid4(), job_id, json.dumps(payload, separators=(",", ":")),
|
||||
)
|
||||
await (connection or self.pool).execute(
|
||||
"UPDATE attachment_jobs SET next_attempt_at = 'infinity' WHERE job_id = $1", job_id
|
||||
)
|
||||
except DB_ERRORS as error:
|
||||
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
|
||||
return dict(row)
|
||||
|
||||
async def ensure_attachment_queue_capacity(self, connection: asyncpg.Connection, maximum: int) -> None:
|
||||
"""Globally serialize admission so replicas cannot over-accept queued work."""
|
||||
try:
|
||||
await connection.execute("SELECT pg_advisory_xact_lock(41005, 1)")
|
||||
pending = await connection.fetchval(
|
||||
"SELECT count(*) FROM attachment_jobs WHERE status IN ('queued', 'processing')"
|
||||
)
|
||||
except DB_ERRORS as error:
|
||||
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
|
||||
if pending >= maximum:
|
||||
raise ApiError(429, "rate_limited", "Очередь обработки заполнена")
|
||||
|
||||
async def attachment_for_member(self, attachment_id: UUID, user_id: UUID) -> dict:
|
||||
try:
|
||||
row = await self.pool.fetchrow(
|
||||
"SELECT a.* FROM attachments a JOIN chat_members m ON m.chat_id = a.chat_id "
|
||||
"WHERE a.id = $1 AND m.user_id = $2", attachment_id, user_id,
|
||||
)
|
||||
except DB_ERRORS as error:
|
||||
raise ApiError(503, "unavailable", "PostgreSQL недоступен") from error
|
||||
if row is None:
|
||||
raise ApiError(404, "not_found", "Вложение не найдено")
|
||||
return await self._attachment_with_variants(row)
|
||||
|
||||
async def _attachment_with_variants(self, row: asyncpg.Record | dict) -> dict:
|
||||
result = dict(row)
|
||||
variants = await self.pool.fetch(
|
||||
"SELECT name, content_type, size_bytes, width, height, sha256 FROM attachment_variants "
|
||||
"WHERE attachment_id = $1 AND pipeline_version = $2 ORDER BY name",
|
||||
result["id"], result["pipeline_version"],
|
||||
)
|
||||
result["variants"] = [dict(item) for item in variants]
|
||||
return result
|
||||
|
||||
async def claim_attachment_job(self, attachment_id: UUID, lease_seconds: int) -> dict | None:
|
||||
try:
|
||||
async with self.pool.acquire() as connection, connection.transaction():
|
||||
row = await connection.fetchrow(
|
||||
"SELECT a.*, j.job_id, j.attempt, j.lease_until, "
|
||||
"(j.next_attempt_at <> 'infinity'::timestamptz AND j.next_attempt_at > now()) AS retry_waiting "
|
||||
"FROM attachments a JOIN attachment_jobs j ON j.attachment_id = a.id "
|
||||
"WHERE a.id = $1 FOR UPDATE", attachment_id
|
||||
)
|
||||
# Only the dispatcher recovers an expired lease and increments
|
||||
# its attempt. Redelivery must not renew it or bypass backoff.
|
||||
if row is None or row["status"] != "queued" or row["retry_waiting"]:
|
||||
return None
|
||||
await connection.execute(
|
||||
"UPDATE attachments SET status = 'processing', processing_started_at = now(), updated_at = now() WHERE id = $1",
|
||||
attachment_id,
|
||||
)
|
||||
await connection.execute(
|
||||
"UPDATE attachment_jobs SET status = 'processing', first_started_at=COALESCE(first_started_at, now()), lease_until = now() + $2 * interval '1 second', updated_at = now() WHERE attachment_id = $1",
|
||||
attachment_id, lease_seconds,
|
||||
)
|
||||
result = dict(row)
|
||||
result['claim_time'] = await connection.fetchval('SELECT processing_started_at FROM attachments WHERE id=$1', attachment_id)
|
||||
return result
|
||||
except DB_ERRORS as error:
|
||||
raise RuntimeError("PostgreSQL is unavailable") from error
|
||||
|
||||
async def complete_attachment_job(self, attachment_id: UUID, original_key: str, variants: list[dict], claim_time) -> bool:
|
||||
try:
|
||||
async with self.pool.acquire() as connection, connection.transaction():
|
||||
valid = await connection.fetchval(
|
||||
"SELECT 1 FROM attachments a JOIN attachment_jobs j ON j.attachment_id=a.id WHERE a.id=$1 AND a.status='processing' AND a.processing_started_at=$2 AND j.lease_until > now() FOR UPDATE", attachment_id, claim_time
|
||||
)
|
||||
if not valid:
|
||||
return False
|
||||
for variant in variants:
|
||||
await connection.execute(
|
||||
"INSERT INTO attachment_variants (attachment_id, pipeline_version, name, object_key, content_type, size_bytes, width, height, sha256) "
|
||||
"VALUES ($1, 1, $2, $3, $4, $5, $6, $7, $8) "
|
||||
"ON CONFLICT (attachment_id, pipeline_version, name) DO UPDATE SET object_key = EXCLUDED.object_key, content_type = EXCLUDED.content_type, size_bytes = EXCLUDED.size_bytes, width = EXCLUDED.width, height = EXCLUDED.height, sha256 = EXCLUDED.sha256",
|
||||
attachment_id, variant["name"], variant["object_key"], variant["content_type"], variant["size_bytes"], variant["width"], variant["height"], variant["sha256"],
|
||||
)
|
||||
await connection.execute(
|
||||
"UPDATE attachments SET status = 'ready', original_key = $2, error_code = NULL, updated_at = now() WHERE id = $1",
|
||||
attachment_id, original_key,
|
||||
)
|
||||
await connection.execute("UPDATE attachment_jobs SET status = 'ready', lease_until = NULL, updated_at = now() WHERE attachment_id = $1", attachment_id)
|
||||
await connection.execute(
|
||||
"UPDATE attachment_slo SET ready_xid=pg_current_xact_id()::xid "
|
||||
"WHERE attachment_id=$1 AND ready_xid IS NULL", attachment_id
|
||||
)
|
||||
return True
|
||||
except DB_ERRORS as error:
|
||||
raise RuntimeError("PostgreSQL is unavailable") from error
|
||||
|
||||
async def ready_seconds(self, attachment_id: UUID):
|
||||
# Both ends are DB commit timestamps, not transaction start or a worker's clock.
|
||||
return await self.pool.fetchval("""
|
||||
SELECT EXTRACT(EPOCH FROM (
|
||||
COALESCE(ready_at, pg_xact_commit_timestamp(ready_xid)) -
|
||||
COALESCE(accepted_at, pg_xact_commit_timestamp(accepted_xid))))::float8
|
||||
FROM attachment_slo WHERE attachment_id=$1
|
||||
""", attachment_id)
|
||||
|
||||
async def sample_ready_slo(self):
|
||||
# Materialize promptly: PostgreSQL does not retain commit timestamps forever.
|
||||
async with self.pool.acquire() as connection, connection.transaction():
|
||||
await connection.execute("""
|
||||
UPDATE attachment_slo SET
|
||||
accepted_at=COALESCE(accepted_at, pg_xact_commit_timestamp(accepted_xid)),
|
||||
ready_at=COALESCE(ready_at, pg_xact_commit_timestamp(ready_xid))
|
||||
WHERE accepted_at IS NULL OR (ready_xid IS NOT NULL AND ready_at IS NULL)
|
||||
""")
|
||||
await connection.execute("""
|
||||
UPDATE attachment_slo SET bad=(ready_at IS NULL OR ready_at>accepted_at+interval '30 seconds')
|
||||
WHERE bad IS NULL AND accepted_at<=now()-interval '30 seconds'
|
||||
AND (ready_xid IS NULL OR ready_at IS NOT NULL)
|
||||
""")
|
||||
return await connection.fetchrow("""
|
||||
SELECT count(bad) AS eligible, count(*) FILTER (WHERE bad) AS bad,
|
||||
count(*) FILTER (WHERE accepted_at IS NULL OR
|
||||
(ready_xid IS NOT NULL AND ready_at IS NULL)) AS unknown
|
||||
FROM attachment_slo
|
||||
""")
|
||||
|
||||
async def retry_attachment_job(self, attachment_id: UUID, max_attempts: int, delay_seconds: float, claim_time, permanent_code=None) -> bool:
|
||||
"""Return true only when a bounded at-least-once retry was recorded."""
|
||||
try:
|
||||
async with self.pool.acquire() as connection, connection.transaction():
|
||||
job = await connection.fetchrow(
|
||||
"SELECT j.attempt FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id WHERE a.id=$1 AND a.status='processing' AND a.processing_started_at=$2 FOR UPDATE", attachment_id, claim_time
|
||||
)
|
||||
if job is None:
|
||||
return False
|
||||
if permanent_code is None and job["attempt"] < max_attempts:
|
||||
await connection.execute(
|
||||
"UPDATE attachment_jobs SET attempt = attempt + 1, status = 'queued', last_error = 'processing_failed', lease_until = NULL, next_attempt_at = now() + $2 * interval '1 second', updated_at = now() WHERE attachment_id = $1",
|
||||
attachment_id, delay_seconds,
|
||||
)
|
||||
await connection.execute(
|
||||
"UPDATE attachments SET status = 'queued', updated_at = now() WHERE id = $1", attachment_id
|
||||
)
|
||||
return True
|
||||
code = permanent_code or 'retry_exhausted'
|
||||
await connection.execute("UPDATE attachments SET status='failed', error_code=$2, updated_at=now() WHERE id=$1", attachment_id, code)
|
||||
await connection.execute("UPDATE attachment_jobs SET status='failed', last_error=$2, lease_until=NULL, updated_at=now() WHERE attachment_id=$1", attachment_id, code)
|
||||
return False
|
||||
except DB_ERRORS as error:
|
||||
raise RuntimeError("PostgreSQL is unavailable") from error
|
||||
|
||||
async def due_outbox_events(self, limit: int = 20) -> list[dict]:
|
||||
try:
|
||||
return [{**dict(row), 'payload': json.loads(row['payload']) if isinstance(row['payload'], str) else row['payload']} for row in await self.pool.fetch(
|
||||
"SELECT o.id, o.payload, j.trace_context FROM attachment_outbox o JOIN attachment_jobs j ON j.job_id=o.job_id WHERE o.published_at IS NULL ORDER BY o.created_at LIMIT $1", limit
|
||||
)]
|
||||
except DB_ERRORS as error:
|
||||
raise RuntimeError("PostgreSQL is unavailable") from error
|
||||
|
||||
async def mark_outbox_published(self, event_id: UUID) -> None:
|
||||
await self.pool.execute("UPDATE attachment_outbox SET published_at = now(), attempts = attempts + 1 WHERE id = $1", event_id)
|
||||
|
||||
async def schedule_due_jobs(self, max_attempts: int = 5) -> None:
|
||||
"""Outbox dispatcher also restores expired leases and scheduled retries."""
|
||||
try:
|
||||
async with self.pool.acquire() as connection, connection.transaction():
|
||||
rows = await connection.fetch(
|
||||
"SELECT job_id, attachment_id, pipeline_version, attempt, status FROM attachment_jobs "
|
||||
"WHERE (status = 'queued' AND (next_attempt_at <= now() OR "
|
||||
"(next_attempt_at = 'infinity'::timestamptz AND updated_at < now() - interval '60 seconds'))) "
|
||||
"OR (status = 'processing' AND lease_until < now()) "
|
||||
"FOR UPDATE SKIP LOCKED"
|
||||
)
|
||||
for row in rows:
|
||||
row = dict(row)
|
||||
if row["status"] == "processing":
|
||||
if row['attempt'] >= max_attempts:
|
||||
await connection.execute("UPDATE attachment_jobs SET status='failed', lease_until=NULL, last_error='retry_exhausted', updated_at=now() WHERE job_id=$1", row['job_id'])
|
||||
await connection.execute("UPDATE attachments SET status='failed', error_code='retry_exhausted', updated_at=now() WHERE id=$1", row['attachment_id'])
|
||||
continue
|
||||
row['attempt'] += 1
|
||||
await connection.execute(
|
||||
"UPDATE attachment_jobs SET status = 'queued', attempt=$2, lease_until = NULL, next_attempt_at = now(), last_error = 'lease_expired', updated_at = now() WHERE job_id = $1", row["job_id"], row['attempt']
|
||||
)
|
||||
await connection.execute("UPDATE attachments SET status = 'queued', updated_at = now() WHERE id = $1", row["attachment_id"])
|
||||
payload = {"schema_version": 1, "job_id": str(row["job_id"]), "type": "attachment.process.v1", "attachment_id": str(row["attachment_id"]), "pipeline_version": row["pipeline_version"], "attempt": row["attempt"], "created_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")}
|
||||
await connection.execute("INSERT INTO attachment_outbox (id, job_id, payload) VALUES ($1, $2, $3::jsonb)", uuid4(), row["job_id"], json.dumps(payload, separators=(",", ":")))
|
||||
# Refresh the watchdog on publication intent, not on claim.
|
||||
# Unclaimed jobs are republished after 60s. At-least-once
|
||||
# duplicates are safe, and a published-but-lost delivery
|
||||
# can no longer strand durable accepted work forever.
|
||||
await connection.execute("UPDATE attachment_jobs SET next_attempt_at = 'infinity', updated_at=now() WHERE job_id = $1", row["job_id"])
|
||||
except DB_ERRORS as error:
|
||||
raise RuntimeError("PostgreSQL is unavailable") from error
|
||||
|
||||
async def replay_failed_attachment(self, attachment_id: UUID) -> bool:
|
||||
"""Explicit operator-only replay; never requeues an already successful job."""
|
||||
try:
|
||||
async with self.pool.acquire() as connection, connection.transaction():
|
||||
job = await connection.fetchrow(
|
||||
"SELECT job_id, status FROM attachment_jobs WHERE attachment_id = $1 FOR UPDATE", attachment_id
|
||||
)
|
||||
if job is None or job["status"] != "failed":
|
||||
return False
|
||||
await connection.execute(
|
||||
"UPDATE attachment_jobs SET status = 'queued', attempt = 1, next_attempt_at = now(), lease_until = NULL, replayed_at = now(), last_error = NULL, updated_at = now() WHERE attachment_id = $1", attachment_id
|
||||
)
|
||||
await connection.execute("UPDATE attachments SET status = 'queued', error_code = NULL, updated_at = now() WHERE id = $1", attachment_id)
|
||||
return True
|
||||
except DB_ERRORS as error:
|
||||
raise RuntimeError("PostgreSQL is unavailable") from error
|
||||
|
||||
async def attachment_keys(self) -> dict[str, UUID]:
|
||||
"""Inventory used only by the maintenance reconciler."""
|
||||
try:
|
||||
rows = await self.pool.fetch("SELECT staging_key AS object_key, id FROM attachments WHERE status <> 'ready' UNION ALL SELECT original_key, id FROM attachments WHERE original_key IS NOT NULL UNION ALL SELECT object_key, attachment_id AS id FROM attachment_variants")
|
||||
except DB_ERRORS as error:
|
||||
raise RuntimeError("PostgreSQL is unavailable") from error
|
||||
return {row["object_key"]: row["id"] for row in rows}
|
||||
|
||||
# Span names describe operations only; never export SQL, parameters, credentials or IDs.
|
||||
def _trace_db(method):
|
||||
from functools import wraps
|
||||
@wraps(method)
|
||||
async def wrapped(*args, **kwargs):
|
||||
with tel.tracer.start_as_current_span('postgres.' + method.__name__, kind=tel.SpanKind.CLIENT,
|
||||
record_exception=False, set_status_on_exception=False) as span:
|
||||
try:
|
||||
return await method(*args, **kwargs)
|
||||
except Exception:
|
||||
span.set_status(tel.Status(tel.StatusCode.ERROR))
|
||||
raise
|
||||
return wrapped
|
||||
|
||||
for _name in ('ready', 'create_user', 'authenticate', 'create_session', 'user_for_token', 'revoke_session',
|
||||
'create_chat', 'get_chat_for_member', 'list_chats_for_member', 'create_message_idempotent',
|
||||
'list_messages_for_member', 'create_attachment', 'attachment_for_member', 'claim_attachment_job',
|
||||
'complete_attachment_job', 'retry_attachment_job'):
|
||||
setattr(PostgresStore, _name, _trace_db(getattr(PostgresStore, _name)))
|
||||
@@ -0,0 +1,126 @@
|
||||
"""Bounded S3 operations; synchronous SDK calls run outside the event loop."""
|
||||
from dataclasses import dataclass
|
||||
from hashlib import sha256
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
|
||||
from ..errors import ApiError
|
||||
from .. import telemetry as tel
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class S3Settings:
|
||||
endpoint: str
|
||||
region: str
|
||||
bucket: str
|
||||
access_key: str
|
||||
secret_key: str
|
||||
max_bytes: int
|
||||
max_pixels: int
|
||||
|
||||
@classmethod
|
||||
def load(cls):
|
||||
def secret(name):
|
||||
path = os.environ.get(name + "_FILE")
|
||||
result = Path(path).read_text().strip() if path else os.environ.get(name, "")
|
||||
if not result:
|
||||
raise ValueError(f"Missing {name}")
|
||||
return result
|
||||
|
||||
max_bytes = int(os.environ.get("MAX_UPLOAD_BYTES", "10485760"))
|
||||
max_pixels = int(os.environ.get("MAX_IMAGE_PIXELS", "40000000"))
|
||||
if not 1 <= max_bytes <= 10485760 or not 1 <= max_pixels <= 40000000:
|
||||
raise ValueError("Image limits exceed contract")
|
||||
endpoint = os.environ.get("S3_ENDPOINT", "https://s3:8333")
|
||||
if not endpoint.startswith("https://") or not os.environ.get("AWS_CA_BUNDLE"):
|
||||
raise ValueError("S3 requires HTTPS and AWS_CA_BUNDLE")
|
||||
return cls(endpoint,
|
||||
os.environ.get("S3_REGION", "us-east-1"),
|
||||
os.environ.get("S3_BUCKET", "messenger-attachments"),
|
||||
secret("S3_ACCESS_KEY_ID"), secret("S3_SECRET_ACCESS_KEY"),
|
||||
max_bytes, max_pixels)
|
||||
|
||||
|
||||
class S3Store:
|
||||
def __init__(self, settings):
|
||||
self.settings = settings
|
||||
self.client = boto3.client(
|
||||
"s3", endpoint_url=settings.endpoint, region_name=settings.region,
|
||||
aws_access_key_id=settings.access_key, aws_secret_access_key=settings.secret_key,
|
||||
config=Config(signature_version="s3v4", connect_timeout=2, read_timeout=5,
|
||||
retries={"total_max_attempts": 1},
|
||||
s3={"addressing_style": "path"},
|
||||
request_checksum_calculation="when_required",
|
||||
response_checksum_validation="when_required"),
|
||||
)
|
||||
|
||||
async def call(self, method, **kwargs):
|
||||
with tel.tracer.start_as_current_span("s3." + method, kind=tel.SpanKind.CLIENT, record_exception=False, set_status_on_exception=False) as span:
|
||||
try:
|
||||
return await run_in_threadpool(getattr(self.client, method), **kwargs)
|
||||
except (BotoCoreError, ClientError, OSError) as error:
|
||||
span.set_status(tel.Status(tel.StatusCode.ERROR))
|
||||
raise ApiError(503, "unavailable", "S3 недоступно") from error
|
||||
|
||||
async def ready(self):
|
||||
await self.call("head_bucket", Bucket=self.settings.bucket)
|
||||
|
||||
async def put(self, key, file, size, content_type):
|
||||
file.seek(0)
|
||||
await self.call("put_object", Bucket=self.settings.bucket, Key=key,
|
||||
Body=file, ContentLength=size, ContentType=content_type)
|
||||
|
||||
async def copy(self, source_key: str, destination_key: str, content_type: str) -> None:
|
||||
await self.call(
|
||||
"copy_object", Bucket=self.settings.bucket, Key=destination_key,
|
||||
CopySource={"Bucket": self.settings.bucket, "Key": source_key},
|
||||
ContentType=content_type, MetadataDirective="REPLACE",
|
||||
)
|
||||
|
||||
async def list(self, prefix: str) -> dict[str, object]:
|
||||
"""Return every object under a controlled prefix, handling S3 pagination."""
|
||||
objects, _ = await self.list_with_pages(prefix)
|
||||
return objects
|
||||
|
||||
async def list_with_pages(self, prefix: str) -> tuple[dict[str, object], int]:
|
||||
"""Return inventory and number of S3 ListObjectsV2 pages consumed."""
|
||||
result: dict[str, object] = {}
|
||||
token = None
|
||||
pages = 0
|
||||
while True:
|
||||
args = {"Bucket": self.settings.bucket, "Prefix": prefix}
|
||||
if token:
|
||||
args["ContinuationToken"] = token
|
||||
page = await self.call("list_objects_v2", **args)
|
||||
pages += 1
|
||||
for item in page.get("Contents", []):
|
||||
result[item["Key"]] = item["LastModified"]
|
||||
if not page.get("IsTruncated"):
|
||||
return result, pages
|
||||
token = page["NextContinuationToken"]
|
||||
|
||||
async def delete(self, key: str) -> None:
|
||||
await self.call("delete_object", Bucket=self.settings.bucket, Key=key)
|
||||
|
||||
async def download(self, attachment):
|
||||
return await self.download_key(attachment["original_key"], attachment["size_bytes"], attachment["sha256"])
|
||||
|
||||
async def download_key(self, key: str, expected_size: int | None = None,
|
||||
expected_sha256: str | None = None) -> bytes:
|
||||
response = await self.call("get_object", Bucket=self.settings.bucket, Key=key)
|
||||
body = response["Body"]
|
||||
try:
|
||||
data = await run_in_threadpool(body.read, self.settings.max_bytes + 1)
|
||||
except (BotoCoreError, OSError) as error:
|
||||
raise ApiError(503, "unavailable", "S3 недоступно") from error
|
||||
finally:
|
||||
body.close()
|
||||
if ((expected_size is not None and len(data) != expected_size) or
|
||||
(expected_sha256 is not None and sha256(data).hexdigest() != expected_sha256)):
|
||||
raise ApiError(503, "unavailable", "Оригинал недоступен")
|
||||
return data
|
||||
@@ -0,0 +1,118 @@
|
||||
"""Bounded OTLP telemetry; only explicitly selected, non-sensitive fields leave the process."""
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import socket
|
||||
import time
|
||||
import resource
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from opentelemetry import metrics, trace
|
||||
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
|
||||
from opentelemetry.trace import SpanKind, Status, StatusCode
|
||||
|
||||
tracer = trace.get_tracer("messenger")
|
||||
meter = metrics.get_meter("messenger")
|
||||
trace_context = TraceContextTextMapPropagator()
|
||||
http_requests = meter.create_counter("messenger.http.requests", unit="{request}")
|
||||
http_duration = meter.create_histogram("messenger.http.duration", unit="s")
|
||||
jobs = meter.create_counter("messenger.jobs", unit="{job}")
|
||||
job_duration = meter.create_histogram("messenger.job.duration", unit="s")
|
||||
ready_duration = meter.create_histogram("messenger.job.ready.duration", unit="s")
|
||||
busy = meter.create_up_down_counter("messenger.worker.busy", unit="{worker}")
|
||||
capacity = meter.create_up_down_counter("messenger.worker.capacity", unit="{worker}")
|
||||
state = {"queue_depth": 0, "queue_age": 0, "pool_used": 0, "pool_capacity": 0, "pool_waiting": 0,
|
||||
"slo_ready_eligible": 0, "slo_ready_bad": 0, "slo_unknown": 0, "queue_sample_time": 0}
|
||||
for name, unit in (("queue_sample_time", "s"), ("slo_unknown", "{job}"), ("queue_depth", "{job}"), ("queue_age", "s"), ("pool_used", "{connection}"), ("pool_capacity", "{connection}"), ("pool_waiting", "{request}")):
|
||||
meter.create_observable_gauge("messenger." + name, callbacks=[lambda options, key=name: [metrics.Observation(state[key], {"queue": "attachment.process.v1"} if key.startswith("queue_") else {})]], unit=unit)
|
||||
for name in ("slo_ready_eligible", "slo_ready_bad"):
|
||||
meter.create_observable_counter("messenger." + name, callbacks=[lambda options, key=name: [metrics.Observation(state[key])]], unit="{job}")
|
||||
|
||||
def process_cpu(options):
|
||||
usage = resource.getrusage(resource.RUSAGE_SELF)
|
||||
return [metrics.Observation(usage.ru_utime + usage.ru_stime)]
|
||||
|
||||
def process_rss(options):
|
||||
try:
|
||||
with open('/proc/self/statm', encoding='ascii') as stream:
|
||||
return [metrics.Observation(int(stream.read().split()[1]) * os.sysconf('SC_PAGE_SIZE'))]
|
||||
except (OSError, ValueError, IndexError):
|
||||
return []
|
||||
|
||||
meter.create_observable_counter("messenger.process.cpu", callbacks=[process_cpu], unit="s")
|
||||
meter.create_observable_gauge("messenger.process.memory", callbacks=[process_rss], unit="By")
|
||||
|
||||
log = logging.getLogger("messenger.telemetry")
|
||||
log.setLevel(logging.INFO)
|
||||
log.propagate = False
|
||||
|
||||
LOG_FIELDS = ("request_id", "method", "route", "status", "outcome")
|
||||
LOG_EVENTS = {"http.request", "job.processed", "telemetry.unavailable"}
|
||||
STANDARD_LOG_FIELDS = frozenset(logging.makeLogRecord({}).__dict__)
|
||||
|
||||
|
||||
def http_method(value):
|
||||
return value if value in {"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS", "CONNECT", "TRACE"} else "_OTHER"
|
||||
|
||||
|
||||
class SafeLogFilter(logging.Filter):
|
||||
"""Sanitize the shared record BEFORE both stdout and OTLP handlers."""
|
||||
def filter(self, record):
|
||||
for key in list(record.__dict__):
|
||||
if key not in STANDARD_LOG_FIELDS and key not in LOG_FIELDS:
|
||||
del record.__dict__[key]
|
||||
record.msg = record.msg if isinstance(record.msg, str) and record.msg in LOG_EVENTS else "telemetry.unavailable"
|
||||
record.args = ()
|
||||
record.exc_info = record.exc_text = record.stack_info = None
|
||||
return True
|
||||
|
||||
|
||||
log.addFilter(SafeLogFilter())
|
||||
|
||||
class JsonFormatter(logging.Formatter):
|
||||
def format(self, record):
|
||||
ctx = trace.get_current_span().get_span_context()
|
||||
obj = {"timestamp": datetime.now(timezone.utc).isoformat(), "severity": record.levelname,
|
||||
"service.name": os.environ.get("OTEL_SERVICE_NAME", "messenger"), "event": record.getMessage()}
|
||||
if ctx.is_valid:
|
||||
obj.update(trace_id=f"{ctx.trace_id:032x}", span_id=f"{ctx.span_id:016x}")
|
||||
for field in LOG_FIELDS:
|
||||
if hasattr(record, field): obj[field] = getattr(record, field)
|
||||
return json.dumps(obj, ensure_ascii=False)
|
||||
|
||||
def setup(service):
|
||||
if os.environ.get("OTEL_ENABLED", "0") != "1":
|
||||
return
|
||||
os.environ["OTEL_SERVICE_NAME"] = service
|
||||
from opentelemetry.sdk.resources import Resource
|
||||
from opentelemetry.sdk.trace import TracerProvider
|
||||
from opentelemetry.sdk.trace.export import BatchSpanProcessor
|
||||
from opentelemetry.sdk.metrics import MeterProvider
|
||||
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
|
||||
from opentelemetry.sdk.metrics.view import View, ExplicitBucketHistogramAggregation
|
||||
from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler
|
||||
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
|
||||
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
|
||||
from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
|
||||
from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
|
||||
resource = Resource.create({"service.name": service, "service.version": "1.6.0", "service.instance.id": socket.gethostname(), "deployment.environment.name": "lab"})
|
||||
provider = TracerProvider(resource=resource)
|
||||
provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter(timeout=2), max_queue_size=2048, max_export_batch_size=256, schedule_delay_millis=1000))
|
||||
trace.set_tracer_provider(provider)
|
||||
buckets = [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60, 120, 300, 600]
|
||||
views = [View(instrument_name=name, aggregation=ExplicitBucketHistogramAggregation(boundaries=buckets)) for name in ("messenger.http.duration", "messenger.job.duration", "messenger.job.ready.duration")]
|
||||
metrics.set_meter_provider(MeterProvider(resource=resource, views=views, metric_readers=[PeriodicExportingMetricReader(OTLPMetricExporter(timeout=2), export_interval_millis=5000)]))
|
||||
logs = LoggerProvider(resource=resource)
|
||||
logs.add_log_record_processor(BatchLogRecordProcessor(OTLPLogExporter(timeout=2), max_queue_size=2048, max_export_batch_size=256, schedule_delay_millis=1000))
|
||||
log.addHandler(LoggingHandler(level=logging.INFO, logger_provider=logs))
|
||||
stream = logging.StreamHandler()
|
||||
stream.setFormatter(JsonFormatter())
|
||||
log.addHandler(stream)
|
||||
|
||||
def carrier():
|
||||
result = {}
|
||||
trace_context.inject(result)
|
||||
return result
|
||||
|
||||
def extract(value):
|
||||
return trace_context.extract(value or {})
|
||||
+265
@@ -0,0 +1,265 @@
|
||||
"""RabbitMQ consumer for the version-1 attachment pipeline."""
|
||||
import asyncio
|
||||
from hashlib import sha256
|
||||
from io import BytesIO
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import random
|
||||
import pickle
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from PIL import Image, ImageOps
|
||||
|
||||
from .broker import QUEUE, _connection, publish_dlq
|
||||
from .config import load_settings
|
||||
from .storage.postgres import PostgresStore
|
||||
from .storage.s3 import S3Settings, S3Store
|
||||
from . import telemetry as tel
|
||||
from datetime import datetime, timezone
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s worker %(message)s")
|
||||
|
||||
|
||||
class PermanentFailure(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def fit(image, bound):
|
||||
longest = max(image.size)
|
||||
if longest <= bound:
|
||||
return image.copy()
|
||||
return image.resize((max(1, image.width * bound // longest),
|
||||
max(1, image.height * bound // longest)), Image.Resampling.LANCZOS)
|
||||
|
||||
|
||||
def render_isolated(data, timeout):
|
||||
try:
|
||||
result = subprocess.run([sys.executable, '-m', 'src.render'], input=data,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, timeout=timeout)
|
||||
except subprocess.TimeoutExpired as error:
|
||||
raise TimeoutError('render deadline exceeded') from error
|
||||
if result.returncode in (20, 21):
|
||||
raise PermanentFailure('invalid_image' if result.returncode == 20 else 'image_resource_limit')
|
||||
if result.returncode:
|
||||
raise RuntimeError('renderer exited')
|
||||
# Only our own child process produces this payload; no external pickle input.
|
||||
return pickle.loads(result.stdout)
|
||||
|
||||
|
||||
def thumbnail(data: bytes) -> tuple[bytes, int, int]:
|
||||
with Image.open(BytesIO(data), formats=("PNG", "JPEG")) as source:
|
||||
image = ImageOps.exif_transpose(source)
|
||||
if image.mode in {"RGBA", "LA"} or (image.mode == "P" and "transparency" in image.info):
|
||||
background = Image.new("RGBA", image.size, "white")
|
||||
background.alpha_composite(image.convert("RGBA"))
|
||||
image = background.convert("RGB")
|
||||
else:
|
||||
image = image.convert("RGB")
|
||||
image = fit(image, 256)
|
||||
output = BytesIO()
|
||||
image.save(output, format="JPEG", quality=85, optimize=True)
|
||||
return output.getvalue(), image.width, image.height
|
||||
|
||||
|
||||
def variants(data: bytes, max_pixels: int = 40_000_000) -> list[tuple[str, bytes, str, int, int]]:
|
||||
"""Render required variants without preserving EXIF or other input metadata."""
|
||||
with Image.open(BytesIO(data), formats=("PNG", "JPEG")) as source:
|
||||
if source.width * source.height > max_pixels:
|
||||
raise ValueError("image exceeds configured pixel limit")
|
||||
image = ImageOps.exif_transpose(source).convert("RGBA")
|
||||
white = Image.new("RGBA", image.size, "white")
|
||||
white.alpha_composite(image)
|
||||
rgb = white.convert("RGB")
|
||||
|
||||
thumb = fit(rgb, 256)
|
||||
thumbnail_out = BytesIO(); thumb.save(thumbnail_out, "JPEG", quality=85, optimize=True)
|
||||
|
||||
side = min(rgb.width, rgb.height)
|
||||
left, top = (rgb.width - side) // 2, (rgb.height - side) // 2
|
||||
crop = rgb.crop((left, top, left + side, top + side)).resize((128, 128), Image.Resampling.LANCZOS)
|
||||
crop_out = BytesIO(); crop.save(crop_out, "JPEG", quality=85, optimize=True)
|
||||
|
||||
optimized = fit(rgb, 1280)
|
||||
optimized_out = BytesIO(); optimized.save(optimized_out, "WEBP", quality=80, method=4)
|
||||
return [
|
||||
("thumbnail", thumbnail_out.getvalue(), "image/jpeg", thumb.width, thumb.height),
|
||||
("crop", crop_out.getvalue(), "image/jpeg", 128, 128),
|
||||
("optimized", optimized_out.getvalue(), "image/webp", optimized.width, optimized.height),
|
||||
]
|
||||
|
||||
|
||||
async def process(store: PostgresStore, s3: S3Store, payload: dict, lease_seconds: int) -> str:
|
||||
# Excludes cleanup for the whole lifetime of S3 effects, including stale attempts.
|
||||
async with store.attachment_transaction():
|
||||
return await process_locked(store, s3, payload, lease_seconds)
|
||||
|
||||
|
||||
async def process_locked(store: PostgresStore, s3: S3Store, payload: dict, lease_seconds: int) -> str:
|
||||
attachment_id = UUID(payload["attachment_id"])
|
||||
attachment = await store.claim_attachment_job(attachment_id, lease_seconds)
|
||||
if attachment is None:
|
||||
return "skipped"
|
||||
payload['_claim_time'] = attachment['claim_time']
|
||||
payload['attempt'] = attachment.get('attempt', payload.get('attempt', 1))
|
||||
attempt_key = uuid4().hex
|
||||
original_key = f"originals/{attachment_id}/{attempt_key}"
|
||||
await s3.copy(attachment["staging_key"], original_key, attachment["content_type"])
|
||||
original = await s3.download_key(attachment["staging_key"], attachment["size_bytes"], attachment["sha256"])
|
||||
rendered = await asyncio.to_thread(render_isolated, original, lease_seconds)
|
||||
metadata = []
|
||||
for name, content, content_type, width, height in rendered:
|
||||
extension = "webp" if name == "optimized" else "jpg"
|
||||
object_key = f"variants/{attachment_id}/{attempt_key}/{name}.{extension}"
|
||||
await s3.put(object_key, BytesIO(content), len(content), content_type)
|
||||
metadata.append({"name": name, "object_key": object_key, "content_type": content_type,
|
||||
"size_bytes": len(content), "width": width, "height": height,
|
||||
"sha256": sha256(content).hexdigest()})
|
||||
# Explicit, opt-in integration fault. Marker survives container restart,
|
||||
# so one crash exercises lease recovery without a permanent crash loop.
|
||||
if os.environ.get('WORKER_FAULT_AFTER_S3_PUT') == '1':
|
||||
marker = Path('/tmp/worker-fault-after-s3')
|
||||
try:
|
||||
with marker.open('x') as stream:
|
||||
stream.write(str(attachment_id))
|
||||
except FileExistsError:
|
||||
pass
|
||||
else:
|
||||
os._exit(70)
|
||||
committed = await store.complete_attachment_job(attachment_id, original_key, metadata, attachment['claim_time'])
|
||||
if committed:
|
||||
try:
|
||||
duration = await store.ready_seconds(attachment_id)
|
||||
if duration is not None:
|
||||
tel.ready_duration.record(duration, {"job_type": "attachment"})
|
||||
except Exception:
|
||||
tel.log.warning("telemetry.unavailable")
|
||||
try:
|
||||
await s3.delete(attachment["staging_key"])
|
||||
except Exception:
|
||||
logging.warning('staging cleanup deferred attachment_id=%s', attachment_id)
|
||||
|
||||
return "success" if committed else "skipped"
|
||||
|
||||
def settle_delivery(channel, delivery_tag, future):
|
||||
"""Only a successful durable disposition permits acknowledgement."""
|
||||
try:
|
||||
success = future.result() is True
|
||||
except Exception:
|
||||
success = False
|
||||
if channel.is_open:
|
||||
if success:
|
||||
channel.basic_ack(delivery_tag)
|
||||
else:
|
||||
channel.basic_nack(delivery_tag, requeue=True)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
tel.setup("messenger-worker")
|
||||
settings = load_settings()
|
||||
connection = _connection()
|
||||
channel = connection.channel()
|
||||
workers = max(1, int(os.environ.get("WORKER_CONCURRENCY", "2")))
|
||||
tel.capacity.add(workers)
|
||||
channel.basic_qos(prefetch_count=max(1, int(os.environ.get("WORKER_PREFETCH", str(workers)))))
|
||||
|
||||
async def handle_async(payload):
|
||||
"""Each executor thread owns its event loop and its DB/S3 clients."""
|
||||
store = PostgresStore(settings.database_url)
|
||||
s3 = S3Store(S3Settings.load())
|
||||
await store.connect()
|
||||
try:
|
||||
return await process(store, s3, payload, max(1, int(os.environ.get("JOB_TIMEOUT_SECONDS", "60"))))
|
||||
finally:
|
||||
s3.client.close()
|
||||
await store.close()
|
||||
|
||||
async def schedule_retry(attachment_id, delay, claim_time, permanent_code=None):
|
||||
retry_store = PostgresStore(settings.database_url)
|
||||
await retry_store.connect()
|
||||
try:
|
||||
return await retry_store.retry_attachment_job(
|
||||
attachment_id, max(1, int(os.environ.get("JOB_MAX_ATTEMPTS", "5"))), delay, claim_time, permanent_code
|
||||
)
|
||||
finally:
|
||||
await retry_store.close()
|
||||
|
||||
def handle_job(body):
|
||||
payload = None
|
||||
try:
|
||||
payload = json.loads(body)
|
||||
if not isinstance(payload, dict):
|
||||
raise ValueError('job must be an object')
|
||||
if payload["type"] != "attachment.process.v1" or payload["schema_version"] != 1:
|
||||
raise ValueError("unexpected broker payload")
|
||||
UUID(payload['attachment_id'])
|
||||
UUID(payload['job_id'])
|
||||
tel.trace.get_current_span().set_attribute("messaging.retry.attempt", int(payload.get('attempt', 1)))
|
||||
except (ValueError, KeyError, TypeError):
|
||||
try:
|
||||
asyncio.run(publish_dlq({'failure': 'invalid_job'}))
|
||||
return True, "failed"
|
||||
except Exception:
|
||||
return False, "failed"
|
||||
try:
|
||||
outcome = asyncio.run(handle_async(payload))
|
||||
except Exception as error:
|
||||
logging.warning("job failed attachment_id=%s", payload['attachment_id'])
|
||||
if '_claim_time' not in payload:
|
||||
return False, "failed"
|
||||
try:
|
||||
attachment_id = UUID(payload["attachment_id"])
|
||||
attempt = int(payload.get("attempt", 1))
|
||||
delay = min(60.0, float(2 ** min(attempt, 6))) * random.uniform(0.5, 1.5)
|
||||
asyncio.run(schedule_retry(attachment_id, delay, payload['_claim_time'],
|
||||
str(error) if isinstance(error, PermanentFailure) else None))
|
||||
except Exception:
|
||||
return False, "failed"
|
||||
return True, "failed"
|
||||
return True, outcome
|
||||
|
||||
def handle(body, headers):
|
||||
started = time.monotonic()
|
||||
tel.busy.add(1)
|
||||
with tel.tracer.start_as_current_span("attachment.consume", context=tel.extract(headers), kind=tel.SpanKind.CONSUMER, record_exception=False, set_status_on_exception=False) as span:
|
||||
try:
|
||||
acknowledged, outcome = handle_job(body)
|
||||
return acknowledged
|
||||
except Exception:
|
||||
outcome = "failed"
|
||||
raise
|
||||
finally:
|
||||
if 'outcome' not in locals(): outcome = "failed"
|
||||
if outcome == "failed": span.set_status(tel.Status(tel.StatusCode.ERROR))
|
||||
attrs = {"job_type": "attachment", "outcome": outcome}
|
||||
tel.jobs.add(1, attrs)
|
||||
tel.job_duration.record(time.monotonic() - started, attrs)
|
||||
tel.log.info("job.processed", extra={"outcome": outcome})
|
||||
tel.busy.add(-1)
|
||||
|
||||
def consume(ch, method, properties, body):
|
||||
future = executor.submit(handle, body, properties.headers or {})
|
||||
def acknowledged(_future):
|
||||
if connection.is_open:
|
||||
connection.add_callback_threadsafe(lambda: settle_delivery(ch, method.delivery_tag, _future))
|
||||
future.add_done_callback(acknowledged)
|
||||
|
||||
try:
|
||||
def heartbeat():
|
||||
Path('/tmp/worker-heartbeat').write_text(str(time.time()))
|
||||
connection.call_later(2, heartbeat)
|
||||
heartbeat()
|
||||
with ThreadPoolExecutor(max_workers=workers, thread_name_prefix="attachment-worker") as executor:
|
||||
channel.basic_consume(queue=QUEUE, on_message_callback=consume, auto_ack=False)
|
||||
channel.start_consuming()
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,27 @@
|
||||
rule_files:
|
||||
- /workspace/infra/prometheus/alerts.yaml
|
||||
evaluation_interval: 5s
|
||||
tests:
|
||||
- interval: 5s
|
||||
input_series:
|
||||
- series: 'messenger_http_requests_total{method="POST",route="/api/v1/chats/{chat_id}/messages",status_class="5xx"}'
|
||||
values: '0+50x30'
|
||||
- series: 'messenger_http_requests_total{method="POST",route="/api/v1/chats/{chat_id}/messages",status_class="2xx"}'
|
||||
values: '0+450x30'
|
||||
- series: 'messenger_queue_age_seconds{service_name="messenger-outbox"}'
|
||||
values: '60x30'
|
||||
alert_rule_test:
|
||||
- eval_time: 2m
|
||||
alertname: MessengerHighErrorRate
|
||||
exp_alerts:
|
||||
- exp_labels: {severity: warning}
|
||||
exp_annotations:
|
||||
summary: 'API 5xx ratio exceeds 5%'
|
||||
runbook: 'Inspect API latency, traces and dependency spans; check DB readiness.'
|
||||
- eval_time: 2m
|
||||
alertname: MessengerQueueLag
|
||||
exp_alerts:
|
||||
- exp_labels: {severity: warning}
|
||||
exp_annotations:
|
||||
summary: 'Oldest queued job exceeds 30 seconds'
|
||||
runbook: 'Check worker health, busy/capacity, broker and consumer traces.'
|
||||
@@ -0,0 +1,120 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Explicit local Docker tests: private bucket, uploader failover, S3 outage."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client, Failure, arguments, check, run
|
||||
|
||||
|
||||
def compose(*args, input=None):
|
||||
return subprocess.check_output(['docker', 'compose', *args], cwd=ROOT, input=input,
|
||||
text=True, stderr=subprocess.DEVNULL)
|
||||
|
||||
|
||||
def wait_ready(c):
|
||||
deadline = time.monotonic() + 90
|
||||
while True:
|
||||
try:
|
||||
c.call('GET', '/health/ready', schema='Health')
|
||||
return
|
||||
except Failure:
|
||||
check(time.monotonic() < deadline, 'stack did not recover')
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
def main():
|
||||
def configure(parser):
|
||||
parser.add_argument('--mode', required=True, choices=['private', 'failover', 's3-outage'])
|
||||
args = arguments(__doc__, configure)
|
||||
c = Client(args.base_url, args.ca_file)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
data = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
uploaded = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=sample.png',
|
||||
201, actor=alice, raw=data, headers={'Content-Type': 'image/png'}, schema='Attachment')
|
||||
att = uploaded['json']
|
||||
content_path = '/api/v1/attachments/' + att['id'] + '/content'
|
||||
if args.mode == 'private':
|
||||
script = '''import sys, urllib.request, urllib.error
|
||||
url = "http://s3:8333/messenger-attachments/originals/" + sys.stdin.read().strip()
|
||||
try:
|
||||
urllib.request.urlopen(url, timeout=5)
|
||||
except urllib.error.HTTPError as error:
|
||||
assert error.code == 403, error.code
|
||||
print("PASS: anonymous S3 GET returns 403 for an existing object")
|
||||
else:
|
||||
raise AssertionError("private object leaked")
|
||||
'''
|
||||
print(compose('exec', '-T', 'api-a', '/app/.venv/bin/python', '-c', script, input=att['id']).strip())
|
||||
elif args.mode == 'failover':
|
||||
target = uploaded['headers']['X-Instance-Id']
|
||||
service = None
|
||||
for candidate in ('api-a', 'api-b'):
|
||||
container = compose('ps', '-q', candidate).strip()
|
||||
hostname = subprocess.check_output(['docker', 'inspect', '--format', '{{.Config.Hostname}}', container], text=True).strip()
|
||||
if hostname == target:
|
||||
service = candidate
|
||||
check(service is not None, 'uploading replica not found')
|
||||
try:
|
||||
compose('stop', service)
|
||||
deadline = time.monotonic() + 15
|
||||
while True:
|
||||
try:
|
||||
download = c.call('GET', content_path, actor=bob)
|
||||
break
|
||||
except Failure:
|
||||
check(time.monotonic() < deadline, 'download did not recover')
|
||||
time.sleep(0.5)
|
||||
check(download['headers']['X-Instance-Id'] != target, 'download used stopped uploader')
|
||||
check(download['bytes'] == data, 'original changed after stopping uploader')
|
||||
print('PASS: uploaded via ' + service + '; stopped that container; original downloaded through another replica')
|
||||
finally:
|
||||
compose('start', service)
|
||||
wait_ready(c)
|
||||
else:
|
||||
try:
|
||||
compose('stop', 's3')
|
||||
# Direct API request inside the network: LB excludes unready backends.
|
||||
script = '''import json, sys, urllib.request, urllib.error
|
||||
payload = json.load(sys.stdin)
|
||||
for method, path, body, headers in [
|
||||
("GET", "/health/ready", None, {}),
|
||||
("GET", payload["path"], None, {"Authorization": "Bearer " + payload["token"]}),
|
||||
("POST", payload["upload_path"], bytes.fromhex(payload["bytes"]),
|
||||
{"Authorization": "Bearer " + payload["token"], "Content-Type": "image/png"}),
|
||||
]:
|
||||
req = urllib.request.Request("http://localhost:8080" + path, data=body, headers=headers, method=method)
|
||||
try:
|
||||
urllib.request.urlopen(req, timeout=15)
|
||||
except urllib.error.HTTPError as error:
|
||||
assert error.code == 503, error.code
|
||||
document = json.load(error)
|
||||
assert document["error"]["code"] == "unavailable"
|
||||
assert document["error"]["request_id"] == error.headers["X-Request-Id"]
|
||||
else:
|
||||
raise AssertionError("S3 outage was not reported")
|
||||
assert urllib.request.urlopen("http://localhost:8080/health/live").status == 200
|
||||
print("PASS: S3 outage gives 503 for readiness, download and upload; liveness stays 200")
|
||||
'''
|
||||
payload = {'path': content_path, 'token': bob['token'], 'bytes': data.hex(),
|
||||
'upload_path': '/api/v1/chats/' + chat['id'] + '/attachments?filename=outage.png'}
|
||||
print(compose('exec', '-T', 'api-a', '/app/.venv/bin/python', '-c', script,
|
||||
input=json.dumps(payload)).strip())
|
||||
finally:
|
||||
compose('start', 's3')
|
||||
# HeadBucket/read recovery alone does not prove the write path is ready.
|
||||
# Use the same write-probing bootstrap as the documented restart hook.
|
||||
compose('run', '--rm', '--no-deps', 's3-init')
|
||||
wait_ready(c)
|
||||
check(c.call('GET', content_path, actor=bob)['bytes'] == data, 'original lost after S3 outage')
|
||||
c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=after-recovery.png',
|
||||
201, actor=alice, raw=data, headers={'Content-Type': 'image/png'}, schema='Attachment')
|
||||
print('PASS: original available and new upload accepted after S3 restart/bootstrap')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,113 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Attachment contract checks against the running lab5 stack."""
|
||||
import hashlib
|
||||
import http.client
|
||||
from io import BytesIO
|
||||
from pathlib import Path
|
||||
import struct
|
||||
import sys
|
||||
import uuid
|
||||
import zlib
|
||||
from urllib.parse import quote, urlsplit
|
||||
|
||||
from PIL import Image
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments(__doc__)
|
||||
c = Client(args.base_url, args.ca_file, timeout=30)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
path = '/api/v1/chats/' + chat['id'] + '/attachments?filename='
|
||||
png = (Path(__file__).resolve().parents[1] / 'tests/fixtures/sample.png').read_bytes()
|
||||
|
||||
def upload(data, mime='image/png', filename='photo.png', status=202, actor=alice):
|
||||
return c.call('POST', path + quote(filename, safe=''), status, actor=actor, raw=data,
|
||||
headers={'Content-Type': mime}, schema='Attachment' if status == 202 else None)
|
||||
|
||||
for fmt, mime in [('PNG', 'image/png'), ('JPEG', 'image/jpeg')]:
|
||||
buf = BytesIO()
|
||||
Image.new('RGB', (32, 20), 'blue').save(buf, fmt)
|
||||
data = buf.getvalue()
|
||||
att = upload(data, mime)['json']
|
||||
check(att['variants'] == [] and att['status'] == 'queued', 'wrong attachment state')
|
||||
att = c.wait_ready(bob, att)
|
||||
check(att['sha256'] == hashlib.sha256(data).hexdigest(), 'wrong checksum')
|
||||
content_path = '/api/v1/attachments/' + att['id']
|
||||
check(c.call('GET', content_path, actor=bob, schema='Attachment')['json'] == att,
|
||||
'metadata changed')
|
||||
check(c.call('GET', content_path + '/content', actor=bob)['bytes'] == data, 'bytes changed')
|
||||
c.call('GET', content_path, 404, actor=eve)
|
||||
c.call('GET', content_path + '/content', 404, actor=eve)
|
||||
c.call('GET', content_path + '/content', 401)
|
||||
c.call('GET', content_path + '/content?variant=thumbnail', actor=bob)
|
||||
message = c.message(bob, chat, '', attachments=[att['id']])['json']
|
||||
history = c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages',
|
||||
actor=alice, schema='MessagePage')['json']['items']
|
||||
check(message in history, 'attachment message missing in history')
|
||||
print('PASS: PNG/JPEG originals, metadata, attachment-only messages and ACL')
|
||||
|
||||
for name in ('../x.png', 'x/y.png', 'x\\y.png', 'x\x00.png', 'x\n.png', 'x\x7f.png', ' ', 'x' * 256):
|
||||
upload(png, filename=name, status=400)
|
||||
upload(png, mime='image/jpeg', status=415)
|
||||
upload(b'not an image', status=415)
|
||||
upload(png[:30], status=415)
|
||||
upload(png, mime='application/octet-stream', status=415)
|
||||
upload(png, status=404, actor=eve)
|
||||
upload(b'x' * (10485760 + 1), status=413)
|
||||
|
||||
# Valid PNG header with an oversized canvas: reject before attempting pixel decoding.
|
||||
def chunk(kind, data):
|
||||
return struct.pack('>I', len(data)) + kind + data + struct.pack('>I', zlib.crc32(kind + data))
|
||||
huge = b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', struct.pack('>IIBBBBB', 8001, 5000, 8, 2, 0, 0, 0))
|
||||
huge += chunk(b'IDAT', zlib.compress(b'')) + chunk(b'IEND', b'')
|
||||
upload(huge, status=413)
|
||||
|
||||
# No Content-Length: limits must also work for chunked requests.
|
||||
url = urlsplit(c.base)
|
||||
connection = http.client.HTTPConnection(url.hostname, url.port, timeout=30)
|
||||
connection.request('POST', path + 'chunked.png', body=iter([b'x' * 65536] * 161),
|
||||
headers={'Authorization': 'Bearer ' + alice['token'], 'Content-Type': 'image/png'},
|
||||
encode_chunked=True)
|
||||
response = connection.getresponse()
|
||||
check(response.status == 413, 'chunked upload bypassed byte limit')
|
||||
response.read()
|
||||
connection.close()
|
||||
print('PASS: filename, MIME, malformed image, byte/pixel and chunked limits')
|
||||
|
||||
att = upload(png)['json']
|
||||
other_chat = c.call('POST', '/api/v1/chats', 201, actor=alice,
|
||||
body={'title': 'other', 'member_ids': [alice['id']]}, schema='Chat')['json']
|
||||
for target, ids, code in ((chat, [str(uuid.uuid4())], 404),
|
||||
(other_chat, [att['id']], 404),
|
||||
(chat, [att['id'], att['id']], 400)):
|
||||
c.call('POST', '/api/v1/chats/' + target['id'] + '/messages', code, actor=alice,
|
||||
body={'text': '', 'attachment_ids': ids}, headers={'Idempotency-Key': uuid.uuid4().hex})
|
||||
key = uuid.uuid4().hex
|
||||
first = c.message(alice, chat, 'same', key=key)['json']
|
||||
check(c.message(alice, chat, 'same', key=key, attachments=[])['json'] == first,
|
||||
'omitted and empty attachment_ids differ')
|
||||
key = uuid.uuid4().hex
|
||||
first = c.message(alice, chat, '', key=key, attachments=[att['id']])['json']
|
||||
check(c.message(alice, chat, '', key=key, attachments=[att['id']])['json'] == first, 'replay differs')
|
||||
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 409, actor=alice,
|
||||
body={'text': 'changed', 'attachment_ids': [att['id']]}, headers={'Idempotency-Key': key})
|
||||
print('PASS: attachment scope, duplicates and idempotency normalization')
|
||||
|
||||
# Exact limits are accepted; original bytes (including PNG trailing data) survive.
|
||||
exact = png + b'\0' * (10485760 - len(png))
|
||||
att = upload(exact)['json']
|
||||
c.wait_ready(bob, att)
|
||||
check(c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=bob)['bytes'] == exact,
|
||||
'10 MiB original changed')
|
||||
buf = BytesIO()
|
||||
Image.new('RGB', (8000, 5000)).save(buf, 'PNG')
|
||||
att = upload(buf.getvalue())['json']
|
||||
check(att['size_bytes'] == len(buf.getvalue()), '40M pixel upload failed')
|
||||
print('PASS: inclusive 10 MiB and 40 million pixel boundaries')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,83 @@
|
||||
rule_files:
|
||||
- /workspace/infra/prometheus/alerts.yaml
|
||||
evaluation_interval: 5s
|
||||
tests:
|
||||
- name: healthy
|
||||
interval: 5s
|
||||
input_series:
|
||||
- series: 'messenger_http_requests_total{route="/api/v1/users",status_class="2xx"}'
|
||||
values: '0+100x80'
|
||||
- series: 'messenger_http_requests_total{route="/api/v1/users",status_class="5xx"}'
|
||||
values: '0+0x80'
|
||||
- series: 'messenger_slo_ready_eligible_total{service_name="messenger-outbox"}'
|
||||
values: '0+100x80'
|
||||
- series: 'messenger_slo_ready_bad_total{service_name="messenger-outbox"}'
|
||||
values: '0+0x80'
|
||||
alert_rule_test:
|
||||
- {eval_time: 5m, alertname: MessengerApiBurnFast, exp_alerts: []}
|
||||
- {eval_time: 5m, alertname: MessengerApiBurnSlow, exp_alerts: []}
|
||||
- {eval_time: 5m, alertname: MessengerReadyBurnFast, exp_alerts: []}
|
||||
- {eval_time: 5m, alertname: MessengerReadyBurnSlow, exp_alerts: []}
|
||||
- name: brief severe spike and recovery
|
||||
interval: 5s
|
||||
input_series:
|
||||
- series: 'messenger_http_requests_total{route="/api/v1/users",status_class="2xx"}'
|
||||
values: '0+100x12 1200+0x8 1200+100x60'
|
||||
- series: 'messenger_http_requests_total{route="/api/v1/users",status_class="5xx"}'
|
||||
values: '0+0x12 0+100x8 800+0x60'
|
||||
alert_rule_test:
|
||||
- eval_time: 1m30s
|
||||
alertname: MessengerApiBurnFast
|
||||
exp_alerts:
|
||||
- exp_labels: {severity: critical, slo: api, burn: fast}
|
||||
exp_annotations: {summary: 'api SLO fast burn', runbook: 'See docs/slo-runbook.md'}
|
||||
- {eval_time: 3m, alertname: MessengerApiBurnFast, exp_alerts: []}
|
||||
- name: sustained moderate degradation
|
||||
interval: 5s
|
||||
input_series:
|
||||
- series: 'messenger_http_requests_total{route="/api/v1/users",status_class="2xx"}'
|
||||
values: '0+80x80'
|
||||
- series: 'messenger_http_requests_total{route="/api/v1/users",status_class="5xx"}'
|
||||
values: '0+20x80'
|
||||
- series: 'messenger_slo_ready_eligible_total{service_name="messenger-outbox"}'
|
||||
values: '0+100x80'
|
||||
- series: 'messenger_slo_ready_bad_total{service_name="messenger-outbox"}'
|
||||
values: '0+20x80'
|
||||
alert_rule_test:
|
||||
- {eval_time: 5m, alertname: MessengerApiBurnFast, exp_alerts: []}
|
||||
- {eval_time: 5m, alertname: MessengerReadyBurnFast, exp_alerts: []}
|
||||
- eval_time: 5m
|
||||
alertname: MessengerApiBurnSlow
|
||||
exp_alerts:
|
||||
- exp_labels: {severity: warning, slo: api, burn: slow}
|
||||
exp_annotations: {summary: 'api SLO slow burn', runbook: 'See docs/slo-runbook.md'}
|
||||
- eval_time: 5m
|
||||
alertname: MessengerReadyBurnSlow
|
||||
exp_alerts:
|
||||
- exp_labels: {severity: warning, slo: ready, burn: slow}
|
||||
exp_annotations: {summary: 'ready SLO slow burn', runbook: 'See docs/slo-runbook.md'}
|
||||
- name: low-volume guard
|
||||
interval: 5s
|
||||
input_series:
|
||||
- series: 'messenger_http_requests_total{route="/api/v1/users",status_class="5xx"}'
|
||||
values: '0+1x80'
|
||||
- series: 'messenger_slo_ready_eligible_total{service_name="messenger-outbox"}'
|
||||
values: '0+1x80'
|
||||
- series: 'messenger_slo_ready_bad_total{service_name="messenger-outbox"}'
|
||||
values: '0+1x80'
|
||||
alert_rule_test:
|
||||
- {eval_time: 5m, alertname: MessengerApiBurnFast, exp_alerts: []}
|
||||
- {eval_time: 5m, alertname: MessengerReadyBurnFast, exp_alerts: []}
|
||||
- name: late ready events fast burn
|
||||
interval: 5s
|
||||
input_series:
|
||||
- series: 'messenger_slo_ready_eligible_total{service_name="messenger-outbox"}'
|
||||
values: '0+100x30'
|
||||
- series: 'messenger_slo_ready_bad_total{service_name="messenger-outbox"}'
|
||||
values: '0+100x30'
|
||||
alert_rule_test:
|
||||
- eval_time: 1m
|
||||
alertname: MessengerReadyBurnFast
|
||||
exp_alerts:
|
||||
- exp_labels: {severity: critical, slo: ready, burn: fast}
|
||||
exp_annotations: {summary: 'ready SLO fast burn', runbook: 'See docs/slo-runbook.md'}
|
||||
@@ -0,0 +1,41 @@
|
||||
"""Export synthetic trace/log evidence through Grafana; credentials never enter artifacts."""
|
||||
import argparse
|
||||
import base64
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
from pathlib import Path
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
auth = 'Basic ' + base64.b64encode(('admin:' + (ROOT/'secrets/grafana_password').read_text().strip()).encode()).decode()
|
||||
def get(source, path, params=None):
|
||||
url = f'http://127.0.0.1:3000/api/datasources/proxy/uid/{source}/' + path
|
||||
if params: url += '?' + urllib.parse.urlencode(params)
|
||||
with urllib.request.urlopen(urllib.request.Request(url,headers={'Authorization':auth}),timeout=15) as r:
|
||||
return json.load(r)
|
||||
|
||||
def capture(trace_id=None, query=None):
|
||||
query = query or '{service_name="messenger-api"} | status="503"'
|
||||
if trace_id:
|
||||
query = '{service_name=~"messenger-api|messenger-worker"} | trace_id="' + trace_id + '"'
|
||||
logs = get('loki','loki/api/v1/query_range',{'query':query,'since':'30m','limit':20,'direction':'backward'})
|
||||
if not trace_id:
|
||||
for stream in logs['data']['result']:
|
||||
for value in stream['values']:
|
||||
metadata = dict(stream['stream'])
|
||||
if len(value)>2: metadata.update(value[2])
|
||||
trace_id = metadata.get('trace_id')
|
||||
if trace_id: break
|
||||
if trace_id: break
|
||||
if not trace_id:
|
||||
raise RuntimeError('No correlated log/trace found')
|
||||
trace = get('tempo','api/traces/'+trace_id)
|
||||
return {'captured_at':datetime.now(timezone.utc).isoformat(),'query':query,'trace_id':trace_id,'logs':logs,'trace':trace}
|
||||
|
||||
if __name__=='__main__':
|
||||
parser=argparse.ArgumentParser();parser.add_argument('--trace-id');parser.add_argument('--output',required=True)
|
||||
args=parser.parse_args()
|
||||
result=capture(args.trace_id)
|
||||
(ROOT/args.output).write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n')
|
||||
print('Saved correlated evidence:',args.output,'trace_id:',result['trace_id'])
|
||||
@@ -0,0 +1,18 @@
|
||||
"""Execute every provisioned PromQL target against the running Grafana datasource."""
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
spec=importlib.util.spec_from_file_location('capture',ROOT/'student-tests/capture_observability.py')
|
||||
capture=importlib.util.module_from_spec(spec);spec.loader.exec_module(capture)
|
||||
dashboard=json.loads((ROOT/'infra/grafana/dashboards/messenger.json').read_text())
|
||||
results=[]
|
||||
for panel in dashboard['panels']:
|
||||
for target in panel.get('targets',[]):
|
||||
if 'expr' not in target:continue
|
||||
query=target['expr'].replace('$__rate_interval','1m').replace('$__interval','5s')
|
||||
result=capture.get('prometheus','api/v1/query',{'query':query})
|
||||
assert result['status']=='success',result
|
||||
results.append({'panel':panel['title'],'query':query,'series':len(result['data']['result'])})
|
||||
(ROOT/'evidence/review-dashboard.json').write_text(json.dumps(results,ensure_ascii=False,indent=2)+'\n')
|
||||
print('PASS:',len(results),'dashboard queries; empty targets:',sum(r['series']==0 for r in results))
|
||||
@@ -0,0 +1,31 @@
|
||||
"""Verify exported parent relationships and the completed retry, not just trace existence."""
|
||||
import base64
|
||||
import json
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
data=json.loads((ROOT/'evidence/review-retry-trace.json').read_text())
|
||||
spans=[s for batch in data['trace']['batches'] for scope in batch.get('scopeSpans',[]) for s in scope.get('spans',[])]
|
||||
by_id={s['spanId']:s for s in spans}
|
||||
counts=Counter(s['name'] for s in spans)
|
||||
producers=[s for s in spans if s['kind']=='SPAN_KIND_PRODUCER']
|
||||
consumers=[s for s in spans if s['kind']=='SPAN_KIND_CONSUMER']
|
||||
assert len(producers)>=2 and consumers,counts
|
||||
for producer in producers:
|
||||
ancestor = producer
|
||||
for _ in range(len(spans)):
|
||||
ancestor = by_id[ancestor['parentSpanId']]
|
||||
if ancestor['kind']=='SPAN_KIND_SERVER': break
|
||||
else: raise AssertionError('producer has no API ancestor')
|
||||
for consumer in consumers:
|
||||
assert by_id[consumer['parentSpanId']]['kind']=='SPAN_KIND_PRODUCER'
|
||||
assert counts['postgres.complete_attachment_job']>=1,counts
|
||||
assert any(s['name'].startswith('s3.') for s in spans),counts
|
||||
assert all(base64.b64decode(s['traceId']).hex()==data['trace_id'] for s in spans)
|
||||
services={stream['stream']['service_name'] for stream in data['logs']['data']['result']}
|
||||
assert {'messenger-api','messenger-worker'}<=services,services
|
||||
result={'trace_id':data['trace_id'],'span_count':len(spans),'span_names':dict(counts),
|
||||
'producer_count':len(producers),'consumer_count':len(consumers),'log_services':sorted(services),
|
||||
'parent_relationships':'PASS','note':'Abrupt os._exit may lose unfinished spans of the crashed attempt; redelivery and committed retry remain visible.'}
|
||||
(ROOT/'evidence/review-retry-summary.json').write_text(json.dumps(result,indent=2)+'\n')
|
||||
print('PASS:',json.dumps(result))
|
||||
@@ -0,0 +1,40 @@
|
||||
"""Probe trusted and untrusted TLS plus inaccessible plaintext dependency ports."""
|
||||
import os
|
||||
import socket
|
||||
import ssl
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
ca = os.environ['BAO_CACERT']
|
||||
for host, port in [('s3', 8333), ('broker', 5671), ('openbao', 8200)]:
|
||||
trusted = ssl.create_default_context(cafile=ca)
|
||||
with socket.create_connection((host, port), timeout=5) as raw:
|
||||
with trusted.wrap_socket(raw, server_hostname=host) as connection:
|
||||
assert connection.version() in {'TLSv1.2', 'TLSv1.3'}
|
||||
untrusted = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
|
||||
try:
|
||||
with socket.create_connection((host, port), timeout=5) as raw:
|
||||
with untrusted.wrap_socket(raw, server_hostname=host):
|
||||
pass
|
||||
except ssl.SSLCertVerificationError:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError(f'{host}: untrusted CA accepted')
|
||||
print(f'PASS {host}: verified TLS; untrusted CA rejected')
|
||||
|
||||
for host, port in [('s3', 8888), ('s3', 9333), ('s3', 18333), ('broker', 5672), ('broker', 4369), ('broker', 25672), ('broker', 15692), ('loki', 9095), ('tempo', 9095)]:
|
||||
try:
|
||||
socket.create_connection((host, port), timeout=3).close()
|
||||
except ConnectionRefusedError:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError(f'{host}:{port}: unexpected accessible plaintext port')
|
||||
print('PASS: S3 internal and broker plaintext ports are closed')
|
||||
request = urllib.request.Request('https://s3:8333/', data=b'', method='POST')
|
||||
try:
|
||||
urllib.request.urlopen(request, context=ssl.create_default_context(cafile=ca), timeout=5)
|
||||
except urllib.error.HTTPError as error:
|
||||
assert error.code == 403
|
||||
else:
|
||||
raise AssertionError('S3 proxy allowed the blocked POST method')
|
||||
print('PASS: S3 proxy blocks POST')
|
||||
Executable
+32
@@ -0,0 +1,32 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Один ключ одновременно через LB создаёт ровно одно сообщение."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client, check, run # noqa: E402
|
||||
|
||||
|
||||
def main() -> None:
|
||||
client = Client()
|
||||
alice, _bob, _eve, chat = client.bootstrap()
|
||||
key = uuid.uuid4().hex
|
||||
text = "concurrent idempotency " + key
|
||||
|
||||
def send(_number: int):
|
||||
return Client().message(alice, chat, text, key=key)["json"]
|
||||
|
||||
with ThreadPoolExecutor(max_workers=16) as pool:
|
||||
replies = list(pool.map(send, range(16)))
|
||||
check(all(reply == replies[0] for reply in replies), "replays returned different messages")
|
||||
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages?limit=100"
|
||||
history = client.call("GET", path, actor=alice, schema="MessagePage")["json"]["items"]
|
||||
check(sum(message["id"] == replies[0]["id"] for message in history) == 1, "concurrent retries created duplicates")
|
||||
print("PASS: concurrent idempotency through load balancer")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,35 @@
|
||||
"""Check that request-controlled secrets are absent from actual access logs."""
|
||||
from datetime import datetime, timezone
|
||||
import os
|
||||
from pathlib import Path
|
||||
import ssl
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from uuid import uuid4
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
ctx = ssl.create_default_context(cafile=str(root / 'secrets/ca.crt'))
|
||||
base = os.environ.get('BASE_URL', 'https://localhost:8443').rstrip('/')
|
||||
marker = 'audit-private-' + uuid4().hex
|
||||
since = datetime.now(timezone.utc).isoformat()
|
||||
for path in ('/health/ready?token=' + marker, '/missing/' + marker):
|
||||
request = urllib.request.Request(base + path, headers={
|
||||
'Authorization': 'Bearer ' + marker, 'X-Request-Id': marker})
|
||||
try:
|
||||
with urllib.request.urlopen(request, context=ctx, timeout=10) as response:
|
||||
response.read()
|
||||
except urllib.error.HTTPError as error:
|
||||
assert error.code == 404
|
||||
error.read()
|
||||
for attempt in range(20):
|
||||
logs = subprocess.check_output(['docker', 'compose', 'logs', '--since', since,
|
||||
'load_balancer', 'api-a', 'api-b'], cwd=root, text=True)
|
||||
assert marker not in logs, 'request secret leaked into container logs'
|
||||
if 'ingress status=200' in logs and 'ingress status=404' in logs and 'http.request' in logs:
|
||||
break
|
||||
time.sleep(0.25)
|
||||
else:
|
||||
raise AssertionError('missing positive evidence of access logging')
|
||||
print('PASS: ingress/API access records present; query, path and header markers absent')
|
||||
@@ -0,0 +1,31 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check real producer payloads and redeliver a complete persisted message."""
|
||||
import json
|
||||
import time
|
||||
from jsonschema import Draft202012Validator, FormatChecker
|
||||
from pipeline_integration import ROOT, Client, remote, duplicate, snapshot, wait, check
|
||||
|
||||
|
||||
def main():
|
||||
c = Client('http://localhost:8080', timeout=30)
|
||||
actor, _, _, chat = c.bootstrap()
|
||||
att, _ = c.attachment(actor, chat)
|
||||
wait(c, actor, att)
|
||||
payloads = remote('''rows = await db.pool.fetch('SELECT payload FROM attachment_outbox')
|
||||
print(json.dumps([json.loads(row['payload']) if isinstance(row['payload'], str) else row['payload'] for row in rows]))''')
|
||||
validator = Draft202012Validator(json.loads((ROOT / 'contracts/jobs.schema.json').read_text()), format_checker=FormatChecker())
|
||||
for payload in payloads:
|
||||
validator.validate(payload)
|
||||
before = snapshot(att)
|
||||
duplicate(att)
|
||||
duplicate(att)
|
||||
time.sleep(3)
|
||||
check(snapshot(att) == before, 'persisted redelivery changed result')
|
||||
result = dict(status='PASS', validated_outbox_payloads=len(payloads),
|
||||
extra_payload_fields=False, persisted_redelivery_noop=True)
|
||||
(ROOT / 'evidence/job-contract.json').write_text(json.dumps(result, indent=2) + '\n')
|
||||
print(json.dumps(result))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,67 @@
|
||||
"""Offline tests of login throttling and bounded request bodies."""
|
||||
import asyncio
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from src.login_limit import LoginLimiter
|
||||
from src.main import app
|
||||
|
||||
|
||||
async def request(chunks, limiter=None):
|
||||
app.state.settings = SimpleNamespace(instance_id="test")
|
||||
app.state.login_limiter = limiter or LoginLimiter(attempts=1, window_seconds=60)
|
||||
app.state.store = object()
|
||||
messages = [{"type": "http.request", "body": chunk, "more_body": i < len(chunks) - 1}
|
||||
for i, chunk in enumerate(chunks)]
|
||||
response = []
|
||||
async def receive():
|
||||
if messages:
|
||||
return messages.pop(0)
|
||||
await asyncio.Event().wait()
|
||||
async def send(message):
|
||||
response.append(message)
|
||||
scope = {"type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1",
|
||||
"method": "POST", "scheme": "http", "path": "/api/v1/auth/sessions",
|
||||
"raw_path": b"/api/v1/auth/sessions", "query_string": b"", "headers": [],
|
||||
"client": ("127.0.0.1", 1234), "server": ("localhost", 8080), "root_path": ""}
|
||||
await app(scope, receive, send)
|
||||
return response
|
||||
|
||||
|
||||
class LimitsTests(unittest.TestCase):
|
||||
def test_window_and_retry(self):
|
||||
now = [100.0]
|
||||
limiter = LoginLimiter(2, 60, lambda: now[0])
|
||||
self.assertEqual([limiter.retry_after() for _ in range(3)], [0, 0, 60])
|
||||
now[0] = 159.5
|
||||
self.assertEqual(limiter.retry_after(), 1)
|
||||
now[0] = 160
|
||||
self.assertEqual(limiter.retry_after(), 0)
|
||||
|
||||
def test_chunked_oversized_body(self):
|
||||
result = asyncio.run(request([b"x" * 40000, b"x" * 30000]))
|
||||
start = result[0]
|
||||
self.assertEqual(start["status"], 413)
|
||||
headers = dict(start["headers"])
|
||||
self.assertIn(b"x-request-id", headers)
|
||||
self.assertIn(b"x-instance-id", headers)
|
||||
self.assertIn(b'"payload_too_large"', b"".join(x.get("body", b"") for x in result))
|
||||
|
||||
def test_small_body_reaches_route(self):
|
||||
result = asyncio.run(request([b""]))
|
||||
self.assertEqual(result[0]["status"], 401)
|
||||
|
||||
def test_rate_limit_returns_retry_after(self):
|
||||
limiter = LoginLimiter(attempts=1, window_seconds=60)
|
||||
first = asyncio.run(request([b""], limiter))
|
||||
second = asyncio.run(request([b""], limiter))
|
||||
self.assertEqual(first[0]["status"], 401)
|
||||
self.assertEqual(second[0]["status"], 429)
|
||||
self.assertGreater(int(dict(second[0]["headers"])[b"retry-after"]), 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,49 @@
|
||||
"""TLS hostname, cross-chat attachment ACL, and actual session expiry."""
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import ssl
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from urllib.parse import urlsplit
|
||||
from uuid import uuid4
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
from client import Client, arguments, run
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments(__doc__)
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
target = urlsplit(client.base)
|
||||
context = ssl.create_default_context(cafile=args.ca_file)
|
||||
try:
|
||||
with socket.create_connection((target.hostname, target.port or 443), timeout=5) as raw:
|
||||
with context.wrap_socket(raw, server_hostname='wrong-host.invalid'):
|
||||
pass
|
||||
except ssl.SSLCertVerificationError:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError('TLS accepted wrong server hostname')
|
||||
alice, bob, eve, chat = client.bootstrap()
|
||||
attachment, _ = client.attachment(alice, chat)
|
||||
other_chat = client.call('POST', '/api/v1/chats', 201, actor=eve,
|
||||
body={'title': 'Other chat', 'member_ids': [eve['id']]}, schema='Chat')['json']
|
||||
client.call('POST', '/api/v1/chats/' + other_chat['id'] + '/messages', 404, actor=eve,
|
||||
body={'text': '', 'attachment_ids': [attachment['id']]},
|
||||
headers={'Idempotency-Key': uuid4().hex})
|
||||
client.call('GET', '/api/v1/users/me', actor=alice, schema='User')
|
||||
digest = hashlib.sha256(alice['token'].encode('ascii')).hexdigest()
|
||||
sql = "UPDATE sessions SET expires_at=now()+interval '2 seconds' WHERE token_hash='" + digest + "';\n"
|
||||
result = subprocess.run(['docker', 'compose', 'exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger', '-q'],
|
||||
cwd=ROOT, input=sql, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True)
|
||||
del result
|
||||
time.sleep(3)
|
||||
client.call('GET', '/api/v1/users/me', 401, actor=alice)
|
||||
print('PASS: wrong hostname rejected; cross-chat attachment denied; expired session rejected')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user