commit bd342f3333863bb48ad20686ab942e55024e2fe6 Author: eqktrin Date: Fri Oct 30 22:16:54 2026 +0300 4 diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 00000000..bc16e556 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,20 @@ +.git +.github +.env +.env.* +!.env.example +secrets +certs +volumes +data +backups +*.key +*.pem +*.p12 +*.pfx +*.jks +.venv +__pycache__ +node_modules +evidence +.DS_Store diff --git a/.env.example b/.env.example new file mode 100644 index 00000000..d99d26a2 --- /dev/null +++ b/.env.example @@ -0,0 +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 +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=http://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 diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 00000000..1bec5472 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,18 @@ +## Лабораторная 4 + +Автор / группа: TODO +Целевая оценка (3/4/5): TODO +Трек 5, если заявлен: TODO + +Что реализовано и что перенесено: TODO +Команды запуска из чистого clone: TODO +Результаты проверок и ссылка на REPORT.md: TODO +Ограничения / известные ошибки: TODO +Источники и использование ИИ: TODO + +- [ ] Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами. +- [ ] Контракт и публичные тесты не ослаблены. +- [ ] make check и make test выполнены; приложен реальный вывод. +- [ ] Сценарии отказов/безопасности своего уровня воспроизведены. +- [ ] Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens. +- [ ] README задания сохранён, REPORT.md содержит инструкцию именно моего решения. diff --git a/.github/workflows/contracts.yml b/.github/workflows/contracts.yml new file mode 100644 index 00000000..11cf289f --- /dev/null +++ b/.github/workflows/contracts.yml @@ -0,0 +1,16 @@ +name: Skeleton contracts +on: [push, pull_request] +permissions: + contents: read +jobs: + contracts: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - run: python -m pip install -r requirements-dev.txt + - run: make check validate PYTHON=python +# This job validates the skeleton, not a student solution. +# Add build, readiness and make test in a separate application job. diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..44726df3 --- /dev/null +++ b/.gitignore @@ -0,0 +1,33 @@ +# Local/private state +.env +.env.* +!.env.example +secrets/ +certs/private/ +*.key +*.p12 +*.pfx +*.jks +*.pem +*.tfstate* +volumes/ +data/ +backups/ +# Runtime/build artifacts +.venv/ +__pycache__/ +*.py[cod] +node_modules/ +dist/ +build/ +target/ +bin/ +obj/ +coverage/ +*.log +.DS_Store +.idea/ +.vscode/ +# Keep small, sanitized evidence summaries in evidence/ under version control. +# Inspect git diff --cached: ignore rules are not a secret scanner. +venv/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 00000000..ee5533d1 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,19 @@ +# Работа через fork и pull request + +1. После публикации преподавателем сделайте fork репозитория **текущей** лабораторной в своём аккаунте и clone своего fork. URL преподаватель выдаёт отдельно. +2. Создайте ветку `solution/-` от исходной ветки skeleton. Ветка преподавателя и файлы контракта остаются основой проверки. +3. Для lab2–7 перенесите из своей предыдущей лабы только исходники, миграции, собственные тесты, Dockerfile и нужные конфигурации. Не копируйте `.git`, `.env`, credentials, volumes, `README.md`, `COURSE.md`, публичные `tests/` и `contracts/` поверх новой версии. Сначала сравните изменения API в `COURSE.md`. +4. Реализуйте задание, добавьте свою инструкцию запуска и заполните `REPORT.md`. Публичные проверки дополняйте отдельными тестами, не ослабляйте assertions. +5. Выполните `make check`, запустите свой стенд, затем `make test`. Выполните сценарии отказов текущей лабы. Их запуск всегда явный: scaffold сам не останавливает контейнеры. +6. Commit и push делайте в свой fork. Откройте PR в исходный репозиторий преподавателя, заголовок: `ЛР N — Группа — Фамилия — на 3/4/5`. Выберите правильную базовую ветку и заполните шаблон. +7. После замечаний обновляйте тот же PR. Чужие решения не переносите без указания источника и согласованных правил курса. + +Платформа может называть PR «merge request» — процесс тот же. `.github/` содержит необязательные удобства для GitHub; проверки локально от платформы не зависят. Инициализация и публикация исходных Git-репозиториев выполняются преподавателем отдельно. + +## Правила изменения skeleton + +Не удаляйте обязательные endpoint, поля, рубрику и публичные проверки. Изменение контракта согласуйте отдельным комментарием/PR; обход тестов не является решением. Код приложения размещайте в `src/` либо в принятой для языка структуре. Собственные тесты — `student-tests/` или штатный каталог фреймворка. Ссылки на результаты проверки и команды запуска должны переживать clone на другой машине. + +## CI + +Готовый GitHub workflow проверяет целостность контракта и синтаксис Python-проверок. Он **не запускает отсутствующее приложение** и **не подтверждает оценку**. Студент добавляет сборку своего приложения, запуск/готовность стенда и `make test` в отдельный job. Не используйте `pull_request_target` для запуска кода из fork, не выдавайте CI секреты или доступ к общему Docker-host. diff --git a/COURSE.md b/COURSE.md new file mode 100644 index 00000000..b02172bb --- /dev/null +++ b/COURSE.md @@ -0,0 +1,53 @@ +# Сквозной проект: мессенджер под нагрузкой + +Семь самостоятельных репозиториев содержат задания и проверяемые контракты одной системы. Вы переносите собственную реализацию между лабораторными. Язык, фреймворк и библиотеки выбираете сами. Web UI, WebSocket, редактирование/удаление сообщений, публичный поиск пользователей и Kubernetes не входят в обязательный минимум: достаточно REST API. + +| Лаба | Новая инженерная задача | Что появляется в системе | +| --- | --- | --- | +| 1 | Контракт, процессы и контейнер | In-memory API, Dockerfile, HTTP smoke | +| 2 | Сохранность и идентификация | PostgreSQL, Basic → сессия; Redis/Valkey на 4 | +| 3 | Горизонтальное масштабирование | Балансировщик, ≥2 API-реплики, общие сессии, идемпотентность | +| 4 | Бинарные данные | Приватное S3-совместимое хранилище и вложения | +| 5 | Фоновая работа | Брокер, worker, состояния вложений и преобразование изображений | +| 6 | Диагностика | OTel Collector, хранилища сигналов, Grafana | +| 7 | Защита и эксплуатация | Argon2id, TLS/mTLS, OpenBao, минимальные привилегии | + +## Как оценивать + +Оценки накопительные **внутри лабораторной**: 4 = весь уровень 3 + весь уровень 4; 5 = весь уровень 4 + **один** полностью выполненный трек 5 на выбор. Несколько недоделанных треков не заменяют один завершённый. Условие «весь уровень» включает реализацию, проверку и объяснение на защите. Красивые схемы и дополнительные технологии не компенсируют неработающий обязательный сценарий. + +Для начала следующей лабы достаточно обязательного минимума предыдущей. Сохраняются предыдущие обязательные возможности, с явно описанными переходами API ниже. Не требуется сначала получить 5 за все ранние лабы. Можно исправлять свою базу по ходу курса; такие исправления выделяйте в PR. Реализация на 3 работоспособна, но не претендует на промышленную готовность. Даже 5 в lab7 — учебная доказанная защита в заявленной модели угроз, а не сертификат полной безопасности. + +На 3 студент самостоятельно собирает рабочую систему. На 4 показывает практики, ожидаемые от стажёра/джуна в команде: воспроизводимость, диагностику, обработку ошибок и проверки отказов. На 5 формулирует гипотезу, ставит эксперимент, приводит измерения и обсуждает границы решения — это предмет конкретной похвалы магистранту. + +## Контракт и совместимость + +`contracts/openapi.json` — OpenAPI 3.1.0, `contracts/README.md` — нормативная семантика. Контракт каждого репозитория самодостаточен; соседние папки на машине преподавателя не нужны. `tests/` — публичные проверки, а не эталонное решение. Контракт, рубрика и публичные тесты имеют приоритет над случайным поведением библиотек. При противоречии создайте вопрос преподавателю; не подгоняйте тест под приложение. + +Три объявленных изменения обязательного API: + +1. **1 → 2:** регистрация требует `password`; `X-User-Id` заменяется Bearer. Basic используется только при создании сессии. +2. **2 → 3:** `Idempotency-Key` обязателен для отправки сообщения; ответы API содержат `X-Instance-Id`. +3. **4 → 5:** загрузка вложения возвращает `202` вместо `201`, состояние становится асинхронным. Клиент опрашивает метаданные. Старое текстовое сообщение остаётся валидным: `attachment_ids` по умолчанию `[]`. + +У lab7 меняется транспорт на HTTPS, бизнес-эндпоинты остаются прежними. Внутреннее mTLS не заменяет пользовательскую сессию. Новые возможности на 4/5 добавляйте обратно совместимо, в отдельном `contracts/extensions.openapi.json` или документе; обязательный контракт сохраняйте. + +## Общая предметная модель + +Пользователь (`username`, `display_name`) состоит в чатах. Список участников задаётся при создании чата и в обязательном API не изменяется. В чате отправляются сообщения, с lab4 — со ссылками на вложения этого чата. Сервер назначает UUID и время. Порядок истории — `(created_at, id)` по возрастанию. Для защиты достаточно показать взаимодействие нескольких API-клиентов; фронтенд не требуется. + +С lab2 данные PostgreSQL — источник истины. Сессии могут храниться в PostgreSQL или Redis/Valkey, если выполняют контракт срока жизни и перезапуска. Файлы с lab4 живут в S3, метаданные — в PostgreSQL. Redis и Valkey — альтернативы: оба одновременно не нужны. Аналогично выбирается одно S3-хранилище, один брокер и один основной путь оркестрации. + +## Воспроизводимость и честные измерения + +- Укажите версии runtime и контейнерных образов, аппаратную конфигурацию, CPU/RAM-лимиты, команду запуска и время прогрева. Для образов используйте явный тег версии или digest, не `latest`. +- Все тестовые пользователи и изображения синтетические. `make test` создаёт данные: запускайте его на учебном стенде. Не публикуйте пароли, токены, приватные ключи, персональные данные или подписанные URL. +- Минимальный отчёт о нагрузке: длительность, конкуренция/интенсивность, успешные RPS, доля ошибок, p50/p95/p99, CPU/RAM, размер набора данных. Универсального проходного RPS для разных ноутбуков нет. +- Сравнивайте одинаковые запросы при одинаковых ресурсах. Успешный `/health/live` не доказывает сохранность сообщений, а HTTP `202` — окончание обработки. +- Один Docker-host не обеспечивает отказоустойчивость к потере этого host. Несколько API-процессов не делают единственную БД или LB высокодоступными. Отдельно называйте, какие отказы выдерживает эксперимент. + +## Что сдавать + +Исходники, Dockerfile, нужные манифесты и конфигурации, миграции, собственные тесты, заполненный `REPORT.md`, сведения об использовании внешнего кода и ИИ. Уметь объяснить и изменить своё решение на защите обязательно. Приложите команды и текстовые результаты; скриншоты — дополнение, а не единственное доказательство. + +PR должен собираться из чистого clone по инструкции автора. Секреты создаются отдельно; тестовые fixtures и открытые конфигурации хранятся в репозитории. Перенос кода между лабами описан в [CONTRIBUTING.md](CONTRIBUTING.md). diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..dc05a08a --- /dev/null +++ b/Dockerfile @@ -0,0 +1,22 @@ +# syntax=docker/dockerfile:1 +FROM python:3.11.9-slim + +ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 PIP_NO_CACHE_DIR=1 PIP_DISABLE_PIP_VERSION_CHECK=1 +WORKDIR /app + +COPY requirements.txt . +RUN pip install -r requirements.txt + +COPY main.py . +COPY app ./app +COPY scripts ./scripts + +RUN useradd --system --uid 10001 --no-create-home --shell /usr/sbin/nologin appuser +USER 10001 + +EXPOSE 8080 + +HEALTHCHECK --interval=5s --timeout=3s --start-period=10s --retries=10 \ + CMD ["python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health/live', timeout=2)"] + +CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8080", "--timeout-graceful-shutdown", "5"] \ No newline at end of file diff --git a/Dockerfile.example b/Dockerfile.example new file mode 100644 index 00000000..e333a12e --- /dev/null +++ b/Dockerfile.example @@ -0,0 +1,8 @@ +# Teaching outline, not a runnable Dockerfile. Implement your own Dockerfile. +# 1. Choose a runtime/toolchain version and pin the base image tag/digest. +# 2. Copy dependency manifests first; install from the language lockfile. +# 3. Copy source and build. For compiled languages use a separate runtime stage. +# 4. Run the HTTP process as PID 1; listen on 0.0.0.0:8080. +# 5. Add non-root, signals and healthcheck according to the current rubric. +# 6. Pass runtime config/secrets at startup, never COPY .env or secret files. +# This file deliberately has no FROM/CMD: selecting/implementing them is the task. diff --git a/MAINTAINERS.md b/MAINTAINERS.md new file mode 100644 index 00000000..bb10fed7 --- /dev/null +++ b/MAINTAINERS.md @@ -0,0 +1,38 @@ +# Памятка преподавателю — лабораторная 4 + +## Что подготовлено + +Язык реализации не задан. README содержит накопительные уровни 3/4/5, сценарий защиты и вопросы. В каждой лабе собственная полная версия OpenAPI, поэтому fork не зависит от соседних каталогов. Публичный HTTP smoke не содержит реализации сервера; Dockerfile.example и compose.example.yaml (если есть) — задания/ориентиры, не готовый deployment. + +## Перед публикацией + +1. Выберите GitHub/GitLab и организацию, опубликуйте каждый каталог как отдельный template/skeleton repository, сообщите студентам URL и правила именования PR/MR. Эти материалы не публикуют репозитории автоматически. +2. Задайте default branch, защиту исходных материалов и правила приёма. `.github/` уже содержит шаблон PR и CI контракта; в GitLab перенесите эквивалентные настройки, локальные Makefile-команды одинаковы. +3. Сообщите, индивидуальная работа или командная, сроки, правила использования стороннего кода/ИИ и ресурсы демонстрационного стенда. Эти организационные решения намеренно не выдуманы в задании. +4. Уточните ограничения площадки (например доступна ли виртуализация/несколько узлов). Для 5 предусмотрено по два трека: один можно выполнить без настоящего multi-node cloud. Универсальный проходной RPS не установлен. + +## Что проверять + +| Проверка | Что подтверждает | Чего не подтверждает | +| --- | --- | --- | +| make check | Структура файлов, JSON, локальные refs, синтаксис Python | Реализация/запуск API | +| make validate | Полная OpenAPI 3.1, JSON Schema и примеры | Поведение сервера | +| make test | Один сквозной контрактный сценарий текущей лабы | Все ошибки, persistence, HA, security | +| test-persistence (lab2+) | Данные/прежний токен после вызова restart hook | Реальный перезапуск, если hook — no-op | +| test-failover (lab3+) | Смена обслуживающей реплики, сохранность, retry без дубля | Несколько физических узлов, HA DB/LB | +| test-security (lab7) | Доверенный HTTPS и отказ недоверенного CA | Внутреннее mTLS/identity/ACL/OpenBao | +| Защита и тесты студента | Реальность инфраструктуры и критерии выбранного уровня | Неограниченная промышленная безопасность | + +Проверяйте реальные контейнеры/логи процессов и данные до/после отказа: одного X-Instance-Id недостаточно. Для 4 требуются все пункты 3+4, для 5 — все пункты 3+4 и один **завершённый** трек 5. Сравнивайте подтверждённые результаты со сформулированными критериями, а не количество установленных сервисов. + +## Приём PR + +Проверка запускается на изолированном учебном окружении с синтетическими secrets, не на общей production БД. Студенческие Dockerfile/hooks/CI — выполняемый код: обычный fork workflow без секретов и без доступа к общему Docker socket. Не запускайте PR через pull_request_target с привилегиями преподавателя. + +Исходные README/контракт/публичные tests сохраняются, реализация переносится студентом между лабами через собственные исходники и миграции. Исправление общей спецификации публикуйте отдельным изменением, объясняя влияние на все затронутые лабораторные. + +## Проверка этой версии skeleton + +На 2026-09-10 выполнены структурные проверки и полная валидация всех семи OpenAPI/JSON Schema, проверка локальных Markdown-ссылок/YAML и декодирование PNG fixture. HTTP-клиенты проверены на временном изолированном тестовом стенде: позитивный smoke 1–7, отрицательные варианты неправильного sender, pagination, ACL, logout, bytes и пустого API; также пути persistence/failover/load и внешнего TLS. + +Временный стенд не включён в студенческие каталоги и не является эталонным решением. Реальное приложение, Compose, PostgreSQL/S3/broker и mTLS/OpenBao в skeleton отсутствуют: их работоспособность не заявляется. Docker CLI в среде подготовки не был доступен. Это проверка материалов и тестовых драйверов, не приёмка будущих решений студентов. diff --git a/Makefile b/Makefile new file mode 100644 index 00000000..5d86d171 --- /dev/null +++ b/Makefile @@ -0,0 +1,30 @@ +PYTHON ?= python3 +BASE_URL ?= http://localhost:8080 +CA_FILE ?= +ACTION_SCRIPT ?= +TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",) + +.PHONY: help check validate test load test-persistence test-failover + +help: + @echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes" + +check: + $(PYTHON) scripts/check_contract.py + +validate: + $(PYTHON) scripts/validate_openapi.py + +test: + $(PYTHON) tests/smoke.py --base-url "$(BASE_URL)" $(TLS_ARGS) + +load: + $(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS) + +test-persistence: + @test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2) + $(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS) + +test-failover: + @test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable stop-one hook"; exit 2) + $(PYTHON) tests/resilience.py --mode failover --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS) diff --git a/README.md b/README.md new file mode 100644 index 00000000..947094c3 --- /dev/null +++ b/README.md @@ -0,0 +1,105 @@ +# Лабораторная 4. S3-хранилище и вложения + +Разделить метаданные и бинарное содержимое, добавить изображения в сообщения и сохранить доступ к ним при переключении API-реплики. + +Это **skeleton**, а не готовый сервер. Здесь есть задание, контракт и публичные проверки. Реализацию приложения, Dockerfile и требуемую инфраструктуру пишет студент. Язык и framework свободные; UI не обязателен. + +[Карта курса](COURSE.md) · [Процесс fork/PR](CONTRIBUTING.md) · [OpenAPI](contracts/openapi.json) · [Семантика API](contracts/README.md) · [Проверки](tests/README.md) · [Отчёт](REPORT.md) · [Примеры JSON](contracts/examples.json) · [Памятка преподавателю](MAINTAINERS.md) + +## Откуда начинаем + +Перенесите минимум lab3. Дополняются поля сообщения и endpoint вложений; прежние текстовые POST остаются валидными. + +**Архитектура:** Клиент → LB → API × 2+ → PostgreSQL (метаданные) + приватное S3-хранилище (байты). + +## Что сделать + +1. Выберите один S3-совместимый сервер: MinIO, SeaweedFS или RustFS. Закрепите проверенную версию образа и опишите создание приватного bucket. +2. Спроектируйте Attachment и связь с чатом/сообщением. S3 object key назначает сервер, filename используется только для отображения. +3. Реализуйте синхронный binary upload PNG/JPEG с ограничениями, сохранение метаданных и авторизованный download через API. +4. Включите S3 и persistent volumes в общий Compose/Swarm. Проверьте, что другая API-реплика скачивает файл после остановки загрузившей. +5. Проверьте недоступность S3, чужой чат и restart всего стенда. + +## Оценка «3»: работающий минимум + +- Все обязательные возможности lab3 сохранены. S3-сервер находится в общем стенде; метаданные вложений живут в PostgreSQL, байты — в приватном bucket, не в БД или локальном каталоге API. +- POST вложения возвращает 201 ready после сохранения; оригинал скачивается побайтно. Message с attachment_ids читается участниками чата. Публичный smoke проверяет checksum и отсутствие доступа у постороннего. +- Принимаются реальные PNG/JPEG ≤10 MiB и ≤40 млн пикселей; MIME проверяется по содержимому, опасные filename отклоняются, лимиты применяются до неограниченного чтения/декодирования. +- Upload → остановка обслужившей API-реплики → download через другую возвращает тот же файл. Restart с сохранением volumes сохраняет метаданные и оригинал. + +## Оценка «4»: уровень стажёра/джуна + +Весь уровень 3 **и все** пункты ниже: + +- Тесты покрывают слишком большой файл, повреждённое изображение, подмену MIME, чужое attachment_id и привязку файла другого чата. Пользовательская ошибка не превращается в 500. +- Прерывание загрузки и отказ между записью S3/БД не оставляют вечных неучтённых объектов: есть документированный механизм компенсации/сверки/очистки с безопасным grace period. +- Лимиты/таймауты и потоковая обработка не позволяют одной загрузке занять неограниченную RAM. Проведён эксперимент ≥10 одновременных загрузок с измерением пика памяти. +- Bucket bootstrap идемпотентен; API использует отдельные S3 credentials с ограниченными правами. Административная консоль не открыта в общей сети. Есть проверка private bucket вне API. + +## Оценка «5»: исследование и доказанный результат + +Весь уровень 4 **и один законченный трек на выбор**. Приведите гипотезу, повторяемую методику, результаты и ограничения. + +**Трек 1. Прямой upload.** Добавьте отдельный безопасный presigned-upload flow: короткая подпись, уникальный ключ, проверка принадлежности, размера/checksum при complete, обработка незавершённой загрузки. Сохраните обязательный proxy endpoint. Сравните трафик и RAM API при ≥2 размерах файлов, покажите негативные сценарии. + +**Трек 2. Согласованность двух хранилищ.** Разработайте повторяемый reconciler для orphan/missing объектов и метаданных. Внедрите ошибки на обеих сторонах, покажите обнаружение и безопасное исправление с dry-run/повторным запуском. Докажите, что свежие и используемые вложения не удаляются; измерьте стоимость обхода. + +## Как начать и проверить + +```sh +# Работает прямо в skeleton, Python 3.9+; приложение не запускается: +make check + +# После реализации запустите свой сервер/стенд по REPORT.md. +# По умолчанию тест использует http://localhost:8080. +make test +``` + +`.env.example`, `compose.example.yaml` и `contracts/infrastructure.json` описывают настройки и роли компонентов. **compose.example.yaml — список ролей с пустым services, не запускаемый стенд.** Реализуйте свой `compose.yaml`/`stack.yaml`, закрепите версии образов, заполните локальный `.env` и опишите bootstrap/миграции. Все зависимости поднимаются из этого репозитория; ссылка «у меня БД уже установлена» не заменяет воспроизводимость. + +```sh +# Compose-вариант после реализации: +docker compose --env-file .env config --quiet +docker compose --env-file .env up -d --build +# Дождитесь /health/ready; затем make test. +# Для Swarm укажите эквивалентные build/push/deploy-команды в REPORT.md. +``` + + +Примеры запросов доступны в `examples/requests.http`, примеры JSON — в `contracts/examples.json`. Для полной проверки схемы (по желанию локально; CI делает её автоматически): + +```sh +python3 -m venv .venv +.venv/bin/python -m pip install -r requirements-dev.txt +make validate PYTHON=.venv/bin/python +``` + +Smoke не выставляет оценку автоматически. Проверку сохранности/отказов запускайте явно по [tests/README.md](tests/README.md), остальные доказательства приведите в отчёте. + +## Сценарий защиты + +1. Загрузить fixture, отправить message с attachment_ids, скачать как второй участник и сравнить SHA-256. +2. С третьим пользователем получить 404 для метаданных и bytes; direct unauthenticated S3 GET не отдаёт объект. +3. Выполнить persistence и failover: общий тест начиная с lab4 сохраняет и повторно читает оригинал через API. +4. Показать, что на API нет обязательного локального файла оригинала. Для 4/5 — отказы и эксперименты. + +## Что должно быть в PR + +Дополненный стенд, настройка bucket/политики, миграции Attachment, тесты файлов, описание согласованности БД/S3 и результаты. + +Заполните `REPORT.md` и [шаблон PR](.github/pull_request_template.md), укажите целевую оценку/трек. Не меняйте обязательный контракт и публичные tests ради зелёного результата. Сохраняйте возможности предыдущих лабораторных в пределах [объявленных переходов](COURSE.md). + +## Вопросы на защите + +- Почему файл в Docker volume одной API-реплики не равен объектному хранилищу? +- Когда можно честно вернуть 201? +- Что произойдёт, если S3 PUT прошёл, а COMMIT в PostgreSQL — нет? +- Почему случайный object key и приватный bucket не заменяют ACL приложения? + +## Первичные материалы + +- [S3 object uploads](https://docs.aws.amazon.com/AmazonS3/latest/userguide/upload-objects.html) +- [Presigned URLs](https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-presigned-url.html) +- [MinIO](https://github.com/minio/minio) +- [SeaweedFS](https://github.com/seaweedfs/seaweedfs) +- [RustFS](https://docs.rustfs.com/) diff --git a/REPORT.md b/REPORT.md new file mode 100644 index 00000000..2f5376ee --- /dev/null +++ b/REPORT.md @@ -0,0 +1,41 @@ +# Отчёт — лабораторная 4 + +- Автор, группа: Никифорова Екатерина, БВТ2301 +- Целевая оценка: **4** (уровни 3 и 4, трек 5 не заявлен) +- Commit/PR: https://gitea.privcloud.tech/eqktrin/mtusi2026lab4/pulls (PR после публикации) +- Источники, библиотеки, помощь ИИ: FastAPI 0.115, Uvicorn 0.30, + PostgreSQL 17.6, Valkey 8.1.3, Silo (`pgsty/silo` — поддерживаемый форк + MinIO: официальные образы MinIO удалены с Docker Hub и Quay в 2025), + Nginx 1.27, psycopg 3.2, boto3 1.43.107, Pillow 12.3.0, Argon2id. + Помощь ИИ при написании кода и отчёта. + +## Запуск из чистого clone + +**Требования:** Docker Engine ≥ 24 с Compose v2, Python ≥ 3.9, +PowerShell (Windows) или sh (Linux/macOS), `PYTHONUTF8=1` для корректной +работы публичных тестов на Windows. + +```powershell +git clone https://gitea.privcloud.tech/eqktrin/mtusi2026lab4.git +cd mtusi2026lab4 + +# 1. Секреты. На Windows — PowerShell-скрипт ниже; на Linux/macOS — sh scripts/init-secrets.sh +# (PowerShell-вариант создаёт secrets/* и .env через System.Security.Cryptography) +$bytes = New-Object byte[] 16 +[System.Security.Cryptography.RandomNumberGenerator]::Create().GetBytes($bytes) +$pgPass = -join ($bytes | ForEach-Object { $_.ToString("x2") }) +# ... и т.д. — см. README или скрипт init-secrets.sh +docker compose --env-file .env config --quiet + +# 2. Сборка и запуск +docker compose --env-file .env up -d --build + +# 3. Дождаться готовности +Invoke-RestMethod http://localhost:8080/health/ready + +# 4. Тесты +$env:PYTHONUTF8 = "1" +python tests/smoke.py --base-url http://localhost:8080 +python student-tests/test_attachments_negative.py --base-url http://localhost:8080 +python tests/resilience.py --mode persistence --action-script scripts/restart.cmd --base-url http://localhost:8080 +python tests/resilience.py --mode failover --action-script scripts/stop-one.cmd --base-url http://localhost:8080 \ No newline at end of file diff --git a/app/__init__.py b/app/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/app/attachments.py b/app/attachments.py new file mode 100644 index 00000000..6d977c5c --- /dev/null +++ b/app/attachments.py @@ -0,0 +1,121 @@ +"""Логика вложений: проверка изображений, загрузка в S3, компенсация.""" +import logging +import uuid + +from PIL import Image, UnidentifiedImageError + +from . import config, db, repo, s3 +from .errors import ApiError, bad_request, not_found + +log = logging.getLogger("attachments") + +ALLOWED_FORMATS = {"PNG": "image/png", "JPEG": "image/jpeg"} + +# PIL отказывается читать изображение с числом пикселей больше лимита, +# ещё до полной распаковки — это защита от decompression bomb. +Image.MAX_IMAGE_PIXELS = config.MAX_IMAGE_PIXELS + + +def validate_filename(filename): + """Отображаемое имя; ключ S3 формирует сервер.""" + if not isinstance(filename, str) or not (1 <= len(filename) <= 255): + raise bad_request("Некорректное имя файла") + if any(c in filename for c in ("/", "\\", "\x00")) or any(ord(c) < 0x20 for c in filename): + raise bad_request("Недопустимое имя файла") + return filename + + +def _inspect_image(fileobj): + """Формат и размеры из заголовка, затем целостность через verify(). + + verify() не декодирует пиксели, только проверяет CRC/структуру. + """ + try: + with Image.open(fileobj) as img: + fmt = img.format + width, height = img.size + img.verify() + except UnidentifiedImageError: + raise ApiError(415, "unsupported_media_type", "Неизвестный формат изображения") + except Image.DecompressionBombError: + raise ApiError(413, "payload_too_large", "Слишком много пикселей") + except Exception: + raise ApiError(415, "unsupported_media_type", "Повреждённое изображение") + + if fmt not in ALLOWED_FORMATS: + raise ApiError(415, "unsupported_media_type", "Ожидается PNG или JPEG") + if width <= 0 or height <= 0: + raise ApiError(415, "unsupported_media_type", "Повреждённое изображение") + if width * height > config.MAX_IMAGE_PIXELS: + raise ApiError(413, "payload_too_large", "Слишком много пикселей") + return ALLOWED_FORMATS[fmt] + + +def inspect_image_file(fileobj, total_bytes): + """Проверяет уже прочитанное тело. Возвращает фактический content_type. + + fileobj должен быть seekable; после вызова позиция = 0. + """ + if total_bytes == 0: + raise bad_request("Пустой файл") + if total_bytes > config.MAX_UPLOAD_BYTES: + raise ApiError(413, "payload_too_large", "Файл больше 10 MiB") + fileobj.seek(0) + content_type = _inspect_image(fileobj) + fileobj.seek(0) + return content_type + + +def upload_stream(chat_id, owner_id, filename, fileobj, total_bytes, digest, content_type): + """pending в БД → S3 PUT → ready. fileobj уже провалидирован и на позиции 0.""" + validate_filename(filename) + object_key = "originals/%s/%s" % (chat_id, uuid.uuid4().hex) + + with db.connection() as conn: + if not repo.is_member(conn, chat_id, owner_id): + raise not_found() + row = repo.insert_attachment_pending( + conn, chat_id, owner_id, filename, content_type, total_bytes, digest, object_key + ) + attachment_id = row["id"] + + try: + fileobj.seek(0) + s3.put_object(object_key, fileobj, content_type, content_length=total_bytes) + except Exception as exc: + log.warning("S3 PUT failed for %s: %s", attachment_id, type(exc).__name__) + # Компенсация: удаляем возможный частичный объект. + s3.delete_object(object_key) + with db.connection() as conn: + repo.mark_attachment_failed(conn, attachment_id, "storage_unavailable") + raise ApiError(503, "unavailable", "Хранилище временно недоступно") + + try: + with db.connection() as conn: + ready = repo.mark_attachment_ready(conn, attachment_id) + except Exception: + # Объект уже в S3, но COMMIT в БД не прошёл → orphan-pending. + # scripts/reconcile_s3.py найдёт и удалит после grace period. + log.error("S3 object %s left orphaned after DB failure", object_key) + raise + if ready is None: + raise ApiError(409, "conflict", "Вложение уже в обработке") + return repo.attachment_json(ready) + + +def download(attachment_id, user_id): + """Возвращает (metadata_row, s3_body) или 404/409/503.""" + with db.connection() as conn: + row = repo.get_attachment_for_member(conn, attachment_id, user_id) + if row is None: + raise not_found() + if row["status"] == "failed": + raise ApiError(409, "conflict", "Вложение недоступно") + if row["status"] != "ready": + raise ApiError(409, "conflict", "Вложение ещё не готово") + try: + body = s3.get_object(row["object_key"]) + except Exception as exc: + log.warning("S3 GET failed for %s: %s", attachment_id, type(exc).__name__) + raise ApiError(503, "unavailable", "Хранилище временно недоступно") + return row, body \ No newline at end of file diff --git a/app/cache.py b/app/cache.py new file mode 100644 index 00000000..eff9b5f9 --- /dev/null +++ b/app/cache.py @@ -0,0 +1,52 @@ +"""Тонкая обёртка над Redis/Valkey.""" +import logging +import threading +import time + +import redis + +from . import config + +log = logging.getLogger("cache") +_client = None +_down_until = 0.0 +_lock = threading.Lock() + + +def _get_client(): + global _client + if not config.CACHE_URL: + return None + if _client is None: + with _lock: + if _client is None: + _client = redis.Redis.from_url( + config.CACHE_URL, socket_timeout=config.CACHE_TIMEOUT, + socket_connect_timeout=config.CACHE_TIMEOUT, max_connections=20, + decode_responses=True, retry_on_timeout=False) + return _client + + +def _call(fn): + global _down_until + client = _get_client() + if client is None or time.monotonic() < _down_until: + return None + try: + return fn(client) + except redis.RedisError as exc: + _down_until = time.monotonic() + config.CACHE_BACKOFF + log.warning("cache unavailable (%s); bypassing for %.0fs", type(exc).__name__, config.CACHE_BACKOFF) + return None + + +def get(key): + return _call(lambda c: c.get(key)) + + +def set_if_absent(key, value, ttl_ms): + return _call(lambda c: c.set(key, value, nx=True, px=ttl_ms)) + + +def set_always(key, value, ttl_ms): + return _call(lambda c: c.set(key, value, px=ttl_ms)) \ No newline at end of file diff --git a/app/config.py b/app/config.py new file mode 100644 index 00000000..7c0cdabc --- /dev/null +++ b/app/config.py @@ -0,0 +1,69 @@ +"""Конфигурация из переменных окружения. Секреты читаются из файлов (*_FILE), а не из env.""" +import os +import socket +from pathlib import Path + + +def _read(name): + """NAME_FILE (путь к секрету) имеет приоритет над NAME (прямое значение для локальной отладки).""" + path = os.environ.get(name + "_FILE") + if path: + return Path(path).read_text(encoding="utf-8").strip() + return os.environ.get(name) or None + + +def _int(name, default, low, high): + value = int(os.environ.get(name, default)) + if not low <= value <= high: + raise ValueError("%s must be in %d..%d" % (name, low, high)) + return value + + +APP_HOST = os.environ.get("APP_HOST", "0.0.0.0") +APP_PORT = _int("APP_PORT", 8080, 1, 65535) +APP_ENV = os.environ.get("APP_ENV", "lab") + +SESSION_TTL_SECONDS = _int("SESSION_TTL_SECONDS", 3600, 1, 30 * 24 * 3600) +SESSION_STORE = os.environ.get("SESSION_STORE", "postgres+cache") +SESSION_CACHE_TTL_SECONDS = _int("SESSION_CACHE_TTL_SECONDS", 60, 1, 3600) + +DATABASE_URL = _read("DATABASE_URL") +CACHE_URL = _read("CACHE_URL") if SESSION_STORE == "postgres+cache" else None + +DB_POOL_MIN = _int("DB_POOL_MIN", 1, 0, 50) +DB_POOL_MAX = _int("DB_POOL_MAX", 16, 1, 50) +DB_POOL_TIMEOUT = float(os.environ.get("DB_POOL_TIMEOUT", "3")) +DB_STATEMENT_TIMEOUT_MS = _int("DB_STATEMENT_TIMEOUT_MS", 5000, 100, 60000) +CACHE_TIMEOUT = float(os.environ.get("CACHE_TIMEOUT", "0.25")) +CACHE_BACKOFF = float(os.environ.get("CACHE_BACKOFF", "2")) + +ARGON2_MEMORY_KIB = _int("ARGON2_MEMORY_KIB", 19456, 8, 1048576) +ARGON2_TIME_COST = _int("ARGON2_TIME_COST", 2, 1, 10) +MAX_BODY_BYTES = 64 * 1024 +THREAD_LIMIT = _int("THREAD_LIMIT", 24, 1, 200) +HASH_CONCURRENCY = _int("HASH_CONCURRENCY", 4, 1, 32) + +# --- lab3 --- +INSTANCE_ID = os.environ.get("INSTANCE_ID") or socket.gethostname() +IDEMPOTENCY_TTL_SECONDS = _int("IDEMPOTENCY_TTL_SECONDS", 86400, 60, 86400 * 7) + +# --- lab4: S3 --- +S3_ENDPOINT = os.environ.get("S3_ENDPOINT", "http://s3:9000") +S3_REGION = os.environ.get("S3_REGION", "us-east-1") +S3_BUCKET = os.environ.get("S3_BUCKET", "messenger-attachments") +S3_ACCESS_KEY_ID = _read("S3_ACCESS_KEY_ID") +S3_SECRET_ACCESS_KEY = _read("S3_SECRET_ACCESS_KEY") +S3_CONNECT_TIMEOUT = float(os.environ.get("S3_CONNECT_TIMEOUT", "3")) +S3_READ_TIMEOUT = float(os.environ.get("S3_READ_TIMEOUT", "30")) + +# --- lab4: лимиты загрузки --- +# 10 MiB = 10 485 760 байт, как в контракте +MAX_UPLOAD_BYTES = _int("MAX_UPLOAD_BYTES", 10485760, 1, 10485760) +# 40 млн пикселей +MAX_IMAGE_PIXELS = _int("MAX_IMAGE_PIXELS", 40000000, 1, 40000000) +# Сколько ждать между S3 PUT и записью метаданных, прежде чем считать объект orphan (компенсация) +S3_ORPHAN_GRACE_SECONDS = _int("S3_ORPHAN_GRACE_SECONDS", 3600, 60, 7 * 24 * 3600) +# Размер чанка при потоковой загрузке в S3 +UPLOAD_CHUNK_BYTES = _int("UPLOAD_CHUNK_BYTES", 256 * 1024, 4096, 4 * 1024 * 1024) +# Сколько ждать чтения тела запроса (защита от slowloris на upload) +UPLOAD_READ_TIMEOUT_SECONDS = float(os.environ.get("UPLOAD_READ_TIMEOUT", "30")) \ No newline at end of file diff --git a/app/cursor.py b/app/cursor.py new file mode 100644 index 00000000..9fa0f163 --- /dev/null +++ b/app/cursor.py @@ -0,0 +1,27 @@ +"""Непрозрачный keyset-курсор (created_at, id).""" +import base64 +import json +import uuid +from datetime import datetime, timezone + +from .errors import bad_request + + +def encode(kind, scope, created_at, row_id): + payload = {"k": kind, "s": str(scope), "t": created_at.astimezone(timezone.utc).isoformat(), "i": str(row_id)} + return base64.urlsafe_b64encode(json.dumps(payload, separators=(",", ":")).encode()).rstrip(b"=").decode() + + +def decode(value, kind, scope): + if not value: + raise bad_request("Некорректный cursor") + try: + raw = base64.urlsafe_b64decode(value + "=" * (-len(value) % 4)) + payload = json.loads(raw.decode("utf-8")) + created_at = datetime.fromisoformat(payload["t"]) + row_id = uuid.UUID(payload["i"]) + if payload["k"] != kind or payload["s"] != str(scope) or created_at.tzinfo is None: + raise ValueError("scope mismatch") + return created_at, row_id + except (ValueError, KeyError, TypeError, UnicodeDecodeError): + raise bad_request("Некорректный cursor") \ No newline at end of file diff --git a/app/db.py b/app/db.py new file mode 100644 index 00000000..b3349cd8 --- /dev/null +++ b/app/db.py @@ -0,0 +1,53 @@ +"""Пул соединений PostgreSQL.""" +import threading + +import psycopg +from psycopg.rows import dict_row +from psycopg_pool import ConnectionPool, PoolClosed, PoolTimeout + +from . import config + +TRANSIENT = (psycopg.OperationalError, PoolTimeout, PoolClosed, psycopg.errors.QueryCanceled, + psycopg.errors.LockNotAvailable) + +_pool = None +_lock = threading.Lock() + + +def get_pool(): + global _pool + if _pool is None: + with _lock: + if _pool is None: + if not config.DATABASE_URL: + raise RuntimeError("DATABASE_URL(_FILE) is not configured") + options = ("-c statement_timeout=%d -c lock_timeout=3000 " + "-c idle_in_transaction_session_timeout=10000" % config.DB_STATEMENT_TIMEOUT_MS) + pool = ConnectionPool( + config.DATABASE_URL, + min_size=config.DB_POOL_MIN, max_size=config.DB_POOL_MAX, + timeout=config.DB_POOL_TIMEOUT, max_lifetime=1800, max_idle=300, + reconnect_timeout=5, + check=ConnectionPool.check_connection, + kwargs={"row_factory": dict_row, "connect_timeout": 3, "options": options, + "application_name": "messenger-api"}, + open=False) + pool.open(wait=False) + _pool = pool + return _pool + + +def connection(timeout=None): + return get_pool().connection(timeout=timeout) + + +def ping(): + with connection(timeout=1.5) as conn: + conn.execute("SELECT 1") + + +def close(): + global _pool + if _pool is not None: + _pool.close(timeout=5) + _pool = None \ No newline at end of file diff --git a/app/errors.py b/app/errors.py new file mode 100644 index 00000000..29f95263 --- /dev/null +++ b/app/errors.py @@ -0,0 +1,20 @@ +class ApiError(Exception): + def __init__(self, status, code, message, headers=None): + super().__init__(message) + self.status, self.code, self.message, self.headers = status, code, message, headers or {} + + +BASIC_CHALLENGE = {"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'} +BEARER_CHALLENGE = {"WWW-Authenticate": 'Bearer realm="messenger"'} + + +def bad_request(message="Некорректный запрос"): + return ApiError(400, "invalid_request", message) + + +def unauthorized(challenge): + return ApiError(401, "unauthorized", "Требуется аутентификация", challenge) + + +def not_found(): + return ApiError(404, "not_found", "Объект не найден") \ No newline at end of file diff --git a/app/idempotency.py b/app/idempotency.py new file mode 100644 index 00000000..d1d233c5 --- /dev/null +++ b/app/idempotency.py @@ -0,0 +1,67 @@ +"""Логика идемпотентности для POST запросов.""" +import hashlib +import json +from .errors import ApiError, bad_request + + +def get_request_hash(data: dict) -> str: + """Хеш тела запроса, независимый от порядка ключей.""" + return hashlib.sha256(json.dumps(data, sort_keys=True).encode("utf-8")).hexdigest() + + +def check_and_lock(conn, user_id: str, method: str, path: str, key: str, req_hash: str): + """ + Блокирует ключ идемпотентности через advisory lock в PostgreSQL. + """ + if not key: + raise bad_request("Missing Idempotency-Key") + if not isinstance(key, str) or not (1 <= len(key) <= 128): + raise bad_request("Invalid Idempotency-Key format") + + # Берем блокировку на уровне БД по хешу ключа. + lock_id = f"{user_id}:{method}:{path}:{key}" + conn.execute("SELECT pg_advisory_xact_lock(hashtext(%s))", (lock_id,)) + + # Проверяем, есть ли уже такой ключ + row = conn.execute(""" + SELECT request_hash, status_code, response_body + FROM idempotency_keys + WHERE user_id = %s AND method = %s AND path = %s AND key = %s + """, (user_id, method, path, key)).fetchone() + + if row: + # Ключ уже существует + if row["request_hash"] != req_hash: + raise ApiError(409, "conflict", "Idempotency-Key conflict: body differs") + + # Если запрос уже был успешно обработан, возвращаем сохраненный ответ + if row["status_code"] is not None and row["response_body"] is not None: + return False, json.loads(row["response_body"]) + + # Если status_code пустой, значит первая транзакция упала. Разрешаем перезапись. + return True, None + + return True, None + + +def save_result(conn, user_id: str, method: str, path: str, key: str, req_hash: str, status_code: int, response_body: dict): + """Сохраняет результат выполнения запроса для будущих повторных вызовов.""" + conn.execute(""" + INSERT INTO idempotency_keys (user_id, method, path, key, request_hash, status_code, response_body) + VALUES (%s, %s, %s, %s, %s, %s, %s) + ON CONFLICT (user_id, method, path, key) DO UPDATE + SET status_code = EXCLUDED.status_code, response_body = EXCLUDED.response_body + """, (user_id, method, path, key, req_hash, status_code, json.dumps(response_body))) + + +def cleanup(conn, ttl_seconds: int): + """Оппортунистическая очистка старых ключей (через подзапрос, т.к. DELETE LIMIT в PG нет).""" + conn.execute(""" + DELETE FROM idempotency_keys + WHERE (user_id, method, path, key) IN ( + SELECT user_id, method, path, key + FROM idempotency_keys + WHERE created_at < now() - make_interval(secs => %s) + LIMIT 100 + ) + """, (ttl_seconds,)) \ No newline at end of file diff --git a/app/migrate.py b/app/migrate.py new file mode 100644 index 00000000..18e35751 --- /dev/null +++ b/app/migrate.py @@ -0,0 +1,61 @@ +"""Версионируемые миграции.""" +import hashlib +import logging +import sys +import time +from pathlib import Path + +import psycopg + +from . import config + +LOCK_ID = 727_002_001 +log = logging.getLogger("migrate") + + +def migration_files(): + return sorted((Path(__file__).parent / "migrations").glob("[0-9][0-9][0-9][0-9]_*.sql")) + + +def apply_all(conninfo): + files = migration_files() + with psycopg.connect(conninfo, connect_timeout=3) as conn: + conn.execute("SELECT pg_advisory_xact_lock(%s)", (LOCK_ID,)) + conn.execute("""CREATE TABLE IF NOT EXISTS schema_migrations ( + version text PRIMARY KEY, + checksum text NOT NULL, + applied_at timestamptz NOT NULL DEFAULT now())""") + applied = dict(conn.execute("SELECT version, checksum FROM schema_migrations").fetchall()) + done = [] + for path in files: + sql = path.read_text(encoding="utf-8") + checksum = hashlib.sha256(sql.encode()).hexdigest() + if path.stem in applied: + if applied[path.stem] != checksum: + raise RuntimeError("migration %s was modified after being applied" % path.stem) + continue + conn.execute(sql) + conn.execute("INSERT INTO schema_migrations (version, checksum) VALUES (%s, %s)", (path.stem, checksum)) + done.append(path.stem) + return done + + +def main(): + logging.basicConfig(level=logging.INFO, format="%(asctime)s %(name)s %(message)s") + if not config.DATABASE_URL: + sys.exit("DATABASE_URL(_FILE) is not configured") + deadline = time.monotonic() + 60 + while True: + try: + done = apply_all(config.DATABASE_URL) + break + except psycopg.OperationalError as exc: + if time.monotonic() > deadline: + raise + log.info("database not ready (%s), retrying", type(exc).__name__) + time.sleep(1) + log.info("applied: %s", ", ".join(done) if done else "nothing to do (schema is up to date)") + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/app/migrations/0001_core.sql b/app/migrations/0001_core.sql new file mode 100644 index 00000000..10147f3f --- /dev/null +++ b/app/migrations/0001_core.sql @@ -0,0 +1,39 @@ +CREATE TABLE users ( + id uuid PRIMARY KEY, + username text NOT NULL, + display_name text NOT NULL, + password_hash text NOT NULL, + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + CONSTRAINT users_username_key UNIQUE (username), + CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9_]{3,32}$'), + CONSTRAINT users_display_name_length CHECK (char_length(display_name) BETWEEN 1 AND 100) +); + +CREATE TABLE chats ( + id uuid PRIMARY KEY, + title text NOT NULL, + created_by uuid NOT NULL REFERENCES users (id), + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + CONSTRAINT chats_title_length CHECK (char_length(title) BETWEEN 1 AND 100) +); +CREATE INDEX chats_created_at_id_idx ON chats (created_at, id); + +CREATE TABLE chat_members ( + chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE, + user_id uuid NOT NULL REFERENCES users (id), + added_at timestamptz NOT NULL DEFAULT clock_timestamp(), + PRIMARY KEY (chat_id, user_id) +); +CREATE INDEX chat_members_user_chat_idx ON chat_members (user_id, chat_id); + +CREATE TABLE messages ( + id uuid PRIMARY KEY, + chat_id uuid NOT NULL, + sender_id uuid NOT NULL, + text text NOT NULL, + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + CONSTRAINT messages_text_length CHECK (char_length(text) BETWEEN 1 AND 4000), + CONSTRAINT messages_sender_is_member FOREIGN KEY (chat_id, sender_id) + REFERENCES chat_members (chat_id, user_id) +); +CREATE INDEX messages_chat_created_id_idx ON messages (chat_id, created_at, id); \ No newline at end of file diff --git a/app/migrations/0002_sessions.sql b/app/migrations/0002_sessions.sql new file mode 100644 index 00000000..d34c43d1 --- /dev/null +++ b/app/migrations/0002_sessions.sql @@ -0,0 +1,10 @@ +CREATE TABLE sessions ( + token_hash bytea PRIMARY KEY, + user_id uuid NOT NULL REFERENCES users (id), + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + expires_at timestamptz NOT NULL, + CONSTRAINT sessions_hash_length CHECK (octet_length(token_hash) = 32), + CONSTRAINT sessions_expiry_after_creation CHECK (expires_at > created_at) +); +CREATE INDEX sessions_expires_at_idx ON sessions (expires_at); +CREATE INDEX sessions_user_idx ON sessions (user_id); \ No newline at end of file diff --git a/app/migrations/0003_idempotency.sql b/app/migrations/0003_idempotency.sql new file mode 100644 index 00000000..33b24334 --- /dev/null +++ b/app/migrations/0003_idempotency.sql @@ -0,0 +1,13 @@ +CREATE TABLE idempotency_keys ( + user_id uuid NOT NULL REFERENCES users(id), + method text NOT NULL, + path text NOT NULL, + key text NOT NULL, + request_hash text NOT NULL, + status_code int, + response_body text, + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + PRIMARY KEY (user_id, method, path, key) +); + +CREATE INDEX idempotency_keys_created_at_idx ON idempotency_keys (created_at); \ No newline at end of file diff --git a/app/migrations/0004_attachments.sql b/app/migrations/0004_attachments.sql new file mode 100644 index 00000000..cf74bc5f --- /dev/null +++ b/app/migrations/0004_attachments.sql @@ -0,0 +1,36 @@ +CREATE TABLE attachments ( + id uuid PRIMARY KEY, + chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE, + owner_id uuid NOT NULL REFERENCES users (id), + filename text NOT NULL, + content_type text NOT NULL, + size_bytes bigint NOT NULL, + sha256 char(64) NOT NULL, + object_key text NOT NULL, + status text NOT NULL, + error_code text, + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + updated_at timestamptz NOT NULL DEFAULT clock_timestamp(), + CONSTRAINT attachments_filename_length CHECK (char_length(filename) BETWEEN 1 AND 255), + CONSTRAINT attachments_content_type CHECK (content_type IN ('image/png', 'image/jpeg')), + CONSTRAINT attachments_size_positive CHECK (size_bytes > 0 AND size_bytes <= 10485760), + CONSTRAINT attachments_sha256_format CHECK (sha256 ~ '^[a-f0-9]{64}$'), + CONSTRAINT attachments_object_key_unique UNIQUE (object_key), + CONSTRAINT attachments_status CHECK (status IN ('pending', 'ready', 'failed')), + CONSTRAINT attachments_error_code CHECK ( + (status = 'ready' AND error_code IS NULL) OR + (status = 'failed' AND error_code IS NOT NULL) OR + (status = 'pending') + ) +); +CREATE INDEX attachments_chat_created_idx ON attachments (chat_id, created_at); +CREATE INDEX attachments_pending_idx ON attachments (created_at) WHERE status = 'pending'; + +CREATE TABLE message_attachments ( + message_id uuid NOT NULL REFERENCES messages (id) ON DELETE CASCADE, + attachment_id uuid NOT NULL REFERENCES attachments (id) ON DELETE RESTRICT, + position int NOT NULL, + PRIMARY KEY (message_id, attachment_id), + CONSTRAINT message_attachments_position CHECK (position >= 0) +); +CREATE INDEX message_attachments_attachment_idx ON message_attachments (attachment_id); \ No newline at end of file diff --git a/app/migrations/0005_messages_text_allow_empty.sql b/app/migrations/0005_messages_text_allow_empty.sql new file mode 100644 index 00000000..96316025 --- /dev/null +++ b/app/migrations/0005_messages_text_allow_empty.sql @@ -0,0 +1,5 @@ +-- lab4: разрешаем пустой text, если есть вложения. Проверка «text или вложения» +-- делается в приложении, а БД гарантирует только верхнюю границу. +ALTER TABLE messages DROP CONSTRAINT messages_text_length; +ALTER TABLE messages ADD CONSTRAINT messages_text_length + CHECK (char_length(text) BETWEEN 0 AND 4000); \ No newline at end of file diff --git a/app/repo.py b/app/repo.py new file mode 100644 index 00000000..626e34f2 --- /dev/null +++ b/app/repo.py @@ -0,0 +1,191 @@ +"""Доступ к данным.""" +import uuid + +from . import cursor, security +from .errors import bad_request +from .sessions import fmt_ts + + +def username_exists(conn, username): + return conn.execute("SELECT 1 FROM users WHERE username = %s", (username,)).fetchone() is not None + + +def insert_user(conn, username, display_name, password_hash): + return conn.execute( + """INSERT INTO users (id, username, display_name, password_hash) VALUES (%s, %s, %s, %s) + RETURNING id, username, display_name, created_at""", + (uuid.uuid4(), username, display_name, password_hash)).fetchone() + + +def user_for_login(conn, username): + return conn.execute("SELECT id, username, display_name, password_hash, created_at FROM users WHERE username = %s", + (username,)).fetchone() + + +def update_password_hash(conn, user_id, new_hash): + conn.execute("UPDATE users SET password_hash = %s WHERE id = %s", (new_hash, user_id)) + + +def chat_json(row): + return {"id": str(row["id"]), "title": row["title"], "member_ids": [str(x) for x in row["member_ids"]], + "created_at": fmt_ts(row["created_at"])} + + +def create_chat(conn, creator_id, title, member_ids, check_members=True): + if check_members: + found = conn.execute("SELECT count(*) AS n FROM users WHERE id = ANY(%s)", (member_ids,)).fetchone()["n"] + if found != len(member_ids): + raise bad_request("Неизвестный участник чата") + chat = conn.execute( + "INSERT INTO chats (id, title, created_by) VALUES (%s, %s, %s) RETURNING id, title, created_at", + (uuid.uuid4(), title, creator_id)).fetchone() + conn.execute("INSERT INTO chat_members (chat_id, user_id) SELECT %s, unnest(%s::uuid[])", + (chat["id"], member_ids)) + chat["member_ids"] = sorted(member_ids) + return chat + + +def get_chat(conn, chat_id, user_id): + return conn.execute( + """SELECT c.id, c.title, c.created_at, + ARRAY(SELECT m.user_id FROM chat_members m WHERE m.chat_id = c.id ORDER BY m.user_id) AS member_ids + FROM chats c + WHERE c.id = %s AND EXISTS (SELECT 1 FROM chat_members me WHERE me.chat_id = c.id AND me.user_id = %s)""", + (chat_id, user_id)).fetchone() + + +def is_member(conn, chat_id, user_id): + return conn.execute("SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s", + (chat_id, user_id)).fetchone() is not None + + +def list_chats(conn, user_id, after, limit): + base = """SELECT c.id, c.title, c.created_at, + ARRAY(SELECT m.user_id FROM chat_members m WHERE m.chat_id = c.id ORDER BY m.user_id) AS member_ids + FROM chat_members me JOIN chats c ON c.id = me.chat_id + WHERE me.user_id = %s""" + params = [user_id] + if after: + base += " AND (c.created_at, c.id) > (%s, %s)" + params += list(after) + rows = conn.execute(base + " ORDER BY c.created_at, c.id LIMIT %s", params + [limit + 1]).fetchall() + page, more = rows[:limit], len(rows) > limit + nxt = cursor.encode("chats", user_id, page[-1]["created_at"], page[-1]["id"]) if more else None + return [chat_json(r) for r in page], nxt + + +# ---------- Сообщения ---------- + +def _message_json(row): + return {"id": str(row["id"]), "chat_id": str(row["chat_id"]), "sender_id": str(row["sender_id"]), + "text": row["text"], "created_at": fmt_ts(row["created_at"]), + "attachment_ids": [str(x) for x in (row.get("attachment_ids") or [])]} + + +def message_json(row): + return _message_json(row) + + +def insert_message(conn, chat_id, sender_id, text, attachment_ids=None): + """Создаёт сообщение и связывает вложения в одной транзакции.""" + attachment_ids = attachment_ids or [] + if attachment_ids: + # Все вложения должны принадлежать этому чату и быть ready. + rows = conn.execute( + """SELECT id, status FROM attachments + WHERE id = ANY(%s) AND chat_id = %s""", + (attachment_ids, chat_id)).fetchall() + by_id = {r["id"]: r for r in rows} + if len(by_id) != len(attachment_ids): + raise bad_request("Неизвестное вложение") + for att_id in attachment_ids: + if by_id[att_id]["status"] == "failed": + raise bad_request("Нельзя прикрепить failed-вложение") + if by_id[att_id]["status"] != "ready": + raise bad_request("Вложение ещё не готово") + + row = conn.execute( + """INSERT INTO messages (id, chat_id, sender_id, text) VALUES (%s, %s, %s, %s) + RETURNING id, chat_id, sender_id, text, created_at""", + (uuid.uuid4(), chat_id, sender_id, text)).fetchone() + if attachment_ids: + conn.execute( + """INSERT INTO message_attachments (message_id, attachment_id, position) + SELECT %s, unnest(%s::uuid[]), generate_subscripts(%s::uuid[], 1) - 1""", + (row["id"], attachment_ids, attachment_ids)) + row["attachment_ids"] = attachment_ids + return row + + +def list_messages(conn, chat_id, after, limit): + sql = """SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at, + ARRAY(SELECT ma.attachment_id FROM message_attachments ma + WHERE ma.message_id = m.id ORDER BY ma.position) AS attachment_ids + FROM messages m WHERE m.chat_id = %s""" + params = [chat_id] + if after: + sql += " AND (m.created_at, m.id) > (%s, %s)" + params += list(after) + rows = conn.execute(sql + " ORDER BY m.created_at, m.id LIMIT %s", params + [limit + 1]).fetchall() + page, more = rows[:limit], len(rows) > limit + nxt = cursor.encode("messages", chat_id, page[-1]["created_at"], page[-1]["id"]) if more else None + return [_message_json(r) for r in page], nxt + + +# ---------- Вложения ---------- + +def insert_attachment_pending(conn, chat_id, owner_id, filename, content_type, + size_bytes, sha256, object_key): + return conn.execute( + """INSERT INTO attachments + (id, chat_id, owner_id, filename, content_type, size_bytes, sha256, object_key, status) + VALUES (%s, %s, %s, %s, %s, %s, %s, %s, 'pending') + RETURNING id, chat_id, owner_id, filename, content_type, size_bytes, sha256, object_key, + status, error_code, created_at, updated_at""", + (uuid.uuid4(), chat_id, owner_id, filename, content_type, size_bytes, sha256, object_key) + ).fetchone() + + +def mark_attachment_ready(conn, attachment_id): + return conn.execute( + """UPDATE attachments + SET status = 'ready', error_code = NULL, updated_at = clock_timestamp() + WHERE id = %s AND status = 'pending' + RETURNING id, chat_id, owner_id, filename, content_type, size_bytes, sha256, object_key, + status, error_code, created_at, updated_at""", + (attachment_id,)).fetchone() + + +def mark_attachment_failed(conn, attachment_id, error_code): + conn.execute( + """UPDATE attachments + SET status = 'failed', error_code = %s, updated_at = clock_timestamp() + WHERE id = %s AND status = 'pending'""", + (error_code, attachment_id)) + + +def get_attachment_for_member(conn, attachment_id, user_id): + return conn.execute( + """SELECT a.id, a.chat_id, a.owner_id, a.filename, a.content_type, a.size_bytes, a.sha256, + a.object_key, a.status, a.error_code, a.created_at, a.updated_at + FROM attachments a + WHERE a.id = %s + AND EXISTS (SELECT 1 FROM chat_members m WHERE m.chat_id = a.chat_id AND m.user_id = %s)""", + (attachment_id, user_id)).fetchone() + + +def attachment_json(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": [], + "error_code": row["error_code"], + "created_at": fmt_ts(row["created_at"]), + "updated_at": fmt_ts(row["updated_at"]), + } \ No newline at end of file diff --git a/app/s3.py b/app/s3.py new file mode 100644 index 00000000..93d36553 --- /dev/null +++ b/app/s3.py @@ -0,0 +1,78 @@ +"""Работа с S3-совместимым хранилищем (Silo/MinIO).""" +import logging +import threading + +import boto3 +from botocore.config import Config +from botocore.exceptions import BotoCoreError, ClientError + +from . import config + +log = logging.getLogger("s3") +_client = None +_lock = threading.Lock() + + +def _get_client(): + global _client + if _client is None: + with _lock: + if _client is None: + _client = boto3.client( + "s3", + endpoint_url=config.S3_ENDPOINT, + aws_access_key_id=config.S3_ACCESS_KEY_ID, + aws_secret_access_key=config.S3_SECRET_ACCESS_KEY, + region_name=config.S3_REGION, + config=Config( + signature_version="s3v4", + s3={"addressing_style": "path"}, + retries={"max_attempts": 3, "mode": "standard"}, + connect_timeout=config.S3_CONNECT_TIMEOUT, + read_timeout=config.S3_READ_TIMEOUT, + ), + ) + return _client + + +def ensure_bucket(): + client = _get_client() + try: + client.head_bucket(Bucket=config.S3_BUCKET) + except ClientError as exc: + if exc.response.get("Error", {}).get("Code") in ("404", "NoSuchBucket"): + client.create_bucket(Bucket=config.S3_BUCKET) + else: + raise + + +def put_object(key: str, body, content_type: str, content_length: int): + """Загружает объект из file-like body, потоково, с явной длиной.""" + client = _get_client() + client.put_object( + Bucket=config.S3_BUCKET, + Key=key, + Body=body, + ContentType=content_type, + ContentLength=content_length, + ) + + +def get_object(key: str): + """Возвращает StreamingBody, а не весь ответ boto3.""" + client = _get_client() + resp = client.get_object(Bucket=config.S3_BUCKET, Key=key) + return resp["Body"] + + +def delete_object(key: str): + client = _get_client() + try: + client.delete_object(Bucket=config.S3_BUCKET, Key=key) + except (ClientError, BotoCoreError): + log.warning("failed to delete object %s", key) + + +def ping(): + client = _get_client() + client.head_bucket(Bucket=config.S3_BUCKET) \ No newline at end of file diff --git a/app/security.py b/app/security.py new file mode 100644 index 00000000..8ceb69c8 --- /dev/null +++ b/app/security.py @@ -0,0 +1,72 @@ +"""Пароли (Argon2id), токены, разбор заголовка Authorization.""" +import base64 +import binascii +import hashlib +import re +import secrets +import threading + +from argon2 import PasswordHasher, Type +from argon2.exceptions import InvalidHashError, VerificationError + +from . import config + +_hasher = PasswordHasher(time_cost=config.ARGON2_TIME_COST, memory_cost=config.ARGON2_MEMORY_KIB, + parallelism=1, hash_len=32, salt_len=16, type=Type.ID) +_DUMMY_HASH = _hasher.hash("dummy-password-for-constant-time") +_hash_slots = threading.BoundedSemaphore(config.HASH_CONCURRENCY) +_TOKEN_RE = re.compile(r"[A-Za-z0-9._~+/=-]{16,512}") + + +def hash_password(password): + with _hash_slots: + return _hasher.hash(password) + + +def verify_password(stored_hash, password): + with _hash_slots: + try: + _hasher.verify(stored_hash, password) + except (VerificationError, InvalidHashError): + return False, None + return True, (_hasher.hash(password) if _hasher.check_needs_rehash(stored_hash) else None) + + +def burn_verify(password): + with _hash_slots: + try: + _hasher.verify(_DUMMY_HASH, password) + except VerificationError: + pass + + +def new_token(): + return secrets.token_urlsafe(32) + + +def token_hash(token): + return hashlib.sha256(token.encode("ascii")).digest() + + +def parse_basic(header): + if not header: + return None + scheme, _, rest = header.partition(" ") + if scheme.lower() != "basic": + return None + try: + text = base64.b64decode(rest.strip(), validate=True).decode("utf-8") + except (binascii.Error, UnicodeDecodeError, ValueError): + return None + username, sep, password = text.partition(":") + return (username, password) if sep else None + + +def parse_bearer(header): + if not header: + return None + scheme, _, rest = header.partition(" ") + token = rest.strip() + if scheme.lower() != "bearer" or not _TOKEN_RE.fullmatch(token): + return None + return token \ No newline at end of file diff --git a/app/sessions.py b/app/sessions.py new file mode 100644 index 00000000..ecb4d011 --- /dev/null +++ b/app/sessions.py @@ -0,0 +1,81 @@ +"""Сессии: PostgreSQL — источник истины, Redis/Valkey — read-through кэш.""" +import json +import time +from datetime import timezone + +from . import cache, config, db, security +from .errors import ApiError + +TOMBSTONE = "revoked" +_KEY = "sess:v1:" + + +def fmt_ts(value): + return value.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ") + + +def user_json(row): + return {"id": str(row["id"]), "username": row["username"], "display_name": row["display_name"], + "created_at": fmt_ts(row["created_at"])} + + +def _ttl_ms(expires_epoch): + remaining = expires_epoch - time.time() + return int(min(config.SESSION_CACHE_TTL_SECONDS, remaining) * 1000) if remaining > 0 else 0 + + +def create(conn, user_row): + token = security.new_token() + row = conn.execute( + """INSERT INTO sessions (token_hash, user_id, expires_at) + VALUES (%s, %s, clock_timestamp() + make_interval(secs => %s)) + RETURNING expires_at""", + (security.token_hash(token), user_row["id"], config.SESSION_TTL_SECONDS)).fetchone() + conn.execute("""DELETE FROM sessions WHERE token_hash IN ( + SELECT token_hash FROM sessions WHERE expires_at < now() - interval '1 hour' LIMIT 100)""") + return token, row["expires_at"] + + +def warm(token, user, expires_at): + entry = {"user": user, "exp": expires_at.timestamp()} + ttl = _ttl_ms(entry["exp"]) + if ttl > 0: + cache.set_if_absent(_KEY + security.token_hash(token).hex(), json.dumps(entry), ttl) + + +def lookup(token): + digest = security.token_hash(token) + key = _KEY + digest.hex() + cached = cache.get(key) + if cached == TOMBSTONE: + return None + if cached: + try: + entry = json.loads(cached) + if entry["exp"] > time.time(): + return {"user": entry["user"], "digest": digest} + return None + except (ValueError, KeyError, TypeError): + pass + with db.connection() as conn: + row = conn.execute( + """SELECT u.id, u.username, u.display_name, u.created_at, + extract(epoch FROM s.expires_at) AS exp + FROM sessions s JOIN users u ON u.id = s.user_id + WHERE s.token_hash = %s AND s.expires_at > clock_timestamp()""", (digest,)).fetchone() + if row is None: + return None + user = user_json(row) + ttl = _ttl_ms(float(row["exp"])) + if ttl > 0: + cache.set_if_absent(key, json.dumps({"user": user, "exp": float(row["exp"])}), ttl) + return {"user": user, "digest": digest} + + +def revoke(digest): + if config.CACHE_URL: + wrote = cache.set_always(_KEY + digest.hex(), TOMBSTONE, config.SESSION_CACHE_TTL_SECONDS * 1000) + if not wrote: + raise ApiError(503, "unavailable", "Сервис временно недоступен") + with db.connection() as conn: + conn.execute("DELETE FROM sessions WHERE token_hash = %s", (digest,)) \ No newline at end of file diff --git a/app/validation.py b/app/validation.py new file mode 100644 index 00000000..4088efee --- /dev/null +++ b/app/validation.py @@ -0,0 +1,83 @@ +"""Строгая валидация входа.""" +import json +import re +import uuid + +from .errors import ApiError, bad_request + +_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}") +_USERNAME_RE = re.compile(r"[a-z0-9_]{3,32}") +_INT_RE = re.compile(r"[0-9]{1,6}") + + +def parse_uuid(value): + if isinstance(value, str) and _UUID_RE.fullmatch(value): + return uuid.UUID(value) + return None + + +def require_uuid(value, name="id"): + parsed = parse_uuid(value) + if parsed is None: + raise bad_request("Некорректный %s" % name) + return parsed + + +def _reject_constant(name): + raise ValueError("non-finite number") + + +def _no_duplicates(pairs): + result = {} + for key, value in pairs: + if key in result: + raise ValueError("duplicate key") + result[key] = value + return result + + +def json_body(content_type, raw, allowed, required): + if content_type.split(";")[0].strip().lower() != "application/json": + raise ApiError(415, "unsupported_media_type", "Ожидается Content-Type: application/json") + try: + data = json.loads(raw.decode("utf-8"), parse_constant=_reject_constant, object_pairs_hook=_no_duplicates) + except (ValueError, UnicodeDecodeError, RecursionError): + raise bad_request("Некорректный JSON") + if not isinstance(data, dict) or set(data) - set(allowed) or not set(required) <= set(data): + raise bad_request("Некорректный набор полей") + return data + + +def text_field(value, name, low, high, allow_blank=False): + if not isinstance(value, str): + raise bad_request("Поле %s должно быть строкой" % name) + if "\x00" in value or not _encodable(value): + raise bad_request("Поле %s содержит недопустимые символы" % name) + if not low <= len(value) <= high: + raise bad_request("Поле %s: длина должна быть %d–%d" % (name, low, high)) + if not allow_blank and not value.strip(): + raise bad_request("Поле %s не должно состоять только из пробелов" % name) + return value + + +def _encodable(value): + try: + value.encode("utf-8") + return True + except UnicodeEncodeError: + return False + + +def username_field(value): + if not isinstance(value, str) or not _USERNAME_RE.fullmatch(value): + raise bad_request("username должен соответствовать [a-z0-9_]{3,32}") + return value + + +def limit_param(params): + raw = params.get("limit") + if raw is None: + return 50 + if not _INT_RE.fullmatch(raw) or not 1 <= int(raw) <= 100: + raise bad_request("limit должен быть целым числом 1–100") + return int(raw) \ No newline at end of file diff --git a/compose.example.yaml b/compose.example.yaml new file mode 100644 index 00000000..76a785ff --- /dev/null +++ b/compose.example.yaml @@ -0,0 +1,12 @@ +# Topology worksheet, deliberately NOT a runnable stack (no application supplied). +# Implement compose.yaml or stack.yaml; do not submit this empty file as deployment. +# Service names below are logical roles, not imposed container names. +x-lab-number: 4 +x-required-roles: + - api + - postgres + - load_balancer + - s3 +# TODO: implement real images/builds, network wiring, volumes, healthchecks, +# credentials and bootstrap. Details: contracts/infrastructure.json and README.md. +services: {} diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 00000000..285a4957 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,191 @@ +name: messenger-lab4 + +x-app-env: &app-env + APP_HOST: "0.0.0.0" + APP_PORT: "8080" + APP_ENV: ${APP_ENV:-lab} + SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} + SESSION_STORE: ${SESSION_STORE:-postgres+cache} + SESSION_CACHE_TTL_SECONDS: ${SESSION_CACHE_TTL_SECONDS:-60} + DATABASE_URL_FILE: /run/secrets/database_url + CACHE_URL_FILE: /run/secrets/cache_url + IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400} + S3_ENDPOINT: http://minio:9000 + S3_REGION: ${S3_REGION:-us-east-1} + S3_BUCKET: ${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: ${MAX_UPLOAD_BYTES:-10485760} + MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000} + S3_ORPHAN_GRACE_SECONDS: ${S3_ORPHAN_GRACE_SECONDS:-3600} + +services: + postgres: + image: postgres:17.6-alpine + restart: unless-stopped + environment: + POSTGRES_DB: messenger + POSTGRES_USER: messenger + POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password + secrets: [postgres_password] + command: ["postgres", "-c", "fsync=on", "-c", "synchronous_commit=on", + "-c", "full_page_writes=on", "-c", "max_connections=100"] + volumes: + - pgdata:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U messenger -d messenger"] + interval: 3s + timeout: 3s + retries: 20 + stop_grace_period: 30s + networks: [backend] + deploy: + resources: + limits: {cpus: '1.0', memory: 1G} + + valkey: + image: valkey/valkey:8.1.3-alpine + restart: unless-stopped + secrets: [valkey_password] + command: + - sh + - -c + - >- + exec valkey-server --requirepass "$$(cat /run/secrets/valkey_password)" + --appendonly yes --appendfsync everysec --save "" + --maxmemory 64mb --maxmemory-policy volatile-ttl + volumes: + - valkeydata:/data + healthcheck: + test: ["CMD-SHELL", "REDISCLI_AUTH=\"$$(cat /run/secrets/valkey_password)\" valkey-cli ping | grep -q PONG"] + interval: 3s + timeout: 3s + retries: 20 + networks: [backend] + deploy: + resources: + limits: {cpus: '0.5', memory: 256M} + + minio: + image: pgsty/silo:latest + restart: unless-stopped + command: ["server", "/data", "--console-address", ":9001"] + environment: + MINIO_ROOT_USER_FILE: /run/secrets/minio_root_user + MINIO_ROOT_PASSWORD_FILE: /run/secrets/minio_root_password + secrets: [minio_root_user, minio_root_password] + volumes: + - miniodata:/data + healthcheck: + test: ["CMD", "silo", "healthcheck", "ready"] + interval: 5s + timeout: 3s + retries: 20 + start_period: 10s + networks: [backend] + deploy: + resources: + limits: {cpus: '0.5', memory: 512M} + + minio-init: + image: pgsty/mc:latest + depends_on: + minio: {condition: service_healthy} + secrets: [minio_root_user, minio_root_password, s3_access_key_id, s3_secret_access_key] + entrypoint: ["/bin/sh", "-c"] + command: + - | + set -eu + ROOT_USER=$$(cat /run/secrets/minio_root_user) + ROOT_PASS=$$(cat /run/secrets/minio_root_password) + APP_KEY=$$(cat /run/secrets/s3_access_key_id) + APP_SECRET=$$(cat /run/secrets/s3_secret_access_key) + mc alias set local http://minio:9000 "$$ROOT_USER" "$$ROOT_PASS" + mc mb --ignore-existing --with-lock=false local/messenger-attachments + mc anonymous set none local/messenger-attachments + mc admin user add local "$$APP_KEY" "$$APP_SECRET" || true + cat >/tmp/app-policy.json <`; отсутствие/неизвестный ID — 401. Это учебный выбор пользователя: любой клиент может выдать себя за другого. + +**Lab2–7:** `POST /auth/sessions` принимает только `Authorization: Basic `, без JSON body. Username ограничен ASCII; пароль кодируется UTF-8, 12–128 code points, двоеточие в пароле допустимо. Неверные credentials — одинаковый 401 и `WWW-Authenticate: Basic realm="messenger", charset="UTF-8"`. + +Вход возвращает `201 {"token":"...","token_type":"Bearer","expires_at":"...Z","user":{...}}`. Токен — непрозрачное случайное значение, не username/UUID и не обязательный JWT; энтропия не менее 256 бит. Храните серверную сессию с expiry; TTL задаётся `SESSION_TTL_SECONDS`, по умолчанию 3600 (в тесте истечения можно 2). В обычном smoke TTL должен быть не менее 300. + +Все защищённые endpoint принимают только `Authorization: Bearer `. Истёкший/отозванный/неизвестный токен — 401 с `WWW-Authenticate: Bearer realm="messenger"`. Basic на бизнес-endpoint — 401. `X-User-Id` с lab2 игнорируется: он не меняет владельца сессии и сам по себе не даёт доступ. `DELETE /auth/sessions/current` отзывает текущий токен и возвращает 204 без тела; повтор с отозванным токеном — 401. + +Пользователи, чаты, сообщения и ещё действительные сессии переживают перезапуск приложения и используемых хранилищ с сохранёнными volumes. TTL не продлевается из-за рестарта. Пароли уже с lab2 хешируются библиотечным password KDF (Argon2id, scrypt или bcrypt с учётом ограничений библиотеки), не SHA-256 и не plaintext. Если bcrypt не поддерживает весь диапазон UTF-8 паролей без усечения, выберите другую библиотечную схему. В lab7 обязателен Argon2id. + +Basic — это кодирование, не шифрование. HTTP lab1–6 допускается только для локального изолированного стенда с синтетическими данными; для удалённой демонстрации нужен TLS. Lab7 использует HTTPS обязательно. См. [RFC 7617](https://www.rfc-editor.org/info/rfc7617/). + +## Балансировка и повторная отправка (с lab3) + +- Каждый ответ, созданный API, содержит `X-Instance-Id`; значение стабильно для жизни процесса. Ошибки соединения, созданные самим LB, могут не иметь этого заголовка. В lab7 используйте случайный alias реплики без раскрытия hostname/IP. +- Для POST сообщения обязателен `Idempotency-Key` (ASCII `[A-Za-z0-9._:-]{1,128}`). Нет/неверный ключ — 400. Область уникальности: текущий пользователь + HTTP-метод + путь чата + ключ. +- При повторе того же валидного JSON в течение 24 часов сервер возвращает тот же код 201 и то же Message. Порядок ключей JSON и отсутствующий `attachment_ids` вместо `[]` семантически равны. Другой body при том же ключе — 409. Разные пользователи/чаты могут использовать одинаковый ключ независимо. +- Одновременные повторы через разные реплики создают ровно одно сообщение. Повтор снова проверяет действительность сессии и доступ. Транзиентные 5xx не фиксируются как окончательный результат; побочный эффект и запись результата должны быть атомарны. +- Ключ обязателен только для сообщений. Самостоятельный retry загрузки файла или создания чата может создать ещё один объект; не добавляйте прозрачные повторы этих POST без расширения контракта. + +## Вложения (с lab4) + +- `POST /chats/{chat_id}/attachments?filename=photo.png`: сырые bytes одного PNG/JPEG; `Content-Type: image/png` или `image/jpeg`. Не multipart. Максимум **10 MiB = 10 485 760 байт**. MIME проверяется по содержимому; заведомо повреждённые/чужие форматы — 415, превышение bytes — 413. Не более 40 миллионов декодированных пикселей (превышение — 413). Устанавливайте лимит до полной распаковки изображения. +- `filename` — отображаемое имя (1–255 code points). Не используйте его как путь/ключ S3. Имя с `/`, `\`, NUL или управляющими символами — 400. Bucket приватен; object key генерирует сервер. Оригинал возвращается побайтно, его lowercase SHA-256 и размер соответствуют исходному файлу. +- Lab4 возвращает `201 Attachment` со `status=ready`, `variants=[]`, `error_code=null` только после сохранения оригинала и метаданных. Lab5–7 возвращают `202 Attachment` со снимком `status=queued`; готовность определяется последующим GET метаданных. Быстрый worker может закончить до первого GET — это нормально. +- Файл заранее привязан к чату. В POST сообщения добавляется `attachment_ids` (0–10 уникальных ID, по умолчанию []). Можно отправить `text=""` с хотя бы одним вложением. Все вложения должны принадлежать этому чату; чужое/неизвестное — 404. Любой участник может ссылаться на доступное вложение чата. Failed-вложение прикреплять нельзя (409); queued/processing с lab5 можно. +- `GET /attachments/{id}` и `/content` доступны только участникам чата. Download возвращает байты с истинным Content-Type, через авторизованный API, **без redirect** в обязательном контракте. Приватный bucket сам по себе не заменяет эту проверку. `variant` по умолчанию original. Для queued/processing content — 409; для failed — 409. Отсутствующий вариант ready-объекта — 404. +- В ready-метаданных `error_code=null`. В failed — краткий машинный код (например `invalid_image`, `processing_failed`, `retry_exhausted`), без stack trace. `size_bytes`, `sha256`, `content_type` всегда описывают оригинал; у вариантов отдельные поля. Публичный API не раскрывает ключи бакета, внутренние адреса и credentials. +- Прямой upload/download по временной подписи — факультативное расширение. Его дополняют ограничение срока/размера, уникальный ключ и подтверждение реально загруженного объекта; он не заменяет стандартный endpoint. Особенности подписанных URL: [S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-presigned-url.html). + +## Фоновая обработка (с lab5) + +До 202 все байты приняты в **устойчивый staging**, а намерение обработать файл надёжно сохранено. HTTP-передача клиента не исчезает и не становится мгновенной. Staging — приватный S3-prefix либо общий persistent volume, доступный worker; локальная память/API ephemeral disk не подходит. Worker асинхронно переносит/публикует оригинал в конечный S3-prefix и создаёт варианты; если staging уже в S3, опишите эту границу честно. + +Обязательный thumbnail: JPEG, изображение вписано в 256×256 с сохранением пропорций, без увеличения маленьких исходников, EXIF orientation применяется; alpha компонуется на белый. Размеры округляются вниз, минимум 1 px. Fixture 320×200 должен дать 256×160. Статус ready ставится после сохранения оригинала и thumbnail. Crop на 4: JPEG, центрированный квадрат 128×128 (для маленьких исходников допускается увеличение). Optimized на 4: WebP, вписан в 1280×1280 без увеличения, параметры качества и удаления EXIF документируются; не обещайте уменьшение каждого маленького файла. + +Допустимые состояния и события описаны в `jobs.schema.json` и `attachment-states.md`. Доставка — at least once; обработка идемпотентна, повторы не размножают варианты. Финальные ошибки наблюдаемы, бесконечный немой retry недопустим. Обязательный smoke ждёт ready до 60 секунд; это бюджет локального smoke для одного файла при свободном worker, не универсальный production SLA. В очередь идут ссылки/ID, не бинарное содержимое. diff --git a/contracts/examples.json b/contracts/examples.json new file mode 100644 index 00000000..060abd0f --- /dev/null +++ b/contracts/examples.json @@ -0,0 +1,60 @@ +{ + "CreateUser": { + "username": "alice", + "display_name": "Алиса", + "password": "Example-only-not-a-real-secret-123" + }, + "User": { + "id": "11111111-1111-4111-8111-111111111111", + "username": "alice", + "display_name": "Алиса", + "created_at": "2026-09-01T12:00:00Z" + }, + "CreateChat": { + "title": "Проект по ВНП", + "member_ids": [ + "11111111-1111-4111-8111-111111111111", + "22222222-2222-4222-8222-222222222222" + ] + }, + "Chat": { + "title": "Проект по ВНП", + "member_ids": [ + "11111111-1111-4111-8111-111111111111", + "22222222-2222-4222-8222-222222222222" + ], + "id": "33333333-3333-4333-8333-333333333333", + "created_at": "2026-09-01T12:00:00Z" + }, + "CreateMessage": { + "text": "Привет, Боб!" + }, + "Message": { + "id": "44444444-4444-4444-8444-444444444444", + "chat_id": "33333333-3333-4333-8333-333333333333", + "sender_id": "11111111-1111-4111-8111-111111111111", + "text": "Привет, Боб!", + "created_at": "2026-09-01T12:00:00Z", + "attachment_ids": [] + }, + "MessagePage": { + "items": [ + { + "id": "44444444-4444-4444-8444-444444444444", + "chat_id": "33333333-3333-4333-8333-333333333333", + "sender_id": "11111111-1111-4111-8111-111111111111", + "text": "Привет, Боб!", + "created_at": "2026-09-01T12:00:00Z", + "attachment_ids": [] + } + ], + "next_cursor": null + }, + "Error": { + "error": { + "code": "not_found", + "message": "Объект не найден", + "request_id": "example-request-id" + } + } +} diff --git a/contracts/infrastructure.json b/contracts/infrastructure.json new file mode 100644 index 00000000..dd2edf2d --- /dev/null +++ b/contracts/infrastructure.json @@ -0,0 +1,46 @@ +{ + "lab": 4, + "kind": "requirements, not runnable deployment", + "required_for_grade_3": [ + { + "role": "api", + "count_min": 2, + "student_implements": true, + "persistent_local_state": false + }, + { + "role": "postgres", + "purpose": "users/chats/membership/messages/metadata", + "persistent_volume": true + }, + { + "role": "load_balancer", + "public_entrypoint": true, + "backend_readiness": true + }, + { + "role": "s3", + "choose_one": [ + "MinIO", + "SeaweedFS", + "RustFS" + ], + "private_bucket": true, + "persistent_volume": true + } + ], + "optional_components": [ + { + "role": "redis_or_valkey", + "required_for_lab2_grade4": true, + "note": "Choose one; if only store of sessions, configure durable persistence." + } + ], + "rules": [ + "Choose Compose or Swarm for lab3+; do not need both.", + "Never publish internal API replica ports in bypass of LB from lab3.", + "Versions/digests must be fixed in implementation.", + "Do not remove volumes in restart/failover checks.", + "Document service names, healthchecks, bootstrap/migrations and credentials." + ] +} diff --git a/contracts/openapi.json b/contracts/openapi.json new file mode 100644 index 00000000..138f07c0 --- /dev/null +++ b/contracts/openapi.json @@ -0,0 +1,3506 @@ +{ + "openapi": "3.1.0", + "info": { + "title": "MTUSI Messenger — лабораторная 4", + "version": "1.4.0", + "description": "Нормативный минимум на 3. Семантика: contracts/README.md. Расширения на 4/5 не должны менять этот API. Наличие кода ошибки в схеме не требует реализовать факультативную причину его выдачи." + }, + "servers": [ + { + "url": "http://localhost:8080", + "description": "Локальный учебный стенд" + } + ], + "security": [ + { + "bearerAuth": [] + } + ], + "paths": { + "/health/live": { + "get": { + "operationId": "liveness", + "summary": "Процесс жив", + "responses": { + "200": { + "description": "Успех", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Health" + } + } + } + }, + "500": { + "description": "Неожиданная ошибка без внутренних деталей", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "security": [] + } + }, + "/health/ready": { + "get": { + "operationId": "readiness", + "summary": "Готов принимать трафик", + "responses": { + "200": { + "description": "Успех", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Health" + } + } + } + }, + "503": { + "description": "Зависимость недоступна", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Неожиданная ошибка без внутренних деталей", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "security": [] + } + }, + "/api/v1/users": { + "post": { + "operationId": "registerUser", + "summary": "Создать пользователя", + "responses": { + "201": { + "description": "Успех", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/User" + } + } + } + }, + "400": { + "description": "Неверный запрос", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Конфликт", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "429": { + "description": "Ограничение частоты запросов", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "Retry-After": { + "description": "Положительное число секунд.", + "schema": { + "type": "integer", + "minimum": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Зависимость недоступна", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Неожиданная ошибка без внутренних деталей", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "security": [], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateUser" + } + } + } + } + } + }, + "/api/v1/users/me": { + "get": { + "operationId": "currentUser", + "summary": "Текущий пользователь", + "responses": { + "200": { + "description": "Успех", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/User" + } + } + } + }, + "400": { + "description": "Неверный запрос", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Нет действительной аутентификации", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "WWW-Authenticate": { + "description": "Basic realm=\"messenger\", charset=\"UTF-8\" для входа; Bearer realm=\"messenger\" для защищённого API lab2+.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Объект отсутствует или недоступен", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Конфликт", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "429": { + "description": "Ограничение частоты запросов", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "Retry-After": { + "description": "Положительное число секунд.", + "schema": { + "type": "integer", + "minimum": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Зависимость недоступна", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Неожиданная ошибка без внутренних деталей", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/api/v1/chats": { + "post": { + "operationId": "createChat", + "summary": "Создать чат; вызывающий должен входить в member_ids", + "responses": { + "201": { + "description": "Успех", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Chat" + } + } + } + }, + "400": { + "description": "Неверный запрос", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Нет действительной аутентификации", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "WWW-Authenticate": { + "description": "Basic realm=\"messenger\", charset=\"UTF-8\" для входа; Bearer realm=\"messenger\" для защищённого API lab2+.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Объект отсутствует или недоступен", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Конфликт", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "429": { + "description": "Ограничение частоты запросов", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "Retry-After": { + "description": "Положительное число секунд.", + "schema": { + "type": "integer", + "minimum": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Зависимость недоступна", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Неожиданная ошибка без внутренних деталей", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateChat" + } + } + } + } + }, + "get": { + "operationId": "listChats", + "summary": "Чаты текущего пользователя", + "responses": { + "200": { + "description": "Успех", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ChatPage" + } + } + } + }, + "400": { + "description": "Неверный запрос", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Нет действительной аутентификации", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "WWW-Authenticate": { + "description": "Basic realm=\"messenger\", charset=\"UTF-8\" для входа; Bearer realm=\"messenger\" для защищённого API lab2+.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Объект отсутствует или недоступен", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Конфликт", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "429": { + "description": "Ограничение частоты запросов", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "Retry-After": { + "description": "Положительное число секунд.", + "schema": { + "type": "integer", + "minimum": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Зависимость недоступна", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Неожиданная ошибка без внутренних деталей", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "parameters": [ + { + "name": "limit", + "in": "query", + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 100, + "default": 50 + } + }, + { + "name": "cursor", + "in": "query", + "schema": { + "type": "string", + "minLength": 1 + } + } + ] + } + }, + "/api/v1/chats/{chat_id}": { + "get": { + "operationId": "getChat", + "summary": "Получить доступный чат", + "responses": { + "200": { + "description": "Успех", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Chat" + } + } + } + }, + "400": { + "description": "Неверный запрос", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Нет действительной аутентификации", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "WWW-Authenticate": { + "description": "Basic realm=\"messenger\", charset=\"UTF-8\" для входа; Bearer realm=\"messenger\" для защищённого API lab2+.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Объект отсутствует или недоступен", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Конфликт", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "429": { + "description": "Ограничение частоты запросов", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "Retry-After": { + "description": "Положительное число секунд.", + "schema": { + "type": "integer", + "minimum": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Зависимость недоступна", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Неожиданная ошибка без внутренних деталей", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "parameters": [ + { + "name": "chat_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ] + } + }, + "/api/v1/chats/{chat_id}/messages": { + "post": { + "operationId": "createMessage", + "summary": "Отправить сообщение", + "responses": { + "201": { + "description": "Успех", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Message" + } + } + } + }, + "400": { + "description": "Неверный запрос", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Нет действительной аутентификации", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "WWW-Authenticate": { + "description": "Basic realm=\"messenger\", charset=\"UTF-8\" для входа; Bearer realm=\"messenger\" для защищённого API lab2+.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Объект отсутствует или недоступен", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Конфликт", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "429": { + "description": "Ограничение частоты запросов", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "Retry-After": { + "description": "Положительное число секунд.", + "schema": { + "type": "integer", + "minimum": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Зависимость недоступна", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Неожиданная ошибка без внутренних деталей", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "parameters": [ + { + "name": "chat_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + }, + { + "name": "Idempotency-Key", + "in": "header", + "required": true, + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 128, + "pattern": "^[A-Za-z0-9._:-]+$" + }, + "description": "Обязателен с lab3. Область: пользователь + метод + путь + ключ; хранить результат не менее 24 ч. Повтор того же JSON возвращает исходный 201 и то же сообщение, другой JSON — 409." + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateMessage" + } + } + } + } + }, + "get": { + "operationId": "listMessages", + "summary": "Сообщения по (created_at, id) по возрастанию", + "responses": { + "200": { + "description": "Успех", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/MessagePage" + } + } + } + }, + "400": { + "description": "Неверный запрос", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Нет действительной аутентификации", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "WWW-Authenticate": { + "description": "Basic realm=\"messenger\", charset=\"UTF-8\" для входа; Bearer realm=\"messenger\" для защищённого API lab2+.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Объект отсутствует или недоступен", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Конфликт", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "429": { + "description": "Ограничение частоты запросов", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "Retry-After": { + "description": "Положительное число секунд.", + "schema": { + "type": "integer", + "minimum": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Зависимость недоступна", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Неожиданная ошибка без внутренних деталей", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "parameters": [ + { + "name": "chat_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + }, + { + "name": "limit", + "in": "query", + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 100, + "default": 50 + } + }, + { + "name": "cursor", + "in": "query", + "schema": { + "type": "string", + "minLength": 1 + } + } + ] + } + }, + "/api/v1/auth/sessions": { + "post": { + "operationId": "createSession", + "summary": "Вход: Basic username:password; выдаёт сессию", + "responses": { + "201": { + "description": "Успех", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Session" + } + } + } + }, + "400": { + "description": "Неверный запрос", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Нет действительной аутентификации", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "WWW-Authenticate": { + "description": "Basic realm=\"messenger\", charset=\"UTF-8\" для входа; Bearer realm=\"messenger\" для защищённого API lab2+.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "429": { + "description": "Ограничение частоты запросов", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "Retry-After": { + "description": "Положительное число секунд.", + "schema": { + "type": "integer", + "minimum": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Зависимость недоступна", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Неожиданная ошибка без внутренних деталей", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "security": [ + { + "basicAuth": [] + } + ] + } + }, + "/api/v1/auth/sessions/current": { + "delete": { + "operationId": "revokeSession", + "summary": "Отозвать текущую сессию", + "responses": { + "204": { + "description": "Успех", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + } + }, + "401": { + "description": "Нет действительной аутентификации", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "WWW-Authenticate": { + "description": "Basic realm=\"messenger\", charset=\"UTF-8\" для входа; Bearer realm=\"messenger\" для защищённого API lab2+.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "429": { + "description": "Ограничение частоты запросов", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "Retry-After": { + "description": "Положительное число секунд.", + "schema": { + "type": "integer", + "minimum": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Зависимость недоступна", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Неожиданная ошибка без внутренних деталей", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/api/v1/chats/{chat_id}/attachments": { + "post": { + "operationId": "uploadAttachment", + "summary": "Принять один PNG/JPEG, до 10 MiB", + "responses": { + "201": { + "description": "Успех", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Attachment" + } + } + } + }, + "400": { + "description": "Неверный запрос", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Нет действительной аутентификации", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "WWW-Authenticate": { + "description": "Basic realm=\"messenger\", charset=\"UTF-8\" для входа; Bearer realm=\"messenger\" для защищённого API lab2+.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Объект отсутствует или недоступен", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Превышен лимит", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "415": { + "description": "Неподдерживаемый тип", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "429": { + "description": "Ограничение частоты запросов", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "Retry-After": { + "description": "Положительное число секунд.", + "schema": { + "type": "integer", + "minimum": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Зависимость недоступна", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Неожиданная ошибка без внутренних деталей", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "parameters": [ + { + "name": "chat_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + }, + { + "name": "filename", + "in": "query", + "required": true, + "schema": { + "type": "string", + "minLength": 1, + "maxLength": 255 + } + } + ], + "requestBody": { + "required": true, + "description": "Сырые байты изображения, НЕ multipart и НЕ JSON/base64.", + "content": { + "image/png": { + "schema": { + "type": "string", + "format": "binary" + } + }, + "image/jpeg": { + "schema": { + "type": "string", + "format": "binary" + } + } + } + } + } + }, + "/api/v1/attachments/{attachment_id}": { + "get": { + "operationId": "getAttachment", + "summary": "Метаданные вложения, доступ участникам чата", + "responses": { + "200": { + "description": "Успех", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Attachment" + } + } + } + }, + "400": { + "description": "Неверный запрос", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Нет действительной аутентификации", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "WWW-Authenticate": { + "description": "Basic realm=\"messenger\", charset=\"UTF-8\" для входа; Bearer realm=\"messenger\" для защищённого API lab2+.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Объект отсутствует или недоступен", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Конфликт", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "429": { + "description": "Ограничение частоты запросов", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "Retry-After": { + "description": "Положительное число секунд.", + "schema": { + "type": "integer", + "minimum": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Зависимость недоступна", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Неожиданная ошибка без внутренних деталей", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "parameters": [ + { + "name": "attachment_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ] + } + }, + "/api/v1/attachments/{attachment_id}/content": { + "get": { + "operationId": "downloadAttachment", + "summary": "Скачать байты через авторизованный API", + "responses": { + "200": { + "description": "Успех", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "image/png": { + "schema": { + "type": "string", + "format": "binary" + } + }, + "image/jpeg": { + "schema": { + "type": "string", + "format": "binary" + } + }, + "image/webp": { + "schema": { + "type": "string", + "format": "binary" + } + } + } + }, + "400": { + "description": "Неверный запрос", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Нет действительной аутентификации", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "WWW-Authenticate": { + "description": "Basic realm=\"messenger\", charset=\"UTF-8\" для входа; Bearer realm=\"messenger\" для защищённого API lab2+.", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Объект отсутствует или недоступен", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Конфликт", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "429": { + "description": "Ограничение частоты запросов", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "Retry-After": { + "description": "Положительное число секунд.", + "schema": { + "type": "integer", + "minimum": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "503": { + "description": "Зависимость недоступна", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Неожиданная ошибка без внутренних деталей", + "headers": { + "X-Request-Id": { + "description": "Непустой идентификатор запроса; обязателен во всех ответах.", + "schema": { + "type": "string", + "minLength": 1 + } + }, + "X-Instance-Id": { + "description": "Идентификатор обслужившей API-реплики; стабилен в пределах жизни процесса. В lab7 используйте непрозрачный alias, без hostname/IP.", + "schema": { + "type": "string", + "minLength": 1 + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + }, + "parameters": [ + { + "name": "attachment_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + }, + { + "name": "variant", + "in": "query", + "schema": { + "type": "string", + "enum": [ + "original" + ], + "default": "original" + } + } + ] + } + } + }, + "components": { + "securitySchemes": { + "basicAuth": { + "type": "http", + "scheme": "basic" + }, + "bearerAuth": { + "type": "http", + "scheme": "bearer", + "bearerFormat": "opaque session token" + } + }, + "schemas": { + "Error": { + "type": "object", + "properties": { + "error": { + "type": "object", + "properties": { + "code": { + "type": "string", + "enum": [ + "invalid_request", + "unauthorized", + "not_found", + "conflict", + "payload_too_large", + "unsupported_media_type", + "rate_limited", + "unavailable", + "internal_error" + ] + }, + "message": { + "type": "string", + "minLength": 1 + }, + "request_id": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "code", + "message", + "request_id" + ], + "additionalProperties": false + } + }, + "required": [ + "error" + ], + "additionalProperties": false, + "examples": [ + { + "error": { + "code": "not_found", + "message": "Объект не найден", + "request_id": "example-request-id" + } + } + ] + }, + "Health": { + "type": "object", + "properties": { + "status": { + "type": "string", + "enum": [ + "ok" + ] + } + }, + "required": [ + "status" + ], + "additionalProperties": false + }, + "User": { + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "username": { + "type": "string", + "pattern": "^[a-z0-9_]{3,32}$" + }, + "display_name": { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "created_at": { + "type": "string", + "format": "date-time" + } + }, + "required": [ + "id", + "username", + "display_name", + "created_at" + ], + "additionalProperties": false, + "examples": [ + { + "id": "11111111-1111-4111-8111-111111111111", + "username": "alice", + "display_name": "Алиса", + "created_at": "2026-09-01T12:00:00Z" + } + ] + }, + "CreateUser": { + "type": "object", + "properties": { + "username": { + "type": "string", + "pattern": "^[a-z0-9_]{3,32}$" + }, + "display_name": { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "password": { + "type": "string", + "minLength": 12, + "maxLength": 128, + "writeOnly": true + } + }, + "required": [ + "username", + "display_name", + "password" + ], + "additionalProperties": false, + "examples": [ + { + "username": "alice", + "display_name": "Алиса", + "password": "Example-only-not-a-real-secret-123" + } + ] + }, + "Chat": { + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "title": { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "member_ids": { + "type": "array", + "items": { + "type": "string", + "format": "uuid" + }, + "minItems": 1, + "maxItems": 100, + "uniqueItems": true + }, + "created_at": { + "type": "string", + "format": "date-time" + } + }, + "required": [ + "id", + "title", + "member_ids", + "created_at" + ], + "additionalProperties": false, + "examples": [ + { + "title": "Проект по ВНП", + "member_ids": [ + "11111111-1111-4111-8111-111111111111", + "22222222-2222-4222-8222-222222222222" + ], + "id": "33333333-3333-4333-8333-333333333333", + "created_at": "2026-09-01T12:00:00Z" + } + ] + }, + "CreateChat": { + "type": "object", + "properties": { + "title": { + "type": "string", + "minLength": 1, + "maxLength": 100 + }, + "member_ids": { + "type": "array", + "items": { + "type": "string", + "format": "uuid" + }, + "minItems": 1, + "maxItems": 100, + "uniqueItems": true + } + }, + "required": [ + "title", + "member_ids" + ], + "additionalProperties": false, + "examples": [ + { + "title": "Проект по ВНП", + "member_ids": [ + "11111111-1111-4111-8111-111111111111", + "22222222-2222-4222-8222-222222222222" + ] + } + ] + }, + "Message": { + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "chat_id": { + "type": "string", + "format": "uuid" + }, + "sender_id": { + "type": "string", + "format": "uuid" + }, + "text": { + "type": "string", + "maxLength": 4000 + }, + "created_at": { + "type": "string", + "format": "date-time" + }, + "attachment_ids": { + "type": "array", + "items": { + "type": "string", + "format": "uuid" + }, + "maxItems": 10, + "uniqueItems": true + } + }, + "required": [ + "id", + "chat_id", + "sender_id", + "text", + "created_at", + "attachment_ids" + ], + "additionalProperties": false, + "anyOf": [ + { + "properties": { + "text": { + "minLength": 1 + } + } + }, + { + "properties": { + "attachment_ids": { + "minItems": 1 + } + } + } + ], + "examples": [ + { + "id": "44444444-4444-4444-8444-444444444444", + "chat_id": "33333333-3333-4333-8333-333333333333", + "sender_id": "11111111-1111-4111-8111-111111111111", + "text": "Привет, Боб!", + "created_at": "2026-09-01T12:00:00Z", + "attachment_ids": [] + } + ] + }, + "CreateMessage": { + "type": "object", + "properties": { + "text": { + "type": "string", + "maxLength": 4000 + }, + "attachment_ids": { + "type": "array", + "items": { + "type": "string", + "format": "uuid" + }, + "maxItems": 10, + "uniqueItems": true, + "default": [] + } + }, + "required": [ + "text" + ], + "additionalProperties": false, + "anyOf": [ + { + "properties": { + "text": { + "minLength": 1 + } + } + }, + { + "properties": { + "attachment_ids": { + "minItems": 1 + } + }, + "required": [ + "attachment_ids" + ] + } + ], + "examples": [ + { + "text": "Привет, Боб!" + } + ] + }, + "ChatPage": { + "type": "object", + "properties": { + "items": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Chat" + } + }, + "next_cursor": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "items", + "next_cursor" + ], + "additionalProperties": false + }, + "MessagePage": { + "type": "object", + "properties": { + "items": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Message" + } + }, + "next_cursor": { + "type": [ + "string", + "null" + ] + } + }, + "required": [ + "items", + "next_cursor" + ], + "additionalProperties": false, + "examples": [ + { + "items": [ + { + "id": "44444444-4444-4444-8444-444444444444", + "chat_id": "33333333-3333-4333-8333-333333333333", + "sender_id": "11111111-1111-4111-8111-111111111111", + "text": "Привет, Боб!", + "created_at": "2026-09-01T12:00:00Z", + "attachment_ids": [] + } + ], + "next_cursor": null + } + ] + }, + "Session": { + "type": "object", + "properties": { + "token": { + "type": "string", + "minLength": 32 + }, + "token_type": { + "type": "string", + "const": "Bearer" + }, + "expires_at": { + "type": "string", + "format": "date-time" + }, + "user": { + "$ref": "#/components/schemas/User" + } + }, + "required": [ + "token", + "token_type", + "expires_at", + "user" + ], + "additionalProperties": false + }, + "Variant": { + "type": "object", + "properties": { + "name": { + "type": "string", + "enum": [ + "thumbnail", + "crop", + "optimized" + ] + }, + "content_type": { + "type": "string", + "enum": [ + "image/jpeg", + "image/png", + "image/webp" + ] + }, + "size_bytes": { + "type": "integer", + "minimum": 1 + }, + "width": { + "type": "integer", + "minimum": 1 + }, + "height": { + "type": "integer", + "minimum": 1 + }, + "sha256": { + "type": "string", + "pattern": "^[a-f0-9]{64}$" + } + }, + "required": [ + "name", + "content_type", + "size_bytes", + "width", + "height", + "sha256" + ], + "additionalProperties": false + }, + "Attachment": { + "type": "object", + "properties": { + "id": { + "type": "string", + "format": "uuid" + }, + "chat_id": { + "type": "string", + "format": "uuid" + }, + "owner_id": { + "type": "string", + "format": "uuid" + }, + "filename": { + "type": "string", + "minLength": 1, + "maxLength": 255 + }, + "content_type": { + "type": "string", + "enum": [ + "image/png", + "image/jpeg" + ] + }, + "size_bytes": { + "type": "integer", + "minimum": 1, + "maximum": 10485760 + }, + "sha256": { + "type": "string", + "pattern": "^[a-f0-9]{64}$" + }, + "status": { + "type": "string", + "enum": [ + "ready" + ] + }, + "variants": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Variant" + } + }, + "error_code": { + "type": [ + "string", + "null" + ] + }, + "created_at": { + "type": "string", + "format": "date-time" + }, + "updated_at": { + "type": "string", + "format": "date-time" + } + }, + "required": [ + "id", + "chat_id", + "owner_id", + "filename", + "content_type", + "size_bytes", + "sha256", + "status", + "variants", + "error_code", + "created_at", + "updated_at" + ], + "additionalProperties": false + } + } + } +} diff --git a/evidence/README.md b/evidence/README.md new file mode 100644 index 00000000..8df70015 --- /dev/null +++ b/evidence/README.md @@ -0,0 +1,5 @@ +# Доказательства + +Храните небольшие обезличенные результаты: команды и stdout проверок, JSON/CSV агрегатов нагрузки, EXPLAIN, dashboard JSON, текст разбора отказа. Укажите дату, commit, аппаратные лимиты и профиль нагрузки. + +Не добавляйте .env, session tokens, cookies, приватные ключи, credentials, реальные сообщения, raw dumps и signed URLs. Для скриншотов скрывайте секреты. Большие логи/бинарные traces сохраняйте отдельно по правилам преподавателя; одного скриншота без методики недостаточно. diff --git a/evidence/load-uploads.py b/evidence/load-uploads.py new file mode 100644 index 00000000..cab3feba --- /dev/null +++ b/evidence/load-uploads.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python3 +"""10+ одновременных upload для замера пика памяти.""" +import argparse +import io +import sys +import time +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tests")) + +from PIL import Image # noqa: E402 + +from client import Client, Failure, arguments, check, run # noqa: E402 + + +def make_png(size_mib: float) -> bytes: + buf = io.BytesIO() + Image.new("RGB", (64, 64), (128, 128, 128)).save(buf, "PNG") + data = buf.getvalue() + target = int(size_mib * 1024 * 1024) + check(len(data) <= target, "fixture bigger than target") + return data + b"\x00" * (target - len(data)) + + +def main(): + def configure(p): + p.add_argument("--concurrency", type=int, default=10) + p.add_argument("--size-mib", type=float, default=9.5) + + args = arguments("Concurrent upload memory probe", configure) + check(1 <= args.concurrency <= 64, "concurrency 1..64") + check(0.1 <= args.size_mib <= 10, "size 0.1..10 MiB") + + c = Client(args.base_url, args.ca_file, timeout=60) + alice, bob, eve, chat = c.bootstrap() + blob = make_png(args.size_mib) + + def upload(i): + local = Client(args.base_url, args.ca_file, timeout=60) + t = time.monotonic() + att = local.call( + "POST", + "/api/v1/chats/%s/attachments?filename=load-%d.png" % (chat["id"], i), + 201, actor=alice, raw=blob, + headers={"Content-Type": "image/png"}, schema="Attachment", + )["json"] + return time.monotonic() - t, att["size_bytes"] + + started = time.monotonic() + with ThreadPoolExecutor(max_workers=args.concurrency) as pool: + results = list(pool.map(upload, range(args.concurrency))) + elapsed = time.monotonic() - started + lat = sorted(r[0] for r in results) + print("concurrency=%d size=%.2fMiB total=%.2fs p50=%.2fs p95=%.2fs" + % (args.concurrency, args.size_mib, elapsed, + lat[len(lat) // 2], lat[max(0, int(len(lat) * 0.95) - 1)])) + + +if __name__ == "__main__": + run(main) \ No newline at end of file diff --git a/evidence/mem-baseline.txt b/evidence/mem-baseline.txt new file mode 100644 index 00000000..d5efd340 Binary files /dev/null and b/evidence/mem-baseline.txt differ diff --git a/evidence/memory-peak.txt b/evidence/memory-peak.txt new file mode 100644 index 00000000..203473e1 Binary files /dev/null and b/evidence/memory-peak.txt differ diff --git a/examples/requests.http b/examples/requests.http new file mode 100644 index 00000000..052497b1 --- /dev/null +++ b/examples/requests.http @@ -0,0 +1,53 @@ +# Optional HTTP-client worksheet; no extension is required by the course. +# Replace IDs/token locally from real responses; do not commit filled-in credentials. +# Canonical API: contracts/openapi.json and contracts/README.md. +@baseUrl = http://localhost:8080 +@aliceId = REPLACE_WITH_CREATED_ALICE_UUID +@bobId = REPLACE_WITH_CREATED_BOB_UUID +@chatId = REPLACE_WITH_CREATED_CHAT_UUID +@sessionToken = REPLACE_LOCALLY_DO_NOT_COMMIT + +### Liveness +GET {{baseUrl}}/health/live + +### Register Alice (repeat with username bob/display_name Боб) +POST {{baseUrl}}/api/v1/users +Content-Type: application/json + +{ + "username": "alice", + "display_name": "Алиса", + "password": "Example-only-not-a-real-secret-123" +} + +### Create session: generate the Base64 value locally, do not commit credentials +# Base64 of UTF-8 username:password; only this endpoint accepts Basic. +POST {{baseUrl}}/api/v1/auth/sessions +Authorization: Basic REPLACE_WITH_LOCAL_BASE64_CREDENTIAL + + +### Create chat; both UUIDs must be real registered users +POST {{baseUrl}}/api/v1/chats +Authorization: Bearer {{sessionToken}} +Content-Type: application/json + +{"title":"Проект по ВНП","member_ids":["{{aliceId}}","{{bobId}}"]} + +### Send message +POST {{baseUrl}}/api/v1/chats/{{chatId}}/messages +Authorization: Bearer {{sessionToken}} +Idempotency-Key: example-message-001 +Content-Type: application/json + +{"text":"Привет, Боб!"} + +### Read first page +GET {{baseUrl}}/api/v1/chats/{{chatId}}/messages?limit=50 +Authorization: Bearer {{sessionToken}} + +### Binary upload; HTTP file-client syntax for reading local fixture +POST {{baseUrl}}/api/v1/chats/{{chatId}}/attachments?filename=sample.png +Authorization: Bearer {{sessionToken}} +Content-Type: image/png + +< ../tests/fixtures/sample.png diff --git a/infra/README.md b/infra/README.md new file mode 100644 index 00000000..5a39e862 --- /dev/null +++ b/infra/README.md @@ -0,0 +1,7 @@ +# Инфраструктура студента + +Здесь разместите конфигурации выбранных сервисов; основную топологию — в корневом compose.yaml/stack.yaml. `compose.example.yaml` — только worksheet ролей и намеренно не запускается. `contracts/infrastructure.json` задаёт минимальные роли, не готовые образы/пароли. + +В REPORT.md сопоставьте роль → service name → версия/digest → health/readiness → volume → сеть/порт → способ передачи credentials. Приведите bootstrap (schema, bucket, broker topology, а с lab6 provisioning) и безопасное повторение этих команд. + +Приложение строится из исходников. Не используйте заранее существующий образ преподавательского сервера вместо своей реализации. Restart hook перезапускает все соответствующие stores с volumes; failover hook останавливает только заданную API-реплику. diff --git a/lab.json b/lab.json new file mode 100644 index 00000000..e9ffc9f7 --- /dev/null +++ b/lab.json @@ -0,0 +1,8 @@ +{ + "number": 4, + "title": "S3-хранилище и вложения", + "contract_version": "1.4.0", + "default_base_url": "http://localhost:8080", + "grading": "3; 4 includes 3; 5 includes 4 plus one completed research track", + "scaffold_has_application": false +} diff --git a/main.py b/main.py new file mode 100644 index 00000000..34c3ef38 --- /dev/null +++ b/main.py @@ -0,0 +1,364 @@ +"""Мессенджер, лабораторная 4: lab3 + S3-вложения.""" +import hashlib +import logging +import re +import tempfile +import uuid +from contextlib import asynccontextmanager +from typing import NamedTuple +from urllib.parse import quote + +import anyio.to_thread +import psycopg +from fastapi import Depends, FastAPI, Request +from fastapi.exceptions import RequestValidationError +from fastapi.responses import JSONResponse, Response +from starlette.exceptions import HTTPException as StarletteHTTPException + +from app import (attachments, config, cursor, db, idempotency, repo, + security, sessions, s3, validation) +from app.errors import (BASIC_CHALLENGE, BEARER_CHALLENGE, ApiError, + bad_request, not_found, unauthorized) + +logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s") +log = logging.getLogger("api") + +_REQUEST_ID_RE = re.compile(r"[A-Za-z0-9._-]{1,64}") +INSTANCE_ID = config.INSTANCE_ID + + +@asynccontextmanager +async def lifespan(_app): + anyio.to_thread.current_default_thread_limiter().total_tokens = config.THREAD_LIMIT + yield + db.close() + + +app = FastAPI(lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None) + + +def make_error(code, message, request_id): + return {"error": {"code": code, "message": message, "request_id": request_id}} + + +def _rid(request): + return getattr(request.state, "request_id", None) or uuid.uuid4().hex + + +def error_response(request, status, code, message, headers=None): + rid = _rid(request) + out = {"X-Request-Id": rid, "Cache-Control": "no-store"} + out.update(headers or {}) + return JSONResponse(status_code=status, content=make_error(code, message, rid), headers=out) + + +@app.middleware("http") +async def add_request_id(request: Request, call_next): + incoming = request.headers.get("X-Request-Id", "") + rid = incoming if _REQUEST_ID_RE.fullmatch(incoming) else uuid.uuid4().hex + request.state.request_id = rid + response = await call_next(request) + response.headers["X-Request-Id"] = rid + response.headers["X-Instance-Id"] = INSTANCE_ID + response.headers["Cache-Control"] = "no-store" + return response + + +@app.exception_handler(ApiError) +async def api_error_handler(request: Request, exc: ApiError): + return error_response(request, exc.status, exc.code, exc.message, exc.headers) + + +@app.exception_handler(RequestValidationError) +async def validation_handler(request: Request, exc): + return error_response(request, 400, "invalid_request", "Некорректный запрос") + + +@app.exception_handler(StarletteHTTPException) +async def http_exc_handler(request: Request, exc: StarletteHTTPException): + mapping = {404: ("not_found", "Объект не найден"), 405: ("invalid_request", "Метод не поддерживается")} + code, message = mapping.get(exc.status_code, ("invalid_request", "Ошибка запроса")) + return error_response(request, exc.status_code, code, message) + + +@app.exception_handler(Exception) +async def generic_handler(request: Request, exc: Exception): + if isinstance(exc, db.TRANSIENT): + log.warning("dependency unavailable [%s]: %s", _rid(request), type(exc).__name__) + return error_response(request, 503, "unavailable", "Сервис временно недоступен") + log.error("unhandled error [%s]", _rid(request), exc_info=exc) + return error_response(request, 500, "internal_error", "Внутренняя ошибка сервера") + + +class Auth(NamedTuple): + user: dict + user_id: uuid.UUID + digest: bytes + + +def authenticated(request: Request) -> Auth: + token = security.parse_bearer(request.headers.get("Authorization")) + if token is None: + raise unauthorized(BEARER_CHALLENGE) + found = sessions.lookup(token) + if found is None: + raise unauthorized(BEARER_CHALLENGE) + return Auth(found["user"], uuid.UUID(found["user"]["id"]), found["digest"]) + + +class RawBody(NamedTuple): + content_type: str + data: bytes + + +async def raw_body(request: Request) -> RawBody: + declared = request.headers.get("content-length") + if declared is not None and declared.isdigit() and int(declared) > config.MAX_BODY_BYTES: + raise ApiError(413, "payload_too_large", "Тело запроса слишком большое") + chunks, size = [], 0 + async for chunk in request.stream(): + size += len(chunk) + if size > config.MAX_BODY_BYTES: + raise ApiError(413, "payload_too_large", "Тело запроса слишком большое") + chunks.append(chunk) + return RawBody(request.headers.get("content-type", ""), b"".join(chunks)) + + +@app.get("/health/live") +def live(): + return {"status": "ok"} + + +@app.get("/health/ready") +def ready(): + db.ping() + s3.ping() + return {"status": "ok"} + + +# ---------- пользователи / сессии / чаты (lab2–3 без изменений) ---------- + +@app.post("/api/v1/users", status_code=201) +def create_user(body: RawBody = Depends(raw_body)): + data = validation.json_body(body.content_type, body.data, + {"username", "display_name", "password"}, {"username", "display_name", "password"}) + username = validation.username_field(data["username"]) + display_name = validation.text_field(data["display_name"], "display_name", 1, 100) + password = validation.text_field(data["password"], "password", 12, 128) + with db.connection() as conn: + if repo.username_exists(conn, username): + raise ApiError(409, "conflict", "Имя пользователя занято") + password_hash = security.hash_password(password) + try: + with db.connection() as conn: + row = repo.insert_user(conn, username, display_name, password_hash) + except psycopg.errors.UniqueViolation: + raise ApiError(409, "conflict", "Имя пользователя занято") + return sessions.user_json(row) + + +@app.get("/api/v1/users/me") +def get_me(auth: Auth = Depends(authenticated)): + return auth.user + + +@app.post("/api/v1/auth/sessions", status_code=201) +def login(request: Request): + creds = security.parse_basic(request.headers.get("Authorization")) + if creds is None: + raise unauthorized(BASIC_CHALLENGE) + username, password = creds + with db.connection() as conn: + user = repo.user_for_login(conn, username) if validation._USERNAME_RE.fullmatch(username) else None + if user is None: + security.burn_verify(password) + raise unauthorized(BASIC_CHALLENGE) + ok, new_hash = security.verify_password(user["password_hash"], password) + if not ok: + raise unauthorized(BASIC_CHALLENGE) + with db.connection() as conn: + if new_hash: + repo.update_password_hash(conn, user["id"], new_hash) + token, expires_at = sessions.create(conn, user) + user_json = sessions.user_json(user) + sessions.warm(token, user_json, expires_at) + return {"token": token, "token_type": "Bearer", "expires_at": sessions.fmt_ts(expires_at), "user": user_json} + + +@app.delete("/api/v1/auth/sessions/current") +def logout(auth: Auth = Depends(authenticated)): + sessions.revoke(auth.digest) + return Response(status_code=204) + + +@app.post("/api/v1/chats", status_code=201) +def create_chat(auth: Auth = Depends(authenticated), body: RawBody = Depends(raw_body)): + data = validation.json_body(body.content_type, body.data, {"title", "member_ids"}, {"title", "member_ids"}) + title = validation.text_field(data["title"], "title", 1, 100) + raw = data["member_ids"] + if not isinstance(raw, list) or not 1 <= len(raw) <= 100: + raise bad_request("member_ids: от 1 до 100 элементов") + members = [validation.require_uuid(x, "member_id") for x in raw] + if len(set(members)) != len(members) or auth.user_id not in members: + raise bad_request("member_ids должны быть уникальны и включать вызывающего") + with db.connection() as conn: + chat = repo.create_chat(conn, auth.user_id, title, members) + return repo.chat_json(chat) + + +@app.get("/api/v1/chats") +def list_chats(request: Request, auth: Auth = Depends(authenticated)): + limit = validation.limit_param(request.query_params) + raw = request.query_params.get("cursor") + after = cursor.decode(raw, "chats", auth.user_id) if raw is not None else None + with db.connection() as conn: + items, nxt = repo.list_chats(conn, auth.user_id, after, limit) + return {"items": items, "next_cursor": nxt} + + +@app.get("/api/v1/chats/{chat_id}") +def get_chat(chat_id: str, auth: Auth = Depends(authenticated)): + cid = validation.require_uuid(chat_id, "chat_id") + with db.connection() as conn: + chat = repo.get_chat(conn, cid, auth.user_id) + if chat is None: + raise not_found() + return repo.chat_json(chat) + + +# ---------- сообщения (lab3 + attachment_ids) ---------- + +def _parse_attachment_ids(data): + raw = data.get("attachment_ids", []) + if not isinstance(raw, list) or len(raw) > 10: + raise bad_request("attachment_ids: до 10 элементов") + ids = [validation.require_uuid(x, "attachment_id") for x in raw] + if len(set(ids)) != len(ids): + raise bad_request("attachment_ids должны быть уникальны") + return ids + + +@app.post("/api/v1/chats/{chat_id}/messages", status_code=201) +def create_message(chat_id: str, request: Request, auth: Auth = Depends(authenticated), body: RawBody = Depends(raw_body)): + cid = validation.require_uuid(chat_id, "chat_id") + with db.connection() as conn: + if not repo.is_member(conn, cid, auth.user_id): + raise not_found() + + data = validation.json_body(body.content_type, body.data, {"text", "attachment_ids"}, {"text"}) + text = validation.text_field(data["text"], "text", 0, 4000, allow_blank=True) + attachment_ids = _parse_attachment_ids(data) + if not text.strip() and not attachment_ids: + raise bad_request("Пустое сообщение без вложений") + + idem_key = request.headers.get("Idempotency-Key") + path = "/api/v1/chats/%s/messages" % chat_id + req_hash = idempotency.get_request_hash(data) + + with db.connection() as conn: + idempotency.cleanup(conn, config.IDEMPOTENCY_TTL_SECONDS) + need_exec, cached_resp = idempotency.check_and_lock( + conn, str(auth.user_id), "POST", path, idem_key, req_hash + ) + if not need_exec: + return JSONResponse(status_code=201, content=cached_resp) + msg = repo.insert_message(conn, cid, auth.user_id, text, attachment_ids) + msg_json = repo.message_json(msg) + idempotency.save_result(conn, str(auth.user_id), "POST", path, idem_key, req_hash, 201, msg_json) + return msg_json + + +@app.get("/api/v1/chats/{chat_id}/messages") +def list_messages(chat_id: str, request: Request, auth: Auth = Depends(authenticated)): + cid = validation.require_uuid(chat_id, "chat_id") + limit = validation.limit_param(request.query_params) + raw = request.query_params.get("cursor") + after = cursor.decode(raw, "messages", cid) if raw is not None else None + with db.connection() as conn: + if not repo.is_member(conn, cid, auth.user_id): + raise not_found() + items, nxt = repo.list_messages(conn, cid, after, limit) + return {"items": items, "next_cursor": nxt} + + +# ---------- вложения (lab4) ---------- + +@app.post("/api/v1/chats/{chat_id}/attachments", status_code=201) +async def upload_attachment(chat_id: str, request: Request, auth: Auth = Depends(authenticated)): + cid = validation.require_uuid(chat_id, "chat_id") + filename = request.query_params.get("filename") + if filename is None: + raise bad_request("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") + + # Проверяем доступ до чтения тела: посторонний не должен отправить 10 MiB. + def _check_member(): + with db.connection() as conn: + return repo.is_member(conn, cid, auth.user_id) + + if not await anyio.to_thread.run_sync(_check_member): + raise not_found() + + declared_len = request.headers.get("content-length") + if declared_len is not None and declared_len.isdigit() and int(declared_len) > config.MAX_UPLOAD_BYTES: + raise ApiError(413, "payload_too_large", "Файл больше 10 MiB") + + spool = tempfile.SpooledTemporaryFile(max_size=1024 * 1024) + hasher = hashlib.sha256() + total = 0 + try: + async for chunk in request.stream(): + total += len(chunk) + if total > config.MAX_UPLOAD_BYTES: + raise ApiError(413, "payload_too_large", "Файл больше 10 MiB") + hasher.update(chunk) + spool.write(chunk) + if total == 0: + raise bad_request("Пустой файл") + spool.seek(0) + digest = hasher.hexdigest() + + def _process(): + actual = attachments.inspect_image_file(spool, total) + if actual != declared: + raise ApiError(415, "unsupported_media_type", "MIME не соответствует содержимому") + return attachments.upload_stream(cid, auth.user_id, filename, spool, total, digest, actual) + + return await anyio.to_thread.run_sync(_process) + finally: + spool.close() + + +@app.get("/api/v1/attachments/{attachment_id}") +def get_attachment(attachment_id: str, auth: Auth = Depends(authenticated)): + aid = validation.require_uuid(attachment_id, "attachment_id") + with db.connection() as conn: + row = repo.get_attachment_for_member(conn, aid, auth.user_id) + if row is None: + raise not_found() + return repo.attachment_json(row) + + +@app.get("/api/v1/attachments/{attachment_id}/content") +async def download_attachment(attachment_id: str, auth: Auth = Depends(authenticated)): + aid = validation.require_uuid(attachment_id, "attachment_id") + + # boto3 StreamingBody нельзя читать в чужом потоке: читаем всё в одном run_sync. + # Файл ≤ 10 MiB, поэтому память ограничена лимитом загрузки. + def _read_all(): + row, body = attachments.download(aid, auth.user_id) + try: + data = body.read() + finally: + body.close() + return row, data + + row, data = await anyio.to_thread.run_sync(_read_all) + + headers = { + "Content-Disposition": "attachment; filename*=UTF-8''%s" % quote(row["filename"], safe="") + } + return Response(content=data, media_type=row["content_type"], headers=headers) \ No newline at end of file diff --git a/nginx.conf b/nginx.conf new file mode 100644 index 00000000..7d015360 --- /dev/null +++ b/nginx.conf @@ -0,0 +1,33 @@ +worker_processes auto; +events { worker_connections 1024; } + +http { + upstream api_pool { + server messenger-lab4-api-1:8080 max_fails=1 fail_timeout=5s; + server messenger-lab4-api-2:8080 max_fails=1 fail_timeout=5s; + keepalive 16; + } + + server { + listen 80; + + location / { + proxy_pass http://api_pool; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header Connection ""; + + proxy_next_upstream error timeout; + proxy_next_upstream_tries 2; + + proxy_connect_timeout 2s; + proxy_send_timeout 15s; + proxy_read_timeout 15s; + + client_max_body_size 11m; + proxy_request_buffering on; + } + } +} \ No newline at end of file diff --git a/requirements-dev.txt b/requirements-dev.txt new file mode 100644 index 00000000..0a4bd4b4 --- /dev/null +++ b/requirements-dev.txt @@ -0,0 +1,4 @@ +# Only for full OpenAPI/JSON Schema validation; HTTP tests use stdlib. +openapi-spec-validator==0.7.2 +boto3==1.35.0 +Pillow==10.4.0 \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 00000000..fbed5d91 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,28 @@ +boto3==1.43.107 +Pillow==12.3.0 +annotated-types==0.8.0 +anyio==4.15.1 +argon2-cffi==25.1.0 +argon2-cffi-bindings==26.1.0 +cffi==2.1.1 +click==8.5.0 +fastapi==0.115.0 +h11==0.16.0 +httptools==0.9.0 +idna==3.20 +psycopg==3.2.9 +psycopg-binary==3.2.9 +psycopg-pool==3.2.6 +pycparser==3.11 +pydantic==2.14.1 +pydantic_core==2.50.1 +python-dotenv==1.2.4 +PyYAML==6.0.3 +redis==6.4.0 +starlette==0.38.6 +typing-inspection==0.4.4 +typing_extensions==4.16.0 +uvicorn==0.30.6 +uvloop==0.23.0 +watchfiles==1.3.0 +websockets==17.2 \ No newline at end of file diff --git a/scripts/check_contract.py b/scripts/check_contract.py new file mode 100644 index 00000000..dcb34dfa --- /dev/null +++ b/scripts/check_contract.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python3 +"""Offline structural checks; full schema validation is a separate target.""" +import ast +import json +from pathlib import Path +import re + +ROOT = Path(__file__).resolve().parents[1] + +def main(): + lab = json.loads((ROOT/'lab.json').read_text())['number'] + spec = json.loads((ROOT/'contracts/openapi.json').read_text()) + assert spec['openapi']=='3.1.0' + assert spec['info']['version']=='1.%d.0'%lab + operation_ids = set() + def walk(value): + if isinstance(value,dict): + if '$ref' in value: + pointer = value['$ref'] + assert pointer.startswith('#/'), 'unexpected external reference' + target = spec + for part in pointer[2:].split('/'): + target = target[part.replace('~1','/').replace('~0','~')] + for v in value.values(): + walk(v) + elif isinstance(value,list): + for v in value: + walk(v) + walk(spec) + for route,methods in spec['paths'].items(): + placeholders = set(re.findall(r'\{([^}]+)\}',route)) + for method,op in methods.items(): + assert op['operationId'] not in operation_ids, 'duplicate operationId' + operation_ids.add(op['operationId']) + params = {p['name'] for p in op.get('parameters',[]) if p['in']=='path' and p.get('required')} + assert placeholders==params, 'path parameter mismatch: '+route + for response in op['responses'].values(): + assert 'X-Request-Id' in response['headers'] + if lab>=3: + assert 'X-Instance-Id' in response['headers'] + assert ('/api/v1/auth/sessions' in spec['paths']) == (lab>=2) + assert ('/api/v1/attachments/{attachment_id}' in spec['paths']) == (lab>=4) + for file in list((ROOT/'tests').glob('*.py'))+list((ROOT/'scripts').glob('*.py')): + ast.parse(file.read_text(),filename=str(file)) + for file in ROOT.rglob('*.json'): + if any(part in {'.git','.venv','node_modules','vendor','output'} for part in file.parts): + continue + json.loads(file.read_text()) + for required in ('README.md','COURSE.md','CONTRIBUTING.md','REPORT.md','contracts/README.md','tests/smoke.py','tests/README.md'): + assert (ROOT/required).is_file(), 'missing '+required + print('PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.') + +if __name__=='__main__': + main() diff --git a/scripts/init-secrets.sh b/scripts/init-secrets.sh new file mode 100644 index 00000000..57ff48f7 --- /dev/null +++ b/scripts/init-secrets.sh @@ -0,0 +1,57 @@ +#!/bin/sh +# Создаёт локальные синтетические секреты для учебного стенда. Идемпотентен. +set -eu + +umask 077 +cd "$(dirname "$0")/.." +mkdir -p secrets + +gen() { + # 32 случайных байта в†’ base64 в†’ только URL-safe символы. + head -c 32 /dev/urandom | base64 | tr -d '/+=\n' | cut -c1-32 +} + +ensure() { + f="secrets/$1" + if [ ! -s "$f" ]; then + printf '%s' "$2" > "$f" + chmod 600 "$f" + echo "created $f" + fi +} + +PG_PASS=$(cat secrets/postgres_password 2>/dev/null || gen) +VALKEY_PASS=$(cat secrets/valkey_password 2>/dev/null || gen) +MINIO_ROOT_USER_VAL="minioadmin" +MINIO_ROOT_PASS=$(cat secrets/minio_root_password 2>/dev/null || gen) +S3_KEY=$(cat secrets/s3_access_key_id 2>/dev/null || "app$(gen | cut -c1-20)") +S3_SECRET=$(cat secrets/s3_secret_access_key 2>/dev/null || gen) + +ensure postgres_password "$PG_PASS" +ensure valkey_password "$VALKEY_PASS" +ensure minio_root_user "$MINIO_ROOT_USER_VAL" +ensure minio_root_password "$MINIO_ROOT_PASS" +ensure s3_access_key_id "$S3_KEY" +ensure s3_secret_access_key "$S3_SECRET" + +ensure database_url "postgresql://messenger:${PG_PASS}@postgres:5432/messenger" +ensure cache_url "redis://:${VALKEY_PASS}@valkey:6379/0" + +if [ ! -f .env ]; then + cat > .env <<'EOF' +APP_ENV=lab +SESSION_TTL_SECONDS=3600 +SESSION_STORE=postgres+cache +SESSION_CACHE_TTL_SECONDS=60 +IDEMPOTENCY_TTL_SECONDS=86400 +API_REPLICAS=2 +S3_REGION=us-east-1 +S3_BUCKET=messenger-attachments +MAX_UPLOAD_BYTES=10485760 +MAX_IMAGE_PIXELS=40000000 +S3_ORPHAN_GRACE_SECONDS=3600 +EOF + echo "created .env" +fi + +echo "secrets ready in ./secrets (РЅРµ коммить)" \ No newline at end of file diff --git a/scripts/reconcile_s3.py b/scripts/reconcile_s3.py new file mode 100644 index 00000000..05a82618 --- /dev/null +++ b/scripts/reconcile_s3.py @@ -0,0 +1,115 @@ +#!/usr/bin/env python3 +"""Сверка S3 и метаданных PostgreSQL. + +Классы проблем: + orphan_object — объект в S3 без строки attachments (или с pending > grace) + missing_object — attachments.status=ready, но объекта в S3 нет + failed_referenced — attachments.status=failed, объект всё ещё лежит в S3 + +Действия: + orphan_object → DELETE объекта (только старше grace) + missing_object → UPDATE status='failed', error_code='object_missing' + failed_referenced → DELETE объекта + +Использование: + python scripts/reconcile_s3.py --dry-run + python scripts/reconcile_s3.py --apply +""" +import argparse +import sys +import time +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) + +from app import config, db, repo, s3 # noqa: E402 + + +def _paginate(client, prefix): + """Возвращает {key: last_modified}.""" + token = None + out = {} + while True: + kwargs = {"Bucket": config.S3_BUCKET, "Prefix": prefix} + if token: + kwargs["ContinuationToken"] = token + resp = client.list_objects_v2(**kwargs) + for obj in resp.get("Contents", []): + out[obj["Key"]] = obj["LastModified"] + if not resp.get("IsTruncated"): + return out + token = resp["NextContinuationToken"] + + +def reconcile(dry_run: bool, grace_seconds: int): + client = s3._get_client() + now = time.time() + report = {"orphans_deleted": [], "orphans_skipped_fresh": [], + "missing_marked_failed": [], "failed_objects_deleted": []} + + with db.connection() as conn: + rows = conn.execute( + """SELECT id, object_key, status, created_at, + extract(epoch FROM created_at) AS created_epoch + FROM attachments""").fetchall() + by_key = {r["object_key"]: r for r in rows} + referenced = set(by_key) + + for key, last_modified in _paginate(client, "originals/").items(): + if key in referenced: + continue + age = now - last_modified.timestamp() + if age < grace_seconds: + report["orphans_skipped_fresh"].append(key) + continue + report["orphans_deleted"].append(key) + if not dry_run: + s3.delete_object(key) + + for row in rows: + key = row["object_key"] + if row["status"] == "ready" and key not in _paginate(client, key): + report["missing_marked_failed"].append(key) + if not dry_run: + with db.connection() as conn: + conn.execute( + """UPDATE attachments + SET status='failed', error_code='object_missing', + updated_at=clock_timestamp() + WHERE id=%s AND status='ready'""", (row["id"],)) + elif row["status"] == "failed": + if key in _paginate(client, key): + report["failed_objects_deleted"].append(key) + if not dry_run: + s3.delete_object(key) + elif row["status"] == "pending": + age = now - float(row["created_epoch"]) + if age >= grace_seconds and key in _paginate(client, key): + # pending дольше grace, а объект есть → API упал между S3 PUT и COMMIT + report["orphans_deleted"].append(key) + if not dry_run: + with db.connection() as conn: + repo.mark_attachment_failed(conn, row["id"], "orphaned_pending") + s3.delete_object(key) + + import json + print(json.dumps(report, ensure_ascii=False, indent=2, default=str)) + print("dry-run" if dry_run else "applied") + + +def main(): + p = argparse.ArgumentParser() + p.add_argument("--apply", action="store_true") + p.add_argument("--dry-run", action="store_true") + p.add_argument("--grace-seconds", type=int, default=config.S3_ORPHAN_GRACE_SECONDS) + args = p.parse_args() + if args.apply and args.dry_run: + sys.exit("use --apply or --dry-run, not both") + if not (args.apply or args.dry_run): + sys.exit("choose --dry-run or --apply") + reconcile(dry_run=not args.apply, grace_seconds=args.grace_seconds) + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/scripts/restart.cmd b/scripts/restart.cmd new file mode 100644 index 00000000..d79c2b8c --- /dev/null +++ b/scripts/restart.cmd @@ -0,0 +1,7 @@ +@echo off +REM Перезапуск стенда с сохранением volumes. Возврат 0 = ОК. +cd /d "%~dp0\.." +docker compose --env-file .env stop +timeout /t 2 /nobreak >nul +docker compose --env-file .env up -d +exit /b 0 \ No newline at end of file diff --git a/scripts/restart.example.sh b/scripts/restart.example.sh new file mode 100644 index 00000000..967e9512 --- /dev/null +++ b/scripts/restart.example.sh @@ -0,0 +1,10 @@ +#!/bin/sh +set -eu +# TODO: copy to restart.sh and implement using YOUR compose/stack services. +# Restart API and ALL used state stores (DB, sessions, S3, broker as applicable). +# Preserve persistent volumes and schema/data; never down -v / flush / re-seed. +# Allow operator unseal if required in lab7; do not print credentials. +# Exit 0 only after the intended action; test waits for API readiness separately. +printf '%s +' 'TODO: implement restart.sh for your infrastructure' >&2 +exit 2 diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100644 index 00000000..a5144659 --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,23 @@ +#!/bin/sh +# Перезапуск всего стенда СЃ сохранением volumes Рё данных. +# Никаких down -v / reset / seed. Останавливает РїРѕ dependency-РїРѕСЂСЏРґРєСѓ, +# поднимает РІ обратном. Ждёт /health/ready РґРѕ 90 секунд. +set -eu + +cd "$(dirname "$0")/.." + +# Compose сам соблюдает зависимость: stop РІ обратном РїРѕСЂСЏРґРєРµ, up РІ РїСЂСЏРјРѕРј. +docker compose --env-file .env stop +sleep 1 +docker compose --env-file .env up -d + +for i in $(seq 1 90); do + if curl -fs -o /dev/null http://127.0.0.1:8080/health/ready 2>/dev/null; then + echo "stack ready after ${i}s" + exit 0 + fi + sleep 1 +done + +echo "stack did not become ready in 90s" >&2 +exit 1 \ No newline at end of file diff --git a/scripts/stop-one.cmd b/scripts/stop-one.cmd new file mode 100644 index 00000000..611f6df3 --- /dev/null +++ b/scripts/stop-one.cmd @@ -0,0 +1,19 @@ +@echo off +REM Остановить одну API-реплику по её X-Instance-Id (== Hostname контейнера). +setlocal +if "%TARGET_INSTANCE_ID%"=="" ( + echo TARGET_INSTANCE_ID is not set + exit /b 1 +) + +for /f "tokens=*" %%c in ('docker ps -q --filter "name=messenger-lab4-api"') do ( + for /f "tokens=*" %%h in ('docker inspect -f "{{.Config.Hostname}}" %%c') do ( + if "%%h"=="%TARGET_INSTANCE_ID%" ( + echo Stopping container %%c + docker stop %%c + exit /b 0 + ) + ) +) +echo Container with instance ID %TARGET_INSTANCE_ID% not found +exit /b 1 \ No newline at end of file diff --git a/scripts/stop-one.example.sh b/scripts/stop-one.example.sh new file mode 100644 index 00000000..ae149e89 --- /dev/null +++ b/scripts/stop-one.example.sh @@ -0,0 +1,10 @@ +#!/bin/sh +set -eu +# TODO: copy to stop-one.sh, map TARGET_INSTANCE_ID to ONE API container/task. +# Stop that instance and leave it stopped; no stop of DB/LB/volumes. +# Return quickly (within 10 s); the test sends requests during this script. +# Restore the replica explicitly after the test. Never print credentials. +: "${TARGET_INSTANCE_ID:?test provides target API instance alias}" +printf '%s +' 'TODO: implement stop-one.sh for your infrastructure' >&2 +exit 2 diff --git a/scripts/stop-one.sh b/scripts/stop-one.sh new file mode 100644 index 00000000..aa8ab595 --- /dev/null +++ b/scripts/stop-one.sh @@ -0,0 +1,30 @@ +#!/bin/sh +# Останавливает конкретную реплику API Р С—Р С• её X-Instance-Id. +set -eu + +if [ -z "${TARGET_INSTANCE_ID:-}" ]; then + echo "TARGET_INSTANCE_ID is not set" >&2 + exit 1 +fi + +# INSTANCE_ID = socket.gethostname(), Р Р† Docker это короткий ID контейнера. +cid=$(docker ps -q --filter "id=$TARGET_INSTANCE_ID" || true) + +if [ -z "$cid" ]; then + # Fallback: искать Р С—Р С• имени проекта Р С‘ сверять hostname + for c in $(docker ps -q --filter "name=messenger-lab4"); do + h=$(docker inspect -f '{{.Config.Hostname}}' "$c") + if [ "$h" = "$TARGET_INSTANCE_ID" ]; then + cid="$c" + break + fi + done +fi + +if [ -n "$cid" ]; then + echo "Stopping container $cid (Instance ID: $TARGET_INSTANCE_ID)" + docker stop "$cid" +else + echo "Container with instance ID $TARGET_INSTANCE_ID not found" >&2 + exit 1 +fi \ No newline at end of file diff --git a/scripts/validate_openapi.py b/scripts/validate_openapi.py new file mode 100644 index 00000000..1dfe4a98 --- /dev/null +++ b/scripts/validate_openapi.py @@ -0,0 +1,23 @@ +#!/usr/bin/env python3 +"""Full OpenAPI and JSON Schema checks; install requirements-dev.txt first.""" +import json +from pathlib import Path +from openapi_spec_validator import validate +from jsonschema import Draft202012Validator + +root = Path(__file__).resolve().parents[1] +spec = json.loads((root/'contracts/openapi.json').read_text()) +validate(spec) +from referencing import Registry, Resource +# The base URI resolves local #/components references inside examples. +resource = dict(spec, **{'$schema': 'https://json-schema.org/draft/2020-12/schema'}) +registry = Registry().with_resource('urn:mtusi:openapi', Resource.from_contents(resource)) +for name, example in json.loads((root/'contracts/examples.json').read_text()).items(): + schema = {'$ref': 'urn:mtusi:openapi#/components/schemas/' + name} + Draft202012Validator(schema, registry=registry).validate(example) +for path in (root/'contracts').glob('*.schema.json'): + schema = json.loads(path.read_text()) + Draft202012Validator.check_schema(schema) + for example in schema.get('examples',[]): + Draft202012Validator(schema).validate(example) +print('PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.') diff --git a/student-tests/test_attachments_negative.py b/student-tests/test_attachments_negative.py new file mode 100644 index 00000000..18be2ef4 --- /dev/null +++ b/student-tests/test_attachments_negative.py @@ -0,0 +1,75 @@ +#!/usr/bin/env python3 +"""Негативные сценарии вложений. Запускается против запущенного стенда.""" +import sys +import uuid +from pathlib import Path +from urllib.parse import quote + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "tests")) + +from client import Client, Failure, arguments, check, run # noqa: E402 + +PNG_MAGIC = b"\x89PNG\r\n\x1a\n" + + +def main(): + args = arguments("Lab4 attachment negative tests") + c = Client(args.base_url, args.ca_file) + alice, bob, eve, chat = c.bootstrap() + other_chat = c.call( + "POST", "/api/v1/chats", 201, actor=bob, + body={"title": "Другой чат", "member_ids": [bob["id"]]}, schema="Chat")["json"] + base = "/api/v1/chats/%s/attachments" % chat["id"] + png_fixture = (ROOT / "tests/fixtures/sample.png").read_bytes() + + # 1. Слишком большой файл: 10 MiB + 1 байт, Content-Length сразу отвергается. + big = PNG_MAGIC + b"\x00" * (10485760) + r = c.call("POST", base + "?filename=big.png", 413, actor=alice, raw=big, + headers={"Content-Type": "image/png"}) + check(r["status"] == 413, "oversize not rejected") + + # 2. Подмена MIME: объявляем image/png, а байты не PNG. + r = c.call("POST", base + "?filename=x.png", 415, actor=alice, + raw=b"not an image at all", + headers={"Content-Type": "image/png"}) + check(r["status"] == 415, "mime mismatch not rejected") + + # 3. Повреждённый PNG: валидный заголовок, битая структура. + broken = png_fixture[:20] + b"\x00" * 32 + png_fixture[52:] + c.call("POST", base + "?filename=broken.png", 415, actor=alice, raw=broken, + headers={"Content-Type": "image/png"}) + + # 4. Опасное имя файла. URL-кодируем: NUL, /, \ в URL напрямую запрещены + # клиентом (http.client), но после декодирования сервер обязан отклонить. + for bad in ("../etc/passwd", "a\\b.png", "a\x00b.png", "a/b.png"): + c.call("POST", base + "?filename=" + quote(bad, safe=""), 400, actor=alice, + raw=png_fixture, headers={"Content-Type": "image/png"}) + + # 5. Чужой чат: eve не участник — 404 до чтения тела. + c.call("POST", base + "?filename=sample.png", 404, actor=eve, + raw=png_fixture, headers={"Content-Type": "image/png"}) + + # 6. Сослаться на чужое вложение в сообщении. + foreign = c.call("POST", "/api/v1/chats/%s/attachments?filename=s.png" % other_chat["id"], + 201, actor=bob, raw=png_fixture, + headers={"Content-Type": "image/png"}, schema="Attachment")["json"] + c.call("POST", "/api/v1/chats/%s/messages" % chat["id"], 400, + actor=alice, + body={"text": "hi", "attachment_ids": [foreign["id"]]}, + headers={"Idempotency-Key": uuid.uuid4().hex}) + + # 7. Чтение чужого attachment_id — 404 на metadata и bytes. + c.call("GET", "/api/v1/attachments/" + foreign["id"], 404, actor=eve) + c.call("GET", "/api/v1/attachments/" + foreign["id"] + "/content", 404, actor=eve) + + # 8. Несуществующий id — 404, не 500. + ghost = str(uuid.uuid4()) + c.call("GET", "/api/v1/attachments/" + ghost, 404, actor=alice) + c.call("GET", "/api/v1/attachments/" + ghost + "/content", 404, actor=alice) + + print("PASS: 8 negative attachment scenarios") + + +if __name__ == "__main__": + run(main) \ No newline at end of file diff --git a/tests/README.md b/tests/README.md new file mode 100644 index 00000000..0dfa3f89 --- /dev/null +++ b/tests/README.md @@ -0,0 +1,57 @@ +# Публичные проверки + +Python **3.9+**, стандартная библиотека. Сервер уже должен быть запущен; проверки не создают готовое приложение и сами не управляют Docker. `make check` можно выполнить на исходном skeleton, `make test` — только после реализации API. Полная OpenAPI-валидация отдельно: `make validate` после установки `requirements-dev.txt` в venv. + +```sh +make check +make test BASE_URL=http://localhost:8080 +# без make: +python3 tests/smoke.py --base-url http://localhost:8080 +``` + +`smoke.py` выполняет **один сквозной сценарий**, автоматически выбирая профиль из `lab.json`: health → три пользователя → вход с lab2 → чат → сообщения → пагинация → ошибки доступа → идемпотентность с lab3 → файл с lab4 → thumbnail с lab5 → logout. Он проверяет JSON по используемому подмножеству схемы, коды/headers, Unicode, SHA-256 оригинала и фактические JPEG-размеры thumbnail. Это публичный минимум, не полный fuzz/security/load suite. + +Каждый запуск создаёт уникальных синтетических пользователей, чат и сообщения. Данные автоматически не удаляются: в API курса нет delete. Для чистого повтора используйте отдельный тестовый стенд/volume и осознанный сброс своего окружения. Session tokens хранятся только в памяти процесса и не печатаются/не сохраняются. + +## Проверка сохранности, lab2+ + +Скопируйте `scripts/restart.example.sh` в `scripts/restart.sh`, реализуйте перезапуск **API и всех используемых хранилищ** с сохранением volumes и задайте executable bit. Скрипт может опираться на ваш compose.yaml или stack.yaml. Он не должен удалять volumes, повторно seed-ить БД или менять тестовые данные. + +```sh +chmod +x scripts/restart.sh +make test-persistence ACTION_SCRIPT=scripts/restart.sh +``` + +Тест создаёт данные и сессию, запускает указанный файл без shell interpolation, ожидает готовности и проверяет те же данные **с прежним токеном**. В lab4+ также проверяется исходный файл. Hook может работать до 90 секунд, готовность затем ожидается до 90 секунд. TTL сессии для этого теста — минимум 300 секунд. Успех не доказывает, что hook действительно перезапустил БД: приложите команды/состояния контейнеров до и после. + +## Проверка отказа, lab3+ + +Реализуйте `scripts/stop-one.sh` на основе примера. `TARGET_INSTANCE_ID` в окружении содержит alias обслужившей тест API-реплики: сопоставьте его своему контейнеру/Swarm task и остановите именно его. Скрипт должен быстро вернуть 0 и **оставить эту реплику остановленной**; восстановление выполняйте отдельно. Swarm может создать новую task с другим ID — это допустимо. + +```sh +chmod +x scripts/stop-one.sh +make test-failover ACTION_SCRIPT=scripts/stop-one.sh +``` + +Перед отказом тест наблюдает ≥2 API-реплики; 15 секунд отправляет сообщения параллельно выполнению hook, повторяет неопределённый POST с тем же ключом, проверяет восстановление записи за ≤10 секунд, отсутствие остановленной реплики в последних ответах, сохранность подтверждённых сообщений и отсутствие дублей. Ошибки переходного периода учитываются. Затем восстановите реплику и повторите для другой. Скрипт — проверка одного отказа API, не гарантия HA БД/LB/host. Вывод hook скрыт, чтобы не утекли секреты; отлаживайте его отдельно с безопасным выводом. + +## Нагрузка + +```sh +python3 tests/load.py --duration 30 --concurrency 4 --output evidence/load.json +``` + +Это простой **closed-loop** генератор POST сообщений; он ограничен производительностью клиента и страдает coordinated omission. Он выдаёт successful RPS, ошибки и p50/p95/p99 **только успешных запросов**. Во время нагрузки нет прозрачных retry; timeout мог скрыть совершённую запись, поэтому это throughput HTTP-подтверждений, не точный счётчик COMMIT. Изменение размера истории входит в профиль. Для серьёзного исследования используйте k6/Locust/wrk либо свой обоснованный генератор, а не выводите максимальную пропускную способность из одного запуска этого скрипта. Для нагрузки pipeline изображений нужен отдельный сценарий студента. + +## HTTPS, lab7 + +```sh +make test BASE_URL=https://localhost:8443 CA_FILE=/absolute/path/to/ca.crt +make test-security BASE_URL=https://localhost:8443 CA_FILE=/absolute/path/to/ca.crt +``` + +Все скрипты принимают `--ca-file`/`CA_FILE` и проверяют серверный сертификат и hostname. `--insecure` отсутствует. TLS-тест сначала проверяет рабочее доверенное соединение, затем намеренно пустой trust store и именно ошибку проверки сертификата; network timeout не засчитывается как правильный отказ. **Внутреннее mTLS, identity/authorization, OpenBao policy и hardening проверяют отдельные тесты студента** по trust matrix. Клиентский сертификат внешнему учебному REST-клиенту не требуется: mTLS находится на внутренних связях. + +## Что ещё остаётся доказать + +Smoke не доказывает persistence, число реальных контейнеров, durability брокера, outbox, отсутствие утечек/уязвимостей, полноту telemetry или выполнение уровня 4/5. Конкурентные/нагрузочные/негативные проверки своего решения добавляйте отдельно. Список защиты текущей лабы находится в README.md. Проверки рассчитаны на localhost-стенд, не на production. diff --git a/tests/client.py b/tests/client.py new file mode 100644 index 00000000..f0499a29 --- /dev/null +++ b/tests/client.py @@ -0,0 +1,217 @@ +"""HTTP helpers for public black-box tests; Python 3.9+, standard library only.""" +import base64 +import datetime as dt +import hashlib +import json +import os +from pathlib import Path +import re +import ssl +import time +import urllib.error +import urllib.request +import uuid + +ROOT = Path(__file__).resolve().parents[1] +LAB = json.loads((ROOT / 'lab.json').read_text())['number'] +SPEC = json.loads((ROOT / 'contracts/openapi.json').read_text()) + +class Failure(AssertionError): + pass + +def check(condition, message): + if not condition: + raise Failure(message) + +def timestamp(value): + check(isinstance(value, str) and value.endswith('Z'), 'timestamp must be UTC ending in Z') + try: + return dt.datetime.fromisoformat(value[:-1] + '+00:00') + except ValueError as exc: + raise Failure('invalid RFC3339 timestamp') from exc + +def validate(value, schema, where='response'): + """Validate the JSON Schema subset used by the supplied contract, not arbitrary OpenAPI.""" + if '$ref' in schema: + target = SPEC + for part in schema['$ref'].split('/')[1:]: + target = target[part] + return validate(value, target, where) + kinds = schema.get('type', []) + if isinstance(kinds, str): + kinds = [kinds] + matches = {'null':value is None, 'boolean':isinstance(value,bool), 'integer':isinstance(value,int) and not isinstance(value,bool), 'number':isinstance(value,(int,float)) and not isinstance(value,bool), 'string':isinstance(value,str), 'array':isinstance(value,list), 'object':isinstance(value,dict)} + if kinds: + check(any(matches.get(k,False) for k in kinds), where + ': incorrect type') + if 'enum' in schema: + check(value in schema['enum'], where + ': invalid enum') + if 'const' in schema: + check(value == schema['const'], where + ': invalid const') + if isinstance(value,dict): + props = schema.get('properties',{}) + check(all(k in value for k in schema.get('required',[])), where + ': missing required fields') + if schema.get('additionalProperties') is False: + check(not set(value).difference(props), where + ': unexpected fields') + for key, sub in props.items(): + if key in value: + validate(value[key], sub, where + '.' + key) + if isinstance(value,list): + check(len(value) >= schema.get('minItems',0), where + ': too few items') + check(len(value) <= schema.get('maxItems',float('inf')), where + ': too many items') + if schema.get('uniqueItems'): + encoded = [json.dumps(x,sort_keys=True) for x in value] + check(len(encoded)==len(set(encoded)), where + ': duplicate items') + if 'items' in schema: + for item in value: + validate(item, schema['items'], where + '[]') + if isinstance(value,str): + check(len(value) >= schema.get('minLength',0), where + ': too short') + check(len(value) <= schema.get('maxLength',float('inf')), where + ': too long') + if 'pattern' in schema: + check(re.search(schema['pattern'], value) is not None, where + ': pattern mismatch') + if schema.get('format') == 'uuid': + try: + uuid.UUID(value) + except ValueError as exc: + raise Failure(where + ': invalid UUID') from exc + if schema.get('format') == 'date-time': + timestamp(value) + if isinstance(value,(int,float)) and not isinstance(value,bool): + check(value >= schema.get('minimum',-float('inf')), where + ': below minimum') + check(value <= schema.get('maximum',float('inf')), where + ': above maximum') + if 'anyOf' in schema: + for alternative in schema['anyOf']: + try: + validate(value, alternative, where) + break + except Failure: + pass + else: + raise Failure(where + ': no anyOf branch matches') + +def shape(value, name): + validate(value, SPEC['components']['schemas'][name]) + return value + +class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, headers, newurl): + return None + +class Client: + def __init__(self, base_url=None, ca_file=None, timeout=10): + self.base = (base_url or os.environ.get('BASE_URL') or ('https://localhost:8443' if LAB==7 else 'http://localhost:8080')).rstrip('/') + check(self.base.startswith(('http://','https://')), 'BASE_URL must be HTTP(S)') + check(LAB != 7 or self.base.startswith('https://'), 'lab7 requires HTTPS') + self.timeout = timeout + context = ssl.create_default_context(cafile=ca_file or os.environ.get('CA_FILE') or None) + self.opener = urllib.request.build_opener(NoRedirect(), urllib.request.HTTPSHandler(context=context)) + + def call(self, method, path, expected=200, body=None, actor=None, headers=None, raw=None, schema=None): + h = {'Accept':'application/json'} + if actor: + h['X-User-Id' if LAB==1 else 'Authorization'] = actor['id'] if LAB==1 else 'Bearer ' + actor['token'] + if body is not None: + raw = json.dumps(body,ensure_ascii=False).encode('utf-8') + h['Content-Type'] = 'application/json' + h.update(headers or {}) + req = urllib.request.Request(self.base + path, data=raw, headers=h, method=method) + start = time.monotonic() + try: + response = self.opener.open(req, timeout=self.timeout) + except urllib.error.HTTPError as error: + response = error + except (urllib.error.URLError,TimeoutError,OSError) as exc: + # Do not print URL query, headers, request body, or credentials. + raise Failure(method + ' ' + path.split('?')[0] + ': connection/TLS failure (' + type(exc).__name__ + ')') from None + with response: + status = response.code + rh = response.headers + data = response.read(16*1024*1024 + 1) + check(len(data) <= 16*1024*1024, 'response exceeds test safety limit') + allowed = [expected] if isinstance(expected,int) else expected + check(status in allowed, method + ' ' + path.split('?')[0] + ': expected ' + str(allowed) + ', received ' + str(status)) + check(bool(rh.get('X-Request-Id')), 'missing X-Request-Id') + if LAB>=3: + check(bool(rh.get('X-Instance-Id')), 'missing X-Instance-Id') + payload = None + if schema or status>=400: + check(rh.get_content_type()=='application/json', 'expected application/json') + try: + payload = json.loads(data) + except (ValueError,UnicodeError): + raise Failure('invalid response JSON') from None + shape(payload, 'Error' if status>=400 else schema) + if status>=400: + check(payload['error']['request_id']==rh.get('X-Request-Id'),'error request_id differs from header') + if status==401 and LAB>=2: + scheme = 'Basic' if path=='/api/v1/auth/sessions' else 'Bearer' + check(rh.get('WWW-Authenticate','').lower().startswith(scheme.lower()), 'incorrect WWW-Authenticate challenge') + if status==204: + check(not data, '204 must not contain body') + return {'status':status,'headers':rh,'json':payload,'bytes':data,'elapsed':time.monotonic()-start} + + def user(self, label): + username = 'u_' + label + '_' + uuid.uuid4().hex[:12] + password = 'T3st-' + uuid.uuid4().hex + body = {'username':username,'display_name':'Студент ' + label} + if LAB>=2: + body['password'] = password + user = self.call('POST','/api/v1/users',201,body=body,schema='User')['json'] + check(user['username']==username,'username changed') + actor = {'id':user['id'],'user':user,'registration':body} + if LAB>=2: + credential = base64.b64encode((username+':'+password).encode()).decode() + session = self.call('POST','/api/v1/auth/sessions',201,headers={'Authorization':'Basic '+credential},schema='Session')['json'] + check(session['user']==user,'session user mismatch') + check(timestamp(session['expires_at']) > dt.datetime.now(dt.timezone.utc),'session already expired') + actor['token'] = session['token'] + return actor + + def bootstrap(self): + self.call('GET','/health/live',schema='Health') + self.call('GET','/health/ready',schema='Health') + alice, bob, eve = (self.user(label) for label in ('alice','bob','eve')) + chat = self.call('POST','/api/v1/chats',201,actor=alice,body={'title':'Контрактный тест','member_ids':[alice['id'],bob['id']]},schema='Chat')['json'] + check(set(chat['member_ids'])=={alice['id'],bob['id']},'chat member mismatch') + return alice,bob,eve,chat + + def message(self, actor, chat, text, key=None, attachments=None): + body = {'text':text} + if attachments is not None: + body['attachment_ids'] = attachments + headers = {'Idempotency-Key':key or uuid.uuid4().hex} if LAB>=3 else {} + return self.call('POST','/api/v1/chats/'+chat['id']+'/messages',201,actor=actor,body=body,headers=headers,schema='Message') + + def attachment(self, actor, chat): + content = (ROOT / 'tests/fixtures/sample.png').read_bytes() + att = self.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=sample.png',201 if LAB==4 else 202,actor=actor,raw=content,headers={'Content-Type':'image/png'},schema='Attachment')['json'] + check(att['status']==('ready' if LAB==4 else 'queued'),'incorrect upload status') + check(att['chat_id']==chat['id'] and att['owner_id']==actor['id'],'attachment ownership mismatch') + check(att['sha256']==hashlib.sha256(content).hexdigest() and att['size_bytes']==len(content),'original checksum/size mismatch') + return att,content + + def wait_ready(self, actor, att, wait_seconds=60): + deadline = time.monotonic()+wait_seconds + while time.monotonic()=2 and i+length<=len(data),'invalid JPEG segment length') + if marker in sof: + check(length>=8,'invalid JPEG SOF') + return (int.from_bytes(data[i+5:i+7],'big'),int.from_bytes(data[i+3:i+5],'big')) + i += length + raise Failure('JPEG dimensions not found') diff --git a/tests/load.py b/tests/load.py new file mode 100644 index 00000000..ad81d596 --- /dev/null +++ b/tests/load.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Small closed-loop HTTP write benchmark; not an open-loop capacity proof.""" +from concurrent.futures import ThreadPoolExecutor +import json +import math +from pathlib import Path +import threading +import time +from client import Client, Failure, LAB, arguments, check, run + + +def main(): + def configure(p): + p.add_argument('--duration',type=float,default=30) + p.add_argument('--concurrency',type=int,default=4) + p.add_argument('--output',default=None,help='Optional JSON metrics, no session tokens') + args = arguments('Synthetic POST message load, closed loop; creates users/messages',configure) + check(1<=args.duration<=3600,'duration must be 1..3600 seconds') + check(1<=args.concurrency<=128,'concurrency must be 1..128') + c = Client(args.base_url,args.ca_file) + alice,bob,eve,chat = c.bootstrap() + barrier = threading.Barrier(args.concurrency) + def worker(worker_id): + local = Client(args.base_url,args.ca_file,timeout=5) + barrier.wait() + deadline = time.monotonic()+args.duration + latencies,errors = [],0 + index = 0 + while time.monotonic()=2,'persistence requires lab2+') + check(args.mode!='failover' or LAB>=3,'failover requires lab3+') + script = Path(args.action_script).expanduser().resolve() + check(script.is_file() and os.access(script,os.X_OK),'action script must exist and be executable (chmod +x)') + check('.example.' not in script.name,'copy and implement the example hook first') + c = Client(args.base_url,args.ca_file,timeout=2) + alice,bob,eve,chat = c.bootstrap() + sent = c.message(alice,chat,'Сохранить при отказе') + original = sent['json'] + target = sent['headers'].get('X-Instance-Id','') + attachment = content = None + if LAB>=4: + attachment,content = c.attachment(alice,chat) + if LAB>=5: + attachment = c.wait_ready(alice,attachment) + env = dict(os.environ) + env['TARGET_INSTANCE_ID'] = target + observed = set() + if args.mode=='failover': + for _ in range(40): + observed.add(c.call('GET','/api/v1/users/me',actor=alice,schema='User')['headers']['X-Instance-Id']) + check(len(observed)>=2,'less than two API instances observed before failure; verify LB/session affinity') + print('Executing explicit '+args.mode+' hook; hook output suppressed to avoid leaking secrets.') + # No shell interpolation and no Docker commands in this test. + proc = subprocess.Popen([str(script)],env=env,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL) + started = time.monotonic() + successes,failures,after_instances = [],0,[] + try: + if args.mode=='persistence': + try: + code = proc.wait(timeout=90) + except subprocess.TimeoutExpired: + raise Failure('restart hook exceeded 90 seconds') from None + check(code==0,'restart hook failed (inspect your script locally)') + deadline = time.monotonic()+90 + while True: + try: + c.call('GET','/health/ready',schema='Health') + c.call('GET','/api/v1/users/me',actor=alice,schema='User') + break + except Failure: + check(time.monotonic()=5,'too few successful writes after stop') + check(target not in after_instances[-5:],'target replica still serves requests; hook must leave it stopped') + print(json.dumps({'observed_instances_before':len(observed),'successful_writes':len(successes),'failed_attempts':failures,'first_recovery_seconds':round(first_recovery,3)},ensure_ascii=False)) + # Existing token, no re-login. Read all confirmations and reject duplicates. + messages = history(c,bob,chat) + ids = [m['id'] for m in messages] + check(len(ids)==len(set(ids)),'duplicated message IDs in history') + check(any(m==original for m in messages),'confirmed pre-failure message lost or altered') + for msg in successes: + check(any(m==msg for m in messages),'confirmed in-flight message lost or altered') + # Bodies are unique in this scenario: an uncertain request may exist once, never twice. + texts = [m['text'] for m in messages] + check(len(texts)==len(set(texts)),'uncertain retry created duplicate message') + if attachment: + c.call('GET','/api/v1/attachments/'+attachment['id'],actor=bob,schema='Attachment') + downloaded = c.call('GET','/api/v1/attachments/'+attachment['id']+'/content',actor=bob) + check(downloaded['bytes']==content,'attachment lost or changed across failure') + print('PASS: '+args.mode+' preserved confirmed data and existing session. Hook scope needs operator evidence.') + finally: + if proc.poll() is None: + proc.terminate() + try: + proc.wait(timeout=5) + except subprocess.TimeoutExpired: + proc.kill() + proc.wait() + +if __name__=='__main__': + run(main) diff --git a/tests/smoke.py b/tests/smoke.py new file mode 100644 index 00000000..4cbfa558 --- /dev/null +++ b/tests/smoke.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python3 +"""One complete public acceptance scenario, cumulative by lab number.""" +import base64 +import hashlib +import uuid +from client import Client, LAB, arguments, check, run, timestamp + + +def main(): + args = arguments('Messenger public smoke; creates synthetic users and messages') + c = Client(args.base_url,args.ca_file) + alice,bob,eve,chat = c.bootstrap() + path = '/api/v1/chats/'+chat['id'] + c.call('POST','/api/v1/users',409,body=alice['registration']) + c.call('GET','/api/v1/users/me',401) + c.call('GET',path,404,actor=eve) + me = c.call('GET','/api/v1/users/me',actor=alice,schema='User')['json'] + check(me==alice['user'],'current user mismatch') + listed = c.call('GET','/api/v1/chats?limit=100',actor=bob,schema='ChatPage')['json'] + check(any(x['id']==chat['id'] for x in listed['items']),'member cannot list chat') + hidden = c.call('GET','/api/v1/chats?limit=100',actor=eve,schema='ChatPage')['json'] + check(all(x['id']!=chat['id'] for x in hidden['items']),'chat leaks to outsider') + key = uuid.uuid4().hex + first = c.message(alice,chat,'Привет, мир 👋',key=key)['json'] + second = c.message(bob,chat,'Сообщение Боба')['json'] + check(first['sender_id']==alice['id'] and second['sender_id']==bob['id'],'sender was not derived from actor') + check(first['chat_id']==second['chat_id']==chat['id'],'wrong chat in message') + check(first['text']=='Привет, мир 👋' and second['text']=='Сообщение Боба','message text changed') + page1 = c.call('GET',path+'/messages?limit=1',actor=bob,schema='MessagePage')['json'] + check(len(page1['items'])==1 and page1['next_cursor'],'first page must have one item and cursor') + from urllib.parse import quote + page2 = c.call('GET',path+'/messages?limit=1&cursor='+quote(page1['next_cursor'],safe=''),actor=alice,schema='MessagePage')['json'] + check(len(page2['items'])==1 and page2['next_cursor'] is None,'second page must finish history') + ordered = sorted([first,second],key=lambda x:(timestamp(x['created_at']),uuid.UUID(x['id']).int)) + check(page1['items']+page2['items']==ordered,'pagination lost, duplicated or reordered a message') + h = {'Idempotency-Key':uuid.uuid4().hex} if LAB>=3 else {} + c.call('POST',path+'/messages',400,actor=alice,body={'text':''},headers=h) + c.call('POST',path+'/messages',404,actor=eve,body={'text':'чужое'},headers=h) + c.call('GET',path+'/messages?limit=0',400,actor=alice) + if LAB>=2: + bad = base64.b64encode((alice['registration']['username']+':wrong-password').encode()).decode() + c.call('POST','/api/v1/auth/sessions',401,headers={'Authorization':'Basic '+bad}) + good = base64.b64encode((alice['registration']['username']+':'+alice['registration']['password']).encode()).decode() + c.call('GET','/api/v1/users/me',401,headers={'Authorization':'Basic '+good}) + c.call('GET','/api/v1/users/me',401,headers={'X-User-Id':alice['id']}) + me = c.call('GET','/api/v1/users/me',actor=alice,headers={'X-User-Id':eve['id']},schema='User')['json'] + check(me['id']==alice['id'],'X-User-Id overrode bearer identity') + if LAB>=3: + replay = c.message(alice,chat,first['text'],key=key)['json'] + check(replay==first,'idempotency replay differs') + c.call('POST',path+'/messages',409,actor=alice,body={'text':'другой body'},headers={'Idempotency-Key':key}) + c.call('POST',path+'/messages',400,actor=alice,body={'text':'без ключа'}) + if LAB>=4: + att,content = c.attachment(alice,chat) + # A queued attachment must already be linkable to its own chat. + attached = c.message(alice,chat,'',attachments=[att['id']])['json'] + check(attached['attachment_ids']==[att['id']],'message lost attachment') + ready = c.wait_ready(bob,att) if LAB>=5 else att + check(ready['error_code'] is None,'ready attachment has an error') + download = c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=bob) + check(download['bytes']==content,'download differs from original') + check(download['headers'].get_content_type()=='image/png','original content type mismatch') + for suffix in ('','/content'): + c.call('GET','/api/v1/attachments/'+att['id']+suffix,404,actor=eve) + if LAB>=5: + variants = [x for x in ready['variants'] if x['name']=='thumbnail'] + check(len(variants)==1,'expected exactly one thumbnail') + v = variants[0] + check((v['width'],v['height'])==(256,160),'thumbnail metadata has wrong dimensions') + thumb = c.call('GET','/api/v1/attachments/'+att['id']+'/content?variant=thumbnail',actor=bob) + check(thumb['headers'].get_content_type()=='image/jpeg','thumbnail content type mismatch') + check(len(thumb['bytes'])==v['size_bytes'] and hashlib.sha256(thumb['bytes']).hexdigest()==v['sha256'],'thumbnail checksum mismatch') + from image_probe import jpeg_size + check(jpeg_size(thumb['bytes'])==(256,160),'actual JPEG dimensions mismatch') + if LAB>=2: + c.call('DELETE','/api/v1/auth/sessions/current',204,actor=alice) + c.call('GET','/api/v1/users/me',401,actor=alice) + c.call('DELETE','/api/v1/auth/sessions/current',401,actor=alice) + print('PASS: lab%d public API scenario; infrastructure and grading evidence remain separate.' % LAB) + +if __name__=='__main__': + run(main)