ЛР7 - БВТ2302 - Зюлина - на 3
Skeleton contracts / contracts (pull_request) Blocked by required conditions
Skeleton contracts / contracts (pull_request) Blocked by required conditions
This commit is contained in:
+25
-37
@@ -1,41 +1,29 @@
|
||||
# Copy to .env for your LOCAL synthetic test environment; never commit .env.
|
||||
# These are logical interface suggestions; map actual framework names in REPORT.md.
|
||||
APP_HOST=0.0.0.0
|
||||
APP_PORT=8080
|
||||
APP_ENV=lab
|
||||
# Copy to .env and replace each placeholder locally. Never commit .env.
|
||||
APP_PORT=8443
|
||||
SESSION_TTL_SECONDS=3600
|
||||
# Choose credentials locally. File paths contain no secret values.
|
||||
DATABASE_URL_FILE=/run/secrets/database_url
|
||||
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
|
||||
SESSION_STORE=postgres
|
||||
CACHE_URL_FILE=/run/secrets/cache_url
|
||||
API_REPLICAS=2
|
||||
IDEMPOTENCY_TTL_SECONDS=86400
|
||||
S3_ENDPOINT=https://s3:9000
|
||||
S3_REGION=us-east-1
|
||||
S3_BUCKET=messenger-attachments
|
||||
S3_ACCESS_KEY_ID_FILE=/run/secrets/s3_access_key_id
|
||||
S3_SECRET_ACCESS_KEY_FILE=/run/secrets/s3_secret_access_key
|
||||
MAX_UPLOAD_BYTES=10485760
|
||||
MAX_IMAGE_PIXELS=40000000
|
||||
BROKER_URL_FILE=/run/secrets/broker_url
|
||||
WORKER_CONCURRENCY=2
|
||||
JOB_MAX_ATTEMPTS=5
|
||||
JOB_TIMEOUT_SECONDS=60
|
||||
STAGING_RETENTION_SECONDS=86400
|
||||
OTEL_SERVICE_NAME=messenger-api
|
||||
# Worker must set a distinct service.name.
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT=https://otel-collector:4318
|
||||
OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
|
||||
OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=lab
|
||||
# TLS and OpenBao: actual paths/ports depend on your implemented trust matrix.
|
||||
PUBLIC_BASE_URL=https://localhost:8443
|
||||
TLS_CA_FILE=/run/secrets/ca.crt
|
||||
TLS_CERT_FILE=/run/secrets/service.crt
|
||||
TLS_KEY_FILE=/run/secrets/service.key
|
||||
BAO_ADDR=https://openbao:8200
|
||||
BAO_CACERT=/run/secrets/bao-ca.crt
|
||||
# No root token here. Bootstrap operator -> short-lived service auth -> scoped token.
|
||||
ARGON2_MEMORY_KIB=19456
|
||||
ARGON2_ITERATIONS=2
|
||||
ARGON2_PARALLELISM=1
|
||||
S3_ENDPOINT=https://minio:9000
|
||||
S3_REGION=us-east-1
|
||||
S3_BUCKET=messenger-attachments
|
||||
S3_ACCESS_KEY=replace-with-local-minio-service-user
|
||||
S3_SECRET_KEY=replace-with-random-secret
|
||||
S3_WORKER_ACCESS_KEY=replace-with-distinct-worker-user
|
||||
S3_WORKER_SECRET_KEY=replace-with-distinct-random-secret
|
||||
CACHE_API_PASSWORD=replace-with-random-cache-password
|
||||
BROKER_API_PASSWORD=replace-with-random-api-broker-password
|
||||
BROKER_WORKER_PASSWORD=replace-with-distinct-worker-broker-password
|
||||
JOB_MAX_ATTEMPTS=5
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT=https://otel-collector:4317
|
||||
OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=lab
|
||||
|
||||
POSTGRES_USER=messenger
|
||||
POSTGRES_PASSWORD=replace-with-random-password
|
||||
POSTGRES_API_PASSWORD=replace-with-distinct-api-db-password
|
||||
POSTGRES_WORKER_PASSWORD=replace-with-distinct-worker-db-password
|
||||
POSTGRES_DB=messenger
|
||||
MINIO_ROOT_USER=minio-admin
|
||||
MINIO_ROOT_PASSWORD=replace-with-random-password
|
||||
GRAFANA_PORT=3000
|
||||
GRAFANA_PASSWORD=replace-with-random-password
|
||||
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
FROM python:3.11.10-slim-bookworm
|
||||
|
||||
WORKDIR /app
|
||||
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1
|
||||
|
||||
# Устанавливаем зависимости
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
# Копируем код приложения
|
||||
COPY src/ ./src/
|
||||
COPY alembic/ ./alembic/
|
||||
COPY alembic.ini .
|
||||
COPY scripts/grant_worker_db.py ./scripts/grant_worker_db.py
|
||||
COPY scripts/internal_mtls_probe.py ./scripts/internal_mtls_probe.py
|
||||
COPY scripts/benchmark_argon2.py ./scripts/benchmark_argon2.py
|
||||
COPY entrypoint.sh .
|
||||
|
||||
RUN chmod 755 entrypoint.sh && groupadd --gid 10001 app && useradd --uid 10001 --gid app --no-create-home --shell /usr/sbin/nologin app
|
||||
|
||||
USER 10001:10001
|
||||
|
||||
# Открываем порт
|
||||
EXPOSE 8080
|
||||
|
||||
ENTRYPOINT ["./entrypoint.sh"]
|
||||
|
||||
# Команда запуска
|
||||
CMD ["uvicorn", "src.main:app", "--host", "127.0.0.1", "--port", "8080", "--limit-concurrency", "64", "--timeout-keep-alive", "5"]
|
||||
@@ -4,7 +4,7 @@ CA_FILE ?=
|
||||
ACTION_SCRIPT ?=
|
||||
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
||||
|
||||
.PHONY: help check validate test load test-persistence test-failover test-security
|
||||
.PHONY: help check validate test load test-persistence test-failover test-security test-internal-mtls
|
||||
|
||||
help:
|
||||
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
|
||||
@@ -31,3 +31,7 @@ test-failover:
|
||||
|
||||
test-security:
|
||||
$(PYTHON) tests/security.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
test-internal-mtls:
|
||||
docker compose --profile security-test run --rm api1-negative-probe
|
||||
docker compose --profile security-test run --rm api2-negative-probe
|
||||
|
||||
@@ -1,37 +1,58 @@
|
||||
# Отчёт — лабораторная 7
|
||||
|
||||
- Автор, группа: TODO
|
||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
||||
- Commit/PR: TODO после публикации
|
||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
||||
- Автор, группа: Зюлина Екатерина Михайловна, БВТ2302 (из отчёта lab6; проверьте перед сдачей).
|
||||
- Целевая оценка: 3.
|
||||
- Commit/PR:
|
||||
- Источники и помощь: контракт и материалы skeleton lab7, собственный проект lab6; FastAPI, SQLAlchemy, Alembic, boto3, Pillow, redis-py, OpenTelemetry, argon2-cffi, hvac; Codex помог прочитать требования, перенести и изменить код и конфигурации.
|
||||
|
||||
## Запуск из чистого clone
|
||||
|
||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
||||
Нужны Windows PowerShell, OpenSSL, Docker Desktop в режиме Linux containers, Docker Compose v2, Python 3.11 и OpenBao CLI 2.3.1. Runtime image закреплён на Python 3.11.10-slim-bookworm; Compose использует версии образов лаборатории 6 и OpenBao 2.3.1. TLS certificates генерируются локально, не коммитятся:
|
||||
|
||||
```powershell
|
||||
pwsh -File infra/tls/bootstrap.ps1
|
||||
Copy-Item .env.example .env
|
||||
# В .env замените все replace-* значения криптографически случайными локальными секретами.
|
||||
docker compose --env-file .env config --quiet
|
||||
docker compose --env-file .env up -d openbao
|
||||
```
|
||||
|
||||
Затем выполните одноразовую операторскую настройку из [infra/openbao/README.md](infra/openbao/README.md): TLS-verified init/unseal, KV v2, scoped API/worker policies, AppRole credentials и KV credentials. Ни root token, ни unseal shares, ни AppRole SecretID не записывайте в проект. После подготовки OpenBao и локальных `secrets/openbao-api/` и `secrets/openbao-worker/` запускайте `docker compose --env-file .env up -d --build`. Это staged bootstrap: app стартует только когда оператор поднял и разблокировал OpenBao. Для публичного CA теста используйте `make test BASE_URL=https://localhost:8443 CA_FILE=secrets/ingress/public-ca.crt`; синтетические smoke данные сохраняются в volumes. `docker compose --env-file .env down` сохраняет данные; только для намеренного удаления локальной учебной БД используйте `down --volumes`.
|
||||
|
||||
Публичные команды указаны в `tests/README.md`; внутренние mTLS/OpenBao проверки — в `contracts/trust-matrix.md`. Конфигурация Compose содержит локальные placeholder variables; `.env` и `secrets/` игнорируются Git.
|
||||
|
||||
## Архитектура и решения
|
||||
|
||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab6, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
||||
Перенесены собственные API, PostgreSQL модели/migrations, сессии, идемпотентность, вложения, Redis Streams worker, OTel instrumentation, dashboards и зависимости lab6. Бизнес API не меняется. Пароли хранятся Argon2id с параметрами не ниже memory=19456 KiB, t=2, p=1. Ingress использует публичную CA и hostname SAN; per-replica TLS proxy requires LB client cert and allowlists its subject. App process is loopback-only behind that proxy. OpenBao uses persistent file storage, TLS, separate AppRoles and scoped KV v2 policies. Login is limited to 10 attempts per minute per client IP per replica and returns `429 Retry-After`.
|
||||
|
||||
PostgreSQL остаётся источником истины для пользователей/сессий/чатов/сообщений/attachment metadata; Redis хранит session cache и durable stream; MinIO — объекты; telemetry backends остаются как в lab6. Postgres uses verify-full and distinct limited API/worker roles; Redis uses server-verified TLS and ACL; API/worker use separate S3 credentials; OpenBao uses scoped AppRoles; API/worker OTLP uses client TLS to Collector. Подробная схема, порт, identity и предел каждой связи приведены в [матрице доверия](contracts/trust-matrix.md).
|
||||
|
||||
## Доказательства критериев
|
||||
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||
| Критерий | Команда/сценарий | Наблюдаемый результат | Результат в этой рабочей копии |
|
||||
| --- | --- | --- | --- |
|
||||
| Публичный smoke | make test | TODO | TODO |
|
||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
||||
| Структура/Compose и HTTPS smoke | `scripts/check_contract.py`; `docker compose --env-file .env config --quiet`; `tests/smoke.py --base-url https://localhost:8443 --ca-file secrets/ingress/public-ca.crt` | Контракт и YAML валидны; полный сквозной HTTPS сценарий проходит | Все три команды прошли. `make` не установлен, поэтому эквивалентные Python-скрипты запускались напрямую |
|
||||
| Argon2id | `docker compose exec api1 python scripts/benchmark_argon2.py` | Argon2id; memory=19456 KiB, t=2,p=1; семь timings и median | PASS; samples 38.6, 32.4, 30.2, 30.6, 29.1, 40.2, 40.9 ms; median 32.4 ms |
|
||||
| Public TLS и mTLS LB→API | `tests/security.py`; `curl.exe --resolve wrong.example:8443:127.0.0.1 ...`; `scripts/internal_mtls_probe.py` на обеих репликах | Trusted HTTPS проходит; пустой CA и неверный hostname отклоняются; без/с чужим client cert — отказ, чужой CN — 403, LB identity — 200 | PASS. Обе API реплики дали все четыре ожидаемых mTLS результата; hostname mismatch вернул curl certificate error 60 |
|
||||
| OpenBao | API и worker AppRole read/cross-path/write allow/deny probes | Каждый service читает только собственный KV path; чужой path и запись запрещены | PASS для обоих AppRole. OpenBao работает non-dev с persistent file storage и TLS |
|
||||
| ACL/logout/session/expiry | Публичный smoke и синтетическая истёкшая сессия | Чужой чат/attachment — 404; logout и expired session — 401; rate limit — 429 + `Retry-After` | PASS. В отдельном rate-limit probe первые 10 неверных login получили 401, попытка 11 — 429 с положительным `Retry-After` |
|
||||
| TLS и least privilege service links | TLS-aware API smoke; plaintext DB/Redis probes; PostgreSQL, Redis ACL, S3 prefix, OTel mTLS, Tempo/Loki/Prometheus TLS checks | DB/S3/Redis/OTLP/telemetry/OpenBao шифруют соединения и проверяют ожидаемую identity/CA; неизвестные DB/Redis пути отклоняются | PASS: PostgreSQL `verify-full`, plaintext DB/Redis отклонён; API/worker Redis ACL и MinIO prefixes отклоняют запрещённые операции; worker DB видит `attachments`, но не `users`; Collector отвергает OTLP без сертификата и принимает раздельные API/worker leaves; Tempo/Loki HTTPS готовы, Prometheus mTLS scrape Collector показывает `up=1` |
|
||||
| Сохранность и отказ реплики | `tests/resilience.py --mode persistence`; два `--mode failover`, по одному на каждую replica alias | Сохранены прежний Bearer/session, подтверждённые сообщения и история; после отказа API writes восстанавливаются до 10 секунд без дублей | PASS. Persistence сохраняет данные после рестарта API, DB, Redis, broker и MinIO. Failover прошёл для обеих реплик: recovery 5.028 s и 1.799 s; в каждом прогоне smoke проверил существующую сессию и отсутствие потерь/дублей. Остановленные реплики затем восстановлены |
|
||||
| Минимальные привилегии/секреты | Compose config/runtime inspect; `git check-ignore` для `.env`, CA key и AppRole SecretID | App/worker non-root; нет privileged/host network/capabilities; API port не опубликован; локальные секреты не отслеживаются Git | PASS: user `10001:10001`, `privileged=false`, Compose bridge network, `cap_add=null`, лимит 512 MiB; порт API 8080 не имеет host binding; локальные `.env`/private keys/SecretID игнорируются Git. Полный repository secret scan не запускался |
|
||||
|
||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
||||
Live checks выполнены 29.11.2026 на локальном Docker Desktop/Linux стенде. Smoke создаёт только синтетические данные в сохранённых Compose volumes. После тестов обе API реплики и worker запущены; `secrets/` и `.env` остаются локальными и игнорируются Git.
|
||||
|
||||
## Эксперименты и отказы
|
||||
|
||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
||||
Эксперимент уровня 4/5 не заявляется. Практический стенд после bootstrap должен отдельно проверить: закрытый API port с host, внешний TLS с доверенным CA и отказ с пустым CA, mTLS через Nginx, OpenBao allow/deny, отзыв пользовательской сессии, недоступность/sealed OpenBao с закрытым отказом. Результаты, commit и дата должны быть добавлены после реального запуска. Не приводятся вымышленные RPS/latency.
|
||||
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||
| Воздействие | Ожидание | Наблюдение | Восстановление / потери |
|
||||
| --- | --- | --- | --- |
|
||||
| TODO | TODO | TODO | TODO |
|
||||
| Неверный внешний CA / hostname | TLS verification error, не timeout | Empty trust store rejected; wrong hostname returned curl exit 60 | Без изменения стенда |
|
||||
| Нет/чужой API client cert, неверный CN | Отказ до FastAPI | Проверены обе реплики: no cert/foreign CA rejected, wrong CN → 403, allowlisted identity → 200 | API app оставался доступен только через loopback proxy |
|
||||
| Отказ одной API replica | LB продолжает запись без потери подтверждённых данных | Оба replica aliases проверены отдельно; восстановление 5.028 s и 1.799 s, подтверждённые записи сохранились, дублей нет | Остановленные API/sidecar контейнеры запущены обратно |
|
||||
| Истечение пользовательской сессии | Bearer token отклоняется | Синтетическая сессия с истёкшим DB expiry после cache invalidation получила 401 | Тестовый пользователь и expired session остались в синтетической БД |
|
||||
|
||||
## Ограничения и следующие шаги
|
||||
|
||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
||||
Это учебный one-host Compose стенд. Rate limit хранится в памяти реплики; общий распределённый лимит — работа уровня 4. Не тестировались sealed/unavailable OpenBao во время работы, отзыв/ротация CA leaf и secret, полный repository/image secret scan, dependency scan и Grafana dashboard queries. Docker Desktop Engine был доступен из разрешённой локальной сессии; для POSIX resilience checks использовался WSL с Python 3.12.3. Итоговую оценку преподаватель определяет по защите, этот отчёт не гарантирует оценку автоматически.
|
||||
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
[alembic]
|
||||
script_location = alembic
|
||||
sqlalchemy.url = postgresql://postgres:postgres@db:5432/messenger
|
||||
|
||||
[loggers]
|
||||
keys = root,sqlalchemy,alembic
|
||||
|
||||
[handlers]
|
||||
keys = console
|
||||
|
||||
[formatters]
|
||||
keys = generic
|
||||
|
||||
[logger_root]
|
||||
level = WARN
|
||||
handlers = console
|
||||
qualname =
|
||||
|
||||
[logger_sqlalchemy]
|
||||
level = WARN
|
||||
handlers =
|
||||
qualname = sqlalchemy.engine
|
||||
|
||||
[logger_alembic]
|
||||
level = INFO
|
||||
handlers =
|
||||
qualname = alembic
|
||||
|
||||
[handler_console]
|
||||
class = StreamHandler
|
||||
args = (sys.stderr,)
|
||||
level = NOTSET
|
||||
formatter = generic
|
||||
|
||||
[formatter_generic]
|
||||
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||
datefmt = %H:%M:%S
|
||||
@@ -0,0 +1,48 @@
|
||||
from logging.config import fileConfig
|
||||
from sqlalchemy import engine_from_config
|
||||
from alembic import context
|
||||
import sys
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
from src.database import Base, DATABASE_URL
|
||||
|
||||
config = context.config
|
||||
config.set_main_option("sqlalchemy.url", DATABASE_URL)
|
||||
|
||||
if config.config_file_name is not None:
|
||||
fileConfig(config.config_file_name)
|
||||
|
||||
target_metadata = Base.metadata
|
||||
|
||||
|
||||
def run_migrations_offline():
|
||||
url = context.config.get_main_option("sqlalchemy.url")
|
||||
context.configure(
|
||||
url=url,
|
||||
target_metadata=target_metadata,
|
||||
literal_binds=True,
|
||||
dialect_opts={"paramstyle": "named"},
|
||||
)
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
def run_migrations_online():
|
||||
connectable = engine_from_config(
|
||||
config.get_section(config.config_ini_section),
|
||||
prefix="sqlalchemy.",
|
||||
poolclass=None,
|
||||
connect_args={"sslmode": "verify-full", "sslrootcert": os.getenv("DB_CA_FILE", "/run/tls/service-ca.crt")},
|
||||
)
|
||||
with connectable.connect() as connection:
|
||||
context.configure(connection=connection, target_metadata=target_metadata)
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
if context.is_offline_mode():
|
||||
run_migrations_offline()
|
||||
else:
|
||||
run_migrations_online()
|
||||
@@ -0,0 +1,22 @@
|
||||
"""${message}
|
||||
|
||||
Revision ID: ${up_revision}
|
||||
Revises: ${down_revision | comma,n}
|
||||
Create Date: ${create_date}
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
${imports if imports else ""}
|
||||
|
||||
revision = ${repr(up_revision)}
|
||||
down_revision = ${repr(down_revision)}
|
||||
branch_labels = ${repr(branch_labels)}
|
||||
depends_on = ${repr(depends_on)}
|
||||
|
||||
|
||||
def upgrade():
|
||||
${upgrades if upgrades else "pass"}
|
||||
|
||||
|
||||
def downgrade():
|
||||
${downgrades if downgrades else "pass"}
|
||||
@@ -0,0 +1,70 @@
|
||||
"""Initial schema
|
||||
|
||||
Revision ID: 001
|
||||
Revises:
|
||||
Create Date: 2026-10-12
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
revision = '001'
|
||||
down_revision = None
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.create_table('users',
|
||||
sa.Column('id', sa.String(), nullable=False),
|
||||
sa.Column('username', sa.String(length=32), nullable=False),
|
||||
sa.Column('display_name', sa.String(length=100), nullable=False),
|
||||
sa.Column('password_hash', sa.String(length=255), nullable=False),
|
||||
sa.Column('created_at', sa.DateTime(timezone=True), nullable=True),
|
||||
sa.PrimaryKeyConstraint('id'))
|
||||
op.create_index('ix_users_username', 'users', ['username'], unique=True)
|
||||
|
||||
op.create_table('sessions',
|
||||
sa.Column('id', sa.String(), nullable=False),
|
||||
sa.Column('token', sa.String(length=255), nullable=False),
|
||||
sa.Column('user_id', sa.String(), nullable=False),
|
||||
sa.Column('expires_at', sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column('created_at', sa.DateTime(timezone=True), nullable=True),
|
||||
sa.ForeignKeyConstraint(['user_id'], ['users.id']),
|
||||
sa.PrimaryKeyConstraint('id'))
|
||||
op.create_index('ix_sessions_token', 'sessions', ['token'], unique=True)
|
||||
|
||||
op.create_table('chats',
|
||||
sa.Column('id', sa.String(), nullable=False),
|
||||
sa.Column('title', sa.String(length=100), nullable=False),
|
||||
sa.Column('created_at', sa.DateTime(timezone=True), nullable=True),
|
||||
sa.PrimaryKeyConstraint('id'))
|
||||
|
||||
op.create_table('chat_members',
|
||||
sa.Column('id', sa.String(), nullable=False),
|
||||
sa.Column('chat_id', sa.String(), nullable=False),
|
||||
sa.Column('user_id', sa.String(), nullable=False),
|
||||
sa.ForeignKeyConstraint(['chat_id'], ['chats.id']),
|
||||
sa.ForeignKeyConstraint(['user_id'], ['users.id']),
|
||||
sa.PrimaryKeyConstraint('id'))
|
||||
|
||||
op.create_table('messages',
|
||||
sa.Column('id', sa.String(), nullable=False),
|
||||
sa.Column('chat_id', sa.String(), nullable=False),
|
||||
sa.Column('sender_id', sa.String(), nullable=False),
|
||||
sa.Column('text', sa.Text(), nullable=False),
|
||||
sa.Column('created_at', sa.DateTime(timezone=True), nullable=True),
|
||||
sa.ForeignKeyConstraint(['chat_id'], ['chats.id']),
|
||||
sa.ForeignKeyConstraint(['sender_id'], ['users.id']),
|
||||
sa.PrimaryKeyConstraint('id'))
|
||||
op.create_index('ix_messages_chat_created', 'messages', ['chat_id', 'created_at'])
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_index('ix_messages_chat_created', table_name='messages')
|
||||
op.drop_table('messages')
|
||||
op.drop_table('chat_members')
|
||||
op.drop_table('chats')
|
||||
op.drop_index('ix_sessions_token', table_name='sessions')
|
||||
op.drop_table('sessions')
|
||||
op.drop_index('ix_users_username', table_name='users')
|
||||
op.drop_table('users')
|
||||
@@ -0,0 +1,35 @@
|
||||
"""Add membership uniqueness and the keyset history index.
|
||||
|
||||
Revision ID: 002
|
||||
Revises: 001
|
||||
Create Date: 2026-10-14
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
revision = '002'
|
||||
down_revision = '001'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
# Older schemas allowed nullable timestamps. Backfill before tightening the
|
||||
# constraint so the migration also works on an existing populated database.
|
||||
for table in ('users', 'sessions', 'chats', 'messages'):
|
||||
op.execute(sa.text(f'UPDATE {table} SET created_at = CURRENT_TIMESTAMP WHERE created_at IS NULL'))
|
||||
op.alter_column(table, 'created_at', existing_type=sa.DateTime(timezone=True), nullable=False)
|
||||
|
||||
op.create_unique_constraint('uq_chat_member', 'chat_members', ['chat_id', 'user_id'])
|
||||
op.create_index('ix_chat_members_user_chat', 'chat_members', ['user_id', 'chat_id'])
|
||||
op.drop_index('ix_messages_chat_created', table_name='messages')
|
||||
op.create_index('ix_messages_chat_created_id', 'messages', ['chat_id', 'created_at', 'id'])
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_index('ix_messages_chat_created_id', table_name='messages')
|
||||
op.create_index('ix_messages_chat_created', 'messages', ['chat_id', 'created_at'])
|
||||
op.drop_index('ix_chat_members_user_chat', table_name='chat_members')
|
||||
op.drop_constraint('uq_chat_member', 'chat_members', type_='unique')
|
||||
for table in ('users', 'sessions', 'chats', 'messages'):
|
||||
op.alter_column(table, 'created_at', existing_type=sa.DateTime(timezone=True), nullable=True)
|
||||
@@ -0,0 +1,30 @@
|
||||
"""Persist message idempotency claims in the shared PostgreSQL database."""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
revision = "003_message_idempotency"
|
||||
down_revision = "002"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.create_table(
|
||||
"message_idempotency",
|
||||
sa.Column("id", sa.String(), nullable=False),
|
||||
sa.Column("user_id", sa.String(), nullable=False),
|
||||
sa.Column("method", sa.String(length=8), nullable=False),
|
||||
sa.Column("chat_path", sa.String(length=80), nullable=False),
|
||||
sa.Column("key", sa.String(length=128), nullable=False),
|
||||
sa.Column("request_hash", sa.String(length=64), nullable=False),
|
||||
sa.Column("message_id", sa.String(), nullable=True),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.ForeignKeyConstraint(["message_id"], ["messages.id"]),
|
||||
sa.ForeignKeyConstraint(["user_id"], ["users.id"]),
|
||||
sa.PrimaryKeyConstraint("id"),
|
||||
sa.UniqueConstraint("user_id", "method", "chat_path", "key", name="uq_idempotency_scope"),
|
||||
)
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_table("message_idempotency")
|
||||
@@ -0,0 +1,38 @@
|
||||
"""Add attachment metadata and message references.
|
||||
|
||||
Revision ID: 004_attachments
|
||||
Revises: 003_message_idempotency
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
revision = "004_attachments"
|
||||
down_revision = "003_message_idempotency"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.add_column("messages", sa.Column("attachment_ids", sa.JSON(), nullable=False,
|
||||
server_default=sa.text("'[]'")))
|
||||
op.create_table(
|
||||
"attachments",
|
||||
sa.Column("id", sa.String(), primary_key=True),
|
||||
sa.Column("chat_id", sa.String(), sa.ForeignKey("chats.id"), nullable=False),
|
||||
sa.Column("owner_id", sa.String(), sa.ForeignKey("users.id"), nullable=False),
|
||||
sa.Column("filename", sa.String(255), nullable=False),
|
||||
sa.Column("content_type", sa.String(32), nullable=False),
|
||||
sa.Column("size_bytes", sa.Integer(), nullable=False),
|
||||
sa.Column("sha256", sa.String(64), nullable=False),
|
||||
sa.Column("object_key", sa.String(128), nullable=False, unique=True),
|
||||
sa.Column("status", sa.String(16), nullable=False),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
|
||||
)
|
||||
op.create_index("ix_attachments_chat_id", "attachments", ["chat_id"])
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_index("ix_attachments_chat_id", table_name="attachments")
|
||||
op.drop_table("attachments")
|
||||
op.drop_column("messages", "attachment_ids")
|
||||
@@ -0,0 +1,29 @@
|
||||
"""Add durable staging and asynchronous attachment job state."""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
revision = "005_async_attachments"
|
||||
down_revision = "004_attachments"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.add_column("attachments", sa.Column("staging_key", sa.String(128), nullable=True))
|
||||
op.add_column("attachments", sa.Column("job_id", sa.String(36), nullable=True))
|
||||
op.add_column("attachments", sa.Column("error_code", sa.String(64), nullable=True))
|
||||
op.add_column("attachments", sa.Column("variants", sa.JSON(), nullable=False, server_default="[]"))
|
||||
op.execute("UPDATE attachments SET staging_key = object_key, job_id = id")
|
||||
op.alter_column("attachments", "staging_key", nullable=False)
|
||||
op.alter_column("attachments", "job_id", nullable=False)
|
||||
op.create_unique_constraint("uq_attachments_staging_key", "attachments", ["staging_key"])
|
||||
op.create_unique_constraint("uq_attachments_job_id", "attachments", ["job_id"])
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_constraint("uq_attachments_job_id", "attachments", type_="unique")
|
||||
op.drop_constraint("uq_attachments_staging_key", "attachments", type_="unique")
|
||||
op.drop_column("attachments", "variants")
|
||||
op.drop_column("attachments", "error_code")
|
||||
op.drop_column("attachments", "job_id")
|
||||
op.drop_column("attachments", "staging_key")
|
||||
+331
@@ -0,0 +1,331 @@
|
||||
services:
|
||||
api1:
|
||||
build: .
|
||||
image: mtusi-messenger-api:7.0.0
|
||||
environment: &api-env
|
||||
CACHE_URL: rediss://messenger-api:${CACHE_API_PASSWORD:?Create a cache API password}@redis:6379/0
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||
S3_ENDPOINT: ${S3_ENDPOINT:-https://minio:9000}
|
||||
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
|
||||
S3_REGION: ${S3_REGION:-us-east-1}
|
||||
BAO_ADDR: https://openbao:8200
|
||||
BAO_CACERT: /run/tls/bao-ca.crt
|
||||
DB_CA_FILE: /run/tls/service-ca.crt
|
||||
BROKER_URL: rediss://messenger-api:${BROKER_API_PASSWORD:?Create an API broker password}@redis-broker:6379/0
|
||||
ATTACHMENT_QUEUE: attachment.jobs.v1
|
||||
JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5}
|
||||
OTEL_SERVICE_NAME: messenger-api
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: ${OTEL_EXPORTER_OTLP_ENDPOINT:-https://otel-collector:4317}
|
||||
OTEL_RESOURCE_ATTRIBUTES: ${OTEL_RESOURCE_ATTRIBUTES:-deployment.environment.name=lab}
|
||||
ARGON2_MEMORY_KIB: ${ARGON2_MEMORY_KIB:-19456}
|
||||
ARGON2_ITERATIONS: ${ARGON2_ITERATIONS:-2}
|
||||
ARGON2_PARALLELISM: ${ARGON2_PARALLELISM:-1}
|
||||
INSTANCE_ID: replica-a
|
||||
depends_on:
|
||||
migrate: {condition: service_completed_successfully}
|
||||
s3-bootstrap: {condition: service_completed_successfully}
|
||||
db: {condition: service_healthy}
|
||||
redis: {condition: service_started}
|
||||
redis-broker: {condition: service_healthy}
|
||||
otel-collector: {condition: service_started}
|
||||
openbao: {condition: service_started}
|
||||
mem_limit: 512m
|
||||
cpus: 1.0
|
||||
stop_grace_period: 15s
|
||||
restart: unless-stopped
|
||||
volumes: ["./secrets/api:/run/tls:ro", "./secrets/openbao-api:/run/secrets:ro"]
|
||||
|
||||
api1-mtls:
|
||||
image: nginx:1.27.5-alpine
|
||||
network_mode: "service:api1"
|
||||
volumes: ["./infra/api-proxy.conf:/etc/nginx/conf.d/default.conf:ro", "./secrets/api-proxy1:/run/tls:ro"]
|
||||
depends_on: [api1]
|
||||
mem_limit: 96m
|
||||
cpus: 0.25
|
||||
restart: unless-stopped
|
||||
healthcheck:
|
||||
test: ["CMD", "nginx", "-t"]
|
||||
interval: 10s
|
||||
timeout: 3s
|
||||
retries: 3
|
||||
|
||||
api1-negative-probe:
|
||||
profiles: [security-test]
|
||||
build: .
|
||||
image: mtusi-messenger-api:7.0.0
|
||||
entrypoint: ["python", "scripts/internal_mtls_probe.py"]
|
||||
network_mode: "service:api1"
|
||||
volumes:
|
||||
- ./secrets/test-client/foreign-client.crt:/test/foreign-client.crt:ro
|
||||
- ./secrets/test-client/foreign-client.key:/test/foreign-client.key:ro
|
||||
- ./secrets/test-client/wrong-lb-client.crt:/test/wrong-lb-client.crt:ro
|
||||
- ./secrets/test-client/wrong-lb-client.key:/test/wrong-lb-client.key:ro
|
||||
- ./secrets/ingress/lb-client.crt:/test/lb-client.crt:ro
|
||||
- ./secrets/ingress/lb-client.key:/test/lb-client.key:ro
|
||||
- ./secrets/api/service-ca.crt:/run/tls/service-ca.crt:ro
|
||||
depends_on:
|
||||
api1-mtls: {condition: service_healthy}
|
||||
restart: "no"
|
||||
|
||||
api2-negative-probe:
|
||||
profiles: [security-test]
|
||||
build: .
|
||||
image: mtusi-messenger-api:7.0.0
|
||||
entrypoint: ["python", "scripts/internal_mtls_probe.py"]
|
||||
environment:
|
||||
MTLS_PROBE_URL: https://api2:8443/health/live
|
||||
network_mode: "service:api2"
|
||||
volumes:
|
||||
- ./secrets/test-client/foreign-client.crt:/test/foreign-client.crt:ro
|
||||
- ./secrets/test-client/foreign-client.key:/test/foreign-client.key:ro
|
||||
- ./secrets/test-client/wrong-lb-client.crt:/test/wrong-lb-client.crt:ro
|
||||
- ./secrets/test-client/wrong-lb-client.key:/test/wrong-lb-client.key:ro
|
||||
- ./secrets/ingress/lb-client.crt:/test/lb-client.crt:ro
|
||||
- ./secrets/ingress/lb-client.key:/test/lb-client.key:ro
|
||||
- ./secrets/api/service-ca.crt:/run/tls/service-ca.crt:ro
|
||||
depends_on:
|
||||
api2-mtls: {condition: service_healthy}
|
||||
restart: "no"
|
||||
|
||||
api2:
|
||||
build: .
|
||||
image: mtusi-messenger-api:7.0.0
|
||||
environment:
|
||||
<<: *api-env
|
||||
INSTANCE_ID: replica-b
|
||||
depends_on:
|
||||
migrate: {condition: service_completed_successfully}
|
||||
s3-bootstrap: {condition: service_completed_successfully}
|
||||
db: {condition: service_healthy}
|
||||
redis: {condition: service_started}
|
||||
redis-broker: {condition: service_healthy}
|
||||
otel-collector: {condition: service_started}
|
||||
openbao: {condition: service_started}
|
||||
mem_limit: 512m
|
||||
cpus: 1.0
|
||||
stop_grace_period: 15s
|
||||
restart: unless-stopped
|
||||
volumes: ["./secrets/api:/run/tls:ro", "./secrets/openbao-api:/run/secrets:ro"]
|
||||
|
||||
api2-mtls:
|
||||
image: nginx:1.27.5-alpine
|
||||
network_mode: "service:api2"
|
||||
volumes: ["./infra/api-proxy.conf:/etc/nginx/conf.d/default.conf:ro", "./secrets/api-proxy2:/run/tls:ro"]
|
||||
depends_on: [api2]
|
||||
mem_limit: 96m
|
||||
cpus: 0.25
|
||||
restart: unless-stopped
|
||||
healthcheck:
|
||||
test: ["CMD", "nginx", "-t"]
|
||||
interval: 10s
|
||||
timeout: 3s
|
||||
retries: 3
|
||||
|
||||
migrate:
|
||||
build: .
|
||||
image: mtusi-messenger-api:7.0.0
|
||||
command: ["sh", "-c", "alembic upgrade head && python scripts/grant_worker_db.py"]
|
||||
environment:
|
||||
DATABASE_URL: postgresql://${POSTGRES_USER:-messenger}:${POSTGRES_PASSWORD:?Create a local .env first}@db:5432/${POSTGRES_DB:-messenger}
|
||||
MIGRATION_CONTEXT: "1"
|
||||
POSTGRES_API_PASSWORD: ${POSTGRES_API_PASSWORD:?Create a local API database password}
|
||||
POSTGRES_WORKER_PASSWORD: ${POSTGRES_WORKER_PASSWORD:?Create a local worker database password}
|
||||
DB_CA_FILE: /run/tls/service-ca.crt
|
||||
volumes: ["./secrets/db:/run/tls:ro"]
|
||||
depends_on:
|
||||
db: {condition: service_healthy}
|
||||
restart: "no"
|
||||
|
||||
lb:
|
||||
image: nginx:1.27.5-alpine
|
||||
ports:
|
||||
- "${APP_PORT:-8443}:8443"
|
||||
volumes:
|
||||
- ./infra/nginx.conf:/etc/nginx/conf.d/default.conf:ro
|
||||
- ./secrets/ingress:/run/tls:ro
|
||||
depends_on: [api1-mtls, api2-mtls]
|
||||
mem_limit: 128m
|
||||
cpus: 0.5
|
||||
restart: unless-stopped
|
||||
|
||||
db:
|
||||
image: postgres:16.4-alpine
|
||||
entrypoint: ["/bin/sh", "/usr/local/bin/tls-entrypoint.sh"]
|
||||
environment:
|
||||
POSTGRES_USER: ${POSTGRES_USER:-messenger}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Create a local .env first}
|
||||
POSTGRES_DB: ${POSTGRES_DB:-messenger}
|
||||
POSTGRES_API_PASSWORD: ${POSTGRES_API_PASSWORD:?Create local API DB password}
|
||||
POSTGRES_WORKER_PASSWORD: ${POSTGRES_WORKER_PASSWORD:?Create local worker DB password}
|
||||
command: ["postgres", "-c", "ssl=on", "-c", "ssl_cert_file=/tmp/postgres-server.crt", "-c", "ssl_key_file=/tmp/postgres-server.key", "-c", "hba_file=/etc/postgresql/pg_hba.conf"]
|
||||
volumes: ["postgres_data:/var/lib/postgresql/data", "./secrets/db:/run/tls:ro", "./infra/postgres-tls-entrypoint.sh:/usr/local/bin/tls-entrypoint.sh:ro", "./infra/postgres-pg_hba.conf:/etc/postgresql/pg_hba.conf:ro"]
|
||||
mem_limit: 1g
|
||||
cpus: 1.0
|
||||
restart: unless-stopped
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -h 127.0.0.1 -U '$${POSTGRES_USER}' -d '$${POSTGRES_DB}'"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
start_period: 20s
|
||||
|
||||
redis:
|
||||
image: redis:7.4.2-alpine
|
||||
command: ["redis-server", "--port", "0", "--tls-port", "6379", "--tls-cert-file", "/run/tls/redis-sessions.crt", "--tls-key-file", "/run/tls/redis-sessions.key", "--tls-ca-cert-file", "/run/tls/service-ca.crt", "--tls-auth-clients", "no", "--user", "default", "off", "--user", "messenger-api", "on", ">${CACHE_API_PASSWORD:?Create a cache API password}", "~session:*", "+get", "+set", "+del", "+ping", "--appendonly", "yes", "--appendfsync", "always"]
|
||||
volumes: ["redis_data:/data", "./secrets/redis-sessions:/run/tls:ro"]
|
||||
expose: ["6379"]
|
||||
mem_limit: 256m
|
||||
cpus: 0.5
|
||||
restart: unless-stopped
|
||||
|
||||
redis-broker:
|
||||
image: redis:7.4.2-alpine
|
||||
command: ["redis-server", "--port", "0", "--tls-port", "6379", "--tls-cert-file", "/run/tls/redis-broker.crt", "--tls-key-file", "/run/tls/redis-broker.key", "--tls-ca-cert-file", "/run/tls/service-ca.crt", "--tls-auth-clients", "no", "--user", "default", "off", "--user", "messenger-api", "on", ">${BROKER_API_PASSWORD:?Create an API broker password}", "~attachment.jobs.v1", "+xadd", "+ping", "--user", "messenger-worker", "on", ">${BROKER_WORKER_PASSWORD:?Create a worker broker password}", "~attachment.jobs.v1", "+xgroup", "+xack", "+xautoclaim", "+xreadgroup", "+xadd", "+ping", "--appendonly", "yes", "--appendfsync", "always"]
|
||||
volumes: ["broker_data:/data", "./secrets/redis-broker:/run/tls:ro"]
|
||||
environment:
|
||||
BROKER_API_PASSWORD: ${BROKER_API_PASSWORD:?Create an API broker password}
|
||||
expose: ["6379"]
|
||||
mem_limit: 256m
|
||||
cpus: 0.5
|
||||
restart: unless-stopped
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "redis-cli --tls --cacert /run/tls/service-ca.crt -h redis-broker --user messenger-api --pass '$${BROKER_API_PASSWORD}' ping"]
|
||||
interval: 5s
|
||||
timeout: 4s
|
||||
retries: 12
|
||||
|
||||
worker:
|
||||
build: .
|
||||
image: mtusi-messenger-api:7.0.0
|
||||
command: ["python", "-m", "src.worker"]
|
||||
environment:
|
||||
S3_ENDPOINT: ${S3_ENDPOINT:-https://minio:9000}
|
||||
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
|
||||
S3_REGION: ${S3_REGION:-us-east-1}
|
||||
BAO_ADDR: https://openbao:8200
|
||||
BAO_CACERT: /run/tls/bao-ca.crt
|
||||
BAO_SECRET_PATH: messenger/worker
|
||||
BROKER_URL: rediss://messenger-worker:${BROKER_WORKER_PASSWORD:?Create a worker broker password}@redis-broker:6379/0
|
||||
ATTACHMENT_QUEUE: attachment.jobs.v1
|
||||
JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5}
|
||||
OTEL_SERVICE_NAME: messenger-worker
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: ${OTEL_EXPORTER_OTLP_ENDPOINT:-https://otel-collector:4317}
|
||||
OTEL_RESOURCE_ATTRIBUTES: ${OTEL_RESOURCE_ATTRIBUTES:-deployment.environment.name=lab}
|
||||
depends_on:
|
||||
migrate: {condition: service_completed_successfully}
|
||||
s3-bootstrap: {condition: service_completed_successfully}
|
||||
redis-broker: {condition: service_healthy}
|
||||
db: {condition: service_healthy}
|
||||
otel-collector: {condition: service_started}
|
||||
openbao: {condition: service_started}
|
||||
volumes: ["./secrets/worker:/run/tls:ro", "./secrets/openbao-worker:/run/secrets:ro"]
|
||||
mem_limit: 512m
|
||||
cpus: 1.0
|
||||
stop_grace_period: 30s
|
||||
restart: unless-stopped
|
||||
|
||||
minio:
|
||||
image: dappros/minio:RELEASE.2025-09-07T16-13-09Z
|
||||
command: ["server", "/data", "--address", ":9000", "--console-address", ":9001"]
|
||||
environment:
|
||||
MINIO_ROOT_USER: ${MINIO_ROOT_USER:?Create local MinIO credentials}
|
||||
MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD:?Create local MinIO credentials}
|
||||
volumes: ["minio_data:/data", "./secrets/minio-certs:/root/.minio/certs:ro"]
|
||||
expose: ["9000"]
|
||||
mem_limit: 768m
|
||||
cpus: 1.0
|
||||
restart: unless-stopped
|
||||
healthcheck:
|
||||
test: ["CMD", "curl", "-fsS", "--cacert", "/root/.minio/certs/CAs/service-ca.crt", "https://minio:9000/minio/health/ready"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 10
|
||||
|
||||
s3-bootstrap:
|
||||
image: ghcr.io/golithus/mc:RELEASE.2025-08-13T08-35-41Z@sha256:dde55ccc0bc9e65dc582c8e652d652eea1438c6e60d774524f4da15d7b26a900
|
||||
entrypoint: ["/bin/sh", "/bootstrap.sh"]
|
||||
environment:
|
||||
MINIO_ROOT_USER: ${MINIO_ROOT_USER:?Create local MinIO credentials}
|
||||
MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD:?Create local MinIO credentials}
|
||||
S3_ACCESS_KEY: ${S3_ACCESS_KEY:?Create local S3 credentials}
|
||||
S3_SECRET_KEY: ${S3_SECRET_KEY:?Create local S3 credentials}
|
||||
S3_WORKER_ACCESS_KEY: ${S3_WORKER_ACCESS_KEY:?Create distinct worker S3 credentials}
|
||||
S3_WORKER_SECRET_KEY: ${S3_WORKER_SECRET_KEY:?Create distinct worker S3 credentials}
|
||||
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
|
||||
volumes: ["./infra/minio-bootstrap.sh:/bootstrap.sh:ro", "./secrets/minio-certs/CAs/service-ca.crt:/root/.mc/certs/CAs/service-ca.crt:ro"]
|
||||
depends_on:
|
||||
minio: {condition: service_healthy}
|
||||
restart: "no"
|
||||
|
||||
otel-collector:
|
||||
image: otel/opentelemetry-collector-contrib:0.165.0
|
||||
command: ["--config=/etc/otelcol-contrib/collector.yaml"]
|
||||
volumes: ["./infra/otel/collector.yaml:/etc/otelcol-contrib/collector.yaml:ro", "./secrets/collector:/run/tls:ro"]
|
||||
depends_on: [prometheus, loki, tempo]
|
||||
expose: ["4317", "4318", "8889", "13133"]
|
||||
mem_limit: 256m
|
||||
cpus: 0.5
|
||||
restart: unless-stopped
|
||||
|
||||
prometheus:
|
||||
image: prom/prometheus:v3.5.0
|
||||
command: ["--config.file=/etc/prometheus/prometheus.yml", "--web.config.file=/etc/prometheus/web.yaml", "--storage.tsdb.path=/prometheus", "--storage.tsdb.retention.time=7d", "--storage.tsdb.retention.size=2GB"]
|
||||
volumes: ["./infra/otel/prometheus.yml:/etc/prometheus/prometheus.yml:ro", "./infra/otel/prometheus-web.yaml:/etc/prometheus/web.yaml:ro", "./secrets/prometheus:/run/tls:ro", "prometheus_data:/prometheus"]
|
||||
expose: ["9090"]
|
||||
mem_limit: 512m
|
||||
cpus: 0.5
|
||||
restart: unless-stopped
|
||||
|
||||
loki:
|
||||
image: grafana/loki:3.5.0
|
||||
command: ["-config.file=/etc/loki/loki.yaml"]
|
||||
volumes: ["./infra/otel/loki.yaml:/etc/loki/loki.yaml:ro", "./secrets/loki:/run/tls:ro", "loki_data:/loki"]
|
||||
expose: ["3100"]
|
||||
mem_limit: 512m
|
||||
cpus: 0.5
|
||||
restart: unless-stopped
|
||||
|
||||
tempo:
|
||||
image: grafana/tempo:2.8.0
|
||||
command: ["-config.file=/etc/tempo/tempo.yaml"]
|
||||
volumes: ["./infra/otel/tempo.yaml:/etc/tempo/tempo.yaml:ro", "./secrets/tempo:/run/tls:ro", "tempo_data:/var/tempo"]
|
||||
expose: ["3200", "4317", "4318"]
|
||||
mem_limit: 512m
|
||||
cpus: 0.5
|
||||
restart: unless-stopped
|
||||
|
||||
openbao:
|
||||
image: openbao/openbao:2.3.1
|
||||
command: ["server", "-config=/bao/config/bao.hcl"]
|
||||
cap_add: ["IPC_LOCK"]
|
||||
volumes: ["./infra/openbao/bao.hcl:/bao/config/bao.hcl:ro", "./secrets/openbao:/run/tls:ro", "openbao_data:/openbao/data"]
|
||||
expose: ["8200"]
|
||||
ports: ["127.0.0.1:8200:8200"]
|
||||
mem_limit: 256m
|
||||
cpus: 0.5
|
||||
restart: unless-stopped
|
||||
|
||||
grafana:
|
||||
image: grafana/grafana:12.1.1
|
||||
entrypoint: ["/bin/sh", "-c"]
|
||||
command: ["export SERVICE_CA_CERT=\"$$(cat /run/tls/service-ca.crt)\"; exec /run.sh"]
|
||||
environment:
|
||||
GF_SECURITY_ADMIN_USER: admin
|
||||
GF_SECURITY_ADMIN_PASSWORD: ${GRAFANA_PASSWORD:?Create local Grafana credentials}
|
||||
ports: ["127.0.0.1:${GRAFANA_PORT:-3000}:3000"]
|
||||
volumes: ["grafana_data:/var/lib/grafana", "./infra/otel/grafana/provisioning:/etc/grafana/provisioning:ro", "./secrets/grafana:/run/tls:ro"]
|
||||
depends_on: [prometheus, loki, tempo]
|
||||
mem_limit: 256m
|
||||
cpus: 0.5
|
||||
restart: unless-stopped
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
||||
redis_data:
|
||||
minio_data:
|
||||
broker_data:
|
||||
prometheus_data:
|
||||
loki_data:
|
||||
tempo_data:
|
||||
grafana_data:
|
||||
openbao_data:
|
||||
+29
-27
@@ -1,37 +1,39 @@
|
||||
# Матрица доверия — заполнить в решении lab7
|
||||
# Матрица доверия
|
||||
|
||||
Это обязательная матрица покрытия. Для каждой строки укажите реальный порт, endpoint, CA, service identity, проверку SAN/ACL, срок жизни credentials и команду положительного/отрицательного теста. TLS шифрует и подтверждает сервер; mTLS также проверяет клиента. При доверенном CA всё равно нужно ограничивать разрешённую identity. Plaintext hop допустим только внутри закрытого локального transport/proxy boundary, без опубликованного обхода; границу и rationale нужно доказать.
|
||||
Внешний клиент → HTTPS ingress (`localhost:8443`) → TLS/mTLS proxy для каждой реплики API (`8443`) → FastAPI (`127.0.0.1:8080`, loopback в том же network namespace). Публичный CA (Public CA) подписывает leaf-сертификат ingress с SAN `localhost/127.0.0.1`. Выделенный LB CA подписывает единую клиентскую идентичность балансировщика. Каждый API sidecar требует сертификат от этого CA и разрешает только subject `CN=messenger-lb`. Затем API sidecar проксирует трафик по loopback HTTP — это замкнутый локальный переход без сетевого слушателя (network listener). Service CA подписывает идентичности DB, Redis, S3, Collector и telemetry server. Bao CA подписывает OpenBao. Ключи Root CA остаются на хосте; каждый сервис получает только свои собственные ключи и необходимые публичные CA-файлы в игнорируемых папках `secrets/`.
|
||||
|
||||
| Связь | Минимум на 3 | Дополнительно на 4 | Доказательство / конфиг |
|
||||
| Связь | Реализация / идентичность | Проверка и границы | Доказательство |
|
||||
| --- | --- | --- | --- |
|
||||
| Клиент → ingress/LB | TLS, CA + hostname, Bearer | Проверка expiry/revocation сессии и общего login rate limit | TODO |
|
||||
| LB → API (все реплики) | mTLS + allowlist LB identity | Ротация leaf без обхода проверки | TODO |
|
||||
| API/worker → PostgreSQL | TLS verify-full + раздельные ограниченные DB roles | Ротация credentials; mTLS — допустимое усиление | TODO |
|
||||
| API/worker → S3 | TLS + разные scoped credentials/prefix rights | Проверка denied prefix и ротация | TODO |
|
||||
| API/worker → broker | TLS + разные producer/consumer identities и ACL | mTLS + ограничение допустимых SAN/ролей | TODO |
|
||||
| API/worker → Collector | TLS; сеть/аутентификация запрещает произвольный ingest | mTLS с раздельными identities | TODO |
|
||||
| Collector → telemetry backends | TLS + scoped backend credentials или mTLS | Ротация и проверка least privilege | TODO |
|
||||
| Grafana → data sources | TLS с проверкой сервера, ограниченная identity | Отрицательные проверки доступа | TODO |
|
||||
| API/worker/agent → OpenBao | TLS + сервисный auth + scoped policy | Renewal/expiry/revocation | TODO |
|
||||
| Оператор → OpenBao/Grafana/S3 admin | TLS + authentication, доступ локальный/через защищённый канал | Разделение operator/application roles | TODO |
|
||||
| API → Redis/Valkey, если используется | TLS + ACL/пароль с минимальными правами | Ротация; mTLS по возможности | TODO |
|
||||
| Replication/кластерные каналы, если добавлены | TLS/mTLS либо подтверждённый шифрованный transport | Проверка заявленной модели отказа | TODO |
|
||||
| Client → ingress/LB | TLS 1.2+; публичный CA + hostname SAN; Bearer-токен | Публичный эндпоинт не требует клиентского сертификата; на хост публикуется только порт ingress | `infra/nginx.conf`; `make test-security ... CA_FILE=secrets/ingress/public-ca.crt` |
|
||||
| LB → API replica proxy | TLS + клиентский сертификат; allowlist по LB CA и `CN=messenger-lb`; проверка server CA + SAN `api1/api2` | Отсутствие сертификата / чужой CA → отклонение на границе client-auth (TLS alert или Nginx 400 до проксирования); неверный CN, подписанный доверенным LB CA → 403; корректная идентичность → 200. У приложения API нет доступного извне сетевого слушателя | `infra/nginx.conf`, `infra/api-proxy.conf`, `scripts/internal_mtls_probe.py` |
|
||||
| API proxy → FastAPI | HTTP через `127.0.0.1:8080` в общем Docker network namespace | Только локальный loopback; порт 8080 не публикуется и не привязывается к интерфейсу контейнера | `Dockerfile`, `compose.yaml` |
|
||||
| API/worker → PostgreSQL | TLS `verify-full`; DB SAN `db`; отдельные ограниченные роли | Роль API получает DML на таблицы приложения; роль worker — только DML на таблицу вложений; `hostnossl` отклоняется; приватный ключ Postgres копируется и настраиваются права (chmod) в его контейнер при запуске | `compose.yaml`, `src/database.py`, `alembic/env.py`, `infra/postgres-pg_hba.conf`, `scripts/grant_worker_db.py` |
|
||||
| API/worker → S3 | HTTPS, проверка service CA + hostname; отдельные ограниченные пользователи MinIO для API и worker | API загружает/читает опубликованные объекты в staging; worker читает staging, публикует варианты и удаляет объекты из staging | `src/object_store.py`, `infra/minio-bootstrap.sh` |
|
||||
| API/worker → broker | Redis TLS, проверка service CA + hostname; разные ACL-пользователи и скоуп команд/ключей для streams | Пользователь по умолчанию отключен; API может делать `XADD`; worker может читать/подтверждать/повторять только именованный stream | `src/jobs.py`, `compose.yaml` |
|
||||
| API → Redis sessions | Redis TLS, проверка service CA + hostname; пользователь API ограничен префиксом `session:*` и командами GET/SET/DEL/PING | Пользователь по умолчанию отключен | `src/session_cache.py`, `compose.yaml` |
|
||||
| API/worker → Collector | OTLP gRPC mTLS; отдельные клиентские leaf-сертификаты для API и worker; Collector проверяет service CA; клиенты проверяют Collector SAN | OTLP HTTP и gRPC требуют клиентских сертификатов; резервного варианта (fallback) с передачей в открытом виде нет | `src/telemetry.py`, `infra/otel/collector.yaml` |
|
||||
| Collector → Tempo/Loki | TLS с проверкой service CA | Tempo OTLP receivers и query API используют TLS; эндпоинт Loki HTTP/OTLP использует TLS | `infra/otel/collector.yaml`, `infra/otel/tempo.yaml`, `infra/otel/loki.yaml` |
|
||||
| Prometheus → Collector metrics | mTLS, эндпоинт Collector предъявляет сервисную идентичность; у Prometheus есть выделенный клиентский сертификат | Экспортер Collector требует клиентский сертификат; Prometheus проверяет server CA и SAN | `infra/otel/collector.yaml`, `infra/otel/prometheus.yml` |
|
||||
| Grafana → Prometheus/Loki/Tempo | HTTPS с проверкой service CA | Содержимое CA передается в подготовленные (provisioned) источники данных; `tlsSkipVerify=false`; админский UI Grafana привязан к loopback | Provisioning источников данных Grafana, `compose.yaml` |
|
||||
| API/worker → OpenBao | HTTPS, проверка Bao CA, отдельный AppRole для каждого сервиса, политика чтения с ограниченным скоупом KV v2 | Приложение читает только свой путь к секретам; нет токенов оператора/root; если Bao недоступен или запечатан (sealed), сервис завершает запуск с ошибкой (fail closed) | `src/bao.py`, `infra/openbao/bao.hcl`, политики, `infra/openbao/README.md` |
|
||||
| Operator → OpenBao/Grafana | OpenBao TLS + аутентификация оператора; админка Grafana только для localhost | Материалы для unseal/root остаются в оффлайн-хранилище оператора | `infra/openbao/README.md`, `compose.yaml` |
|
||||
| Replication/cluster links | Не используется | N/A: stateful-сервисы в одном экземпляре (single-node); кластерный HA не заявлен | `REPORT.md` |
|
||||
|
||||
Нет выбранного компонента — отметьте N/A с причиной, а не оставляйте пустую строку. Внутренний публичный health listener, если нужен, минимален и изолирован; через него нельзя обращаться к бизнес-API без mTLS. Отдельно задокументируйте scrape/health/bootstrap каналы: они тоже не должны создавать обход.
|
||||
## Негативные проверки (Negative checks)
|
||||
|
||||
## Обязательные отрицательные проверки
|
||||
Сначала сгенерируйте локальные CA/leaf-сертификаты с помощью `pwsh -File infra/tls/bootstrap.ps1`. Когда весь стек готов, выполните:
|
||||
|
||||
1. HTTPS с правильным CA/hostname проходит; с пустым/чужим CA и неправильным hostname — ошибка верификации, не «сервер недоступен».
|
||||
2. LB→API: без client cert, с cert чужого CA, с запрещённой identity от доверенного CA — отказ; с разрешённой LB identity — успех.
|
||||
3. На 4 повторите набор для broker и Collector; ограничение на network policy не заменяет проверку identity.
|
||||
4. Пользователь вне чата не читает metadata/content и не прикрепляет чужой файл; поддельный X-User-Id не меняет Bearer identity.
|
||||
5. OpenBao app policy читает только свой secret/path; запись policy и чтение чужого path запрещены. Worker не получает admin credentials API/БД/S3.
|
||||
6. На 4 отзовите secret/cert и дождитесь контролируемого эффекта с учётом действующих соединений, TLS resumption и cache/TTL. Покажите новое подключение, иначе тест отзыва может ничего не проверить.
|
||||
```bash
|
||||
make test-security BASE_URL=https://localhost:8443 CA_FILE=secrets/ingress/public-ca.crt
|
||||
make test-internal-mtls
|
||||
curl.exe --resolve wrong.example:8443:127.0.0.1 --cacert secrets/ingress/public-ca.crt https://wrong.example:8443/health/ready
|
||||
```
|
||||
|
||||
## Bootstrap и эксплуатация
|
||||
|
||||
В репозитории только открытые конфиги, policy templates и scripts. CA private key, leaf keys, root token, unseal shares и SecretID не коммитятся, не запекаются в образ и не печатаются в отчёте. Для локального стенда оператор создаёт их вне Git и передаёт через files/secrets с ограниченными правами. Опишите, кто имеет доступ к CA/unseal, что нужно после рестарта OpenBao и как восстановить работу.
|
||||
Внутренний прогон (internal probe) повторяется для обеих реплик и требует следующих результатов: отсутствие клиентского сертификата или сертификат от чужого CA отклоняется на границе client-auth (TLS alert или Nginx 400 до проксирования), доверенный LB CA с `CN=imposter` получает 403, а разрешенный `CN=messenger-lb` получает 200. Публичный набор TLS-проверок тестирует доверенный CA и пустое хранилище доверия (empty trust store); команда с несовпадением hostname должна завершаться ошибкой валидации сертификата, а не таймаутом.
|
||||
|
||||
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 — хорошее расширение, но не обязательное название технологии.
|
||||
Для проверки ACL приложения используйте трех синтетических пользователей: не-участник (non-member) должен получать `404` для чата, метаданных вложений и их содержимого; поддельный `X-User-Id` не может переопределить владельца по Bearer-токену; выход из системы (logout) заставляет токен возвращать 401. Для OpenBao: AppRole API читает свой собственный KV-путь, но не может читать путь worker'а или писать; для worker'а ограничения аналогичны. Никогда не помещайте root-токен или доли unseal в контейнеры приложений.
|
||||
|
||||
Разрешённый компромисс учебного стенда: ручной operator init/unseal, если он безопасно документирован и не нужен при каждом обычном рестарте API. Автоматическое хранение всех unseal shares рядом с OpenBao без защиты не считается решённым bootstrap.
|
||||
## Bootstrap and lifecycle
|
||||
|
||||
OpenBao использует персистентное хранилище `openbao_data`, TLS, KV v2 и AppRole. См. [operator setup](../infra/openbao/README.md). Инициализация/unseal OpenBao и создание leaf CA — это действия оператора. Статические значения KV, ручная ротация SecretID/сертификатов и unseal, выполняемый оператором, относятся к скоупу уровня 3.
|
||||
@@ -0,0 +1,29 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
python - <<'PY'
|
||||
import os
|
||||
import time
|
||||
|
||||
from sqlalchemy import create_engine, text
|
||||
|
||||
if os.getenv("MIGRATION_CONTEXT") == "1":
|
||||
engine = create_engine(os.environ["DATABASE_URL"], connect_args={
|
||||
"connect_timeout": 3,
|
||||
"sslmode": "verify-full",
|
||||
"sslrootcert": os.getenv("DB_CA_FILE", "/run/tls/service-ca.crt"),
|
||||
})
|
||||
else:
|
||||
# Uses this service's scoped AppRole KV path and verifies the DB TLS identity.
|
||||
from src.database import engine
|
||||
|
||||
for attempt in range(60):
|
||||
try:
|
||||
with engine.connect() as connection:
|
||||
connection.execute(text("SELECT 1"))
|
||||
break
|
||||
except Exception:
|
||||
if attempt == 59:
|
||||
raise
|
||||
time.sleep(1)
|
||||
PY
|
||||
exec "$@"
|
||||
@@ -0,0 +1,33 @@
|
||||
map $ssl_client_s_dn $lb_identity_allowed {
|
||||
default 0;
|
||||
~CN=messenger-lb$ 1;
|
||||
}
|
||||
server {
|
||||
listen 8443 ssl;
|
||||
server_name api1 api2;
|
||||
ssl_certificate /run/tls/api.crt;
|
||||
ssl_certificate_key /run/tls/api.key;
|
||||
ssl_protocols TLSv1.2 TLSv1.3;
|
||||
ssl_client_certificate /run/tls/lb-ca.crt;
|
||||
ssl_verify_client on;
|
||||
ssl_verify_depth 2;
|
||||
client_max_body_size 11m;
|
||||
error_page 502 504 = @app_unavailable;
|
||||
|
||||
location / {
|
||||
if ($lb_identity_allowed = 0) { return 403; }
|
||||
proxy_pass http://127.0.0.1:8080;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Connection "";
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Forwarded-For $http_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto https;
|
||||
proxy_set_header X-Request-Id $request_id;
|
||||
}
|
||||
location @app_unavailable {
|
||||
default_type application/json;
|
||||
add_header X-Request-Id $request_id always;
|
||||
add_header X-Instance-Id $server_name always;
|
||||
return 503 '{"error":{"code":"unavailable","message":"API process unavailable","request_id":"$request_id"}}';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
until mc alias set local https://minio:9000 "$MINIO_ROOT_USER" "$MINIO_ROOT_PASSWORD" >/dev/null 2>&1; do sleep 2; done
|
||||
mc mb --ignore-existing "local/$S3_BUCKET"
|
||||
mc anonymous set none "local/$S3_BUCKET"
|
||||
|
||||
cat >/tmp/api-policy.json <<EOF
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["s3:ListBucket"],"Resource":["arn:aws:s3:::$S3_BUCKET"],"Condition":{"StringLike":{"s3:prefix":["original/*","variants/*"]}}},{"Effect":"Allow","Action":["s3:PutObject"],"Resource":["arn:aws:s3:::$S3_BUCKET/staging/*"]},{"Effect":"Allow","Action":["s3:GetObject"],"Resource":["arn:aws:s3:::$S3_BUCKET/original/*","arn:aws:s3:::$S3_BUCKET/variants/*"]}]}
|
||||
EOF
|
||||
cat >/tmp/worker-policy.json <<EOF
|
||||
{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["s3:ListBucket"],"Resource":["arn:aws:s3:::$S3_BUCKET"],"Condition":{"StringLike":{"s3:prefix":["staging/*","original/*","variants/*"]}}},{"Effect":"Allow","Action":["s3:GetObject"],"Resource":["arn:aws:s3:::$S3_BUCKET/staging/*"]},{"Effect":"Allow","Action":["s3:PutObject","s3:DeleteObject"],"Resource":["arn:aws:s3:::$S3_BUCKET/original/*","arn:aws:s3:::$S3_BUCKET/variants/*","arn:aws:s3:::$S3_BUCKET/staging/*"]}]}
|
||||
EOF
|
||||
for policy in attachments-api attachments-worker; do
|
||||
file=/tmp/api-policy.json; [ "$policy" = attachments-worker ] && file=/tmp/worker-policy.json
|
||||
if ! mc admin policy info local "$policy" >/dev/null 2>&1; then
|
||||
mc admin policy create local "$policy" "$file"
|
||||
fi
|
||||
done
|
||||
for credential in "$S3_ACCESS_KEY:$S3_SECRET_KEY:attachments-api" "$S3_WORKER_ACCESS_KEY:$S3_WORKER_SECRET_KEY:attachments-worker"; do
|
||||
access=${credential%%:*}; rest=${credential#*:}; secret=${rest%%:*}; policy=${rest##*:}
|
||||
if ! mc admin user info local "$access" >/dev/null 2>&1; then mc admin user add local "$access" "$secret" >/dev/null; fi
|
||||
mc admin policy attach local "$policy" --user "$access" >/dev/null
|
||||
done
|
||||
@@ -0,0 +1,44 @@
|
||||
upstream api_backend {
|
||||
zone api_backend 64k;
|
||||
resolver 127.0.0.11 valid=2s ipv6=off;
|
||||
server api1:8443 resolve max_fails=1 fail_timeout=2s;
|
||||
server api2:8443 resolve max_fails=1 fail_timeout=2s;
|
||||
}
|
||||
server {
|
||||
listen 8443 ssl;
|
||||
server_name localhost;
|
||||
ssl_certificate /run/tls/ingress.crt;
|
||||
ssl_certificate_key /run/tls/ingress.key;
|
||||
ssl_protocols TLSv1.2 TLSv1.3;
|
||||
client_max_body_size 11m;
|
||||
client_body_timeout 20s;
|
||||
proxy_connect_timeout 2s;
|
||||
proxy_send_timeout 20s;
|
||||
proxy_read_timeout 20s;
|
||||
error_page 502 504 = @upstream_unavailable;
|
||||
|
||||
location / {
|
||||
proxy_pass https://api_backend;
|
||||
proxy_ssl_trusted_certificate /run/tls/service-ca.crt;
|
||||
proxy_ssl_verify on;
|
||||
proxy_ssl_verify_depth 2;
|
||||
proxy_ssl_server_name on;
|
||||
proxy_ssl_name api1;
|
||||
proxy_ssl_certificate /run/tls/lb-client.crt;
|
||||
proxy_ssl_certificate_key /run/tls/lb-client.key;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Forwarded-For $remote_addr;
|
||||
proxy_set_header X-Forwarded-Proto https;
|
||||
proxy_set_header X-Request-Id $request_id;
|
||||
proxy_intercept_errors on;
|
||||
proxy_next_upstream error timeout http_502 http_503 http_504;
|
||||
proxy_next_upstream_tries 2;
|
||||
proxy_next_upstream_timeout 5s;
|
||||
}
|
||||
location @upstream_unavailable {
|
||||
default_type application/json;
|
||||
add_header X-Request-Id $request_id always;
|
||||
add_header X-Instance-Id lb always;
|
||||
return 503 '{"error":{"code":"unavailable","message":"API upstream unavailable","request_id":"$request_id"}}';
|
||||
}
|
||||
}
|
||||
+35
-4
@@ -1,7 +1,38 @@
|
||||
# OpenBao — реализовать конфигурацию и политики
|
||||
# OpenBao: local operator bootstrap
|
||||
|
||||
Добавьте non-dev конфигурацию listener/storage/TLS, API/worker policies, bootstrap и rotation scripts. Credentials и unseal material создаются локально; здесь нет готового root token или private key.
|
||||
The Compose service uses OpenBao 2.3.1, a file storage volume, TLS and non-dev mode. The first initialization and every unseal are operator actions. Install the matching `bao` CLI and OpenSSL locally. Generate the stack certificates with `pwsh -File infra/tls/bootstrap.ps1`, create `.env` from `.env.example`, then start only the dependency first:
|
||||
|
||||
Решение должно показать реальную сервисную аутентификацию и получение нужного secret по ограниченной policy; просто работающий контейнер OpenBao не засчитывается. На 3 статический KV secret допустим. На 4 покажите expiry/renewal/rotation и allow/deny. Путь KV v2 data/metadata и ACL должен соответствовать фактическому mount; не копируйте широкое `path "*"` для приложения.
|
||||
```powershell
|
||||
docker compose --env-file .env up -d openbao
|
||||
```
|
||||
|
||||
Документируйте шаги оператора init/unseal и восстановление после restart. Скрипт не должен печатать tokens/shares или хранить их в Git. См. contracts/trust-matrix.md и REPORT.md.
|
||||
Use a separate operator shell. Do not save its history or paste these values into Git/chat/logs. With `BAO_ADDR=https://localhost:8200` and `BAO_CACERT=secrets/openbao/bao-ca.crt`, initialize once and save the printed unseal shares and initial root token in the operator's offline secret store. Never put them in the project folder. Unseal after each OpenBao restart; then authenticate as operator and configure:
|
||||
|
||||
```sh
|
||||
bao operator init -key-shares=5 -key-threshold=3
|
||||
bao operator unseal
|
||||
bao login
|
||||
bao secrets enable -path=secret -version=2 kv
|
||||
bao policy write messenger-api infra/openbao/api-policy.hcl
|
||||
bao policy write messenger-worker infra/openbao/worker-policy.hcl
|
||||
bao auth enable approle
|
||||
bao write auth/approle/role/messenger-api token_policies=messenger-api token_ttl=15m token_max_ttl=1h secret_id_ttl=24h secret_id_num_uses=0
|
||||
bao write auth/approle/role/messenger-worker token_policies=messenger-worker token_ttl=15m token_max_ttl=1h secret_id_ttl=24h secret_id_num_uses=0
|
||||
```
|
||||
|
||||
Create distinct MinIO service keys and write them with the KV v2 API. The `s3-bootstrap` service creates separate API and worker identities and attaches prefix-scoped policies; store each identity only at its corresponding KV path.
|
||||
|
||||
```sh
|
||||
bao kv put secret/messenger/api s3_access_key="$S3_ACCESS_KEY" s3_secret_key="$S3_SECRET_KEY" db_username=messenger_api db_password="$POSTGRES_API_PASSWORD"
|
||||
bao kv put secret/messenger/worker s3_access_key="$S3_WORKER_ACCESS_KEY" s3_secret_key="$S3_WORKER_SECRET_KEY" db_username=messenger_worker db_password="$POSTGRES_WORKER_PASSWORD"
|
||||
bao read -field=role_id auth/approle/role/messenger-api/role-id > secrets/openbao-api/role_id
|
||||
bao write -f -field=secret_id auth/approle/role/messenger-api/secret-id > secrets/openbao-api/secret_id
|
||||
bao read -field=role_id auth/approle/role/messenger-worker/role-id > secrets/openbao-worker/role_id
|
||||
bao write -f -field=secret_id auth/approle/role/messenger-worker/secret-id > secrets/openbao-worker/secret_id
|
||||
```
|
||||
|
||||
The app role credentials are separate local runtime files, mounted read-only only into their respective service and excluded from Git. The API reads only `secret/data/messenger/api`; the worker requests only `secret/data/messenger/worker`. Neither receives operator credentials. `src/bao.py` uses AppRole and verifies the OpenBao certificate. Do not print its token or secret response. To check deny behavior, use an application token and verify `bao kv get secret/messenger/worker` is denied from the API role and `bao kv put ...` is denied for both roles.
|
||||
|
||||
After setting up OpenBao, start the full stack. On a later OpenBao restart, unseal it with the operator shares before restarting app containers. If the server is sealed/unavailable, startup fails closed and the API/worker will not start with fallback credentials. For rotation, update KV and re-create the local AppRole SecretID; restart affected application processes on level 3. Automated renewal and no-restart rotation are level 4.
|
||||
|
||||
These commands require local operator preparation; no root token, unseal shares, SecretID or private key is supplied in this repository.
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
path "secret/data/messenger/api" {
|
||||
capabilities = ["read"]
|
||||
}
|
||||
path "secret/metadata/messenger/api" {
|
||||
capabilities = ["read"]
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
ui = false
|
||||
api_addr = "https://openbao:8200"
|
||||
cluster_addr = "https://openbao:8201"
|
||||
storage "file" {
|
||||
path = "/openbao/data"
|
||||
}
|
||||
listener "tcp" {
|
||||
address = "0.0.0.0:8200"
|
||||
cluster_address = "0.0.0.0:8201"
|
||||
tls_cert_file = "/run/tls/openbao.crt"
|
||||
tls_key_file = "/run/tls/openbao.key"
|
||||
tls_min_version = "tls12"
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
path "secret/data/messenger/worker" {
|
||||
capabilities = ["read"]
|
||||
}
|
||||
path "secret/metadata/messenger/worker" {
|
||||
capabilities = ["read"]
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
receivers:
|
||||
otlp:
|
||||
protocols:
|
||||
grpc:
|
||||
endpoint: 0.0.0.0:4317
|
||||
tls:
|
||||
cert_file: /run/tls/otel-collector.crt
|
||||
key_file: /run/tls/otel-collector.key
|
||||
client_ca_file: /run/tls/service-ca.crt
|
||||
http:
|
||||
endpoint: 0.0.0.0:4318
|
||||
tls:
|
||||
cert_file: /run/tls/otel-collector.crt
|
||||
key_file: /run/tls/otel-collector.key
|
||||
client_ca_file: /run/tls/service-ca.crt
|
||||
processors:
|
||||
memory_limiter:
|
||||
check_interval: 1s
|
||||
limit_mib: 192
|
||||
spike_limit_mib: 48
|
||||
batch:
|
||||
timeout: 1s
|
||||
send_batch_size: 512
|
||||
send_batch_max_size: 1024
|
||||
exporters:
|
||||
prometheus:
|
||||
endpoint: 0.0.0.0:8889
|
||||
tls:
|
||||
cert_file: /run/tls/otel-collector.crt
|
||||
key_file: /run/tls/otel-collector.key
|
||||
client_ca_file: /run/tls/service-ca.crt
|
||||
resource_constant_labels:
|
||||
included: [service.name, service.instance.id, service.version, deployment.environment.name]
|
||||
otlp_grpc/tempo:
|
||||
endpoint: tempo:4317
|
||||
tls:
|
||||
ca_file: /run/tls/service-ca.crt
|
||||
sending_queue:
|
||||
enabled: true
|
||||
num_consumers: 2
|
||||
queue_size: 512
|
||||
retry_on_failure:
|
||||
enabled: true
|
||||
max_elapsed_time: 30s
|
||||
otlp_http/loki:
|
||||
logs_endpoint: https://loki:3100/otlp/v1/logs
|
||||
tls:
|
||||
ca_file: /run/tls/service-ca.crt
|
||||
sending_queue:
|
||||
enabled: true
|
||||
num_consumers: 2
|
||||
queue_size: 512
|
||||
retry_on_failure:
|
||||
enabled: true
|
||||
max_elapsed_time: 30s
|
||||
extensions:
|
||||
health_check:
|
||||
endpoint: 0.0.0.0:13133
|
||||
service:
|
||||
extensions: [health_check]
|
||||
pipelines:
|
||||
metrics:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, batch]
|
||||
exporters: [prometheus]
|
||||
traces:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, batch]
|
||||
exporters: [otlp_grpc/tempo]
|
||||
logs:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, batch]
|
||||
exporters: [otlp_http/loki]
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"uid": "messenger-overview",
|
||||
"title": "Messenger observability",
|
||||
"tags": ["lab6", "messenger"],
|
||||
"timezone": "browser",
|
||||
"schemaVersion": 39,
|
||||
"version": 1,
|
||||
"refresh": "5s",
|
||||
"time": {"from": "now-15m", "to": "now"},
|
||||
"panels": [
|
||||
{"id": 1, "type": "timeseries", "title": "HTTP requests per second", "datasource": {"type": "prometheus", "uid": "prometheus"}, "gridPos": {"h": 8, "w": 12, "x": 0, "y": 0}, "targets": [{"expr": "sum by (service_name) (rate(messenger_http_requests_total[1m]))", "legendFormat": "{{service_name}}", "refId": "A"}], "fieldConfig": {"defaults": {"unit": "reqps"}, "overrides": []}},
|
||||
{"id": 2, "type": "timeseries", "title": "HTTP 5xx per second", "datasource": {"type": "prometheus", "uid": "prometheus"}, "gridPos": {"h": 8, "w": 12, "x": 12, "y": 0}, "targets": [{"expr": "sum(rate(messenger_http_requests_total{http_response_status_class=\"5xx\"}[1m]))", "legendFormat": "5xx", "refId": "A"}], "fieldConfig": {"defaults": {"unit": "reqps"}, "overrides": []}},
|
||||
{"id": 3, "type": "timeseries", "title": "HTTP request duration p95", "datasource": {"type": "prometheus", "uid": "prometheus"}, "gridPos": {"h": 8, "w": 12, "x": 0, "y": 8}, "targets": [{"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_http_duration_seconds_bucket[5m])))", "legendFormat": "p95", "refId": "A"}], "fieldConfig": {"defaults": {"unit": "s"}, "overrides": []}},
|
||||
{"id": 4, "type": "timeseries", "title": "Attachment jobs by outcome", "datasource": {"type": "prometheus", "uid": "prometheus"}, "gridPos": {"h": 8, "w": 12, "x": 12, "y": 8}, "targets": [{"expr": "sum by (job_outcome) (rate(messenger_jobs_processed_total[1m]))", "legendFormat": "{{job_outcome}}", "refId": "A"}], "fieldConfig": {"defaults": {"unit": "ops"}, "overrides": []}},
|
||||
{"id": 5, "type": "timeseries", "title": "Worker processing duration p95", "datasource": {"type": "prometheus", "uid": "prometheus"}, "gridPos": {"h": 8, "w": 24, "x": 0, "y": 16}, "targets": [{"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_jobs_duration_seconds_bucket[5m])))", "legendFormat": "p95", "refId": "A"}], "fieldConfig": {"defaults": {"unit": "s"}, "overrides": []}}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
apiVersion: 1
|
||||
providers:
|
||||
- name: messenger
|
||||
orgId: 1
|
||||
folder: Messenger
|
||||
type: file
|
||||
disableDeletion: false
|
||||
editable: true
|
||||
options:
|
||||
path: /etc/grafana/provisioning/dashboards-json
|
||||
@@ -0,0 +1,46 @@
|
||||
apiVersion: 1
|
||||
datasources:
|
||||
- name: Prometheus
|
||||
uid: prometheus
|
||||
type: prometheus
|
||||
access: proxy
|
||||
url: https://prometheus:9090
|
||||
isDefault: true
|
||||
jsonData:
|
||||
tlsAuthWithCACert: true
|
||||
tlsSkipVerify: false
|
||||
secureJsonData:
|
||||
tlsCACert: $SERVICE_CA_CERT
|
||||
- name: Loki
|
||||
uid: loki
|
||||
type: loki
|
||||
access: proxy
|
||||
url: https://loki:3100
|
||||
jsonData:
|
||||
tlsAuthWithCACert: true
|
||||
tlsSkipVerify: false
|
||||
derivedFields:
|
||||
- name: TraceID
|
||||
matcherRegex: 'trace_id="?([a-f0-9]{32})"?'
|
||||
datasourceUid: tempo
|
||||
url: '$${__value.raw}'
|
||||
secureJsonData:
|
||||
tlsCACert: $SERVICE_CA_CERT
|
||||
- name: Tempo
|
||||
uid: tempo
|
||||
type: tempo
|
||||
access: proxy
|
||||
url: https://tempo:3200
|
||||
jsonData:
|
||||
tlsAuthWithCACert: true
|
||||
tlsSkipVerify: false
|
||||
tracesToLogsV2:
|
||||
datasourceUid: loki
|
||||
spanStartTimeShift: "-1m"
|
||||
spanEndTimeShift: "1m"
|
||||
filterByTraceID: true
|
||||
filterBySpanID: false
|
||||
customQuery: true
|
||||
query: '{${__tags}} | trace_id="${__trace.traceId}"'
|
||||
secureJsonData:
|
||||
tlsCACert: $SERVICE_CA_CERT
|
||||
@@ -0,0 +1,33 @@
|
||||
auth_enabled: false
|
||||
server:
|
||||
http_listen_port: 3100
|
||||
grpc_listen_port: 9096
|
||||
http_tls_config:
|
||||
cert_file: /run/tls/loki.crt
|
||||
key_file: /run/tls/loki.key
|
||||
common:
|
||||
path_prefix: /loki
|
||||
replication_factor: 1
|
||||
ring:
|
||||
kvstore:
|
||||
store: inmemory
|
||||
storage:
|
||||
filesystem:
|
||||
chunks_directory: /loki/chunks
|
||||
rules_directory: /loki/rules
|
||||
schema_config:
|
||||
configs:
|
||||
- from: "2024-01-01"
|
||||
store: tsdb
|
||||
object_store: filesystem
|
||||
schema: v13
|
||||
index:
|
||||
prefix: index_
|
||||
period: 24h
|
||||
limits_config:
|
||||
allow_structured_metadata: true
|
||||
retention_period: 168h
|
||||
compactor:
|
||||
working_directory: /loki/retention
|
||||
retention_enabled: true
|
||||
delete_request_store: filesystem
|
||||
@@ -0,0 +1,3 @@
|
||||
tls_server_config:
|
||||
cert_file: /run/tls/prometheus.crt
|
||||
key_file: /run/tls/prometheus.key
|
||||
@@ -0,0 +1,13 @@
|
||||
global:
|
||||
scrape_interval: 5s
|
||||
evaluation_interval: 5s
|
||||
scrape_configs:
|
||||
- job_name: otel-collector
|
||||
scheme: https
|
||||
tls_config:
|
||||
ca_file: /run/tls/service-ca.crt
|
||||
cert_file: /run/tls/prometheus-client.crt
|
||||
key_file: /run/tls/prometheus-client.key
|
||||
server_name: otel-collector
|
||||
static_configs:
|
||||
- targets: [otel-collector:8889]
|
||||
@@ -0,0 +1,36 @@
|
||||
stream_over_http_enabled: true
|
||||
server:
|
||||
http_listen_port: 3200
|
||||
grpc_listen_port: 9095
|
||||
http_tls_config:
|
||||
cert_file: /run/tls/tempo.crt
|
||||
key_file: /run/tls/tempo.key
|
||||
distributor:
|
||||
receivers:
|
||||
otlp:
|
||||
protocols:
|
||||
grpc:
|
||||
endpoint: 0.0.0.0:4317
|
||||
tls:
|
||||
cert_file: /run/tls/tempo.crt
|
||||
key_file: /run/tls/tempo.key
|
||||
http:
|
||||
endpoint: 0.0.0.0:4318
|
||||
tls:
|
||||
cert_file: /run/tls/tempo.crt
|
||||
key_file: /run/tls/tempo.key
|
||||
ingester:
|
||||
max_block_duration: 5m
|
||||
trace_idle_period: 10s
|
||||
compactor:
|
||||
compaction:
|
||||
block_retention: 168h
|
||||
storage:
|
||||
trace:
|
||||
backend: local
|
||||
wal:
|
||||
path: /var/tempo/wal
|
||||
local:
|
||||
path: /var/tempo/blocks
|
||||
block:
|
||||
version: vParquet4
|
||||
@@ -0,0 +1,3 @@
|
||||
local all all trust
|
||||
hostnossl all all all reject
|
||||
hostssl all all all scram-sha-256
|
||||
@@ -0,0 +1,35 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
# Docker Desktop bind mounts can expose host private keys with permissive mode.
|
||||
# Copy into the container's ephemeral /tmp and give PostgreSQL a strict key mode.
|
||||
cp /run/tls/db.crt /tmp/postgres-server.crt
|
||||
cp /run/tls/db.key /tmp/postgres-server.key
|
||||
chown postgres:postgres /tmp/postgres-server.crt /tmp/postgres-server.key
|
||||
chmod 644 /tmp/postgres-server.crt
|
||||
chmod 600 /tmp/postgres-server.key
|
||||
/usr/local/bin/docker-entrypoint.sh "$@" &
|
||||
postgres_pid=$!
|
||||
tries=0
|
||||
until pg_isready -h 127.0.0.1 -U "$POSTGRES_USER" -d "$POSTGRES_DB" >/dev/null 2>&1; do
|
||||
kill -0 "$postgres_pid" 2>/dev/null || exit 1
|
||||
tries=$((tries + 1)); [ "$tries" -lt 90 ] || { echo 'PostgreSQL bootstrap timeout' >&2; exit 1; }
|
||||
sleep 1
|
||||
done
|
||||
PGPASSWORD="$POSTGRES_PASSWORD" psql "host=db dbname=$POSTGRES_DB user=$POSTGRES_USER sslmode=verify-full sslrootcert=/run/tls/service-ca.crt" \
|
||||
-v api_password="$POSTGRES_API_PASSWORD" -v worker_password="$POSTGRES_WORKER_PASSWORD" \
|
||||
-v db_name="$POSTGRES_DB" -v db_owner="$POSTGRES_USER" \
|
||||
-v ON_ERROR_STOP=1 <<'SQL'
|
||||
SELECT format('CREATE ROLE messenger_api LOGIN PASSWORD %L', :'api_password')
|
||||
WHERE NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'messenger_api') \gexec
|
||||
SELECT format('ALTER ROLE messenger_api LOGIN PASSWORD %L', :'api_password') \gexec
|
||||
SELECT format('CREATE ROLE messenger_worker LOGIN PASSWORD %L', :'worker_password')
|
||||
WHERE NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'messenger_worker') \gexec
|
||||
SELECT format('ALTER ROLE messenger_worker LOGIN PASSWORD %L', :'worker_password') \gexec
|
||||
GRANT CONNECT ON DATABASE :"db_name" TO messenger_api, messenger_worker;
|
||||
GRANT USAGE ON SCHEMA public TO messenger_api, messenger_worker;
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO messenger_api;
|
||||
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO messenger_api;
|
||||
ALTER DEFAULT PRIVILEGES FOR ROLE :"db_owner" IN SCHEMA public GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO messenger_api;
|
||||
ALTER DEFAULT PRIVILEGES FOR ROLE :"db_owner" IN SCHEMA public GRANT USAGE, SELECT ON SEQUENCES TO messenger_api;
|
||||
SQL
|
||||
wait "$postgres_pid"
|
||||
@@ -0,0 +1,75 @@
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$root = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path
|
||||
$out = Join-Path $root 'secrets\tls'
|
||||
New-Item -ItemType Directory -Force -Path $out | Out-Null
|
||||
if (-not (Get-Command openssl -ErrorAction SilentlyContinue)) { throw 'Install OpenSSL and make openssl available on PATH.' }
|
||||
|
||||
function New-Ca($name) {
|
||||
$key = Join-Path $out "$name-ca.key"
|
||||
$crt = Join-Path $out "$name-ca.crt"
|
||||
& openssl genrsa -out $key 3072
|
||||
& openssl req -x509 -new -key $key -sha256 -days 365 -subj "/CN=VisPril-$name-CA" -out $crt
|
||||
if ($LASTEXITCODE) { throw "Failed to create $name CA" }
|
||||
}
|
||||
function New-Leaf($name, $ca, $usage, $sans, $subject=$name) {
|
||||
$key = Join-Path $out "$name.key"
|
||||
$csr = Join-Path $out "$name.csr"
|
||||
$crt = Join-Path $out "$name.crt"
|
||||
$ext = Join-Path $out "$name.ext"
|
||||
"basicConstraints=CA:FALSE`nextendedKeyUsage=$usage`nsubjectAltName=$sans`nkeyUsage=digitalSignature,keyEncipherment" | Set-Content -NoNewline $ext
|
||||
& openssl genrsa -out $key 2048
|
||||
& openssl req -new -key $key -subj "/CN=$subject" -out $csr
|
||||
& openssl x509 -req -in $csr -CA (Join-Path $out "$ca-ca.crt") -CAkey (Join-Path $out "$ca-ca.key") -CAcreateserial -out $crt -days 90 -sha256 -extfile $ext
|
||||
Remove-Item $csr,$ext -Force
|
||||
if ($LASTEXITCODE) { throw "Failed to create $name certificate" }
|
||||
}
|
||||
|
||||
New-Ca 'public'
|
||||
New-Ca 'service'
|
||||
New-Ca 'bao'
|
||||
New-Ca 'lb'
|
||||
New-Leaf 'ingress' 'public' 'serverAuth' 'DNS:localhost,IP:127.0.0.1'
|
||||
New-Leaf 'api' 'service' 'serverAuth' 'DNS:api1,DNS:api2'
|
||||
New-Leaf 'lb-client' 'lb' 'clientAuth' 'DNS:messenger-lb' 'messenger-lb'
|
||||
New-Leaf 'imposter' 'lb' 'clientAuth' 'DNS:imposter'
|
||||
New-Leaf 'foreign-client' 'public' 'clientAuth' 'DNS:foreign-client'
|
||||
New-Leaf 'openbao' 'bao' 'serverAuth' 'DNS:openbao,DNS:localhost,IP:127.0.0.1'
|
||||
New-Leaf 'minio' 'service' 'serverAuth' 'DNS:minio'
|
||||
New-Leaf 'db' 'service' 'serverAuth' 'DNS:db'
|
||||
New-Leaf 'redis-sessions' 'service' 'serverAuth' 'DNS:redis'
|
||||
New-Leaf 'redis-broker' 'service' 'serverAuth' 'DNS:redis-broker'
|
||||
New-Leaf 'otel-collector' 'service' 'serverAuth' 'DNS:otel-collector'
|
||||
New-Leaf 'api-otel-client' 'service' 'clientAuth' 'DNS:messenger-api'
|
||||
New-Leaf 'worker-otel-client' 'service' 'clientAuth' 'DNS:messenger-worker'
|
||||
New-Leaf 'tempo' 'service' 'serverAuth' 'DNS:tempo'
|
||||
New-Leaf 'loki' 'service' 'serverAuth' 'DNS:loki'
|
||||
New-Leaf 'prometheus' 'service' 'serverAuth' 'DNS:prometheus'
|
||||
New-Leaf 'prometheus-client' 'service' 'clientAuth' 'DNS:prometheus-scraper'
|
||||
New-Item -ItemType Directory -Force -Path (Join-Path $root 'secrets\minio-certs') | Out-Null
|
||||
New-Item -ItemType Directory -Force -Path (Join-Path $root 'secrets\minio-certs\CAs') | Out-Null
|
||||
$targetDirs = @('ingress','api','api-proxy1','api-proxy2','worker','db','redis-sessions','redis-broker','minio-certs','openbao','openbao-api','openbao-worker','collector','loki','tempo','prometheus','grafana','test-client')
|
||||
foreach ($dir in $targetDirs) { New-Item -ItemType Directory -Force -Path (Join-Path $root "secrets\$dir") | Out-Null }
|
||||
function Copy-Tls($file, $dir, $name=$file) { Copy-Item (Join-Path $out $file) (Join-Path $root "secrets\$dir\$name") -Force }
|
||||
Copy-Tls 'ingress.crt' ingress; Copy-Tls 'ingress.key' ingress; Copy-Tls 'public-ca.crt' ingress
|
||||
Copy-Tls 'service-ca.crt' ingress; Copy-Tls 'lb-ca.crt' ingress; Copy-Tls 'lb-client.crt' ingress; Copy-Tls 'lb-client.key' ingress
|
||||
Copy-Tls 'service-ca.crt' api; Copy-Tls 'bao-ca.crt' api
|
||||
Copy-Tls 'api-otel-client.crt' api; Copy-Tls 'api-otel-client.key' api
|
||||
Copy-Tls 'api.crt' api-proxy1; Copy-Tls 'api.key' api-proxy1; Copy-Tls 'lb-ca.crt' api-proxy1
|
||||
Copy-Tls 'api.crt' api-proxy2; Copy-Tls 'api.key' api-proxy2; Copy-Tls 'lb-ca.crt' api-proxy2
|
||||
Copy-Tls 'imposter.crt' test-client 'wrong-lb-client.crt'; Copy-Tls 'imposter.key' test-client 'wrong-lb-client.key'
|
||||
Copy-Tls 'foreign-client.crt' test-client; Copy-Tls 'foreign-client.key' test-client
|
||||
Copy-Tls 'service-ca.crt' worker; Copy-Tls 'bao-ca.crt' worker
|
||||
Copy-Tls 'worker-otel-client.crt' worker; Copy-Tls 'worker-otel-client.key' worker
|
||||
Copy-Tls 'db.crt' db; Copy-Tls 'db.key' db; Copy-Tls 'service-ca.crt' db
|
||||
Copy-Tls 'redis-sessions.crt' redis-sessions; Copy-Tls 'redis-sessions.key' redis-sessions; Copy-Tls 'service-ca.crt' redis-sessions
|
||||
Copy-Tls 'redis-broker.crt' redis-broker; Copy-Tls 'redis-broker.key' redis-broker; Copy-Tls 'service-ca.crt' redis-broker
|
||||
Copy-Tls 'minio.crt' minio-certs 'public.crt'; Copy-Tls 'minio.key' minio-certs 'private.key'
|
||||
Copy-Tls 'service-ca.crt' minio-certs 'CAs\service-ca.crt'
|
||||
Copy-Tls 'openbao.crt' openbao; Copy-Tls 'openbao.key' openbao; Copy-Tls 'bao-ca.crt' openbao
|
||||
Copy-Tls 'otel-collector.crt' collector; Copy-Tls 'otel-collector.key' collector; Copy-Tls 'service-ca.crt' collector
|
||||
Copy-Tls 'loki.crt' loki; Copy-Tls 'loki.key' loki; Copy-Tls 'service-ca.crt' loki
|
||||
Copy-Tls 'tempo.crt' tempo; Copy-Tls 'tempo.key' tempo; Copy-Tls 'service-ca.crt' tempo
|
||||
Copy-Tls 'prometheus.crt' prometheus; Copy-Tls 'prometheus.key' prometheus; Copy-Tls 'service-ca.crt' prometheus
|
||||
Copy-Tls 'prometheus-client.crt' prometheus; Copy-Tls 'prometheus-client.key' prometheus
|
||||
Copy-Tls 'service-ca.crt' 'grafana'
|
||||
Write-Host "Local certificates created in $out. Keep all *.key files out of Git."
|
||||
@@ -0,0 +1,14 @@
|
||||
fastapi==0.109.0
|
||||
uvicorn[standard]==0.27.0
|
||||
pydantic==2.5.3
|
||||
sqlalchemy==2.0.25
|
||||
alembic==1.13.1
|
||||
psycopg2-binary==2.9.9
|
||||
redis==5.0.1
|
||||
boto3==1.35.99
|
||||
Pillow==11.0.0
|
||||
argon2-cffi==23.1.0
|
||||
hvac==2.3.0
|
||||
opentelemetry-api==1.27.0
|
||||
opentelemetry-sdk==1.27.0
|
||||
opentelemetry-exporter-otlp-proto-grpc==1.27.0
|
||||
@@ -0,0 +1,17 @@
|
||||
"""Measure the selected Argon2id cost using only synthetic input."""
|
||||
from statistics import median
|
||||
from time import perf_counter
|
||||
|
||||
from argon2 import PasswordHasher, Type
|
||||
|
||||
memory_kib, iterations, parallelism = 19456, 2, 1
|
||||
hasher = PasswordHasher(time_cost=iterations, memory_cost=memory_kib,
|
||||
parallelism=parallelism, hash_len=32, salt_len=16,
|
||||
type=Type.ID)
|
||||
samples = []
|
||||
for _ in range(7):
|
||||
started = perf_counter()
|
||||
hasher.hash("synthetic-lab7-password")
|
||||
samples.append((perf_counter() - started) * 1000)
|
||||
print(f"algorithm=Argon2id memory_kib={memory_kib} iterations={iterations} parallelism={parallelism}")
|
||||
print(f"samples_ms={','.join(f'{sample:.1f}' for sample in samples)} median_ms={median(samples):.1f}")
|
||||
@@ -0,0 +1,12 @@
|
||||
"""Apply worker's narrow table grant after migrations have created attachments."""
|
||||
import os
|
||||
import psycopg2
|
||||
|
||||
conn = psycopg2.connect(os.environ["DATABASE_URL"], sslmode="verify-full",
|
||||
sslrootcert=os.getenv("DB_CA_FILE", "/run/tls/service-ca.crt"))
|
||||
try:
|
||||
with conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE attachments TO messenger_worker")
|
||||
finally:
|
||||
conn.close()
|
||||
@@ -0,0 +1,47 @@
|
||||
"""Exercise the per-replica mTLS sidecar from its isolated network namespace."""
|
||||
import ssl
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import os
|
||||
|
||||
BASE = os.getenv("MTLS_PROBE_URL", "https://api1:8443/health/live")
|
||||
|
||||
|
||||
def probe(cert=None, key=None):
|
||||
context = ssl.create_default_context(cafile="/run/tls/service-ca.crt")
|
||||
context.check_hostname = True
|
||||
if cert:
|
||||
context.load_cert_chain(cert, key)
|
||||
try:
|
||||
with urllib.request.urlopen(BASE, context=context, timeout=4) as response:
|
||||
return response.status
|
||||
except urllib.error.HTTPError as exc:
|
||||
return exc.code
|
||||
|
||||
|
||||
def rejected_at_client_auth(cert=None, key=None):
|
||||
try:
|
||||
status = probe(cert, key)
|
||||
except urllib.error.URLError as exc:
|
||||
if not isinstance(exc.reason, ssl.SSLError):
|
||||
raise SystemExit("FAIL: client-auth probe failed for a non-TLS reason") from exc
|
||||
return True
|
||||
# Nginx may complete the TLS handshake and answer 400 before proxying when
|
||||
# ssl_verify_client is on and the peer sends no acceptable certificate.
|
||||
return status == 400
|
||||
|
||||
if not rejected_at_client_auth():
|
||||
raise SystemExit("FAIL: API sidecar accepted a connection without a client certificate")
|
||||
print("PASS: no client certificate rejected")
|
||||
|
||||
if not rejected_at_client_auth("/test/foreign-client.crt", "/test/foreign-client.key"):
|
||||
raise SystemExit("FAIL: API sidecar accepted a foreign-CA client certificate")
|
||||
print("PASS: foreign CA rejected")
|
||||
|
||||
if probe("/test/wrong-lb-client.crt", "/test/wrong-lb-client.key") != 403:
|
||||
raise SystemExit("FAIL: trusted but wrong client identity was not denied with 403")
|
||||
print("PASS: wrong identity from the trusted LB CA denied")
|
||||
|
||||
if probe("/test/lb-client.crt", "/test/lb-client.key") != 200:
|
||||
raise SystemExit("FAIL: allowlisted LB identity did not reach API")
|
||||
print("PASS: allowlisted LB identity accepted")
|
||||
@@ -0,0 +1,33 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$ROOT"
|
||||
DOCKER_COMMAND=${DOCKER_COMMAND:-docker}
|
||||
DOCKER_ROOT=$ROOT
|
||||
case "$DOCKER_COMMAND" in *.exe) DOCKER_ROOT=$(wslpath -w "$ROOT") ;; esac
|
||||
compose() { "$DOCKER_COMMAND" compose --env-file "$DOCKER_ROOT/.env" -f "$DOCKER_ROOT/compose.yaml" "$@"; }
|
||||
|
||||
# Stop ingress/apps before stores so no new requests are admitted while state
|
||||
# services restart. Persistent Compose volumes are retained; OpenBao stays up
|
||||
# so its operator-only unseal shares are never needed by this hook.
|
||||
compose stop lb api1-mtls api2-mtls api1 api2 worker db redis redis-broker minio
|
||||
compose start db redis redis-broker minio
|
||||
|
||||
wait_healthy() {
|
||||
service=$1
|
||||
container=$(compose ps -q "$service")
|
||||
[ -n "$container" ] || { echo "Missing container: $service" >&2; exit 1; }
|
||||
tries=0
|
||||
while [ "$("$DOCKER_COMMAND" inspect --format '{{.State.Health.Status}}' "$container" 2>/dev/null || true)" != healthy ]; do
|
||||
tries=$((tries + 1))
|
||||
[ "$tries" -lt 90 ] || { echo "Timed out waiting for $service" >&2; exit 1; }
|
||||
sleep 1
|
||||
done
|
||||
}
|
||||
|
||||
wait_healthy db
|
||||
wait_healthy minio
|
||||
wait_healthy redis-broker
|
||||
sleep 2
|
||||
compose start api1 api2 worker api1-mtls api2-mtls lb
|
||||
@@ -0,0 +1,15 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||
cd "$ROOT"
|
||||
DOCKER_COMMAND=${DOCKER_COMMAND:-docker}
|
||||
DOCKER_ROOT=$ROOT
|
||||
case "$DOCKER_COMMAND" in *.exe) DOCKER_ROOT=$(wslpath -w "$ROOT") ;; esac
|
||||
compose() { "$DOCKER_COMMAND" compose --env-file "$DOCKER_ROOT/.env" -f "$DOCKER_ROOT/compose.yaml" "$@"; }
|
||||
|
||||
case "${TARGET_INSTANCE_ID:?test provides an API replica alias}" in
|
||||
replica-a) compose stop api1-mtls api1 ;;
|
||||
replica-b) compose stop api2-mtls api2 ;;
|
||||
*) echo 'Unknown API replica alias' >&2; exit 2 ;;
|
||||
esac
|
||||
@@ -1,19 +1,33 @@
|
||||
# Модель угроз — заполнить
|
||||
# Модель угроз
|
||||
|
||||
## Активы и акторы
|
||||
|
||||
TODO: пользовательские credentials/сессии, сообщения/вложения, service identities, CA/secrets, telemetry. Акторы: участник чата, посторонний пользователь, внешний клиент, скомпрометированный сервис, оператор. Опишите доступ атакующего и границы учебного стенда.
|
||||
Активы: пароли и Argon2id hashes, Bearer sessions, сообщения и вложения, DB/S3/broker credentials, TLS CA and leaf private keys, OpenBao storage/unseal material, telemetry. Акторы: внешний REST клиент, аутентифицированный участник/посторонний пользователь, процесс ingress/API/worker, оператор учебного Docker host. Рассматриваем синтетические данные на одном локальном host; доступ к Docker daemon или filesystem host означает компрометацию всего стенда и не защищается приложением.
|
||||
|
||||
## Границы доверия
|
||||
|
||||
TODO: схема и ссылка на заполненную contracts/trust-matrix.md; публичные/внутренние интерфейсы, процессы, секреты и их выдача.
|
||||
```text
|
||||
external client --HTTPS/public CA--> Nginx ingress --mTLS/service CA--> API replicas
|
||||
|--> PostgreSQL
|
||||
|--> S3
|
||||
|--> Redis session/broker
|
||||
|--> OTel Collector -> telemetry stores
|
||||
`--> HTTPS/OpenBao AppRole -> scoped KV
|
||||
operator --local authenticated channel--> OpenBao/Grafana administration
|
||||
```
|
||||
|
||||
| Угроза и конкретный путь | Нарушаемый инвариант | Контроль | Отрицательный тест | Остаточное ограничение |
|
||||
Конфигурации и текущие ограничения каждой линии перечислены в [trust matrix](../contracts/trust-matrix.md). Наружу опубликован HTTPS ingress; Grafana привязана к loopback; API ports и service ports наружу не опубликованы. На host TLS certificate generation is local. OpenBao init/unseal and role setup are operator operations.
|
||||
|
||||
| Угроза и конкретный путь | Нарушаемый инвариант | Контроль | Негативная проверка | Остаточное ограничение |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| TODO | TODO | TODO | TODO | TODO |
|
||||
| Клиент посылает password/Bearer через недоверенную сеть | Credential confidentiality | Public HTTPS leaf, CA + SAN validation | `make test-security`, неверный CA/hostname | Локальный CA — только для стенда |
|
||||
| Посторонний участник подменяет `X-User-Id` или угадывает attachment ID | Идентичность и ACL должны исходить из сессии; чужие объекты не раскрываются | Bearer-only protected API, member check, чужой объект даёт 404 | Отдельный чужой token + поддельный header; metadata/content 404 | Нужны собственные API regression runs перед защитой |
|
||||
| Клиент подключается напрямую к API в обход LB | Каждый API запрос должен пройти ingress boundary | API порт не опубликован; app доступен только loopback; nginx checks allowed client DN | Внутрисетевая попытка без cert/с чужой CA отвергается на client-auth boundary; неверный CN gets 403; LB identity succeeds | Docker host/root user can join the network |
|
||||
| Пользователь перебирает пароли | Пароль не должен быть дешёвым для перебора; burst ограничен | Argon2id ≥19 MiB, t=2,p=1; per-replica login limit 10/minute + Retry-After | 11 login attempts from same source returns 429 | Rate limit in-memory and per replica; distributed evasion possible |
|
||||
| API process/read-only filesystem attacker пытается извлечь root/unseal | Application identity must not grant operator access | OpenBao AppRole scoped KV read; operator material absent from image/repo | API policy read own path; deny worker path/write | Static SecretID local file; no automatic expiry/rotation demonstrated |
|
||||
| Compromised API abuses worker credentials or bucket | Least privilege between API and worker | Distinct OpenBao policies, AppRole paths, MinIO users/prefix policies, PostgreSQL roles and Redis ACL identities | KV path deny, S3 denied-prefix probe, DB privilege review, Redis ACL negative probe | Live deny checks have not been run; static AppRole SecretID rotation is manual |
|
||||
| DB/broker/telemetry traffic observed on Docker network | Service data confidentiality | PostgreSQL verify-full + hostnossl reject; Redis TLS/ACL; OTLP mTLS; Collector-to-backend TLS; Grafana datasource verification | TLS probes and logs for each channel are outstanding | Configurations are present but runtime handshake/failure behavior is unverified |
|
||||
|
||||
На 4 минимум 6 конкретных угроз. Не заменяйте сценарии словами «SQL injection», «безопасный Docker», «mTLS включён» без пути и проверки.
|
||||
## Lifecycle and incident handling
|
||||
|
||||
## Lifecycle и инциденты
|
||||
|
||||
TODO: bootstrap, expiry/renewal, revoke/rotation, компрометация identity, sealed OpenBao и восстановление. Указать владельца CA/unseal и способ защиты bootstrap credentials. Сопоставить scan findings с реальной применимостью и исправлением/остаточным риском.
|
||||
Operator creates the public, service and Bao CAs/leaf certs locally with `infra/tls/bootstrap.ps1`. OpenBao persistent data lives in `openbao_data`; operator performs one-time init, stores quorum shares offline, enables KV v2 and AppRole, writes scoped policies and creates local role credentials. After restart the operator unseals Bao before API/worker can fetch credentials. Sealed/unavailable Bao fails closed; the app has no embedded root token or plaintext fallback. On level 3 secret rotation is manual and requires an application restart; automatic leaf/secret renewal, revocation test and scan triage are future work.
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
"""MTUSI Messenger service package."""
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
"""Argon2id password hashes and opaque, cryptographically random sessions."""
|
||||
import base64
|
||||
import os
|
||||
import secrets
|
||||
|
||||
from argon2 import PasswordHasher, Type
|
||||
from argon2.exceptions import InvalidHashError, VerificationError, VerifyMismatchError
|
||||
|
||||
SESSION_TTL_SECONDS = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
|
||||
ARGON2_MEMORY_KIB = max(19456, int(os.getenv("ARGON2_MEMORY_KIB", "19456")))
|
||||
ARGON2_ITERATIONS = max(2, int(os.getenv("ARGON2_ITERATIONS", "2")))
|
||||
ARGON2_PARALLELISM = max(1, int(os.getenv("ARGON2_PARALLELISM", "1")))
|
||||
_hasher = PasswordHasher(time_cost=ARGON2_ITERATIONS,
|
||||
memory_cost=ARGON2_MEMORY_KIB,
|
||||
parallelism=ARGON2_PARALLELISM,
|
||||
hash_len=32, salt_len=16, type=Type.ID)
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
return _hasher.hash(password)
|
||||
|
||||
|
||||
def verify_password(password: str, encoded: str) -> bool:
|
||||
try:
|
||||
return _hasher.verify(encoded, password)
|
||||
except (VerifyMismatchError, VerificationError, InvalidHashError, ValueError, TypeError):
|
||||
return False
|
||||
|
||||
|
||||
def new_token() -> str:
|
||||
return secrets.token_urlsafe(32)
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
"""Fetch scoped runtime secrets from OpenBao using AppRole over verified TLS."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import hvac
|
||||
|
||||
|
||||
def read_secret(path: str) -> dict:
|
||||
address = os.environ["BAO_ADDR"]
|
||||
role_id = Path(os.environ.get("BAO_ROLE_ID_FILE", "/run/secrets/role_id")).read_text().strip()
|
||||
secret_id = Path(os.environ.get("BAO_SECRET_ID_FILE", "/run/secrets/secret_id")).read_text().strip()
|
||||
client = hvac.Client(url=address, verify=os.environ.get("BAO_CACERT", "/run/tls/bao-ca.crt"))
|
||||
client.auth.approle.login(role_id=role_id, secret_id=secret_id)
|
||||
if not client.is_authenticated():
|
||||
raise RuntimeError("OpenBao service authentication failed")
|
||||
result = client.secrets.kv.v2.read_secret_version(path=path, mount_point="secret")
|
||||
return result["data"]["data"]
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
"""PostgreSQL schema and bounded connection pool."""
|
||||
import os
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from sqlalchemy import (Column, DateTime, ForeignKey, Index, String, Text, Integer, JSON,
|
||||
UniqueConstraint, create_engine)
|
||||
from sqlalchemy.engine import URL
|
||||
from sqlalchemy.orm import declarative_base, relationship, sessionmaker
|
||||
from .bao import read_secret
|
||||
|
||||
if os.getenv("MIGRATION_CONTEXT") == "1":
|
||||
DATABASE_URL = os.environ["DATABASE_URL"]
|
||||
else:
|
||||
_db_credentials = read_secret(os.getenv("BAO_SECRET_PATH", "messenger/api"))
|
||||
DATABASE_URL = URL.create(
|
||||
"postgresql+psycopg2", username=_db_credentials["db_username"],
|
||||
password=_db_credentials["db_password"], host=os.getenv("DB_HOST", "db"),
|
||||
port=int(os.getenv("DB_PORT", "5432")), database=os.getenv("DB_NAME", "messenger"),
|
||||
)
|
||||
engine = create_engine(DATABASE_URL, pool_size=5, max_overflow=5, pool_timeout=5,
|
||||
pool_pre_ping=True, connect_args={"connect_timeout": 5,
|
||||
"sslmode": "verify-full", "sslrootcert": os.getenv("DB_CA_FILE", "/run/tls/service-ca.crt"),
|
||||
"options": "-c statement_timeout=5000"})
|
||||
SessionLocal = sessionmaker(bind=engine, expire_on_commit=False)
|
||||
Base = declarative_base()
|
||||
now = lambda: datetime.now(timezone.utc)
|
||||
|
||||
|
||||
class User(Base):
|
||||
__tablename__ = "users"
|
||||
id = Column(String, primary_key=True, default=lambda: str(uuid.uuid4()))
|
||||
username = Column(String(32), nullable=False)
|
||||
display_name = Column(String(100), nullable=False)
|
||||
password_hash = Column(String(255), nullable=False)
|
||||
created_at = Column(DateTime(timezone=True), nullable=False, default=now)
|
||||
__table_args__ = (Index("ix_users_username", "username", unique=True),)
|
||||
|
||||
|
||||
class Session(Base):
|
||||
__tablename__ = "sessions"
|
||||
id = Column(String, primary_key=True, default=lambda: str(uuid.uuid4()))
|
||||
token = Column(String(255), nullable=False)
|
||||
user_id = Column(String, ForeignKey("users.id"), nullable=False)
|
||||
expires_at = Column(DateTime(timezone=True), nullable=False)
|
||||
created_at = Column(DateTime(timezone=True), nullable=False, default=now)
|
||||
user = relationship("User")
|
||||
__table_args__ = (Index("ix_sessions_token", "token", unique=True),)
|
||||
|
||||
|
||||
class Chat(Base):
|
||||
__tablename__ = "chats"
|
||||
id = Column(String, primary_key=True, default=lambda: str(uuid.uuid4()))
|
||||
title = Column(String(100), nullable=False)
|
||||
created_at = Column(DateTime(timezone=True), nullable=False, default=now)
|
||||
members = relationship("ChatMember", back_populates="chat", cascade="all, delete-orphan")
|
||||
|
||||
|
||||
class ChatMember(Base):
|
||||
__tablename__ = "chat_members"
|
||||
id = Column(String, primary_key=True, default=lambda: str(uuid.uuid4()))
|
||||
chat_id = Column(String, ForeignKey("chats.id"), nullable=False)
|
||||
user_id = Column(String, ForeignKey("users.id"), nullable=False)
|
||||
chat = relationship("Chat", back_populates="members")
|
||||
user = relationship("User")
|
||||
__table_args__ = (UniqueConstraint("chat_id", "user_id", name="uq_chat_member"),
|
||||
Index("ix_chat_members_user_chat", "user_id", "chat_id"))
|
||||
|
||||
|
||||
class Message(Base):
|
||||
__tablename__ = "messages"
|
||||
id = Column(String, primary_key=True, default=lambda: str(uuid.uuid4()))
|
||||
chat_id = Column(String, ForeignKey("chats.id"), nullable=False)
|
||||
sender_id = Column(String, ForeignKey("users.id"), nullable=False)
|
||||
text = Column(Text, nullable=False)
|
||||
attachment_ids = Column(JSON, nullable=False, default=list)
|
||||
created_at = Column(DateTime(timezone=True), nullable=False, default=now)
|
||||
chat = relationship("Chat")
|
||||
sender = relationship("User")
|
||||
__table_args__ = (Index("ix_messages_chat_created_id", "chat_id", "created_at", "id"),)
|
||||
|
||||
|
||||
class Attachment(Base):
|
||||
__tablename__ = "attachments"
|
||||
id = Column(String, primary_key=True)
|
||||
chat_id = Column(String, ForeignKey("chats.id"), nullable=False, index=True)
|
||||
owner_id = Column(String, ForeignKey("users.id"), nullable=False)
|
||||
filename = Column(String(255), nullable=False)
|
||||
content_type = Column(String(32), nullable=False)
|
||||
size_bytes = Column(Integer, nullable=False)
|
||||
sha256 = Column(String(64), nullable=False)
|
||||
object_key = Column(String(128), nullable=False, unique=True)
|
||||
staging_key = Column(String(128), nullable=False, unique=True)
|
||||
status = Column(String(16), nullable=False, default="ready")
|
||||
job_id = Column(String(36), nullable=False, unique=True)
|
||||
error_code = Column(String(64), nullable=True)
|
||||
variants = Column(JSON, nullable=False, default=list)
|
||||
created_at = Column(DateTime(timezone=True), nullable=False, default=now)
|
||||
updated_at = Column(DateTime(timezone=True), nullable=False, default=now)
|
||||
|
||||
|
||||
class MessageIdempotency(Base):
|
||||
__tablename__ = "message_idempotency"
|
||||
id = Column(String, primary_key=True, default=lambda: str(uuid.uuid4()))
|
||||
user_id = Column(String, ForeignKey("users.id"), nullable=False)
|
||||
method = Column(String(8), nullable=False)
|
||||
chat_path = Column(String(80), nullable=False)
|
||||
key = Column(String(128), nullable=False)
|
||||
request_hash = Column(String(64), nullable=False)
|
||||
message_id = Column(String, ForeignKey("messages.id"), nullable=True)
|
||||
created_at = Column(DateTime(timezone=True), nullable=False, default=now)
|
||||
__table_args__ = (UniqueConstraint("user_id", "method", "chat_path", "key",
|
||||
name="uq_idempotency_scope"),)
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
"""Redis Streams producer for durable attachment jobs."""
|
||||
import json
|
||||
import os
|
||||
from datetime import datetime, timezone
|
||||
import redis
|
||||
from opentelemetry.propagate import inject
|
||||
|
||||
QUEUE = os.getenv("ATTACHMENT_QUEUE", "attachment.jobs.v1")
|
||||
CONSUMER_GROUP = os.getenv("ATTACHMENT_CONSUMER_GROUP", "attachment-workers-v1")
|
||||
MAX_ATTEMPTS = int(os.getenv("JOB_MAX_ATTEMPTS", "5"))
|
||||
|
||||
|
||||
def client():
|
||||
return redis.Redis.from_url(os.environ["BROKER_URL"], decode_responses=True,
|
||||
ssl_cert_reqs="required" if os.environ["BROKER_URL"].startswith("rediss:") else None,
|
||||
ssl_ca_certs=os.getenv("TLS_CA_FILE", "/run/tls/service-ca.crt") if os.environ["BROKER_URL"].startswith("rediss:") else None,
|
||||
ssl_check_hostname=True if os.environ["BROKER_URL"].startswith("rediss:") else False,
|
||||
socket_connect_timeout=3, socket_timeout=10,
|
||||
retry_on_timeout=True)
|
||||
|
||||
|
||||
def publish(attachment_id, job_id, attempt=1):
|
||||
job = {"schema_version": 1, "job_id": job_id,
|
||||
"type": "attachment.process.v1", "attachment_id": attachment_id,
|
||||
"pipeline_version": 1, "attempt": attempt,
|
||||
"created_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")}
|
||||
carrier = {}
|
||||
inject(carrier)
|
||||
if "traceparent" in carrier:
|
||||
job["traceparent"] = carrier["traceparent"]
|
||||
if "tracestate" in carrier:
|
||||
job["tracestate"] = carrier["tracestate"]
|
||||
client().xadd(QUEUE, {"body": json.dumps(job, separators=(",", ":"))})
|
||||
|
||||
|
||||
def ping():
|
||||
client().ping()
|
||||
+441
@@ -0,0 +1,441 @@
|
||||
"""Lab 4 REST API: shared messenger state and private S3 attachments."""
|
||||
import base64
|
||||
import binascii
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import uuid
|
||||
import time
|
||||
import os
|
||||
import hashlib
|
||||
import tempfile
|
||||
import re as regex
|
||||
import threading
|
||||
from collections import defaultdict, deque
|
||||
from datetime import timezone
|
||||
from fastapi import FastAPI, Request, Query
|
||||
from fastapi.responses import JSONResponse, StreamingResponse
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
from PIL import Image, UnidentifiedImageError
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
import redis
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from .database import SessionLocal
|
||||
from .models import CreateUser, CreateChat, CreateMessage
|
||||
from .store import store, cursor_for_chat, cursor_for_message
|
||||
from . import session_cache
|
||||
from . import object_store
|
||||
from . import jobs
|
||||
from . import telemetry
|
||||
from opentelemetry import trace
|
||||
from opentelemetry.propagate import extract
|
||||
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
|
||||
|
||||
|
||||
class AppError(Exception):
|
||||
def __init__(self, status, code, message, headers=None):
|
||||
self.status, self.code, self.message, self.headers = status, code, message, headers or {}
|
||||
|
||||
|
||||
app = FastAPI(title="MTUSI Messenger", version="6.0.0")
|
||||
INSTANCE_ID = os.getenv("INSTANCE_ID") or str(uuid.uuid4())
|
||||
_login_attempts = defaultdict(deque)
|
||||
_login_rate_lock = threading.Lock()
|
||||
|
||||
|
||||
def enforce_login_rate_limit(request):
|
||||
now = time.monotonic()
|
||||
forwarded = request.headers.get("X-Forwarded-For", "")
|
||||
peer = forwarded.rsplit(",", 1)[-1].strip() if forwarded else (request.client.host if request.client else "unknown")
|
||||
with _login_rate_lock:
|
||||
attempts = _login_attempts[peer]
|
||||
while attempts and now - attempts[0] >= 60:
|
||||
attempts.popleft()
|
||||
if len(attempts) >= 10:
|
||||
retry_after = max(1, 60 - int(now - attempts[0]))
|
||||
raise AppError(429, "rate_limited", "Too many login attempts",
|
||||
{"Retry-After": str(retry_after)})
|
||||
attempts.append(now)
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def observe_request(request: Request, call_next):
|
||||
started = time.perf_counter()
|
||||
request_id = request.headers.get("X-Request-Id") or str(uuid.uuid4())
|
||||
request.state.request_id = request_id
|
||||
carrier = {key.lower(): value for key, value in request.headers.items() if key.lower() in ("traceparent", "tracestate")}
|
||||
parent = extract(carrier)
|
||||
with telemetry.tracer.start_as_current_span("http.request", context=parent, kind=trace.SpanKind.SERVER) as span:
|
||||
span.set_attribute("http.request.method", request.method)
|
||||
span.set_attribute("messenger.request_id", request_id)
|
||||
try:
|
||||
response = await call_next(request)
|
||||
except Exception:
|
||||
span.set_attribute("http.response.status_code", 500)
|
||||
span.record_exception(Exception("unhandled request failure"))
|
||||
route = request.scope.get("route")
|
||||
route_name = getattr(route, "path", "unmatched")
|
||||
attrs = {"http.request.method": request.method, "http.route": route_name,
|
||||
"http.response.status_class": "5xx"}
|
||||
elapsed = time.perf_counter() - started
|
||||
telemetry.http_requests.add(1, attrs)
|
||||
telemetry.http_duration.record(elapsed, attrs)
|
||||
logging.getLogger("messenger.api").error("http_request_failed", extra={"request_id": request_id, "http_route": route_name, "http_status": 500, "duration_seconds": round(elapsed, 6)})
|
||||
raise
|
||||
route = request.scope.get("route")
|
||||
route_name = getattr(route, "path", "unmatched")
|
||||
response.headers["X-Request-Id"] = request_id
|
||||
response.headers["X-Instance-Id"] = INSTANCE_ID
|
||||
span.set_attribute("http.route", route_name)
|
||||
span.set_attribute("http.response.status_code", response.status_code)
|
||||
attrs = {"http.request.method": request.method, "http.route": route_name,
|
||||
"http.response.status_class": f"{response.status_code // 100}xx"}
|
||||
elapsed = time.perf_counter() - started
|
||||
telemetry.http_requests.add(1, attrs)
|
||||
telemetry.http_duration.record(elapsed, attrs)
|
||||
if response.status_code >= 500:
|
||||
span.set_status(trace.Status(trace.StatusCode.ERROR))
|
||||
logging.getLogger("messenger.api").info("http_request_completed", extra={"request_id": request_id, "http_route": route_name, "http_status": response.status_code, "duration_seconds": round(elapsed, 6)})
|
||||
return response
|
||||
|
||||
|
||||
@app.exception_handler(AppError)
|
||||
async def app_error_handler(request, exc):
|
||||
headers = {"X-Request-Id": request.state.request_id, **exc.headers}
|
||||
headers["X-Instance-Id"] = INSTANCE_ID
|
||||
return JSONResponse(status_code=exc.status, content={"error":{"code":exc.code,"message":exc.message,"request_id":request.state.request_id}}, headers=headers)
|
||||
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_handler(request, exc):
|
||||
return JSONResponse(status_code=400, content={"error":{"code":"invalid_request","message":"Invalid request","request_id":request.state.request_id}}, headers={"X-Request-Id":request.state.request_id,"X-Instance-Id":INSTANCE_ID})
|
||||
|
||||
|
||||
@app.exception_handler(SQLAlchemyError)
|
||||
async def database_error_handler(request, exc):
|
||||
return JSONResponse(status_code=503, content={"error":{"code":"unavailable","message":"Database unavailable","request_id":request.state.request_id}}, headers={"X-Request-Id":request.state.request_id,"X-Instance-Id":INSTANCE_ID})
|
||||
|
||||
|
||||
@app.exception_handler(Exception)
|
||||
async def internal_handler(request, exc):
|
||||
return JSONResponse(status_code=500, content={"error":{"code":"internal_error","message":"Internal server error","request_id":request.state.request_id}}, headers={"X-Request-Id":request.state.request_id,"X-Instance-Id":INSTANCE_ID})
|
||||
|
||||
|
||||
def stamp(value):
|
||||
if value.tzinfo is None:
|
||||
value = value.replace(tzinfo=timezone.utc)
|
||||
return value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")
|
||||
|
||||
|
||||
def user_json(user):
|
||||
return {"id":user.id,"username":user.username,"display_name":user.display_name,"created_at":stamp(user.created_at)}
|
||||
|
||||
|
||||
def auth_user(request):
|
||||
header = request.headers.get("Authorization", "")
|
||||
if not header.startswith("Bearer ") or not header[7:]:
|
||||
raise AppError(401,"unauthorized","Authentication required",{"WWW-Authenticate":'Bearer realm="messenger"'})
|
||||
try:
|
||||
found = store.get_session_by_token(header[7:])
|
||||
except session_cache.CacheUnavailable:
|
||||
raise AppError(503,"unavailable","Session cache unavailable")
|
||||
except SQLAlchemyError:
|
||||
raise AppError(503,"unavailable","Authentication store unavailable")
|
||||
if not found:
|
||||
raise AppError(401,"unauthorized","Invalid or expired session",{"WWW-Authenticate":'Bearer realm="messenger"'})
|
||||
return found[0]
|
||||
|
||||
|
||||
def chat_json(chat):
|
||||
return {"id":chat.id,"title":chat.title,"member_ids":[m.user_id for m in chat.members],"created_at":stamp(chat.created_at)}
|
||||
|
||||
|
||||
def validate_uuid(value):
|
||||
try:
|
||||
uuid.UUID(value)
|
||||
except (ValueError, AttributeError):
|
||||
raise AppError(400,"invalid_request","Invalid UUID")
|
||||
|
||||
|
||||
@app.get("/health/live")
|
||||
async def live():
|
||||
return {"status":"ok"}
|
||||
|
||||
|
||||
@app.get("/health/ready")
|
||||
async def ready():
|
||||
try:
|
||||
with SessionLocal() as db:
|
||||
db.execute(text("SELECT 1"))
|
||||
session_cache.ping()
|
||||
object_store.s3.list_objects_v2(Bucket=object_store.S3_BUCKET, Prefix="original/", MaxKeys=1)
|
||||
await run_in_threadpool(jobs.ping)
|
||||
return {"status":"ok"}
|
||||
except session_cache.CacheUnavailable:
|
||||
raise AppError(503,"unavailable","Session cache unavailable")
|
||||
except SQLAlchemyError:
|
||||
raise AppError(503,"unavailable","Database unavailable")
|
||||
except (BotoCoreError, ClientError):
|
||||
raise AppError(503,"unavailable","Object storage unavailable")
|
||||
except (redis.exceptions.RedisError, OSError):
|
||||
raise AppError(503,"unavailable","Attachment queue unavailable")
|
||||
|
||||
|
||||
@app.post("/api/v1/users", status_code=201)
|
||||
async def register(data: CreateUser):
|
||||
if not data.display_name.strip() or not 12 <= len(data.password) <= 128:
|
||||
raise AppError(400,"invalid_request","Invalid user fields")
|
||||
try:
|
||||
return user_json(store.add_user(data.username,data.display_name,data.password))
|
||||
except ValueError as exc:
|
||||
if str(exc) == "USERNAME_EXISTS":
|
||||
raise AppError(409,"conflict","Username already exists")
|
||||
raise AppError(400,"invalid_request","Invalid user fields")
|
||||
except SQLAlchemyError:
|
||||
raise AppError(503,"unavailable","Database unavailable")
|
||||
|
||||
|
||||
@app.post("/api/v1/auth/sessions", status_code=201)
|
||||
async def login(request: Request):
|
||||
enforce_login_rate_limit(request)
|
||||
header = request.headers.get("Authorization", "")
|
||||
challenge = {'WWW-Authenticate':'Basic realm="messenger", charset="UTF-8"'}
|
||||
if not header.startswith("Basic "):
|
||||
raise AppError(401,"unauthorized","Invalid credentials",challenge)
|
||||
try:
|
||||
decoded = base64.b64decode(header[6:], validate=True).decode("utf-8")
|
||||
username, password = decoded.split(":", 1)
|
||||
except (binascii.Error, UnicodeError, ValueError):
|
||||
raise AppError(401,"unauthorized","Invalid credentials",challenge)
|
||||
try:
|
||||
user = store.verify_user_password(username,password)
|
||||
if not user:
|
||||
raise AppError(401,"unauthorized","Invalid credentials",challenge)
|
||||
session = store.create_session(user.id)
|
||||
return {"token":session.token,"token_type":"Bearer","expires_at":stamp(session.expires_at),"user":user_json(user)}
|
||||
except session_cache.CacheUnavailable:
|
||||
raise AppError(503,"unavailable","Session cache unavailable")
|
||||
except SQLAlchemyError:
|
||||
raise AppError(503,"unavailable","Database unavailable")
|
||||
|
||||
|
||||
@app.delete("/api/v1/auth/sessions/current", status_code=204)
|
||||
async def logout(request: Request):
|
||||
auth_user(request)
|
||||
try:
|
||||
store.delete_session(request.headers["Authorization"][7:])
|
||||
except session_cache.CacheUnavailable:
|
||||
raise AppError(503,"unavailable","Session cache unavailable")
|
||||
except SQLAlchemyError:
|
||||
raise AppError(503,"unavailable","Authentication store unavailable")
|
||||
return None
|
||||
|
||||
|
||||
@app.get("/api/v1/users/me")
|
||||
async def me(request: Request):
|
||||
user_id = auth_user(request)
|
||||
user = store.get_user_by_id(user_id)
|
||||
if not user:
|
||||
raise AppError(401,"unauthorized","Invalid session",{'WWW-Authenticate':'Bearer realm="messenger"'})
|
||||
return user_json(user)
|
||||
|
||||
|
||||
@app.post("/api/v1/chats", status_code=201)
|
||||
async def create_chat(data: CreateChat, request: Request):
|
||||
user_id = auth_user(request)
|
||||
if not data.title.strip():
|
||||
raise AppError(400,"invalid_request","Invalid title")
|
||||
try:
|
||||
return chat_json(store.create_chat(data.title,data.member_ids,user_id))
|
||||
except ValueError as exc:
|
||||
if str(exc)=="USER_NOT_FOUND":
|
||||
raise AppError(400,"invalid_request","Unknown member")
|
||||
raise AppError(400,"invalid_request","Invalid members")
|
||||
except SQLAlchemyError:
|
||||
raise AppError(503,"unavailable","Database unavailable")
|
||||
|
||||
|
||||
@app.get("/api/v1/chats")
|
||||
async def list_chats(request: Request, limit: int = Query(50,ge=1,le=100), cursor: str|None=None):
|
||||
user_id=auth_user(request)
|
||||
try:
|
||||
rows=store.get_user_chats(user_id,cursor,limit+1)
|
||||
except ValueError:
|
||||
raise AppError(400,"invalid_request","Invalid cursor")
|
||||
more=len(rows)>limit
|
||||
rows=rows[:limit]
|
||||
return {"items":[chat_json(c) for c in rows],"next_cursor":cursor_for_chat(rows[-1]) if more else None}
|
||||
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}")
|
||||
async def get_chat(chat_id: str, request: Request):
|
||||
user_id=auth_user(request)
|
||||
validate_uuid(chat_id)
|
||||
if not store.is_chat_member(chat_id,user_id):
|
||||
raise AppError(404,"not_found","Chat not found")
|
||||
chat=store.get_chat(chat_id)
|
||||
if not chat:
|
||||
raise AppError(404,"not_found","Chat not found")
|
||||
return chat_json(chat)
|
||||
|
||||
|
||||
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
|
||||
async def create_message(chat_id: str, data: CreateMessage, request: Request):
|
||||
user_id=auth_user(request)
|
||||
validate_uuid(chat_id)
|
||||
if data.text is None or len(data.text)>4000 or len(data.attachment_ids) != len(set(data.attachment_ids)):
|
||||
raise AppError(400,"invalid_request","Invalid message text")
|
||||
for attachment_id in data.attachment_ids:
|
||||
validate_uuid(attachment_id)
|
||||
if not data.text.strip() and not data.attachment_ids:
|
||||
raise AppError(400,"invalid_request","Message must contain text or attachments")
|
||||
key = request.headers.get("Idempotency-Key", "")
|
||||
if not re.fullmatch(r"[A-Za-z0-9._:-]{1,128}", key, flags=re.ASCII):
|
||||
raise AppError(400,"invalid_request","A valid Idempotency-Key is required")
|
||||
canonical = json.dumps({"text":data.text,"attachment_ids":data.attachment_ids}, ensure_ascii=False,
|
||||
sort_keys=True, separators=(",", ":"))
|
||||
request_hash = hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
||||
try:
|
||||
msg=store.add_message_idempotent(chat_id,user_id,data.text,data.attachment_ids,key,request_hash)
|
||||
return {"id":msg.id,"chat_id":msg.chat_id,"sender_id":msg.sender_id,"text":msg.text,"created_at":stamp(msg.created_at),"attachment_ids":msg.attachment_ids}
|
||||
except ValueError as exc:
|
||||
if str(exc) == "IDEMPOTENCY_CONFLICT":
|
||||
raise AppError(409,"conflict","Idempotency key was used with a different request")
|
||||
if str(exc) == "EMPTY_MESSAGE":
|
||||
raise AppError(400,"invalid_request","Message must contain text or attachments")
|
||||
if str(exc) == "ATTACHMENT_FAILED":
|
||||
raise AppError(409,"conflict","Failed attachment cannot be added to a message")
|
||||
raise AppError(404,"not_found","Chat not found")
|
||||
except SQLAlchemyError:
|
||||
raise AppError(503,"unavailable","Database unavailable")
|
||||
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}/messages")
|
||||
async def list_messages(chat_id: str, request: Request, limit: int=Query(50,ge=1,le=100), cursor: str|None=None):
|
||||
user_id=auth_user(request)
|
||||
validate_uuid(chat_id)
|
||||
if not store.is_chat_member(chat_id,user_id):
|
||||
raise AppError(404,"not_found","Chat not found")
|
||||
try:
|
||||
rows=store.get_messages(chat_id,cursor,limit+1)
|
||||
except ValueError:
|
||||
raise AppError(400,"invalid_request","Invalid cursor")
|
||||
more=len(rows)>limit
|
||||
rows=rows[:limit]
|
||||
items=[{"id":m.id,"chat_id":m.chat_id,"sender_id":m.sender_id,"text":m.text,"created_at":stamp(m.created_at),"attachment_ids":m.attachment_ids or []} for m in rows]
|
||||
return {"items":items,"next_cursor":cursor_for_message(rows[-1]) if more else None}
|
||||
|
||||
|
||||
def attachment_json(row):
|
||||
return {"id":row.id,"chat_id":row.chat_id,"owner_id":row.owner_id,"filename":row.filename,
|
||||
"content_type":row.content_type,"size_bytes":row.size_bytes,"sha256":row.sha256,
|
||||
"status":row.status,"variants":row.variants or [],"error_code":row.error_code,
|
||||
"created_at":stamp(row.created_at),"updated_at":stamp(row.updated_at)}
|
||||
|
||||
|
||||
@app.post("/api/v1/chats/{chat_id}/attachments", status_code=202)
|
||||
async def upload_attachment(chat_id: str, request: Request, filename: str = Query(...)):
|
||||
user_id = auth_user(request)
|
||||
validate_uuid(chat_id)
|
||||
if not store.is_chat_member(chat_id, user_id):
|
||||
raise AppError(404, "not_found", "Chat not found")
|
||||
if not 1 <= len(filename) <= 255 or any(ch in filename for ch in "/\\\x00") or any(ord(ch) < 32 or 127 <= ord(ch) < 160 for ch in filename):
|
||||
raise AppError(400, "invalid_request", "Invalid filename")
|
||||
declared = request.headers.get("content-type", "").split(";", 1)[0].lower()
|
||||
if declared not in ("image/png", "image/jpeg"):
|
||||
raise AppError(415, "unsupported_media_type", "Only PNG and JPEG are accepted")
|
||||
max_bytes = 10 * 1024 * 1024
|
||||
spool = tempfile.SpooledTemporaryFile(max_size=1024 * 1024, mode="w+b")
|
||||
digest = hashlib.sha256()
|
||||
size = 0
|
||||
try:
|
||||
async for chunk in request.stream():
|
||||
size += len(chunk)
|
||||
if size > max_bytes:
|
||||
raise AppError(413, "payload_too_large", "Image exceeds 10 MiB")
|
||||
digest.update(chunk)
|
||||
spool.write(chunk)
|
||||
if size == 0:
|
||||
raise AppError(415, "unsupported_media_type", "Empty image")
|
||||
spool.seek(0)
|
||||
try:
|
||||
image = Image.open(spool)
|
||||
fmt = image.format
|
||||
width, height = image.size
|
||||
if width * height > 40_000_000:
|
||||
raise AppError(413, "payload_too_large", "Image exceeds 40 million pixels")
|
||||
if (fmt, declared) not in (("PNG", "image/png"), ("JPEG", "image/jpeg")):
|
||||
raise AppError(415, "unsupported_media_type", "Image content does not match Content-Type")
|
||||
image.verify()
|
||||
except AppError:
|
||||
raise
|
||||
except (UnidentifiedImageError, OSError, Image.DecompressionBombError, Image.DecompressionBombWarning):
|
||||
raise AppError(415, "unsupported_media_type", "Invalid or unsupported image")
|
||||
object_id = str(uuid.uuid4())
|
||||
object_key = f"original/{object_id}"
|
||||
staging_key = f"staging/{object_id}"
|
||||
job_id = str(uuid.uuid4())
|
||||
spool.seek(0)
|
||||
await run_in_threadpool(object_store.s3.put_object, Bucket=object_store.S3_BUCKET,
|
||||
Key=staging_key, Body=spool, ContentLength=size, ContentType=declared)
|
||||
row = store.save_attachment(dict(id=object_id, chat_id=chat_id, owner_id=user_id,
|
||||
filename=filename, content_type=declared, size_bytes=size, sha256=digest.hexdigest(),
|
||||
object_key=object_key, staging_key=staging_key, status="queued", job_id=job_id,
|
||||
variants=[], error_code=None))
|
||||
await run_in_threadpool(jobs.publish, object_id, job_id)
|
||||
return attachment_json(row)
|
||||
except AppError:
|
||||
raise
|
||||
except (BotoCoreError, ClientError):
|
||||
raise AppError(503, "unavailable", "Object storage unavailable")
|
||||
except (redis.exceptions.RedisError, OSError, RuntimeError):
|
||||
raise AppError(503, "unavailable", "Attachment queue unavailable")
|
||||
finally:
|
||||
spool.close()
|
||||
|
||||
|
||||
@app.get("/api/v1/attachments/{attachment_id}")
|
||||
async def get_attachment(attachment_id: str, request: Request):
|
||||
user_id = auth_user(request)
|
||||
validate_uuid(attachment_id)
|
||||
row = store.get_attachment(attachment_id, user_id)
|
||||
if not row:
|
||||
raise AppError(404, "not_found", "Attachment not found")
|
||||
return attachment_json(row)
|
||||
|
||||
|
||||
@app.get("/api/v1/attachments/{attachment_id}/content")
|
||||
async def download_attachment(attachment_id: str, request: Request, variant: str = "original"):
|
||||
user_id = auth_user(request)
|
||||
validate_uuid(attachment_id)
|
||||
row = store.get_attachment(attachment_id, user_id)
|
||||
if not row:
|
||||
raise AppError(404, "not_found", "Attachment not found")
|
||||
if row.status in ("queued", "processing", "failed"):
|
||||
raise AppError(409, "conflict", "Attachment content is not ready")
|
||||
if variant == "original":
|
||||
key, content_type, length = row.object_key, row.content_type, row.size_bytes
|
||||
elif variant in {item.get("name") for item in row.variants or []}:
|
||||
key = f"variants/{attachment_id}/{variant}"
|
||||
item = next(item for item in row.variants if item.get("name") == variant)
|
||||
content_type, length = item["content_type"], item["size_bytes"]
|
||||
else:
|
||||
raise AppError(404, "not_found", "Attachment variant not found")
|
||||
try:
|
||||
obj = await run_in_threadpool(object_store.s3.get_object, Bucket=object_store.S3_BUCKET, Key=key)
|
||||
except (BotoCoreError, ClientError):
|
||||
raise AppError(503, "unavailable", "Object storage unavailable")
|
||||
body = obj["Body"]
|
||||
def chunks():
|
||||
try:
|
||||
while True:
|
||||
chunk = body.read(64 * 1024)
|
||||
if not chunk:
|
||||
break
|
||||
yield chunk
|
||||
finally:
|
||||
body.close()
|
||||
return StreamingResponse(chunks(), media_type=content_type, headers={"Content-Length": str(length)})
|
||||
@@ -0,0 +1,28 @@
|
||||
from pydantic import BaseModel, Field, ConfigDict
|
||||
from typing import List
|
||||
|
||||
|
||||
# ==================== REQUEST MODELS ====================
|
||||
|
||||
class CreateUser(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", str_strip_whitespace=False)
|
||||
username: str = Field(..., pattern=r"^[a-z0-9_]{3,32}$")
|
||||
display_name: str = Field(..., min_length=1, max_length=100)
|
||||
password: str = Field(..., min_length=12, max_length=128)
|
||||
|
||||
|
||||
class CreateChat(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
title: str = Field(..., min_length=1, max_length=100)
|
||||
member_ids: List[str] = Field(..., min_length=1, max_length=100)
|
||||
|
||||
|
||||
class CreateMessage(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
text: str = Field(..., max_length=4000)
|
||||
attachment_ids: List[str] = Field(default_factory=list, max_length=10)
|
||||
|
||||
|
||||
class LoginRequest(BaseModel):
|
||||
username: str
|
||||
password: str
|
||||
@@ -0,0 +1,17 @@
|
||||
"""Private S3-compatible object storage client."""
|
||||
import os
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
from .bao import read_secret
|
||||
|
||||
S3_BUCKET = os.environ.get("S3_BUCKET", "messenger-attachments")
|
||||
_credentials = read_secret(os.getenv("BAO_SECRET_PATH", "messenger/api"))
|
||||
s3 = boto3.client(
|
||||
"s3",
|
||||
endpoint_url=os.environ.get("S3_ENDPOINT", "http://minio:9000"),
|
||||
aws_access_key_id=_credentials["s3_access_key"],
|
||||
aws_secret_access_key=_credentials["s3_secret_key"],
|
||||
region_name=os.environ.get("S3_REGION", "us-east-1"),
|
||||
verify=os.environ.get("S3_CA_FILE", "/run/tls/service-ca.crt"),
|
||||
config=Config(connect_timeout=3, read_timeout=10, retries={"max_attempts": 2}),
|
||||
)
|
||||
@@ -0,0 +1,75 @@
|
||||
"""Redis TTL cache for active sessions; PostgreSQL remains authoritative."""
|
||||
import os
|
||||
import socket
|
||||
from urllib.parse import urlparse
|
||||
from redis import Redis
|
||||
from redis.backoff import NoBackoff
|
||||
from redis.exceptions import RedisError
|
||||
from redis.retry import Retry
|
||||
|
||||
CACHE_URL = os.getenv("CACHE_URL", "redis://redis:6379/0")
|
||||
_cache_address = urlparse(CACHE_URL)
|
||||
_cache_host = _cache_address.hostname or "redis"
|
||||
_cache_port = _cache_address.port or (6380 if _cache_address.scheme == "rediss" else 6379)
|
||||
try:
|
||||
_cache_ips = tuple(dict.fromkeys(item[4][0] for item in socket.getaddrinfo(
|
||||
_cache_host, _cache_port, type=socket.SOCK_STREAM)))
|
||||
except OSError:
|
||||
_cache_ips = (_cache_host,)
|
||||
client = Redis.from_url(CACHE_URL, decode_responses=True,
|
||||
ssl_cert_reqs="required" if _cache_address.scheme == "rediss" else None,
|
||||
ssl_ca_certs=os.getenv("TLS_CA_FILE", "/run/tls/service-ca.crt") if _cache_address.scheme == "rediss" else None,
|
||||
ssl_check_hostname=True if _cache_address.scheme == "rediss" else False,
|
||||
socket_connect_timeout=0.2, socket_timeout=0.2,
|
||||
health_check_interval=15, retry=Retry(NoBackoff(), 0))
|
||||
|
||||
|
||||
class CacheUnavailable(Exception):
|
||||
"""The required session cache cannot be reached within its short timeout."""
|
||||
|
||||
|
||||
def _check_port():
|
||||
# Fail fast when the Redis container is stopped. redis-py may otherwise
|
||||
# spend several seconds cycling through connection retries on Docker DNS.
|
||||
try:
|
||||
for address in _cache_ips:
|
||||
try:
|
||||
with socket.create_connection((address, _cache_port), timeout=0.2):
|
||||
return
|
||||
except OSError:
|
||||
continue
|
||||
raise OSError("Redis is not accepting connections")
|
||||
except OSError as exc:
|
||||
raise CacheUnavailable from exc
|
||||
|
||||
|
||||
def get(token: str):
|
||||
try:
|
||||
_check_port()
|
||||
return client.get("session:" + token)
|
||||
except RedisError as exc:
|
||||
raise CacheUnavailable from exc
|
||||
|
||||
|
||||
def put(token: str, user_id: str, ttl_seconds: int):
|
||||
try:
|
||||
_check_port()
|
||||
client.set("session:" + token, user_id, ex=max(1, ttl_seconds))
|
||||
except RedisError as exc:
|
||||
raise CacheUnavailable from exc
|
||||
|
||||
|
||||
def delete(token: str):
|
||||
try:
|
||||
_check_port()
|
||||
client.delete("session:" + token)
|
||||
except RedisError as exc:
|
||||
raise CacheUnavailable from exc
|
||||
|
||||
|
||||
def ping():
|
||||
try:
|
||||
_check_port()
|
||||
return bool(client.ping())
|
||||
except RedisError as exc:
|
||||
raise CacheUnavailable from exc
|
||||
+248
@@ -0,0 +1,248 @@
|
||||
"""Small repository layer; each operation owns and closes its DB transaction."""
|
||||
import base64
|
||||
import json
|
||||
import uuid
|
||||
from datetime import datetime, timezone, timedelta
|
||||
import math
|
||||
from sqlalchemy import and_, or_, select, update
|
||||
from sqlalchemy.dialects.postgresql import insert
|
||||
from sqlalchemy.orm import selectinload
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from .database import User, Session as SessionRow, Chat, ChatMember, Message, MessageIdempotency, Attachment, SessionLocal
|
||||
from .auth import hash_password, verify_password, new_token, SESSION_TTL_SECONDS
|
||||
from . import session_cache
|
||||
|
||||
|
||||
class Store:
|
||||
def add_user(self, username, display_name, password):
|
||||
with SessionLocal() as db:
|
||||
user = User(username=username, display_name=display_name, password_hash=hash_password(password))
|
||||
db.add(user)
|
||||
try:
|
||||
db.commit()
|
||||
except IntegrityError:
|
||||
db.rollback()
|
||||
raise ValueError("USERNAME_EXISTS")
|
||||
db.refresh(user)
|
||||
return user
|
||||
|
||||
def get_user_by_id(self, user_id):
|
||||
with SessionLocal() as db:
|
||||
return db.query(User).filter(User.id == user_id).first()
|
||||
|
||||
def verify_user_password(self, username, password):
|
||||
with SessionLocal() as db:
|
||||
user = db.query(User).filter(User.username == username).first()
|
||||
# A fixed dummy hash is avoided here; the public contract only requires
|
||||
# identical response status and challenge for unknown users/bad passwords.
|
||||
if not user or not verify_password(password, user.password_hash):
|
||||
return None
|
||||
return user
|
||||
|
||||
def create_session(self, user_id):
|
||||
with SessionLocal() as db:
|
||||
row = SessionRow(token=new_token(), user_id=user_id,
|
||||
expires_at=datetime.now(timezone.utc) + timedelta(seconds=SESSION_TTL_SECONDS))
|
||||
db.add(row)
|
||||
db.commit()
|
||||
db.refresh(row)
|
||||
try:
|
||||
session_cache.put(row.token, row.user_id, SESSION_TTL_SECONDS)
|
||||
except session_cache.CacheUnavailable:
|
||||
db.delete(row)
|
||||
db.commit()
|
||||
raise
|
||||
return row
|
||||
|
||||
def get_session_by_token(self, token):
|
||||
cached_user_id = session_cache.get(token)
|
||||
if cached_user_id:
|
||||
return (cached_user_id, None)
|
||||
with SessionLocal() as db:
|
||||
row = db.query(SessionRow).filter(SessionRow.token == token,
|
||||
SessionRow.expires_at > datetime.now(timezone.utc)).first()
|
||||
if not row:
|
||||
return None
|
||||
remaining = math.ceil((row.expires_at - datetime.now(timezone.utc)).total_seconds())
|
||||
session_cache.put(row.token, row.user_id, remaining)
|
||||
return (row.user_id, row.expires_at)
|
||||
|
||||
def delete_session(self, token):
|
||||
# Require successful cache invalidation before reporting a completed logout.
|
||||
session_cache.delete(token)
|
||||
with SessionLocal() as db:
|
||||
row = db.query(SessionRow).filter(SessionRow.token == token).first()
|
||||
if row:
|
||||
db.delete(row)
|
||||
db.commit()
|
||||
return True
|
||||
return False
|
||||
|
||||
def create_chat(self, title, member_ids, creator_id):
|
||||
if creator_id not in member_ids:
|
||||
raise ValueError("CREATOR_NOT_MEMBER")
|
||||
if len(member_ids) != len(set(member_ids)):
|
||||
raise ValueError("DUPLICATE_MEMBER")
|
||||
with SessionLocal() as db:
|
||||
users = db.query(User.id).filter(User.id.in_(member_ids)).all()
|
||||
if len(users) != len(member_ids):
|
||||
raise ValueError("USER_NOT_FOUND")
|
||||
chat = Chat(title=title)
|
||||
chat.members = [ChatMember(user_id=mid) for mid in member_ids]
|
||||
db.add(chat)
|
||||
db.commit()
|
||||
db.refresh(chat)
|
||||
list(chat.members)
|
||||
return chat
|
||||
|
||||
def get_chat(self, chat_id):
|
||||
with SessionLocal() as db:
|
||||
return db.query(Chat).options(selectinload(Chat.members)).filter(Chat.id == chat_id).first()
|
||||
|
||||
def get_user_chats(self, user_id, cursor=None, limit=50):
|
||||
with SessionLocal() as db:
|
||||
query = db.query(Chat).options(selectinload(Chat.members)).join(ChatMember).filter(ChatMember.user_id == user_id)
|
||||
if cursor:
|
||||
decoded = decode_cursor(cursor, "chats")
|
||||
query = query.filter(or_(Chat.created_at > decoded[0], and_(Chat.created_at == decoded[0], Chat.id > decoded[1])))
|
||||
rows = query.order_by(Chat.created_at, Chat.id).limit(limit).all()
|
||||
for row in rows:
|
||||
list(row.members)
|
||||
return rows
|
||||
|
||||
def is_chat_member(self, chat_id, user_id):
|
||||
with SessionLocal() as db:
|
||||
return db.query(ChatMember.id).filter(ChatMember.chat_id == chat_id, ChatMember.user_id == user_id).first() is not None
|
||||
|
||||
def add_message(self, chat_id, sender_id, text):
|
||||
with SessionLocal() as db:
|
||||
if not db.query(Chat.id).filter(Chat.id == chat_id).first():
|
||||
raise ValueError("CHAT_NOT_FOUND")
|
||||
if not db.query(ChatMember.id).filter(ChatMember.chat_id == chat_id, ChatMember.user_id == sender_id).first():
|
||||
raise ValueError("NOT_MEMBER")
|
||||
msg = Message(chat_id=chat_id, sender_id=sender_id, text=text)
|
||||
db.add(msg)
|
||||
db.commit()
|
||||
db.refresh(msg)
|
||||
return msg
|
||||
|
||||
def add_message_idempotent(self, chat_id, sender_id, text, attachment_ids, key, request_hash):
|
||||
"""Claim a scoped key and create its message in the same DB transaction."""
|
||||
with SessionLocal() as db:
|
||||
if not db.query(ChatMember.id).filter(ChatMember.chat_id == chat_id,
|
||||
ChatMember.user_id == sender_id).first():
|
||||
raise ValueError("CHAT_NOT_FOUND")
|
||||
if not text.strip() and not attachment_ids:
|
||||
raise ValueError("EMPTY_MESSAGE")
|
||||
if attachment_ids:
|
||||
rows = db.query(Attachment).filter(Attachment.id.in_(attachment_ids),
|
||||
Attachment.chat_id == chat_id).all()
|
||||
if len(rows) != len(attachment_ids):
|
||||
raise ValueError("ATTACHMENT_NOT_FOUND")
|
||||
if any(row.status == "failed" for row in rows):
|
||||
raise ValueError("ATTACHMENT_FAILED")
|
||||
scope = dict(user_id=sender_id, method="POST", chat_path=f"/api/v1/chats/{chat_id}/messages", key=key)
|
||||
claim = insert(MessageIdempotency).values(**scope, request_hash=request_hash,
|
||||
message_id=None).on_conflict_do_nothing(
|
||||
constraint="uq_idempotency_scope").returning(MessageIdempotency.id)
|
||||
claimed = db.execute(claim).scalar_one_or_none()
|
||||
if claimed is None:
|
||||
record = db.execute(select(MessageIdempotency).filter_by(**scope)).scalar_one()
|
||||
if record.request_hash != request_hash:
|
||||
raise ValueError("IDEMPOTENCY_CONFLICT")
|
||||
msg = db.get(Message, record.message_id)
|
||||
if msg is None:
|
||||
raise RuntimeError("Idempotency record has no message")
|
||||
return msg
|
||||
msg = Message(chat_id=chat_id, sender_id=sender_id, text=text, attachment_ids=attachment_ids)
|
||||
db.add(msg)
|
||||
db.flush()
|
||||
db.execute(update(MessageIdempotency).where(MessageIdempotency.id == claimed).values(message_id=msg.id))
|
||||
db.commit()
|
||||
db.refresh(msg)
|
||||
return msg
|
||||
|
||||
def get_messages(self, chat_id, cursor=None, limit=50):
|
||||
with SessionLocal() as db:
|
||||
query = db.query(Message).filter(Message.chat_id == chat_id)
|
||||
if cursor:
|
||||
created, message_id = decode_cursor(cursor, chat_id)
|
||||
query = query.filter(or_(Message.created_at > created,
|
||||
and_(Message.created_at == created, Message.id > message_id)))
|
||||
return query.order_by(Message.created_at, Message.id).limit(limit).all()
|
||||
|
||||
def save_attachment(self, attachment):
|
||||
with SessionLocal() as db:
|
||||
row = Attachment(**attachment)
|
||||
db.add(row)
|
||||
db.commit()
|
||||
db.refresh(row)
|
||||
return row
|
||||
|
||||
def get_attachment_for_worker(self, attachment_id):
|
||||
with SessionLocal() as db:
|
||||
return db.query(Attachment).filter(Attachment.id == attachment_id).first()
|
||||
|
||||
def set_attachment_processing(self, attachment_id):
|
||||
with SessionLocal() as db:
|
||||
row = db.query(Attachment).filter(Attachment.id == attachment_id).with_for_update().first()
|
||||
if not row or row.status == "ready":
|
||||
return row
|
||||
row.status = "processing"
|
||||
row.error_code = None
|
||||
row.updated_at = datetime.now(timezone.utc)
|
||||
db.commit()
|
||||
db.refresh(row)
|
||||
return row
|
||||
|
||||
def finish_attachment(self, attachment_id, variants):
|
||||
with SessionLocal() as db:
|
||||
row = db.query(Attachment).filter(Attachment.id == attachment_id).with_for_update().first()
|
||||
if row and row.status != "ready":
|
||||
row.variants = variants
|
||||
row.status = "ready"
|
||||
row.error_code = None
|
||||
row.updated_at = datetime.now(timezone.utc)
|
||||
db.commit()
|
||||
db.refresh(row)
|
||||
return row
|
||||
|
||||
def fail_attachment(self, attachment_id, error_code):
|
||||
with SessionLocal() as db:
|
||||
row = db.query(Attachment).filter(Attachment.id == attachment_id).with_for_update().first()
|
||||
if row and row.status != "ready":
|
||||
row.status = "failed"
|
||||
row.error_code = error_code
|
||||
row.updated_at = datetime.now(timezone.utc)
|
||||
db.commit()
|
||||
|
||||
def get_attachment(self, attachment_id, user_id):
|
||||
with SessionLocal() as db:
|
||||
return db.query(Attachment).join(ChatMember, ChatMember.chat_id == Attachment.chat_id).filter(
|
||||
Attachment.id == attachment_id, ChatMember.user_id == user_id).first()
|
||||
|
||||
|
||||
def encode_cursor(resource, created_at, item_id):
|
||||
raw = json.dumps([resource, created_at.isoformat(), item_id], separators=(",", ":")).encode()
|
||||
return base64.urlsafe_b64encode(raw).decode().rstrip("=")
|
||||
|
||||
|
||||
def decode_cursor(cursor, resource):
|
||||
try:
|
||||
data = json.loads(base64.urlsafe_b64decode(cursor + "=" * (-len(cursor) % 4)))
|
||||
if data[0] != resource:
|
||||
raise ValueError
|
||||
return datetime.fromisoformat(data[1]), data[2]
|
||||
except Exception:
|
||||
raise ValueError("INVALID_CURSOR")
|
||||
|
||||
|
||||
def cursor_for_chat(chat):
|
||||
return encode_cursor("chats", chat.created_at, chat.id)
|
||||
|
||||
|
||||
def cursor_for_message(message):
|
||||
return encode_cursor(message.chat_id, message.created_at, message.id)
|
||||
|
||||
|
||||
store = Store()
|
||||
@@ -0,0 +1,64 @@
|
||||
"""Bounded OTLP instrumentation shared by the API and image worker."""
|
||||
import logging
|
||||
import os
|
||||
import socket
|
||||
from pathlib import Path
|
||||
import grpc
|
||||
|
||||
from opentelemetry import metrics, trace
|
||||
from opentelemetry.exporter.otlp.proto.grpc.metric_exporter import OTLPMetricExporter
|
||||
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
|
||||
from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler
|
||||
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
|
||||
from opentelemetry.sdk.metrics import MeterProvider
|
||||
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
|
||||
from opentelemetry.sdk.resources import Resource
|
||||
from opentelemetry.sdk.trace import TracerProvider
|
||||
from opentelemetry.sdk.trace.export import BatchSpanProcessor
|
||||
|
||||
SERVICE = os.getenv("OTEL_SERVICE_NAME", "messenger-api")
|
||||
ENDPOINT = os.getenv("OTEL_EXPORTER_OTLP_ENDPOINT", "http://otel-collector:4317")
|
||||
configured_attributes = {}
|
||||
for attribute in os.getenv("OTEL_RESOURCE_ATTRIBUTES", "deployment.environment.name=lab").split(","):
|
||||
key, separator, value = attribute.partition("=")
|
||||
if separator and key.strip() not in {"service.name", "service.version", "service.instance.id"}:
|
||||
configured_attributes[key.strip()] = value.strip()
|
||||
resource = Resource.create({
|
||||
"service.name": SERVICE,
|
||||
"service.version": "6.0.0",
|
||||
"service.instance.id": os.getenv("HOSTNAME", socket.gethostname()),
|
||||
**{"deployment.environment.name": "lab", **configured_attributes},
|
||||
})
|
||||
_tls_root = Path(os.getenv("OTEL_TLS_CA", "/run/tls/service-ca.crt")).read_bytes()
|
||||
_tls_key = Path(os.getenv("OTEL_TLS_KEY", "/run/tls/api-otel-client.key" if SERVICE == "messenger-api" else "/run/tls/worker-otel-client.key")).read_bytes()
|
||||
_tls_cert = Path(os.getenv("OTEL_TLS_CERT", "/run/tls/api-otel-client.crt" if SERVICE == "messenger-api" else "/run/tls/worker-otel-client.crt")).read_bytes()
|
||||
_tls_credentials = grpc.ssl_channel_credentials(root_certificates=_tls_root,
|
||||
private_key=_tls_key,
|
||||
certificate_chain=_tls_cert)
|
||||
|
||||
tracer_provider = TracerProvider(resource=resource)
|
||||
tracer_provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter(endpoint=ENDPOINT, insecure=False, credentials=_tls_credentials, timeout=3), max_queue_size=2048, max_export_batch_size=256, schedule_delay_millis=1000, export_timeout_millis=3000))
|
||||
trace.set_tracer_provider(tracer_provider)
|
||||
|
||||
metric_reader = PeriodicExportingMetricReader(OTLPMetricExporter(endpoint=ENDPOINT, insecure=False, credentials=_tls_credentials, timeout=3), export_interval_millis=5000, export_timeout_millis=3000)
|
||||
metrics.set_meter_provider(MeterProvider(resource=resource, metric_readers=[metric_reader]))
|
||||
|
||||
logger_provider = LoggerProvider(resource=resource)
|
||||
logger_provider.add_log_record_processor(BatchLogRecordProcessor(
|
||||
__import__("opentelemetry.exporter.otlp.proto.grpc._log_exporter", fromlist=["OTLPLogExporter"]).OTLPLogExporter(endpoint=ENDPOINT, insecure=False, credentials=_tls_credentials, timeout=3),
|
||||
max_queue_size=2048, max_export_batch_size=256, schedule_delay_millis=1000, export_timeout_millis=3000))
|
||||
logging.getLogger().addHandler(LoggingHandler(level=logging.INFO, logger_provider=logger_provider))
|
||||
logging.getLogger().setLevel(os.getenv("LOG_LEVEL", "INFO"))
|
||||
|
||||
tracer = trace.get_tracer("messenger")
|
||||
meter = metrics.get_meter("messenger")
|
||||
http_requests = meter.create_counter("messenger.http.requests", description="Completed HTTP requests")
|
||||
http_duration = meter.create_histogram("messenger.http.duration", unit="s", description="HTTP request duration")
|
||||
jobs_processed = meter.create_counter("messenger.jobs.processed", description="Completed attachment jobs")
|
||||
job_duration = meter.create_histogram("messenger.jobs.duration", unit="s", description="Attachment processing duration")
|
||||
|
||||
|
||||
def shutdown():
|
||||
logger_provider.force_flush(timeout_millis=3000)
|
||||
tracer_provider.force_flush(timeout_millis=3000)
|
||||
metrics.get_meter_provider().force_flush(timeout_millis=3000)
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
"""At-least-once Redis Streams image worker with idempotent S3/DB effects."""
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import logging
|
||||
import math
|
||||
import os
|
||||
import socket
|
||||
import time
|
||||
import redis
|
||||
from PIL import Image, ImageOps, UnidentifiedImageError
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
from . import object_store
|
||||
from .jobs import QUEUE, CONSUMER_GROUP, MAX_ATTEMPTS, client, publish
|
||||
from .store import store
|
||||
from . import telemetry
|
||||
from opentelemetry.propagate import extract
|
||||
from opentelemetry.trace import SpanKind
|
||||
|
||||
logging.basicConfig(level=os.getenv("LOG_LEVEL", "INFO"))
|
||||
log = logging.getLogger("attachment-worker")
|
||||
CONSUMER = f"worker-{socket.gethostname()}-{os.getpid()}"
|
||||
RECLAIM_IDLE_MS = int(os.getenv("JOB_RECLAIM_IDLE_MS", "30000"))
|
||||
|
||||
|
||||
def thumbnail(source):
|
||||
source.seek(0)
|
||||
with Image.open(source) as opened:
|
||||
image = ImageOps.exif_transpose(opened)
|
||||
image.load()
|
||||
if image.mode in ("RGBA", "LA") or (image.mode == "P" and "transparency" in image.info):
|
||||
rgba = image.convert("RGBA")
|
||||
background = Image.new("RGB", rgba.size, "white")
|
||||
background.paste(rgba, mask=rgba.getchannel("A"))
|
||||
image = background
|
||||
else:
|
||||
image = image.convert("RGB")
|
||||
scale = min(1.0, 256 / image.width, 256 / image.height)
|
||||
dimensions = (max(1, math.floor(image.width * scale)),
|
||||
max(1, math.floor(image.height * scale)))
|
||||
if dimensions != image.size:
|
||||
image = image.resize(dimensions, Image.Resampling.LANCZOS)
|
||||
output = io.BytesIO()
|
||||
image.save(output, format="JPEG", quality=85, optimize=True)
|
||||
return output.getvalue(), image.width, image.height
|
||||
|
||||
|
||||
def process(job):
|
||||
row = store.get_attachment_for_worker(job["attachment_id"])
|
||||
if row is None or row.job_id != job["job_id"] or row.status == "ready":
|
||||
return
|
||||
row = store.set_attachment_processing(row.id)
|
||||
if row is None or row.status == "ready":
|
||||
return
|
||||
obj = object_store.s3.get_object(Bucket=object_store.S3_BUCKET, Key=row.staging_key)
|
||||
raw = obj["Body"].read()
|
||||
obj["Body"].close()
|
||||
try:
|
||||
with Image.open(io.BytesIO(raw)) as image:
|
||||
if image.width * image.height > 40_000_000:
|
||||
raise ValueError("invalid_image")
|
||||
image.verify()
|
||||
except (UnidentifiedImageError, OSError, Image.DecompressionBombError) as exc:
|
||||
raise ValueError("invalid_image") from exc
|
||||
thumb, width, height = thumbnail(io.BytesIO(raw))
|
||||
s3 = object_store.s3
|
||||
s3.put_object(Bucket=object_store.S3_BUCKET, Key=row.object_key, Body=raw,
|
||||
ContentLength=len(raw), ContentType=row.content_type)
|
||||
key = f"variants/{row.id}/thumbnail"
|
||||
s3.put_object(Bucket=object_store.S3_BUCKET, Key=key, Body=thumb,
|
||||
ContentLength=len(thumb), ContentType="image/jpeg")
|
||||
variant = {"name": "thumbnail", "content_type": "image/jpeg",
|
||||
"size_bytes": len(thumb), "width": width, "height": height,
|
||||
"sha256": hashlib.sha256(thumb).hexdigest()}
|
||||
store.finish_attachment(row.id, [variant])
|
||||
|
||||
|
||||
def handle(broker, stream_id, body):
|
||||
job = None
|
||||
started = time.perf_counter()
|
||||
outcome = "success"
|
||||
trace_id = None
|
||||
span_id = None
|
||||
try:
|
||||
job = json.loads(body)
|
||||
if job.get("schema_version") != 1 or job.get("type") != "attachment.process.v1":
|
||||
raise ValueError("invalid_job")
|
||||
parent = extract({key: job[key] for key in ("traceparent", "tracestate") if key in job})
|
||||
with telemetry.tracer.start_as_current_span("attachment.process", context=parent, kind=SpanKind.CONSUMER) as span:
|
||||
span.set_attribute("messenger.job.type", "attachment.process.v1")
|
||||
span.set_attribute("messenger.job.attempt", int(job.get("attempt", 1)))
|
||||
span_context = span.get_span_context()
|
||||
trace_id = format(span_context.trace_id, "032x")
|
||||
span_id = format(span_context.span_id, "016x")
|
||||
process(job)
|
||||
except (ValueError, KeyError) as exc:
|
||||
outcome = "failed"
|
||||
log.warning("permanent job failure code=%s", str(exc)[:64])
|
||||
if job:
|
||||
code = "invalid_image" if str(exc) == "invalid_image" else "invalid_job"
|
||||
store.fail_attachment(job.get("attachment_id"), code)
|
||||
except Exception as exc:
|
||||
outcome = "failed"
|
||||
log.error("attachment processing failure class=%s", type(exc).__name__)
|
||||
if job:
|
||||
attempt = int(job.get("attempt", 1))
|
||||
if attempt >= MAX_ATTEMPTS:
|
||||
store.fail_attachment(job.get("attachment_id"), "retry_exhausted")
|
||||
else:
|
||||
time.sleep(min(2 ** (attempt - 1), 8))
|
||||
# Add the next bounded attempt before acking this delivery.
|
||||
publish(job["attachment_id"], job["job_id"], attempt + 1)
|
||||
finally:
|
||||
telemetry.jobs_processed.add(1, {"job.type": "attachment.process.v1", "job.outcome": outcome})
|
||||
telemetry.job_duration.record(time.perf_counter() - started, {"job.type": "attachment.process.v1", "job.outcome": outcome})
|
||||
logging.getLogger("messenger.worker").info("attachment_job_finished", extra={"job_type": "attachment.process.v1", "job_outcome": outcome, "trace_id": trace_id, "span_id": span_id})
|
||||
broker.xack(QUEUE, CONSUMER_GROUP, stream_id)
|
||||
|
||||
|
||||
def main():
|
||||
while True:
|
||||
try:
|
||||
broker = client()
|
||||
try:
|
||||
broker.xgroup_create(QUEUE, CONSUMER_GROUP, id="0-0", mkstream=True)
|
||||
except redis.ResponseError as exc:
|
||||
if "BUSYGROUP" not in str(exc):
|
||||
raise
|
||||
log.info("worker consuming Redis Stream %s as %s", QUEUE, CONSUMER)
|
||||
cursor = "0-0"
|
||||
while True:
|
||||
reclaimed = broker.xautoclaim(QUEUE, CONSUMER_GROUP, CONSUMER,
|
||||
min_idle_time=RECLAIM_IDLE_MS,
|
||||
start_id=cursor, count=1)
|
||||
cursor, pending = reclaimed[0], reclaimed[1]
|
||||
if pending:
|
||||
for stream_id, fields in pending:
|
||||
handle(broker, stream_id, fields["body"])
|
||||
continue
|
||||
fresh = broker.xreadgroup(CONSUMER_GROUP, CONSUMER,
|
||||
{QUEUE: ">"}, count=1, block=5000)
|
||||
for _, entries in fresh:
|
||||
for stream_id, fields in entries:
|
||||
handle(broker, stream_id, fields["body"])
|
||||
except Exception:
|
||||
log.exception("broker unavailable; reconnecting")
|
||||
time.sleep(2)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,43 @@
|
||||
"""Verify that S3 outages fail readiness/uploads cleanly and recover after restart."""
|
||||
import subprocess
|
||||
import time
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, arguments, run # noqa: E402
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("MinIO outage and recovery checks")
|
||||
# S3 health checks can spend the configured botocore connect timeout on an
|
||||
# unreachable service before the API returns the expected JSON 503.
|
||||
c = Client(args.base_url, args.ca_file, timeout=30)
|
||||
alice, _bob, _eve, chat = c.bootstrap()
|
||||
fixture = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
subprocess.run(["docker", "compose", "--env-file", ".env", "stop", "minio"],
|
||||
cwd=ROOT, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
try:
|
||||
# Nginx may hit its upstream timeout while both replicas are waiting
|
||||
# for the S3 connect timeout, so 504 is also an expected outage result.
|
||||
c.call("GET", "/health/ready", [503, 504])
|
||||
c.call("POST", f"/api/v1/chats/{chat['id']}/attachments?filename=outage.png", [503, 504],
|
||||
actor=alice, raw=fixture, headers={"Content-Type": "image/png"})
|
||||
finally:
|
||||
subprocess.run(["docker", "compose", "--env-file", ".env", "start", "minio"],
|
||||
cwd=ROOT, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
deadline = time.monotonic() + 45
|
||||
while True:
|
||||
try:
|
||||
c.call("GET", "/health/ready", schema="Health")
|
||||
break
|
||||
except Exception:
|
||||
if time.monotonic() >= deadline:
|
||||
raise
|
||||
time.sleep(0.5)
|
||||
print("PASS: MinIO outage returned 503/504 for readiness/upload and recovered after service restart")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,57 @@
|
||||
"""Demonstrate accepted upload recovery while the worker is stopped."""
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, check
|
||||
from image_probe import jpeg_size
|
||||
|
||||
|
||||
def compose(*args):
|
||||
subprocess.run(["docker", "compose", "--env-file", ".env", *args],
|
||||
cwd=ROOT, check=True)
|
||||
|
||||
|
||||
def main():
|
||||
client = Client("http://localhost:8080", timeout=10)
|
||||
alice, bob, _, chat = client.bootstrap()
|
||||
print("Created synthetic users and chat", flush=True)
|
||||
compose("stop", "worker")
|
||||
print("Stopped worker", flush=True)
|
||||
try:
|
||||
attachment, original = client.attachment(alice, chat)
|
||||
print("Upload returned queued", flush=True)
|
||||
sent = client.message(alice, chat, "", attachments=[attachment["id"]])["json"]
|
||||
check(sent["attachment_ids"] == [attachment["id"]], "message did not retain attachment reference")
|
||||
client.call("GET", "/api/v1/attachments/" + attachment["id"] + "/content",
|
||||
409, actor=bob)
|
||||
print("Message linked; content correctly unavailable while queued", flush=True)
|
||||
|
||||
# The worker stays stopped while the API and durable broker are restarted.
|
||||
compose("restart", "api1", "api2", "redis-broker", "lb")
|
||||
print("Restarted API and broker with worker stopped", flush=True)
|
||||
compose("start", "worker")
|
||||
print("Started worker", flush=True)
|
||||
|
||||
ready = client.wait_ready(bob, attachment)
|
||||
original_response = client.call("GET", "/api/v1/attachments/" + attachment["id"] + "/content",
|
||||
actor=bob)
|
||||
check(original_response["bytes"] == original, "recovered original bytes changed")
|
||||
check(hashlib.sha256(original_response["bytes"]).hexdigest() == attachment["sha256"],
|
||||
"recovered original SHA-256 mismatch")
|
||||
thumbnail_meta = next(v for v in ready["variants"] if v["name"] == "thumbnail")
|
||||
thumbnail = client.call("GET", "/api/v1/attachments/" + attachment["id"] +
|
||||
"/content?variant=thumbnail", actor=bob)
|
||||
check(thumbnail["headers"].get_content_type() == "image/jpeg", "thumbnail is not JPEG")
|
||||
check(jpeg_size(thumbnail["bytes"]) == (256, 160), "thumbnail dimensions mismatch")
|
||||
check(hashlib.sha256(thumbnail["bytes"]).hexdigest() == thumbnail_meta["sha256"],
|
||||
"thumbnail checksum mismatch")
|
||||
print("PASS: worker recovery; upload stayed queued through API/broker restart and became ready")
|
||||
finally:
|
||||
compose("start", "worker")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user