From 8c75b7266f9f1f9892f5a833ddd7506b6b640239 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=AF=D0=BA=D0=BE=D0=B2=D0=BB=D0=B5=D0=B2=20=D0=9C=D0=B0?= =?UTF-8?q?=D1=82=D0=B2=D0=B5=D0=B9=20=D0=94=D0=BC=D0=B8=D1=82=D1=80=D0=B8?= =?UTF-8?q?=D0=B5=D0=B2=D0=B8=D1=87?= Date: Sat, 28 Nov 2026 12:29:50 +0100 Subject: [PATCH] =?UTF-8?q?=D0=9B=D0=A0=207:=20TLS/mTLS,=20Argon2id,=20Ope?= =?UTF-8?q?nBao=20=D0=B8=20negative=20tests=20(=D0=BE=D1=86=D0=B5=D0=BD?= =?UTF-8?q?=D0=BA=D0=B0=203)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env.example | 55 +-- Dockerfile | 17 + REPORT.md | 96 ++++- app/__init__.py | 1 + app/__main__.py | 26 ++ app/bao.py | 47 +++ app/broker.py | 49 +++ app/db.py | 172 ++++++++ app/images.py | 49 +++ app/main.py | 682 +++++++++++++++++++++++++++++++ app/s3.py | 70 ++++ app/security.py | 66 +++ app/telemetry.py | 138 +++++++ certs/api.crt | 19 + certs/ca.crt | 19 + certs/db.crt | 19 + certs/ingress.crt | 19 + certs/lb.crt | 19 + certs/mesh-ca.crt | 19 + certs/minio.crt | 19 + certs/openbao.crt | 19 + certs/otel-collector.crt | 19 + certs/redis.crt | 19 + compose.yaml | 225 ++++++++++ contracts/trust-matrix.md | 61 ++- evidence/lifecycle.txt | 92 +++++ infra/grafana-dashboard.json | 65 +++ infra/grafana-dashboards.yml | 13 + infra/grafana-datasources.yml | 26 ++ infra/loki-config.yaml | 34 ++ infra/nginx.conf | 43 ++ infra/otel-collector-config.yaml | 47 +++ infra/prometheus.yml | 14 + infra/tempo-config.yaml | 20 + migrations/001_init.sql | 79 ++++ requirements.txt | 9 + scripts/bootstrap_bao.py | 91 +++++ scripts/demo_worker_restart.py | 55 +++ scripts/generate_certs.py | 107 +++++ scripts/restart.cmd | 5 + scripts/restart.sh | 7 + scripts/stop-one.cmd | 9 + scripts/stop-one.sh | 8 + scripts/stop-worker.cmd | 8 + scripts/stop-worker.sh | 10 + scripts/verify_security.py | 137 +++++++ scripts/verify_telemetry.py | 53 +++ security/app-policy.hcl | 7 + security/bao.hcl | 15 + student-tests/test_security.py | 131 ++++++ worker/__init__.py | 1 + worker/__main__.py | 4 + worker/main.py | 169 ++++++++ 53 files changed, 3114 insertions(+), 89 deletions(-) create mode 100644 Dockerfile create mode 100644 app/__init__.py create mode 100644 app/__main__.py create mode 100644 app/bao.py create mode 100644 app/broker.py create mode 100644 app/db.py create mode 100644 app/images.py create mode 100644 app/main.py create mode 100644 app/s3.py create mode 100644 app/security.py create mode 100644 app/telemetry.py create mode 100644 certs/api.crt create mode 100644 certs/ca.crt create mode 100644 certs/db.crt create mode 100644 certs/ingress.crt create mode 100644 certs/lb.crt create mode 100644 certs/mesh-ca.crt create mode 100644 certs/minio.crt create mode 100644 certs/openbao.crt create mode 100644 certs/otel-collector.crt create mode 100644 certs/redis.crt create mode 100644 compose.yaml create mode 100644 evidence/lifecycle.txt create mode 100644 infra/grafana-dashboard.json create mode 100644 infra/grafana-dashboards.yml create mode 100644 infra/grafana-datasources.yml create mode 100644 infra/loki-config.yaml create mode 100644 infra/nginx.conf create mode 100644 infra/otel-collector-config.yaml create mode 100644 infra/prometheus.yml create mode 100644 infra/tempo-config.yaml create mode 100644 migrations/001_init.sql create mode 100644 requirements.txt create mode 100644 scripts/bootstrap_bao.py create mode 100644 scripts/demo_worker_restart.py create mode 100644 scripts/generate_certs.py create mode 100644 scripts/restart.cmd create mode 100755 scripts/restart.sh create mode 100644 scripts/stop-one.cmd create mode 100755 scripts/stop-one.sh create mode 100644 scripts/stop-worker.cmd create mode 100755 scripts/stop-worker.sh create mode 100644 scripts/verify_security.py create mode 100644 scripts/verify_telemetry.py create mode 100644 security/app-policy.hcl create mode 100644 security/bao.hcl create mode 100644 student-tests/test_security.py create mode 100644 worker/__init__.py create mode 100644 worker/__main__.py create mode 100644 worker/main.py diff --git a/.env.example b/.env.example index 2e9f054..53eb099 100644 --- a/.env.example +++ b/.env.example @@ -1,41 +1,20 @@ # 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 +POSTGRES_USER=messenger +POSTGRES_PASSWORD=replace-with-local-synthetic-password +POSTGRES_DB=messenger +DATABASE_URL=postgresql://messenger:replace-with-local-synthetic-password@db:5432/messenger 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 + +S3_BUCKET=messenger +S3_ACCESS_KEY=messenger +S3_SECRET_KEY=replace-with-local-synthetic-s3-secret +REDIS_PASSWORD=replace-with-local-synthetic-redis + +# TLS trust: public CA is committed in certs/ca.crt, private keys stay local. +TLS_CA_FILE=/certs/ca.crt 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 +BAO_APPROLE_FILE=/certs/private/bao-approle.json +OTEL_EXPORTER_OTLP_ENDPOINT=https://otel-collector:4318 +GRAFANA_PASSWORD=admin-local-only + +MAX_ATTEMPTS=5 diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..c58e923 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,17 @@ +FROM python:3.12-slim + +ENV PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1 PIP_NO_CACHE_DIR=1 +WORKDIR /opt/app + +COPY requirements.txt ./ +RUN pip install --no-cache-dir -r requirements.txt + +COPY app/ ./app/ +COPY worker/ ./worker/ +COPY migrations/ ./migrations/ + +RUN useradd --create-home --uid 10001 appuser && chown -R appuser:appuser /opt/app +USER appuser + +EXPOSE 8080 +CMD ["python", "-m", "app"] diff --git a/REPORT.md b/REPORT.md index 9801db4..180ab6e 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,37 +1,95 @@ # Отчёт — лабораторная 7 -- Автор, группа: TODO -- Целевая оценка; выбранный трек 5, если нужен: TODO -- Commit/PR: TODO после публикации -- Использованные источники, библиотеки и помощь ИИ: TODO +- Автор, группа: Яковлев Матвей Дмитриевич, БПИ2304 +- Целевая оценка; выбранный трек 5, если нужен: 3 +- Commit/PR: ветка: (solution/BPI2304-Yakovlev); MR: (TODO после публикации) +- Использованные источники, библиотеки и помощь ИИ: Python 3.12, FastAPI 0.135.3, psycopg 3.3.3, boto3 1.40.67, argon2-cffi 25.1.0, redis-py 7.4.0, OpenTelemetry 1.45.2, PostgreSQL 16, MinIO, Redis 7, OpenBao 2.2.0, nginx 1.27, Prometheus/Loki/Tempo/Grafana. При подготовке использовалась помощь Claude. -## Запуск из чистого clone +## Bootstrap оператора (из чистого clone) -TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. +```sh +python scripts/generate_certs.py # CA + leaf-сертификаты; приватные ключи — certs/private/ +cp .env.example .env # синтетические локальные секреты; .env не в Git +docker compose --env-file .env up -d +python scripts/bootstrap_bao.py # init 5-of-3, unseal, KV-v2, scoped AppRole, secrets +make test BASE_URL=https://localhost:8443 CA_FILE=$(pwd)/certs/ca.crt +make test-security BASE_URL=https://localhost:8443 CA_FILE=$(pwd)/certs/ca.crt +python scripts/verify_security.py +python scripts/verify_telemetry.py +``` -## Архитектура и решения +Публикуется только `8443` (TLS ingress) и локальные админские порты (8200/3000/9090/…). +Прямого publiчного доступа к API-портам нет: `api1`/`api2` слушают TLS внутри сети Compose +и принимают только mTLS-клиент с identity `lb`. Unseal keys и root token OpenBao хранятся +у оператора в `certs/private/bao-init.json` (вне Git); при обычном рестарте API unseal не нужен. -TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab6, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. +## Модель угроз и решение + +Активы: учётные данные пользователей (Argon2id-хэши), Bearer-сессии, сообщения, байты +вложений, сервисные секреты БД/S3/Redis, приватные ключи TLS. Акторы: клиент, LB, API, +worker, БД, S3, брокер, Collector, телеметрия-бэкенды, OpenBao, оператор. Границы и +проверки перечислены в `contracts/trust-matrix.md` (заполнена, без TODO). + +- **Хранение паролей**: Argon2id, `m=19456 KiB (19 MiB), t=2, p=1, hash_len=32`, + случайная соль 16 байт; формат `argon2id$m$t$p$salt$hash`. Параметры не ниже минимума + курса; подобраны как минимальные проходящие на стенде (19 MiB/2 итерации). +- **Внешний TLS**: nginx с `ingress.crt` (SAN `localhost`, `127.0.0.1`), клиент проверяет + `certs/ca.crt` и hostname. Пустой/чужой trust store отклоняется именно как + `ssl.SSLCertVerificationError` (не «сервер недоступен»). +- **Внутренний mTLS**: LB представляет `lb.crt` upstream'ам; API запускается через + uvicorn с `ssl_cert_reqs=CERT_REQUIRED`, доверяет **отдельному** `mesh-ca.crt`, + которым выпускается единственная client-identity `lb`. Сертификат, подписанный + основным CA, но с SAN `evil-lb`,应用层 не принимается — проверяется не только цепочка, + но и разрешённая identity. Прямой обход через API-порт невозможен. +- **Остальные связи**: PostgreSQL (`sslmode=verify-full`), MinIO (`https` + `verify=cafile`), + Redis (`TLS + CERT_REQUIRED + пароль`), OTel Collector (OTLP/HTTP + `certificate_file`), + OpenBao (HTTPS + AppRole). Раздельные учётные данные и минимальные права зафиксированы в матрице. +- **OpenBao**: не dev-mode, file-бэкенд в volume `baodata`, TLS-листener, 5-of-3 unseal, + AppRole `messenger-app` с policy только на `secret/data/messenger/app`, token TTL 1h/max 4h. + Приложение получает секреты через AppRole (`app/bao.py`), не использует root token или unseal keys. +- **Hardening**: app/worker — non-root в образе, без privileged/host network/Docker socket, + лишние порты не публикуются; логи/трассы не содержат пароли, токены, тела сообщений + и изображения (проверено в Loki/Tempo). +- **Ограничение входа**: общий для реплик счётчик в Redis, 5 попыток/60 с, 6-я → `429` + с `Retry-After: 60`. Ограничение размера запроса (1 MiB JSON / 10 MiB upload) сохранено. + +## Соответствие имен сигналов + +Как в lab6: `http_server_requests_total`, `http_server_duration_bucket`, +`messenger_jobs_total`, `messenger_job_duration_bucket`; логи Loki несут `traceid`/`spanid`, +трассы API и worker — в Tempo. Dashboard UID `messenger-lab6` импортируется provisioning'ом. ## Доказательства критериев -| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | +| Критерий README | Команда | Результат | Файл | | --- | --- | --- | --- | -| Публичный smoke | make test | TODO | TODO | -| Остальные пункты уровня 3 | TODO | TODO | TODO | -| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | -| Выбранный трек 5, если заявлен | TODO | TODO | TODO | - -TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. +| HTTPS с проверяемым CA и hostname | `tests/security.py` | PASS; пустой CA → SSLCertVerificationError | `evidence/lifecycle.txt`, раздел 2 | +| Smoke через HTTPS | `make test` | PASS (upload 202 → ready, thumbnail 256×160) | раздел 1 | +| mTLS LB→API, identity | `verify_security.py` | `MTLS OK` × 2 (нет серта / чужой SAN) | раздел 3 | +| Argon2id | unit-тесты | `argon2id$2$19456$1$...`, 16 тестов OK | раздел 8 | +| OpenBao policy | `verify_security.py` | `BAO OK`: своя path read, write/чужой → 403 | раздел 3 | +| Rate limit | `verify_security.py` | `RATE OK: 5×401 → 429 + Retry-After=60` | раздел 3 | +| Сессии/вложения при рестарте по HTTPS | persistence | PASS | раздел 5 | +| Отказ реплики через mTLS-mesh | failover | 2 реплики, 103 записи, recovery 0.879 с, PASS | разделы 6–7 | +| Телеметрия по TLS | `verify_telemetry.py` | METRICS/LOGS/TRACES/GRAFANA OK | раздел 4 | ## Эксперименты и отказы -TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. +Не проводились (целевая оценка 3); уровень 4 требует ротации, expiry/revocation, + сбалансированных алертов и разбора двух инцидентов — не заявлен. -| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | +| Воздействие | Что ожидаем | Что наблюдали | Время / потери | | --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | +| Не trusted CA / нет client cert / чужой SAN | отказ на TLS-уровне | три отрицательных теста PASS | потерь нет | +| Останов API-реплики | вторая продолжает через LB | 103 успешные записи, recovery 0.879 с | потерь нет | +| Перезапускstores | данные и сессии сохраняются | PASS | потерь нет | ## Ограничения и следующие шаги -TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. +- Уровень 4 не реализован: нет mTLS на API/worker→broker и →Collector с разными service + identities (здесь TLS + server verification), нет rotation/expiry/DLQ, outbox, + read_only/no-new-privileges, dependency scan и полного аудита 6 угроз. +- OpenBao требует ручного unseal после рестарта контейнера; это документированное допущение уровня 3. +- MinIO, Redis и Collector шифруют трафик с проверкой сервера, но не mTLS — + уровень 4 требует расширения матрицы. +- Локальный CA и синтетические ключи создаются скриптом и подходят только для изолированного стенда. diff --git a/app/__init__.py b/app/__init__.py new file mode 100644 index 0000000..a4254e9 --- /dev/null +++ b/app/__init__.py @@ -0,0 +1 @@ +"""Messenger lab2: PostgreSQL-backed API.""" diff --git a/app/__main__.py b/app/__main__.py new file mode 100644 index 0000000..254be3a --- /dev/null +++ b/app/__main__.py @@ -0,0 +1,26 @@ +"""Local entry point: python -m app (HTTPS with required client cert inside the mesh).""" +import os +import ssl + +import uvicorn + +if __name__ == "__main__": + cert = os.environ.get("TLS_CERTFILE") + key = os.environ.get("TLS_KEYFILE") + options = {} + if cert and key: + options = dict( + ssl_certfile=cert, + ssl_keyfile=key, + ssl_ca_certs=os.environ.get("TLS_CLIENT_CA", "/certs/ca.crt"), + ssl_cert_reqs=ssl.CERT_REQUIRED if os.environ.get("TLS_REQUIRE_CLIENT", "1") == "1" + else ssl.CERT_NONE, + ) + uvicorn.run( + "app.main:app", + host=os.environ.get("APP_HOST", "0.0.0.0"), + port=int(os.environ.get("APP_PORT", "8443")), + workers=1, + log_level=os.environ.get("LOG_LEVEL", "info"), + **options, + ) diff --git a/app/bao.py b/app/bao.py new file mode 100644 index 0000000..8ccd38e --- /dev/null +++ b/app/bao.py @@ -0,0 +1,47 @@ +"""Fetch runtime secrets from OpenBao using a scoped AppRole (never root token).""" +import json +import logging +import os +import ssl +import urllib.request +from pathlib import Path + +log = logging.getLogger("messenger.bao") + + +def load_secrets(): + """Populate environment variables from secret/messenger/app via AppRole login.""" + if os.environ.get("BAO_ENABLED", "1") == "0": + log.info("OpenBao integration disabled for local offline work") + return {} + creds_path = Path(os.environ.get("BAO_APPROLE_FILE", "/certs/private/bao-approle.json")) + if not creds_path.exists(): + raise RuntimeError("AppRole credentials are missing: run scripts/bootstrap_bao.py") + creds = json.loads(creds_path.read_text()) + ca = os.environ.get("TLS_CA_FILE", "/certs/ca.crt") + address = os.environ.get("BAO_ADDR", "https://openbao:8200").rstrip("/") + context = ssl.create_default_context(cafile=ca) + + def post(path, body, token=None): + headers = {"Content-Type": "application/json"} + if token: + headers["X-Vault-Token"] = token + request = urllib.request.Request( + address + path, data=json.dumps(body).encode(), headers=headers, method="POST") + with urllib.request.urlopen(request, context=context, timeout=8) as response: + return json.loads(response.read()) + + login = post("/v1/auth/approle/login", { + "role_id": creds["role_id"], "secret_id": creds["secret_id"], + }) + token = login["auth"]["client_token"] + request = urllib.request.Request(address + "/v1/secret/data/messenger/app", + headers={"X-Vault-Token": token}) + with urllib.request.urlopen(request, context=context, timeout=8) as response: + secret = json.loads(response.read())["data"]["data"] + + for key in ("DATABASE_URL", "S3_ACCESS_KEY", "S3_SECRET_KEY", "REDIS_PASSWORD"): + if key in secret: + os.environ[key] = str(secret[key]) + log.info("loaded scoped secrets from OpenBao (token TTL=%s)", login["auth"].get("lease_duration")) + return secret diff --git a/app/broker.py b/app/broker.py new file mode 100644 index 0000000..179e429 --- /dev/null +++ b/app/broker.py @@ -0,0 +1,49 @@ +"""Redis Streams durable job broker (at-least-once, consumer group, no bytes in messages).""" +import json +import logging +import os + +log = logging.getLogger("messenger.broker") + +client = None +STREAM = "attachment.jobs" +GROUP = "attachment-workers" + + +def start(): + global client + import redis + import ssl + client = redis.Redis( + host=os.environ.get("BROKER_HOST", "redis"), + port=int(os.environ.get("BROKER_PORT", "6379")), + db=0, + decode_responses=True, + socket_connect_timeout=3, + socket_timeout=5, + password=os.environ.get("REDIS_PASSWORD"), + ssl=True, + ssl_cert_reqs=ssl.CERT_REQUIRED, + ssl_ca_certs=os.environ.get("TLS_CA_FILE", "/certs/ca.crt"), + ) + client.ping() + try: + client.xgroup_create(STREAM, GROUP, id="0", mkstream=True) + except redis.ResponseError as exc: + if "BUSYGROUP" not in str(exc): + raise + log.info("broker ready: stream=%s group=%s", STREAM, GROUP) + + +def publish(job): + """Publisher confirm = the XADD reply id. The job carries IDs, never bytes or secrets.""" + return client.xadd(STREAM, {"job": json.dumps(job, ensure_ascii=False)}) + + +def ready(): + try: + client.ping() + return True + except Exception: + log.exception("broker readiness check failed") + return False diff --git a/app/db.py b/app/db.py new file mode 100644 index 0000000..0b2d35e --- /dev/null +++ b/app/db.py @@ -0,0 +1,172 @@ +"""PostgreSQL access: small bounded connection pool, versioned migrations, row helpers.""" +import logging +import os +import queue +from contextlib import contextmanager +from datetime import timezone +from pathlib import Path + +import psycopg +from psycopg.rows import dict_row + +log = logging.getLogger("messenger.db") + +ROOT = Path(__file__).resolve().parents[1] +MIGRATIONS = ROOT / "migrations" + + +def _read_secret(path): + if not path: + return None + value = Path(path).read_text(encoding="utf-8").strip() + if not value: + raise RuntimeError("secret file is empty: " + path) + return value + + +def database_url(): + """Prefer a mounted secret file; fall back to an environment variable for local runs.""" + url = _read_secret(os.environ.get("DATABASE_URL_FILE")) + if url: + return url + url = os.environ.get("DATABASE_URL") + if not url: + raise RuntimeError("DATABASE_URL or DATABASE_URL_FILE is required") + if os.environ.get("DB_TLS", "1") != "0": + separator = "&" if "?" in url else "?" + url += separator + "sslmode=verify-full&sslrootcert=" + os.environ.get( + "TLS_CA_FILE", "/certs/ca.crt") + return url + + +class Database: + """A tiny FIFO pool. Each request borrows one connection and returns it.""" + + def __init__(self): + self._pool = None + self.dsn = None + + def start(self): + self.dsn = database_url() + size = int(os.environ.get("DB_POOL_MAX", "8")) + self._pool = queue.Queue(maxsize=size) + for _ in range(size): + self._pool.put(self._connect()) + self.migrate() + + def _connect(self): + return psycopg.connect(self.dsn, connect_timeout=3, row_factory=dict_row, autocommit=True) + + def stop(self): + if self._pool is None: + return + while not self._pool.empty(): + try: + self._pool.get_nowait().close() + except queue.Empty: + break + self._pool = None + + @contextmanager + def connection(self): + conn = self._pool.get(timeout=5) + try: + yield conn + finally: + self._pool.put(conn) + + @contextmanager + def transaction(self): + with self.connection() as conn: + # Explicit BEGIN/COMMIT; rollback on any exception. + conn.execute("BEGIN") + try: + yield conn + except BaseException: + conn.execute("ROLLBACK") + raise + else: + conn.execute("COMMIT") + + def ready(self): + try: + with self.connection() as conn: + conn.execute("SELECT 1").fetchone() + return True + except Exception: + log.exception("readiness check failed") + return False + + def migrate(self): + """Apply *.sql in name order, at most once each; restart-safe with the same volume.""" + with self.transaction() as conn: + # All API replicas start against the same database. A transaction-scoped + # advisory lock makes the migration step strictly single-runner: + # the second replica waits, then sees schema_migrations already filled. + conn.execute("SELECT pg_advisory_xact_lock(20261116)") + conn.execute( + "CREATE TABLE IF NOT EXISTS schema_migrations (" + "name TEXT PRIMARY KEY, applied_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp())" + ) + applied = {r["name"] for r in conn.execute("SELECT name FROM schema_migrations").fetchall()} + for path in sorted(MIGRATIONS.glob("*.sql")): + if path.name in applied: + continue + conn.execute(path.read_text(encoding="utf-8")) + conn.execute("INSERT INTO schema_migrations(name) VALUES (%s)", (path.name,)) + log.info("applied migration %s", path.name) + + +db = Database() + + +def utc_text(value): + """RFC 3339 UTC with an explicit Z and microsecond precision.""" + value = value.astimezone(timezone.utc) + return value.strftime("%Y-%m-%dT%H:%M:%S.%fZ") + + +def user_public(row): + return { + "id": str(row["id"]), + "username": row["username"], + "display_name": row["display_name"], + "created_at": utc_text(row["created_at"]), + } + + +def chat_public(row): + return { + "id": str(row["id"]), + "title": row["title"], + "member_ids": [str(x) for x in (row["member_ids"] or [])], + "created_at": utc_text(row["created_at"]), + } + + +def message_public(row): + return { + "id": str(row["id"]), + "chat_id": str(row["chat_id"]), + "sender_id": str(row["sender_id"]), + "text": row["text"], + "attachment_ids": [str(x) for x in (row["attachment_ids"] or [])], + "created_at": utc_text(row["created_at"]), + } + + +def attachment_public(row): + return { + "id": str(row["id"]), + "chat_id": str(row["chat_id"]), + "owner_id": str(row["owner_id"]), + "filename": row["filename"], + "content_type": row["content_type"], + "size_bytes": row["size_bytes"], + "sha256": row["sha256"], + "status": row["status"], + "variants": row["variants"] or [], + "error_code": row["error_code"], + "created_at": utc_text(row["created_at"]), + "updated_at": utc_text(row["updated_at"]), + } diff --git a/app/images.py b/app/images.py new file mode 100644 index 0000000..8d4da42 --- /dev/null +++ b/app/images.py @@ -0,0 +1,49 @@ +"""Cheap header-only PNG/JPEG probing: magic, declared MIME and pixel limit.""" +import struct + +PNG_MAGIC = b"\x89PNG\r\n\x1a\n" +JPEG_MAGIC = b"\xff\xd8\xff" +SOF_MARKERS = {0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF} + + +class InvalidImage(ValueError): + pass + + +def probe(data): + """Return (content_type, width, height) without decoding the whole image.""" + if data.startswith(PNG_MAGIC): + if len(data) < 24 or data[12:16] != b"IHDR": + raise InvalidImage("truncated PNG") + width, height = struct.unpack(">II", data[16:24]) + if width == 0 or height == 0: + raise InvalidImage("invalid PNG dimensions") + return "image/png", width, height + + if data[:3] == JPEG_MAGIC: + i = 2 + while i + 9 < len(data): + if data[i] != 0xFF: + i += 1 + continue + marker = data[i + 1] + if marker == 0xFF: + i += 1 + continue + if marker == 0xD8 or 0xD0 <= marker <= 0xD7 or marker == 0x01: + i += 2 + continue + if marker == 0xD9: + break + length = struct.unpack(">H", data[i + 2:i + 4])[0] + if length < 2 or i + 2 + length > len(data): + raise InvalidImage("truncated JPEG segment") + if marker in SOF_MARKERS: + height, width = struct.unpack(">HH", data[i + 5:i + 9]) + if width == 0 or height == 0: + raise InvalidImage("invalid JPEG dimensions") + return "image/jpeg", width, height + i += 2 + length + raise InvalidImage("JPEG has no SOF marker") + + raise InvalidImage("not a PNG or JPEG") diff --git a/app/main.py b/app/main.py new file mode 100644 index 0000000..2ecb79d --- /dev/null +++ b/app/main.py @@ -0,0 +1,682 @@ +"""Lab2 messenger HTTP layer. Contract: contracts/openapi.json. + +State lives in PostgreSQL: users, chats, memberships, messages and sessions. +Basic is accepted only on POST /auth/sessions; every other protected route needs Bearer. +""" +import base64 +import binascii +import datetime as dt +import hashlib +import json +import logging +import os +import collections +import re +import threading +import time +import uuid +from contextlib import asynccontextmanager + +import psycopg +from fastapi import FastAPI, Request +from fastapi.exceptions import RequestValidationError +from fastapi.responses import JSONResponse, Response +from starlette.datastructures import MutableHeaders +from starlette.exceptions import HTTPException as StarletteHTTPException + +from . import broker, s3, telemetry +from .db import attachment_public, chat_public, db, message_public, user_public, utc_text +from .images import InvalidImage, probe +from .security import bearer_token, hash_password, parse_basic, token_hash, verify_password + +log = logging.getLogger("messenger") + +MAX_BODY_BYTES = 1 << 20 +MAX_UPLOAD_BYTES = 10 * 1024 * 1024 # 10 MiB +MAX_IMAGE_PIXELS = 40_000_000 +DEFAULT_LIMIT, MAX_LIMIT = 50, 100 +USERNAME_RE = re.compile(r"[a-z0-9_]{3,32}\Z") +UUID_RE = re.compile(r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\Z") +IDEMPOTENCY_KEY_RE = re.compile(r"[A-Za-z0-9._:-]{1,128}\Z") +BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"' +BEARER_CHALLENGE = 'Bearer realm="messenger"' +INSTANCE_ID = os.environ.get("INSTANCE_ALIAS") or uuid.uuid4().hex[:12] + +UTC = dt.timezone.utc + +# Local login rate limit (per process; shared across replicas is level 4). +LOGIN_MAX_ATTEMPTS = 5 +LOGIN_WINDOW_SECONDS = 60 +_login_attempts = collections.defaultdict(collections.deque) +_login_lock = threading.Lock() + + +def limit_login(username): + """Shared across API replicas via the broker; local fallback before startup.""" + key = "rate:login:" + username + try: + if broker.client is not None: + count = broker.client.incr(key) + if count == 1: + broker.client.expire(key, LOGIN_WINDOW_SECONDS) + limited = count > LOGIN_MAX_ATTEMPTS + else: + raise RuntimeError("broker not ready") + except Exception: + now = time.monotonic() + with _login_lock: + window = _login_attempts[username] + while window and now - window[0] > LOGIN_WINDOW_SECONDS: + window.popleft() + if len(window) >= LOGIN_MAX_ATTEMPTS: + limited = True + else: + window.append(now) + limited = False + if limited: + raise ApiError(429, "rate_limited", "Слишком много попыток входа", + {"Retry-After": str(LOGIN_WINDOW_SECONDS)}) + + +class ApiError(Exception): + def __init__(self, status, code, message, headers=None): + self.status, self.code, self.message, self.headers = status, code, message, headers + + +def bad_request(message): + return ApiError(400, "invalid_request", message) + + +def unauthorized(challenge, message="Требуется действительная аутентификация"): + return ApiError(401, "unauthorized", message, {"WWW-Authenticate": challenge}) + + +def not_found(): + return ApiError(404, "not_found", "Объект не найден") + + +def error_response(status, code, message, request_id, headers=None): + body = {"error": {"code": code, "message": message, "request_id": request_id}} + return JSONResponse(body, status_code=status, headers=headers) + + +class RequestContextMiddleware: + """Request IDs, server spans and low-cardinality HTTP metrics for every response.""" + + def __init__(self, app): + self.app = app + + async def __call__(self, scope, receive, send): + if scope["type"] != "http": + await self.app(scope, receive, send) + return + request_id = str(uuid.uuid4()) + scope.setdefault("state", {})["request_id"] = request_id + started = False + status = [None] + begun = time.monotonic() + + async def send_with_id(message): + nonlocal started + if message["type"] == "http.response.start": + started = True + status[0] = message["status"] + headers = MutableHeaders(scope=message) + headers["X-Request-Id"] = request_id + headers["X-Instance-Id"] = INSTANCE_ID + await send(message) + + with telemetry.http_span(scope["method"], "unmatched") as span: + try: + await self.app(scope, receive, send_with_id) + except Exception: + log.exception("unhandled error request_id=%s", request_id) + if not started: + response = error_response(500, "internal_error", "Внутренняя ошибка сервера", request_id) + await response(scope, receive, send_with_id) + finally: + route = scope.get("route") + # Use the route TEMPLATE, never the raw path with UUIDs. + template = route.path if route is not None else "unmatched" + code = status[0] or 500 + status_class = "%dxx" % (code // 100) + telemetry.record_http(scope["method"], template, status_class, time.monotonic() - begun) + if span is not None and span.is_recording(): + span.set_attribute("http.response.status_code", code) + span.set_attribute("messenger.request_id", request_id) + + +@asynccontextmanager +async def lifespan(app): + from .bao import load_secrets + load_secrets() + telemetry.init("messenger-api", INSTANCE_ID) + db.start() + s3.start() + broker.start() + try: + yield + finally: + db.stop() + + +app = FastAPI(title="Messenger lab2", docs_url=None, redoc_url=None, openapi_url=None, lifespan=lifespan) +app.add_middleware(RequestContextMiddleware) + + +@app.exception_handler(ApiError) +async def handle_api_error(request: Request, exc: ApiError): + return error_response(exc.status, exc.code, exc.message, request.state.request_id, exc.headers) + + +@app.exception_handler(StarletteHTTPException) +async def handle_http_exception(request: Request, exc: StarletteHTTPException): + if exc.status_code == 404: + code, message = "not_found", "Объект не найден" + elif exc.status_code < 500: + code, message = "invalid_request", "Некорректный запрос" + else: + code, message = "internal_error", "Внутренняя ошибка сервера" + return error_response(exc.status_code, code, message, request.state.request_id, exc.headers) + + +@app.exception_handler(RequestValidationError) +async def handle_validation_error(request: Request, exc: RequestValidationError): + return error_response(400, "invalid_request", "Некорректный запрос", request.state.request_id) + + +# ---------- validation helpers ---------- + +def clean_string(data, field, max_len): + value = data.get(field) + if not isinstance(value, str): + raise bad_request("Поле %s должно быть строкой" % field) + if not value.strip() or len(value) > max_len: + raise bad_request("Поле %s должно содержать от 1 до %d символов" % (field, max_len)) + return value + + +def idempotency_key(request): + value = request.headers.get("idempotency-key") + if not value or not IDEMPOTENCY_KEY_RE.fullmatch(value): + raise bad_request("Idempotency-Key обязателен и должен соответствовать [A-Za-z0-9._:-]{1,128}") + return value + + +async def read_raw(request, limit): + """Read a binary body with a hard byte limit applied before buffering everything.""" + declared = request.headers.get("content-length", "") + if declared.isdigit() and int(declared) > limit: + raise ApiError(413, "payload_too_large", "Файл слишком большой") + body = bytearray() + async for chunk in request.stream(): + body += chunk + if len(body) > limit: + raise ApiError(413, "payload_too_large", "Файл слишком большой") + return bytes(body) + + +def validate_filename(value): + if not isinstance(value, str) or not 1 <= len(value) <= 255: + raise bad_request("filename должен содержать от 1 до 255 символов") + if any(ch in value for ch in ("/", "\\", "\x00")) or any(ord(ch) < 32 or ord(ch) == 127 for ch in value): + raise bad_request("filename содержит недопустимые символы") + return value + + +def parse_uuid(value, what): + if not isinstance(value, str) or not UUID_RE.fullmatch(value): + raise bad_request("Некорректный UUID: %s" % what) + return value.lower() + + +async def read_json_object(request, required, optional=()): + declared = request.headers.get("content-length", "") + if declared.isdigit() and int(declared) > MAX_BODY_BYTES: + raise ApiError(413, "payload_too_large", "Тело запроса слишком большое") + content_type = request.headers.get("content-type", "").split(";")[0].strip().lower() + if content_type and content_type != "application/json": + raise ApiError(415, "unsupported_media_type", "Ожидается application/json") + body = bytearray() + async for chunk in request.stream(): + body += chunk + if len(body) > MAX_BODY_BYTES: + raise ApiError(413, "payload_too_large", "Тело запроса слишком большое") + try: + data = json.loads(bytes(body).decode("utf-8")) + except (UnicodeDecodeError, ValueError): + raise bad_request("Тело запроса не является корректным JSON") from None + if not isinstance(data, dict): + raise bad_request("Тело запроса должно быть JSON-объектом") + expected = set(required) | set(optional) + if not set(required).issubset(data) or not set(data).issubset(expected): + raise bad_request("Ожидаемые поля: " + ", ".join(sorted(expected))) + return data + + +def page_params(request): + query = request.query_params + raw_limit = query.getlist("limit") + if len(raw_limit) > 1 or len(query.getlist("cursor")) > 1: + raise bad_request("Параметры limit и cursor можно указать только один раз") + limit = DEFAULT_LIMIT + if raw_limit: + text = raw_limit[0] + if not (text.isascii() and text.isdigit()) or not 1 <= int(text) <= MAX_LIMIT: + raise bad_request("limit должен быть целым числом от 1 до %d" % MAX_LIMIT) + limit = int(text) + return limit, query.get("cursor") or None + + +def encode_cursor(kind, scope, created_at, item_id): + raw = json.dumps( + {"k": kind, "s": scope, + "t": int(created_at.timestamp() * 1_000_000), + "i": uuid.UUID(str(item_id)).int}, + separators=(",", ":"), + ) + return base64.urlsafe_b64encode(raw.encode()).decode().rstrip("=") + + +def decode_cursor(text, kind, scope): + try: + data = json.loads(base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))) + t, i = data["t"], data["i"] + valid = (data["k"] == kind and data["s"] == scope + and type(t) is int and type(i) is int and t >= 0 and i >= 0) + if not valid: + raise ValueError + return dt.datetime.fromtimestamp(t / 1_000_000, tz=UTC), uuid.UUID(int=i) + except (ValueError, KeyError, TypeError, binascii.Error, OverflowError): + raise bad_request("Некорректный cursor") from None + + +def page_response(items, limit, kind, scope, rows): + """items are public JSON dicts; rows are the raw DB rows used for the opaque cursor.""" + more = len(items) > limit + window = items[:limit] + last = rows[limit - 1] if more and len(rows) >= limit else None + cursor = (encode_cursor(kind, scope, last["created_at"], last["id"]) + if last is not None else None) + return JSONResponse({"items": window, "next_cursor": cursor}) + + +# ---------- authentication and resource access ---------- + +def current_user(request): + """Lab2: only an opaque Bearer session identifies the caller; X-User-Id is ignored.""" + token = bearer_token(request.headers.get("authorization")) + if not token: + raise unauthorized(BEARER_CHALLENGE) + with db.connection() as conn: + row = conn.execute( + "SELECT u.id, u.username, u.display_name, u.created_at " + "FROM sessions s JOIN users u ON u.id = s.user_id " + "WHERE s.token_hash = %s AND s.expires_at > clock_timestamp()", + (token_hash(token),), + ).fetchone() + if row is None: + raise unauthorized(BEARER_CHALLENGE) + return user_public(row) + + +def authenticated_chat(request, chat_id): + user = current_user(request) + chat_uuid = parse_uuid(chat_id, "chat_id") + with db.connection() as conn: + row = conn.execute( + "SELECT c.id, c.title, c.created_at, " + "array_agg(m.user_id ORDER BY m.user_id) AS member_ids " + "FROM chats c JOIN chat_members m ON m.chat_id = c.id " + "WHERE c.id = %s AND m.user_id = %s GROUP BY c.id", + (chat_uuid, uuid.UUID(user["id"])), + ).fetchone() + if row is None: + raise not_found() # unknown and foreign chats look identical + return user, chat_public(row) + + +# ---------- health ---------- + +@app.get("/health/live") +async def live(): + return {"status": "ok"} + + +@app.get("/health/ready") +async def ready(): + if not db.ready(): + raise ApiError(503, "unavailable", "Хранилище данных недоступно") + if not s3.ready(): + raise ApiError(503, "unavailable", "Хранилище вложений недоступно") + if not broker.ready(): + raise ApiError(503, "unavailable", "Брокер заданий недоступен") + return {"status": "ok"} + + +# ---------- users and sessions ---------- + +@app.post("/api/v1/users") +async def register_user(request: Request): + data = await read_json_object(request, ("username", "display_name", "password")) + username = data["username"] + if not isinstance(username, str) or not USERNAME_RE.fullmatch(username): + raise bad_request("username должен соответствовать [a-z0-9_]{3,32}") + display_name = clean_string(data, "display_name", 100) + password = data["password"] + if not isinstance(password, str) or not 12 <= len(password) <= 128: + raise bad_request("password должен содержать от 12 до 128 символов") + user_id = uuid.uuid4() + try: + with db.transaction() as conn: + conn.execute( + "INSERT INTO users(id, username, display_name, password_hash) VALUES (%s,%s,%s,%s)", + (user_id, username, display_name, hash_password(password)), + ) + row = conn.execute("SELECT * FROM users WHERE id = %s", (user_id,)).fetchone() + except psycopg.errors.UniqueViolation: + raise ApiError(409, "conflict", "Имя пользователя уже занято") from None + return JSONResponse(user_public(row), status_code=201) + + +@app.post("/api/v1/auth/sessions") +async def create_session(request: Request): + credential = parse_basic(request.headers.get("authorization")) + if credential is None: + raise unauthorized(BASIC_CHALLENGE, "Неверные учетные данные") + username, password = credential + limit_login(username) + with db.connection() as conn: + row = conn.execute("SELECT * FROM users WHERE username = %s", (username,)).fetchone() + if row is None or not verify_password(password, row["password_hash"]): + raise unauthorized(BASIC_CHALLENGE, "Неверные учетные данные") + token = base64.urlsafe_b64encode(os.urandom(32)).decode().rstrip("=") + ttl = int(os.environ.get("SESSION_TTL_SECONDS", "3600")) + expires_at = dt.datetime.now(UTC) + dt.timedelta(seconds=ttl) + with db.transaction() as conn: + conn.execute( + "INSERT INTO sessions(token_hash, user_id, expires_at) VALUES (%s,%s,%s)", + (token_hash(token), row["id"], expires_at), + ) + return JSONResponse({ + "token": token, + "token_type": "Bearer", + "expires_at": utc_text(expires_at), + "user": user_public(row), + }, status_code=201) + + +@app.delete("/api/v1/auth/sessions/current") +async def revoke_session(request: Request): + token = bearer_token(request.headers.get("authorization")) + if not token: + raise unauthorized(BEARER_CHALLENGE) + with db.transaction() as conn: + result = conn.execute( + "DELETE FROM sessions WHERE token_hash = %s AND expires_at > clock_timestamp()", + (token_hash(token),), + ) + if result.rowcount == 0: + raise unauthorized(BEARER_CHALLENGE) + return Response(status_code=204) + + +@app.get("/api/v1/users/me") +async def get_me(request: Request): + return current_user(request) + + +# ---------- chats ---------- + +@app.post("/api/v1/chats") +async def create_chat(request: Request): + user = current_user(request) + data = await read_json_object(request, ("title", "member_ids")) + title = clean_string(data, "title", 100) + raw_members = data["member_ids"] + if not isinstance(raw_members, list) or not 1 <= len(raw_members) <= 100: + raise bad_request("member_ids должен быть списком из 1–100 UUID") + members = [parse_uuid(m, "member_ids") for m in raw_members] + if len(set(members)) != len(members): + raise bad_request("member_ids содержит дубликаты") + if user["id"] not in members: + raise bad_request("member_ids должен содержать вызывающего пользователя") + chat_id = uuid.uuid4() + member_uuids = [uuid.UUID(x) for x in members] + try: + with db.transaction() as conn: + found = conn.execute( + "SELECT id FROM users WHERE id = ANY(%s::uuid[])", (member_uuids,) + ).fetchall() + if len(found) != len(member_uuids): + raise bad_request("member_ids содержит неизвестного пользователя") + conn.execute("INSERT INTO chats(id, title) VALUES (%s,%s)", (chat_id, title)) + for member in member_uuids: + conn.execute( + "INSERT INTO chat_members(chat_id, user_id) VALUES (%s,%s)", + (chat_id, member), + ) + row = conn.execute( + "SELECT c.id, c.title, c.created_at, array_agg(m.user_id ORDER BY m.user_id) AS member_ids " + "FROM chats c JOIN chat_members m ON m.chat_id = c.id WHERE c.id = %s GROUP BY c.id", + (chat_id,), + ).fetchone() + except psycopg.errors.ForeignKeyViolation: + raise bad_request("member_ids содержит неизвестного пользователя") from None + return JSONResponse(chat_public(row), status_code=201) + + +@app.get("/api/v1/chats") +async def list_chats(request: Request): + user = current_user(request) + limit, cursor = page_params(request) + after = decode_cursor(cursor, "chats", user["id"]) if cursor else None + sql = ( + "SELECT c.id, c.title, c.created_at, array_agg(m.user_id ORDER BY m.user_id) AS member_ids " + "FROM chats c JOIN chat_members m ON m.chat_id = c.id WHERE m.user_id = %s" + ) + params = [uuid.UUID(user["id"])] + if after: + sql += " AND (c.created_at, c.id) > (%s, %s::uuid)" + params.extend([after[0], after[1]]) + sql += " GROUP BY c.id ORDER BY c.created_at, c.id LIMIT %s" + params.append(limit + 1) + with db.connection() as conn: + rows = conn.execute(sql, params).fetchall() + items = [chat_public(r) for r in rows] + return page_response(items, limit, "chats", user["id"], rows) + + +@app.get("/api/v1/chats/{chat_id}") +async def get_chat(chat_id: str, request: Request): + _, chat = authenticated_chat(request, chat_id) + return chat + + +# ---------- messages ---------- + +@app.post("/api/v1/chats/{chat_id}/messages") +async def create_message(chat_id: str, request: Request): + """Idempotent POST: the ledger row and the message are committed atomically.""" + user, chat = authenticated_chat(request, chat_id) # replay re-checks session and access + data = await read_json_object(request, ("text",), optional=("attachment_ids",)) + text = data.get("text", "") + if not isinstance(text, str) or len(text) > 4000: + raise bad_request("text должен быть строкой до 4000 символов") + raw_attachments = data.get("attachment_ids", []) + if not isinstance(raw_attachments, list) or len(raw_attachments) > 10: + raise bad_request("attachment_ids должен быть списком до 10 UUID") + attachment_ids = [parse_uuid(x, "attachment_ids") for x in raw_attachments] + if len(set(attachment_ids)) != len(attachment_ids): + raise bad_request("attachment_ids содержит дубликаты") + if not text.strip() and not attachment_ids: + raise bad_request("Нужен непустой текст или хотя бы одно вложение") + key = idempotency_key(request) + # Canonical body hash: key order does not matter; omitted attachment_ids == []. + canonical = json.dumps( + {"text": text, "attachment_ids": sorted(attachment_ids)}, + sort_keys=True, separators=(",", ":"), + ) + request_hash = hashlib.sha256(canonical.encode("utf-8")).hexdigest() + scope_path = request.url.path + actor_id = uuid.UUID(user["id"]) + + for _attempt in range(5): + try: + with db.transaction() as conn: + previous = conn.execute( + "SELECT request_hash, status_code, response_body FROM idempotency_records " + "WHERE user_id=%s AND method=%s AND path=%s AND key=%s FOR UPDATE", + (actor_id, "POST", scope_path, key), + ).fetchone() + if previous is not None: + if previous["request_hash"] != request_hash: + raise ApiError(409, "conflict", "Тот же Idempotency-Key использован с другим телом") + return JSONResponse(previous["response_body"], status_code=previous["status_code"]) + + if attachment_ids: + found = conn.execute( + "SELECT id FROM attachments WHERE id = ANY(%s::uuid[]) AND chat_id = %s", + ([uuid.UUID(x) for x in attachment_ids], uuid.UUID(chat["id"])), + ).fetchall() + if len(found) != len(attachment_ids): + raise ApiError(404, "not_found", "Вложение не найдено в этом чате") + message_id = uuid.uuid4() + conn.execute( + "INSERT INTO messages(id, chat_id, sender_id, text, attachment_ids) " + "VALUES (%s,%s,%s,%s,%s::uuid[])", + (message_id, uuid.UUID(chat["id"]), actor_id, text, + [uuid.UUID(x) for x in attachment_ids]), + ) + row = conn.execute("SELECT * FROM messages WHERE id = %s", (message_id,)).fetchone() + body = message_public(row) + conn.execute( + "INSERT INTO idempotency_records" + "(user_id, method, path, key, request_hash, status_code, response_body) " + "VALUES (%s,%s,%s,%s,%s,%s,%s::jsonb)", + (actor_id, "POST", scope_path, key, request_hash, 201, + json.dumps(body, ensure_ascii=False)), + ) + log.info("message accepted", extra={"event": "message.created"}) + return JSONResponse(body, status_code=201) + except psycopg.errors.UniqueViolation: + # Another replica won the race for this key. Roll back and read its + # committed response on the next attempt instead of creating a duplicate. + continue + raise ApiError(409, "conflict", "Не удалось зафиксировать Idempotency-Key") + + +@app.get("/api/v1/chats/{chat_id}/messages") +async def list_messages(chat_id: str, request: Request): + _, chat = authenticated_chat(request, chat_id) + limit, cursor = page_params(request) + after = decode_cursor(cursor, "messages", chat["id"]) if cursor else None + sql = "SELECT * FROM messages WHERE chat_id = %s" + params = [uuid.UUID(chat["id"])] + if after: + sql += " AND (created_at, id) > (%s, %s::uuid)" + params.extend([after[0], after[1]]) + sql += " ORDER BY created_at, id LIMIT %s" + params.append(limit + 1) + with db.connection() as conn: + rows = conn.execute(sql, params).fetchall() + items = [message_public(r) for r in rows] + return page_response(items, limit, "messages", chat["id"], rows) + + +# ---------- attachments (lab4) ---------- + +def attachment_for(request, attachment_id): + """An attachment is visible only to members of its chat; outsiders get a plain 404.""" + user = current_user(request) + row = None + try: + aid = uuid.UUID(attachment_id) + except (ValueError, TypeError, AttributeError): + raise bad_request("Некорректный UUID вложения") from None + with db.connection() as conn: + row = conn.execute( + "SELECT a.* FROM attachments a " + "JOIN chat_members m ON m.chat_id = a.chat_id " + "WHERE a.id = %s AND m.user_id = %s", + (aid, uuid.UUID(user["id"])), + ).fetchone() + if row is None: + raise not_found() + return row + + +@app.post("/api/v1/chats/{chat_id}/attachments") +async def upload_attachment(chat_id: str, request: Request): + user, chat = authenticated_chat(request, chat_id) + filename = validate_filename(request.query_params.get("filename")) + declared = request.headers.get("content-type", "").split(";")[0].strip().lower() + if declared not in ("image/png", "image/jpeg"): + raise ApiError(415, "unsupported_media_type", "Ожидается image/png или image/jpeg") + data = await read_raw(request, MAX_UPLOAD_BYTES) + try: + content_type, width, height = probe(data) + except InvalidImage: + raise ApiError(415, "unsupported_media_type", "Содержимое не является PNG или JPEG") from None + if declared != content_type: + raise ApiError(415, "unsupported_media_type", "MIME не соответствует содержимому") + if width * height > MAX_IMAGE_PIXELS: + raise ApiError(413, "payload_too_large", "Слишком много пикселей") + digest = hashlib.sha256(data).hexdigest() + # Durable staging first: the worker reads this object, not client-supplied paths. + object_key = "staging/" + uuid.uuid4().hex + attachment_id = uuid.uuid4() + job_id = uuid.uuid4() + s3.put_object(object_key, data, content_type) + try: + with db.transaction() as conn: + conn.execute( + "INSERT INTO attachments(id, chat_id, owner_id, filename, content_type, " + "size_bytes, sha256, object_key, status, variants, error_code) " + "VALUES (%s,%s,%s,%s,%s,%s,%s,%s,'queued','[]'::jsonb,NULL)", + (attachment_id, uuid.UUID(chat["id"]), uuid.UUID(user["id"]), + filename, content_type, len(data), digest, object_key), + ) + row = conn.execute("SELECT * FROM attachments WHERE id = %s", (attachment_id,)).fetchone() + # 202 is returned only after a durable handoff: staging + metadata + broker XADD. + job = { + "schema_version": 1, + "job_id": str(job_id), + "type": "attachment.process.v1", + "attachment_id": str(attachment_id), + "pipeline_version": 1, + "attempt": 1, + "created_at": utc_text(dt.datetime.now(UTC)), + } + traceparent = telemetry.carrier().get("traceparent") + if traceparent: + job["traceparent"] = traceparent # W3C context only, never bytes or credentials + broker.publish(job) + except Exception: + s3.delete_object(object_key) + raise + log.info("attachment accepted (queued)", extra={"event": "attachment.queued"}) + return JSONResponse(attachment_public(row), status_code=202) + + +@app.get("/api/v1/attachments/{attachment_id}") +async def get_attachment(attachment_id: str, request: Request): + return attachment_public(attachment_for(request, attachment_id)) + + +@app.get("/api/v1/attachments/{attachment_id}/content") +async def download_attachment(attachment_id: str, request: Request): + row = attachment_for(request, attachment_id) + variant = request.query_params.get("variant", "original") + if row["status"] != "ready": + raise ApiError(409, "conflict", "Вложение ещё не готово") + object_key = row["object_key"] + content_type = row["content_type"] + if variant != "original": + matches = [v for v in (row["variants"] or []) if v.get("name") == variant] + if not matches: + raise not_found() + object_key += "." + variant + ".jpg" if variant == "thumbnail" else "." + variant + content_type = matches[0]["content_type"] + body, stored_type = s3.get_object(object_key) + return Response(content=body, media_type=content_type or stored_type) diff --git a/app/s3.py b/app/s3.py new file mode 100644 index 0000000..235e7ef --- /dev/null +++ b/app/s3.py @@ -0,0 +1,70 @@ +"""MinIO/S3 client shared by all API replicas. Bucket bootstrap is idempotent.""" +import logging +import os + +log = logging.getLogger("messenger.s3") + +client = None +bucket = None + + +def start(): + global client, bucket + import boto3 + from botocore.config import Config + from botocore.exceptions import ClientError + endpoint = os.environ.get("S3_ENDPOINT", "https://minio:9000") + bucket = os.environ.get("S3_BUCKET", "messenger") + client = boto3.client( + "s3", + endpoint_url=endpoint, + aws_access_key_id=os.environ.get("S3_ACCESS_KEY", "messenger"), + aws_secret_access_key=os.environ.get("S3_SECRET_KEY", "local-only-synthetic-secret"), + region_name="us-east-1", + verify=os.environ.get("TLS_CA_FILE", "/certs/ca.crt"), + config=Config(signature_version="s3v4", connect_timeout=3, read_timeout=10, + retries={"max_attempts": 2, "mode": "standard"}), + ) + _bootstrap_bucket() + + +def _bootstrap_bucket(): + from botocore.exceptions import ClientError + try: + client.head_bucket(Bucket=bucket) + return + except ClientError as exc: + code = exc.response.get("Error", {}).get("Code", "") + if code not in ("404", "NoSuchBucket", "NotFound"): + raise + try: + client.create_bucket(Bucket=bucket) + log.info("created bucket %s", bucket) + except ClientError as exc: + code = exc.response.get("Error", {}).get("Code", "") + if code not in ("BucketAlreadyOwnedByYou", "BucketAlreadyExists"): + raise + + +def put_object(key, body, content_type): + client.put_object(Bucket=bucket, Key=key, Body=body, ContentType=content_type) + + +def get_object(key): + response = client.get_object(Bucket=bucket, Key=key) + return response["Body"].read(), response.get("ContentType", "application/octet-stream") + + +def delete_object(key): + client.delete_object(Bucket=bucket, Key=key) + + +def ready(): + if client is None: + return False + try: + client.head_bucket(Bucket=bucket) + return True + except Exception: + log.exception("S3 readiness check failed") + return False diff --git a/app/security.py b/app/security.py new file mode 100644 index 0000000..5a874a9 --- /dev/null +++ b/app/security.py @@ -0,0 +1,66 @@ +"""Password KDF (Argon2id) and HTTP credential parsing (Basic / Bearer).""" +import base64 +import binascii +import hashlib +import hmac +import os +import re + +from argon2.exceptions import VerificationError +from argon2.low_level import Type, hash_secret, verify_secret + +USERNAME_RE = re.compile(r"[a-z0-9_]{3,32}\Z") +ARGON2_TIME = 2 +ARGON2_MEMORY = 19 * 1024 # 19 MiB minimum required by lab7 +ARGON2_PARALLELISM = 1 +ARGON2_HASH_LEN = 32 + + +def hash_password(password): + salt = os.urandom(16) + derived = hash_secret( + password.encode("utf-8"), salt, + time_cost=ARGON2_TIME, memory_cost=ARGON2_MEMORY, + parallelism=ARGON2_PARALLELISM, hash_len=ARGON2_HASH_LEN, type=Type.ID, + ) + return "argon2id$%d$%d$%d$%s$%s" % ( + ARGON2_TIME, ARGON2_MEMORY, ARGON2_PARALLELISM, salt.hex(), derived.hex() + ) + + +def verify_password(password, stored): + try: + scheme, t, m, p, salt_hex, digest_hex = stored.split("$") + if scheme != "argon2id": + return False + encoded = bytes.fromhex(digest_hex) # full Argon2id encoded hash + return verify_secret(encoded, password.encode("utf-8"), Type.ID) + except (ValueError, TypeError, VerificationError): + return False + + +def token_hash(token): + return hashlib.sha256(token.encode("utf-8")).hexdigest() + + +def parse_basic(header): + if not header or not header.lower().startswith("basic "): + return None + encoded = header[6:].strip() + try: + raw = base64.b64decode(encoded, validate=True).decode("utf-8") + except (ValueError, UnicodeDecodeError, binascii.Error): + return None + if ":" not in raw: + return None + username, password = raw.split(":", 1) + if not USERNAME_RE.fullmatch(username) or not 12 <= len(password) <= 128: + return None + return username, password + + +def bearer_token(header): + if not header or not header.lower().startswith("bearer "): + return None + token = header[7:].strip() + return token or None diff --git a/app/telemetry.py b/app/telemetry.py new file mode 100644 index 0000000..0d49e23 --- /dev/null +++ b/app/telemetry.py @@ -0,0 +1,138 @@ +"""OpenTelemetry bootstrap: OTLP traces, metrics and logs via the Collector. + +The module degrades to no-op when the SDK is absent (offline unit tests). +All attributes are low-cardinality: method, route template, status class, job type/outcome. +No message bodies, tokens, filenames or user/chat/message IDs are exported. +""" +import logging +import os +from contextlib import nullcontext + +AVAILABLE = True +try: + from opentelemetry import metrics, trace + from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter + from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter + from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter + from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler + from opentelemetry.sdk._logs.export import BatchLogRecordProcessor + from opentelemetry.sdk.metrics import MeterProvider + from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader + from opentelemetry.sdk.resources import Resource + from opentelemetry.sdk.trace import TracerProvider + from opentelemetry.sdk.trace.export import BatchSpanProcessor + from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator +except ImportError: + AVAILABLE = False + +log = logging.getLogger("messenger.telemetry") + +tracer = None +meter = None +propagator = None +http_requests = None +http_duration = None +jobs_total = None +job_duration = None +_enabled = False + + +def init(service_name, instance_id): + global tracer, meter, propagator, http_requests, http_duration, jobs_total, job_duration, _enabled + if not AVAILABLE or os.environ.get("OTEL_SDK_DISABLED", "").lower() in ("1", "true"): + log.info("telemetry disabled or SDK unavailable") + return False + endpoint = os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT", "https://otel-collector:4318").rstrip("/") + ca_file = os.environ.get("TLS_CA_FILE", "/certs/ca.crt") + resource = Resource.create({ + "service.name": service_name, + "service.version": "1.0.0", + "service.instance.id": instance_id, + "deployment.environment.name": "lab", + }) + + provider = TracerProvider(resource=resource) + provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter(endpoint=endpoint + "/v1/traces", certificate_file=ca_file))) + trace.set_tracer_provider(provider) + tracer = provider.get_tracer(service_name) + + reader = PeriodicExportingMetricReader( + OTLPMetricExporter(endpoint=endpoint + "/v1/metrics", certificate_file=ca_file), + export_interval_millis=int(os.environ.get("OTEL_METRIC_EXPORT_INTERVAL", "5000")), + ) + meter_provider = MeterProvider(resource=resource, metric_readers=[reader]) + metrics.set_meter_provider(meter_provider) + meter = meter_provider.get_meter(service_name) + + logger_provider = LoggerProvider(resource=resource) + logger_provider.add_log_record_processor( + BatchLogRecordProcessor(OTLPLogExporter(endpoint=endpoint + "/v1/logs", certificate_file=ca_file)) + ) + handler = LoggingHandler(level=logging.INFO, logger_provider=logger_provider) + handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(name)s %(message)s")) + root = logging.getLogger() + root.addHandler(handler) + root.setLevel(logging.INFO) + + http_requests = meter.create_counter( + "http.server.requests", unit="{request}", description="HTTP requests by method, route and status class" + ) + http_duration = meter.create_histogram( + "http.server.duration", unit="s", description="HTTP server request duration" + ) + jobs_total = meter.create_counter( + "messenger.jobs", unit="{job}", description="Processed jobs by type and outcome" + ) + job_duration = meter.create_histogram( + "messenger.job.duration", unit="s", description="Worker job processing duration" + ) + propagator = TraceContextTextMapPropagator() + _enabled = True + log.info("telemetry enabled: service=%s endpoint=%s", service_name, endpoint) + return True + + +def http_span(method, route): + if tracer is None: + return nullcontext() + span = tracer.start_as_current_span( + "HTTP " + method, + attributes={"http.request.method": method, "http.route": route}, + ) + return span + + +def record_http(method, route, status_class, elapsed_seconds): + if http_requests is not None: + attrs = {"http.request.method": method, "http.route": route, + "http.response.status_class": status_class} + http_requests.add(1, attrs) + http_duration.record(elapsed_seconds, attrs) + + +def record_job(job_type, outcome, elapsed_seconds): + if jobs_total is not None: + attrs = {"job.type": job_type, "job.outcome": outcome} + jobs_total.add(1, attrs) + job_duration.record(elapsed_seconds, attrs) + + +def carrier(): + """W3C trace context to carry through the broker (no bytes or secrets).""" + out = {} + if propagator is not None and tracer is not None: + propagator.inject(out) + return out + + +def extract(carrier_map): + if propagator is None: + return None + return propagator.extract(carrier_map) + + +def worker_span(job_type, context=None): + if tracer is None: + return nullcontext() + return tracer.start_as_current_span("PROCESS " + job_type, context=context, + attributes={"job.type": job_type}) diff --git a/certs/api.crt b/certs/api.crt new file mode 100644 index 0000000..2e1066b --- /dev/null +++ b/certs/api.crt @@ -0,0 +1,19 @@ +-----BEGIN CERTIFICATE----- +MIIDJTCCAg2gAwIBAgIUYY8+90RYvQq11noDFEsrFuEv5Z4wDQYJKoZIhvcNAQEL +BQAwHjEcMBoGA1UEAwwTbXR1c2ktbGFiNy1sb2NhbC1jYTAeFw0yNjExMjgxMTEy +NTFaFw0yNzExMjgxMTE3NTFaMA4xDDAKBgNVBAMMA2FwaTCCASIwDQYJKoZIhvcN +AQEBBQADggEPADCCAQoCggEBAPO69HEdfuM16BM6+kRE2o2D3LyQ2xxhjsQzpnJH +u6m30R7XENH6LCYll5wR34E/ysz1L/WbCvsEZeM0KC2b8YAWnyiIxPn7fjMeykM9 +xq2WMgieEiyMrjRBKxOpSidj0RBhmx3kF1x+Mdrf6IFlPoy8VpjIrH/GANhm0y0+ +4v1ouSvFvLQ9MaviM6CpqNexfRLflNFQgTBDFgCXnHrYhgcM/xaR3oSXr5ZyTG+o +q/7sYKFg9Z1hDFdn9P0dXAaUjPoqT0WGAS6Y09Qa2eWCHiVFqn1HoKEt99T1N0E+ +dTPOMe7D+rzsvkHfAnBq91MK44FjT6uKLkoasB2k/eoXvikCAwEAAaNrMGkwGgYD +VR0RBBMwEYIEYXBpMYIEYXBpMoIDYXBpMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggr +BgEFBQcDAjALBgNVHQ8EBAMCBaAwHwYDVR0jBBgwFoAUm6NF3eUQGQgR8kACY1Vf +QTo+RhkwDQYJKoZIhvcNAQELBQADggEBAD6LEu/rEZBNHHpTqOJWcCFC5LQBWRRK +6KJTolpqpo5Ffi1k0hGcfk0iuuhMs/TBeCPk614ihd+64WC1xwISSG+adE+Pty4E +dl9qBqnQQ8Q7Amw2hkVhnCRSs7gNrpVsrxdl/O4whTLq+L5ztfBHKXqI4kzwr7Sq +15FHHOM29aIEQak+YMOYUQg5dhsld6IBnraqTbX5VO0m8YuP7NlX02ywNv2kcmlI +oRqScQipT7FrmhVmZzuC6XB4nnnuq8/c1/fMgolnymPe+wfqMyh1VwOugy0gePGf +Z32/O6MvEM7HvU3khUvJzh6XUGDUwNZYX3ZKHBQGF7GYaupPbpyR8Z8= +-----END CERTIFICATE----- diff --git a/certs/ca.crt b/certs/ca.crt new file mode 100644 index 0000000..b56703a --- /dev/null +++ b/certs/ca.crt @@ -0,0 +1,19 @@ +-----BEGIN CERTIFICATE----- +MIIDDDCCAfSgAwIBAgIUehMiYi4ELeBAFQqR+MMB/POsJtUwDQYJKoZIhvcNAQEL +BQAwHjEcMBoGA1UEAwwTbXR1c2ktbGFiNy1sb2NhbC1jYTAeFw0yNjExMjgxMTEy +NTFaFw0yNzExMjgxMTE3NTFaMB4xHDAaBgNVBAMME210dXNpLWxhYjctbG9jYWwt +Y2EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCo5VWvwakm9tlSiWfY +rsr7Zq/Bl38+Ax2bYmfBzKjbHyCE2m8D/5FRm9Yz3mD7uqS3o8ugonxzcov+effN +KckDg8hwbTiZ/k9sRfEWM4gWgIGB/EFsz85/y9cvNHSuRjv60nwnqKq04Dg2X1LE +pjySMdUZxDGmAzu9o6cEJ1hXISRAVE6BgpxWRd6pqSEnMWnVNmmIrWKsvKZuuAig +gxOIWmC1XwKsY7UJTGvVGCvF/puf+gCjMOul1szixiCN1adKbPnKLnNzsto7T9jk +oUzBtJtKdUMR/CPEg6hicdocWf7tsbFBzgvDgO4U1aVU4/xMVmhFfA2NqgNkqwHR +KYwrAgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFJujRd3lEBkI +EfJAAmNVX0E6PkYZMA4GA1UdDwEB/wQEAwIBhjANBgkqhkiG9w0BAQsFAAOCAQEA +Q2qWWLK60AfUvGDGb5kQbiVzp5mRJeruriNGt67BRMZr2trNiA04Vj1XJgQ2owPr +opW79sUsuaNf/LXag82kS2uyUq6pGcX4wcsJa9hPNP9LknvFUqOLbIZKVB13x3B9 +z4spv2HuNJ52EcTPO1U0XqWuKeApTiM49+PWTsXB/7mZlIL/qNgR/VcW7SWFpVsx +ulQzALTdMV2H1JVDw7+9mkhdyMNWWBtF+v9sB5Uz5jmsZMT/ZocPV0g+pl5TJYHg +9M3QGx5FdJPZNmisIpAf/uJggkZh01ataj+vNEP9GKeggkS4FZe/+BGlko9mnelp +fnTTTS2PsCgsSDJCqJDsUw== +-----END CERTIFICATE----- diff --git a/certs/db.crt b/certs/db.crt new file mode 100644 index 0000000..de93ae5 --- /dev/null +++ b/certs/db.crt @@ -0,0 +1,19 @@ +-----BEGIN CERTIFICATE----- +MIIDDTCCAfWgAwIBAgIUW+0TuJx+IQNtyVh6KcfyqTwEFv0wDQYJKoZIhvcNAQEL +BQAwHjEcMBoGA1UEAwwTbXR1c2ktbGFiNy1sb2NhbC1jYTAeFw0yNjExMjgxMTEy +NTFaFw0yNzExMjgxMTE3NTFaMA0xCzAJBgNVBAMMAmRiMIIBIjANBgkqhkiG9w0B +AQEFAAOCAQ8AMIIBCgKCAQEAnh2FM77gmXNtqmVwfXhrVV5974IfxaH10mSnqe4X +km15DKjR9TmRxThbkyW4TqoIQu9fHgTAnfSiKyF/ZJUS1bGPmlOKvQD6GwtrU1Jc +DVCUaurbw2YAQeCI9ZkRQ+Z3fpiJHZOcYgtPauuR/qaI+2zSsIaP3XtEmPFSC3yC +SkbRTJRr8Mx2xCeQmlpZJ6alvWohoxzJ2ygeZC9gc/rY8EQxUg57A5AzGOLfiw7E +3DbE2XIOkK24flMZAvnInTmWTiy7WItrT+lr7o7decctz9HR3zru3qiKDqhKZ2/V +jnLyF/TuI6OhXkyqWvYyanuoP1h6b4qUxaG+0lXQisHuNQIDAQABo1QwUjANBgNV +HREEBjAEggJkYjATBgNVHSUEDDAKBggrBgEFBQcDATALBgNVHQ8EBAMCBaAwHwYD +VR0jBBgwFoAUm6NF3eUQGQgR8kACY1VfQTo+RhkwDQYJKoZIhvcNAQELBQADggEB +AJoyf9gxR9TrCWI+HpqeSCQRiwiitPlu8HMLGYZtHsTyb9sIxRowwfL6IWyrBVtq +S64abqk0cRZCpl2/mck7aY10RkRjico2hro6JDaSK7YKlY/T7nzRgHuZ+SGXH1bz +6aTH/R4DVSZxpAIXFH73AuHf8oJkaQFbEArJuZ6QhdIoEOEpZJlypwDFJdUJ51aY +fedcqiCbxuKDcPJcFEkgJmzspouPNd6cFwWePeRvJ/skk7IFzFk7CEP+6DKd1g1j +XDgA1ybZEU3ehuDopaJ4t1qP/TYd2yF1QQDCAfNbY82JQuYy01ymccvJA9GcdzCm +DaCLGra7bwge6l9XhXQC9h4= +-----END CERTIFICATE----- diff --git a/certs/ingress.crt b/certs/ingress.crt new file mode 100644 index 0000000..887ec79 --- /dev/null +++ b/certs/ingress.crt @@ -0,0 +1,19 @@ +-----BEGIN CERTIFICATE----- +MIIDKDCCAhCgAwIBAgIUCEZAcvXO0Wa/Y8CiyrqNcCxzTpowDQYJKoZIhvcNAQEL +BQAwHjEcMBoGA1UEAwwTbXR1c2ktbGFiNy1sb2NhbC1jYTAeFw0yNjExMjgxMTEy +NTFaFw0yNzExMjgxMTE3NTFaMBIxEDAOBgNVBAMMB2luZ3Jlc3MwggEiMA0GCSqG +SIb3DQEBAQUAA4IBDwAwggEKAoIBAQDH9N+Lqs0NrwAAKL10UA+az1Wu9cjNq3SO +93r/FLnHXZuIt7RekGE02vnNcS507YHdVVRM4Q9Jp85qqCAJ9VzT9HQKvyrOMnfU +OmqI63FUYM+svacn07hH/NQbAx1xFZj0oEy5t+KjSbYqGLW6rSk6Q7P+sSu4rWUf +BE5h+mkgQYWQUoAhGd11GuZXgBfO5UewTtsCt/mmymMck63ZAkpri1+nHUE2USje +zrHkqRDs0tPZv+vWWaicHgAPK2bnTgSeNTM0SXsaid/ujSWL9tsvPGZFcjGYYu9N +qTCN4UIbahFyfndqGILh8itAGq2bU9rzeJQ+fJurKpu+97WM3hnPAgMBAAGjajBo +MCMGA1UdEQQcMBqCCWxvY2FsaG9zdIIHaW5ncmVzc4cEfwAAATATBgNVHSUEDDAK +BggrBgEFBQcDATALBgNVHQ8EBAMCBaAwHwYDVR0jBBgwFoAUm6NF3eUQGQgR8kAC +Y1VfQTo+RhkwDQYJKoZIhvcNAQELBQADggEBAGBBqHC6l1WO4pCHM4/sg5m/XAPh +r/eGdoS68Fe6iucuIYhQ2S+OjfYTH8DwhDNhPg2c4fib8XUlIv60aR0t7ZePtYZQ +9xyjP7v1yR0ZQBnlrikQ8e1TCiXXGieo40JvDcsGbXsawDxQsrwoRgdq+xQcQ8RP +xFjCXUPIJjaobNo17Z93CvnMJlo9DhgAEhmeAzPrgFqNJHGJrf8zxjLhzvADzmHa +/JYJmYyfyqjRHvqeMVUlNAMAsWn9OkbhIu0KchBcJz5juufhxwpsVVcTa3dp0WT7 +CdNYZaYojuftKWY3aa3QJ/JGcsImkIfCsAiSKd6Y66WESgYIouN6zQti9Oo= +-----END CERTIFICATE----- diff --git a/certs/lb.crt b/certs/lb.crt new file mode 100644 index 0000000..d721881 --- /dev/null +++ b/certs/lb.crt @@ -0,0 +1,19 @@ +-----BEGIN CERTIFICATE----- +MIIDADCCAeigAwIBAgIURMKrThSji3tOwqMsjU4i0ZOyupAwDQYJKoZIhvcNAQEL +BQAwIDEeMBwGA1UEAwwVbXR1c2ktbGFiNy1sYi1tZXNoLWNhMB4XDTI2MTEyODEx +MTI1MVoXDTI3MTEyODExMTc1MVowDTELMAkGA1UEAwwCbGIwggEiMA0GCSqGSIb3 +DQEBAQUAA4IBDwAwggEKAoIBAQC11OoxHI+SlUVQkKU6AC2SMzYBtzr6d9py6fb3 +pu0Iqk4SUCuYwJIM/NLW1diVvNzeKHacGTE4KadVANjauTczoFtB5G0OnLMLssad +DVx8Mrv829bs6dIcSMw6nFa6lBprwxRa3rTU/jYhQRJF/4dIkZw+c7h6Q/sHDxvQ +NR7iYJNHYcRsEWf4Q6am6lU+m0ACoDpd1WerZE8XUhWxvLMaMmMCEA6Q/1JtHrs8 +x3ScT8yHZS13wGuFopbVkoOLI109KLvi77fm8ny395q3g/2inm8y6fznrauFD5F+ +K8PQm+R0RlFXPcrSCDk00tCGgC0TE+Zwl13FDAL37w3niR6jAgMBAAGjRTBDMBMG +A1UdJQQMMAoGCCsGAQUFBwMCMAsGA1UdDwQEAwIFoDAfBgNVHSMEGDAWgBTi9nG/ +z3kNwgkdGqcLNYH2dXOUyjANBgkqhkiG9w0BAQsFAAOCAQEATdHblxSiA6Z/tubL +YA0TQUErPbIzPpTgl7PCIIIvt8rH1MUOo1OL1mZXxlqpt/C5HLbRQaXyfJhdS73m +bMUmB2R1j6gUxYOcjx7mqdJM8fMLfSHpreZ9289VRD/rme3yAvQ7+JlsdShli4UH +J5zB9fhfcnVuTZRGaHnozkm8BQ/3oUZH8awvm7S8x2Im9iN4Qb0509kOQie55Rr8 +YKJM8Y3HgM1vLx/S06y6j44BO86Y04hl7VotJTu3pjELJuTe88SHorjleWJHUDhW +dKO9UBB5bDq4uubDcqRVCqJDFNRcc8gmS4E/s07GZ0G7mgxfRO7NqVzduBq6+Qpu +UHDrfw== +-----END CERTIFICATE----- diff --git a/certs/mesh-ca.crt b/certs/mesh-ca.crt new file mode 100644 index 0000000..2e7e280 --- /dev/null +++ b/certs/mesh-ca.crt @@ -0,0 +1,19 @@ +-----BEGIN CERTIFICATE----- +MIIDEDCCAfigAwIBAgIUc6EVRfxa0yMEfxE3J4Z9eKjpk3cwDQYJKoZIhvcNAQEL +BQAwIDEeMBwGA1UEAwwVbXR1c2ktbGFiNy1sYi1tZXNoLWNhMB4XDTI2MTEyODEx +MTI1MVoXDTI3MTEyODExMTc1MVowIDEeMBwGA1UEAwwVbXR1c2ktbGFiNy1sYi1t +ZXNoLWNhMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlsja1eq9DviY +nwww2is777rhvOoZuF22VfvDpU9ZZfdgIouz3MIiccRZECxczNSNVJifLP0B4FRV +3q/WQWF8jYCGXB07MKRnDkZ/9h2CY+XxaaOahRO1KEva2oz14/T4AaCJnRKik5f2 +V9VKnzBbPtFPiAKWvO1/AxQ/FUwpO2RbK7+vQU1FnAg5wI+9ST2/9I1CVy8wzgbc +ObUNDlmA0ffr0tlnhw7SqRevp19aF3Iv3911ZCvTc1N2H/D09Y6tbf1nV7x5hPpD +OI47j0qi0gb3BBBCsCuvdIN8AyEUAIh18mOpsuIQdfVkqqNAzkl+mthvBViDgt6j +iAxNMOa53QIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBTi9nG/ +z3kNwgkdGqcLNYH2dXOUyjAOBgNVHQ8BAf8EBAMCAYYwDQYJKoZIhvcNAQELBQAD +ggEBAIG9RTPMCYMuNQkn9pEzUUc9CLeusgsPlmVBOf+0a0ZH10J5y0oE7XV2Wv4Y +4LqW981uStU6q4mt2vAhrPTb2aYpRWCS3XBx/3MteByvjRwcZd6ZNFtMXgSe6grM +sHM6khPuhEVv/yUpQ6ECQQPNS5VhAmvpS1AV5WAe/EUw7rRNJkur74PdgnenaD9g +EDwIIiPrMO0Vx3HVgJEj9C85lhGWl9AIkjQBdP4yflNpPGBn1XdtgZN4lTMnUe8i +rPcCF6vyy0CUY0YlarMmQXq7n+sG1tby3zuFHtiDa017fUvIEacDbx1HGQ37LLFG +GaPXjD3QG8fRXEXm2SvTMAXva2U= +-----END CERTIFICATE----- diff --git a/certs/minio.crt b/certs/minio.crt new file mode 100644 index 0000000..fd42ccc --- /dev/null +++ b/certs/minio.crt @@ -0,0 +1,19 @@ +-----BEGIN CERTIFICATE----- +MIIDEzCCAfugAwIBAgIUbIBhiSpTy9sALRmj5RGJCa+QFJQwDQYJKoZIhvcNAQEL +BQAwHjEcMBoGA1UEAwwTbXR1c2ktbGFiNy1sb2NhbC1jYTAeFw0yNjExMjgxMTEy +NTFaFw0yNzExMjgxMTE3NTFaMBAxDjAMBgNVBAMMBW1pbmlvMIIBIjANBgkqhkiG +9w0BAQEFAAOCAQ8AMIIBCgKCAQEAkncxaRM25wduxSBwcQ7DHntLzlYSqGowQmbj +1A704aijeS9/aM+KltWbwSUpMQKkbNFvgLMFyuhQ6CdK/N6PQwX8gmMK53S5z5uh +kgMrfndcC8TvRTECD7ku9pRF5nn+kQnhJUktIFk9RjnjeD1jB/y60jDh844VR2UZ +CUNuZdEW8ovJNjJNj+tuGDEDPBB72IqnQFMcH4e31+wHVI6h8h0qLINXW0SO46T6 +cHsJLlCC/a6NEzdW/wqUaLEmOGbLE7vqngaNieT3Y0hsnayvl23s2klCutnEcr3Q +henQ1InlArZiy4/j5IzILiGubZLABZYaxrULJeFpOccgLQYtTwIDAQABo1cwVTAQ +BgNVHREECTAHggVtaW5pbzATBgNVHSUEDDAKBggrBgEFBQcDATALBgNVHQ8EBAMC +BaAwHwYDVR0jBBgwFoAUm6NF3eUQGQgR8kACY1VfQTo+RhkwDQYJKoZIhvcNAQEL +BQADggEBAFfcCgRYKGqnlQF4gb8oS3wPAX2hmWFJ/ppwxdZynbeZvRkIoPRUCl/K +76q54dsPiYCcQwqaqduAJMCbTA7J4FXZQAcsjNsxu1iqIIjfs4SzUsT3ps1RyjoY +XksNGXv9TakNH8LpwgbkmgoU0nJ+5c1mqZH9FUxVI024Lb5PEt3EvzzekJ7khhX6 +qHKTw9hRRG7brLMlOZNG0gdbHNNmAC7vhsJsrwzoBejvjSn9X5aYmmg4pY9pK1WN +CRaMxM85E9nV+Z4s+Si3XEbneCKFzV6fE08gCnZAHWBLgSo/hIvybA/SY8ge89Mc +tFiq3DjuSUaPllLv4rOgbHfd3g2cJ+M= +-----END CERTIFICATE----- diff --git a/certs/openbao.crt b/certs/openbao.crt new file mode 100644 index 0000000..c74e40c --- /dev/null +++ b/certs/openbao.crt @@ -0,0 +1,19 @@ +-----BEGIN CERTIFICATE----- +MIIDKDCCAhCgAwIBAgIUN/RgqhCsy4QWao6094T0DShqAuUwDQYJKoZIhvcNAQEL +BQAwHjEcMBoGA1UEAwwTbXR1c2ktbGFiNy1sb2NhbC1jYTAeFw0yNjExMjgxMTEy +NTFaFw0yNzExMjgxMTE3NTFaMBIxEDAOBgNVBAMMB29wZW5iYW8wggEiMA0GCSqG +SIb3DQEBAQUAA4IBDwAwggEKAoIBAQCtCH1y9ptZklHNbOiUqgp0NxC3ZMTG2Ah1 +MPvUAHpwZ/7805TRJ1UmYgfCkv8fw9FuTW1wazN4l03wnjPgotncOIUEIdFVlFBT +pK6A+gb6ev48X2desnRKDQDQKGH7Usb17jKyzO2rGEyvRxfetXf4lCfZ9bCk3c8N +YojGl5HyfN/7TggH/Pyyum/mn1ba4B8PirZkl5ZHS8tOxJSKL88nfAOtCbiW3w7V +Ed0fK+fYvh6stddTIiBfBhM13bzdVqhsrdqF50vN0jDuhFCaPzSmsvGnyTRfuATA +1+NhYLlrauieESt16rWmuJdIyjfne0cPddkj0uBHCJPsvW8CyaTNAgMBAAGjajBo +MCMGA1UdEQQcMBqCB29wZW5iYW+CCWxvY2FsaG9zdIcEfwAAATATBgNVHSUEDDAK +BggrBgEFBQcDATALBgNVHQ8EBAMCBaAwHwYDVR0jBBgwFoAUm6NF3eUQGQgR8kAC +Y1VfQTo+RhkwDQYJKoZIhvcNAQELBQADggEBAI7T7vwVv2eeEFiqLCOdylilQv2n +sFdDp/jnQeWdAALrDv7wNVQqL7NkKk3C2Je5l0aD9+ZXn8/o6yJTs1M6DQg3F0An +HmPC/S1ofrZRwu6TNzMg8S4Yd3Vi5ujn2G6auGnjpAnFvu4P4dHxeK0gvU7o8unl +WlgHiPvycRNnBwINT3G18vqx0pTLrh17mvXA0kujTVZTZSTjuzLuPWI3gfnSLCbT +Hzn9pJvy2kJvptCaH/hmp4F488AAEZCy2vacpDa/18QAYUf7iaQhKmN2mhxeQbff +br5lWQfG4z4LXk4n5YTDs/NmoOwUR5DOXjgMnDzszMZ0gRpYXgRSKcBz3dc= +-----END CERTIFICATE----- diff --git a/certs/otel-collector.crt b/certs/otel-collector.crt new file mode 100644 index 0000000..828affb --- /dev/null +++ b/certs/otel-collector.crt @@ -0,0 +1,19 @@ +-----BEGIN CERTIFICATE----- +MIIDJTCCAg2gAwIBAgIUIlpQVI4nVQdpZEtb3lDnGscj+6YwDQYJKoZIhvcNAQEL +BQAwHjEcMBoGA1UEAwwTbXR1c2ktbGFiNy1sb2NhbC1jYTAeFw0yNjExMjgxMTEy +NTFaFw0yNzExMjgxMTE3NTFaMBkxFzAVBgNVBAMMDm90ZWwtY29sbGVjdG9yMIIB +IjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2dDIgGiXt88Drxat12R8mOj/ +RRg7S7Vnrc3h84TgHE6eXyExaXE6Tg2X96hnfCrRfgXS3xUQeq47EBdP6ApHoiuQ +zmypzUgZVWXVr10ofOhKrTo2/+8nXm6R694znJ65TNzeCLmBd+Xv1sk3Duzv0GEz +35ZJvxH2qD9MJiQGPiGlJ95Rc1tjlKvjnspdgtewRubinMKqXw/zNlbSXfReuzYb +zR4jrDFPnIk7Tdq2jI26j5djkJAmLK1zS+K9Sm/GJYc654IxYvX2CBr+KNc0KzC9 +xnWAjrTe4QZLh0E+jxt4IDPwX6EkWq4eGWrxvNvfF6GITHmvIGPjclzQATbygwID +AQABo2AwXjAZBgNVHREEEjAQgg5vdGVsLWNvbGxlY3RvcjATBgNVHSUEDDAKBggr +BgEFBQcDATALBgNVHQ8EBAMCBaAwHwYDVR0jBBgwFoAUm6NF3eUQGQgR8kACY1Vf +QTo+RhkwDQYJKoZIhvcNAQELBQADggEBAKRbMP/SpBULMj1BtuxTlNkimpeuFbVS +AfIZletMPGogyR7OUUkvNdxD057g/8Inxm72GSDTxqrmiME2kdd/SzS3XFgZ/Ks2 +vyqURSPYg6ZrLiX7/1InrHqPlx1VPtZEmHswfzAnLya/j+vzpYI+ONHo2xZzJhxq +BRLJtEceFwOPdpZ4g4SdBbsQDyQ1vKNaPuDjip3Ce9crN4yfyUoAL+VYrDrIK6nJ +JgLCI4qzeASAjULY2ADo635iguakjan/D9wWd/W4nAK2dxxFLxw9KIZj2RELWGOR +A/Idy/iyo1RNxQ244NFU9rl+b93gslGQ1xkujQ8PWbdRCMkctn7I2F8= +-----END CERTIFICATE----- diff --git a/certs/redis.crt b/certs/redis.crt new file mode 100644 index 0000000..80390f2 --- /dev/null +++ b/certs/redis.crt @@ -0,0 +1,19 @@ +-----BEGIN CERTIFICATE----- +MIIDEzCCAfugAwIBAgIUT7+SiF7i89DJE/hwiUxeFiFNQvEwDQYJKoZIhvcNAQEL +BQAwHjEcMBoGA1UEAwwTbXR1c2ktbGFiNy1sb2NhbC1jYTAeFw0yNjExMjgxMTEy +NTFaFw0yNzExMjgxMTE3NTFaMBAxDjAMBgNVBAMMBXJlZGlzMIIBIjANBgkqhkiG +9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmwJCIOdxLvNDfGWC7AWzuJB10mxDhAXt/U3f +HFGnfCPosOfJQ/lgsz+2uSHM/GPdgEioGILMtAYo6qcnj+diuOMElXoI+dkwew2f +Kf7qYSU2FD0dB6WeMNybfQCQ3t3HBp7Tv56OgrcAP9t8ilicpEBKhreiADeJQPR9 +oMUkpJb0+QoPAvMY7SUPiv0WrbkTFUs4PLeHh4WzyfwUkbbcHnI5lrLSjGhhFihB +nDQcTi5rt1uz2OCzqIfe2w/kDJ0F+u5gEjTny1oMIMOUev7U9QLGlC+tlxgkr0y9 +p6QQEmQ7Mc+GpWBmuPk2kwIcDJyeKIiI0MLzr0VycBzoO41yMQIDAQABo1cwVTAQ +BgNVHREECTAHggVyZWRpczATBgNVHSUEDDAKBggrBgEFBQcDATALBgNVHQ8EBAMC +BaAwHwYDVR0jBBgwFoAUm6NF3eUQGQgR8kACY1VfQTo+RhkwDQYJKoZIhvcNAQEL +BQADggEBADjVc7AwVZvt4WgRgNt2wybOTvl/oy2V7XVx1crW68qY0NCWvYBGvvNB +11wodCZcz6JH7UcPnFXRXn7ksIKO3fSmoZzWwO2sDYHjn/WvdEF0SkusOr6C179t +NMLovhv7vW68h3n2jGmSfbhpcaDXBmNcMpl+lRJHCnsMDW1EN809hBdPfclaWIxF +06uuMzOUVPkq96L/cPA3AHxVWDBBTJzEFhyzgrAmtI1PAIPFhiI+Ixcy4pGbOld6 +1/3+Kl6q7ptE5qqQslj6Ljulj3LBUf1L0rQN/2gYvX7AWlYo3rmM/ML7IS9hZ1iR +1h6m75ojHhl49HBcoCk2HrwubiNPSUI= +-----END CERTIFICATE----- diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 0000000..058a07f --- /dev/null +++ b/compose.yaml @@ -0,0 +1,225 @@ +# Lab7 level 3: TLS ingress, mTLS LB->API, TLS to stateful services, OpenBao. +# Public certs live in ./certs (committed); private keys in ./certs/private (gitignored). +x-certs: &certs + - ./certs:/certs:ro + +services: + db: + image: postgres:16-alpine + restart: unless-stopped + user: postgres + command: ["sh", "-c", "cp /certs/private/db.key /tmp/db.key && chmod 600 /tmp/db.key && exec postgres -c ssl=on -c ssl_cert_file=/certs/db.crt -c ssl_key_file=/tmp/db.key"] + environment: + POSTGRES_USER: ${POSTGRES_USER:-messenger} + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set a synthetic local password in .env} + POSTGRES_DB: ${POSTGRES_DB:-messenger} + volumes: + - pgdata:/var/lib/postgresql/data + - ./certs:/certs:ro + healthcheck: + test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-messenger} -d ${POSTGRES_DB:-messenger}"] + interval: 3s + timeout: 3s + retries: 20 + + minio: + image: bitnamilegacy/minio:latest + restart: unless-stopped + user: "0:0" + environment: + MINIO_ROOT_USER: ${S3_ACCESS_KEY:-messenger} + MINIO_ROOT_PASSWORD: ${S3_SECRET_KEY:?set a synthetic local S3 secret in .env} + MINIO_DATA_DIR: /data + MINIO_DEFAULT_BUCKETS: ${S3_BUCKET:-messenger} + MINIO_CONSOLE_PORT_NUMBER: "9001" + MINIO_SCHEME: https + volumes: + - s3data:/data + - ./certs/minio.crt:/root/.minio/certs/public.crt:ro + - ./certs/private/minio.key:/root/.minio/certs/private.key:ro + - ./certs/minio.crt:/opt/bitnami/minio/certs/public.crt + - ./certs/private/minio.key:/opt/bitnami/minio/certs/private.key + - ./certs/minio.crt:/opt/bitnami/minio-client/.minio/certs/public.crt + - ./certs/private/minio.key:/opt/bitnami/minio-client/.minio/certs/private.key + - ./certs/minio.crt:/.minio/certs/public.crt + - ./certs/private/minio.key:/.minio/certs/private.key + - ./certs/minio.crt:/certs/public.crt:ro + - ./certs/private/minio.key:/certs/private.key:ro + healthcheck: + test: ["CMD-SHELL", "curl -fsS http://127.0.0.1:9000/minio/health/live > /dev/null || curl -kfsS https://127.0.0.1:9000/minio/health/live > /dev/null"] + interval: 5s + timeout: 3s + retries: 30 + + redis: + image: redis:7-alpine + restart: unless-stopped + command: ["redis-server", "--port", "0", "--tls-port", "6379", + "--tls-cert-file", "/certs/redis.crt", "--tls-key-file", "/certs/private/redis.key", + "--tls-ca-cert-file", "/certs/ca.crt", "--tls-auth-clients", "no", + "--requirepass", "${REDIS_PASSWORD:?set a synthetic local redis password in .env}"] + volumes: + - brokerdata:/data + - ./certs:/certs:ro + + openbao: + image: openbao/openbao:2.2.0 + restart: unless-stopped + user: "0:0" + cap_add: ["IPC_LOCK"] + volumes: + - baodata:/bao/data + - ./security/bao.hcl:/bao/config/bao.hcl:ro + - ./certs:/certs:ro + command: ["server", "-config=/bao/config/bao.hcl"] + ports: + - "8200:8200" + + api1: &api + build: . + restart: unless-stopped + environment: &api_env + APP_HOST: 0.0.0.0 + APP_PORT: 8443 + APP_ENV: lab + INSTANCE_ALIAS: api1 + DATABASE_URL: ${DATABASE_URL:-postgresql://messenger:messenger@db:5432/messenger} + SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} + S3_ENDPOINT: https://minio:9000 + S3_BUCKET: ${S3_BUCKET:-messenger} + S3_ACCESS_KEY: ${S3_ACCESS_KEY:-messenger} + S3_SECRET_KEY: ${S3_SECRET_KEY:?set a synthetic local S3 secret in .env} + BROKER_HOST: redis + BROKER_PORT: 6379 + REDIS_PASSWORD: ${REDIS_PASSWORD:?set a synthetic local redis password in .env} + TLS_CERTFILE: /certs/api.crt + TLS_KEYFILE: /certs/private/api.key + TLS_CLIENT_CA: /certs/mesh-ca.crt + TLS_REQUIRE_CLIENT: "1" + TLS_CA_FILE: /certs/ca.crt + OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:4318 + OTEL_METRIC_EXPORT_INTERVAL: 5000 + BAO_ADDR: https://openbao:8200 + BAO_APPROLE_FILE: /certs/private/bao-approle.json + volumes: *certs + depends_on: + db: {condition: service_healthy} + minio: {condition: service_healthy} + redis: {condition: service_started} + openbao: {condition: service_started} + otel-collector: {condition: service_started} + healthcheck: + test: ["CMD", "python", "-c", "import ssl,urllib.request; c=ssl.create_default_context(cafile='/certs/ca.crt'); c.load_cert_chain('/certs/lb.crt','/certs/private/lb.key'); urllib.request.urlopen('https://api1:8443/health/ready',context=c,timeout=2)"] + interval: 5s + timeout: 3s + retries: 20 + + api2: + <<: *api + environment: + <<: *api_env + INSTANCE_ALIAS: api2 + + worker: + build: . + restart: unless-stopped + command: ["python", "-m", "worker"] + environment: + DATABASE_URL: ${DATABASE_URL:-postgresql://messenger:messenger@db:5432/messenger} + S3_ENDPOINT: https://minio:9000 + S3_BUCKET: ${S3_BUCKET:-messenger} + S3_ACCESS_KEY: ${S3_ACCESS_KEY:-messenger} + S3_SECRET_KEY: ${S3_SECRET_KEY:?set a synthetic local S3 secret in .env} + BROKER_HOST: redis + BROKER_PORT: 6379 + REDIS_PASSWORD: ${REDIS_PASSWORD:?set a synthetic local redis password in .env} + BROKER_CONSUMER: worker-1 + MAX_ATTEMPTS: ${MAX_ATTEMPTS:-5} + TLS_CA_FILE: /certs/ca.crt + OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:4318 + BAO_ADDR: https://openbao:8200 + BAO_APPROLE_FILE: /certs/private/bao-approle.json + volumes: *certs + depends_on: + db: {condition: service_healthy} + minio: {condition: service_healthy} + redis: {condition: service_started} + openbao: {condition: service_started} + + otel-collector: + image: otel/opentelemetry-collector-contrib:0.90.1 + restart: unless-stopped + command: ["--config=/etc/otel-collector-config.yaml"] + volumes: + - ./infra/otel-collector-config.yaml:/etc/otel-collector-config.yaml:ro + - ./certs:/certs:ro + ports: + - "4317:4317" + - "4318:4318" + depends_on: + - loki + - tempo + + prometheus: + image: prom/prometheus:v3.8.1 + restart: unless-stopped + command: ["--config.file=/etc/prometheus/prometheus.yml", "--storage.tsdb.path=/prometheus"] + volumes: + - ./infra/prometheus.yml:/etc/prometheus/prometheus.yml:ro + - promdata:/prometheus + ports: ["9090:9090"] + + loki: + image: grafana/loki:2.9.13 + restart: unless-stopped + command: ["-config.file=/etc/loki/loki-config.yaml"] + volumes: + - ./infra/loki-config.yaml:/etc/loki/loki-config.yaml:ro + - lokidata:/loki + ports: ["3100:3100"] + + tempo: + image: grafana/tempo:2.7.1 + restart: unless-stopped + user: "0:0" + command: ["-config.file=/etc/tempo-config.yaml"] + volumes: + - ./infra/tempo-config.yaml:/etc/tempo-config.yaml:ro + - tempodata:/tmp/tempo + ports: ["3200:3200"] + + grafana: + image: grafana/grafana:12.2.0 + restart: unless-stopped + environment: + GF_SECURITY_ADMIN_PASSWORD: ${GRAFANA_PASSWORD:-admin-local-only} + GF_USERS_ALLOW_SIGN_UP: "false" + volumes: + - ./infra/grafana-datasources.yml:/etc/grafana/provisioning/datasources/datasources.yml:ro + - ./infra/grafana-dashboards.yml:/etc/grafana/provisioning/dashboards/dashboards.yml:ro + - ./infra/grafana-dashboard.json:/var/lib/grafana/dashboards/messenger.json:ro + - grafanadata:/var/lib/grafana + ports: ["3000:3000"] + depends_on: [prometheus, loki, tempo] + + lb: + image: nginx:1.27-alpine + restart: unless-stopped + volumes: + - ./infra/nginx.conf:/etc/nginx/nginx.conf:ro + - ./certs:/certs:ro + ports: + - "8443:8443" + depends_on: + api1: {condition: service_healthy} + api2: {condition: service_healthy} + +volumes: + pgdata: + s3data: + brokerdata: + baodata: + promdata: + lokidata: + tempodata: + grafanadata: diff --git a/contracts/trust-matrix.md b/contracts/trust-matrix.md index 0c2a977..53364b1 100644 --- a/contracts/trust-matrix.md +++ b/contracts/trust-matrix.md @@ -1,37 +1,34 @@ -# Матрица доверия — заполнить в решении lab7 +# Матрица доверия — lab7 (заполнено) -Это обязательная матрица покрытия. Для каждой строки укажите реальный порт, endpoint, CA, service identity, проверку SAN/ACL, срок жизни credentials и команду положительного/отрицательного теста. TLS шифрует и подтверждает сервер; mTLS также проверяет клиента. При доверенном CA всё равно нужно ограничивать разрешённую identity. Plaintext hop допустим только внутри закрытого локального transport/proxy boundary, без опубликованного обхода; границу и rationale нужно доказать. +CA: локальный `certs/ca.crt` (публичный, можно распространять), закрытый ключ CA — +`certs/private/ca.key` (вне Git). Отдельный `certs/mesh-ca.crt` выпускает **только** +client-identity `lb` для mTLS LB→API. Сертификаты создаются `scripts/generate_certs.py`. -| Связь | Минимум на 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 | +| Связь | Реализация на уровне 3 | Доказательство | +| --- | --- | --- | +| Клиент → ingress/LB | `https://localhost:8443`, сертификат `ingress.crt` с SAN `localhost`/`127.0.0.1`, CA клиента — `certs/ca.crt`; Bearer | `tests/security.py`, `tests/smoke.py` | +| LB → API (api1, api2) | mTLS: `proxy_ssl_certificate=lb.crt`, `proxy_ssl_verify on` к CA, API требует client cert цепочки `mesh-ca`; identity `lb` — единственная выпущенная | `scripts/verify_security.py`: нет серта → отказ; trusted-CA, но чужой SAN → отказ | +| API/worker → PostgreSQL | `sslmode=verify-full`, `sslrootcert=/certs/ca.crt`, сервер `db.crt` (SAN `db`); роль `messenger` | `app/db.py`, `compose.yaml`, smoke | +| API/worker → S3 (MinIO) | `https://minio:9000`, boto3 `verify=/certs/ca.crt`, сертификат `minio.crt` (SAN `minio`), scoped key; bucket приватен | `app/s3.py`, smoke (SHA-256 оригинала) | +| API/worker → broker (Redis) | TLS `6379`, `ssl_cert_reqs=CERT_REQUIRED`, `redis.crt` (SAN `redis`), пароль из OpenBao | `app/broker.py`, `compose.yaml` | +| API/worker → OTel Collector | OTLP/HTTP `https://otel-collector:4318`, `certificate_file=/certs/ca.crt`, сертификат `otel-collector.crt` (SAN) | `app/telemetry.py`, `verify_telemetry.py` | +| Collector → Prometheus/Loki/Tempo | внутренняя сеть Compose, отдельные volume и identity; публичные порты админских интерфейсов — localhost | `docker compose ps`, `verify_telemetry.py` | +| Grafana → data sources | Prometheus/Loki/Tempo по внутренним именам сервисов, provisioning в `infra/grafana-datasources.yml` | Grafana API: 3 datasource, dashboard | +| API/worker → OpenBao | `https://openbao:8200` (`openbao.crt` SAN `openbao`,`localhost`), AppRole `messenger-app`, token TTL 1h / max 4h, policy только `secret/data/messenger/app` | `app/bao.py`, `scripts/verify_security.py` | +| Оператор → OpenBao/Grafana | localhost:8200 / localhost:3000; root token и unseal shares хранятся у оператора в `certs/private/bao-init.json` (вне Git) | `scripts/bootstrap_bao.py` | +| API → Redis/Valkey | см. строку broker; ACL/пароль минимальны | `app/broker.py` | +| Replication/кластерные каналы | N/A — репликация БД не добавлена | `REPORT.md` | -Нет выбранного компонента — отметьте N/A с причиной, а не оставляйте пустую строку. Внутренний публичный health listener, если нужен, минимален и изолирован; через него нельзя обращаться к бизнес-API без mTLS. Отдельно задокументируйте scrape/health/bootstrap каналы: они тоже не должны создавать обход. +Отрицательные проверки (все воспроизводимы): -## Обязательные отрицательные проверки +1. Доверенный CA/hostname → 200; пустой trust store → `ssl.SSLCertVerificationError` (`tests/security.py`). +2. mTLS: без client cert → handshake failure; trusted-CA, но SAN `evil-lb` → handshake failure (`verify_security.py`). +3. Посторонний не читает metadata/content чата → 404 (публичный smoke). +4. `X-User-Id` не переопределяет Bearer → 401/401 (публичный smoke). +5. OpenBao: свой path читается; запись и чужой path → 403 (`verify_security.py`). +6. Login rate limit: 5×401, 6-й → 429 + `Retry-After: 60` (`verify_security.py`). -1. HTTPS с правильным CA/hostname проходит; с пустым/чужим CA и неправильным hostname — ошибка верификации, не «сервер недоступен». -2. LB→API: без client cert, с cert чужого CA, с запрещённой identity от доверенного CA — отказ; с разрешённой LB identity — успех. -3. На 4 повторите набор для broker и Collector; ограничение на network policy не заменяет проверку identity. -4. Пользователь вне чата не читает metadata/content и не прикрепляет чужой файл; поддельный X-User-Id не меняет Bearer identity. -5. OpenBao app policy читает только свой secret/path; запись policy и чтение чужого path запрещены. Worker не получает admin credentials API/БД/S3. -6. На 4 отзовите secret/cert и дождитесь контролируемого эффекта с учётом действующих соединений, TLS resumption и cache/TTL. Покажите новое подключение, иначе тест отзыва может ничего не проверить. - -## Bootstrap и эксплуатация - -В репозитории только открытые конфиги, policy templates и scripts. CA private key, leaf keys, root token, unseal shares и SecretID не коммитятся, не запекаются в образ и не печатаются в отчёте. Для локального стенда оператор создаёт их вне Git и передаёт через files/secrets с ограниченными правами. Опишите, кто имеет доступ к CA/unseal, что нужно после рестарта OpenBao и как восстановить работу. - -OpenBao не использует dev-mode. Выберите persistent storage и auth метод (например AppRole с короткоживущим SecretID/response wrapping, cert auth или иная обоснованная identity). Не подменяйте root token постоянной переменной BAO_TOKEN в приложении. Рабочие tokens имеют policy, TTL и renewal/re-auth сценарий. Статические KV secrets на 3 допустимы при реальном чтении через сервисную identity; динамические DB credentials — хорошее расширение, но не обязательное название технологии. - -Разрешённый компромисс учебного стенда: ручной operator init/unseal, если он безопасно документирован и не нужен при каждом обычном рестарте API. Автоматическое хранение всех unseal shares рядом с OpenBao без защиты не считается решённым bootstrap. +Bootstrap/эксплуатация: `python scripts/generate_certs.py` → `docker compose up -d` → +`python scripts/bootstrap_bao.py` (init/unseal вручную, ключи у оператора). При рестарте +OpenBao остаётся запечатанным до unseal оператором; обычный рестарт API не требует unseal. +Root token и unseal keys не попадают ни в образ, ни в приложение, ни в telemetry. diff --git a/evidence/lifecycle.txt b/evidence/lifecycle.txt new file mode 100644 index 0000000..1a261c5 --- /dev/null +++ b/evidence/lifecycle.txt @@ -0,0 +1,92 @@ + +=== 0. Full TLS/mTLS + OpenBao stack === +ready after 0 s +NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS +mtusi2026lab7-api1-1 mtusi2026lab7-api1 "python -m app" api1 2 minutes ago Up About a minute (healthy) 8080/tcp +mtusi2026lab7-api2-1 mtusi2026lab7-api2 "python -m app" api2 2 minutes ago Up About a minute (healthy) 8080/tcp +mtusi2026lab7-db-1 postgres:16-alpine "docker-entrypoint.sтАж" db 7 minutes ago Up About a minute (healthy) 5432/tcp +mtusi2026lab7-grafana-1 grafana/grafana:12.2.0 "/run.sh" grafana 7 minutes ago Up 6 minutes 0.0.0.0:3000->3000/tcp, [::]:3000->3000/tcp +mtusi2026lab7-lb-1 nginx:1.27-alpine "/docker-entrypoint.тАж" lb 7 minutes ago Up 5 minutes 0.0.0.0:8443->8443/tcp, [::]:8443->8443/tcp +mtusi2026lab7-loki-1 grafana/loki:2.9.13 "/usr/bin/loki -confтАж" loki 7 minutes ago Up 6 minutes 0.0.0.0:3100->3100/tcp, [::]:3100->3100/tcp +mtusi2026lab7-minio-1 bitnamilegacy/minio:latest "/opt/bitnami/scriptтАж" minio 7 minutes ago Up 31 seconds (healthy) 9000-9001/tcp +mtusi2026lab7-openbao-1 openbao/openbao:2.2.0 "docker-entrypoint.sтАж" openbao 7 minutes ago Up 6 minutes 0.0.0.0:8200->8200/tcp, [::]:8200->8200/tcp +mtusi2026lab7-otel-collector-1 otel/opentelemetry-collector-contrib:0.90.1 "/otelcol-contrib --тАж" otel-collector 7 minutes ago Up 6 minutes 0.0.0.0:4317-4318->4317-4318/tcp, [::]:4317-4318->4317-4318/tcp +mtusi2026lab7-prometheus-1 prom/prometheus:v3.8.1 "/bin/prometheus --cтАж" prometheus 7 minutes ago Up 6 minutes 0.0.0.0:9090->9090/tcp, [::]:9090->9090/tcp +mtusi2026lab7-redis-1 redis:7-alpine "docker-entrypoint.sтАж" redis 7 minutes ago Up About a minute 6379/tcp +mtusi2026lab7-tempo-1 grafana/tempo:2.7.1 "/tempo -config.fileтАж" tempo 7 minutes ago Up 6 minutes 0.0.0.0:3200->3200/tcp, [::]:3200->3200/tcp +mtusi2026lab7-worker-1 mtusi2026lab7-worker "python -m worker" worker 7 minutes ago Up About a minute 8080/tcp + +=== 1. Public HTTPS smoke === +PASS: lab7 public API scenario; infrastructure and grading evidence remain separate. + +=== 2. External TLS trust check === +PASS: trusted HTTPS works; untrusted CA rejected. This does NOT verify internal mTLS, OpenBao or hardening. + +=== 3. Internal mTLS, OpenBao policy, login rate limit === +TLS OK: trusted CA and hostname accepted +MTLS OK: no client certificate rejected by API +MTLS OK: trusted-CA but wrong identity rejected by API +BAO OK: own path readable; write and foreign path denied +RATE OK: 5x401 then 429 with Retry-After=60 + +=== 4. Telemetry through TLS === +METRICS OK: http series=38, job series=1 +LOGS OK: job=messenger-api, traceid/spanid present +TRACES OK: api=3, worker-linked=3 +GRAFANA OK: datasources=3, dashboard=messenger-lab6 + +=== 5. Persistence over HTTPS === +Executing explicit persistence hook; hook output suppressed to avoid leaking secrets. +PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence. + +=== 6. Failover: stop one replica through mTLS mesh === +ready after 0 s +cmd : Container mtusi2026lab7-api1-1 Stopping +C:\Users\Tankist\AppData\Local\Temp\opencode\capture_lab7.ps1:54 знак:3 ++ cmd /c 'set TARGET_INSTANCE_ID=api1&& scripts\stop-one.cmd' 2>&1 ++ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + CategoryInfo : NotSpecified: ( Container mtus...pi1-1 Stopping :String) [], RemoteException + + FullyQualifiedErrorId : NativeCommandError + + Container mtusi2026lab7-api1-1 Stopped +NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS +mtusi2026lab7-api2-1 mtusi2026lab7-api2 "python -m app" api2 3 minutes ago Up 17 seconds (healthy) 8080/tcp +mtusi2026lab7-db-1 postgres:16-alpine "docker-entrypoint.sтАж" db 7 minutes ago Up 17 seconds (healthy) 5432/tcp +mtusi2026lab7-grafana-1 grafana/grafana:12.2.0 "/run.sh" grafana 7 minutes ago Up 6 minutes 0.0.0.0:3000->3000/tcp, [::]:3000->3000/tcp +mtusi2026lab7-lb-1 nginx:1.27-alpine "/docker-entrypoint.тАж" lb 7 minutes ago Up 5 minutes 0.0.0.0:8443->8443/tcp, [::]:8443->8443/tcp +mtusi2026lab7-loki-1 grafana/loki:2.9.13 "/usr/bin/loki -confтАж" loki 7 minutes ago Up 6 minutes 0.0.0.0:3100->3100/tcp, [::]:3100->3100/tcp +mtusi2026lab7-minio-1 bitnamilegacy/minio:latest "/opt/bitnami/scriptтАж" minio 7 minutes ago Up 16 seconds (healthy) 9000-9001/tcp +mtusi2026lab7-openbao-1 openbao/openbao:2.2.0 "docker-entrypoint.sтАж" openbao 7 minutes ago Up 6 minutes 0.0.0.0:8200->8200/tcp, [::]:8200->8200/tcp +mtusi2026lab7-otel-collector-1 otel/opentelemetry-collector-contrib:0.90.1 "/otelcol-contrib --тАж" otel-collector 7 minutes ago Up 6 minutes 0.0.0.0:4317-4318->4317-4318/tcp, [::]:4317-4318->4317-4318/tcp +mtusi2026lab7-prometheus-1 prom/prometheus:v3.8.1 "/bin/prometheus --cтАж" prometheus 7 minutes ago Up 6 minutes 0.0.0.0:9090->9090/tcp, [::]:9090->9090/tcp +mtusi2026lab7-redis-1 redis:7-alpine "docker-entrypoint.sтАж" redis 7 minutes ago Up 17 seconds 6379/tcp +mtusi2026lab7-tempo-1 grafana/tempo:2.7.1 "/tempo -config.fileтАж" tempo 7 minutes ago Up 6 minutes 0.0.0.0:3200->3200/tcp, [::]:3200->3200/tcp +mtusi2026lab7-worker-1 mtusi2026lab7-worker "python -m worker" worker 7 minutes ago Up 16 seconds 8080/tcp +ready after 0 s + +=== 7. Failover test over HTTPS === +Executing explicit failover hook; hook output suppressed to avoid leaking secrets. +{"observed_instances_before": 2, "successful_writes": 103, "failed_attempts": 0, "first_recovery_seconds": 0.879} +PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence. +ready after 0 s +NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS +mtusi2026lab7-api1-1 mtusi2026lab7-api1 "python -m app" api1 3 minutes ago Up 34 seconds (healthy) 8080/tcp +mtusi2026lab7-api2-1 mtusi2026lab7-api2 "python -m app" api2 3 minutes ago Up 8 seconds (healthy) 8080/tcp +mtusi2026lab7-db-1 postgres:16-alpine "docker-entrypoint.sтАж" db 8 minutes ago Up 52 seconds (healthy) 5432/tcp +mtusi2026lab7-grafana-1 grafana/grafana:12.2.0 "/run.sh" grafana 8 minutes ago Up 7 minutes 0.0.0.0:3000->3000/tcp, [::]:3000->3000/tcp +mtusi2026lab7-lb-1 nginx:1.27-alpine "/docker-entrypoint.тАж" lb 8 minutes ago Up 5 minutes 0.0.0.0:8443->8443/tcp, [::]:8443->8443/tcp +mtusi2026lab7-loki-1 grafana/loki:2.9.13 "/usr/bin/loki -confтАж" loki 8 minutes ago Up 7 minutes 0.0.0.0:3100->3100/tcp, [::]:3100->3100/tcp +mtusi2026lab7-minio-1 bitnamilegacy/minio:latest "/opt/bitnami/scriptтАж" minio 8 minutes ago Up 51 seconds (healthy) 9000-9001/tcp +mtusi2026lab7-openbao-1 openbao/openbao:2.2.0 "docker-entrypoint.sтАж" openbao 8 minutes ago Up 7 minutes 0.0.0.0:8200->8200/tcp, [::]:8200->8200/tcp +mtusi2026lab7-otel-collector-1 otel/opentelemetry-collector-contrib:0.90.1 "/otelcol-contrib --тАж" otel-collector 8 minutes ago Up 7 minutes 0.0.0.0:4317-4318->4317-4318/tcp, [::]:4317-4318->4317-4318/tcp +mtusi2026lab7-prometheus-1 prom/prometheus:v3.8.1 "/bin/prometheus --cтАж" prometheus 8 minutes ago Up 7 minutes 0.0.0.0:9090->9090/tcp, [::]:9090->9090/tcp +mtusi2026lab7-redis-1 redis:7-alpine "docker-entrypoint.sтАж" redis 8 minutes ago Up 52 seconds 6379/tcp +mtusi2026lab7-tempo-1 grafana/tempo:2.7.1 "/tempo -config.fileтАж" tempo 8 minutes ago Up 7 minutes 0.0.0.0:3200->3200/tcp, [::]:3200->3200/tcp +mtusi2026lab7-worker-1 mtusi2026lab7-worker "python -m worker" worker 8 minutes ago Up 51 seconds 8080/tcp + +=== 8. Unit tests and offline check === +---------------------------------------------------------------------- +Ran 16 tests in 0.264s + +OK +PASS: offline skeleton structure, local refs and Python syntax; application NOT tested. diff --git a/infra/grafana-dashboard.json b/infra/grafana-dashboard.json new file mode 100644 index 0000000..dfbfc7d --- /dev/null +++ b/infra/grafana-dashboard.json @@ -0,0 +1,65 @@ +{ + "uid": "messenger-lab6", + "title": "Messenger lab6 — API, worker, traces", + "tags": ["messenger", "lab6"], + "timezone": "utc", + "schemaVersion": 39, + "version": 1, + "refresh": "5s", + "time": {"from": "now-15m", "to": "now"}, + "panels": [ + { + "id": 1, + "type": "stat", + "title": "API RPS", + "gridPos": {"h": 6, "w": 6, "x": 0, "y": 0}, + "datasource": {"type": "prometheus", "uid": "prometheus"}, + "targets": [{"expr": "sum(rate(http_server_requests_total[1m]))", "refId": "A"}], + "fieldConfig": {"defaults": {"unit": "reqps"}, "overrides": []} + }, + { + "id": 2, + "type": "timeseries", + "title": "HTTP 5xx ratio (business routes)", + "gridPos": {"h": 6, "w": 9, "x": 6, "y": 0}, + "datasource": {"type": "prometheus", "uid": "prometheus"}, + "targets": [{"expr": "sum(rate(http_server_requests_total{http_response_status_class=\"5xx\"}[1m])) / clamp_min(sum(rate(http_server_requests_total[1m])), 0.001)", "refId": "A"}], + "fieldConfig": {"defaults": {"unit": "percentunit"}, "overrides": []} + }, + { + "id": 3, + "type": "timeseries", + "title": "HTTP p95 duration (histogram)", + "gridPos": {"h": 6, "w": 9, "x": 15, "y": 0}, + "datasource": {"type": "prometheus", "uid": "prometheus"}, + "targets": [{"expr": "histogram_quantile(0.95, sum by (le) (rate(http_server_duration_bucket[1m])))", "refId": "A"}], + "fieldConfig": {"defaults": {"unit": "s"}, "overrides": []} + }, + { + "id": 4, + "type": "timeseries", + "title": "Worker jobs by outcome", + "gridPos": {"h": 7, "w": 10, "x": 0, "y": 6}, + "datasource": {"type": "prometheus", "uid": "prometheus"}, + "targets": [{"expr": "sum by (job_outcome) (rate(messenger_jobs_total[1m]))", "refId": "A"}], + "fieldConfig": {"defaults": {"unit": "ops"}, "overrides": []} + }, + { + "id": 5, + "type": "timeseries", + "title": "Worker job p95 duration", + "gridPos": {"h": 7, "w": 8, "x": 10, "y": 6}, + "datasource": {"type": "prometheus", "uid": "prometheus"}, + "targets": [{"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_job_duration_bucket[1m])))", "refId": "A"}], + "fieldConfig": {"defaults": {"unit": "s"}, "overrides": []} + }, + { + "id": 6, + "type": "logs", + "title": "API + worker structured logs", + "gridPos": {"h": 9, "w": 24, "x": 0, "y": 13}, + "datasource": {"type": "loki", "uid": "loki"}, + "targets": [{"expr": "{job=~\"messenger-(api|worker)\"}", "refId": "A"}] + } + ] +} diff --git a/infra/grafana-dashboards.yml b/infra/grafana-dashboards.yml new file mode 100644 index 0000000..efb0ec3 --- /dev/null +++ b/infra/grafana-dashboards.yml @@ -0,0 +1,13 @@ +apiVersion: 1 + +providers: + - name: Messenger observability + orgId: 1 + folder: Messenger + type: file + disableDeletion: false + updateIntervalSeconds: 10 + allowUiUpdates: false + options: + path: /var/lib/grafana/dashboards + foldersFromFilesStructure: false diff --git a/infra/grafana-datasources.yml b/infra/grafana-datasources.yml new file mode 100644 index 0000000..350ebb5 --- /dev/null +++ b/infra/grafana-datasources.yml @@ -0,0 +1,26 @@ +apiVersion: 1 + +datasources: + - name: Prometheus + uid: prometheus + type: prometheus + access: proxy + url: http://prometheus:9090 + isDefault: true + editable: false + - name: Loki + uid: loki + type: loki + access: proxy + url: http://loki:3100 + editable: false + - name: Tempo + type: tempo + access: proxy + url: http://tempo:3200 + editable: false + jsonData: + tracesToLogsV2: + datasourceUid: 'loki' + spanStartTimeShift: '-1m' + spanEndTimeShift: '1m' diff --git a/infra/loki-config.yaml b/infra/loki-config.yaml new file mode 100644 index 0000000..9367fc0 --- /dev/null +++ b/infra/loki-config.yaml @@ -0,0 +1,34 @@ +auth_enabled: false + +server: + http_listen_port: 3100 + +common: + path_prefix: /loki + storage: + filesystem: + chunks_directory: /loki/chunks + rules_directory: /loki/rules + replication_factor: 1 + ring: + instance_addr: 127.0.0.1 + kvstore: + store: inmemory + +schema_config: + configs: + - from: 2024-01-01 + store: tsdb + object_store: filesystem + schema: v13 + index: + prefix: index_ + period: 24h + +limits_config: + retention_period: 168h + ingestion_rate_mb: 16 + ingestion_burst_size_mb: 32 + +ruler: + alertmanager_url: http://localhost:9093 diff --git a/infra/nginx.conf b/infra/nginx.conf new file mode 100644 index 0000000..4932e62 --- /dev/null +++ b/infra/nginx.conf @@ -0,0 +1,43 @@ +events { + worker_connections 1024; +} + +http { + access_log /dev/stdout; + error_log /dev/stderr warn; + + upstream api_backend { + server api1:8443 max_fails=1 fail_timeout=5s; + server api2:8443 max_fails=1 fail_timeout=5s; + } + + server { + listen 8443 ssl; + ssl_certificate /certs/ingress.crt; + ssl_certificate_key /certs/private/ingress.key; + ssl_protocols TLSv1.2 TLSv1.3; + ssl_session_cache off; + + location / { + # Outbound mTLS: the API replicas require and verify the LB identity. + proxy_pass https://api_backend; + proxy_ssl_certificate /certs/lb.crt; + proxy_ssl_certificate_key /certs/private/lb.key; + proxy_ssl_trusted_certificate /certs/ca.crt; + proxy_ssl_verify on; + proxy_ssl_verify_depth 2; + proxy_ssl_name api1; # both leaf certs carry api1/api2/api SANs + proxy_ssl_server_name on; + proxy_ssl_protocols TLSv1.2 TLSv1.3; + + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header Connection ""; + proxy_next_upstream error timeout http_502 http_503 http_504; + proxy_connect_timeout 1s; + proxy_send_timeout 10s; + proxy_read_timeout 10s; + } + } +} diff --git a/infra/otel-collector-config.yaml b/infra/otel-collector-config.yaml new file mode 100644 index 0000000..23c1e94 --- /dev/null +++ b/infra/otel-collector-config.yaml @@ -0,0 +1,47 @@ +receivers: + otlp: + protocols: + grpc: + endpoint: 0.0.0.0:4317 + tls: + cert_file: /certs/otel-collector.crt + key_file: /certs/private/otel-collector.key + http: + endpoint: 0.0.0.0:4318 + tls: + cert_file: /certs/otel-collector.crt + key_file: /certs/private/otel-collector.key + +processors: + memory_limiter: + check_interval: 1s + limit_mib: 200 + spike_limit_mib: 50 + batch: + timeout: 5s + send_batch_size: 512 + +exporters: + prometheus: + endpoint: 0.0.0.0:8889 + loki: + endpoint: http://loki:3100/loki/api/v1/push + otlp/tempo: + endpoint: tempo:4317 + tls: + insecure: true + +service: + pipelines: + traces: + receivers: [otlp] + processors: [memory_limiter, batch] + exporters: [otlp/tempo] + metrics: + receivers: [otlp] + processors: [memory_limiter, batch] + exporters: [prometheus] + logs: + receivers: [otlp] + processors: [memory_limiter, batch] + exporters: [loki] diff --git a/infra/prometheus.yml b/infra/prometheus.yml new file mode 100644 index 0000000..7d36c61 --- /dev/null +++ b/infra/prometheus.yml @@ -0,0 +1,14 @@ +global: + scrape_interval: 5s + evaluation_interval: 5s + +scrape_configs: + - job_name: otel-collector + static_configs: + - targets: ["otel-collector:8889"] + - job_name: otel-collector-internal + static_configs: + - targets: ["otel-collector:8888"] + - job_name: prometheus + static_configs: + - targets: ["localhost:9090"] diff --git a/infra/tempo-config.yaml b/infra/tempo-config.yaml new file mode 100644 index 0000000..c7980f0 --- /dev/null +++ b/infra/tempo-config.yaml @@ -0,0 +1,20 @@ +server: + http_listen_port: 3200 + +distributor: + receivers: + otlp: + protocols: + grpc: + endpoint: 0.0.0.0:4317 + http: + endpoint: 0.0.0.0:4318 + +storage: + trace: + backend: local + wal: + path: /tmp/tempo/wal + local: + path: /tmp/tempo/blocks + diff --git a/migrations/001_init.sql b/migrations/001_init.sql new file mode 100644 index 0000000..efb305a --- /dev/null +++ b/migrations/001_init.sql @@ -0,0 +1,79 @@ +-- Lab2 initial schema. Applied once by app/db.py; safe to keep volumes on restart. +-- Source of truth for users, chats, memberships, messages and sessions is PostgreSQL. + +CREATE TABLE IF NOT EXISTS users ( + id UUID PRIMARY KEY, + username TEXT NOT NULL UNIQUE CHECK (username ~ '^[a-z0-9_]{3,32}$'), + display_name TEXT NOT NULL CHECK (length(display_name) BETWEEN 1 AND 100), + password_hash TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp() +); + +CREATE TABLE IF NOT EXISTS chats ( + id UUID PRIMARY KEY, + title TEXT NOT NULL CHECK (length(title) BETWEEN 1 AND 100), + created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp() +); + +CREATE TABLE IF NOT EXISTS chat_members ( + chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE, + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + PRIMARY KEY (chat_id, user_id) +); +CREATE INDEX IF NOT EXISTS ix_chat_members_user ON chat_members (user_id, chat_id); + +CREATE TABLE IF NOT EXISTS messages ( + id UUID PRIMARY KEY, + chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE, + sender_id UUID NOT NULL REFERENCES users(id), + text TEXT NOT NULL CHECK (length(text) <= 4000), + attachment_ids UUID[] NOT NULL DEFAULT '{}', + created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp() +); +-- Keyset pagination reads strictly one (created_at, id) window; no full-history scan. +CREATE INDEX IF NOT EXISTS ix_messages_history ON messages (chat_id, created_at, id); + +CREATE TABLE IF NOT EXISTS sessions ( + token_hash TEXT PRIMARY KEY, + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + expires_at TIMESTAMPTZ NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp() +); +CREATE INDEX IF NOT EXISTS ix_sessions_user ON sessions (user_id); +CREATE INDEX IF NOT EXISTS ix_sessions_expiry ON sessions (expires_at); + +-- Shared idempotency ledger for POST /chats/{id}/messages (lab3+). +-- Uniqueness scope: user + HTTP method + chat path + key. Stored alongside the +-- message insert in the SAME transaction, so a retry cannot create a duplicate. +CREATE TABLE IF NOT EXISTS idempotency_records ( + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + method TEXT NOT NULL, + path TEXT NOT NULL, + key TEXT NOT NULL, + request_hash TEXT NOT NULL, + status_code INTEGER NOT NULL, + response_body JSONB NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), + PRIMARY KEY (user_id, method, path, key) +); +CREATE INDEX IF NOT EXISTS ix_idempotency_created ON idempotency_records (created_at); + +-- Attachment metadata lives in PostgreSQL; bytes live in a private S3 bucket. +CREATE TABLE IF NOT EXISTS attachments ( + id UUID PRIMARY KEY, + chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE, + owner_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + filename TEXT NOT NULL CHECK (length(filename) BETWEEN 1 AND 255), + content_type TEXT NOT NULL CHECK (content_type IN ('image/png', 'image/jpeg')), + size_bytes INTEGER NOT NULL CHECK (size_bytes BETWEEN 1 AND 10485760), + sha256 TEXT NOT NULL CHECK (sha256 ~ '^[a-f0-9]{64}$'), + object_key TEXT NOT NULL UNIQUE, + status TEXT NOT NULL DEFAULT 'queued' + CHECK (status IN ('queued','processing','ready','failed')), + variants JSONB NOT NULL DEFAULT '[]'::jsonb, + error_code TEXT, + attempts INTEGER NOT NULL DEFAULT 0, + created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp() +); +CREATE INDEX IF NOT EXISTS ix_attachments_chat ON attachments (chat_id); diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..0c7cc10 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,9 @@ +fastapi==0.135.3 +uvicorn==0.44.0 +psycopg[binary]==3.3.3 +boto3==1.40.67 +argon2-cffi==25.1.0 +redis==7.4.0 +Pillow==12.2.0 +opentelemetry-sdk==1.45.2 +opentelemetry-exporter-otlp-proto-http==1.45.2 diff --git a/scripts/bootstrap_bao.py b/scripts/bootstrap_bao.py new file mode 100644 index 0000000..2aea374 --- /dev/null +++ b/scripts/bootstrap_bao.py @@ -0,0 +1,91 @@ +#!/usr/bin/env python3 +"""One-time operator bootstrap for the lab7 OpenBao instance. + +Creates init keys (saved outside Git), unseals, enables KV-v2, writes a scoped +policy and an AppRole, stores role_id/secret_id outside Git, and writes the +application secrets. Root token and unseal keys are never given to the app. +""" +import json +import os +import ssl +import urllib.error +import urllib.request +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +PRIVATE = ROOT / "certs" / "private" +CA = ROOT / "certs" / "ca.crt" +ADDR = "https://localhost:8200" +CTX = ssl.create_default_context(cafile=str(CA)) + + +def call(method, path, body=None, token=None, allow_codes=()): + data = json.dumps(body).encode() if body is not None else None + headers = {"Content-Type": "application/json"} + if token: + headers["X-Vault-Token"] = token + req = urllib.request.Request(ADDR + path, data=data, headers=headers, method=method) + try: + with urllib.request.urlopen(req, context=CTX, timeout=10) as response: + raw = response.read() + return json.loads(raw) if raw else {} + except urllib.error.HTTPError as exc: + if exc.code in allow_codes: + return json.loads(exc.read()) + raise RuntimeError("%s %s -> %s: %s" % (method, path, exc.code, exc.read()[:300])) from None + + +def load_dotenv(): + env_file = ROOT / ".env" + if env_file.exists(): + for line in env_file.read_text().splitlines(): + if "=" in line and not line.lstrip().startswith("#"): + key, value = line.split("=", 1) + os.environ.setdefault(key.strip(), value.strip()) + + +def main(): + load_dotenv() + init_file = PRIVATE / "bao-init.json" + if init_file.exists(): + initial = json.loads(init_file.read_text()) + else: + if call("GET", "/v1/sys/init").get("initialized"): + raise SystemExit("OpenBao is already initialized but local init file is missing") + initial = call("POST", "/v1/sys/init", {"secret_shares": 5, "secret_threshold": 3}) + init_file.write_text(json.dumps(initial, indent=2)) + os.chmod(init_file, 0o600) + root = initial["root_token"] + health = call("GET", "/v1/sys/health", allow_codes=(503, 472, 473)) + if health.get("sealed"): + for key in initial["keys"][:3]: + call("POST", "/v1/sys/unseal", {"key": key}, token=root) + print("OpenBao unsealed with operator-held keys") + configured = (PRIVATE / "bao-approle.json").exists() + if not configured: + call("POST", "/v1/sys/mounts/secret", {"type": "kv", "options": {"version": "2"}}, token=root) + policy = (ROOT / "security" / "app-policy.hcl").read_text() + call("POST", "/v1/sys/policies/acl/messenger-app", {"policy": policy}, token=root) + call("POST", "/v1/sys/auth/approle", {"type": "approle"}, token=root) + call("POST", "/v1/auth/approle/role/messenger-app", { + "token_policies": "messenger-app", "token_ttl": "1h", "token_max_ttl": "4h", + }, token=root) + role_id = call("GET", "/v1/auth/approle/role/messenger-app/role-id", token=root)["data"]["role_id"] + secret_id = call("POST", "/v1/auth/approle/role/messenger-app/secret-id", token=root)["data"]["secret_id"] + approle_file = PRIVATE / "bao-approle.json" + approle_file.write_text(json.dumps({"role_id": role_id, "secret_id": secret_id}, indent=2)) + os.chmod(approle_file, 0o600) + + secret = { + "DATABASE_URL": os.environ.get("DATABASE_URL", + "postgresql://messenger:messenger@db:5432/messenger"), + "S3_ACCESS_KEY": os.environ.get("S3_ACCESS_KEY", "messenger"), + "S3_SECRET_KEY": os.environ.get("S3_SECRET_KEY", "local-only-synthetic-s3-secret"), + "REDIS_PASSWORD": os.environ.get("REDIS_PASSWORD", "local-only-synthetic-redis"), + } + call("POST", "/v1/secret/data/messenger/app", {"data": secret}, token=root) + print("OpenBao bootstrapped: unsealed, KV-v2 + scoped AppRole, secret path secret/messenger/app") + + +if __name__ == "__main__": + main() diff --git a/scripts/demo_worker_restart.py b/scripts/demo_worker_restart.py new file mode 100644 index 0000000..7bef54a --- /dev/null +++ b/scripts/demo_worker_restart.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +"""Level-3 demonstration: accepted work survives a stopped worker. + +Stops only the worker, uploads (expects 202 queued and 409 on content), then starts +the worker again and waits for ready + a valid 256x160 thumbnail. +""" +import subprocess +import sys +import time +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tests")) +from client import Client, check # noqa: E402 + + +def compose(*args): + script = ROOT / "scripts" / ("stop-worker.cmd" if sys.platform == "win32" else "stop-worker.sh") + subprocess.run([str(script), *args], cwd=str(ROOT), check=True, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + + +def main(): + c = Client("http://localhost:8080") + alice, bob, _eve, chat = c.bootstrap() + + compose("stop") # worker down, broker/API/S3 intact + attachment, original = c.attachment(alice, chat) + check(attachment["status"] == "queued", "upload must be 202 queued") + c.call("GET", "/api/v1/attachments/" + attachment["id"] + "/content", 409, actor=bob) + print("ACCEPTED:", attachment["id"], "status=queued; content=409 while worker is stopped") + + compose("start") + deadline = time.monotonic() + 90 + while True: + ready = c.call("GET", "/api/v1/attachments/" + attachment["id"], 200, + actor=bob, schema="Attachment")["json"] + if ready["status"] == "ready": + break + check(ready["status"] != "failed", "job reached failed") + check(time.monotonic() < deadline, "job did not reach ready within 90 s") + time.sleep(0.3) + + thumb = [v for v in ready["variants"] if v["name"] == "thumbnail"] + check(len(thumb) == 1 and (thumb[0]["width"], thumb[0]["height"]) == (256, 160), + "thumbnail missing or wrong size") + check(len(c.call("GET", "/api/v1/attachments/" + attachment["id"] + "/content", + 200, actor=bob)["bytes"]) == len(original), "original changed") + c.call("GET", "/api/v1/attachments/" + attachment["id"] + "/content?variant=thumbnail", + 200, actor=bob) + print("RECOVERED:", attachment["id"], "status=ready, thumbnail=256x160, original intact") + + +if __name__ == "__main__": + main() diff --git a/scripts/generate_certs.py b/scripts/generate_certs.py new file mode 100644 index 0000000..d93a2fc --- /dev/null +++ b/scripts/generate_certs.py @@ -0,0 +1,107 @@ +#!/usr/bin/env python3 +"""Local synthetic PKI bootstrap. Private keys stay outside Git (certs/private/). + +Generates one CA plus leaf certificates with explicit SANs for every service in +the lab7 trust matrix. Re-run to rotate leaves (keep the CA unless rotating trust). +""" +import datetime as dt +from pathlib import Path + +from cryptography import x509 +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import rsa +from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID + +ROOT = Path(__file__).resolve().parents[1] +CERTS = ROOT / "certs" +PRIVATE = CERTS / "private" +DAYS = 365 + + +def new_key(): + return rsa.generate_private_key(public_exponent=65537, key_size=2048) + + +def save(key, cert, name): + PRIVATE.mkdir(parents=True, exist_ok=True) + CERTS.mkdir(parents=True, exist_ok=True) + (PRIVATE / (name + ".key")).write_bytes(key.private_bytes( + serialization.Encoding.PEM, serialization.PrivateFormat.TraditionalOpenSSL, + serialization.NoEncryption())) + (CERTS / (name + ".crt")).write_bytes(cert.public_bytes(serialization.Encoding.PEM)) + + +def make_ca(common_name="mtusi-lab7-local-ca", filename="ca"): + key = new_key() + name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, common_name)]) + cert = (x509.CertificateBuilder() + .subject_name(name).issuer_name(name).public_key(key.public_key()) + .serial_number(x509.random_serial_number()) + .not_valid_before(dt.datetime.now(dt.timezone.utc) - dt.timedelta(minutes=5)) + .not_valid_after(dt.datetime.now(dt.timezone.utc) + dt.timedelta(days=DAYS)) + .add_extension(x509.BasicConstraints(ca=True, path_length=None), critical=True) + .add_extension(x509.SubjectKeyIdentifier.from_public_key(key.public_key()), critical=False) + .add_extension(x509.KeyUsage( + digital_signature=True, content_commitment=False, key_encipherment=False, + data_encipherment=False, key_agreement=False, key_cert_sign=True, + crl_sign=True, encipher_only=False, decipher_only=False), critical=True) + .sign(key, hashes.SHA256())) + save(key, cert, filename) + return key, cert + + +def leaf(ca_key, ca_cert, name, dns, ips=(), client=False, server=True): + key = new_key() + subject = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, name)]) + builder = (x509.CertificateBuilder() + .subject_name(subject).issuer_name(ca_cert.subject) + .public_key(key.public_key()).serial_number(x509.random_serial_number()) + .not_valid_before(dt.datetime.now(dt.timezone.utc) - dt.timedelta(minutes=5)) + .not_valid_after(dt.datetime.now(dt.timezone.utc) + dt.timedelta(days=DAYS))) + if server: + builder = builder.add_extension( + x509.SubjectAlternativeName( + [x509.DNSName(d) for d in dns] + [x509.IPAddress(__import__("ipaddress").ip_address(i)) for i in ips]), + critical=False) + eku = [] + if server: + eku.append(ExtendedKeyUsageOID.SERVER_AUTH) + if client: + eku.append(ExtendedKeyUsageOID.CLIENT_AUTH) + if eku: + builder = builder.add_extension(x509.ExtendedKeyUsage(eku), critical=False) + builder = builder.add_extension(x509.KeyUsage( + digital_signature=True, content_commitment=False, key_encipherment=True, + data_encipherment=False, key_agreement=False, key_cert_sign=False, + crl_sign=False, encipher_only=False, decipher_only=False), critical=False) + builder = builder.add_extension( + x509.AuthorityKeyIdentifier.from_issuer_public_key(ca_key.public_key()), critical=False) + cert = builder.sign(ca_key, hashes.SHA256()) + save(key, cert, name) + + +def main(): + ca_key, ca_cert = make_ca() + # Dedicated issuing CA for the only allowed mesh client identity (the LB). + mesh_key, mesh_cert = make_ca("mtusi-lab7-lb-mesh-ca", "mesh-ca") + specs = [ + ("ingress", ["localhost", "ingress"], ["127.0.0.1"], True, False), + ("api", ["api1", "api2", "api"], [], True, True), + ("lb", ["lb"], [], False, True), + ("db", ["db"], [], True, False), + ("minio", ["minio"], [], True, False), + ("redis", ["redis"], [], True, False), + ("otel-collector", ["otel-collector"], [], True, False), + ("openbao", ["openbao", "localhost"], ["127.0.0.1"], True, False), + ] + for name, dns, ips, server, client in specs: + if name == "lb": + leaf(mesh_key, mesh_cert, name, dns, ips, client=client, server=server) + else: + leaf(ca_key, ca_cert, name, dns, ips, client=client, server=server) + print("generated CA and %d leaves in %s (private keys in %s)" % (len(specs), CERTS, PRIVATE)) + print("public CA: %s" % (CERTS / "ca.crt")) + + +if __name__ == "__main__": + main() diff --git a/scripts/restart.cmd b/scripts/restart.cmd new file mode 100644 index 0000000..3cd082d --- /dev/null +++ b/scripts/restart.cmd @@ -0,0 +1,5 @@ +@echo off +cd /d "%~dp0.." +docker compose --env-file .env restart db minio redis api1 api2 worker +docker compose --env-file .env exec -T lb nginx -s reload +exit /b %ERRORLEVEL% diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100755 index 0000000..60cb01b --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,7 @@ +#!/bin/sh +set -eu +# Restart business services through the TLS mesh; OpenBao stays unsealed with its volume. +cd "$(dirname "$0")/.." +docker compose restart db minio redis api1 api2 worker +# nginx caches upstream IPs at start; reload after container recreation. +docker compose exec -T lb nginx -s reload diff --git a/scripts/stop-one.cmd b/scripts/stop-one.cmd new file mode 100644 index 0000000..1e804f2 --- /dev/null +++ b/scripts/stop-one.cmd @@ -0,0 +1,9 @@ +@echo off +cd /d "%~dp0.." +if "%TARGET_INSTANCE_ID%"=="api1" goto stop +if "%TARGET_INSTANCE_ID%"=="api2" goto stop +echo unknown target instance: %TARGET_INSTANCE_ID% >&2 +exit /b 1 +:stop +docker compose --env-file .env stop %TARGET_INSTANCE_ID% +exit /b %ERRORLEVEL% diff --git a/scripts/stop-one.sh b/scripts/stop-one.sh new file mode 100755 index 0000000..6f4cb63 --- /dev/null +++ b/scripts/stop-one.sh @@ -0,0 +1,8 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." +: "${TARGET_INSTANCE_ID:?test provides target API instance alias}" +case "$TARGET_INSTANCE_ID" in + api1|api2) docker compose stop "$TARGET_INSTANCE_ID" ;; + *) echo "unknown target instance: $TARGET_INSTANCE_ID" >&2; exit 1 ;; +esac diff --git a/scripts/stop-worker.cmd b/scripts/stop-worker.cmd new file mode 100644 index 0000000..74264e4 --- /dev/null +++ b/scripts/stop-worker.cmd @@ -0,0 +1,8 @@ +@echo off +cd /d "%~dp0.." +if "%~1"=="start" goto start +docker compose --env-file .env stop worker +exit /b %ERRORLEVEL% +:start +docker compose --env-file .env start worker +exit /b %ERRORLEVEL% diff --git a/scripts/stop-worker.sh b/scripts/stop-worker.sh new file mode 100755 index 0000000..10062d3 --- /dev/null +++ b/scripts/stop-worker.sh @@ -0,0 +1,10 @@ +#!/bin/sh +set -eu +# Explicit demo hook: stop or start ONLY the worker. +# Stop: uploads keep returning 202; accepted jobs remain in Redis Streams. +cd "$(dirname "$0")/.." +if [ "${1:-stop}" = "start" ]; then + docker compose start worker +else + docker compose stop worker +fi diff --git a/scripts/verify_security.py b/scripts/verify_security.py new file mode 100644 index 0000000..084e6ac --- /dev/null +++ b/scripts/verify_security.py @@ -0,0 +1,137 @@ +#!/usr/bin/env python3 +"""Level-3 negative checks: internal mTLS identity and scoped OpenBao policy.""" +import datetime as dt +import json +import ssl +import urllib.error +import urllib.request +from pathlib import Path + +from cryptography import x509 +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import rsa +from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID + +ROOT = Path(__file__).resolve().parents[1] +CERTS = ROOT / "certs" +PRIVATE = CERTS / "private" + + +def https(url, cert=None, key=None, cafile=None, data=None, headers=None, timeout=8, method=None): + context = ssl.create_default_context(cafile=str(cafile or CERTS / "ca.crt")) + if cert: + context.load_cert_chain(str(cert), str(key)) + request = urllib.request.Request( + url, data=data, headers=headers or {}, method=method or ("POST" if data is not None else "GET")) + try: + with urllib.request.urlopen(request, context=context, timeout=timeout) as response: + return response.status, response.read(), dict(response.headers) + except urllib.error.HTTPError as exc: + return exc.code, exc.read(), dict(exc.headers) + except (urllib.error.URLError, ssl.SSLError, OSError) as exc: + return 0, str(exc).encode(), {} + + +def make_rogue_client(): + key = rsa.generate_private_key(public_exponent=65537, key_size=2048) + ca_key = serialization.load_pem_private_key((PRIVATE / "ca.key").read_bytes(), password=None) + ca_cert = x509.load_pem_x509_certificate((CERTS / "ca.crt").read_bytes()) + subject = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "evil-lb")]) + cert = (x509.CertificateBuilder() + .subject_name(subject).issuer_name(ca_cert.subject).public_key(key.public_key()) + .serial_number(x509.random_serial_number()) + .not_valid_before(dt.datetime.now(dt.timezone.utc) - dt.timedelta(minutes=5)) + .not_valid_after(dt.datetime.now(dt.timezone.utc) + dt.timedelta(hours=1)) + .add_extension(x509.SubjectAlternativeName([x509.DNSName("evil-lb")]), critical=False) + .add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.CLIENT_AUTH]), critical=False) + .sign(ca_key, hashes.SHA256())) + (PRIVATE / "rogue-lb.key").write_bytes(key.private_bytes( + serialization.Encoding.PEM, serialization.PrivateFormat.TraditionalOpenSSL, + serialization.NoEncryption())) + (CERTS / "rogue-lb.crt").write_bytes(cert.public_bytes(serialization.Encoding.PEM)) + + +def main(): + url = "https://api1:8443/health/ready" # direct API port, bypassing the LB + host_ctx = None + # Resolve api1 through Docker DNS: run checks from the host against published LB + # for lack of DNS, so we use the container network via a temporary helper. + # Here we verify the API's client-cert requirement through the LB's upstream: + # the LB always presents a valid identity; a direct no-cert probe must fail. + status, body, _ = https("https://localhost:8443/health/ready") + assert status == 200, "valid trusted HTTPS failed: %s" % body[:100] + print("TLS OK: trusted CA and hostname accepted") + + # Direct API probes are executed inside the api1 container (Docker DNS + network). + import subprocess + script = ( + "import ssl,urllib.request;" + "c=ssl.create_default_context(cafile='/certs/ca.crt');" + "print(urllib.request.urlopen('https://api1:8443/health/ready',context=c,timeout=3).status)" + ) + result = subprocess.run( + ["docker", "compose", "--env-file", ".env", "exec", "-T", "api1", "python", "-c", script], + cwd=str(ROOT), capture_output=True, text=True) + assert result.returncode != 0, "API accepted a client without a certificate" + print("MTLS OK: no client certificate rejected by API") + + make_rogue_client() + script = ( + "import ssl,urllib.request;" + "c=ssl.create_default_context(cafile='/certs/ca.crt');" + "c.load_cert_chain('/certs/rogue-lb.crt','/certs/private/rogue-lb.key');" + "print(urllib.request.urlopen('https://api1:8443/health/ready',context=c,timeout=3).status)" + ) + result = subprocess.run( + ["docker", "compose", "--env-file", ".env", "exec", "-T", "api1", "python", "-c", script], + cwd=str(ROOT), capture_output=True, text=True) + assert result.returncode != 0, "API accepted a trusted-CA but unauthorized identity" + print("MTLS OK: trusted-CA but wrong identity rejected by API") + + # OpenBao: scoped AppRole may read its own path, not write it or read others. + creds = json.loads((PRIVATE / "bao-approle.json").read_text()) + ctx = ssl.create_default_context(cafile=str(CERTS / "ca.crt")) + login = urllib.request.Request( + "https://localhost:8200/v1/auth/approle/login", + data=json.dumps(creds).encode(), headers={"Content-Type": "application/json"}, method="POST") + with urllib.request.urlopen(login, context=ctx, timeout=8) as response: + token = json.loads(response.read())["auth"]["client_token"] + + def bao(path, method="GET", body=None): + request = urllib.request.Request( + "https://localhost:8200/v1/" + path, + data=json.dumps(body).encode() if body else None, + headers={"X-Vault-Token": token, "Content-Type": "application/json"}, method=method) + try: + with urllib.request.urlopen(request, context=ctx, timeout=8) as response: + return response.status + except urllib.error.HTTPError as exc: + return exc.code + + assert bao("secret/data/messenger/app") == 200 + assert bao("secret/data/messenger/other") == 403 + assert bao("secret/data/messenger/app", "POST", {"data": {"x": "y"}}) == 403 + print("BAO OK: own path readable; write and foreign path denied") + + # Login rate limit: the sixth attempt in a minute is rejected with Retry-After. + import base64 + import uuid + user = "u_rate_" + uuid.uuid4().hex[:10] + credential = base64.b64encode((user + ":wrong-password-123").encode()).decode() + statuses = [] + last_headers = {} + for _ in range(6): + status, _, headers = https( + "https://localhost:8443/api/v1/auth/sessions", + headers={"Authorization": "Basic " + credential}, method="POST", + ) + statuses.append(status) + last_headers = headers + assert statuses[:5] == [401] * 5, "unexpected login statuses: %s" % statuses + retry_after = next((v for k, v in last_headers.items() if k.lower() == "retry-after"), None) + assert statuses[5] == 429 and retry_after, "429/Retry-After missing" + print("RATE OK: 5x401 then 429 with Retry-After=%s" % retry_after) + + +if __name__ == "__main__": + main() diff --git a/scripts/verify_telemetry.py b/scripts/verify_telemetry.py new file mode 100644 index 0000000..a3d5417 --- /dev/null +++ b/scripts/verify_telemetry.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python3 +"""Verify that all three telemetry signals are really stored and queryable.""" +import base64 +import json +import time +import urllib.parse +import urllib.request + + +def get(url, headers=None): + req = urllib.request.Request(url, headers=headers or {}) + with urllib.request.urlopen(req, timeout=15) as response: + return json.loads(response.read().decode()) + + +def main(): + # 1. Metrics: real low-cardinality HTTP and job metrics from the Collector. + prom = get("http://localhost:9090/api/v1/query?query=" + + urllib.parse.quote("http_server_requests_total"))["data"]["result"] + assert prom, "no http_server_requests_total series" + assert any("http_route" in s["metric"] for s in prom), "route label missing" + jobs = get("http://localhost:9090/api/v1/query?query=" + + urllib.parse.quote("messenger_jobs_total"))["data"]["result"] + assert jobs, "no messenger_jobs_total series" + print("METRICS OK: http series=%d, job series=%d" % (len(prom), len(jobs))) + + # 2. Logs: structured OTLP records with trace/span IDs for an API request. + now = int(time.time() * 1e9) + query = urllib.parse.quote('{job=~"messenger-.*"} |= "message.created"') + logs = get("http://localhost:3100/loki/api/v1/query_range?query=%s&start=%d&end=%d&limit=3" + % (query, now - 30 * 60 * 10**9, now + 30 * 60 * 10**9))["data"]["result"] + assert logs, "no API logs in Loki" + line = logs[0]["values"][0][1] + assert "traceid" in line and "spanid" in line, "trace/span IDs missing from log" + print("LOGS OK: job=%s, traceid/spanid present" % logs[0]["stream"]["job"]) + + # 3. Traces: real API and worker spans in Tempo. + api = get("http://localhost:3200/api/search?tags=service.name%3Dmessenger-api&limit=3")["traces"] + worker = get("http://localhost:3200/api/search?tags=service.name%3Dmessenger-worker&limit=3")["traces"] + assert api and worker, "missing API or worker traces" + print("TRACES OK: api=%d, worker-linked=%d" % (len(api), len(worker))) + + # 4. Grafana provisioning: datasources and an imported dashboard. + auth = {"Authorization": "Basic " + base64.b64encode(b"admin:admin-local-only").decode()} + sources = get("http://localhost:3000/api/datasources", auth) + boards = get("http://localhost:3000/api/search?type=dash-db", auth) + assert len(sources) >= 3, "datasources not provisioned" + assert any(b["uid"] == "messenger-lab6" for b in boards), "dashboard not provisioned" + print("GRAFANA OK: datasources=%d, dashboard=messenger-lab6" % len(sources)) + + +if __name__ == "__main__": + main() diff --git a/security/app-policy.hcl b/security/app-policy.hcl new file mode 100644 index 0000000..b4493a5 --- /dev/null +++ b/security/app-policy.hcl @@ -0,0 +1,7 @@ +# Scoped application policy: read ONLY its own secret path. +path "secret/data/messenger/app" { + capabilities = ["read"] +} +path "secret/metadata/messenger/app" { + capabilities = ["read"] +} diff --git a/security/bao.hcl b/security/bao.hcl new file mode 100644 index 0000000..4c9a257 --- /dev/null +++ b/security/bao.hcl @@ -0,0 +1,15 @@ +# OpenBao in production mode: persistent file backend, TLS listener, no dev-mode. +storage "file" { + path = "/bao/data" +} + +listener "tcp" { + address = "0.0.0.0:8200" + tls_cert_file = "/certs/openbao.crt" + tls_key_file = "/certs/private/openbao.key" + tls_client_ca_file = "/certs/ca.crt" +} + +ui = true +disable_mlock = true +api_addr = "https://openbao:8200" diff --git a/student-tests/test_security.py b/student-tests/test_security.py new file mode 100644 index 0000000..c0561aa --- /dev/null +++ b/student-tests/test_security.py @@ -0,0 +1,131 @@ +"""Own tests for the security helpers and keyset cursors (stdlib unittest).""" +import base64 +import datetime as dt +import json +import sys +import unittest +import uuid +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) + +from app import main as api +from app.security import (bearer_token, hash_password, parse_basic, + token_hash, verify_password) + + +class PasswordTests(unittest.TestCase): + def test_kdf_round_trip_and_uniqueness(self): + first = hash_password("T3st-passphrase-123") + second = hash_password("T3st-passphrase-123") + self.assertNotEqual(first, second, "salt must be unique") + self.assertTrue(first.startswith("argon2id$2$19456$1$")) + self.assertTrue(verify_password("T3st-passphrase-123", first)) + self.assertFalse(verify_password("wrong-password", first)) + + def test_unicode_and_colon_password(self): + secret = "пароль:с:двоеточием-123" + stored = hash_password(secret) + self.assertTrue(verify_password(secret, stored)) + self.assertFalse(verify_password("пароль", stored)) + + +class CredentialTests(unittest.TestCase): + def test_basic_colon_inside_password(self): + raw = "u_alice_123:T3st-with:colon-12345" + header = "Basic " + base64.b64encode(raw.encode()).decode() + self.assertEqual(parse_basic(header), ("u_alice_123", "T3st-with:colon-12345")) + + def test_basic_rejects_short_password_and_bad_scheme(self): + raw = "u_alice_123:short" + self.assertIsNone(parse_basic("Basic " + base64.b64encode(raw.encode()).decode())) + self.assertIsNone(parse_basic("Bearer abcdef")) + + def test_bearer_only(self): + self.assertEqual(bearer_token("Bearer abc"), "abc") + self.assertIsNone(bearer_token("Basic abc")) + self.assertIsNone(bearer_token(None)) + + def test_token_hash_is_stable_and_not_the_token(self): + token = "s" * 43 + self.assertEqual(token_hash(token), token_hash(token)) + self.assertNotEqual(token_hash(token), token) + + +class IdempotencyTests(unittest.TestCase): + def test_key_pattern(self): + self.assertIsNotNone(api.IDEMPOTENCY_KEY_RE.fullmatch('abc-123.XYZ:9_')) + self.assertIsNone(api.IDEMPOTENCY_KEY_RE.fullmatch('bad key')) + self.assertIsNone(api.IDEMPOTENCY_KEY_RE.fullmatch('')) + + def test_canonical_body_hash_ignores_key_order(self): + import hashlib + a = json.dumps({'text': 'Привет'}, sort_keys=True, separators=(',', ':')) + b = json.dumps({'text': 'Привет'}, separators=(',', ':')) + self.assertEqual(hashlib.sha256(a.encode()).hexdigest(), + hashlib.sha256(b.encode()).hexdigest()) + + +class AttachmentTests(unittest.TestCase): + def test_filename_rejects_path_traversal(self): + for bad in ('../x.png', 'a/b.png', 'a\\b.png', 'a\x00b', 'a\nb'): + with self.assertRaises(api.ApiError): + api.validate_filename(bad) + self.assertEqual(api.validate_filename('photo.png'), 'photo.png') + + def test_probe_real_fixture(self): + from app.images import probe + data = (ROOT / 'tests/fixtures/sample.png').read_bytes() + content_type, width, height = probe(data) + self.assertEqual(content_type, 'image/png') + self.assertGreater(width, 0) + self.assertGreater(height, 0) + + def test_probe_rejects_garbage(self): + from app.images import InvalidImage, probe + with self.assertRaises(InvalidImage): + probe(b'not an image at all') + + +class WorkerTests(unittest.TestCase): + def test_thumbnail_from_fixture(self): + from worker.main import make_thumbnail + data = (ROOT / 'tests/fixtures/sample.png').read_bytes() + thumb, width, height = make_thumbnail(data) + self.assertEqual((width, height), (256, 160)) + self.assertTrue(thumb.startswith(b'\xff\xd8\xff')) + + def test_job_shape_matches_schema(self): + # The broker carries IDs only: no bytes, no object keys, no credentials. + job = {"schema_version": 1, "job_id": 'f' * 32, "type": "attachment.process.v1", + "attachment_id": 'a' * 32, "pipeline_version": 1, "attempt": 1, + "created_at": "2026-11-28T12:00:00.000000Z"} + schema = json.loads((ROOT / 'contracts/jobs.schema.json').read_text(encoding='utf-8')) + self.assertTrue(set(schema['required']).issubset(job)) + self.assertNotIn('data', job) + self.assertNotIn('object_key', job) + + +class CursorTests(unittest.TestCase): + def test_round_trip(self): + created = dt.datetime(2026, 11, 16, 12, 0, 0, 123456, tzinfo=dt.timezone.utc) + item_id = uuid.uuid4() + encoded = api.encode_cursor("messages", "scope-1", created, item_id) + back_created, back_id = api.decode_cursor(encoded, "messages", "scope-1") + self.assertEqual(back_created, created) + self.assertEqual(back_id, item_id) + + def test_wrong_scope_rejected(self): + created = dt.datetime.now(dt.timezone.utc) + encoded = api.encode_cursor("messages", "chat-A", created, uuid.uuid4()) + with self.assertRaises(api.ApiError): + api.decode_cursor(encoded, "messages", "chat-B") + + def test_garbage_rejected(self): + with self.assertRaises(api.ApiError): + api.decode_cursor("not-a-cursor", "messages", "chat-A") + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/worker/__init__.py b/worker/__init__.py new file mode 100644 index 0000000..a9d717f --- /dev/null +++ b/worker/__init__.py @@ -0,0 +1 @@ +"""Asynchronous attachment processor for lab5.""" diff --git a/worker/__main__.py b/worker/__main__.py new file mode 100644 index 0000000..ac8f136 --- /dev/null +++ b/worker/__main__.py @@ -0,0 +1,4 @@ +from .main import run + +if __name__ == "__main__": + run() diff --git a/worker/main.py b/worker/main.py new file mode 100644 index 0000000..6f94767 --- /dev/null +++ b/worker/main.py @@ -0,0 +1,169 @@ +"""Worker: durable-stream consumer that publishes originals and thumbnails. + +Effects are idempotent by (attachment_id, pipeline_version, variant). A redelivered +job for an already-ready attachment is a no-op followed by XACK. The broker message +carries only IDs and counters — never bytes, S3 keys derived from client input, or +credentials. +""" +import hashlib +import io +import json +import logging +import os +import uuid + +import time + +from app import broker, s3, telemetry +from app.db import db + +log = logging.getLogger("messenger.worker") + +MAX_ATTEMPTS = int(os.environ.get("MAX_ATTEMPTS", "5")) +CONSUMER = os.environ.get("BROKER_CONSUMER", "worker-1") +PIPELINE_VERSION = 1 + + +def make_thumbnail(data): + from PIL import Image, ImageOps + image = Image.open(io.BytesIO(data)) + image = ImageOps.exif_transpose(image) + 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, (255, 255, 255)) + background.paste(rgba, mask=rgba.getchannel("A")) + image = background + else: + image = image.convert("RGB") + # Fit into 256x256, preserve aspect ratio, never upscale. No EXIF is written. + image.thumbnail((256, 256), Image.Resampling.LANCZOS) + if image.width < 1 or image.height < 1: + raise ValueError("invalid thumbnail size") + output = io.BytesIO() + image.save(output, format="JPEG", quality=85) + return output.getvalue(), image.width, image.height + + +def _update(attachment_id, **fields): + assignments = ", ".join("%s = %s" % (k, v) for k, v in fields.items()) + with db.transaction() as conn: + conn.execute( + "UPDATE attachments SET " + assignments + ", updated_at = clock_timestamp() WHERE id = %s", + (uuid.UUID(attachment_id),), + ) + + +def _process(job): + attachment_id = job["attachment_id"] + attempt = int(job.get("attempt", 1)) + with db.connection() as conn: + row = conn.execute("SELECT * FROM attachments WHERE id = %s", (attachment_id,)).fetchone() + if row is None: + log.warning("job for unknown attachment %s", attachment_id) + return "unknown" + if row["status"] == "ready" and any(v.get("name") == "thumbnail" for v in (row["variants"] or [])): + log.info("already ready: %s — no-op", attachment_id) + return "noop" # at-least-once redelivery: identical effect, no duplicate variant + + _update(attachment_id, status="'processing'", attempts=str(attempt)) + try: + original, content_type = s3.get_object(row["object_key"]) + thumb, width, height = make_thumbnail(original) + final_key = row["object_key"].replace("staging/", "final/", 1) + thumb_key = final_key + ".thumbnail.jpg" + s3.put_object(final_key, original, content_type) + s3.put_object(thumb_key, thumb, "image/jpeg") + variant = { + "name": "thumbnail", + "content_type": "image/jpeg", + "size_bytes": len(thumb), + "width": width, + "height": height, + "sha256": hashlib.sha256(thumb).hexdigest(), + } + with db.transaction() as conn: + conn.execute( + "UPDATE attachments SET object_key = %s, status = 'ready', variants = %s::jsonb, " + "error_code = NULL, updated_at = clock_timestamp() " + "WHERE id = %s AND status <> 'ready'", + (final_key, json.dumps([variant]), uuid.UUID(attachment_id)), + ) + log.info("job finished: ready", extra={"event": "job.ready"}) + return "success" + except Exception as exc: + log.exception("processing failed: attachment=%s attempt=%s", attachment_id, attempt) + if attempt < MAX_ATTEMPTS: + _update(attachment_id, status="'queued'", error_code="NULL") + retry = { + "schema_version": 1, + "job_id": job.get("job_id") or str(uuid.uuid4()), + "type": "attachment.process.v1", + "attachment_id": attachment_id, + "pipeline_version": PIPELINE_VERSION, + "attempt": attempt + 1, + "created_at": job.get("created_at"), + } + if job.get("traceparent"): + retry["traceparent"] = job["traceparent"] + broker.publish(retry) + log.info("job retried", extra={"event": "job.retry"}) + return "retry" + _update(attachment_id, status="'failed'", error_code="'processing_failed'") + log.info("job failed", extra={"event": "job.failed"}) + return "failed" + + +def process_job(job): + begun = time.monotonic() + context = telemetry.extract({"traceparent": job["traceparent"]}) if job.get("traceparent") else None + with telemetry.worker_span("attachment.process.v1", context) as span: + if span is not None and span.is_recording(): + span.set_attribute("attachment.id", job["attachment_id"]) + span.set_attribute("job.attempt", int(job.get("attempt", 1))) + outcome = "error" + try: + outcome = _process(job) + finally: + telemetry.record_job("attachment.process.v1", outcome, time.monotonic() - begun) + + +def _handle(msg_id, fields): + try: + process_job(json.loads(fields["job"])) + except Exception: + log.exception("unhandled job message %s", msg_id) + finally: + broker.client.xack(broker.STREAM, broker.GROUP, msg_id) + + +def reclaim_pending(): + """Recover jobs left pending by a worker that died before XACK.""" + start = "0-0" + while True: + next_id, claimed, _ = broker.client.xautoclaim( + broker.STREAM, broker.GROUP, CONSUMER, min_idle_time=0, start_id=start, count=10 + ) + for msg_id, fields in claimed: + _handle(msg_id, fields) + if not claimed or next_id in ("0-0", None): + break + start = next_id + + +def run(): + logging.basicConfig(level=os.environ.get("LOG_LEVEL", "INFO").upper()) + from app.bao import load_secrets + load_secrets() + telemetry.init("messenger-worker", CONSUMER) + db.start() + s3.start() + broker.start() + reclaim_pending() + log.info("worker started: consumer=%s max_attempts=%s", CONSUMER, MAX_ATTEMPTS) + while True: + streams = broker.client.xreadgroup( + broker.GROUP, CONSUMER, {broker.STREAM: ">"}, count=1, block=2000 + ) + for _, messages in streams: + for msg_id, fields in messages: + _handle(msg_id, fields)