diff --git a/.dockerignore b/.dockerignore index bc16e556..2b710ee9 100644 --- a/.dockerignore +++ b/.dockerignore @@ -18,3 +18,4 @@ __pycache__ node_modules evidence .DS_Store +app/messenger diff --git a/.env.example b/.env.example index d99d26a2..53b00b4a 100644 --- a/.env.example +++ b/.env.example @@ -7,7 +7,7 @@ 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 +SESSION_STORE=valkey CACHE_URL_FILE=/run/secrets/cache_url API_REPLICAS=2 IDEMPOTENCY_TTL_SECONDS=86400 @@ -18,3 +18,17 @@ 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 +# Загрузок на одну реплику одновременно; сверх него API отвечает 429. Определяет объём диска под +# временные файлы: не больше MAX_CONCURRENT_UPLOADS x MAX_UPLOAD_BYTES. +MAX_CONCURRENT_UPLOADS=16 +# Очиститель объектов S3 без метаданных. Grace period не меньше 60 с: моложе может быть идущая загрузка. +JANITOR_GRACE_SECONDS=3600 +JANITOR_INTERVAL_SECONDS=600 +JANITOR_MAX_DELETES=1000 +JANITOR_DRY_RUN=false + +# Host used in direct-upload signatures (local development). +S3_PUBLIC_ENDPOINT=http://127.0.0.1:19090 + +# Maximum internal SeaweedFS volumes; existing data is preserved on restart. +S3_MAX_VOLUMES=64 diff --git a/.gitignore b/.gitignore index b5a71896..941db38c 100644 --- a/.gitignore +++ b/.gitignore @@ -14,6 +14,7 @@ volumes/ data/ backups/ # Runtime/build artifacts +/app/messenger .venv/ __pycache__/ *.py[cod] diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..0c426880 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,119 @@ +# syntax=docker/dockerfile:1.7 + +# Многоэтапная сборка: компилятор и исходники остаются в промежуточных этапах, а в итоговые +# образы попадают только готовые файлы. Какой этап собрать, задаёт target в compose.yaml. +# Версии образов закреплены, чтобы сборка повторялась. + +# Этап 1: компиляция всех программ проекта. +FROM golang:1.26.10-alpine3.24 AS builder +WORKDIR /src + +# Сначала только списки зависимостей: при изменении кода их загрузка берётся из кэша Docker. +COPY app/go.mod app/go.sum ./ +RUN go mod download + +# Затем весь код. Лишнее отсекает .dockerignore. +COPY app/ ./ + +# Основной сервер API. CGO_ENABLED=0 — статический файл без зависимостей от системных библиотек, +# -s -w убирают отладочные данные и уменьшают размер, -trimpath убирает локальные пути из файла. +RUN CGO_ENABLED=0 GOOS=linux go build \ + -ldflags="-s -w" \ + -trimpath \ + -o /out/messenger ./cmd/messenger + +# Генератор нагрузки для проверок под нагрузкой. +RUN CGO_ENABLED=0 GOOS=linux go build \ + -ldflags="-s -w" \ + -trimpath \ + -o /out/loadgen ./cmd/loadgen + +# Одноразовая подготовка S3-bucket. +RUN CGO_ENABLED=0 GOOS=linux go build \ + -ldflags="-s -w" \ + -trimpath \ + -o /out/s3init ./cmd/s3init + +# Очиститель объектов без метаданных и проверка прав S3 мимо API. +RUN CGO_ENABLED=0 GOOS=linux go build \ + -ldflags="-s -w" \ + -trimpath \ + -o /out/janitor ./cmd/janitor +RUN CGO_ENABLED=0 GOOS=linux go build \ + -ldflags="-s -w" \ + -trimpath \ + -o /out/s3check ./cmd/s3check + +# Этап 2: сборка инструмента миграций goose. Версия закреплена, драйверы ненужных БД +# исключены тегами: нужен только PostgreSQL. +FROM golang:1.26.10-alpine3.24 AS goose-builder +RUN CGO_ENABLED=0 go install -trimpath -ldflags="-s -w" \ + -tags='no_clickhouse no_libsql no_mssql no_mysql no_sqlite3 no_vertica no_ydb' \ + github.com/pressly/goose/v3/cmd/goose@v3.26.0 + +# Образ одноразового сервиса migrate: только goose и файлы миграций. +# Адрес БД читается из секрета при запуске, поэтому в образ не попадает. +# exec заменяет оболочку на goose, и тот сам получает сигналы остановки. +FROM alpine:3.24.3 AS migrate +COPY --from=goose-builder /go/bin/goose /usr/local/bin/goose +COPY migrations /migrations +ENTRYPOINT ["/bin/sh", "-c", "exec goose -dir /migrations postgres \"$(cat \"$DATABASE_URL_FILE\")\" up"] + +# Образ генератора нагрузки (профиль bench). Работает не от root. +FROM alpine:3.24.3 AS loadgen +COPY --from=builder /out/loadgen /usr/local/bin/loadgen +USER nobody +ENTRYPOINT ["/usr/local/bin/loadgen"] + +# Образ одноразового сервиса s3-init. Credentials читаются из секретов при запуске. Работает не от root. +FROM alpine:3.24.3 AS s3init +COPY --from=builder /out/s3init /usr/local/bin/s3init +USER nobody +ENTRYPOINT ["/usr/local/bin/s3init"] + +# Образ очистителя. Работает не от root. +FROM alpine:3.24.3 AS janitor +COPY --from=builder /out/janitor /usr/local/bin/janitor +USER nobody +ENTRYPOINT ["/usr/local/bin/janitor"] + +# Образ проверки прав S3 (профиль tools). Работает не от root. +FROM alpine:3.24.3 AS s3check +COPY --from=builder /out/s3check /usr/local/bin/s3check +USER nobody +ENTRYPOINT ["/usr/local/bin/s3check"] + +# Итоговый образ API. Это последний этап, поэтому он собирается, когда target не указан. +# В нём нет ни компилятора, ни goose, ни файлов миграций: реплики не могут запускать их при старте. +FROM alpine:3.24.3 + +# Метка версии сборки: видна в образе и в окружении. По ней rolling update показывает смену версии. +ARG APP_BUILD=dev +ENV APP_VERSION=$APP_BUILD +LABEL org.opencontainers.image.version=$APP_BUILD + +# Корневые сертификаты и отдельный пользователь без прав: процесс работает не от root. +RUN apk add --no-cache ca-certificates && \ + addgroup -S app && \ + adduser -S -G app -H app + +WORKDIR /app + +# Из этапа сборки берётся только готовый файл. +COPY --from=builder /out/messenger /app/messenger + +# Все следующие команды и сам сервер выполняются от этого пользователя. +USER app + +# Документация порта. Наружу он не публикуется: снаружи доступен только LB. +EXPOSE 8080 +# Docker останавливает контейнер этим сигналом: приложение выводит себя из балансировки +# и завершает открытые запросы. +STOPSIGNAL SIGTERM + +# Проверка готовности для Docker (статус healthy). Трафик направляет не она, а собственные +# проверки LB. wget входит в alpine, отдельно его ставить не нужно. +HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \ + CMD wget --quiet --spider "http://127.0.0.1:${APP_PORT:-8080}/health/ready" || exit 1 + +ENTRYPOINT ["/app/messenger"] diff --git a/REPORT.md b/REPORT.md index 9ad2b84f..ac8c4df7 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,37 +1,102 @@ # Отчёт — лабораторная 4 -- Автор, группа: TODO -- Целевая оценка; выбранный трек 5, если нужен: TODO -- Commit/PR: TODO после публикации -- Использованные источники, библиотеки и помощь ИИ: TODO +- Автор, группа: Нурлыгаянова Екатерина, БПИ2302. +- Целевая оценка: **5, трек 1 — прямой upload**. +- Commit/PR: после публикации; проверки выполнялись на рабочем дереве. +- Источники: README задания и семантика `contracts/README.md`. Библиотеки: Echo, pgx, go-redis, minio-go, google/uuid; миграции goose. Помощь ИИ: Claude Code — исходная реализация, Codex — прямой upload, проверки и оформление отчёта. ## Запуск из чистого clone -TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. +Нужны Docker Compose и Python 3.9+. Образы закреплены: PostgreSQL 17.6, Valkey 8.1.3, SeaweedFS 4.00, HAProxy 3.2.9; Go 1.26 используется при сборке приложения. + +```sh +cp .env.example .env +sh scripts/init-secrets.sh +docker compose --env-file .env up -d --build --wait +make test BASE_URL=http://localhost:8080 +``` + +Миграции и подготовку приватного bucket выполняют одноразовые сервисы `migrate` и `s3-init`. Повторная подготовка не удаляет данные. Пароли и ключи создаются локально в `secrets/`, значения в отчёт не включены. + +Порт API задаётся через `API_PUBLISH_PORT`; на проверявшемся стенде использовался `18080`, по умолчанию — `8080`. Порты PostgreSQL и Valkey задаются через `POSTGRES_PORT` и `VALKEY_PORT`. Для прямого PUT открыт только S3-порт шлюза `127.0.0.1:19090`; подписываемый адрес задаёт `S3_PUBLIC_ENDPOINT`. + +```sh +# Проверки на уже запущенном стенде; для :18080 замените BASE_URL. +make check +python3 -m venv .venv +.venv/bin/pip install -r requirements-dev.txt +make validate PYTHON=.venv/bin/python +BASE_URL=http://localhost:8080 sh scripts/level3-evidence.sh +BASE_URL=http://localhost:8080 sh scripts/level4-evidence.sh +python3 student-tests/direct_upload.py --base-url http://localhost:8080 +(cd app && go test -count=1 -race ./...) +``` + +Скрипты уровней 3–4 временно останавливают сервисы и возвращают их. Для дополнительного замера JPEG 40 Мп нужен `.venv/bin/pip install pillow`. Вернуть остановленные сервисы можно через `docker compose up -d --wait`. + +Безопасная остановка: `docker compose stop`. Остановка с удалением контейнеров и сохранением томов: `docker compose down`. **Намеренное удаление учебных данных:** `docker compose down -v`. ## Архитектура и решения -TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab3, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. +Клиент → HAProxy → две реплики Go API → PostgreSQL, Valkey и приватный S3. PostgreSQL хранит пользователей, чаты, сообщения, метаданные вложений и ключи идемпотентности; Valkey — сессии; SeaweedFS — байты файлов. Из lab3 сохранены авторизация, балансировка, общие данные и идемпотентная отправка сообщений. Добавлены вложения, связи с сообщениями, S3 и очиститель. + +Обязательный proxy `POST /api/v1/chats/{chat_id}/attachments` принимает сырые PNG/JPEG. Проверяются доступ, filename, MIME, размер до 10 МиБ и число пикселей до 40 млн. Тело поступает потоком во временный файл; сначала сохраняется объект S3, затем метаданные. `201 ready` означает сохранение обеих частей. Download авторизован и возвращает исходные байты через API. + +При ошибке БД выполняется безопасная компенсация. Объекты без метаданных удаляет отдельный janitor после grace period: по умолчанию 3600 с, минимум 300 с. Ошибка проверки БД не считается отсутствием строки. API и очиститель используют разные ограниченные S3 credentials; служебные интерфейсы SeaweedFS из общей сети закрыты. + +**Прямой upload, трек 1:** + +1. `POST /api/v1/chats/{chat_id}/attachments/direct/init` с Bearer и JSON `{"filename":"a.png","content_type":"image/png","size_bytes":1234,"sha256":"<64 hex>"}` возвращает `url`, `headers`, `token`, `expires_in: 60`. +2. Клиент отправляет файл методом PUT непосредственно в S3 с полученными заголовками. Content-Length включён в подпись и должен совпадать с заявленным размером. +3. `POST /api/v1/chats/{chat_id}/attachments/direct/complete`, JSON `{"token":"..."}`, проверяет владельца, чат, фактический размер, SHA-256 и корректность изображения. После этого возвращается `201 Attachment`. + +Временный ключ — случайный UUID. HMAC-ticket связан с владельцем и чатом, действует 120 с и проверяется любой репликой. Готовая копия получает другой ключ: повторный PUT по старой ссылке её не меняет. Повторный complete возвращает прежнее вложение. Заброшенные временные объекты остаются без строки в БД и удаляются janitor; используется одиночный PUT, multipart-сессий нет. + +`MAX_UPLOAD_BYTES`, `MAX_IMAGE_PIXELS` и `MAX_CONCURRENT_UPLOADS` ограничивают загрузки; `JANITOR_*` управляют очисткой. Для небольшого стенда настроено выделение одного внутреннего тома SeaweedFS за раз; `S3_MAX_VOLUMES=64`. Обязательные `contracts/openapi.json`, публичные тесты и README задания сохранены без изменений. Прямой flow — отдельное расширение API. ## Доказательства критериев + | Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | | --- | --- | --- | --- | -| Публичный smoke | make test | TODO | TODO | -| Остальные пункты уровня 3 | TODO | TODO | TODO | -| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | -| Выбранный трек 5, если заявлен | TODO | TODO | TODO | - -TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. +| Контракт и обязательный API | `make check validate`, `openapi_contract.py --scenario smoke`, `go test -race ./...` | PASS; 14 обязательных операций, 37 обменов; исходный OpenAPI не изменён | [recheck.txt](evidence/recheck.txt) | +| Proxy, ready, checksum, сообщения с вложением | `make test`, `student-tests/attachments.py` | PASS; скачанные байты совпали, сообщение читает второй участник | [level3.txt](evidence/level3.txt), [recheck.txt](evidence/recheck.txt) | +| Ограничения PNG/JPEG, размера, пикселей и filename | `student-tests/attachments.py`, `memory_peak.py` | 10 МиБ принято; превышение размера/пикселей — 413; опасные имена — 400 | [level4.txt](evidence/level4.txt), [manual-checks.txt](evidence/manual-checks.txt) | +| Upload → остановка загрузившей реплики → download | `student-tests/upload_failover.py` | Для каждой из двух реплик: файл скачан через другую, SHA-256 совпал | [recheck.txt](evidence/recheck.txt) | +| Restart сохраняет файл, метаданные и сессию | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | PASS с прежним токеном; hook перезапускает API, LB, PostgreSQL, Valkey, S3 и его шлюз | [recheck.txt](evidence/recheck.txt) | +| Недоступность S3 | `student-tests/s3_outage.py` | Вложения — 503; метаданные и сообщения работают; после возврата файл совпал | [recheck.txt](evidence/recheck.txt) | +| Повреждение, подмена MIME, чужое вложение/чат | `openapi_contract.py --scenario attachments` | PASS: 415/404/400 по сценарию; 58 обменов соответствуют OpenAPI | [recheck.txt](evidence/recheck.txt) | +| Компенсация, обрыв, безопасная очистка | `student-tests/orphans.py`, Go-тесты janitor | Старый полный прогон PASS; в последнем повторе компенсация PASS, дальнейшая проверка прервана | [level4.txt](evidence/level4.txt), [recheck.txt](evidence/recheck.txt) | +| ≥10 параллельных загрузок, ограниченная RAM | `student-tests/memory_concurrent.py`, `memory_peak.py` | В старом прогоне 16/24 загрузки без OOM и рестартов | [level4.txt](evidence/level4.txt), [memory-peak.txt](evidence/memory-peak.txt) | +| Bootstrap, отдельные credentials, private bucket, закрытые консоли | Двойной `s3-init`, `s3check`, проверка сетей/портов | PASS в повторе после исправления лимита томов | [recheck.txt](evidence/recheck.txt) | +| Трек 1: подпись, принадлежность, checksum, незавершённые загрузки | `student-tests/direct_upload.py`, Go-тест `TestDirectSizeExpiryAndCleanup` | Негативные сценарии PASS; истёкший PUT — 403, complete — 409; очистка проверена с продвижением часов | [level5-direct.txt](evidence/level5-direct.txt), [recheck.txt](evidence/recheck.txt) | ## Эксперименты и отказы -TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. +**Гипотеза трека 1:** прямой PUT уменьшит трафик и RAM API. Стенд: Darwin arm64, Docker; две API-реплики, каждой выделены 1 CPU и 1 ГиБ RAM. Один последовательный прогон без отдельного прогрева. Один маленький PNG дополнен до 1 и 8 МиБ: влияние размера тела отделено от затрат на декодирование. RX/TX суммируются по репликам; RAM — максимум `anon` среди реплик при опросе каждые 0,2 с. -| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | +| Размер | Режим | RX API, байт | TX API, байт | RAM до → максимум, МиБ | +| --- | --- | ---: | ---: | ---: | +| 1 МиБ | proxy | 1 057 362 | 1 060 683 | 43,50 → 43,50 | +| 1 МиБ | direct | 1 058 909 | 1 061 230 | 43,50 → 43,52 | +| 8 МиБ | proxy | 8 450 669 | 8 436 929 | 43,51 → 43,56 | +| 8 МиБ | direct | 8 433 327 | 8 431 340 | 43,56 → 43,59 | + +Гипотеза не подтвердилась для суммарного трафика: complete читает оригинал из S3 и сохраняет проверенную копию, поэтому через API проходит примерно `2 × размер файла`. RAM почти одинакова: proxy уже потоковый. Малые различия — шум и служебный трафик; опрос может пропустить короткий пик. RPS и p95 этим экспериментом не измерялись. + +В старом нагрузочном прогоне выполнены три раунда по 16 и 24 параллельных PNG около 10 МиБ: 48/72 успешные загрузки, пик `anon` 51/54 МиБ, без OOM. Для JPEG 40 Мп пик `anon` достигал 794 МиБ; из 24 запросов 23 получили 201, один — 429. Эти числа относятся к версии до добавления прямого flow. + +| Воздействие | Что ожидаем | Что наблюдали | Восстановление / потеря данных | | --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | +| Остановка одной API-реплики | Обслуживание другой | Failover PASS; запись восстановилась за 3,19 с | Подтверждённые сообщения и файл сохранены | +| Остановка S3 | Ошибки вложений, остальное API работает | Upload 503 за 8,01 с; download 503 за 5,42 с | Download восстановился за 23,7 с после старта; файл совпал | +| Блокировка INSERT после PUT | 503 и компенсация | 503 за 3 с; число объектов/строк не выросло | Лишний объект удалён | +| SIGKILL между PUT и INSERT | Временный orphan, затем очистка | В последнем повторе orphan найден и оставлен свежим | Прогон остановлен до окончания grace period | +| Подмена token/ключа/размера/checksum | Отказ без готового вложения | 400/403 по сценарию; неверное изображение — 415 | Готовая копия не меняется повторным PUT | +| Истечение подписи/ticket | PUT/complete отклоняются | 403 после 60 с и 409 после 120 с | Метаданные незавершённой загрузки не создаются | ## Ограничения и следующие шаги -TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. +Подтверждены остановка одной API-реплики и штатный перезапуск хранилищ. PostgreSQL, Valkey, S3 и LB существуют в одном экземпляре: отказ всего хоста не выдерживается. Потеря питания и заполнение диска не проверены. Очиститель удаляет объекты без метаданных, но не восстанавливает потерянные байты для существующей строки. + + diff --git a/app/cmd/janitor/main.go b/app/cmd/janitor/main.go new file mode 100644 index 00000000..c632ae87 --- /dev/null +++ b/app/cmd/janitor/main.go @@ -0,0 +1,104 @@ +// janitor — очиститель объектов S3 без метаданных. Отдельный сервис со своими credentials S3: API +// не имеет права на листинг, а очиститель не имеет права читать содержимое файлов. +// +// Постоянная работа: janitor. Один проход: janitor -once. Только отчёт: janitor -once -dry-run. +// Настройки: JANITOR_GRACE_SECONDS, JANITOR_INTERVAL_SECONDS, JANITOR_MAX_DELETES, JANITOR_DRY_RUN. +package main + +import ( + "context" + "encoding/json" + "flag" + "fmt" + "log/slog" + "os" + "os/signal" + "syscall" + "time" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/config" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/janitor" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/logging" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/objectstore" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/service" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store/db" +) + +// passTimeout ограничивает один проход: зависший S3 не должен останавливать очиститель навсегда. +const passTimeout = 10 * time.Minute + +func main() { + once := flag.Bool("once", false, "выполнить один проход и завершиться") + dryRun := flag.Bool("dry-run", false, "только отчёт, ничего не удалять") + flag.Parse() + if err := run(*once, *dryRun); err != nil { + fmt.Fprintln(os.Stderr, "janitor:", err) + os.Exit(1) + } +} + +func run(once, dryRun bool) error { + cfg, err := config.Load() + if err != nil { + return err + } + logger, err := logging.New(cfg.Logger.Level, cfg.Env, cfg.Version) + if err != nil { + return err + } + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + + pool, err := db.Connect(ctx, cfg.Database) + if err != nil { + return err + } + storage := db.New(pool, time.Duration(cfg.Database.QueryTimeoutMs)*time.Millisecond) + defer storage.Close() + objects, err := objectstore.NewS3(cfg.S3) + if err != nil { + return err + } + + opts := janitor.Options{ + Prefix: service.ObjectKeyPrefix, + Grace: time.Duration(cfg.Janitor.GraceSeconds) * time.Second, + MaxDeletes: cfg.Janitor.MaxDeletes, + DryRun: cfg.Janitor.DryRun || dryRun, + Now: time.Now, + Logger: logger, + } + pass := func() error { + passCtx, cancel := context.WithTimeout(ctx, passTimeout) + defer cancel() + report, err := janitor.Run(passCtx, objects, storage.Attachments, opts) + logger.Info("janitor pass", slog.Any("report", report), slog.Duration("elapsed", report.Elapsed), slog.Any("err", err)) + if once { + // Машиночитаемый итог для проверок: stdout содержит и этот объект, и строки журнала. + if line, jsonErr := json.Marshal(struct { + Report janitor.Report `json:"janitor_report"` + }{report}); jsonErr == nil { + fmt.Println(string(line)) + } + } + return err + } + if once { + return pass() + } + + // Первый проход сразу: после простоя очистителя мусор не ждёт ещё один интервал. + ticker := time.NewTicker(time.Duration(cfg.Janitor.IntervalSeconds) * time.Second) + defer ticker.Stop() + for { + // Ошибка прохода не фатальна: S3 или БД вернутся, следующий проход повторит работу. + if err := pass(); err != nil { + logger.Warn("janitor pass failed", slog.Any("err", err)) + } + select { + case <-ctx.Done(): + return nil + case <-ticker.C: + } + } +} diff --git a/app/cmd/loadgen/main.go b/app/cmd/loadgen/main.go new file mode 100644 index 00000000..c3549fc4 --- /dev/null +++ b/app/cmd/loadgen/main.go @@ -0,0 +1,601 @@ +// loadgen — closed-loop генератор нагрузки для экспериментов с репликами. +// +// Смесь чтения истории и записи сообщений. Неподтверждённая запись повторяется с тем же +// Idempotency-Key, как у настоящего клиента. После прогона вся история сверяется с +// подтверждёнными сообщениями. Closed-loop занижает задержки при перегрузке (coordinated +// omission), поэтому результат показывает пропускную способность, а не задержку при заданной +// интенсивности. Токены и пароли не печатает. +// +// Запуск из корня проекта при поднятом стенде: +// +// docker compose --env-file .env --profile bench run --rm -T loadgen -duration 20s -concurrency 16 +// +// Этапы: подготовка данных, прогрев, замер, сверка истории, запись результата. +// Код выхода ненулевой, если сверка нашла потери или дубли либо не смогла прочитать историю. +package main + +import ( + "bytes" + "context" + "crypto/rand" + "encoding/hex" + "encoding/json" + "flag" + "fmt" + "io" + mathrand "math/rand/v2" + "net/http" + "net/url" + "os" + "slices" + "strconv" + "sync" + "time" +) + +// options — параметры запуска из флагов командной строки. +type options struct { + baseURL string + duration time.Duration + warmup time.Duration + concurrency int + writeShare float64 + chats int + seed int + timeout time.Duration + label string + out string +} + +// actor — один клиент API: токен его сессии и его чат. Токен хранится только в памяти. +type actor struct { + token string + chatID string +} + +// confirmed — запись, на которую сервер ответил 201. После замера она обязана быть в истории: +// chat — индекс чата, id — ID сообщения, text — уникальный текст для поиска дублей. +type confirmed struct { + chat int + id string + text string +} + +// workerStats заполняется одной горутиной, поэтому без блокировок. +// Поля: задержки успешных чтений и записей; ошибки по видам (код ответа или net); +// записи, подтверждённые после повтора; запросы по репликам; успехи и ошибки по секундам; +// время каждой ошибки; подтверждённые записи. +type workerStats struct { + reads, writes []time.Duration + errors map[string]int + retried int + instances map[string]int + secOK, secErr map[int]int + errTimes []time.Duration + confirmed []confirmed +} + +// main разбирает флаги и запускает прогон. Значения по умолчанию рассчитаны на запуск в сети Docker. +func main() { + var o options + flag.StringVar(&o.baseURL, "base-url", "http://lb:8080", "адрес балансировщика") + flag.DurationVar(&o.duration, "duration", 30*time.Second, "длительность замера") + flag.DurationVar(&o.warmup, "warmup", 5*time.Second, "прогрев, не входит в замер") + flag.IntVar(&o.concurrency, "concurrency", 16, "число клиентов closed-loop") + flag.Float64Var(&o.writeShare, "write-share", 0.2, "доля записей") + flag.IntVar(&o.chats, "chats", 8, "число пар пользователь+чат") + flag.IntVar(&o.seed, "seed", 100, "начальных сообщений на чат") + flag.DurationVar(&o.timeout, "timeout", 5*time.Second, "таймаут запроса") + flag.StringVar(&o.label, "label", "", "метка прогона") + flag.StringVar(&o.out, "out", "", "файл для JSON-результата") + flag.Parse() + + if err := run(o); err != nil { + fmt.Fprintln(os.Stderr, "loadgen:", err) + os.Exit(1) + } +} + +// run выполняет прогон целиком и возвращает ошибку, если проверка истории не пройдена. +func run(o options) error { + // Один общий клиент на всех. Запас простаивающих соединений нужен, чтобы клиенты повторно + // использовали их: иначе замер включал бы постоянную установку новых соединений. + client := &http.Client{ + Timeout: o.timeout, + Transport: &http.Transport{ + MaxIdleConns: o.concurrency * 2, + MaxIdleConnsPerHost: o.concurrency * 2, + IdleConnTimeout: 30 * time.Second, + }, + } + // Подготовка до начала отсчёта: в замер не входит. + actors, err := setup(client, o) + if err != nil { + return fmt.Errorf("setup: %w", err) + } + + // Границы замера. Клиенты работают и в прогреве, но запросы до measureFrom не учитываются. + start := time.Now() + measureFrom := start.Add(o.warmup) + end := measureFrom.Add(o.duration) + // Скрипты отказов ждут эту строку, чтобы привязать действия ко времени замера. + go func() { + time.Sleep(o.warmup) + fmt.Printf("measure_start unix=%d\n", time.Now().Unix()) + }() + + // У каждого клиента своя статистика и своя горутина. Общие данные появляются только после wg.Wait. + stats := make([]*workerStats, o.concurrency) + var wg sync.WaitGroup + for i := range o.concurrency { + stats[i] = newWorkerStats() + wg.Add(1) + go func() { + defer wg.Done() + work(client, o, i, actors, measureFrom, end, stats[i]) + }() + } + wg.Wait() + + // Сверка идёт уже после нагрузки, поэтому на RPS она не влияет. + res := summarize(o, stats) + res.Verify = verify(client, o, actors, stats) + if err := writeResult(o, res); err != nil { + return err + } + // Результат записан и при неудаче: так можно разобрать, что именно пошло не так. + if res.Verify.Error != "" || res.Verify.Lost > 0 || res.Verify.DuplicateIDs > 0 || res.Verify.DuplicateTexts > 0 { + return fmt.Errorf("проверка истории не пройдена: %+v", res.Verify) + } + return nil +} + +// newWorkerStats создаёт пустую статистику клиента. +func newWorkerStats() *workerStats { + return &workerStats{ + errors: map[string]int{}, + instances: map[string]int{}, + secOK: map[int]int{}, + secErr: map[int]int{}, + } +} + +// work — цикл одного клиента до конца замера (closed-loop): следующий запрос уходит только +// после ответа на предыдущий. Клиенты равномерно распределены по чатам. +func work(client *http.Client, o options, worker int, actors []actor, from, end time.Time, st *workerStats) { + chat := worker % len(actors) + a := actors[chat] + path := "/api/v1/chats/" + a.chatID + "/messages" + // Свой генератор у каждого клиента: общий потребовал бы блокировки. + rng := mathrand.New(mathrand.NewPCG(uint64(worker), uint64(time.Now().UnixNano()))) + + // observe учитывает результат одного запроса и возвращает true, если он успешен. В замер + // входит только запрос, начатый после прогрева и завершившийся до конца замера. lat — куда + // записать задержку успешного запроса, want — ожидаемый код ответа. + observe := func(began time.Time, status int, instance string, err error, want int, lat *[]time.Duration) bool { + now := time.Now() + measured := !began.Before(from) && now.Before(end) + // Номер секунды замера: из него строится посекундная шкала. + sec := int(now.Sub(from) / time.Second) + if err == nil && status == want { + if measured { + *lat = append(*lat, now.Sub(began)) + st.instances[instance]++ + st.secOK[sec]++ + } + return true + } + if measured { + // net — ответа не было вообще (обрыв, таймаут), иначе вид ошибки — код ответа. + kind := "net" + if err == nil { + kind = strconv.Itoa(status) + } + st.errors[kind]++ + st.secErr[sec]++ + st.errTimes = append(st.errTimes, now.Sub(from)) + } + return false + } + + for seq := 0; time.Now().Before(end); seq++ { + // Чтение первой страницы истории. После ошибки короткая пауза, чтобы не долбить сервер в цикле. + if rng.Float64() >= o.writeShare { + began := time.Now() + status, inst, _, err := do(client, o, http.MethodGet, path+"?limit=50", a.token, "", nil) + if !observe(began, status, inst, err, http.StatusOK, &st.reads) { + time.Sleep(50 * time.Millisecond) + } + continue + } + // Запись: новый ключ идемпотентности и уникальный текст, по которому видны дубли. + key := randomHex(16) + text := fmt.Sprintf("w-%d-%d-%s", worker, seq, key[:8]) + // Неопределённый результат повторяется с исходным ключом и телом. + // Цикл повторов. При обрыве клиент не знает, записал ли сервер сообщение, поэтому повторяет + // с теми же ключом и текстом: сервер должен вернуть то же сообщение, а не создать новое. + for attempt := 0; time.Now().Before(end); attempt++ { + began := time.Now() + status, inst, body, err := do(client, o, http.MethodPost, path, a.token, key, map[string]string{"text": text}) + if observe(began, status, inst, err, http.StatusCreated, &st.writes) { + var m struct { + ID string `json:"id"` + } + if json.Unmarshal(body, &m) == nil { + st.confirmed = append(st.confirmed, confirmed{chat: chat, id: m.ID, text: text}) + } + // Запись подтвердилась только с повтора: это видно в результате. + if attempt > 0 { + st.retried++ + } + break + } + time.Sleep(100 * time.Millisecond) + } + } +} + +// do выполняет один HTTP-запрос с таймаутом и возвращает код, реплику из X-Instance-Id, тело +// и ошибку сети. payload кодируется в JSON; пустые token и key не добавляют заголовки. +func do(client *http.Client, o options, method, path, token, key string, payload any) (int, string, []byte, error) { + var body io.Reader + if payload != nil { + b, err := json.Marshal(payload) + if err != nil { + return 0, "", nil, err + } + body = bytes.NewReader(b) + } + ctx, cancel := context.WithTimeout(context.Background(), o.timeout) + defer cancel() + req, err := http.NewRequestWithContext(ctx, method, o.baseURL+path, body) + if err != nil { + return 0, "", nil, err + } + if payload != nil { + req.Header.Set("Content-Type", "application/json") + } + if token != "" { + req.Header.Set("Authorization", "Bearer "+token) + } + if key != "" { + req.Header.Set("Idempotency-Key", key) + } + resp, err := client.Do(req) + if err != nil { + return 0, "", nil, err + } + defer resp.Body.Close() + // Тело читается полностью: иначе соединение нельзя использовать повторно. + data, err := io.ReadAll(resp.Body) + if err != nil { + return 0, "", nil, err + } + return resp.StatusCode, resp.Header.Get("X-Instance-Id"), data, nil +} + +// setup параллельно создаёт пользователей и чаты для всех участников нагрузки. +func setup(client *http.Client, o options) ([]actor, error) { + actors := make([]actor, o.chats) + errs := make([]error, o.chats) + var wg sync.WaitGroup + for i := range o.chats { + wg.Add(1) + go func() { + defer wg.Done() + actors[i], errs[i] = setupActor(client, o) + }() + } + wg.Wait() + for _, err := range errs { + if err != nil { + return nil, err + } + } + return actors, nil +} + +// setupActor создаёт одного участника: пользователь, вход, чат и начальные сообщения. +// Имена и пароли случайные и нигде не печатаются. +func setupActor(client *http.Client, o options) (actor, error) { + username, password := "lg_"+randomHex(8), "T3st-"+randomHex(16) + status, _, body, err := do(client, o, http.MethodPost, "/api/v1/users", "", "", + map[string]string{"username": username, "display_name": "Load", "password": password}) + if err != nil || status != http.StatusCreated { + return actor{}, fmt.Errorf("create user: status %d: %v", status, err) + } + var user struct { + ID string `json:"id"` + } + if err := json.Unmarshal(body, &user); err != nil { + return actor{}, err + } + + // Вход выполняется через Basic: пользователь получает токен сессии. + req, err := http.NewRequest(http.MethodPost, o.baseURL+"/api/v1/auth/sessions", nil) + if err != nil { + return actor{}, err + } + req.SetBasicAuth(username, password) + resp, err := client.Do(req) + if err != nil { + return actor{}, fmt.Errorf("login: %w", err) + } + defer resp.Body.Close() + var session struct { + Token string `json:"token"` + } + if resp.StatusCode != http.StatusCreated { + return actor{}, fmt.Errorf("login: status %d", resp.StatusCode) + } + if err := json.NewDecoder(resp.Body).Decode(&session); err != nil { + return actor{}, err + } + + status, _, body, err = do(client, o, http.MethodPost, "/api/v1/chats", session.Token, "", + map[string]any{"title": "Load", "member_ids": []string{user.ID}}) + if err != nil || status != http.StatusCreated { + return actor{}, fmt.Errorf("create chat: status %d: %v", status, err) + } + var chat struct { + ID string `json:"id"` + } + if err := json.Unmarshal(body, &chat); err != nil { + return actor{}, err + } + + // Начальные сообщения, чтобы чтение первой страницы возвращало полноценный ответ. + for i := range o.seed { + status, _, _, err := do(client, o, http.MethodPost, "/api/v1/chats/"+chat.ID+"/messages", session.Token, + randomHex(16), map[string]string{"text": fmt.Sprintf("seed-%d", i)}) + if err != nil || status != http.StatusCreated { + return actor{}, fmt.Errorf("seed: status %d: %v", status, err) + } + } + return actor{token: session.Token, chatID: chat.ID}, nil +} + +// verifyResult — итог сверки истории с подтверждёнными записями. +type verifyResult struct { + Confirmed int `json:"confirmed"` + Lost int `json:"lost"` + DuplicateIDs int `json:"duplicate_ids"` + DuplicateTexts int `json:"duplicate_texts"` + Error string `json:"error,omitempty"` +} + +// verify читает всю историю каждого чата и сверяет её с подтверждёнными записями. +// Потеря — подтверждённого ID нет в истории. Дубль — ID или текст встретился дважды. +func verify(client *http.Client, o options, actors []actor, stats []*workerStats) verifyResult { + var res verifyResult + // Какие ID должны быть в каждом чате. + wanted := make([]map[string]bool, len(actors)) + for i := range wanted { + wanted[i] = map[string]bool{} + } + for _, st := range stats { + for _, c := range st.confirmed { + wanted[c.chat][c.id] = true + res.Confirmed++ + } + } + // История читается постранично по курсору, с запасом на временные ошибки. + for chat, a := range actors { + ids, texts := map[string]bool{}, map[string]bool{} + cursor := "" + for { + q := "?limit=100" + if cursor != "" { + q += "&cursor=" + url.QueryEscape(cursor) + } + status, _, body, err := getWithRetry(client, o, "/api/v1/chats/"+a.chatID+"/messages"+q, a.token) + if err != nil || status != http.StatusOK { + res.Error = fmt.Sprintf("read history: status %d: %v", status, err) + return res + } + var page struct { + Items []struct { + ID string `json:"id"` + Text string `json:"text"` + } `json:"items"` + NextCursor *string `json:"next_cursor"` + } + if err := json.Unmarshal(body, &page); err != nil { + res.Error = "decode history: " + err.Error() + return res + } + for _, m := range page.Items { + if ids[m.ID] { + res.DuplicateIDs++ + } + ids[m.ID] = true + if texts[m.Text] { + res.DuplicateTexts++ + } + texts[m.Text] = true + } + if page.NextCursor == nil { + break + } + cursor = *page.NextCursor + } + // Всё, что было подтверждено, должно найтись. + for id := range wanted[chat] { + if !ids[id] { + res.Lost++ + } + } + } + return res +} + +// getWithRetry повторяет чтение до 5 раз: сразу после отказа реплики сверка не должна падать +// из-за временной ошибки. +func getWithRetry(client *http.Client, o options, path, token string) (int, string, []byte, error) { + var ( + status int + inst string + body []byte + err error + ) + for range 5 { + status, inst, body, err = do(client, o, http.MethodGet, path, token, "", nil) + if err == nil && status == http.StatusOK { + break + } + time.Sleep(500 * time.Millisecond) + } + return status, inst, body, err +} + +// latency — задержки успешных запросов одного вида, в миллисекундах. +type latency struct { + Count int `json:"count"` + P50 float64 `json:"p50_ms"` + P95 float64 `json:"p95_ms"` + P99 float64 `json:"p99_ms"` +} + +// incident — эпизод ошибок: начало, длительность и количество. +type incident struct { + StartS float64 `json:"start_s"` + DurationS float64 `json:"duration_s"` + Errors int `json:"errors"` +} + +// second — одна секунда шкалы: успехи и ошибки. +type second struct { + T int `json:"t"` + OK int `json:"ok"` + Err int `json:"err"` +} + +// result — итог прогона. Он записывается в JSON и разбирается скриптами сводок. +type result struct { + Label string `json:"label"` + Concurrency int `json:"concurrency"` + WriteShare float64 `json:"write_share"` + Chats int `json:"chats"` + Seed int `json:"seed_per_chat"` + DurationS float64 `json:"duration_s"` + WarmupS float64 `json:"warmup_s"` + RPS float64 `json:"successful_rps"` + ReadRPS float64 `json:"read_rps"` + WriteRPS float64 `json:"write_rps"` + ErrorShare float64 `json:"error_share"` + Errors map[string]int `json:"errors"` + RetriedWrites int `json:"writes_confirmed_after_retry"` + Read latency `json:"read"` + Write latency `json:"write"` + Instances map[string]int `json:"requests_per_instance"` + Incidents []incident `json:"error_incidents"` + SecondsNoOK int `json:"seconds_without_success"` + Verify verifyResult `json:"verify"` + Timeline []second `json:"timeline,omitempty"` +} + +// summarize объединяет статистику всех клиентов и считает показатели замера. +func summarize(o options, stats []*workerStats) result { + res := result{ + Label: o.label, Concurrency: o.concurrency, WriteShare: o.writeShare, Chats: o.chats, Seed: o.seed, + DurationS: o.duration.Seconds(), WarmupS: o.warmup.Seconds(), + Errors: map[string]int{}, Instances: map[string]int{}, + } + var reads, writes, errTimes []time.Duration + secOK, secErr := map[int]int{}, map[int]int{} + for _, st := range stats { + reads = append(reads, st.reads...) + writes = append(writes, st.writes...) + errTimes = append(errTimes, st.errTimes...) + res.RetriedWrites += st.retried + for k, v := range st.errors { + res.Errors[k] += v + } + for k, v := range st.instances { + res.Instances[k] += v + } + for k, v := range st.secOK { + secOK[k] += v + } + for k, v := range st.secErr { + secErr[k] += v + } + } + res.Read, res.Write = percentiles(reads), percentiles(writes) + secs := o.duration.Seconds() + // RPS учитывает только успешные запросы. + res.ReadRPS = float64(len(reads)) / secs + res.WriteRPS = float64(len(writes)) / secs + res.RPS = res.ReadRPS + res.WriteRPS + if total := len(reads) + len(writes) + len(errTimes); total > 0 { + res.ErrorShare = float64(len(errTimes)) / float64(total) + } + res.Incidents = incidents(errTimes, time.Second) + // Шкала за все секунды, включая пустые: секунда без успехов — признак полной недоступности. + for t := range int(secs) { + res.Timeline = append(res.Timeline, second{T: t, OK: secOK[t], Err: secErr[t]}) + if secOK[t] == 0 { + res.SecondsNoOK++ + } + } + return res +} + +// percentiles считает p50, p95, p99 по отсортированным задержкам. Метод ближайшего ранга: +// значение берётся из данных, без интерполяции. +func percentiles(d []time.Duration) latency { + if len(d) == 0 { + return latency{} + } + slices.Sort(d) + at := func(p float64) float64 { + i := min(int(float64(len(d))*p), len(d)-1) + return float64(d[i].Microseconds()) / 1000 + } + return latency{Count: len(d), P50: at(0.50), P95: at(0.95), P99: at(0.99)} +} + +// incidents объединяет ошибки с разрывом меньше gap в один эпизод. +func incidents(times []time.Duration, gap time.Duration) []incident { + times = slices.Clone(times) + slices.Sort(times) + out := []incident{} + for i, t := range times { + if i == 0 || t-times[i-1] >= gap { + out = append(out, incident{StartS: t.Seconds()}) + } + last := &out[len(out)-1] + last.Errors++ + last.DurationS = t.Seconds() - last.StartS + } + return out +} + +// writeResult пишет полный JSON в файл, а краткую версию без шкалы печатает на экран. +func writeResult(o options, res result) error { + full, err := json.MarshalIndent(res, "", " ") + if err != nil { + return err + } + if o.out != "" { + if err := os.WriteFile(o.out, append(full, '\n'), 0o644); err != nil { + return err + } + } + res.Timeline = nil + brief, err := json.Marshal(res) + if err != nil { + return err + } + fmt.Println(string(brief)) + return nil +} + +// randomHex возвращает n случайных байт в hex. Без случайности нет смысла продолжать, поэтому panic. +func randomHex(n int) string { + b := make([]byte, n) + if _, err := rand.Read(b); err != nil { + panic(err) + } + return hex.EncodeToString(b) +} diff --git a/app/cmd/loadgen/main_test.go b/app/cmd/loadgen/main_test.go new file mode 100644 index 00000000..b6c92f42 --- /dev/null +++ b/app/cmd/loadgen/main_test.go @@ -0,0 +1,31 @@ +package main + +import ( + "testing" + "time" +) + +func TestIncidentsGroupsByGap(t *testing.T) { + got := incidents([]time.Duration{ + 5 * time.Second, + 1 * time.Second, + 1500 * time.Millisecond, + }, time.Second) + if len(got) != 2 { + t.Fatalf("incidents = %+v, want 2", got) + } + if got[0].Errors != 2 || got[0].DurationS != 0.5 || got[1].Errors != 1 || got[1].DurationS != 0 { + t.Errorf("incidents = %+v", got) + } +} + +func TestPercentiles(t *testing.T) { + d := make([]time.Duration, 100) + for i := range d { + d[i] = time.Duration(100-i) * time.Millisecond + } + got := percentiles(d) + if got.Count != 100 || got.P50 != 51 || got.P95 != 96 || got.P99 != 100 { + t.Errorf("percentiles = %+v", got) + } +} diff --git a/app/cmd/messenger/main.go b/app/cmd/messenger/main.go new file mode 100644 index 00000000..4456fcf3 --- /dev/null +++ b/app/cmd/messenger/main.go @@ -0,0 +1,207 @@ +// messenger — сервер API мессенджера, один процесс одной реплики. Своего состояния у реплики нет: +// данные лежат в PostgreSQL, сессии в Valkey, поэтому реплик может быть несколько. +// +// Здесь только сборка: загрузка настроек, подключения, создание сервисов, запуск HTTP-сервера и +// штатное завершение по SIGTERM. Логика находится в internal. +package main + +import ( + "context" + "fmt" + "log/slog" + "os" + "os/signal" + "runtime" + "syscall" + "time" + + httpapi "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/cache" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/config" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/logging" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/objectstore" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/password" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/service" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/session" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store/db" +) + +// main запускает сервер и завершается после сигнала остановки. При ошибке запуска код выхода 1. +// os.Exit не выполняет defer, поэтому перед ним подключение к БД закрывается явно. +func main() { + // Настройки из окружения. Логгера ещё нет, поэтому ошибка идёт прямо в stderr. + cfg, err := config.Load() + if err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } + + logger, err := logging.New(cfg.Logger.Level, cfg.Env, cfg.Version) + if err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } + slog.SetDefault(logger) + + // Пул подключений к PostgreSQL. Без БД реплика работать не может и завершается: Docker её перезапустит. + pool, err := db.Connect(context.Background(), cfg.Database) + if err != nil { + logger.Error("database connect failed", slog.Any("err", err)) + os.Exit(1) + } + // Хранилище с таймаутом запросов на все обращения к БД. + storage := db.New(pool, time.Duration(cfg.Database.QueryTimeoutMs)*time.Millisecond) + defer storage.Close() + + // Общее хранилище сессий в Valkey: токен, выданный одной репликой, принимают все остальные. + sessClient, err := session.Connect(context.Background(), cfg.Cache) + if err != nil { + logger.Error("session store connect failed", slog.Any("err", err)) + storage.Close() + os.Exit(1) + } + defer sessClient.Close() + sessions := session.NewValkey(sessClient) + + // Хеширование паролей. Оно тяжёлое, поэтому одновременных вычислений не больше числа ядер и не больше 4. + hasher := password.NewHasher(password.Default, min(runtime.GOMAXPROCS(0), 4)) + + auth, err := service.NewAuth(storage, sessions, hasher, time.Duration(cfg.Session.TTLSeconds)*time.Second) + if err != nil { + logger.Error("auth init failed", slog.Any("err", err)) + storage.Close() + os.Exit(1) + } + + // История сообщений по умолчанию читается прямо из БД. Кэш подключается, только если он включён, + // и заменяет собой источник: остальной код разницы не видит. + var messages store.MessageStore = storage + if cfg.HistoryCache.Mode != cache.ModeOff { + hcClient, err := cache.Connect(cfg.HistoryCache) + if err != nil { + logger.Error("history cache config failed", slog.Any("err", err)) + storage.Close() + os.Exit(1) + } + defer hcClient.Close() + hc := cache.New(storage.Messages, hcClient, cache.Options{ + Mode: cfg.HistoryCache.Mode, + Outbox: storage.Messages, + PageTTL: time.Duration(cfg.HistoryCache.PageTTLSeconds) * time.Second, + FillDelay: time.Duration(cfg.HistoryCache.FillDelayMs) * time.Millisecond, + Logger: logger, + }) + defer hc.Close() + messages = hc + } + logger.Info("history cache", slog.String("mode", cfg.HistoryCache.Mode)) + + // Клиент S3 не обращается к серверу при создании: bucket готовит сервис s3-init. + objects, err := objectstore.NewS3(cfg.S3) + if err != nil { + logger.Error("object store config failed", slog.Any("err", err)) + storage.Close() + os.Exit(1) + } + + // Сборка HTTP-сервера из готовых зависимостей. + srv := httpapi.NewServer(httpapi.Deps{ + Config: cfg, + Logger: logger, + Store: storage, + Auth: auth, + Users: service.NewUsers(storage, hasher), + Chats: service.NewChats(storage), + Messages: service.NewMessages(messages), + Attachments: service.NewAttachments(storage, objects, service.AttachmentLimits{ + MaxUploadBytes: cfg.Attachments.MaxUploadBytes, + MaxImagePixels: cfg.Attachments.MaxImagePixels, + MaxConcurrentUploads: cfg.Attachments.MaxConcurrentUploads, + }, logger), + // Readiness: реплика готова, только если доступны и БД, и Valkey. Иначе LB выведет её из + // работы. Схему БД эта проверка не проверяет. S3 сюда намеренно не входит: без него + // недоступны только вложения (503), а пользователи и текстовые сообщения продолжают работать. + // Если бы S3 входил в readiness, его отказ снял бы с балансировки все реплики сразу. + Ready: func(ctx context.Context) error { + if err := storage.Ping(ctx); err != nil { + return err + } + return sessions.Ping(ctx) + }, + }) + + // ctx отменяется при SIGTERM (docker stop) или Ctrl+C: это начало штатного завершения. + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + + // Фоновая очистка старых ключей идемпотентности. Останавливается вместе с ctx. + go purgeIdempotencyKeys(ctx, storage, time.Duration(cfg.Idempotency.TTLSeconds)*time.Second, logger) + + // Сервер блокирует поток до остановки, поэтому запускается отдельно. Буфер 1 не даёт горутине + // зависнуть на отправке, если её уже никто не ждёт. + startErr := make(chan error, 1) + go func() { + startErr <- srv.Start() + }() + + // Ждём первое из двух событий: сервер сам завершился или пришёл сигнал остановки. + select { + case err := <-startErr: + if err != nil { + logger.Error("server failed to start", slog.Any("err", err)) + storage.Close() + os.Exit(1) + } + case <-ctx.Done(): + logger.Info("shutdown signal received") + // Drain: readiness начинает отвечать 503, но запросы ещё обслуживаются. За это время LB + // выводит реплику, поэтому новые запросы перестают приходить до закрытия порта. + srv.Drain(time.Duration(cfg.HTTP.ShutdownDrainMs) * time.Millisecond) + } + + // Предел на завершение открытых запросов. Он должен быть меньше stop_grace_period в compose.yaml, + // иначе Docker пришлёт SIGKILL раньше. + shutdownCtx, cancel := context.WithTimeout( + context.Background(), + time.Duration(cfg.HTTP.ShutdownTimeoutMs)*time.Millisecond, + ) + defer cancel() + + // Закрыть порт и дождаться открытых запросов. Если не успели за предел, это ошибка завершения. + if err := srv.Shutdown(shutdownCtx); err != nil { + logger.Error("shutdown failed", slog.Any("err", err)) + storage.Close() + os.Exit(1) + } + + // Эта строка в логе подтверждает штатное завершение: её ищет failure-detection.py. + logger.Info("server stopped cleanly") +} + +// Как часто удалять устаревшие ключи идемпотентности. +const idempotencyPurgeInterval = time.Hour + +// purgeIdempotencyKeys удаляет ключи старше ttl: сразу при запуске и затем по таймеру. Ошибка не +// опасна: очистка просто повторится позже. Удаление работает на каждой реплике, это безопасно, +// потому что удалять будет нечего после первой из них. +func purgeIdempotencyKeys(ctx context.Context, storage *db.DB, ttl time.Duration, logger *slog.Logger) { + t := time.NewTicker(idempotencyPurgeInterval) + defer t.Stop() + for { + if n, err := storage.PurgeIdempotencyKeys(ctx, ttl); err != nil { + // Ошибка из-за остановки сервера ожидаема: просто выходим. + if ctx.Err() != nil { + return + } + logger.Warn("idempotency keys purge failed", slog.Any("err", err)) + } else if n > 0 { + logger.Info("idempotency keys purged", slog.Int64("count", n)) + } + select { + case <-ctx.Done(): + return + case <-t.C: + } + } +} diff --git a/app/cmd/s3check/main.go b/app/cmd/s3check/main.go new file mode 100644 index 00000000..42ce90ee --- /dev/null +++ b/app/cmd/s3check/main.go @@ -0,0 +1,226 @@ +// s3check проверяет права в S3 мимо API: анонимный доступ, ограничения ключей API и очистителя, +// закрытые служебные операции. Создаёт объект и временный bucket, в конце убирает их за собой. +// Запуск: docker compose --env-file .env run --rm s3check +package main + +import ( + "bytes" + "context" + "fmt" + "io" + "net/http" + "net/url" + "os" + "strings" + "time" + + "github.com/google/uuid" + "github.com/minio/minio-go/v7" + "github.com/minio/minio-go/v7/pkg/credentials" +) + +const publicPolicy = `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":"*","Action":["s3:GetObject"],"Resource":["arn:aws:s3:::%s/*"]}]}` + +var failures int + +func expect(name string, allowed bool, err error) { + // Отказом считается именно ответ сервера о правах: обрыв связи не доказывает, что доступа нет. + code := minio.ToErrorResponse(err).Code + denied := err != nil && (code == "AccessDenied" || code == "InvalidAccessKeyId" || code == "SignatureDoesNotMatch") + observed := "разрешено" + switch { + case denied: + observed = "запрещено (" + code + ")" + case err != nil: + observed = "ошибка: " + err.Error() + } + ok := (allowed && err == nil) || (!allowed && denied) + verdict := "ok " + if !ok { + verdict = "FAIL" + failures++ + } + fmt.Printf("%s %-58s %s\n", verdict, name, observed) +} + +func secret(name string) string { + b, err := os.ReadFile("/run/secrets/" + name) + if err != nil { + fmt.Fprintln(os.Stderr, "s3check:", err) + os.Exit(2) + } + return strings.TrimSpace(string(b)) +} + +func client(endpoint *url.URL, region, role string) *minio.Client { + c, err := minio.New(endpoint.Host, &minio.Options{ + Creds: credentials.NewStaticV4(secret(role+"access_key_id"), secret(role+"secret_access_key"), ""), + Secure: endpoint.Scheme == "https", + Region: region, + BucketLookup: minio.BucketLookupPath, + }) + if err != nil { + fmt.Fprintln(os.Stderr, "s3check:", err) + os.Exit(2) + } + return c +} + +func put(ctx context.Context, c *minio.Client, bucket, key string) error { + body := []byte("s3check") + _, err := c.PutObject(ctx, bucket, key, bytes.NewReader(body), int64(len(body)), minio.PutObjectOptions{DisableMultipart: true}) + return err +} + +func get(ctx context.Context, c *minio.Client, bucket, key string) error { + object, err := c.GetObject(ctx, bucket, key, minio.GetObjectOptions{}) + if err != nil { + return err + } + defer object.Close() + _, err = io.ReadAll(object) + return err +} + +func list(ctx context.Context, c *minio.Client, bucket string) error { + for object := range c.ListObjects(ctx, bucket, minio.ListObjectsOptions{Recursive: true}) { + return object.Err + } + return nil +} + +// anonymous делает запрос без подписи и возвращает код ответа. +func anonymous(ctx context.Context, method, target string) (int, error) { + req, err := http.NewRequestWithContext(ctx, method, target, nil) + if err != nil { + return 0, err + } + resp, err := http.DefaultClient.Do(req) + if err != nil { + return 0, err + } + defer resp.Body.Close() + return resp.StatusCode, nil +} + +func main() { + os.Exit(run()) +} + +// run возвращает код завершения: os.Exit не выполнил бы отложенную уборку. +func run() int { + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + defer cancel() + endpoint, err := url.Parse(os.Getenv("S3_ENDPOINT")) + if err != nil || endpoint.Host == "" { + fmt.Fprintln(os.Stderr, "s3check: S3_ENDPOINT is required") + return 2 + } + region, bucket := os.Getenv("S3_REGION"), os.Getenv("S3_BUCKET") + admin := client(endpoint, region, "s3_admin_") + api := client(endpoint, region, "s3_") + cleaner := client(endpoint, region, "s3_janitor_") + + // Настоящий префикс оригиналов: ключи API и очистителя ограничены им. Объект свежий, поэтому + // работающий очиститель его не тронет, а в конце проверка удаляет его сама. + probe := "originals/" + uuid.NewString() + outside := "s3check/" + uuid.NewString() + other := "s3check-" + uuid.NewString() + + fmt.Println("== Ключ подготовки (admin)") + expect("создать временный чужой bucket", true, admin.MakeBucket(ctx, other, minio.MakeBucketOptions{})) + expect("записать объект в чужой bucket", true, put(ctx, admin, other, "probe")) + defer func() { + _ = admin.RemoveObject(context.Background(), other, "probe", minio.RemoveObjectOptions{}) + _ = admin.RemoveBucket(context.Background(), other) + }() + + fmt.Println("== Ключ API: только объекты своего bucket") + expect("PUT объекта в свой bucket", true, put(ctx, api, bucket, probe)) + expect("GET объекта из своего bucket", true, get(ctx, api, bucket, probe)) + expect("LIST своего bucket", false, list(ctx, api, bucket)) + expect("PUT вне префикса originals/", false, put(ctx, api, bucket, outside)) + expect("GET из чужого bucket", false, get(ctx, api, other, "probe")) + expect("PUT в чужой bucket", false, put(ctx, api, other, "api-probe")) + expect("DELETE из чужого bucket", false, api.RemoveObject(ctx, other, "probe", minio.RemoveObjectOptions{})) + expect("создать bucket", false, api.MakeBucket(ctx, "s3check-"+uuid.NewString(), minio.MakeBucketOptions{})) + expect("удалить bucket", false, api.RemoveBucket(ctx, other)) + expect("сделать bucket публичным (policy)", false, api.SetBucketPolicy(ctx, bucket, fmt.Sprintf(publicPolicy, bucket))) + expect("прочитать policy bucket", false, func() error { _, err := api.GetBucketPolicy(ctx, bucket); return err }()) + + fmt.Println("== Ключ очистителя: листинг и удаление, без чтения содержимого") + expect("LIST своего bucket", true, list(ctx, cleaner, bucket)) + expect("GET содержимого объекта", false, get(ctx, cleaner, bucket, probe)) + expect("LIST чужого bucket", false, list(ctx, cleaner, other)) + expect("PUT вне префикса originals/", false, put(ctx, cleaner, bucket, outside)) + expect("сделать bucket публичным (policy)", false, cleaner.SetBucketPolicy(ctx, bucket, fmt.Sprintf(publicPolicy, bucket))) + expect("создать bucket", false, cleaner.MakeBucket(ctx, "s3check-"+uuid.NewString(), minio.MakeBucketOptions{})) + expect("удалить чужой bucket", false, cleaner.RemoveBucket(ctx, other)) + expect("DELETE объекта в своём bucket", true, cleaner.RemoveObject(ctx, bucket, probe, minio.RemoveObjectOptions{})) + + fmt.Println("== Политика bucket: не задана, доступ только по ключам") + policy, err := admin.GetBucketPolicy(ctx, bucket) + if err != nil && minio.ToErrorResponse(err).Code == "NoSuchBucketPolicy" { + err = nil + } + expect("прочитать политику ключом администратора", true, err) + verdict := "ok " + if policy != "" { + verdict = "FAIL" + failures++ + } + fmt.Printf("%s %-58s %d байт\n", verdict, "политика пуста", len(policy)) + + fmt.Println("== Без подписи: приватность вне API") + if err := put(ctx, admin, bucket, probe); err != nil { + expect("подготовить объект", true, err) + } + defer func() { _ = admin.RemoveObject(context.Background(), bucket, probe, minio.RemoveObjectOptions{}) }() + base := strings.TrimRight(endpoint.String(), "/") + "/" + for _, request := range []struct{ name, method, target string }{ + {"GET объекта", http.MethodGet, base + bucket + "/" + probe}, + {"HEAD объекта", http.MethodHead, base + bucket + "/" + probe}, + {"GET списка объектов", http.MethodGet, base + bucket + "/"}, + {"GET списка bucket", http.MethodGet, base}, + {"PUT объекта", http.MethodPut, base + bucket + "/" + probe + "-anon"}, + {"DELETE объекта", http.MethodDelete, base + bucket + "/" + probe}, + } { + status, err := anonymous(ctx, request.method, request.target) + verdict = "ok " + if err != nil || status != http.StatusForbidden { + verdict = "FAIL" + failures++ + } + fmt.Printf("%s %-58s HTTP %d\n", verdict, request.name, status) + } + + fmt.Println("== Служебные порты SeaweedFS из сети стенда (шлюз пропускает только 9000)") + host := endpoint.Hostname() + for _, port := range []string{"19000", "8888", "8080", "9333", "18888", "18080", "19333", "8333", "8111", "23646"} { + _, err := anonymous(ctx, http.MethodGet, "http://"+host+":"+port+"/") + verdict = "ok " + closed := "закрыт" + if err == nil { + verdict, closed = "FAIL", "ОТКРЫТ" + failures++ + } + fmt.Printf("%s порт %-53s %s\n", verdict, port, closed) + } + + // Имя настоящего сервера существует только во внутренней сети, куда входит лишь шлюз. + _, err = anonymous(ctx, http.MethodGet, "http://s3-storage:9000/") + verdict = "ok " + observed := "недоступен" + if err == nil { + verdict, observed = "FAIL", "ДОСТУПЕН" + failures++ + } + fmt.Printf("%s %-58s %s\n", verdict, "SeaweedFS напрямую, минуя шлюз (s3-storage:9000)", observed) + + if failures > 0 { + fmt.Printf("\nFAIL: %d проверок не прошли\n", failures) + return 1 + } + fmt.Println("\nPASS: права S3 ограничены, bucket приватен, служебные порты закрыты") + return 0 +} diff --git a/app/cmd/s3init/main.go b/app/cmd/s3init/main.go new file mode 100644 index 00000000..9135f731 --- /dev/null +++ b/app/cmd/s3init/main.go @@ -0,0 +1,55 @@ +// s3init — одноразовая подготовка хранилища: дожидается S3, создаёт bucket, удаляет постороннюю +// политику и проверяет, что bucket приватный. Повторный запуск безопасен: объекты не затрагиваются. Запускается сервисом s3-init до старта API. +package main + +import ( + "context" + "fmt" + "os" + "time" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/config" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/objectstore" +) + +const waitLimit = 90 * time.Second + +func main() { + if err := run(); err != nil { + fmt.Fprintln(os.Stderr, "s3init:", err) + os.Exit(1) + } + fmt.Println("s3init: bucket is ready and private") +} + +func run() error { + cfg, err := config.Load() + if err != nil { + return err + } + s3, err := objectstore.NewS3(cfg.S3) + if err != nil { + return err + } + ctx, cancel := context.WithTimeout(context.Background(), waitLimit) + defer cancel() + // Шлюз S3 может стать здоровым раньше, чем готово хранилище под ним: первые ошибки ожидаемы. + for { + err = s3.EnsureBucket(ctx) + if err == nil { + removed, err := s3.RemovePolicy(ctx) + if err != nil { + return err + } + if removed { + fmt.Println("s3init: foreign bucket policy removed") + } + return s3.CheckPrivate(ctx) + } + select { + case <-ctx.Done(): + return err + case <-time.After(time.Second): + } + } +} diff --git a/app/e2e/lb_idempotency_test.go b/app/e2e/lb_idempotency_test.go new file mode 100644 index 00000000..373ae7c3 --- /dev/null +++ b/app/e2e/lb_idempotency_test.go @@ -0,0 +1,228 @@ +// Package e2e — проверки против запущенного стенда через балансировщик. +// +// Запуск: E2E_BASE_URL=http://localhost:8080 go test -count=1 -v ./e2e/ +// Без E2E_BASE_URL тесты пропускаются, поэтому обычный go test ./... стенд не требует. +// Создаёт только синтетические данные, токены и пароли не печатает. +package e2e + +import ( + "bytes" + "crypto/rand" + "encoding/hex" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "os" + "slices" + "strings" + "sync" + "testing" + "time" +) + +const ( + rounds = 20 + workers = 16 +) + +type client struct { + t *testing.T + base string + http *http.Client + token string +} + +type result struct { + status int + instance string + body []byte +} + +func randomHex(n int) string { + b := make([]byte, n) + if _, err := rand.Read(b); err != nil { + panic(err) + } + return hex.EncodeToString(b) +} + +// do не вызывает t.Fatal: он работает и из горутин. +func (c *client) do(method, path string, headers map[string]string, payload any) (result, error) { + var body io.Reader + if payload != nil { + b, err := json.Marshal(payload) + if err != nil { + return result{}, err + } + body = bytes.NewReader(b) + } + req, err := http.NewRequest(method, c.base+path, body) + if err != nil { + return result{}, err + } + if payload != nil { + req.Header.Set("Content-Type", "application/json") + } + if c.token != "" { + req.Header.Set("Authorization", "Bearer "+c.token) + } + for k, v := range headers { + req.Header.Set(k, v) + } + resp, err := c.http.Do(req) + if err != nil { + return result{}, fmt.Errorf("%s %s: %w", method, strings.Split(path, "?")[0], err) + } + defer resp.Body.Close() + data, err := io.ReadAll(resp.Body) + if err != nil { + return result{}, err + } + return result{status: resp.StatusCode, instance: resp.Header.Get("X-Instance-Id"), body: data}, nil +} + +func (c *client) mustDo(method, path string, want int, payload any, out any) { + c.t.Helper() + res, err := c.do(method, path, nil, payload) + if err != nil { + c.t.Fatal(err) + } + if res.status != want { + c.t.Fatalf("%s %s: status = %d, want %d", method, strings.Split(path, "?")[0], res.status, want) + } + if out != nil { + if err := json.Unmarshal(res.body, out); err != nil { + c.t.Fatalf("%s %s: decode: %v", method, path, err) + } + } +} + +// bootstrap создаёт пользователя с сессией и чат с ним. +func bootstrap(t *testing.T, base string) (*client, string) { + t.Helper() + c := &client{t: t, base: strings.TrimRight(base, "/"), http: &http.Client{Timeout: 10 * time.Second}} + + username, password := "lb_"+randomHex(8), "T3st-"+randomHex(16) + var user struct { + ID string `json:"id"` + } + c.mustDo(http.MethodPost, "/api/v1/users", http.StatusCreated, map[string]string{ + "username": username, "display_name": "LB test", "password": password, + }, &user) + + req, err := http.NewRequest(http.MethodPost, c.base+"/api/v1/auth/sessions", nil) + if err != nil { + t.Fatal(err) + } + req.SetBasicAuth(username, password) + resp, err := c.http.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusCreated { + t.Fatalf("login: status = %d", resp.StatusCode) + } + var session struct { + Token string `json:"token"` + } + if err := json.NewDecoder(resp.Body).Decode(&session); err != nil { + t.Fatal(err) + } + c.token = session.Token + + var chat struct { + ID string `json:"id"` + } + c.mustDo(http.MethodPost, "/api/v1/chats", http.StatusCreated, map[string]any{ + "title": "LB test", "member_ids": []string{user.ID}, + }, &chat) + return c, chat.ID +} + +// Одинаковый Idempotency-Key одновременно через разные реплики создаёт ровно одно сообщение. +func TestLBSameKeyConcurrentlyThroughReplicas(t *testing.T) { + base := os.Getenv("E2E_BASE_URL") + if base == "" { + t.Skip("E2E_BASE_URL не задан") + } + c, chatID := bootstrap(t, base) + path := "/api/v1/chats/" + chatID + "/messages" + + perInstance := map[string]int{} + var created []string + for round := range rounds { + key, text := randomHex(16), fmt.Sprintf("гонка %d", round) + results := make([]result, workers) + errs := make([]error, workers) + start := make(chan struct{}) + var wg sync.WaitGroup + for i := range workers { + wg.Add(1) + go func() { + defer wg.Done() + <-start + results[i], errs[i] = c.do(http.MethodPost, path, + map[string]string{"Idempotency-Key": key}, map[string]string{"text": text}) + }() + } + close(start) + wg.Wait() + + instances := map[string]bool{} + for i := range workers { + if errs[i] != nil { + t.Fatalf("round %d: %v", round, errs[i]) + } + if results[i].status != http.StatusCreated { + t.Fatalf("round %d: status = %d, want 201", round, results[i].status) + } + if !bytes.Equal(results[i].body, results[0].body) { + t.Fatalf("round %d: реплики вернули разные сообщения", round) + } + instances[results[i].instance] = true + perInstance[results[i].instance]++ + } + if len(instances) < 2 { + t.Fatalf("round %d обслужила одна реплика: проверьте LB", round) + } + var msg struct { + ID string `json:"id"` + } + if err := json.Unmarshal(results[0].body, &msg); err != nil { + t.Fatal(err) + } + created = append(created, msg.ID) + } + + var history []string + for cursor := ""; ; { + q := "?limit=100" + if cursor != "" { + q += "&cursor=" + url.QueryEscape(cursor) + } + var page struct { + Items []struct { + ID string `json:"id"` + } `json:"items"` + NextCursor *string `json:"next_cursor"` + } + c.mustDo(http.MethodGet, path+q, http.StatusOK, nil, &page) + for _, m := range page.Items { + history = append(history, m.ID) + } + if page.NextCursor == nil { + break + } + cursor = *page.NextCursor + } + slices.Sort(created) + slices.Sort(history) + if !slices.Equal(created, history) { + t.Fatalf("история отличается от подтверждённого: %d сообщений, ожидалось %d", len(history), len(created)) + } + t.Logf("раундов: %d, запросов в раунде: %d, запросов по репликам: %v, сообщений в истории: %d", + rounds, workers, perInstance, len(history)) +} diff --git a/app/go.mod b/app/go.mod new file mode 100644 index 00000000..c4d4c1d3 --- /dev/null +++ b/app/go.mod @@ -0,0 +1,39 @@ +module gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl + +go 1.26.0 + +require ( + github.com/google/uuid v1.6.0 + github.com/jackc/pgx/v5 v5.7.6 + github.com/labstack/echo/v4 v4.16.2 + github.com/minio/minio-go/v7 v7.0.95 + github.com/redis/go-redis/v9 v9.7.3 + golang.org/x/crypto v0.57.0 + golang.org/x/sync v0.23.0 +) + +require ( + github.com/cespare/xxhash/v2 v2.2.0 // indirect + github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect + github.com/dustin/go-humanize v1.0.1 // indirect + github.com/go-ini/ini v1.67.0 // indirect + github.com/goccy/go-json v0.10.5 // indirect + github.com/jackc/pgpassfile v1.0.0 // indirect + github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect + github.com/jackc/puddle/v2 v2.2.2 // indirect + github.com/klauspost/compress v1.18.0 // indirect + github.com/klauspost/cpuid/v2 v2.2.11 // indirect + github.com/labstack/gommon v0.5.0 // indirect + github.com/mattn/go-colorable v0.1.15 // indirect + github.com/mattn/go-isatty v0.0.22 // indirect + github.com/minio/crc64nvme v1.0.2 // indirect + github.com/minio/md5-simd v1.1.2 // indirect + github.com/philhofer/fwd v1.2.0 // indirect + github.com/rs/xid v1.6.0 // indirect + github.com/tinylib/msgp v1.3.0 // indirect + github.com/valyala/bytebufferpool v1.0.0 // indirect + github.com/valyala/fasttemplate v1.2.2 // indirect + golang.org/x/net v0.60.0 // indirect + golang.org/x/sys v0.48.0 // indirect + golang.org/x/text v0.42.0 // indirect +) diff --git a/app/go.sum b/app/go.sum new file mode 100644 index 00000000..cf065f57 --- /dev/null +++ b/app/go.sum @@ -0,0 +1,79 @@ +github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs= +github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c= +github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA= +github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0= +github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44= +github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= +github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= +github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= +github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= +github.com/go-ini/ini v1.67.0 h1:z6ZrTEZqSWOTyH2FlglNbNgARyHG8oLW9gMELqKr06A= +github.com/go-ini/ini v1.67.0/go.mod h1:ByCAeIL28uOIIG0E3PJtZPDL8WnHpFKFOtgjp+3Ies8= +github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4= +github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= +github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= +github.com/jackc/pgx/v5 v5.7.6 h1:rWQc5FwZSPX58r1OQmkuaNicxdmExaEz5A2DO2hUuTk= +github.com/jackc/pgx/v5 v5.7.6/go.mod h1:aruU7o91Tc2q2cFp5h4uP3f6ztExVpyVv88Xl/8Vl8M= +github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= +github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= +github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo= +github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ= +github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= +github.com/klauspost/cpuid/v2 v2.2.11 h1:0OwqZRYI2rFrjS4kvkDnqJkKHdHaRnCm68/DY4OxRzU= +github.com/klauspost/cpuid/v2 v2.2.11/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= +github.com/labstack/echo/v4 v4.16.2 h1:WFPVqfogOZGH4dTr1UCIB1sqjFIQ/k7vIk5ByL6oWjY= +github.com/labstack/echo/v4 v4.16.2/go.mod h1:V/EQaTVHYJH92QhbQe7kFQ4mjgcjxLQQUQtAN87zZdw= +github.com/labstack/gommon v0.5.0 h1:6VSQ2NOzsnEJ5W6+84E0RbcaDDmgB6NIAzWCczTEe6c= +github.com/labstack/gommon v0.5.0/go.mod h1:Rzlg7HHy1maLfzBYGg9NZcVuz1sA68HHhLjhcEllYE0= +github.com/mattn/go-colorable v0.1.15 h1:+u9SLTRGnXv73cEsnsmoZBom+dMU88B2M0aDcWy0/jY= +github.com/mattn/go-colorable v0.1.15/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8= +github.com/mattn/go-isatty v0.0.22 h1:j8l17JJ9i6VGPUFUYoTUKPSgKe/83EYU2zBC7YNKMw4= +github.com/mattn/go-isatty v0.0.22/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4= +github.com/minio/crc64nvme v1.0.2 h1:6uO1UxGAD+kwqWWp7mBFsi5gAse66C4NXO8cmcVculg= +github.com/minio/crc64nvme v1.0.2/go.mod h1:eVfm2fAzLlxMdUGc0EEBGSMmPwmXD5XiNRpnu9J3bvg= +github.com/minio/md5-simd v1.1.2 h1:Gdi1DZK69+ZVMoNHRXJyNcxrMA4dSxoYHZSQbirFg34= +github.com/minio/md5-simd v1.1.2/go.mod h1:MzdKDxYpY2BT9XQFocsiZf/NKVtR7nkE4RoEpN+20RM= +github.com/minio/minio-go/v7 v7.0.95 h1:ywOUPg+PebTMTzn9VDsoFJy32ZuARN9zhB+K3IYEvYU= +github.com/minio/minio-go/v7 v7.0.95/go.mod h1:wOOX3uxS334vImCNRVyIDdXX9OsXDm89ToynKgqUKlo= +github.com/philhofer/fwd v1.2.0 h1:e6DnBTl7vGY+Gz322/ASL4Gyp1FspeMvx1RNDoToZuM= +github.com/philhofer/fwd v1.2.0/go.mod h1:RqIHx9QI14HlwKwm98g9Re5prTQ6LdeRQn+gXJFxsJM= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/redis/go-redis/v9 v9.7.3 h1:YpPyAayJV+XErNsatSElgRZZVCwXX9QzkKYNvO7x0wM= +github.com/redis/go-redis/v9 v9.7.3/go.mod h1:bGUrSggJ9X9GUmZpZNEOQKaANxSGgOEBRltRTZHSvrA= +github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU= +github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/tinylib/msgp v1.3.0 h1:ULuf7GPooDaIlbyvgAxBV/FI7ynli6LZ1/nVUNu+0ww= +github.com/tinylib/msgp v1.3.0/go.mod h1:ykjzy2wzgrlvpDCRc4LA8UXy6D8bzMSuAF3WD57Gok0= +github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= +github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= +github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo= +github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ= +golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M= +golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA= +golang.org/x/net v0.60.0 h1:79p50tfZlm0J9YfoDsSi639qSXNGVwEzOPLCxM2FsYU= +golang.org/x/net v0.60.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg= +golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk= +golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= +golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo= +golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI= +golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/app/internal/api/http/access_test.go b/app/internal/api/http/access_test.go new file mode 100644 index 00000000..b3e45978 --- /dev/null +++ b/app/internal/api/http/access_test.go @@ -0,0 +1,115 @@ +package http + +import ( + "bytes" + "io" + "net/http" + "strings" + "testing" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto" +) + +func TestAccess_ForeignChat(t *testing.T) { + r := newTestRig(t) + _, _, eve, chat := bootstrap(r) + base := "/api/v1/chats/" + chat.ID + + cases := []struct { + method, path string + body any + }{ + {http.MethodGet, base, nil}, + {http.MethodGet, base + "/messages?limit=10", nil}, + {http.MethodPost, base + "/messages", textMessage("вторжение")}, + } + for _, tc := range cases { + var resp *http.Response + if tc.body == nil { + resp = r.do(tc.method, tc.path, eve.ID, nil, nil) + } else { + resp = r.doJSON(tc.method, tc.path, eve.ID, tc.body) + } + if resp.StatusCode != http.StatusNotFound { + data, _ := io.ReadAll(resp.Body) + resp.Body.Close() + t.Fatalf("%s %s expected 404, got %d; body=%s", tc.method, tc.path, resp.StatusCode, string(data)) + } + e := readError(t, resp) + if e.Error.Code != CodeNotFound { + t.Fatalf("%s %s expected code %q, got %q", tc.method, tc.path, CodeNotFound, e.Error.Code) + } + } + + resp := r.do(http.MethodGet, "/api/v1/chats?limit=100", eve.ID, nil, nil) + expectStatus(t, resp, http.StatusOK) + var page dto.ChatsPageResponse + readJSON(t, resp, &page) + for _, item := range page.Items { + if item.ID == chat.ID { + t.Fatalf("чат утёк в список чужого пользователя") + } + } +} + +func TestAccess_AuthBeforeContentType(t *testing.T) { + r := newTestRig(t) + resp := r.do(http.MethodPost, "/api/v1/chats", "", + map[string]string{"Content-Type": "text/plain"}, strings.NewReader("x")) + expectStatus(t, resp, http.StatusUnauthorized) + resp.Body.Close() + + resp = r.do(http.MethodPost, "/api/v1/nope", "", nil, strings.NewReader("x")) + expectStatus(t, resp, http.StatusNotFound) + if resp.Header.Get("X-Request-Id") == "" { + t.Fatal("404 without X-Request-Id") + } + resp.Body.Close() +} + +func TestAccess_RouterErrors(t *testing.T) { + r := newTestRig(t) + alice, _, _, chat := bootstrap(r) + chatPath := "/api/v1/chats/" + chat.ID + + cases := []struct { + method, path, actor string + status int + code, message string + }{ + {http.MethodGet, "/nope", "", http.StatusNotFound, CodeNotFound, "Object not found"}, + {http.MethodGet, "/health/live/", "", http.StatusNotFound, CodeNotFound, "Object not found"}, + {http.MethodGet, "/api/v1/nope", alice.ID, http.StatusNotFound, CodeNotFound, "Object not found"}, + {http.MethodPost, "/health/live", "", http.StatusMethodNotAllowed, CodeInvalidRequest, "Method not allowed"}, + {http.MethodGet, "/api/v1/users", "", http.StatusMethodNotAllowed, CodeInvalidRequest, "Method not allowed"}, + {http.MethodPost, "/api/v1/users/me", "", http.StatusMethodNotAllowed, CodeInvalidRequest, "Method not allowed"}, + {http.MethodDelete, "/api/v1/users/me", alice.ID, http.StatusMethodNotAllowed, CodeInvalidRequest, "Method not allowed"}, + {http.MethodDelete, "/api/v1/chats", alice.ID, http.StatusMethodNotAllowed, CodeInvalidRequest, "Method not allowed"}, + {http.MethodPut, chatPath, alice.ID, http.StatusMethodNotAllowed, CodeInvalidRequest, "Method not allowed"}, + {http.MethodPatch, chatPath + "/messages", alice.ID, http.StatusMethodNotAllowed, CodeInvalidRequest, "Method not allowed"}, + } + for _, tc := range cases { + var body io.Reader + headers := map[string]string{} + if tc.method == http.MethodPost || tc.method == http.MethodPut || tc.method == http.MethodPatch { + body = bytes.NewReader([]byte(`{}`)) + headers["Content-Type"] = "application/json" + } + resp := r.do(tc.method, tc.path, tc.actor, headers, body) + if resp.StatusCode != tc.status { + data, _ := io.ReadAll(resp.Body) + resp.Body.Close() + t.Fatalf("%s %s: expected %d, got %d; body=%s", tc.method, tc.path, tc.status, resp.StatusCode, string(data)) + } + if tc.status == http.StatusMethodNotAllowed && resp.Header.Get("Allow") == "" { + t.Fatalf("%s %s: 405 без заголовка Allow", tc.method, tc.path) + } + e := readError(t, resp) + if e.Error.Code != tc.code || e.Error.Message != tc.message { + t.Fatalf("%s %s: expected %q/%q, got %q/%q", tc.method, tc.path, tc.code, tc.message, e.Error.Code, e.Error.Message) + } + if e.Error.RequestID == "" || e.Error.RequestID != resp.Header.Get("X-Request-Id") { + t.Fatalf("%s %s: request_id %q не совпадает с заголовком %q", tc.method, tc.path, e.Error.RequestID, resp.Header.Get("X-Request-Id")) + } + } +} diff --git a/app/internal/api/http/attachments.go b/app/internal/api/http/attachments.go new file mode 100644 index 00000000..e51337a7 --- /dev/null +++ b/app/internal/api/http/attachments.go @@ -0,0 +1,130 @@ +package http + +import ( + "context" + "io" + "mime" + "net/http" + "strconv" + "time" + + "github.com/labstack/echo/v4" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/middleware" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/service" +) + +// routeUploadAttachment освобождён от общего лимита тела: свой лимит применяется в сервисе, после +// аутентификации и проверки доступа. +const routeUploadAttachment = "/api/v1/chats/:chat_id/attachments" + +// transferTimeout — предел на передачу одного файла. Общие таймауты сервера (10 с) рассчитаны на +// JSON и оборвали бы загрузку 10 МиБ на медленном канале. Предел обязателен: иначе медленный клиент +// занимал бы слот загрузки неограниченно долго. +const transferTimeout = 60 * time.Second + +type attachmentsHandler struct { + attachments service.AttachmentsService +} + +// rejectedBodyDrainLimit — сколько байт отклонённой загрузки дочитывается впустую. Клиент обычно +// сначала отправляет всё тело и только потом читает ответ: если перестать читать, он зависнет и +// вместо 413 получит обрыв. Дочитывание идёт в никуда, поэтому память не расходует, а его время +// ограничено transferTimeout. Тело больше этого предела приводит к закрытию соединения. +const rejectedBodyDrainLimit = 64 << 20 + +func extendDeadlines(c echo.Context) { + rc := http.NewResponseController(c.Response()) + deadline := time.Now().Add(transferTimeout) + // Ошибка значит, что соединение не поддерживает дедлайны: тогда действуют общие таймауты. + _ = rc.SetReadDeadline(deadline) + _ = rc.SetWriteDeadline(deadline) +} + +// uploadTransfer стоит снаружи аутентификации, поэтому покрывает и отказы 401. Небольшой ответ об +// ошибке остаётся в буфере сервера и уходит клиенту после дочитывания. +func uploadTransfer(next echo.HandlerFunc) echo.HandlerFunc { + return func(c echo.Context) error { + extendDeadlines(c) + err := next(c) + _, _ = io.CopyN(io.Discard, c.Request().Body, rejectedBodyDrainLimit) + return err + } +} + +func (h *attachmentsHandler) upload(c echo.Context) error { + req := c.Request() + // Несколько filename неоднозначны: пустое значение сервис отклонит как неверное имя. + var filename string + if values := c.QueryParams()["filename"]; len(values) == 1 { + filename = values[0] + } + att, err := h.attachments.Upload(req.Context(), service.UploadInput{ + CallerID: c.Get(middleware.AuthUserIDKey).(string), + ChatID: c.Param("chat_id"), + Filename: filename, + ContentType: req.Header.Get(echo.HeaderContentType), + ContentLength: req.ContentLength, + Body: req.Body, + }) + if err != nil { + return WriteError(c, err) + } + return c.JSON(http.StatusCreated, toAttachmentResponse(att)) +} + +func (h *attachmentsHandler) get(c echo.Context) error { + att, err := h.attachments.Get(c.Request().Context(), c.Get(middleware.AuthUserIDKey).(string), c.Param("attachment_id")) + if err != nil { + return WriteError(c, err) + } + return c.JSON(http.StatusOK, toAttachmentResponse(att)) +} + +func (h *attachmentsHandler) content(c echo.Context) error { + extendDeadlines(c) + variant := service.VariantOriginal + if values, ok := c.QueryParams()["variant"]; ok { + variant = values[0] + } + ctx, cancel := context.WithTimeout(c.Request().Context(), transferTimeout) + defer cancel() + + att, body, err := h.attachments.Content(ctx, c.Get(middleware.AuthUserIDKey).(string), c.Param("attachment_id"), variant) + if err != nil { + return WriteError(c, err) + } + defer body.Close() + + header := c.Response().Header() + header.Set(echo.HeaderContentLength, strconv.FormatInt(att.SizeBytes, 10)) + // Файл загрузил пользователь: браузер не должен угадывать тип или показывать его как страницу. + header.Set("X-Content-Type-Options", "nosniff") + header.Set("Cache-Control", "private, no-store") + if cd := mime.FormatMediaType("attachment", map[string]string{"filename": att.Filename}); cd != "" { + header.Set(echo.HeaderContentDisposition, cd) + } else { + header.Set(echo.HeaderContentDisposition, "attachment") + } + // Обрыв после начала передачи клиент увидит как неполный ответ: длина объявлена заранее. + return c.Stream(http.StatusOK, att.ContentType, body) +} + +func toAttachmentResponse(a domain.Attachment) dto.AttachmentResponse { + return dto.AttachmentResponse{ + ID: a.ID, + ChatID: a.ChatID, + OwnerID: a.OwnerID, + Filename: a.Filename, + ContentType: a.ContentType, + SizeBytes: a.SizeBytes, + SHA256: a.SHA256, + Status: a.Status, + Variants: []dto.VariantResponse{}, + ErrorCode: nil, + CreatedAt: dto.NewTimestamp(a.CreatedAt), + UpdatedAt: dto.NewTimestamp(a.UpdatedAt), + } +} diff --git a/app/internal/api/http/attachments_test.go b/app/internal/api/http/attachments_test.go new file mode 100644 index 00000000..624a24d7 --- /dev/null +++ b/app/internal/api/http/attachments_test.go @@ -0,0 +1,546 @@ +package http + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "image" + "image/jpeg" + "image/png" + "io" + "log/slog" + "net/http" + "net/url" + "os" + "strings" + "testing" + + "github.com/google/uuid" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/objectstore" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/service" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate" +) + +func testPNG(t *testing.T, w, h int) []byte { + t.Helper() + var b bytes.Buffer + if err := png.Encode(&b, image.NewRGBA(image.Rect(0, 0, w, h))); err != nil { + t.Fatal(err) + } + return b.Bytes() +} + +func testJPEG(t *testing.T) []byte { + t.Helper() + var b bytes.Buffer + if err := jpeg.Encode(&b, image.NewRGBA(image.Rect(0, 0, 8, 8)), nil); err != nil { + t.Fatal(err) + } + return b.Bytes() +} + +func (r *testRig) upload(actor, chatID, filename, contentType string, data []byte) *http.Response { + r.t.Helper() + return r.do(http.MethodPost, "/api/v1/chats/"+chatID+"/attachments?filename="+url.QueryEscape(filename), actor, + map[string]string{"Content-Type": contentType}, bytes.NewReader(data)) +} + +func (r *testRig) uploadOK(actor, chatID string, data []byte) dto.AttachmentResponse { + r.t.Helper() + resp := r.upload(actor, chatID, "photo.png", "image/png", data) + expectStatus(r.t, resp, http.StatusCreated) + var att dto.AttachmentResponse + readJSON(r.t, resp, &att) + return att +} + +func TestAttachment_UploadAndDownloadByteForByte(t *testing.T) { + r := newTestRig(t) + alice, bob, eve, chat := bootstrap(r) + data := testPNG(t, 16, 16) + att := r.uploadOK(alice.ID, chat.ID, data) + + sum := sha256.Sum256(data) + if att.Status != "ready" || att.SHA256 != hex.EncodeToString(sum[:]) || att.SizeBytes != int64(len(data)) || + att.OwnerID != alice.ID || att.ChatID != chat.ID || att.ErrorCode != nil || att.Variants == nil { + t.Errorf("metadata = %+v", att) + } + + resp := r.do(http.MethodGet, "/api/v1/attachments/"+att.ID+"/content", bob.ID, nil, nil) + expectStatus(t, resp, http.StatusOK) + defer resp.Body.Close() + got, _ := io.ReadAll(resp.Body) + if !bytes.Equal(got, data) { + t.Error("downloaded bytes differ") + } + if ct := resp.Header.Get("Content-Type"); ct != "image/png" { + t.Errorf("Content-Type = %q", ct) + } + if resp.Header.Get("X-Content-Type-Options") != "nosniff" { + t.Error("nosniff missing") + } + + for _, suffix := range []string{"", "/content"} { + resp := r.do(http.MethodGet, "/api/v1/attachments/"+att.ID+suffix, eve.ID, nil, nil) + expectStatus(t, resp, http.StatusNotFound) + resp.Body.Close() + } +} + +func TestAttachment_ObjectKeyIsServerAssignedAndHidden(t *testing.T) { + r := newTestRig(t) + alice, _, _, chat := bootstrap(r) + resp := r.upload(alice.ID, chat.ID, "evil..name.png", "image/png", testPNG(t, 2, 2)) + expectStatus(t, resp, http.StatusCreated) + defer resp.Body.Close() + body, _ := io.ReadAll(resp.Body) + + keys := r.objects.Keys() + if len(keys) != 1 || strings.Contains(keys[0], "evil") { + t.Fatalf("object keys = %v", keys) + } + if bytes.Contains(body, []byte(keys[0])) || bytes.Contains(body, []byte("object_key")) { + t.Errorf("response exposes object key: %s", body) + } +} + +func TestAttachment_Rejections(t *testing.T) { + r := newTestRig(t) + alice, _, eve, chat := bootstrap(r) + valid := testPNG(t, 4, 4) + oversized := append(bytes.Clone(valid), make([]byte, testMaxUploadBytes)...) + + cases := []struct { + name string + actor string + chat string + filename string + contentType string + data []byte + want int + }{ + {"outsider", eve.ID, chat.ID, "a.png", "image/png", valid, 404}, + {"outsider sees 404 before size check", eve.ID, chat.ID, "a.png", "image/png", oversized, 404}, + {"unknown chat", alice.ID, uuid.NewString(), "a.png", "image/png", valid, 404}, + {"bad chat id", alice.ID, "nope", "a.png", "image/png", valid, 400}, + {"path in filename", alice.ID, chat.ID, "../a.png", "image/png", valid, 400}, + {"backslash in filename", alice.ID, chat.ID, `a\b.png`, "image/png", valid, 400}, + {"NUL in filename", alice.ID, chat.ID, "a\x00.png", "image/png", valid, 400}, + {"empty filename", alice.ID, chat.ID, "", "image/png", valid, 400}, + {"too many bytes", alice.ID, chat.ID, "a.png", "image/png", oversized, 413}, + {"too many pixels", alice.ID, chat.ID, "a.png", "image/png", testPNG(t, 101, 100), 413}, + {"wrong declared type", alice.ID, chat.ID, "a.png", "application/json", valid, 415}, + {"no declared type", alice.ID, chat.ID, "a.png", "", valid, 415}, + {"declared jpeg, actual png", alice.ID, chat.ID, "a.jpg", "image/jpeg", valid, 415}, + {"declared png, actual jpeg", alice.ID, chat.ID, "a.png", "image/png", testJPEG(t), 415}, + {"not an image", alice.ID, chat.ID, "a.png", "image/png", []byte(""), 415}, + {"truncated", alice.ID, chat.ID, "a.png", "image/png", valid[:len(valid)/2], 415}, + {"empty body", alice.ID, chat.ID, "a.png", "image/png", nil, 415}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + resp := r.upload(tc.actor, tc.chat, tc.filename, tc.contentType, tc.data) + defer resp.Body.Close() + if resp.StatusCode != tc.want { + body, _ := io.ReadAll(resp.Body) + t.Fatalf("status = %d, want %d, body = %s", resp.StatusCode, tc.want, body) + } + }) + } + if keys := r.objects.Keys(); len(keys) != 0 { + t.Errorf("rejected uploads left objects: %v", keys) + } +} + +func TestAttachment_RequiresAuthentication(t *testing.T) { + r := newTestRig(t) + _, _, _, chat := bootstrap(r) + resp := r.upload("", chat.ID, "a.png", "image/png", testPNG(t, 2, 2)) + expectStatus(t, resp, http.StatusUnauthorized) + resp.Body.Close() +} + +func TestAttachment_S3UnavailableGives503AndKeepsMessagesWorking(t *testing.T) { + r := newTestRig(t) + alice, _, _, chat := bootstrap(r) + data := testPNG(t, 2, 2) + att := r.uploadOK(alice.ID, chat.ID, data) + + r.objects.Down.Store(true) + resp := r.upload(alice.ID, chat.ID, "b.png", "image/png", data) + expectStatus(t, resp, http.StatusServiceUnavailable) + if code := readError(t, resp).Error.Code; code != "unavailable" { + t.Errorf("code = %q", code) + } + resp = r.do(http.MethodGet, "/api/v1/attachments/"+att.ID+"/content", alice.ID, nil, nil) + expectStatus(t, resp, http.StatusServiceUnavailable) + resp.Body.Close() + // Метаданные лежат в БД и остаются доступными. + resp = r.do(http.MethodGet, "/api/v1/attachments/"+att.ID, alice.ID, nil, nil) + expectStatus(t, resp, http.StatusOK) + resp.Body.Close() + if code, _ := r.send(alice, chat.ID, "текст без S3"); code != http.StatusCreated { + t.Errorf("message status = %d", code) + } + + r.objects.Down.Store(false) + resp = r.do(http.MethodGet, "/api/v1/attachments/"+att.ID+"/content", alice.ID, nil, nil) + expectStatus(t, resp, http.StatusOK) + resp.Body.Close() +} + +func TestAttachment_UnknownVariant(t *testing.T) { + r := newTestRig(t) + alice, _, _, chat := bootstrap(r) + att := r.uploadOK(alice.ID, chat.ID, testPNG(t, 2, 2)) + for query, want := range map[string]int{"?variant=original": 200, "?variant=thumbnail": 404, "?variant=../x": 400, "?variant=": 400} { + resp := r.do(http.MethodGet, "/api/v1/attachments/"+att.ID+"/content"+query, alice.ID, nil, nil) + if resp.StatusCode != want { + t.Errorf("%s: status = %d, want %d", query, resp.StatusCode, want) + } + resp.Body.Close() + } +} + +func TestMessage_AttachmentRules(t *testing.T) { + r := newTestRig(t) + alice, bob, _, chat := bootstrap(r) + other := r.createChat(alice, "другой", alice.ID) + data := testPNG(t, 2, 2) + att := r.uploadOK(alice.ID, chat.ID, data) + foreign := r.uploadOK(alice.ID, other.ID, data) + path := "/api/v1/chats/" + chat.ID + "/messages" + + post := func(body string) *http.Response { + return r.do(http.MethodPost, path, bob.ID, map[string]string{"Content-Type": "application/json"}, strings.NewReader(body)) + } + cases := []struct { + name string + body string + want int + }{ + {"empty text with attachment", `{"text":"","attachment_ids":["` + att.ID + `"]}`, 201}, + {"spaces with attachment", `{"text":" ","attachment_ids":["` + att.ID + `"]}`, 201}, + {"empty attachment list is the old form", `{"text":"x","attachment_ids":[]}`, 201}, + {"empty text without attachments", `{"text":"","attachment_ids":[]}`, 400}, + {"text is still required", `{"attachment_ids":["` + att.ID + `"]}`, 400}, + {"null list", `{"text":"x","attachment_ids":null}`, 400}, + {"wrong type", `{"text":"x","attachment_ids":"` + att.ID + `"}`, 400}, + {"invalid id", `{"text":"x","attachment_ids":["nope"]}`, 400}, + {"duplicate", `{"text":"x","attachment_ids":["` + att.ID + `","` + strings.ToUpper(att.ID) + `"]}`, 400}, + {"unknown attachment", `{"text":"x","attachment_ids":["` + uuid.NewString() + `"]}`, 404}, + {"attachment of another chat", `{"text":"x","attachment_ids":["` + foreign.ID + `"]}`, 404}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + resp := post(tc.body) + defer resp.Body.Close() + if resp.StatusCode != tc.want { + body, _ := io.ReadAll(resp.Body) + t.Fatalf("status = %d, want %d, body = %s", resp.StatusCode, tc.want, body) + } + }) + } + + items, _ := r.listMessages(alice, chat.ID, 100) + if len(items) != 3 || len(items[0].AttachmentIDs) != 1 || items[0].AttachmentIDs[0] != att.ID { + t.Errorf("history = %+v", items) + } + if items[2].AttachmentIDs == nil { + t.Error("message without attachments must have [] rather than null") + } +} + +func TestMessage_IdempotencyCoversAttachments(t *testing.T) { + r := newTestRig(t) + alice, _, _, chat := bootstrap(r) + a := r.uploadOK(alice.ID, chat.ID, testPNG(t, 2, 2)).ID + b := r.uploadOK(alice.ID, chat.ID, testPNG(t, 3, 3)).ID + key := uuid.NewString() + + code, first := r.postKeyed(alice.ID, chat.ID, key, `{"text":"x","attachment_ids":["`+a+`","`+b+`"]}`) + if code != http.StatusCreated { + t.Fatalf("first: %d %s", code, first) + } + code, replay := r.postKeyed(alice.ID, chat.ID, key, `{"attachment_ids":["`+a+`","`+b+`"],"text":"x"}`) + if code != http.StatusCreated || !bytes.Equal(first, replay) { + t.Errorf("replay: %d %s", code, replay) + } + if code, body := r.postKeyed(alice.ID, chat.ID, key, `{"text":"x","attachment_ids":["`+b+`"]}`); code != http.StatusConflict { + t.Errorf("other attachments: %d %s", code, body) + } + // Отсутствующий attachment_ids равен пустому списку. + plain := uuid.NewString() + if code, _ := r.postKeyed(alice.ID, chat.ID, plain, `{"text":"y"}`); code != http.StatusCreated { + t.Fatalf("plain: %d", code) + } + if code, body := r.postKeyed(alice.ID, chat.ID, plain, `{"text":"y","attachment_ids":[]}`); code != http.StatusCreated { + t.Errorf("plain replay: %d %s", code, body) + } +} + +// failingMetadata имитирует отказ БД между записью в S3 и записью метаданных. +type failingMetadata struct{ *store.Memory } + +func (f failingMetadata) CreateAttachment(context.Context, domain.Attachment) (domain.Attachment, error) { + return domain.Attachment{}, domain.ErrUnavailable +} + +func TestAttachment_MetadataFailureRemovesObject(t *testing.T) { + r := newTestRig(t) + alice, _, _, chat := bootstrap(r) + objects := objectstore.NewMemory() + svc := service.NewAttachments(failingMetadata{r.memory}, objects, service.AttachmentLimits{ + MaxUploadBytes: testMaxUploadBytes, MaxImagePixels: testMaxImagePixels, MaxConcurrentUploads: 1, + }, slog.New(slog.NewTextHandler(io.Discard, nil))) + + data := testPNG(t, 2, 2) + _, err := svc.Upload(context.Background(), service.UploadInput{ + CallerID: alice.ID, ChatID: chat.ID, Filename: "a.png", ContentType: "image/png", + ContentLength: int64(len(data)), Body: bytes.NewReader(data), + }) + if !errors.Is(err, domain.ErrUnavailable) { + t.Fatalf("err = %v", err) + } + if keys := objects.Keys(); len(keys) != 0 { + t.Errorf("object left without metadata: %v", keys) + } +} + +// lostCommit имитирует потерю ответа: строка сохранилась, а INSERT вернул ошибку. +type lostCommit struct{ *store.Memory } + +func (l lostCommit) CreateAttachment(ctx context.Context, att domain.Attachment) (domain.Attachment, error) { + if _, err := l.Memory.CreateAttachment(ctx, att); err != nil { + return domain.Attachment{}, err + } + return domain.Attachment{}, domain.ErrUnavailable +} + +// metadataDown имитирует БД, недоступную и для записи, и для проверки перед компенсацией. +type metadataDown struct{ failingMetadata } + +func (metadataDown) AttachmentExists(context.Context, string) (bool, error) { + return false, domain.ErrUnavailable +} + +func uploadVia(t *testing.T, svc *service.Attachments, caller, chatID string, body io.Reader, size int64) error { + t.Helper() + _, err := svc.Upload(context.Background(), service.UploadInput{ + CallerID: caller, ChatID: chatID, Filename: "a.png", ContentType: "image/png", ContentLength: size, Body: body, + }) + return err +} + +// Строка в БД не должна остаться без файла: при потерянном ответе объект удалять нельзя. +func TestAttachment_LostCommitKeepsObject(t *testing.T) { + r := newTestRig(t) + alice, _, _, chat := bootstrap(r) + objects := objectstore.NewMemory() + svc := service.NewAttachments(lostCommit{r.memory}, objects, service.AttachmentLimits{ + MaxUploadBytes: testMaxUploadBytes, MaxImagePixels: testMaxImagePixels, MaxConcurrentUploads: 1, + }, slog.New(slog.NewTextHandler(io.Discard, nil))) + data := testPNG(t, 2, 2) + if err := uploadVia(t, svc, alice.ID, chat.ID, bytes.NewReader(data), int64(len(data))); !errors.Is(err, domain.ErrUnavailable) { + t.Fatalf("err = %v", err) + } + if keys := objects.Keys(); len(keys) != 1 { + t.Errorf("object of a committed row was deleted: %v", keys) + } +} + +// Если проверить нельзя, объект остаётся очистителю, а не удаляется вслепую. +func TestAttachment_UncheckableMetadataLeavesObjectToJanitor(t *testing.T) { + r := newTestRig(t) + alice, _, _, chat := bootstrap(r) + objects := objectstore.NewMemory() + svc := service.NewAttachments(metadataDown{failingMetadata{r.memory}}, objects, service.AttachmentLimits{ + MaxUploadBytes: testMaxUploadBytes, MaxImagePixels: testMaxImagePixels, MaxConcurrentUploads: 1, + }, slog.New(slog.NewTextHandler(io.Discard, nil))) + data := testPNG(t, 2, 2) + if err := uploadVia(t, svc, alice.ID, chat.ID, bytes.NewReader(data), int64(len(data))); !errors.Is(err, domain.ErrUnavailable) { + t.Fatalf("err = %v", err) + } + if keys := objects.Keys(); len(keys) != 1 { + t.Errorf("object deleted without a metadata check: %v", keys) + } +} + +// brokenBody отдаёт начало файла и обрывается: так выглядит отключившийся клиент. +type brokenBody struct{ data []byte } + +func (b *brokenBody) Read(p []byte) (int, error) { + if len(b.data) == 0 { + return 0, io.ErrUnexpectedEOF + } + n := copy(p, b.data) + b.data = b.data[n:] + return n, nil +} + +func spoolFiles(t *testing.T, dir string) []string { + t.Helper() + entries, err := os.ReadDir(dir) + if err != nil { + t.Fatal(err) + } + names := make([]string, 0, len(entries)) + for _, entry := range entries { + names = append(names, entry.Name()) + } + return names +} + +func TestAttachment_InterruptedUploadLeavesNothing(t *testing.T) { + dir := t.TempDir() + t.Setenv("TMPDIR", dir) + r := newTestRig(t) + alice, _, _, chat := bootstrap(r) + svc := service.NewAttachments(r.memory, r.objects, service.AttachmentLimits{ + MaxUploadBytes: testMaxUploadBytes, MaxImagePixels: testMaxImagePixels, MaxConcurrentUploads: 1, + }, slog.New(slog.NewTextHandler(io.Discard, nil))) + data := testPNG(t, 8, 8) + err := uploadVia(t, svc, alice.ID, chat.ID, &brokenBody{data: bytes.Clone(data[:len(data)/2])}, int64(len(data))) + var invalid *validate.Error + if !errors.As(err, &invalid) { + t.Fatalf("err = %v, want a client error rather than 500", err) + } + if keys := r.objects.Keys(); len(keys) != 0 { + t.Errorf("interrupted upload reached S3: %v", keys) + } + if files := spoolFiles(t, dir); len(files) != 0 { + t.Errorf("temporary files left: %v", files) + } + // Слот освобождён: следующая загрузка проходит при лимите в один файл. + if err := uploadVia(t, svc, alice.ID, chat.ID, bytes.NewReader(data), int64(len(data))); err != nil { + t.Errorf("slot was not released: %v", err) + } +} + +func TestAttachment_TemporaryFileIsRemovedWhileUploadIsRunning(t *testing.T) { + dir := t.TempDir() + t.Setenv("TMPDIR", dir) + r := newTestRig(t) + alice, _, _, chat := bootstrap(r) + svc := service.NewAttachments(r.memory, r.objects, service.AttachmentLimits{ + MaxUploadBytes: testMaxUploadBytes, MaxImagePixels: testMaxImagePixels, MaxConcurrentUploads: 1, + }, slog.New(slog.NewTextHandler(io.Discard, nil))) + blocked := &blockingReader{release: make(chan struct{}), started: make(chan struct{})} + done := make(chan error, 1) + go func() { done <- uploadVia(t, svc, alice.ID, chat.ID, blocked, -1) }() + <-blocked.started + // Файл уже открыт и убран из каталога: падение процесса в этот момент ничего не оставит. + if files := spoolFiles(t, dir); len(files) != 0 { + t.Errorf("temporary file is visible during upload: %v", files) + } + close(blocked.release) + <-done +} + +// Тело без Content-Length не должно обойти лимит размера. +func TestAttachment_ChunkedOverLimitGives413(t *testing.T) { + r := newTestRig(t) + alice, _, _, chat := bootstrap(r) + big := append(testPNG(t, 2, 2), make([]byte, testMaxUploadBytes)...) + req, err := http.NewRequest(http.MethodPost, r.server.URL+"/api/v1/chats/"+chat.ID+"/attachments?filename=a.png", io.MultiReader(bytes.NewReader(big))) + if err != nil { + t.Fatal(err) + } + req.ContentLength = -1 + req.Header.Set("Content-Type", "image/png") + r.setAuth(req, alice.ID) + resp, err := r.client.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + expectStatus(t, resp, http.StatusRequestEntityTooLarge) + if keys := r.objects.Keys(); len(keys) != 0 { + t.Errorf("oversized upload reached S3: %v", keys) + } +} + +// blockingReader держит загрузку открытой, пока тест не разрешит продолжить. +type blockingReader struct { + release chan struct{} + started chan struct{} +} + +func (b *blockingReader) Read([]byte) (int, error) { + close(b.started) + <-b.release + return 0, io.EOF +} + +func TestAttachment_ConcurrentUploadLimitGives429(t *testing.T) { + r := newTestRig(t) + alice, _, _, chat := bootstrap(r) + objects := objectstore.NewMemory() + svc := service.NewAttachments(r.memory, objects, service.AttachmentLimits{ + MaxUploadBytes: testMaxUploadBytes, MaxImagePixels: testMaxImagePixels, MaxConcurrentUploads: 1, + }, slog.New(slog.NewTextHandler(io.Discard, nil))) + + blocked := &blockingReader{release: make(chan struct{}), started: make(chan struct{})} + done := make(chan error, 1) + go func() { + _, err := svc.Upload(context.Background(), service.UploadInput{ + CallerID: alice.ID, ChatID: chat.ID, Filename: "a.png", ContentType: "image/png", Body: blocked, + }) + done <- err + }() + <-blocked.started + + data := testPNG(t, 2, 2) + _, err := svc.Upload(context.Background(), service.UploadInput{ + CallerID: alice.ID, ChatID: chat.ID, Filename: "b.png", ContentType: "image/png", Body: bytes.NewReader(data), + }) + if !errors.Is(err, domain.ErrRateLimited) { + t.Errorf("second upload: %v", err) + } + close(blocked.release) + <-done +} + +// Клиент, который читает ответ только после отправки всего тела, должен получить код, а не обрыв. +func TestAttachment_RejectedBodyIsDrainedSoClientGetsStatus(t *testing.T) { + r := newTestRig(t) + alice, _, eve, chat := bootstrap(r) + big := make([]byte, 8*testMaxUploadBytes) + path := "/api/v1/chats/" + chat.ID + "/attachments?filename=a.png" + cases := []struct { + name string + actor string + want int + }{ + {"too large", alice.ID, http.StatusRequestEntityTooLarge}, + {"outsider", eve.ID, http.StatusNotFound}, + {"no session", "", http.StatusUnauthorized}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + for _, length := range []int64{int64(len(big)), -1} { // с Content-Length и chunked + req, err := http.NewRequest(http.MethodPost, r.server.URL+path, io.MultiReader(bytes.NewReader(big))) + if err != nil { + t.Fatal(err) + } + req.ContentLength = length + req.Header.Set("Content-Type", "image/png") + r.setAuth(req, tc.actor) + resp, err := r.client.Do(req) + if err != nil { + t.Fatalf("length %d: %v", length, err) + } + resp.Body.Close() + if resp.StatusCode != tc.want { + t.Errorf("length %d: status = %d, want %d", length, resp.StatusCode, tc.want) + } + } + }) + } +} diff --git a/app/internal/api/http/auth.go b/app/internal/api/http/auth.go new file mode 100644 index 00000000..535a2a59 --- /dev/null +++ b/app/internal/api/http/auth.go @@ -0,0 +1,69 @@ +package http + +import ( + "encoding/base64" + "errors" + "net/http" + "strings" + "unicode/utf8" + + "github.com/labstack/echo/v4" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/middleware" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/service" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate" +) + +type authHandler struct { + auth service.AuthService +} + +func (h *authHandler) createSession(c echo.Context) error { + if c.Request().ContentLength > 0 { + return WriteError(c, &validate.Error{Field: "body", Reason: "must be empty, credentials go in Authorization: Basic"}) + } + username, password, ok := parseBasic(c.Request().Header.Get(echo.HeaderAuthorization)) + if !ok { + return middleware.Unauthorized(c, middleware.BasicChallenge, "Invalid credentials") + } + + s, err := h.auth.Login(c.Request().Context(), username, password) + if err != nil { + if errors.Is(err, domain.ErrUnauthorized) { + return middleware.Unauthorized(c, middleware.BasicChallenge, "Invalid credentials") + } + return WriteError(c, err) + } + return c.JSON(http.StatusCreated, dto.SessionResponse{ + Token: s.Token, + TokenType: "Bearer", + ExpiresAt: dto.NewTimestamp(s.ExpiresAt), + User: toUserResponse(s.User), + }) +} + +func (h *authHandler) revokeSession(c echo.Context) error { + tok := c.Get(middleware.AuthTokenKey).(string) + if err := h.auth.Logout(c.Request().Context(), tok); err != nil { + return WriteError(c, err) + } + return c.NoContent(http.StatusNoContent) +} + +func parseBasic(header string) (username, password string, ok bool) { + scheme, encoded, found := strings.Cut(header, " ") + if !found || !strings.EqualFold(scheme, "Basic") { + return "", "", false + } + raw, err := base64.StdEncoding.DecodeString(strings.TrimSpace(encoded)) + if err != nil || !utf8.Valid(raw) { + return "", "", false + } + username, password, found = strings.Cut(string(raw), ":") + if !found || username == "" || password == "" { + return "", "", false + } + return username, password, true +} diff --git a/app/internal/api/http/auth_test.go b/app/internal/api/http/auth_test.go new file mode 100644 index 00000000..7bc85548 --- /dev/null +++ b/app/internal/api/http/auth_test.go @@ -0,0 +1,217 @@ +package http + +import ( + "context" + "encoding/base64" + "io" + "net/http" + "strings" + "testing" + "time" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/session" +) + +const ( + basicChallenge = `Basic realm="messenger", charset="UTF-8"` + bearerChallenge = `Bearer realm="messenger"` +) + +func expectUnauthorized(t *testing.T, resp *http.Response, challenge string) { + t.Helper() + defer resp.Body.Close() + if resp.StatusCode != http.StatusUnauthorized { + data, _ := io.ReadAll(resp.Body) + t.Fatalf("expected 401, got %d; body=%s", resp.StatusCode, string(data)) + } + if got := resp.Header.Get("WWW-Authenticate"); got != challenge { + t.Fatalf("WWW-Authenticate = %q, want %q", got, challenge) + } + e := readError(t, resp) + if e.Error.Code != CodeUnauthorized || e.Error.RequestID == "" { + t.Fatalf("unexpected error body: %+v", e) + } +} + +func (r *testRig) withHeaders(method, path string, headers map[string]string) *http.Response { + r.t.Helper() + return r.do(method, path, "", headers, nil) +} + +func TestAuth_LoginReturnsSession(t *testing.T) { + r := newTestRig(t) + alice := r.createUser("login_"+randomSuffix(), "Алиса") + + before := time.Now() + s := r.login(alice.Username, testPassword) + if s.TokenType != "Bearer" || len(s.Token) < 32 { + t.Fatalf("bad session: type=%q len(token)=%d", s.TokenType, len(s.Token)) + } + if s.User.ID != alice.ID || s.User.Username != alice.Username { + t.Fatalf("session user = %+v, want %s", s.User, alice.ID) + } + if strings.Contains(s.Token, alice.ID) || strings.Contains(s.Token, alice.Username) { + t.Fatal("token is derived from user identity") + } + if !s.ExpiresAt.After(before.Add(59*time.Minute)) || s.ExpiresAt.After(before.Add(61*time.Minute)) { + t.Fatalf("expires_at = %s, want ~now+1h", s.ExpiresAt) + } + + if again := r.login(alice.Username, testPassword); again.Token == s.Token { + t.Fatal("second login returned the same token") + } +} + +func TestAuth_LoginRejectsBadCredentialsUniformly(t *testing.T) { + r := newTestRig(t) + alice := r.createUser("bad_"+randomSuffix(), "Алиса") + + expectUnauthorized(t, r.basicLogin(alice.Username, "wrong-password-123"), basicChallenge) + expectUnauthorized(t, r.basicLogin("nobody_"+randomSuffix(), testPassword), basicChallenge) + + b64 := func(s string) string { return base64.StdEncoding.EncodeToString([]byte(s)) } + for _, h := range []string{ + "", + "Bearer " + b64(alice.Username+":"+testPassword), + "Basic not-base64!!!", + "Basic " + b64(alice.Username), + "Basic " + b64(alice.Username+":"), + "Basic " + b64(":"+testPassword), + "Basic " + b64(alice.Username+":\xff\xfe"), + } { + headers := map[string]string{} + if h != "" { + headers["Authorization"] = h + } + expectUnauthorized(t, r.withHeaders(http.MethodPost, "/api/v1/auth/sessions", headers), basicChallenge) + } +} + +func TestAuth_PasswordWithColonAndUnicode(t *testing.T) { + r := newTestRig(t) + username := "colon_" + randomSuffix() + pw := "пароль:с:двоеточиями🙂" + resp := r.doJSON(http.MethodPost, "/api/v1/users", "", dto.CreateUserRequest{ + Username: username, DisplayName: "Двоеточие", Password: pw, + }) + expectStatus(t, resp, http.StatusCreated) + resp.Body.Close() + + r.login(username, pw) + expectUnauthorized(t, r.basicLogin(username, "пароль"), basicChallenge) +} + +func TestAuth_LoginRejectsBody(t *testing.T) { + r := newTestRig(t) + alice := r.createUser("body_"+randomSuffix(), "Алиса") + req, _ := http.NewRequest(http.MethodPost, r.server.URL+"/api/v1/auth/sessions", + strings.NewReader(`{"username":"`+alice.Username+`"}`)) + req.Header.Set("Content-Type", "application/json") + req.SetBasicAuth(alice.Username, testPassword) + resp, err := r.client.Do(req) + if err != nil { + t.Fatal(err) + } + expectStatus(t, resp, http.StatusBadRequest) + resp.Body.Close() +} + +func TestAuth_BearerRequired(t *testing.T) { + r := newTestRig(t) + alice, _, eve, _ := bootstrap(r) + + expectUnauthorized(t, r.withHeaders(http.MethodGet, "/api/v1/users/me", nil), bearerChallenge) + expectUnauthorized(t, r.withHeaders(http.MethodGet, "/api/v1/users/me", + map[string]string{"X-User-Id": alice.ID}), bearerChallenge) + basic := base64.StdEncoding.EncodeToString([]byte(alice.Username + ":" + testPassword)) + expectUnauthorized(t, r.withHeaders(http.MethodGet, "/api/v1/users/me", + map[string]string{"Authorization": "Basic " + basic}), bearerChallenge) + expectUnauthorized(t, r.withHeaders(http.MethodGet, "/api/v1/users/me", + map[string]string{"Authorization": "Bearer " + strings.Repeat("A", 43)}), bearerChallenge) + expectUnauthorized(t, r.withHeaders(http.MethodGet, "/api/v1/users/me", + map[string]string{"Authorization": "Bearer " + alice.ID}), bearerChallenge) + + resp := r.do(http.MethodGet, "/api/v1/users/me", alice.ID, map[string]string{"X-User-Id": eve.ID}, nil) + expectStatus(t, resp, http.StatusOK) + var me dto.UserResponse + readJSON(t, resp, &me) + if me.ID != alice.ID { + t.Fatalf("X-User-Id overrode bearer identity: got %s", me.ID) + } + + tok := r.tokens[alice.ID] + resp = r.withHeaders(http.MethodGet, "/api/v1/users/me", map[string]string{"Authorization": "bearer " + tok}) + expectStatus(t, resp, http.StatusOK) + resp.Body.Close() +} + +func TestAuth_Logout(t *testing.T) { + r := newTestRig(t) + alice := r.createUser("logout_"+randomSuffix(), "Алиса") + other := r.login(alice.Username, testPassword) + + resp := r.do(http.MethodDelete, "/api/v1/auth/sessions/current", alice.ID, nil, nil) + expectStatus(t, resp, http.StatusNoContent) + body, _ := io.ReadAll(resp.Body) + resp.Body.Close() + if len(body) != 0 { + t.Fatalf("204 with body %q", body) + } + + expectUnauthorized(t, r.do(http.MethodGet, "/api/v1/users/me", alice.ID, nil, nil), bearerChallenge) + expectUnauthorized(t, r.do(http.MethodDelete, "/api/v1/auth/sessions/current", alice.ID, nil, nil), bearerChallenge) + + resp = r.withHeaders(http.MethodGet, "/api/v1/users/me", map[string]string{"Authorization": "Bearer " + other.Token}) + expectStatus(t, resp, http.StatusOK) + resp.Body.Close() +} + +func TestAuth_SessionExpires(t *testing.T) { + r := newRig(t, defaultTestLimits, session.NewMemory(), 2*time.Second) + alice := r.createUser("ttl_"+randomSuffix(), "Алиса") + + resp := r.do(http.MethodGet, "/api/v1/users/me", alice.ID, nil, nil) + expectStatus(t, resp, http.StatusOK) + resp.Body.Close() + + time.Sleep(2100 * time.Millisecond) + expectUnauthorized(t, r.do(http.MethodGet, "/api/v1/users/me", alice.ID, nil, nil), bearerChallenge) +} + +type brokenSessions struct { + *session.Memory + down bool +} + +func (b *brokenSessions) Get(ctx context.Context, h []byte) (session.Session, error) { + if b.down { + return session.Session{}, domain.ErrUnavailable + } + return b.Memory.Get(ctx, h) +} + +func (b *brokenSessions) Save(ctx context.Context, h []byte, s session.Session) error { + if b.down { + return domain.ErrUnavailable + } + return b.Memory.Save(ctx, h, s) +} + +func TestAuth_SessionStoreDownIs503NotAnonymous(t *testing.T) { + store := &brokenSessions{Memory: session.NewMemory()} + r := newRig(t, defaultTestLimits, store, time.Hour) + alice := r.createUser("down_"+randomSuffix(), "Алиса") + store.down = true + + resp := r.do(http.MethodGet, "/api/v1/users/me", alice.ID, nil, nil) + expectStatus(t, resp, http.StatusServiceUnavailable) + if e := readError(t, resp); e.Error.Code != CodeUnavailable { + t.Fatalf("code = %q, want %q", e.Error.Code, CodeUnavailable) + } + + resp = r.basicLogin(alice.Username, testPassword) + expectStatus(t, resp, http.StatusServiceUnavailable) + resp.Body.Close() +} diff --git a/app/internal/api/http/chats.go b/app/internal/api/http/chats.go new file mode 100644 index 00000000..7f64886e --- /dev/null +++ b/app/internal/api/http/chats.go @@ -0,0 +1,103 @@ +package http + +import ( + "net/http" + "strconv" + + "github.com/labstack/echo/v4" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/middleware" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/service" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate" +) + +type chatsHandler struct { + chats service.ChatsService +} + +func (h *chatsHandler) create(c echo.Context) error { + callerID := c.Get(middleware.AuthUserIDKey).(string) + var req dto.CreateChatRequest + if err := decodeJSON(c.Request().Body, &req); err != nil { + return WriteError(c, err) + } + + chat, err := h.chats.Create(c.Request().Context(), callerID, req.Title, req.MemberIDs) + if err != nil { + return WriteError(c, err) + } + return c.JSON(http.StatusCreated, toChatResponse(chat)) +} + +func (h *chatsHandler) get(c echo.Context) error { + callerID := c.Get(middleware.AuthUserIDKey).(string) + chatID := c.Param("chat_id") + + chat, err := h.chats.Get(c.Request().Context(), callerID, chatID) + if err != nil { + return WriteError(c, err) + } + return c.JSON(http.StatusOK, toChatResponse(chat)) +} + +func (h *chatsHandler) list(c echo.Context) error { + callerID := c.Get(middleware.AuthUserIDKey).(string) + limit, cursor, err := parsePageParams(c) + if err != nil { + return WriteError(c, err) + } + + page, err := h.chats.List(c.Request().Context(), callerID, cursor, limit) + if err != nil { + return WriteError(c, err) + } + return c.JSON(http.StatusOK, toChatsPage(page)) +} + +func toChatResponse(ch domain.Chat) dto.ChatResponse { + members := make([]string, len(ch.MemberIDs)) + copy(members, ch.MemberIDs) + return dto.ChatResponse{ + ID: ch.ID, + Title: ch.Title, + MemberIDs: members, + CreatedAt: dto.NewTimestamp(ch.CreatedAt), + } +} + +func toChatsPage(p domain.Page[domain.Chat]) dto.ChatsPageResponse { + items := make([]dto.ChatResponse, 0, len(p.Items)) + for _, ch := range p.Items { + items = append(items, toChatResponse(ch)) + } + var next *string + if p.NextCursor != "" { + s := p.NextCursor + next = &s + } + return dto.ChatsPageResponse{Items: items, NextCursor: next} +} + +func parsePageParams(c echo.Context) (int, string, error) { + q := c.QueryParams() + + limit := validate.LimitDefault + if vals, ok := q["limit"]; ok { + n, err := strconv.Atoi(vals[0]) + if err != nil { + return 0, "", &validate.Error{Field: "limit", Reason: "must be an integer"} + } + limit = n + } + + cursor := "" + if vals, ok := q["cursor"]; ok { + if vals[0] == "" { + return 0, "", &validate.Error{Field: "cursor", Reason: "must not be empty"} + } + cursor = vals[0] + } + return limit, cursor, nil +} diff --git a/app/internal/api/http/concurrency_test.go b/app/internal/api/http/concurrency_test.go new file mode 100644 index 00000000..a567cbd8 --- /dev/null +++ b/app/internal/api/http/concurrency_test.go @@ -0,0 +1,84 @@ +package http + +import ( + "fmt" + "net/http" + "sync" + "testing" +) + +func TestConcurrency_100MessagesFrom10Clients(t *testing.T) { + const clients = 10 + const perClient = 10 + const total = clients * perClient + + r := newTestRig(t) + users := make([]testUser, clients) + memberIDs := make([]string, clients) + for i := range users { + users[i] = r.createUser(fmt.Sprintf("race_%02d_%s", i, randomSuffix()), fmt.Sprintf("Клиент %d", i)) + memberIDs[i] = users[i].ID + } + chat := r.createChat(users[0], "Гонка", memberIDs...) + + type result struct { + id, text string + err error + } + results := make(chan result, total) + start := make(chan struct{}) + var wg sync.WaitGroup + for i, actor := range users { + wg.Add(1) + go func() { + defer wg.Done() + <-start + for j := 0; j < perClient; j++ { + text := fmt.Sprintf("race-c%02d-m%02d", i, j) + status, msg, body := r.sendRaw(actor, chat.ID, mustJSON(map[string]string{"text": text})) + if status != http.StatusCreated { + results <- result{err: fmt.Errorf("%s: status %d: %s", text, status, body)} + continue + } + results <- result{id: msg.ID, text: msg.Text} + } + }() + } + close(start) + wg.Wait() + close(results) + + sentIDs := make(map[string]string, total) + for res := range results { + if res.err != nil { + t.Fatal(res.err) + } + if _, dup := sentIDs[res.id]; dup { + t.Fatalf("сервер выдал один id %s двум сообщениям", res.id) + } + sentIDs[res.id] = res.text + } + if len(sentIDs) != total { + t.Fatalf("подтверждено %d сообщений, ожидалось %d", len(sentIDs), total) + } + + history, _ := r.listMessages(users[0], chat.ID, 100) + if len(history) != total { + t.Fatalf("в истории %d сообщений, ожидалось ровно %d", len(history), total) + } + seen := make(map[string]struct{}, total) + for i, m := range history { + if _, dup := seen[m.ID]; dup { + t.Fatalf("id %s встречается в истории дважды", m.ID) + } + seen[m.ID] = struct{}{} + if text, ok := sentIDs[m.ID]; !ok || text != m.Text { + t.Fatalf("сообщение %s (%q) в истории не совпадает с подтверждённым", m.ID, m.Text) + } + if i > 0 && !history[i-1].CreatedAt.Before(m.CreatedAt.Time) { + t.Fatalf("порядок (created_at) нарушен на индексе %d", i) + } + } + t.Logf("%d клиентов × %d сообщений = %d уникальных сообщений в истории, 0 дубликатов", + clients, perClient, total) +} diff --git a/app/internal/api/http/direct_upload.go b/app/internal/api/http/direct_upload.go new file mode 100644 index 00000000..44c3e705 --- /dev/null +++ b/app/internal/api/http/direct_upload.go @@ -0,0 +1,54 @@ +package http + +import ( + "context" + "net/http" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/middleware" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/service" + "github.com/labstack/echo/v4" +) + +// Optional extension keeps the mandatory proxy contract unchanged. +type directAttachments interface { + InitDirect(context.Context, string, string, service.DirectInput) (service.DirectUpload, error) + CompleteDirect(context.Context, string, string, string) (domain.Attachment, error) +} + +func (h *attachmentsHandler) directInit(c echo.Context) error { + svc, ok := h.attachments.(directAttachments) + if !ok { + return WriteError(c, domain.ErrUnavailable) + } + var in service.DirectInput + if err := decodeJSON(c.Request().Body, &in); err != nil { + return WriteError(c, domain.ErrInvalidArgument) + } + out, err := svc.InitDirect(c.Request().Context(), c.Get(middleware.AuthUserIDKey).(string), c.Param("chat_id"), in) + if err != nil { + return WriteError(c, err) + } + c.Response().Header().Set("Cache-Control", "no-store") + return c.JSON(http.StatusCreated, out) +} + +func (h *attachmentsHandler) directComplete(c echo.Context) error { + svc, ok := h.attachments.(directAttachments) + if !ok { + return WriteError(c, domain.ErrUnavailable) + } + var in struct { + Token string `json:"token"` + } + if err := decodeJSON(c.Request().Body, &in); err != nil { + return WriteError(c, domain.ErrInvalidArgument) + } + ctx, cancel := context.WithTimeout(c.Request().Context(), transferTimeout) + defer cancel() + att, err := svc.CompleteDirect(ctx, c.Get(middleware.AuthUserIDKey).(string), c.Param("chat_id"), in.Token) + if err != nil { + return WriteError(c, err) + } + return c.JSON(http.StatusCreated, toAttachmentResponse(att)) +} diff --git a/app/internal/api/http/dto/attachment.go b/app/internal/api/http/dto/attachment.go new file mode 100644 index 00000000..a59e9ed6 --- /dev/null +++ b/app/internal/api/http/dto/attachment.go @@ -0,0 +1,27 @@ +package dto + +// VariantResponse — преобразованная копия. В lab4 вариантов нет, список всегда пуст. +type VariantResponse struct { + Name string `json:"name"` + ContentType string `json:"content_type"` + SizeBytes int64 `json:"size_bytes"` + Width int `json:"width"` + Height int `json:"height"` + SHA256 string `json:"sha256"` +} + +// AttachmentResponse намеренно не содержит object key: он внутренний. +type AttachmentResponse struct { + ID string `json:"id"` + ChatID string `json:"chat_id"` + OwnerID string `json:"owner_id"` + Filename string `json:"filename"` + ContentType string `json:"content_type"` + SizeBytes int64 `json:"size_bytes"` + SHA256 string `json:"sha256"` + Status string `json:"status"` + Variants []VariantResponse `json:"variants"` + ErrorCode *string `json:"error_code"` + CreatedAt Timestamp `json:"created_at"` + UpdatedAt Timestamp `json:"updated_at"` +} diff --git a/app/internal/api/http/dto/chat.go b/app/internal/api/http/dto/chat.go new file mode 100644 index 00000000..7f7bbdd2 --- /dev/null +++ b/app/internal/api/http/dto/chat.go @@ -0,0 +1,18 @@ +package dto + +type CreateChatRequest struct { + Title string `json:"title"` + MemberIDs []string `json:"member_ids"` +} + +type ChatResponse struct { + ID string `json:"id"` + Title string `json:"title"` + MemberIDs []string `json:"member_ids"` + CreatedAt Timestamp `json:"created_at"` +} + +type ChatsPageResponse struct { + Items []ChatResponse `json:"items"` + NextCursor *string `json:"next_cursor"` +} diff --git a/app/internal/api/http/dto/message.go b/app/internal/api/http/dto/message.go new file mode 100644 index 00000000..bd1c2686 --- /dev/null +++ b/app/internal/api/http/dto/message.go @@ -0,0 +1,37 @@ +package dto + +import ( + "encoding/json" + "errors" +) + +// AttachmentIDList — необязательное поле: отсутствие равно [], но явный null по контракту неверен. +// Обычный срез принял бы null молча, поэтому разбор свой. +type AttachmentIDList []string + +func (l *AttachmentIDList) UnmarshalJSON(data []byte) error { + if string(data) == "null" { + return errors.New("attachment_ids must be an array") + } + return json.Unmarshal(data, (*[]string)(l)) +} + +type CreateMessageRequest struct { + // Text — указатель: поле обязательно и при наличии вложений, а "" допустим только с ними. + Text *string `json:"text"` + AttachmentIDs AttachmentIDList `json:"attachment_ids"` +} + +type MessageResponse struct { + ID string `json:"id"` + ChatID string `json:"chat_id"` + SenderID string `json:"sender_id"` + Text string `json:"text"` + CreatedAt Timestamp `json:"created_at"` + AttachmentIDs []string `json:"attachment_ids"` +} + +type MessagesPageResponse struct { + Items []MessageResponse `json:"items"` + NextCursor *string `json:"next_cursor"` +} diff --git a/app/internal/api/http/dto/timestamp.go b/app/internal/api/http/dto/timestamp.go new file mode 100644 index 00000000..02a5693b --- /dev/null +++ b/app/internal/api/http/dto/timestamp.go @@ -0,0 +1,20 @@ +package dto + +import "time" + +const timestampLayout = "2006-01-02T15:04:05.000000Z" + +// Timestamp сериализуется в UTC всегда с 6 цифрами дробной части. Стандартный формат +// time.Time отбрасывает нули в конце (…17.95188Z): это корректный RFC 3339, но такое значение +// не разбирает datetime.fromisoformat в Python 3.9–3.10, на которых идут публичные тесты. +type Timestamp struct { + time.Time +} + +func NewTimestamp(t time.Time) Timestamp { + return Timestamp{Time: t} +} + +func (t Timestamp) MarshalJSON() ([]byte, error) { + return []byte(`"` + t.UTC().Format(timestampLayout) + `"`), nil +} diff --git a/app/internal/api/http/dto/timestamp_test.go b/app/internal/api/http/dto/timestamp_test.go new file mode 100644 index 00000000..7a4df0e2 --- /dev/null +++ b/app/internal/api/http/dto/timestamp_test.go @@ -0,0 +1,48 @@ +package dto + +import ( + "encoding/json" + "testing" + "time" +) + +func TestTimestampAlwaysHasSixFractionalDigits(t *testing.T) { + moscow := time.FixedZone("MSK", 3*60*60) + cases := []struct { + name string + in time.Time + want string + }{ + {"нули в конце", time.Date(2026, 11, 4, 9, 47, 17, 951880000, time.UTC), `"2026-11-04T09:47:17.951880Z"`}, + {"без дробной части", time.Date(2026, 11, 4, 9, 47, 17, 0, time.UTC), `"2026-11-04T09:47:17.000000Z"`}, + {"шесть цифр", time.Date(2026, 11, 4, 9, 47, 17, 123456000, time.UTC), `"2026-11-04T09:47:17.123456Z"`}, + {"наносекунды отбрасываются", time.Date(2026, 11, 4, 9, 47, 17, 123456789, time.UTC), `"2026-11-04T09:47:17.123456Z"`}, + {"приводится к UTC", time.Date(2026, 11, 4, 12, 47, 17, 500000000, moscow), `"2026-11-04T09:47:17.500000Z"`}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + got, err := json.Marshal(NewTimestamp(c.in)) + if err != nil { + t.Fatal(err) + } + if string(got) != c.want { + t.Fatalf("got %s, want %s", got, c.want) + } + }) + } +} + +func TestTimestampRoundTrip(t *testing.T) { + want := time.Date(2026, 11, 4, 9, 47, 17, 951880000, time.UTC) + data, err := json.Marshal(MessageResponse{CreatedAt: NewTimestamp(want)}) + if err != nil { + t.Fatal(err) + } + var got MessageResponse + if err := json.Unmarshal(data, &got); err != nil { + t.Fatal(err) + } + if !got.CreatedAt.Equal(want) { + t.Fatalf("got %s, want %s", got.CreatedAt, want) + } +} diff --git a/app/internal/api/http/dto/user.go b/app/internal/api/http/dto/user.go new file mode 100644 index 00000000..65905cf2 --- /dev/null +++ b/app/internal/api/http/dto/user.go @@ -0,0 +1,21 @@ +package dto + +type CreateUserRequest struct { + Username string `json:"username"` + DisplayName string `json:"display_name"` + Password string `json:"password"` +} + +type UserResponse struct { + ID string `json:"id"` + Username string `json:"username"` + DisplayName string `json:"display_name"` + CreatedAt Timestamp `json:"created_at"` +} + +type SessionResponse struct { + Token string `json:"token"` + TokenType string `json:"token_type"` + ExpiresAt Timestamp `json:"expires_at"` + User UserResponse `json:"user"` +} diff --git a/app/internal/api/http/errors.go b/app/internal/api/http/errors.go new file mode 100644 index 00000000..5a4dc8ff --- /dev/null +++ b/app/internal/api/http/errors.go @@ -0,0 +1,83 @@ +package http + +import ( + "errors" + "net/http" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate" + "github.com/labstack/echo/v4" +) + +const ( + CodeInvalidRequest = "invalid_request" + CodeUnauthorized = "unauthorized" + CodeNotFound = "not_found" + CodeConflict = "conflict" + CodePayloadTooLarge = "payload_too_large" + CodeUnsupportedMedia = "unsupported_media_type" + CodeRateLimited = "rate_limited" + CodeUnavailable = "unavailable" + CodeInternalError = "internal_error" +) + +type errorBody struct { + Error errorPayload `json:"error"` +} + +type errorPayload struct { + Code string `json:"code"` + Message string `json:"message"` + RequestID string `json:"request_id"` +} + +var ( + ErrUnauthorized = errors.New("unauthorized") + ErrUnsupportedMedia = errors.New("unsupported media type") +) + +func Classify(err error) (status int, code, message string) { + switch { + case errors.Is(err, domain.ErrIdempotencyConflict): + return http.StatusConflict, CodeConflict, "Idempotency-Key was already used with a different request" + case errors.Is(err, domain.ErrNotFound): + return http.StatusNotFound, CodeNotFound, "Object not found" + case errors.Is(err, domain.ErrConflict): + return http.StatusConflict, CodeConflict, "Resource already exists" + case errors.Is(err, domain.ErrInvalidArgument): + return http.StatusBadRequest, CodeInvalidRequest, "Invalid request arguments" + case errors.Is(err, domain.ErrUnavailable): + return http.StatusServiceUnavailable, CodeUnavailable, "Service temporarily unavailable" + case errors.Is(err, domain.ErrPayloadTooLarge): + return http.StatusRequestEntityTooLarge, CodePayloadTooLarge, "Request body too large" + case errors.Is(err, domain.ErrRateLimited): + return http.StatusTooManyRequests, CodeRateLimited, "Too many concurrent requests" + case errors.Is(err, ErrUnauthorized), errors.Is(err, domain.ErrUnauthorized): + return http.StatusUnauthorized, CodeUnauthorized, "Identification required" + case errors.Is(err, domain.ErrUnsupportedMedia): + return http.StatusUnsupportedMediaType, CodeUnsupportedMedia, "Expected a valid PNG or JPEG image" + case errors.Is(err, ErrUnsupportedMedia): + return http.StatusUnsupportedMediaType, CodeUnsupportedMedia, "Expected Content-Type: application/json" + } + + var vErr *validate.Error + if errors.As(err, &vErr) { + return http.StatusBadRequest, CodeInvalidRequest, vErr.Error() + } + + return http.StatusInternalServerError, CodeInternalError, "Internal server error" +} + +func WriteError(c echo.Context, err error) error { + status, code, msg := Classify(err) + if status == http.StatusTooManyRequests { + c.Response().Header().Set("Retry-After", "1") + } + return c.JSON(status, errorBody{ + Error: errorPayload{ + Code: code, + Message: msg, + RequestID: c.Response().Header().Get(echo.HeaderXRequestID), + }, + }) +} diff --git a/app/internal/api/http/health.go b/app/internal/api/http/health.go new file mode 100644 index 00000000..ae459ea1 --- /dev/null +++ b/app/internal/api/http/health.go @@ -0,0 +1,24 @@ +package http + +import ( + "net/http" + + "github.com/labstack/echo/v4" +) + +type healthResponse struct { + Status string `json:"status"` +} + +func healthLive(c echo.Context) error { + return c.JSON(http.StatusOK, healthResponse{Status: "ok"}) +} + +func healthReady(isReady func() bool) echo.HandlerFunc { + return func(c echo.Context) error { + if !isReady() { + return echo.NewHTTPError(http.StatusServiceUnavailable, "Service unavailable") + } + return c.JSON(http.StatusOK, healthResponse{Status: "ok"}) + } +} diff --git a/app/internal/api/http/helpers_test.go b/app/internal/api/http/helpers_test.go new file mode 100644 index 00000000..97bffb9f --- /dev/null +++ b/app/internal/api/http/helpers_test.go @@ -0,0 +1,358 @@ +package http + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync" + "testing" + "time" + + "github.com/google/uuid" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/config" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/objectstore" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/password" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/service" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/session" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store" +) + +type testRig struct { + t *testing.T + server *httptest.Server + srv *Server + memory *store.Memory + objects *objectstore.Memory + sessions session.Store + client *http.Client + + mu sync.Mutex + tokens map[string]string +} + +func newTestRig(t *testing.T) *testRig { + return newTestRigWithLimits(t, config.Limits{ + MaxBodyBytes: 1 << 20, + MaxInFlight: 256, + MaxMessagesGlobal: 100000, + MaxHeapBytes: 1 << 40, + }) +} + +func newTestRigWithLimits(t *testing.T, limits config.Limits) *testRig { + t.Helper() + return newRig(t, limits, session.NewMemory(), time.Hour) +} + +const testInstanceID = "test-instance" + +var defaultTestLimits = config.Limits{ + MaxBodyBytes: 1 << 20, + MaxInFlight: 256, + MaxMessagesGlobal: 100000, + MaxHeapBytes: 1 << 40, +} + +func newRig(t *testing.T, limits config.Limits, sessions session.Store, ttl time.Duration) *testRig { + t.Helper() + cfg := &config.Config{ + Env: "test", + Version: "test", + InstanceID: testInstanceID, + HTTP: config.HTTP{ + Addr: "127.0.0.1:0", + ReadTimeoutMs: 10000, + WriteTimeoutMs: 10000, + IdleTimeoutMs: 60000, + ShutdownTimeoutMs: 1000, + }, + Limits: limits, + } + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) + memory := store.NewWithLimit(limits.MaxMessagesGlobal) + hasher := password.NewHasher(testHashParams, 8) + auth, err := service.NewAuth(memory, sessions, hasher, ttl) + if err != nil { + t.Fatal(err) + } + objects := objectstore.NewMemory() + srv := NewServer(Deps{ + Config: cfg, + Logger: logger, + Store: memory, + Auth: auth, + Users: service.NewUsers(memory, hasher), + Chats: service.NewChats(memory), + Messages: service.NewMessages(memory), + Attachments: service.NewAttachments(memory, objects, service.AttachmentLimits{ + MaxUploadBytes: testMaxUploadBytes, + MaxImagePixels: testMaxImagePixels, + MaxConcurrentUploads: testMaxConcurrentUploads, + }, logger), + }) + ts := httptest.NewServer(srv.e) + t.Cleanup(ts.Close) + return &testRig{ + t: t, + server: ts, + srv: srv, + memory: memory, + objects: objects, + sessions: sessions, + client: &http.Client{Timeout: 10 * time.Second}, + tokens: make(map[string]string), + } +} + +type testUser struct { + ID string + Username string + DisplayName string +} + +type errorResp struct { + Error struct { + Code string `json:"code"` + Message string `json:"message"` + RequestID string `json:"request_id"` + } `json:"error"` +} + +func (r *testRig) do(method, path string, actorID string, headers map[string]string, body io.Reader) *http.Response { + r.t.Helper() + req, err := http.NewRequest(method, r.server.URL+path, body) + if err != nil { + r.t.Fatalf("new request %s %s: %v", method, path, err) + } + req.Header.Set("Accept", "application/json") + r.setAuth(req, actorID) + if method == http.MethodPost && strings.HasSuffix(path, "/messages") { + req.Header.Set("Idempotency-Key", uuid.NewString()) + } + for k, v := range headers { + req.Header.Set(k, v) + } + resp, err := r.client.Do(req) + if err != nil { + r.t.Fatalf("do %s %s: %v", method, path, err) + } + return resp +} + +func (r *testRig) doJSON(method, path string, actorID string, payload any) *http.Response { + r.t.Helper() + var body io.Reader + if payload != nil { + body = bytes.NewReader(mustJSON(payload)) + } + return r.do(method, path, actorID, map[string]string{"Content-Type": "application/json"}, body) +} + +func readJSON(t *testing.T, resp *http.Response, dst any) { + t.Helper() + defer resp.Body.Close() + data, err := io.ReadAll(resp.Body) + if err != nil { + t.Fatalf("read body: %v", err) + } + if len(data) == 0 { + return + } + if err := json.Unmarshal(data, dst); err != nil { + t.Fatalf("decode body (%s): %v", string(data), err) + } +} + +func readError(t *testing.T, resp *http.Response) errorResp { + t.Helper() + var e errorResp + readJSON(t, resp, &e) + return e +} + +func expectStatus(t *testing.T, resp *http.Response, want int) { + t.Helper() + if resp.StatusCode != want { + data, _ := io.ReadAll(resp.Body) + resp.Body.Close() + t.Fatalf("expected status %d, got %d; body=%s", want, resp.StatusCode, string(data)) + } +} + +const testPassword = "test-password-123" + +var testHashParams = password.Params{MemoryKiB: 64, Iterations: 1, Parallelism: 1, SaltLen: 16, KeyLen: 32} + +func (r *testRig) createUser(username, displayName string) testUser { + r.t.Helper() + resp := r.doJSON(http.MethodPost, "/api/v1/users", "", dto.CreateUserRequest{ + Username: username, + DisplayName: displayName, + Password: testPassword, + }) + expectStatus(r.t, resp, http.StatusCreated) + var u dto.UserResponse + readJSON(r.t, resp, &u) + s := r.login(username, testPassword) + r.mu.Lock() + r.tokens[u.ID] = s.Token + r.mu.Unlock() + return testUser{ID: u.ID, Username: u.Username, DisplayName: u.DisplayName} +} + +// login входит по Basic и возвращает сессию; ожидает 201. +func (r *testRig) login(username, pw string) dto.SessionResponse { + r.t.Helper() + resp := r.basicLogin(username, pw) + expectStatus(r.t, resp, http.StatusCreated) + var s dto.SessionResponse + readJSON(r.t, resp, &s) + return s +} + +func (r *testRig) basicLogin(username, pw string) *http.Response { + r.t.Helper() + req, _ := http.NewRequest(http.MethodPost, r.server.URL+"/api/v1/auth/sessions", nil) + req.SetBasicAuth(username, pw) + resp, err := r.client.Do(req) + if err != nil { + r.t.Fatalf("login: %v", err) + } + return resp +} + +func (r *testRig) setAuth(req *http.Request, actorID string) { + if actorID == "" { + return + } + r.mu.Lock() + tok, ok := r.tokens[strings.ToLower(actorID)] + r.mu.Unlock() + if !ok { + tok = "unknown-" + actorID + } + req.Header.Set("Authorization", "Bearer "+tok) +} + +func (r *testRig) createChat(owner testUser, title string, members ...string) dto.ChatResponse { + r.t.Helper() + resp := r.doJSON(http.MethodPost, "/api/v1/chats", owner.ID, dto.CreateChatRequest{ + Title: title, + MemberIDs: members, + }) + expectStatus(r.t, resp, http.StatusCreated) + var ch dto.ChatResponse + readJSON(r.t, resp, &ch) + return ch +} + +func (r *testRig) sendMessage(actor testUser, chatID, text string) (*http.Response, dto.MessageResponse) { + r.t.Helper() + resp := r.doJSON(http.MethodPost, "/api/v1/chats/"+chatID+"/messages", actor.ID, textMessage(text)) + if resp.StatusCode != http.StatusCreated { + return resp, dto.MessageResponse{} + } + var m dto.MessageResponse + readJSON(r.t, resp, &m) + return resp, m +} + +func (r *testRig) sendRaw(actor testUser, chatID string, body []byte) (int, dto.MessageResponse, []byte) { + r.t.Helper() + resp := r.do(http.MethodPost, "/api/v1/chats/"+chatID+"/messages", actor.ID, + map[string]string{"Content-Type": "application/json"}, bytes.NewReader(body)) + defer resp.Body.Close() + data, _ := io.ReadAll(resp.Body) + if resp.StatusCode != http.StatusCreated { + return resp.StatusCode, dto.MessageResponse{}, data + } + var m dto.MessageResponse + if err := json.Unmarshal(data, &m); err != nil { + r.t.Fatalf("decode message: %v", err) + } + return resp.StatusCode, m, data +} + +func (r *testRig) send(actor testUser, chatID, text string) (int, dto.MessageResponse) { + r.t.Helper() + status, msg, _ := r.sendRaw(actor, chatID, mustJSON(textMessage(text))) + return status, msg +} + +func (r *testRig) listMessages(actor testUser, chatID string, pageSize int) ([]dto.MessageResponse, int) { + r.t.Helper() + collected := []dto.MessageResponse{} + cursor := "" + for pages := 1; ; pages++ { + q := fmt.Sprintf("/api/v1/chats/%s/messages?limit=%d", chatID, pageSize) + if cursor != "" { + q += "&cursor=" + url.QueryEscape(cursor) + } + resp := r.do(http.MethodGet, q, actor.ID, nil, nil) + expectStatus(r.t, resp, http.StatusOK) + var page dto.MessagesPageResponse + readJSON(r.t, resp, &page) + collected = append(collected, page.Items...) + if page.NextCursor == nil { + return collected, pages + } + cursor = *page.NextCursor + if pages > 100_000 { + r.t.Fatalf("пагинация не сходится: next_cursor не исчезает") + } + } +} + +func bootstrap(r *testRig) (alice, bob, eve testUser, chat dto.ChatResponse) { + alice = r.createUser("own_alice_"+randomSuffix(), "Алиса") + bob = r.createUser("own_bob_"+randomSuffix(), "Боб") + eve = r.createUser("own_eve_"+randomSuffix(), "Ева") + chat = r.createChat(alice, "Контрактный тест", alice.ID, bob.ID) + return +} + +var suffixMu sync.Mutex +var suffixSeq int + +func randomSuffix() string { + suffixMu.Lock() + defer suffixMu.Unlock() + suffixSeq++ + return fmt.Sprintf("%09d_%d", time.Now().UnixNano()%1_000_000_000, suffixSeq) +} + +func mustJSON(v any) []byte { + data, err := json.Marshal(v) + if err != nil { + panic(err) + } + return data +} + +func extractErrorCode(t *testing.T, data []byte) string { + t.Helper() + var e errorResp + if err := json.Unmarshal(data, &e); err != nil { + t.Fatalf("decode error body: %v; raw=%s", err, string(data)) + } + return e.Error.Code +} + +const ( + testMaxUploadBytes = 2 << 20 + testMaxImagePixels = 10_000 + testMaxConcurrentUploads = 4 +) + +// textMessage — тело POST сообщения без вложений. +func textMessage(text string) map[string]string { + return map[string]string{"text": text} +} diff --git a/app/internal/api/http/idempotency_test.go b/app/internal/api/http/idempotency_test.go new file mode 100644 index 00000000..67451976 --- /dev/null +++ b/app/internal/api/http/idempotency_test.go @@ -0,0 +1,119 @@ +package http + +import ( + "bytes" + "io" + "net/http" + "sync" + "testing" + + "github.com/google/uuid" +) + +func (r *testRig) postKeyed(actorID, chatID, key, body string) (int, []byte) { + r.t.Helper() + resp := r.do(http.MethodPost, "/api/v1/chats/"+chatID+"/messages", actorID, + map[string]string{"Content-Type": "application/json", "Idempotency-Key": key}, + bytes.NewReader([]byte(body))) + defer resp.Body.Close() + data, err := io.ReadAll(resp.Body) + if err != nil { + r.t.Fatal(err) + } + return resp.StatusCode, data +} + +func TestIdempotency_ReplayReturnsSameBody(t *testing.T) { + r := newTestRig(t) + alice := r.createUser("alice_"+randomSuffix(), "Alice") + chat := r.createChat(alice, "replay", alice.ID) + key := uuid.NewString() + + code, first := r.postKeyed(alice.ID, chat.ID, key, `{"text":"привет"}`) + if code != http.StatusCreated { + t.Fatalf("first: status = %d, body = %s", code, first) + } + // Иное форматирование JSON — тот же запрос. + code, replay := r.postKeyed(alice.ID, chat.ID, key, "{ \"text\" : \"привет\" }") + if code != http.StatusCreated { + t.Fatalf("replay: status = %d, body = %s", code, replay) + } + if !bytes.Equal(first, replay) { + t.Errorf("replay differs:\n%s\n%s", first, replay) + } + if items, _ := r.listMessages(alice, chat.ID, 100); len(items) != 1 { + t.Errorf("messages = %d, want 1", len(items)) + } +} + +func TestIdempotency_DifferentBodyConflicts(t *testing.T) { + r := newTestRig(t) + alice := r.createUser("alice_"+randomSuffix(), "Alice") + chat := r.createChat(alice, "conflict", alice.ID) + key := uuid.NewString() + + if code, body := r.postKeyed(alice.ID, chat.ID, key, `{"text":"раз"}`); code != http.StatusCreated { + t.Fatalf("first: status = %d, body = %s", code, body) + } + if code, body := r.postKeyed(alice.ID, chat.ID, key, `{"text":"два"}`); code != http.StatusConflict { + t.Fatalf("conflict: status = %d, body = %s", code, body) + } + if items, _ := r.listMessages(alice, chat.ID, 100); len(items) != 1 { + t.Errorf("messages = %d, want 1", len(items)) + } +} + +func TestIdempotency_ScopeAndAccess(t *testing.T) { + r := newTestRig(t) + alice := r.createUser("alice_"+randomSuffix(), "Alice") + bob := r.createUser("bob_"+randomSuffix(), "Bob") + eve := r.createUser("eve_"+randomSuffix(), "Eve") + chat := r.createChat(alice, "shared", alice.ID, bob.ID) + other := r.createChat(alice, "other", alice.ID) + key := uuid.NewString() + + if code, body := r.postKeyed(alice.ID, chat.ID, key, `{"text":"от alice"}`); code != http.StatusCreated { + t.Fatalf("alice: status = %d, body = %s", code, body) + } + if code, body := r.postKeyed(bob.ID, chat.ID, key, `{"text":"от bob"}`); code != http.StatusCreated { + t.Fatalf("bob: status = %d, body = %s", code, body) + } + if code, body := r.postKeyed(alice.ID, other.ID, key, `{"text":"другой чат"}`); code != http.StatusCreated { + t.Fatalf("other chat: status = %d, body = %s", code, body) + } + if code, body := r.postKeyed(eve.ID, chat.ID, key, `{"text":"от alice"}`); code != http.StatusNotFound { + t.Fatalf("stranger: status = %d, body = %s", code, body) + } +} + +func TestIdempotency_ConcurrentCreatesOne(t *testing.T) { + r := newTestRig(t) + alice := r.createUser("alice_"+randomSuffix(), "Alice") + chat := r.createChat(alice, "race", alice.ID) + key := uuid.NewString() + + const workers = 20 + bodies := make([][]byte, workers) + codes := make([]int, workers) + var wg sync.WaitGroup + for i := range workers { + wg.Add(1) + go func() { + defer wg.Done() + codes[i], bodies[i] = r.postKeyed(alice.ID, chat.ID, key, `{"text":"гонка"}`) + }() + } + wg.Wait() + + for i := range workers { + if codes[i] != http.StatusCreated { + t.Fatalf("worker %d: status = %d, body = %s", i, codes[i], bodies[i]) + } + if !bytes.Equal(bodies[i], bodies[0]) { + t.Errorf("worker %d: body differs", i) + } + } + if items, _ := r.listMessages(alice, chat.ID, 100); len(items) != 1 { + t.Errorf("messages = %d, want 1", len(items)) + } +} diff --git a/app/internal/api/http/instance_test.go b/app/internal/api/http/instance_test.go new file mode 100644 index 00000000..bc4b23b2 --- /dev/null +++ b/app/internal/api/http/instance_test.go @@ -0,0 +1,121 @@ +package http + +import ( + "bytes" + "net/http" + "strings" + "testing" + "time" + + "github.com/google/uuid" +) + +func TestInstanceID_OnEveryResponse(t *testing.T) { + r := newTestRig(t) + cases := []struct { + name, method, path string + want int + }{ + {"live", http.MethodGet, "/health/live", http.StatusOK}, + {"ready", http.MethodGet, "/health/ready", http.StatusOK}, + {"unauthorized", http.MethodGet, "/api/v1/users/me", http.StatusUnauthorized}, + {"unknown route", http.MethodGet, "/api/v1/nope", http.StatusNotFound}, + {"wrong method", http.MethodPatch, "/api/v1/users", http.StatusMethodNotAllowed}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + resp := r.do(tc.method, tc.path, "", nil, nil) + defer resp.Body.Close() + if resp.StatusCode != tc.want { + t.Fatalf("status = %d, want %d", resp.StatusCode, tc.want) + } + if got := resp.Header.Get("X-Instance-Id"); got != testInstanceID { + t.Errorf("X-Instance-Id = %q, want %q", got, testInstanceID) + } + }) + } +} + +func TestIdempotencyKey_Validation(t *testing.T) { + r := newTestRig(t) + alice := r.createUser("alice_key", "Alice") + chat := r.createChat(alice, "keys", alice.ID) + url := r.server.URL + "/api/v1/chats/" + chat.ID + "/messages" + + post := func(setKey func(http.Header)) int { + t.Helper() + req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader([]byte(`{"text":"hi"}`))) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Content-Type", "application/json") + r.setAuth(req, alice.ID) + setKey(req.Header) + resp, err := r.client.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + return resp.StatusCode + } + withKey := func(key string) func(http.Header) { + return func(h http.Header) { h.Set("Idempotency-Key", key) } + } + + if got := post(func(http.Header) {}); got != http.StatusBadRequest { + t.Errorf("missing key: status = %d, want 400", got) + } + for name, key := range map[string]string{ + "empty": "", + "too long": strings.Repeat("a", 129), + "space": "a b", + "unicode": "ключ", + "slash": "a/b", + } { + if got := post(withKey(key)); got != http.StatusBadRequest { + t.Errorf("%s: status = %d, want 400", name, got) + } + } + for name, key := range map[string]string{ + "all allowed chars": "aZ09._:-", + "max length": strings.Repeat("a", 128), + "uuid": uuid.NewString(), + } { + if got := post(withKey(key)); got != http.StatusCreated { + t.Errorf("%s: status = %d, want 201", name, got) + } + } +} + +func TestDrain_NotReadyButStillServing(t *testing.T) { + r := newTestRig(t) + status := func(path string) int { + t.Helper() + resp := r.do(http.MethodGet, path, "", nil, nil) + defer resp.Body.Close() + return resp.StatusCode + } + if got := status("/health/ready"); got != http.StatusOK { + t.Fatalf("ready before drain = %d", got) + } + + done := make(chan struct{}) + go func() { + defer close(done) + r.srv.Drain(500 * time.Millisecond) + }() + deadline := time.Now().Add(400 * time.Millisecond) + for status("/health/ready") != http.StatusServiceUnavailable { + if time.Now().After(deadline) { + t.Fatal("readiness did not become 503 during drain") + } + time.Sleep(5 * time.Millisecond) + } + if got := status("/health/live"); got != http.StatusOK { + t.Errorf("live during drain = %d, want 200", got) + } + if got := status("/api/v1/users/me"); got != http.StatusUnauthorized { + t.Errorf("API during drain = %d, want 401: запросы должны обслуживаться", got) + } + <-done +} diff --git a/app/internal/api/http/limits_test.go b/app/internal/api/http/limits_test.go new file mode 100644 index 00000000..d567d042 --- /dev/null +++ b/app/internal/api/http/limits_test.go @@ -0,0 +1,318 @@ +package http + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/google/uuid" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/config" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/session" +) + +func TestLimits_PayloadTooLarge(t *testing.T) { + r := newTestRigWithLimits(t, config.Limits{ + MaxBodyBytes: 256, + MaxInFlight: 16, + MaxMessagesGlobal: 100, + MaxHeapBytes: 1 << 40, + }) + alice := r.createUser("a_"+randomSuffix(), "Алиса") + bob := r.createUser("b_"+randomSuffix(), "Боб") + chat := r.createChat(alice, "Деградация", alice.ID, bob.ID) + + ok, _, _ := r.sendRaw(alice, chat.ID, mustJSON(textMessage("ok"))) + if ok != http.StatusCreated { + t.Fatalf("baseline send expected 201, got %d", ok) + } + stored := r.memory.MessagesTotal() + if stored != 1 { + t.Fatalf("baseline total expected 1, got %d", stored) + } + + big := strings.Repeat("x", 512) + status, _, body := r.sendRaw(alice, chat.ID, mustJSON(textMessage(big))) + if status != http.StatusRequestEntityTooLarge { + t.Fatalf("expected 413 by content-length, got %d body=%s", status, string(body)) + } + code := extractErrorCode(t, body) + if code != CodePayloadTooLarge { + t.Fatalf("expected code %q, got %q", CodePayloadTooLarge, code) + } + + if got := r.memory.MessagesTotal(); got != stored { + t.Fatalf("после 413 store изменился: было %d, стало %d", stored, got) + } +} + +func TestLimits_PayloadBoundaries(t *testing.T) { + const limit = 256 + r := newTestRigWithLimits(t, config.Limits{ + MaxBodyBytes: limit, + MaxInFlight: 16, + MaxMessagesGlobal: 100, + MaxHeapBytes: 1 << 40, + }) + alice := r.createUser("a_"+randomSuffix(), "Алиса") + bob := r.createUser("b_"+randomSuffix(), "Боб") + chat := r.createChat(alice, "Деградация", alice.ID, bob.ID) + + exact := []byte(`{"text":"` + strings.Repeat("x", limit-len(`{"text":""}`)) + `"}`) + if len(exact) != limit { + t.Fatalf("test bug: body is %d bytes, want %d", len(exact), limit) + } + + post := func(body io.Reader) (int, []byte) { + req, _ := http.NewRequest(http.MethodPost, + r.server.URL+"/api/v1/chats/"+chat.ID+"/messages", body) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Idempotency-Key", uuid.NewString()) + r.setAuth(req, alice.ID) + resp, err := r.client.Do(req) + if err != nil { + t.Fatalf("send: %v", err) + } + defer resp.Body.Close() + data, _ := io.ReadAll(resp.Body) + return resp.StatusCode, data + } + chunked := func(b []byte) io.Reader { return io.MultiReader(bytes.NewReader(b)) } + + if status, body := post(bytes.NewReader(exact)); status != http.StatusCreated { + t.Fatalf("body ровно %d байт с Content-Length: expected 201, got %d body=%s", limit, status, body) + } + if status, body := post(chunked(exact)); status != http.StatusCreated { + t.Fatalf("body ровно %d байт без Content-Length: expected 201, got %d body=%s", limit, status, body) + } + stored := r.memory.MessagesTotal() + + over := []byte(`{"text":"` + strings.Repeat("x", limit) + `"}`) + status, body := post(chunked(over)) + if status != http.StatusRequestEntityTooLarge { + t.Fatalf("body %d байт без Content-Length: expected 413, got %d body=%s", len(over), status, body) + } + if code := extractErrorCode(t, body); code != CodePayloadTooLarge { + t.Fatalf("expected code %q, got %q", CodePayloadTooLarge, code) + } + if got := r.memory.MessagesTotal(); got != stored { + t.Fatalf("после 413 store изменился: было %d, стало %d", stored, got) + } +} + +type slowSessions struct { + *session.Memory + delay atomic.Int64 +} + +func (s *slowSessions) Get(ctx context.Context, h []byte) (session.Session, error) { + time.Sleep(time.Duration(s.delay.Load())) + return s.Memory.Get(ctx, h) +} + +func TestLimits_RateLimited(t *testing.T) { + sessions := &slowSessions{Memory: session.NewMemory()} + r := newRig(t, config.Limits{ + MaxBodyBytes: 1 << 16, + MaxInFlight: 2, + MaxMessagesGlobal: 10000, + MaxHeapBytes: 1 << 40, + }, sessions, time.Hour) + alice := r.createUser("c_"+randomSuffix(), "Алиса") + bob := r.createUser("d_"+randomSuffix(), "Боб") + chat := r.createChat(alice, "Деградация", alice.ID, bob.ID) + sessions.delay.Store(int64(20 * time.Millisecond)) + + const total = 50 + var ( + ok atomic.Int32 + throttled atomic.Int32 + errs atomic.Int32 + wg sync.WaitGroup + ) + wg.Add(total) + start := make(chan struct{}) + for i := 0; i < total; i++ { + i := i + go func() { + defer wg.Done() + <-start + client := &http.Client{Timeout: 10 * time.Second} + body, _ := json.Marshal(textMessage(fmt.Sprintf("flood-%d", i))) + req, _ := http.NewRequest(http.MethodPost, + r.server.URL+"/api/v1/chats/"+chat.ID+"/messages", + bytes.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Idempotency-Key", uuid.NewString()) + r.setAuth(req, alice.ID) + resp, err := client.Do(req) + if err != nil { + errs.Add(1) + return + } + switch resp.StatusCode { + case http.StatusCreated: + ok.Add(1) + case http.StatusTooManyRequests: + throttled.Add(1) + if resp.Header.Get("Retry-After") != "1" { + errs.Add(1) + } + default: + errs.Add(1) + } + resp.Body.Close() + }() + } + close(start) + wg.Wait() + sessions.delay.Store(0) + + if errs.Load() != 0 { + t.Fatalf("неожиданные ошибки/статусы под нагрузкой: %d", errs.Load()) + } + if throttled.Load() == 0 { + t.Fatalf("ожидался хотя бы один 429 при maxInFlight=2 и %d параллельных запросах", total) + } + if ok.Load() == 0 { + t.Fatalf("ни одного 201 — лимит не пропускает валидный трафик") + } + if int(ok.Load()+throttled.Load()) != total { + t.Fatalf("ok=%d throttled=%d не покрывают total=%d", ok.Load(), throttled.Load(), total) + } + + deadline := time.Now().Add(3 * time.Second) + for time.Now().Before(deadline) { + status, _ := r.send(alice, chat.ID, "после-пика "+randomSuffix()) + if status == http.StatusCreated { + break + } + time.Sleep(20 * time.Millisecond) + } + status, _ := r.send(alice, chat.ID, "после-пика-2 "+randomSuffix()) + if status != http.StatusCreated { + t.Fatalf("после отступления нагрузки сервис не восстановился: %d", status) + } + + collected, _ := r.listMessages(alice, chat.ID, 100) + if int32(len(collected)) < ok.Load() { + t.Fatalf("часть подтверждённых сообщений потеряна: подтверждено %d, в истории %d", + ok.Load(), len(collected)) + } + t.Logf("ok=%d throttled=%d errors=%d; history=%d", ok.Load(), throttled.Load(), errs.Load(), len(collected)) +} + +func TestLimits_MessageQuota(t *testing.T) { + const quota = 10 + r := newTestRigWithLimits(t, config.Limits{ + MaxBodyBytes: 1 << 16, + MaxInFlight: 16, + MaxMessagesGlobal: quota, + MaxHeapBytes: 1 << 40, + }) + alice := r.createUser("e_"+randomSuffix(), "Алиса") + bob := r.createUser("f_"+randomSuffix(), "Боб") + chat := r.createChat(alice, "Деградация", alice.ID, bob.ID) + + var saved []string + for i := 0; i < quota; i++ { + status, msg := r.send(alice, chat.ID, fmt.Sprintf("saved-%02d", i)) + if status != http.StatusCreated { + t.Fatalf("send %d: expected 201, got %d", i, status) + } + saved = append(saved, msg.ID) + } + + status, _, body := r.sendRaw(alice, chat.ID, mustJSON(textMessage("overflow"))) + if status != http.StatusServiceUnavailable { + t.Fatalf("expected 503 after quota exhausted, got %d body=%s", status, string(body)) + } + if code := extractErrorCode(t, body); code != CodeUnavailable { + t.Fatalf("expected code %q, got %q", CodeUnavailable, code) + } + + collected, _ := r.listMessages(alice, chat.ID, 100) + if len(collected) != quota { + t.Fatalf("после 503 история чата %d, ожидалось %d", len(collected), quota) + } + gotIDs := make(map[string]struct{}, len(collected)) + for _, m := range collected { + gotIDs[m.ID] = struct{}{} + } + for _, id := range saved { + if _, ok := gotIDs[id]; !ok { + t.Fatalf("подтверждённое сообщение %s исчезло из истории", id) + } + } + + for i := 0; i < 5; i++ { + s, _, _ := r.sendRaw(alice, chat.ID, mustJSON(textMessage("still-over"))) + if s != http.StatusServiceUnavailable { + t.Fatalf("повторный 503 ожидался, получен %d", s) + } + } + + req, _ := http.NewRequest(http.MethodGet, r.server.URL+"/health/live", nil) + resp, err := r.client.Do(req) + if err != nil { + t.Fatalf("health/live: %v", err) + } + resp.Body.Close() + if resp.StatusCode != http.StatusOK { + t.Fatalf("health/live под перегрузкой: ожидали 200, получили %d", resp.StatusCode) + } +} + +func TestLimits_NoSilentLoss(t *testing.T) { + const quota = 20 + r := newTestRigWithLimits(t, config.Limits{ + MaxBodyBytes: 1 << 16, + MaxInFlight: 8, + MaxMessagesGlobal: quota, + MaxHeapBytes: 1 << 40, + }) + alice := r.createUser("g_"+randomSuffix(), "Алиса") + bob := r.createUser("h_"+randomSuffix(), "Боб") + chat := r.createChat(alice, "Деградация", alice.ID, bob.ID) + + const attempts = quota * 3 + acked := make([]string, 0, quota) + codes := make(map[int]int) + for i := 0; i < attempts; i++ { + status, msg, _ := r.sendRaw(alice, chat.ID, mustJSON(textMessage(fmt.Sprintf("loss-%03d", i)))) + codes[status]++ + if status == http.StatusCreated { + acked = append(acked, msg.ID) + } + } + if len(acked) != quota { + t.Fatalf("ожидалось ровно %d подтверждённых записей, получено %d; codes=%v", quota, len(acked), codes) + } + if codes[http.StatusServiceUnavailable] == 0 { + t.Fatalf("ни одного 503 — лимит не сработал") + } + + collected, _ := r.listMessages(alice, chat.ID, 100) + gotIDs := make(map[string]struct{}, len(collected)) + for _, m := range collected { + gotIDs[m.ID] = struct{}{} + } + for _, id := range acked { + if _, ok := gotIDs[id]; !ok { + t.Fatalf("подтверждённое сообщение %s исчезло из истории — незаметная потеря данных", id) + } + } + if len(collected) != len(acked) { + t.Fatalf("история чата содержит %d сообщений, подтверждено %d — скрытое отличие", + len(collected), len(acked)) + } + t.Logf("codes=%v acked=%d history=%d", codes, len(acked), len(collected)) +} diff --git a/app/internal/api/http/messages.go b/app/internal/api/http/messages.go new file mode 100644 index 00000000..80121838 --- /dev/null +++ b/app/internal/api/http/messages.go @@ -0,0 +1,80 @@ +package http + +import ( + "net/http" + + "github.com/labstack/echo/v4" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/middleware" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/service" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate" +) + +const headerIdempotencyKey = "Idempotency-Key" + +type messagesHandler struct { + messages service.MessagesService +} + +func (h *messagesHandler) send(c echo.Context) error { + callerID := c.Get(middleware.AuthUserIDKey).(string) + chatID := c.Param("chat_id") + + var req dto.CreateMessageRequest + if err := decodeJSON(c.Request().Body, &req); err != nil { + return WriteError(c, err) + } + + if req.Text == nil { + return WriteError(c, &validate.Error{Field: "text", Reason: "is required"}) + } + + msg, err := h.messages.Send(c.Request().Context(), callerID, chatID, c.Request().Header.Get(headerIdempotencyKey), *req.Text, req.AttachmentIDs) + if err != nil { + return WriteError(c, err) + } + return c.JSON(http.StatusCreated, toMessageResponse(msg)) +} + +func (h *messagesHandler) list(c echo.Context) error { + callerID := c.Get(middleware.AuthUserIDKey).(string) + chatID := c.Param("chat_id") + + limit, cursor, err := parsePageParams(c) + if err != nil { + return WriteError(c, err) + } + + page, err := h.messages.List(c.Request().Context(), callerID, chatID, cursor, limit) + if err != nil { + return WriteError(c, err) + } + return c.JSON(http.StatusOK, toMessagesPage(page)) +} + +func toMessageResponse(m domain.Message) dto.MessageResponse { + return dto.MessageResponse{ + ID: m.ID, + ChatID: m.ChatID, + SenderID: m.AuthorID, + Text: m.Text, + CreatedAt: dto.NewTimestamp(m.CreatedAt), + // Без вложений в JSON должен быть [], а не null. + AttachmentIDs: append([]string{}, m.AttachmentIDs...), + } +} + +func toMessagesPage(p domain.Page[domain.Message]) dto.MessagesPageResponse { + items := make([]dto.MessageResponse, 0, len(p.Items)) + for _, m := range p.Items { + items = append(items, toMessageResponse(m)) + } + var next *string + if p.NextCursor != "" { + s := p.NextCursor + next = &s + } + return dto.MessagesPageResponse{Items: items, NextCursor: next} +} diff --git a/app/internal/api/http/middleware/auth.go b/app/internal/api/http/middleware/auth.go new file mode 100644 index 00000000..c21a1ef8 --- /dev/null +++ b/app/internal/api/http/middleware/auth.go @@ -0,0 +1,61 @@ +package middleware + +import ( + "context" + "errors" + "net/http" + "strings" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" + "github.com/labstack/echo/v4" +) + +const AuthTokenKey = "auth_token" + +const ( + BearerChallenge = `Bearer realm="messenger"` + BasicChallenge = `Basic realm="messenger", charset="UTF-8"` +) + +type Authenticator interface { + Authenticate(ctx context.Context, token string) (userID string, err error) +} + +func Bearer(auth Authenticator) echo.MiddlewareFunc { + return func(next echo.HandlerFunc) echo.HandlerFunc { + return func(c echo.Context) error { + tok, ok := BearerToken(c.Request().Header.Get(echo.HeaderAuthorization)) + if !ok { + return unauthorized(c, BearerChallenge, "Bearer token required") + } + userID, err := auth.Authenticate(c.Request().Context(), tok) + if err != nil { + if errors.Is(err, domain.ErrUnauthorized) { + return unauthorized(c, BearerChallenge, "Invalid or expired session") + } + return err + } + c.Set(AuthUserIDKey, userID) + c.Set(AuthTokenKey, tok) + return next(c) + } + } +} + +func BearerToken(header string) (string, bool) { + scheme, tok, found := strings.Cut(header, " ") + if !found || !strings.EqualFold(scheme, "Bearer") { + return "", false + } + tok = strings.TrimSpace(tok) + return tok, tok != "" +} + +func unauthorized(c echo.Context, challenge, msg string) error { + c.Response().Header().Set(echo.HeaderWWWAuthenticate, challenge) + return echo.NewHTTPError(http.StatusUnauthorized, msg) +} + +func Unauthorized(c echo.Context, challenge, msg string) error { + return unauthorized(c, challenge, msg) +} diff --git a/app/internal/api/http/middleware/content_type.go b/app/internal/api/http/middleware/content_type.go new file mode 100644 index 00000000..dc6ef036 --- /dev/null +++ b/app/internal/api/http/middleware/content_type.go @@ -0,0 +1,42 @@ +package middleware + +import ( + "mime" + "net/http" + "strings" + + "github.com/labstack/echo/v4" +) + +func ContentType() echo.MiddlewareFunc { + return func(next echo.HandlerFunc) echo.HandlerFunc { + return func(c echo.Context) error { + if !methodHasBody(c.Request().Method) { + return next(c) + } + if !isApplicationJSON(c.Request().Header.Get(echo.HeaderContentType)) { + return echo.NewHTTPError(http.StatusUnsupportedMediaType, "Expected Content-Type: application/json") + } + return next(c) + } + } +} + +func methodHasBody(method string) bool { + switch method { + case http.MethodPost, http.MethodPut, http.MethodPatch: + return true + } + return false +} + +func isApplicationJSON(ct string) bool { + if ct == "" { + return false + } + mediatype, _, err := mime.ParseMediaType(ct) + if err != nil { + return false + } + return strings.EqualFold(mediatype, "application/json") +} diff --git a/app/internal/api/http/middleware/instance_id.go b/app/internal/api/http/middleware/instance_id.go new file mode 100644 index 00000000..0c6cde4a --- /dev/null +++ b/app/internal/api/http/middleware/instance_id.go @@ -0,0 +1,14 @@ +package middleware + +import "github.com/labstack/echo/v4" + +const HeaderInstanceID = "X-Instance-Id" + +func InstanceID(id string) echo.MiddlewareFunc { + return func(next echo.HandlerFunc) echo.HandlerFunc { + return func(c echo.Context) error { + c.Response().Header().Set(HeaderInstanceID, id) + return next(c) + } + } +} diff --git a/app/internal/api/http/middleware/limits.go b/app/internal/api/http/middleware/limits.go new file mode 100644 index 00000000..48ca8748 --- /dev/null +++ b/app/internal/api/http/middleware/limits.go @@ -0,0 +1,112 @@ +package middleware + +import ( + "io" + "runtime" + "slices" + "sync/atomic" + "time" + + "github.com/labstack/echo/v4" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" +) + +// BodyLimit ограничивает тело запроса. Маршруты из exemptRoutes применяют собственный лимит. +func BodyLimit(maxBytes int64, exemptRoutes ...string) echo.MiddlewareFunc { + return func(next echo.HandlerFunc) echo.HandlerFunc { + return func(c echo.Context) error { + if !methodHasBody(c.Request().Method) || slices.Contains(exemptRoutes, c.Path()) { + return next(c) + } + if cl := c.Request().ContentLength; cl > maxBytes { + return domain.ErrPayloadTooLarge + } + c.Request().Body = &limitedBody{ + raw: c.Request().Body, + maxLeft: maxBytes, + } + return next(c) + } + } +} + +type limitedBody struct { + raw io.ReadCloser + maxLeft int64 +} + +func (b *limitedBody) Read(p []byte) (int, error) { + if int64(len(p)) > b.maxLeft+1 { + p = p[:b.maxLeft+1] + } + n, err := b.raw.Read(p) + b.maxLeft -= int64(n) + if b.maxLeft < 0 { + return n, domain.ErrPayloadTooLarge + } + return n, err +} + +func (b *limitedBody) Close() error { + return b.raw.Close() +} + +func InFlight(maxInFlight int) echo.MiddlewareFunc { + sem := make(chan struct{}, maxInFlight) + return func(next echo.HandlerFunc) echo.HandlerFunc { + return func(c echo.Context) error { + if isHealthPath(c.Request().URL.Path) { + return next(c) + } + select { + case sem <- struct{}{}: + defer func() { <-sem }() + return next(c) + default: + return domain.ErrRateLimited + } + } + } +} + +func MemoryGuard(maxHeapBytes uint64, poll time.Duration) echo.MiddlewareFunc { + var sample atomic.Uint64 + + readOnce := func() { + var m runtime.MemStats + runtime.ReadMemStats(&m) + if m.HeapInuse > maxHeapBytes { + runtime.GC() + runtime.ReadMemStats(&m) + } + sample.Store(m.HeapInuse) + } + readOnce() + + if poll > 0 { + go func() { + t := time.NewTicker(poll) + defer t.Stop() + for range t.C { + readOnce() + } + }() + } + + return func(next echo.HandlerFunc) echo.HandlerFunc { + return func(c echo.Context) error { + if !methodHasBody(c.Request().Method) || isHealthPath(c.Request().URL.Path) { + return next(c) + } + if sample.Load() > maxHeapBytes { + return domain.ErrUnavailable + } + return next(c) + } + } +} + +func isHealthPath(path string) bool { + return path == "/health/live" || path == "/health/ready" +} diff --git a/app/internal/api/http/middleware/logger.go b/app/internal/api/http/middleware/logger.go new file mode 100644 index 00000000..ed94ef1b --- /dev/null +++ b/app/internal/api/http/middleware/logger.go @@ -0,0 +1,48 @@ +package middleware + +import ( + "log/slog" + "time" + + "github.com/labstack/echo/v4" +) + +const AuthUserIDKey = "caller_id" + +func Logger(logger *slog.Logger) echo.MiddlewareFunc { + return func(next echo.HandlerFunc) echo.HandlerFunc { + return func(c echo.Context) error { + start := time.Now() + if err := next(c); err != nil { + c.Error(err) + } + status := c.Response().Status + + rid, _ := c.Get(RequestIDKey).(string) + uid, _ := c.Get(AuthUserIDKey).(string) + + attrs := []slog.Attr{ + slog.String("request_id", rid), + slog.String("method", c.Request().Method), + slog.String("path", c.Request().URL.Path), + slog.Int("status", status), + slog.Int64("duration_ms", time.Since(start).Milliseconds()), + slog.String("remote_ip", c.RealIP()), + } + if uid != "" { + attrs = append(attrs, slog.String("user_id", uid)) + } + + level := slog.LevelInfo + switch { + case status >= 500: + level = slog.LevelError + case status >= 400: + level = slog.LevelWarn + } + logger.LogAttrs(c.Request().Context(), level, "http request", attrs...) + + return nil + } + } +} diff --git a/app/internal/api/http/middleware/recover.go b/app/internal/api/http/middleware/recover.go new file mode 100644 index 00000000..862313de --- /dev/null +++ b/app/internal/api/http/middleware/recover.go @@ -0,0 +1,32 @@ +package middleware + +import ( + "log/slog" + "net/http" + "runtime/debug" + + "github.com/labstack/echo/v4" +) + +func Recover(logger *slog.Logger) echo.MiddlewareFunc { + return func(next echo.HandlerFunc) echo.HandlerFunc { + return func(c echo.Context) (err error) { + defer func() { + r := recover() + if r == nil { + return + } + rid, _ := c.Get(RequestIDKey).(string) + logger.Error("panic recovered", + slog.String("request_id", rid), + slog.String("method", c.Request().Method), + slog.String("path", c.Request().URL.Path), + slog.Any("panic", r), + slog.String("stack", string(debug.Stack())), + ) + err = echo.NewHTTPError(http.StatusInternalServerError, "Internal server error") + }() + return next(c) + } + } +} diff --git a/app/internal/api/http/middleware/request_id.go b/app/internal/api/http/middleware/request_id.go new file mode 100644 index 00000000..6447646d --- /dev/null +++ b/app/internal/api/http/middleware/request_id.go @@ -0,0 +1,22 @@ +package middleware + +import ( + "github.com/google/uuid" + "github.com/labstack/echo/v4" +) + +const RequestIDKey = "request_id" + +func RequestID() echo.MiddlewareFunc { + return func(next echo.HandlerFunc) echo.HandlerFunc { + return func(c echo.Context) error { + rid := c.Request().Header.Get(echo.HeaderXRequestID) + if rid == "" { + rid = uuid.NewString() + } + c.Response().Header().Set(echo.HeaderXRequestID, rid) + c.Set(RequestIDKey, rid) + return next(c) + } + } +} diff --git a/app/internal/api/http/pagination_test.go b/app/internal/api/http/pagination_test.go new file mode 100644 index 00000000..0eaec70c --- /dev/null +++ b/app/internal/api/http/pagination_test.go @@ -0,0 +1,126 @@ +package http + +import ( + "encoding/base64" + "fmt" + "net/http" + "net/url" + "testing" +) + +func TestPagination_MultiPageWalk(t *testing.T) { + r := newTestRig(t) + alice, bob, _, chat := bootstrap(r) + + const total = 7 + var sentIDs []string + for i := 0; i < total; i++ { + actor := alice + if i%2 == 1 { + actor = bob + } + _, msg := r.sendMessage(actor, chat.ID, fmt.Sprintf("page-%02d", i)) + if msg.ID == "" { + t.Fatalf("send message %d failed", i) + } + sentIDs = append(sentIDs, msg.ID) + } + + history, pages := r.listMessages(alice, chat.ID, 3) + if pages != 3 { + t.Fatalf("ожидалось 3 страницы (3+3+1), получено %d", pages) + } + if len(history) != total { + t.Fatalf("собрано %d сообщений, ожидалось %d", len(history), total) + } + for i, m := range history { + if m.ID != sentIDs[i] { + t.Fatalf("позиция %d: ожидался %s, получен %s (повтор, пропуск или нарушен порядок)", i, sentIDs[i], m.ID) + } + } +} + +func TestPagination_ExactPageAndEmptyChat(t *testing.T) { + r := newTestRig(t) + alice, _, _, chat := bootstrap(r) + + history, pages := r.listMessages(alice, chat.ID, 5) + if len(history) != 0 || pages != 1 { + t.Fatalf("пустой чат: items=%d pages=%d", len(history), pages) + } + + for i := 0; i < 4; i++ { + r.send(alice, chat.ID, fmt.Sprintf("m%d", i)) + } + if _, pages := r.listMessages(alice, chat.ID, 4); pages != 1 { + t.Fatalf("4 сообщения при limit=4: ожидалась 1 страница, получено %d", pages) + } + if _, pages := r.listMessages(alice, chat.ID, 2); pages != 2 { + t.Fatalf("4 сообщения при limit=2: ожидалось 2 страницы, получено %d", pages) + } +} + +func TestPagination_CursorBoundToChat(t *testing.T) { + r := newTestRig(t) + alice, bob, _, chat := bootstrap(r) + other := r.createChat(alice, "Другой", alice.ID, bob.ID) + for i := 0; i < 3; i++ { + r.send(alice, chat.ID, fmt.Sprintf("m%d", i)) + } + + resp := r.do(http.MethodGet, "/api/v1/chats/"+chat.ID+"/messages?limit=1", alice.ID, nil, nil) + expectStatus(t, resp, http.StatusOK) + var page struct { + NextCursor *string `json:"next_cursor"` + } + readJSON(t, resp, &page) + if page.NextCursor == nil { + t.Fatal("ожидался next_cursor") + } + + for _, path := range []string{ + "/api/v1/chats/" + other.ID + "/messages?cursor=" + url.QueryEscape(*page.NextCursor), + "/api/v1/chats?cursor=" + url.QueryEscape(*page.NextCursor), + "/api/v1/chats/" + chat.ID + "/messages?cursor=not-a-cursor", + } { + resp := r.do(http.MethodGet, path, alice.ID, nil, nil) + expectStatus(t, resp, http.StatusBadRequest) + resp.Body.Close() + } +} + +func TestPagination_IncompleteCursor(t *testing.T) { + r := newTestRig(t) + alice, _, _, chat := bootstrap(r) + r.send(alice, chat.ID, "m0") + + enc := func(s string) string { return base64.RawURLEncoding.EncodeToString([]byte(s)) } + msgScope := `"s":"chat:` + chat.ID + `"` + chatsScope := `"s":"chats:` + alice.ID + `"` + ts := `"t":"2026-01-01T00:00:00Z"` + id := `"i":"` + chat.ID + `"` + + cases := map[string]string{ + "только scope": enc(`{` + msgScope + `}`), + "без i": enc(`{` + ts + `,` + msgScope + `}`), + "без t": enc(`{` + id + `,` + msgScope + `}`), + "i не UUID": enc(`{` + ts + `,"i":"zzz",` + msgScope + `}`), + "нулевое t": enc(`{"t":"0001-01-01T00:00:00Z",` + id + `,` + msgScope + `}`), + "лишнее поле": enc(`{` + ts + `,` + id + `,` + msgScope + `,"x":1}`), + "данные после объекта": enc(`{` + ts + `,` + id + `,` + msgScope + `}}`), + "base64 с паддингом": base64.URLEncoding.EncodeToString([]byte(`{` + ts + `,` + id + `,` + msgScope + `}`)), + "пустой объект": enc(`{}`), + "null": enc(`null`), + } + for name, cur := range cases { + resp := r.do(http.MethodGet, "/api/v1/chats/"+chat.ID+"/messages?cursor="+url.QueryEscape(cur), alice.ID, nil, nil) + if resp.StatusCode != http.StatusBadRequest { + t.Errorf("messages, %s: ожидался 400, получен %d", name, resp.StatusCode) + } + resp.Body.Close() + } + + resp := r.do(http.MethodGet, "/api/v1/chats?cursor="+url.QueryEscape(enc(`{`+chatsScope+`}`)), alice.ID, nil, nil) + expectStatus(t, resp, http.StatusBadRequest) + resp.Body.Close() +} diff --git a/app/internal/api/http/router.go b/app/internal/api/http/router.go new file mode 100644 index 00000000..a8fdc059 --- /dev/null +++ b/app/internal/api/http/router.go @@ -0,0 +1,39 @@ +package http + +import ( + "github.com/labstack/echo/v4" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/middleware" +) + +func registerRoutes(e *echo.Echo, d Deps, isReady func() bool) { + e.GET("/health/live", healthLive) + e.GET("/health/ready", healthReady(isReady)) + + usersH := &usersHandler{users: d.Users} + chatsH := &chatsHandler{chats: d.Chats} + messagesH := &messagesHandler{messages: d.Messages} + authH := &authHandler{auth: d.Auth} + attachmentsH := &attachmentsHandler{attachments: d.Attachments} + + auth := middleware.Bearer(d.Auth) + + jsonBody := middleware.ContentType() + + v1 := e.Group("/api/v1") + v1.POST("/users", usersH.create, jsonBody) + v1.POST("/auth/sessions", authH.createSession) + v1.DELETE("/auth/sessions/current", authH.revokeSession, auth) + v1.GET("/users/me", usersH.me, auth) + v1.POST("/chats", chatsH.create, auth, jsonBody) + v1.GET("/chats", chatsH.list, auth) + v1.GET("/chats/:chat_id", chatsH.get, auth) + v1.POST("/chats/:chat_id/messages", messagesH.send, auth, jsonBody) + v1.GET("/chats/:chat_id/messages", messagesH.list, auth) + // Тело здесь не JSON: Content-Type и размер проверяет сервис, после проверки доступа. + v1.POST("/chats/:chat_id/attachments", attachmentsH.upload, uploadTransfer, auth) + v1.POST("/chats/:chat_id/attachments/direct/init", attachmentsH.directInit, auth, jsonBody) + v1.POST("/chats/:chat_id/attachments/direct/complete", attachmentsH.directComplete, uploadTransfer, auth, jsonBody) + v1.GET("/attachments/:attachment_id", attachmentsH.get, auth) + v1.GET("/attachments/:attachment_id/content", attachmentsH.content, auth) +} diff --git a/app/internal/api/http/server.go b/app/internal/api/http/server.go new file mode 100644 index 00000000..811a3194 --- /dev/null +++ b/app/internal/api/http/server.go @@ -0,0 +1,174 @@ +package http + +import ( + "context" + "errors" + "log/slog" + nethttp "net/http" + "sync/atomic" + "time" + + "github.com/labstack/echo/v4" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/middleware" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/config" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/service" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store" +) + +type Deps struct { + Config *config.Config + Logger *slog.Logger + Store store.Store + Auth service.AuthService + Users service.UsersService + Chats service.ChatsService + Messages service.MessagesService + Attachments service.AttachmentsService + + Ready func(ctx context.Context) error +} + +type Server struct { + e *echo.Echo + cfg config.HTTP + logger *slog.Logger + shutting atomic.Bool + ready func(ctx context.Context) error +} + +func NewServer(d Deps) *Server { + s := &Server{ + e: echo.New(), + cfg: d.Config.HTTP, + logger: d.Logger, + ready: d.Ready, + } + + s.e.HideBanner = true + s.e.HidePort = true + s.e.HTTPErrorHandler = s.httpErrorHandler + + s.e.Server.ReadTimeout = time.Duration(s.cfg.ReadTimeoutMs) * time.Millisecond + s.e.Server.WriteTimeout = time.Duration(s.cfg.WriteTimeoutMs) * time.Millisecond + s.e.Server.IdleTimeout = time.Duration(s.cfg.IdleTimeoutMs) * time.Millisecond + + s.e.Use(middleware.InstanceID(d.Config.InstanceID)) + s.e.Use(middleware.Recover(d.Logger)) + s.e.Use(middleware.RequestID()) + s.e.Use(middleware.Logger(d.Logger)) + s.e.Use(middleware.InFlight(d.Config.Limits.MaxInFlight)) + s.e.Use(middleware.BodyLimit(d.Config.Limits.MaxBodyBytes, routeUploadAttachment)) + s.e.Use(middleware.MemoryGuard(d.Config.Limits.MaxHeapBytes, 100*time.Millisecond)) + + registerRoutes(s.e, d, s.IsReady) + return s +} + +func (s *Server) Start() error { + s.logger.Info("http server starting", slog.String("addr", s.cfg.Addr)) + err := s.e.Start(s.cfg.Addr) + if errors.Is(err, nethttp.ErrServerClosed) { + return nil + } + return err +} + +// Drain переводит readiness в 503 и ждёт d, продолжая обслуживать запросы: за это время +// балансировщик выводит реплику, и новые запросы не попадают на закрытый listener. +func (s *Server) Drain(d time.Duration) { + s.shutting.Store(true) + s.logger.Info("http server draining", slog.Duration("for", d)) + time.Sleep(d) +} + +func (s *Server) Shutdown(ctx context.Context) error { + s.shutting.Store(true) + s.logger.Info("http server shutting down") + return s.e.Shutdown(ctx) +} + +func (s *Server) IsReady() bool { + if s.shutting.Load() { + return false + } + if s.ready == nil { + return true + } + ctx, cancel := context.WithTimeout(context.Background(), readyTimeout) + defer cancel() + return s.ready(ctx) == nil +} + +const readyTimeout = time.Second + +func (s *Server) Handler() nethttp.Handler { + return s.e +} + +func (s *Server) httpErrorHandler(err error, c echo.Context) { + if c.Response().Committed { + return + } + + var httpErr *echo.HTTPError + if errors.As(err, &httpErr) { + code := codeFromStatus(httpErr.Code) + msg, _ := httpErr.Message.(string) + if msg == "" || msg == nethttp.StatusText(httpErr.Code) { + msg = messageFor(httpErr.Code, code) + } + _ = c.JSON(httpErr.Code, errorBody{ + Error: errorPayload{ + Code: code, + Message: msg, + RequestID: c.Response().Header().Get(echo.HeaderXRequestID), + }, + }) + return + } + + _ = WriteError(c, err) +} + +var codesByStatus = map[int]string{ + nethttp.StatusBadRequest: CodeInvalidRequest, + nethttp.StatusUnauthorized: CodeUnauthorized, + nethttp.StatusNotFound: CodeNotFound, + nethttp.StatusMethodNotAllowed: CodeInvalidRequest, + nethttp.StatusConflict: CodeConflict, + nethttp.StatusRequestEntityTooLarge: CodePayloadTooLarge, + nethttp.StatusUnsupportedMediaType: CodeUnsupportedMedia, + nethttp.StatusTooManyRequests: CodeRateLimited, + nethttp.StatusServiceUnavailable: CodeUnavailable, +} + +func codeFromStatus(status int) string { + if c, ok := codesByStatus[status]; ok { + return c + } + return CodeInternalError +} + +var messagesByStatus = map[int]string{ + nethttp.StatusMethodNotAllowed: "Method not allowed", +} + +func messageFor(status int, code string) string { + if m, ok := messagesByStatus[status]; ok { + return m + } + return defaultMessages[code] +} + +var defaultMessages = map[string]string{ + CodeInvalidRequest: "Invalid request", + CodeUnauthorized: "Identification required", + CodeNotFound: "Object not found", + CodeConflict: "Conflict", + CodePayloadTooLarge: "Request body too large", + CodeUnsupportedMedia: "Unsupported Content-Type", + CodeRateLimited: "Too many requests", + CodeUnavailable: "Service unavailable", + CodeInternalError: "Internal server error", +} diff --git a/app/internal/api/http/users.go b/app/internal/api/http/users.go new file mode 100644 index 00000000..2533a19b --- /dev/null +++ b/app/internal/api/http/users.go @@ -0,0 +1,114 @@ +package http + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "reflect" + "strings" + "unicode/utf8" + + "github.com/labstack/echo/v4" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/middleware" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/service" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate" +) + +type usersHandler struct { + users service.UsersService +} + +func (h *usersHandler) create(c echo.Context) error { + var req dto.CreateUserRequest + if err := decodeJSON(c.Request().Body, &req); err != nil { + return WriteError(c, err) + } + + user, err := h.users.Register(c.Request().Context(), req.Username, req.DisplayName, req.Password) + if err != nil { + return WriteError(c, err) + } + return c.JSON(http.StatusCreated, toUserResponse(user)) +} + +func (h *usersHandler) me(c echo.Context) error { + callerID := c.Get(middleware.AuthUserIDKey).(string) + user, err := h.users.Me(c.Request().Context(), callerID) + if err != nil { + return WriteError(c, err) + } + return c.JSON(http.StatusOK, toUserResponse(user)) +} + +func toUserResponse(u domain.User) dto.UserResponse { + return dto.UserResponse{ + ID: u.ID, + Username: u.Username, + DisplayName: u.DisplayName, + CreatedAt: dto.NewTimestamp(u.CreatedAt), + } +} + +func decodeJSON(body io.Reader, dst any) error { + data, err := io.ReadAll(body) + if err != nil { + if errors.Is(err, domain.ErrPayloadTooLarge) { + return err + } + return &validate.Error{Field: "body", Reason: "cannot read body"} + } + if !utf8.Valid(data) { + return &validate.Error{Field: "body", Reason: "invalid UTF-8"} + } + dec := json.NewDecoder(bytes.NewReader(data)) + dec.DisallowUnknownFields() + if err := dec.Decode(dst); err != nil { + return &validate.Error{Field: "body", Reason: jsonErrorReason(err)} + } + if _, err := dec.Token(); !errors.Is(err, io.EOF) { + return &validate.Error{Field: "body", Reason: "unexpected data after JSON object"} + } + return checkExactKeys(data, dst) +} + +func checkExactKeys(data []byte, dst any) error { + var obj map[string]json.RawMessage + if err := json.Unmarshal(data, &obj); err != nil { + return nil + } + allowed := make(map[string]struct{}) + t := reflect.TypeOf(dst).Elem() + for i := 0; i < t.NumField(); i++ { + name, _, _ := strings.Cut(t.Field(i).Tag.Get("json"), ",") + allowed[name] = struct{}{} + } + for key := range obj { + if _, ok := allowed[key]; !ok { + return &validate.Error{Field: "body", Reason: fmt.Sprintf("unknown field %q", key)} + } + } + return nil +} + +func jsonErrorReason(err error) string { + if errors.Is(err, io.EOF) { + return "empty body" + } + var typeErr *json.UnmarshalTypeError + if errors.As(err, &typeErr) { + if typeErr.Field == "" { + return "expected a JSON object" + } + return fmt.Sprintf("field %q: invalid type", typeErr.Field) + } + if name, ok := strings.CutPrefix(err.Error(), "json: unknown field "); ok { + return "unknown field " + name + } + return "invalid JSON" +} diff --git a/app/internal/api/http/validation_test.go b/app/internal/api/http/validation_test.go new file mode 100644 index 00000000..20c047d8 --- /dev/null +++ b/app/internal/api/http/validation_test.go @@ -0,0 +1,230 @@ +package http + +import ( + "bytes" + "io" + "net/http" + "strings" + "testing" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto" +) + +func TestValidation_InvalidJSON(t *testing.T) { + r := newTestRig(t) + alice, _, _, chat := bootstrap(r) + path := "/api/v1/chats/" + chat.ID + "/messages" + + bad := [][]byte{ + []byte(`{"text":`), + []byte(`not json at all`), + []byte(`{"text": 123,}`), + []byte(``), + []byte(`{"text": "ok"}{"text":"bonus"}`), + []byte(`{"text": "ok"}}`), + []byte(`{"text": "ok"}]`), + []byte(`{"text": "ok"} }`), + []byte(`{"text": "ok"} x`), + []byte("{\"text\":\"\xff\xfe bad utf8\"}"), + } + for _, payload := range bad { + resp := r.do(http.MethodPost, path, alice.ID, + map[string]string{"Content-Type": "application/json"}, + bytes.NewReader(payload)) + if resp.StatusCode != http.StatusBadRequest { + data, _ := io.ReadAll(resp.Body) + resp.Body.Close() + t.Fatalf("payload %q: expected 400, got %d; body=%s", payload, resp.StatusCode, string(data)) + } + e := readError(t, resp) + if e.Error.Code != CodeInvalidRequest { + t.Fatalf("payload %q: expected code %q, got %q", payload, CodeInvalidRequest, e.Error.Code) + } + if e.Error.RequestID == "" { + t.Fatalf("payload %q: missing request_id in body", payload) + } + } +} + +func TestValidation_InvalidUTF8(t *testing.T) { + r := newTestRig(t) + alice, bob, _, _ := bootstrap(r) + + cases := []struct { + path, actor string + payload []byte + }{ + {"/api/v1/users", "", []byte("{\"username\":\"u_" + randomSuffix()[:8] + "\",\"display_name\":\"\xc3\x28\"}")}, + {"/api/v1/chats", alice.ID, []byte("{\"title\":\"\xe2\x82\",\"member_ids\":[\"" + alice.ID + "\",\"" + bob.ID + "\"]}")}, + } + for _, tc := range cases { + resp := r.do(http.MethodPost, tc.path, tc.actor, + map[string]string{"Content-Type": "application/json"}, + bytes.NewReader(tc.payload)) + if resp.StatusCode != http.StatusBadRequest { + data, _ := io.ReadAll(resp.Body) + resp.Body.Close() + t.Fatalf("%s %q: expected 400, got %d; body=%s", tc.path, tc.payload, resp.StatusCode, string(data)) + } + e := readError(t, resp) + if e.Error.Code != CodeInvalidRequest { + t.Fatalf("%s: expected code %q, got %q", tc.path, CodeInvalidRequest, e.Error.Code) + } + } +} + +func TestValidation_JSONKeysAreCaseSensitive(t *testing.T) { + r := newTestRig(t) + resp := r.do(http.MethodPost, "/api/v1/users", "", + map[string]string{"Content-Type": "application/json"}, + strings.NewReader(`{"USERNAME":"case_bob","Display_Name":"B"}`)) + expectStatus(t, resp, http.StatusBadRequest) + resp.Body.Close() +} + +func TestValidation_ErrorMessages(t *testing.T) { + r := newTestRig(t) + alice, bob, _, chat := bootstrap(r) + msgs := "/api/v1/chats/" + chat.ID + "/messages" + + cases := []struct { + method, path, actor, body, message string + }{ + {http.MethodPost, "/api/v1/users", "", `{"username":"ab","display_name":"x"}`, + "username: must match [a-z0-9_]{3,32}"}, + {http.MethodPost, "/api/v1/users", "", `{"username":"abc_` + randomSuffix()[:6] + `","display_name":" "}`, + "display_name: must not be empty or whitespace only"}, + {http.MethodPost, "/api/v1/users", "", `{"username":123,"display_name":"x"}`, + `body: field "username": invalid type`}, + {http.MethodPost, "/api/v1/users", "", `{"username":"abc","display_name":"x","password":"p"}`, + "password: length must be in [12, 128] code points"}, + {http.MethodPost, "/api/v1/users", "", `{"username":"abc","display_name":"x"}`, + "password: must not be empty or whitespace only"}, + {http.MethodPost, "/api/v1/users", "", `{"username":"abc","display_name":"x","password":"` + strings.Repeat("я", 129) + `"}`, + "password: length must be in [12, 128] code points"}, + {http.MethodPost, "/api/v1/users", "", `{"username":"abc","display_name":"x","password":"long-enough-pw","password_hash":"h"}`, + `body: unknown field "password_hash"`}, + {http.MethodPost, "/api/v1/users", "", `{"username":`, "body: invalid JSON"}, + {http.MethodPost, "/api/v1/users", "", ``, "body: empty body"}, + {http.MethodPost, "/api/v1/users", "", `[]`, "body: expected a JSON object"}, + {http.MethodPost, "/api/v1/users", "", `{"username":"abc","display_name":"x"} {}`, "body: unexpected data after JSON object"}, + {http.MethodPost, "/api/v1/users", "", `{"username":"abc","display_name":"x"}}`, "body: unexpected data after JSON object"}, + {http.MethodPost, "/api/v1/users", "", "{\"username\":\"abc\",\"display_name\":\"\xff\"}", + "body: invalid UTF-8"}, + {http.MethodPost, "/api/v1/chats", alice.ID, `{"title":"t","member_ids":["` + bob.ID + `"]}`, + "member_ids: must contain caller"}, + {http.MethodPost, "/api/v1/chats", alice.ID, `{"title":"t","member_ids":["` + alice.ID + `","x"]}`, + "member_ids[1]: must be a valid UUID"}, + {http.MethodPost, msgs, alice.ID, `{"text":" "}`, "text: must not be empty or whitespace only"}, + {http.MethodGet, msgs + "?limit=abc", alice.ID, "", "limit: must be an integer"}, + {http.MethodGet, msgs + "?limit=0", alice.ID, "", "limit: must be in [1, 100]"}, + {http.MethodGet, msgs + "?limit=", alice.ID, "", "limit: must be an integer"}, + {http.MethodGet, msgs + "?cursor=", alice.ID, "", "cursor: must not be empty"}, + {http.MethodGet, msgs + "?limit=10&cursor=", alice.ID, "", "cursor: must not be empty"}, + {http.MethodGet, "/api/v1/chats?limit=", alice.ID, "", "limit: must be an integer"}, + {http.MethodGet, "/api/v1/chats?cursor=", alice.ID, "", "cursor: must not be empty"}, + } + for _, tc := range cases { + headers := map[string]string{} + var body io.Reader + if tc.method == http.MethodPost { + headers["Content-Type"] = "application/json" + body = bytes.NewReader([]byte(tc.body)) + } + resp := r.do(tc.method, tc.path, tc.actor, headers, body) + if resp.StatusCode != http.StatusBadRequest { + data, _ := io.ReadAll(resp.Body) + resp.Body.Close() + t.Fatalf("%s %s %q: expected 400, got %d; body=%s", tc.method, tc.path, tc.body, resp.StatusCode, string(data)) + } + e := readError(t, resp) + if e.Error.Message != tc.message { + t.Fatalf("%s %s %q:\n want %q\n got %q", tc.method, tc.path, tc.body, tc.message, e.Error.Message) + } + } +} + +func TestValidation_EmptyMessage(t *testing.T) { + r := newTestRig(t) + alice, _, _, chat := bootstrap(r) + path := "/api/v1/chats/" + chat.ID + "/messages" + + for _, text := range []string{"", " ", "\n\t "} { + resp := r.doJSON(http.MethodPost, path, alice.ID, textMessage(text)) + if resp.StatusCode != http.StatusBadRequest { + data, _ := io.ReadAll(resp.Body) + resp.Body.Close() + t.Fatalf("text %q: expected 400, got %d; body=%s", text, resp.StatusCode, string(data)) + } + e := readError(t, resp) + if e.Error.Code != CodeInvalidRequest { + t.Fatalf("text %q: expected code %q, got %q", text, CodeInvalidRequest, e.Error.Code) + } + } +} + +func TestValidation_DuplicateUsername(t *testing.T) { + r := newTestRig(t) + username := "own_dup_" + randomSuffix() + + first := r.doJSON(http.MethodPost, "/api/v1/users", "", dto.CreateUserRequest{ + Username: username, + DisplayName: "Первый", + Password: testPassword, + }) + expectStatus(t, first, http.StatusCreated) + first.Body.Close() + + second := r.doJSON(http.MethodPost, "/api/v1/users", "", dto.CreateUserRequest{ + Username: username, + DisplayName: "Второй", + Password: testPassword, + }) + if second.StatusCode != http.StatusConflict { + data, _ := io.ReadAll(second.Body) + second.Body.Close() + t.Fatalf("second POST same username: expected 409, got %d; body=%s", second.StatusCode, string(data)) + } + e := readError(t, second) + if e.Error.Code != CodeConflict { + t.Fatalf("expected code %q, got %q", CodeConflict, e.Error.Code) + } + + third := r.doJSON(http.MethodPost, "/api/v1/users", "", dto.CreateUserRequest{ + Username: username, + DisplayName: "Первый", + Password: testPassword, + }) + if third.StatusCode != http.StatusConflict { + data, _ := io.ReadAll(third.Body) + third.Body.Close() + t.Fatalf("third POST same username/display_name: expected 409, got %d; body=%s", third.StatusCode, string(data)) + } + third.Body.Close() +} + +func TestValidation_UUIDForms(t *testing.T) { + r := newTestRig(t) + alice, bob, _, chat := bootstrap(r) + upper := strings.ToUpper(alice.ID) + + resp := r.do(http.MethodGet, "/api/v1/users/me", upper, nil, nil) + expectStatus(t, resp, http.StatusOK) + resp.Body.Close() + resp = r.do(http.MethodGet, "/api/v1/chats/"+strings.ToUpper(chat.ID), alice.ID, nil, nil) + expectStatus(t, resp, http.StatusOK) + resp.Body.Close() + + resp = r.do(http.MethodGet, "/api/v1/users/me", "{"+alice.ID+"}", nil, nil) + expectStatus(t, resp, http.StatusUnauthorized) + resp.Body.Close() + resp = r.do(http.MethodGet, "/api/v1/chats/"+strings.ReplaceAll(chat.ID, "-", ""), alice.ID, nil, nil) + expectStatus(t, resp, http.StatusBadRequest) + resp.Body.Close() + + resp = r.doJSON(http.MethodPost, "/api/v1/chats", alice.ID, map[string]any{ + "title": "dup", "member_ids": []string{alice.ID, upper, bob.ID}, + }) + expectStatus(t, resp, http.StatusBadRequest) + resp.Body.Close() +} diff --git a/app/internal/cache/history.go b/app/internal/cache/history.go new file mode 100644 index 00000000..e389e055 --- /dev/null +++ b/app/internal/cache/history.go @@ -0,0 +1,478 @@ +package cache + +import ( + "context" + "crypto/rand" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "log/slog" + "os" + "strconv" + "strings" + "sync" + "sync/atomic" + "time" + + "github.com/redis/go-redis/v9" + "golang.org/x/sync/singleflight" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/config" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store" +) + +const ( + ModeOff = "off" + ModeNaive = "naive" + ModeSafe = "safe" +) + +type Source interface { + store.MessageStore + IsMember(ctx context.Context, chatID, userID string) (bool, error) + HistoryPage(ctx context.Context, chatID, cursor string, limit int) (domain.Page[domain.Message], error) +} + +// Outbox хранит долг инвалидации в источнике истины, чтобы он пережил +// рестарт API. Без него отложенная инвалидация живёт только в памяти. +type Outbox interface { + AddPendingInvalidation(ctx context.Context, chatID string) (int64, error) + PendingInvalidations(ctx context.Context) (map[string]int64, error) + ResolvePendingInvalidation(ctx context.Context, chatID string, gen int64) error +} + +type Options struct { + Mode string + Outbox Outbox + PageTTL time.Duration + LockTTL time.Duration + FillDelay time.Duration + Logger *slog.Logger +} + +var _ store.MessageStore = (*Messages)(nil) + +// pendingEntry — несброшенная версия чата. seq меняется при каждом новом +// сбое: повтор снимает запись, только если seq не изменился с его снимка. +// gen — поколение строки в Outbox (0 — не записана). +type pendingEntry struct { + seq uint64 + gen int64 +} + +type Messages struct { + src Source + rdb *redis.Client + opt Options + group singleflight.Group + log *slog.Logger + + downUntil atomic.Int64 + // loaded: долг инвалидации из Outbox прочитан. До этого любой чат может + // иметь устаревшую версию, поэтому все чтения идут мимо кэша. + loaded atomic.Bool + + mu sync.Mutex + pending map[string]pendingEntry + seq uint64 + stop chan struct{} + done chan struct{} +} + +const ( + memberTTL = 24 * time.Hour + versionTTL = 24 * time.Hour + breakerPause = time.Second + retryInterval = 200 * time.Millisecond + pollInterval = 5 * time.Millisecond + defaultPageTTL = 30 * time.Second + defaultLockTTL = 500 * time.Millisecond +) + +func New(src Source, rdb *redis.Client, opt Options) *Messages { + if opt.PageTTL <= 0 { + opt.PageTTL = defaultPageTTL + } + if opt.LockTTL <= 0 { + opt.LockTTL = defaultLockTTL + } + if opt.Logger == nil { + opt.Logger = slog.Default() + } + m := &Messages{ + src: src, + rdb: rdb, + opt: opt, + log: opt.Logger, + pending: make(map[string]pendingEntry), + stop: make(chan struct{}), + done: make(chan struct{}), + } + m.loaded.Store(opt.Outbox == nil || opt.Mode != ModeSafe) + go m.retryLoop() + return m +} + +func Connect(cfg config.HistoryCache) (*redis.Client, error) { + url := cfg.URL + if cfg.URLFile != "" { + b, err := os.ReadFile(cfg.URLFile) + if err != nil { + return nil, fmt.Errorf("cache: read HISTORY_CACHE_URL_FILE: %w", err) + } + url = strings.TrimSpace(string(b)) + } + if url == "" { + return nil, errors.New("cache: HISTORY_CACHE_URL_FILE or HISTORY_CACHE_URL is required unless HISTORY_CACHE=off") + } + opts, err := redis.ParseURL(url) + if err != nil { + return nil, errors.New("cache: invalid HISTORY_CACHE_URL") + } + timeout := time.Duration(cfg.TimeoutMs) * time.Millisecond + opts.PoolSize = cfg.PoolSize + opts.DialTimeout = timeout + opts.ReadTimeout = timeout + opts.WriteTimeout = timeout + opts.PoolTimeout = timeout + opts.MaxRetries = -1 // без повторов: промах кэша дешевле ожидания + return redis.NewClient(opts), nil +} + +func (m *Messages) Close() { + close(m.stop) + <-m.done +} + +func (m *Messages) AddMessage(ctx context.Context, callerID, chatID, idempotencyKey, text string, attachmentIDs []string) (domain.Message, error) { + msg, err := m.src.AddMessage(ctx, callerID, chatID, idempotencyKey, text, attachmentIDs) + if err != nil { + return msg, err + } + // Инвалидация нужна и при повторе: реплика, выполнившая COMMIT, могла упасть до + // сброса кэша, и тогда ответ 201 на повтор — первое подтверждение этого сообщения. + ictx := context.WithoutCancel(ctx) + switch m.opt.Mode { + case ModeNaive: + m.naiveInvalidate(ictx, chatID) + case ModeSafe: + if err := m.rdb.Del(ictx, verKey(chatID)).Err(); err != nil { + m.markDown(err) + m.addPending(ictx, chatID) + } + } + return msg, nil +} + +func (m *Messages) ListMessages(ctx context.Context, callerID, chatID, cursor string, limit int) (domain.Page[domain.Message], error) { + if m.opt.Mode == ModeOff || m.bypass(chatID) { + return m.src.ListMessages(ctx, callerID, chatID, cursor, limit) + } + if err := m.checkMember(ctx, chatID, callerID); err != nil { + return domain.Page[domain.Message]{}, err + } + if m.opt.Mode == ModeNaive { + return m.naiveList(ctx, chatID, cursor, limit) + } + return m.safeList(ctx, chatID, cursor, limit) +} + +func (m *Messages) checkMember(ctx context.Context, chatID, userID string) error { + key := "hc:member:" + chatID + ":" + userID + if !m.isDown() { + v, err := m.rdb.Get(ctx, key).Result() + if err == nil && v == "1" { + return nil + } + m.markDown(err) + } + ok, err := m.src.IsMember(ctx, chatID, userID) + if err != nil { + return err + } + if !ok { + // Отрицательный ответ не кэшируем. + return domain.ErrNotFound + } + if !m.isDown() { + m.markDown(m.rdb.Set(ctx, key, "1", memberTTL).Err()) + } + return nil +} + +func (m *Messages) naiveList(ctx context.Context, chatID, cursor string, limit int) (domain.Page[domain.Message], error) { + key := pageKey("hc:naive:"+chatID, cursor, limit) + if page, ok := m.getPage(ctx, key); ok { + return page, nil + } + page, err := m.src.HistoryPage(ctx, chatID, cursor, limit) + if err != nil { + return page, err + } + m.sleepFill(ctx) + if b, err := encodePage(page); err == nil { + setKey := "hc:naive:keys:" + chatID + _, err := m.rdb.TxPipelined(ctx, func(p redis.Pipeliner) error { + p.Set(ctx, key, b, m.opt.PageTTL) + p.SAdd(ctx, setKey, key) + p.Expire(ctx, setKey, m.opt.PageTTL) + return nil + }) + m.markDown(err) + } + return page, nil +} + +func (m *Messages) naiveInvalidate(ctx context.Context, chatID string) { + setKey := "hc:naive:keys:" + chatID + keys, err := m.rdb.SMembers(ctx, setKey).Result() + if err != nil { + m.markDown(err) + return + } + m.markDown(m.rdb.Del(ctx, append(keys, setKey)...).Err()) +} + +func (m *Messages) safeList(ctx context.Context, chatID, cursor string, limit int) (domain.Page[domain.Message], error) { + ver, err := m.version(ctx, chatID) + if err != nil { + m.markDown(err) + return m.src.HistoryPage(ctx, chatID, cursor, limit) + } + key := pageKey("hc:page:"+chatID+":"+ver, cursor, limit) + if page, ok := m.getPage(ctx, key); ok { + return page, nil + } + v, err, _ := m.group.Do(key, func() (any, error) { + return m.fill(context.WithoutCancel(ctx), key, chatID, cursor, limit) + }) + if err != nil { + return domain.Page[domain.Message]{}, err + } + return v.(domain.Page[domain.Message]), nil +} + +func (m *Messages) version(ctx context.Context, chatID string) (string, error) { + key := verKey(chatID) + v, err := m.rdb.Get(ctx, key).Result() + if err == nil { + return v, nil + } + if !errors.Is(err, redis.Nil) { + return "", err + } + fresh := randomVersion() + old, err := m.rdb.SetArgs(ctx, key, fresh, redis.SetArgs{Mode: "NX", Get: true, TTL: versionTTL}).Result() + if errors.Is(err, redis.Nil) { + return fresh, nil + } + if err != nil { + return "", err + } + return old, nil +} + +var unlockScript = redis.NewScript(` +if redis.call("GET", KEYS[1]) == ARGV[1] then return redis.call("DEL", KEYS[1]) end +return 0`) + +func (m *Messages) fill(ctx context.Context, key, chatID, cursor string, limit int) (domain.Page[domain.Message], error) { + lockKey := "hc:lock:" + key + token := randomVersion() + locked, err := m.rdb.SetNX(ctx, lockKey, token, m.opt.LockTTL).Result() + if err != nil { + m.markDown(err) + return m.src.HistoryPage(ctx, chatID, cursor, limit) + } + if !locked { + deadline := time.Now().Add(m.opt.LockTTL) + for time.Now().Before(deadline) { + time.Sleep(pollInterval) + if page, ok := m.getPage(ctx, key); ok { + return page, nil + } + } + return m.src.HistoryPage(ctx, chatID, cursor, limit) + } + defer unlockScript.Run(ctx, m.rdb, []string{lockKey}, token) + + page, err := m.src.HistoryPage(ctx, chatID, cursor, limit) + if err != nil { + return page, err + } + m.sleepFill(ctx) + if b, err := encodePage(page); err == nil { + m.markDown(m.rdb.Set(ctx, key, b, m.opt.PageTTL).Err()) + } + return page, nil +} + +// addPending вызывается до ответа 201: после него чат читается мимо кэша, +// пока версия не будет сброшена, в том числе после рестарта API. +func (m *Messages) addPending(ctx context.Context, chatID string) { + m.markPending(chatID, 0) + if m.opt.Outbox == nil { + m.log.Warn("history cache invalidation deferred", slog.String("chat_id", chatID)) + return + } + gen, err := m.opt.Outbox.AddPendingInvalidation(ctx, chatID) + if err != nil { + m.log.Error("history cache invalidation deferred in memory only, lost on restart", + slog.String("chat_id", chatID), slog.Any("err", err)) + return + } + m.markPending(chatID, gen) + m.log.Warn("history cache invalidation deferred", + slog.String("chat_id", chatID), slog.Int64("gen", gen)) +} + +// markPending всегда выдаёт новый seq, чтобы повтор, начатый раньше, не снял +// запись. gen не уменьшается. +func (m *Messages) markPending(chatID string, gen int64) { + m.mu.Lock() + m.seq++ + e := m.pending[chatID] + e.seq = m.seq + e.gen = max(e.gen, gen) + m.pending[chatID] = e + m.mu.Unlock() +} + +func (m *Messages) bypass(chatID string) bool { + if m.isDown() || !m.loaded.Load() { + return true + } + m.mu.Lock() + _, ok := m.pending[chatID] + m.mu.Unlock() + return ok +} + +func (m *Messages) loadPending() { + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + rows, err := m.opt.Outbox.PendingInvalidations(ctx) + if err != nil { + m.log.Warn("history cache: pending invalidations not loaded, bypassing", slog.Any("err", err)) + return + } + for id, gen := range rows { + m.markPending(id, gen) + } + m.loaded.Store(true) + if len(rows) > 0 { + m.log.Info("history cache: pending invalidations loaded", slog.Int("chats", len(rows))) + } +} + +func (m *Messages) retryLoop() { + defer close(m.done) + t := time.NewTicker(retryInterval) + defer t.Stop() + for { + if !m.loaded.Load() { + m.loadPending() + } + m.retryPending() + select { + case <-m.stop: + return + case <-t.C: + } + } +} + +func (m *Messages) retryPending() { + m.mu.Lock() + chats := make(map[string]pendingEntry, len(m.pending)) + for id, e := range m.pending { + chats[id] = e + } + m.mu.Unlock() + for id, e := range chats { + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + err := m.rdb.Del(ctx, verKey(id)).Err() + if err == nil && e.gen > 0 { + err = m.opt.Outbox.ResolvePendingInvalidation(ctx, id, e.gen) + } + cancel() + if err != nil { + return + } + m.resolved(id, e) + } +} + +// resolved снимает запись, если после снимка e не было нового сбоя. +func (m *Messages) resolved(chatID string, e pendingEntry) { + m.mu.Lock() + if m.pending[chatID].seq == e.seq { + delete(m.pending, chatID) + } + m.mu.Unlock() +} + +func (m *Messages) isDown() bool { + return time.Now().UnixNano() < m.downUntil.Load() +} + +func (m *Messages) markDown(err error) { + if err == nil || errors.Is(err, redis.Nil) { + return + } + if !m.isDown() { + m.log.Warn("history cache unavailable, bypassing", slog.Any("err", err)) + } + m.downUntil.Store(time.Now().Add(breakerPause).UnixNano()) +} + +func (m *Messages) getPage(ctx context.Context, key string) (domain.Page[domain.Message], bool) { + b, err := m.rdb.Get(ctx, key).Bytes() + if err != nil { + m.markDown(err) + return domain.Page[domain.Message]{}, false + } + page, err := decodePage(b) + return page, err == nil +} + +func (m *Messages) sleepFill(ctx context.Context) { + if m.opt.FillDelay <= 0 { + return + } + select { + case <-time.After(m.opt.FillDelay): + case <-ctx.Done(): + } +} + +func verKey(chatID string) string { return "hc:ver:" + chatID } + +func pageKey(prefix, cursor string, limit int) string { + return prefix + ":" + strconv.Itoa(limit) + ":" + cursor +} + +func randomVersion() string { + var b [8]byte + _, _ = rand.Read(b[:]) + return hex.EncodeToString(b[:]) +} + +type cachedPage struct { + Items []domain.Message `json:"items"` + NextCursor string `json:"next_cursor"` +} + +func encodePage(p domain.Page[domain.Message]) ([]byte, error) { + return json.Marshal(cachedPage{Items: p.Items, NextCursor: p.NextCursor}) +} + +func decodePage(b []byte) (domain.Page[domain.Message], error) { + var c cachedPage + if err := json.Unmarshal(b, &c); err != nil { + return domain.Page[domain.Message]{}, err + } + return domain.Page[domain.Message]{Items: c.Items, NextCursor: c.NextCursor}, nil +} diff --git a/app/internal/cache/history_test.go b/app/internal/cache/history_test.go new file mode 100644 index 00000000..ed93d70f --- /dev/null +++ b/app/internal/cache/history_test.go @@ -0,0 +1,208 @@ +package cache + +import ( + "context" + "errors" + "fmt" + "io" + "log/slog" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/redis/go-redis/v9" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" +) + +const member = "alice" + +type fakeSource struct { + mu sync.Mutex + msgs []domain.Message + queryDelay time.Duration + pageCalls atomic.Int64 +} + +func (f *fakeSource) AddMessage(_ context.Context, callerID, chatID, _, text string, _ []string) (domain.Message, error) { + f.mu.Lock() + defer f.mu.Unlock() + m := domain.Message{ + ID: fmt.Sprintf("m%04d", len(f.msgs)), + ChatID: chatID, + AuthorID: callerID, + Text: text, + CreatedAt: time.Now().UTC(), + } + f.msgs = append(f.msgs, m) + return m, nil +} + +func (f *fakeSource) IsMember(_ context.Context, _, userID string) (bool, error) { + return userID == member, nil +} + +func (f *fakeSource) HistoryPage(context.Context, string, string, int) (domain.Page[domain.Message], error) { + f.pageCalls.Add(1) + f.mu.Lock() + snapshot := append([]domain.Message(nil), f.msgs...) + f.mu.Unlock() + time.Sleep(f.queryDelay) + return domain.Page[domain.Message]{Items: snapshot}, nil +} + +func (f *fakeSource) ListMessages(ctx context.Context, callerID, chatID, cursor string, limit int) (domain.Page[domain.Message], error) { + if ok, _ := f.IsMember(ctx, chatID, callerID); !ok { + return domain.Page[domain.Message]{}, domain.ErrNotFound + } + return f.HistoryPage(ctx, chatID, cursor, limit) +} + +func newCache(t *testing.T, c *redis.Client, mode string, src *fakeSource, fillDelay time.Duration) *Messages { + t.Helper() + m := New(src, c, Options{ + Mode: mode, + PageTTL: time.Minute, + FillDelay: fillDelay, + Logger: slog.New(slog.NewTextHandler(io.Discard, nil)), + }) + t.Cleanup(m.Close) + return m +} + +func contains(p domain.Page[domain.Message], id string) bool { + for _, m := range p.Items { + if m.ID == id { + return true + } + } + return false +} + +func TestCacheDown_Bypass(t *testing.T) { + ctx := context.Background() + dead := redis.NewClient(&redis.Options{ + Addr: "127.0.0.1:1", DialTimeout: 50 * time.Millisecond, MaxRetries: -1, + }) + t.Cleanup(func() { dead.Close() }) + src := &fakeSource{} + h := newCache(t, dead, ModeSafe, src, 0) + + msg, err := h.AddMessage(ctx, member, "chat-down", randomVersion(), "при упавшем кэше", nil) + if err != nil { + t.Fatalf("запись при упавшем кэше: %v", err) + } + page, err := h.ListMessages(ctx, member, "chat-down", "", 50) + if err != nil || !contains(page, msg.ID) { + t.Fatalf("чтение при упавшем кэше: err=%v", err) + } + if !h.bypass("chat-down") { + t.Fatal("чат с несброшенной версией должен читаться мимо кэша") + } + if _, err := h.ListMessages(ctx, "mallory", "chat-down", "", 50); !errors.Is(err, domain.ErrNotFound) { + t.Fatalf("обход кэша не должен пропускать постороннего: %v", err) + } +} + +type fakeOutbox struct { + mu sync.Mutex + rows map[string]int64 + seq int64 // как cache_invalidations_gen_seq: gen не повторяется + loadErr error +} + +func (f *fakeOutbox) AddPendingInvalidation(_ context.Context, chatID string) (int64, error) { + f.mu.Lock() + defer f.mu.Unlock() + f.seq++ + f.rows[chatID] = f.seq + return f.seq, nil +} + +func (f *fakeOutbox) PendingInvalidations(context.Context) (map[string]int64, error) { + f.mu.Lock() + defer f.mu.Unlock() + if f.loadErr != nil { + return nil, f.loadErr + } + out := make(map[string]int64, len(f.rows)) + for k, v := range f.rows { + out[k] = v + } + return out, nil +} + +func (f *fakeOutbox) ResolvePendingInvalidation(_ context.Context, chatID string, gen int64) error { + f.mu.Lock() + defer f.mu.Unlock() + if f.rows[chatID] == gen { + delete(f.rows, chatID) + } + return nil +} + +func (f *fakeOutbox) len() int { + f.mu.Lock() + defer f.mu.Unlock() + return len(f.rows) +} + +func TestBypassUntilOutboxLoaded(t *testing.T) { + outbox := &fakeOutbox{rows: map[string]int64{}, loadErr: errors.New("db down")} + h := New(&fakeSource{}, redis.NewClient(&redis.Options{Addr: "127.0.0.1:1"}), Options{ + Mode: ModeSafe, + Outbox: outbox, + Logger: slog.New(slog.NewTextHandler(io.Discard, nil)), + }) + defer h.Close() + time.Sleep(3 * retryInterval) + if !h.bypass("any") { + t.Fatal("пока долг из Outbox не прочитан, кэш не должен отдавать страницы") + } + outbox.mu.Lock() + outbox.loadErr = nil + outbox.mu.Unlock() + deadline := time.Now().Add(2 * time.Second) + for h.bypass("any") { + if time.Now().After(deadline) { + t.Fatal("после загрузки Outbox чтение через кэш не включилось") + } + time.Sleep(20 * time.Millisecond) + } +} + +// Повтор сбросил версию и снял строку Outbox, но до того, как он снял запись +// из памяти, новая запись снова не смогла сбросить версию. Запись в памяти и +// строка Outbox должны остаться, иначе ответ 201 придёт при устаревшем кэше. +func TestRetryDoesNotDropNewerFailure(t *testing.T) { + ctx := context.Background() + outbox := &fakeOutbox{rows: map[string]int64{}} + h := New(&fakeSource{}, redis.NewClient(&redis.Options{Addr: "127.0.0.1:1"}), Options{ + Mode: ModeSafe, + Outbox: outbox, + Logger: slog.New(slog.NewTextHandler(io.Discard, nil)), + }) + h.Close() // повтор ведём вручную + h.loaded.Store(true) + chat := "chat-retry-race" + + h.addPending(ctx, chat) + snap := h.pending[chat] // снимок повтора; DEL версии прошёл + if err := outbox.ResolvePendingInvalidation(ctx, chat, snap.gen); err != nil { + t.Fatal(err) + } + h.addPending(ctx, chat) // новый сбой DEL до ответа 201 + h.resolved(chat, snap) + + if !h.bypass(chat) { + t.Fatal("повтор снял запись о более новом сбое") + } + if rows, _ := outbox.PendingInvalidations(ctx); rows[chat] <= snap.gen { + t.Fatalf("строка Outbox: gen=%d, ожидался новый gen > %d", rows[chat], snap.gen) + } + h.resolved(chat, h.pending[chat]) + if h.bypass(chat) { + t.Fatal("актуальный повтор должен снять запись") + } +} diff --git a/app/internal/config/attachments.go b/app/internal/config/attachments.go new file mode 100644 index 00000000..6e815c7b --- /dev/null +++ b/app/internal/config/attachments.go @@ -0,0 +1,40 @@ +package config + +// Верхние границы из контракта: конфигурация может их уменьшить, но не превысить. +const ( + ContractMaxUploadBytes = 10 * 1024 * 1024 + ContractMaxImagePixels = 40_000_000 +) + +type S3 struct { + Endpoint string + Region string + Bucket string + AccessKeyIDFile string + SecretAccessKeyFile string + // TimeoutMs — предел на одну операцию с S3. Меньше timeout server балансировщика (15 с): + // клиент получает 503 от API, а не 504 от LB. + TimeoutMs int +} + +type Attachments struct { + MaxUploadBytes int64 + MaxImagePixels int64 + // MaxConcurrentUploads ограничивает загрузки на одну реплику и тем самым диск под временные + // файлы (не больше MaxConcurrentUploads × MaxUploadBytes); сверх него — 429. + MaxConcurrentUploads int +} + +// MinJanitorGraceSeconds covers the direct ticket lifetime (120s), complete +// timeout (60s), and an additional safety margin before orphan deletion. +const MinJanitorGraceSeconds = 300 + +// Janitor — очиститель объектов без метаданных (cmd/janitor). +type Janitor struct { + GraceSeconds int + IntervalSeconds int + // MaxDeletes — сколько объектов без строки допустимо удалить за проход. Больше — признак аварии + // (например, БД восстановлена из старой копии), и очиститель ничего не удаляет. + MaxDeletes int + DryRun bool +} diff --git a/app/internal/config/config.go b/app/internal/config/config.go new file mode 100644 index 00000000..df077808 --- /dev/null +++ b/app/internal/config/config.go @@ -0,0 +1,215 @@ +package config + +import ( + "errors" + "fmt" + "os" + "regexp" + "strings" + + "github.com/google/uuid" +) + +var instanceIDPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`) + +type Config struct { + Env string + Version string + InstanceID string + + HTTP HTTP + Logger Logger + Limits Limits + Database Database + Cache Cache + Session Session + + S3 S3 + Attachments Attachments + Janitor Janitor + + Idempotency Idempotency + HistoryCache HistoryCache +} + +func Load() (*Config, error) { + cfg := defaults() + if err := cfg.applyEnv(os.LookupEnv); err != nil { + return nil, fmt.Errorf("config: env: %w", err) + } + if cfg.InstanceID == "" { + cfg.InstanceID = defaultInstanceID() + } + if err := cfg.validate(); err != nil { + return nil, fmt.Errorf("config: validate: %w", err) + } + return cfg, nil +} + +func defaults() *Config { + return &Config{ + Env: "lab", + Version: "dev", + HTTP: HTTP{ + Addr: "0.0.0.0:8080", + ReadTimeoutMs: 10000, + WriteTimeoutMs: 10000, + IdleTimeoutMs: 60000, + ShutdownTimeoutMs: 10000, + ShutdownDrainMs: 3000, + }, + Logger: Logger{Level: "info"}, + Limits: Limits{ + MaxBodyBytes: 64 * 1024, + MaxInFlight: 64, + MaxMessagesGlobal: 100000, + MaxHeapBytes: 256 * 1024 * 1024, + }, + Database: Database{ + MaxConns: 10, + ConnectTimeoutMs: 5000, + QueryTimeoutMs: 3000, + }, + Cache: Cache{ + PoolSize: 20, + TimeoutMs: 1000, + }, + Session: Session{Store: "valkey", TTLSeconds: 3600}, + S3: S3{ + Endpoint: "http://s3:9000", + Region: "us-east-1", + Bucket: "messenger-attachments", + TimeoutMs: 8000, + }, + Attachments: Attachments{ + MaxUploadBytes: ContractMaxUploadBytes, + MaxImagePixels: ContractMaxImagePixels, + MaxConcurrentUploads: 16, + }, + Janitor: Janitor{GraceSeconds: 3600, IntervalSeconds: 600, MaxDeletes: 1000}, + Idempotency: Idempotency{TTLSeconds: MinIdempotencyTTLSeconds}, + HistoryCache: HistoryCache{ + Mode: "off", + PageTTLSeconds: 30, + TimeoutMs: 200, + PoolSize: 20, + }, + } +} + +// defaultInstanceID — hostname: в Docker это короткий ID контейнера, поэтому ответ +// можно сопоставить с конкретным контейнером. Значение неизменно на всю жизнь процесса. +func defaultInstanceID() string { + if h, err := os.Hostname(); err == nil && instanceIDPattern.MatchString(h) { + return h + } + return uuid.NewString() +} + +func (c *Config) validate() error { + if !instanceIDPattern.MatchString(c.InstanceID) { + return fmt.Errorf("APP_INSTANCE_ID must match %s", instanceIDPattern) + } + if strings.TrimSpace(c.Env) == "" { + return errors.New("env is required") + } + if strings.TrimSpace(c.Version) == "" { + return errors.New("version is required") + } + if strings.TrimSpace(c.HTTP.Addr) == "" { + return errors.New("http.addr is required") + } + if c.HTTP.ShutdownTimeoutMs <= 0 || c.HTTP.ShutdownTimeoutMs > 10000 { + return fmt.Errorf("APP_SHUTDOWN_TIMEOUT_MS must be in (0, 10000], got %d", c.HTTP.ShutdownTimeoutMs) + } + if c.HTTP.ShutdownDrainMs < 0 || c.HTTP.ShutdownDrainMs > 10000 { + return fmt.Errorf("APP_SHUTDOWN_DRAIN_MS must be in [0, 10000], got %d", c.HTTP.ShutdownDrainMs) + } + if c.HTTP.ReadTimeoutMs <= 0 { + return fmt.Errorf("APP_READ_TIMEOUT_MS must be > 0, got %d", c.HTTP.ReadTimeoutMs) + } + if c.HTTP.WriteTimeoutMs <= 0 { + return fmt.Errorf("APP_WRITE_TIMEOUT_MS must be > 0, got %d", c.HTTP.WriteTimeoutMs) + } + if c.HTTP.IdleTimeoutMs <= 0 { + return fmt.Errorf("APP_IDLE_TIMEOUT_MS must be > 0, got %d", c.HTTP.IdleTimeoutMs) + } + + if c.Limits.MaxBodyBytes <= 0 { + return fmt.Errorf("APP_MAX_BODY_BYTES must be > 0, got %d", c.Limits.MaxBodyBytes) + } + if c.Limits.MaxInFlight <= 0 { + return fmt.Errorf("APP_MAX_INFLIGHT must be > 0, got %d", c.Limits.MaxInFlight) + } + if c.Limits.MaxMessagesGlobal <= 0 { + return fmt.Errorf("APP_MAX_MESSAGES must be > 0, got %d", c.Limits.MaxMessagesGlobal) + } + if c.Limits.MaxHeapBytes == 0 { + return errors.New("APP_MAX_HEAP_BYTES must be > 0") + } + + if c.S3.TimeoutMs <= 0 { + return fmt.Errorf("S3_TIMEOUT_MS must be > 0, got %d", c.S3.TimeoutMs) + } + if c.Attachments.MaxUploadBytes <= 0 || c.Attachments.MaxUploadBytes > ContractMaxUploadBytes { + return fmt.Errorf("MAX_UPLOAD_BYTES must be in (0, %d], got %d", ContractMaxUploadBytes, c.Attachments.MaxUploadBytes) + } + if c.Attachments.MaxImagePixels <= 0 || c.Attachments.MaxImagePixels > ContractMaxImagePixels { + return fmt.Errorf("MAX_IMAGE_PIXELS must be in (0, %d], got %d", ContractMaxImagePixels, c.Attachments.MaxImagePixels) + } + if c.Attachments.MaxConcurrentUploads <= 0 { + return fmt.Errorf("MAX_CONCURRENT_UPLOADS must be > 0, got %d", c.Attachments.MaxConcurrentUploads) + } + + if c.Janitor.GraceSeconds < MinJanitorGraceSeconds { + return fmt.Errorf("JANITOR_GRACE_SECONDS must be >= %d, got %d", MinJanitorGraceSeconds, c.Janitor.GraceSeconds) + } + if c.Janitor.IntervalSeconds <= 0 { + return fmt.Errorf("JANITOR_INTERVAL_SECONDS must be > 0, got %d", c.Janitor.IntervalSeconds) + } + if c.Janitor.MaxDeletes <= 0 { + return fmt.Errorf("JANITOR_MAX_DELETES must be > 0, got %d", c.Janitor.MaxDeletes) + } + + if c.Database.MaxConns <= 0 { + return fmt.Errorf("DB_MAX_CONNS must be > 0, got %d", c.Database.MaxConns) + } + if c.Database.ConnectTimeoutMs <= 0 { + return fmt.Errorf("DB_CONNECT_TIMEOUT_MS must be > 0, got %d", c.Database.ConnectTimeoutMs) + } + if c.Database.QueryTimeoutMs <= 0 { + return fmt.Errorf("DB_QUERY_TIMEOUT_MS must be > 0, got %d", c.Database.QueryTimeoutMs) + } + if c.Cache.PoolSize <= 0 { + return fmt.Errorf("CACHE_POOL_SIZE must be > 0, got %d", c.Cache.PoolSize) + } + if c.Cache.TimeoutMs <= 0 { + return fmt.Errorf("CACHE_TIMEOUT_MS must be > 0, got %d", c.Cache.TimeoutMs) + } + switch c.HistoryCache.Mode { + case "off", "naive", "safe": + default: + return fmt.Errorf("HISTORY_CACHE must be off|naive|safe, got %q", c.HistoryCache.Mode) + } + if c.HistoryCache.PageTTLSeconds <= 0 { + return fmt.Errorf("HISTORY_CACHE_TTL_SECONDS must be > 0, got %d", c.HistoryCache.PageTTLSeconds) + } + if c.HistoryCache.TimeoutMs <= 0 || c.HistoryCache.PoolSize <= 0 { + return errors.New("HISTORY_CACHE_TIMEOUT_MS and HISTORY_CACHE_POOL_SIZE must be > 0") + } + if c.HistoryCache.FillDelayMs < 0 || c.HistoryCache.FillDelayMs > 1000 { + return fmt.Errorf("HISTORY_CACHE_FILL_DELAY_MS must be in [0, 1000], got %d", c.HistoryCache.FillDelayMs) + } + // Реализовано одно хранилище сессий; иное значение — ошибка конфигурации, а не тихий выбор. + if c.Session.Store != "valkey" { + return fmt.Errorf("SESSION_STORE must be valkey (the only implemented session store), got %q", c.Session.Store) + } + if c.Idempotency.TTLSeconds < MinIdempotencyTTLSeconds { + return fmt.Errorf("IDEMPOTENCY_TTL_SECONDS must be >= %d, got %d", MinIdempotencyTTLSeconds, c.Idempotency.TTLSeconds) + } + if c.Session.TTLSeconds <= 0 { + return fmt.Errorf("SESSION_TTL_SECONDS must be > 0, got %d", c.Session.TTLSeconds) + } + + return nil +} diff --git a/app/internal/config/database.go b/app/internal/config/database.go new file mode 100644 index 00000000..05a00862 --- /dev/null +++ b/app/internal/config/database.go @@ -0,0 +1,13 @@ +package config + +type Database struct { + URLFile string + URL string + MaxConns int32 + ConnectTimeoutMs int + QueryTimeoutMs int + // EnableBitmapScan: по умолчанию выключено. Для чата, которого ещё нет в статистике, + // планировщик может ожидать почти пустой результат и выбрать чтение всего чата с сортировкой. + // Это гипотеза: замеров, подтверждающих выигрыш, в evidence нет. Флаг нужен для сравнения. + EnableBitmapScan bool +} diff --git a/app/internal/config/env.go b/app/internal/config/env.go new file mode 100644 index 00000000..21e91c07 --- /dev/null +++ b/app/internal/config/env.go @@ -0,0 +1,176 @@ +package config + +import ( + "fmt" + "net" + "strconv" + "strings" +) + +func (c *Config) applyEnv(lookup func(string) (string, bool)) error { + get := func(key string) (string, bool) { + v, ok := lookup(key) + v = strings.TrimSpace(v) + return v, ok && v != "" + } + + if v, ok := get("APP_ENV"); ok { + c.Env = v + } + if v, ok := get("APP_VERSION"); ok { + c.Version = v + } + if v, ok := get("APP_INSTANCE_ID"); ok { + c.InstanceID = v + } + if v, ok := get("APP_LOG_LEVEL"); ok { + c.Logger.Level = v + } + if v, ok := get("DATABASE_URL_FILE"); ok { + c.Database.URLFile = v + } + if v, ok := get("DATABASE_URL"); ok { + c.Database.URL = v + } + if v, ok := get("CACHE_URL_FILE"); ok { + c.Cache.URLFile = v + } + if v, ok := get("CACHE_URL"); ok { + c.Cache.URL = v + } + if v, ok := get("SESSION_STORE"); ok { + c.Session.Store = strings.ToLower(v) + } + if v, ok := get("S3_ENDPOINT"); ok { + c.S3.Endpoint = v + } + if v, ok := get("S3_REGION"); ok { + c.S3.Region = v + } + if v, ok := get("S3_BUCKET"); ok { + c.S3.Bucket = v + } + if v, ok := get("S3_ACCESS_KEY_ID_FILE"); ok { + c.S3.AccessKeyIDFile = v + } + if v, ok := get("S3_SECRET_ACCESS_KEY_FILE"); ok { + c.S3.SecretAccessKeyFile = v + } + if v, ok := get("HISTORY_CACHE"); ok { + c.HistoryCache.Mode = strings.ToLower(v) + } + if v, ok := get("HISTORY_CACHE_URL_FILE"); ok { + c.HistoryCache.URLFile = v + } + if v, ok := get("HISTORY_CACHE_URL"); ok { + c.HistoryCache.URL = v + } + + if v, ok := get("JANITOR_DRY_RUN"); ok { + dryRun, err := strconv.ParseBool(v) + if err != nil { + return fmt.Errorf("JANITOR_DRY_RUN: not a boolean: %q", v) + } + c.Janitor.DryRun = dryRun + } + + host, port, err := net.SplitHostPort(c.HTTP.Addr) + if err != nil { + return fmt.Errorf("default addr %q: %w", c.HTTP.Addr, err) + } + if v, ok := get("APP_HOST"); ok { + host = v + } + if v, ok := get("APP_PORT"); ok { + port = v + } + if n, err := strconv.Atoi(port); err != nil || n < 1 || n > 65535 { + return fmt.Errorf("APP_PORT must be in [1, 65535], got %q", port) + } + c.HTTP.Addr = net.JoinHostPort(host, port) + + ints := []struct { + key string + dst *int + }{ + {"APP_READ_TIMEOUT_MS", &c.HTTP.ReadTimeoutMs}, + {"APP_WRITE_TIMEOUT_MS", &c.HTTP.WriteTimeoutMs}, + {"APP_IDLE_TIMEOUT_MS", &c.HTTP.IdleTimeoutMs}, + {"APP_SHUTDOWN_TIMEOUT_MS", &c.HTTP.ShutdownTimeoutMs}, + {"APP_SHUTDOWN_DRAIN_MS", &c.HTTP.ShutdownDrainMs}, + {"APP_MAX_INFLIGHT", &c.Limits.MaxInFlight}, + {"APP_MAX_MESSAGES", &c.Limits.MaxMessagesGlobal}, + {"DB_CONNECT_TIMEOUT_MS", &c.Database.ConnectTimeoutMs}, + {"DB_QUERY_TIMEOUT_MS", &c.Database.QueryTimeoutMs}, + {"S3_TIMEOUT_MS", &c.S3.TimeoutMs}, + {"MAX_CONCURRENT_UPLOADS", &c.Attachments.MaxConcurrentUploads}, + {"JANITOR_GRACE_SECONDS", &c.Janitor.GraceSeconds}, + {"JANITOR_INTERVAL_SECONDS", &c.Janitor.IntervalSeconds}, + {"JANITOR_MAX_DELETES", &c.Janitor.MaxDeletes}, + {"CACHE_POOL_SIZE", &c.Cache.PoolSize}, + {"CACHE_TIMEOUT_MS", &c.Cache.TimeoutMs}, + {"SESSION_TTL_SECONDS", &c.Session.TTLSeconds}, + {"IDEMPOTENCY_TTL_SECONDS", &c.Idempotency.TTLSeconds}, + {"HISTORY_CACHE_TTL_SECONDS", &c.HistoryCache.PageTTLSeconds}, + {"HISTORY_CACHE_TIMEOUT_MS", &c.HistoryCache.TimeoutMs}, + {"HISTORY_CACHE_POOL_SIZE", &c.HistoryCache.PoolSize}, + {"HISTORY_CACHE_FILL_DELAY_MS", &c.HistoryCache.FillDelayMs}, + } + for _, it := range ints { + v, ok := get(it.key) + if !ok { + continue + } + n, err := strconv.Atoi(v) + if err != nil { + return fmt.Errorf("%s: not an integer: %q", it.key, v) + } + *it.dst = n + } + + if v, ok := get("APP_MAX_BODY_BYTES"); ok { + n, err := strconv.ParseInt(v, 10, 64) + if err != nil { + return fmt.Errorf("APP_MAX_BODY_BYTES: not an integer: %q", v) + } + c.Limits.MaxBodyBytes = n + } + for _, it := range []struct { + key string + dst *int64 + }{ + {"MAX_UPLOAD_BYTES", &c.Attachments.MaxUploadBytes}, + {"MAX_IMAGE_PIXELS", &c.Attachments.MaxImagePixels}, + } { + if v, ok := get(it.key); ok { + n, err := strconv.ParseInt(v, 10, 64) + if err != nil { + return fmt.Errorf("%s: not an integer: %q", it.key, v) + } + *it.dst = n + } + } + if v, ok := get("DB_MAX_CONNS"); ok { + n, err := strconv.ParseInt(v, 10, 32) + if err != nil { + return fmt.Errorf("DB_MAX_CONNS: not an integer: %q", v) + } + c.Database.MaxConns = int32(n) + } + if v, ok := get("DB_ENABLE_BITMAPSCAN"); ok { + b, err := strconv.ParseBool(v) + if err != nil { + return fmt.Errorf("DB_ENABLE_BITMAPSCAN: not a boolean: %q", v) + } + c.Database.EnableBitmapScan = b + } + if v, ok := get("APP_MAX_HEAP_BYTES"); ok { + n, err := strconv.ParseUint(v, 10, 64) + if err != nil { + return fmt.Errorf("APP_MAX_HEAP_BYTES: not a non-negative integer: %q", v) + } + c.Limits.MaxHeapBytes = n + } + + return nil +} diff --git a/app/internal/config/env_test.go b/app/internal/config/env_test.go new file mode 100644 index 00000000..4bea642b --- /dev/null +++ b/app/internal/config/env_test.go @@ -0,0 +1,85 @@ +package config + +import "testing" + +func TestLoad_Defaults(t *testing.T) { + cfg, err := Load() + if err != nil { + t.Fatal(err) + } + if cfg.HTTP.Addr != "0.0.0.0:8080" || cfg.Env != "lab" || cfg.Limits.MaxInFlight != 64 { + t.Errorf("cfg = %+v", cfg) + } +} + +func TestLoad_EnvOverridesDefaults(t *testing.T) { + t.Setenv("APP_HOST", "127.0.0.1") + t.Setenv("APP_PORT", "9090") + t.Setenv("APP_ENV", "docker") + t.Setenv("APP_MAX_INFLIGHT", "8") + t.Setenv("APP_MAX_BODY_BYTES", "2048") + + cfg, err := Load() + if err != nil { + t.Fatal(err) + } + if cfg.HTTP.Addr != "127.0.0.1:9090" { + t.Errorf("addr = %q, want 127.0.0.1:9090", cfg.HTTP.Addr) + } + if cfg.Env != "docker" { + t.Errorf("env = %q, want docker", cfg.Env) + } + if cfg.Limits.MaxInFlight != 8 || cfg.Limits.MaxBodyBytes != 2048 { + t.Errorf("limits = %+v", cfg.Limits) + } +} + +func TestLoad_PortOnlyKeepsDefaultHost(t *testing.T) { + t.Setenv("APP_PORT", "18080") + + cfg, err := Load() + if err != nil { + t.Fatal(err) + } + if cfg.HTTP.Addr != "0.0.0.0:18080" { + t.Errorf("addr = %q, want 0.0.0.0:18080", cfg.HTTP.Addr) + } +} + +func TestLoad_InstanceID(t *testing.T) { + cfg, err := Load() + if err != nil { + t.Fatal(err) + } + if cfg.InstanceID == "" { + t.Error("default instance id is empty") + } + + t.Setenv("APP_INSTANCE_ID", "api-1") + cfg, err = Load() + if err != nil { + t.Fatal(err) + } + if cfg.InstanceID != "api-1" { + t.Errorf("instance id = %q, want api-1", cfg.InstanceID) + } +} + +func TestLoad_InvalidEnvFails(t *testing.T) { + for key, val := range map[string]string{ + "APP_PORT": "http", + "APP_MAX_INFLIGHT": "many", + "APP_MAX_MESSAGES": "0", + "APP_SHUTDOWN_TIMEOUT_MS": "30000", + "APP_INSTANCE_ID": "bad id", + "APP_SHUTDOWN_DRAIN_MS": "-1", + "IDEMPOTENCY_TTL_SECONDS": "3600", + } { + t.Run(key, func(t *testing.T) { + t.Setenv(key, val) + if _, err := Load(); err == nil { + t.Errorf("%s=%q: expected error", key, val) + } + }) + } +} diff --git a/app/internal/config/history_cache.go b/app/internal/config/history_cache.go new file mode 100644 index 00000000..e28fb818 --- /dev/null +++ b/app/internal/config/history_cache.go @@ -0,0 +1,11 @@ +package config + +type HistoryCache struct { + Mode string + URLFile string + URL string + PageTTLSeconds int + TimeoutMs int + PoolSize int + FillDelayMs int +} diff --git a/app/internal/config/http.go b/app/internal/config/http.go new file mode 100644 index 00000000..3059c719 --- /dev/null +++ b/app/internal/config/http.go @@ -0,0 +1,12 @@ +package config + +type HTTP struct { + Addr string + ReadTimeoutMs int + WriteTimeoutMs int + IdleTimeoutMs int + ShutdownTimeoutMs int + // ShutdownDrainMs — сколько после SIGTERM обслуживать запросы, отвечая на readiness 503, + // чтобы балансировщик успел вывести реплику. Должно быть больше времени его обнаружения. + ShutdownDrainMs int +} diff --git a/app/internal/config/idempotency.go b/app/internal/config/idempotency.go new file mode 100644 index 00000000..32c97cc0 --- /dev/null +++ b/app/internal/config/idempotency.go @@ -0,0 +1,8 @@ +package config + +// MinIdempotencyTTLSeconds — контракт требует хранить результат не менее 24 часов. +const MinIdempotencyTTLSeconds = 86400 + +type Idempotency struct { + TTLSeconds int +} diff --git a/app/internal/config/limits.go b/app/internal/config/limits.go new file mode 100644 index 00000000..889fab56 --- /dev/null +++ b/app/internal/config/limits.go @@ -0,0 +1,8 @@ +package config + +type Limits struct { + MaxBodyBytes int64 + MaxInFlight int + MaxMessagesGlobal int + MaxHeapBytes uint64 +} diff --git a/app/internal/config/logger.go b/app/internal/config/logger.go new file mode 100644 index 00000000..be8e36b4 --- /dev/null +++ b/app/internal/config/logger.go @@ -0,0 +1,5 @@ +package config + +type Logger struct { + Level string +} diff --git a/app/internal/config/session.go b/app/internal/config/session.go new file mode 100644 index 00000000..56e0da42 --- /dev/null +++ b/app/internal/config/session.go @@ -0,0 +1,13 @@ +package config + +type Session struct { + Store string + TTLSeconds int +} + +type Cache struct { + URLFile string + URL string + PoolSize int + TimeoutMs int +} diff --git a/app/internal/domain/attachment.go b/app/internal/domain/attachment.go new file mode 100644 index 00000000..0d1de6f2 --- /dev/null +++ b/app/internal/domain/attachment.go @@ -0,0 +1,27 @@ +package domain + +import "time" + +// StatusReady — единственное состояние вложения в lab4: метаданные появляются только после +// сохранения оригинала. Асинхронные состояния добавляются с lab5. +const StatusReady = "ready" + +const ( + ContentTypePNG = "image/png" + ContentTypeJPEG = "image/jpeg" +) + +type Attachment struct { + ID string + ChatID string + OwnerID string + Filename string + ContentType string + SizeBytes int64 + SHA256 string + // ObjectKey — внутренний ключ в bucket, назначает сервер. В публичный API не попадает. + ObjectKey string + Status string + CreatedAt time.Time + UpdatedAt time.Time +} diff --git a/app/internal/domain/chat.go b/app/internal/domain/chat.go new file mode 100644 index 00000000..2de7174e --- /dev/null +++ b/app/internal/domain/chat.go @@ -0,0 +1,10 @@ +package domain + +import "time" + +type Chat struct { + ID string + Title string + MemberIDs []string + CreatedAt time.Time +} diff --git a/app/internal/domain/errors.go b/app/internal/domain/errors.go new file mode 100644 index 00000000..02ad86ee --- /dev/null +++ b/app/internal/domain/errors.go @@ -0,0 +1,27 @@ +package domain + +import ( + "errors" + "fmt" +) + +var ( + ErrNotFound = errors.New("not found") + + ErrUnauthorized = errors.New("unauthorized") + + ErrConflict = errors.New("conflict") + + // ErrIdempotencyConflict — ключ уже использован с другим телом запроса. + ErrIdempotencyConflict = fmt.Errorf("idempotency key reused with different request: %w", ErrConflict) + + ErrInvalidArgument = errors.New("invalid argument") + + ErrUnavailable = errors.New("unavailable") + + ErrPayloadTooLarge = errors.New("payload too large") + + ErrRateLimited = errors.New("rate limited") + + ErrUnsupportedMedia = errors.New("unsupported media") +) diff --git a/app/internal/domain/message.go b/app/internal/domain/message.go new file mode 100644 index 00000000..036fd121 --- /dev/null +++ b/app/internal/domain/message.go @@ -0,0 +1,13 @@ +package domain + +import "time" + +type Message struct { + ID string + ChatID string + AuthorID string + Text string + CreatedAt time.Time + // AttachmentIDs — вложения этого чата в порядке из запроса; без вложений пусто. + AttachmentIDs []string +} diff --git a/app/internal/domain/page.go b/app/internal/domain/page.go new file mode 100644 index 00000000..494a7a47 --- /dev/null +++ b/app/internal/domain/page.go @@ -0,0 +1,67 @@ +package domain + +import ( + "encoding/base64" + "encoding/json" + "time" + + "github.com/google/uuid" +) + +type Page[T any] struct { + Items []T + NextCursor string +} + +type Cursor struct { + CreatedAt time.Time `json:"t"` + ID string `json:"i"` + Scope string `json:"s,omitempty"` +} + +func (c Cursor) IsZero() bool { + return c.ID == "" && c.CreatedAt.IsZero() +} + +func (c Cursor) Less(createdAt time.Time, id string) bool { + if c.CreatedAt.Before(createdAt) { + return true + } + if c.CreatedAt.After(createdAt) { + return false + } + return c.ID < id +} + +func EncodeCursor(c Cursor) string { + if c.IsZero() { + return "" + } + b, _ := json.Marshal(c) + return base64.RawURLEncoding.EncodeToString(b) +} + +func DecodeCursor(s string) (Cursor, error) { + if s == "" { + return Cursor{}, nil + } + raw, err := base64.RawURLEncoding.DecodeString(s) + if err != nil { + return Cursor{}, ErrInvalidArgument + } + var c Cursor + if err := json.Unmarshal(raw, &c); err != nil { + return Cursor{}, ErrInvalidArgument + } + + if c.CreatedAt.IsZero() || c.Scope == "" { + return Cursor{}, ErrInvalidArgument + } + if _, err := uuid.Parse(c.ID); err != nil || len(c.ID) != 36 { + return Cursor{}, ErrInvalidArgument + } + if EncodeCursor(c) != s { + return Cursor{}, ErrInvalidArgument + } + return c, nil +} diff --git a/app/internal/domain/session.go b/app/internal/domain/session.go new file mode 100644 index 00000000..f62cd52d --- /dev/null +++ b/app/internal/domain/session.go @@ -0,0 +1,9 @@ +package domain + +import "time" + +type Session struct { + Token string + ExpiresAt time.Time + User User +} diff --git a/app/internal/domain/user.go b/app/internal/domain/user.go new file mode 100644 index 00000000..34d52353 --- /dev/null +++ b/app/internal/domain/user.go @@ -0,0 +1,10 @@ +package domain + +import "time" + +type User struct { + ID string + Username string + DisplayName string + CreatedAt time.Time +} diff --git a/app/internal/imagecheck/imagecheck.go b/app/internal/imagecheck/imagecheck.go new file mode 100644 index 00000000..437020a2 --- /dev/null +++ b/app/internal/imagecheck/imagecheck.go @@ -0,0 +1,128 @@ +// Package imagecheck определяет тип изображения по содержимому и проверяет, что файл целый. +package imagecheck + +import ( + "bufio" + "bytes" + "context" + "errors" + "fmt" + "image" + "image/jpeg" + "image/png" + "io" + "time" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" +) + +var ( + // ErrUnsupported — не PNG/JPEG либо файл повреждён. + ErrUnsupported = errors.New("imagecheck: not a valid PNG or JPEG") + // ErrTooManyPixels — размеры из заголовка превышают лимит. + ErrTooManyPixels = errors.New("imagecheck: too many pixels") + // ErrBusy — очередь на декодирование не подошла за decodeWait. + ErrBusy = errors.New("imagecheck: decoder is busy") +) + +var ( + pngMagic = []byte("\x89PNG\r\n\x1a\n") + jpegMagic = []byte{0xff, 0xd8, 0xff} +) + +const ( + // decodeWait ограничивает ожидание очереди на декодирование. Вместе с записью в S3 и БД ответ + // должен уложиться в timeout server балансировщика (15 с): лучше честный 429, чем 504. + decodeWait = 5 * time.Second + // Файл читается с диска маленькими порциями; буфер убирает лишние системные вызовы. + readBuffer = 64 << 10 +) + +type format struct { + contentType string + config func(io.Reader) (image.Config, error) + decode func(io.Reader) (image.Image, error) +} + +func detect(head []byte) (format, bool) { + switch { + case bytes.HasPrefix(head, pngMagic): + return format{domain.ContentTypePNG, png.DecodeConfig, png.Decode}, true + case bytes.HasPrefix(head, jpegMagic): + return format{domain.ContentTypeJPEG, jpeg.DecodeConfig, jpeg.Decode}, true + } + return format{}, false +} + +func read(r io.ReadSeeker) (format, error) { + if _, err := r.Seek(0, io.SeekStart); err != nil { + return format{}, err + } + head := make([]byte, len(pngMagic)) + n, err := io.ReadFull(r, head) + if err != nil && !errors.Is(err, io.EOF) && !errors.Is(err, io.ErrUnexpectedEOF) { + return format{}, err + } + f, ok := detect(head[:n]) + if !ok { + return format{}, ErrUnsupported + } + if _, err := r.Seek(0, io.SeekStart); err != nil { + return format{}, err + } + return f, nil +} + +// Checker ограничивает расход памяти на проверку: размеры читаются из заголовка без распаковки, +// а полное декодирование выполняется только в пределах лимита пикселей и по одному за раз. +// Декодирование 40 Мп занимает сотни мегабайт, поэтому параллелить его нельзя. +type Checker struct { + maxPixels int64 + decoding chan struct{} +} + +func New(maxPixels int64) *Checker { + return &Checker{maxPixels: maxPixels, decoding: make(chan struct{}, 1)} +} + +// Inspect определяет истинный Content-Type по сигнатуре и проверяет размеры из заголовка. Пиксели +// не распаковываются, поэтому «бомба» и подмена типа отклоняются почти без затрат. +func (c *Checker) Inspect(r io.ReadSeeker) (string, error) { + f, err := read(r) + if err != nil { + return "", err + } + cfg, err := f.config(bufio.NewReaderSize(r, readBuffer)) + if err != nil { + return "", fmt.Errorf("%w: header", ErrUnsupported) + } + if cfg.Width <= 0 || cfg.Height <= 0 { + return "", fmt.Errorf("%w: empty image", ErrUnsupported) + } + if int64(cfg.Width) > c.maxPixels || int64(cfg.Width)*int64(cfg.Height) > c.maxPixels { + return "", ErrTooManyPixels + } + return f.contentType, nil +} + +// Decode полностью декодирует файл, уже прошедший Inspect. Результат не нужен: важно, что файл целый. +func (c *Checker) Decode(ctx context.Context, r io.ReadSeeker) error { + timer := time.NewTimer(decodeWait) + defer timer.Stop() + select { + case c.decoding <- struct{}{}: + defer func() { <-c.decoding }() + case <-timer.C: + return ErrBusy + case <-ctx.Done(): + return ctx.Err() + } + f, err := read(r) + if err != nil { + return err + } + if _, err := f.decode(bufio.NewReaderSize(r, readBuffer)); err != nil { + return fmt.Errorf("%w: body", ErrUnsupported) + } + return nil +} diff --git a/app/internal/imagecheck/imagecheck_test.go b/app/internal/imagecheck/imagecheck_test.go new file mode 100644 index 00000000..97fcc3b6 --- /dev/null +++ b/app/internal/imagecheck/imagecheck_test.go @@ -0,0 +1,139 @@ +package imagecheck + +import ( + "bytes" + "context" + "encoding/binary" + "errors" + "hash/crc32" + "image" + "image/color" + "image/jpeg" + "image/png" + "testing" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" +) + +func sampleImage(w, h int) image.Image { + img := image.NewRGBA(image.Rect(0, 0, w, h)) + for y := range h { + for x := range w { + img.Set(x, y, color.RGBA{uint8(x), uint8(y), 80, 255}) + } + } + return img +} + +func encodePNG(t *testing.T, w, h int) []byte { + t.Helper() + var b bytes.Buffer + if err := png.Encode(&b, sampleImage(w, h)); err != nil { + t.Fatal(err) + } + return b.Bytes() +} + +func encodeJPEG(t *testing.T, w, h int) []byte { + t.Helper() + var b bytes.Buffer + if err := jpeg.Encode(&b, sampleImage(w, h), nil); err != nil { + t.Fatal(err) + } + return b.Bytes() +} + +// pngHeaderOnly — сигнатура и IHDR с заданными размерами, без пикселей: так выглядит «бомба». +func pngHeaderOnly(w, h uint32) []byte { + var ihdr bytes.Buffer + ihdr.WriteString("IHDR") + binary.Write(&ihdr, binary.BigEndian, w) + binary.Write(&ihdr, binary.BigEndian, h) + ihdr.Write([]byte{8, 6, 0, 0, 0}) + var out bytes.Buffer + out.Write(pngMagic) + binary.Write(&out, binary.BigEndian, uint32(13)) + out.Write(ihdr.Bytes()) + binary.Write(&out, binary.BigEndian, crc32.ChecksumIEEE(ihdr.Bytes())) + return out.Bytes() +} + +// check — обе стадии проверки в том порядке, в каком их вызывает сервис. +func check(ctx context.Context, c *Checker, data []byte) (string, error) { + r := bytes.NewReader(data) + contentType, err := c.Inspect(r) + if err != nil { + return "", err + } + if err := c.Decode(ctx, r); err != nil { + return "", err + } + return contentType, nil +} + +func TestCheck(t *testing.T) { + validPNG := encodePNG(t, 20, 10) + validJPEG := encodeJPEG(t, 20, 10) + flipped := bytes.Clone(validPNG) + flipped[len(flipped)/2] ^= 0xff + + cases := []struct { + name string + data []byte + want string + wantErr error + }{ + {"png", validPNG, domain.ContentTypePNG, nil}, + {"jpeg", validJPEG, domain.ContentTypeJPEG, nil}, + {"empty", nil, "", ErrUnsupported}, + {"text", []byte(""), "", ErrUnsupported}, + {"gif", []byte("GIF89a\x01\x00\x01\x00\x00\x00\x00;"), "", ErrUnsupported}, + {"png magic only", pngMagic, "", ErrUnsupported}, + {"jpeg magic only", jpegMagic, "", ErrUnsupported}, + {"png truncated", validPNG[:len(validPNG)/2], "", ErrUnsupported}, + {"jpeg truncated", validJPEG[:len(validJPEG)/2], "", ErrUnsupported}, + {"png byte flipped", flipped, "", ErrUnsupported}, + {"png header without pixels", pngHeaderOnly(20, 10), "", ErrUnsupported}, + {"png pixel bomb", pngHeaderOnly(100000, 100000), "", ErrTooManyPixels}, + } + c := New(1000) + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got, err := check(context.Background(), c, tc.data) + if !errors.Is(err, tc.wantErr) { + t.Fatalf("err = %v, want %v", err, tc.wantErr) + } + if got != tc.want { + t.Errorf("type = %q, want %q", got, tc.want) + } + }) + } +} + +func TestCheck_PixelLimitIsInclusive(t *testing.T) { + c := New(200) + if _, err := check(context.Background(), c, encodePNG(t, 20, 10)); err != nil { + t.Errorf("exactly at limit: %v", err) + } + if _, err := check(context.Background(), c, encodePNG(t, 21, 10)); !errors.Is(err, ErrTooManyPixels) { + t.Errorf("over limit: %v", err) + } +} + +func TestCheck_CancelledWhileWaitingForDecodeSlot(t *testing.T) { + c := New(1000) + c.decoding <- struct{}{} + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if _, err := check(ctx, c, encodePNG(t, 2, 2)); !errors.Is(err, context.Canceled) { + t.Errorf("err = %v, want context.Canceled", err) + } +} + +func TestInspect_DoesNotNeedDecodeSlot(t *testing.T) { + c := New(1000) + c.decoding <- struct{}{} // декодер занят, но отказ по заголовку не должен его ждать + if _, err := c.Inspect(bytes.NewReader(pngHeaderOnly(100000, 100000))); !errors.Is(err, ErrTooManyPixels) { + t.Errorf("err = %v, want ErrTooManyPixels", err) + } +} diff --git a/app/internal/janitor/janitor.go b/app/internal/janitor/janitor.go new file mode 100644 index 00000000..e3b18474 --- /dev/null +++ b/app/internal/janitor/janitor.go @@ -0,0 +1,133 @@ +// Package janitor находит и удаляет объекты S3 без строки в attachments. Такие объекты появляются, +// если процесс упал между PUT и INSERT или не удалось компенсирующее удаление. +// +// Почему удаление безопасно: +// - Загрузка сначала пишет объект, потом строку, поэтому свежий объект без строки — обычное +// состояние идущей загрузки. Объекты моложе grace period не рассматриваются вовсе. +// - Порядок проверки: листинг, затем запрос в БД. Строка, появившаяся до запроса, защищает объект. +// После запроса строка появиться не может: объект старше grace, а загрузка живёт секунды. +// - Удаление начинается только после полного обхода. Ошибка БД или листинга прерывает проход без +// удалений: «не удалось проверить» никогда не означает «строки нет». +// - Слишком много кандидатов — признак аварии, а не мусора: проход отказывается что-либо удалять. +package janitor + +import ( + "context" + "errors" + "fmt" + "log/slog" + "strings" + "time" + + "github.com/google/uuid" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/objectstore" +) + +const batchSize = 500 + +// ErrTooManyOrphans — кандидатов больше MaxDeletes, ничего не удалено, нужен оператор. +var ErrTooManyOrphans = errors.New("janitor: too many orphans, nothing deleted") + +// Objects — права очистителя в S3: листинг и удаление, чтения содержимого нет. +type Objects interface { + objectstore.Lister + Delete(ctx context.Context, key string) error +} + +// Metadata отвечает, на какие ключи есть строка в БД. +type Metadata interface { + ExistingObjectKeys(ctx context.Context, keys []string) (map[string]struct{}, error) +} + +type Options struct { + Prefix string + Grace time.Duration + MaxDeletes int + DryRun bool + Now func() time.Time + Logger *slog.Logger +} + +// Report — итог прохода. Значения попадают в лог и в доказательства. +type Report struct { + Scanned int `json:"scanned"` + Fresh int `json:"fresh"` + Referenced int `json:"referenced"` + Skipped int `json:"skipped"` + Orphans int `json:"orphans"` + Deleted int `json:"deleted"` + DeleteFailed int `json:"delete_failed"` + DryRun bool `json:"dry_run"` + Elapsed time.Duration `json:"-"` +} + +// Run выполняет один проход. Повторный запуск безопасен: удалённый объект просто исчезает из обхода. +func Run(ctx context.Context, objects Objects, metadata Metadata, opts Options) (Report, error) { + started := opts.Now() + report := Report{DryRun: opts.DryRun} + var orphans, batch []string + + flush := func() error { + if len(batch) == 0 { + return nil + } + existing, err := metadata.ExistingObjectKeys(ctx, batch) + if err != nil { + return fmt.Errorf("janitor: check metadata: %w", err) + } + for _, key := range batch { + if _, ok := existing[key]; ok { + report.Referenced++ + } else { + orphans = append(orphans, key) + } + } + batch = batch[:0] + return nil + } + + err := objects.List(ctx, opts.Prefix, func(object objectstore.ObjectInfo) error { + report.Scanned++ + // Чужие ключи очиститель не создавал и не трогает. + if _, err := uuid.Parse(strings.TrimPrefix(object.Key, opts.Prefix)); err != nil { + report.Skipped++ + return nil + } + // Неизвестное время считается свежим: отсутствие сведений не повод для удаления. + if object.LastModified.IsZero() || opts.Now().Sub(object.LastModified) < opts.Grace { + report.Fresh++ + return nil + } + batch = append(batch, object.Key) + if len(batch) == batchSize { + return flush() + } + return nil + }) + if err == nil { + err = flush() + } + report.Orphans = len(orphans) + report.Elapsed = opts.Now().Sub(started) + if err != nil { + return report, err + } + if len(orphans) > opts.MaxDeletes { + return report, fmt.Errorf("%w: %d orphans, limit %d", ErrTooManyOrphans, len(orphans), opts.MaxDeletes) + } + if opts.DryRun { + return report, nil + } + for _, key := range orphans { + if err := objects.Delete(ctx, key); err != nil { + report.DeleteFailed++ + opts.Logger.Warn("orphan delete failed, will retry on the next pass", slog.String("object_key", key), slog.Any("err", err)) + continue + } + report.Deleted++ + opts.Logger.Info("orphan deleted", slog.String("object_key", key)) + } + report.Elapsed = opts.Now().Sub(started) + return report, nil +} diff --git a/app/internal/janitor/janitor_test.go b/app/internal/janitor/janitor_test.go new file mode 100644 index 00000000..140a36ce --- /dev/null +++ b/app/internal/janitor/janitor_test.go @@ -0,0 +1,186 @@ +package janitor + +import ( + "context" + "errors" + "io" + "log/slog" + "testing" + "time" + + "github.com/google/uuid" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/objectstore" +) + +const prefix = "originals/" + +var now = time.Date(2026, 11, 4, 12, 0, 0, 0, time.UTC) + +type metadata struct { + keys map[string]struct{} + err error +} + +func (m *metadata) ExistingObjectKeys(_ context.Context, keys []string) (map[string]struct{}, error) { + if m.err != nil { + return nil, m.err + } + out := map[string]struct{}{} + for _, key := range keys { + if _, ok := m.keys[key]; ok { + out[key] = struct{}{} + } + } + return out, nil +} + +func options() Options { + return Options{ + Prefix: prefix, Grace: time.Hour, MaxDeletes: 100, + Now: func() time.Time { return now }, + Logger: slog.New(slog.NewTextHandler(io.Discard, nil)), + } +} + +func key() string { return prefix + uuid.NewString() } + +// rig: старый объект без строки, старый со строкой, свежий без строки, чужой старый. +type rig struct { + objects *objectstore.Memory + meta *metadata + orphan, used, fresh, foreign string +} + +func newRig() *rig { + r := &rig{objects: objectstore.NewMemory(), orphan: key(), used: key(), fresh: key(), foreign: prefix + "not-a-uuid"} + old := now.Add(-2 * time.Hour) + r.objects.PutAt(r.orphan, []byte("x"), old) + r.objects.PutAt(r.used, []byte("x"), old) + r.objects.PutAt(r.foreign, []byte("x"), old) + r.objects.PutAt(r.fresh, []byte("x"), now.Add(-time.Minute)) + r.meta = &metadata{keys: map[string]struct{}{r.used: {}}} + return r +} + +func (r *rig) has(key string) bool { + for _, k := range r.objects.Keys() { + if k == key { + return true + } + } + return false +} + +func TestRun_DeletesOnlyExpiredOrphans(t *testing.T) { + r := newRig() + report, err := Run(context.Background(), r.objects, r.meta, options()) + if err != nil { + t.Fatal(err) + } + if r.has(r.orphan) { + t.Error("expired orphan was kept") + } + if !r.has(r.used) || !r.has(r.fresh) || !r.has(r.foreign) { + t.Errorf("deleted too much: %v", r.objects.Keys()) + } + want := Report{Scanned: 4, Fresh: 1, Referenced: 1, Skipped: 1, Orphans: 1, Deleted: 1} + report.Elapsed = 0 + if report != want { + t.Errorf("report = %+v, want %+v", report, want) + } + + // Повторный проход ничего не меняет. + report, err = Run(context.Background(), r.objects, r.meta, options()) + if err != nil || report.Deleted != 0 || report.Orphans != 0 { + t.Errorf("second pass: %+v, %v", report, err) + } +} + +func TestRun_GraceBoundaryIsKept(t *testing.T) { + r := newRig() + almost := key() + r.objects.PutAt(almost, []byte("x"), now.Add(-time.Hour+time.Second)) + if _, err := Run(context.Background(), r.objects, r.meta, options()); err != nil { + t.Fatal(err) + } + if !r.has(almost) { + t.Error("object younger than grace was deleted") + } +} + +func TestRun_UnknownTimeIsTreatedAsFresh(t *testing.T) { + r := newRig() + unknown := key() + r.objects.PutAt(unknown, []byte("x"), time.Time{}) + if _, err := Run(context.Background(), r.objects, r.meta, options()); err != nil { + t.Fatal(err) + } + if !r.has(unknown) { + t.Error("object with unknown time was deleted") + } +} + +func TestRun_DryRunDeletesNothing(t *testing.T) { + r := newRig() + opts := options() + opts.DryRun = true + report, err := Run(context.Background(), r.objects, r.meta, opts) + if err != nil { + t.Fatal(err) + } + if report.Orphans != 1 || report.Deleted != 0 || !r.has(r.orphan) { + t.Errorf("report = %+v, keys = %v", report, r.objects.Keys()) + } +} + +func TestRun_MetadataFailureDeletesNothing(t *testing.T) { + r := newRig() + r.meta.err = errors.New("db down") + if _, err := Run(context.Background(), r.objects, r.meta, options()); err == nil { + t.Fatal("expected an error") + } + if !r.has(r.orphan) || !r.has(r.used) { + t.Error("objects were deleted without a metadata check") + } +} + +func TestRun_ListFailureIsReported(t *testing.T) { + r := newRig() + r.objects.Down.Store(true) + if _, err := Run(context.Background(), r.objects, r.meta, options()); err == nil { + t.Fatal("expected an error") + } +} + +// Пустая БД при полном bucket выглядит как «всё мусор». Это авария, а не повод всё удалить. +func TestRun_TooManyOrphansDeletesNothing(t *testing.T) { + r := newRig() + r.meta.keys = nil + opts := options() + opts.MaxDeletes = 1 + report, err := Run(context.Background(), r.objects, r.meta, opts) + if !errors.Is(err, ErrTooManyOrphans) { + t.Fatalf("err = %v", err) + } + if report.Deleted != 0 || !r.has(r.orphan) || !r.has(r.used) { + t.Errorf("report = %+v, keys = %v", report, r.objects.Keys()) + } +} + +func TestRun_ChecksMetadataInBatches(t *testing.T) { + objects := objectstore.NewMemory() + meta := &metadata{keys: map[string]struct{}{}} + for range batchSize + 7 { + k := key() + objects.PutAt(k, []byte("x"), now.Add(-2*time.Hour)) + meta.keys[k] = struct{}{} + } + report, err := Run(context.Background(), objects, meta, options()) + if err != nil { + t.Fatal(err) + } + if report.Referenced != batchSize+7 || report.Deleted != 0 { + t.Errorf("report = %+v", report) + } +} diff --git a/app/internal/logging/logging.go b/app/internal/logging/logging.go new file mode 100644 index 00000000..551b53b9 --- /dev/null +++ b/app/internal/logging/logging.go @@ -0,0 +1,51 @@ +package logging + +import ( + "fmt" + "io" + "log/slog" + "os" + "strings" +) + +func New(level, env, version string) (*slog.Logger, error) { + lvl, err := parseLevel(level) + if err != nil { + return nil, err + } + return build(os.Stdout, lvl, env, version), nil +} + +func build(w io.Writer, lvl slog.Level, env, version string) *slog.Logger { + handler := slog.NewJSONHandler(w, &slog.HandlerOptions{ + Level: lvl, + ReplaceAttr: forceUTCTime, + }) + return slog.New(handler).With( + slog.String("service", "messenger"), + slog.String("env", env), + slog.String("version", version), + ) +} + +func forceUTCTime(_ []string, a slog.Attr) slog.Attr { + if a.Value.Kind() == slog.KindTime { + a.Value = slog.TimeValue(a.Value.Time().UTC()) + } + return a +} + +func parseLevel(s string) (slog.Level, error) { + switch strings.ToLower(strings.TrimSpace(s)) { + case "", "info": + return slog.LevelInfo, nil + case "debug": + return slog.LevelDebug, nil + case "warn", "warning": + return slog.LevelWarn, nil + case "error": + return slog.LevelError, nil + default: + return 0, fmt.Errorf("logging: unknown level %q (want debug|info|warn|error)", s) + } +} diff --git a/app/internal/objectstore/memory.go b/app/internal/objectstore/memory.go new file mode 100644 index 00000000..5a90821e --- /dev/null +++ b/app/internal/objectstore/memory.go @@ -0,0 +1,117 @@ +package objectstore + +import ( + "bytes" + "context" + "fmt" + "io" + "strings" + "sync" + "sync/atomic" + "time" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" +) + +// Memory — хранилище для модульных тестов. В работающем приложении не используется. +type Memory struct { + mu sync.Mutex + objects map[string][]byte + modified map[string]time.Time + // Down имитирует недоступность S3. + Down atomic.Bool +} + +var ( + _ Store = (*Memory)(nil) + _ Lister = (*Memory)(nil) +) + +func NewMemory() *Memory { + return &Memory{objects: make(map[string][]byte), modified: make(map[string]time.Time)} +} + +func (m *Memory) check() error { + if m.Down.Load() { + return fmt.Errorf("%w: s3 down", domain.ErrUnavailable) + } + return nil +} + +func (m *Memory) Put(_ context.Context, key, _ string, body io.Reader, size int64) error { + if err := m.check(); err != nil { + return err + } + data, err := io.ReadAll(body) + if err != nil { + return fmt.Errorf("%w: s3 put: %v", domain.ErrUnavailable, err) + } + if int64(len(data)) != size { + return fmt.Errorf("%w: s3 put: got %d of %d bytes", domain.ErrUnavailable, len(data), size) + } + m.PutAt(key, data, time.Now()) + return nil +} + +// PutAt кладёт объект с заданным временем: так тест получает объект нужного возраста. +func (m *Memory) PutAt(key string, data []byte, at time.Time) { + m.mu.Lock() + defer m.mu.Unlock() + m.objects[key] = bytes.Clone(data) + m.modified[key] = at +} + +func (m *Memory) List(_ context.Context, prefix string, visit func(ObjectInfo) error) error { + if err := m.check(); err != nil { + return err + } + m.mu.Lock() + infos := make([]ObjectInfo, 0, len(m.objects)) + for key := range m.objects { + if strings.HasPrefix(key, prefix) { + infos = append(infos, ObjectInfo{Key: key, LastModified: m.modified[key]}) + } + } + m.mu.Unlock() + for _, info := range infos { + if err := visit(info); err != nil { + return err + } + } + return nil +} + +func (m *Memory) Get(_ context.Context, key string) (io.ReadCloser, int64, error) { + if err := m.check(); err != nil { + return nil, 0, err + } + m.mu.Lock() + defer m.mu.Unlock() + data, ok := m.objects[key] + if !ok { + return nil, 0, ErrNotFound + } + return io.NopCloser(bytes.NewReader(data)), int64(len(data)), nil +} + +func (m *Memory) Delete(_ context.Context, key string) error { + if err := m.check(); err != nil { + return err + } + m.mu.Lock() + defer m.mu.Unlock() + delete(m.objects, key) + delete(m.modified, key) + return nil +} + +// Keys возвращает ключи объектов для проверок в тестах. +func (m *Memory) Keys() []string { + m.mu.Lock() + defer m.mu.Unlock() + out := make([]string, 0, len(m.objects)) + for k := range m.objects { + out = append(out, k) + } + return out +} diff --git a/app/internal/objectstore/objectstore.go b/app/internal/objectstore/objectstore.go new file mode 100644 index 00000000..1432550a --- /dev/null +++ b/app/internal/objectstore/objectstore.go @@ -0,0 +1,34 @@ +// Package objectstore — хранилище байтов вложений. Интерфейс не зависит от конкретного сервера. +package objectstore + +import ( + "context" + "errors" + "io" + "time" +) + +// ErrNotFound — в bucket нет объекта. Метаданные пишутся после объекта, поэтому для существующего +// вложения это нарушение согласованности, а не обычная ошибка клиента. +var ErrNotFound = errors.New("objectstore: object not found") + +// ObjectInfo — то, что очистителю нужно знать об объекте из листинга. +type ObjectInfo struct { + Key string + LastModified time.Time +} + +type Store interface { + // Put передаёт объект потоком: size байт из body, без чтения всего файла в память. + Put(ctx context.Context, key, contentType string, body io.Reader, size int64) error + // Get возвращает поток и размер объекта. Поток обязательно закрыть. + Get(ctx context.Context, key string) (io.ReadCloser, int64, error) + Delete(ctx context.Context, key string) error +} + +// Lister обходит объекты bucket. Право на листинг есть только у очистителя, поэтому метод вынесен +// из Store: API не может и не должно перечислять объекты. +type Lister interface { + // List вызывает visit для каждого объекта с заданным префиксом. + List(ctx context.Context, prefix string, visit func(ObjectInfo) error) error +} diff --git a/app/internal/objectstore/s3.go b/app/internal/objectstore/s3.go new file mode 100644 index 00000000..e03d75d3 --- /dev/null +++ b/app/internal/objectstore/s3.go @@ -0,0 +1,251 @@ +package objectstore + +import ( + "context" + "crypto/hmac" + "crypto/sha256" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "os" + "strings" + "time" + + "github.com/minio/minio-go/v7" + "github.com/minio/minio-go/v7/pkg/credentials" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/config" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" +) + +// S3 работает с любым S3-совместимым сервером; на стенде это SeaweedFS. +type S3 struct { + signingCreds *credentials.Credentials + region string + ticketKey []byte + client *minio.Client + core minio.Core + endpoint string + bucket string + timeout time.Duration +} + +var ( + _ Store = (*S3)(nil) + _ Lister = (*S3)(nil) +) + +// NewS3 только готовит клиента и не обращается к серверу: недоступность S3 при запуске не мешает +// реплике обслуживать пользователей и сообщения. +func NewS3(cfg config.S3) (*S3, error) { + u, err := url.Parse(cfg.Endpoint) + if err != nil || u.Host == "" || (u.Scheme != "http" && u.Scheme != "https") { + return nil, errors.New("objectstore: S3_ENDPOINT must be http(s)://host:port") + } + id, err := readSecret("S3_ACCESS_KEY_ID_FILE", cfg.AccessKeyIDFile) + if err != nil { + return nil, err + } + secret, err := readSecret("S3_SECRET_ACCESS_KEY_FILE", cfg.SecretAccessKeyFile) + if err != nil { + return nil, err + } + client, err := minio.New(u.Host, &minio.Options{ + Creds: credentials.NewStaticV4(id, secret, ""), + Secure: u.Scheme == "https", + Region: cfg.Region, + BucketLookup: minio.BucketLookupPath, + }) + if err != nil { + return nil, fmt.Errorf("objectstore: client: %w", err) + } + return &S3{ + signingCreds: credentials.NewStaticV4(id, secret, ""), + region: cfg.Region, + ticketKey: []byte(secret), + client: client, + core: minio.Core{Client: client}, + endpoint: cfg.Endpoint, + bucket: cfg.Bucket, + timeout: time.Duration(cfg.TimeoutMs) * time.Millisecond, + }, nil +} + +func readSecret(name, path string) (string, error) { + if path == "" { + return "", fmt.Errorf("objectstore: %s is required", name) + } + b, err := os.ReadFile(path) + if err != nil { + return "", fmt.Errorf("objectstore: read %s: %w", name, err) + } + v := strings.TrimSpace(string(b)) + if v == "" { + return "", fmt.Errorf("objectstore: %s is empty", name) + } + return v, nil +} + +// unavailable скрывает детали S3 от клиента: наружу уходит только 503. +func unavailable(op string, err error) error { + return fmt.Errorf("%w: s3 %s: %v", domain.ErrUnavailable, op, err) +} + +// Put отправляет объект одним запросом и не буферизует его. Multipart выключен намеренно: при обрыве +// одиночного PUT объект не появляется, а незавершённых multipart-загрузок, которые надо отдельно +// искать и отменять, просто не существует. +func (s *S3) Put(ctx context.Context, key, contentType string, body io.Reader, size int64) error { + ctx, cancel := context.WithTimeout(ctx, s.timeout) + defer cancel() + info, err := s.client.PutObject(ctx, s.bucket, key, body, size, + minio.PutObjectOptions{ContentType: contentType, DisableMultipart: true}) + if err != nil { + return unavailable("put", err) + } + if info.Size != size { + return unavailable("put", fmt.Errorf("stored %d of %d bytes", info.Size, size)) + } + return nil +} + +// List постранично обходит bucket; размер страницы задаёт сервер, в памяти одна страница. +func (s *S3) List(ctx context.Context, prefix string, visit func(ObjectInfo) error) error { + // Отмена нужна, чтобы при раннем выходе остановить горутину листинга клиента S3. + ctx, cancel := context.WithCancel(ctx) + defer cancel() + for object := range s.client.ListObjects(ctx, s.bucket, minio.ListObjectsOptions{Prefix: prefix, Recursive: true}) { + if object.Err != nil { + return unavailable("list", object.Err) + } + if err := visit(ObjectInfo{Key: object.Key, LastModified: object.LastModified}); err != nil { + return err + } + } + return ctx.Err() +} + +func (s *S3) Get(ctx context.Context, key string) (io.ReadCloser, int64, error) { + // Таймаут нужен только на получение ответа: чтение потока ограничивает родительский контекст. + ctx, cancel := context.WithCancel(ctx) + timer := time.AfterFunc(s.timeout, cancel) + body, info, _, err := s.core.GetObject(ctx, s.bucket, key, minio.GetObjectOptions{}) + timer.Stop() + if err != nil { + cancel() + if minio.ToErrorResponse(err).Code == "NoSuchKey" { + return nil, 0, ErrNotFound + } + return nil, 0, unavailable("get", err) + } + return &cancelOnClose{ReadCloser: body, cancel: cancel}, info.Size, nil +} + +type cancelOnClose struct { + io.ReadCloser + cancel context.CancelFunc +} + +func (c *cancelOnClose) Close() error { + defer c.cancel() + return c.ReadCloser.Close() +} + +func (s *S3) Delete(ctx context.Context, key string) error { + ctx, cancel := context.WithTimeout(ctx, s.timeout) + defer cancel() + if err := s.client.RemoveObject(ctx, s.bucket, key, minio.RemoveObjectOptions{}); err != nil { + return unavailable("delete", err) + } + return nil +} + +// EnsureBucket создаёт bucket, если его нет. Повторный запуск ничего не меняет и не трогает объекты. +func (s *S3) EnsureBucket(ctx context.Context) error { + ctx, cancel := context.WithTimeout(ctx, s.timeout) + defer cancel() + exists, err := s.client.BucketExists(ctx, s.bucket) + if err != nil { + return fmt.Errorf("objectstore: bucket exists: %w", err) + } + if exists { + return nil + } + err = s.client.MakeBucket(ctx, s.bucket, minio.MakeBucketOptions{}) + if err != nil && minio.ToErrorResponse(err).Code != "BucketAlreadyOwnedByYou" { + return fmt.Errorf("objectstore: make bucket: %w", err) + } + return nil +} + +// RemovePolicy удаляет политику bucket, если она есть, и сообщает, была ли она. Доступ на стенде +// определяют только ключи, поэтому любая политика — чужеродное изменение, а не настройка. +func (s *S3) RemovePolicy(ctx context.Context) (bool, error) { + ctx, cancel := context.WithTimeout(ctx, s.timeout) + defer cancel() + policy, err := s.client.GetBucketPolicy(ctx, s.bucket) + if err != nil && minio.ToErrorResponse(err).Code != "NoSuchBucketPolicy" { + return false, fmt.Errorf("objectstore: get policy: %w", err) + } + if policy == "" { + return false, nil + } + if err := s.client.SetBucketPolicy(ctx, s.bucket, ""); err != nil { + return false, fmt.Errorf("objectstore: remove policy: %w", err) + } + return true, nil +} + +// CheckPrivate делает запрос без подписи и ожидает отказ. Политику bucket никто не задаёт, поэтому +// приватность — поведение по умолчанию, а эта проверка не даёт запустить стенд, если это не так. +func (s *S3) CheckPrivate(ctx context.Context) error { + ctx, cancel := context.WithTimeout(ctx, s.timeout) + defer cancel() + req, err := http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimRight(s.endpoint, "/")+"/"+s.bucket+"/", nil) + if err != nil { + return err + } + resp, err := http.DefaultClient.Do(req) + if err != nil { + return fmt.Errorf("objectstore: anonymous probe: %w", err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusForbidden && resp.StatusCode != http.StatusUnauthorized { + return fmt.Errorf("objectstore: anonymous listing returned %d, bucket is not private", resp.StatusCode) + } + return nil +} + +// UploadMAC uses a separate domain from S3 request signatures. Shared credentials +// allow init and complete to run on different replicas without pending DB rows. +func (s *S3) UploadMAC(data []byte) []byte { + h := hmac.New(sha256.New, s.ticketKey) + h.Write([]byte("lab4-upload-ticket-v1\x00")) + h.Write(data) + return h.Sum(nil) +} + +func (s *S3) PresignUpload(ctx context.Context, key, contentType string, size int64) (string, error) { + endpoint := os.Getenv("S3_PUBLIC_ENDPOINT") + if endpoint == "" { + endpoint = s.endpoint + } + u, err := url.Parse(endpoint) + if err != nil || u.Host == "" || (u.Scheme != "http" && u.Scheme != "https") { + return "", domain.ErrUnavailable + } + // Presign with the public Host from the outset: rewriting a signed URL breaks SigV4. + client, err := minio.New(u.Host, &minio.Options{Creds: s.signingCreds, Secure: u.Scheme == "https", Region: s.region, BucketLookup: minio.BucketLookupPath}) + if err != nil { + return "", unavailable("presign", err) + } + headers := http.Header{} + headers.Set("Content-Type", contentType) + headers.Set("Content-Length", fmt.Sprint(size)) + signed, err := client.PresignHeader(ctx, http.MethodPut, s.bucket, key, 60*time.Second, nil, headers) + if err != nil { + return "", unavailable("presign", err) + } + return signed.String(), nil +} diff --git a/app/internal/password/password.go b/app/internal/password/password.go new file mode 100644 index 00000000..5959fd39 --- /dev/null +++ b/app/internal/password/password.go @@ -0,0 +1,112 @@ +package password + +import ( + "context" + "crypto/rand" + "crypto/subtle" + "encoding/base64" + "errors" + "fmt" + "strings" + + "golang.org/x/crypto/argon2" +) + +type Params struct { + MemoryKiB uint32 + Iterations uint32 + Parallelism uint8 + SaltLen uint32 + KeyLen uint32 +} + +var Default = Params{ + MemoryKiB: 19 * 1024, + Iterations: 2, + Parallelism: 1, + SaltLen: 16, + KeyLen: 32, +} + +var ErrMalformedHash = errors.New("password: malformed hash") + +var b64 = base64.RawStdEncoding + +type Hasher struct { + params Params + slots chan struct{} +} + +func NewHasher(p Params, maxConcurrent int) *Hasher { + if maxConcurrent <= 0 { + maxConcurrent = 1 + } + return &Hasher{params: p, slots: make(chan struct{}, maxConcurrent)} +} + +func (h *Hasher) acquire(ctx context.Context) error { + select { + case h.slots <- struct{}{}: + return nil + case <-ctx.Done(): + return ctx.Err() + } +} + +func (h *Hasher) release() { <-h.slots } + +// Hash возвращает PHC-строку Argon2id со случайной солью. +func (h *Hasher) Hash(ctx context.Context, plain string) (string, error) { + salt := make([]byte, h.params.SaltLen) + if _, err := rand.Read(salt); err != nil { + return "", fmt.Errorf("password: rand: %w", err) + } + if err := h.acquire(ctx); err != nil { + return "", err + } + defer h.release() + + p := h.params + key := argon2.IDKey([]byte(plain), salt, p.Iterations, p.MemoryKiB, p.Parallelism, p.KeyLen) + return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s", + argon2.Version, p.MemoryKiB, p.Iterations, p.Parallelism, + b64.EncodeToString(salt), b64.EncodeToString(key)), nil +} + +func (h *Hasher) Verify(ctx context.Context, plain, encoded string) (bool, error) { + p, salt, want, err := decode(encoded) + if err != nil { + return false, err + } + if err := h.acquire(ctx); err != nil { + return false, err + } + defer h.release() + + got := argon2.IDKey([]byte(plain), salt, p.Iterations, p.MemoryKiB, p.Parallelism, uint32(len(want))) + return subtle.ConstantTimeCompare(got, want) == 1, nil +} + +func decode(encoded string) (Params, []byte, []byte, error) { + parts := strings.Split(encoded, "$") + if len(parts) != 6 || parts[0] != "" || parts[1] != "argon2id" { + return Params{}, nil, nil, ErrMalformedHash + } + var version int + if _, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil || version != argon2.Version { + return Params{}, nil, nil, ErrMalformedHash + } + var p Params + if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &p.MemoryKiB, &p.Iterations, &p.Parallelism); err != nil { + return Params{}, nil, nil, ErrMalformedHash + } + salt, err := b64.DecodeString(parts[4]) + if err != nil || len(salt) == 0 { + return Params{}, nil, nil, ErrMalformedHash + } + key, err := b64.DecodeString(parts[5]) + if err != nil || len(key) == 0 { + return Params{}, nil, nil, ErrMalformedHash + } + return p, salt, key, nil +} diff --git a/app/internal/password/password_test.go b/app/internal/password/password_test.go new file mode 100644 index 00000000..d4dabda0 --- /dev/null +++ b/app/internal/password/password_test.go @@ -0,0 +1,76 @@ +package password + +import ( + "context" + "errors" + "strings" + "testing" +) + +var testParams = Params{MemoryKiB: 64, Iterations: 1, Parallelism: 1, SaltLen: 16, KeyLen: 32} + +func TestHashVerify(t *testing.T) { + h := NewHasher(testParams, 2) + ctx := context.Background() + + pw := "пароль:с-двоеточием-и-юникодом" + encoded, err := h.Hash(ctx, pw) + if err != nil { + t.Fatal(err) + } + if !strings.HasPrefix(encoded, "$argon2id$v=19$m=64,t=1,p=1$") { + t.Errorf("unexpected format %q", encoded) + } + if strings.Contains(encoded, pw) { + t.Error("hash contains plaintext") + } + + ok, err := h.Verify(ctx, pw, encoded) + if err != nil || !ok { + t.Errorf("Verify(correct) = %v, %v", ok, err) + } + ok, err = h.Verify(ctx, pw+"x", encoded) + if err != nil || ok { + t.Errorf("Verify(wrong) = %v, %v", ok, err) + } +} + +func TestHash_RandomSalt(t *testing.T) { + h := NewHasher(testParams, 1) + a, _ := h.Hash(context.Background(), "same-password-123") + b, _ := h.Hash(context.Background(), "same-password-123") + if a == b { + t.Error("two hashes of the same password are equal: salt is not random") + } +} + +func TestVerify_UsesParamsFromHash(t *testing.T) { + old := NewHasher(testParams, 1) + encoded, _ := old.Hash(context.Background(), "long-enough-password") + + stronger := testParams + stronger.Iterations = 3 + ok, err := NewHasher(stronger, 1).Verify(context.Background(), "long-enough-password", encoded) + if err != nil || !ok { + t.Errorf("old hash must verify after params change: %v, %v", ok, err) + } +} + +func TestVerify_Malformed(t *testing.T) { + h := NewHasher(testParams, 1) + for _, s := range []string{"", "!", "$argon2i$v=19$m=64,t=1,p=1$AAAA$AAAA", "$argon2id$v=19$m=64$AAAA$AAAA"} { + if _, err := h.Verify(context.Background(), "x", s); !errors.Is(err, ErrMalformedHash) { + t.Errorf("Verify(%q) err = %v, want ErrMalformedHash", s, err) + } + } +} + +func TestHash_RespectsContextWhenBusy(t *testing.T) { + h := NewHasher(testParams, 1) + h.slots <- struct{}{} // единственный слот занят + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if _, err := h.Hash(ctx, "long-enough-password"); !errors.Is(err, context.Canceled) { + t.Errorf("err = %v, want context.Canceled", err) + } +} diff --git a/app/internal/service/attachments.go b/app/internal/service/attachments.go new file mode 100644 index 00000000..16238d64 --- /dev/null +++ b/app/internal/service/attachments.go @@ -0,0 +1,277 @@ +package service + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "io" + "log/slog" + "mime" + "os" + "time" + + "github.com/google/uuid" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/imagecheck" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/objectstore" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate" +) + +var _ AttachmentsService = (*Attachments)(nil) + +// ObjectKeyPrefix — префикс ключей оригиналов. Очиститель обходит только его. +const ObjectKeyPrefix = "originals/" + +// Предел на компенсирующее удаление объекта, когда запись метаданных не удалась. +const compensationTimeout = 5 * time.Second + +type AttachmentLimits struct { + MaxUploadBytes int64 + MaxImagePixels int64 + MaxConcurrentUploads int +} + +type attachmentRepo interface { + store.ChatStore + store.AttachmentStore +} + +type Attachments struct { + repo attachmentRepo + objects objectstore.Store + limits AttachmentLimits + checker *imagecheck.Checker + // uploads — слоты загрузок. Вместе с лимитом размера они ограничивают диск реплики под временные + // файлы; память на одну загрузку от размера файла не зависит. + uploads chan struct{} + logger *slog.Logger +} + +func NewAttachments(repo attachmentRepo, objects objectstore.Store, limits AttachmentLimits, logger *slog.Logger) *Attachments { + return &Attachments{ + repo: repo, + objects: objects, + limits: limits, + checker: imagecheck.New(limits.MaxImagePixels), + uploads: make(chan struct{}, limits.MaxConcurrentUploads), + logger: logger, + } +} + +// Upload выполняет проверки от дешёвых к дорогим: доступ, параметры, заявленный размер и только +// потом чтение тела. Тело идёт потоком во временный файл, из него в декодер и в S3, поэтому в памяти +// файл целиком не лежит. Порядок записи: сначала объект, затем метаданные, поэтому строка в БД +// никогда не ссылается на несуществующий файл, а 201 означает, что сохранено и то и другое. +func (a *Attachments) Upload(ctx context.Context, in UploadInput) (domain.Attachment, error) { + chatID, err := validate.CanonicalUUID("chat_id", in.ChatID) + if err != nil { + return domain.Attachment{}, err + } + if _, err := a.repo.ChatByID(ctx, in.CallerID, chatID); err != nil { + return domain.Attachment{}, err + } + if err := validate.Filename(in.Filename); err != nil { + return domain.Attachment{}, err + } + declared, err := parseImageType(in.ContentType) + if err != nil { + return domain.Attachment{}, err + } + if in.ContentLength > a.limits.MaxUploadBytes { + return domain.Attachment{}, domain.ErrPayloadTooLarge + } + + select { + case a.uploads <- struct{}{}: + defer func() { <-a.uploads }() + default: + return domain.Attachment{}, domain.ErrRateLimited + } + + spool, size, sum, err := a.spoolBody(in.Body) + if err != nil { + return domain.Attachment{}, err + } + defer spool.Close() + + if err := a.checkImage(ctx, spool, declared); err != nil { + return domain.Attachment{}, err + } + if _, err := spool.Seek(0, io.SeekStart); err != nil { + return domain.Attachment{}, fmt.Errorf("%w: spool: %v", domain.ErrUnavailable, err) + } + + id := uuid.NewString() + att := domain.Attachment{ + ID: id, + ChatID: chatID, + OwnerID: in.CallerID, + Filename: in.Filename, + ContentType: declared, + SizeBytes: size, + SHA256: sum, + ObjectKey: ObjectKeyPrefix + id, + Status: domain.StatusReady, + } + if err := a.objects.Put(ctx, att.ObjectKey, att.ContentType, spool, size); err != nil { + // Объект мог успеть сохраниться. Удалять его здесь бессмысленно: при недоступном S3 удаление + // тоже не пройдёт, а клиент лишние секунды ждал бы ответа. Его уберёт очиститель. + a.logger.Warn("attachment object put failed", slog.Any("err", err)) + return domain.Attachment{}, err + } + saved, err := a.repo.CreateAttachment(ctx, att) + if err != nil { + a.compensate(ctx, att) + return domain.Attachment{}, err + } + return saved, nil +} + +// checkImage сравнивает заявленный тип с настоящим до декодирования: подмена типа не тратит память. +func (a *Attachments) checkImage(ctx context.Context, file io.ReadSeeker, declared string) error { + detected, err := a.checker.Inspect(file) + if err == nil && detected != declared { + return domain.ErrUnsupportedMedia + } + if err == nil { + err = a.checker.Decode(ctx, file) + } + switch { + case err == nil: + return nil + case errors.Is(err, imagecheck.ErrTooManyPixels): + return domain.ErrPayloadTooLarge + case errors.Is(err, imagecheck.ErrUnsupported): + return domain.ErrUnsupportedMedia + case errors.Is(err, imagecheck.ErrBusy): + return domain.ErrRateLimited + } + return fmt.Errorf("%w: image check: %v", domain.ErrUnavailable, err) +} + +// compensate убирает объект, для которого метаданные не сохранились. Контекст отвязан от запроса: +// клиент мог уже отключиться. Удалять можно, только убедившись, что строки нет: ошибка INSERT не +// доказывает отсутствие записи (COMMIT мог пройти, а ответ потеряться), и удаление оставило бы +// подтверждённую строку без файла. Если проверить нельзя, объект остаётся очистителю: он удаляет +// только объекты без строки и только после grace period (cmd/janitor). +func (a *Attachments) compensate(ctx context.Context, att domain.Attachment) { + ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), compensationTimeout) + defer cancel() + exists, err := a.repo.AttachmentExists(ctx, att.ID) + if err != nil { + a.logger.Warn("orphan check failed, object is left to the janitor", slog.String("object_key", att.ObjectKey), slog.Any("err", err)) + return + } + if exists { + a.logger.Warn("metadata write reported an error but the row exists, object is kept", slog.String("attachment_id", att.ID)) + return + } + if err := a.objects.Delete(ctx, att.ObjectKey); err != nil { + a.logger.Warn("compensating delete failed, object is left to the janitor", slog.String("object_key", att.ObjectKey), slog.Any("err", err)) + } +} + +// spoolBody пишет тело во временный файл и считает SHA-256 на лету. Файл удаляется из каталога сразу +// после создания: данные живут, пока он открыт, поэтому при любом завершении, даже kill -9, на диске +// ничего не остаётся и отдельная уборка не нужна. Это не хранилище: 201 вернётся только после S3. +func (a *Attachments) spoolBody(body io.Reader) (*os.File, int64, string, error) { + file, err := os.CreateTemp("", "upload-*") + if err != nil { + return nil, 0, "", fmt.Errorf("%w: spool: %v", domain.ErrUnavailable, err) + } + if err := os.Remove(file.Name()); err != nil { + file.Close() + return nil, 0, "", fmt.Errorf("%w: spool: %v", domain.ErrUnavailable, err) + } + + hash := sha256.New() + source := &errorTrackingReader{r: body} + // LimitReader на байт больше лимита: так отличается файл ровно на границе от файла больше неё. + n, err := io.Copy(io.MultiWriter(file, hash), io.LimitReader(source, a.limits.MaxUploadBytes+1)) + switch { + case source.err != nil: + file.Close() + // Клиент оборвал передачу или не уложился в таймаут. Отвечать чаще всего уже некому. + return nil, 0, "", &validate.Error{Field: "body", Reason: "cannot read body"} + case err != nil: + file.Close() + return nil, 0, "", fmt.Errorf("%w: spool: %v", domain.ErrUnavailable, err) + case n > a.limits.MaxUploadBytes: + file.Close() + return nil, 0, "", domain.ErrPayloadTooLarge + } + return file, n, hex.EncodeToString(hash.Sum(nil)), nil +} + +// errorTrackingReader отделяет ошибку чтения от клиента (400) от ошибки записи на диск (503). +type errorTrackingReader struct { + r io.Reader + err error +} + +func (e *errorTrackingReader) Read(p []byte) (int, error) { + n, err := e.r.Read(p) + if err != nil && !errors.Is(err, io.EOF) { + e.err = err + } + return n, err +} + +func parseImageType(header string) (string, error) { + mediaType, _, err := mime.ParseMediaType(header) + if err != nil { + return "", domain.ErrUnsupportedMedia + } + switch mediaType { + case domain.ContentTypePNG, domain.ContentTypeJPEG: + return mediaType, nil + } + return "", domain.ErrUnsupportedMedia +} + +func (a *Attachments) Get(ctx context.Context, callerID, attachmentID string) (domain.Attachment, error) { + id, err := validate.CanonicalUUID("attachment_id", attachmentID) + if err != nil { + return domain.Attachment{}, err + } + return a.repo.AttachmentForMember(ctx, callerID, id) +} + +func (a *Attachments) Content(ctx context.Context, callerID, attachmentID, variant string) (domain.Attachment, io.ReadCloser, error) { + if err := validateVariantName(variant); err != nil { + return domain.Attachment{}, nil, err + } + att, err := a.Get(ctx, callerID, attachmentID) + if err != nil { + return domain.Attachment{}, nil, err + } + // Вариантов в lab4 нет: допустимое имя кроме original — отсутствующий вариант готового объекта. + if variant != VariantOriginal { + return domain.Attachment{}, nil, domain.ErrNotFound + } + body, size, err := a.objects.Get(ctx, att.ObjectKey) + if err != nil { + if errors.Is(err, objectstore.ErrNotFound) { + return domain.Attachment{}, nil, fmt.Errorf("attachment %s: object missing in bucket", att.ID) + } + a.logger.Warn("attachment object get failed", slog.Any("err", err)) + return domain.Attachment{}, nil, err + } + if size != att.SizeBytes { + body.Close() + return domain.Attachment{}, nil, fmt.Errorf("attachment %s: object size %d differs from metadata %d", att.ID, size, att.SizeBytes) + } + return att, body, nil +} + +func validateVariantName(variant string) error { + switch variant { + case VariantOriginal, "thumbnail", "crop", "optimized": + return nil + } + return &validate.Error{Field: "variant", Reason: "unknown variant"} +} diff --git a/app/internal/service/auth.go b/app/internal/service/auth.go new file mode 100644 index 00000000..770735e6 --- /dev/null +++ b/app/internal/service/auth.go @@ -0,0 +1,101 @@ +package service + +import ( + "context" + "errors" + "fmt" + "time" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/password" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/session" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/token" +) + +var ( + _ AuthService = (*Auth)(nil) +) + +type Auth struct { + users store.UserStore + sessions session.Store + hasher *password.Hasher + ttl time.Duration + now func() time.Time + + dummyHash string +} + +func NewAuth(users store.UserStore, sessions session.Store, hasher *password.Hasher, ttl time.Duration) (*Auth, error) { + dummy, err := hasher.Hash(context.Background(), "dummy-password-for-timing") + if err != nil { + return nil, fmt.Errorf("auth: dummy hash: %w", err) + } + return &Auth{ + users: users, + sessions: sessions, + hasher: hasher, + ttl: ttl, + now: time.Now, + dummyHash: dummy, + }, nil +} + +func (a *Auth) Login(ctx context.Context, username, plainPassword string) (domain.Session, error) { + user, hash, err := a.users.CredentialsByUsername(ctx, username) + switch { + case errors.Is(err, domain.ErrNotFound): + _, _ = a.hasher.Verify(ctx, plainPassword, a.dummyHash) + return domain.Session{}, domain.ErrUnauthorized + case err != nil: + return domain.Session{}, err + } + + ok, err := a.hasher.Verify(ctx, plainPassword, hash) + if err != nil { + if errors.Is(err, password.ErrMalformedHash) { + return domain.Session{}, domain.ErrUnauthorized + } + return domain.Session{}, err + } + if !ok { + return domain.Session{}, domain.ErrUnauthorized + } + + plain, tokenHash, err := token.New() + if err != nil { + return domain.Session{}, err + } + expiresAt := a.now().Add(a.ttl).UTC().Truncate(time.Second) + if err := a.sessions.Save(ctx, tokenHash, session.Session{UserID: user.ID, ExpiresAt: expiresAt}); err != nil { + return domain.Session{}, err + } + return domain.Session{Token: plain, ExpiresAt: expiresAt, User: user}, nil +} + +func (a *Auth) Authenticate(ctx context.Context, plainToken string) (string, error) { + tokenHash, err := token.Parse(plainToken) + if err != nil { + return "", domain.ErrUnauthorized + } + s, err := a.sessions.Get(ctx, tokenHash) + if errors.Is(err, session.ErrNotFound) { + return "", domain.ErrUnauthorized + } + if err != nil { + return "", err + } + if !a.now().Before(s.ExpiresAt) { + return "", domain.ErrUnauthorized + } + return s.UserID, nil +} + +func (a *Auth) Logout(ctx context.Context, plainToken string) error { + tokenHash, err := token.Parse(plainToken) + if err != nil { + return domain.ErrUnauthorized + } + return a.sessions.Delete(ctx, tokenHash) +} diff --git a/app/internal/service/chats.go b/app/internal/service/chats.go new file mode 100644 index 00000000..b3db00cd --- /dev/null +++ b/app/internal/service/chats.go @@ -0,0 +1,47 @@ +package service + +import ( + "context" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate" +) + +var ( + _ ChatsService = (*Chats)(nil) +) + +type Chats struct { + store store.ChatStore +} + +func NewChats(s store.ChatStore) *Chats { + return &Chats{store: s} +} + +func (c *Chats) Create(ctx context.Context, callerID, title string, memberIDs []string) (domain.Chat, error) { + if err := validate.ChatTitle(title); err != nil { + return domain.Chat{}, err + } + memberIDs, err := validate.MemberIDs(memberIDs, callerID) + if err != nil { + return domain.Chat{}, err + } + return c.store.CreateChat(ctx, callerID, title, memberIDs) +} + +func (c *Chats) Get(ctx context.Context, callerID, chatID string) (domain.Chat, error) { + chatID, err := validate.CanonicalUUID("chat_id", chatID) + if err != nil { + return domain.Chat{}, err + } + return c.store.ChatByID(ctx, callerID, chatID) +} + +func (c *Chats) List(ctx context.Context, callerID, cursor string, limit int) (domain.Page[domain.Chat], error) { + if err := validate.Limit(limit); err != nil { + return domain.Page[domain.Chat]{}, err + } + return c.store.ListChats(ctx, callerID, cursor, limit) +} diff --git a/app/internal/service/direct_upload.go b/app/internal/service/direct_upload.go new file mode 100644 index 00000000..028c5abe --- /dev/null +++ b/app/internal/service/direct_upload.go @@ -0,0 +1,177 @@ +package service + +import ( + "context" + "crypto/hmac" + "encoding/base64" + "encoding/hex" + "encoding/json" + "errors" + "io" + "strings" + "time" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/objectstore" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate" + "github.com/google/uuid" +) + +// A ticket is authenticated, not encrypted. No user-supplied object key is accepted. +// Staging keys share the janitor's UUID namespace; they never have metadata. +type directSigner interface { + UploadMAC([]byte) []byte + PresignUpload(context.Context, string, string, int64) (string, error) +} + +type DirectInput struct { + Filename string `json:"filename"` + ContentType string `json:"content_type"` + SizeBytes int64 `json:"size_bytes"` + SHA256 string `json:"sha256"` +} + +type directTicket struct { + Input DirectInput + ID string + Staging string + Owner string + Chat string + Expires int64 +} + +type DirectUpload struct { + URL string `json:"url"` + Token string `json:"token"` + ExpiresIn int `json:"expires_in"` + Headers map[string]string `json:"headers"` +} + +func (a *Attachments) InitDirect(ctx context.Context, caller, chat string, in DirectInput) (DirectUpload, error) { + chat, err := validate.CanonicalUUID("chat_id", chat) + if err != nil { + return DirectUpload{}, err + } + if _, err = a.repo.ChatByID(ctx, caller, chat); err != nil { + return DirectUpload{}, err + } + if err = validate.Filename(in.Filename); err != nil { + return DirectUpload{}, err + } + if in.ContentType != domain.ContentTypePNG && in.ContentType != domain.ContentTypeJPEG { + return DirectUpload{}, domain.ErrUnsupportedMedia + } + in.ContentType, err = parseImageType(in.ContentType) + if err != nil { + return DirectUpload{}, err + } + if in.SizeBytes > a.limits.MaxUploadBytes { + return DirectUpload{}, domain.ErrPayloadTooLarge + } + sum, err := hex.DecodeString(in.SHA256) + if in.SizeBytes <= 0 || err != nil || len(sum) != 32 { + return DirectUpload{}, domain.ErrInvalidArgument + } + in.SHA256 = strings.ToLower(in.SHA256) + signer, ok := a.objects.(directSigner) + if !ok { + return DirectUpload{}, domain.ErrUnavailable + } + ticket := directTicket{Input: in, ID: uuid.NewString(), Staging: ObjectKeyPrefix + uuid.NewString(), Owner: caller, Chat: chat, Expires: time.Now().Add(2 * time.Minute).Unix()} + data, err := json.Marshal(ticket) + if err != nil { + return DirectUpload{}, err + } + url, err := signer.PresignUpload(ctx, ticket.Staging, in.ContentType, in.SizeBytes) + if err != nil { + return DirectUpload{}, err + } + token := base64.RawURLEncoding.EncodeToString(data) + "." + base64.RawURLEncoding.EncodeToString(signer.UploadMAC(data)) + return DirectUpload{URL: url, Token: token, ExpiresIn: 60, Headers: map[string]string{"Content-Type": in.ContentType}}, nil +} + +func (a *Attachments) CompleteDirect(ctx context.Context, caller, chat, token string) (domain.Attachment, error) { + signer, ok := a.objects.(directSigner) + if !ok { + return domain.Attachment{}, domain.ErrUnavailable + } + parts := strings.Split(token, ".") + if len(parts) != 2 || len(token) > 4096 { + return domain.Attachment{}, domain.ErrInvalidArgument + } + data, err := base64.RawURLEncoding.DecodeString(parts[0]) + if err != nil { + return domain.Attachment{}, domain.ErrInvalidArgument + } + mac, err := base64.RawURLEncoding.DecodeString(parts[1]) + if err != nil || !hmac.Equal(mac, signer.UploadMAC(data)) { + return domain.Attachment{}, domain.ErrInvalidArgument + } + var t directTicket + if json.Unmarshal(data, &t) != nil { + return domain.Attachment{}, domain.ErrInvalidArgument + } + if t.Owner != caller || t.Chat != chat { + return domain.Attachment{}, domain.ErrNotFound + } + if _, err := a.repo.ChatByID(ctx, caller, chat); err != nil { + return domain.Attachment{}, err + } + // Retry is idempotent, including a retry after an uncertain database COMMIT. + if att, err := a.repo.AttachmentForMember(ctx, caller, t.ID); err == nil { + return att, nil + } else if !errors.Is(err, domain.ErrNotFound) { + return domain.Attachment{}, err + } + if time.Now().Unix() >= t.Expires { + return domain.Attachment{}, domain.ErrConflict + } + select { + case a.uploads <- struct{}{}: + defer func() { <-a.uploads }() + default: + return domain.Attachment{}, domain.ErrRateLimited + } + body, size, err := a.objects.Get(ctx, t.Staging) + if errors.Is(err, objectstore.ErrNotFound) { + return domain.Attachment{}, domain.ErrConflict + } + if err != nil { + return domain.Attachment{}, err + } + defer body.Close() + if size != t.Input.SizeBytes { + return domain.Attachment{}, domain.ErrInvalidArgument + } + file, actual, sum, err := a.spoolBody(body) + if err != nil { + return domain.Attachment{}, err + } + defer file.Close() + if actual != size || sum != t.Input.SHA256 { + return domain.Attachment{}, domain.ErrInvalidArgument + } + if err = a.checkImage(ctx, file, t.Input.ContentType); err != nil { + return domain.Attachment{}, err + } + if _, err = file.Seek(0, io.SeekStart); err != nil { + return domain.Attachment{}, domain.ErrUnavailable + } + // A unique permanent key per attempt prevents a concurrent failed attempt from + // deleting an object saved by another complete. Clients can write only staging. + att := domain.Attachment{ID: t.ID, ChatID: chat, OwnerID: caller, Filename: t.Input.Filename, ContentType: t.Input.ContentType, SizeBytes: size, SHA256: sum, ObjectKey: ObjectKeyPrefix + uuid.NewString(), Status: domain.StatusReady} + if err = a.objects.Put(ctx, att.ObjectKey, att.ContentType, file, size); err != nil { + return domain.Attachment{}, err + } + saved, err := a.repo.CreateAttachment(ctx, att) + if err != nil { + // Leave unreferenced keys to the janitor: an uncertain COMMIT must not delete data. + if existing, lookup := a.repo.AttachmentForMember(ctx, caller, t.ID); lookup == nil { + return existing, nil + } + return domain.Attachment{}, err + } + // Keep staging until expiry/grace: deleting while its PUT URL is valid allows + // recreation anyway. The janitor reclaims abandoned and completed staging alike. + return saved, nil +} diff --git a/app/internal/service/direct_upload_test.go b/app/internal/service/direct_upload_test.go new file mode 100644 index 00000000..134e40bb --- /dev/null +++ b/app/internal/service/direct_upload_test.go @@ -0,0 +1,87 @@ +package service + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "encoding/json" + "errors" + "io" + "log/slog" + "testing" + "time" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/janitor" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/objectstore" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store" +) + +type signedMemory struct{ *objectstore.Memory } + +func (s signedMemory) UploadMAC(b []byte) []byte { + h := sha256.Sum256(append([]byte("test-key"), b...)) + return h[:] +} +func (s signedMemory) PresignUpload(_ context.Context, key, _ string, _ int64) (string, error) { + return key, nil +} + +func TestDirectSizeExpiryAndCleanup(t *testing.T) { + ctx := context.Background() + repo := store.New() + alice, err := repo.CreateUser(ctx, "alice", "Alice", "hash") + if err != nil { + t.Fatal(err) + } + chat, err := repo.CreateChat(ctx, alice.ID, "chat", []string{alice.ID}) + if err != nil { + t.Fatal(err) + } + objects := signedMemory{objectstore.NewMemory()} + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) + svc := NewAttachments(repo, objects, AttachmentLimits{MaxUploadBytes: 1024, MaxImagePixels: 100, MaxConcurrentUploads: 2}, logger) + data := []byte("1234") + sum := sha256.Sum256(data) + u, err := svc.InitDirect(ctx, alice.ID, chat.ID, DirectInput{Filename: "x.png", ContentType: "image/png", SizeBytes: 4, SHA256: hex.EncodeToString(sum[:])}) + if err != nil { + t.Fatal(err) + } + objects.PutAt(u.URL, data[:3], time.Now()) + if _, err = svc.CompleteDirect(ctx, alice.ID, chat.ID, u.Token); !errors.Is(err, domain.ErrInvalidArgument) { + t.Fatalf("wrong size: %v", err) + } + // Expire a correctly authenticated ticket without sleeping in a unit test. + encoded := bytes.Split([]byte(u.Token), []byte("."))[0] + raw, _ := base64.RawURLEncoding.DecodeString(string(encoded)) + var ticket directTicket + if err = json.Unmarshal(raw, &ticket); err != nil { + t.Fatal(err) + } + ticket.Expires = time.Now().Add(-time.Second).Unix() + raw, _ = json.Marshal(ticket) + token := base64.RawURLEncoding.EncodeToString(raw) + "." + base64.RawURLEncoding.EncodeToString(objects.UploadMAC(raw)) + if _, err = svc.CompleteDirect(ctx, alice.ID, chat.ID, token); !errors.Is(err, domain.ErrConflict) { + t.Fatalf("expired: %v", err) + } + future := time.Now().Add(6 * time.Minute) + report, err := janitor.Run(ctx, objects, noMetadata{}, janitor.Options{Prefix: ObjectKeyPrefix, Grace: 5 * time.Minute, MaxDeletes: 100, Now: func() time.Time { return future }, Logger: logger}) + if err != nil || report.Deleted != 1 { + t.Fatalf("cleanup: %+v %v", report, err) + } + if _, _, err = objects.Get(ctx, u.URL); !errors.Is(err, objectstore.ErrNotFound) { + t.Fatalf("abandoned staging remains: %v", err) + } + report, err = janitor.Run(ctx, objects, noMetadata{}, janitor.Options{Prefix: ObjectKeyPrefix, Grace: 5 * time.Minute, MaxDeletes: 100, Now: func() time.Time { return future }, Logger: logger}) + if err != nil || report.Deleted != 0 { + t.Fatalf("repeat cleanup: %+v %v", report, err) + } +} + +type noMetadata struct{} + +func (noMetadata) ExistingObjectKeys(context.Context, []string) (map[string]struct{}, error) { + return map[string]struct{}{}, nil +} diff --git a/app/internal/service/messages.go b/app/internal/service/messages.go new file mode 100644 index 00000000..3d4c5bd2 --- /dev/null +++ b/app/internal/service/messages.go @@ -0,0 +1,50 @@ +package service + +import ( + "context" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate" +) + +var ( + _ MessagesService = (*Messages)(nil) +) + +type Messages struct { + store store.MessageStore +} + +func NewMessages(s store.MessageStore) *Messages { + return &Messages{store: s} +} + +func (m *Messages) Send(ctx context.Context, callerID, chatID, idempotencyKey, text string, attachmentIDs []string) (domain.Message, error) { + chatID, err := validate.CanonicalUUID("chat_id", chatID) + if err != nil { + return domain.Message{}, err + } + if err := validate.IdempotencyKey(idempotencyKey); err != nil { + return domain.Message{}, err + } + ids, err := validate.AttachmentIDs(attachmentIDs) + if err != nil { + return domain.Message{}, err + } + if err := validate.MessageText(text, len(ids) > 0); err != nil { + return domain.Message{}, err + } + return m.store.AddMessage(ctx, callerID, chatID, idempotencyKey, text, ids) +} + +func (m *Messages) List(ctx context.Context, callerID, chatID, cursor string, limit int) (domain.Page[domain.Message], error) { + chatID, err := validate.CanonicalUUID("chat_id", chatID) + if err != nil { + return domain.Page[domain.Message]{}, err + } + if err := validate.Limit(limit); err != nil { + return domain.Page[domain.Message]{}, err + } + return m.store.ListMessages(ctx, callerID, chatID, cursor, limit) +} diff --git a/app/internal/service/service.go b/app/internal/service/service.go new file mode 100644 index 00000000..cc65adaa --- /dev/null +++ b/app/internal/service/service.go @@ -0,0 +1,50 @@ +package service + +import ( + "context" + "io" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" +) + +type UsersService interface { + Register(ctx context.Context, username, displayName, password string) (domain.User, error) + Me(ctx context.Context, callerID string) (domain.User, error) +} + +type ChatsService interface { + Create(ctx context.Context, callerID, title string, memberIDs []string) (domain.Chat, error) + Get(ctx context.Context, callerID, chatID string) (domain.Chat, error) + List(ctx context.Context, callerID, cursor string, limit int) (domain.Page[domain.Chat], error) +} + +type MessagesService interface { + Send(ctx context.Context, callerID, chatID, idempotencyKey, text string, attachmentIDs []string) (domain.Message, error) + List(ctx context.Context, callerID, chatID, cursor string, limit int) (domain.Page[domain.Message], error) +} + +// VariantOriginal — вариант содержимого по умолчанию. +const VariantOriginal = "original" + +// UploadInput — параметры загрузки файла. Body читается не дальше лимита размера. +type UploadInput struct { + CallerID string + ChatID string + Filename string + ContentType string + ContentLength int64 + Body io.Reader +} + +type AttachmentsService interface { + Upload(ctx context.Context, in UploadInput) (domain.Attachment, error) + Get(ctx context.Context, callerID, attachmentID string) (domain.Attachment, error) + // Content возвращает метаданные и поток байтов. Поток обязательно закрыть. + Content(ctx context.Context, callerID, attachmentID, variant string) (domain.Attachment, io.ReadCloser, error) +} + +type AuthService interface { + Login(ctx context.Context, username, password string) (domain.Session, error) + Authenticate(ctx context.Context, token string) (userID string, err error) + Logout(ctx context.Context, token string) error +} diff --git a/app/internal/service/users.go b/app/internal/service/users.go new file mode 100644 index 00000000..297938c3 --- /dev/null +++ b/app/internal/service/users.go @@ -0,0 +1,44 @@ +package service + +import ( + "context" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/password" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate" +) + +var ( + _ UsersService = (*Users)(nil) +) + +type Users struct { + store store.UserStore + hasher *password.Hasher +} + +func NewUsers(s store.UserStore, h *password.Hasher) *Users { + return &Users{store: s, hasher: h} +} + +func (u *Users) Register(ctx context.Context, username, displayName, plainPassword string) (domain.User, error) { + if err := validate.Username(username); err != nil { + return domain.User{}, err + } + if err := validate.DisplayName(displayName); err != nil { + return domain.User{}, err + } + if err := validate.Password(plainPassword); err != nil { + return domain.User{}, err + } + hash, err := u.hasher.Hash(ctx, plainPassword) + if err != nil { + return domain.User{}, err + } + return u.store.CreateUser(ctx, username, displayName, hash) +} + +func (u *Users) Me(ctx context.Context, callerID string) (domain.User, error) { + return u.store.UserByID(ctx, callerID) +} diff --git a/app/internal/session/memory.go b/app/internal/session/memory.go new file mode 100644 index 00000000..b6896dfc --- /dev/null +++ b/app/internal/session/memory.go @@ -0,0 +1,49 @@ +package session + +import ( + "context" + "sync" + "time" +) + +var _ Store = (*Memory)(nil) + +type Memory struct { + mu sync.Mutex + sessions map[string]Session + now func() time.Time +} + +func NewMemory() *Memory { + return &Memory{sessions: make(map[string]Session), now: time.Now} +} + +func (m *Memory) Save(_ context.Context, tokenHash []byte, s Session) error { + m.mu.Lock() + defer m.mu.Unlock() + m.sessions[string(tokenHash)] = s + return nil +} + +func (m *Memory) Get(_ context.Context, tokenHash []byte) (Session, error) { + m.mu.Lock() + defer m.mu.Unlock() + s, ok := m.sessions[string(tokenHash)] + if !ok { + return Session{}, ErrNotFound + } + if !m.now().Before(s.ExpiresAt) { + delete(m.sessions, string(tokenHash)) + return Session{}, ErrNotFound + } + return s, nil +} + +func (m *Memory) Delete(_ context.Context, tokenHash []byte) error { + m.mu.Lock() + defer m.mu.Unlock() + delete(m.sessions, string(tokenHash)) + return nil +} + +func (m *Memory) Ping(context.Context) error { return nil } diff --git a/app/internal/session/session.go b/app/internal/session/session.go new file mode 100644 index 00000000..7e3047ce --- /dev/null +++ b/app/internal/session/session.go @@ -0,0 +1,21 @@ +package session + +import ( + "context" + "errors" + "time" +) + +type Session struct { + UserID string `json:"user_id"` + ExpiresAt time.Time `json:"expires_at"` +} + +var ErrNotFound = errors.New("session: not found") + +type Store interface { + Save(ctx context.Context, tokenHash []byte, s Session) error + Get(ctx context.Context, tokenHash []byte) (Session, error) + Delete(ctx context.Context, tokenHash []byte) error + Ping(ctx context.Context) error +} diff --git a/app/internal/session/valkey.go b/app/internal/session/valkey.go new file mode 100644 index 00000000..9deddbd0 --- /dev/null +++ b/app/internal/session/valkey.go @@ -0,0 +1,120 @@ +package session + +import ( + "context" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "os" + "strings" + "time" + + "github.com/redis/go-redis/v9" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/config" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" +) + +var _ Store = (*Valkey)(nil) + +const keyPrefix = "session:" + +type Valkey struct { + client *redis.Client +} + +func NewValkey(client *redis.Client) *Valkey { + return &Valkey{client: client} +} + +func Connect(ctx context.Context, cfg config.Cache) (*redis.Client, error) { + url, err := urlFrom(cfg) + if err != nil { + return nil, err + } + opts, err := redis.ParseURL(url) + if err != nil { + return nil, errors.New("session: invalid CACHE_URL") + } + timeout := time.Duration(cfg.TimeoutMs) * time.Millisecond + opts.PoolSize = cfg.PoolSize + opts.DialTimeout = timeout + opts.ReadTimeout = timeout + opts.WriteTimeout = timeout + opts.PoolTimeout = timeout + opts.MaxRetries = 1 + + client := redis.NewClient(opts) + pingCtx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + if err := client.Ping(pingCtx).Err(); err != nil { + _ = client.Close() + return nil, fmt.Errorf("session: ping: %w", err) + } + return client, nil +} + +func urlFrom(cfg config.Cache) (string, error) { + if cfg.URLFile != "" { + b, err := os.ReadFile(cfg.URLFile) + if err != nil { + return "", fmt.Errorf("session: read CACHE_URL_FILE: %w", err) + } + return strings.TrimSpace(string(b)), nil + } + if cfg.URL != "" { + return cfg.URL, nil + } + return "", errors.New("session: CACHE_URL_FILE or CACHE_URL is required") +} + +func key(tokenHash []byte) string { + return keyPrefix + hex.EncodeToString(tokenHash) +} + +func (v *Valkey) Save(ctx context.Context, tokenHash []byte, s Session) error { + val, err := json.Marshal(s) + if err != nil { + return err + } + // NX: 256-битный токен не совпадёт, но перезаписать чужую сессию нельзя даже теоретически. + err = v.client.SetArgs(ctx, key(tokenHash), val, redis.SetArgs{ + Mode: "NX", + ExpireAt: s.ExpiresAt, + }).Err() + if errors.Is(err, redis.Nil) { + return fmt.Errorf("session: token collision") + } + return unavailable(err) +} + +func (v *Valkey) Get(ctx context.Context, tokenHash []byte) (Session, error) { + val, err := v.client.Get(ctx, key(tokenHash)).Bytes() + if errors.Is(err, redis.Nil) { + return Session{}, ErrNotFound + } + if err != nil { + return Session{}, unavailable(err) + } + var s Session + if err := json.Unmarshal(val, &s); err != nil { + return Session{}, fmt.Errorf("session: corrupt value: %w", err) + } + return s, nil +} + +func (v *Valkey) Delete(ctx context.Context, tokenHash []byte) error { + return unavailable(v.client.Del(ctx, key(tokenHash)).Err()) +} + +func (v *Valkey) Ping(ctx context.Context) error { + return unavailable(v.client.Ping(ctx).Err()) +} + +func unavailable(err error) error { + if err == nil { + return nil + } + return fmt.Errorf("%w: session store: %v", domain.ErrUnavailable, err) +} diff --git a/app/internal/store/db/attachments.go b/app/internal/store/db/attachments.go new file mode 100644 index 00000000..c65a6a85 --- /dev/null +++ b/app/internal/store/db/attachments.go @@ -0,0 +1,94 @@ +package db + +import ( + "context" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" +) + +type Attachments struct { + conn +} + +// CreateAttachment сохраняет метаданные. FK на chat_members не даёт записать вложение постороннего. +func (a *Attachments) CreateAttachment(ctx context.Context, att domain.Attachment) (domain.Attachment, error) { + ctx, cancel := a.withTimeout(ctx) + defer cancel() + + err := a.pool.QueryRow(ctx, ` + INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256, object_key, status) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) + RETURNING created_at, updated_at`, + att.ID, att.ChatID, att.OwnerID, att.Filename, att.ContentType, att.SizeBytes, att.SHA256, att.ObjectKey, att.Status, + ).Scan(&att.CreatedAt, &att.UpdatedAt) + if isFKViolation(err) { + return domain.Attachment{}, domain.ErrNotFound + } + if err != nil { + return domain.Attachment{}, mapErr(err) + } + att.CreatedAt = att.CreatedAt.UTC() + att.UpdatedAt = att.UpdatedAt.UTC() + return att, nil +} + +// AttachmentForMember возвращает вложение, только если вызывающий состоит в его чате: для +// постороннего результат неотличим от отсутствующего объекта. +func (a *Attachments) AttachmentForMember(ctx context.Context, callerID, attachmentID string) (domain.Attachment, error) { + ctx, cancel := a.withTimeout(ctx) + defer cancel() + + var att domain.Attachment + err := a.pool.QueryRow(ctx, ` + SELECT a.id::text, a.chat_id::text, a.owner_id::text, a.filename, a.content_type, a.size_bytes, + a.sha256, a.object_key, a.status, a.created_at, a.updated_at + FROM attachments a + JOIN chat_members cm ON cm.chat_id = a.chat_id AND cm.user_id = $2 + WHERE a.id = $1`, + attachmentID, callerID, + ).Scan(&att.ID, &att.ChatID, &att.OwnerID, &att.Filename, &att.ContentType, &att.SizeBytes, + &att.SHA256, &att.ObjectKey, &att.Status, &att.CreatedAt, &att.UpdatedAt) + if err != nil { + return domain.Attachment{}, mapErr(err) + } + att.CreatedAt = att.CreatedAt.UTC() + att.UpdatedAt = att.UpdatedAt.UTC() + return att, nil +} + +// AttachmentExists отвечает без учёта доступа: вызывается только сервером при компенсации. +func (a *Attachments) AttachmentExists(ctx context.Context, attachmentID string) (bool, error) { + ctx, cancel := a.withTimeout(ctx) + defer cancel() + + var exists bool + err := a.pool.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM attachments WHERE id = $1)`, attachmentID).Scan(&exists) + if err != nil { + return false, mapErr(err) + } + return exists, nil +} + +// ExistingObjectKeys возвращает те ключи из списка, на которые есть строка. Нужен очистителю. +func (a *Attachments) ExistingObjectKeys(ctx context.Context, keys []string) (map[string]struct{}, error) { + ctx, cancel := a.withTimeout(ctx) + defer cancel() + + rows, err := a.pool.Query(ctx, `SELECT object_key FROM attachments WHERE object_key = ANY($1)`, keys) + if err != nil { + return nil, mapErr(err) + } + defer rows.Close() + existing := make(map[string]struct{}, len(keys)) + for rows.Next() { + var key string + if err := rows.Scan(&key); err != nil { + return nil, mapErr(err) + } + existing[key] = struct{}{} + } + if err := rows.Err(); err != nil { + return nil, mapErr(err) + } + return existing, nil +} diff --git a/app/internal/store/db/chats.go b/app/internal/store/db/chats.go new file mode 100644 index 00000000..104ef5f4 --- /dev/null +++ b/app/internal/store/db/chats.go @@ -0,0 +1,165 @@ +package db + +import ( + "context" + "strings" + "time" + + "github.com/jackc/pgx/v5" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" +) + +type Chats struct { + conn +} + +func (c *Chats) CreateChat(ctx context.Context, callerID, title string, memberIDs []string) (domain.Chat, error) { + if strings.TrimSpace(title) == "" { + return domain.Chat{}, domain.ErrInvalidArgument + } + if len(memberIDs) == 0 || len(memberIDs) > 100 { + return domain.Chat{}, domain.ErrInvalidArgument + } + seen := make(map[string]struct{}, len(memberIDs)) + callerInMembers := false + for _, id := range memberIDs { + if _, dup := seen[id]; dup { + return domain.Chat{}, domain.ErrInvalidArgument + } + seen[id] = struct{}{} + if id == callerID { + callerInMembers = true + } + } + if !callerInMembers { + return domain.Chat{}, domain.ErrInvalidArgument + } + + ctx, cancel := c.withTimeout(ctx) + defer cancel() + + tx, err := c.pool.Begin(ctx) + if err != nil { + return domain.Chat{}, mapErr(err) + } + defer tx.Rollback(ctx) + + chat := domain.Chat{Title: title} + err = tx.QueryRow(ctx, ` + INSERT INTO chats (title) + VALUES ($1) + RETURNING id::text, created_at`, + encodeText(title), + ).Scan(&chat.ID, &chat.CreatedAt) + if err != nil { + return domain.Chat{}, mapErr(err) + } + + _, err = tx.Exec(ctx, ` + INSERT INTO chat_members (chat_id, user_id) + SELECT $1, unnest($2::uuid[])`, + chat.ID, memberIDs, + ) + if err != nil { + return domain.Chat{}, mapErr(err) + } + + if err := tx.Commit(ctx); err != nil { + return domain.Chat{}, mapErr(err) + } + + chat.MemberIDs = append([]string(nil), memberIDs...) + chat.CreatedAt = chat.CreatedAt.UTC() + return chat, nil +} + +func (c *Chats) ChatByID(ctx context.Context, callerID, chatID string) (domain.Chat, error) { + ctx, cancel := c.withTimeout(ctx) + defer cancel() + + chat := domain.Chat{} + err := c.pool.QueryRow(ctx, ` + SELECT c.id::text, c.title, c.created_at, + (SELECT array_agg(m.user_id::text ORDER BY m.user_id) + FROM chat_members m WHERE m.chat_id = c.id) + FROM chats c + JOIN chat_members me ON me.chat_id = c.id AND me.user_id = $2 + WHERE c.id = $1`, + chatID, callerID, + ).Scan(&chat.ID, &chat.Title, &chat.CreatedAt, &chat.MemberIDs) + if err != nil { + err = mapErr(err) + if err == domain.ErrInvalidArgument { + return domain.Chat{}, domain.ErrNotFound + } + return domain.Chat{}, err + } + chat.Title = decodeText(chat.Title) + chat.CreatedAt = chat.CreatedAt.UTC() + return chat, nil +} + +func (c *Chats) ListChats(ctx context.Context, callerID, cursor string, limit int) (domain.Page[domain.Chat], error) { + if limit <= 0 || limit > 100 { + return domain.Page[domain.Chat]{}, domain.ErrInvalidArgument + } + cur, err := domain.DecodeCursor(cursor) + if err != nil { + return domain.Page[domain.Chat]{}, err + } + scope := "chats:" + callerID + if cursor != "" && cur.Scope != scope { + return domain.Page[domain.Chat]{}, domain.ErrInvalidArgument + } + afterTime, afterID := cursorArgs(cur) + + ctx, cancel := c.withTimeout(ctx) + defer cancel() + + rows, err := c.pool.Query(ctx, ` + SELECT c.id::text, c.title, c.created_at, + (SELECT array_agg(m.user_id::text ORDER BY m.user_id) + FROM chat_members m WHERE m.chat_id = c.id) + FROM chat_members me + JOIN chats c ON c.id = me.chat_id + WHERE me.user_id = $1 + AND ($2::timestamptz IS NULL OR (c.created_at, c.id) > ($2, $3::uuid)) + ORDER BY c.created_at, c.id + LIMIT $4`, + callerID, afterTime, afterID, limit+1, + ) + if err != nil { + return domain.Page[domain.Chat]{}, mapErr(err) + } + out, err := pgx.CollectRows(rows, func(r pgx.CollectableRow) (domain.Chat, error) { + var ch domain.Chat + err := r.Scan(&ch.ID, &ch.Title, &ch.CreatedAt, &ch.MemberIDs) + ch.Title = decodeText(ch.Title) + ch.CreatedAt = ch.CreatedAt.UTC() + return ch, err + }) + if err != nil { + return domain.Page[domain.Chat]{}, mapErr(err) + } + + page := domain.Page[domain.Chat]{} + if len(out) > limit { + last := out[limit-1] + page.NextCursor = domain.EncodeCursor(domain.Cursor{ + CreatedAt: last.CreatedAt, + ID: last.ID, + Scope: scope, + }) + out = out[:limit] + } + page.Items = out + return page, nil +} + +func cursorArgs(c domain.Cursor) (*time.Time, *string) { + if c.IsZero() { + return nil, nil + } + return &c.CreatedAt, &c.ID +} diff --git a/app/internal/store/db/db.go b/app/internal/store/db/db.go new file mode 100644 index 00000000..b0660dea --- /dev/null +++ b/app/internal/store/db/db.go @@ -0,0 +1,136 @@ +package db + +import ( + "context" + "errors" + "fmt" + "os" + "strings" + "time" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgxpool" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/config" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store" +) + +var _ store.Store = (*DB)(nil) + +type DB struct { + *Users + *Chats + *Messages + *Attachments + + pool *pgxpool.Pool +} + +func New(pool *pgxpool.Pool, queryTimeout time.Duration) *DB { + c := conn{pool: pool, timeout: queryTimeout} + return &DB{ + Users: &Users{conn: c}, + Chats: &Chats{conn: c}, + Messages: &Messages{conn: c}, + Attachments: &Attachments{conn: c}, + pool: pool, + } +} + +func Connect(ctx context.Context, cfg config.Database) (*pgxpool.Pool, error) { + dsn, err := dsnFrom(cfg) + if err != nil { + return nil, err + } + pcfg, err := pgxpool.ParseConfig(dsn) + if err != nil { + return nil, errors.New("db: invalid DSN") + } + pcfg.MaxConns = cfg.MaxConns + pcfg.ConnConfig.ConnectTimeout = time.Duration(cfg.ConnectTimeoutMs) * time.Millisecond + if !cfg.EnableBitmapScan { + pcfg.ConnConfig.RuntimeParams["enable_bitmapscan"] = "off" + } + + pool, err := pgxpool.NewWithConfig(ctx, pcfg) + if err != nil { + return nil, fmt.Errorf("db: pool: %w", err) + } + + pingCtx, cancel := context.WithTimeout(ctx, pcfg.ConnConfig.ConnectTimeout) + defer cancel() + if err := pool.Ping(pingCtx); err != nil { + pool.Close() + return nil, fmt.Errorf("db: ping: %w", err) + } + return pool, nil +} + +func dsnFrom(cfg config.Database) (string, error) { + if cfg.URLFile != "" { + b, err := os.ReadFile(cfg.URLFile) + if err != nil { + return "", fmt.Errorf("db: read DATABASE_URL_FILE: %w", err) + } + return strings.TrimSpace(string(b)), nil + } + if cfg.URL != "" { + return cfg.URL, nil + } + return "", errors.New("db: DATABASE_URL_FILE or DATABASE_URL is required") +} + +func (d *DB) Ping(ctx context.Context) error { + return d.pool.Ping(ctx) +} + +func (d *DB) Close() { + d.pool.Close() +} + +type conn struct { + pool *pgxpool.Pool + timeout time.Duration +} + +func (c conn) withTimeout(parent context.Context) (context.Context, context.CancelFunc) { + return context.WithTimeout(parent, c.timeout) +} + +const ( + codeUniqueViolation = "23505" + codeForeignKeyViolation = "23503" + codeCheckViolation = "23514" + codeInvalidTextRepr = "22P02" +) + +func mapErr(err error) error { + if err == nil { + return nil + } + if errors.Is(err, pgx.ErrNoRows) { + return domain.ErrNotFound + } + var pgErr *pgconn.PgError + if errors.As(err, &pgErr) { + switch pgErr.Code { + case codeUniqueViolation: + return domain.ErrConflict + case codeForeignKeyViolation, codeCheckViolation, codeInvalidTextRepr: + return domain.ErrInvalidArgument + } + switch pgErr.Code[:2] { + case "08", "53", "57": + return fmt.Errorf("%w: db: %s", domain.ErrUnavailable, pgErr.Code) + } + return fmt.Errorf("db: %s: %w", pgErr.Code, err) + } + return fmt.Errorf("%w: db: %v", domain.ErrUnavailable, err) +} + +func isFKViolation(err error) bool { + var pgErr *pgconn.PgError + return errors.As(err, &pgErr) && pgErr.Code == codeForeignKeyViolation +} diff --git a/app/internal/store/db/db_test.go b/app/internal/store/db/db_test.go new file mode 100644 index 00000000..5fe65db5 --- /dev/null +++ b/app/internal/store/db/db_test.go @@ -0,0 +1,46 @@ +package db + +import ( + "context" + "errors" + "fmt" + "testing" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" +) + +func TestMapErr(t *testing.T) { + pg := func(code string) error { return &pgconn.PgError{Code: code} } + cases := []struct { + name string + err error + want error + }{ + {"no rows", pgx.ErrNoRows, domain.ErrNotFound}, + {"unique", pg("23505"), domain.ErrConflict}, + {"fk", pg("23503"), domain.ErrInvalidArgument}, + {"check", pg("23514"), domain.ErrInvalidArgument}, + {"bad uuid text", pg("22P02"), domain.ErrInvalidArgument}, + {"admin shutdown (postgres stop)", pg("57P01"), domain.ErrUnavailable}, + {"cannot connect now (starting up)", pg("57P03"), domain.ErrUnavailable}, + {"connection failure", pg("08006"), domain.ErrUnavailable}, + {"too many connections", pg("53300"), domain.ErrUnavailable}, + {"timeout", fmt.Errorf("query: %w", context.DeadlineExceeded), domain.ErrUnavailable}, + {"dial refused", errors.New("dial tcp: connection refused"), domain.ErrUnavailable}, + } + for _, tc := range cases { + if got := mapErr(tc.err); !errors.Is(got, tc.want) { + t.Errorf("%s: mapErr = %v, want %v", tc.name, got, tc.want) + } + } + + if got := mapErr(pg("42601")); errors.Is(got, domain.ErrUnavailable) || errors.Is(got, domain.ErrInvalidArgument) { + t.Errorf("syntax error mapped to %v", got) + } + if mapErr(nil) != nil { + t.Error("mapErr(nil) != nil") + } +} diff --git a/app/internal/store/db/invalidations.go b/app/internal/store/db/invalidations.go new file mode 100644 index 00000000..3bcaf7f6 --- /dev/null +++ b/app/internal/store/db/invalidations.go @@ -0,0 +1,59 @@ +package db + +import ( + "context" + + "github.com/jackc/pgx/v5" +) + +func (m *Messages) AddPendingInvalidation(ctx context.Context, chatID string) (int64, error) { + ctx, cancel := m.withTimeout(ctx) + defer cancel() + + var gen int64 + err := m.pool.QueryRow(ctx, ` + INSERT INTO cache_invalidations (chat_id) VALUES ($1) + ON CONFLICT (chat_id) DO UPDATE + SET gen = nextval('cache_invalidations_gen_seq'), updated_at = now() + RETURNING gen`, + chatID, + ).Scan(&gen) + if err != nil { + return 0, mapErr(err) + } + return gen, nil +} + +func (m *Messages) PendingInvalidations(ctx context.Context) (map[string]int64, error) { + ctx, cancel := m.withTimeout(ctx) + defer cancel() + + rows, err := m.pool.Query(ctx, `SELECT chat_id::text, gen FROM cache_invalidations`) + if err != nil { + return nil, mapErr(err) + } + out := map[string]int64{} + var ( + id string + gen int64 + ) + _, err = pgx.ForEachRow(rows, []any{&id, &gen}, func() error { + out[id] = gen + return nil + }) + if err != nil { + return nil, mapErr(err) + } + return out, nil +} + +func (m *Messages) ResolvePendingInvalidation(ctx context.Context, chatID string, gen int64) error { + ctx, cancel := m.withTimeout(ctx) + defer cancel() + + _, err := m.pool.Exec(ctx, + `DELETE FROM cache_invalidations WHERE chat_id = $1 AND gen = $2`, + chatID, gen, + ) + return mapErr(err) +} diff --git a/app/internal/store/db/messages.go b/app/internal/store/db/messages.go new file mode 100644 index 00000000..89d52092 --- /dev/null +++ b/app/internal/store/db/messages.go @@ -0,0 +1,209 @@ +package db + +import ( + "context" + "errors" + "slices" + "strings" + "time" + + "github.com/jackc/pgx/v5" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" +) + +type Messages struct { + conn +} + +func (m *Messages) AddMessage(ctx context.Context, callerID, chatID, idempotencyKey, text string, attachmentIDs []string) (domain.Message, error) { + if strings.TrimSpace(text) == "" && len(attachmentIDs) == 0 { + return domain.Message{}, domain.ErrInvalidArgument + } + + ctx, cancel := m.withTimeout(ctx) + defer cancel() + + tx, err := m.pool.Begin(ctx) + if err != nil { + return domain.Message{}, mapErr(err) + } + defer tx.Rollback(ctx) + + msg := domain.Message{ChatID: chatID, AuthorID: callerID, Text: text, AttachmentIDs: attachmentIDs} + err = tx.QueryRow(ctx, ` + INSERT INTO message_idempotency_keys (user_id, chat_id, key, message_id) + VALUES ($1, $2, $3, gen_random_uuid()) + ON CONFLICT (user_id, chat_id, key) DO NOTHING + RETURNING message_id::text`, + callerID, chatID, idempotencyKey, + ).Scan(&msg.ID) + switch { + case errors.Is(err, pgx.ErrNoRows): + return replayMessage(ctx, tx, callerID, chatID, idempotencyKey, text, attachmentIDs) + case isFKViolation(err): + return domain.Message{}, domain.ErrNotFound + case err != nil: + return domain.Message{}, mapErr(err) + } + + err = tx.QueryRow(ctx, ` + INSERT INTO messages (id, chat_id, sender_id, text) + VALUES ($1, $2, $3, $4) + RETURNING created_at`, + msg.ID, chatID, callerID, encodeText(text), + ).Scan(&msg.CreatedAt) + if err != nil { + return domain.Message{}, mapErr(err) + } + // Составной FK сам отклоняет вложение другого чата и неизвестное вложение. Та же транзакция: + // при ошибке не останется ни сообщения, ни ключа идемпотентности. + if len(attachmentIDs) > 0 { + _, err = tx.Exec(ctx, ` + INSERT INTO message_attachments (message_id, chat_id, attachment_id, position) + SELECT $1, $2, t.id::uuid, t.ord::int + FROM unnest($3::text[]) WITH ORDINALITY AS t(id, ord)`, + msg.ID, chatID, attachmentIDs, + ) + if isFKViolation(err) { + return domain.Message{}, domain.ErrNotFound + } + if err != nil { + return domain.Message{}, mapErr(err) + } + } + if err := tx.Commit(ctx); err != nil { + return domain.Message{}, mapErr(err) + } + msg.CreatedAt = msg.CreatedAt.UTC() + return msg, nil +} + +func replayMessage(ctx context.Context, tx pgx.Tx, callerID, chatID, idempotencyKey, text string, attachmentIDs []string) (domain.Message, error) { + msg := domain.Message{ChatID: chatID, AuthorID: callerID} + err := tx.QueryRow(ctx, ` + SELECT m.id::text, m.text, m.created_at, COALESCE((SELECT array_agg(ma.attachment_id::text ORDER BY ma.position) FROM message_attachments ma WHERE ma.message_id = m.id), ARRAY[]::text[]) + FROM message_idempotency_keys k + JOIN messages m ON m.id = k.message_id + WHERE k.user_id = $1 AND k.chat_id = $2 AND k.key = $3`, + callerID, chatID, idempotencyKey, + ).Scan(&msg.ID, &msg.Text, &msg.CreatedAt, &msg.AttachmentIDs) + if errors.Is(err, pgx.ErrNoRows) { + return domain.Message{}, domain.ErrUnavailable + } + if err != nil { + return domain.Message{}, mapErr(err) + } + msg.Text = decodeText(msg.Text) + if msg.Text != text || !slices.Equal(msg.AttachmentIDs, attachmentIDs) { + return domain.Message{}, domain.ErrIdempotencyConflict + } + msg.CreatedAt = msg.CreatedAt.UTC() + return msg, nil +} + +func (m *Messages) PurgeIdempotencyKeys(ctx context.Context, ttl time.Duration) (int64, error) { + ctx, cancel := m.withTimeout(ctx) + defer cancel() + + tag, err := m.pool.Exec(ctx, + `DELETE FROM message_idempotency_keys WHERE created_at < now() - make_interval(secs => $1)`, + ttl.Seconds(), + ) + if err != nil { + return 0, mapErr(err) + } + return tag.RowsAffected(), nil +} + +func (m *Messages) ListMessages(ctx context.Context, callerID, chatID, cursor string, limit int) (domain.Page[domain.Message], error) { + member, err := m.IsMember(ctx, chatID, callerID) + if err != nil { + return domain.Page[domain.Message]{}, err + } + if !member { + return domain.Page[domain.Message]{}, domain.ErrNotFound + } + return m.HistoryPage(ctx, chatID, cursor, limit) +} + +func (m *Messages) IsMember(ctx context.Context, chatID, userID string) (bool, error) { + ctx, cancel := m.withTimeout(ctx) + defer cancel() + + var member bool + err := m.pool.QueryRow(ctx, + `SELECT EXISTS (SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2)`, + chatID, userID, + ).Scan(&member) + if err != nil { + return false, mapErr(err) + } + return member, nil +} + +func (m *Messages) HistoryPage(ctx context.Context, chatID, cursor string, limit int) (domain.Page[domain.Message], error) { + if limit <= 0 || limit > 100 { + return domain.Page[domain.Message]{}, domain.ErrInvalidArgument + } + cur, err := domain.DecodeCursor(cursor) + if err != nil { + return domain.Page[domain.Message]{}, err + } + scope := "chat:" + chatID + if cursor != "" && cur.Scope != scope { + return domain.Page[domain.Message]{}, domain.ErrInvalidArgument + } + ctx, cancel := m.withTimeout(ctx) + defer cancel() + + var rows pgx.Rows + if cur.IsZero() { + rows, err = m.pool.Query(ctx, ` + SELECT m.id::text, m.chat_id::text, m.sender_id::text, m.text, m.created_at, + COALESCE((SELECT array_agg(ma.attachment_id::text ORDER BY ma.position) FROM message_attachments ma WHERE ma.message_id = m.id), ARRAY[]::text[]) + FROM messages m + WHERE m.chat_id = $1 + ORDER BY m.created_at, m.id + LIMIT $2`, + chatID, limit+1, + ) + } else { + rows, err = m.pool.Query(ctx, ` + SELECT m.id::text, m.chat_id::text, m.sender_id::text, m.text, m.created_at, + COALESCE((SELECT array_agg(ma.attachment_id::text ORDER BY ma.position) FROM message_attachments ma WHERE ma.message_id = m.id), ARRAY[]::text[]) + FROM messages m + WHERE m.chat_id = $1 + AND (m.created_at, m.id) > ($2, $3::uuid) + ORDER BY m.created_at, m.id + LIMIT $4`, + chatID, cur.CreatedAt, cur.ID, limit+1, + ) + } + if err != nil { + return domain.Page[domain.Message]{}, mapErr(err) + } + out, err := pgx.CollectRows(rows, func(r pgx.CollectableRow) (domain.Message, error) { + var msg domain.Message + err := r.Scan(&msg.ID, &msg.ChatID, &msg.AuthorID, &msg.Text, &msg.CreatedAt, &msg.AttachmentIDs) + msg.Text = decodeText(msg.Text) + msg.CreatedAt = msg.CreatedAt.UTC() + return msg, err + }) + if err != nil { + return domain.Page[domain.Message]{}, mapErr(err) + } + + page := domain.Page[domain.Message]{} + if len(out) > limit { + last := out[limit-1] + page.NextCursor = domain.EncodeCursor(domain.Cursor{ + CreatedAt: last.CreatedAt, + ID: last.ID, + Scope: scope, + }) + out = out[:limit] + } + page.Items = out + return page, nil +} diff --git a/app/internal/store/db/text.go b/app/internal/store/db/text.go new file mode 100644 index 00000000..4c9e30f1 --- /dev/null +++ b/app/internal/store/db/text.go @@ -0,0 +1,22 @@ +package db + +import "strings" + +var ( + textEncoder = strings.NewReplacer(`\`, `\\`, "\x00", `\0`) + textDecoder = strings.NewReplacer(`\\`, `\`, `\0`, "\x00") +) + +func encodeText(s string) string { + if !strings.ContainsAny(s, "\\\x00") { + return s + } + return textEncoder.Replace(s) +} + +func decodeText(s string) string { + if !strings.Contains(s, `\`) { + return s + } + return textDecoder.Replace(s) +} diff --git a/app/internal/store/db/text_test.go b/app/internal/store/db/text_test.go new file mode 100644 index 00000000..a957c8d5 --- /dev/null +++ b/app/internal/store/db/text_test.go @@ -0,0 +1,18 @@ +package db + +import "testing" + +func TestTextEscapeRoundTrip(t *testing.T) { + cases := []string{"", "plain", "\x00", "a\x00b", `\`, `\0`, `\\0`, "\\\x00", "\x00\\0\x00", "привет\x00мир"} + for _, s := range cases { + enc := encodeText(s) + for i := 0; i < len(enc); i++ { + if enc[i] == 0 { + t.Fatalf("encodeText(%q) = %q содержит NUL", s, enc) + } + } + if got := decodeText(enc); got != s { + t.Fatalf("decodeText(encodeText(%q)) = %q", s, got) + } + } +} diff --git a/app/internal/store/db/users.go b/app/internal/store/db/users.go new file mode 100644 index 00000000..3ab1beb2 --- /dev/null +++ b/app/internal/store/db/users.go @@ -0,0 +1,89 @@ +package db + +import ( + "context" + "strings" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" +) + +type Users struct { + conn +} + +func (u *Users) CreateUser(ctx context.Context, username, displayName, passwordHash string) (domain.User, error) { + if strings.TrimSpace(username) == "" || strings.TrimSpace(displayName) == "" || passwordHash == "" { + return domain.User{}, domain.ErrInvalidArgument + } + + ctx, cancel := u.withTimeout(ctx) + defer cancel() + + user := domain.User{Username: username, DisplayName: displayName} + err := u.pool.QueryRow(ctx, ` + INSERT INTO users (username, display_name, password_hash) + VALUES ($1, $2, $3) + RETURNING id::text, created_at`, + username, encodeText(displayName), passwordHash, + ).Scan(&user.ID, &user.CreatedAt) + if err != nil { + return domain.User{}, mapErr(err) + } + user.CreatedAt = user.CreatedAt.UTC() + return user, nil +} + +func (u *Users) UserByID(ctx context.Context, id string) (domain.User, error) { + ctx, cancel := u.withTimeout(ctx) + defer cancel() + + user := domain.User{} + err := u.pool.QueryRow(ctx, ` + SELECT id::text, username, display_name, created_at + FROM users + WHERE id = $1`, + id, + ).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt) + if err != nil { + err = mapErr(err) + if err == domain.ErrInvalidArgument { + return domain.User{}, domain.ErrNotFound + } + return domain.User{}, err + } + user.DisplayName = decodeText(user.DisplayName) + user.CreatedAt = user.CreatedAt.UTC() + return user, nil +} + +func (u *Users) CredentialsByUsername(ctx context.Context, username string) (domain.User, string, error) { + ctx, cancel := u.withTimeout(ctx) + defer cancel() + + user := domain.User{} + var hash string + err := u.pool.QueryRow(ctx, ` + SELECT id::text, username, display_name, created_at, password_hash + FROM users + WHERE username = $1`, + encodeText(username), + ).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt, &hash) + if err != nil { + return domain.User{}, "", mapErr(err) + } + user.DisplayName = decodeText(user.DisplayName) + user.CreatedAt = user.CreatedAt.UTC() + return user, hash, nil +} + +func (u *Users) UsernameExists(ctx context.Context, username string) bool { + ctx, cancel := u.withTimeout(ctx) + defer cancel() + + var exists bool + err := u.pool.QueryRow(ctx, + `SELECT EXISTS (SELECT 1 FROM users WHERE username = $1)`, + encodeText(username), + ).Scan(&exists) + return err == nil && exists +} diff --git a/app/internal/store/memory.go b/app/internal/store/memory.go new file mode 100644 index 00000000..92491189 --- /dev/null +++ b/app/internal/store/memory.go @@ -0,0 +1,368 @@ +package store + +import ( + "context" + "slices" + "strings" + "sync" + "time" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" + "github.com/google/uuid" +) + +var _ Store = (*Memory)(nil) + +type Memory struct { + mu sync.RWMutex + + users map[string]domain.User + byName map[string]string + hashes map[string]string + + chats map[string]*chatBucket + chatOrder []string + + lastTime time.Time + + idempotency map[string]domain.Message + + attachments map[string]domain.Attachment + + maxMessages int + messagesTotal int +} + +type chatBucket struct { + chat domain.Chat + members map[string]struct{} + messages []domain.Message +} + +func New() *Memory { + return NewWithLimit(0) +} + +func NewWithLimit(maxMessages int) *Memory { + return &Memory{ + users: make(map[string]domain.User), + byName: make(map[string]string), + hashes: make(map[string]string), + chats: make(map[string]*chatBucket), + idempotency: make(map[string]domain.Message), + attachments: make(map[string]domain.Attachment), + maxMessages: maxMessages, + } +} + +func (m *Memory) MessagesTotal() int { + m.mu.RLock() + defer m.mu.RUnlock() + return m.messagesTotal +} + +func (m *Memory) now() time.Time { + t := time.Now().UTC() + if !t.After(m.lastTime) { + t = m.lastTime.Add(time.Nanosecond) + } + m.lastTime = t + return t +} + +func (m *Memory) CreateUser(_ context.Context, username, displayName, passwordHash string) (domain.User, error) { + if strings.TrimSpace(username) == "" || strings.TrimSpace(displayName) == "" { + return domain.User{}, domain.ErrInvalidArgument + } + + m.mu.Lock() + defer m.mu.Unlock() + + if _, taken := m.byName[username]; taken { + return domain.User{}, domain.ErrConflict + } + + u := domain.User{ + ID: uuid.NewString(), + Username: username, + DisplayName: displayName, + CreatedAt: m.now(), + } + m.users[u.ID] = u + m.byName[username] = u.ID + m.hashes[u.ID] = passwordHash + return u, nil +} + +func (m *Memory) UserByID(_ context.Context, id string) (domain.User, error) { + m.mu.RLock() + defer m.mu.RUnlock() + u, ok := m.users[id] + if !ok { + return domain.User{}, domain.ErrNotFound + } + return u, nil +} + +func (m *Memory) CredentialsByUsername(_ context.Context, username string) (domain.User, string, error) { + m.mu.RLock() + defer m.mu.RUnlock() + id, ok := m.byName[username] + if !ok { + return domain.User{}, "", domain.ErrNotFound + } + return m.users[id], m.hashes[id], nil +} + +func (m *Memory) UsernameExists(_ context.Context, username string) bool { + m.mu.RLock() + defer m.mu.RUnlock() + _, taken := m.byName[username] + return taken +} + +func (m *Memory) CreateChat(_ context.Context, callerID, title string, memberIDs []string) (domain.Chat, error) { + if strings.TrimSpace(title) == "" { + return domain.Chat{}, domain.ErrInvalidArgument + } + if len(memberIDs) == 0 || len(memberIDs) > 100 { + return domain.Chat{}, domain.ErrInvalidArgument + } + + seen := make(map[string]struct{}, len(memberIDs)) + callerInMembers := false + for _, id := range memberIDs { + if _, dup := seen[id]; dup { + return domain.Chat{}, domain.ErrInvalidArgument + } + seen[id] = struct{}{} + if id == callerID { + callerInMembers = true + } + } + if !callerInMembers { + return domain.Chat{}, domain.ErrInvalidArgument + } + + m.mu.Lock() + defer m.mu.Unlock() + + for _, id := range memberIDs { + if _, ok := m.users[id]; !ok { + return domain.Chat{}, domain.ErrInvalidArgument + } + } + + members := append([]string(nil), memberIDs...) + + chat := domain.Chat{ + ID: uuid.NewString(), + Title: title, + MemberIDs: members, + CreatedAt: m.now(), + } + m.chats[chat.ID] = &chatBucket{ + chat: chat, + members: seen, + } + m.chatOrder = append(m.chatOrder, chat.ID) + return cloneChat(chat), nil +} + +func (m *Memory) ChatByID(_ context.Context, callerID, chatID string) (domain.Chat, error) { + m.mu.RLock() + defer m.mu.RUnlock() + + b, ok := m.chats[chatID] + if !ok { + return domain.Chat{}, domain.ErrNotFound + } + if _, member := b.members[callerID]; !member { + return domain.Chat{}, domain.ErrNotFound + } + return cloneChat(b.chat), nil +} + +func (m *Memory) ListChats(_ context.Context, callerID, cursor string, limit int) (domain.Page[domain.Chat], error) { + if limit <= 0 || limit > 100 { + return domain.Page[domain.Chat]{}, domain.ErrInvalidArgument + } + c, err := domain.DecodeCursor(cursor) + if err != nil { + return domain.Page[domain.Chat]{}, err + } + if cursor != "" && c.Scope != "chats:"+callerID { + return domain.Page[domain.Chat]{}, domain.ErrInvalidArgument + } + + m.mu.RLock() + defer m.mu.RUnlock() + + out := make([]domain.Chat, 0, limit+1) + for _, id := range m.chatOrder { + b := m.chats[id] + if _, member := b.members[callerID]; !member { + continue + } + if !c.Less(b.chat.CreatedAt, b.chat.ID) { + continue + } + out = append(out, cloneChat(b.chat)) + if len(out) > limit { + break + } + } + + page := domain.Page[domain.Chat]{} + if len(out) > limit { + last := out[limit-1] + page.NextCursor = domain.EncodeCursor(domain.Cursor{ + CreatedAt: last.CreatedAt, + ID: last.ID, + Scope: "chats:" + callerID, + }) + out = out[:limit] + } + page.Items = out + return page, nil +} + +func (m *Memory) AddMessage(_ context.Context, callerID, chatID, idempotencyKey, text string, attachmentIDs []string) (domain.Message, error) { + if strings.TrimSpace(text) == "" && len(attachmentIDs) == 0 { + return domain.Message{}, domain.ErrInvalidArgument + } + + m.mu.Lock() + defer m.mu.Unlock() + + b, ok := m.chats[chatID] + if !ok { + return domain.Message{}, domain.ErrNotFound + } + if _, member := b.members[callerID]; !member { + return domain.Message{}, domain.ErrNotFound + } + + idemKey := callerID + "\x00" + chatID + "\x00" + idempotencyKey + if prev, ok := m.idempotency[idemKey]; ok { + if prev.Text != text || !slices.Equal(prev.AttachmentIDs, attachmentIDs) { + return domain.Message{}, domain.ErrIdempotencyConflict + } + return prev, nil + } + + if m.maxMessages > 0 && m.messagesTotal >= m.maxMessages { + return domain.Message{}, domain.ErrUnavailable + } + + for _, id := range attachmentIDs { + if att, ok := m.attachments[id]; !ok || att.ChatID != chatID { + return domain.Message{}, domain.ErrNotFound + } + } + + msg := domain.Message{ + ID: uuid.NewString(), + ChatID: chatID, + AuthorID: callerID, + Text: text, + CreatedAt: m.now(), + AttachmentIDs: attachmentIDs, + } + b.messages = append(b.messages, msg) + m.idempotency[idemKey] = msg + m.messagesTotal++ + return msg, nil +} + +func (m *Memory) ListMessages(_ context.Context, callerID, chatID, cursor string, limit int) (domain.Page[domain.Message], error) { + if limit <= 0 || limit > 100 { + return domain.Page[domain.Message]{}, domain.ErrInvalidArgument + } + c, err := domain.DecodeCursor(cursor) + if err != nil { + return domain.Page[domain.Message]{}, err + } + + if cursor != "" && c.Scope != "chat:"+chatID { + return domain.Page[domain.Message]{}, domain.ErrInvalidArgument + } + + m.mu.RLock() + defer m.mu.RUnlock() + + b, ok := m.chats[chatID] + if !ok { + return domain.Page[domain.Message]{}, domain.ErrNotFound + } + if _, member := b.members[callerID]; !member { + return domain.Page[domain.Message]{}, domain.ErrNotFound + } + + start := 0 + for ; start < len(b.messages); start++ { + if c.Less(b.messages[start].CreatedAt, b.messages[start].ID) { + break + } + } + + end := start + limit + hasMore := end < len(b.messages) + if end > len(b.messages) { + end = len(b.messages) + } + + out := make([]domain.Message, end-start) + copy(out, b.messages[start:end]) + + page := domain.Page[domain.Message]{Items: out} + if hasMore && len(out) > 0 { + last := out[len(out)-1] + page.NextCursor = domain.EncodeCursor(domain.Cursor{ + CreatedAt: last.CreatedAt, + ID: last.ID, + Scope: "chat:" + chatID, + }) + } + return page, nil +} + +func (m *Memory) CreateAttachment(_ context.Context, att domain.Attachment) (domain.Attachment, error) { + m.mu.Lock() + defer m.mu.Unlock() + if b, ok := m.chats[att.ChatID]; !ok { + return domain.Attachment{}, domain.ErrNotFound + } else if _, member := b.members[att.OwnerID]; !member { + return domain.Attachment{}, domain.ErrNotFound + } + att.CreatedAt = m.now() + att.UpdatedAt = att.CreatedAt + m.attachments[att.ID] = att + return att, nil +} + +func (m *Memory) AttachmentForMember(_ context.Context, callerID, attachmentID string) (domain.Attachment, error) { + m.mu.RLock() + defer m.mu.RUnlock() + att, ok := m.attachments[attachmentID] + if !ok { + return domain.Attachment{}, domain.ErrNotFound + } + if _, member := m.chats[att.ChatID].members[callerID]; !member { + return domain.Attachment{}, domain.ErrNotFound + } + return att, nil +} + +func (m *Memory) AttachmentExists(_ context.Context, attachmentID string) (bool, error) { + m.mu.RLock() + defer m.mu.RUnlock() + _, ok := m.attachments[attachmentID] + return ok, nil +} + +func cloneChat(c domain.Chat) domain.Chat { + out := c + out.MemberIDs = append([]string(nil), c.MemberIDs...) + return out +} diff --git a/app/internal/store/store.go b/app/internal/store/store.go new file mode 100644 index 00000000..727f9494 --- /dev/null +++ b/app/internal/store/store.go @@ -0,0 +1,43 @@ +package store + +import ( + "context" + + "gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain" +) + +type UserStore interface { + CreateUser(ctx context.Context, username, displayName, passwordHash string) (domain.User, error) + UserByID(ctx context.Context, id string) (domain.User, error) + CredentialsByUsername(ctx context.Context, username string) (domain.User, string, error) + UsernameExists(ctx context.Context, username string) bool +} + +type ChatStore interface { + CreateChat(ctx context.Context, callerID, title string, memberIDs []string) (domain.Chat, error) + ChatByID(ctx context.Context, callerID, chatID string) (domain.Chat, error) + ListChats(ctx context.Context, callerID, cursor string, limit int) (domain.Page[domain.Chat], error) +} + +type MessageStore interface { + // AddMessage идемпотентен по (callerID, chatID, idempotencyKey): повтор с тем же + // text и attachmentIDs возвращает исходное сообщение, с другими — domain.ErrIdempotencyConflict. + // Вложение не из этого чата или неизвестное — domain.ErrNotFound. + AddMessage(ctx context.Context, callerID, chatID, idempotencyKey, text string, attachmentIDs []string) (domain.Message, error) + ListMessages(ctx context.Context, callerID, chatID, cursor string, limit int) (domain.Page[domain.Message], error) +} + +type AttachmentStore interface { + CreateAttachment(ctx context.Context, att domain.Attachment) (domain.Attachment, error) + // AttachmentForMember для постороннего возвращает domain.ErrNotFound. + AttachmentForMember(ctx context.Context, callerID, attachmentID string) (domain.Attachment, error) + // AttachmentExists нужен компенсации: ошибка INSERT не доказывает, что строки нет. + AttachmentExists(ctx context.Context, attachmentID string) (bool, error) +} + +type Store interface { + UserStore + ChatStore + MessageStore + AttachmentStore +} diff --git a/app/internal/token/token.go b/app/internal/token/token.go new file mode 100644 index 00000000..877c8db2 --- /dev/null +++ b/app/internal/token/token.go @@ -0,0 +1,42 @@ +package token + +import ( + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "errors" + "fmt" +) + +const Bytes = 32 + +var encoding = base64.RawURLEncoding + +var EncodedLen = encoding.EncodedLen(Bytes) + +var ErrMalformed = errors.New("token: malformed") + +func New() (plain string, hash []byte, err error) { + buf := make([]byte, Bytes) + if _, err := rand.Read(buf); err != nil { + return "", nil, fmt.Errorf("token: rand: %w", err) + } + plain = encoding.EncodeToString(buf) + return plain, Hash(plain), nil +} + +func Hash(plain string) []byte { + sum := sha256.Sum256([]byte(plain)) + return sum[:] +} + +func Parse(plain string) ([]byte, error) { + if len(plain) != EncodedLen { + return nil, ErrMalformed + } + raw, err := encoding.DecodeString(plain) + if err != nil || len(raw) != Bytes { + return nil, ErrMalformed + } + return Hash(plain), nil +} diff --git a/app/internal/token/token_test.go b/app/internal/token/token_test.go new file mode 100644 index 00000000..ea6d8b25 --- /dev/null +++ b/app/internal/token/token_test.go @@ -0,0 +1,65 @@ +package token + +import ( + "bytes" + "errors" + "testing" +) + +func TestNew_FormatAndHash(t *testing.T) { + plain, hash, err := New() + if err != nil { + t.Fatal(err) + } + if len(plain) != EncodedLen || len(plain) < 32 { + t.Errorf("len(token) = %d, want %d", len(plain), EncodedLen) + } + if len(hash) != 32 { + t.Errorf("len(hash) = %d, want 32", len(hash)) + } + if !bytes.Equal(hash, Hash(plain)) { + t.Error("hash from New differs from Hash(token)") + } +} + +func TestNew_Unique(t *testing.T) { + seen := make(map[string]struct{}, 1000) + for i := 0; i < 1000; i++ { + plain, _, err := New() + if err != nil { + t.Fatal(err) + } + if _, ok := seen[plain]; ok { + t.Fatalf("duplicate token %q", plain) + } + seen[plain] = struct{}{} + } +} + +func TestParse(t *testing.T) { + plain, hash, err := New() + if err != nil { + t.Fatal(err) + } + got, err := Parse(plain) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, hash) { + t.Error("Parse hash differs from New hash") + } + + bad := []string{ + "", + "short", + plain[:EncodedLen-1], + plain + "A", + "+" + plain[1:], + "00000000-0000-0000-0000-000000000000", + } + for _, s := range bad { + if _, err := Parse(s); !errors.Is(err, ErrMalformed) { + t.Errorf("Parse(%q) err = %v, want ErrMalformed", s, err) + } + } +} diff --git a/app/internal/validate/attachment.go b/app/internal/validate/attachment.go new file mode 100644 index 00000000..05e880f2 --- /dev/null +++ b/app/internal/validate/attachment.go @@ -0,0 +1,70 @@ +package validate + +import ( + "fmt" + "strings" + "unicode" + "unicode/utf8" +) + +const ( + FilenameMinLen = 1 + FilenameMaxLen = 255 + + AttachmentIDsMax = 10 +) + +// Filename проверяет отображаемое имя. Оно нигде не используется как путь, но попадает в заголовки +// и к другим клиентам, поэтому разделители и невидимые управляющие символы запрещены. +func Filename(s string) error { + if !utf8.ValidString(s) { + return newError("filename", "must be valid UTF-8") + } + if !notOnlyWhitespace(s) { + return newError("filename", "must not be empty or whitespace only") + } + if !codePointsBetween(s, FilenameMinLen, FilenameMaxLen) { + return newError("filename", fmt.Sprintf("length must be in [%d, %d] code points", FilenameMinLen, FilenameMaxLen)) + } + if s == "." || s == ".." { + return newError("filename", "must not be a path component") + } + if strings.ContainsFunc(s, unsafeFilenameRune) { + return newError("filename", "must not contain path separators or control characters") + } + return nil +} + +func unsafeFilenameRune(r rune) bool { + switch { + case r == '/', r == '\\', unicode.IsControl(r): + return true + case r == '
', r == '
': + return true + case r >= '‪' && r <= '‮', r >= '⁦' && r <= '⁩': + // Символы смены направления текста позволяют выдать evil.exe за безобидное имя. + return true + } + return false +} + +// AttachmentIDs приводит ID к каноничному виду с сохранением порядка. +func AttachmentIDs(ids []string) ([]string, error) { + if len(ids) > AttachmentIDsMax { + return nil, newError("attachment_ids", fmt.Sprintf("count must be at most %d", AttachmentIDsMax)) + } + out := make([]string, 0, len(ids)) + seen := make(map[string]struct{}, len(ids)) + for i, raw := range ids { + id, err := CanonicalUUID(fmt.Sprintf("attachment_ids[%d]", i), raw) + if err != nil { + return nil, err + } + if _, dup := seen[id]; dup { + return nil, newError("attachment_ids", "must not contain duplicates") + } + seen[id] = struct{}{} + out = append(out, id) + } + return out, nil +} diff --git a/app/internal/validate/attachment_test.go b/app/internal/validate/attachment_test.go new file mode 100644 index 00000000..3dd42f55 --- /dev/null +++ b/app/internal/validate/attachment_test.go @@ -0,0 +1,39 @@ +package validate + +import ( + "strings" + "testing" +) + +func TestFilename(t *testing.T) { + valid := []string{"photo.png", "фото отпуска.jpeg", "a", strings.Repeat("я", 255), "👋.png", "..hidden.png"} + for _, s := range valid { + if err := Filename(s); err != nil { + t.Errorf("Filename(%q) = %v", s, err) + } + } + invalid := []string{"", " ", ".", "..", "../etc/passwd", `a\b.png`, "a/b.png", "a\x00.png", "a\nb.png", "a\x7f.png", + "\xff.png", "evil‮gnp.exe", "a
b", strings.Repeat("я", 256)} + for _, s := range invalid { + if err := Filename(s); err == nil { + t.Errorf("Filename(%q) accepted", s) + } + } +} + +func TestAttachmentIDs(t *testing.T) { + const a = "11111111-1111-4111-8111-111111111111" + got, err := AttachmentIDs([]string{strings.ToUpper(a)}) + if err != nil || got[0] != a { + t.Errorf("canonical form: %v, %v", got, err) + } + if _, err := AttachmentIDs([]string{a, strings.ToUpper(a)}); err == nil { + t.Error("duplicates accepted after canonicalization") + } + if _, err := AttachmentIDs([]string{"not-a-uuid"}); err == nil { + t.Error("invalid UUID accepted") + } + if _, err := AttachmentIDs(make([]string, AttachmentIDsMax+1)); err == nil { + t.Error("too many IDs accepted") + } +} diff --git a/app/internal/validate/chat.go b/app/internal/validate/chat.go new file mode 100644 index 00000000..62bf3f66 --- /dev/null +++ b/app/internal/validate/chat.go @@ -0,0 +1,42 @@ +package validate + +import "fmt" + +func ChatTitle(s string) error { + if !notOnlyWhitespace(s) { + return newError("title", "must not be empty or whitespace only") + } + if !codePointsBetween(s, ChatTitleMinLen, ChatTitleMaxLen) { + return newError("title", fmt.Sprintf("length must be in [%d, %d] code points", ChatTitleMinLen, ChatTitleMaxLen)) + } + return nil +} + +func MemberIDs(ids []string, callerID string) ([]string, error) { + if len(ids) < MemberIDsMin || len(ids) > MemberIDsMax { + return nil, newError("member_ids", fmt.Sprintf("count must be in [%d, %d]", MemberIDsMin, MemberIDsMax)) + } + + out := make([]string, 0, len(ids)) + seen := make(map[string]struct{}, len(ids)) + callerIn := false + for i, raw := range ids { + id, err := CanonicalUUID(fmt.Sprintf("member_ids[%d]", i), raw) + if err != nil { + return nil, err + } + if _, dup := seen[id]; dup { + return nil, newError("member_ids", "must not contain duplicates") + } + seen[id] = struct{}{} + if id == callerID { + callerIn = true + } + out = append(out, id) + } + + if !callerIn { + return nil, newError("member_ids", "must contain caller") + } + return out, nil +} diff --git a/app/internal/validate/idempotency.go b/app/internal/validate/idempotency.go new file mode 100644 index 00000000..68411a14 --- /dev/null +++ b/app/internal/validate/idempotency.go @@ -0,0 +1,12 @@ +package validate + +import "regexp" + +var idempotencyKeyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`) + +func IdempotencyKey(s string) error { + if !idempotencyKeyPattern.MatchString(s) { + return newError("Idempotency-Key", "must match [A-Za-z0-9._:-]{1,128}") + } + return nil +} diff --git a/app/internal/validate/message.go b/app/internal/validate/message.go new file mode 100644 index 00000000..2ec37d97 --- /dev/null +++ b/app/internal/validate/message.go @@ -0,0 +1,14 @@ +package validate + +import "fmt" + +// MessageText: пустой или пробельный текст допустим, только если у сообщения есть вложения. +func MessageText(s string, hasAttachments bool) error { + if !hasAttachments && !notOnlyWhitespace(s) { + return newError("text", "must not be empty or whitespace only") + } + if !codePointsBetween(s, 0, MessageTextMaxLen) { + return newError("text", fmt.Sprintf("length must be at most %d code points", MessageTextMaxLen)) + } + return nil +} diff --git a/app/internal/validate/rules.go b/app/internal/validate/rules.go new file mode 100644 index 00000000..05792a94 --- /dev/null +++ b/app/internal/validate/rules.go @@ -0,0 +1,80 @@ +package validate + +import ( + "fmt" + "regexp" + "strings" + "unicode/utf8" + + "github.com/google/uuid" +) + +const ( + UsernameMinLen = 3 + UsernameMaxLen = 32 + + DisplayNameMinLen = 1 + DisplayNameMaxLen = 100 + + PasswordMinLen = 12 + PasswordMaxLen = 128 + + ChatTitleMinLen = 1 + ChatTitleMaxLen = 100 + + MessageTextMaxLen = 4000 + + MemberIDsMin = 1 + MemberIDsMax = 100 + + LimitMin = 1 + LimitMax = 100 + LimitDefault = 50 +) + +var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`) + +func CanonicalUUID(field, s string) (string, error) { + if len(s) != 36 { + return "", newError(field, "must be a valid UUID") + } + u, err := uuid.Parse(s) + if err != nil { + return "", newError(field, "must be a valid UUID") + } + return u.String(), nil +} + +func Limit(n int) error { + if n < LimitMin || n > LimitMax { + return newError("limit", fmt.Sprintf("must be in [%d, %d]", LimitMin, LimitMax)) + } + return nil +} + +func codePointsBetween(s string, min, max int) bool { + n := utf8.RuneCountInString(s) + return n >= min && n <= max +} + +func notOnlyWhitespace(s string) bool { + return strings.TrimSpace(s) != "" +} + +type Error struct { + Field string + Reason string +} + +func (e *Error) Error() string { + return e.Field + ": " + e.Reason +} + +func (e *Error) Is(target error) bool { + _, ok := target.(*Error) + return ok +} + +func newError(field, reason string) *Error { + return &Error{Field: field, Reason: reason} +} diff --git a/app/internal/validate/user.go b/app/internal/validate/user.go new file mode 100644 index 00000000..cf97468a --- /dev/null +++ b/app/internal/validate/user.go @@ -0,0 +1,30 @@ +package validate + +import "fmt" + +func Username(s string) error { + if !usernamePattern.MatchString(s) { + return newError("username", fmt.Sprintf("must match [a-z0-9_]{%d,%d}", UsernameMinLen, UsernameMaxLen)) + } + return nil +} + +func DisplayName(s string) error { + if !notOnlyWhitespace(s) { + return newError("display_name", "must not be empty or whitespace only") + } + if !codePointsBetween(s, DisplayNameMinLen, DisplayNameMaxLen) { + return newError("display_name", fmt.Sprintf("length must be in [%d, %d] code points", DisplayNameMinLen, DisplayNameMaxLen)) + } + return nil +} + +func Password(s string) error { + if !notOnlyWhitespace(s) { + return newError("password", "must not be empty or whitespace only") + } + if !codePointsBetween(s, PasswordMinLen, PasswordMaxLen) { + return newError("password", fmt.Sprintf("length must be in [%d, %d] code points", PasswordMinLen, PasswordMaxLen)) + } + return nil +} diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 00000000..1ba47c8c --- /dev/null +++ b/compose.yaml @@ -0,0 +1,430 @@ +# Весь стенд лабораторной: LB, реплики API, PostgreSQL, Valkey, S3 (SeaweedFS) и одноразовая подготовка. +# Запуск: docker compose --env-file .env up -d --wait Перед первым запуском: sh scripts/init-secrets.sh +# Остановка с сохранением данных: docker compose --env-file .env down С удалением данных: добавить -v +# Значения вида ${X:-8080} можно менять через окружение или .env. + +name: mtusi-lab4 + +# Секреты лежат в файлах вне Git и видны контейнеру в /run/secrets только там, где подключены. +secrets: + postgres_password: + file: ./secrets/postgres_password + database_url: + file: ./secrets/database_url + valkey_password: + file: ./secrets/valkey_password + cache_url: + file: ./secrets/cache_url + valkey_cache_password: + file: ./secrets/valkey_cache_password + history_cache_url: + file: ./secrets/history_cache_url + s3_access_key_id: + file: ./secrets/s3_access_key_id + s3_secret_access_key: + file: ./secrets/s3_secret_access_key + s3_admin_access_key_id: + file: ./secrets/s3_admin_access_key_id + s3_admin_secret_access_key: + file: ./secrets/s3_admin_secret_access_key + s3_janitor_access_key_id: + file: ./secrets/s3_janitor_access_key_id + s3_janitor_secret_access_key: + file: ./secrets/s3_janitor_secret_access_key + s3_config: + file: ./secrets/s3_config + +services: + # Основная БД и источник истины. Общая для всех реплик; реплицирования нет, поэтому это единая точка отказа. + postgres: + image: postgres:17.6-alpine + deploy: + resources: + limits: + cpus: "2.0" + memory: 1G + # pg_stat_statements собирает статистику запросов для диагностики. + command: + - postgres + - -c + - shared_preload_libraries=pg_stat_statements + environment: + POSTGRES_USER: messenger + POSTGRES_DB: messenger + POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password + secrets: + - postgres_password + # Именованный том: данные переживают пересоздание контейнера и удаляются только через down -v. + volumes: + - pgdata:/var/lib/postgresql/data + # Только 127.0.0.1: для диагностики с этого хоста. Из сети порт недоступен. + ports: + - "127.0.0.1:${POSTGRES_PORT:-5432}:5432" + # Готовность БД: от неё зависят migrate и API. + healthcheck: + test: ["CMD-SHELL", "pg_isready -U messenger -d messenger"] + interval: 5s + timeout: 3s + retries: 10 + start_period: 10s + # Docker поднимет контейнер после сбоя, но не после ручной остановки: тесты отказа это используют. + restart: unless-stopped + + # Общее хранилище сессий: поэтому токен принимает любая реплика API. + valkey: + image: valkey/valkey:8.1.3-alpine + deploy: + resources: + limits: + cpus: "1.0" + memory: 256M + # Файл журнала с записью на диск раз в секунду: сессии переживают перезапуск, при аварии + # возможна потеря последней секунды. noeviction: при нехватке памяти сессии не вытесняются молча. + # $$ передаёт $ в контейнер: пароль читается из секрета при запуске, а не хранится в файле. + command: + - /bin/sh + - -c + - >- + exec valkey-server + --appendonly yes + --appendfsync everysec + --maxmemory 128mb + --maxmemory-policy noeviction + --requirepass "$$(cat /run/secrets/valkey_password)" + secrets: + - valkey_password + volumes: + - valkeydata:/data + # Только 127.0.0.1: для диагностики с этого хоста. + ports: + - "127.0.0.1:${VALKEY_PORT:-6379}:6379" + healthcheck: + test: + - CMD-SHELL + - 'valkey-cli -a "$$(cat /run/secrets/valkey_password)" ping 2>/dev/null | grep -q PONG' + interval: 5s + timeout: 3s + retries: 10 + start_period: 5s + restart: unless-stopped + + # Кэш истории выключен по умолчанию (HISTORY_CACHE=off): его долг инвалидации хранится + # в памяти реплики, поэтому при нескольких API он не гарантирует чтение после записи. + valkey-cache: + # Профили: сервис запускается только по явному запросу. Тома нет: кэш не требует сохранности, + # при нехватке памяти вытесняются давние записи (allkeys-lru). + profiles: ["cache"] + image: valkey/valkey:8.1.3-alpine + deploy: + resources: + limits: + cpus: "0.5" + memory: 128M + command: + - /bin/sh + - -c + - >- + exec valkey-server + --save "" + --appendonly no + --maxmemory 64mb + --maxmemory-policy allkeys-lru + --requirepass "$$(cat /run/secrets/valkey_cache_password)" + secrets: + - valkey_cache_password + ports: + - "127.0.0.1:${VALKEY_CACHE_PORT:-6380}:6379" + healthcheck: + test: + - CMD-SHELL + - 'valkey-cli -a "$$(cat /run/secrets/valkey_cache_password)" ping 2>/dev/null | grep -q PONG' + interval: 5s + timeout: 3s + retries: 10 + start_period: 5s + restart: unless-stopped + + + # Приватное хранилище байтов вложений. Порты на хост не публикуются. Находится только во внутренней + # сети s3-private: остальные сервисы видят его через s3-gateway и только порт S3. + # -ip.bind=127.0.0.1 важен для приватности: master, volume и filer отдают файлы БЕЗ проверки подписи + # S3, поэтому они доступны только внутри этого контейнера. Из сети стенда виден только шлюз S3 на 9000. + # -volume.preStopSeconds=0: иначе процесс ждёт 10 с при остановке и не успевает до SIGKILL. + s3: + image: chrislusf/seaweedfs:4.00 + deploy: + resources: + limits: + cpus: "1.0" + memory: 1G + entrypoint: ["weed"] + command: + - server + - -dir=/data + - -ip=127.0.0.1 + - -ip.bind=127.0.0.1 + - -master.volumeSizeLimitMB=1024 + - -volume.max=${S3_MAX_VOLUMES:-64} + - -volume.preStopSeconds=0 + - -filer + - -s3 + - -s3.ip.bind=0.0.0.0 + - -s3.port=9000 + - -s3.config=/run/secrets/s3_config + networks: + s3-private: + aliases: + - s3-storage + secrets: + - s3_config + volumes: + - s3data:/data + - ./infra/seaweedfs/master.toml:/etc/seaweedfs/master.toml:ro + # healthz отвечает только шлюз; готовность записи подтверждает s3-init. + healthcheck: + test: ["CMD", "wget", "--quiet", "--spider", "http://127.0.0.1:9000/healthz"] + interval: 3s + timeout: 3s + retries: 20 + start_period: 30s + restart: unless-stopped + + # Шлюз к S3: в общей сети отвечает на имя s3 и пропускает только порт 9000. Служебные порты + # SeaweedFS (в том числе gRPC шлюза 19000, открытый на всех интерфейсах) из общей сети недоступны. + s3-gateway: + ports: + - "127.0.0.1:19090:9000" + image: haproxy:3.2.9-alpine + deploy: + resources: + limits: + cpus: "0.5" + memory: 64M + volumes: + - ./infra/s3-gateway/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro + networks: + default: + aliases: + - s3 + s3-private: + healthcheck: + test: ["CMD", "wget", "--quiet", "--spider", "http://127.0.0.1:8405/health"] + interval: 3s + timeout: 3s + retries: 10 + start_period: 3s + restart: unless-stopped + + # Одноразовая подготовка S3: создаёт bucket и проверяет, что анонимный доступ запрещён. + # Повторный запуск ничего не меняет и не трогает объекты. Единственный сервис с ключом администратора. + s3-init: + build: + context: . + target: s3init + deploy: + resources: + limits: + cpus: "0.5" + memory: 128M + environment: + S3_ENDPOINT: ${S3_ENDPOINT:-http://s3:9000} + S3_REGION: ${S3_REGION:-us-east-1} + S3_BUCKET: ${S3_BUCKET:-messenger-attachments} + S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_admin_access_key_id + S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_admin_secret_access_key + secrets: + - s3_admin_access_key_id + - s3_admin_secret_access_key + depends_on: + s3: + condition: service_healthy + s3-gateway: + condition: service_healthy + restart: "no" + + # Очиститель: удаляет объекты без строки в attachments старше grace period. Отдельный сервис со + # своим ключом: только у него есть право на листинг, и у него нет права читать содержимое файлов. + janitor: + build: + context: . + target: janitor + deploy: + resources: + limits: + cpus: "0.5" + memory: 128M + environment: + S3_ENDPOINT: ${S3_ENDPOINT:-http://s3:9000} + S3_REGION: ${S3_REGION:-us-east-1} + S3_BUCKET: ${S3_BUCKET:-messenger-attachments} + S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_janitor_access_key_id + S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_janitor_secret_access_key + DATABASE_URL_FILE: /run/secrets/database_url + DB_MAX_CONNS: 2 + JANITOR_GRACE_SECONDS: ${JANITOR_GRACE_SECONDS:-3600} + JANITOR_INTERVAL_SECONDS: ${JANITOR_INTERVAL_SECONDS:-600} + JANITOR_MAX_DELETES: ${JANITOR_MAX_DELETES:-1000} + JANITOR_DRY_RUN: ${JANITOR_DRY_RUN:-false} + secrets: + - database_url + - s3_janitor_access_key_id + - s3_janitor_secret_access_key + depends_on: + postgres: + condition: service_healthy + migrate: + condition: service_completed_successfully + s3-init: + condition: service_completed_successfully + restart: unless-stopped + + # Проверка прав S3 мимо API, запускается вручную: docker compose --env-file .env run --rm s3check + s3check: + profiles: ["tools"] + build: + context: . + target: s3check + environment: + S3_ENDPOINT: ${S3_ENDPOINT:-http://s3:9000} + S3_REGION: ${S3_REGION:-us-east-1} + S3_BUCKET: ${S3_BUCKET:-messenger-attachments} + secrets: + - s3_access_key_id + - s3_secret_access_key + - s3_janitor_access_key_id + - s3_janitor_secret_access_key + - s3_admin_access_key_id + - s3_admin_secret_access_key + restart: "no" + + # Одноразовый запуск миграций: выполняется один раз до API и завершается. + migrate: + build: + context: . + target: migrate + deploy: + resources: + limits: + cpus: "0.5" + memory: 128M + environment: + DATABASE_URL_FILE: /run/secrets/database_url + secrets: + - database_url + # Миграции начинаются только после готовности БД. + depends_on: + postgres: + condition: service_healthy + # Завершение — штатный итог, перезапускать его не нужно. + restart: "no" + + # Реплики API. Нет container_name и опубликованных портов: сервис масштабируется, а весь трафик + # идёт через LB. Своего состояния у реплик нет. + api: + # target не указан: собирается последний этап Dockerfile. APP_BUILD — метка версии для rolling update. + build: + context: . + args: + APP_BUILD: ${APP_BUILD:-dev} + env_file: .env + deploy: + # Лимиты указаны на одну реплику: при N репликах суммарно N × лимит. + replicas: ${API_REPLICAS:-2} + resources: + limits: + cpus: "1.0" + # Запас под полное декодирование изображения 40 Мп и дисковый кэш временных файлов; замер в REPORT.md. + memory: 1G + # Больше, чем APP_SHUTDOWN_DRAIN_MS + APP_SHUTDOWN_TIMEOUT_MS (3 с + 10 с), иначе Docker пришлёт SIGKILL. + stop_grace_period: 15s + environment: + S3_PUBLIC_ENDPOINT: ${S3_PUBLIC_ENDPOINT:-http://127.0.0.1:19090} + SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} + HISTORY_CACHE: ${HISTORY_CACHE:-off} + HISTORY_CACHE_TTL_SECONDS: ${HISTORY_CACHE_TTL_SECONDS:-30} + HISTORY_CACHE_FILL_DELAY_MS: ${HISTORY_CACHE_FILL_DELAY_MS:-0} + # Подключений к БД на одну реплику: 8 реплик × 10 меньше max_connections (100). + DB_MAX_CONNS: ${DB_MAX_CONNS:-10} + # Выключает bitmap scan в БД. Обоснование в app/internal/config/database.go; замеров, + # подтверждающих это, сейчас в evidence нет. + DB_ENABLE_BITMAPSCAN: ${DB_ENABLE_BITMAPSCAN:-false} + # Цепочка согласована с infra/haproxy/haproxy.cfg, расчёт в REPORT.md. + # Мягкий предел для сборщика мусора и порог защиты от перегрузки: оба ниже лимита контейнера. + GOMEMLIMIT: 800MiB + APP_MAX_HEAP_BYTES: 805306368 + APP_READ_TIMEOUT_MS: 10000 # = timeout http-request LB + APP_WRITE_TIMEOUT_MS: 10000 # < timeout server LB (15 с): 504 от LB не опережает ответ API + APP_IDLE_TIMEOUT_MS: 60000 # > keep-alive LB (30 с): API не закрывает соединение первым + APP_SHUTDOWN_DRAIN_MS: 3000 # > вывода по readiness (2 проверки * 1 с) + APP_SHUTDOWN_TIMEOUT_MS: 10000 # = APP_WRITE_TIMEOUT_MS: запрос успевает завершиться + secrets: + - database_url + - cache_url + - s3_access_key_id + - s3_secret_access_key + # Старт только после готовности хранилищ и успешных миграций. depends_on задаёт лишь порядок + # запуска: выводить упавшую реплику из работы должен LB. + depends_on: + postgres: + condition: service_healthy + valkey: + condition: service_healthy + migrate: + condition: service_completed_successfully + s3-init: + condition: service_completed_successfully + restart: unless-stopped + + # Балансировщик: единственная публичная точка входа. Настройки в infra/haproxy/haproxy.cfg. + lb: + image: haproxy:3.2.9-alpine + deploy: + resources: + limits: + cpus: "1.0" + memory: 256M + # Конфигурация только для чтения. + volumes: + - ./infra/haproxy/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro + # Без адреса: порт открыт на всех интерфейсах хоста, в том числе в локальной сети. + ports: + - "${API_PUBLISH_PORT:-8080}:8080" + # Ждать готовности реплик не нужно: LB сам проверяет их и не шлёт трафик на неготовые. + depends_on: + api: + condition: service_started + # Проверяет сам LB, а не реплики: порт 8404 доступен только внутри контейнера. + healthcheck: + test: ["CMD", "wget", "--quiet", "--spider", "http://127.0.0.1:8404/health"] + interval: 5s + timeout: 3s + retries: 5 + start_period: 5s + restart: unless-stopped + + # Генератор нагрузки в той же сети: без накладных расходов проброса портов Docker Desktop. + loadgen: + profiles: ["bench"] + build: + context: . + target: loadgen + deploy: + resources: + limits: + cpus: "4.0" + memory: 1G + # Каталог для результатов замеров. + volumes: + - ./evidence:/evidence + restart: "no" + +# internal: у этой сети нет выхода наружу. В ней только SeaweedFS и его шлюз. +networks: + s3-private: + internal: true + +# Именованные тома только у хранилищ. Реплики API томов не используют. +volumes: + pgdata: + valkeydata: + s3data: diff --git a/evidence/level3.txt b/evidence/level3.txt new file mode 100644 index 00000000..1865dd51 --- /dev/null +++ b/evidence/level3.txt @@ -0,0 +1,151 @@ +date: 2026-11-04T20:36:02Z +commit: ec540a1+dirty +host: Darwin arm64, docker 29.2.1, Python 3.13.7 + +=== Контракт: make check +.venv/bin/python scripts/check_contract.py +PASS: offline skeleton structure, local refs and Python syntax; application NOT tested. + +=== Контракт: make validate +.venv/bin/python scripts/validate_openapi.py +PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested. + +=== Модульные тесты: go vet, go test +ok gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/cmd/loadgen 0.548s +ok gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/e2e 0.699s +ok gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http 3.637s +ok gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto 1.426s +ok gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/cache 1.678s +ok gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/config 2.579s +ok gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/imagecheck 1.785s +ok gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/janitor 1.991s +ok gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/password 1.247s +ok gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store/db 2.377s +ok gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/token 1.603s +ok gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate 2.161s + +=== Стенд и версии образов +api: mtusi-lab4-api Up 2 minutes (healthy) +api: mtusi-lab4-api Up 2 minutes (healthy) +janitor: mtusi-lab4-janitor Up 3 minutes +lb: haproxy:3.2.9-alpine Up 3 minutes (healthy) +migrate: mtusi-lab4-migrate Exited (0) About a minute ago +postgres: postgres:17.6-alpine Up 3 minutes (healthy) +s3-gateway: haproxy:3.2.9-alpine Up 3 minutes (healthy) +s3-init: mtusi-lab4-s3-init Exited (0) About a minute ago +s3: chrislusf/seaweedfs:4.00 Up 3 minutes (healthy) +valkey: valkey/valkey:8.1.3-alpine Up 3 minutes (healthy) +опубликованные порты: +lb: 8080/tcp на [::]:18080;8080/tcp на 0.0.0.0:18080; +postgres: 5432/tcp на 127.0.0.1:15432; +valkey: 6379/tcp на 127.0.0.1:16379; + +=== Публичный smoke: make test +.venv/bin/python tests/smoke.py --base-url "http://localhost:18080" +PASS: lab4 public API scenario; infrastructure and grading evidence remain separate. + +=== Негативные и граничные сценарии +ok файл на байт больше лимита -> 413 payload_too_large +ok размеры на пиксель больше лимита -> 413 payload_too_large +ok «бомба» 100000x100000 -> 413 payload_too_large +ok chunked: файл на байт больше лимита -> 413 payload_too_large +ok заголовок PNG без пикселей -> 415 unsupported_media_type +ok обрезанный PNG -> 415 unsupported_media_type +ok изменённый байт PNG -> 415 unsupported_media_type +ok обрезанный JPEG -> 415 unsupported_media_type +ok JPEG: только сигнатура -> 415 unsupported_media_type +ok текст вместо картинки -> 415 unsupported_media_type +ok пустое тело -> 415 unsupported_media_type +ok подмена: объявлен JPEG, внутри PNG -> 415 unsupported_media_type +ok подмена: объявлен PNG, внутри JPEG -> 415 unsupported_media_type +ok неподдерживаемый Content-Type -> 415 unsupported_media_type +ok опасное имя '../etc/passwd' -> 400 invalid_request +ok опасное имя 'a\\b.png' -> 400 invalid_request +ok опасное имя 'a\x00.png' -> 400 invalid_request +ok опасное имя 'a\nb.png' -> 400 invalid_request +ok опасное имя '..' -> 400 invalid_request +ok опасное имя ' ' -> 400 invalid_request +ok опасное имя 'xxxxxxxxxxxxxxxx' -> 400 invalid_request +ok посторонний загружает в чужой чат -> 404 not_found +ok посторонний: размер не важнее доступа -> 404 not_found +ok файл ровно 10 MiB принят и скачан побайтно +ok JPEG с именем не ASCII принят и скачан, SHA-256 совпал +ok посторонний 404, без сессии 401, неверный UUID 400, несуществующий 404 +ok вложение чужого чата 404, чужой пользователь 404, неизвестное 404, пустое сообщение 400, дубли 400, смешанный список без записи +ok второй участник читает сообщение, порядок вложений сохранён +PASS: attachment negative and boundary scenarios + +=== Байты лежат в S3, а метаданные в PostgreSQL +колонки attachments: +id:uuid, chat_id:uuid, owner_id:uuid, filename:text, content_type:text, size_bytes:bigint, sha256:text, object_key:text, status:text, created_at:timestamp with time zone, updated_at:timestamp with time zone +PostgreSQL: size=111817 sha256=99ea7533c441f79cd630d15ce4d58d1ec4e06f6f0efb3b77a5c088305cd1bd75 +объект в S3: sha256=99ea7533c441f79cd630d15ce4d58d1ec4e06f6f0efb3b77a5c088305cd1bd75 +PASS: SHA-256 объекта в хранилище равен записи в БД + +=== Bucket приватный: запросы без подписи из сети стенда +GET объекта: HTTP/1.1 403 Forbidden +GET списка: HTTP/1.1 403 Forbidden +служебные порты SeaweedFS отдают файлы без подписи, поэтому должны быть закрыты: + 8888: wget: can't connect to remote host (172.20.0.4): Connection + 8080: wget: can't connect to remote host (172.20.0.4): Connection + 9333: wget: can't connect to remote host (172.20.0.4): Connection +PASS: прямой доступ отклонён + +=== На API нет локального файла оригинала +e05701592599: изменённых файлов=0, томов=0 +1b5c7434a309: изменённых файлов=0, томов=0 +PASS: у реплик нет томов, файлов от загрузок на диске нет, изменены только /tmp и точки монтирования секретов + +=== Failover: остановка реплики, обслужившей загрузку, для каждой реплики +upload served by replica e05701592599 status 201 +replica e05701592599 stopped +downloaded 5 times via ['1b5c7434a309'] in 0.021s, SHA-256 matches +PASS: file survives stop of the replica that uploaded it +реплика e05701592599 возвращена +upload served by replica 1b5c7434a309 status 201 +replica 1b5c7434a309 stopped +downloaded 5 times via ['e05701592599'] in 0.021s, SHA-256 matches +PASS: file survives stop of the replica that uploaded it +реплика 1b5c7434a309 возвращена + +=== Публичный failover: make test-failover +.venv/bin/python tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://localhost:18080" +Executing explicit failover hook; hook output suppressed to avoid leaking secrets. +{"observed_instances_before": 2, "successful_writes": 137, "failed_attempts": 0, "first_recovery_seconds": 3.22} +PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence. + +=== Отказ S3 +s3 stopped +upload without S3 503 in 7.49s +download without S3 503 in 3.76s +metadata without S3 200 in 0.00s +text message without S3 201 in 0.01s +readiness without S3 200 in 0.00s +download recovered in 23.9s after start, bytes match +upload works again +PASS: S3 outage is contained to attachments and loses no data + +=== Сохранность при перезапуске всего стенда: make test-persistence +до: +api started=2026-11-04T20:36:15.313781718Z volumes= +api started=2026-11-04T20:36:54.141346708Z volumes= +janitor started=2026-11-04T20:32:48.197555595Z volumes= +lb started=2026-11-04T20:32:48.42127547Z volumes= +postgres started=2026-11-04T20:32:21.928744638Z volumes=mtusi-lab4_pgdata +s3 started=2026-11-04T20:37:15.666762177Z volumes=mtusi-lab4_s3data +s3-gateway started=2026-11-04T20:32:21.91828893Z volumes= +valkey started=2026-11-04T20:32:21.929235722Z volumes=mtusi-lab4_valkeydata +.venv/bin/python tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://localhost:18080" +Executing explicit persistence hook; hook output suppressed to avoid leaking secrets. +PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence. +после: +api started=2026-11-04T20:38:08.957091299Z volumes= +api started=2026-11-04T20:38:09.054190299Z volumes= +janitor started=2026-11-04T20:38:08.94445509Z volumes= +lb started=2026-11-04T20:38:09.162717299Z volumes= +postgres started=2026-11-04T20:37:47.694000886Z volumes=mtusi-lab4_pgdata +s3 started=2026-11-04T20:37:47.69261822Z volumes=mtusi-lab4_s3data +s3-gateway started=2026-11-04T20:37:47.683603136Z volumes= +valkey started=2026-11-04T20:37:47.694250095Z volumes=mtusi-lab4_valkeydata + +ИТОГ: все шаги уровня 3 пройдены diff --git a/evidence/level4.txt b/evidence/level4.txt new file mode 100644 index 00000000..66c36c83 --- /dev/null +++ b/evidence/level4.txt @@ -0,0 +1,191 @@ +date: 2026-11-04T20:38:15Z +commit: ec540a1+dirty +host: Darwin arm64, docker 29.2.1, Python 3.13.7 + +=== Модульные тесты отказов и очистителя +--- PASS: TestRun_DeletesOnlyExpiredOrphans (0.00s) +--- PASS: TestRun_GraceBoundaryIsKept (0.00s) +--- PASS: TestRun_UnknownTimeIsTreatedAsFresh (0.00s) +--- PASS: TestRun_DryRunDeletesNothing (0.00s) +--- PASS: TestRun_MetadataFailureDeletesNothing (0.00s) +--- PASS: TestRun_ListFailureIsReported (0.00s) +--- PASS: TestRun_TooManyOrphansDeletesNothing (0.00s) +--- PASS: TestRun_ChecksMetadataInBatches (0.00s) +PASS +ok gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/janitor 0.856s +--- PASS: TestAttachment_Rejections (0.01s) +--- PASS: TestMessage_AttachmentRules (0.00s) +--- PASS: TestAttachment_MetadataFailureRemovesObject (0.00s) +--- PASS: TestAttachment_LostCommitKeepsObject (0.00s) +--- PASS: TestAttachment_UncheckableMetadataLeavesObjectToJanitor (0.00s) +--- PASS: TestAttachment_InterruptedUploadLeavesNothing (0.00s) +--- PASS: TestAttachment_TemporaryFileIsRemovedWhileUploadIsRunning (0.00s) +--- PASS: TestAttachment_ChunkedOverLimitGives413 (0.00s) +PASS +ok gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http 1.113s + +=== Отрицательные сценарии: слишком большой файл, повреждение, подмена MIME, чужое вложение, файл другого чата +ok файл на байт больше лимита -> 413 payload_too_large +ok размеры на пиксель больше лимита -> 413 payload_too_large +ok «бомба» 100000x100000 -> 413 payload_too_large +ok chunked: файл на байт больше лимита -> 413 payload_too_large +ok заголовок PNG без пикселей -> 415 unsupported_media_type +ok обрезанный PNG -> 415 unsupported_media_type +ok изменённый байт PNG -> 415 unsupported_media_type +ok обрезанный JPEG -> 415 unsupported_media_type +ok JPEG: только сигнатура -> 415 unsupported_media_type +ok текст вместо картинки -> 415 unsupported_media_type +ok пустое тело -> 415 unsupported_media_type +ok подмена: объявлен JPEG, внутри PNG -> 415 unsupported_media_type +ok подмена: объявлен PNG, внутри JPEG -> 415 unsupported_media_type +ok неподдерживаемый Content-Type -> 415 unsupported_media_type +ok опасное имя '../etc/passwd' -> 400 invalid_request +ok опасное имя 'a\\b.png' -> 400 invalid_request +ok опасное имя 'a\x00.png' -> 400 invalid_request +ok опасное имя 'a\nb.png' -> 400 invalid_request +ok опасное имя '..' -> 400 invalid_request +ok опасное имя ' ' -> 400 invalid_request +ok опасное имя 'xxxxxxxxxxxxxxxx' -> 400 invalid_request +ok посторонний загружает в чужой чат -> 404 not_found +ok посторонний: размер не важнее доступа -> 404 not_found +ok файл ровно 10 MiB принят и скачан побайтно +ok JPEG с именем не ASCII принят и скачан, SHA-256 совпал +ok посторонний 404, без сессии 401, неверный UUID 400, несуществующий 404 +ok вложение чужого чата 404, чужой пользователь 404, неизвестное 404, пустое сообщение 400, дубли 400, смешанный список без записи +ok второй участник читает сообщение, порядок вложений сохранён +PASS: attachment negative and boundary scenarios + +=== Bootstrap bucket идемпотентен: двойной запуск на существующем bucket с данными +s3init: bucket is ready and private +s3init: bucket is ready and private +объектов до: 774, после двух запусков: 774 +PASS: повторная подготовка завершается успешно и не меняет объекты + +=== Права S3 и приватность bucket мимо API +== Ключ подготовки (admin) +ok создать временный чужой bucket разрешено +ok записать объект в чужой bucket разрешено +== Ключ API: только объекты своего bucket +ok PUT объекта в свой bucket разрешено +ok GET объекта из своего bucket разрешено +ok LIST своего bucket запрещено (AccessDenied) +ok PUT вне префикса originals/ запрещено (AccessDenied) +ok GET из чужого bucket запрещено (AccessDenied) +ok PUT в чужой bucket запрещено (AccessDenied) +ok DELETE из чужого bucket запрещено (AccessDenied) +ok создать bucket запрещено (AccessDenied) +ok удалить bucket запрещено (AccessDenied) +ok сделать bucket публичным (policy) запрещено (AccessDenied) +ok прочитать policy bucket запрещено (AccessDenied) +== Ключ очистителя: листинг и удаление, без чтения содержимого +ok LIST своего bucket разрешено +ok GET содержимого объекта запрещено (AccessDenied) +ok LIST чужого bucket запрещено (AccessDenied) +ok PUT вне префикса originals/ запрещено (AccessDenied) +ok сделать bucket публичным (policy) запрещено (AccessDenied) +ok создать bucket запрещено (AccessDenied) +ok удалить чужой bucket запрещено (AccessDenied) +ok DELETE объекта в своём bucket разрешено +== Политика bucket: не задана, доступ только по ключам +ok прочитать политику ключом администратора разрешено +ok политика пуста 0 байт +== Без подписи: приватность вне API +ok GET объекта HTTP 403 +ok HEAD объекта HTTP 403 +ok GET списка объектов HTTP 403 +ok GET списка bucket HTTP 403 +ok PUT объекта HTTP 403 +ok DELETE объекта HTTP 403 +== Служебные порты SeaweedFS из сети стенда (шлюз пропускает только 9000) +ok порт 19000 закрыт +ok порт 8888 закрыт +ok порт 8080 закрыт +ok порт 9333 закрыт +ok порт 18888 закрыт +ok порт 18080 закрыт +ok порт 19333 закрыт +ok порт 8333 закрыт +ok порт 8111 закрыт +ok порт 23646 закрыт +ok SeaweedFS напрямую, минуя шлюз (s3-storage:9000) недоступен + +PASS: права S3 ограничены, bucket приватен, служебные порты закрыты + +=== Секреты по сервисам: ключ администратора есть только у s3-init +api: cache_url database_url s3_access_key_id s3_secret_access_key +janitor: database_url s3_janitor_access_key_id s3_janitor_secret_access_key +PASS: у API и очистителя нет ключа администратора + +=== Служебные интерфейсы SeaweedFS не открыты в сети +опубликованные на хосте порты: s3=[] s3-gateway=[] +сети контейнера s3: mtusi-lab4_s3-private +внутренняя сеть (internal=true): mtusi-lab4-s3-gateway-1 mtusi-lab4-s3-1 +порты внутри контейнера s3 (доступны только из внутренней сети, кроме 127.0.0.1): + :::19000 + :::9000 + 127.0.0.1:18080 + 127.0.0.1:18888 + 127.0.0.1:19333 + 127.0.0.1:8080 + 127.0.0.1:8888 + 127.0.0.1:9333 +порты шлюза на всех интерфейсах: + 0.0.0.0:9000 +PASS: из сети стенда доступен только порт S3 через шлюз; консоли master и filer привязаны к 127.0.0.1 + +=== Отказы между S3 и PostgreSQL +== Исходное состояние +очиститель, только отчёт просмотрено=776 свежих=124 со строкой=652 без строки=0 удалено=0 +== 1. Отказ БД между PUT и INSERT: компенсация +INSERT заблокирован: клиент получил 503 за 3.0 с +после компенсации просмотрено=776 свежих=124 со строкой=652 без строки=0 удалено=0 +ok объект удалён сразу, строки нет, очиститель не понадобился +== 2. Падение процесса между PUT и INSERT: kill -9 +реплики убиты SIGKILL: клиент получил обрыв соединения +сразу после падения, grace 1 ч просмотрено=777 свежих=125 со строкой=652 без строки=0 удалено=0 +ok объект без строки есть в bucket, но он моложе grace period: не тронут +через 60 с, только отчёт просмотрено=778 свежих=1 со строкой=776 без строки=1 удалено=0 +ok только отчёт: объект найден, ничего не удалено +через 60 с, очистка просмотрено=778 свежих=1 со строкой=776 без строки=1 удалено=1 +повторный проход просмотрено=777 свежих=1 со строкой=776 без строки=0 удалено=0 +ok объект удалён, повтор ничего не меняет; файл сообщения, файл без сообщения и свежий файл скачиваются, SHA-256 совпал +== 3. Обрыв загрузки клиентом +после 40 оборванных загрузок просмотрено=777 свежих=125 со строкой=652 без строки=0 удалено=0 +ok объектов и строк не прибавилось, каталог временных файлов пуст на всех репликах +ok слоты не утекли: следующие загрузки проходят +итог: объектов 781, строк 781 +PASS: failures between S3 and PostgreSQL leave no unaccounted objects +последний проход постоянно работающего очистителя: +{"time":"2026-11-04T20:38:09.068666715Z","level":"INFO","msg":"janitor pass","service":"messenger","env":"lab","version":"dev","report":{"scanned":770,"fresh":118,"referenced":652,"skipped":0,"orphans":0,"deleted":0,"delete_failed":0,"dry_run":false},"elapsed":25372000,"err":null} + +=== Память: 16 одновременных загрузок файлов 10 МиБ, потоковая обработка +файл: 10484238 байт, одновременно: 16, раундов: 3 +длительность 10.0 с; 201=48, 429=0; опросов памяти: 28 +время успешной загрузки: p50=2.91 с, p95=4.16 с, max=4.16 с +реплика 36d40687b8c2: anon до 43 МиБ, пик anon 51 МиБ, memory.peak 140 МиБ, упоров в лимит 0, oom_kill=0, перезапусков=0 +реплика a3c97c7103a7: anon до 44 МиБ, пик anon 51 МиБ, memory.peak 129 МиБ, упоров в лимит 0, oom_kill=0, перезапусков=0 +PASS: concurrent uploads caused no OOM or restart + +=== Память: 24 одновременных загрузок файлов 10 МиБ, потоковая обработка +файл: 10484238 байт, одновременно: 24, раундов: 3 +длительность 16.2 с; 201=72, 429=0; опросов памяти: 46 +время успешной загрузки: p50=4.21 с, p95=4.79 с, max=7.62 с +реплика 0639ee930798: anon до 44 МиБ, пик anon 51 МиБ, memory.peak 184 МиБ, упоров в лимит 0, oom_kill=0, перезапусков=0 +реплика 5dae1c6de275: anon до 43 МиБ, пик anon 54 МиБ, memory.peak 179 МиБ, упоров в лимит 0, oom_kill=0, перезапусков=0 +PASS: concurrent uploads caused no OOM or restart + +=== Память: худшие допустимые файлы, JPEG 40 Мп +до загрузок + 9c3c4c6b8613: anon 0, memory.peak 47 МиБ, упоров в лимит 0, oom_kill=0 + fb14d4eae946: anon 44, memory.peak 47 МиБ, упоров в лимит 0, oom_kill=0 +4 x JPEG 40 Мп, progressive 4:4:4 + 9c3c4c6b8613: anon 784, memory.peak 789 МиБ, упоров в лимит 0, oom_kill=0 + fb14d4eae946: anon 738, memory.peak 768 МиБ, упоров в лимит 0, oom_kill=0 +24 одновременные загрузки JPEG 40 Мп по 10 МиБ: 201=23, 429=1 (очередь на декодирование) +после параллельных загрузок + 9c3c4c6b8613: anon 784, memory.peak 936 МиБ, упоров в лимит 0, oom_kill=0 + fb14d4eae946: anon 794, memory.peak 916 МиБ, упоров в лимит 0, oom_kill=0 +OOMKilled=false, RestartCount=0 у всех реплик, readiness 200 +PASS: no OOM or restart, anonymous memory stays below the 1024 MiB container limit + +ИТОГ: все шаги уровня 4 пройдены diff --git a/evidence/level5-direct.txt b/evidence/level5-direct.txt new file mode 100644 index 00000000..ccddb6ba --- /dev/null +++ b/evidence/level5-direct.txt @@ -0,0 +1,9 @@ +PASS: auth, membership/owner/chat, limit, missing PUT, tampered token/key, checksum, size, invalid image, retry, overwrite protection +mode size_bytes api_rx_bytes api_tx_bytes anon_before_MiB anon_peak_MiB +proxy 1048576 1057362 1060683 43.5 43.5 +direct 1048576 1058909 1061230 43.5 43.52 +proxy 8388608 8450669 8436929 43.51 43.56 +direct 8388608 8433327 8431340 43.56 43.59 +Waiting for real signature/ticket expiration... +PASS: expired PUT -> 403; abandoned upload complete after 120s -> 409; no ready metadata created +Abandoned staging key (janitor after grace): /messenger-attachments/originals/cf889b11-076d-4b38-8b9e-703312208239 diff --git a/evidence/manual-checks.txt b/evidence/manual-checks.txt new file mode 100644 index 00000000..30cf359c --- /dev/null +++ b/evidence/manual-checks.txt @@ -0,0 +1,6 @@ +date: 2026-11-04T19:06:59Z, ручные проверки на потоковом коде +медленная загрузка 10 МиБ, curl --limit-rate 420k: 201 24.387781 +медленное скачивание, байты совпали: True 200 24.333690 +тело 100 МиБ, curl: 413 1.359797 +JPEG 8000x5000: HTTP 201 за 0.20 с +JPEG 8000x5001: HTTP 413 за 0.01 с diff --git a/evidence/memory-baseline-level3.txt b/evidence/memory-baseline-level3.txt new file mode 100644 index 00000000..0bbe6c04 --- /dev/null +++ b/evidence/memory-baseline-level3.txt @@ -0,0 +1,8 @@ +date: 2026-11-04T18:29:51Z +код: буферизация файла в RAM (уровень 3), MAX_CONCURRENT_UPLOADS=8, реплики перезапущены перед замером +файл: 10484238 байт, одновременно: 16, раундов: 3 +длительность 12.5 с; 201=48, 429=0; опросов памяти: 34 +время успешной загрузки: p50=4.19 с, p95=4.50 с, max=4.50 с +реплика c09dfb5cf3c3: anon до 44 МиБ, пик anon 205 МиБ, memory.peak 218 МиБ, OOM=false, перезапусков=0 +реплика b1fa3a609870: anon до 43 МиБ, пик anon 204 МиБ, memory.peak 218 МиБ, OOM=false, перезапусков=0 +PASS: concurrent uploads stayed within the container limit diff --git a/evidence/memory-peak.txt b/evidence/memory-peak.txt new file mode 100644 index 00000000..c14d7c6f --- /dev/null +++ b/evidence/memory-peak.txt @@ -0,0 +1,12 @@ +до загрузок + 9c3c4c6b8613: anon 0, memory.peak 47 МиБ, упоров в лимит 0, oom_kill=0 + fb14d4eae946: anon 44, memory.peak 47 МиБ, упоров в лимит 0, oom_kill=0 +4 x JPEG 40 Мп, progressive 4:4:4 + 9c3c4c6b8613: anon 784, memory.peak 789 МиБ, упоров в лимит 0, oom_kill=0 + fb14d4eae946: anon 738, memory.peak 768 МиБ, упоров в лимит 0, oom_kill=0 +24 одновременные загрузки JPEG 40 Мп по 10 МиБ: 201=23, 429=1 (очередь на декодирование) +после параллельных загрузок + 9c3c4c6b8613: anon 784, memory.peak 936 МиБ, упоров в лимит 0, oom_kill=0 + fb14d4eae946: anon 794, memory.peak 916 МиБ, упоров в лимит 0, oom_kill=0 +OOMKilled=false, RestartCount=0 у всех реплик, readiness 200 +PASS: no OOM or restart, anonymous memory stays below the 1024 MiB container limit diff --git a/evidence/recheck.txt b/evidence/recheck.txt new file mode 100644 index 00000000..31d7c6e6 --- /dev/null +++ b/evidence/recheck.txt @@ -0,0 +1,395 @@ +Перепроверка 2026-11-05 + +OpenAPI сохранён без изменений. Уровень 3 пройден. +Полный повтор уровня 4 НЕ завершён: остановлен пользователем во время ожидания grace period. +В первом прогоне обнаружен лимит внутренних томов SeaweedFS; конфигурация исправлена. +В повторном прогоне права S3, приватность bucket и компенсация отказа БД прошли. +Стенд и проверки остановлены; новые проверки при очистке evidence не запускались. + +=== Контракт и JSON Schema === +.venv/bin/python scripts/check_contract.py +PASS: offline skeleton structure, local refs and Python syntax; application NOT tested. +.venv/bin/python scripts/validate_openapi.py +PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested. + +=== Go-тесты с проверкой гонок данных === +? gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/cmd/janitor [no test files] +ok gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/cmd/loadgen 1.834s +? gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/cmd/messenger [no test files] +? gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/cmd/s3check [no test files] +? gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/cmd/s3init [no test files] +ok gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/e2e 2.018s +ok gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http 5.459s +ok gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto 2.486s +? gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/middleware [no test files] +ok gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/cache 3.830s +ok gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/config 3.611s +? gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain [no test files] +ok gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/imagecheck 3.417s +ok gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/janitor 3.018s +? gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/logging [no test files] +? gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/objectstore [no test files] +ok gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/password 3.814s +ok gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/service 3.959s +? gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/session [no test files] +? gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store [no test files] +ok gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store/db 4.347s +ok gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/token 4.131s +ok gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate 2.857s + +=== Исходный OpenAPI и маршруты === +PASS: mandatory OpenAPI matches HEAD byte-for-byte; all 14 mandatory operations implemented. +Only two additional routes: direct upload init/complete (separate optional flow). + +=== Реальные ответы обязательного API по OpenAPI === +PASS: lab4 public API scenario; infrastructure and grading evidence remain separate. +DELETE /api/v1/auth/sessions/current -> 204: 1 checked +DELETE /api/v1/auth/sessions/current -> 401: 1 checked +GET /api/v1/attachments/{attachment_id} -> 404: 1 checked +GET /api/v1/attachments/{attachment_id}/content -> 200: 1 checked +GET /api/v1/attachments/{attachment_id}/content -> 404: 1 checked +GET /api/v1/chats -> 200: 2 checked +GET /api/v1/chats/{chat_id} -> 404: 1 checked +GET /api/v1/chats/{chat_id}/messages -> 200: 2 checked +GET /api/v1/chats/{chat_id}/messages -> 400: 1 checked +GET /api/v1/users/me -> 200: 2 checked +GET /api/v1/users/me -> 401: 4 checked +GET /health/live -> 200: 1 checked +GET /health/ready -> 200: 1 checked +POST /api/v1/auth/sessions -> 201: 3 checked +POST /api/v1/auth/sessions -> 401: 1 checked +POST /api/v1/chats -> 201: 1 checked +POST /api/v1/chats/{chat_id}/attachments -> 201: 1 checked +POST /api/v1/chats/{chat_id}/messages -> 201: 4 checked +POST /api/v1/chats/{chat_id}/messages -> 400: 2 checked +POST /api/v1/chats/{chat_id}/messages -> 404: 1 checked +POST /api/v1/chats/{chat_id}/messages -> 409: 1 checked +POST /api/v1/users -> 201: 3 checked +POST /api/v1/users -> 409: 1 checked +PASS: actual request/response schemas, formats, headers and statuses match OpenAPI; 14 operations, 37 exchanges + +=== Негативные сценарии вложений по OpenAPI === +ok файл на байт больше лимита -> 413 payload_too_large +ok размеры на пиксель больше лимита -> 413 payload_too_large +ok «бомба» 100000x100000 -> 413 payload_too_large +ok chunked: файл на байт больше лимита -> 413 payload_too_large +ok заголовок PNG без пикселей -> 415 unsupported_media_type +ok обрезанный PNG -> 415 unsupported_media_type +ok изменённый байт PNG -> 415 unsupported_media_type +ok обрезанный JPEG -> 415 unsupported_media_type +ok JPEG: только сигнатура -> 415 unsupported_media_type +ok текст вместо картинки -> 415 unsupported_media_type +ok пустое тело -> 415 unsupported_media_type +ok подмена: объявлен JPEG, внутри PNG -> 415 unsupported_media_type +ok подмена: объявлен PNG, внутри JPEG -> 415 unsupported_media_type +ok неподдерживаемый Content-Type -> 415 unsupported_media_type +ok опасное имя '../etc/passwd' -> 400 invalid_request +ok опасное имя 'a\\b.png' -> 400 invalid_request +ok опасное имя 'a\x00.png' -> 400 invalid_request +ok опасное имя 'a\nb.png' -> 400 invalid_request +ok опасное имя '..' -> 400 invalid_request +ok опасное имя ' ' -> 400 invalid_request +ok опасное имя 'xxxxxxxxxxxxxxxx' -> 400 invalid_request +ok посторонний загружает в чужой чат -> 404 not_found +ok посторонний: размер не важнее доступа -> 404 not_found +ok файл ровно 10 MiB принят и скачан побайтно +ok JPEG с именем не ASCII принят и скачан, SHA-256 совпал +ok посторонний 404, без сессии 401, неверный UUID 400, несуществующий 404 +ok вложение чужого чата 404, чужой пользователь 404, неизвестное 404, пустое сообщение 400, дубли 400, смешанный список без записи +ok второй участник читает сообщение, порядок вложений сохранён +PASS: attachment negative and boundary scenarios +GET /api/v1/attachments/{attachment_id} -> 400: 1 checked +GET /api/v1/attachments/{attachment_id} -> 401: 1 checked +GET /api/v1/attachments/{attachment_id} -> 404: 3 checked +GET /api/v1/attachments/{attachment_id}/content -> 200: 2 checked +GET /api/v1/attachments/{attachment_id}/content -> 401: 1 checked +GET /api/v1/attachments/{attachment_id}/content -> 404: 2 checked +GET /api/v1/chats/{chat_id}/messages -> 200: 3 checked +GET /health/live -> 200: 1 checked +GET /health/ready -> 200: 1 checked +POST /api/v1/auth/sessions -> 201: 3 checked +POST /api/v1/chats -> 201: 3 checked +POST /api/v1/chats/{chat_id}/attachments -> 201: 4 checked +POST /api/v1/chats/{chat_id}/attachments -> 400: 7 checked +POST /api/v1/chats/{chat_id}/attachments -> 404: 2 checked +POST /api/v1/chats/{chat_id}/attachments -> 413: 4 checked +POST /api/v1/chats/{chat_id}/attachments -> 415: 10 checked +POST /api/v1/chats/{chat_id}/messages -> 201: 1 checked +POST /api/v1/chats/{chat_id}/messages -> 400: 2 checked +POST /api/v1/chats/{chat_id}/messages -> 404: 4 checked +POST /api/v1/users -> 201: 3 checked +PASS: actual request/response schemas, formats, headers and statuses match OpenAPI; 10 operations, 58 exchanges + +=== Полный повтор уровня 3 — завершён === +2026-11-05T16:13:33Z + +=== Обязательный API: smoke +python3 tests/smoke.py --base-url "http://localhost:18080" +PASS: lab4 public API scenario; infrastructure and grading evidence remain separate. + +=== Идемпотентность через две реплики +=== RUN TestLBSameKeyConcurrentlyThroughReplicas + lb_idempotency_test.go:226: раундов: 20, запросов в раунде: 16, запросов по репликам: map[c22aef97d79c:160 e2494da1a4f7:160], сообщений в истории: 20 +--- PASS: TestLBSameKeyConcurrentlyThroughReplicas (0.24s) +PASS +ok gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/e2e 0.979s + +=== Загрузка → остановка обслужившей реплики → скачивание через другую +upload served by replica c22aef97d79c status 201 +replica c22aef97d79c stopped +downloaded 5 times via ['e2494da1a4f7'] in 0.019s, SHA-256 matches +PASS: file survives stop of the replica that uploaded it +STOPPED=c22aef97d79c +upload served by replica e2494da1a4f7 status 201 +replica e2494da1a4f7 stopped +downloaded 5 times via ['c22aef97d79c'] in 0.029s, SHA-256 matches +PASS: file survives stop of the replica that uploaded it +STOPPED=e2494da1a4f7 + +=== Публичный failover: сообщения и файл +python3 tests/resilience.py --mode failover --action-script "scripts/stop-one.sh" --base-url "http://localhost:18080" +Executing explicit failover hook; hook output suppressed to avoid leaking secrets. +{"observed_instances_before": 2, "successful_writes": 136, "failed_attempts": 0, "first_recovery_seconds": 3.19} +PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence. + +=== Недоступность S3 и восстановление +s3 stopped +upload without S3 503 in 8.01s +download without S3 503 in 5.42s +metadata without S3 200 in 0.01s +text message without S3 201 in 0.01s +readiness without S3 200 in 0.00s +download recovered in 23.7s after start, bytes match +upload works again +PASS: S3 outage is contained to attachments and loses no data + +=== Перезапуск всего стенда: файл, метаданные, прежний токен +python3 tests/resilience.py --mode persistence --action-script "scripts/restart.sh" --base-url "http://localhost:18080" +Executing explicit persistence hook; hook output suppressed to avoid leaking secrets. +PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence. + +=== Итоговый smoke +python3 tests/smoke.py --base-url "http://localhost:18080" +PASS: lab4 public API scenario; infrastructure and grading evidence remain separate. +ИТОГ: все шаги уровня 3 пройдены + +=== Повтор уровня 4 — ОСТАНОВЛЕН пользователем до завершения === +date: 2026-11-05T16:24:45Z +commit: ec540a1+dirty +host: Darwin arm64, docker 29.2.1, Python 3.13.7 + +=== Модульные тесты отказов и очистителя +=== RUN TestRun_DeletesOnlyExpiredOrphans +--- PASS: TestRun_DeletesOnlyExpiredOrphans (0.00s) +=== RUN TestRun_GraceBoundaryIsKept +--- PASS: TestRun_GraceBoundaryIsKept (0.00s) +=== RUN TestRun_UnknownTimeIsTreatedAsFresh +--- PASS: TestRun_UnknownTimeIsTreatedAsFresh (0.00s) +=== RUN TestRun_DryRunDeletesNothing +--- PASS: TestRun_DryRunDeletesNothing (0.00s) +=== RUN TestRun_MetadataFailureDeletesNothing +--- PASS: TestRun_MetadataFailureDeletesNothing (0.00s) +=== RUN TestRun_ListFailureIsReported +--- PASS: TestRun_ListFailureIsReported (0.00s) +=== RUN TestRun_TooManyOrphansDeletesNothing +--- PASS: TestRun_TooManyOrphansDeletesNothing (0.00s) +=== RUN TestRun_ChecksMetadataInBatches +--- PASS: TestRun_ChecksMetadataInBatches (0.00s) +PASS +ok gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/janitor 0.170s +=== RUN TestAttachment_Rejections +=== RUN TestAttachment_Rejections/outsider +=== RUN TestAttachment_Rejections/outsider_sees_404_before_size_check +=== RUN TestAttachment_Rejections/unknown_chat +=== RUN TestAttachment_Rejections/bad_chat_id +=== RUN TestAttachment_Rejections/path_in_filename +=== RUN TestAttachment_Rejections/backslash_in_filename +=== RUN TestAttachment_Rejections/NUL_in_filename +=== RUN TestAttachment_Rejections/empty_filename +=== RUN TestAttachment_Rejections/too_many_bytes +=== RUN TestAttachment_Rejections/too_many_pixels +=== RUN TestAttachment_Rejections/wrong_declared_type +=== RUN TestAttachment_Rejections/no_declared_type +=== RUN TestAttachment_Rejections/declared_jpeg,_actual_png +=== RUN TestAttachment_Rejections/declared_png,_actual_jpeg +=== RUN TestAttachment_Rejections/not_an_image +=== RUN TestAttachment_Rejections/truncated +=== RUN TestAttachment_Rejections/empty_body +--- PASS: TestAttachment_Rejections (0.01s) + --- PASS: TestAttachment_Rejections/outsider (0.00s) + --- PASS: TestAttachment_Rejections/outsider_sees_404_before_size_check (0.00s) + --- PASS: TestAttachment_Rejections/unknown_chat (0.00s) + --- PASS: TestAttachment_Rejections/bad_chat_id (0.00s) + --- PASS: TestAttachment_Rejections/path_in_filename (0.00s) + --- PASS: TestAttachment_Rejections/backslash_in_filename (0.00s) + --- PASS: TestAttachment_Rejections/NUL_in_filename (0.00s) + --- PASS: TestAttachment_Rejections/empty_filename (0.00s) + --- PASS: TestAttachment_Rejections/too_many_bytes (0.00s) + --- PASS: TestAttachment_Rejections/too_many_pixels (0.00s) + --- PASS: TestAttachment_Rejections/wrong_declared_type (0.00s) + --- PASS: TestAttachment_Rejections/no_declared_type (0.00s) + --- PASS: TestAttachment_Rejections/declared_jpeg,_actual_png (0.00s) + --- PASS: TestAttachment_Rejections/declared_png,_actual_jpeg (0.00s) + --- PASS: TestAttachment_Rejections/not_an_image (0.00s) + --- PASS: TestAttachment_Rejections/truncated (0.00s) + --- PASS: TestAttachment_Rejections/empty_body (0.00s) +=== RUN TestMessage_AttachmentRules +=== RUN TestMessage_AttachmentRules/empty_text_with_attachment +=== RUN TestMessage_AttachmentRules/spaces_with_attachment +=== RUN TestMessage_AttachmentRules/empty_attachment_list_is_the_old_form +=== RUN TestMessage_AttachmentRules/empty_text_without_attachments +=== RUN TestMessage_AttachmentRules/text_is_still_required +=== RUN TestMessage_AttachmentRules/null_list +=== RUN TestMessage_AttachmentRules/wrong_type +=== RUN TestMessage_AttachmentRules/invalid_id +=== RUN TestMessage_AttachmentRules/duplicate +=== RUN TestMessage_AttachmentRules/unknown_attachment +=== RUN TestMessage_AttachmentRules/attachment_of_another_chat +--- PASS: TestMessage_AttachmentRules (0.00s) + --- PASS: TestMessage_AttachmentRules/empty_text_with_attachment (0.00s) + --- PASS: TestMessage_AttachmentRules/spaces_with_attachment (0.00s) + --- PASS: TestMessage_AttachmentRules/empty_attachment_list_is_the_old_form (0.00s) + --- PASS: TestMessage_AttachmentRules/empty_text_without_attachments (0.00s) + --- PASS: TestMessage_AttachmentRules/text_is_still_required (0.00s) + --- PASS: TestMessage_AttachmentRules/null_list (0.00s) + --- PASS: TestMessage_AttachmentRules/wrong_type (0.00s) + --- PASS: TestMessage_AttachmentRules/invalid_id (0.00s) + --- PASS: TestMessage_AttachmentRules/duplicate (0.00s) + --- PASS: TestMessage_AttachmentRules/unknown_attachment (0.00s) + --- PASS: TestMessage_AttachmentRules/attachment_of_another_chat (0.00s) +=== RUN TestAttachment_MetadataFailureRemovesObject +--- PASS: TestAttachment_MetadataFailureRemovesObject (0.00s) +=== RUN TestAttachment_LostCommitKeepsObject +--- PASS: TestAttachment_LostCommitKeepsObject (0.00s) +=== RUN TestAttachment_UncheckableMetadataLeavesObjectToJanitor +--- PASS: TestAttachment_UncheckableMetadataLeavesObjectToJanitor (0.00s) +=== RUN TestAttachment_InterruptedUploadLeavesNothing +--- PASS: TestAttachment_InterruptedUploadLeavesNothing (0.00s) +=== RUN TestAttachment_TemporaryFileIsRemovedWhileUploadIsRunning +--- PASS: TestAttachment_TemporaryFileIsRemovedWhileUploadIsRunning (0.00s) +=== RUN TestAttachment_ChunkedOverLimitGives413 +--- PASS: TestAttachment_ChunkedOverLimitGives413 (0.00s) +PASS +ok gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http 0.313s + +=== Отрицательные сценарии: слишком большой файл, повреждение, подмена MIME, чужое вложение, файл другого чата +ok файл на байт больше лимита -> 413 payload_too_large +ok размеры на пиксель больше лимита -> 413 payload_too_large +ok «бомба» 100000x100000 -> 413 payload_too_large +ok chunked: файл на байт больше лимита -> 413 payload_too_large +ok заголовок PNG без пикселей -> 415 unsupported_media_type +ok обрезанный PNG -> 415 unsupported_media_type +ok изменённый байт PNG -> 415 unsupported_media_type +ok обрезанный JPEG -> 415 unsupported_media_type +ok JPEG: только сигнатура -> 415 unsupported_media_type +ok текст вместо картинки -> 415 unsupported_media_type +ok пустое тело -> 415 unsupported_media_type +ok подмена: объявлен JPEG, внутри PNG -> 415 unsupported_media_type +ok подмена: объявлен PNG, внутри JPEG -> 415 unsupported_media_type +ok неподдерживаемый Content-Type -> 415 unsupported_media_type +ok опасное имя '../etc/passwd' -> 400 invalid_request +ok опасное имя 'a\\b.png' -> 400 invalid_request +ok опасное имя 'a\x00.png' -> 400 invalid_request +ok опасное имя 'a\nb.png' -> 400 invalid_request +ok опасное имя '..' -> 400 invalid_request +ok опасное имя ' ' -> 400 invalid_request +ok опасное имя 'xxxxxxxxxxxxxxxx' -> 400 invalid_request +ok посторонний загружает в чужой чат -> 404 not_found +ok посторонний: размер не важнее доступа -> 404 not_found +ok файл ровно 10 MiB принят и скачан побайтно +ok JPEG с именем не ASCII принят и скачан, SHA-256 совпал +ok посторонний 404, без сессии 401, неверный UUID 400, несуществующий 404 +ok вложение чужого чата 404, чужой пользователь 404, неизвестное 404, пустое сообщение 400, дубли 400, смешанный список без записи +ok второй участник читает сообщение, порядок вложений сохранён +PASS: attachment negative and boundary scenarios + +=== Bootstrap bucket идемпотентен: двойной запуск на существующем bucket с данными +s3init: bucket is ready and private +s3init: bucket is ready and private +объектов до: 989, после двух запусков: 989 +PASS: повторная подготовка завершается успешно и не меняет объекты + +=== Права S3 и приватность bucket мимо API +== Ключ подготовки (admin) +ok создать временный чужой bucket разрешено +ok записать объект в чужой bucket разрешено +== Ключ API: только объекты своего bucket +ok PUT объекта в свой bucket разрешено +ok GET объекта из своего bucket разрешено +ok LIST своего bucket запрещено (AccessDenied) +ok PUT вне префикса originals/ запрещено (AccessDenied) +ok GET из чужого bucket запрещено (AccessDenied) +ok PUT в чужой bucket запрещено (AccessDenied) +ok DELETE из чужого bucket запрещено (AccessDenied) +ok создать bucket запрещено (AccessDenied) +ok удалить bucket запрещено (AccessDenied) +ok сделать bucket публичным (policy) запрещено (AccessDenied) +ok прочитать policy bucket запрещено (AccessDenied) +== Ключ очистителя: листинг и удаление, без чтения содержимого +ok LIST своего bucket разрешено +ok GET содержимого объекта запрещено (AccessDenied) +ok LIST чужого bucket запрещено (AccessDenied) +ok PUT вне префикса originals/ запрещено (AccessDenied) +ok сделать bucket публичным (policy) запрещено (AccessDenied) +ok создать bucket запрещено (AccessDenied) +ok удалить чужой bucket запрещено (AccessDenied) +ok DELETE объекта в своём bucket разрешено +== Политика bucket: не задана, доступ только по ключам +ok прочитать политику ключом администратора разрешено +ok политика пуста 0 байт +== Без подписи: приватность вне API +ok GET объекта HTTP 403 +ok HEAD объекта HTTP 403 +ok GET списка объектов HTTP 403 +ok GET списка bucket HTTP 403 +ok PUT объекта HTTP 403 +ok DELETE объекта HTTP 403 +== Служебные порты SeaweedFS из сети стенда (шлюз пропускает только 9000) +ok порт 19000 закрыт +ok порт 8888 закрыт +ok порт 8080 закрыт +ok порт 9333 закрыт +ok порт 18888 закрыт +ok порт 18080 закрыт +ok порт 19333 закрыт +ok порт 8333 закрыт +ok порт 8111 закрыт +ok порт 23646 закрыт +ok SeaweedFS напрямую, минуя шлюз (s3-storage:9000) недоступен + +PASS: права S3 ограничены, bucket приватен, служебные порты закрыты + +=== Секреты по сервисам: ключ администратора есть только у s3-init +api: cache_url database_url s3_access_key_id s3_secret_access_key +janitor: database_url s3_janitor_access_key_id s3_janitor_secret_access_key +PASS: у API и очистителя нет ключа администратора + +=== Служебные интерфейсы SeaweedFS не открыты в сети +опубликованные на хосте порты: s3=[] s3-gateway=[9000/tcp -> 127.0.0.1:19090;] +сети контейнера s3: mtusi-lab4_s3-private +внутренняя сеть (internal=true): mtusi-lab4-s3-gateway-1 mtusi-lab4-s3-1 +порты внутри контейнера s3 (доступны только из внутренней сети, кроме 127.0.0.1): + 127.0.0.1:18080 + 127.0.0.1:18888 + 127.0.0.1:19333 + 127.0.0.1:8080 + 127.0.0.1:8888 + 127.0.0.1:9333 + :::19000 + :::9000 +порты шлюза на всех интерфейсах: + 0.0.0.0:9000 +PASS: из сети стенда доступен только порт S3 через шлюз; консоли master и filer привязаны к 127.0.0.1 + +=== Отказы между S3 и PostgreSQL +== Очистка старых объектов от предыдущих прогонов +старые неучтённые объекты просмотрено=991 свежих=15 со строкой=958 без строки=18 удалено=18 +== Исходное состояние +очиститель, только отчёт просмотрено=973 свежих=45 со строкой=928 без строки=0 удалено=0 +== 1. Отказ БД между PUT и INSERT: компенсация +INSERT заблокирован: клиент получил 503 за 3.0 с +после компенсации просмотрено=973 свежих=45 со строкой=928 без строки=0 удалено=0 +ok объект удалён сразу, строки нет, очиститель не понадобился +== 2. Падение процесса между PUT и INSERT: kill -9 +реплики убиты SIGKILL: клиент получил обрыв соединения +сразу после падения, grace 1 ч просмотрено=974 свежих=46 со строкой=928 без строки=0 удалено=0 diff --git a/infra/haproxy/haproxy.cfg b/infra/haproxy/haproxy.cfg new file mode 100644 index 00000000..99fae45d --- /dev/null +++ b/infra/haproxy/haproxy.cfg @@ -0,0 +1,54 @@ +global + log stdout format raw local0 info + +resolvers docker + nameserver dns 127.0.0.11:53 + accepted_payload_size 8192 + resolve_retries 3 + timeout resolve 1s + timeout retry 1s + hold valid 5s + hold obsolete 5s + +defaults + mode http + log global + option httplog + option dontlognull + + retries 2 + retry-on conn-failure + option redispatch 1 + + timeout connect 500ms + timeout client 30s + timeout server 15s + timeout http-request 10s + timeout http-keep-alive 30s + timeout queue 5s + timeout check 1500ms + + # Ответы самого LB в формате контракта: схема Error и X-Request-Id, совпадающий с request_id. + # Контракт разрешает таким ответам не иметь X-Instance-Id. Ответы реплик эти правила не меняют. + http-error status 502 content-type application/json hdr X-Request-Id "%[var(txn.request_id)]" lf-string '{"error":{"code":"unavailable","message":"Service temporarily unavailable","request_id":"%[var(txn.request_id)]"}}' + http-error status 503 content-type application/json hdr X-Request-Id "%[var(txn.request_id)]" lf-string '{"error":{"code":"unavailable","message":"Service temporarily unavailable","request_id":"%[var(txn.request_id)]"}}' + http-error status 504 content-type application/json hdr X-Request-Id "%[var(txn.request_id)]" lf-string '{"error":{"code":"unavailable","message":"Service temporarily unavailable","request_id":"%[var(txn.request_id)]"}}' + +frontend public + bind :8080 + # Идентификатор для ответов самого LB. У ответов реплик свой X-Request-Id. + http-request set-var(txn.request_id) uuid() + default_backend api + +backend api + balance roundrobin + option httpchk GET /health/ready + http-check expect status 200 + default-server check init-state down inter 1s fall 2 rise 2 observe layer4 error-limit 2 on-error mark-down resolvers docker init-addr none resolve-prefer ipv4 + server-template api 1-8 api:8080 + +frontend stats + bind 127.0.0.1:8404 + monitor-uri /health + stats enable + stats uri /stats diff --git a/infra/s3-gateway/haproxy.cfg b/infra/s3-gateway/haproxy.cfg new file mode 100644 index 00000000..d8974ec5 --- /dev/null +++ b/infra/s3-gateway/haproxy.cfg @@ -0,0 +1,37 @@ +# Единственный путь к SeaweedFS из сети стенда: пропускает только порт S3 (9000). +# Нужен потому, что флаг -s3.ip.bind открывает на всех интерфейсах и служебный gRPC-порт шлюза 19000, +# отдельно его не закрыть. Сам SeaweedFS находится во внутренней сети, куда входит только этот шлюз. +# Режим TCP: подпись S3 проверяет сервер, заголовок Host не меняется. + +global + log stdout format raw local0 warning + +resolvers docker + nameserver dns 127.0.0.11:53 + hold valid 2s + hold obsolete 2s + timeout resolve 1s + timeout retry 1s + +defaults + log global + timeout connect 1s + # Больше передачи файла в API (60 с). + timeout client 90s + timeout server 90s + +frontend s3 + mode tcp + bind :9000 + default_backend storage + +backend storage + mode tcp + # Имя s3-storage существует только во внутренней сети. После перезапуска адрес определяется заново. + default-server check inter 1s fall 2 rise 1 init-addr none resolvers docker resolve-prefer ipv4 + server s3 s3-storage:9000 + +frontend health + mode http + bind 127.0.0.1:8405 + monitor-uri /health diff --git a/infra/seaweedfs/master.toml b/infra/seaweedfs/master.toml new file mode 100644 index 00000000..cffbcc04 --- /dev/null +++ b/infra/seaweedfs/master.toml @@ -0,0 +1,4 @@ +# Allocate one volume at a time for this single-node teaching setup. +# The default batch of seven quickly exhausts volume slots across buckets. +[master.volume_growth] +copy_1 = 1 diff --git a/migrations/00001_create_users_table.sql b/migrations/00001_create_users_table.sql new file mode 100644 index 00000000..34e3184d --- /dev/null +++ b/migrations/00001_create_users_table.sql @@ -0,0 +1,22 @@ +-- +goose Up +-- +goose StatementBegin +CREATE TABLE users ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + username text NOT NULL, + display_name text NOT NULL, + -- Строка password KDF (Argon2id/scrypt) вместе с солью и параметрами; никогда не отдаётся в API. + password_hash text NOT NULL, + created_at timestamptz NOT NULL DEFAULT now(), + + CONSTRAINT users_username_key UNIQUE (username), + CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9_]{3,32}$'), + CONSTRAINT users_display_name_len CHECK (char_length(display_name) BETWEEN 1 AND 100 + AND btrim(display_name) <> ''), + CONSTRAINT users_password_hash_not_empty CHECK (password_hash <> '') +); +-- +goose StatementEnd + +-- +goose Down +-- +goose StatementBegin +DROP TABLE IF EXISTS users; +-- +goose StatementEnd diff --git a/migrations/00002_create_chats_table.sql b/migrations/00002_create_chats_table.sql new file mode 100644 index 00000000..7b5cdd4d --- /dev/null +++ b/migrations/00002_create_chats_table.sql @@ -0,0 +1,16 @@ +-- +goose Up +-- +goose StatementBegin +CREATE TABLE chats ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + title text NOT NULL, + created_at timestamptz NOT NULL DEFAULT now(), + + CONSTRAINT chats_title_len CHECK (char_length(title) BETWEEN 1 AND 100 + AND btrim(title) <> '') +); +-- +goose StatementEnd + +-- +goose Down +-- +goose StatementBegin +DROP TABLE IF EXISTS chats; +-- +goose StatementEnd diff --git a/migrations/00003_create_chat_members_table.sql b/migrations/00003_create_chat_members_table.sql new file mode 100644 index 00000000..91aaf572 --- /dev/null +++ b/migrations/00003_create_chat_members_table.sql @@ -0,0 +1,16 @@ +-- +goose Up +-- +goose StatementBegin +CREATE TABLE chat_members ( + chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE, + user_id uuid NOT NULL REFERENCES users (id) ON DELETE RESTRICT, + + CONSTRAINT chat_members_pkey PRIMARY KEY (chat_id, user_id) +); + +CREATE INDEX chat_members_user_id_chat_id_idx ON chat_members (user_id, chat_id); +-- +goose StatementEnd + +-- +goose Down +-- +goose StatementBegin +DROP TABLE IF EXISTS chat_members; +-- +goose StatementEnd diff --git a/migrations/00004_create_messages_table.sql b/migrations/00004_create_messages_table.sql new file mode 100644 index 00000000..4466222f --- /dev/null +++ b/migrations/00004_create_messages_table.sql @@ -0,0 +1,25 @@ +-- +goose Up +-- +goose StatementBegin +CREATE TABLE messages ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + chat_id uuid NOT NULL, + sender_id uuid NOT NULL, + text text NOT NULL, + created_at timestamptz NOT NULL DEFAULT now(), + + -- Отправитель обязан быть участником этого чата: FK на пару из chat_members. + CONSTRAINT messages_chat_member_fkey FOREIGN KEY (chat_id, sender_id) + REFERENCES chat_members (chat_id, user_id) ON DELETE RESTRICT, + CONSTRAINT messages_text_len CHECK (char_length(text) BETWEEN 1 AND 4000) +); + +-- История чата с keyset-пагинацией: +-- WHERE chat_id = $1 AND (created_at, id) > ($2, $3) ORDER BY created_at, id LIMIT $4 +-- Индекс отдаёт страницу без полного scan и без сортировки. +CREATE INDEX messages_chat_id_created_at_id_idx ON messages (chat_id, created_at, id); +-- +goose StatementEnd + +-- +goose Down +-- +goose StatementBegin +DROP TABLE IF EXISTS messages; +-- +goose StatementEnd diff --git a/migrations/00005_escape_nul_in_text.sql b/migrations/00005_escape_nul_in_text.sql new file mode 100644 index 00000000..2aede12c --- /dev/null +++ b/migrations/00005_escape_nul_in_text.sql @@ -0,0 +1,45 @@ +-- PostgreSQL text не хранит U+0000, а контракт допускает его в display_name, +-- title и text. Приложение пишет эти поля экранированными: `\` → `\\`, +-- U+0000 → `\0` (app/internal/store/db/text.go). Ограничения длины проверяют +-- раскодированное значение: regexp_replace(x, '\\(.)', '\1', 'g') сворачивает +-- каждую escape-пару в один символ, поэтому char_length совпадает с числом +-- code points исходной строки. + +-- +goose Up +-- +goose StatementBegin +ALTER TABLE users DROP CONSTRAINT users_display_name_len; +ALTER TABLE chats DROP CONSTRAINT chats_title_len; +ALTER TABLE messages DROP CONSTRAINT messages_text_len; + +UPDATE users SET display_name = replace(display_name, '\', '\\') WHERE strpos(display_name, '\') > 0; +UPDATE chats SET title = replace(title, '\', '\\') WHERE strpos(title, '\') > 0; +UPDATE messages SET text = replace(text, '\', '\\') WHERE strpos(text, '\') > 0; + +ALTER TABLE users ADD CONSTRAINT users_display_name_len + CHECK (char_length(regexp_replace(display_name, '\\(.)', '\1', 'g')) BETWEEN 1 AND 100 + AND btrim(regexp_replace(display_name, '\\(.)', '\1', 'g')) <> ''); +ALTER TABLE chats ADD CONSTRAINT chats_title_len + CHECK (char_length(regexp_replace(title, '\\(.)', '\1', 'g')) BETWEEN 1 AND 100 + AND btrim(regexp_replace(title, '\\(.)', '\1', 'g')) <> ''); +ALTER TABLE messages ADD CONSTRAINT messages_text_len + CHECK (char_length(regexp_replace(text, '\\(.)', '\1', 'g')) BETWEEN 1 AND 4000); +-- +goose StatementEnd + +-- +goose Down +-- Откат с потерей: U+0000 непредставим в text и превращается в '0'. +-- +goose StatementBegin +ALTER TABLE users DROP CONSTRAINT users_display_name_len; +ALTER TABLE chats DROP CONSTRAINT chats_title_len; +ALTER TABLE messages DROP CONSTRAINT messages_text_len; + +UPDATE users SET display_name = regexp_replace(display_name, '\\(.)', '\1', 'g') WHERE strpos(display_name, '\') > 0; +UPDATE chats SET title = regexp_replace(title, '\\(.)', '\1', 'g') WHERE strpos(title, '\') > 0; +UPDATE messages SET text = regexp_replace(text, '\\(.)', '\1', 'g') WHERE strpos(text, '\') > 0; + +ALTER TABLE users ADD CONSTRAINT users_display_name_len + CHECK (char_length(display_name) BETWEEN 1 AND 100 AND btrim(display_name) <> ''); +ALTER TABLE chats ADD CONSTRAINT chats_title_len + CHECK (char_length(title) BETWEEN 1 AND 100 AND btrim(title) <> ''); +ALTER TABLE messages ADD CONSTRAINT messages_text_len + CHECK (char_length(text) BETWEEN 1 AND 4000); +-- +goose StatementEnd diff --git a/migrations/00006_create_cache_invalidations_table.sql b/migrations/00006_create_cache_invalidations_table.sql new file mode 100644 index 00000000..852dddb9 --- /dev/null +++ b/migrations/00006_create_cache_invalidations_table.sql @@ -0,0 +1,23 @@ +-- Отложенная инвалидация кэша истории. Если после COMMIT сообщения сброс +-- версии чата в Valkey не удался, строка фиксирует долг до ответа 201 и +-- переживает рестарт API. gen берётся из общей последовательности и при +-- каждом новом сбое получает ещё не выданное значение: строку удаляет только +-- тот повтор, который видел актуальный gen (compare-and-delete). Счётчик +-- внутри строки не годится: после удаления строки он начался бы снова с 1. + +-- +goose Up +-- +goose StatementBegin +CREATE SEQUENCE cache_invalidations_gen_seq; + +CREATE TABLE cache_invalidations ( + chat_id uuid PRIMARY KEY REFERENCES chats (id) ON DELETE CASCADE, + gen bigint NOT NULL DEFAULT nextval('cache_invalidations_gen_seq'), + updated_at timestamptz NOT NULL DEFAULT now() +); +-- +goose StatementEnd + +-- +goose Down +-- +goose StatementBegin +DROP TABLE IF EXISTS cache_invalidations; +DROP SEQUENCE IF EXISTS cache_invalidations_gen_seq; +-- +goose StatementEnd diff --git a/migrations/00007_create_message_idempotency_keys_table.sql b/migrations/00007_create_message_idempotency_keys_table.sql new file mode 100644 index 00000000..e4c1b49d --- /dev/null +++ b/migrations/00007_create_message_idempotency_keys_table.sql @@ -0,0 +1,32 @@ +-- Идемпотентность отправки сообщений, общая для всех реплик API. +-- Область ключа: пользователь + чат + ключ (метод и путь у эндпоинта фиксированы). +-- Строка ключа и сообщение пишутся одной транзакцией: конкурентный INSERT с тем же +-- ключом ждёт её завершения и после COMMIT получает конфликт, после ROLLBACK — вставляет. +-- FK на chat_members не даёт появиться ключу постороннего, поэтому существующий ключ +-- означает, что вызывающий — участник чата. Это и есть проверка доступа при повторе. +-- FK на messages отложенный: ключ вставляется первым, чтобы захватить право на запись. + +-- +goose Up +-- +goose StatementBegin +CREATE TABLE message_idempotency_keys ( + user_id uuid NOT NULL, + chat_id uuid NOT NULL, + key text NOT NULL, + message_id uuid NOT NULL, + created_at timestamptz NOT NULL DEFAULT now(), + + PRIMARY KEY (user_id, chat_id, key), + CONSTRAINT message_idempotency_keys_member_fkey FOREIGN KEY (chat_id, user_id) + REFERENCES chat_members (chat_id, user_id) ON DELETE RESTRICT, + CONSTRAINT message_idempotency_keys_message_fkey FOREIGN KEY (message_id) + REFERENCES messages (id) ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED +); + +-- Для удаления ключей старше срока хранения. +CREATE INDEX message_idempotency_keys_created_at_idx ON message_idempotency_keys (created_at); +-- +goose StatementEnd + +-- +goose Down +-- +goose StatementBegin +DROP TABLE IF EXISTS message_idempotency_keys; +-- +goose StatementEnd diff --git a/migrations/00008_create_attachments_tables.sql b/migrations/00008_create_attachments_tables.sql new file mode 100644 index 00000000..f752e24f --- /dev/null +++ b/migrations/00008_create_attachments_tables.sql @@ -0,0 +1,69 @@ +-- Вложения: метаданные живут здесь, байты — в приватном S3-bucket (object_key назначает сервер). +-- Составные FK гарантируют на уровне БД: загрузил участник чата, а сообщение ссылается только +-- на вложения своего чата. Поэтому чужое вложение в сообщении невозможно даже при ошибке в коде. +-- Текст сообщения теперь может быть пустым: правило «пустой текст только с вложением» проверяет +-- приложение, потому что вложения пишутся отдельной таблицей. + +-- +goose Up +-- +goose StatementBegin +CREATE TABLE attachments ( + id uuid PRIMARY KEY, + chat_id uuid NOT NULL, + owner_id uuid NOT NULL, + filename text NOT NULL, + content_type text NOT NULL, + size_bytes bigint NOT NULL, + sha256 text NOT NULL, + object_key text NOT NULL, + status text NOT NULL DEFAULT 'ready', + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now(), + + CONSTRAINT attachments_member_fkey FOREIGN KEY (chat_id, owner_id) + REFERENCES chat_members (chat_id, user_id) ON DELETE RESTRICT, + CONSTRAINT attachments_chat_id_id_key UNIQUE (chat_id, id), + CONSTRAINT attachments_object_key_key UNIQUE (object_key), + CONSTRAINT attachments_filename_len CHECK (char_length(filename) BETWEEN 1 AND 255), + CONSTRAINT attachments_content_type CHECK (content_type IN ('image/png', 'image/jpeg')), + CONSTRAINT attachments_size CHECK (size_bytes BETWEEN 1 AND 10485760), + CONSTRAINT attachments_sha256 CHECK (sha256 ~ '^[a-f0-9]{64}$'), + CONSTRAINT attachments_status CHECK (status = 'ready') +); + +ALTER TABLE messages ADD CONSTRAINT messages_id_chat_id_key UNIQUE (id, chat_id); + +-- position сохраняет порядок attachment_ids из запроса: повтор POST и чтение истории возвращают +-- тот же порядок. +CREATE TABLE message_attachments ( + message_id uuid NOT NULL, + chat_id uuid NOT NULL, + attachment_id uuid NOT NULL, + position int NOT NULL, + + PRIMARY KEY (message_id, attachment_id), + CONSTRAINT message_attachments_position_key UNIQUE (message_id, position), + CONSTRAINT message_attachments_message_fkey FOREIGN KEY (message_id, chat_id) + REFERENCES messages (id, chat_id) ON DELETE CASCADE, + CONSTRAINT message_attachments_attachment_fkey FOREIGN KEY (chat_id, attachment_id) + REFERENCES attachments (chat_id, id) ON DELETE RESTRICT +); + +CREATE INDEX message_attachments_chat_id_attachment_id_idx ON message_attachments (chat_id, attachment_id); + +ALTER TABLE messages DROP CONSTRAINT messages_text_len; +ALTER TABLE messages ADD CONSTRAINT messages_text_len + CHECK (char_length(regexp_replace(text, '\\(.)', '\1', 'g')) <= 4000); +-- +goose StatementEnd + +-- +goose Down +-- Откат удаляет только метаданные: объекты в bucket остаются. Сообщения без текста получают +-- заполнитель, иначе прежнее ограничение нельзя вернуть. +-- +goose StatementBegin +UPDATE messages SET text = '(attachment)' WHERE text = ''; +ALTER TABLE messages DROP CONSTRAINT messages_text_len; +ALTER TABLE messages ADD CONSTRAINT messages_text_len + CHECK (char_length(regexp_replace(text, '\\(.)', '\1', 'g')) BETWEEN 1 AND 4000); +DROP TABLE message_attachments; +ALTER TABLE messages DROP CONSTRAINT messages_id_chat_id_key; +DROP TABLE attachments; +-- +goose StatementEnd diff --git a/scripts/init-secrets.sh b/scripts/init-secrets.sh new file mode 100755 index 00000000..acc1aeae --- /dev/null +++ b/scripts/init-secrets.sh @@ -0,0 +1,108 @@ +#!/bin/sh +# Создаёт локальные секреты стенда в каталоге secrets/ (он в .gitignore). Запускается один раз +# на чистом clone, до первого docker compose up: compose.yaml читает секреты из этих файлов. +# +# Запуск из любого каталога: sh scripts/init-secrets.sh +# Настройки через окружение: POSTGRES_USER, POSTGRES_DB (по умолчанию messenger). +# Повторный запуск безопасен: непустые файлы не перезаписываются, значения секретов не печатаются. +# Не удаляйте пароль при существующих томах: PostgreSQL задаёт пароль только при создании своего +# тома, и новый пароль с ним не совпадёт. + +# -e: выйти при ошибке команды; -u: считать ошибкой неизвестную переменную. +set -eu + +# Перейти в корень проекта: все пути ниже указаны относительно него. +cd "$(dirname "$0")/.." +DIR=secrets +# Должны совпадать с POSTGRES_USER и POSTGRES_DB сервиса postgres в compose.yaml. +DB_USER="${POSTGRES_USER:-messenger}" +DB_NAME="${POSTGRES_DB:-messenger}" + +# Новые файлы и каталог сразу доступны только владельцу: секрет не открыт ни на миг. +umask 077 +mkdir -p "$DIR" + +# Пароль PostgreSQL: 24 случайных байта в hex. -s: файла нет или он пуст. +if [ ! -s "$DIR/postgres_password" ]; then + # hex, чтобы пароль не требовал URL-экранирования в DSN. + od -An -tx1 -N24 /dev/urandom | tr -d ' \n' > "$DIR/postgres_password" + echo "init-secrets: created $DIR/postgres_password" +fi + +# Строка подключения к БД для API и migrate. Хост postgres — имя сервиса в сети Compose. +# TLS выключен: подключение идёт только внутри сети учебного стенда. +if [ ! -s "$DIR/database_url" ]; then + pw="$(cat "$DIR/postgres_password")" + printf 'postgres://%s:%s@postgres:5432/%s?sslmode=disable' "$DB_USER" "$pw" "$DB_NAME" > "$DIR/database_url" + echo "init-secrets: created $DIR/database_url" +fi + +# Пароль Valkey, в котором хранятся сессии. +if [ ! -s "$DIR/valkey_password" ]; then + od -An -tx1 -N24 /dev/urandom | tr -d ' \n' > "$DIR/valkey_password" + echo "init-secrets: created $DIR/valkey_password" +fi + +# Адрес хранилища сессий для API. +if [ ! -s "$DIR/cache_url" ]; then + pw="$(cat "$DIR/valkey_password")" + printf 'redis://:%s@valkey:6379/0' "$pw" > "$DIR/cache_url" + echo "init-secrets: created $DIR/cache_url" +fi + +# Пароль отдельного Valkey для кэша истории (необязательный профиль). Перевод строки в кавычках +# ниже — это символ для удаления, как \n в блоках выше. +if [ ! -s "$DIR/valkey_cache_password" ]; then + od -An -tx1 -N24 /dev/urandom | tr -d ' +' > "$DIR/valkey_cache_password" + echo "init-secrets: created $DIR/valkey_cache_password" +fi + +# Адрес кэша истории для API. +if [ ! -s "$DIR/history_cache_url" ]; then + pw="$(cat "$DIR/valkey_cache_password")" + printf 'redis://:%s@valkey-cache:6379/0' "$pw" > "$DIR/history_cache_url" + echo "init-secrets: created $DIR/history_cache_url" +fi + +# Ключи S3, отдельные на каждую роль. Hex: значения не требуют экранирования в JSON. +# s3_* — API; s3_janitor_* — очиститель; s3_admin_* — только подготовка bucket (s3-init). +for role in s3 s3_janitor s3_admin; do + if [ ! -s "$DIR/${role}_access_key_id" ]; then + od -An -tx1 -N10 /dev/urandom | tr -d ' \n' > "$DIR/${role}_access_key_id" + echo "init-secrets: created $DIR/${role}_access_key_id" + fi + if [ ! -s "$DIR/${role}_secret_access_key" ]; then + od -An -tx1 -N20 /dev/urandom | tr -d ' \n' > "$DIR/${role}_secret_access_key" + echo "init-secrets: created $DIR/${role}_secret_access_key" + fi +done + +# Пользователи SeaweedFS. Выводится из ключей выше и перезаписывается всегда, поэтому изменение прав +# здесь применяется и к уже созданному стенду (после перезапуска сервиса s3). Секретов не добавляет. +# Отсутствие записи anonymous означает, что запрос без подписи получает отказ: bucket приватный. +# Права на запись ограничены префиксом объектов, а не bucket: в SeaweedFS Write: разрешает +# и PUT политики bucket, то есть позволил бы API сделать bucket публичным (найдено cmd/s3check). +BUCKET="$(sed -n 's/^S3_BUCKET=//p' .env 2>/dev/null || true)" +BUCKET="${BUCKET:-messenger-attachments}" +identity() { + printf '{"name":"%s","credentials":[{"accessKey":"%s","secretKey":"%s"}],"actions":[%s]}' \ + "$1" "$(cat "$DIR/$2_access_key_id")" "$(cat "$DIR/$2_secret_access_key")" "$3" +} +{ + printf '{"identities":[' + identity messenger-admin s3_admin '"Admin","Read","Write","List"' + printf ',' + identity messenger-api s3 "\"Read:$BUCKET/originals/*\",\"Write:$BUCKET/originals/*\"" + printf ',' + identity messenger-janitor s3_janitor "\"List:$BUCKET\",\"Write:$BUCKET/originals/*\"" + printf ']}' +} > "$DIR/s3_config" + +# Каталог закрыт от других пользователей хоста. Сами файлы открыты на чтение: Compose монтирует +# их в контейнеры с правами хоста, а процессы там работают не от root (API — uid 100). +chmod 0700 "$DIR" +chmod 0644 "$DIR/postgres_password" "$DIR/database_url" "$DIR/valkey_password" "$DIR/cache_url" "$DIR/valkey_cache_password" "$DIR/history_cache_url" \ + "$DIR/s3_access_key_id" "$DIR/s3_secret_access_key" \ + "$DIR/s3_janitor_access_key_id" "$DIR/s3_janitor_secret_access_key" \ + "$DIR/s3_admin_access_key_id" "$DIR/s3_admin_secret_access_key" "$DIR/s3_config" diff --git a/scripts/level3-evidence.sh b/scripts/level3-evidence.sh new file mode 100755 index 00000000..09307047 --- /dev/null +++ b/scripts/level3-evidence.sh @@ -0,0 +1,47 @@ +#!/bin/sh +# Runs the level 3 checks; stops/restarts local services, preserving volumes. +set -eu +cd "$(dirname "$0")/.." +BASE_URL="${BASE_URL:-http://localhost:8080}" +PYTHON="${PYTHON:-python3}" +OUT="${OUT:-evidence/level3.txt}" +compose() { docker compose --env-file .env "$@"; } +step() { printf '\n=== %s\n' "$1"; } +restore() { compose up -d --wait >/dev/null 2>&1; } +main() { + date -u +%Y-%m-%dT%H:%M:%SZ + step "Обязательный API: smoke" + make test PYTHON="$PYTHON" BASE_URL="$BASE_URL" + step "Идемпотентность через две реплики" + (cd app && E2E_BASE_URL="$BASE_URL" go test -count=1 -v ./e2e) + step "Загрузка → остановка обслужившей реплики → скачивание через другую" + first="" + for attempt in 1 2; do + result="$($PYTHON student-tests/upload_failover.py --base-url "$BASE_URL" --avoid-instance "$first")" + printf '%s\n' "$result" + first="$(printf '%s\n' "$result" | sed -n 's/^STOPPED=//p')" + [ -n "$first" ] + restore + done + step "Публичный failover: сообщения и файл" + make test-failover PYTHON="$PYTHON" BASE_URL="$BASE_URL" ACTION_SCRIPT=scripts/stop-one.sh + restore + step "Недоступность S3 и восстановление" + "$PYTHON" student-tests/s3_outage.py --base-url "$BASE_URL" + step "Перезапуск всего стенда: файл, метаданные, прежний токен" + make test-persistence PYTHON="$PYTHON" BASE_URL="$BASE_URL" ACTION_SCRIPT=scripts/restart.sh + step "Итоговый smoke" + make test PYTHON="$PYTHON" BASE_URL="$BASE_URL" + echo "ИТОГ: все шаги уровня 3 пройдены" +} +# Capture the exit status without a pipe to tee: a failed test must fail this script. +set +e +( set -e; main ) >"$OUT" 2>&1 +status=$? +set -e +restore || status=1 +cat "$OUT" +if [ "$status" -ne 0 ]; then + printf '\nИТОГ: ПРОВЕРКА НЕ ПРОЙДЕНА, код %s\n' "$status" | tee -a "$OUT" +fi +exit "$status" diff --git a/scripts/level4-evidence.sh b/scripts/level4-evidence.sh new file mode 100755 index 00000000..c5057f0f --- /dev/null +++ b/scripts/level4-evidence.sh @@ -0,0 +1,118 @@ +#!/bin/sh +# Прогоняет проверки уровня 4 на работающем стенде и пишет результат в evidence/level4.txt. +# Убивает и возвращает реплики API; volumes не удаляет, токены и ключи не печатает. Около 10 минут. +# Запуск: BASE_URL=http://localhost:8080 sh scripts/level4-evidence.sh +# Для замера 40 Мп нужен Pillow: .venv/bin/pip install pillow +set -eu +cd "$(dirname "$0")/.." +BASE_URL="${BASE_URL:-http://localhost:8080}" +PYTHON="${PYTHON:-python3}" +OUT="${OUT:-evidence/level4.txt}" +MEMORY_OUT="${MEMORY_OUT:-evidence/memory-peak.txt}" + +compose() { docker compose --env-file .env "$@"; } +step() { printf '\n=== %s\n' "$1"; } +objects() { compose run --rm --no-deps -T janitor -once -dry-run 2>/dev/null | sed -n 's/.*"janitor_report":{"scanned":\([0-9]*\).*/\1/p'; } +fresh_replicas() { + # memory.peak считается с запуска контейнера, поэтому каждый замер начинается с перезапуска. + compose up -d --wait --force-recreate --no-deps api >/dev/null 2>&1 + sleep 5 +} + +main() { + echo "date: $(date -u +%Y-%m-%dT%H:%M:%SZ)" + echo "commit: $(git rev-parse --short HEAD)$(test -z "$(git status --porcelain)" || echo +dirty)" + echo "host: $(uname -sm), docker $(docker version --format '{{.Server.Version}}'), $($PYTHON --version)" + + step "Модульные тесты отказов и очистителя" + (cd app && go test -count=1 -v ./internal/janitor ./internal/api/http \ + -run 'TestRun_|TestAttachment_(MetadataFailure|LostCommit|Uncheckable|Interrupted|TemporaryFile|ChunkedOverLimit|Rejections)|TestMessage_AttachmentRules' \ + ) + + step "Отрицательные сценарии: слишком большой файл, повреждение, подмена MIME, чужое вложение, файл другого чата" + "$PYTHON" student-tests/attachments.py --base-url "$BASE_URL" + + step "Bootstrap bucket идемпотентен: двойной запуск на существующем bucket с данными" + before="$(objects)" + compose run --rm --no-deps -T s3-init 2>/dev/null + compose run --rm --no-deps -T s3-init 2>/dev/null + after="$(objects)" + echo "объектов до: $before, после двух запусков: $after" + [ "$before" = "$after" ] + echo "PASS: повторная подготовка завершается успешно и не меняет объекты" + + step "Права S3 и приватность bucket мимо API" + compose --profile tools run --rm --no-deps -T s3check 2>/dev/null + + step "Секреты по сервисам: ключ администратора есть только у s3-init" + for service in api janitor; do + id="$(compose ps -q "$service" | head -n 1)" + names="$(docker inspect --format '{{range .Mounts}}{{.Destination}} {{end}}' "$id" | tr ' ' '\n' | sed -n 's|^/run/secrets/||p' | sort | tr '\n' ' ')" + echo "$service: $names" + case "$names" in *admin*) echo "FAIL: у $service есть ключ администратора"; return 1 ;; esac + done + echo "PASS: у API и очистителя нет ключа администратора" + + step "Служебные интерфейсы SeaweedFS не открыты в сети" + s3="$(compose ps -q s3)" + gateway="$(compose ps -q s3-gateway)" + echo "опубликованные на хосте порты: s3=[$(docker port "$s3" | tr '\n' ';')] s3-gateway=[$(docker port "$gateway" | tr '\n' ';')]" + [ -z "$(docker port "$s3")" ] + # Direct uploads publish only the S3 data port, bound to localhost. + if docker port "$gateway" | grep -Ev '^9000/tcp -> 127\.0\.0\.1:19090$'; then + echo "FAIL: шлюз публикует лишний порт или внешний интерфейс"; return 1 + fi + networks="$(docker inspect --format '{{range $name, $_ := .NetworkSettings.Networks}}{{$name}} {{end}}' "$s3")" + echo "сети контейнера s3: $networks" + [ "$(echo "$networks" | wc -w | tr -d ' ')" = 1 ] + network="$(echo "$networks" | tr -d ' ')" + echo "внутренняя сеть (internal=$(docker network inspect --format '{{.Internal}}' "$network")): $(docker network inspect --format '{{range .Containers}}{{.Name}} {{end}}' "$network")" + [ "$(docker network inspect --format '{{.Internal}}' "$network")" = true ] + [ "$(docker network inspect --format '{{len .Containers}}' "$network")" = 2 ] + echo "порты внутри контейнера s3 (доступны только из внутренней сети, кроме 127.0.0.1):" + docker exec "$s3" netstat -ltn 2>/dev/null | awk 'NR>2 {print " " $4}' | grep -v 127.0.0.11 | sort -u + echo "порты шлюза на всех интерфейсах:" + docker exec "$gateway" netstat -ltn 2>/dev/null | awk 'NR>2 {print $4}' | grep -v '^127\.' | sort -u | sed 's/^/ /' + if docker exec "$gateway" netstat -ltn 2>/dev/null | awk 'NR>2 {print $4}' | grep -v '^127\.' | grep -v ':9000$'; then + echo "FAIL: шлюз открывает лишний порт"; return 1 + fi + echo "PASS: из сети стенда доступен только порт S3 через шлюз; консоли master и filer привязаны к 127.0.0.1" + + step "Отказы между S3 и PostgreSQL" + "$PYTHON" student-tests/orphans.py --base-url "$BASE_URL" + echo "последний проход постоянно работающего очистителя:" + compose logs --no-log-prefix janitor 2>/dev/null | grep '"janitor pass"' | tail -n 1 + + for uploads in 16 24; do + step "Память: $uploads одновременных загрузок файлов 10 МиБ, потоковая обработка" + fresh_replicas + UPLOADS="$uploads" "$PYTHON" student-tests/memory_concurrent.py --base-url "$BASE_URL" + done + + if [ -x .venv/bin/python ] && .venv/bin/python -c 'import PIL' 2>/dev/null; then + step "Память: худшие допустимые файлы, JPEG 40 Мп" + fresh_replicas + # Без конвейера: код выхода конвейера с tee скрыл бы провал замера. + if ! .venv/bin/python student-tests/memory_peak.py --base-url "$BASE_URL" >"$MEMORY_OUT" 2>&1; then + cat "$MEMORY_OUT" + return 1 + fi + cat "$MEMORY_OUT" + fi + + compose up -d --wait >/dev/null 2>&1 + printf '\nИТОГ: все шаги уровня 4 пройдены\n' +} + +# Причины такой конструкции описаны в level3-evidence.sh. +set +e +( set -e; main ) >"$OUT" 2>&1 +status=$? +set -e +# Always restore the local stand, including when a failure test exits early. +compose up -d --wait >/dev/null 2>&1 || status=1 +cat "$OUT" +if [ "$status" -ne 0 ]; then + printf '\nИТОГ: ПРОВЕРКА НЕ ПРОЙДЕНА, код %s\n' "$status" | tee -a "$OUT" +fi +exit "$status" diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100755 index 00000000..f636c752 --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,24 @@ +#!/bin/sh +# Перезапускает API, LB и все используемые хранилища с сохранением volumes. +# Без down -v, flush и повторного seed; migrate при up повторно ничего не применяет. +# +# Вызывается тестом сохранности: make test-persistence ACTION_SCRIPT=scripts/restart.sh +# Можно запускать и вручную из любого каталога: sh scripts/restart.sh +# Стенд на время перезапуска недоступен. Удаляет данные только down -v, здесь его нет. + +# -e: выйти при ошибке команды; -u: считать ошибкой неизвестную переменную. +set -eu +# Перейти в корень проекта: compose.yaml и .env ищутся в нём. +cd "$(dirname "$0")/.." + +# docker compose с настройками стенда. +compose() { docker compose --env-file .env "$@"; } + +# Сначала точка входа и API: они перестают принимать запросы и штатно завершают открытые, +# пока БД и сессии ещё доступны. Контейнеры останавливаются, но не удаляются. +compose stop lb api janitor +# Затем хранилища: штатная остановка, тома остаются на месте. +compose stop postgres valkey s3-gateway s3 +# Запустить всё и дождаться готовности. Миграции уже применены, поэтому migrate ничего не меняет. +# Отказ на любом шаге завершит скрипт с ошибкой благодаря set -e. +compose up -d --wait diff --git a/scripts/stop-one.sh b/scripts/stop-one.sh new file mode 100755 index 00000000..065dd760 --- /dev/null +++ b/scripts/stop-one.sh @@ -0,0 +1,34 @@ +#!/bin/sh +# Останавливает одну реплику API, которую назвал тест, и оставляет её остановленной. +# TARGET_INSTANCE_ID — значение X-Instance-Id, то есть короткий ID контейнера. +# БД, сессии и LB не трогает. Восстановление: docker compose --env-file .env up -d --wait +# +# Вызывается тестом отказа: make test-failover ACTION_SCRIPT=scripts/stop-one.sh +# Вручную из любого каталога: TARGET_INSTANCE_ID=<короткий ID> sh scripts/stop-one.sh +# Код выхода: 0 — реплика остановлена, 2 — такой реплики нет. + +# -e: выйти при ошибке команды; -u: считать ошибкой неизвестную переменную. +set -eu +# Перейти в корень проекта: compose.yaml и .env ищутся в нём. +cd "$(dirname "$0")/.." + +# Без ID завершиться с этим сообщением: останавливать случайную реплику нельзя. +: "${TARGET_INSTANCE_ID:?test provides target API instance alias}" + +# Перебрать работающие API-контейнеры. Полные ID сравниваются с коротким по началу строки. +for id in $(docker compose --env-file .env ps -q api); do + case "$id" in + # Шаблон с *: совпадает полный ID, начинающийся с короткого. + "$TARGET_INSTANCE_ID"*) + # Штатная остановка: SIGTERM, реплика уходит из балансировки и завершает открытые запросы. + docker stop "$id" >/dev/null + # Первые 12 символов ID: в обычном sh нет записи ${id:0:12}. + echo "stopped api container ${id%"${id#????????????}"}" + exit 0 + ;; + esac +done + +# Сюда дошли, только если ни один контейнер не подошёл: реплика уже остановлена или ID неверный. +echo "stop-one: no running api container matches the given instance id" >&2 +exit 2 diff --git a/student-tests/attachments.py b/student-tests/attachments.py new file mode 100755 index 00000000..9ab74b1e --- /dev/null +++ b/student-tests/attachments.py @@ -0,0 +1,97 @@ +#!/usr/bin/env python3 +"""Негативные и граничные сценарии вложений через работающий стенд. Создаёт синтетические данные.""" +import hashlib +import uuid +from urllib.parse import quote + +from common import Client, MAX_BYTES, MAX_PIXELS, SAMPLE_JPEG, SAMPLE_PNG, arguments, check, png_with_size, run + + +def main(): + args = arguments('Attachment negative and boundary scenarios') + c = Client(args.base_url, args.ca_file, timeout=60) + alice, bob, eve, chat = c.bootstrap() + other = c.call('POST', '/api/v1/chats', 201, actor=alice, body={'title': 'Другой', 'member_ids': [alice['id']]}, schema='Chat')['json'] + + def upload(data, content_type='image/png', filename='a.png', actor=alice, target=chat, expected=201): + path = '/api/v1/chats/' + target['id'] + '/attachments?filename=' + quote(filename, safe='') + return c.call('POST', path, expected, actor=actor, raw=data, headers={'Content-Type': content_type}, + schema='Attachment' if expected == 201 else None) + + def rejected(name, expected, data, **kwargs): + response = upload(data, expected=expected, **kwargs) + print('ok %-44s -> %d %s' % (name, expected, response['json']['error']['code'])) + + half = SAMPLE_PNG[:len(SAMPLE_PNG) // 2] + flipped = bytearray(SAMPLE_PNG) + flipped[len(flipped) // 2] ^= 0xff + rejected('файл на байт больше лимита', 413, SAMPLE_PNG + b'\0' * (MAX_BYTES - len(SAMPLE_PNG) + 1)) + rejected('размеры на пиксель больше лимита', 413, png_with_size(MAX_PIXELS + 1, 1)) + rejected('«бомба» 100000x100000', 413, png_with_size(100000, 100000)) + # Без Content-Length размер неизвестен заранее: лимит должен сработать при чтении. + rejected('chunked: файл на байт больше лимита', 413, iter([SAMPLE_PNG, b'\0' * (MAX_BYTES - len(SAMPLE_PNG) + 1)])) + rejected('заголовок PNG без пикселей', 415, png_with_size(16, 16)) + rejected('обрезанный PNG', 415, half) + rejected('изменённый байт PNG', 415, bytes(flipped)) + rejected('обрезанный JPEG', 415, SAMPLE_JPEG[:len(SAMPLE_JPEG) // 2], content_type='image/jpeg') + rejected('JPEG: только сигнатура', 415, b'\xff\xd8\xff', content_type='image/jpeg') + rejected('текст вместо картинки', 415, b'') + rejected('пустое тело', 415, b'') + rejected('подмена: объявлен JPEG, внутри PNG', 415, SAMPLE_PNG, content_type='image/jpeg') + rejected('подмена: объявлен PNG, внутри JPEG', 415, SAMPLE_JPEG, content_type='image/png') + rejected('неподдерживаемый Content-Type', 415, SAMPLE_PNG, content_type='image/gif') + for name in ('../etc/passwd', 'a\\b.png', 'a\x00.png', 'a\nb.png', '..', ' ', 'x' * 256): + rejected('опасное имя %r' % name[:16], 400, SAMPLE_PNG, filename=name) + rejected('посторонний загружает в чужой чат', 404, SAMPLE_PNG, actor=eve) + rejected('посторонний: размер не важнее доступа', 404, b'\0' * (MAX_BYTES + 1), actor=eve) + + exact = SAMPLE_PNG + b'\0' * (MAX_BYTES - len(SAMPLE_PNG)) + att = upload(exact)['json'] + check(att['size_bytes'] == MAX_BYTES, 'size mismatch at limit') + got = c.call('GET', '/api/v1/attachments/' + att['id'] + '/content', actor=bob) + check(got['bytes'] == exact, 'byte-exact download failed at limit') + print('ok файл ровно 10 MiB принят и скачан побайтно') + + jpeg = upload(SAMPLE_JPEG, content_type='image/jpeg', filename='фото.jpg')['json'] + got = c.call('GET', '/api/v1/attachments/' + jpeg['id'] + '/content', actor=bob) + check(got['headers'].get_content_type() == 'image/jpeg', 'wrong JPEG content type') + check(hashlib.sha256(got['bytes']).hexdigest() == jpeg['sha256'], 'JPEG checksum mismatch') + print('ok JPEG с именем не ASCII принят и скачан, SHA-256 совпал') + + for suffix in ('', '/content'): + c.call('GET', '/api/v1/attachments/' + jpeg['id'] + suffix, 404, actor=eve) + c.call('GET', '/api/v1/attachments/' + jpeg['id'] + suffix, 401) + c.call('GET', '/api/v1/attachments/not-a-uuid', 400, actor=alice) + c.call('GET', '/api/v1/attachments/' + str(uuid.uuid4()), 404, actor=alice) + print('ok посторонний 404, без сессии 401, неверный UUID 400, несуществующий 404') + + foreign = upload(SAMPLE_PNG, target=other)['json'] + messages = '/api/v1/chats/' + chat['id'] + '/messages' + key = {'Idempotency-Key': uuid.uuid4().hex} + c.call('POST', messages, 404, actor=alice, headers=key, body={'text': 'x', 'attachment_ids': [foreign['id']]}) + c.call('POST', messages, 404, actor=alice, headers=key, body={'text': 'x', 'attachment_ids': [str(uuid.uuid4())]}) + c.call('POST', messages, 400, actor=alice, headers=key, body={'text': '', 'attachment_ids': []}) + c.call('POST', messages, 400, actor=alice, headers=key, body={'text': 'x', 'attachment_ids': [jpeg['id'], jpeg['id']]}) + # Чужой файл: Eve загрузила его в свой чат, а Alice ссылается на него в своём и пытается прочитать. + eve_chat = c.call('POST', '/api/v1/chats', 201, actor=eve, body={'title': 'Чат Eve', 'member_ids': [eve['id']]}, schema='Chat')['json'] + eve_file = upload(SAMPLE_PNG, actor=eve, target=eve_chat)['json'] + c.call('POST', messages, 404, actor=alice, headers=key, body={'text': 'x', 'attachment_ids': [eve_file['id']]}) + for suffix in ('', '/content'): + c.call('GET', '/api/v1/attachments/' + eve_file['id'] + suffix, 404, actor=alice) + # Смешанный список: одно своё вложение не даёт привязать чужое, сообщение не создаётся. + before = c.call('GET', messages + '?limit=100', actor=alice, schema='MessagePage')['json']['items'] + c.call('POST', messages, 404, actor=alice, headers={'Idempotency-Key': uuid.uuid4().hex}, body={'text': 'x', 'attachment_ids': [jpeg['id'], foreign['id']]}) + after = c.call('GET', messages + '?limit=100', actor=alice, schema='MessagePage')['json']['items'] + check(len(after) == len(before), 'message was created with a foreign attachment') + print('ok вложение чужого чата 404, чужой пользователь 404, неизвестное 404, пустое сообщение 400, дубли 400, смешанный список без записи') + + sent = c.message(alice, chat, 'с файлами', attachments=[att['id'], jpeg['id']])['json'] + page = c.call('GET', messages + '?limit=100', actor=bob, schema='MessagePage')['json'] + found = [m for m in page['items'] if m['id'] == sent['id']] + check(len(found) == 1 and found[0]['attachment_ids'] == [att['id'], jpeg['id']], 'attachment order lost in history') + print('ok второй участник читает сообщение, порядок вложений сохранён') + print('PASS: attachment negative and boundary scenarios') + + +if __name__ == '__main__': + run(main) diff --git a/student-tests/common.py b/student-tests/common.py new file mode 100755 index 00000000..e185bc2b --- /dev/null +++ b/student-tests/common.py @@ -0,0 +1,25 @@ +"""Общая часть собственных проверок: клиент из публичных тестов и построение тестовых файлов.""" +import pathlib +import struct +import sys +import zlib + +ROOT = pathlib.Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / 'tests')) + +from client import Client, Failure, arguments, check, run # noqa: E402,F401 + +SAMPLE_PNG = (ROOT / 'tests/fixtures/sample.png').read_bytes() +SAMPLE_JPEG = (ROOT / 'student-tests/fixtures/sample.jpg').read_bytes() +MAX_BYTES = 10 * 1024 * 1024 +MAX_PIXELS = 40_000_000 + + +def png_chunk(kind, data): + return struct.pack('>I', len(data)) + kind + data + struct.pack('>I', zlib.crc32(kind + data)) + + +def png_with_size(width, height): + """Корректный заголовок с заданными размерами и почти без данных: так выглядит «бомба».""" + ihdr = struct.pack('>IIBBBBB', width, height, 8, 2, 0, 0, 0) + return b'\x89PNG\r\n\x1a\n' + png_chunk(b'IHDR', ihdr) + png_chunk(b'IDAT', zlib.compress(b'\0' * 16)) + png_chunk(b'IEND', b'') diff --git a/student-tests/direct_upload.py b/student-tests/direct_upload.py new file mode 100644 index 00000000..d62c93d7 --- /dev/null +++ b/student-tests/direct_upload.py @@ -0,0 +1,132 @@ +#!/usr/bin/env python3 +"""Track 1: negative scenarios, expiry, and API traffic/RAM at 1 and 8 MiB.""" +import hashlib +import json +import subprocess +import time +import urllib.error +import urllib.request +from urllib.parse import urlsplit, urlunsplit + +from common import Client, SAMPLE_PNG, arguments, check, run +from memory_concurrent import Sampler, anon_bytes, container_read, replicas + + +def put(upload, data, expected=200): + req = urllib.request.Request(upload['url'], data=data, headers=upload['headers'], method='PUT') + try: + response = urllib.request.urlopen(req, timeout=60) + except urllib.error.HTTPError as exc: + response = exc + with response: + response.read() + check(response.status == expected, 'S3 PUT: expected %d, got %d' % (expected, response.status)) + + +def traffic(containers): + rx = tx = 0 + for container in containers: + for line in container_read(container, '/proc/net/dev').splitlines(): + if ':' in line and line.split(':')[0].strip() != 'lo': + values = line.split(':')[1].split() + rx += int(values[0]) + tx += int(values[8]) + return rx, tx + + +def main(): + def configure(parser): + parser.add_argument('--skip-expiry', action='store_true', help='Skip real-clock expiry during a quick contract recheck') + args = arguments(__doc__, configure) + c = Client(args.base_url, args.ca_file, timeout=90) + alice, bob, eve, chat = c.bootstrap() + path = '/api/v1/chats/' + chat['id'] + '/attachments' + + def init(data=SAMPLE_PNG, expected=201, actor=alice, **overrides): + body = dict(filename='direct.png', content_type='image/png', size_bytes=len(data), sha256=hashlib.sha256(data).hexdigest()) + body.update(overrides) + out = c.call('POST', path+'/direct/init', expected, actor=actor, body=body) + return json.loads(out['bytes']) + + def complete(u, expected=201, actor=alice, target=path): + return c.call('POST', target+'/direct/complete', expected, actor=actor, body={'token':u['token']}, schema='Attachment' if expected == 201 else None) + + started = time.monotonic() + expired = init() + abandoned = init() + put(abandoned, SAMPLE_PNG) + init(expected=401, actor=None) + init(expected=404, actor=eve) + init(expected=413, size_bytes=10*1024*1024+1) + init(expected=400, sha256='bad') + init(expected=415, content_type='image/png; charset=utf-8') + init(expected=400, extra='unknown field') + init(expected=400, size_bytes=True) + c.call('POST', path+'/direct/complete', 400, actor=alice, body={'token':'x', 'extra':1}) + c.call('POST', path+'/direct/complete', 400, actor=alice, raw=b'{"token":"x"} {}', headers={'Content-Type':'application/json'}) + missing = init() + complete(missing, 409) + put(missing, SAMPLE_PNG) + complete(missing, 404, actor=bob) # Even another member cannot complete this ticket. + complete(missing, 404, actor=eve) + other = c.call('POST', '/api/v1/chats', 201, actor=alice, body={'title':'other', 'member_ids':[alice['id']]}, schema='Chat')['json'] + complete(missing, 404, target='/api/v1/chats/'+other['id']+'/attachments') + complete(dict(missing, token='A'+missing['token'][1:]), 400) + altered = dict(missing) + parts = urlsplit(missing['url']) + altered['url'] = urlunsplit(parts._replace(path=parts.path+'x')) + put(altered, SAMPLE_PNG, 403) + wrong_sum = init(sha256='0'*64) + put(wrong_sum, SAMPLE_PNG) + complete(wrong_sum, 400) + wrong_size = init(size_bytes=len(SAMPLE_PNG)+1) + # Signed content length must be enforced by the actual S3 implementation. + put(wrong_size, SAMPLE_PNG, 403) + invalid = init(data=b'not an image') + put(invalid, b'not an image') + complete(invalid, 415) + good = complete(missing)['json'] + check(complete(missing)['json']['id'] == good['id'], 'complete is not idempotent') + put(missing, b'x'*len(SAMPLE_PNG)) + downloaded = c.call('GET', '/api/v1/attachments/'+good['id']+'/content', actor=alice)['bytes'] + check(downloaded == SAMPLE_PNG, 'presigned replay modified a ready attachment') + print('PASS: auth, membership/owner/chat, limit, missing PUT, tampered token/key, checksum, size, invalid image, retry, overwrite protection', flush=True) + + containers = replicas() + print('mode size_bytes api_rx_bytes api_tx_bytes anon_before_MiB anon_peak_MiB', flush=True) + for size in (1024*1024, 8*1024*1024): + # Same tiny image, different payload sizes: isolate buffering from decoder RAM. + data = SAMPLE_PNG + b'\0'*(size-len(SAMPLE_PNG)) + for mode in ('proxy', 'direct'): + before_ram = max(anon_bytes(x) for x in containers) + sampler = Sampler(containers) + sampler.start() + before = traffic(containers) + try: + if mode == 'proxy': + c.call('POST', path+'?filename=proxy.png', 201, actor=alice, raw=data, headers={'Content-Type':'image/png'}, schema='Attachment') + else: + u = init(data) + put(u, data) + complete(u) + after = traffic(containers) + finally: + sampler.done.set() + sampler.join() + peak = max(before_ram, *sampler.peak.values()) + print(mode, size, after[0]-before[0], after[1]-before[1], round(before_ram/2**20,2), round(peak/2**20,2), flush=True) + + if args.skip_expiry: + print('SKIP: real-clock expiry; run without --skip-expiry for the full check', flush=True) + return + print('Waiting for real signature/ticket expiration...', flush=True) + time.sleep(max(0, 62-(time.monotonic()-started))) + put(expired, SAMPLE_PNG, 403) + time.sleep(max(0, 122-(time.monotonic()-started))) + complete(abandoned, 409) + print('PASS: expired PUT -> 403; abandoned upload complete after 120s -> 409; no ready metadata created', flush=True) + print('Abandoned staging key (janitor after grace):', urlsplit(abandoned['url']).path, flush=True) + + +if __name__ == '__main__': + run(main) diff --git a/student-tests/fixtures/sample.jpg b/student-tests/fixtures/sample.jpg new file mode 100644 index 00000000..b121f417 Binary files /dev/null and b/student-tests/fixtures/sample.jpg differ diff --git a/student-tests/memory_concurrent.py b/student-tests/memory_concurrent.py new file mode 100755 index 00000000..12bb3b77 --- /dev/null +++ b/student-tests/memory_concurrent.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Память реплик при одновременных загрузках файлов на границе 10 МиБ. Только стандартная библиотека. + +Файл: случайный несжатый PNG примерно на 3,5 Мп, размером почти ровно 10 МиБ. Его декодирование +дешёвое, поэтому результат показывает расход на приём тела, а не на декодирование 40 Мп (для этого +есть memory_peak.py). + +Что измеряется для каждой реплики: + anon — анонимная память процесса (куча и стеки), опрос memory.stat каждые 0,2 с; + peak — memory.peak из cgroup, точный максимум, но он включает вытесняемый дисковый кэш. +Запускать на только что перезапущенных репликах, иначе peak включает более ранние нагрузки. +""" +from concurrent.futures import ThreadPoolExecutor +import hashlib +import os +import statistics +import subprocess +import threading +import time +import struct +import zlib + +from common import Client, MAX_BYTES, ROOT, arguments, check, png_chunk, run + +COMPOSE = ['docker', 'compose', '--env-file', '.env'] +LIMIT = 1024 ** 3 +MIB = 1024 ** 2 + + +def noise_png(target): + """Несжимаемый PNG truecolor размером не больше target байт.""" + width = 2048 + height = (target - 1024) // (width * 3 + 1) + raw = b''.join(b'\0' + os.urandom(width * 3) for _ in range(height)) + ihdr = struct.pack('>IIBBBBB', width, height, 8, 2, 0, 0, 0) + data = b'\x89PNG\r\n\x1a\n' + png_chunk(b'IHDR', ihdr) + png_chunk(b'IDAT', zlib.compress(raw, 0)) + png_chunk(b'IEND', b'') + check(len(data) <= target, 'test file exceeds target size') + return data + + +def replicas(): + return subprocess.run(COMPOSE + ['ps', '-q', 'api'], cwd=ROOT, check=True, capture_output=True, text=True).stdout.split() + + +def container_read(container, path): + return subprocess.run(['docker', 'exec', container, 'cat', path], check=True, capture_output=True, text=True).stdout + + +def anon_bytes(container): + for line in container_read(container, '/sys/fs/cgroup/memory.stat').splitlines(): + name, value = line.split() + if name == 'anon': + return int(value) + raise RuntimeError('anon is missing from memory.stat') + + +def memory_event(container, name): + """Счётчик из memory.events: max — упор в лимит (ядро вытесняет кэш), oom_kill — убитые процессы.""" + for line in container_read(container, '/sys/fs/cgroup/memory.events').splitlines(): + key, value = line.split() + if key == name: + return int(value) + raise RuntimeError(name + ' is missing from memory.events') + + +class Sampler(threading.Thread): + """Опрашивает анонимную память реплик и помнит максимум.""" + + def __init__(self, containers): + super().__init__(daemon=True) + self.containers = containers + self.peak = {c: 0 for c in containers} + self.samples = 0 + self.done = threading.Event() + + def run(self): + while not self.done.is_set(): + for container in self.containers: + try: + self.peak[container] = max(self.peak[container], anon_bytes(container)) + except (subprocess.CalledProcessError, RuntimeError): + pass + self.samples += 1 + self.done.wait(0.2) + + +def main(): + parser_args = arguments('Replica memory under concurrent uploads', None) + concurrency = int(os.environ.get('UPLOADS', '20')) + rounds = int(os.environ.get('ROUNDS', '3')) + check(concurrency >= 10, 'the experiment needs at least 10 concurrent uploads') + + c = Client(parser_args.base_url, parser_args.ca_file, timeout=120) + alice, _, _, chat = c.bootstrap() + path = '/api/v1/chats/' + chat['id'] + '/attachments?filename=load.png' + data = noise_png(MAX_BYTES) + digest = hashlib.sha256(data).hexdigest() + print('файл: %d байт, одновременно: %d, раундов: %d' % (len(data), concurrency, rounds)) + + containers = replicas() + before = {x: anon_bytes(x) for x in containers} + sampler = Sampler(containers) + sampler.start() + + def upload(_): + client = Client(parser_args.base_url, parser_args.ca_file, timeout=120) + started = time.monotonic() + response = client.call('POST', path, [201, 429], actor=alice, raw=data, headers={'Content-Type': 'image/png'}, schema='Attachment') + if response['status'] == 201: + check(response['json']['sha256'] == digest, 'checksum differs after concurrent upload') + return response['status'], time.monotonic() - started + + results = [] + started = time.monotonic() + with ThreadPoolExecutor(max_workers=concurrency) as pool: + for _ in range(rounds): + results += list(pool.map(upload, range(concurrency))) + elapsed = time.monotonic() - started + sampler.done.set() + sampler.join() + + ok = sorted(seconds for status, seconds in results if status == 201) + print('длительность %.1f с; 201=%d, 429=%d; опросов памяти: %d' % (elapsed, len(ok), len(results) - len(ok), sampler.samples)) + if ok: + p95 = ok[min(len(ok) - 1, int(len(ok) * 0.95))] + print('время успешной загрузки: p50=%.2f с, p95=%.2f с, max=%.2f с' % (statistics.median(ok), p95, ok[-1])) + for x in containers: + peak = int(container_read(x, '/sys/fs/cgroup/memory.peak')) + state = subprocess.run(['docker', 'inspect', '--format', '{{.State.OOMKilled}} {{.RestartCount}}', x], check=True, capture_output=True, text=True).stdout.split() + kills = memory_event(x, 'oom_kill') + print('реплика %s: anon до %d МиБ, пик anon %d МиБ, memory.peak %d МиБ, упоров в лимит %d, oom_kill=%d, перезапусков=%s' % ( + x[:12], before[x] // MIB, sampler.peak[x] // MIB, peak // MIB, memory_event(x, 'max'), kills, state[1])) + check(sampler.peak[x] < LIMIT and kills == 0 and state == ['false', '0'], 'replica ran out of memory or was restarted') + print('PASS: concurrent uploads caused no OOM or restart') + + +if __name__ == '__main__': + run(main) diff --git a/student-tests/memory_peak.py b/student-tests/memory_peak.py new file mode 100755 index 00000000..e6789962 --- /dev/null +++ b/student-tests/memory_peak.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python3 +"""Пик памяти реплик на худших допустимых файлах. Нужен Pillow: .venv/bin/pip install pillow. + +Запускать на только что запущенных репликах, иначе пик включает более ранние нагрузки. + +Критерий: нет OOM и перезапусков, анонимная память ниже лимита контейнера. memory.peak только +выводится: он включает вытесняемый дисковый кэш временных файлов, поэтому может дойти до лимита без +всякой опасности (ядро просто освобождает кэш). Счётчик max показывает, сколько раз это случилось. +""" +from concurrent.futures import ThreadPoolExecutor +import io +import subprocess + +from PIL import Image + +from common import Client, MAX_BYTES, arguments, check, run +from memory_concurrent import LIMIT, MIB, Sampler, container_read, memory_event, replicas + +Image.MAX_IMAGE_PIXELS = None + + +def report(label, sampler): + values = [] + for container in sampler.containers: + values.append('%s: anon %d, memory.peak %d МиБ, упоров в лимит %d, oom_kill=%d' % ( + container[:12], sampler.peak[container] // MIB, int(container_read(container, '/sys/fs/cgroup/memory.peak')) // MIB, + memory_event(container, 'max'), memory_event(container, 'oom_kill'))) + print(label, *values, sep='\n ', flush=True) + for container in sampler.containers: + check(sampler.peak[container] < LIMIT and memory_event(container, 'oom_kill') == 0, 'replica ran out of memory') + + +def main(): + args = arguments('Peak memory on worst allowed uploads', None) + c = Client(args.base_url, args.ca_file, timeout=120) + alice, _, _, chat = c.bootstrap() + path = '/api/v1/chats/' + chat['id'] + '/attachments?filename=x' + containers = replicas() + sampler = Sampler(containers) + sampler.start() + report('до загрузок', sampler) + + def upload(data, content_type, client=c): + return client.call('POST', path, [201, 429], actor=alice, raw=data, headers={'Content-Type': content_type}) + + # Прогрессивный JPEG 4:4:4 — самый затратный вариант: декодер хранит коэффициенты всех компонентов. + picture = Image.effect_noise((400, 250), 60).convert('RGB').resize((8000, 5000)) + buffer = io.BytesIO() + picture.save(buffer, 'JPEG', progressive=True, quality=40, subsampling=0) + check(len(buffer.getvalue()) <= MAX_BYTES, 'test file exceeds byte limit') + for _ in range(4): + response = upload(buffer.getvalue(), 'image/jpeg') + check(response['status'] == 201, 'worst-case JPEG rejected') + report('4 x JPEG 40 Мп, progressive 4:4:4', sampler) + + # Худший случай целиком: тот же JPEG, дополненный до 10 МиБ нулями после конца изображения. + # Декодируется один файл за раз, остальные ждут своей очереди во временных файлах, а не в памяти. + big = buffer.getvalue() + b'\0' * (MAX_BYTES - len(buffer.getvalue())) + + def parallel(_): + return upload(big, 'image/jpeg', Client(args.base_url, args.ca_file, timeout=120))['status'] + with ThreadPoolExecutor(max_workers=24) as pool: + statuses = list(pool.map(parallel, range(24))) + print('24 одновременные загрузки JPEG 40 Мп по 10 МиБ: 201=%d, 429=%d (очередь на декодирование)' % (statuses.count(201), statuses.count(429))) + check(statuses.count(201) + statuses.count(429) == len(statuses), 'unexpected status') + report('после параллельных загрузок', sampler) + sampler.done.set() + sampler.join() + for container in containers: + state = subprocess.run(['docker', 'inspect', '--format', '{{.State.OOMKilled}} {{.RestartCount}}', container], check=True, capture_output=True, text=True).stdout.split() + check(state == ['false', '0'], 'replica was OOM-killed or restarted') + # Реплика после всего этого обслуживает запросы. + c.call('GET', '/health/ready', schema='Health') + print('OOMKilled=false, RestartCount=0 у всех реплик, readiness 200') + print('PASS: no OOM or restart, anonymous memory stays below the %d MiB container limit' % (LIMIT // MIB)) + + +if __name__ == '__main__': + run(main) diff --git a/student-tests/openapi_contract.py b/student-tests/openapi_contract.py new file mode 100644 index 00000000..cfcd9c75 --- /dev/null +++ b/student-tests/openapi_contract.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python3 +"""Validate real API exchanges against OpenAPI; public tests stay unchanged.""" +import argparse +from collections import Counter +import json +import re +import sys +from urllib.parse import parse_qs, urlsplit + +from jsonschema import Draft202012Validator, FormatChecker +from referencing import Registry, Resource + +from common import Client, ROOT, check + +SPEC = json.loads((ROOT/'contracts/openapi.json').read_text()) +RESOURCE = dict(SPEC, **{'$schema':'https://json-schema.org/draft/2020-12/schema'}) +REGISTRY = Registry().with_resource('urn:mtusi:openapi', Resource.from_contents(RESOURCE)) +OBSERVED = Counter() + + +def validate(value, schema): + # Put the schema under the same base URI so local component references resolve. + wrapped = dict(RESOURCE) + wrapped['$id'] = 'urn:mtusi:openapi' + wrapped.update(schema) + Draft202012Validator(wrapped, registry=REGISTRY, format_checker=FormatChecker()).validate(value) + + +original_call = Client.call + + +def checked_call(self, method, path, *args, **kwargs): + split = urlsplit(path) + matches = [(template, operations) for template, operations in SPEC['paths'].items() + if re.fullmatch(re.sub(r'\{[^}]+\}', '[^/]+', template), split.path)] + check(len(matches) == 1, 'Undocumented/ambiguous API route: '+method+' '+path) + template, operations = matches[0] + check(method.lower() in operations, 'Undocumented method: '+method+' '+template) + operation = operations[method.lower()] + response = original_call(self, method, path, *args, **kwargs) + status = str(response['status']) + check(status in operation['responses'], 'Undocumented response: '+method+' '+template+' '+status) + declared = operation['responses'][status] + for name, header in declared.get('headers', {}).items(): + value = response['headers'].get(name) + if value is not None: + schema = header['schema'] + if schema.get('type') == 'integer': + value = int(value) + validate(value, schema) + if declared.get('content'): + media = response['headers'].get_content_type() + check(media in declared['content'], 'Undocumented response Content-Type: '+media) + schema = declared['content'][media]['schema'] + if media == 'application/json': + validate(json.loads(response['bytes']), schema) + else: + check(not response['bytes'], 'Body returned for a response with no content') + if response['status'] < 400: + body = kwargs.get('body') + if body is not None: + validate(body, operation['requestBody']['content']['application/json']['schema']) + query = parse_qs(split.query) + path_values = dict(zip(re.findall(r'\{([^}]+)\}', template), + [v for t, v in zip(template.split('/'), split.path.split('/')) if t.startswith('{')])) + for parameter in operation.get('parameters', []): + values = {'path': path_values, 'query': query, 'header': kwargs.get('headers', {})}.get(parameter['in'], {}) + name, schema = parameter['name'], parameter['schema'] + check(not parameter.get('required') or name in values, 'Required parameter missing: '+name) + if name in values: + value = values[name] + if isinstance(value, list): + value = value[0] + if schema.get('type') == 'integer': + value = int(value) + validate(value, schema) + OBSERVED[(method, template, status)] += 1 + return response + + +def main(): + parser = argparse.ArgumentParser(add_help=False) + parser.add_argument('--scenario', choices=['smoke', 'attachments'], default='smoke') + args, remainder = parser.parse_known_args() + sys.argv = [sys.argv[0], *remainder] + Client.call = checked_call + if args.scenario == 'smoke': + import smoke as scenario + else: + import attachments as scenario + scenario.main() + for (method, path, status), count in sorted(OBSERVED.items()): + print('%s %s -> %s: %d checked' % (method, path, status, count)) + routes = {(m, p) for m, p, _ in OBSERVED} + print('PASS: actual request/response schemas, formats, headers and statuses match OpenAPI; %d operations, %d exchanges' % (len(routes), sum(OBSERVED.values()))) + + +if __name__ == '__main__': + main() diff --git a/student-tests/orphans.py b/student-tests/orphans.py new file mode 100755 index 00000000..d6cac86f --- /dev/null +++ b/student-tests/orphans.py @@ -0,0 +1,192 @@ +#!/usr/bin/env python3 +"""Отказы между S3 и PostgreSQL на работающем стенде: компенсация, падение процесса, обрыв загрузки. + +Отказ БД создаётся настоящей блокировкой: LOCK TABLE attachments IN SHARE MODE не мешает чтению, но +задерживает INSERT. Пока он ждёт, объект уже в S3, а строки ещё нет. Это и есть опасное окно. +Останавливает реплики API сигналом SIGKILL и возвращает их. Тома не трогает. Занимает около 6 минут. +""" +import hashlib +import json +import socket +import subprocess +import threading +import time +from urllib.parse import urlsplit + +from common import Client, Failure, ROOT, SAMPLE_PNG, arguments, check, run + +COMPOSE = ['docker', 'compose', '--env-file', '.env'] +MIN_GRACE = 300 +LOCK_SECONDS = 10 + + +def compose(*command, **kwargs): + return subprocess.run(COMPOSE + list(command), cwd=ROOT, check=True, capture_output=True, text=True, **kwargs).stdout + + +def janitor(grace=3600, dry_run=False): + """Один проход очистителя со своими настройками; работающий сервис остаётся с grace 1 час.""" + flags = ['-once'] + (['-dry-run'] if dry_run else []) + out = compose('run', '--rm', '--no-deps', '-T', '-e', 'JANITOR_GRACE_SECONDS=%d' % grace, 'janitor', *flags) + for line in out.splitlines(): + if line.startswith('{"janitor_report"'): + return json.loads(line)['janitor_report'] + raise Failure('janitor printed no report') + + +def show(label, report): + print('%-52s просмотрено=%d свежих=%d со строкой=%d без строки=%d удалено=%d' % ( + label, report['scanned'], report['fresh'], report['referenced'], report['orphans'], report['deleted']), flush=True) + + +def sql(query): + return int(compose('exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger', '-Atc', query).strip()) + + +def rows(): + return sql('SELECT count(*) FROM attachments') + + +class TableLock: + """Держит блокировку в отдельной транзакции, пока не истечёт время или не вызван release.""" + + def __enter__(self): + sql = 'BEGIN; LOCK TABLE attachments IN SHARE MODE; SELECT pg_sleep(%d); COMMIT;' % LOCK_SECONDS + self.process = subprocess.Popen(COMPOSE + ['exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger', '-c', sql], + cwd=ROOT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + time.sleep(1.5) # блокировка должна быть получена до загрузки + return self + + def __exit__(self, *_): + self.process.wait(timeout=LOCK_SECONDS + 10) + + +def interrupted_upload(base_url, token, chat_id, sent, declared): + """Отправляет часть объявленного тела и закрывает соединение.""" + url = urlsplit(base_url) + with socket.create_connection((url.hostname, url.port or 80), timeout=10) as connection: + connection.sendall(( + 'POST /api/v1/chats/%s/attachments?filename=cut.png HTTP/1.1\r\nHost: %s\r\nAuthorization: Bearer %s\r\n' + 'Content-Type: image/png\r\nContent-Length: %d\r\n\r\n' % (chat_id, url.hostname, token, declared)).encode()) + connection.sendall(SAMPLE_PNG[:sent]) + + +def main(): + args = arguments('Failures between S3 and PostgreSQL') + c = Client(args.base_url, args.ca_file, timeout=30) + alice, bob, _, chat = c.bootstrap() + path = '/api/v1/chats/' + chat['id'] + '/attachments?filename=sample.png' + headers = {'Content-Type': 'image/png'} + + def upload(client=c, expected=201, schema='Attachment'): + return client.call('POST', path, expected, actor=alice, raw=SAMPLE_PNG, headers=headers, schema=schema) + + def verify_download(attachment): + got = c.call('GET', '/api/v1/attachments/' + attachment['id'] + '/content', actor=bob) + check(hashlib.sha256(got['bytes']).hexdigest() == attachment['sha256'], 'attached file changed') + + # Объекты, которые нельзя потерять: один привязан к сообщению, другой ещё ни к чему не привязан. + linked = upload()['json'] + c.message(alice, chat, 'с вложением', attachments=[linked['id']]) + unlinked = upload()['json'] + + print('== Очистка старых объектов от предыдущих прогонов') + show('старые неучтённые объекты', janitor(grace=MIN_GRACE)) + print('== Исходное состояние') + show('очиститель, только отчёт', janitor(dry_run=True)) + before = janitor(dry_run=True)['scanned'] + rows_before = rows() + + print('== 1. Отказ БД между PUT и INSERT: компенсация') + with TableLock(): + started = time.monotonic() + failed = upload(expected=503, schema=None) + print('INSERT заблокирован: клиент получил %d за %.1f с' % (failed['status'], time.monotonic() - started)) + report = janitor(dry_run=True) + show('после компенсации', report) + check(report['scanned'] == before and rows() == rows_before, 'compensation left an object or a row') + print('ok объект удалён сразу, строки нет, очиститель не понадобился') + + print('== 2. Падение процесса между PUT и INSERT: kill -9') + outcome = {} + + def doomed(): + try: + outcome['status'] = upload(Client(args.base_url, args.ca_file, timeout=30), [201, 500, 502, 503, 504], schema=None)['status'] + except Failure as failure: + outcome['error'] = type(failure).__name__ + + with TableLock(): + thread = threading.Thread(target=doomed) + thread.start() + time.sleep(1.5) # PUT прошёл, INSERT ждёт блокировку + replicas = compose('ps', '-q', 'api').split() + subprocess.run(['docker', 'kill', '--signal', 'SIGKILL'] + replicas, check=True, capture_output=True) + thread.join() + # INSERT убитой реплики всё ещё ждёт блокировку внутри PostgreSQL и выполнился бы после её снятия: + # тогда и файл, и строка на месте, расхождения нет. Здесь нужен случай, когда запись не дошла до + # COMMIT, поэтому обслуживающий её процесс БД завершается. Итог тот же, что при падении до INSERT. + terminated = sql("SELECT count(pg_terminate_backend(pid)) FROM pg_stat_activity " + "WHERE wait_event_type = 'Lock' AND query LIKE '%INSERT INTO attachments%'") + check(terminated == 1, 'expected exactly one blocked INSERT, got %d' % terminated) + print('реплики убиты SIGKILL: клиент получил %s' % (outcome.get('status') or 'обрыв соединения')) + compose('up', '-d', '--wait') + time.sleep(3) + crashed_at = time.monotonic() + check(rows() == rows_before, 'row appeared for the crashed upload') + + fresh = janitor(dry_run=True) + show('сразу после падения, grace 1 ч', fresh) + check(fresh['scanned'] == before + 1, 'orphan was not found in the bucket') + check(janitor(grace=MIN_GRACE)['deleted'] == 0, 'fresh object was deleted') + print('ok объект без строки есть в bucket, но он моложе grace period: не тронут') + + time.sleep(max(0, MIN_GRACE + 2 - (time.monotonic() - crashed_at))) + # Свежая загрузка прямо перед очисткой: её объект должен пережить проход. + newest = upload()['json'] + dry = janitor(grace=MIN_GRACE, dry_run=True) + show('через %d с, только отчёт' % MIN_GRACE, dry) + check(dry['deleted'] == 0, 'dry run deleted an object') + check(dry['orphans'] >= 1, 'orphan was not detected') + check(janitor(dry_run=True)['scanned'] == before + 2, 'dry run changed the bucket') + print('ok только отчёт: объект найден, ничего не удалено') + + orphans = dry['orphans'] + cleaned = janitor(grace=MIN_GRACE) + show('через %d с, очистка' % MIN_GRACE, cleaned) + check(cleaned['deleted'] == orphans, 'wrong number of objects deleted') + again = janitor(grace=MIN_GRACE) + show('повторный проход', again) + check(again['deleted'] == 0 and again['orphans'] == 0, 'second pass is not idempotent') + for attachment in (linked, unlinked, newest): + verify_download(attachment) + print('ok объект удалён, повтор ничего не меняет; файл сообщения, файл без сообщения и свежий файл скачиваются, SHA-256 совпал') + + print('== 3. Обрыв загрузки клиентом') + state = janitor(dry_run=True)['scanned'] + rows_state = rows() + # Попыток больше, чем слотов на реплику: утечка слота дала бы 429 на следующей загрузке. + for _ in range(40): + interrupted_upload(c.base, alice['token'], chat['id'], len(SAMPLE_PNG) // 2, len(SAMPLE_PNG)) + time.sleep(3) + report = janitor(dry_run=True) + show('после 40 оборванных загрузок', report) + check(report['scanned'] == state and rows() == rows_state, 'interrupted upload left an object or a row') + for container in compose('ps', '-q', 'api').split(): + listing = subprocess.run(['docker', 'exec', container, 'ls', '-A', '/tmp'], check=True, capture_output=True, text=True).stdout + check(listing == '', 'temporary files are left on a replica') + print('ok объектов и строк не прибавилось, каталог временных файлов пуст на всех репликах') + for _ in range(4): + last = upload()['json'] + verify_download(last) + print('ok слоты не утекли: следующие загрузки проходят') + + final = janitor(grace=MIN_GRACE, dry_run=True) + rows_final = rows() + print('итог: объектов %d, строк %d' % (final['scanned'], rows_final)) + check(final['scanned'] == rows_final, 'objects and rows differ') + print('PASS: failures between S3 and PostgreSQL leave no unaccounted objects') + + +if __name__ == '__main__': + run(main) diff --git a/student-tests/s3_outage.py b/student-tests/s3_outage.py new file mode 100755 index 00000000..86481b6b --- /dev/null +++ b/student-tests/s3_outage.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python3 +"""Отказ S3: вложения отвечают 503, остальное API работает, после возврата файл на месте. + +Останавливает и запускает сервис s3 на текущем стенде; volume не трогает. +""" +import subprocess +import time +import uuid + +from common import Client, ROOT, SAMPLE_PNG, arguments, check, run + +COMPOSE = ['docker', 'compose', '--env-file', '.env'] +RECOVERY_LIMIT = 90 + + +def compose(*command): + subprocess.run(COMPOSE + list(command), cwd=ROOT, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + + +def main(): + args = arguments('S3 outage scenario') + c = Client(args.base_url, args.ca_file, timeout=30) + alice, bob, _, chat = c.bootstrap() + upload = '/api/v1/chats/' + chat['id'] + '/attachments?filename=sample.png' + headers = {'Content-Type': 'image/png'} + att = c.call('POST', upload, 201, actor=alice, raw=SAMPLE_PNG, headers=headers, schema='Attachment')['json'] + content = '/api/v1/attachments/' + att['id'] + '/content' + + compose('stop', 's3') + print('s3 stopped') + try: + def measured(name, *call_args, **call_kwargs): + response = c.call(*call_args, **call_kwargs) + print('%-34s %d in %.2fs' % (name, response['status'], response['elapsed'])) + return response + first = measured('upload without S3', 'POST', upload, 503, actor=alice, raw=SAMPLE_PNG, headers=headers) + check(first['json']['error']['code'] == 'unavailable', 'wrong error code') + check(first['elapsed'] < 15, 'answer slower than LB timeout') + measured('download without S3', 'GET', content, 503, actor=bob) + measured('metadata without S3', 'GET', '/api/v1/attachments/' + att['id'], 200, actor=bob, schema='Attachment') + measured('text message without S3', 'POST', '/api/v1/chats/' + chat['id'] + '/messages', 201, actor=alice, + body={'text': 'без S3'}, headers={'Idempotency-Key': uuid.uuid4().hex}, schema='Message') + measured('readiness without S3', 'GET', '/health/ready', 200, schema='Health') + finally: + compose('start', 's3') + started = time.monotonic() + while True: + response = c.call('GET', content, [200, 503], actor=bob) + if response['status'] == 200: + break + check(time.monotonic() - started < RECOVERY_LIMIT, 'S3 did not recover in time') + time.sleep(1) + check(response['bytes'] == SAMPLE_PNG, 'file changed across S3 outage') + print('download recovered in %.1fs after start, bytes match' % (time.monotonic() - started)) + c.call('POST', upload, 201, actor=alice, raw=SAMPLE_PNG, headers=headers, schema='Attachment') + print('upload works again') + print('PASS: S3 outage is contained to attachments and loses no data') + + +if __name__ == '__main__': + run(main) diff --git a/student-tests/upload_failover.py b/student-tests/upload_failover.py new file mode 100755 index 00000000..9cd7c1ef --- /dev/null +++ b/student-tests/upload_failover.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python3 +"""Загрузка -> остановка реплики, ОБСЛУЖИВШЕЙ загрузку -> скачивание через другую. + +Публичный resilience.py останавливает реплику, принявшую сообщение; сценарий README требует именно +реплику, принявшую файл, поэтому он проверяется отдельно. Реплику возвращает вызывающий скрипт. +""" +import hashlib +import os +import subprocess +import time + +from common import Client, ROOT, SAMPLE_PNG, arguments, check, run + + +def main(): + def configure(parser): + parser.add_argument('--avoid-instance', default='', help='Не останавливать эту реплику: так проверяется каждая по очереди') + args = arguments('Upload, stop the replica that served it, download via another', configure) + c = Client(args.base_url, args.ca_file, timeout=10) + alice, bob, _, chat = c.bootstrap() + path = '/api/v1/chats/' + chat['id'] + '/attachments?filename=sample.png' + for _ in range(10): + response = c.call('POST', path, 201, actor=alice, raw=SAMPLE_PNG, headers={'Content-Type': 'image/png'}, schema='Attachment') + target = response['headers']['X-Instance-Id'] + if target != args.avoid_instance: + break + check(target != args.avoid_instance, 'all uploads were served by the replica to avoid') + attachment = response['json'] + print('upload served by replica', target, 'status', response['status']) + + env = dict(os.environ, TARGET_INSTANCE_ID=target) + subprocess.run([str(ROOT / 'scripts/stop-one.sh')], env=env, check=True, stdout=subprocess.DEVNULL) + print('replica', target, 'stopped') + + url = '/api/v1/attachments/' + attachment['id'] + '/content' + served = set() + started = time.monotonic() + for _ in range(5): + download = c.call('GET', url, actor=bob) + served.add(download['headers']['X-Instance-Id']) + check(download['bytes'] == SAMPLE_PNG, 'downloaded bytes differ') + check(hashlib.sha256(download['bytes']).hexdigest() == attachment['sha256'], 'checksum differs') + check(target not in served, 'stopped replica still serves downloads') + print('downloaded 5 times via', sorted(served), 'in %.3fs, SHA-256 matches' % (time.monotonic() - started)) + print('PASS: file survives stop of the replica that uploaded it') + print('STOPPED=' + target) + + +if __name__ == '__main__': + run(main)