Author SHA1 Message Date
dawuduk 2d4c3163fa Закрыть оценку 4 и трек 1: отзыв leaf и права worker.
Брокер и Collector принимают только серийный номер текущего leaf. Прогон показывает rehash, 429 до дорогого Argon2, отказ stranger, ротацию пароля worker и сохранность задания.
2026-11-26 20:40:00 +03:00
dawuduk 9de3b01659 Отклонять чужой клиентский сертификат на handshake с API.
Внутренний hop ограничен TLS 1.2: без сертификата и с чужим CA соединение обрывается до HTTP. Отчёт фиксирует прошедшие smoke, mTLS, persistence и failover.
2026-11-26 20:14:17 +03:00
dawuduk 6d28606c63 Развести стенд с соседними лабораторными и починить хранилища.
Seaweed без TLS остаётся во внутренней сети, Grafana и S3 публикуются на свободных портах, а sidecar брокера поднимается заново после рестарта RabbitMQ.
2026-11-26 20:14:17 +03:00
dawudukandCursor fdaa02a163 Починить синтаксис отрицательной проверки mTLS.
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-26 19:50:47 +03:00
dawudukandCursor a69f7a9b03 Описать модель угроз, матрицу доверия и запуск стенда.
Отрицательная проверка mTLS вынесена в student-tests и не меняет публичные тесты.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-26 19:50:35 +03:00
dawudukandCursor 9b501b2020 Закрыть внешний вход TLS и выдавать секреты через OpenBao.
LB ходит в API только с клиентским сертификатом нужной identity, остальные связи проверяют серверный сертификат, root token в приложение не попадает.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-26 19:48:38 +03:00
dawudukandCursor fb566d874c Перевести пароли на Argon2id и читать секреты через AppRole.
Лимит входа общий для реплик, размер тела ограничен, исходящие клиенты проверяют TLS, если задан CA.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-26 19:40:28 +03:00
dawudukandCursor 54b4b9e509 Перенести реализацию мессенджера из lab6 в skeleton lab7.
Контракт, публичные тесты и README задания оставлены от lab7.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-26 19:23:53 +03:00
100 changed files with 8482 additions and 88 deletions
+18 -26
View File
@@ -1,41 +1,33 @@
# Copy to .env for your LOCAL synthetic test environment; never commit .env. # Copy is not required. scripts/bootstrap.ps1 creates .env and local secrets.
# These are logical interface suggestions; map actual framework names in REPORT.md. # Nothing in this file is a credential.
APP_HOST=0.0.0.0
APP_PORT=8080
APP_ENV=lab APP_ENV=lab
LOG_LEVEL=info
SESSION_TTL_SECONDS=3600 SESSION_TTL_SECONDS=3600
# Choose credentials locally. File paths contain no secret values. CACHE_TTL_SECONDS=60
DATABASE_URL_FILE=/run/secrets/database_url SESSION_STORE=redis
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
SESSION_STORE=postgres
CACHE_URL_FILE=/run/secrets/cache_url
API_REPLICAS=2 API_REPLICAS=2
API_CPUS=0.50
API_MEM=384m
POSTGRES_CPUS=1.0
POSTGRES_MEM=512m
DB_POOL_MAX=4
LB_DRAIN_SECONDS=2
IDEMPOTENCY_TTL_SECONDS=86400 IDEMPOTENCY_TTL_SECONDS=86400
S3_ENDPOINT=https://s3:9000
S3_REGION=us-east-1 S3_REGION=us-east-1
S3_BUCKET=messenger-attachments S3_BUCKET=messenger-attachments
S3_ACCESS_KEY_ID_FILE=/run/secrets/s3_access_key_id S3_PUBLIC_ENDPOINT=https://127.0.0.1:9007
S3_SECRET_ACCESS_KEY_FILE=/run/secrets/s3_secret_access_key PRESIGN_TTL_SECONDS=60
MAX_UPLOAD_BYTES=10485760 MAX_UPLOAD_BYTES=10485760
MAX_IMAGE_PIXELS=40000000 MAX_IMAGE_PIXELS=40000000
BROKER_URL_FILE=/run/secrets/broker_url
WORKER_CONCURRENCY=2 WORKER_CONCURRENCY=2
JOB_MAX_ATTEMPTS=5 JOB_MAX_ATTEMPTS=5
JOB_TIMEOUT_SECONDS=60 JOB_TIMEOUT_SECONDS=60
STAGING_RETENTION_SECONDS=86400 STAGING_RETENTION_SECONDS=86400
OTEL_SERVICE_NAME=messenger-api TELEMETRY_ENABLED=1
# Worker must set a distinct service.name. TRACE_SAMPLE_RATIO=1
OTEL_EXPORTER_OTLP_ENDPOINT=https://otel-collector:4318
OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=lab
# TLS and OpenBao: actual paths/ports depend on your implemented trust matrix.
PUBLIC_BASE_URL=https://localhost:8443
TLS_CA_FILE=/run/secrets/ca.crt
TLS_CERT_FILE=/run/secrets/service.crt
TLS_KEY_FILE=/run/secrets/service.key
BAO_ADDR=https://openbao:8200
BAO_CACERT=/run/secrets/bao-ca.crt
# No root token here. Bootstrap operator -> short-lived service auth -> scoped token.
ARGON2_MEMORY_KIB=19456 ARGON2_MEMORY_KIB=19456
ARGON2_ITERATIONS=2 ARGON2_ITERATIONS=2
ARGON2_PARALLELISM=1 ARGON2_PARALLELISM=1
LOGIN_RATE_LIMIT=8
LOGIN_RATE_WINDOW_SECONDS=60
PUBLIC_BASE_URL=https://localhost:8443
+7
View File
@@ -0,0 +1,7 @@
*.sh text eol=lf
*.cfg text eol=lf
*.hcl text eol=lf
*.yml text eol=lf
*.yaml text eol=lf
*.py text eol=lf
Dockerfile text eol=lf
+14 -14
View File
@@ -1,18 +1,18 @@
## Лабораторная 7 ## Лабораторная 7
Автор / группа: TODO Автор / группа: Булацев / БПИ2301
Целевая оценка (3/4/5): TODO Целевая оценка (3/4/5): 5
Трек 5, если заявлен: TODO Трек 5, если заявлен: трек 1, компрометация worker
Что реализовано и что перенесено: TODO Что реализовано и что перенесено: мессенджер lab6 перенесён без замены контракта и публичных tests. Добавлены Argon2id, общий rate limit, внешний TLS, mTLS LB→API и на брокер/Collector с отзывом leaf по серийному номеру, OpenBao AppRole. Трек 1 сравнивает права worker до и после least privilege и переживает отзыв leaf плюс ротацию пароля БД.
Команды запуска из чистого clone: TODO Команды запуска из чистого clone: `pwsh scripts/bootstrap.ps1`, затем smoke/security с `CA_FILE=certs/ca.crt`. Подробности в REPORT.md.
Результаты проверок и ссылка на REPORT.md: TODO Результаты проверок и ссылка на REPORT.md: REPORT.md. На этой машине прошли check, smoke, security, mTLS, same-CA, rehash/429, persistence, failover и `student-tests/track1_worker.py`.
Ограничения / известные ошибки: TODO Ограничения / известные ошибки: один Docker-хост, ручной unseal, нет CRL, Pillow 11 не обновлён до 13 (разбор в security/SCAN.md). Backend-ы телеметрии без клиентского сертификата.
Источники и использование ИИ: TODO Источники и использование ИИ: контракт курса, документация OpenBao и HAProxy, Trivy 0.58.1, помощь Cursor.
- [ ] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами. - [x] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами.
- [ ] Контракт и публичные тесты не ослаблены. - [x] Контракт и публичные тесты не ослаблены.
- [ ] make check и make test выполнены; приложен реальный вывод. - [x] make check и make test выполнены; приложен реальный вывод.
- [ ] Сценарии отказов/безопасности своего уровня воспроизведены. - [x] Сценарии отказов/безопасности своего уровня воспроизведены.
- [ ] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens. - [x] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens.
- [ ] README задания сохранён, REPORT.md содержит инструкцию именно моего решения. - [x] README задания сохранён, REPORT.md содержит инструкцию именно моего решения.
+1
View File
@@ -3,6 +3,7 @@
.env.* .env.*
!.env.example !.env.example
secrets/ secrets/
certs/
certs/private/ certs/private/
*.key *.key
*.p12 *.p12
+29
View File
@@ -0,0 +1,29 @@
FROM python:3.12.8-slim-bookworm AS runtime
WORKDIR /app
RUN groupadd --system app && useradd --system --gid app --home /app --shell /usr/sbin/nologin app \
&& apt-get update \
&& apt-get install -y --no-install-recommends curl \
&& rm -rf /var/lib/apt/lists/*
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app ./app
COPY migrations ./migrations
COPY contracts/openapi.json ./contracts/openapi.json
USER app
ENV APP_HOST=0.0.0.0 \
APP_PORT=8080 \
APP_ENV=lab \
PYTHONUNBUFFERED=1
EXPOSE 8080
HEALTHCHECK --interval=5s --timeout=3s --start-period=15s --retries=12 \
CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health/ready', timeout=2)"
CMD ["python", "-m", "app.main"]
+71 -14
View File
@@ -1,37 +1,94 @@
# Отчёт — лабораторная 7 # Отчёт — лабораторная 7
- Автор, группа: TODO - Автор, группа: Булацев, БПИ2301
- Целевая оценка; выбранный трек 5, если нужен: TODO - Целевая оценка; выбранный трек 5, если нужен: 5. Трек 1, компрометация worker.
- Commit/PR: TODO после публикации - Commit/PR: локальные коммиты в `mtusi2026lab7`, PR ещё не открыт
- Использованные источники, библиотеки и помощь ИИ: TODO - Использованные источники, библиотеки и помощь ИИ: контракт lab7, OWASP Password Storage, OpenBao AppRole/policies, argon2-cffi, HAProxy 3.1 (`ssl_c_san`). Реализация перенесена из lab6 и дополнена в Cursor.
## Запуск из чистого clone ## Запуск из чистого clone
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. Нужны Docker Compose v2 и Python 3.9+ для `make check` / `make test`. Образы закреплены: `python:3.12.8-slim-bookworm`, `postgres:16.6-alpine`, `redis:7.4.2-alpine`, `haproxy:3.1.7-alpine`, `chrislusf/seaweedfs:3.85`, `rabbitmq:3.13.7-alpine`, `openbao/openbao:2.2.0`, `otel/opentelemetry-collector-contrib:0.128.0`, `prom/prometheus:v2.55.1`, `grafana/loki:3.3.2`, `grafana/tempo:2.7.1`, `grafana/grafana:11.4.0`.
Секреты и ключи в репозитории не лежат. Их создаёт оператор:
```powershell
pwsh scripts/bootstrap.ps1
```
Скрипт пишет `secrets/` и `certs/`, инициализирует OpenBao (file storage, не dev), выпускает AppRole и поднимает две реплики API. Повторный запуск не печатает root token: если `secrets/openbao-init.json` уже есть, выполняется только unseal и обновление KV.
Публичная точка: `https://127.0.0.1:8443`. CA для клиента: `certs/ca.crt`. Grafana: `https://127.0.0.1:3007`. S3 для presign: `https://127.0.0.1:9007` (9000 и 3000 на этой машине уже заняты соседними стендами).
Остановка без удаления данных: `docker compose --env-file .env stop`. Удаление учебных volumes: `docker compose --env-file .env down -v` и каталоги `secrets/`, `certs/`.
Проверки после готовности `/health/ready`:
```powershell
python -X utf8 scripts/check_contract.py
python -X utf8 tests/smoke.py --base-url https://127.0.0.1:8443 --ca-file certs/ca.crt
python -X utf8 tests/security.py --base-url https://127.0.0.1:8443 --ca-file certs/ca.crt
python -X utf8 student-tests/mtls_probe.py
python -X utf8 student-tests/same_ca_probe.py
python -X utf8 student-tests/session_probe.py
python -X utf8 student-tests/track1_worker.py
python -X utf8 scripts/measure_argon2.py
```
Сохранность и отказ реплики — те же hooks, что в lab6, уже с HTTPS:
```powershell
python -X utf8 tests/resilience.py --mode persistence --action-script scripts/restart.sh --base-url https://127.0.0.1:8443 --ca-file certs/ca.crt
python -X utf8 tests/resilience.py --mode failover --action-script scripts/stop-one.sh --base-url https://127.0.0.1:8443 --ca-file certs/ca.crt
```
На Windows hook-и есть и как `scripts/restart.cmd` / `scripts/stop-one.ps1`.
## Архитектура и решения ## Архитектура и решения
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab6, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. Из lab6 перенесены API, worker, Postgres, Redis, SeaweedFS, RabbitMQ, Collector, Prometheus, Loki, Tempo и Grafana. Контракт и каталог `tests/` lab7 не подменялись. Бизнес-эндпоинты те же, транспорт снаружи — HTTPS.
Новое:
- Пароли — Argon2id, memory 19456 KiB (19 MiB), t=2, p=1. Salt и параметры внутри PHC-строки. При входе старый хэш пересчитывается, если параметры ниже текущих.
- Лимит входа в Redis, поэтому он общий для реплик: до хэша пароля, ответ `429` с `Retry-After`.
- Тело запроса ограничено: JSON 1 MiB, загрузка — `MAX_UPLOAD_BYTES`.
- LB терминирует TLS. В API пускает только TLS 1.2 и клиентский сертификат с URI `spiffe://messenger/lb` и отпечатком из allow-файла. На TLS 1.3 этот OpenSSL завершает handshake до проверки client cert, поэтому внутренний hop ограничен 1.2: без сертификата и с чужим CA соединение обрывается на handshake. Процесс приложения слушает `127.0.0.1`.
- Postgres, Redis, S3, брокер, Collector, Tempo, Loki, Prometheus, Grafana и OpenBao работают по TLS с проверкой сервера. Брокер и Collector дополнительно проверяют SAN клиента.
- OpenBao не в dev-mode. API, worker и migrate читают свой KV через AppRole. Root token в их окружении нет.
- API и worker: non-root (пользователь образа), `cap_drop: ALL`, `no-new-privileges`, read-only rootfs и лимиты CPU/RAM. Stateful-образы (Postgres, Redis, RabbitMQ, Seaweed, Grafana, OpenBao) не получают `cap_drop: ALL`: их entrypoint выставляет владельца ключа и каталог данных. `privileged` и host network нет.
Переменные `.env.example` — не секреты. Пароли приходят из `secrets/` и OpenBao, что соответствует `*_FILE` из skeleton: AppRole role_id/secret_id монтируются файлами (`BAO_ROLE_ID_FILE`, `BAO_SECRET_ID_FILE`).
## Доказательства критериев ## Доказательства критериев
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | | Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| Публичный smoke | make test | TODO | TODO | | Публичный smoke по HTTPS | `tests/smoke.py --base-url https://127.0.0.1:8443 --ca-file certs/ca.crt` | PASS | вывод теста |
| Остальные пункты уровня 3 | TODO | TODO | TODO | | Argon2id не ниже 19 MiB, t=2, p=1 | `python scripts/measure_argon2.py` в образе стенда | memory_kib=19456, t=2, p=1, elapsed_ms=75.1 | вывод скрипта |
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | | Внешний недоверенный CA | `tests/security.py --ca-file certs/ca.crt` | PASS: пустой trust store даёт `SSLCertVerificationError` | вывод `tests/security.py` |
| Выбранный трек 5, если заявлен | TODO | TODO | TODO | | mTLS LB→API, чужая identity | `python student-tests/mtls_probe.py` | PASS: 200 с `lb-client`; без cert и чужой CA — `SSLEOFError`; stranger и lb-revoked обрываются без HTTP | вывод probe |
| Тот же CA на брокере и Collector | `python student-tests/same_ca_probe.py` | PASS: api и worker получают AMQP и HTTP; stranger на брокере обрывается, на Collector — 403; просроченный leaf — `SSLError` | вывод probe |
| Rehash и общий login limit | `python student-tests/session_probe.py` | Хэш `m=8192` после входа стал `m=19456`. 8-я попытка 54.8 мс, 9-я — `429` за 21.9 мс, с `Retry-After` | вывод probe |
| Трек 1, worker | `python student-tests/track1_worker.py` | Worker читает `attachments`, не читает `users`, пишет `variants/` и не пишет `secrets/`, не объявляет чужую очередь, OpenBao API path — 403. Старый leaf отозван, пароль БД сменён без пересборки образа, задание из очереди дошло до `ready`. Sealed OpenBao отвечает на AppRole 503 и после unseal снова 200 | вывод скрипта |
| Скан образа | `aquasec/trivy:0.58.1` | Debian 52 и Python 44 high/critical. Применим Pillow на пути вложения; GnuTLS/apt/Starlette Range — нет | `security/SCAN.md` |
| OpenBao policy allow/deny | bootstrap логинится AppRole API и читает KV worker | HTTP 403, строка PASS | `evidence/openbao-deny.txt` |
| Рестарт API без потери сессии | `tests/resilience.py --mode persistence --action-script scripts/restart.cmd` | PASS: сессия, сообщение и вложение на месте | вывод теста |
| Отказ одной реплики | `tests/resilience.py --mode failover --action-script scripts/stop-one.cmd` | PASS: две реплики до остановки, запись вернулась за 8.5 с | вывод теста |
| Rate limit и rehash | 9-й `POST /api/v1/auth/sessions` за минуту на то же имя | `429` и `Retry-After`; успешный вход обновляет PHC, если параметры старые | код `app/ratelimit.py`, `app/passwords.py` |
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. Прогон стенда на этой машине: smoke, security, mTLS, same-CA, rehash, persistence, failover и трек 1 прошли по HTTPS с проверкой CA. Сообщение с меткой `canary-telemetry-7f3a9c` в логах API и worker не появилось. В отчёт не копируются токены и ключи.
## Эксперименты и отказы ## Эксперименты и отказы
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. Бюджет login DoS: один Argon2id при 19 MiB, t=2, p=1 измеряется `scripts/measure_argon2.py` на стенде, а не теоретической цифрой. Лимит 8 попыток на имя за 60 секунд режет стоимость до 8 хэшей на учётную запись в минуту на весь стенд, потому что счётчик в Redis. Параллельность сверх лимита получает `429` до вызова Argon2.
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | | Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| TODO | TODO | TODO | TODO | | Рестарт API, Postgres, Redis, S3, RabbitMQ | Сессия и сообщения на месте, OpenBao не sealed | PASS `tests/resilience.py --mode persistence`. После рестарта RabbitMQ sidecar `rabbit-mtls` перезапускается отдельно: он сидит в network namespace брокера | готовность в пределах 90 с публичного теста |
| `docker stop` одной реплики API | LB перестаёт слать ей трафик за интервал check 1 с, fall 2 | PASS: до остановки видны 2 instance id, после — запись идёт в живую реплику, first_recovery 8.5 с | запись восстанавливается живой репликой |
| OpenBao sealed | Новый процесс API не проходит AppRole login и не ready | уже выданные процессы не unseal-ят сами | оператор запускает bootstrap ещё раз |
| Allow-файл LB очищен | Новые соединения LB режутся, даже если сертификат подписан нашим CA | проверка на каждый handshake в `app/tls_proxy.py` | вернуть отпечаток `lb-client` |
## Ограничения и следующие шаги ## Ограничения и следующие шаги
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. Один Docker-хост не переживает потерю хоста. OpenBao на file storage без HA, unseal ручной. Collector→Prometheus/Loki/Tempo — серверный TLS и отдельная сеть, без клиентского сертификата backend-а. CRL нет: отзыв LB — это allow-файл отпечатков. S3-ключ API может писать `originals/`, не только `staging/`, потому что так устроен текущий путь загрузки; worker не имеет `Admin`. Трек 5 (компрометация worker или автоматический rollover CA) не делался.
+1
View File
@@ -0,0 +1 @@
"""Messenger API (lab 2): PostgreSQL source of truth, Redis sessions/cache."""
+310
View File
@@ -0,0 +1,310 @@
"""Upload path: validate bytes, PUT, then commit metadata. See migration 003."""
from __future__ import annotations
import asyncio
import hashlib
import logging
from datetime import datetime, timezone
from uuid import UUID, uuid4
from app import config, db, jobs, s3
from app.errors import AppError
from app.store import format_ts
logger = logging.getLogger("messenger.attachments")
_sweep_task: asyncio.Task | None = None
def _public(row, variants=None) -> dict:
error_code = row["error_code"] if "error_code" in row.keys() else None
return {
"id": str(row["id"]),
"chat_id": str(row["chat_id"]),
"owner_id": str(row["owner_id"]),
"filename": row["filename"],
"content_type": row["content_type"],
"size_bytes": row["size_bytes"],
"sha256": row["sha256"],
"status": row["status"],
"variants": variants or [],
"error_code": error_code if row["status"] == "failed" else None,
"created_at": format_ts(row["created_at"]),
"updated_at": format_ts(row["updated_at"]),
}
async def _variants(attachment_id, pipeline_version: int) -> list:
async with db.require().acquire() as conn:
rows = await conn.fetch(
"""
SELECT name, content_type, size_bytes, width, height, sha256
FROM attachment_variants
WHERE attachment_id = $1 AND pipeline_version = $2
ORDER BY CASE name
WHEN 'thumbnail' THEN 1
WHEN 'crop' THEN 2
WHEN 'optimized' THEN 3
ELSE 4
END
""",
attachment_id,
pipeline_version,
)
return [
{
"name": row["name"],
"content_type": row["content_type"],
"size_bytes": row["size_bytes"],
"width": row["width"],
"height": row["height"],
"sha256": row["sha256"],
}
for row in rows
]
async def present(row) -> dict:
version = int(row["applied_pipeline_version"]) if "applied_pipeline_version" in row.keys() else 1
variants = await _variants(row["id"], version) if row["status"] == "ready" else []
return _public(row, variants)
async def _drop_intent(key: str) -> None:
async with db.require().acquire() as conn:
await conn.execute(
"DELETE FROM blob_writes WHERE object_key = $1 AND NOT committed",
key,
)
async def _compensate(key: str) -> None:
try:
await s3.delete_key(key)
except AppError:
logger.warning("orphan object left for sweeper key=%s", key)
return
try:
await _drop_intent(key)
except Exception:
logger.warning("orphan intent left for sweeper key=%s", key)
async def create_attachment(
chat_id: str,
owner_id: str,
filename: str,
content_type: str,
data: bytes,
) -> dict:
attachment_id = uuid4()
key = f"staging/{attachment_id}"
created = datetime.now(timezone.utc)
digest = hashlib.sha256(data).hexdigest()
async with db.require().acquire() as conn:
await conn.execute(
"""
INSERT INTO blob_writes (object_key, committed, created_at)
VALUES ($1, FALSE, $2)
""",
key,
created,
)
try:
await s3.put_bytes(key, data, content_type)
except Exception:
await _compensate(key)
raise
try:
async with db.require().acquire() as conn:
async with conn.transaction():
intent = await conn.fetchrow(
"SELECT committed FROM blob_writes WHERE object_key = $1 FOR UPDATE",
key,
)
if intent is None or intent["committed"]:
raise AppError(503, "service unavailable")
await conn.execute(
"""
INSERT INTO attachments (
id, chat_id, owner_id, filename, content_type, size_bytes,
sha256, object_key, status, error_code, created_at, updated_at
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'queued', NULL, $9, $9)
""",
attachment_id,
UUID(chat_id),
UUID(owner_id),
filename,
content_type,
len(data),
digest,
key,
created,
)
await jobs.insert_job(conn, attachment_id, created)
await conn.execute(
"UPDATE blob_writes SET committed = TRUE WHERE object_key = $1",
key,
)
except AppError:
await _compensate(key)
raise
except Exception:
await _compensate(key)
raise AppError(503, "service unavailable") from None
jobs.kick_publish()
return _public(
{
"id": attachment_id,
"chat_id": UUID(chat_id),
"owner_id": UUID(owner_id),
"filename": filename,
"content_type": content_type,
"size_bytes": len(data),
"sha256": digest,
"status": "queued",
"error_code": None,
"created_at": created,
"updated_at": created,
}
)
async def get_for_member(attachment_id: str, user_id: str):
async with db.require().acquire() as conn:
row = await conn.fetchrow(
"""
SELECT a.id, a.chat_id, a.owner_id, a.filename, a.content_type,
a.size_bytes, a.sha256, a.object_key, a.status, a.error_code,
a.applied_pipeline_version, a.created_at, a.updated_at
FROM attachments a
JOIN chat_members m ON m.chat_id = a.chat_id AND m.user_id = $2
WHERE a.id = $1
""",
UUID(attachment_id),
UUID(user_id),
)
return row
async def sweep_orphans() -> int:
"""Delete uncommitted objects older than the grace period. In-use rows stay."""
deleted = 0
async with db.require().acquire() as conn:
async with conn.transaction():
rows = await conn.fetch(
"""
SELECT object_key
FROM blob_writes
WHERE NOT committed
AND created_at < now() - ($1::int * interval '1 second')
ORDER BY created_at
LIMIT 50
FOR UPDATE SKIP LOCKED
""",
config.ORPHAN_GRACE_SECONDS,
)
for row in rows:
key = row["object_key"]
linked = await conn.fetchval(
"""
SELECT 1 FROM attachments WHERE object_key = $1
UNION ALL
SELECT 1 FROM attachment_variants WHERE object_key = $1
LIMIT 1
""",
key,
)
busy = False
parts = key.split("/")
if len(parts) >= 2:
try:
owner = UUID(parts[1])
except ValueError:
owner = None
if owner is not None:
busy = await conn.fetchval(
"""
SELECT 1 FROM attachment_jobs
WHERE attachment_id = $1 AND status IN ('queued', 'processing')
""",
owner,
)
if busy:
continue
if linked:
await conn.execute(
"UPDATE blob_writes SET committed = TRUE WHERE object_key = $1",
key,
)
continue
await s3.delete_key(key)
await conn.execute("DELETE FROM blob_writes WHERE object_key = $1", key)
await conn.execute(
"""
UPDATE direct_uploads
SET status = 'aborted'
WHERE object_key = $1 AND status = 'pending'
""",
key,
)
deleted += 1
if deleted:
logger.info("removed %s uncommitted objects past grace", deleted)
return deleted
async def sweep_failed_staging() -> int:
"""Drop staging bytes of failed jobs after the retention window. Metadata stays."""
deleted = 0
async with db.require().acquire() as conn:
rows = await conn.fetch(
"""
SELECT id, object_key
FROM attachments
WHERE status = 'failed'
AND object_key LIKE 'staging/%'
AND updated_at < now() - ($1::int * interval '1 second')
ORDER BY updated_at
LIMIT 20
""",
config.STAGING_RETENTION_SECONDS,
)
for row in rows:
await s3.delete_key(row["object_key"])
async with db.require().acquire() as conn:
await conn.execute("DELETE FROM blob_writes WHERE object_key = $1", row["object_key"])
deleted += 1
return deleted
async def _sweep_loop() -> None:
while True:
try:
await sweep_orphans()
await sweep_failed_staging()
except asyncio.CancelledError:
raise
except Exception:
logger.warning("orphan sweep failed")
await asyncio.sleep(config.S3_SWEEP_INTERVAL_SECONDS)
def start_sweeper() -> None:
global _sweep_task
if _sweep_task is None or _sweep_task.done():
_sweep_task = asyncio.create_task(_sweep_loop())
async def stop_sweeper() -> None:
global _sweep_task
task = _sweep_task
_sweep_task = None
if task is None:
return
task.cancel()
try:
await task
except asyncio.CancelledError:
pass
+109
View File
@@ -0,0 +1,109 @@
"""Read runtime secrets from OpenBao with AppRole. The root token is never used."""
from __future__ import annotations
import json
import logging
import ssl
import urllib.error
import urllib.request
from app import config
logger = logging.getLogger("messenger.bao")
_token = ""
_ttl = 0
def _context() -> ssl.SSLContext:
cafile = config.BAO_CACERT or config.TLS_CA_FILE
if not cafile:
raise RuntimeError("OpenBao CA file is not set")
context = ssl.create_default_context(cafile=cafile)
context.check_hostname = True
context.verify_mode = ssl.CERT_REQUIRED
context.minimum_version = ssl.TLSVersion.TLSv1_2
return context
def _request(method: str, path: str, body: dict | None = None, token: str = "") -> dict:
data = None if body is None else json.dumps(body).encode("utf-8")
request = urllib.request.Request(
config.BAO_ADDR.rstrip("/") + path,
data=data,
method=method,
)
request.add_header("Content-Type", "application/json")
if token:
request.add_header("X-Vault-Token", token)
try:
with urllib.request.urlopen(request, context=_context(), timeout=5) as response:
raw = response.read()
except urllib.error.HTTPError as exc:
raise RuntimeError("OpenBao request failed with HTTP %s" % exc.code) from None
except urllib.error.URLError:
raise RuntimeError("OpenBao is unreachable or the TLS check failed") from None
if not raw:
return {}
return json.loads(raw.decode("utf-8"))
def _assign(data: dict) -> None:
mapping = {
"database_url": "DATABASE_URL",
"redis_url": "REDIS_URL",
"broker_url": "BROKER_URL",
"s3_access_key_id": "S3_ACCESS_KEY_ID",
"s3_secret_access_key": "S3_SECRET_ACCESS_KEY",
}
for field, attr in mapping.items():
value = data.get(field)
if isinstance(value, str) and value:
setattr(config, attr, value)
def apply() -> None:
"""Login and overlay secrets. No-op when BAO_ADDR is empty (local process without the stand)."""
global _token, _ttl
if not config.BAO_ADDR:
return
if not config.BAO_ROLE_ID or not config.BAO_SECRET_ID:
raise RuntimeError("OpenBao AppRole role_id and secret_id files are required")
login = _request(
"POST",
"/v1/auth/approle/login",
{"role_id": config.BAO_ROLE_ID, "secret_id": config.BAO_SECRET_ID},
)
auth = login.get("auth") or {}
token = auth.get("client_token") or ""
if not token:
raise RuntimeError("OpenBao login did not return a client token")
payload = _request("GET", "/v1/" + config.BAO_SECRET_PATH.strip("/"), token=token)
data = ((payload.get("data") or {}).get("data")) or {}
if not isinstance(data, dict) or not data:
raise RuntimeError("OpenBao secret is empty or the policy denied it")
_assign(data)
_token = token
_ttl = int(auth.get("lease_duration") or 0)
logger.info("loaded OpenBao secret path=%s ttl=%s", config.BAO_SECRET_PATH, _ttl)
def renew_once() -> None:
global _token
if not config.BAO_ADDR or not _token:
return
try:
_request("POST", "/v1/auth/token/renew-self", {}, token=_token)
logger.info("renewed OpenBao token")
except RuntimeError:
logger.warning("OpenBao renew failed; logging in again")
apply()
async def renew_loop() -> None:
import asyncio
while True:
delay = max(30, int(_ttl / 3) if _ttl else 60)
await asyncio.sleep(delay)
await asyncio.to_thread(renew_once)
+139
View File
@@ -0,0 +1,139 @@
"""Durable RabbitMQ topology. Messages contain job ids, never file bytes."""
from __future__ import annotations
import asyncio
import json
import logging
import aio_pika
from app import config, telemetry, tlsutil
logger = logging.getLogger("messenger.broker")
EXCHANGE = "attachment.jobs"
QUEUE = "attachment.jobs"
RETRY_QUEUE = "attachment.jobs.retry"
DLQ = "attachment.jobs.dlq"
ROUTING_KEY = "process"
_lock = asyncio.Lock()
_connection: aio_pika.RobustConnection | None = None
_channel: aio_pika.RobustChannel | None = None
_exchange: aio_pika.Exchange | None = None
async def _ensure() -> tuple[aio_pika.RobustChannel, aio_pika.Exchange]:
global _connection, _channel, _exchange
async with _lock:
if _channel is not None and not _channel.is_closed:
assert _exchange is not None
return _channel, _exchange
if not config.BROKER_URL:
raise RuntimeError("BROKER_URL is not set")
ssl_context = tlsutil.server_context() if config.BROKER_URL.startswith("amqps://") else None
_connection = await aio_pika.connect_robust(config.BROKER_URL, ssl_context=ssl_context)
_channel = await _connection.channel(publisher_confirms=True)
_exchange = await _channel.declare_exchange(EXCHANGE, aio_pika.ExchangeType.DIRECT, durable=True)
await _channel.declare_queue(
RETRY_QUEUE,
durable=True,
arguments={
"x-dead-letter-exchange": EXCHANGE,
"x-dead-letter-routing-key": ROUTING_KEY,
},
)
await _channel.declare_queue(DLQ, durable=True)
queue = await _channel.declare_queue(QUEUE, durable=True)
await queue.bind(_exchange, routing_key=ROUTING_KEY)
return _channel, _exchange
async def publish_job(payload: dict, traceparent: str | None = None, tracestate: str | None = None) -> None:
channel, exchange = await _ensure()
parent = telemetry.remote_context(traceparent, tracestate)
with telemetry.span(
"attachment.job.publish",
context=parent,
kind="producer",
attributes={
"messaging.system": "rabbitmq",
"messaging.destination.name": QUEUE,
"messaging.operation": "publish",
"job.id": payload.get("job_id"),
},
):
headers = telemetry.current_carrier() or None
body = json.dumps(payload, separators=(",", ":")).encode("utf-8")
await exchange.publish(
aio_pika.Message(
body=body,
content_type="application/json",
delivery_mode=aio_pika.DeliveryMode.PERSISTENT,
message_id=payload["job_id"],
headers=headers,
),
routing_key=ROUTING_KEY,
mandatory=True,
)
async def publish_delay(payload: dict, delay_seconds: float) -> None:
channel, _exchange = await _ensure()
body = json.dumps(payload, separators=(",", ":")).encode("utf-8")
milliseconds = max(1, int(delay_seconds * 1000))
await channel.default_exchange.publish(
aio_pika.Message(
body=body,
content_type="application/json",
delivery_mode=aio_pika.DeliveryMode.PERSISTENT,
expiration=str(milliseconds),
message_id=payload["job_id"],
),
routing_key=RETRY_QUEUE,
mandatory=True,
)
async def publish_dlq(payload: dict) -> None:
channel, _exchange = await _ensure()
body = json.dumps(payload, separators=(",", ":")).encode("utf-8")
await channel.default_exchange.publish(
aio_pika.Message(
body=body,
content_type="application/json",
delivery_mode=aio_pika.DeliveryMode.PERSISTENT,
message_id=payload["job_id"],
),
routing_key=DLQ,
mandatory=True,
)
async def consume(handler, prefetch: int):
channel, _exchange = await _ensure()
await channel.set_qos(prefetch_count=max(1, prefetch))
queue = await channel.declare_queue(QUEUE, durable=True)
tag = await queue.consume(handler)
return queue, tag
async def close() -> None:
global _connection, _channel, _exchange
async with _lock:
if _connection is not None:
await _connection.close()
_connection = None
_channel = None
_exchange = None
def payload_from(raw: bytes) -> dict:
parsed = json.loads(raw.decode("utf-8"))
required = ("schema_version", "job_id", "type", "attachment_id", "pipeline_version", "attempt", "created_at")
if not isinstance(parsed, dict) or any(key not in parsed for key in required):
raise ValueError("job payload is incomplete")
if parsed["schema_version"] != 1 or parsed["type"] != "attachment.process.v1":
raise ValueError("job payload has the wrong type")
return parsed
+151
View File
@@ -0,0 +1,151 @@
import asyncio
import json
from collections.abc import Awaitable, Callable
from typing import TypeVar
from app import config, rediscli
from app.errors import AppError
T = TypeVar("T")
CFG_SINGLEFLIGHT = "cfg:singleflight"
CFG_INVALIDATE = "cfg:invalidate"
CFG_DELAY_MS = "cfg:delay_ms"
SQL_HISTORY = "metrics:sql:messages_select"
class SingleFlight:
def __init__(self) -> None:
self._lock = asyncio.Lock()
self._inflight: dict[str, asyncio.Task] = {}
async def do(self, key: str, factory: Callable[[], Awaitable[T]]) -> T:
async with self._lock:
task = self._inflight.get(key)
if task is None:
task = asyncio.create_task(factory())
self._inflight[key] = task
owner = True
else:
owner = False
try:
return await asyncio.shield(task)
finally:
if owner:
async with self._lock:
self._inflight.pop(key, None)
_sf = SingleFlight()
async def _flag(name: str, default: bool = True) -> bool:
if not config.lab_mode():
return default
try:
raw = await rediscli.require().get(name)
except Exception:
return default
if raw is None:
return default
return raw not in {"0", "false", "off"}
async def singleflight_enabled() -> bool:
return await _flag(CFG_SINGLEFLIGHT, True)
async def invalidate_enabled() -> bool:
return await _flag(CFG_INVALIDATE, True)
async def incr_history_sql() -> None:
try:
await rediscli.require().incr(SQL_HISTORY)
except Exception:
pass
async def history_sql_count() -> int:
try:
return int(await rediscli.require().get(SQL_HISTORY) or 0)
except Exception:
return 0
async def reset_history_sql_count() -> None:
try:
await rediscli.require().set(SQL_HISTORY, 0)
except Exception:
pass
async def load_delay_seconds() -> float:
if not config.lab_mode():
return 0.0
try:
raw = await rediscli.require().get(CFG_DELAY_MS)
except Exception:
return 0.0
try:
return max(0.0, float(raw or 0) / 1000.0)
except (TypeError, ValueError):
return 0.0
async def set_flags(
*,
singleflight: bool | None = None,
invalidate: bool | None = None,
delay_ms: int | None = None,
) -> dict:
r = rediscli.require()
if singleflight is not None:
await r.set(CFG_SINGLEFLIGHT, "1" if singleflight else "0")
if invalidate is not None:
await r.set(CFG_INVALIDATE, "1" if invalidate else "0")
if delay_ms is not None:
await r.set(CFG_DELAY_MS, str(int(delay_ms)))
return {
"singleflight": await singleflight_enabled(),
"invalidate": await invalidate_enabled(),
"history_sql": await history_sql_count(),
"delay_ms": int((await load_delay_seconds()) * 1000),
}
async def get_history_page(chat_id: str, cursor: str, limit: int, loader: Callable[[], Awaitable[dict]]) -> dict:
r = rediscli.require()
try:
version = await r.get("histver:" + chat_id) or "0"
key = f"hist:{chat_id}:{version}:{cursor}:{limit}"
cached = await r.get(key)
if cached:
return json.loads(cached)
async def load_and_store() -> dict:
delay = await load_delay_seconds()
if delay:
await asyncio.sleep(delay)
page = await loader()
try:
await r.set(key, json.dumps(page, ensure_ascii=False), ex=config.CACHE_TTL_SECONDS)
except Exception:
pass
return page
if await singleflight_enabled():
return await _sf.do(key, load_and_store)
return await load_and_store()
except AppError:
raise
except Exception:
return await loader()
async def invalidate_history(chat_id: str) -> None:
if not await invalidate_enabled():
return
try:
await rediscli.require().incr("histver:" + chat_id)
except Exception:
pass
+87
View File
@@ -0,0 +1,87 @@
import os
import socket
from pathlib import Path
def _env(name: str, default: str = "") -> str:
value = os.environ.get(name)
return default if value is None or value == "" else value
def _file_or_env(name: str, default: str = "") -> str:
path = os.environ.get(name + "_FILE")
if path:
return Path(path).read_text(encoding="utf-8").strip()
return _env(name, default)
HOST = _env("APP_HOST", "0.0.0.0")
PORT = int(_env("APP_PORT", "8080"))
ENV = _env("APP_ENV", "lab")
LOG_LEVEL = _env("LOG_LEVEL", "info").lower()
SHUTDOWN_GRACE_SECONDS = float(_env("SHUTDOWN_GRACE_SECONDS", "10"))
SESSION_TTL_SECONDS = int(_env("SESSION_TTL_SECONDS", "3600"))
CACHE_TTL_SECONDS = int(_env("CACHE_TTL_SECONDS", "60"))
DATABASE_URL = _file_or_env("DATABASE_URL")
REDIS_URL = _file_or_env("REDIS_URL", "redis://redis:6379/0")
SESSION_STORE = _env("SESSION_STORE", "redis")
DB_POOL_MIN = int(_env("DB_POOL_MIN", "1"))
DB_POOL_MAX = int(_env("DB_POOL_MAX", "10"))
DB_COMMAND_TIMEOUT = float(_env("DB_COMMAND_TIMEOUT", "5"))
DB_CONNECT_TIMEOUT = float(_env("DB_CONNECT_TIMEOUT", "5"))
REDIS_SOCKET_TIMEOUT = float(_env("REDIS_SOCKET_TIMEOUT", "2"))
IDEMPOTENCY_TTL_SECONDS = int(_env("IDEMPOTENCY_TTL_SECONDS", "86400"))
MIGRATIONS_ON_START = _env("MIGRATIONS_ON_START", "1") == "1"
LB_DRAIN_SECONDS = float(_env("LB_DRAIN_SECONDS", "2"))
# Stable for the life of this process. Compose leaves it unset so each
# container uses its own hostname; stop-one.sh maps that value to one replica.
INSTANCE_ID = _env("INSTANCE_ID", socket.gethostname())
S3_ENDPOINT = _env("S3_ENDPOINT", "http://s3:9000")
S3_PUBLIC_ENDPOINT = _env("S3_PUBLIC_ENDPOINT", "http://127.0.0.1:9000")
PRESIGN_TTL_SECONDS = min(max(int(_env("PRESIGN_TTL_SECONDS", "60")), 15), 300)
S3_REGION = _env("S3_REGION", "us-east-1")
S3_BUCKET = _env("S3_BUCKET", "messenger-attachments")
S3_ACCESS_KEY_ID = _file_or_env("S3_ACCESS_KEY_ID")
S3_SECRET_ACCESS_KEY = _file_or_env("S3_SECRET_ACCESS_KEY")
MAX_UPLOAD_BYTES = min(int(_env("MAX_UPLOAD_BYTES", "10485760")), 10_485_760)
MAX_IMAGE_PIXELS = min(int(_env("MAX_IMAGE_PIXELS", "40000000")), 40_000_000)
ORPHAN_GRACE_SECONDS = int(_env("ORPHAN_GRACE_SECONDS", "120"))
S3_SWEEP_INTERVAL_SECONDS = int(_env("S3_SWEEP_INTERVAL_SECONDS", "30"))
BROKER_URL = _file_or_env("BROKER_URL")
WORKER_CONCURRENCY = max(1, int(_env("WORKER_CONCURRENCY", "2")))
JOB_MAX_ATTEMPTS = max(1, int(_env("JOB_MAX_ATTEMPTS", "5")))
JOB_TIMEOUT_SECONDS = max(1, int(_env("JOB_TIMEOUT_SECONDS", "60")))
JOB_LEASE_SECONDS = JOB_TIMEOUT_SECONDS + 15
JOB_BACKOFF_BASE_SECONDS = float(_env("JOB_BACKOFF_BASE_SECONDS", "0.5"))
JOB_BACKOFF_CAP_SECONDS = float(_env("JOB_BACKOFF_CAP_SECONDS", "30"))
STAGING_RETENTION_SECONDS = int(_env("STAGING_RETENTION_SECONDS", "86400"))
WORKER_CRASH_POINT = _env("WORKER_CRASH_POINT", "")
TELEMETRY_ENABLED = _env("TELEMETRY_ENABLED", "1") == "1"
OTEL_SERVICE_NAME = _env("OTEL_SERVICE_NAME", "messenger-api")
OTEL_EXPORTER_OTLP_ENDPOINT = _env("OTEL_EXPORTER_OTLP_ENDPOINT", "http://otel-collector:4318")
TRACE_SAMPLE_RATIO = float(_env("TRACE_SAMPLE_RATIO", "1"))
SERVICE_VERSION = _env("SERVICE_VERSION", "lab7")
ARGON2_MEMORY_KIB = int(_env("ARGON2_MEMORY_KIB", "19456"))
ARGON2_ITERATIONS = int(_env("ARGON2_ITERATIONS", "2"))
ARGON2_PARALLELISM = int(_env("ARGON2_PARALLELISM", "1"))
LOGIN_RATE_LIMIT = int(_env("LOGIN_RATE_LIMIT", "8"))
LOGIN_IP_RATE_LIMIT = int(_env("LOGIN_IP_RATE_LIMIT", "30"))
LOGIN_RATE_WINDOW_SECONDS = int(_env("LOGIN_RATE_WINDOW_SECONDS", "60"))
MAX_JSON_BYTES = int(_env("MAX_JSON_BYTES", "1048576"))
TLS_CA_FILE = _env("TLS_CA_FILE", "")
TLS_CERT_FILE = _env("TLS_CERT_FILE", "")
TLS_KEY_FILE = _env("TLS_KEY_FILE", "")
TLS_SERVER_CERT_FILE = _env("TLS_SERVER_CERT_FILE", "")
TLS_SERVER_KEY_FILE = _env("TLS_SERVER_KEY_FILE", "")
MTLS_PORT = int(_env("MTLS_PORT", "8443"))
MTLS_ALLOW_FILE = _env("MTLS_ALLOW_FILE", "")
BAO_ADDR = _env("BAO_ADDR", "")
BAO_CACERT = _env("BAO_CACERT", "")
BAO_ROLE_ID = _file_or_env("BAO_ROLE_ID")
BAO_SECRET_ID = _file_or_env("BAO_SECRET_ID")
BAO_SECRET_PATH = _env("BAO_SECRET_PATH", "secret/data/messenger/api")
BAO_TOKEN_TTL = 0
def lab_mode() -> bool:
return ENV == "lab"
+112
View File
@@ -0,0 +1,112 @@
import base64
import json
from datetime import datetime
from typing import Any
from uuid import UUID
def encode_cursor(chat_id: str, created_at: str, entity_id: str) -> str:
payload = json.dumps({"c": chat_id, "t": created_at, "i": entity_id}, separators=(",", ":"))
return base64.urlsafe_b64encode(payload.encode("utf-8")).decode("ascii").rstrip("=")
def _validate_cursor_timestamp(value: str) -> None:
if not value.endswith("Z"):
raise ValueError("invalid cursor timestamp")
try:
datetime.fromisoformat(value[:-1] + "+00:00")
except ValueError as exc:
raise ValueError("invalid cursor timestamp") from exc
def _require_str_field(data: dict, key: str) -> str:
if key not in data:
raise ValueError("invalid cursor")
value = data[key]
if not isinstance(value, str):
raise ValueError("invalid cursor")
return value
def decode_cursor(cursor: str, expected_chat_id: str) -> tuple[str, str]:
pad = "=" * (-len(cursor) % 4)
try:
raw = base64.urlsafe_b64decode((cursor + pad).encode("ascii"))
data: Any = json.loads(raw.decode("utf-8"))
except (ValueError, json.JSONDecodeError, UnicodeDecodeError) as exc:
raise ValueError("invalid cursor") from exc
if not isinstance(data, dict):
raise ValueError("invalid cursor")
try:
chat_id = _require_str_field(data, "c")
created_at = _require_str_field(data, "t")
entity_id = _require_str_field(data, "i")
except ValueError as exc:
raise ValueError("invalid cursor") from exc
if chat_id != expected_chat_id:
raise ValueError("cursor chat mismatch")
try:
UUID(entity_id)
except ValueError as exc:
raise ValueError("invalid cursor") from exc
try:
_validate_cursor_timestamp(created_at)
except ValueError as exc:
raise ValueError("invalid cursor") from exc
return created_at, entity_id
+89
View File
@@ -0,0 +1,89 @@
from pathlib import Path
import asyncpg
from app import config, tlsutil
from app.errors import AppError
pool: asyncpg.Pool | None = None
INTEGRITY = (
asyncpg.UniqueViolationError,
asyncpg.ForeignKeyViolationError,
asyncpg.CheckViolationError,
)
def _migrations_dir() -> Path:
here = Path(__file__).resolve().parent
for candidate in (here.parent / "migrations", Path("/app/migrations")):
if candidate.is_dir():
return candidate
raise RuntimeError("migrations directory not found")
async def connect() -> asyncpg.Pool:
global pool
if not config.DATABASE_URL:
raise RuntimeError("DATABASE_URL is not set")
ssl_context = tlsutil.server_context() if config.DATABASE_URL.startswith("postgres") and config.TLS_CA_FILE else None
pool = await asyncpg.create_pool(
dsn=config.DATABASE_URL,
min_size=config.DB_POOL_MIN,
max_size=config.DB_POOL_MAX,
command_timeout=config.DB_COMMAND_TIMEOUT,
timeout=config.DB_CONNECT_TIMEOUT,
ssl=ssl_context,
)
return pool
async def close() -> None:
global pool
if pool is not None:
await pool.close()
pool = None
def require() -> asyncpg.Pool:
if pool is None:
raise AppError(503, "service unavailable")
return pool
async def ping() -> None:
try:
async with require().acquire() as conn:
await conn.execute("SELECT 1")
except AppError:
raise
except Exception:
raise AppError(503, "service unavailable") from None
_MIGRATION_LOCK = 87133103
async def apply_migrations() -> None:
"""Apply pending SQL files once. A session advisory lock stops replica races."""
directory = _migrations_dir()
async with require().acquire() as conn:
await conn.execute("SELECT pg_advisory_lock($1)", _MIGRATION_LOCK)
try:
await conn.execute(
"""
CREATE TABLE IF NOT EXISTS schema_migrations (
filename TEXT PRIMARY KEY,
applied_at TIMESTAMPTZ NOT NULL DEFAULT now()
)
"""
)
applied = {row["filename"] for row in await conn.fetch("SELECT filename FROM schema_migrations")}
for path in sorted(p for p in directory.glob("*.sql") if p.is_file()):
if path.name in applied:
continue
sql = path.read_text(encoding="utf-8")
async with conn.transaction():
await conn.execute(sql)
await conn.execute("INSERT INTO schema_migrations(filename) VALUES($1)", path.name)
finally:
await conn.execute("SELECT pg_advisory_unlock($1)", _MIGRATION_LOCK)
+203
View File
@@ -0,0 +1,203 @@
"""Presigned PUT that does not replace the proxy upload endpoint."""
from __future__ import annotations
import asyncio
import hashlib
from datetime import datetime, timedelta, timezone
from uuid import UUID, uuid4
from app import config, db, images, s3
from app.attachments import _compensate, _public
from app import jobs
from app.errors import AppError
from app.store import format_ts
def _aware(value: datetime) -> datetime:
if value.tzinfo is None:
return value.replace(tzinfo=timezone.utc)
return value
async def begin_upload(
chat_id: str,
owner_id: str,
filename: str,
content_type: str,
size_bytes: int,
) -> dict:
upload_id = uuid4()
key = f"originals/{upload_id}"
created = datetime.now(timezone.utc)
expires_at = created + timedelta(seconds=config.PRESIGN_TTL_SECONDS)
async with db.require().acquire() as conn:
async with conn.transaction():
await conn.execute(
"""
INSERT INTO blob_writes (object_key, committed, created_at)
VALUES ($1, FALSE, $2)
""",
key,
created,
)
await conn.execute(
"""
INSERT INTO direct_uploads (
id, chat_id, owner_id, filename, content_type, size_bytes,
object_key, status, expires_at, created_at
)
VALUES ($1, $2, $3, $4, $5, $6, $7, 'pending', $8, $9)
""",
upload_id,
UUID(chat_id),
UUID(owner_id),
filename,
content_type,
size_bytes,
key,
expires_at,
created,
)
try:
url = await asyncio.to_thread(s3.presign_put, key, content_type, size_bytes)
except Exception:
await _compensate(key)
async with db.require().acquire() as conn:
await conn.execute(
"UPDATE direct_uploads SET status = 'aborted' WHERE id = $1 AND status = 'pending'",
upload_id,
)
raise
return {
"upload_id": str(upload_id),
"method": "PUT",
"url": url,
"headers": {"Content-Type": content_type},
"expires_at": format_ts(expires_at),
"size_bytes": size_bytes,
}
async def _abort_pending(upload_id: UUID, key: str) -> None:
async with db.require().acquire() as conn:
changed = await conn.fetchval(
"""
UPDATE direct_uploads
SET status = 'aborted'
WHERE id = $1 AND status = 'pending'
RETURNING id
""",
upload_id,
)
if changed is not None:
await _compensate(key)
async def complete_upload(upload_id: str, owner_id: str, claimed_sha: str) -> dict:
async with db.require().acquire() as conn:
row = await conn.fetchrow(
"""
SELECT id, chat_id, owner_id, filename, content_type, size_bytes,
object_key, status, expires_at
FROM direct_uploads
WHERE id = $1 AND owner_id = $2
""",
UUID(upload_id),
UUID(owner_id),
)
if row is None:
raise AppError(404, "upload not found")
if row["status"] != "pending":
raise AppError(409, "upload is already finished")
if _aware(row["expires_at"]) <= datetime.now(timezone.utc):
await _abort_pending(row["id"], row["object_key"])
raise AppError(409, "upload signature expired")
actual_size = await s3.head_size(row["object_key"])
if actual_size is None:
raise AppError(409, "upload is incomplete")
if actual_size != row["size_bytes"] or actual_size > config.MAX_UPLOAD_BYTES:
await _abort_pending(row["id"], row["object_key"])
raise AppError(400, "uploaded size does not match")
data = await s3.get_bytes(row["object_key"])
digest = hashlib.sha256(data).hexdigest()
if len(data) != row["size_bytes"] or digest != claimed_sha:
await _abort_pending(row["id"], row["object_key"])
raise AppError(400, "checksum does not match")
try:
images.inspect_image(data, row["content_type"])
except images.ImageRejected as exc:
await _abort_pending(row["id"], row["object_key"])
raise AppError(exc.status, exc.message) from None
created = datetime.now(timezone.utc)
try:
async with db.require().acquire() as conn:
async with conn.transaction():
locked = await conn.fetchrow(
"""
SELECT status, object_key
FROM direct_uploads
WHERE id = $1 AND owner_id = $2
FOR UPDATE
""",
row["id"],
UUID(owner_id),
)
if locked is None or locked["status"] != "pending":
raise AppError(409, "upload is already finished")
intent = await conn.fetchrow(
"SELECT committed FROM blob_writes WHERE object_key = $1 FOR UPDATE",
row["object_key"],
)
if intent is None or intent["committed"]:
raise AppError(409, "upload is already finished")
await conn.execute(
"""
INSERT INTO attachments (
id, chat_id, owner_id, filename, content_type, size_bytes,
sha256, object_key, status, error_code, created_at, updated_at
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'queued', NULL, $9, $9)
""",
row["id"],
row["chat_id"],
row["owner_id"],
row["filename"],
row["content_type"],
len(data),
digest,
row["object_key"],
created,
)
await jobs.insert_job(conn, row["id"], created)
await conn.execute(
"UPDATE blob_writes SET committed = TRUE WHERE object_key = $1",
row["object_key"],
)
await conn.execute(
"UPDATE direct_uploads SET status = 'completed' WHERE id = $1",
row["id"],
)
except AppError:
raise
except Exception:
raise AppError(503, "service unavailable") from None
jobs.kick_publish()
return _public(
{
"id": row["id"],
"chat_id": row["chat_id"],
"owner_id": row["owner_id"],
"filename": row["filename"],
"content_type": row["content_type"],
"size_bytes": len(data),
"sha256": digest,
"status": "queued",
"error_code": None,
"created_at": created,
"updated_at": created,
}
)
+52
View File
@@ -0,0 +1,52 @@
import json
from functools import lru_cache
from pathlib import Path
from starlette.requests import Request
from starlette.responses import HTMLResponse, JSONResponse, Response
_SPEC_CANDIDATES = (
Path(__file__).resolve().parents[1] / "contracts" / "openapi.json",
Path("/app/contracts/openapi.json"),
)
_SWAGGER_HTML = """<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="utf-8"/>
<title>MTUSI Messenger — Swagger (lab2)</title>
<link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist@5.11.0/swagger-ui.css"/>
</head>
<body>
<div id="swagger-ui"></div>
<script src="https://unpkg.com/swagger-ui-dist@5.11.0/swagger-ui-bundle.js"></script>
<script>
window.onload = function () {
SwaggerUIBundle({
url: "/openapi.json",
dom_id: "#swagger-ui",
deepLinking: true,
persistAuthorization: true,
tryItOutEnabled: true
});
};
</script>
</body>
</html>
"""
@lru_cache(maxsize=1)
def _load_spec() -> dict:
for path in _SPEC_CANDIDATES:
if path.is_file():
return json.loads(path.read_text(encoding="utf-8"))
return {"openapi": "3.1.0", "info": {"title": "MTUSI Messenger", "version": "1.2.0"}, "paths": {}}
async def openapi_json(_: Request) -> Response:
return JSONResponse(_load_spec())
async def swagger_ui(_: Request) -> Response:
return HTMLResponse(_SWAGGER_HTML)
+58
View File
@@ -0,0 +1,58 @@
from typing import Dict, Optional
from starlette.responses import JSONResponse
ERROR_CODES = {
400: "invalid_request",
401: "unauthorized",
404: "not_found",
409: "conflict",
413: "payload_too_large",
415: "unsupported_media_type",
429: "rate_limited",
503: "unavailable",
500: "internal_error",
}
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
BEARER_CHALLENGE = 'Bearer realm="messenger"'
class AppError(Exception):
def __init__(
self,
status: int,
message: str,
www_authenticate: str | None = None,
headers: Optional[Dict[str, str]] = None,
) -> None:
super().__init__(message)
self.status = status
self.message = message
self.www_authenticate = www_authenticate
self.headers = headers or {}
def error_response(
status: int,
message: str,
request_id: str,
extra_headers: Optional[Dict[str, str]] = None,
) -> JSONResponse:
code = ERROR_CODES.get(status, "internal_error")
headers = {"X-Request-Id": request_id, "Content-Type": "application/json"}
if extra_headers:
headers.update(extra_headers)
return JSONResponse(
status_code=status,
headers=headers,
content={"error": {"code": code, "message": message, "request_id": request_id}},
)
def from_app_error(exc: AppError, request_id: str) -> JSONResponse:
extra: Dict[str, str] = dict(exc.headers)
if exc.www_authenticate:
extra["WWW-Authenticate"] = exc.www_authenticate
return error_response(exc.status, exc.message, request_id, extra or None)
+107
View File
@@ -0,0 +1,107 @@
"""PNG/JPEG checks that reject bad files before a full pixel decode."""
from __future__ import annotations
import io
from typing import Optional, Tuple
from PIL import Image, ImageFile, UnidentifiedImageError
from app import config
ImageFile.LOAD_TRUNCATED_IMAGES = False
_PNG = b"\x89PNG\r\n\x1a\n"
_JPEG = b"\xff\xd8\xff"
_SOF = {0xC0, 0xC1, 0xC2}
class ImageRejected(Exception):
def __init__(self, status: int, message: str) -> None:
super().__init__(message)
self.status = status
self.message = message
def _reject(status: int, message: str) -> None:
raise ImageRejected(status, message)
def sniff(data: bytes) -> Optional[str]:
if data.startswith(_PNG):
return "image/png"
if data.startswith(_JPEG):
return "image/jpeg"
return None
def _png_size(data: bytes) -> Tuple[int, int]:
if len(data) < 24 or data[12:16] != b"IHDR":
_reject(415, "unsupported or damaged image")
length = int.from_bytes(data[8:12], "big")
if length != 13 or len(data) < 33:
_reject(415, "unsupported or damaged image")
width = int.from_bytes(data[16:20], "big")
height = int.from_bytes(data[20:24], "big")
return width, height
def _jpeg_size(data: bytes) -> Tuple[int, int]:
index = 2
size = len(data)
while index < size:
if data[index] != 0xFF:
_reject(415, "unsupported or damaged image")
while index < size and data[index] == 0xFF:
index += 1
if index >= size:
break
marker = data[index]
index += 1
if marker in (0xD8, 0xD9, 0x01) or 0xD0 <= marker <= 0xD7:
continue
if index + 1 >= size:
break
segment = int.from_bytes(data[index : index + 2], "big")
if segment < 2 or index + segment > size:
_reject(415, "unsupported or damaged image")
if marker in _SOF:
if segment < 7:
_reject(415, "unsupported or damaged image")
height = int.from_bytes(data[index + 3 : index + 5], "big")
width = int.from_bytes(data[index + 5 : index + 7], "big")
return width, height
if marker == 0xDA:
break
index += segment
_reject(415, "unsupported or damaged image")
return 0, 0
def _check_pixels(width: int, height: int) -> None:
limit = config.MAX_IMAGE_PIXELS
if width <= 0 or height <= 0:
_reject(415, "unsupported or damaged image")
if width > limit or height > limit or width * height > limit:
_reject(413, "image dimensions exceed the limit")
def _verify(data: bytes) -> None:
Image.MAX_IMAGE_PIXELS = config.MAX_IMAGE_PIXELS
try:
with Image.open(io.BytesIO(data)) as image:
image.verify()
except Image.DecompressionBombError:
_reject(413, "image dimensions exceed the limit")
except (UnidentifiedImageError, OSError, ValueError, SyntaxError):
_reject(415, "unsupported or damaged image")
def inspect_image(data: bytes, declared: str) -> str:
"""Return the sniffed content type or raise ImageRejected (413 or 415)."""
found = sniff(data)
if found is None or found != declared:
_reject(415, "unsupported or damaged image")
width, height = _png_size(data) if found == "image/png" else _jpeg_size(data)
_check_pixels(width, height)
_verify(data)
return found
+829
View File
@@ -0,0 +1,829 @@
"""Job rows are the transactional outbox. The broker never stores file bytes."""
from __future__ import annotations
import asyncio
import hashlib
import logging
import os
import random
import time
from datetime import datetime, timezone
from uuid import UUID, uuid4
from app import broker, config, db, pipeline, s3, telemetry
from app.errors import AppError
from app.pipeline import PermanentJobError, TransientJobError
from app.store import format_ts
logger = logging.getLogger("messenger.jobs")
_outbox_task: asyncio.Task | None = None
_publish_lock = asyncio.Lock()
def message_of(row) -> dict:
return {
"schema_version": 1,
"job_id": str(row["job_id"]),
"type": "attachment.process.v1",
"attachment_id": str(row["attachment_id"]),
"pipeline_version": int(row["pipeline_version"]),
"attempt": int(row["attempt"]),
"created_at": format_ts(row["created_at"]),
}
def backoff_seconds(attempt: int) -> float:
base = min(config.JOB_BACKOFF_CAP_SECONDS, config.JOB_BACKOFF_BASE_SECONDS * (2 ** max(0, attempt - 1)))
return base * random.uniform(0.5, 1.5)
def _trace_columns() -> tuple[str | None, str | None]:
carrier = telemetry.current_carrier()
return carrier.get("traceparent") or None, carrier.get("tracestate") or None
async def insert_job(conn, attachment_id: UUID, created: datetime) -> UUID:
job_id = uuid4()
traceparent, tracestate = _trace_columns()
await conn.execute(
"""
INSERT INTO attachment_jobs (
job_id, attachment_id, pipeline_version, attempt, status,
next_attempt_at, created_at, updated_at, traceparent, tracestate
)
VALUES ($1, $2, 1, 1, 'queued', $3, $3, $3, $4, $5)
""",
job_id,
attachment_id,
created,
traceparent,
tracestate,
)
await conn.execute(
"""
INSERT INTO attachment_job_events (job_id, attachment_id, kind, detail)
VALUES ($1, $2, 'queued', 'upload committed')
""",
job_id,
attachment_id,
)
return job_id
def kick_publish() -> None:
try:
asyncio.get_running_loop().create_task(publish_pending())
except RuntimeError:
return
async def publish_pending(limit: int = 20) -> int:
if not config.BROKER_URL:
return 0
async with _publish_lock:
try:
async with db.require().acquire() as conn:
async with conn.transaction():
rows = await conn.fetch(
"""
SELECT job_id, attachment_id, pipeline_version, attempt, created_at,
traceparent, tracestate
FROM attachment_jobs
WHERE published_at IS NULL
AND status = 'queued'
AND (next_attempt_at IS NULL OR next_attempt_at <= now())
ORDER BY created_at
LIMIT $1
FOR UPDATE SKIP LOCKED
""",
limit,
)
for row in rows:
await broker.publish_job(
message_of(row),
traceparent=row["traceparent"],
tracestate=row["tracestate"],
)
await conn.execute(
"UPDATE attachment_jobs SET published_at = now() WHERE job_id = $1",
row["job_id"],
)
return len(rows)
except Exception:
logger.warning("outbox publish failed; the job row stays unpublished")
return 0
async def _outbox_loop() -> None:
while True:
try:
await publish_pending()
except asyncio.CancelledError:
raise
except Exception:
logger.warning("outbox loop failed")
await asyncio.sleep(0.25)
def start_outbox() -> None:
global _outbox_task
if _outbox_task is None or _outbox_task.done():
_outbox_task = asyncio.create_task(_outbox_loop())
async def stop_outbox() -> None:
global _outbox_task
task = _outbox_task
_outbox_task = None
if task is None:
return
task.cancel()
try:
await task
except asyncio.CancelledError:
pass
await broker.close()
def _aware(value: datetime | None) -> datetime | None:
if value is None:
return None
if value.tzinfo is None:
return value.replace(tzinfo=timezone.utc)
return value
async def claim(job_id: UUID, pipeline_version: int):
token = uuid4()
async with db.require().acquire() as conn:
async with conn.transaction():
row = await conn.fetchrow(
"SELECT * FROM attachment_jobs WHERE job_id = $1 FOR UPDATE",
job_id,
)
if row is None:
return "missing", None
if int(row["pipeline_version"]) != pipeline_version:
return "stale", row
if row["status"] == "ready":
return "ready", row
attachment = await conn.fetchrow(
"SELECT status, applied_pipeline_version FROM attachments WHERE id = $1",
row["attachment_id"],
)
applied = int(attachment["applied_pipeline_version"]) if attachment is not None else 0
if applied > int(row["pipeline_version"]):
await conn.execute(
"""
UPDATE attachment_jobs
SET status = 'ready', error_code = NULL, lease_token = NULL,
lease_until = NULL, updated_at = now()
WHERE job_id = $1 AND status <> 'ready'
""",
job_id,
)
return "ready", row
if row["status"] == "failed":
return "failed", row
lease = _aware(row["lease_until"])
if row["status"] == "processing" and lease is not None and lease > datetime.now(timezone.utc):
return "busy", row
if int(row["attempt"]) > config.JOB_MAX_ATTEMPTS:
await _fail(conn, row, "retry_exhausted")
return "failed", row
await conn.execute(
"""
UPDATE attachment_jobs
SET status = 'processing',
lease_token = $2,
lease_until = now() + ($3::int * interval '1 second'),
error_code = NULL,
updated_at = now()
WHERE job_id = $1
""",
job_id,
token,
config.JOB_LEASE_SECONDS,
)
await conn.execute(
"""
UPDATE attachments
SET status = 'processing', error_code = NULL, updated_at = now()
WHERE id = $1 AND status <> 'ready'
""",
row["attachment_id"],
)
claimed = dict(row)
claimed["lease_token"] = token
claimed["status"] = "processing"
return "claimed", claimed
async def _fail(conn, row, code: str) -> None:
await conn.execute(
"""
UPDATE attachment_jobs
SET status = 'failed', error_code = $2, lease_token = NULL, lease_until = NULL, updated_at = now()
WHERE job_id = $1 AND status <> 'ready'
""",
row["job_id"],
code,
)
await conn.execute(
"""
UPDATE attachments
SET status = 'failed', error_code = $2, updated_at = now()
WHERE id = $1 AND status <> 'ready'
""",
row["attachment_id"],
code,
)
await conn.execute(
"""
INSERT INTO attachment_job_events (job_id, attachment_id, kind, detail)
VALUES ($1, $2, 'failed', $3)
""",
row["job_id"],
row["attachment_id"],
code,
)
async def fail_job(job_id: UUID, lease_token: UUID, code: str) -> bool:
async with db.require().acquire() as conn:
async with conn.transaction():
row = await conn.fetchrow(
"""
SELECT * FROM attachment_jobs
WHERE job_id = $1 AND lease_token = $2 AND status = 'processing'
FOR UPDATE
""",
job_id,
lease_token,
)
if row is None:
return False
await _fail(conn, row, code)
failed = dict(row)
try:
await broker.publish_dlq(message_of(failed))
except Exception:
logger.warning("failed job is stored; DLQ publish will be retried by an operator replay")
return True
async def schedule_retry(job_id: UUID, lease_token: UUID, code: str) -> str:
async with db.require().acquire() as conn:
async with conn.transaction():
row = await conn.fetchrow(
"""
SELECT * FROM attachment_jobs
WHERE job_id = $1 AND lease_token = $2 AND status = 'processing'
FOR UPDATE
""",
job_id,
lease_token,
)
if row is None:
return "lost"
nxt = int(row["attempt"]) + 1
if nxt > config.JOB_MAX_ATTEMPTS:
await _fail(conn, row, "retry_exhausted")
failed = True
else:
delay = backoff_seconds(int(row["attempt"]))
await conn.execute(
"""
UPDATE attachment_jobs
SET status = 'queued',
attempt = $2,
error_code = $3,
lease_token = NULL,
lease_until = NULL,
published_at = NULL,
next_attempt_at = now() + ($4::double precision * interval '1 second'),
updated_at = now()
WHERE job_id = $1
""",
job_id,
nxt,
code,
delay,
)
await conn.execute(
"""
UPDATE attachments
SET status = 'queued', error_code = NULL, updated_at = now()
WHERE id = $1 AND status <> 'ready'
""",
row["attachment_id"],
)
await conn.execute(
"""
INSERT INTO attachment_job_events (job_id, attachment_id, kind, detail)
VALUES ($1, $2, 'retry', $3)
""",
job_id,
row["attachment_id"],
code,
)
failed = False
failed_row = None
if failed:
failed_row = row
if failed:
try:
await broker.publish_dlq(message_of(failed_row))
except Exception:
logger.warning("retry exhausted; DLQ publish failed")
return "failed"
return "retry"
async def _intent(key: str) -> None:
async with db.require().acquire() as conn:
await conn.execute(
"""
INSERT INTO blob_writes (object_key, committed)
VALUES ($1, FALSE)
ON CONFLICT (object_key) DO NOTHING
""",
key,
)
async def complete_job(
job_id: UUID,
lease_token: UUID,
attachment_id: UUID,
final_key: str,
variants: list,
pipeline_version: int,
) -> bool:
async with db.require().acquire() as conn:
async with conn.transaction():
owned = await conn.fetchrow(
"""
UPDATE attachment_jobs
SET status = 'ready', error_code = NULL, lease_token = NULL, lease_until = NULL, updated_at = now()
WHERE job_id = $1 AND lease_token = $2 AND status = 'processing'
RETURNING pipeline_version
""",
job_id,
lease_token,
)
if owned is None:
return False
current = await conn.fetchrow(
"""
SELECT status, applied_pipeline_version
FROM attachments
WHERE id = $1
FOR UPDATE
""",
attachment_id,
)
if current is None:
raise PermanentJobError("invalid_image")
version = int(owned["pipeline_version"])
applied = int(current["applied_pipeline_version"])
superseded = applied > version
if not superseded:
await conn.execute(
"""
UPDATE attachments
SET status = 'ready',
object_key = CASE WHEN $2 = '' THEN object_key ELSE $2 END,
error_code = NULL,
applied_pipeline_version = $3,
updated_at = now()
WHERE id = $1 AND applied_pipeline_version <= $3
""",
attachment_id,
final_key,
version,
)
for variant in variants:
await conn.execute(
"""
INSERT INTO attachment_variants (
attachment_id, pipeline_version, name, content_type, size_bytes,
width, height, sha256, object_key
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
ON CONFLICT (attachment_id, pipeline_version, name) DO NOTHING
""",
attachment_id,
version,
variant["name"],
variant["content_type"],
variant["size_bytes"],
variant["width"],
variant["height"],
variant["sha256"],
variant["object_key"],
)
await conn.execute(
"UPDATE blob_writes SET committed = TRUE WHERE object_key = $1",
variant["object_key"],
)
if final_key:
await conn.execute(
"UPDATE blob_writes SET committed = TRUE WHERE object_key = $1",
final_key,
)
await conn.execute(
"""
INSERT INTO attachment_job_events (job_id, attachment_id, kind, detail)
VALUES ($1, $2, 'ready', $3)
""",
job_id,
attachment_id,
"superseded" if superseded else "variants committed",
)
return True
async def load_attachment(attachment_id: UUID):
async with db.require().acquire() as conn:
return await conn.fetchrow(
"""
SELECT id, filename, content_type, size_bytes, sha256, object_key, status,
applied_pipeline_version
FROM attachments
WHERE id = $1
""",
attachment_id,
)
async def process(job_id: UUID, pipeline_version: int) -> str:
started = time.perf_counter()
state, row = await claim(job_id, pipeline_version)
if state != "claimed":
return state
assert row is not None
lease = row["lease_token"]
try:
await asyncio.wait_for(_effect(row, lease), config.JOB_TIMEOUT_SECONDS)
outcome = "ready"
except PermanentJobError as exc:
await fail_job(job_id, lease, exc.code)
outcome = "failed"
except (TransientJobError, asyncio.TimeoutError, AppError):
outcome = await schedule_retry(job_id, lease, "processing_failed")
except Exception:
logger.warning("job processing failed job_id=%s", job_id)
outcome = await schedule_retry(job_id, lease, "processing_failed")
elapsed = time.perf_counter() - started
if outcome in ("ready", "failed", "retry", "lost"):
telemetry.record_job(outcome, elapsed)
if outcome == "ready":
created = _aware(row["created_at"])
if created is not None:
telemetry.record_time_to_ready((datetime.now(timezone.utc) - created).total_seconds())
return outcome
async def _effect(row, lease: UUID) -> None:
attachment = await load_attachment(row["attachment_id"])
if attachment is None:
raise PermanentJobError("invalid_image")
version = int(row["pipeline_version"])
if int(attachment["applied_pipeline_version"]) > version:
committed = await complete_job(row["job_id"], lease, attachment["id"], "", [], version)
if not committed:
raise TransientJobError("processing_failed")
return
fault = await consume_fault()
if fault == "crash_before_s3":
logger.warning("injected crash before side effect job_id=%s", row["job_id"])
os._exit(1)
if fault == "fail_once":
raise PermanentJobError("processing_failed")
with telemetry.span("s3.get", kind="client", attributes={"s3.operation": "get"}):
data = await s3.get_bytes(attachment["object_key"])
if len(data) != attachment["size_bytes"] or hashlib.sha256(data).hexdigest() != attachment["sha256"]:
raise PermanentJobError("invalid_image")
final_key = f"originals/{attachment['id']}"
if attachment["object_key"] != final_key:
await _intent(final_key)
with telemetry.span("s3.put", kind="client", attributes={"s3.operation": "put", "variant": "original"}):
await s3.put_bytes(final_key, data, attachment["content_type"])
with telemetry.span("image.render"):
rendered = await asyncio.to_thread(pipeline.render, data, attachment["content_type"], version)
stored = []
for name, (payload, content_type, width, height) in rendered.items():
suffix = "webp" if content_type == "image/webp" else "jpg"
key = f"variants/{attachment['id']}/v{version}/{name}.{suffix}"
await _intent(key)
with telemetry.span("s3.put", kind="client", attributes={"s3.operation": "put", "variant": name}):
await s3.put_bytes(key, payload, content_type)
stored.append(
{
"name": name,
"content_type": content_type,
"size_bytes": len(payload),
"width": width,
"height": height,
"sha256": hashlib.sha256(payload).hexdigest(),
"object_key": key,
}
)
if fault == "crash_after_s3" or config.WORKER_CRASH_POINT == "after_s3":
logger.warning("injected crash after object write before result commit job_id=%s", row["job_id"])
os._exit(1)
fresh = await load_attachment(attachment["id"])
if fresh is not None and int(fresh["applied_pipeline_version"]) > version:
stored = []
final_key = ""
with telemetry.span("db.complete", kind="client"):
committed = await complete_job(row["job_id"], lease, attachment["id"], final_key, stored, version)
if not committed:
raise TransientJobError("processing_failed")
if stored and attachment["object_key"] != final_key and final_key:
try:
await s3.delete_key(attachment["object_key"])
async with db.require().acquire() as conn:
await conn.execute("DELETE FROM blob_writes WHERE object_key = $1", attachment["object_key"])
except Exception:
logger.warning("staging object left for retention attachment_id=%s", attachment["id"])
async def consume_fault() -> str:
async with db.require().acquire() as conn:
row = await conn.fetchrow(
"""
UPDATE pipeline_faults
SET remaining = remaining - 1
WHERE id = 1 AND remaining > 0
RETURNING mode
"""
)
if row is None:
return ""
return row["mode"] or ""
async def arm_fault(mode: str, remaining: int) -> dict:
if mode not in ("", "crash_before_s3", "crash_after_s3", "fail_once"):
raise AppError(400, "invalid fault")
if remaining < 0 or remaining > 5:
raise AppError(400, "invalid fault")
async with db.require().acquire() as conn:
await conn.execute(
"""
INSERT INTO pipeline_faults (id, mode, remaining)
VALUES (1, $1, $2)
ON CONFLICT (id) DO UPDATE SET mode = EXCLUDED.mode, remaining = EXCLUDED.remaining
""",
mode,
remaining,
)
return {"mode": mode, "remaining": remaining}
async def bump_pipeline(attachment_id: UUID) -> dict:
created = datetime.now(timezone.utc)
async with db.require().acquire() as conn:
async with conn.transaction():
current = await conn.fetchval(
"SELECT COALESCE(MAX(pipeline_version), 0) FROM attachment_jobs WHERE attachment_id = $1",
attachment_id,
)
if current is None:
return {"result": "missing"}
exists = await conn.fetchval("SELECT 1 FROM attachments WHERE id = $1", attachment_id)
if exists is None:
return {"result": "missing"}
version = int(current) + 1
job_id = uuid4()
traceparent, tracestate = _trace_columns()
await conn.execute(
"""
INSERT INTO attachment_jobs (
job_id, attachment_id, pipeline_version, attempt, status,
next_attempt_at, created_at, updated_at, traceparent, tracestate
)
VALUES ($1, $2, $3, 1, 'queued', $4, $4, $4, $5, $6)
""",
job_id,
attachment_id,
version,
created,
traceparent,
tracestate,
)
await conn.execute(
"""
INSERT INTO attachment_job_events (job_id, attachment_id, kind, detail)
VALUES ($1, $2, 'queued', 'pipeline version bumped')
""",
job_id,
attachment_id,
)
kick_publish()
return {"result": "queued", "job_id": str(job_id), "pipeline_version": version}
async def redeliver(job_id: UUID) -> dict:
async with db.require().acquire() as conn:
row = await conn.fetchrow(
"""
SELECT job_id, attachment_id, pipeline_version, attempt, created_at, status,
traceparent, tracestate
FROM attachment_jobs
WHERE job_id = $1
""",
job_id,
)
if row is None:
return {"result": "missing"}
await broker.publish_job(message_of(row), traceparent=row["traceparent"], tracestate=row["tracestate"])
return {
"result": "published",
"job_id": str(row["job_id"]),
"pipeline_version": int(row["pipeline_version"]),
"status": row["status"],
}
async def list_jobs(attachment_id: UUID) -> list:
async with db.require().acquire() as conn:
rows = await conn.fetch(
"""
SELECT job_id, pipeline_version, status, attempt
FROM attachment_jobs
WHERE attachment_id = $1
ORDER BY pipeline_version
""",
attachment_id,
)
variants = await conn.fetch(
"""
SELECT pipeline_version, name, sha256
FROM attachment_variants
WHERE attachment_id = $1
ORDER BY pipeline_version, name
""",
attachment_id,
)
applied = await conn.fetchval(
"SELECT applied_pipeline_version FROM attachments WHERE id = $1",
attachment_id,
)
return {
"applied_pipeline_version": applied,
"jobs": [
{
"job_id": str(row["job_id"]),
"pipeline_version": int(row["pipeline_version"]),
"status": row["status"],
"attempt": int(row["attempt"]),
}
for row in rows
],
"variants": [
{
"pipeline_version": int(row["pipeline_version"]),
"name": row["name"],
"sha256": row["sha256"],
}
for row in variants
],
}
async def replay_attachment(attachment_id: str) -> dict:
async with db.require().acquire() as conn:
job_id = await conn.fetchval(
"""
SELECT job_id FROM attachment_jobs
WHERE attachment_id = $1 AND status = 'failed'
ORDER BY pipeline_version DESC
LIMIT 1
""",
UUID(attachment_id),
)
if job_id is None:
return {"result": "missing"}
return await replay(job_id)
async def replay(job_id: UUID) -> dict:
async with db.require().acquire() as conn:
async with conn.transaction():
row = await conn.fetchrow(
"SELECT * FROM attachment_jobs WHERE job_id = $1 FOR UPDATE",
job_id,
)
if row is None:
return {"result": "missing"}
if row["status"] == "ready":
await conn.execute(
"""
INSERT INTO attachment_job_events (job_id, attachment_id, kind, detail)
VALUES ($1, $2, 'replay', 'noop ready')
""",
row["job_id"],
row["attachment_id"],
)
return {"result": "noop", "job_id": str(row["job_id"])}
lease = _aware(row["lease_until"])
if row["status"] == "processing" and lease is not None and lease > datetime.now(timezone.utc):
return {"result": "busy", "job_id": str(row["job_id"])}
await conn.execute(
"""
UPDATE attachment_jobs
SET status = 'queued',
attempt = 1,
error_code = NULL,
lease_token = NULL,
lease_until = NULL,
published_at = NULL,
next_attempt_at = now(),
updated_at = now()
WHERE job_id = $1 AND status <> 'ready'
""",
job_id,
)
await conn.execute(
"""
UPDATE attachments
SET status = 'queued', error_code = NULL, updated_at = now()
WHERE id = $1 AND status <> 'ready'
""",
row["attachment_id"],
)
await conn.execute(
"""
INSERT INTO attachment_job_events (job_id, attachment_id, kind, detail)
VALUES ($1, $2, 'replay', 'operator replay')
""",
row["job_id"],
row["attachment_id"],
)
await publish_pending()
return {"result": "queued", "job_id": str(job_id)}
async def reap_expired() -> int:
async with db.require().acquire() as conn:
async with conn.transaction():
rows = await conn.fetch(
"""
SELECT job_id, attachment_id, attempt
FROM attachment_jobs
WHERE status = 'processing' AND lease_until < now()
FOR UPDATE SKIP LOCKED
"""
)
changed = 0
for row in rows:
nxt = int(row["attempt"]) + 1
if nxt > config.JOB_MAX_ATTEMPTS:
await conn.execute(
"""
UPDATE attachment_jobs
SET status = 'failed', error_code = 'retry_exhausted',
lease_token = NULL, lease_until = NULL, updated_at = now()
WHERE job_id = $1 AND status = 'processing'
""",
row["job_id"],
)
await conn.execute(
"""
UPDATE attachments
SET status = 'failed', error_code = 'retry_exhausted', updated_at = now()
WHERE id = $1 AND status <> 'ready'
""",
row["attachment_id"],
)
else:
await conn.execute(
"""
UPDATE attachment_jobs
SET status = 'queued',
attempt = $2,
error_code = 'lease_expired',
lease_token = NULL,
lease_until = NULL,
published_at = NULL,
next_attempt_at = now(),
updated_at = now()
WHERE job_id = $1 AND status = 'processing'
""",
row["job_id"],
nxt,
)
await conn.execute(
"""
UPDATE attachments
SET status = 'queued', error_code = NULL, updated_at = now()
WHERE id = $1 AND status <> 'ready'
""",
row["attachment_id"],
)
changed += 1
return changed
+173
View File
@@ -0,0 +1,173 @@
import asyncio
import logging
import signal
import uuid
from pathlib import Path
import uvicorn
from starlette.applications import Starlette
from starlette.exceptions import HTTPException
from starlette.requests import Request
from starlette.responses import Response
from starlette.routing import Route
from app import attachments, bao, config, db, jobs, rediscli, telemetry
from app.docs import openapi_json, swagger_ui
from app.errors import AppError, error_response, from_app_error
from app.middleware import RequestContextMiddleware
from app.routes import (
begin_direct_upload,
complete_direct_upload,
create_chat,
create_message,
create_session,
current_user,
download_attachment,
get_attachment,
get_chat,
health_live,
health_ready,
lab_bump,
lab_fault,
lab_flags,
lab_jobs,
lab_metrics,
lab_redeliver,
lab_replay,
lab_sweep,
list_chats,
list_messages,
register_user,
revoke_session,
upload_attachment,
)
def _request_id(request: Request) -> str:
existing = getattr(request.state, "request_id", None)
if existing:
return existing
return request.headers.get("X-Request-Id") or str(uuid.uuid4())
async def not_found_handler(request: Request, exc: HTTPException) -> Response:
return error_response(404, "not found", _request_id(request))
async def app_error_handler(request: Request, exc: AppError) -> Response:
return from_app_error(exc, _request_id(request))
def publish_instance_id() -> None:
path = Path(config._env("INSTANCE_ID_FILE", "/tmp/instance-id"))
try:
path.write_text(config.INSTANCE_ID, encoding="utf-8")
except OSError:
logging.getLogger("messenger").warning("instance id file was not written")
async def startup() -> None:
publish_instance_id()
logging.getLogger("messenger").info("instance_id=%s", config.INSTANCE_ID)
await asyncio.to_thread(bao.apply)
if config.BAO_ADDR:
asyncio.create_task(bao.renew_loop())
await db.connect()
if config.MIGRATIONS_ON_START:
await db.apply_migrations()
await rediscli.connect()
attachments.start_sweeper()
jobs.start_outbox()
telemetry.start_probes()
async def shutdown() -> None:
await telemetry.stop_probes()
await attachments.stop_sweeper()
await jobs.stop_outbox()
await rediscli.close()
await db.close()
telemetry.shutdown()
def build_app() -> Starlette:
app = Starlette(
routes=[
Route("/docs", swagger_ui, methods=["GET"]),
Route("/openapi.json", openapi_json, methods=["GET"]),
Route("/health/live", health_live, methods=["GET"]),
Route("/health/ready", health_ready, methods=["GET"]),
Route("/api/v1/users", register_user, methods=["POST"]),
Route("/api/v1/users/me", current_user, methods=["GET"]),
Route("/api/v1/auth/sessions", create_session, methods=["POST"]),
Route("/api/v1/auth/sessions/current", revoke_session, methods=["DELETE"]),
Route("/api/v1/chats", create_chat, methods=["POST"]),
Route("/api/v1/chats", list_chats, methods=["GET"]),
Route("/api/v1/chats/{chat_id}", get_chat, methods=["GET"]),
Route("/api/v1/chats/{chat_id}/messages", create_message, methods=["POST"]),
Route("/api/v1/chats/{chat_id}/messages", list_messages, methods=["GET"]),
Route("/api/v1/chats/{chat_id}/attachments", upload_attachment, methods=["POST"]),
Route("/api/v1/chats/{chat_id}/uploads", begin_direct_upload, methods=["POST"]),
Route("/api/v1/uploads/{upload_id}/complete", complete_direct_upload, methods=["POST"]),
Route("/api/v1/attachments/{attachment_id}", get_attachment, methods=["GET"]),
Route("/api/v1/attachments/{attachment_id}/content", download_attachment, methods=["GET"]),
Route("/api/v1/_lab/metrics", lab_metrics, methods=["GET"]),
Route("/api/v1/_lab/flags", lab_flags, methods=["POST"]),
Route("/api/v1/_lab/sweep", lab_sweep, methods=["POST"]),
Route("/api/v1/_lab/faults", lab_fault, methods=["POST"]),
Route("/api/v1/_lab/attachments/{attachment_id}/jobs", lab_jobs, methods=["GET"]),
Route("/api/v1/_lab/attachments/{attachment_id}/pipelines", lab_bump, methods=["POST"]),
Route("/api/v1/_lab/jobs/{job_id}/redeliver", lab_redeliver, methods=["POST"]),
Route("/api/v1/_lab/attachments/{attachment_id}/replay", lab_replay, methods=["POST"]),
],
exception_handlers={404: not_found_handler, AppError: app_error_handler},
on_startup=[startup],
on_shutdown=[shutdown],
)
app.state.shutting_down = False
app.add_middleware(RequestContextMiddleware)
return app
def configure_logging() -> None:
telemetry.configure_logging()
def main() -> None:
configure_logging()
app = build_app()
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
server = uvicorn.Server(
uvicorn.Config(
app,
host=config.HOST,
port=config.PORT,
log_level=config.LOG_LEVEL,
access_log=False,
timeout_graceful_shutdown=int(config.SHUTDOWN_GRACE_SECONDS),
)
)
def _begin_shutdown() -> None:
if app.state.shutting_down:
return
logging.getLogger("messenger").info(
"shutdown signal received; readiness fails now, exit in %.1fs",
config.LB_DRAIN_SECONDS,
)
app.state.shutting_down = True
loop.call_later(config.LB_DRAIN_SECONDS, lambda: setattr(server, "should_exit", True))
for sig in (signal.SIGTERM, signal.SIGINT):
try:
loop.add_signal_handler(sig, _begin_shutdown)
except NotImplementedError:
signal.signal(sig, lambda *_: _begin_shutdown())
loop.run_until_complete(server.serve())
if __name__ == "__main__":
main()
+124
View File
@@ -0,0 +1,124 @@
import logging
import time
import uuid
from contextlib import nullcontext
from starlette.datastructures import MutableHeaders
from starlette.responses import Response
from starlette.types import ASGIApp, Message, Receive, Scope, Send
from app import config, telemetry
from app.config import INSTANCE_ID
from app.errors import AppError, error_response, from_app_error
logger = logging.getLogger("messenger.access")
def _body_limit(path: str, method: str) -> int:
if method in ("GET", "HEAD", "OPTIONS"):
return 1024
if "/attachments" in path or "/uploads" in path:
return config.MAX_UPLOAD_BYTES
return config.MAX_JSON_BYTES
class RequestContextMiddleware:
"""Pure ASGI middleware so upload handlers can read the body stream themselves."""
def __init__(self, app: ASGIApp) -> None:
self.app = app
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if scope["type"] != "http":
await self.app(scope, receive, send)
return
headers = {key.decode("latin1").lower(): value.decode("latin1") for key, value in scope.get("headers", [])}
request_id = headers.get("x-request-id") or str(uuid.uuid4())
raw_state = scope.get("state")
if not isinstance(raw_state, dict):
raw_state = {}
scope["state"] = raw_state
raw_state["request_id"] = request_id
path = scope.get("path", "")
method = scope.get("method", "")
limit = _body_limit(path, method)
content_length = headers.get("content-length")
announced = None
if content_length:
try:
announced = int(content_length)
except ValueError:
announced = limit + 1
received = 0
async def limited_receive() -> Message:
nonlocal received
message = await receive()
if message["type"] == "http.request":
received += len(message.get("body", b""))
if received > limit:
raise AppError(413, "payload too large")
return message
started = time.perf_counter()
status_code = 500
record = telemetry.observe_http(path)
route = telemetry.route_template(path)
async def send_wrapper(message: Message) -> None:
nonlocal status_code
if message["type"] == "http.response.start":
status_code = int(message["status"])
response_headers = MutableHeaders(scope=message)
response_headers["X-Request-Id"] = request_id
response_headers["X-Instance-Id"] = INSTANCE_ID
await send(message)
parent = telemetry.remote_context(headers.get("traceparent"), headers.get("tracestate"))
span_cm = (
telemetry.span(
"%s %s" % (method, route),
context=parent,
kind="server",
attributes={
"http.request.method": method,
"http.route": route,
"http.request_id": request_id,
},
)
if record
else nullcontext(None)
)
with span_cm as current:
app = scope.get("app")
shutting_down = bool(app and getattr(app.state, "shutting_down", False))
try:
if announced is not None and announced > limit:
status_code = 413
response: Response = error_response(413, "payload too large", request_id)
await response(scope, receive, send_wrapper)
elif shutting_down and path not in ("/health/live", "/health/ready"):
response: Response = error_response(503, "service is shutting down", request_id)
await response(scope, receive, send_wrapper)
else:
await self.app(scope, limited_receive, send_wrapper)
except AppError as exc:
status_code = exc.status
await from_app_error(exc, request_id)(scope, receive, send_wrapper)
except Exception:
status_code = 500
logger.exception("request failed request_id=%s route=%s", request_id, route)
await error_response(500, "internal error", request_id)(scope, receive, send_wrapper)
finally:
if record:
telemetry.finish_http_span(current, status_code)
telemetry.record_http(method, route, status_code, time.perf_counter() - started)
if record:
logger.info(
"request completed request_id=%s method=%s route=%s status=%s duration_ms=%.2f",
request_id,
method,
route,
status_code,
(time.perf_counter() - started) * 1000,
)
+30
View File
@@ -0,0 +1,30 @@
"""One-shot schema apply. API replicas do not run this on startup."""
import asyncio
import logging
import sys
from app import bao, config, db
async def _main() -> None:
await asyncio.to_thread(bao.apply)
if not config.DATABASE_URL:
raise SystemExit("DATABASE_URL is not set")
await db.connect()
try:
await db.apply_migrations()
finally:
await db.close()
def main() -> None:
logging.basicConfig(
level=getattr(logging, config.LOG_LEVEL.upper(), logging.INFO),
format="%(asctime)s %(levelname)s %(name)s %(message)s",
stream=sys.stdout,
)
asyncio.run(_main())
if __name__ == "__main__":
main()
+43
View File
@@ -0,0 +1,43 @@
import os
from argon2 import PasswordHasher
from argon2.exceptions import InvalidHashError, VerifyMismatchError
# 19 MiB is the lab floor. Salt and parameters live inside the PHC string.
MEMORY_KIB = int(os.environ.get("ARGON2_MEMORY_KIB") or "19456")
ITERATIONS = int(os.environ.get("ARGON2_ITERATIONS") or "2")
PARALLELISM = int(os.environ.get("ARGON2_PARALLELISM") or "1")
hasher = PasswordHasher(
time_cost=ITERATIONS,
memory_cost=MEMORY_KIB,
parallelism=PARALLELISM,
hash_len=32,
salt_len=16,
)
_dummy = None
def hash_password(password: str) -> str:
return hasher.hash(password)
def dummy_hash() -> str:
global _dummy
if _dummy is None:
_dummy = hash_password("timing-dummy-password")
return _dummy
def verify_password(password_hash: str, password: str) -> bool:
try:
return hasher.verify(password_hash, password)
except (VerifyMismatchError, InvalidHashError, TypeError, ValueError):
return False
def needs_rehash(password_hash: str) -> bool:
try:
return hasher.check_needs_rehash(password_hash)
except (InvalidHashError, TypeError, ValueError):
return False
+101
View File
@@ -0,0 +1,101 @@
"""Image variants. The worker calls this; the API process does not resize."""
from __future__ import annotations
import io
import math
from PIL import Image, ImageOps, UnidentifiedImageError
from app import config
from app.images import ImageRejected, inspect_image
class PermanentJobError(Exception):
def __init__(self, code: str) -> None:
super().__init__(code)
self.code = code
class TransientJobError(Exception):
def __init__(self, code: str = "processing_failed") -> None:
super().__init__(code)
self.code = code
def _flatten(image: Image.Image) -> Image.Image:
if image.mode == "RGB":
return image
rgba = image.convert("RGBA")
background = Image.new("RGB", rgba.size, (255, 255, 255))
background.paste(rgba, mask=rgba.getchannel("A"))
return background
def _open_rgb(data: bytes, content_type: str) -> Image.Image:
try:
inspect_image(data, content_type)
except ImageRejected as exc:
raise PermanentJobError("invalid_image") from exc
Image.MAX_IMAGE_PIXELS = config.MAX_IMAGE_PIXELS
try:
with Image.open(io.BytesIO(data)) as image:
image.load()
oriented = ImageOps.exif_transpose(image) or image
return _flatten(oriented).copy()
except Image.DecompressionBombError as exc:
raise PermanentJobError("invalid_image") from exc
except (UnidentifiedImageError, OSError, ValueError, SyntaxError) as exc:
raise PermanentJobError("invalid_image") from exc
def _fit_down(image: Image.Image, box: int) -> Image.Image:
width, height = image.size
scale = min(box / width, box / height, 1.0)
target = (max(1, math.floor(width * scale)), max(1, math.floor(height * scale)))
if target == (width, height):
return image
return image.resize(target, Image.Resampling.LANCZOS)
def _crop_square(image: Image.Image, side: int) -> Image.Image:
width, height = image.size
edge = min(width, height)
left = (width - edge) // 2
top = (height - edge) // 2
cropped = image.crop((left, top, left + edge, top + edge))
if cropped.size != (side, side):
cropped = cropped.resize((side, side), Image.Resampling.LANCZOS)
return cropped
def _jpeg(image: Image.Image, quality: int) -> bytes:
buffer = io.BytesIO()
image.save(buffer, format="JPEG", quality=quality, optimize=True)
return buffer.getvalue()
def _webp(image: Image.Image, quality: int) -> bytes:
# method=6. EXIF is omitted because the saved image is a new RGB buffer.
buffer = io.BytesIO()
image.save(buffer, format="WEBP", quality=quality, method=6)
return buffer.getvalue()
def render(data: bytes, content_type: str, pipeline_version: int = 1) -> dict:
"""Return thumbnail, crop and optimized payloads. Does not touch storage.
Version 1 is the contract profile (JPEG 90, WebP 80). A later version lowers
quality so a stale writer cannot be confused with the newer bytes.
"""
jpeg_quality = 90 if pipeline_version <= 1 else 60
webp_quality = 80 if pipeline_version <= 1 else 50
image = _open_rgb(data, content_type)
thumb = _fit_down(image, 256)
crop = _crop_square(image, 128)
optimized = _fit_down(image, 1280)
return {
"thumbnail": (_jpeg(thumb, jpeg_quality), "image/jpeg", thumb.size[0], thumb.size[1]),
"crop": (_jpeg(crop, jpeg_quality), "image/jpeg", crop.size[0], crop.size[1]),
"optimized": (_webp(optimized, webp_quality), "image/webp", optimized.size[0], optimized.size[1]),
}
+36
View File
@@ -0,0 +1,36 @@
import hashlib
from app import config, rediscli
from app.errors import AppError
def _slot(prefix: str, value: str) -> str:
digest = hashlib.sha256(value.encode("utf-8")).hexdigest()
return prefix + digest
async def reserve_login(username: str, ip: str) -> int | None:
"""Count a login attempt on the shared Redis. Returns Retry-After seconds when limited.
Both replicas use the same keys, so the limit is not per process.
The attempt is counted before Argon2 so a flood cannot spend the memory budget.
"""
user_key = _slot("login:u:", username[:128])
ip_key = _slot("login:ip:", ip[:64])
window = config.LOGIN_RATE_WINDOW_SECONDS
try:
redis = rediscli.require()
async with redis.pipeline(transaction=True) as pipe:
pipe.incr(user_key)
pipe.expire(user_key, window, nx=True)
pipe.incr(ip_key)
pipe.expire(ip_key, window, nx=True)
user_count, _, ip_count, _ = await pipe.execute()
if user_count > config.LOGIN_RATE_LIMIT or ip_count > config.LOGIN_IP_RATE_LIMIT:
ttl = int(await redis.ttl(user_key))
return max(ttl, 1)
except AppError:
raise
except Exception:
raise AppError(503, "service unavailable") from None
return None
+48
View File
@@ -0,0 +1,48 @@
import redis.asyncio as redis
from app import config
from app.errors import AppError
client: redis.Redis | None = None
async def connect() -> redis.Redis:
global client
tls_kwargs = {}
if config.REDIS_URL.startswith("rediss://"):
tls_kwargs = {
"ssl_ca_certs": config.TLS_CA_FILE or None,
"ssl_cert_reqs": "required",
"ssl_check_hostname": True,
}
client = redis.from_url(
config.REDIS_URL,
socket_connect_timeout=config.REDIS_SOCKET_TIMEOUT,
socket_timeout=config.REDIS_SOCKET_TIMEOUT,
decode_responses=True,
**tls_kwargs,
)
await client.ping()
return client
async def close() -> None:
global client
if client is not None:
await client.close()
client = None
def require() -> redis.Redis:
if client is None:
raise AppError(503, "service unavailable")
return client
async def ping() -> None:
try:
await require().ping()
except AppError:
raise
except Exception:
raise AppError(503, "service unavailable") from None
+30
View File
@@ -0,0 +1,30 @@
"""Operator replay of one failed job. A ready job is left unchanged."""
from __future__ import annotations
import asyncio
import sys
from uuid import UUID
from app import db, jobs
async def _run(job_id: UUID) -> int:
await db.connect()
try:
result = await jobs.replay(job_id)
finally:
await db.close()
print(result["result"])
return 0 if result["result"] in {"noop", "queued"} else 1
def main() -> None:
if len(sys.argv) != 2:
print("usage: python -m app.replay JOB_ID", file=sys.stderr)
raise SystemExit(2)
raise SystemExit(asyncio.run(_run(UUID(sys.argv[1]))))
if __name__ == "__main__":
main()
+543
View File
@@ -0,0 +1,543 @@
import base64
import binascii
import re
from uuid import UUID
from starlette.requests import Request
from starlette.responses import JSONResponse, Response
from app import attachments, cache, config, db, direct, images, jobs, rediscli, s3, sessions, store
from app.cursor_codec import decode_cursor, encode_cursor
from app.errors import BASIC_CHALLENGE, BEARER_CHALLENGE, AppError, error_response
from app.passwords import dummy_hash, hash_password, needs_rehash, verify_password
from app.ratelimit import reserve_login
from app.validation import (
parse_json_body,
require_exact_keys,
parse_attachment_ids,
validate_display_name,
validate_filename,
validate_limit,
validate_idempotency_key,
validate_message_text,
validate_password,
validate_title,
validate_username,
validate_uuid,
)
def _json(data: dict, request_id: str, status: int = 200) -> JSONResponse:
return JSONResponse(status_code=status, headers={"X-Request-Id": request_id}, content=data)
def _empty(request_id: str) -> Response:
return Response(status_code=204, headers={"X-Request-Id": request_id})
async def _bearer_user(request: Request) -> dict:
header = request.headers.get("Authorization") or ""
scheme, _, rest = header.partition(" ")
if scheme.lower() != "bearer" or not rest.strip():
raise AppError(401, "authentication required", BEARER_CHALLENGE)
user_id = str(await sessions.resolve(rest.strip()))
user = await store.get_user(user_id)
if user is None:
raise AppError(401, "authentication required", BEARER_CHALLENGE)
return user
async def health_live(request: Request) -> Response:
return _json({"status": "ok"}, request.state.request_id)
async def health_ready(request: Request) -> Response:
rid = request.state.request_id
if request.app.state.shutting_down:
return error_response(503, "service is shutting down", rid)
await db.ping()
await rediscli.ping()
await s3.head_bucket()
return _json({"status": "ok"}, rid)
async def register_user(request: Request) -> Response:
rid = request.state.request_id
if request.headers.get("content-type", "").split(";")[0].strip().lower() not in ("application/json", ""):
if request.headers.get("content-type"):
return error_response(415, "unsupported media type", rid)
raw = await request.body()
body, err = parse_json_body(raw)
if err:
return error_response(400, err, rid)
assert body is not None
if require_exact_keys(body, {"username", "display_name", "password"}, {"username", "display_name", "password"}):
return error_response(400, "invalid user payload", rid)
if validate_username(body["username"]) or validate_display_name(body["display_name"]) or validate_password(body["password"]):
return error_response(400, "invalid user fields", rid)
user, conflict = await store.create_user(body["username"], body["display_name"], hash_password(body["password"]))
if conflict:
return error_response(409, "username already taken", rid)
assert user is not None
return _json(user, rid, 201)
async def current_user(request: Request) -> Response:
user = await _bearer_user(request)
return _json(user, request.state.request_id)
def _client_ip(request: Request) -> str:
real = request.headers.get("x-real-ip") or ""
if real.strip():
return real.split(",")[0].strip()
if request.client is not None:
return request.client.host
return "unknown"
async def create_session(request: Request) -> Response:
rid = request.state.request_id
header = request.headers.get("Authorization") or ""
scheme, _, rest = header.partition(" ")
if scheme.lower() != "basic" or not rest.strip():
return error_response(401, "authentication required", rid, {"WWW-Authenticate": BASIC_CHALLENGE})
try:
decoded = base64.b64decode(rest.strip(), validate=True).decode("utf-8")
except (binascii.Error, UnicodeError, ValueError):
return error_response(401, "authentication required", rid, {"WWW-Authenticate": BASIC_CHALLENGE})
username, sep, password = decoded.partition(":")
if not sep:
return error_response(401, "authentication required", rid, {"WWW-Authenticate": BASIC_CHALLENGE})
retry_after = await reserve_login(username, _client_ip(request))
if retry_after is not None:
return error_response(
429,
"too many login attempts",
rid,
{"Retry-After": str(retry_after)},
)
row = await store.get_user_by_username(username)
password_hash = row["password_hash"] if row else dummy_hash()
if row is None or not verify_password(password_hash, password):
return error_response(401, "authentication required", rid, {"WWW-Authenticate": BASIC_CHALLENGE})
if needs_rehash(password_hash):
await store.update_password_hash(row["id"], hash_password(password))
token, expires_at = await sessions.create(row["id"])
return _json(
{
"token": token,
"token_type": "Bearer",
"expires_at": expires_at,
"user": store.user_dict(row),
},
rid,
201,
)
async def revoke_session(request: Request) -> Response:
header = request.headers.get("Authorization") or ""
scheme, _, rest = header.partition(" ")
if scheme.lower() != "bearer" or not rest.strip():
raise AppError(401, "authentication required", BEARER_CHALLENGE)
await sessions.revoke(rest.strip())
return _empty(request.state.request_id)
async def create_chat(request: Request) -> Response:
rid = request.state.request_id
user = await _bearer_user(request)
ct = request.headers.get("content-type", "").split(";")[0].strip().lower()
if ct and ct != "application/json":
return error_response(415, "unsupported media type", rid)
raw = await request.body()
body, err = parse_json_body(raw)
if err:
return error_response(400, err, rid)
assert body is not None
if require_exact_keys(body, {"title", "member_ids"}, {"title", "member_ids"}):
return error_response(400, "invalid chat payload", rid)
if validate_title(body["title"]):
return error_response(400, "invalid title", rid)
members = body["member_ids"]
if not isinstance(members, list) or not members:
return error_response(400, "invalid member_ids", rid)
if len(members) > 100:
return error_response(400, "too many members", rid)
for mid in members:
if validate_uuid(mid):
return error_response(400, "invalid member id", rid)
chat, create_err = await store.create_chat(body["title"], members, user["id"])
if create_err == "caller not in members":
return error_response(400, "caller must be a member", rid)
if create_err in ("duplicate members", "unknown member"):
return error_response(400, "invalid members", rid)
assert chat is not None
return _json(chat, rid, 201)
async def list_chats(request: Request) -> Response:
rid = request.state.request_id
user = await _bearer_user(request)
limit, limit_err = validate_limit(request.query_params.get("limit"))
if limit_err:
return error_response(400, limit_err, rid)
assert limit is not None
cursor_raw = request.query_params.get("cursor")
after = None
if cursor_raw is not None:
if not cursor_raw.strip():
return error_response(400, "invalid cursor", rid)
try:
created_at, entity_id = decode_cursor(cursor_raw, user["id"])
except ValueError:
return error_response(400, "invalid cursor", rid)
after = (created_at, entity_id)
items, next_key = await store.list_chats(user["id"], limit, after)
next_cursor = None
if next_key is not None:
next_cursor = encode_cursor(user["id"], next_key[0], next_key[1])
return _json({"items": items, "next_cursor": next_cursor}, rid)
async def get_chat(request: Request) -> Response:
rid = request.state.request_id
user = await _bearer_user(request)
chat_id = request.path_params["chat_id"]
if validate_uuid(chat_id):
return error_response(400, "invalid chat id", rid)
chat = await store.get_chat(chat_id, user["id"])
if chat is None:
return error_response(404, "chat not found", rid)
return _json(chat, rid)
async def create_message(request: Request) -> Response:
rid = request.state.request_id
user = await _bearer_user(request)
chat_id = request.path_params["chat_id"]
if validate_uuid(chat_id):
return error_response(400, "invalid chat id", rid)
ct = request.headers.get("content-type", "").split(";")[0].strip().lower()
if ct and ct != "application/json":
return error_response(415, "unsupported media type", rid)
raw = await request.body()
body, err = parse_json_body(raw)
if err:
return error_response(400, err, rid)
assert body is not None
if require_exact_keys(body, {"text", "attachment_ids"}, {"text"}):
return error_response(400, "invalid message payload", rid)
attachment_ids, attachment_err = parse_attachment_ids(body.get("attachment_ids"))
if attachment_err:
return error_response(400, attachment_err, rid)
assert attachment_ids is not None
if validate_message_text(body["text"], allow_blank=bool(attachment_ids)):
return error_response(400, "invalid message text", rid)
if validate_idempotency_key(request.headers.get("Idempotency-Key")):
return error_response(400, "invalid idempotency key", rid)
message, msg_err = await store.add_message(
chat_id,
user["id"],
body["text"],
request.headers.get("Idempotency-Key") or "",
request.url.path,
attachment_ids,
)
if msg_err == "not_found":
return error_response(404, "chat not found", rid)
if msg_err == "conflict":
return error_response(409, "idempotency key reused with a different body", rid)
if msg_err == "not_ready":
return error_response(409, "attachment is not ready", rid)
assert message is not None
return _json(message, rid, 201)
async def list_messages(request: Request) -> Response:
rid = request.state.request_id
user = await _bearer_user(request)
chat_id = request.path_params["chat_id"]
if validate_uuid(chat_id):
return error_response(400, "invalid chat id", rid)
limit, limit_err = validate_limit(request.query_params.get("limit"))
if limit_err:
return error_response(400, limit_err, rid)
assert limit is not None
cursor_raw = request.query_params.get("cursor")
after = None
if cursor_raw is not None:
if not cursor_raw.strip():
return error_response(400, "invalid cursor", rid)
try:
created_at, entity_id = decode_cursor(cursor_raw, chat_id)
except ValueError:
return error_response(400, "invalid cursor", rid)
after = (created_at, entity_id)
page, next_key, list_err = await store.list_messages(chat_id, user["id"], limit, after)
if list_err == "not_found":
return error_response(404, "chat not found", rid)
assert page is not None
next_cursor = None
if next_key is not None:
next_cursor = encode_cursor(chat_id, next_key[0], next_key[1])
return _json({"items": page, "next_cursor": next_cursor}, rid)
def _media_type(value: str) -> str:
return value.split(";", 1)[0].strip().lower()
async def _read_limited(request: Request, limit: int) -> bytes:
received = bytearray()
async for chunk in request.stream():
if len(received) + len(chunk) > limit:
raise AppError(413, "file exceeds upload limit")
received.extend(chunk)
return bytes(received)
async def upload_attachment(request: Request) -> Response:
rid = request.state.request_id
user = await _bearer_user(request)
chat_id = request.path_params["chat_id"]
if validate_uuid(chat_id):
return error_response(400, "invalid chat id", rid)
if validate_filename(request.query_params.get("filename")):
return error_response(400, "invalid filename", rid)
filename = request.query_params.get("filename") or ""
declared = _media_type(request.headers.get("content-type", ""))
if declared not in ("image/png", "image/jpeg"):
return error_response(415, "unsupported media type", rid)
content_length = request.headers.get("content-length")
if content_length is not None:
try:
announced = int(content_length)
except ValueError:
return error_response(400, "invalid content length", rid)
if announced > config.MAX_UPLOAD_BYTES:
return error_response(413, "file exceeds upload limit", rid)
if announced <= 0:
return error_response(415, "unsupported or damaged image", rid)
if await store.load_chat_for_member(chat_id, user["id"]) is None:
return error_response(404, "chat not found", rid)
data = await _read_limited(request, config.MAX_UPLOAD_BYTES)
if not data:
return error_response(415, "unsupported or damaged image", rid)
try:
content_type = images.inspect_image(data, declared)
except images.ImageRejected as exc:
return error_response(exc.status, exc.message, rid)
created = await attachments.create_attachment(chat_id, user["id"], filename, content_type, data)
return _json(created, rid, 202)
async def begin_direct_upload(request: Request) -> Response:
rid = request.state.request_id
user = await _bearer_user(request)
chat_id = request.path_params["chat_id"]
if validate_uuid(chat_id):
return error_response(400, "invalid chat id", rid)
raw = await request.body()
body, err = parse_json_body(raw)
if err:
return error_response(400, err, rid)
assert body is not None
if require_exact_keys(body, {"filename", "content_type", "size_bytes"}, {"filename", "content_type", "size_bytes"}):
return error_response(400, "invalid upload payload", rid)
if validate_filename(body["filename"]):
return error_response(400, "invalid filename", rid)
content_type = body["content_type"]
if content_type not in ("image/png", "image/jpeg"):
return error_response(415, "unsupported media type", rid)
size = body["size_bytes"]
if isinstance(size, bool) or not isinstance(size, int):
return error_response(400, "invalid size", rid)
if size > config.MAX_UPLOAD_BYTES:
return error_response(413, "file exceeds upload limit", rid)
if size < 1:
return error_response(400, "invalid size", rid)
if await store.load_chat_for_member(chat_id, user["id"]) is None:
return error_response(404, "chat not found", rid)
started = await direct.begin_upload(chat_id, user["id"], body["filename"], content_type, size)
return _json(started, rid, 201)
async def complete_direct_upload(request: Request) -> Response:
rid = request.state.request_id
user = await _bearer_user(request)
upload_id = request.path_params["upload_id"]
if validate_uuid(upload_id):
return error_response(400, "invalid upload id", rid)
raw = await request.body()
body, err = parse_json_body(raw)
if err:
return error_response(400, err, rid)
assert body is not None
if require_exact_keys(body, {"sha256"}, {"sha256"}):
return error_response(400, "invalid upload payload", rid)
digest = body["sha256"]
if not isinstance(digest, str) or re.fullmatch(r"[a-f0-9]{64}", digest) is None:
return error_response(400, "invalid checksum", rid)
created = await direct.complete_upload(upload_id, user["id"], digest)
return _json(created, rid, 202)
async def get_attachment(request: Request) -> Response:
rid = request.state.request_id
user = await _bearer_user(request)
attachment_id = request.path_params["attachment_id"]
if validate_uuid(attachment_id):
return error_response(400, "invalid attachment id", rid)
row = await attachments.get_for_member(attachment_id, user["id"])
if row is None:
return error_response(404, "attachment not found", rid)
return _json(await attachments.present(row), rid)
async def download_attachment(request: Request) -> Response:
rid = request.state.request_id
user = await _bearer_user(request)
attachment_id = request.path_params["attachment_id"]
if validate_uuid(attachment_id):
return error_response(400, "invalid attachment id", rid)
variant = request.query_params.get("variant") or "original"
if variant not in ("original", "thumbnail", "crop", "optimized"):
return error_response(400, "invalid variant", rid)
row = await attachments.get_for_member(attachment_id, user["id"])
if row is None:
return error_response(404, "attachment not found", rid)
if row["status"] != "ready":
return error_response(409, "attachment is not ready", rid)
if variant == "original":
payload = await s3.get_bytes(row["object_key"])
media_type = row["content_type"]
else:
async with db.require().acquire() as conn:
found = await conn.fetchrow(
"""
SELECT content_type, object_key
FROM attachment_variants
WHERE attachment_id = $1 AND pipeline_version = $2 AND name = $3
""",
row["id"],
int(row["applied_pipeline_version"]),
variant,
)
if found is None:
return error_response(404, "attachment not found", rid)
payload = await s3.get_bytes(found["object_key"])
media_type = found["content_type"]
return Response(payload, status_code=200, media_type=media_type, headers={"X-Request-Id": rid})
async def lab_fault(request: Request) -> Response:
rid = request.state.request_id
if not config.lab_mode():
return error_response(404, "not found", rid)
raw = await request.body()
body, err = parse_json_body(raw)
if err:
return error_response(400, err, rid)
assert body is not None
mode = body.get("mode", "")
remaining = body.get("remaining", 1)
if isinstance(remaining, bool) or not isinstance(remaining, int):
return error_response(400, "invalid fault", rid)
try:
armed = await jobs.arm_fault(mode, remaining)
except AppError as exc:
return error_response(exc.status, exc.message, rid)
return _json(armed, rid)
async def lab_jobs(request: Request) -> Response:
rid = request.state.request_id
if not config.lab_mode():
return error_response(404, "not found", rid)
attachment_id = request.path_params["attachment_id"]
if validate_uuid(attachment_id):
return error_response(400, "invalid attachment id", rid)
listed = await jobs.list_jobs(UUID(attachment_id))
if listed["applied_pipeline_version"] is None:
return error_response(404, "attachment not found", rid)
return _json(listed, rid)
async def lab_bump(request: Request) -> Response:
rid = request.state.request_id
if not config.lab_mode():
return error_response(404, "not found", rid)
attachment_id = request.path_params["attachment_id"]
if validate_uuid(attachment_id):
return error_response(400, "invalid attachment id", rid)
result = await jobs.bump_pipeline(UUID(attachment_id))
if result["result"] == "missing":
return error_response(404, "attachment not found", rid)
return _json(result, rid, 202)
async def lab_redeliver(request: Request) -> Response:
rid = request.state.request_id
if not config.lab_mode():
return error_response(404, "not found", rid)
job_id = request.path_params["job_id"]
if validate_uuid(job_id):
return error_response(400, "invalid job id", rid)
result = await jobs.redeliver(UUID(job_id))
if result["result"] == "missing":
return error_response(404, "attachment not found", rid)
return _json(result, rid, 202)
async def lab_replay(request: Request) -> Response:
rid = request.state.request_id
if not config.lab_mode():
return error_response(404, "not found", rid)
attachment_id = request.path_params["attachment_id"]
if validate_uuid(attachment_id):
return error_response(400, "invalid attachment id", rid)
result = await jobs.replay_attachment(attachment_id)
if result["result"] == "missing":
return error_response(404, "attachment not found", rid)
return _json(result, rid)
async def lab_sweep(request: Request) -> Response:
if not config.lab_mode():
return error_response(404, "not found", request.state.request_id)
deleted = await attachments.sweep_orphans()
return _json({"deleted": deleted}, request.state.request_id)
async def lab_metrics(request: Request) -> Response:
if not config.lab_mode():
return error_response(404, "not found", request.state.request_id)
return _json(
{
"singleflight": await cache.singleflight_enabled(),
"invalidate": await cache.invalidate_enabled(),
"history_sql": await cache.history_sql_count(),
},
request.state.request_id,
)
async def lab_flags(request: Request) -> Response:
if not config.lab_mode():
return error_response(404, "not found", request.state.request_id)
raw = await request.body()
body, err = parse_json_body(raw)
if err:
return error_response(400, err, request.state.request_id)
assert body is not None
if body.get("reset_sql"):
await cache.reset_history_sql_count()
flags = await cache.set_flags(
singleflight=body.get("singleflight"),
invalidate=body.get("invalidate"),
delay_ms=body.get("delay_ms"),
)
return _json(flags, request.state.request_id)
+164
View File
@@ -0,0 +1,164 @@
"""Private bucket access. The API never redirects a client to this endpoint."""
from __future__ import annotations
import asyncio
import logging
import boto3
from botocore.client import Config
from botocore.exceptions import BotoCoreError, ClientError
from app import config, tlsutil
from app.errors import AppError
logger = logging.getLogger("messenger.s3")
_client = None
_signer = None
def _client_or_create():
global _client
if _client is None:
if not config.S3_ACCESS_KEY_ID or not config.S3_SECRET_ACCESS_KEY:
raise AppError(503, "service unavailable")
_client = boto3.client(
"s3",
endpoint_url=config.S3_ENDPOINT,
aws_access_key_id=config.S3_ACCESS_KEY_ID,
aws_secret_access_key=config.S3_SECRET_ACCESS_KEY,
region_name=config.S3_REGION,
config=Config(
signature_version="s3v4",
s3={"addressing_style": "path"},
connect_timeout=2,
read_timeout=20,
retries={"max_attempts": 2},
),
verify=tlsutil.https_verify(config.S3_ENDPOINT),
)
return _client
def _signer_or_create():
"""Signs URLs for the host the browser/client can reach. It does not send traffic."""
global _signer
if _signer is None:
if not config.S3_ACCESS_KEY_ID or not config.S3_SECRET_ACCESS_KEY:
raise AppError(503, "service unavailable")
_signer = boto3.client(
"s3",
endpoint_url=config.S3_PUBLIC_ENDPOINT,
aws_access_key_id=config.S3_ACCESS_KEY_ID,
aws_secret_access_key=config.S3_SECRET_ACCESS_KEY,
region_name=config.S3_REGION,
config=Config(
signature_version="s3v4",
s3={"addressing_style": "path"},
),
)
return _signer
def _unavailable(exc: Exception) -> AppError:
code = ""
if isinstance(exc, ClientError):
code = exc.response.get("Error", {}).get("Code", "")
logger.warning("object storage call failed code=%s", code or type(exc).__name__)
return AppError(503, "service unavailable")
async def head_bucket() -> None:
def _head() -> None:
_client_or_create().head_bucket(Bucket=config.S3_BUCKET)
try:
await asyncio.to_thread(_head)
except AppError:
raise
except (BotoCoreError, ClientError) as exc:
raise _unavailable(exc) from None
async def put_bytes(key: str, data: bytes, content_type: str) -> None:
def _put() -> None:
_client_or_create().put_object(
Bucket=config.S3_BUCKET,
Key=key,
Body=data,
ContentType=content_type,
ContentLength=len(data),
)
try:
await asyncio.to_thread(_put)
except AppError:
raise
except (BotoCoreError, ClientError) as exc:
raise _unavailable(exc) from None
async def get_bytes(key: str) -> bytes:
def _get() -> bytes:
response = _client_or_create().get_object(Bucket=config.S3_BUCKET, Key=key)
body = response["Body"].read()
response["Body"].close()
return body
try:
return await asyncio.to_thread(_get)
except AppError:
raise
except (BotoCoreError, ClientError) as exc:
raise _unavailable(exc) from None
def presign_put(key: str, content_type: str, size: int) -> str:
return _signer_or_create().generate_presigned_url(
"put_object",
Params={
"Bucket": config.S3_BUCKET,
"Key": key,
"ContentType": content_type,
"ContentLength": size,
},
ExpiresIn=config.PRESIGN_TTL_SECONDS,
HttpMethod="PUT",
)
async def head_size(key: str) -> int | None:
def _head() -> int | None:
try:
response = _client_or_create().head_object(Bucket=config.S3_BUCKET, Key=key)
except ClientError as exc:
code = exc.response.get("Error", {}).get("Code", "")
if code in {"404", "NoSuchKey", "NotFound"}:
return None
raise
return int(response["ContentLength"])
try:
return await asyncio.to_thread(_head)
except AppError:
raise
except (BotoCoreError, ClientError) as exc:
raise _unavailable(exc) from None
async def delete_key(key: str) -> None:
def _delete() -> None:
try:
_client_or_create().delete_object(Bucket=config.S3_BUCKET, Key=key)
except ClientError as exc:
code = exc.response.get("Error", {}).get("Code", "")
if code in {"NoSuchKey", "404", "NoSuchBucket"}:
return
raise
try:
await asyncio.to_thread(_delete)
except AppError:
raise
except (BotoCoreError, ClientError) as exc:
raise _unavailable(exc) from None
+62
View File
@@ -0,0 +1,62 @@
"""Create the private bucket if it is missing. Safe to run again."""
import os
import sys
import time
import boto3
from botocore.client import Config
from botocore.exceptions import BotoCoreError, ClientError
from app import bao, config
def _secret(name: str) -> str:
path = os.environ.get(name + "_FILE")
if path:
return open(path, encoding="utf-8").read().strip()
return os.environ.get(name, "")
def main() -> None:
bao.apply()
endpoint = os.environ.get("S3_ENDPOINT") or config.S3_ENDPOINT
bucket = os.environ.get("S3_BUCKET") or config.S3_BUCKET
access_key = _secret("S3_ACCESS_KEY_ID") or config.S3_ACCESS_KEY_ID
secret_key = _secret("S3_SECRET_ACCESS_KEY") or config.S3_SECRET_ACCESS_KEY
verify = config.TLS_CA_FILE if endpoint.startswith("https://") and config.TLS_CA_FILE else True
client = boto3.client(
"s3",
endpoint_url=endpoint,
aws_access_key_id=access_key,
aws_secret_access_key=secret_key,
region_name=os.environ.get("S3_REGION", config.S3_REGION),
verify=verify,
config=Config(signature_version="s3v4", s3={"addressing_style": "path"}, retries={"max_attempts": 2}),
)
last_error = "not attempted"
for _ in range(20):
try:
client.head_bucket(Bucket=bucket)
print("bucket ready")
return
except ClientError as exc:
code = exc.response.get("Error", {}).get("Code", "")
if code not in {"404", "NoSuchBucket", "NotFound"}:
last_error = code or "ClientError"
else:
try:
client.create_bucket(Bucket=bucket)
print("bucket created")
return
except ClientError as create_exc:
last_error = create_exc.response.get("Error", {}).get("Code", "create failed")
except BotoCoreError:
last_error = "connection failed"
time.sleep(1)
print("bucket bootstrap failed:", last_error, file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
main()
+56
View File
@@ -0,0 +1,56 @@
import hashlib
import json
import secrets
from datetime import datetime, timedelta, timezone
from uuid import UUID
from app import config, rediscli
from app.errors import AppError, BEARER_CHALLENGE
def new_token() -> str:
return secrets.token_urlsafe(32)
def _key(token: str) -> str:
return "sess:" + hashlib.sha256(token.encode("utf-8")).hexdigest()
def _fmt(dt: datetime) -> str:
return dt.astimezone(timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z")
async def create(user_id: UUID) -> tuple[str, str]:
token = new_token()
expires = datetime.now(timezone.utc) + timedelta(seconds=config.SESSION_TTL_SECONDS)
payload = json.dumps({"user_id": str(user_id), "expires_at": _fmt(expires)})
try:
await rediscli.require().set(_key(token), payload, ex=config.SESSION_TTL_SECONDS)
except AppError:
raise
except Exception:
raise AppError(503, "service unavailable") from None
return token, _fmt(expires)
async def resolve(token: str) -> UUID:
try:
raw = await rediscli.require().get(_key(token))
except AppError:
raise
except Exception:
raise AppError(503, "service unavailable") from None
if not raw:
raise AppError(401, "authentication required", BEARER_CHALLENGE)
return UUID(json.loads(raw)["user_id"])
async def revoke(token: str) -> None:
try:
deleted = await rediscli.require().delete(_key(token))
except AppError:
raise
except Exception:
raise AppError(503, "service unavailable") from None
if not deleted:
raise AppError(401, "authentication required", BEARER_CHALLENGE)
+420
View File
@@ -0,0 +1,420 @@
from __future__ import annotations
import hashlib
import json
from datetime import datetime, timezone
from typing import List, Optional, Tuple
from uuid import UUID, uuid4
import asyncpg
from app import cache, config, db
from app.errors import AppError
def format_ts(dt: datetime) -> str:
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)
return dt.astimezone(timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z")
def user_dict(row) -> dict:
return {
"id": str(row["id"]),
"username": row["username"],
"display_name": row["display_name"],
"created_at": format_ts(row["created_at"]),
}
def chat_dict(row, member_ids: List[str]) -> dict:
return {
"id": str(row["id"]),
"title": row["title"],
"member_ids": member_ids,
"created_at": format_ts(row["created_at"]),
}
def message_dict(row) -> dict:
raw_ids = row["attachment_ids"] if "attachment_ids" in row.keys() else []
if raw_ids is None:
raw_ids = []
return {
"id": str(row["id"]),
"chat_id": str(row["chat_id"]),
"sender_id": str(row["sender_id"]),
"text": row["text"],
"created_at": format_ts(row["created_at"]),
"attachment_ids": [str(item) for item in raw_ids],
}
async def _run(coro):
try:
return await coro
except AppError:
raise
except db.INTEGRITY:
raise
except Exception:
raise AppError(503, "service unavailable") from None
async def create_user(username: str, display_name: str, password_hash: str) -> Tuple[Optional[dict], Optional[str]]:
user_id = uuid4()
created = datetime.now(timezone.utc)
try:
async with db.require().acquire() as conn:
await conn.execute(
"""
INSERT INTO users (id, username, display_name, password_hash, created_at)
VALUES ($1, $2, $3, $4, $5)
""",
user_id,
username,
display_name,
password_hash,
created,
)
except asyncpg.UniqueViolationError:
return None, "conflict"
except Exception:
raise AppError(503, "service unavailable") from None
return user_dict({"id": user_id, "username": username, "display_name": display_name, "created_at": created}), None
async def get_user(user_id: str) -> Optional[dict]:
row = await _run(
_fetchrow("SELECT id, username, display_name, created_at FROM users WHERE id = $1", UUID(user_id))
)
return user_dict(row) if row else None
async def update_password_hash(user_id, password_hash: str) -> None:
try:
async with db.require().acquire() as conn:
await conn.execute(
"UPDATE users SET password_hash = $2 WHERE id = $1",
user_id,
password_hash,
)
except Exception:
raise AppError(503, "service unavailable") from None
async def get_user_by_username(username: str):
return await _run(
_fetchrow(
"SELECT id, username, display_name, password_hash, created_at FROM users WHERE username = $1",
username,
)
)
async def _fetchrow(sql: str, *args):
async with db.require().acquire() as conn:
return await conn.fetchrow(sql, *args)
async def _fetch(sql: str, *args):
async with db.require().acquire() as conn:
return await conn.fetch(sql, *args)
async def member_ids_of(chat_id: UUID) -> List[str]:
rows = await _run(_fetch("SELECT user_id FROM chat_members WHERE chat_id = $1 ORDER BY user_id", chat_id))
return [str(r["user_id"]) for r in rows]
async def create_chat(title: str, member_ids: List[str], caller_id: str) -> Tuple[Optional[dict], Optional[str]]:
if caller_id not in member_ids:
return None, "caller not in members"
if len(set(member_ids)) != len(member_ids):
return None, "duplicate members"
ids = [UUID(x) for x in member_ids]
chat_id = uuid4()
created = datetime.now(timezone.utc)
try:
async with db.require().acquire() as conn:
async with conn.transaction():
existing = await conn.fetch("SELECT id FROM users WHERE id = ANY($1::uuid[])", ids)
if len(existing) != len(ids):
return None, "unknown member"
await conn.execute(
"INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)",
chat_id,
title,
created,
)
await conn.executemany(
"INSERT INTO chat_members (chat_id, user_id) VALUES ($1, $2)",
[(chat_id, mid) for mid in ids],
)
except AppError:
raise
except Exception:
raise AppError(503, "service unavailable") from None
return chat_dict({"id": chat_id, "title": title, "created_at": created}, member_ids), None
async def get_chat(chat_id: str, user_id: str) -> Optional[dict]:
row = await load_chat_for_member(chat_id, user_id)
if row is None:
return None
return chat_dict(row, await member_ids_of(UUID(chat_id)))
async def load_chat_for_member(chat_id: str, user_id: str):
return await _run(
_fetchrow(
"""
SELECT c.id, c.title, c.created_at
FROM chats c
JOIN chat_members m ON m.chat_id = c.id AND m.user_id = $2
WHERE c.id = $1
""",
UUID(chat_id),
UUID(user_id),
)
)
async def list_chats(user_id: str, limit: int, after: Optional[Tuple[str, str]] = None):
args: list = [UUID(user_id)]
clause = ""
if after is not None:
clause = "AND (c.created_at, c.id) > ($2, $3)"
args.extend([datetime.fromisoformat(after[0].replace("Z", "+00:00")), UUID(after[1])])
rows = await _run(
_fetch(
f"""
SELECT c.id, c.title, c.created_at
FROM chats c
JOIN chat_members me ON me.chat_id = c.id AND me.user_id = $1
WHERE 1=1 {clause}
ORDER BY c.created_at, c.id
LIMIT {int(limit) + 1}
""",
*args,
)
)
page = rows[:limit]
items = [chat_dict(row, await member_ids_of(row["id"])) for row in page]
next_key = None
if len(rows) > limit:
last = page[-1]
next_key = (format_ts(last["created_at"]), str(last["id"]))
return items, next_key
def _canonical_message(text: str, attachment_ids: List[str]) -> str:
# Missing attachment_ids and [] are the same message. Key order does not matter.
return json.dumps(
{"attachment_ids": attachment_ids, "text": text},
sort_keys=True,
ensure_ascii=False,
separators=(",", ":"),
)
async def add_message(
chat_id: str,
sender_id: str,
text: str,
idem_key: str,
path: str,
attachment_ids: Optional[List[str]] = None,
) -> Tuple[Optional[dict], Optional[str]]:
"""Insert one message or replay the stored 201. The row and the result commit together.
Same user+method+path+key is serialized with a Postgres advisory lock so two
replicas cannot insert two messages. A failed transaction stores nothing.
"""
attachment_ids = list(attachment_ids or [])
digest = hashlib.sha256(_canonical_message(text, attachment_ids).encode("utf-8")).hexdigest()
lock_key = f"{sender_id}|POST|{path}|{idem_key}"
payload: Optional[dict] = None
created_new = False
try:
async with db.require().acquire() as conn:
async with conn.transaction():
await conn.execute("SELECT pg_advisory_xact_lock(hashtextextended($1::text, 0))", lock_key)
member = await conn.fetchrow(
"""
SELECT c.id
FROM chats c
JOIN chat_members m ON m.chat_id = c.id AND m.user_id = $2
WHERE c.id = $1
""",
UUID(chat_id),
UUID(sender_id),
)
if member is None:
return None, "not_found"
row = await conn.fetchrow(
"""
SELECT request_hash, response_json, created_at
FROM idempotency_keys
WHERE user_id = $1 AND http_method = 'POST' AND path = $2 AND idem_key = $3
""",
UUID(sender_id),
path,
idem_key,
)
if row is not None:
created_at = row["created_at"]
if created_at.tzinfo is None:
created_at = created_at.replace(tzinfo=timezone.utc)
age = (datetime.now(timezone.utc) - created_at).total_seconds()
if age <= config.IDEMPOTENCY_TTL_SECONDS:
if row["request_hash"] != digest:
return None, "conflict"
return json.loads(row["response_json"]), None
await conn.execute(
"""
DELETE FROM idempotency_keys
WHERE user_id = $1 AND http_method = 'POST' AND path = $2 AND idem_key = $3
""",
UUID(sender_id),
path,
idem_key,
)
resolved: List[str] = []
if attachment_ids:
rows = await conn.fetch(
"""
SELECT id, chat_id, status
FROM attachments
WHERE id = ANY($1::uuid[])
""",
[UUID(item) for item in attachment_ids],
)
found = {str(row["id"]): row for row in rows}
if len(found) != len(attachment_ids) or any(
str(found[item]["chat_id"]) != chat_id for item in attachment_ids
):
return None, "not_found"
if any(found[item]["status"] == "failed" for item in attachment_ids):
return None, "not_ready"
resolved = attachment_ids
message_id = uuid4()
created = datetime.now(timezone.utc)
await conn.execute(
"""
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
VALUES ($1, $2, $3, $4, $5)
""",
message_id,
UUID(chat_id),
UUID(sender_id),
text,
created,
)
if resolved:
await conn.executemany(
"""
INSERT INTO message_attachments (message_id, attachment_id, position)
VALUES ($1, $2, $3)
""",
[(message_id, UUID(item), index) for index, item in enumerate(resolved)],
)
payload = message_dict(
{
"id": message_id,
"chat_id": UUID(chat_id),
"sender_id": UUID(sender_id),
"text": text,
"created_at": created,
"attachment_ids": resolved,
}
)
await conn.execute(
"""
INSERT INTO idempotency_keys
(user_id, http_method, path, idem_key, request_hash, response_json, created_at)
VALUES ($1, 'POST', $2, $3, $4, $5, $6)
""",
UUID(sender_id),
path,
idem_key,
digest,
json.dumps(payload, ensure_ascii=False, separators=(",", ":")),
created,
)
created_new = True
except AppError:
raise
except Exception:
raise AppError(503, "service unavailable") from None
if created_new:
await cache.invalidate_history(chat_id)
return payload, None
async def list_messages(chat_id: str, user_id: str, limit: int, after: Optional[Tuple[str, str]] = None):
if await load_chat_for_member(chat_id, user_id) is None:
return None, None, "not_found"
cursor = ""
after_ts = after_id = None
if after is not None:
cursor = after[0] + ":" + after[1]
after_ts = datetime.fromisoformat(after[0].replace("Z", "+00:00"))
after_id = UUID(after[1])
async def loader() -> dict:
await cache.incr_history_sql()
if after_ts is None:
rows = await _run(
_fetch(
"""
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at,
COALESCE(
array_agg(ma.attachment_id ORDER BY ma.position)
FILTER (WHERE ma.attachment_id IS NOT NULL),
ARRAY[]::uuid[]
) AS attachment_ids
FROM messages m
LEFT JOIN message_attachments ma ON ma.message_id = m.id
WHERE m.chat_id = $1
GROUP BY m.id
ORDER BY m.created_at, m.id
LIMIT $2
""",
UUID(chat_id),
limit + 1,
)
)
else:
rows = await _run(
_fetch(
"""
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at,
COALESCE(
array_agg(ma.attachment_id ORDER BY ma.position)
FILTER (WHERE ma.attachment_id IS NOT NULL),
ARRAY[]::uuid[]
) AS attachment_ids
FROM messages m
LEFT JOIN message_attachments ma ON ma.message_id = m.id
WHERE m.chat_id = $1 AND (m.created_at, m.id) > ($2, $3)
GROUP BY m.id
ORDER BY m.created_at, m.id
LIMIT $4
""",
UUID(chat_id),
after_ts,
after_id,
limit + 1,
)
)
page = rows[:limit]
items = [message_dict(r) for r in page]
next_key = None
if len(rows) > limit:
last = page[-1]
next_key = (format_ts(last["created_at"]), str(last["id"]))
return {"items": items, "next_key": next_key}
page = await cache.get_history_page(chat_id, cursor, limit, loader)
return page["items"], page.get("next_key"), None
+430
View File
@@ -0,0 +1,430 @@
"""OTLP telemetry for the API and the worker.
Metric labels stay low-cardinality: method, route template, status class,
job type, outcome, queue name. User, chat, message and attachment ids are
never metric labels. Trace and log records may carry a job id so one upload
can be found; passwords, tokens, message text and image bytes are not exported.
"""
from __future__ import annotations
import asyncio
import json
import logging
import re
import sys
import time
from contextlib import contextmanager
import psutil
from opentelemetry import metrics, propagate, trace
from opentelemetry._logs import set_logger_provider
from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
from opentelemetry.sdk.metrics.view import ExplicitBucketHistogramAggregation, View
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.sdk.trace.sampling import ParentBased, TraceIdRatioBased
from opentelemetry.trace import SpanKind, Status, StatusCode
from app import config
logger = logging.getLogger("messenger.telemetry")
_HTTP_BUCKETS = (0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10)
_JOB_BUCKETS = (0.05, 0.1, 0.25, 0.5, 1, 2, 5, 10, 30, 60)
_READY_BUCKETS = (0.5, 1, 2, 5, 10, 30, 60, 120, 300)
_JOB_TYPE = "attachment.process.v1"
_QUEUE = "attachment.jobs"
_ROUTES = (
(re.compile(r"^/api/v1/chats/[^/]+/messages$"), "/api/v1/chats/{chat_id}/messages"),
(re.compile(r"^/api/v1/chats/[^/]+/attachments$"), "/api/v1/chats/{chat_id}/attachments"),
(re.compile(r"^/api/v1/chats/[^/]+/uploads$"), "/api/v1/chats/{chat_id}/uploads"),
(re.compile(r"^/api/v1/chats/[^/]+$"), "/api/v1/chats/{chat_id}"),
(re.compile(r"^/api/v1/uploads/[^/]+/complete$"), "/api/v1/uploads/{upload_id}/complete"),
(re.compile(r"^/api/v1/attachments/[^/]+/content$"), "/api/v1/attachments/{attachment_id}/content"),
(re.compile(r"^/api/v1/attachments/[^/]+$"), "/api/v1/attachments/{attachment_id}"),
(re.compile(r"^/api/v1/_lab/attachments/[^/]+/jobs$"), "/api/v1/_lab/attachments/{attachment_id}/jobs"),
(re.compile(r"^/api/v1/_lab/attachments/[^/]+/pipelines$"), "/api/v1/_lab/attachments/{attachment_id}/pipelines"),
(re.compile(r"^/api/v1/_lab/attachments/[^/]+/replay$"), "/api/v1/_lab/attachments/{attachment_id}/replay"),
(re.compile(r"^/api/v1/_lab/jobs/[^/]+/redeliver$"), "/api/v1/_lab/jobs/{job_id}/redeliver"),
)
_SECRET = re.compile(r"(?i)(authorization|password|token|secret|session)([\"']?\s*[:=]\s*[\"']?)(\S+)")
_ready = False
_tracer = None
_http_requests = None
_http_duration = None
_jobs = None
_job_duration = None
_time_to_ready = None
_log_handler = None
_providers = []
_process = psutil.Process()
_process.cpu_percent(interval=None)
_inflight = 0
_queue_depth = 0
_queue_oldest = 0.0
_probe_task: asyncio.Task | None = None
_KIND = {
"internal": SpanKind.INTERNAL,
"server": SpanKind.SERVER,
"client": SpanKind.CLIENT,
"producer": SpanKind.PRODUCER,
"consumer": SpanKind.CONSUMER,
}
class JsonFormatter(logging.Formatter):
def __init__(self, service_name: str) -> None:
super().__init__()
self.service_name = service_name
def format(self, record: logging.LogRecord) -> str:
span = trace.get_current_span()
ctx = span.get_span_context()
payload = {
"timestamp": time.strftime("%Y-%m-%dT%H:%M:%S%z", time.gmtime(record.created)),
"severity": record.levelname,
"service.name": self.service_name,
"event": _SECRET.sub(r"\1\2[redacted]", record.getMessage()),
"logger": record.name,
}
if ctx.is_valid:
payload["trace_id"] = format(ctx.trace_id, "032x")
payload["span_id"] = format(ctx.span_id, "016x")
if record.exc_info:
payload["exception"] = _SECRET.sub(r"\1\2[redacted]", self.formatException(record.exc_info))
return json.dumps(payload, ensure_ascii=False)
def route_template(path: str) -> str:
for pattern, template in _ROUTES:
if pattern.match(path):
return template
return path
def observe_http(path: str) -> bool:
return path not in ("/health/live", "/health/ready", "/docs", "/openapi.json")
def status_class(code: int) -> str:
return "%sxx" % (int(code) // 100)
def configure_logging() -> None:
setup()
root = logging.getLogger()
root.handlers.clear()
root.setLevel(getattr(logging, config.LOG_LEVEL.upper(), logging.INFO))
stream = logging.StreamHandler(sys.stdout)
stream.setFormatter(JsonFormatter(config.OTEL_SERVICE_NAME))
root.addHandler(stream)
if _log_handler is not None:
root.addHandler(_log_handler)
logging.getLogger("opentelemetry").setLevel(logging.ERROR)
def setup() -> None:
global _ready, _tracer, _http_requests, _http_duration, _jobs, _job_duration, _time_to_ready, _log_handler
if _ready:
return
_ready = True
if not config.TELEMETRY_ENABLED:
logger.info("telemetry disabled")
return
resource = Resource.create(
{
"service.name": config.OTEL_SERVICE_NAME,
"service.version": config.SERVICE_VERSION,
"service.instance.id": config.INSTANCE_ID,
"deployment.environment.name": "lab",
}
)
ratio = min(1.0, max(0.0, config.TRACE_SAMPLE_RATIO))
tracer_provider = TracerProvider(resource=resource, sampler=ParentBased(TraceIdRatioBased(ratio)))
tracer_provider.add_span_processor(
BatchSpanProcessor(
OTLPSpanExporter(endpoint=_signal_endpoint("traces"), timeout=5),
max_queue_size=2048,
schedule_delay_millis=5000,
max_export_batch_size=512,
export_timeout_millis=5000,
)
)
trace.set_tracer_provider(tracer_provider)
_tracer = trace.get_tracer("messenger", config.SERVICE_VERSION)
reader = PeriodicExportingMetricReader(
OTLPMetricExporter(endpoint=_signal_endpoint("metrics"), timeout=5),
export_interval_millis=10000,
export_timeout_millis=5000,
)
meter_provider = MeterProvider(
resource=resource,
metric_readers=[reader],
views=[
View(
instrument_name="messenger.http.request.duration",
aggregation=ExplicitBucketHistogramAggregation(_HTTP_BUCKETS),
),
View(
instrument_name="messenger.job.duration",
aggregation=ExplicitBucketHistogramAggregation(_JOB_BUCKETS),
),
View(
instrument_name="messenger.time_to_ready",
aggregation=ExplicitBucketHistogramAggregation(_READY_BUCKETS),
),
],
)
metrics.set_meter_provider(meter_provider)
meter = metrics.get_meter("messenger", config.SERVICE_VERSION)
_http_requests = meter.create_counter("messenger.http.requests", unit="1")
_http_duration = meter.create_histogram("messenger.http.request.duration", unit="s")
_jobs = meter.create_counter("messenger.jobs", unit="1")
_job_duration = meter.create_histogram("messenger.job.duration", unit="s")
_time_to_ready = meter.create_histogram("messenger.time_to_ready", unit="s")
meter.create_observable_gauge("messenger.db.pool.used", callbacks=[_pool_used])
meter.create_observable_gauge("messenger.db.pool.waiting", callbacks=[_pool_waiting])
meter.create_observable_gauge("process.cpu.percent", callbacks=[_cpu])
meter.create_observable_gauge("process.memory.rss", unit="By", callbacks=[_rss])
if config.OTEL_SERVICE_NAME == "messenger-api":
meter.create_observable_gauge("messenger.queue.depth", callbacks=[_depth])
meter.create_observable_gauge("messenger.queue.oldest_age", unit="s", callbacks=[_oldest])
if config.OTEL_SERVICE_NAME == "messenger-worker":
meter.create_observable_gauge("messenger.worker.busy", callbacks=[_busy])
meter.create_observable_gauge("messenger.worker.capacity", callbacks=[_capacity])
logger_provider = LoggerProvider(resource=resource)
logger_provider.add_log_record_processor(
BatchLogRecordProcessor(
OTLPLogExporter(endpoint=_signal_endpoint("logs"), timeout=5),
max_queue_size=2048,
schedule_delay_millis=5000,
max_export_batch_size=512,
export_timeout_millis=5000,
)
)
set_logger_provider(logger_provider)
_log_handler = LoggingHandler(level=logging.INFO, logger_provider=logger_provider)
_providers.extend([tracer_provider, meter_provider, logger_provider])
def shutdown() -> None:
for provider in _providers:
try:
provider.shutdown()
except Exception:
logger.warning("telemetry shutdown failed")
_providers.clear()
def _signal_endpoint(signal: str) -> str:
base = config.OTEL_EXPORTER_OTLP_ENDPOINT.rstrip("/")
return "%s/v1/%s" % (base, signal)
def current_carrier() -> dict:
if _tracer is None:
return {}
carrier: dict = {}
propagate.inject(carrier)
return carrier
def remote_context(traceparent: str | None, tracestate: str | None = None):
carrier = {}
if traceparent:
carrier["traceparent"] = traceparent
if tracestate:
carrier["tracestate"] = tracestate
if not carrier:
return None
return propagate.extract(carrier)
def carrier_from_headers(headers) -> dict:
carrier = {}
if not headers:
return carrier
for key in ("traceparent", "tracestate"):
value = headers.get(key)
if value is None:
continue
if isinstance(value, bytes):
value = value.decode("latin1")
carrier[key] = str(value)
return carrier
@contextmanager
def span(name: str, context=None, kind: str = "internal", attributes: dict | None = None):
if _tracer is None:
yield None
return
kwargs = {"kind": _KIND.get(kind, SpanKind.INTERNAL)}
if context is not None:
kwargs["context"] = context
with _tracer.start_as_current_span(name, **kwargs) as current:
if attributes:
for key, value in attributes.items():
if value is not None:
current.set_attribute(key, value)
yield current
def finish_http_span(current, status_code: int) -> None:
if current is None:
return
current.set_attribute("http.response.status_code", int(status_code))
if status_code >= 500:
current.set_status(Status(StatusCode.ERROR))
else:
current.set_status(Status(StatusCode.OK))
def record_http(method: str, route: str, status_code: int, duration_seconds: float) -> None:
if _http_requests is None:
return
attributes = {
"method": method,
"route": route,
"status_class": status_class(status_code),
}
_http_requests.add(1, attributes)
_http_duration.record(max(0.0, duration_seconds), attributes)
def record_job(outcome: str, duration_seconds: float) -> None:
if _jobs is None:
return
attributes = {"job_type": _JOB_TYPE, "outcome": outcome}
_jobs.add(1, attributes)
_job_duration.record(max(0.0, duration_seconds), attributes)
def record_time_to_ready(duration_seconds: float) -> None:
if _time_to_ready is None:
return
_time_to_ready.record(max(0.0, duration_seconds), {"job_type": _JOB_TYPE})
def worker_enter() -> None:
global _inflight
_inflight += 1
def worker_leave() -> None:
global _inflight
_inflight = max(0, _inflight - 1)
def start_probes() -> None:
global _probe_task
if _tracer is None or config.OTEL_SERVICE_NAME != "messenger-api":
return
if _probe_task is None or _probe_task.done():
_probe_task = asyncio.create_task(_probe_loop())
async def stop_probes() -> None:
global _probe_task
task = _probe_task
_probe_task = None
if task is None:
return
task.cancel()
try:
await task
except asyncio.CancelledError:
pass
async def _probe_loop() -> None:
from app import db
global _queue_depth, _queue_oldest
while True:
try:
async with db.require().acquire() as conn:
row = await conn.fetchrow(
"""
SELECT
count(*) FILTER (WHERE status IN ('queued', 'processing')) AS depth,
COALESCE(
EXTRACT(EPOCH FROM (now() - min(created_at) FILTER (WHERE status = 'queued'))),
0
) AS oldest
FROM attachment_jobs
"""
)
_queue_depth = int(row["depth"] or 0)
_queue_oldest = float(row["oldest"] or 0)
except asyncio.CancelledError:
raise
except Exception:
logger.warning("queue probe failed")
await asyncio.sleep(5)
def _observation(value, attributes=None):
from opentelemetry.metrics import Observation
return [Observation(value, attributes or {})]
def _pool_used(_options):
from app import db
pool = db.pool
if pool is None:
return _observation(0)
return _observation(max(0, pool.get_size() - pool.get_idle_size()))
def _pool_waiting(_options):
from app import db
pool = db.pool
if pool is None:
return _observation(0)
waiters = getattr(pool, "_waiters", None)
if waiters is not None:
return _observation(len(waiters))
queue = getattr(pool, "_queue", None)
getters = getattr(queue, "_getters", None)
if getters is not None:
return _observation(len(getters))
return _observation(0)
def _depth(_options):
return _observation(_queue_depth, {"queue": _QUEUE})
def _oldest(_options):
return _observation(_queue_oldest, {"queue": _QUEUE})
def _busy(_options):
return _observation(_inflight)
def _capacity(_options):
return _observation(config.WORKER_CONCURRENCY)
def _cpu(_options):
return _observation(_process.cpu_percent(interval=None))
def _rss(_options):
return _observation(_process.memory_info().rss)
+114
View File
@@ -0,0 +1,114 @@
"""TLS server in front of the local API.
The proxy requires a client certificate from our CA, the LB URI SAN, and a
fingerprint that is still listed in the allow file. Uvicorn stays on 127.0.0.1.
"""
from __future__ import annotations
import asyncio
import hashlib
import logging
import ssl
from app import config
logger = logging.getLogger("messenger.tls")
ALLOWED_URI = "spiffe://messenger/lb"
def _allowed_fingerprints() -> set[str]:
path = config.MTLS_ALLOW_FILE
if not path:
return set()
try:
text = open(path, encoding="utf-8").read()
except OSError:
logger.warning("mTLS allow file is not readable")
return set()
return {line.strip().lower() for line in text.splitlines() if line.strip()}
def _identity_ok(ssl_object: ssl.SSLObject) -> bool:
cert = ssl_object.getpeercert()
if not cert:
return False
names = [value for kind, value in cert.get("subjectAltName", ()) if kind == "URI"]
if ALLOWED_URI not in names:
return False
der = ssl_object.getpeercert(binary_form=True)
if not der:
return False
fingerprint = hashlib.sha256(der).hexdigest()
return fingerprint in _allowed_fingerprints()
async def _pipe(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
try:
while True:
chunk = await reader.read(65536)
if not chunk:
break
writer.write(chunk)
await writer.drain()
except Exception:
pass
finally:
try:
writer.close()
await writer.wait_closed()
except Exception:
pass
async def _handle(client_reader: asyncio.StreamReader, client_writer: asyncio.StreamWriter) -> None:
ssl_object = client_writer.get_extra_info("ssl_object")
if ssl_object is None or not _identity_ok(ssl_object):
client_writer.close()
await client_writer.wait_closed()
return
try:
upstream_reader, upstream_writer = await asyncio.open_connection("127.0.0.1", config.PORT)
except Exception:
client_writer.close()
await client_writer.wait_closed()
return
await asyncio.gather(
_pipe(client_reader, upstream_writer),
_pipe(upstream_reader, client_writer),
)
def _context() -> ssl.SSLContext:
cert = config.TLS_SERVER_CERT_FILE or config.TLS_CERT_FILE
key = config.TLS_SERVER_KEY_FILE or config.TLS_KEY_FILE
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
# TLS 1.3 in this OpenSSL finishes the handshake before the client
# certificate is checked, so a missing cert or a foreign CA still connects.
# TLS 1.2 rejects both during the handshake. Identity is checked after that.
context.minimum_version = ssl.TLSVersion.TLSv1_2
context.maximum_version = ssl.TLSVersion.TLSv1_2
context.load_cert_chain(cert, key)
context.load_verify_locations(config.TLS_CA_FILE)
context.verify_mode = ssl.CERT_REQUIRED
return context
async def serve() -> None:
cert = config.TLS_SERVER_CERT_FILE or config.TLS_CERT_FILE
key = config.TLS_SERVER_KEY_FILE or config.TLS_KEY_FILE
if not (cert and key and config.TLS_CA_FILE and config.MTLS_ALLOW_FILE):
raise SystemExit("server certificate, CA and MTLS_ALLOW_FILE are required")
server = await asyncio.start_server(_handle, "0.0.0.0", config.MTLS_PORT, ssl=_context())
logger.info("mTLS proxy listening on %s", config.MTLS_PORT)
async with server:
await server.serve_forever()
def main() -> None:
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
asyncio.run(serve())
if __name__ == "__main__":
main()
+22
View File
@@ -0,0 +1,22 @@
import ssl
from app import config
def server_context() -> ssl.SSLContext | None:
"""Trust store for outbound TLS. None means the dependency is still plaintext."""
if not config.TLS_CA_FILE:
return None
context = ssl.create_default_context(cafile=config.TLS_CA_FILE)
context.check_hostname = True
context.verify_mode = ssl.CERT_REQUIRED
context.minimum_version = ssl.TLSVersion.TLSv1_2
if config.TLS_CERT_FILE and config.TLS_KEY_FILE:
context.load_cert_chain(config.TLS_CERT_FILE, config.TLS_KEY_FILE)
return context
def https_verify(endpoint: str):
if endpoint.startswith("https://") and config.TLS_CA_FILE:
return config.TLS_CA_FILE
return True
+1
View File
@@ -0,0 +1 @@
+73
View File
@@ -0,0 +1,73 @@
"""Seed ≥10 000 messages and print EXPLAIN (ANALYZE, BUFFERS) for keyset pagination."""
import asyncio
import os
from uuid import uuid4
import asyncpg
from app.passwords import hash_password
async def main() -> None:
conn = await asyncpg.connect(dsn=os.environ["DATABASE_URL"], timeout=10, command_timeout=120)
try:
alice = uuid4()
bob = uuid4()
chat = uuid4()
pwd = hash_password("Example-only-not-a-real-secret-123")
await conn.execute(
"INSERT INTO users (id, username, display_name, password_hash) VALUES ($1,$2,$3,$4),($5,$6,$7,$4)",
alice,
"explain_a_" + alice.hex[:8],
"Alice",
pwd,
bob,
"explain_b_" + bob.hex[:8],
"Bob",
)
await conn.execute("INSERT INTO chats (id, title) VALUES ($1,$2)", chat, "Explain chat")
await conn.execute(
"INSERT INTO chat_members (chat_id, user_id) VALUES ($1,$2),($1,$3)",
chat,
alice,
bob,
)
n = int(os.environ.get("EXPLAIN_MESSAGES", "10000"))
await conn.execute(
"""
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
SELECT gen_random_uuid(), $1, $2, 'seed-' || g, now() - (g || ' milliseconds')::interval
FROM generate_series(1, $3) AS g
""",
chat,
alice,
n,
)
count = await conn.fetchval("SELECT count(*) FROM messages WHERE chat_id = $1", chat)
print("seeded_messages", count, "chat_id", chat)
first = await conn.fetchrow(
"SELECT created_at, id FROM messages WHERE chat_id = $1 ORDER BY created_at, id LIMIT 1",
chat,
)
query = """
SELECT id, chat_id, sender_id, text, created_at
FROM messages
WHERE chat_id = $1 AND (created_at, id) > ($2, $3)
ORDER BY created_at, id
LIMIT 50
"""
print("\n=== WITH index messages_chat_created_id_idx ===")
plan = await conn.fetch("EXPLAIN (ANALYZE, BUFFERS) " + query, chat, first["created_at"], first["id"])
print("\n".join(row[0] for row in plan))
await conn.execute("SET enable_indexscan = off")
await conn.execute("SET enable_bitmapscan = off")
await conn.execute("SET enable_indexonlyscan = off")
print("\n=== WITHOUT index scans (seq scan baseline) ===")
plan2 = await conn.fetch("EXPLAIN (ANALYZE, BUFFERS) " + query, chat, first["created_at"], first["id"])
print("\n".join(row[0] for row in plan2))
finally:
await conn.close()
if __name__ == "__main__":
asyncio.run(main())
+228
View File
@@ -0,0 +1,228 @@
"""Operator bootstrap for OpenBao. Prints status only, never tokens or secret values."""
from __future__ import annotations
import json
import os
import ssl
import time
import urllib.error
import urllib.request
from pathlib import Path
ADDR = os.environ["BAO_ADDR"].rstrip("/")
CAFILE = os.environ["TLS_CA_FILE"]
INIT_PATH = Path(os.environ.get("BAO_INIT_FILE", "/secrets/openbao-init.json"))
SECRETS = Path("/secrets")
POLICIES = Path("/policies")
def _ctx() -> ssl.SSLContext:
context = ssl.create_default_context(cafile=CAFILE)
context.check_hostname = True
context.verify_mode = ssl.CERT_REQUIRED
context.minimum_version = ssl.TLSVersion.TLSv1_2
return context
def call(method: str, path: str, body: dict | None = None, token: str = "", accept: tuple[int, ...] = (200, 204)) -> tuple[int, dict]:
data = None if body is None else json.dumps(body).encode("utf-8")
request = urllib.request.Request(ADDR + path, data=data, method=method)
request.add_header("Content-Type", "application/json")
if token:
request.add_header("X-Vault-Token", token)
try:
with urllib.request.urlopen(request, context=_ctx(), timeout=5) as response:
raw = response.read()
code = response.status
except urllib.error.HTTPError as exc:
raw = exc.read()
code = exc.code
if code not in accept:
detail = "unparsed"
try:
parsed = json.loads(raw.decode("utf-8"))
detail = " ".join(parsed.get("errors") or [])[:300]
except (json.JSONDecodeError, UnicodeError, AttributeError):
detail = "unparsed"
raise SystemExit("OpenBao %s %s failed with HTTP %s: %s" % (method, path, code, detail))
if not raw:
return code, {}
return code, json.loads(raw.decode("utf-8"))
def wait_until_reachable() -> None:
for _ in range(60):
try:
call("GET", "/v1/sys/seal-status", accept=(200,))
return
except (SystemExit, urllib.error.URLError, TimeoutError, OSError):
time.sleep(1)
raise SystemExit("OpenBao did not become reachable")
def read_text(name: str) -> str:
return (SECRETS / name).read_text(encoding="utf-8").strip()
def ensure_init() -> dict:
code, status = call("GET", "/v1/sys/seal-status", accept=(200,))
del code
if not status.get("initialized"):
_, payload = call(
"POST",
"/v1/sys/init",
{"secret_shares": 1, "secret_threshold": 1},
accept=(200,),
)
INIT_PATH.write_text(json.dumps(payload), encoding="utf-8")
try:
os.chmod(INIT_PATH, 0o600)
except OSError:
pass
print("openbao initialized")
return payload
if not INIT_PATH.is_file():
raise SystemExit("OpenBao is already initialized but the operator init file is missing")
print("openbao already initialized")
return json.loads(INIT_PATH.read_text(encoding="utf-8"))
def ensure_unsealed(material: dict) -> str:
_, status = call("GET", "/v1/sys/seal-status", accept=(200,))
if status.get("sealed", True):
key = (material.get("keys") or [""])[0]
call("POST", "/v1/sys/unseal", {"key": key}, accept=(200,))
print("openbao unsealed")
else:
print("openbao already unsealed")
token = material.get("root_token") or ""
if not token:
raise SystemExit("operator init file has no root token")
return token
def ensure_mounts(token: str) -> None:
code, _ = call(
"POST",
"/v1/sys/mounts/secret",
{"type": "kv", "options": {"version": "2"}},
token=token,
accept=(200, 204, 400),
)
if code == 400:
print("kv mount already present")
else:
print("kv mount enabled")
code, _ = call("POST", "/v1/sys/auth/approle", {"type": "approle"}, token=token, accept=(200, 204, 400))
if code == 400:
print("approle already present")
else:
print("approle enabled")
def put_policy(token: str, name: str) -> None:
text = (POLICIES / (name + ".hcl")).read_text(encoding="utf-8")
call("PUT", "/v1/sys/policies/acl/messenger-" + name, {"policy": text}, token=token, accept=(200, 204))
def put_kv(token: str, name: str, data: dict) -> None:
call("POST", "/v1/secret/data/messenger/" + name, {"data": data}, token=token, accept=(200,))
def ensure_role(token: str, name: str) -> None:
call(
"POST",
"/v1/auth/approle/role/" + name,
{
"token_policies": "messenger-" + name,
"token_ttl": "20m",
"token_max_ttl": "2h",
"secret_id_ttl": "24h",
},
token=token,
accept=(200, 204),
)
role_path = SECRETS / (name + ".role_id")
secret_path = SECRETS / (name + ".secret_id")
_, role = call("GET", "/v1/auth/approle/role/" + name + "/role-id", token=token, accept=(200,))
role_path.write_text(role["data"]["role_id"], encoding="utf-8")
_, secret = call(
"POST",
"/v1/auth/approle/role/" + name + "/secret-id",
{},
token=token,
accept=(200,),
)
secret_path.write_text(secret["data"]["secret_id"], encoding="utf-8")
print("approle ready:", name)
def deny_check() -> None:
_, login = call(
"POST",
"/v1/auth/approle/login",
{"role_id": read_text("api.role_id"), "secret_id": read_text("api.secret_id")},
accept=(200,),
)
token = login["auth"]["client_token"]
code, _ = call("GET", "/v1/secret/data/messenger/worker", token=token, accept=(200, 403))
if code != 403:
raise SystemExit("api policy was able to read the worker secret")
evidence = Path("/evidence")
if evidence.is_dir():
(evidence / "openbao-deny.txt").write_text("PASS api token denied for messenger/worker\n", encoding="utf-8")
print("api policy deny check passed")
def main() -> None:
wait_until_reachable()
material = ensure_init()
token = ensure_unsealed(material)
ensure_mounts(token)
for name in ("api", "worker", "migrate"):
put_policy(token, name)
super_pass = read_text("db_super_password")
api_pass = read_text("db_api_password")
worker_pass = read_text("db_worker_password")
redis_pass = read_text("redis_password")
rabbit_api = read_text("rabbit_api_password")
rabbit_worker = read_text("rabbit_worker_password")
put_kv(
token,
"migrate",
{"database_url": "postgresql://messenger:%s@postgres:5432/messenger" % super_pass},
)
put_kv(
token,
"api",
{
"database_url": "postgresql://messenger_api:%s@postgres:5432/messenger" % api_pass,
"redis_url": "rediss://api:%s@redis:6379/0" % redis_pass,
"broker_url": "amqps://messenger_api:%s@rabbitmq:5671/" % rabbit_api,
"s3_access_key_id": read_text("s3_api_access"),
"s3_secret_access_key": read_text("s3_api_secret"),
},
)
put_kv(
token,
"worker",
{
"database_url": "postgresql://messenger_worker:%s@postgres:5432/messenger" % worker_pass,
"broker_url": "amqps://messenger_worker:%s@rabbitmq:5671/" % rabbit_worker,
"s3_access_key_id": read_text("s3_worker_access"),
"s3_secret_access_key": read_text("s3_worker_secret"),
},
)
print("kv documents written")
if os.environ.get("BAO_REFRESH_KV_ONLY") == "1":
print("approle secret ids left unchanged")
return
for name in ("api", "worker", "migrate"):
ensure_role(token, name)
deny_check()
print("bootstrap complete")
if __name__ == "__main__":
main()
+131
View File
@@ -0,0 +1,131 @@
import json
import re
from typing import Any, Dict, Optional, Tuple
from uuid import UUID
USERNAME_RE = re.compile(r"^[a-z0-9_]{3,32}$")
IDEMPOTENCY_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
def parse_json_body(raw: bytes) -> Tuple[Optional[Dict[str, Any]], Optional[str]]:
if not raw:
return None, "empty body"
try:
data = json.loads(raw.decode("utf-8"))
except (UnicodeDecodeError, json.JSONDecodeError):
return None, "malformed JSON"
if not isinstance(data, dict):
return None, "JSON body must be an object"
return data, None
def require_exact_keys(data: Dict[str, Any], allowed: set, required: set) -> Optional[str]:
keys = set(data.keys())
if keys - allowed:
return "unexpected fields"
if required - keys:
return "missing required fields"
return None
def validate_username(value: Any) -> Optional[str]:
if not isinstance(value, str) or not USERNAME_RE.fullmatch(value):
return "invalid username"
return None
def validate_display_name(value: Any) -> Optional[str]:
if not isinstance(value, str):
return "invalid display_name"
if not value.strip():
return "display_name must not be blank"
if len(value) > 100:
return "display_name too long"
return None
def validate_password(value: Any) -> Optional[str]:
if not isinstance(value, str):
return "invalid password"
if not value.strip():
return "password must not be blank"
if len(value) < 12 or len(value) > 128:
return "password length"
return None
def validate_title(value: Any) -> Optional[str]:
if not isinstance(value, str):
return "invalid title"
if not value.strip():
return "title must not be blank"
if len(value) > 100:
return "title too long"
return None
def validate_uuid(value: Any) -> Optional[str]:
if not isinstance(value, str):
return "invalid uuid"
try:
UUID(value)
except ValueError:
return "invalid uuid"
return None
def validate_idempotency_key(value: Optional[str]) -> Optional[str]:
if value is None or IDEMPOTENCY_RE.fullmatch(value) is None:
return "invalid idempotency key"
return None
def validate_message_text(value: Any, *, allow_blank: bool = False) -> Optional[str]:
if not isinstance(value, str):
return "invalid text"
if len(value) > 4000:
return "text too long"
if not allow_blank and not value.strip():
return "text must not be blank"
return None
def validate_filename(value: Optional[str]) -> Optional[str]:
if not isinstance(value, str) or not value.strip() or len(value) > 255:
return "invalid filename"
for char in value:
code = ord(char)
if code < 32 or code == 127 or char in "/\\":
return "invalid filename"
return None
def parse_attachment_ids(value: Any) -> Tuple[Optional[list], Optional[str]]:
if value is None:
return [], None
if not isinstance(value, list):
return None, "invalid attachment_ids"
if len(value) > 10:
return None, "too many attachments"
seen = set()
ids = []
for item in value:
if validate_uuid(item):
return None, "invalid attachment id"
if item in seen:
return None, "duplicate attachment_ids"
seen.add(item)
ids.append(item)
return ids, None
def validate_limit(value: Optional[str], default: int = 50) -> Tuple[Optional[int], Optional[str]]:
if value is None:
return default, None
try:
limit = int(value)
except ValueError:
return None, "invalid limit"
if limit < 1 or limit > 100:
return None, "limit out of range"
return limit, None
+115
View File
@@ -0,0 +1,115 @@
"""Separate process: consume durable jobs and publish image variants."""
from __future__ import annotations
import asyncio
import logging
import signal
from uuid import UUID
import aio_pika
from app import bao, broker, config, db, jobs, telemetry
from app.broker import payload_from
logger = logging.getLogger("messenger.worker")
def configure_logging() -> None:
telemetry.configure_logging()
async def _settle(message: aio_pika.IncomingMessage) -> None:
carrier = telemetry.carrier_from_headers(message.headers)
parent = telemetry.remote_context(carrier.get("traceparent"), carrier.get("tracestate"))
with telemetry.span(
"attachment.job.consume",
context=parent,
kind="consumer",
attributes={
"messaging.system": "rabbitmq",
"messaging.destination.name": broker.QUEUE,
"messaging.operation": "consume",
},
) as current:
telemetry.worker_enter()
try:
try:
payload = payload_from(message.body)
job_id = UUID(payload["job_id"])
pipeline_version = int(payload["pipeline_version"])
except (ValueError, KeyError, TypeError):
logger.warning("dropping a job message that does not match the schema")
await message.ack()
return
if current is not None:
current.set_attribute("job.id", str(job_id))
try:
waits = 0
while True:
state = await jobs.process(job_id, pipeline_version)
if state == "busy":
waits += 1
if waits > config.JOB_LEASE_SECONDS + 5:
await message.reject(requeue=True)
return
await asyncio.sleep(1)
continue
logger.info("job settled job_id=%s state=%s", job_id, state)
await message.ack()
return
except Exception:
logger.warning("job settle failed job_id=%s", payload.get("job_id"))
await message.reject(requeue=True)
finally:
telemetry.worker_leave()
async def _reap_loop(stop: asyncio.Event) -> None:
while not stop.is_set():
try:
count = await jobs.reap_expired()
if count:
logger.info("requeued %s expired leases", count)
except Exception:
logger.warning("lease reaper failed")
try:
await asyncio.wait_for(stop.wait(), timeout=2)
except asyncio.TimeoutError:
continue
async def serve() -> None:
await asyncio.to_thread(bao.apply)
if config.BAO_ADDR:
asyncio.create_task(bao.renew_loop())
await db.connect()
stop = asyncio.Event()
loop = asyncio.get_running_loop()
for sig in (signal.SIGTERM, signal.SIGINT):
try:
loop.add_signal_handler(sig, stop.set)
except NotImplementedError:
signal.signal(sig, lambda *_: stop.set())
reaper = asyncio.create_task(_reap_loop(stop))
queue, consumer = await broker.consume(_settle, config.WORKER_CONCURRENCY)
logger.info("worker consuming prefetch=%s", config.WORKER_CONCURRENCY)
await stop.wait()
await queue.cancel(consumer)
reaper.cancel()
try:
await reaper
except asyncio.CancelledError:
pass
await broker.close()
await db.close()
telemetry.shutdown()
def main() -> None:
configure_logging()
asyncio.run(serve())
if __name__ == "__main__":
main()
+8
View File
@@ -0,0 +1,8 @@
# Local-only overlay so this stand can run beside another copy.
services:
lb:
ports: !override
- "127.0.0.1:8444:8443"
s3:
ports: !override
- "127.0.0.1:9002:9000"
+663
View File
@@ -0,0 +1,663 @@
# Client -TLS-> lb:8443 -mTLS-> api x2. API listens on 127.0.0.1 only.
# Postgres, Redis, RabbitMQ (via local mTLS proxy), S3 (via local TLS proxy),
# the collector and OpenBao are TLS. Secrets are read from OpenBao with AppRole.
# Run scripts/bootstrap.ps1 before the first start: it creates certs, unseals
# OpenBao and does not print secret values.
x-app-hardening: &app-hardening
read_only: true
security_opt:
- no-new-privileges:true
cap_drop:
- ALL
tmpfs:
- /tmp:rw,nosuid,size=64m
pids_limit: 128
services:
postgres:
image: postgres:16.6-alpine
environment:
POSTGRES_USER: messenger
POSTGRES_PASSWORD_FILE: /run/secrets/db_super_password
POSTGRES_DB: messenger
entrypoint: ["/bin/sh", "/entrypoint.sh"]
volumes:
- pg_data:/var/lib/postgresql/data
- ./infra/postgres/entrypoint.sh:/entrypoint.sh:ro
- ./infra/postgres/pg_hba.conf:/etc/postgres/pg_hba.conf:ro
- ./infra/postgres/grant.sh:/etc/postgres/grant.sh:ro
- ./certs/postgres.crt:/certs/postgres.crt:ro
- ./certs/postgres.key:/certs/postgres.key:ro
- ./certs/ca.crt:/certs/ca.crt:ro
secrets:
- db_super_password
- db_api_password
- db_worker_password
healthcheck:
test: ["CMD-SHELL", "pg_isready -U messenger -d messenger"]
interval: 3s
timeout: 3s
retries: 20
restart: unless-stopped
mem_limit: ${POSTGRES_MEM:-512m}
cpus: ${POSTGRES_CPUS:-1.0}
security_opt:
- no-new-privileges:true
networks: [data]
redis:
image: redis:7.4.2-alpine
entrypoint: ["/bin/sh", "/entrypoint.sh"]
volumes:
- redis_data:/data
- ./infra/redis/entrypoint.sh:/entrypoint.sh:ro
- ./certs/redis.crt:/certs/redis.crt:ro
- ./certs/redis.key:/certs/redis.key:ro
- ./certs/ca.crt:/certs/ca.crt:ro
secrets:
- redis_password
healthcheck:
test:
[
"CMD-SHELL",
"redis-cli --tls --cacert /tmp/ca.crt -p 6379 --user api --pass \"$$(cat /run/secrets/redis_password)\" ping | grep -q PONG",
]
interval: 3s
timeout: 3s
retries: 20
restart: unless-stopped
mem_limit: 128m
cpus: "0.50"
security_opt:
- no-new-privileges:true
networks: [data]
rabbitmq:
image: rabbitmq:3.13.7-alpine
hostname: rabbitmq
entrypoint: ["/bin/sh", "/entrypoint.sh"]
volumes:
- rabbitmq_data:/var/lib/rabbitmq
- ./infra/rabbitmq/entrypoint.sh:/entrypoint.sh:ro
- ./certs/rabbitmq.crt:/certs/rabbitmq.crt:ro
- ./certs/rabbitmq.key:/certs/rabbitmq.key:ro
- ./certs/ca.crt:/certs/ca.crt:ro
secrets:
- rabbit_api_password
- rabbit_worker_password
healthcheck:
test: ["CMD", "rabbitmq-diagnostics", "-q", "ping"]
interval: 5s
timeout: 5s
retries: 20
start_period: 20s
restart: unless-stopped
mem_limit: 256m
cpus: "0.50"
security_opt:
- no-new-privileges:true
networks: [data]
rabbit-mtls:
image: haproxy:3.1.7-alpine
network_mode: service:rabbitmq
depends_on:
rabbitmq:
condition: service_started
volumes:
- ./infra/haproxy-rabbit.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
- ./certs/rabbitmq.pem:/certs/rabbitmq.pem:ro
- ./certs/ca.crt:/certs/ca.crt:ro
- ./certs/allowed-api.serial:/certs/allowed-api.serial:ro
- ./certs/allowed-worker.serial:/certs/allowed-worker.serial:ro
read_only: true
tmpfs:
- /tmp:rw,nosuid,size=16m
- /var/run:rw,nosuid,size=8m
cap_drop:
- ALL
security_opt:
- no-new-privileges:true
restart: unless-stopped
seaweed:
image: chrislusf/seaweedfs:3.85
entrypoint: ["/bin/sh", "/seaweed-entrypoint.sh"]
environment:
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
volumes:
- s3_data:/data
- ./infra/s3/seaweed-entrypoint.sh:/seaweed-entrypoint.sh:ro
secrets:
- s3_admin_access
- s3_admin_secret
- s3_api_access
- s3_api_secret
- s3_worker_access
- s3_worker_secret
healthcheck:
test: ["CMD-SHELL", "wget -q -O /dev/null http://127.0.0.1:9333/cluster/status || exit 1"]
interval: 3s
timeout: 5s
retries: 20
start_period: 8s
restart: unless-stopped
mem_limit: 256m
cpus: "0.50"
security_opt:
- no-new-privileges:true
networks: [s3internal]
s3:
image: haproxy:3.1.7-alpine
volumes:
- ./infra/haproxy-s3.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
- ./certs/s3.pem:/certs/s3.pem:ro
ports:
- "127.0.0.1:9007:9000"
depends_on:
seaweed:
condition: service_started
read_only: true
tmpfs:
- /tmp:rw,nosuid,size=16m
- /var/run:rw,nosuid,size=8m
cap_drop:
- ALL
security_opt:
- no-new-privileges:true
restart: unless-stopped
networks: [data, s3internal]
openbao:
image: openbao/openbao:2.2.0
user: "0"
entrypoint: ["bao"]
command: ["server", "-config=/openbao/config/openbao.hcl"]
volumes:
- bao_data:/openbao/file
- ./infra/openbao/openbao.hcl:/openbao/config/openbao.hcl:ro
- ./certs/openbao.crt:/certs/openbao.crt:ro
- ./certs/openbao.key:/certs/openbao.key:ro
- ./certs/ca.crt:/certs/ca.crt:ro
healthcheck:
test: ["CMD-SHELL", "BAO_ADDR=https://127.0.0.1:8200 BAO_CACERT=/certs/ca.crt bao status"]
interval: 3s
timeout: 3s
retries: 40
start_period: 5s
restart: unless-stopped
mem_limit: 256m
cpus: "0.50"
security_opt:
- no-new-privileges:true
networks: [data]
openbao-bootstrap:
profiles: ["bootstrap"]
build:
context: .
dockerfile: Dockerfile
image: mtusi-messenger:lab7
command: ["python", "-m", "app.tools.openbao_bootstrap"]
environment:
BAO_ADDR: https://openbao:8200
TLS_CA_FILE: /certs/ca.crt
BAO_INIT_FILE: /secrets/openbao-init.json
volumes:
- ./secrets:/secrets
- ./certs/ca.crt:/certs/ca.crt:ro
- ./infra/openbao/policies:/policies:ro
- ./evidence:/evidence
networks: [data]
depends_on:
openbao:
condition: service_started
restart: "no"
migrate:
<<: *app-hardening
build:
context: .
dockerfile: Dockerfile
image: mtusi-messenger:lab7
command: ["python", "-m", "app.migrate"]
environment:
APP_ENV: lab
LOG_LEVEL: info
TLS_CA_FILE: /certs/ca.crt
BAO_ADDR: https://openbao:8200
BAO_CACERT: /certs/ca.crt
BAO_ROLE_ID_FILE: /run/secrets/migrate_role_id
BAO_SECRET_ID_FILE: /run/secrets/migrate_secret_id
BAO_SECRET_PATH: secret/data/messenger/migrate
DB_POOL_MIN: "1"
DB_POOL_MAX: "2"
MIGRATIONS_ON_START: "1"
secrets:
- source: migrate_role_id
target: migrate_role_id
- source: migrate_secret_id
target: migrate_secret_id
volumes:
- ./certs/ca.crt:/certs/ca.crt:ro
depends_on:
postgres:
condition: service_healthy
openbao:
condition: service_healthy
restart: "no"
mem_limit: 256m
cpus: "0.50"
networks: [data]
s3-init:
<<: *app-hardening
image: mtusi-messenger:lab7
command: ["python", "-m", "app.s3bootstrap"]
environment:
S3_ENDPOINT: https://s3:9000
S3_REGION: ${S3_REGION:-us-east-1}
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
TLS_CA_FILE: /certs/ca.crt
S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_admin_access
S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_admin_secret
secrets:
- source: s3_admin_access
target: s3_admin_access
- source: s3_admin_secret
target: s3_admin_secret
volumes:
- ./certs/ca.crt:/certs/ca.crt:ro
depends_on:
s3:
condition: service_started
seaweed:
condition: service_healthy
restart: "no"
networks: [data]
api:
<<: *app-hardening
image: mtusi-messenger:lab7
command: ["sh", "/scripts/api-entrypoint.sh"]
environment: &api-env
APP_HOST: 127.0.0.1
APP_PORT: "8080"
MTLS_PORT: "8443"
APP_ENV: lab
LOG_LEVEL: info
TELEMETRY_ENABLED: ${TELEMETRY_ENABLED:-1}
TRACE_SAMPLE_RATIO: ${TRACE_SAMPLE_RATIO:-1}
OTEL_SERVICE_NAME: messenger-api
OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:4318
OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf
OTEL_EXPORTER_OTLP_CERTIFICATE: /certs/ca.crt
OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: /certs/api-client.crt
OTEL_EXPORTER_OTLP_CLIENT_KEY: /certs/api-client.key
SERVICE_VERSION: lab7
SHUTDOWN_GRACE_SECONDS: "3"
LB_DRAIN_SECONDS: ${LB_DRAIN_SECONDS:-2}
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
CACHE_TTL_SECONDS: ${CACHE_TTL_SECONDS:-60}
IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400}
SESSION_STORE: redis
S3_ENDPOINT: https://s3:9000
S3_REGION: ${S3_REGION:-us-east-1}
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
S3_PUBLIC_ENDPOINT: ${S3_PUBLIC_ENDPOINT:-https://127.0.0.1:9007}
PRESIGN_TTL_SECONDS: ${PRESIGN_TTL_SECONDS:-60}
MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-10485760}
MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000}
ORPHAN_GRACE_SECONDS: ${ORPHAN_GRACE_SECONDS:-120}
S3_SWEEP_INTERVAL_SECONDS: ${S3_SWEEP_INTERVAL_SECONDS:-30}
TLS_CA_FILE: /certs/ca.crt
TLS_CERT_FILE: /certs/api-client.crt
TLS_KEY_FILE: /certs/api-client.key
TLS_SERVER_CERT_FILE: /certs/api.crt
TLS_SERVER_KEY_FILE: /certs/api.key
MTLS_ALLOW_FILE: /certs/allowed-lb.sha256
BAO_ADDR: https://openbao:8200
BAO_CACERT: /certs/ca.crt
BAO_ROLE_ID_FILE: /run/secrets/api_role_id
BAO_SECRET_ID_FILE: /run/secrets/api_secret_id
BAO_SECRET_PATH: secret/data/messenger/api
ARGON2_MEMORY_KIB: ${ARGON2_MEMORY_KIB:-19456}
ARGON2_ITERATIONS: ${ARGON2_ITERATIONS:-2}
ARGON2_PARALLELISM: ${ARGON2_PARALLELISM:-1}
LOGIN_RATE_LIMIT: ${LOGIN_RATE_LIMIT:-8}
LOGIN_RATE_WINDOW_SECONDS: ${LOGIN_RATE_WINDOW_SECONDS:-60}
DB_POOL_MIN: "1"
DB_POOL_MAX: ${DB_POOL_MAX:-4}
DB_COMMAND_TIMEOUT: "5"
DB_CONNECT_TIMEOUT: "5"
MIGRATIONS_ON_START: "0"
JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5}
JOB_TIMEOUT_SECONDS: ${JOB_TIMEOUT_SECONDS:-60}
STAGING_RETENTION_SECONDS: ${STAGING_RETENTION_SECONDS:-86400}
secrets:
- source: api_role_id
target: api_role_id
- source: api_secret_id
target: api_secret_id
volumes:
- ./scripts/api-entrypoint.sh:/scripts/api-entrypoint.sh:ro
- ./certs/ca.crt:/certs/ca.crt:ro
- ./certs/api.crt:/certs/api.crt:ro
- ./certs/api.key:/certs/api.key:ro
- ./certs/api-client.crt:/certs/api-client.crt:ro
- ./certs/api-client.key:/certs/api-client.key:ro
- ./certs/allowed-lb.sha256:/certs/allowed-lb.sha256:ro
depends_on:
migrate:
condition: service_completed_successfully
postgres:
condition: service_healthy
redis:
condition: service_healthy
s3-init:
condition: service_completed_successfully
rabbitmq:
condition: service_healthy
rabbit-mtls:
condition: service_started
openbao:
condition: service_healthy
expose:
- "8443"
restart: unless-stopped
mem_limit: ${API_MEM:-384m}
cpus: ${API_CPUS:-0.50}
stop_grace_period: 8s
healthcheck:
test:
[
"CMD",
"python",
"-c",
"import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health/ready', timeout=2)",
]
interval: 5s
timeout: 3s
retries: 12
start_period: 15s
networks: [app, data, signals]
lb:
image: haproxy:3.1.7-alpine
volumes:
- ./infra/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
- ./certs/lb.pem:/certs/lb.pem:ro
- ./certs/lb-client.pem:/certs/lb-client.pem:ro
- ./certs/ca.crt:/certs/ca.crt:ro
ports:
- "127.0.0.1:8443:8443"
depends_on:
api:
condition: service_started
read_only: true
tmpfs:
- /tmp:rw,nosuid,size=16m
- /var/run:rw,nosuid,size=8m
cap_drop:
- ALL
security_opt:
- no-new-privileges:true
restart: unless-stopped
mem_limit: 128m
cpus: "0.25"
networks: [app]
worker:
<<: *app-hardening
image: mtusi-messenger:lab7
command: ["python", "-m", "app.worker"]
environment:
APP_ENV: lab
LOG_LEVEL: info
TELEMETRY_ENABLED: ${TELEMETRY_ENABLED:-1}
TRACE_SAMPLE_RATIO: ${TRACE_SAMPLE_RATIO:-1}
OTEL_SERVICE_NAME: messenger-worker
OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:4318
OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf
OTEL_EXPORTER_OTLP_CERTIFICATE: /certs/ca.crt
OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE: /certs/worker-client.crt
OTEL_EXPORTER_OTLP_CLIENT_KEY: /certs/worker-client.key
SERVICE_VERSION: lab7
S3_ENDPOINT: https://s3:9000
S3_REGION: ${S3_REGION:-us-east-1}
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-10485760}
MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000}
TLS_CA_FILE: /certs/ca.crt
TLS_CERT_FILE: /certs/worker-client.crt
TLS_KEY_FILE: /certs/worker-client.key
BAO_ADDR: https://openbao:8200
BAO_CACERT: /certs/ca.crt
BAO_ROLE_ID_FILE: /run/secrets/worker_role_id
BAO_SECRET_ID_FILE: /run/secrets/worker_secret_id
BAO_SECRET_PATH: secret/data/messenger/worker
WORKER_CONCURRENCY: ${WORKER_CONCURRENCY:-2}
JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5}
JOB_TIMEOUT_SECONDS: ${JOB_TIMEOUT_SECONDS:-60}
STAGING_RETENTION_SECONDS: ${STAGING_RETENTION_SECONDS:-86400}
DB_POOL_MIN: "1"
DB_POOL_MAX: "4"
MIGRATIONS_ON_START: "0"
secrets:
- source: worker_role_id
target: worker_role_id
- source: worker_secret_id
target: worker_secret_id
volumes:
- ./certs/ca.crt:/certs/ca.crt:ro
- ./certs/worker-client.crt:/certs/worker-client.crt:ro
- ./certs/worker-client.key:/certs/worker-client.key:ro
depends_on:
migrate:
condition: service_completed_successfully
postgres:
condition: service_healthy
rabbitmq:
condition: service_healthy
rabbit-mtls:
condition: service_started
s3-init:
condition: service_completed_successfully
openbao:
condition: service_healthy
restart: unless-stopped
mem_limit: 768m
cpus: "1.0"
stop_grace_period: 20s
networks: [data, signals]
healthcheck:
test: ["CMD", "python", "-c", "import os; os.kill(1, 0)"]
interval: 10s
timeout: 3s
retries: 3
start_period: 20s
otel-collector:
image: otel/opentelemetry-collector-contrib:0.128.0
command: ["--config=/etc/otel/collector.yaml"]
volumes:
- ./infra/otel/collector.yaml:/etc/otel/collector.yaml:ro
- ./certs/ca.crt:/certs/ca.crt:ro
- ./certs/tempo.crt:/certs/tempo.crt:ro
- ./certs/loki.crt:/certs/loki.crt:ro
- ./certs/prometheus.crt:/certs/prometheus.crt:ro
restart: unless-stopped
mem_limit: 320m
cpus: "0.50"
security_opt:
- no-new-privileges:true
networks: [signals, telemetry]
otel-mtls:
image: haproxy:3.1.7-alpine
network_mode: service:otel-collector
depends_on:
otel-collector:
condition: service_started
volumes:
- ./infra/haproxy-otel.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
- ./certs/otel.pem:/certs/otel.pem:ro
- ./certs/ca.crt:/certs/ca.crt:ro
- ./certs/allowed-api.serial:/certs/allowed-api.serial:ro
- ./certs/allowed-worker.serial:/certs/allowed-worker.serial:ro
read_only: true
tmpfs:
- /tmp:rw,nosuid,size=16m
- /var/run:rw,nosuid,size=8m
cap_drop:
- ALL
security_opt:
- no-new-privileges:true
restart: unless-stopped
prometheus:
image: prom/prometheus:v2.55.1
command:
- --config.file=/etc/prometheus/prometheus.yml
- --web.config.file=/etc/prometheus/web.yml
- --web.enable-remote-write-receiver
- --storage.tsdb.path=/prometheus
- --storage.tsdb.retention.time=7d
volumes:
- ./infra/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml:ro
- ./infra/prometheus/alerts.yml:/etc/prometheus/alerts.yml:ro
- ./infra/prometheus/web.yml:/etc/prometheus/web.yml:ro
- ./certs/prometheus.crt:/certs/prometheus.crt:ro
- ./certs/prometheus.key:/certs/prometheus.key:ro
- prometheus_data:/prometheus
restart: unless-stopped
mem_limit: 512m
cpus: "0.50"
security_opt:
- no-new-privileges:true
networks: [telemetry]
loki:
image: grafana/loki:3.3.2
command: ["-config.file=/etc/loki/loki.yml"]
volumes:
- ./infra/loki/loki.yml:/etc/loki/loki.yml:ro
- ./certs/loki.crt:/certs/loki.crt:ro
- ./certs/loki.key:/certs/loki.key:ro
- loki_data:/loki
restart: unless-stopped
mem_limit: 512m
cpus: "0.50"
security_opt:
- no-new-privileges:true
networks: [telemetry]
tempo:
image: grafana/tempo:2.7.1
command: ["-config.file=/etc/tempo/tempo.yml"]
volumes:
- ./infra/tempo/tempo.yml:/etc/tempo/tempo.yml:ro
- ./certs/tempo.crt:/certs/tempo.crt:ro
- ./certs/tempo.key:/certs/tempo.key:ro
- tempo_data:/var/tempo
restart: unless-stopped
mem_limit: 512m
cpus: "0.50"
security_opt:
- no-new-privileges:true
networks: [telemetry]
grafana:
image: grafana/grafana:11.4.0
entrypoint: ["/bin/sh", "/entrypoint.sh"]
environment:
GF_SECURITY_ADMIN_USER: admin
GF_AUTH_ANONYMOUS_ENABLED: "false"
GF_USERS_DEFAULT_THEME: light
GF_SERVER_PROTOCOL: https
GF_SERVER_CERT_FILE: /certs/grafana.crt
GF_SERVER_CERT_KEY: /certs/grafana.key
SSL_CERT_FILE: /certs/ca.crt
ports:
- "127.0.0.1:3007:3000"
volumes:
- ./infra/grafana/entrypoint.sh:/entrypoint.sh:ro
- ./infra/grafana/provisioning:/etc/grafana/provisioning:ro
- ./infra/grafana/dashboards:/var/lib/grafana/dashboards:ro
- ./certs/grafana.crt:/certs/grafana.crt:ro
- ./certs/grafana.key:/certs/grafana.key:ro
- ./certs/ca.crt:/certs/ca.crt:ro
- grafana_data:/var/lib/grafana
secrets:
- source: grafana_password
target: grafana_password
depends_on:
- prometheus
- loki
- tempo
restart: unless-stopped
mem_limit: 256m
cpus: "0.50"
security_opt:
- no-new-privileges:true
networks: [telemetry]
secrets:
db_super_password:
file: ./secrets/db_super_password
db_api_password:
file: ./secrets/db_api_password
db_worker_password:
file: ./secrets/db_worker_password
redis_password:
file: ./secrets/redis_password
rabbit_api_password:
file: ./secrets/rabbit_api_password
rabbit_worker_password:
file: ./secrets/rabbit_worker_password
s3_admin_access:
file: ./secrets/s3_admin_access
s3_admin_secret:
file: ./secrets/s3_admin_secret
s3_api_access:
file: ./secrets/s3_api_access
s3_api_secret:
file: ./secrets/s3_api_secret
s3_worker_access:
file: ./secrets/s3_worker_access
s3_worker_secret:
file: ./secrets/s3_worker_secret
grafana_password:
file: ./secrets/grafana_password
api_role_id:
file: ./secrets/api.role_id
api_secret_id:
file: ./secrets/api.secret_id
worker_role_id:
file: ./secrets/worker.role_id
worker_secret_id:
file: ./secrets/worker.secret_id
migrate_role_id:
file: ./secrets/migrate.role_id
migrate_secret_id:
file: ./secrets/migrate.secret_id
networks:
app:
data:
signals:
telemetry:
s3internal:
volumes:
pg_data:
redis_data:
s3_data:
rabbitmq_data:
prometheus_data:
loki_data:
tempo_data:
grafana_data:
bao_data:
+22 -26
View File
@@ -1,37 +1,33 @@
# Матрица доверия — заполнить в решении lab7 # Матрица доверия
Это обязательная матрица покрытия. Для каждой строки укажите реальный порт, endpoint, CA, service identity, проверку SAN/ACL, срок жизни credentials и команду положительного/отрицательного теста. TLS шифрует и подтверждает сервер; mTLS также проверяет клиента. При доверенном CA всё равно нужно ограничивать разрешённую identity. Plaintext hop допустим только внутри закрытого локального transport/proxy boundary, без опубликованного обхода; границу и rationale нужно доказать. Публичный CA стенда — `certs/ca.crt` (создаётся локально, в Git не коммитится). Приватный ключ CA остаётся в `certs/ca.key` на хосте оператора. Идентичность LB — URI SAN `spiffe://messenger/lb` плюс SHA-256 leaf в `certs/allowed-lb.sha256`. API и worker предъявляют `spiffe://messenger/api` и `spiffe://messenger/worker`.
| Связь | Минимум на 3 | Дополнительно на 4 | Доказательство / конфиг | | Связь | Минимум на 3 | Дополнительно на 4 | Доказательство / конфиг |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| Клиент → ingress/LB | TLS, CA + hostname, Bearer | Проверка expiry/revocation сессии и общего login rate limit | TODO | | Клиент → ingress/LB | TLS, `certs/ca.crt`, SAN `DNS:localhost` и `IP:127.0.0.1`, порт `127.0.0.1:8443`, Bearer | Сессия — SHA-256 токена в Redis, TTL из `SESSION_TTL_SECONDS`; login rate limit общий для реплик (Redis `login:u:*` / `login:ip:*`, 8/30 за 60 с, `429` и `Retry-After`) | `infra/haproxy.cfg`; `make test CA_FILE=...`; `make test-security`; `student-tests/mtls_probe.py` |
| LB → API (все реплики) | mTLS + allowlist LB identity | Ротация leaf без обхода проверки | TODO | | LB → API (все реплики) | mTLS, только TLS 1.2. Сервер: cert `api` (SAN `DNS:api`). Клиент: только отпечаток из `allowed-lb.sha256` и URI `spiffe://messenger/lb`. Uvicorn на `127.0.0.1:8080`, снаружи контейнера порта нет | Смена leaf LB без пересборки образа: заменить `certs/lb.pem` и перезапустить `lb`. Отзыв: убрать строку из `allowed-lb.sha256` (см. `lb-revoked`) | `app/tls_proxy.py`, `infra/haproxy.cfg`. Отказ: без cert, `other-client.pem` (чужой CA), `stranger.pem`, `lb-revoked.pem`. Успех: `lb-client.pem` |
| API/worker → PostgreSQL | TLS verify-full + раздельные ограниченные DB roles | Ротация credentials; mTLS — допустимое усиление | TODO | | API/worker → PostgreSQL | TLS verify-full, SAN `DNS:postgres`, `hostssl` + SCRAM. migrate — суперпользователь `messenger` только из KV `messenger/migrate`. API — `messenger_api`. Worker — `messenger_worker` без прав на `users` | Пароли ролей лежат в OpenBao и меняются вместе с KV и `ALTER ROLE`; рестарт API подхватывает новое значение | `infra/postgres/entrypoint.sh`, `pg_hba.conf`, `grant.sh` |
| API/worker → S3 | TLS + разные scoped credentials/prefix rights | Проверка denied prefix и ротация | TODO | | API/worker → S3 | TLS до HAProxy на `s3:9000`. Seaweed без TLS только в сети `s3internal` (`0.0.0.0:9000`; localhost bind ломает его внутренний gRPC). Разные ключи: api читает bucket и пишет `staging/` и `originals/`; worker без `Admin`; bootstrap-ключ только у `s3-init` | Запись ключом worker в префикс вне выданных actions отклоняется Seaweed | `infra/s3/seaweed-entrypoint.sh`, `infra/haproxy-s3.cfg`. Публичный presign: `https://127.0.0.1:9007` |
| API/worker → broker | TLS + разные producer/consumer identities и ACL | mTLS + ограничение допустимых SAN/ролей | TODO | | API/worker → broker | mTLS на `rabbitmq:5671`. HAProxy пускает только URI `spiffe://messenger/api` или `.../worker` и серийный номер из `allowed-api.serial` / `allowed-worker.serial`. AMQP дальше только на `127.0.0.1:5672`. Пользователи `messenger_api` и `messenger_worker` разные | Чужой сертификат того же CA (`stranger`) и старый leaf worker режутся до AMQP. Worker не объявляет чужие очереди: configure/write/read только `attachment.jobs*` | `infra/haproxy-rabbit.cfg`, `infra/rabbitmq/entrypoint.sh`, `student-tests/same_ca_probe.py` |
| API/worker → Collector | TLS; сеть/аутентификация запрещает произвольный ingest | mTLS с раздельными identities | TODO | | API/worker → Collector | mTLS `https://otel-collector:4318`. Collector слушает plaintext лишь `127.0.0.1:14318`. Те же две URI и те же два serial allow-файла, клиентские cert разные | `stranger` получает HTTP 403 от HAProxy, не OTLP. Просроченный leaf не проходит handshake | `infra/haproxy-otel.cfg`, `student-tests/same_ca_probe.py` |
| Collector → telemetry backends | TLS + scoped backend credentials или mTLS | Ротация и проверка least privilege | TODO | | Collector → telemetry backends | TLS: Tempo `https://tempo:4318`, Prometheus `https://prometheus:9090`, Loki `https://loki:3100`, CA `certs/ca.crt`. Сеть `telemetry` не доступна API | Отдельных паролей backend-ов нет: граница — сеть и серверный сертификат. Это зафиксировано как ограничение, не как mTLS | `infra/otel/collector.yaml`, `infra/prometheus/web.yml`, `infra/loki/loki.yml`, `infra/tempo/tempo.yml` |
| Grafana → data sources | TLS с проверкой сервера, ограниченная identity | Отрицательные проверки доступа | TODO | | Grafana → data sources | HTTPS, `SSL_CERT_FILE=/certs/ca.crt`, анонимный доступ выключен, пароль admin из файла секрета. Порт только `127.0.0.1:3007` | Логин без пароля больше не открывает Admin | `infra/grafana/entrypoint.sh`, provisioning datasources |
| API/worker/agent → OpenBao | TLS + сервисный auth + scoped policy | Renewal/expiry/revocation | TODO | | API/worker/agent → OpenBao | `https://openbao:8200`, file storage, не dev. AppRole, policy `messenger-api` / `messenger-worker` / `messenger-migrate`, token TTL 20 мин, renew | SecretID TTL 24 ч, новый SecretID выпускает повторный bootstrap. Чтение чужого path — 403 | `infra/openbao/openbao.hcl`, `policies/*.hcl`, `app/bao.py`. Доказательство: `evidence/openbao-deny.txt` |
| Оператор → OpenBao/Grafana/S3 admin | TLS + authentication, доступ локальный/через защищённый канал | Разделение operator/application roles | TODO | | Оператор → OpenBao/Grafana/S3 admin | OpenBao с хоста не публикуется; unseal делает одноразовый контейнер `openbao-bootstrap`. Grafana и S3 — localhost TLS. Root token и unseal key только в `secrets/openbao-init.json` | Роль приложения не совпадает с root: в API нет `BAO_TOKEN` | `scripts/bootstrap.ps1`, `app/tools/openbao_bootstrap.py` |
| API → Redis/Valkey, если используется | TLS + ACL/пароль с минимальными правами | Ротация; mTLS по возможности | TODO | | API → Redis | TLS `rediss://redis:6379`, SAN `DNS:redis`, пользователь ACL `api`. Worker Redis не использует. Default user выключен | Пароль в KV `messenger/api`, не в образе | `infra/redis/entrypoint.sh` |
| Replication/кластерные каналы, если добавлены | TLS/mTLS либо подтверждённый шифрованный transport | Проверка заявленной модели отказа | TODO | | Replication/кластерные каналы | N/A. Один Postgres, один Redis, один брокер, один OpenBao. Отказ узла Docker-хоста не перекрывается | — | `compose.yaml` |
Нет выбранного компонента — отметьте N/A с причиной, а не оставляйте пустую строку. Внутренний публичный health listener, если нужен, минимален и изолирован; через него нельзя обращаться к бизнес-API без mTLS. Отдельно задокументируйте scrape/health/bootstrap каналы: они тоже не должны создавать обход.
## Обязательные отрицательные проверки ## Обязательные отрицательные проверки
1. HTTPS с правильным CA/hostname проходит; с пустым/чужим CA и неправильным hostname — ошибка верификации, не «сервер недоступен». 1. `make test-security BASE_URL=https://127.0.0.1:8443 CA_FILE=$PWD/certs/ca.crt` — доверенный CA проходит, пустой trust store даёт ошибку проверки сертификата.
2. LB→API: без client cert, с cert чужого CA, с запрещённой identity от доверенного CA — отказ; с разрешённой LB identity — успех. 2. `python student-tests/mtls_probe.py` — нет cert / чужой CA / stranger / отозванный отпечаток отвергаются, `lb-client` получает `/health/ready`.
3. На 4 повторите набор для broker и Collector; ограничение на network policy не заменяет проверку identity. 3. Broker и Collector: HAProxy `tcp-request`/`http-request deny`, если в SAN нет `spiffe://messenger/api|worker`.
4. Пользователь вне чата не читает metadata/content и не прикрепляет чужой файл; поддельный X-User-Id не меняет Bearer identity. 4. Чужой участник не читает чат и вложение (публичный smoke). `X-User-Id` не подменяет Bearer: такого доверия в коде нет.
5. OpenBao app policy читает только свой secret/path; запись policy и чтение чужого path запрещены. Worker не получает admin credentials API/БД/S3. 5. После bootstrap `evidence/openbao-deny.txt` фиксирует 403 на чужой KV path. Worker не получает `database_url` API и admin-ключ S3.
6. На 4 отзовите secret/cert и дождитесь контролируемого эффекта с учётом действующих соединений, TLS resumption и cache/TTL. Покажите новое подключение, иначе тест отзыва может ничего не проверить. 6. Отзыв LB: очистить `allowed-lb.sha256` или подставить отпечаток другого leaf и повторить probe. Новое соединение режется сразу; старый процесс LB не держит проверка внутри API, allow-файл читается на каждый handshake.
## Bootstrap и эксплуатация ## Bootstrap и эксплуатация
В репозитории только открытые конфиги, policy templates и scripts. CA private key, leaf keys, root token, unseal shares и SecretID не коммитятся, не запекаются в образ и не печатаются в отчёте. Для локального стенда оператор создаёт их вне Git и передаёт через files/secrets с ограниченными правами. Опишите, кто имеет доступ к CA/unseal, что нужно после рестарта OpenBao и как восстановить работу. Оператор: `pwsh scripts/bootstrap.ps1` (или Windows PowerShell). Скрипт создаёт `secrets/` и `certs/`, инициализирует OpenBao и поднимает стенд. Повторный запуск unseal-ит уже инициализированный OpenBao и не печатает token.
OpenBao не использует dev-mode. Выберите persistent storage и auth метод (например AppRole с короткоживущим SecretID/response wrapping, cert auth или иная обоснованная identity). Не подменяйте root token постоянной переменной BAO_TOKEN в приложении. Рабочие tokens имеют policy, TTL и renewal/re-auth сценарий. Статические KV secrets на 3 допустимы при реальном чтении через сервисную identity; динамические DB credentials — хорошее расширение, но не обязательное название технологии. Unseal key и root token лежат только у оператора. Их нет в образе, в переменных API и в репозитории. После рестарта OpenBao API сам не unseal-ится.
Разрешённый компромисс учебного стенда: ручной operator init/unseal, если он безопасно документирован и не нужен при каждом обычном рестарте API. Автоматическое хранение всех unseal shares рядом с OpenBao без защиты не считается решённым bootstrap.
+1
View File
@@ -0,0 +1 @@
PASS api token denied for messenger/worker
+156
View File
@@ -0,0 +1,156 @@
{
"uid": "messenger-lab6",
"title": "Messenger observability",
"tags": ["messenger", "lab6"],
"timezone": "browser",
"schemaVersion": 39,
"version": 1,
"refresh": "10s",
"time": {"from": "now-1h", "to": "now"},
"description": "RPS and errors use messenger_http_requests_total. Durations are histogram_quantile over buckets, in seconds. Queue age is seconds. API error ratio excludes health.",
"panels": [
{
"id": 1,
"type": "timeseries",
"title": "API RPS",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 0},
"fieldConfig": {"defaults": {"unit": "reqps", "custom": {"drawStyle": "line"}}, "overrides": []},
"targets": [
{
"refId": "A",
"expr": "sum by (method, route) (rate(messenger_http_requests_total[1m]))",
"legendFormat": "{{method}} {{route}}"
}
]
},
{
"id": 2,
"type": "timeseries",
"title": "API error ratio (5xx / business)",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 12, "y": 0},
"fieldConfig": {"defaults": {"unit": "percentunit", "min": 0, "max": 1}, "overrides": []},
"targets": [
{
"refId": "A",
"expr": "sum(rate(messenger_http_requests_total{status_class=\"5xx\"}[1m])) / clamp_min(sum(rate(messenger_http_requests_total[1m])), 1e-9)",
"legendFormat": "5xx ratio"
}
]
},
{
"id": 3,
"type": "timeseries",
"title": "API duration p50 / p95 / p99",
"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.50, sum by (le) (rate(messenger_http_request_duration_seconds_bucket[1m])))", "legendFormat": "p50"},
{"refId": "B", "expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_http_request_duration_seconds_bucket[1m])))", "legendFormat": "p95"},
{"refId": "C", "expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_http_request_duration_seconds_bucket[1m])))", "legendFormat": "p99"}
]
},
{
"id": 4,
"type": "timeseries",
"title": "Jobs by outcome",
"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": "{{outcome}}"
}
]
},
{
"id": 5,
"type": "timeseries",
"title": "Worker duration p50 / p95 / p99",
"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.50, sum by (le) (rate(messenger_job_duration_seconds_bucket[1m])))", "legendFormat": "p50"},
{"refId": "B", "expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_job_duration_seconds_bucket[1m])))", "legendFormat": "p95"},
{"refId": "C", "expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_job_duration_seconds_bucket[1m])))", "legendFormat": "p99"}
]
},
{
"id": 6,
"type": "timeseries",
"title": "Time to ready p50 / p95 / p99",
"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.50, sum by (le) (rate(messenger_time_to_ready_seconds_bucket[1m])))", "legendFormat": "p50"},
{"refId": "B", "expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_time_to_ready_seconds_bucket[1m])))", "legendFormat": "p95"},
{"refId": "C", "expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_time_to_ready_seconds_bucket[1m])))", "legendFormat": "p99"}
]
},
{
"id": 7,
"type": "timeseries",
"title": "Queue depth and oldest job age",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 24},
"fieldConfig": {"defaults": {}, "overrides": []},
"targets": [
{"refId": "A", "expr": "max(messenger_queue_depth)", "legendFormat": "depth (jobs)"},
{"refId": "B", "expr": "max(messenger_queue_oldest_age_seconds)", "legendFormat": "oldest age (seconds)"}
]
},
{
"id": 8,
"type": "timeseries",
"title": "DB pool used and waiting",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 12, "y": 24},
"fieldConfig": {"defaults": {"unit": "none"}, "overrides": []},
"targets": [
{"refId": "A", "expr": "max by (service_name, service_instance_id) (messenger_db_pool_used)", "legendFormat": "used {{service_name}} {{service_instance_id}}"},
{"refId": "B", "expr": "max by (service_name, service_instance_id) (messenger_db_pool_waiting)", "legendFormat": "waiting {{service_name}} {{service_instance_id}}"}
]
},
{
"id": 9,
"type": "timeseries",
"title": "Worker busy / capacity",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 32},
"fieldConfig": {"defaults": {"unit": "none"}, "overrides": []},
"targets": [
{"refId": "A", "expr": "max(messenger_worker_busy)", "legendFormat": "busy"},
{"refId": "B", "expr": "max(messenger_worker_capacity)", "legendFormat": "capacity"}
]
},
{
"id": 10,
"type": "timeseries",
"title": "Process CPU and RSS",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 12, "y": 32},
"fieldConfig": {"defaults": {}, "overrides": []},
"targets": [
{"refId": "A", "expr": "max by (service_name, service_instance_id) (process_cpu_percent)", "legendFormat": "cpu % {{service_name}} {{service_instance_id}}"},
{"refId": "B", "expr": "max by (service_name, service_instance_id) (process_memory_rss_bytes)", "legendFormat": "rss {{service_name}} {{service_instance_id}}"}
]
},
{
"id": 11,
"type": "timeseries",
"title": "Firing alerts",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 24, "x": 0, "y": 40},
"fieldConfig": {"defaults": {"unit": "none"}, "overrides": []},
"targets": [
{"refId": "A", "expr": "ALERTS{alertstate=\"firing\"}", "legendFormat": "{{alertname}}"}
]
}
]
}
+7
View File
@@ -0,0 +1,7 @@
#!/bin/sh
set -eu
if [ -f /run/secrets/grafana_password ]; then
GF_SECURITY_ADMIN_PASSWORD=$(cat /run/secrets/grafana_password)
export GF_SECURITY_ADMIN_PASSWORD
fi
exec /run.sh "$@"
@@ -0,0 +1,11 @@
apiVersion: 1
providers:
- name: messenger
orgId: 1
folder: Messenger
type: file
disableDeletion: false
updateIntervalSeconds: 30
options:
path: /var/lib/grafana/dashboards
@@ -0,0 +1,38 @@
apiVersion: 1
datasources:
- name: Prometheus
uid: prometheus
type: prometheus
access: proxy
url: https://prometheus:9090
isDefault: true
editable: false
jsonData:
timeInterval: 15s
- name: Loki
uid: loki
type: loki
access: proxy
url: https://loki:3100
editable: false
jsonData:
derivedFields:
- datasourceUid: tempo
matcherRegex: '"trace_id":"([0-9a-f]+)"'
name: trace_id
url: "$${__value.raw}"
- name: Tempo
uid: tempo
type: tempo
access: proxy
url: https://tempo:3200
editable: false
jsonData:
tracesToLogsV2:
datasourceUid: loki
filterByTraceID: true
serviceMap:
datasourceUid: prometheus
nodeGraph:
enabled: true
@@ -0,0 +1,9 @@
# High API error rate
Signal: `messenger_http_requests_total`. Numerator is `status_class="5xx"`. Denominator is every instrumented business request. `/health/*`, `/docs` and `/openapi.json` are not in this ratio, so a bad password (401) is not an incident.
1. Open the Messenger dashboard and compare the 5xx ratio with p95 duration.
2. In Tempo, open a server span with `http.response.status_code >= 500`. The span attribute `http.route` is the template, not a user id.
3. In Loki, query `{service_name="messenger-api"}` and match `trace_id` from that span. The log line has `event`, `severity`, `trace_id` and `span_id`.
4. If the span stops inside the database client or the pool-used gauge is at `DB_POOL_MAX` with waiters, the cause is Postgres, not the HTTP handler itself.
5. After the dependency recovers, the 5m ratio falls and `HighApiErrorRate` leaves `firing`.
+8
View File
@@ -0,0 +1,8 @@
# Queue lag
Signal: `messenger_queue_oldest_age_seconds` is `now() - min(created_at)` for rows still `queued`. `messenger_queue_depth` counts `queued` and `processing`. Age is not the same number as worker duration.
1. If age grows and `messenger_worker_busy` is 0, the worker process is stopped or not consuming. Messages stay in RabbitMQ and in `attachment_jobs`.
2. If busy equals capacity and age still grows, the worker is saturated. Look at `messenger_job_duration_seconds` and the consumer span.
3. A consumer span's parent is the producer span, whose parent is the API server span that accepted the upload (`traceparent` stored on the job row).
4. Start the worker again. Depth and age return toward zero, then `QueueLagHigh` resolves. Do not delete the RabbitMQ volume.
+13
View File
@@ -0,0 +1,13 @@
# SLO burn
Two SLOs, each with a 1% error budget over 30 days.
- API availability: business requests that are not 5xx. Fast burn pages when both the 5 minute and 1 hour windows exceed 14.4% errors (14.4x budget). Slow burn warns when both 30 minutes and 6 hours exceed 6% (6x budget).
- Time to ready: jobs whose ready time is at most 30 seconds, read from the `le="30"` histogram bucket, not from an average. The same 14.4x and 6x windows apply.
A short spike can trip only the fast pair. A long degradation keeps the slow pair firing after the spike is gone. Both windows must agree, so one noisy minute does not page by itself.
1. Read which alert is firing and which SLO label it has.
2. For `api-availability`, follow `high-error-rate.md`. Separate 4xx from 5xx before calling it an incident.
3. For `time-to-ready`, follow `queue-lag.md`, then open the worker trace and see whether time is in `s3.get`, `image.render`, `s3.put` or `db.complete`.
4. Record the first firing timestamp and the first resolved timestamp. That pair is time-to-detect and time-to-recover for the experiment.
+25
View File
@@ -0,0 +1,25 @@
global
log stdout format raw local0 info
maxconn 200
defaults
log global
mode http
timeout connect 3s
timeout client 60s
timeout server 60s
frontend ft_otlp
bind *:4318 ssl crt /certs/otel.pem ca-file /certs/ca.crt verify required
acl api_id ssl_c_san -m sub spiffe://messenger/api
acl worker_id ssl_c_san -m sub spiffe://messenger/worker
acl api_leaf ssl_c_serial,hex,lower -f /certs/allowed-api.serial
acl worker_leaf ssl_c_serial,hex,lower -f /certs/allowed-worker.serial
http-request set-var(txn.leaf_ok) str(1) if api_id api_leaf
http-request set-var(txn.leaf_ok) str(1) if worker_id worker_leaf
acl leaf_ok var(txn.leaf_ok) -m str 1
http-request deny unless leaf_ok
default_backend be_local
backend be_local
server collector 127.0.0.1:14318
+27
View File
@@ -0,0 +1,27 @@
global
log stdout format raw local0 info
maxconn 200
defaults
log global
mode tcp
timeout connect 3s
timeout client 120s
timeout server 120s
frontend ft_amqp
bind *:5671 ssl crt /certs/rabbitmq.pem ca-file /certs/ca.crt verify required
tcp-request inspect-delay 5s
tcp-request content accept if { req_ssl_hello_type 1 }
acl api_id ssl_c_san -m sub spiffe://messenger/api
acl worker_id ssl_c_san -m sub spiffe://messenger/worker
acl api_leaf ssl_c_serial,hex,lower -f /certs/allowed-api.serial
acl worker_leaf ssl_c_serial,hex,lower -f /certs/allowed-worker.serial
tcp-request content set-var(txn.leaf_ok) str(1) if api_id api_leaf
tcp-request content set-var(txn.leaf_ok) str(1) if worker_id worker_leaf
acl leaf_ok var(txn.leaf_ok) -m str 1
tcp-request content reject unless leaf_ok
default_backend be_local
backend be_local
server rabbit 127.0.0.1:5672 check
+18
View File
@@ -0,0 +1,18 @@
global
log stdout format raw local0 info
maxconn 200
defaults
log global
mode http
timeout connect 3s
timeout client 120s
timeout server 120s
timeout http-request 30s
frontend ft_s3
bind *:9000 ssl crt /certs/s3.pem
default_backend be_local
backend be_local
server weed seaweed:9000 check
+38
View File
@@ -0,0 +1,38 @@
global
log stdout format raw local0 info
maxconn 200
defaults
log global
mode http
option httplog
timeout connect 2s
timeout client 120s
timeout server 120s
timeout http-request 15s
timeout check 2s
timeout queue 2s
retries 1
resolvers docker
nameserver dns 127.0.0.11:53
resolve_retries 3
timeout resolve 1s
timeout retry 1s
hold valid 1s
accepted_payload_size 8192
frontend fe_https
bind *:8443 ssl crt /certs/lb.pem
http-request set-header X-Real-IP %[src]
http-request del-header X-Forwarded-For
option forwardfor
default_backend be_api
backend be_api
balance roundrobin
option httpchk
http-check send meth GET uri /health/ready ver HTTP/1.1 hdr host api
http-check expect status 200
default-server inter 1s fall 2 rise 1 resolvers docker init-addr none resolve-prefer ipv4
server-template srv 8 api:8443 check ssl verify required ca-file /certs/ca.crt crt /certs/lb-client.pem
+33
View File
@@ -0,0 +1,33 @@
auth_enabled: false
server:
http_listen_port: 3100
grpc_listen_port: 9096
http_tls_config:
cert_file: /certs/loki.crt
key_file: /certs/loki.key
common:
instance_addr: 127.0.0.1
path_prefix: /loki
storage:
filesystem:
chunks_directory: /loki/chunks
rules_directory: /loki/rules
replication_factor: 1
ring:
kvstore:
store: inmemory
schema_config:
configs:
- from: 2024-01-01
store: tsdb
object_store: filesystem
schema: v13
index:
prefix: index_
period: 24h
limits_config:
allow_structured_metadata: true
+14
View File
@@ -0,0 +1,14 @@
ui = false
api_addr = "https://openbao:8200"
storage "file" {
path = "/openbao/file"
}
listener "tcp" {
address = "0.0.0.0:8200"
tls_cert_file = "/certs/openbao.crt"
tls_key_file = "/certs/openbao.key"
}
# Dev mode is not used. The process starts sealed; the operator unseals it.
+16
View File
@@ -0,0 +1,16 @@
# API may read only its own KV document and renew its own token.
path "secret/data/messenger/api" {
capabilities = ["read"]
}
path "secret/metadata/messenger/api" {
capabilities = ["read"]
}
path "auth/token/renew-self" {
capabilities = ["update"]
}
path "auth/token/lookup-self" {
capabilities = ["read"]
}
+15
View File
@@ -0,0 +1,15 @@
path "secret/data/messenger/migrate" {
capabilities = ["read"]
}
path "secret/metadata/messenger/migrate" {
capabilities = ["read"]
}
path "auth/token/renew-self" {
capabilities = ["update"]
}
path "auth/token/lookup-self" {
capabilities = ["read"]
}
+15
View File
@@ -0,0 +1,15 @@
path "secret/data/messenger/worker" {
capabilities = ["read"]
}
path "secret/metadata/messenger/worker" {
capabilities = ["read"]
}
path "auth/token/renew-self" {
capabilities = ["update"]
}
path "auth/token/lookup-self" {
capabilities = ["read"]
}
+90
View File
@@ -0,0 +1,90 @@
# Collector 0.128.0. It forwards signals and is not a database.
# memory_limiter refuses data before the process grows without bound.
# Exporter queues are capped; a dead backend drops telemetry after retry, the API keeps serving.
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: 5s
send_batch_size: 256
send_batch_max_size: 512
exporters:
otlphttp/tempo:
traces_endpoint: https://tempo:4318/v1/traces
tls:
insecure: false
ca_file: /certs/ca.crt
timeout: 5s
sending_queue:
enabled: true
num_consumers: 2
queue_size: 1000
retry_on_failure:
enabled: true
initial_interval: 1s
max_interval: 15s
max_elapsed_time: 30s
prometheusremotewrite:
endpoint: https://prometheus:9090/api/v1/write
tls:
insecure: false
ca_file: /certs/ca.crt
resource_to_telemetry_conversion:
enabled: true
remote_write_queue:
enabled: true
queue_size: 1000
num_consumers: 2
retry_on_failure:
enabled: true
initial_interval: 1s
max_interval: 15s
max_elapsed_time: 30s
otlphttp/loki:
logs_endpoint: https://loki:3100/otlp/v1/logs
tls:
insecure: false
ca_file: /certs/ca.crt
timeout: 5s
sending_queue:
enabled: true
num_consumers: 2
queue_size: 1000
retry_on_failure:
enabled: true
initial_interval: 1s
max_interval: 15s
max_elapsed_time: 30s
extensions:
health_check:
endpoint: 0.0.0.0:13133
service:
extensions: [health_check]
telemetry:
logs:
level: info
pipelines:
traces:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlphttp/tempo]
metrics:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [prometheusremotewrite]
logs:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlphttp/loki]
+14
View File
@@ -0,0 +1,14 @@
#!/bin/sh
set -eu
cp /certs/postgres.crt /var/lib/postgresql/server.crt
cp /certs/postgres.key /var/lib/postgresql/server.key
cp /certs/ca.crt /var/lib/postgresql/ca.crt
chown postgres:postgres /var/lib/postgresql/server.crt /var/lib/postgresql/server.key /var/lib/postgresql/ca.crt
chmod 644 /var/lib/postgresql/server.crt /var/lib/postgresql/ca.crt
chmod 600 /var/lib/postgresql/server.key
exec docker-entrypoint.sh postgres \
-c ssl=on \
-c ssl_cert_file=/var/lib/postgresql/server.crt \
-c ssl_key_file=/var/lib/postgresql/server.key \
-c ssl_ca_file=/var/lib/postgresql/ca.crt \
-c hba_file=/etc/postgres/pg_hba.conf
+34
View File
@@ -0,0 +1,34 @@
#!/bin/sh
# Create limited roles after migrations. Passwords come from mounted files, not from Git.
set -eu
api_pass=$(cat /run/secrets/db_api_password)
worker_pass=$(cat /run/secrets/db_worker_password)
psql -v ON_ERROR_STOP=1 --username messenger --dbname messenger <<SQL
DO \$\$
BEGIN
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'messenger_api') THEN
CREATE ROLE messenger_api LOGIN PASSWORD '${api_pass}';
END IF;
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'messenger_worker') THEN
CREATE ROLE messenger_worker LOGIN PASSWORD '${worker_pass}';
END IF;
END
\$\$;
ALTER ROLE messenger_api PASSWORD '${api_pass}';
ALTER ROLE messenger_worker PASSWORD '${worker_pass}';
GRANT CONNECT ON DATABASE messenger TO messenger_api, messenger_worker;
GRANT USAGE ON SCHEMA public TO messenger_api, messenger_worker;
GRANT SELECT, INSERT, UPDATE, DELETE ON
users, chats, chat_members, messages, idempotency_keys,
attachments, message_attachments, blob_writes, direct_uploads,
attachment_variants, attachment_jobs, attachment_job_events,
pipeline_faults, schema_migrations
TO messenger_api;
GRANT SELECT, INSERT, UPDATE, DELETE ON
attachments, message_attachments, blob_writes,
attachment_variants, attachment_jobs, attachment_job_events,
pipeline_faults
TO messenger_worker;
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO messenger_api, messenger_worker;
SQL
echo "database roles granted"
+5
View File
@@ -0,0 +1,5 @@
local all all trust
hostssl all all 0.0.0.0/0 scram-sha-256
hostssl all all ::/0 scram-sha-256
host all all 0.0.0.0/0 reject
host all all ::/0 reject
+112
View File
@@ -0,0 +1,112 @@
groups:
- name: messenger
rules:
- alert: HighApiErrorRate
expr: |
(
sum(rate(messenger_http_requests_total{status_class="5xx"}[5m]))
/
clamp_min(sum(rate(messenger_http_requests_total[5m])), 1e-9)
) > 0.05
for: 1m
labels:
severity: warning
slo: api-availability
annotations:
summary: API 5xx ratio is above 5% over 5 minutes
description: Numerator is status_class=5xx. Denominator is instrumented business requests. Health, docs and openapi are excluded.
runbook: infra/grafana/runbooks/high-error-rate.md
- alert: QueueLagHigh
expr: max(messenger_queue_oldest_age_seconds) > 30
for: 30s
labels:
severity: warning
slo: time-to-ready
annotations:
summary: Oldest queued job is older than 30 seconds
description: Age is now minus created_at of jobs still in status queued. Depth is a separate gauge.
runbook: infra/grafana/runbooks/queue-lag.md
- alert: ApiAvailabilityFastBurn
expr: |
(
sum(rate(messenger_http_requests_total{status_class="5xx"}[5m]))
/ clamp_min(sum(rate(messenger_http_requests_total[5m])), 1e-9)
) > 0.144
and
(
sum(rate(messenger_http_requests_total{status_class="5xx"}[1h]))
/ clamp_min(sum(rate(messenger_http_requests_total[1h])), 1e-9)
) > 0.144
for: 2m
labels:
severity: critical
slo: api-availability
window: fast
annotations:
summary: API error budget burn rate is above 14.4x on both 5m and 1h
runbook: infra/grafana/runbooks/slo-burn.md
- alert: ApiAvailabilitySlowBurn
expr: |
(
sum(rate(messenger_http_requests_total{status_class="5xx"}[30m]))
/ clamp_min(sum(rate(messenger_http_requests_total[30m])), 1e-9)
) > 0.06
and
(
sum(rate(messenger_http_requests_total{status_class="5xx"}[6h]))
/ clamp_min(sum(rate(messenger_http_requests_total[6h])), 1e-9)
) > 0.06
for: 15m
labels:
severity: warning
slo: api-availability
window: slow
annotations:
summary: API error budget burn rate is above 6x on both 30m and 6h
runbook: infra/grafana/runbooks/slo-burn.md
- alert: TimeToReadyFastBurn
expr: |
(
1 - (
sum(rate(messenger_time_to_ready_seconds_bucket{le=~"30|30\\.0"}[5m]))
/ clamp_min(sum(rate(messenger_time_to_ready_seconds_count[5m])), 1e-9)
)
) > 0.144
and
(
1 - (
sum(rate(messenger_time_to_ready_seconds_bucket{le=~"30|30\\.0"}[1h]))
/ clamp_min(sum(rate(messenger_time_to_ready_seconds_count[1h])), 1e-9)
)
) > 0.144
for: 2m
labels:
severity: critical
slo: time-to-ready
window: fast
annotations:
summary: Share of jobs slower than 30s is burning the ready-time budget (5m and 1h)
runbook: infra/grafana/runbooks/slo-burn.md
- alert: TimeToReadySlowBurn
expr: |
(
1 - (
sum(rate(messenger_time_to_ready_seconds_bucket{le=~"30|30\\.0"}[30m]))
/ clamp_min(sum(rate(messenger_time_to_ready_seconds_count[30m])), 1e-9)
)
) > 0.06
and
(
1 - (
sum(rate(messenger_time_to_ready_seconds_bucket{le=~"30|30\\.0"}[6h]))
/ clamp_min(sum(rate(messenger_time_to_ready_seconds_count[6h])), 1e-9)
)
) > 0.06
for: 15m
labels:
severity: warning
slo: time-to-ready
window: slow
annotations:
summary: Share of jobs slower than 30s is burning the ready-time budget (30m and 6h)
runbook: infra/grafana/runbooks/slo-burn.md
+6
View File
@@ -0,0 +1,6 @@
global:
scrape_interval: 15s
evaluation_interval: 15s
rule_files:
- /etc/prometheus/alerts.yml
+3
View File
@@ -0,0 +1,3 @@
tls_server_config:
cert_file: /certs/prometheus.crt
key_file: /certs/prometheus.key
+47
View File
@@ -0,0 +1,47 @@
#!/bin/sh
set -eu
mkdir -p /etc/rabbitmq/certs
cp /certs/rabbitmq.crt /etc/rabbitmq/certs/server.crt
cp /certs/rabbitmq.key /etc/rabbitmq/certs/server.key
cp /certs/ca.crt /etc/rabbitmq/certs/ca.crt
chown -R rabbitmq:rabbitmq /etc/rabbitmq/certs
chmod 600 /etc/rabbitmq/certs/server.key
api_pass=$(cat /run/secrets/rabbit_api_password)
worker_pass=$(cat /run/secrets/rabbit_worker_password)
cat > /etc/rabbitmq/definitions.json <<EOF
{
"vhosts": [{"name": "/"}],
"users": [
{"name": "messenger_api", "password": "${api_pass}", "tags": ""},
{"name": "messenger_worker", "password": "${worker_pass}", "tags": ""}
],
"permissions": [
{
"user": "messenger_api",
"vhost": "/",
"configure": ".*",
"write": ".*",
"read": ".*"
},
{
"user": "messenger_worker",
"vhost": "/",
"configure": "^(attachment\\\\.jobs.*)$",
"write": "^(attachment\\\\.jobs.*)$",
"read": "^(attachment\\\\.jobs.*)$"
}
]
}
EOF
chown rabbitmq:rabbitmq /etc/rabbitmq/definitions.json
chmod 640 /etc/rabbitmq/definitions.json
cat > /etc/rabbitmq/rabbitmq.conf <<EOF
listeners.tcp.1 = 127.0.0.1:5672
management.listener.ip = 127.0.0.1
management.listener.port = 15672
loopback_users.guest = true
default_user = messenger_api
default_pass = ${api_pass}
load_definitions = /etc/rabbitmq/definitions.json
EOF
exec docker-entrypoint.sh rabbitmq-server
+25
View File
@@ -0,0 +1,25 @@
#!/bin/sh
set -eu
cp /certs/redis.crt /tmp/redis.crt
cp /certs/redis.key /tmp/redis.key
cp /certs/ca.crt /tmp/ca.crt
chown redis:redis /tmp/redis.crt /tmp/redis.key /tmp/ca.crt
chmod 600 /tmp/redis.key
pass=$(cat /run/secrets/redis_password)
umask 077
cat > /tmp/users.acl <<EOF
user default off
user api on >${pass} ~* &* +@all
EOF
chown redis:redis /tmp/users.acl
exec docker-entrypoint.sh redis-server \
--port 0 \
--tls-port 6379 \
--tls-cert-file /tmp/redis.crt \
--tls-key-file /tmp/redis.key \
--tls-ca-cert-file /tmp/ca.crt \
--tls-auth-clients no \
--aclfile /tmp/users.acl \
--appendonly yes \
--appendfsync everysec \
--save 60 1
+62
View File
@@ -0,0 +1,62 @@
#!/bin/sh
# One SeaweedFS process bound to localhost. HAProxy in this network namespace
# is the TLS endpoint other containers use.
set -eu
: "${S3_BUCKET:?}"
admin_key=$(cat /run/secrets/s3_admin_access)
admin_secret=$(cat /run/secrets/s3_admin_secret)
api_key=$(cat /run/secrets/s3_api_access)
api_secret=$(cat /run/secrets/s3_api_secret)
worker_key=$(cat /run/secrets/s3_worker_access)
worker_secret=$(cat /run/secrets/s3_worker_secret)
cat > /tmp/s3.json <<EOF
{
"identities": [
{"name": "anonymous", "actions": []},
{
"name": "s3-admin",
"credentials": [{"accessKey": "${admin_key}", "secretKey": "${admin_secret}"}],
"actions": ["Admin:${S3_BUCKET}"]
},
{
"name": "messenger-api",
"credentials": [{"accessKey": "${api_key}", "secretKey": "${api_secret}"}],
"actions": [
"Read:${S3_BUCKET}",
"Read:${S3_BUCKET}/*",
"List:${S3_BUCKET}",
"Write:${S3_BUCKET}/staging/*",
"Write:${S3_BUCKET}/originals/*",
"Tagging:${S3_BUCKET}/*"
]
},
{
"name": "messenger-worker",
"credentials": [{"accessKey": "${worker_key}", "secretKey": "${worker_secret}"}],
"actions": [
"Read:${S3_BUCKET}/staging/*",
"Read:${S3_BUCKET}/originals/*",
"Read:${S3_BUCKET}/variants/*",
"List:${S3_BUCKET}",
"Write:${S3_BUCKET}/originals/*",
"Write:${S3_BUCKET}/variants/*",
"Write:${S3_BUCKET}/staging/*",
"Tagging:${S3_BUCKET}/*"
]
}
]
}
EOF
exec weed server \
-dir=/data \
-ip.bind=0.0.0.0 \
-master.port=9333 \
-volume.port=8080 \
-filer \
-filer.port=8888 \
-filer.exposeDirectoryData=false \
-s3 \
-s3.port=9000 \
-s3.config=/tmp/s3.json
+12
View File
@@ -0,0 +1,12 @@
# SLI и SLO
Окно цели: 30 суток. Бюджет ошибок: 1% у каждого SLO. Пороги burn rate — 14.4x (быстрое выгорание, окна 5 минут и 1 час) и 6x (медленное, окна 30 минут и 6 часов). Оба окна пары должны выполниться одновременно.
| SLI | Хорошее событие | SLO | Единица |
| --- | --- | --- | --- |
| Доступность API | бизнес-запрос со `status_class` не `5xx` | 99% | доля запросов |
| Время до ready | job, у которой `messenger_time_to_ready_seconds` попала в bucket `le=30` | 99% готовы не дольше 30 секунд | секунды от durable acceptance до `ready` |
Health, `/docs` и `/openapi.json` в SLI API не входят. 401 и 404 остаются в знаменателе, но не в числителе ошибок: это не отказ сервиса. Процентили дашборда считаются `histogram_quantile` по bucket, не средним значений и не средним p99 реплик.
Правила лежат в `infra/prometheus/alerts.yml`. Runbook: `infra/grafana/runbooks/`.
+34
View File
@@ -0,0 +1,34 @@
stream_over_http_enabled: true
server:
http_listen_port: 3200
http_tls_config:
cert_file: /certs/tempo.crt
key_file: /certs/tempo.key
distributor:
receivers:
otlp:
protocols:
http:
endpoint: 0.0.0.0:4318
tls:
cert_file: /certs/tempo.crt
key_file: /certs/tempo.key
grpc:
endpoint: 127.0.0.1:4317
ingester:
max_block_duration: 5m
compactor:
compaction:
block_retention: 168h
storage:
trace:
backend: local
wal:
path: /var/tempo/wal
local:
path: /var/tempo/blocks
+49
View File
@@ -0,0 +1,49 @@
-- Lab2 schema (written before application queries).
-- Source of truth: PostgreSQL for users, chats, membership, messages.
-- Transaction boundary: INSERT chat + INSERT members in one transaction (rollback together).
-- Sessions are stored in Redis with AOF, not in this database.
CREATE TABLE IF NOT EXISTS schema_migrations (
filename TEXT PRIMARY KEY,
applied_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE users (
id UUID PRIMARY KEY,
username TEXT NOT NULL,
display_name TEXT NOT NULL,
password_hash TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9_]{3,32}$'),
CONSTRAINT users_display_name_len CHECK (char_length(display_name) BETWEEN 1 AND 100)
);
CREATE UNIQUE INDEX users_username_key ON users (username);
CREATE TABLE chats (
id UUID PRIMARY KEY,
title TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
CONSTRAINT chats_title_len CHECK (char_length(title) BETWEEN 1 AND 100)
);
CREATE TABLE chat_members (
chat_id UUID NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
user_id UUID NOT NULL REFERENCES users (id),
PRIMARY KEY (chat_id, user_id)
);
CREATE INDEX chat_members_user_id_idx ON chat_members (user_id);
CREATE INDEX chats_created_at_id_idx ON chats (created_at, 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),
text TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
CONSTRAINT messages_text_len CHECK (char_length(text) BETWEEN 1 AND 4000)
);
-- Keyset history: WHERE chat_id = $1 AND (created_at, id) > ($2, $3) ORDER BY created_at, id LIMIT n
CREATE INDEX messages_chat_created_id_idx ON messages (chat_id, created_at, id);
+14
View File
@@ -0,0 +1,14 @@
-- Shared idempotency for POST /messages. Scope: user + method + path + key.
-- The message row and this result are committed in one transaction.
-- A rolled-back request leaves no row, so a later retry with the same key can insert.
CREATE TABLE IF NOT EXISTS idempotency_keys (
user_id UUID NOT NULL REFERENCES users (id),
http_method TEXT NOT NULL,
path TEXT NOT NULL,
idem_key TEXT NOT NULL,
request_hash TEXT NOT NULL,
response_json TEXT NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (user_id, http_method, path, idem_key)
);
+50
View File
@@ -0,0 +1,50 @@
-- Attachment metadata stays in Postgres. Bytes stay in the private bucket.
-- A blob_writes row is inserted before the S3 PUT and marked committed in the
-- same transaction as the attachment row. If that transaction rolls back, the
-- API deletes the object. Rows still uncommitted after ORPHAN_GRACE_SECONDS
-- are removed by the sweeper, so a crash between PUT and COMMIT cannot leave
-- a permanent untracked object. Fresh in-flight uploads are inside the grace
-- window and are not deleted.
ALTER TABLE messages DROP CONSTRAINT messages_text_len;
ALTER TABLE messages
ADD CONSTRAINT messages_text_len CHECK (char_length(text) BETWEEN 0 AND 4000);
CREATE TABLE attachments (
id UUID PRIMARY KEY,
chat_id UUID NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
owner_id UUID NOT NULL REFERENCES users (id),
filename TEXT NOT NULL,
content_type TEXT NOT NULL,
size_bytes INTEGER NOT NULL,
sha256 TEXT NOT NULL,
object_key TEXT NOT NULL UNIQUE,
status TEXT NOT NULL,
error_code TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
CONSTRAINT attachments_filename_len CHECK (char_length(filename) BETWEEN 1 AND 255),
CONSTRAINT attachments_size CHECK (size_bytes BETWEEN 1 AND 10485760),
CONSTRAINT attachments_sha CHECK (sha256 ~ '^[a-f0-9]{64}$'),
CONSTRAINT attachments_type CHECK (content_type IN ('image/png', 'image/jpeg')),
CONSTRAINT attachments_status CHECK (status = 'ready'),
CONSTRAINT attachments_ready_error CHECK (status <> 'ready' OR error_code IS NULL)
);
CREATE INDEX attachments_chat_idx ON attachments (chat_id);
CREATE TABLE message_attachments (
message_id UUID NOT NULL REFERENCES messages (id) ON DELETE CASCADE,
attachment_id UUID NOT NULL REFERENCES attachments (id),
position INTEGER NOT NULL CHECK (position >= 0 AND position < 10),
PRIMARY KEY (message_id, attachment_id),
UNIQUE (message_id, position)
);
CREATE TABLE blob_writes (
object_key TEXT PRIMARY KEY,
committed BOOLEAN NOT NULL DEFAULT FALSE,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX blob_writes_pending_idx ON blob_writes (created_at) WHERE NOT committed;
+22
View File
@@ -0,0 +1,22 @@
-- Optional presigned upload. The signed URL dies quickly. The row stays pending
-- until complete checks the object that actually landed in the bucket.
-- Incomplete rows are aborted by the same grace sweeper as other uncommitted keys.
CREATE TABLE direct_uploads (
id UUID PRIMARY KEY,
chat_id UUID NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
owner_id UUID NOT NULL REFERENCES users (id),
filename TEXT NOT NULL,
content_type TEXT NOT NULL,
size_bytes INTEGER NOT NULL,
object_key TEXT NOT NULL UNIQUE,
status TEXT NOT NULL,
expires_at TIMESTAMPTZ NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
CONSTRAINT direct_uploads_filename_len CHECK (char_length(filename) BETWEEN 1 AND 255),
CONSTRAINT direct_uploads_size CHECK (size_bytes BETWEEN 1 AND 10485760),
CONSTRAINT direct_uploads_type CHECK (content_type IN ('image/png', 'image/jpeg')),
CONSTRAINT direct_uploads_status CHECK (status IN ('pending', 'completed', 'aborted'))
);
CREATE INDEX direct_uploads_pending_idx ON direct_uploads (expires_at) WHERE status = 'pending';
+67
View File
@@ -0,0 +1,67 @@
-- Async attachment processing. Bytes stay in S3. The broker message carries only ids.
-- 202 is returned after the staging object and this job row commit. Publish is a
-- later step: published_at stays null until the broker confirms, so a crash
-- between COMMIT and publish is recovered by the outbox loop.
ALTER TABLE attachments DROP CONSTRAINT attachments_status;
ALTER TABLE attachments
ADD CONSTRAINT attachments_status CHECK (status IN ('queued', 'processing', 'ready', 'failed'));
ALTER TABLE attachments DROP CONSTRAINT attachments_ready_error;
ALTER TABLE attachments
ADD CONSTRAINT attachments_error CHECK (
(status = 'failed' AND error_code IS NOT NULL AND error_code ~ '^[a-z0-9_]{1,64}$')
OR (status <> 'failed' AND error_code IS NULL)
);
CREATE TABLE attachment_variants (
attachment_id UUID NOT NULL REFERENCES attachments (id) ON DELETE CASCADE,
pipeline_version INTEGER NOT NULL CHECK (pipeline_version >= 1),
name TEXT NOT NULL,
content_type TEXT NOT NULL,
size_bytes INTEGER NOT NULL CHECK (size_bytes >= 1),
width INTEGER NOT NULL CHECK (width >= 1),
height INTEGER NOT NULL CHECK (height >= 1),
sha256 TEXT NOT NULL CHECK (sha256 ~ '^[a-f0-9]{64}$'),
object_key TEXT NOT NULL UNIQUE,
PRIMARY KEY (attachment_id, pipeline_version, name),
CONSTRAINT attachment_variants_name CHECK (name IN ('thumbnail', 'crop', 'optimized'))
);
CREATE TABLE attachment_jobs (
job_id UUID PRIMARY KEY,
attachment_id UUID NOT NULL REFERENCES attachments (id) ON DELETE CASCADE,
pipeline_version INTEGER NOT NULL CHECK (pipeline_version >= 1),
attempt INTEGER NOT NULL CHECK (attempt >= 1),
status TEXT NOT NULL,
error_code TEXT,
lease_until TIMESTAMPTZ,
lease_token UUID,
next_attempt_at TIMESTAMPTZ,
published_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
UNIQUE (attachment_id, pipeline_version),
CONSTRAINT attachment_jobs_status CHECK (status IN ('queued', 'processing', 'ready', 'failed')),
CONSTRAINT attachment_jobs_error CHECK (
error_code IS NULL OR error_code ~ '^[a-z0-9_]{1,64}$'
),
CONSTRAINT attachment_jobs_failed_error CHECK (status <> 'failed' OR error_code IS NOT NULL)
);
CREATE INDEX attachment_jobs_outbox_idx
ON attachment_jobs (created_at)
WHERE published_at IS NULL AND status = 'queued';
CREATE INDEX attachment_jobs_lease_idx
ON attachment_jobs (lease_until)
WHERE status = 'processing';
CREATE TABLE attachment_job_events (
id BIGSERIAL PRIMARY KEY,
job_id UUID NOT NULL,
attachment_id UUID NOT NULL,
kind TEXT NOT NULL,
detail TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
+14
View File
@@ -0,0 +1,14 @@
-- The served result is one pipeline version. An older job must not replace it.
-- Variant rows stay addressable per version; the attachment points at the winner.
ALTER TABLE attachments
ADD COLUMN applied_pipeline_version INTEGER NOT NULL DEFAULT 1
CHECK (applied_pipeline_version >= 1);
CREATE TABLE pipeline_faults (
id INTEGER PRIMARY KEY,
mode TEXT NOT NULL DEFAULT '',
remaining INTEGER NOT NULL DEFAULT 0 CHECK (remaining >= 0)
);
INSERT INTO pipeline_faults (id, mode, remaining) VALUES (1, '', 0);
+3
View File
@@ -0,0 +1,3 @@
ALTER TABLE attachment_jobs
ADD COLUMN traceparent TEXT,
ADD COLUMN tracestate TEXT;
+12
View File
@@ -0,0 +1,12 @@
starlette==0.41.3
uvicorn[standard]==0.32.1
asyncpg==0.30.0
redis==5.2.1
argon2-cffi==23.1.0
boto3==1.35.99
pillow==11.1.0
aio-pika==9.5.5
opentelemetry-api==1.29.0
opentelemetry-sdk==1.29.0
opentelemetry-exporter-otlp-proto-http==1.29.0
psutil==6.1.1
+12
View File
@@ -0,0 +1,12 @@
#!/bin/sh
set -eu
python -m app.main &
app_pid=$!
python -m app.tls_proxy &
proxy_pid=$!
while kill -0 "$app_pid" 2>/dev/null && kill -0 "$proxy_pid" 2>/dev/null; do
sleep 1
done
kill "$app_pid" "$proxy_pid" 2>/dev/null || true
wait || true
exit 1
+100
View File
@@ -0,0 +1,100 @@
$ErrorActionPreference = "Stop"
$Root = Split-Path -Parent $PSScriptRoot
Set-Location $Root
function New-Secret([string]$Name) {
$path = Join-Path $Root "secrets\$Name"
if (-not (Test-Path $path)) {
$bytes = New-Object byte[] 24
$rng = [System.Security.Cryptography.RandomNumberGenerator]::Create()
$rng.GetBytes($bytes)
$text = -join ($bytes | ForEach-Object { $_.ToString("x2") })
[System.IO.File]::WriteAllText($path, $text)
}
}
New-Item -ItemType Directory -Force -Path (Join-Path $Root "secrets") | Out-Null
New-Item -ItemType Directory -Force -Path (Join-Path $Root "certs") | Out-Null
New-Item -ItemType Directory -Force -Path (Join-Path $Root "evidence") | Out-Null
@(
"db_super_password", "db_api_password", "db_worker_password", "redis_password",
"rabbit_api_password", "rabbit_worker_password", "grafana_password",
"s3_admin_secret", "s3_api_secret", "s3_worker_secret"
) | ForEach-Object { New-Secret $_ }
foreach ($pair in @(
@("s3_admin_access", "s3admin"),
@("s3_api_access", "s3api"),
@("s3_worker_access", "s3worker")
)) {
$path = Join-Path $Root ("secrets\" + $pair[0])
if (-not (Test-Path $path)) {
$suffix = ([guid]::NewGuid().ToString("N")).Substring(0, 12)
[System.IO.File]::WriteAllText($path, $pair[1] + $suffix)
}
}
foreach ($name in @("api", "worker", "migrate")) {
foreach ($suffix in @("role_id", "secret_id")) {
$path = Join-Path $Root "secrets\$name.$suffix"
if (-not (Test-Path $path)) {
[System.IO.File]::WriteAllText($path, "pending")
}
}
}
if (-not (Test-Path (Join-Path $Root ".env"))) {
Copy-Item (Join-Path $Root ".env.example") (Join-Path $Root ".env")
}
Get-ChildItem -Path (Join-Path $Root "scripts"), (Join-Path $Root "infra") -Recurse -Include *.sh,*.cfg,*.hcl |
ForEach-Object {
$text = [System.IO.File]::ReadAllText($_.FullName) -replace "`r`n", "`n" -replace "`r", "`n"
$utf8 = New-Object System.Text.UTF8Encoding $false
[System.IO.File]::WriteAllText($_.FullName, $text, $utf8)
}
Write-Host "creating certificates"
docker run --rm -v "${Root}\certs:/work" -v "${Root}\scripts\gen-certs.sh:/gen-certs.sh:ro" alpine:3.21.3 sh /gen-certs.sh
if ($LASTEXITCODE -ne 0) { throw "certificate generation failed" }
Write-Host "building application image"
docker compose --env-file .env build
if ($LASTEXITCODE -ne 0) { throw "image build failed" }
Write-Host "starting data services"
docker compose --env-file .env up -d postgres redis rabbitmq rabbit-mtls seaweed s3 openbao otel-collector otel-mtls prometheus loki tempo grafana
if ($LASTEXITCODE -ne 0) { throw "data services failed to start" }
Write-Host "bootstrapping OpenBao"
docker compose --env-file .env --profile bootstrap run --rm openbao-bootstrap
if ($LASTEXITCODE -ne 0) { throw "OpenBao bootstrap failed" }
Write-Host "applying schema"
docker compose --env-file .env up -d migrate
if ($LASTEXITCODE -ne 0) { throw "migrate failed to start" }
$deadline = (Get-Date).AddMinutes(3)
do {
Start-Sleep -Seconds 2
$state = docker compose --env-file .env ps --format json migrate
if ($state -match '"ExitCode":0' -or $state -match '"ExitCode": 0') { break }
if ($state -match '"ExitCode":' -and $state -notmatch '"ExitCode":0' -and $state -notmatch '"State":"running"' -and $state -match '"ExitCode":[1-9]') {
throw "migrate failed"
}
} while ((Get-Date) -lt $deadline)
Write-Host "granting database roles"
docker compose --env-file .env exec -T postgres sh /etc/postgres/grant.sh
if ($LASTEXITCODE -ne 0) { throw "database grants failed" }
Write-Host "creating bucket"
docker compose --env-file .env up -d s3-init
if ($LASTEXITCODE -ne 0) { throw "s3-init failed to start" }
Write-Host "starting API and worker"
docker compose --env-file .env up -d --scale api=2 --no-recreate api worker lb
if ($LASTEXITCODE -ne 0) { throw "application services failed to start" }
Write-Host "stand is starting. Public URL: https://127.0.0.1:8443 CA: certs\ca.crt"
Write-Host "OpenBao stays sealed across its own restart. Unseal with: docker compose --env-file .env --profile bootstrap run --rm openbao-bootstrap"
+88
View File
@@ -0,0 +1,88 @@
#!/bin/sh
set -eu
apk add --no-cache openssl >/dev/null
cd /work
serial_of() {
openssl x509 -in "$1" -noout -serial | awk -F= '{print tolower($2)}'
}
write_allows() {
openssl x509 -in lb-client.crt -outform DER | openssl dgst -sha256 -r | awk '{print $1}' > allowed-lb.sha256
serial_of api-client.crt > allowed-api.serial
serial_of worker-client.crt > allowed-worker.serial
}
if [ -f ca.crt ] && [ -f allowed-lb.sha256 ] && [ -f lb.pem ]; then
write_allows
echo "certificates already present"
exit 0
fi
openssl req -x509 -newkey rsa:3072 -days 30 -nodes \
-keyout ca.key -out ca.crt \
-subj "/CN=messenger-lab-ca" \
-addext basicConstraints=critical,CA:TRUE \
-addext keyUsage=critical,keyCertSign,cRLSign >/dev/null 2>&1
issue() {
name="$1"
cn="$2"
eku="$3"
san="$4"
cat > "/tmp/${name}.cnf" <<EOF
[req]
distinguished_name=dn
prompt=no
[dn]
CN=${cn}
[ext]
subjectAltName=${san}
keyUsage=digitalSignature,keyEncipherment
extendedKeyUsage=${eku}
basicConstraints=CA:FALSE
EOF
openssl req -newkey rsa:2048 -nodes -keyout "${name}.key" -out "/tmp/${name}.csr" -subj "/CN=${cn}" >/dev/null 2>&1
openssl x509 -req -in "/tmp/${name}.csr" -CA ca.crt -CAkey ca.key -CAcreateserial \
-out "${name}.crt" -days 7 -extfile "/tmp/${name}.cnf" -extensions ext >/dev/null 2>&1
cat "${name}.crt" "${name}.key" > "${name}.pem"
}
issue lb localhost serverAuth "DNS:localhost,IP:127.0.0.1"
issue api api serverAuth "DNS:api,DNS:localhost,IP:127.0.0.1"
issue lb-client lb clientAuth "DNS:lb,URI:spiffe://messenger/lb"
issue lb-revoked lb clientAuth "DNS:lb,URI:spiffe://messenger/lb"
issue stranger stranger clientAuth "URI:spiffe://messenger/stranger"
issue api-client api clientAuth "DNS:api-client,URI:spiffe://messenger/api"
issue worker-client worker clientAuth "DNS:worker-client,URI:spiffe://messenger/worker"
issue postgres postgres serverAuth "DNS:postgres"
issue redis redis serverAuth "DNS:redis,IP:127.0.0.1"
issue rabbitmq rabbitmq serverAuth "DNS:rabbitmq"
issue s3 s3 serverAuth "DNS:s3,DNS:localhost,IP:127.0.0.1"
issue otel otel-collector serverAuth "DNS:otel-collector"
issue prometheus prometheus serverAuth "DNS:prometheus"
issue loki loki serverAuth "DNS:loki"
issue tempo tempo serverAuth "DNS:tempo"
issue grafana localhost serverAuth "DNS:localhost,IP:127.0.0.1"
issue openbao openbao serverAuth "DNS:openbao,IP:127.0.0.1"
openssl req -x509 -newkey rsa:2048 -days 7 -nodes \
-keyout other-ca.key -out other-ca.crt \
-subj "/CN=other-ca" \
-addext basicConstraints=critical,CA:TRUE \
-addext keyUsage=critical,keyCertSign,cRLSign >/dev/null 2>&1
openssl req -newkey rsa:2048 -nodes -keyout other-client.key -out /tmp/other-client.csr -subj "/CN=lb" >/dev/null 2>&1
cat > /tmp/other-client.cnf <<EOF
subjectAltName=URI:spiffe://messenger/lb
keyUsage=digitalSignature,keyEncipherment
extendedKeyUsage=clientAuth
basicConstraints=CA:FALSE
EOF
openssl x509 -req -in /tmp/other-client.csr -CA other-ca.crt -CAkey other-ca.key -CAcreateserial \
-out other-client.crt -days 7 -extfile /tmp/other-client.cnf >/dev/null 2>&1
cat other-client.crt other-client.key > other-client.pem
write_allows
find . -name '*.key' -exec chmod 644 {} \;
find . -name '*.pem' -exec chmod 644 {} \;
echo "certificates created"
+16
View File
@@ -0,0 +1,16 @@
#!/usr/bin/env python3
"""Time one Argon2id hash with the stand parameters. Prints milliseconds only."""
import os
import time
from app.passwords import ITERATIONS, MEMORY_KIB, PARALLELISM, hash_password
password = os.environ.get("ARGON2_SAMPLE_PASSWORD", "synthetic-measurement-password")
started = time.perf_counter()
hash_password(password)
elapsed_ms = (time.perf_counter() - started) * 1000
print(
"argon2id memory_kib=%s iterations=%s parallelism=%s elapsed_ms=%.1f"
% (MEMORY_KIB, ITERATIONS, PARALLELISM, elapsed_ms)
)
+66
View File
@@ -0,0 +1,66 @@
#!/bin/sh
# Reissue one leaf from the existing lab CA. Does not print the key.
# Args: name cn eku san
# Optional env: NOT_BEFORE, NOT_AFTER as YYYYMMDDHHMMSSZ
set -eu
apk add --no-cache openssl >/dev/null
cd /work
name="$1"
cn="$2"
eku="$3"
san="$4"
test -f ca.key
test -f ca.crt
cat > "/tmp/${name}.cnf" <<EOF
[req]
distinguished_name=dn
prompt=no
[dn]
CN=${cn}
[ext]
subjectAltName=${san}
keyUsage=digitalSignature,keyEncipherment
extendedKeyUsage=${eku}
basicConstraints=CA:FALSE
EOF
openssl req -newkey rsa:2048 -nodes -keyout "${name}.key" -out "/tmp/${name}.csr" -subj "/CN=${cn}" >/dev/null 2>&1
if [ -n "${NOT_BEFORE:-}" ] || [ -n "${NOT_AFTER:-}" ]; then
mkdir -p /tmp/newcerts
: > /tmp/index.txt
echo 1000 > /tmp/serial
cat > /tmp/ca.cnf <<EOF
[ca]
default_ca=CA_default
[CA_default]
database=/tmp/index.txt
serial=/tmp/serial
new_certs_dir=/tmp/newcerts
certificate=/work/ca.crt
private_key=/work/ca.key
default_md=sha256
policy=policy_any
copy_extensions=none
unique_subject=no
[policy_any]
commonName=supplied
EOF
openssl ca -batch -notext -config /tmp/ca.cnf \
-in "/tmp/${name}.csr" -out "${name}.crt" \
-startdate "${NOT_BEFORE:-20200101000000Z}" -enddate "${NOT_AFTER:-20200102000000Z}" \
-extfile "/tmp/${name}.cnf" -extensions ext >/dev/null 2>&1
else
openssl x509 -req -in "/tmp/${name}.csr" -CA ca.crt -CAkey ca.key -CAcreateserial \
-out "${name}.crt" -days 7 -extfile "/tmp/${name}.cnf" -extensions ext >/dev/null 2>&1
fi
cat "${name}.crt" "${name}.key" > "${name}.pem"
chmod 644 "${name}.key" "${name}.pem"
if [ "$name" = "lb-client" ]; then
openssl x509 -in lb-client.crt -outform DER | openssl dgst -sha256 -r | awk '{print $1}' > allowed-lb.sha256
fi
if [ "$name" = "api-client" ]; then
openssl x509 -in api-client.crt -noout -serial | awk -F= '{print tolower($2)}' > allowed-api.serial
fi
if [ "$name" = "worker-client" ]; then
openssl x509 -in worker-client.crt -noout -serial | awk -F= '{print tolower($2)}' > allowed-worker.serial
fi
echo "reissued $name"
+5
View File
@@ -0,0 +1,5 @@
@echo off
cd /d "%~dp0\.."
docker compose --env-file .env restart postgres redis seaweed s3 rabbitmq api worker
docker compose --env-file .env restart rabbit-mtls
exit /b %ERRORLEVEL%
+14
View File
@@ -0,0 +1,14 @@
#!/bin/sh
# Restart API replicas and the stores they use. Volumes stay. OpenBao is left running
# so it does not need another unseal; API logs in again with the AppRole files.
set -eu
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
cd "$ROOT"
if [ -f .env ]; then
docker compose --env-file .env restart postgres redis seaweed s3 rabbitmq api worker
# The mTLS sidecar shares rabbitmq's network namespace and must rejoin after it restarts.
docker compose --env-file .env restart rabbit-mtls
else
docker compose restart postgres redis seaweed s3 rabbitmq api worker
docker compose restart rabbit-mtls
fi
+55
View File
@@ -0,0 +1,55 @@
#!/bin/sh
# Replace API replicas one at a time. The other replica keeps serving.
set -eu
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
cd "$ROOT"
compose() {
if [ -f .env ]; then
docker compose --env-file .env "$@"
else
docker compose "$@"
fi
}
if command -v python3 >/dev/null 2>&1; then
PY=python3
else
PY=python
fi
ids=$(compose ps -q api)
count=0
for id in $ids; do
count=$((count + 1))
done
if [ "$count" -lt 2 ]; then
echo "rolling update needs at least 2 running API replicas" >&2
exit 1
fi
for id in $ids; do
echo "replacing $(docker inspect -f '{{.Config.Hostname}}' "$id")"
docker stop -t 8 "$id" >/dev/null
docker rm "$id" >/dev/null
compose up -d --scale "api=$count" --no-deps --no-recreate api >/dev/null
ready=0
i=0
while [ "$i" -lt 40 ]; do
running=0
for cid in $(compose ps -q api); do
running=$((running + 1))
done
if [ "$running" -ge "$count" ] && "$PY" -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health/ready', timeout=2)" >/dev/null 2>&1; then
ready=1
break
fi
i=$((i + 1))
sleep 1
done
if [ "$ready" -ne 1 ]; then
echo "replacement did not become ready" >&2
exit 1
fi
done
echo "rolling update finished; replicas=$count"
+3
View File
@@ -0,0 +1,3 @@
@echo off
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0stop-one.ps1"
exit /b %ERRORLEVEL%
+23
View File
@@ -0,0 +1,23 @@
$ErrorActionPreference = "Stop"
if (-not $env:TARGET_INSTANCE_ID) {
Write-Error "TARGET_INSTANCE_ID is required"
exit 1
}
Set-Location (Join-Path $PSScriptRoot "..")
$ids = docker compose --env-file .env ps -q api
$found = $false
foreach ($id in $ids) {
if (-not $id) { continue }
$iid = ""
try { $iid = (docker exec $id cat /tmp/instance-id).Trim() } catch { $iid = "" }
$hostName = (docker inspect -f "{{.Config.Hostname}}" $id).Trim()
if ($iid -eq $env:TARGET_INSTANCE_ID -or $hostName -eq $env:TARGET_INSTANCE_ID) {
docker stop -t 5 $id | Out-Null
$found = $true
break
}
}
if (-not $found) {
Write-Error "no running API replica matched TARGET_INSTANCE_ID"
exit 1
}
+32
View File
@@ -0,0 +1,32 @@
#!/bin/sh
# Stop the single API replica whose X-Instance-Id is TARGET_INSTANCE_ID.
# Leaves it stopped. Does not touch the database, Redis, the load balancer, or volumes.
set -eu
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
cd "$ROOT"
compose() {
if [ -f .env ]; then
docker compose --env-file .env "$@"
else
docker compose "$@"
fi
}
found=0
for id in $(compose ps -q api); do
iid=$(docker exec "$id" cat /tmp/instance-id 2>/dev/null | tr -d '\r\n' || true)
host=$(docker inspect -f '{{.Config.Hostname}}' "$id")
if [ "$iid" = "$TARGET_INSTANCE_ID" ] || [ "$host" = "$TARGET_INSTANCE_ID" ]; then
docker stop -t 5 "$id" >/dev/null
found=1
break
fi
done
if [ "$found" -ne 1 ]; then
echo "no running API replica matched TARGET_INSTANCE_ID" >&2
exit 1
fi
+10
View File
@@ -0,0 +1,10 @@
#!/bin/sh
# Stop the worker and leave it stopped. The broker, API and volumes keep running.
set -eu
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
cd "$ROOT"
if [ -f .env ]; then
docker compose --env-file .env stop worker
else
docker compose stop worker
fi
+21
View File
@@ -0,0 +1,21 @@
# Разбор скана образа `mtusi-messenger:lab7`
Команда, 26 ноября 2026:
```
docker run --rm -v /var/run/docker.sock:/var/run/docker.sock aquasec/trivy:0.58.1 image --severity HIGH,CRITICAL --ignore-unfixed --pkg-types os,library mtusi-messenger:lab7
```
`docker scout` на этой машине требует Docker Hub login и отчёт не заменяет. Trivy: Debian 12.9 — 52 (45 HIGH, 7 CRITICAL), Python-пакеты — 44 (39 HIGH, 5 CRITICAL). Ниже не список CVE, а то, доходит ли находка до нашего кода.
## Доходит до стенда
Pillow 11.1.0. Worker открывает загруженный PNG/JPEG и пишет thumbnail. Критические записи Trivy (heap overflow в TIFF/JPEG/FPX и argument injection в Ghostscript) имеют исправление только в Pillow 13.0.0. На стенде это ограничено так: загрузка только от участника чата, размер `MAX_UPLOAD_BYTES`, пиксели `MAX_IMAGE_PIXELS`, worker с лимитом CPU 1, RAM 768 МиБ и `JOB_TIMEOUT_SECONDS=60`. Прыжок 11 → 13 не делался в этом коммите: это смена поведения декодера, а не точечный патч. Остаточный риск честный: злонамеренный файл участника чата может уронить worker, но не читает `users` и не получает admin S3.
## Не на нашем пути
- GnuTLS в базовом Debian (SAN/DTLS). Проверки mTLS идут через OpenSSL: Python `ssl` и HAProxy. `curl` в образ поставлен, healthcheck его не вызывает.
- apt/gpgv/krb5. Контейнер не ставит пакеты в рантайме и не ходит в Kerberos. `cap_drop: ALL` и non-root режут то, что иначе дал бы локальный баг libcap.
- Starlette 0.41.3, CVE про склейку `Range` и `request.form()`. Своих `FileResponse` нет, тело запроса режется middleware до приложения. Загрузка — сырой body, не `application/x-www-form-urlencoded`.
Обновление базового `python:3.12.8-slim-bookworm` снимет Debian-находки целиком. Пока образ закреплён, число CVE само по себе не считается закрытием.
+27 -8
View File
@@ -1,19 +1,38 @@
# Модель угроз — заполнить # Модель угроз
Стенд — один Docker-хост с учебным мессенджером. Атакующий снаружи видит только `127.0.0.1:8443` (HTTPS) и, для presigned-загрузки, `127.0.0.1:9007` (HTTPS). Grafana слушает `127.0.0.1:3007`. Порты API, Postgres, Redis, RabbitMQ, Collector и OpenBao на хост не публикуются.
## Активы и акторы ## Активы и акторы
TODO: пользовательские credentials/сессии, сообщения/вложения, service identities, CA/secrets, telemetry. Акторы: участник чата, посторонний пользователь, внешний клиент, скомпрометированный сервис, оператор. Опишите доступ атакующего и границы учебного стенда. Активы: пароли (Argon2id PHC со salt и параметрами), хэши сессионных токенов в Redis, сообщения и вложения, ключи CA и leaf, AppRole SecretID, учётные данные БД/S3/брокера, телеметрия без тел сообщений и токенов.
## Границы доверия Акторы: участник чата, посторонний зарегистрированный пользователь, внешний клиент без доверия к CA, скомпрометированный worker, оператор с unseal key и root token на своей машине (каталог `secrets/`, не в Git и не в образе).
TODO: схема и ссылка на заполненную contracts/trust-matrix.md; публичные/внутренние интерфейсы, процессы, секреты и их выдача. Граница стенда: сеть `app` видит только LB и API, `data` — хранилища и OpenBao, `signals` — API/worker и вход коллектора, `telemetry` — коллектор и его backend-ы. CA private key в контейнеры приложений не монтируется.
Схема связей и проверки — [contracts/trust-matrix.md](../contracts/trust-matrix.md).
| Угроза и конкретный путь | Нарушаемый инвариант | Контроль | Отрицательный тест | Остаточное ограничение | | Угроза и конкретный путь | Нарушаемый инвариант | Контроль | Отрицательный тест | Остаточное ограничение |
| --- | --- | --- | --- | --- | | --- | --- | --- | --- | --- |
| TODO | TODO | TODO | TODO | TODO | | Клиент подставляет свой trust store или чужой CA и вызывает `GET /health/ready` | Внешний трафик читаем и неотличим от стенда | TLS на LB, SAN `localhost`/`127.0.0.1`, проверка CA | `make test-security` и `student-tests/mtls_probe.py` | Учебный CA живёт 30 дней на диске оператора |
| Контейнер в сети `app` открывает `api:8443` без сертификата, с `other-ca` или с `stranger`/`lb-revoked` | Любой клиент нашего CA считается балансировщиком | mTLS, URI `spiffe://messenger/lb` и SHA-256 leaf из `allowed-lb.sha256`; uvicorn только на `127.0.0.1:8080` | `student-tests/mtls_probe.py` | Допуск читается с файла при каждом соединении, CRL нет |
На 4 минимум 6 конкретных угроз. Не заменяйте сценарии словами «SQL injection», «безопасный Docker», «mTLS включён» без пути и проверки. | Подбор пароля или дорогой Argon2id на всех репликах сразу | Учётная запись и CPU стенда | Общий Redis-счётчик, 8 попыток / 60 с на имя и 30 на IP, `429` + `Retry-After` до хэша | Повторный `POST /api/v1/auth/sessions` | Лимит по IP общий для всех, кто пришёл с одного адреса LB; честный IP берётся из `X-Real-IP` |
| Участник B читает вложение или историю чата A, либо шлёт `X-User-Id` | Доступ только у членов чата и только по Bearer | Проверка membership в SQL, Bearer, а не заголовок пользователя | Публичный smoke и отказ чужого `attachment_id` | Список участников после создания чата не меняется, как в контракте |
| Worker или его SecretID читает KV API (`secret/data/messenger/api`) или пишет policy | Компрометация worker не даёт пароли пользователей и admin S3 | Отдельные AppRole и policy; worker без `SELECT` на `users`; S3-ключ без `Admin` | `evidence/openbao-deny.txt` после bootstrap; PutObject в `secrets/` ключом worker | Worker всё ещё пишет `staging/` и `originals/`, это нужно конвейеру |
| Контейнер API рестартится и тянет `DATABASE_URL` из переменной образа или root token | Секрет получения секретов запечён в образ | AppRole SecretID файлом оператора, TTL 24 ч, token TTL 20 мин, renew; root только в `secrets/openbao-init.json` у оператора | В `compose.yaml` нет `BAO_TOKEN`; образ не содержит `secrets/` | Пока SecretID не истёк, файл на хосте — это доверие оператора; автоматический unseal не делается |
## Lifecycle и инциденты ## Lifecycle и инциденты
TODO: bootstrap, expiry/renewal, revoke/rotation, компрометация identity, sealed OpenBao и восстановление. Указать владельца CA/unseal и способ защиты bootstrap credentials. Сопоставить scan findings с реальной применимостью и исправлением/остаточным риском. Bootstrap: `scripts/bootstrap.ps1` создаёт CA и leaf локально, поднимает OpenBao в file storage (не dev), один раз вызывает init и пишет unseal key и root token в `secrets/openbao-init.json`. Обычный рестарт API unseal не требует: OpenBao не входит в `scripts/restart.sh`. После рестарта самого OpenBao оператор повторяет `docker compose --profile bootstrap run --rm openbao-bootstrap` — скрипт читает уже существующий init-файл и делает unseal, не печатая ключ.
Ротация leaf LB: `scripts/reissue-leaf.sh` выпускает новый `lb.crt` тем же CA и перезапускает только `lb`. Клиенты с `certs/ca.crt` принимают его без пересборки образа. На прогоне 26 ноября идентификатор образа `mtusi-messenger:lab7` не изменился.
Отзыв identity worker: брокер и Collector, кроме URI, сверяют серийный номер leaf с `allowed-worker.serial`. Старый файл сохраняется как `worker-client.revoked.*` и после выпуска нового leaf получает отказ. Просроченный сертификат (`notAfter` в 2020) не проходит handshake.
Ротация секрета worker: новый пароль `messenger_worker` пишется в Postgres и в KV `messenger/worker`. SecretID AppRole при этом не перевыпускается (`BAO_REFRESH_KV_ONLY=1`), образ не пересобирается. Задание, поставленное в очередь при остановленном worker, после старта доходит до `ready`.
Истечение и sealed OpenBao: token TTL 20 минут, SecretID 24 часа. `student-tests/seal_probe.py` запечатывает OpenBao, видит отказ AppRole (HTTP 503) и сразу делает unseal. Fallback на plaintext и отключение проверки сертификата в приложении нет.
Скан: `security/SCAN.md`.
Сканы образов в этот коммит не вложены сырым отчётом Trivy: разбор применимости лежит в `security/SCAN.md`. Учебное упрощение — один Docker-хост, file storage OpenBao без HA, ручной unseal. Pillow 11 не поднят до 13.
+128
View File
@@ -0,0 +1,128 @@
#!/usr/bin/env python3
"""Public TLS check on :8443, then mTLS identity checks against api:8443.
The stand must already be up. Private keys are read from certs/ and are not printed.
`--internal` is used by this script when it re-enters through the Docker network.
"""
from __future__ import annotations
import socket
import ssl
import subprocess
import sys
import urllib.error
import urllib.request
from pathlib import Path
PROBE = Path(__file__).resolve()
ROOT = PROBE.parents[1] if len(PROBE.parents) > 1 else PROBE.parent
CERTS = Path("/certs") if "--internal" in sys.argv else ROOT / "certs"
PORT = 8443
def handshake(host: str, server_name: str, cert: Path | None, key: Path | None, ca: Path | None) -> str:
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
context.minimum_version = ssl.TLSVersion.TLSv1_2
if ca is not None:
context.load_verify_locations(ca)
context.check_hostname = True
context.verify_mode = ssl.CERT_REQUIRED
else:
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
if cert is not None and key is not None:
context.load_cert_chain(cert, key)
try:
with socket.create_connection((host, PORT), timeout=5) as raw:
with context.wrap_socket(raw, server_hostname=server_name) as tls:
request = (
"GET /health/ready HTTP/1.1\r\nHost: %s\r\nConnection: close\r\n\r\n" % server_name
).encode("ascii")
tls.sendall(request)
data = b""
while True:
chunk = tls.recv(4096)
if not chunk:
break
data += chunk
head = data.split(b"\r\n", 1)[0].decode("ascii", "replace")
return head or "empty"
except ssl.SSLError as exc:
return "ssl:" + exc.__class__.__name__
except OSError as exc:
return "os:" + exc.__class__.__name__
def expect_fail(label: str, result: str) -> None:
if result.startswith("HTTP/1.1 200"):
raise SystemExit("FAIL %s unexpectedly returned %s" % (label, result))
print("PASS", label, result)
def public_checks() -> None:
ca = CERTS / "ca.crt"
ok = handshake("127.0.0.1", "localhost", None, None, ca)
if not ok.startswith("HTTP/1.1 200"):
raise SystemExit("FAIL public TLS: %s" % ok)
print("PASS public TLS without a client certificate", ok)
try:
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
context.check_hostname = True
context.verify_mode = ssl.CERT_REQUIRED
urllib.request.urlopen("https://localhost:%s/health/ready" % PORT, context=context, timeout=5)
raise SystemExit("FAIL empty trust store was accepted")
except urllib.error.URLError as exc:
if not isinstance(exc.reason, ssl.SSLCertVerificationError):
raise SystemExit("FAIL empty trust store failed for a non-certificate reason") from exc
print("PASS empty trust store rejected")
def internal_checks() -> None:
ca = CERTS / "ca.crt"
ok = handshake("api", "api", CERTS / "lb-client.crt", CERTS / "lb-client.key", ca)
if not ok.startswith("HTTP/1.1 200"):
raise SystemExit("FAIL allowed LB identity: %s" % ok)
print("PASS allowed LB identity", ok)
expect_fail("no client cert", handshake("api", "api", None, None, ca))
expect_fail("other CA", handshake("api", "api", CERTS / "other-client.crt", CERTS / "other-client.key", ca))
expect_fail("same CA wrong identity", handshake("api", "api", CERTS / "stranger.crt", CERTS / "stranger.key", ca))
expect_fail("revoked fingerprint", handshake("api", "api", CERTS / "lb-revoked.crt", CERTS / "lb-revoked.key", ca))
def main() -> None:
if "--internal" in sys.argv:
internal_checks()
return
if not (CERTS / "ca.crt").is_file():
raise SystemExit("missing certs/ca.crt; run scripts/bootstrap.ps1")
public_checks()
probe = Path(__file__).resolve()
completed = subprocess.run(
[
"docker",
"compose",
"--env-file",
".env",
"run",
"--rm",
"--no-deps",
"--entrypoint",
"python",
"-v",
"%s:/probe.py:ro" % probe,
"-v",
"%s:/certs:ro" % CERTS,
"api",
"/probe.py",
"--internal",
],
cwd=ROOT,
check=False,
)
if completed.returncode != 0:
raise SystemExit(completed.returncode)
if __name__ == "__main__":
sys.exit(main() or 0)
+148
View File
@@ -0,0 +1,148 @@
#!/usr/bin/env python3
"""Same-CA identity check for the broker and the collector.
The public client does not present a certificate. This probe joins the
compose networks and checks that a certificate signed by our CA is still
rejected when its SAN or leaf serial is not the API or worker identity.
"""
from __future__ import annotations
import socket
import ssl
import subprocess
import sys
from pathlib import Path
PROBE = Path(__file__).resolve()
ROOT = PROBE.parents[1] if len(PROBE.parents) > 1 else PROBE.parent
CERTS = Path("/certs") if "--internal" in sys.argv else ROOT / "certs"
def context(cert: Path | None, key: Path | None) -> ssl.SSLContext:
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
ctx.minimum_version = ssl.TLSVersion.TLSv1_2
ctx.load_verify_locations(CERTS / "ca.crt")
ctx.check_hostname = True
ctx.verify_mode = ssl.CERT_REQUIRED
if cert is not None and key is not None:
ctx.load_cert_chain(cert, key)
return ctx
def rabbit(cert: Path | None, key: Path | None) -> str:
try:
raw = socket.create_connection(("rabbitmq", 5671), timeout=5)
tls = context(cert, key).wrap_socket(raw, server_hostname="rabbitmq")
tls.sendall(b"AMQP\x00\x00\x09\x01")
data = tls.recv(8)
tls.close()
return "amqp" if data else "closed"
except ssl.SSLError as exc:
return "ssl:" + exc.__class__.__name__
except OSError as exc:
return "os:" + exc.__class__.__name__
def otel(cert: Path | None, key: Path | None) -> str:
try:
raw = socket.create_connection(("otel-collector", 4318), timeout=5)
tls = context(cert, key).wrap_socket(raw, server_hostname="otel-collector")
tls.sendall(b"GET / HTTP/1.1\r\nHost: otel-collector\r\nConnection: close\r\n\r\n")
data = b""
while True:
chunk = tls.recv(1024)
if not chunk:
break
data += chunk
tls.close()
head = data.split(b"\r\n", 1)[0].decode("ascii", "replace")
return head or "closed"
except ssl.SSLError as exc:
return "ssl:" + exc.__class__.__name__
except OSError as exc:
return "os:" + exc.__class__.__name__
def expect_closed(label: str, result: str) -> None:
denied = result == "closed" or result.startswith("ssl:") or result.startswith("os:") or result.startswith("HTTP/1.1 403")
if not denied:
raise SystemExit("FAIL %s was accepted: %s" % (label, result))
print("PASS", label, result)
def internal() -> None:
pairs = (
("api leaf", CERTS / "api-client.crt", CERTS / "api-client.key"),
("worker leaf", CERTS / "worker-client.crt", CERTS / "worker-client.key"),
)
for label, cert, key in pairs:
rabbit_result = rabbit(cert, key)
otel_result = otel(cert, key)
if rabbit_result != "amqp":
raise SystemExit("FAIL %s broker: %s" % (label, rabbit_result))
if not otel_result.startswith("HTTP/"):
raise SystemExit("FAIL %s collector: %s" % (label, otel_result))
print("PASS", label, "broker", rabbit_result, "collector", otel_result)
expect_closed("broker no cert", rabbit(None, None))
expect_closed("broker stranger same CA", rabbit(CERTS / "stranger.crt", CERTS / "stranger.key"))
expect_closed("broker other CA", rabbit(CERTS / "other-client.crt", CERTS / "other-client.key"))
expect_closed("collector no cert", otel(None, None))
expect_closed("collector stranger same CA", otel(CERTS / "stranger.crt", CERTS / "stranger.key"))
expect_closed("collector other CA", otel(CERTS / "other-client.crt", CERTS / "other-client.key"))
revoked = CERTS / "worker-client.revoked.crt"
if revoked.is_file():
expect_closed(
"broker revoked worker leaf",
rabbit(revoked, CERTS / "worker-client.revoked.key"),
)
expect_closed(
"collector revoked worker leaf",
otel(revoked, CERTS / "worker-client.revoked.key"),
)
expired = CERTS / "expired-worker.crt"
if expired.is_file():
expect_closed(
"broker expired worker leaf",
rabbit(expired, CERTS / "expired-worker.key"),
)
expect_closed(
"collector expired worker leaf",
otel(expired, CERTS / "expired-worker.key"),
)
def main() -> None:
if "--internal" in sys.argv:
internal()
return
if not (CERTS / "ca.crt").is_file():
raise SystemExit("missing certs/ca.crt")
completed = subprocess.run(
[
"docker",
"compose",
"--env-file",
".env",
"run",
"--rm",
"--no-deps",
"--entrypoint",
"python",
"-v",
"%s:/probe.py:ro" % PROBE,
"-v",
"%s:/certs:ro" % CERTS,
"api",
"/probe.py",
"--internal",
],
cwd=ROOT,
check=False,
)
if completed.returncode != 0:
raise SystemExit(completed.returncode)
if __name__ == "__main__":
sys.exit(main() or 0)
+78
View File
@@ -0,0 +1,78 @@
"""Seal OpenBao, prove AppRole login fails, then unseal. Prints no key material."""
from __future__ import annotations
import json
import os
import ssl
import urllib.error
import urllib.request
from pathlib import Path
ADDR = os.environ["BAO_ADDR"].rstrip("/")
CAFILE = os.environ["TLS_CA_FILE"]
INIT = json.loads(Path(os.environ["BAO_INIT_FILE"]).read_text(encoding="utf-8"))
ROLE = Path("/secrets/worker.role_id").read_text(encoding="utf-8").strip()
SECRET = Path("/secrets/worker.secret_id").read_text(encoding="utf-8").strip()
def ctx() -> ssl.SSLContext:
context = ssl.create_default_context(cafile=CAFILE)
context.check_hostname = True
context.verify_mode = ssl.CERT_REQUIRED
context.minimum_version = ssl.TLSVersion.TLSv1_2
return context
def call(method: str, path: str, body: dict | None = None, token: str = "") -> int:
data = None if body is None else json.dumps(body).encode("utf-8")
request = urllib.request.Request(ADDR + path, data=data, method=method)
request.add_header("Content-Type", "application/json")
if token:
request.add_header("X-Vault-Token", token)
try:
with urllib.request.urlopen(request, context=ctx(), timeout=5) as response:
response.read()
return response.status
except urllib.error.HTTPError as exc:
exc.read()
return exc.code
def main() -> None:
token = INIT.get("root_token") or ""
key = (INIT.get("keys") or [""])[0]
if not token or not key:
raise SystemExit("operator init file is incomplete")
sealed = False
try:
code = call("PUT", "/v1/sys/seal", token=token)
if code not in (200, 204):
raise SystemExit("FAIL seal returned HTTP %s" % code)
sealed = True
login = call(
"POST",
"/v1/auth/approle/login",
{"role_id": ROLE, "secret_id": SECRET},
)
if login == 200:
raise SystemExit("FAIL sealed OpenBao accepted AppRole")
print("PASS sealed OpenBao rejects AppRole", login)
finally:
if sealed:
status = call("POST", "/v1/sys/unseal", {"key": key})
if status != 200:
raise SystemExit("FAIL unseal returned HTTP %s" % status)
print("PASS OpenBao unsealed")
login = call(
"POST",
"/v1/auth/approle/login",
{"role_id": ROLE, "secret_id": SECRET},
)
if login != 200:
raise SystemExit("FAIL AppRole login after unseal HTTP %s" % login)
print("PASS AppRole login after unseal")
if __name__ == "__main__":
main()
+169
View File
@@ -0,0 +1,169 @@
#!/usr/bin/env python3
"""Rehash and shared login budget. Prints parameters and timings only."""
from __future__ import annotations
import base64
import json
import socket
import ssl
import subprocess
import sys
import time
import uuid
from pathlib import Path
PROBE = Path(__file__).resolve()
ROOT = PROBE.parents[1] if len(PROBE.parents) > 1 else PROBE.parent
def https(method: str, path: str, body: bytes | None = None, headers: dict | None = None) -> tuple[int, str]:
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
ctx.minimum_version = ssl.TLSVersion.TLSv1_2
ctx.load_verify_locations("/certs/ca.crt")
ctx.check_hostname = True
ctx.verify_mode = ssl.CERT_REQUIRED
raw = socket.create_connection(("host.docker.internal", 8443), timeout=10)
tls = ctx.wrap_socket(raw, server_hostname="localhost")
header_lines = ["%s %s HTTP/1.1" % (method, path), "Host: localhost", "Connection: close"]
for key, value in (headers or {}).items():
header_lines.append("%s: %s" % (key, value))
if body is not None:
header_lines.append("Content-Type: application/json")
header_lines.append("Content-Length: %s" % len(body))
payload = ("\r\n".join(header_lines) + "\r\n\r\n").encode("ascii")
if body is not None:
payload += body
tls.sendall(payload)
data = b""
while True:
chunk = tls.recv(8192)
if not chunk:
break
data += chunk
tls.close()
head, _, _rest = data.partition(b"\r\n\r\n")
text = head.decode("latin1", "replace")
status = int(text.split(" ", 2)[1])
return status, text
def internal() -> None:
import asyncio
from argon2 import PasswordHasher
from app import bao, db
username = "rehash_" + uuid.uuid4().hex[:10]
password = "synthetic-rehash-password"
status, _headers = https(
"POST",
"/api/v1/users",
json.dumps(
{"username": username, "display_name": "rehash probe", "password": password}
).encode("utf-8"),
)
if status != 201:
raise SystemExit("FAIL register %s" % status)
bao.apply()
async def memory_param() -> str:
pool = await db.connect()
try:
row = await pool.fetchrow(
"SELECT substring(password_hash from 'm=[0-9]+') AS param FROM users WHERE username = $1",
username,
)
finally:
await db.close()
return row["param"]
weak = PasswordHasher(memory_cost=8192, time_cost=1, parallelism=1, hash_len=32, salt_len=16).hash(password)
async def store_weak() -> None:
pool = await db.connect()
try:
await pool.execute(
"UPDATE users SET password_hash = $1 WHERE username = $2",
weak,
username,
)
finally:
await db.close()
asyncio.run(store_weak())
before = asyncio.run(memory_param())
print("rehash_before", before)
basic = base64.b64encode((username + ":" + password).encode("utf-8")).decode("ascii")
started = time.perf_counter()
status, headers = https(
"POST",
"/api/v1/auth/sessions",
headers={"Authorization": "Basic " + basic},
)
login_ms = (time.perf_counter() - started) * 1000
if status != 201:
raise SystemExit("FAIL rehash login %s" % status)
after = asyncio.run(memory_param())
print("rehash_after", after, "login_ms=%.1f" % login_ms)
if before != "m=8192" or after != "m=19456":
raise SystemExit("FAIL rehash did not move to the floor")
wrong = base64.b64encode((username + ":wrong-password").encode("utf-8")).decode("ascii")
limited_status = None
for attempt in range(2, 12):
started = time.perf_counter()
status, headers = https(
"POST",
"/api/v1/auth/sessions",
headers={"Authorization": "Basic " + wrong},
)
elapsed = (time.perf_counter() - started) * 1000
if status == 429:
if "retry-after" not in headers.lower():
raise SystemExit("FAIL 429 without Retry-After")
print("rate_limit_attempt", attempt, "status", status, "elapsed_ms=%.1f" % elapsed)
limited_status = status
break
if status != 401:
raise SystemExit("FAIL unexpected login status %s" % status)
if attempt == 8:
print("argon2_reject_attempt", attempt, "elapsed_ms=%.1f" % elapsed)
if limited_status != 429:
raise SystemExit("FAIL shared rate limit did not return 429")
print("PASS rehash and shared login limit")
def main() -> None:
if "--internal" in sys.argv:
internal()
return
completed = subprocess.run(
[
"docker",
"compose",
"--env-file",
".env",
"run",
"--rm",
"--no-deps",
"--entrypoint",
"python",
"-e",
"PYTHONPATH=/app",
"-v",
"%s:/probe.py:ro" % PROBE,
"api",
"/probe.py",
"--internal",
],
cwd=ROOT,
check=False,
)
if completed.returncode != 0:
raise SystemExit(completed.returncode)
if __name__ == "__main__":
sys.exit(main() or 0)
+253
View File
@@ -0,0 +1,253 @@
#!/usr/bin/env python3
"""Grade 4 rotation/revocation plus track 1, the worker compromise comparison.
Stops the worker, leaves one upload queued, revokes the old worker leaf,
rotates the worker database password, then shows the same job still reaches ready.
"""
from __future__ import annotations
import secrets
import shutil
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client # noqa: E402
def run(args: list[str], check: bool = True) -> subprocess.CompletedProcess:
completed = subprocess.run(args, cwd=ROOT, check=False)
if check and completed.returncode != 0:
raise SystemExit("command failed: %s" % " ".join(args[:6]))
return completed
def compose(*args: str, check: bool = True) -> subprocess.CompletedProcess:
return run(["docker", "compose", "--env-file", ".env", *args], check=check)
def reissue(name: str, cn: str, eku: str, san: str, not_before: str = "", not_after: str = "") -> None:
env_args: list[str] = []
if not_before:
env_args.extend(["-e", "NOT_BEFORE=" + not_before])
if not_after:
env_args.extend(["-e", "NOT_AFTER=" + not_after])
run(
[
"docker",
"run",
"--rm",
*env_args,
"-v",
"%s:/work" % (ROOT / "certs"),
"-v",
"%s:/reissue-leaf.sh:ro" % (ROOT / "scripts" / "reissue-leaf.sh"),
"alpine:3.21.3",
"sh",
"/reissue-leaf.sh",
name,
cn,
eku,
san,
]
)
def worker_rights() -> None:
completed = compose(
"run",
"--rm",
"--no-deps",
"--entrypoint",
"python",
"-e",
"PYTHONPATH=/app",
"-e",
"BAO_ROLE_ID_FILE=/run/worker/role_id",
"-e",
"BAO_SECRET_ID_FILE=/run/worker/secret_id",
"-e",
"BAO_SECRET_PATH=secret/data/messenger/worker",
"-e",
"TLS_CERT_FILE=/certs/worker-client.crt",
"-e",
"TLS_KEY_FILE=/certs/worker-client.key",
"-v",
"%s:/run/worker/role_id:ro" % (ROOT / "secrets" / "worker.role_id"),
"-v",
"%s:/run/worker/secret_id:ro" % (ROOT / "secrets" / "worker.secret_id"),
"-v",
"%s:/certs/worker-client.crt:ro" % (ROOT / "certs" / "worker-client.crt"),
"-v",
"%s:/certs/worker-client.key:ro" % (ROOT / "certs" / "worker-client.key"),
"-v",
"%s:/probe.py:ro" % (ROOT / "student-tests" / "worker_rights.py"),
"api",
"/probe.py",
)
if completed.returncode != 0:
raise SystemExit(completed.returncode)
def rotate_db_password() -> None:
path = ROOT / "secrets" / "db_worker_password"
path.write_text(secrets.token_hex(24), encoding="utf-8")
container = subprocess.run(
["docker", "compose", "--env-file", ".env", "ps", "-q", "postgres"],
cwd=ROOT,
check=True,
capture_output=True,
text=True,
).stdout.strip()
run(["docker", "cp", str(path), "%s:/tmp/db_worker_password" % container])
run(
[
"docker",
"exec",
container,
"sh",
"-c",
"psql -v ON_ERROR_STOP=1 -U messenger -d messenger -c \"ALTER ROLE messenger_worker PASSWORD '$(cat /tmp/db_worker_password)'\" && rm -f /tmp/db_worker_password",
]
)
compose(
"--profile",
"bootstrap",
"run",
"--rm",
"--entrypoint",
"python",
"-e",
"BAO_REFRESH_KV_ONLY=1",
"-v",
"%s:/app/app/tools/openbao_bootstrap.py:ro" % (ROOT / "app" / "tools" / "openbao_bootstrap.py"),
"openbao-bootstrap",
"-m",
"app.tools.openbao_bootstrap",
)
def image_id() -> str:
completed = subprocess.run(
["docker", "image", "inspect", "mtusi-messenger:lab7", "--format", "{{.Id}}"],
cwd=ROOT,
check=True,
capture_output=True,
text=True,
)
return completed.stdout.strip()
def main() -> None:
before_image = image_id()
print("image_before", before_image.split(":")[-1][:12])
run(
[
"docker",
"run",
"--rm",
"-v",
"%s:/work" % (ROOT / "certs"),
"-v",
"%s:/gen-certs.sh:ro" % (ROOT / "scripts" / "gen-certs.sh"),
"alpine:3.21.3",
"sh",
"/gen-certs.sh",
]
)
compose("up", "-d", "--no-deps", "--force-recreate", "rabbit-mtls", "otel-mtls")
time.sleep(2)
worker_rights()
users = compose(
"exec",
"-T",
"postgres",
"psql",
"-U",
"messenger",
"-d",
"messenger",
"-tAc",
"SELECT count(*) FROM users",
)
del users
print("PASS superuser can read users; worker role cannot")
compose("stop", "worker")
client = Client("https://127.0.0.1:8443", str(ROOT / "certs" / "ca.crt"), timeout=10)
alice, _bob, _eve, chat = client.bootstrap()
attachment, _content = client.attachment(alice, chat)
if attachment["status"] != "queued":
raise SystemExit("FAIL upload was not left queued")
print("PASS upload queued while worker is stopped")
certs = ROOT / "certs"
shutil.copyfile(certs / "worker-client.crt", certs / "worker-client.revoked.crt")
shutil.copyfile(certs / "worker-client.key", certs / "worker-client.revoked.key")
reissue(
"worker-client",
"worker",
"clientAuth",
"DNS:worker-client,URI:spiffe://messenger/worker",
)
compose("up", "-d", "--no-deps", "--force-recreate", "rabbit-mtls", "otel-mtls")
time.sleep(2)
probe = subprocess.run([sys.executable, "-X", "utf8", str(ROOT / "student-tests" / "same_ca_probe.py")], cwd=ROOT)
if probe.returncode != 0:
raise SystemExit(probe.returncode)
reissue("lb", "localhost", "serverAuth", "DNS:localhost,IP:127.0.0.1")
compose("restart", "lb")
time.sleep(2)
client.call("GET", "/health/ready", schema="Health")
print("PASS lb leaf rotated without an image rebuild")
rotate_db_password()
compose("start", "worker")
ready = client.wait_ready(alice, attachment, wait_seconds=90)
if ready["status"] != "ready":
raise SystemExit("FAIL queued attachment did not become ready after rotation")
print("PASS queued job survived worker revocation and secret rotation")
worker_rights()
reissue(
"expired-worker",
"worker",
"clientAuth",
"URI:spiffe://messenger/worker",
not_before="20200101000000Z",
not_after="20200102000000Z",
)
probe = subprocess.run([sys.executable, "-X", "utf8", str(ROOT / "student-tests" / "same_ca_probe.py")], cwd=ROOT)
if probe.returncode != 0:
raise SystemExit(probe.returncode)
seal = compose(
"--profile",
"bootstrap",
"run",
"--rm",
"--no-deps",
"--entrypoint",
"python",
"-v",
"%s:/probe.py:ro" % (ROOT / "student-tests" / "seal_probe.py"),
"openbao-bootstrap",
"/probe.py",
)
if seal.returncode != 0:
raise SystemExit(seal.returncode)
after_image = image_id()
if before_image != after_image:
raise SystemExit("FAIL application image changed during rotation")
print("PASS image unchanged", after_image.split(":")[-1][:12])
print("PASS track1 and grade4 lifecycle")
if __name__ == "__main__":
main()
+91
View File
@@ -0,0 +1,91 @@
#!/usr/bin/env python3
"""What the worker credential can and cannot do. Prints statuses, not secrets."""
from __future__ import annotations
import asyncio
import uuid
import asyncpg
from botocore.exceptions import ClientError
from app import bao, broker, config, db, s3, tlsutil
def openbao_status(path: str) -> str:
try:
login = bao._request(
"POST",
"/v1/auth/approle/login",
{"role_id": config.BAO_ROLE_ID, "secret_id": config.BAO_SECRET_ID},
)
token = (login.get("auth") or {}).get("client_token") or ""
bao._request("GET", path, token=token)
return "200"
except RuntimeError as exc:
text = str(exc)
if "HTTP " in text:
return text.split("HTTP ", 1)[1]
return "error"
async def main() -> None:
bao.apply()
pool = await db.connect()
try:
await pool.fetchval("SELECT count(*) FROM attachments")
print("PASS worker db read attachments")
try:
await pool.fetchval("SELECT count(*) FROM users")
except asyncpg.InsufficientPrivilegeError:
print("PASS worker db cannot read users")
else:
raise SystemExit("FAIL worker read the users table")
finally:
await db.close()
client = s3._client_or_create()
key = "variants/track1-%s" % uuid.uuid4().hex
client.put_object(Bucket=config.S3_BUCKET, Key=key, Body=b"ok")
client.delete_object(Bucket=config.S3_BUCKET, Key=key)
print("PASS worker s3 write variants")
try:
client.put_object(Bucket=config.S3_BUCKET, Key="secrets/track1", Body=b"no")
except ClientError as exc:
code = exc.response.get("Error", {}).get("Code", "")
print("PASS worker s3 cannot write secrets", code)
else:
raise SystemExit("FAIL worker wrote secrets/")
connection = await __import__("aio_pika").connect_robust(
config.BROKER_URL,
ssl_context=tlsutil.server_context(),
)
channel = await connection.channel()
try:
await channel.declare_queue("stolen.queue", durable=False, auto_delete=True)
except Exception as exc:
print("PASS worker broker cannot declare stolen.queue", type(exc).__name__)
else:
raise SystemExit("FAIL worker declared stolen.queue")
await connection.close()
connection = await __import__("aio_pika").connect_robust(
config.BROKER_URL,
ssl_context=tlsutil.server_context(),
)
channel = await connection.channel()
await channel.declare_queue(broker.QUEUE, durable=True, passive=True)
await connection.close()
print("PASS worker broker can see attachment.jobs")
own = openbao_status("/v1/secret/data/messenger/worker")
foreign = openbao_status("/v1/secret/data/messenger/api")
print("PASS worker openbao own path", own)
print("PASS worker openbao api path", foreign)
if own != "200" or foreign != "403":
raise SystemExit("FAIL worker OpenBao policy own=%s api=%s" % (own, foreign))
if __name__ == "__main__":
asyncio.run(main())