diff --git a/.dockerignore b/.dockerignore index bc16e556..ab81db1e 100644 --- a/.dockerignore +++ b/.dockerignore @@ -18,3 +18,8 @@ __pycache__ node_modules evidence .DS_Store +target +.idea +.vscode +*.iml +*.log diff --git a/.env.example b/.env.example index 714c8076..5a86ad61 100644 --- a/.env.example +++ b/.env.example @@ -7,5 +7,6 @@ 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=redis CACHE_URL_FILE=/run/secrets/cache_url +BCRYPT_COST=10 diff --git a/.github/workflows/application.yml b/.github/workflows/application.yml new file mode 100644 index 00000000..c7e0f92c --- /dev/null +++ b/.github/workflows/application.yml @@ -0,0 +1,15 @@ +name: Application +on: [push, pull_request] +permissions: + contents: read +jobs: + application: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '21' + cache: maven + - run: mvn -B test diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..0c58d0a9 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,24 @@ +FROM maven:3.9.9-eclipse-temurin-21@sha256:3a4ab3276a087bf276f79cae96b1af04f53731bec53fb2e651aca79e4b10211e AS build +WORKDIR /src +COPY pom.xml . +RUN mvn -B -DskipTests dependency:go-offline +COPY src ./src +RUN mvn -B -DskipTests package + +FROM eclipse-temurin:21.0.2_13-jre-jammy@sha256:603d23272e30bbefa9e7c436a7165c6303b9c67e27aae07472d8ddc748fe96a2 +RUN groupadd --system --gid 10001 messenger \ + && useradd --system --uid 10001 --gid messenger --home-dir /app --shell /usr/sbin/nologin messenger \ + && mkdir -p /app +WORKDIR /app +COPY --from=build --chown=messenger:messenger /src/target/messenger.jar /app/messenger.jar +USER messenger +ENV APP_HOST=0.0.0.0 \ + APP_PORT=8080 \ + APP_ENV=lab \ + SESSION_TTL_SECONDS=3600 \ + SESSION_STORE=redis \ + BCRYPT_COST=10 +EXPOSE 8080 +HEALTHCHECK --interval=10s --timeout=5s --start-period=20s --retries=5 \ + CMD ["java", "-cp", "/app/messenger.jar", "ru.mtusi.lab2.ReadyProbe"] +ENTRYPOINT ["java", "-jar", "/app/messenger.jar"] diff --git a/Makefile b/Makefile index 9ecb223e..b83cb445 100644 --- a/Makefile +++ b/Makefile @@ -4,7 +4,7 @@ CA_FILE ?= ACTION_SCRIPT ?= TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",) -.PHONY: help check validate test load test-persistence +.PHONY: help check validate test load test-persistence student-test help: @echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes" @@ -24,3 +24,6 @@ load: test-persistence: @test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2) $(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS) + +student-test: + mvn -B test diff --git a/REPORT.md b/REPORT.md index e42f2b05..b6e983a5 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,37 +1,118 @@ # Отчёт — лабораторная 2 -- Автор, группа: TODO -- Целевая оценка; выбранный трек 5, если нужен: TODO -- Commit/PR: TODO после публикации -- Использованные источники, библиотеки и помощь ИИ: TODO +- Автор, группа: Афанасьев Андрей, БПИ2304 +- Целевая оценка; выбранный трек 5, если нужен: 4, трек 5 не выбран +- Commit/PR: ветка `solution/bpi2304-afanasev`, заголовок PR `ЛР 2 — БПИ2304 — Афанасьев — на 4` +- Источники и библиотеки: JDK 21 (`com.sun.net.httpserver`), Jackson 2.18.2, PostgreSQL JDBC 42.7.4, HikariCP 5.1.0, Jedis 5.2.0, bcrypt 0.10.2, JUnit Jupiter 5.11.4. По документации PostgreSQL (транзакции, EXPLAIN) и Redis persistence. Контракт и публичные тесты курса не менялись. ## Запуск из чистого clone -TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. +Нужны Docker и JDK 21 с Maven, если запускать `mvn test` на хосте. Секреты и `.env` в Git не входят. + +Проверенный стенд 2026-10-14: AMD Ryzen 7 8745HS, 16 CPU, 13 GiB RAM, Linux 7.0.0-38-generic, Docker 29.1.3. Лимиты CPU/RAM контейнерам не задавались. Локально: OpenJDK Temurin 21.0.2, Maven 3.9.16. + +```sh +sh scripts/bootstrap-local.sh +docker compose --env-file .env up -d --build +``` + +`bootstrap-local.sh` один раз создаёт `secrets/postgres_password`, `secrets/database_url`, `secrets/cache_url` и копирует `.env` из `.env.example`. Пароль БД в репозиторий не пишется. Файлы `database_url` и `cache_url` должны быть читаемы процессом API (uid 10001), поэтому скрипт ставит им режим 644. `postgres_password` остаётся 600: его читает entrypoint Postgres от root. + +Дождаться `GET /health/ready` = 200, затем: + +```sh +make test +make test-persistence ACTION_SCRIPT=scripts/restart.sh +mvn -B test +``` + +Остановка без удаления данных: `docker compose --env-file .env stop`. +Полное удаление учебных данных: `docker compose --env-file .env down -v`. Volumes после этого пустые, миграция при следующем старте применяется заново. + +Образы закреплены тегом и digest: + +- сборка `maven:3.9.9-eclipse-temurin-21@sha256:3a4ab3276a087bf276f79cae96b1af04f53731bec53fb2e651aca79e4b10211e` +- runtime `eclipse-temurin:21.0.2_13-jre-jammy@sha256:603d23272e30bbefa9e7c436a7165c6303b9c67e27aae07472d8ddc748fe96a2` +- `postgres:16.6@sha256:557fea37a744d5f4c8faab304b0a90858b53ab119735a88c131fd19dab802f36` +- `redis:7.4.2@sha256:fbdbaea47b9ae4ecc2082ecdb4e1cea81e32176ffb1dcf643d422ad07427e5d9` + +API слушает `0.0.0.0:8080` от пользователя `messenger` (uid 10001). Порт наружу только `127.0.0.1:8080`. Postgres и Redis в сеть хоста не публикуются. + +Соответствие `.env.example`: + +| Переменная | Куда попадает | +| --- | --- | +| `APP_HOST`, `APP_PORT`, `APP_ENV` | процесс API | +| `SESSION_TTL_SECONDS` | TTL ключа сессии в Redis, по умолчанию 3600 | +| `SESSION_STORE=redis` | сессии только в Redis; другое значение процесс не принимает | +| `DATABASE_URL_FILE` | файл JDBC URL, на стенде `/run/secrets/database_url` | +| `CACHE_URL_FILE` | файл Redis URL, на стенде `/run/secrets/cache_url` | +| `BCRYPT_COST` | стоимость bcrypt, на стенде 10 | ## Архитектура и решения -TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab1, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. +Из lab1 перенесены контрактные правила мессенджера: коды ошибок, `X-Request-Id`, проверка JSON, keyset-курсор `(created_at, id)`, чужой чат как 404, лог без текста сообщения, остановка по SIGTERM. Память процесса больше не хранит пользователей и сообщения. + +Клиент ходит в один API. Пользователи, чаты, участники и сообщения лежат в PostgreSQL. Это источник истины для этих данных. Сессии лежат только в Redis: ключ `sess:` содержит id пользователя и снимается по TTL. Токен — 32 случайных байта, в ответе base64url. Пароль в ответе не возвращается. + +Пароль хешируется bcrypt (стоимость 10). Перед bcrypt пароль целиком проходит SHA-512 внутри библиотеки, потому что сам bcrypt обрезает вход на 72 байтах. В таблице хранится только строка хеша. + +Миграция `V1__schema.sql` применяется при старте, если в `schema_migrations` ещё нет версии `V1`. Повторный запуск ничего не вставляет второй раз. У `users.username` уникальный ключ. У чатов и сообщений есть первичные и внешние ключи. История читается по индексу `messages_history_idx (chat_id, created_at, id)`. + +Создание чата — одна транзакция: блокировка участников, вставка чата, вставка состава. Если вторая вставка падает, транзакция откатывается и чата не остаётся. Запись сообщения тоже одна транзакция вместе с монотонными часами `app_clock`: время не идёт назад между рестартами одного API. + +Пул HikariCP: максимум 10 соединений, `connectionTimeout` 2 с, у JDBC `connectTimeout` и `socketTimeout` по 2 с. Запросы параметризованные. Пул Jedis: до 16 соединений, ожидание 1 с. Если Postgres или Redis недоступны, бизнес-запрос получает 503 `unavailable`. Отсутствие заголовка по-прежнему 401. Аноним из-за падения Redis не становится пользователем. + +`/health/live` отвечает 200, пока процесс жив. `/health/ready` — 200 только когда оба хранилища отвечают. На SIGTERM приём закрывается, `HttpServer.stop(2)` ждёт текущие запросы. + +Redis запущен с `--appendonly yes --appendfsync everysec` и volume `/data`. AOF — постоянное хранение сессий. Одного TTL мало: после рестарта контейнера ключи читаются с диска. При штатном `docker compose restart` Redis успевает записать AOF. При внезапном kill возможна потеря около одной секунды записей. `synchronous_commit` PostgreSQL оставлен по умолчанию (`on`): `COMMIT` подтверждает запись после сброса WAL на диск этого инстанса, но не защищает от потери всего диска. + +Аутентификация и доступ к чату — разные проверки. Bearer только называет пользователя. Чтение и запись чата дополнительно требуют строку в `chat_members`. Чужой и отсутствующий чат снаружи выглядят одинаково: 404. + +Хеш пароля и быстрая контрольная сумма решают разные задачи. bcrypt намеренно медленный, чтобы перебор пароля был дорогим. Контрольная сумма (например SHA-256 файла) быстро показывает, что байты не изменились, и для хранения пароля не годится. ## Доказательства критериев | Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | | --- | --- | --- | --- | -| Публичный smoke | make test | TODO | TODO | -| Остальные пункты уровня 3 | TODO | TODO | TODO | -| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | -| Выбранный трек 5, если заявлен | TODO | TODO | TODO | - -TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. +| Публичный smoke | `make test` | PASS lab2 | evidence/smoke.txt | +| Данные и сессия переживают рестарт | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | тот же токен читает те же данные; volumes не удалялись | evidence/persistence.txt | +| PostgreSQL: пользователи, чаты, участники, сообщения, ключи, уникальный username | таблицы после миграции на пустом volume | шесть таблиц, владелец messenger | evidence/persistence.txt | +| Миграция повторно не дублирует данные | `mvn -B test`, тест migrationCanRunAgain | одна строка в schema_migrations | evidence/student-tests.txt | +| Basic только на входе, дальше Bearer, X-User-Id не пускает | smoke и свой тест | 401 с нужным WWW-Authenticate | evidence/smoke.txt, evidence/student-tests.txt | +| Пароль — bcrypt, длинный UTF-8 не обрезается | `PasswordTest` | два пароля из 80 символов «п», отличающиеся в конце, не совпали | evidence/student-tests.txt | +| Redis — хранилище сессий с TTL и AOF | `INFO persistence` | aof_enabled:1, ключ живёт SESSION_TTL_SECONDS | evidence/persistence.txt | +| Пул, таймауты, гонка username, откат чата | `mvn -B test` | 1×201 и 15×409; после сбоя триггера число чатов не выросло | evidence/student-tests.txt | +| Индекс истории на 10 000 сообщений | `EXPLAIN (ANALYZE, BUFFERS)`, страница 50 | Index Scan `messages_history_idx`, actual rows=50, shared hit=3, без Seq Scan | evidence/explain-plan.txt | +| Expiry, logout, неверный пароль, падение Redis/БД | `mvn -B test` | короткий TTL даёт 401; logout 204 затем 401; при паузе Redis и Postgres — 503 | evidence/student-tests.txt | +| Параллельные сообщения | 10 потоков × 10 сообщений | unique=100 | evidence/student-tests.txt | +| Непривилегированный процесс и SIGTERM | `docker exec api id`, `docker stop -t 10` | uid=10001, остановка 2280 мс, в логе duration_ms=2006 | evidence/persistence.txt | ## Эксперименты и отказы -TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. +Отдельный трек на 5 не делался. Нагрузка `tests/load.py` в отчёт не входит: для оценки 4 она не требуется. | Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | | --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | +| `scripts/restart.sh` (api, postgres, redis, volumes на месте) | тот же токен и те же сообщения | PASS persistence | в пределах ожидания теста (до 90 с на hook и до 90 с на ready); подтверждённые сообщения на месте | +| Пауза Redis | 503, не 200 от чужого пользователя | `/health/ready` и `/users/me` с токеном — 503; без токена — 401 | после unpause тот же токен снова 200 | +| Пауза PostgreSQL | 503 | ready и `/users/me` — 503 | после unpause ready и тот же токен — 200 | +| `SESSION_TTL_SECONDS=2` | сессия сама кончается | через 3.5 с `GET /users/me` — 401 | данные пользователя в Postgres остаются | +| SIGTERM API | процесс выходит быстрее 10 с | docker_stop_ms=2280, duration_ms=2006 | данные в Postgres и Redis не стираются | + +План страницы истории (10 000 сообщений, курсор около конца, `LIMIT 50`): + +``` +Limit (actual time=0.017..0.028 rows=50 loops=1) + Buffers: shared hit=3 + -> Index Scan using messages_history_idx on messages + Index Cond: (chat_id = ... AND (created_at, id) > ...) + Buffers: shared hit=3 +Execution Time: 0.063 ms +``` + +Полный текст — `evidence/explain-plan.txt`. Страница не читает всю историю: планировщик берёт 50 строк по индексу. ## Ограничения и следующие шаги -TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. +Один процесс API. Падение этой машины вместе с диском volumes не переживается: резервной копии нет. Redis с `appendfsync everysec` при kill -9 может потерять последнюю секунду сессий; сообщения при этом уже в PostgreSQL. Пароль в Postgres не хранится открытым текстом, но локальные файлы секретов лежат на диске стенда и в Git не попадают. Нет ограничения частоты входа, вложений и второго инстанса API. diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 00000000..60ab6005 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,61 @@ +name: mtusi-lab2 + +services: + postgres: + image: postgres:16.6@sha256:557fea37a744d5f4c8faab304b0a90858b53ab119735a88c131fd19dab802f36 + environment: + POSTGRES_USER: messenger + POSTGRES_DB: messenger + POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password + secrets: + - postgres_password + volumes: + - pgdata:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U messenger -d messenger"] + interval: 5s + timeout: 3s + retries: 12 + start_period: 10s + restart: unless-stopped + + redis: + image: redis:7.4.2@sha256:fbdbaea47b9ae4ecc2082ecdb4e1cea81e32176ffb1dcf643d422ad07427e5d9 + command: ["redis-server", "--appendonly", "yes", "--appendfsync", "everysec", "--dir", "/data"] + volumes: + - redisdata:/data + healthcheck: + test: ["CMD", "redis-cli", "ping"] + interval: 5s + timeout: 3s + retries: 12 + start_period: 5s + restart: unless-stopped + + api: + build: . + ports: + - "127.0.0.1:8080:8080" + env_file: + - .env + secrets: + - database_url + - cache_url + depends_on: + postgres: + condition: service_healthy + redis: + condition: service_healthy + restart: unless-stopped + +secrets: + postgres_password: + file: ./secrets/postgres_password + database_url: + file: ./secrets/database_url + cache_url: + file: ./secrets/cache_url + +volumes: + pgdata: + redisdata: diff --git a/evidence/explain-plan.txt b/evidence/explain-plan.txt new file mode 100644 index 00000000..06727a5e --- /dev/null +++ b/evidence/explain-plan.txt @@ -0,0 +1,11 @@ +messages=10000 + +Limit (cost=0.29..53.65 rows=50 width=64) (actual time=0.017..0.028 rows=50 loops=1) + Buffers: shared hit=3 + -> Index Scan using messages_history_idx on messages (cost=0.29..211.62 rows=198 width=64) (actual time=0.017..0.023 rows=50 loops=1) + Index Cond: ((chat_id = 'f472217b-e12b-4007-9998-1c24221d01ca'::uuid) AND (ROW(created_at, id) > ROW('2026-10-14 17:46:51.250266+00'::timestamp with time zone, 'be5a4036-03e8-45a7-8d19-42244139c1d4'::uuid))) + Buffers: shared hit=3 +Planning: + Buffers: shared hit=33 +Planning Time: 0.174 ms +Execution Time: 0.063 ms diff --git a/evidence/persistence.txt b/evidence/persistence.txt new file mode 100644 index 00000000..8c04b006 --- /dev/null +++ b/evidence/persistence.txt @@ -0,0 +1,11 @@ +make test-persistence ACTION_SCRIPT=scripts/restart.sh +PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence. + +scripts/restart.sh перезапускает postgres и redis, ждёт healthy и затем перезапускает api. +Volumes pgdata и redisdata не удаляются. Тот же Bearer-токен после рестарта читает те же данные. + +После прогона: +api, postgres, redis — healthy. +uid процесса API: uid=10001(messenger) +Redis: aof_enabled:1, aof_last_write_status:ok +docker stop -t 10 api: docker_stop_ms=2280, лог event=shutdown phase=end duration_ms=2006 diff --git a/evidence/smoke.txt b/evidence/smoke.txt new file mode 100644 index 00000000..1f586359 --- /dev/null +++ b/evidence/smoke.txt @@ -0,0 +1,5 @@ +PASS: lab2 public API scenario; infrastructure and grading evidence remain separate. + +Команда: make test +BASE_URL: http://localhost:8080 +Стенд: docker compose --env-file .env up -d --build diff --git a/evidence/student-tests.txt b/evidence/student-tests.txt new file mode 100644 index 00000000..3f0f8929 --- /dev/null +++ b/evidence/student-tests.txt @@ -0,0 +1,9 @@ +mvn -B test +Tests run: 10, Failures: 0, Errors: 0, Skipped: 0 +CONCURRENCY PASS clients=10 messages=100 unique=100 +EXPLAIN index=messages_history_idx rows=10000 + +Проверены: повтор миграции, валидация, Bearer/Basic, игнор X-User-Id, +гонка одного username (1 успех и 15 конфликтов), откат создания чата, +expiry при SESSION_TTL_SECONDS=2, logout, неверный пароль, +пауза Redis и PostgreSQL (503, аноним не становится пользователем). diff --git a/pom.xml b/pom.xml new file mode 100644 index 00000000..61af849f --- /dev/null +++ b/pom.xml @@ -0,0 +1,105 @@ + + + 4.0.0 + + ru.mtusi + lab2-messenger + 1.0.0 + lab2-messenger + + + UTF-8 + 21 + 2.18.2 + 5.11.4 + + + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + org.postgresql + postgresql + 42.7.4 + + + com.zaxxer + HikariCP + 5.1.0 + + + redis.clients + jedis + 5.2.0 + + + at.favre.lib + bcrypt + 0.10.2 + + + org.slf4j + slf4j-nop + 2.0.16 + + + org.junit.jupiter + junit-jupiter + ${junit.version} + test + + + + + messenger + + + org.apache.maven.plugins + maven-compiler-plugin + 3.13.0 + + + org.apache.maven.plugins + maven-surefire-plugin + 3.5.2 + + + org.apache.maven.plugins + maven-shade-plugin + 3.6.0 + + + package + + shade + + + false + + + ru.mtusi.lab2.Main + + + + + + *:* + + META-INF/*.SF + META-INF/*.DSA + META-INF/*.RSA + + + + + + + + + + diff --git a/scripts/bootstrap-local.sh b/scripts/bootstrap-local.sh new file mode 100755 index 00000000..33b723db --- /dev/null +++ b/scripts/bootstrap-local.sh @@ -0,0 +1,16 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." +mkdir -p secrets +umask 077 +if [ ! -s secrets/postgres_password ]; then + tr -dc 'A-Za-z0-9' < /dev/urandom | head -c 24 > secrets/postgres_password +fi +pass=$(tr -d '\n' < secrets/postgres_password) +printf 'jdbc:postgresql://postgres:5432/messenger?user=messenger&password=%s\n' "$pass" > secrets/database_url +printf 'redis://redis:6379/0\n' > secrets/cache_url +chmod 600 secrets/postgres_password +chmod 644 secrets/database_url secrets/cache_url +if [ ! -f .env ]; then + cp .env.example .env +fi diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100755 index 00000000..c15cb99b --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,19 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." +docker compose --env-file .env restart postgres redis +i=0 +while [ "$i" -lt 40 ]; do + pg_id=$(docker compose --env-file .env ps -q postgres) + rd_id=$(docker compose --env-file .env ps -q redis) + pg=$(docker inspect --format '{{if .State.Health}}{{.State.Health.Status}}{{end}}' "$pg_id") + rd=$(docker inspect --format '{{if .State.Health}}{{.State.Health.Status}}{{end}}' "$rd_id") + if [ "$pg" = "healthy" ] && [ "$rd" = "healthy" ]; then + docker compose --env-file .env restart api + exit 0 + fi + i=$((i + 1)) + sleep 1 +done +echo 'postgres or redis did not become healthy' >&2 +exit 1 diff --git a/src/main/java/ru/mtusi/lab2/ApiException.java b/src/main/java/ru/mtusi/lab2/ApiException.java new file mode 100644 index 00000000..d3fe8494 --- /dev/null +++ b/src/main/java/ru/mtusi/lab2/ApiException.java @@ -0,0 +1,48 @@ +package ru.mtusi.lab2; + +final class ApiException extends RuntimeException { + final int status; + final String code; + final String clientMessage; + final String challenge; + + private ApiException(int status, String code, String clientMessage, String challenge) { + super(code); + this.status = status; + this.code = code; + this.clientMessage = clientMessage; + this.challenge = challenge; + } + + static ApiException invalid(String message) { + return new ApiException(400, "invalid_request", message, null); + } + + static ApiException unauthorized(String challenge) { + return new ApiException(401, "unauthorized", "Нет действительной идентификации", challenge); + } + + static ApiException notFound() { + return new ApiException(404, "not_found", "Объект не найден", null); + } + + static ApiException conflict() { + return new ApiException(409, "conflict", "Имя пользователя уже занято", null); + } + + static ApiException tooLarge() { + return new ApiException(413, "payload_too_large", "Тело запроса слишком большое", null); + } + + static ApiException dependency() { + return new ApiException(503, "unavailable", "Зависимость недоступна", null); + } + + static ApiException shuttingDown() { + return new ApiException(503, "unavailable", "Сервер останавливается", null); + } + + static ApiException internalError() { + return new ApiException(500, "internal_error", "Внутренняя ошибка", null); + } +} diff --git a/src/main/java/ru/mtusi/lab2/Config.java b/src/main/java/ru/mtusi/lab2/Config.java new file mode 100644 index 00000000..fc1ae63f --- /dev/null +++ b/src/main/java/ru/mtusi/lab2/Config.java @@ -0,0 +1,189 @@ +package ru.mtusi.lab2; + +import java.net.URI; +import java.net.URLDecoder; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; + +final class Config { + final String host; + final int port; + final String appEnv; + final String jdbcUrl; + final String dbUser; + final String dbPassword; + final String redisUrl; + final int sessionTtlSeconds; + final int bcryptCost; + + Config( + String host, + int port, + String appEnv, + String jdbcUrl, + String dbUser, + String dbPassword, + String redisUrl, + int sessionTtlSeconds, + int bcryptCost) { + this.host = host; + this.port = port; + this.appEnv = appEnv; + this.jdbcUrl = jdbcUrl; + this.dbUser = dbUser; + this.dbPassword = dbPassword; + this.redisUrl = redisUrl; + this.sessionTtlSeconds = sessionTtlSeconds; + this.bcryptCost = bcryptCost; + } + + static Config fromEnvironment() { + String host = env("APP_HOST", "0.0.0.0"); + int port = parsePort(env("APP_PORT", "8080")); + String appEnv = env("APP_ENV", "lab"); + int ttl = parsePositive("SESSION_TTL_SECONDS", env("SESSION_TTL_SECONDS", "3600")); + int cost = parsePositive("BCRYPT_COST", env("BCRYPT_COST", "10")); + String store = env("SESSION_STORE", "redis"); + if (!store.equals("redis")) { + fail("SESSION_STORE"); + } + String database = secret("DATABASE_URL", "DATABASE_URL_FILE"); + String redis = secret("REDIS_URL", "CACHE_URL_FILE"); + Jdbc jdbc = jdbc(database); + return new Config(host, port, appEnv, jdbc.url, jdbc.user, jdbc.password, redis.trim(), ttl, cost); + } + + private static String env(String name, String fallback) { + String value = System.getenv(name); + if (value == null || value.isBlank()) { + return fallback; + } + return value.trim(); + } + + private static String secret(String directName, String fileName) { + String direct = System.getenv(directName); + if (direct != null && !direct.isBlank()) { + return direct.trim(); + } + String file = System.getenv(fileName); + if (file == null || file.isBlank()) { + fail(fileName); + } + try { + String value = Files.readString(Path.of(file)).trim(); + if (value.isEmpty()) { + fail(fileName); + } + return value; + } catch (Exception e) { + fail(fileName); + return ""; + } + } + + private static int parsePort(String raw) { + try { + int value = Integer.parseInt(raw); + if (value < 0 || value > 65535) { + throw new NumberFormatException(); + } + return value; + } catch (NumberFormatException e) { + fail("APP_PORT"); + return 8080; + } + } + + private static int parsePositive(String name, String raw) { + try { + int value = Integer.parseInt(raw); + if (value < 1) { + throw new NumberFormatException(); + } + return value; + } catch (NumberFormatException e) { + fail(name); + return 1; + } + } + + private static void fail(String name) { + System.err.println("event=config_failed name=" + name); + System.exit(1); + } + + private record Jdbc(String url, String user, String password) { + } + + private static Jdbc jdbc(String raw) { + String value = raw.trim(); + try { + if (value.startsWith("jdbc:postgresql:")) { + return fromJdbc(value); + } + if (value.startsWith("postgres://")) { + value = "postgresql://" + value.substring("postgres://".length()); + } + if (!value.startsWith("postgresql://")) { + throw new IllegalArgumentException(); + } + URI uri = URI.create(value); + String userInfo = uri.getRawUserInfo(); + if (userInfo == null || !userInfo.contains(":")) { + throw new IllegalArgumentException(); + } + int colon = userInfo.indexOf(':'); + String user = URLDecoder.decode(userInfo.substring(0, colon), StandardCharsets.UTF_8); + String password = URLDecoder.decode(userInfo.substring(colon + 1), StandardCharsets.UTF_8); + String path = uri.getPath(); + if (uri.getHost() == null || path == null || path.length() < 2) { + throw new IllegalArgumentException(); + } + int port = uri.getPort() < 0 ? 5432 : uri.getPort(); + String url = "jdbc:postgresql://" + uri.getHost() + ":" + port + path + + "?user=" + URLEncoder.encode(user, StandardCharsets.UTF_8) + + "&password=" + URLEncoder.encode(password, StandardCharsets.UTF_8); + return new Jdbc(withTimeouts(url), user, password); + } catch (RuntimeException e) { + fail("DATABASE_URL"); + return new Jdbc("", "", ""); + } + } + + private static Jdbc fromJdbc(String url) { + String user = query(url, "user"); + String password = query(url, "password"); + if (user == null || password == null) { + throw new IllegalArgumentException(); + } + return new Jdbc(withTimeouts(url), user, password); + } + + private static String query(String url, String name) { + int question = url.indexOf('?'); + if (question < 0) { + return null; + } + for (String part : url.substring(question + 1).split("&")) { + int eq = part.indexOf('='); + if (eq < 0) { + continue; + } + if (part.substring(0, eq).equals(name)) { + return URLDecoder.decode(part.substring(eq + 1), StandardCharsets.UTF_8); + } + } + return null; + } + + private static String withTimeouts(String url) { + if (url.contains("socketTimeout=")) { + return url; + } + String extra = "connectTimeout=2&socketTimeout=2"; + return url + (url.contains("?") ? "&" : "?") + extra; + } +} diff --git a/src/main/java/ru/mtusi/lab2/Main.java b/src/main/java/ru/mtusi/lab2/Main.java new file mode 100644 index 00000000..7a24f29c --- /dev/null +++ b/src/main/java/ru/mtusi/lab2/Main.java @@ -0,0 +1,36 @@ +package ru.mtusi.lab2; + +public final class Main { + private Main() { + } + + public static void main(String[] args) { + Config config = Config.fromEnvironment(); + MessengerServer server; + try { + server = MessengerServer.start(config, System.out::println, System.err::println); + } catch (Exception e) { + System.err.println("event=startup_failed type=" + e.getClass().getSimpleName()); + System.exit(1); + return; + } + System.out.println("event=listen host=" + config.host + + " port=" + server.port() + + " env=" + config.appEnv + + " session_store=redis" + + " session_ttl_seconds=" + config.sessionTtlSeconds); + Runtime.getRuntime().addShutdownHook(new Thread(() -> { + long started = System.nanoTime(); + System.out.println("event=shutdown phase=begin"); + server.stop(); + long durationMs = (System.nanoTime() - started) / 1_000_000L; + System.out.println("event=shutdown phase=end duration_ms=" + durationMs); + }, "shutdown")); + try { + Thread.currentThread().join(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + server.stop(); + } + } +} diff --git a/src/main/java/ru/mtusi/lab2/MessengerServer.java b/src/main/java/ru/mtusi/lab2/MessengerServer.java new file mode 100644 index 00000000..2ac733e4 --- /dev/null +++ b/src/main/java/ru/mtusi/lab2/MessengerServer.java @@ -0,0 +1,656 @@ +package ru.mtusi.lab2; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.StreamReadFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.json.JsonMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpServer; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.InetSocketAddress; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.security.SecureRandom; +import java.time.Instant; +import java.time.format.DateTimeFormatter; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.Locale; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Consumer; +import java.util.regex.Pattern; + +final class MessengerServer { + static final String BASIC = "Basic realm=\"messenger\", charset=\"UTF-8\""; + static final String BEARER = "Bearer realm=\"messenger\""; + + private static final int MAX_BODY = 64 * 1024; + private static final Pattern USERNAME = Pattern.compile("^[a-z0-9_]{3,32}$"); + private static final Pattern UUID_TEXT = Pattern.compile( + "(?i)[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"); + private static final JsonMapper JSON = JsonMapper.builder() + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .build(); + + private final HttpServer http; + private final PostgresStore store; + private final SessionStore sessions; + private final Passwords passwords; + private final int sessionTtlSeconds; + private final SecureRandom random = new SecureRandom(); + private final AtomicBoolean accepting = new AtomicBoolean(true); + private final AtomicBoolean stopped = new AtomicBoolean(false); + private final Consumer info; + private final Consumer error; + private final int port; + + private MessengerServer(Config config, Consumer info, Consumer error) throws IOException { + this.info = info; + this.error = error; + this.sessionTtlSeconds = config.sessionTtlSeconds; + this.passwords = new Passwords(config.bcryptCost); + this.store = new PostgresStore(config.jdbcUrl, config.dbUser, config.dbPassword, passwords); + this.sessions = new SessionStore(config.redisUrl); + this.store.migrate(); + this.http = HttpServer.create(new InetSocketAddress(config.host, config.port), 128); + this.port = http.getAddress().getPort(); + ExecutorService pool = Executors.newFixedThreadPool(64, runnable -> { + Thread thread = new Thread(runnable, "http"); + thread.setDaemon(true); + return thread; + }); + http.setExecutor(pool); + http.createContext("/", this::handle); + http.start(); + } + + static MessengerServer start(Config config, Consumer info, Consumer error) throws IOException { + return new MessengerServer(config, info, error); + } + + int port() { + return port; + } + + PostgresStore store() { + return store; + } + + void refuseNewRequests() { + accepting.set(false); + } + + void stop() { + accepting.set(false); + if (stopped.compareAndSet(false, true)) { + http.stop(2); + sessions.close(); + store.close(); + } + } + + private void handle(HttpExchange exchange) { + long started = System.nanoTime(); + String requestId = UUID.randomUUID().toString(); + String method = exchange.getRequestMethod(); + String path = exchange.getRequestURI().getPath() == null ? "" : exchange.getRequestURI().getPath(); + int status = 500; + try { + status = dispatch(exchange, requestId, method, path); + } catch (ApiException exception) { + status = writeError(exchange, requestId, exception); + } catch (Exception exception) { + error.accept("event=unexpected type=" + exception.getClass().getName()); + status = writeError(exchange, requestId, ApiException.internalError()); + } finally { + long durationMs = (System.nanoTime() - started) / 1_000_000L; + info.accept("request_id=" + requestId + + " method=" + method + + " path=" + path + + " status=" + status + + " duration_ms=" + durationMs); + exchange.close(); + } + } + + private int dispatch(HttpExchange exchange, String requestId, String method, String path) throws IOException { + if (!accepting.get()) { + if ("GET".equals(method) && "/health/live".equals(path)) { + return writeJson(exchange, requestId, 200, health()); + } + throw ApiException.shuttingDown(); + } + if ("GET".equals(method) && "/health/live".equals(path)) { + rejectQuery(exchange); + return writeJson(exchange, requestId, 200, health()); + } + if ("GET".equals(method) && "/health/ready".equals(path)) { + rejectQuery(exchange); + if (!store.ready() || !sessions.ready()) { + throw ApiException.dependency(); + } + return writeJson(exchange, requestId, 200, health()); + } + if ("POST".equals(method) && "/api/v1/users".equals(path)) { + rejectQuery(exchange); + JsonNode body = readObject(readBody(exchange)); + allowOnly(body, "username", "display_name", "password"); + String username = requiredText(body, "username"); + if (!USERNAME.matcher(username).matches()) { + throw ApiException.invalid("Недопустимый username"); + } + String displayName = requiredText(body, "display_name"); + requireCodePoints(displayName, 1, 100, "display_name"); + String password = requiredText(body, "password"); + int passwordPoints = password.codePointCount(0, password.length()); + if (passwordPoints < 12 || passwordPoints > 128) { + throw ApiException.invalid("Недопустимый пароль"); + } + User user = store.createUser(username, displayName, password); + return writeJson(exchange, requestId, 201, userJson(user)); + } + if ("POST".equals(method) && "/api/v1/auth/sessions".equals(path)) { + rejectQuery(exchange); + if (readLimited(exchange.getRequestBody()).length > 0) { + throw ApiException.invalid("Тело запроса не допускается"); + } + Credentials credentials = basic(exchange); + User user; + try { + user = store.authenticate(credentials.username, credentials.password); + } catch (ApiException exception) { + if (exception.status == 401) { + throw ApiException.unauthorized(BASIC); + } + throw exception; + } + String token = newToken(); + sessions.save(token, user.id(), sessionTtlSeconds); + Instant expires = Instant.now().plusSeconds(sessionTtlSeconds).truncatedTo(ChronoUnit.SECONDS); + ObjectNode session = JSON.createObjectNode(); + session.put("token", token); + session.put("token_type", "Bearer"); + session.put("expires_at", DateTimeFormatter.ISO_INSTANT.format(expires)); + session.set("user", userJson(user)); + return writeJson(exchange, requestId, 201, session); + } + if ("DELETE".equals(method) && "/api/v1/auth/sessions/current".equals(path)) { + rejectQuery(exchange); + String token = bearer(exchange); + if (!sessions.revoke(token)) { + throw ApiException.unauthorized(BEARER); + } + return writeEmpty(exchange, requestId); + } + + if ("GET".equals(method) && "/api/v1/users/me".equals(path)) { + rejectQuery(exchange); + User user = requireUser(exchange); + return writeJson(exchange, requestId, 200, userJson(user)); + } + if ("POST".equals(method) && "/api/v1/chats".equals(path)) { + rejectQuery(exchange); + User user = requireUser(exchange); + JsonNode body = readObject(readBody(exchange)); + allowOnly(body, "title", "member_ids"); + String title = requiredText(body, "title"); + requireCodePoints(title, 1, 100, "title"); + List members = memberIds(body); + Chat chat = store.createChat(user.id(), title, members); + return writeJson(exchange, requestId, 201, chatJson(chat)); + } + if ("GET".equals(method) && "/api/v1/chats".equals(path)) { + User user = requireUser(exchange); + Query query = pagingQuery(exchange); + int limit = query.limit == null ? 50 : query.limit; + Position position = query.cursor == null ? null : decodeCursor(query.cursor, "c", user.id()); + List chats = store.chats( + user.id(), + limit + 1, + position == null ? null : position.createdAt, + position == null ? null : position.id); + return writeSlice(exchange, requestId, chats, limit, "c", user.id(), Chat::createdAt, Chat::id, MessengerServer::chatJson); + } + + ChatRoute chatRoute = matchChat(path); + if (chatRoute != null && "GET".equals(method) && chatRoute.messages) { + User user = requireUser(exchange); + UUID chatId = parsePathUuid(chatRoute.idText); + Query query = pagingQuery(exchange); + int limit = query.limit == null ? 50 : query.limit; + if (store.visibleChat(user.id(), chatId).isEmpty()) { + throw ApiException.notFound(); + } + Position position = query.cursor == null ? null : decodeCursor(query.cursor, "m", chatId); + List messages = store.messages( + user.id(), + chatId, + limit + 1, + position == null ? null : position.createdAt, + position == null ? null : position.id); + return writeSlice(exchange, requestId, messages, limit, "m", chatId, Message::createdAt, Message::id, MessengerServer::messageJson); + } + if (chatRoute != null && "POST".equals(method) && chatRoute.messages) { + rejectQuery(exchange); + User user = requireUser(exchange); + UUID chatId = parsePathUuid(chatRoute.idText); + JsonNode body = readObject(readBody(exchange)); + allowOnly(body, "text"); + String text = requiredText(body, "text"); + requireCodePoints(text, 1, 4000, "text"); + Message message = store.addMessage(user.id(), chatId, text); + return writeJson(exchange, requestId, 201, messageJson(message)); + } + if (chatRoute != null && "GET".equals(method)) { + rejectQuery(exchange); + User user = requireUser(exchange); + UUID chatId = parsePathUuid(chatRoute.idText); + Chat chat = store.visibleChat(user.id(), chatId).orElseThrow(ApiException::notFound); + return writeJson(exchange, requestId, 200, chatJson(chat)); + } + throw ApiException.notFound(); + } + + private User requireUser(HttpExchange exchange) { + String token = bearer(exchange); + UUID userId = sessions.find(token).orElseThrow(() -> ApiException.unauthorized(BEARER)); + return store.findUser(userId).orElseThrow(() -> ApiException.unauthorized(BEARER)); + } + + private String bearer(HttpExchange exchange) { + String header = singleHeader(exchange, "Authorization"); + if (header == null || !header.regionMatches(true, 0, "Bearer ", 0, 7)) { + throw ApiException.unauthorized(BEARER); + } + String token = header.substring(7); + if (token.isBlank() || token.indexOf(' ') >= 0) { + throw ApiException.unauthorized(BEARER); + } + return token; + } + + private Credentials basic(HttpExchange exchange) { + String header = singleHeader(exchange, "Authorization"); + if (header == null || !header.regionMatches(true, 0, "Basic ", 0, 6)) { + throw ApiException.unauthorized(BASIC); + } + byte[] decoded; + try { + decoded = Base64.getDecoder().decode(header.substring(6).trim()); + } catch (IllegalArgumentException e) { + throw ApiException.unauthorized(BASIC); + } + String pair = new String(decoded, StandardCharsets.UTF_8); + int colon = pair.indexOf(':'); + if (colon <= 0 || colon == pair.length() - 1) { + throw ApiException.unauthorized(BASIC); + } + return new Credentials(pair.substring(0, colon), pair.substring(colon + 1)); + } + + private static String singleHeader(HttpExchange exchange, String name) { + List headers = exchange.getRequestHeaders().get(name); + if (headers == null || headers.size() != 1) { + return null; + } + return headers.get(0); + } + + private String newToken() { + byte[] bytes = new byte[32]; + random.nextBytes(bytes); + return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); + } + + private static UUID parsePathUuid(String raw) { + if (!UUID_TEXT.matcher(raw).matches()) { + throw ApiException.invalid("Некорректный идентификатор"); + } + return UUID.fromString(raw); + } + + private static ChatRoute matchChat(String path) { + String prefix = "/api/v1/chats/"; + if (!path.startsWith(prefix)) { + return null; + } + String rest = path.substring(prefix.length()); + if (rest.isEmpty() || rest.charAt(0) == '/') { + return null; + } + int slash = rest.indexOf('/'); + if (slash < 0) { + return new ChatRoute(rest, false); + } + if (rest.substring(slash).equals("/messages")) { + return new ChatRoute(rest.substring(0, slash), true); + } + return null; + } + + private byte[] readBody(HttpExchange exchange) throws IOException { + String contentType = exchange.getRequestHeaders().getFirst("Content-Type"); + if (contentType == null) { + throw ApiException.invalid("Ожидался Content-Type application/json"); + } + String mime = contentType.split(";", 2)[0].trim().toLowerCase(Locale.ROOT); + if (!mime.equals("application/json")) { + throw ApiException.invalid("Ожидался Content-Type application/json"); + } + return readLimited(exchange.getRequestBody()); + } + + private static byte[] readLimited(InputStream input) throws IOException { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + byte[] buffer = new byte[4096]; + int total = 0; + int read; + while ((read = input.read(buffer)) >= 0) { + total += read; + if (total > MAX_BODY) { + throw ApiException.tooLarge(); + } + output.write(buffer, 0, read); + } + return output.toByteArray(); + } + + private static JsonNode readObject(byte[] bytes) { + if (bytes.length == 0) { + throw ApiException.invalid("Пустое тело запроса"); + } + try (JsonParser parser = JSON.createParser(bytes)) { + JsonNode node = JSON.readTree(parser); + if (parser.nextToken() != null) { + throw ApiException.invalid("Некорректный JSON"); + } + if (node == null || !node.isObject()) { + throw ApiException.invalid("Ожидался JSON-объект"); + } + return node; + } catch (ApiException exception) { + throw exception; + } catch (Exception exception) { + throw ApiException.invalid("Некорректный JSON"); + } + } + + private static void allowOnly(JsonNode object, String... fields) { + Set allowed = Set.of(fields); + object.fieldNames().forEachRemaining(name -> { + if (!allowed.contains(name)) { + throw ApiException.invalid("В запросе есть лишние поля"); + } + }); + } + + private static String requiredText(JsonNode object, String field) { + if (!object.has(field) || object.get(field).isNull()) { + throw ApiException.invalid("Отсутствует поле " + field); + } + JsonNode node = object.get(field); + if (!node.isTextual()) { + throw ApiException.invalid("Поле " + field + " должно быть строкой"); + } + return node.textValue(); + } + + private static void requireCodePoints(String value, int min, int max, String field) { + int count = value.codePointCount(0, value.length()); + if (count < min || count > max || isBlank(value)) { + throw ApiException.invalid("Недопустимое значение " + field); + } + } + + private static boolean isBlank(String value) { + return value.codePoints().allMatch(cp -> Character.isWhitespace(cp) || Character.isSpaceChar(cp)); + } + + private static List memberIds(JsonNode object) { + if (!object.has("member_ids") || !object.get("member_ids").isArray()) { + throw ApiException.invalid("Поле member_ids должно быть массивом"); + } + ArrayNode array = (ArrayNode) object.get("member_ids"); + if (array.size() < 1 || array.size() > 100) { + throw ApiException.invalid("Недопустимое число участников"); + } + List ids = new ArrayList<>(); + for (JsonNode item : array) { + if (!item.isTextual() || !UUID_TEXT.matcher(item.textValue()).matches()) { + throw ApiException.invalid("Некорректный идентификатор участника"); + } + UUID id = UUID.fromString(item.textValue()); + if (ids.contains(id)) { + throw ApiException.invalid("Повторяющийся участник"); + } + ids.add(id); + } + return ids; + } + + private static void rejectQuery(HttpExchange exchange) { + String raw = exchange.getRequestURI().getRawQuery(); + if (raw != null && !raw.isEmpty()) { + throw ApiException.invalid("Неподдерживаемые параметры запроса"); + } + } + + private static Query pagingQuery(HttpExchange exchange) { + String raw = exchange.getRequestURI().getRawQuery(); + if (raw == null || raw.isEmpty()) { + return new Query(null, null); + } + java.util.Map> params = new java.util.LinkedHashMap<>(); + for (String part : raw.split("&", -1)) { + if (part.isEmpty()) { + continue; + } + int eq = part.indexOf('='); + String key = decode(eq < 0 ? part : part.substring(0, eq)); + String value = decode(eq < 0 ? "" : part.substring(eq + 1)); + params.computeIfAbsent(key, ignored -> new ArrayList<>()).add(value); + } + for (String key : params.keySet()) { + if (!key.equals("limit") && !key.equals("cursor")) { + throw ApiException.invalid("Неподдерживаемый параметр запроса"); + } + } + Integer limit = null; + if (params.containsKey("limit")) { + List values = params.get("limit"); + if (values.size() != 1 || !values.get(0).matches("[0-9]{1,3}")) { + throw ApiException.invalid("Некорректный limit"); + } + int parsed = Integer.parseInt(values.get(0)); + if (parsed < 1 || parsed > 100) { + throw ApiException.invalid("Некорректный limit"); + } + limit = parsed; + } + String cursor = null; + if (params.containsKey("cursor")) { + List values = params.get("cursor"); + if (values.size() != 1 || values.get(0).isEmpty()) { + throw ApiException.invalid("Некорректный cursor"); + } + cursor = values.get(0); + } + return new Query(limit, cursor); + } + + private static String decode(String value) { + try { + return URLDecoder.decode(value, StandardCharsets.UTF_8); + } catch (IllegalArgumentException exception) { + throw ApiException.invalid("Некорректная строка запроса"); + } + } + + private int writeSlice( + HttpExchange exchange, + String requestId, + List loaded, + int limit, + String kind, + UUID scope, + java.util.function.Function createdAt, + java.util.function.Function id, + java.util.function.Function json) throws IOException { + boolean more = loaded.size() > limit; + int end = more ? limit : loaded.size(); + ObjectNode page = JSON.createObjectNode(); + ArrayNode items = page.putArray("items"); + for (int i = 0; i < end; i++) { + items.add(json.apply(loaded.get(i))); + } + if (more && end > 0) { + T last = loaded.get(end - 1); + page.put("next_cursor", encodeCursor(kind, scope, createdAt.apply(last), id.apply(last))); + } else { + page.putNull("next_cursor"); + } + return writeJson(exchange, requestId, 200, page); + } + + private static String encodeCursor(String kind, UUID scope, Instant createdAt, UUID id) { + String raw = kind + "|" + scope + "|" + createdAt.toEpochMilli() + "|" + id; + return Base64.getUrlEncoder().withoutPadding().encodeToString(raw.getBytes(StandardCharsets.UTF_8)); + } + + private static Position decodeCursor(String cursor, String kind, UUID scope) { + byte[] decoded; + try { + decoded = Base64.getUrlDecoder().decode(pad(cursor)); + } catch (IllegalArgumentException exception) { + throw ApiException.invalid("Некорректный cursor"); + } + String raw = new String(decoded, StandardCharsets.UTF_8); + String[] parts = raw.split("\\|", -1); + if (parts.length != 4) { + throw ApiException.invalid("Некорректный cursor"); + } + if (!parts[0].equals(kind)) { + throw ApiException.invalid("Cursor относится к другому ресурсу"); + } + UUID cursorScope; + long millis; + UUID id; + try { + cursorScope = UUID.fromString(parts[1]); + millis = Long.parseLong(parts[2]); + id = UUID.fromString(parts[3]); + } catch (IllegalArgumentException exception) { + throw ApiException.invalid("Некорректный cursor"); + } + if (!cursorScope.equals(scope)) { + throw ApiException.invalid("Cursor относится к другому ресурсу"); + } + return new Position(Instant.ofEpochMilli(millis), id); + } + + private static String pad(String value) { + int mod = value.length() % 4; + if (mod == 0) { + return value; + } + return value + "====".substring(mod); + } + + private static ObjectNode health() { + return JSON.createObjectNode().put("status", "ok"); + } + + private static ObjectNode userJson(User user) { + ObjectNode node = JSON.createObjectNode(); + node.put("id", user.id().toString()); + node.put("username", user.username()); + node.put("display_name", user.displayName()); + node.put("created_at", DateTimeFormatter.ISO_INSTANT.format(user.createdAt())); + return node; + } + + private static ObjectNode chatJson(Chat chat) { + ObjectNode node = JSON.createObjectNode(); + node.put("id", chat.id().toString()); + node.put("title", chat.title()); + ArrayNode members = node.putArray("member_ids"); + for (UUID memberId : chat.memberIds()) { + members.add(memberId.toString()); + } + node.put("created_at", DateTimeFormatter.ISO_INSTANT.format(chat.createdAt())); + return node; + } + + private static ObjectNode messageJson(Message message) { + ObjectNode node = JSON.createObjectNode(); + node.put("id", message.id().toString()); + node.put("chat_id", message.chatId().toString()); + node.put("sender_id", message.senderId().toString()); + node.put("text", message.text()); + node.put("created_at", DateTimeFormatter.ISO_INSTANT.format(message.createdAt())); + return node; + } + + private int writeJson(HttpExchange exchange, String requestId, int status, JsonNode body) throws IOException { + byte[] bytes = JSON.writeValueAsBytes(body); + return writeBytes(exchange, requestId, status, bytes, null); + } + + private int writeEmpty(HttpExchange exchange, String requestId) throws IOException { + exchange.getResponseHeaders().set("X-Request-Id", requestId); + exchange.sendResponseHeaders(204, -1); + return 204; + } + + private int writeError(HttpExchange exchange, String requestId, ApiException exception) { + ObjectNode body = JSON.createObjectNode(); + ObjectNode errorNode = body.putObject("error"); + errorNode.put("code", exception.code); + errorNode.put("message", exception.clientMessage); + errorNode.put("request_id", requestId); + try { + byte[] bytes = JSON.writeValueAsBytes(body); + return writeBytes(exchange, requestId, exception.status, bytes, exception.challenge); + } catch (IOException ioException) { + error.accept("event=write_failed type=" + ioException.getClass().getName()); + return exception.status; + } + } + + private int writeBytes(HttpExchange exchange, String requestId, int status, byte[] body, String challenge) throws IOException { + exchange.getResponseHeaders().set("Content-Type", "application/json; charset=utf-8"); + exchange.getResponseHeaders().set("X-Request-Id", requestId); + if (challenge != null) { + exchange.getResponseHeaders().set("WWW-Authenticate", challenge); + } + exchange.sendResponseHeaders(status, body.length); + try (OutputStream output = exchange.getResponseBody()) { + output.write(body); + } + return status; + } + + private record Query(Integer limit, String cursor) { + } + + private record Position(Instant createdAt, UUID id) { + } + + private record ChatRoute(String idText, boolean messages) { + } + + private record Credentials(String username, String password) { + } +} diff --git a/src/main/java/ru/mtusi/lab2/Models.java b/src/main/java/ru/mtusi/lab2/Models.java new file mode 100644 index 00000000..3c02ab26 --- /dev/null +++ b/src/main/java/ru/mtusi/lab2/Models.java @@ -0,0 +1,14 @@ +package ru.mtusi.lab2; + +import java.time.Instant; +import java.util.List; +import java.util.UUID; + +record User(UUID id, String username, String displayName, Instant createdAt) { +} + +record Chat(UUID id, String title, List memberIds, Instant createdAt) { +} + +record Message(UUID id, UUID chatId, UUID senderId, String text, Instant createdAt) { +} diff --git a/src/main/java/ru/mtusi/lab2/Passwords.java b/src/main/java/ru/mtusi/lab2/Passwords.java new file mode 100644 index 00000000..83af9829 --- /dev/null +++ b/src/main/java/ru/mtusi/lab2/Passwords.java @@ -0,0 +1,40 @@ +package ru.mtusi.lab2; + +import at.favre.lib.crypto.bcrypt.BCrypt; +import at.favre.lib.crypto.bcrypt.LongPasswordStrategies; +import at.favre.lib.crypto.bcrypt.LongPasswordStrategy; + +/** + * bcrypt сам по себе обрезает пароль на 72 байтах. + * Перед ним пароль целиком проходит через SHA-512, поэтому длинный UTF-8 не теряется. + * Наружу уходит только строка bcrypt, не сам пароль. + */ +final class Passwords { + private final int cost; + private final BCrypt.Hasher hasher; + private final BCrypt.Verifyer verifyer; + private final String dummyHash; + + Passwords(int cost) { + if (cost < 4 || cost > 14) { + throw new IllegalArgumentException("bcrypt cost"); + } + this.cost = cost; + LongPasswordStrategy strategy = LongPasswordStrategies.hashSha512(BCrypt.Version.VERSION_2A); + this.hasher = BCrypt.with(BCrypt.Version.VERSION_2A, strategy); + this.verifyer = BCrypt.verifyer(BCrypt.Version.VERSION_2A, strategy); + this.dummyHash = hasher.hashToString(cost, "missing-user-timing".toCharArray()); + } + + String hash(String password) { + return hasher.hashToString(cost, password.toCharArray()); + } + + boolean verify(String password, String hash) { + return verifyer.verify(password.toCharArray(), hash).verified; + } + + void burnMissing(String password) { + verifyer.verify(password.toCharArray(), dummyHash); + } +} diff --git a/src/main/java/ru/mtusi/lab2/PostgresStore.java b/src/main/java/ru/mtusi/lab2/PostgresStore.java new file mode 100644 index 00000000..09985d92 --- /dev/null +++ b/src/main/java/ru/mtusi/lab2/PostgresStore.java @@ -0,0 +1,546 @@ +package ru.mtusi.lab2; + +import com.zaxxer.hikari.HikariConfig; +import com.zaxxer.hikari.HikariDataSource; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +/** + * Пользователи, чаты, участники и сообщения лежат в PostgreSQL. + * Создание чата и запись сообщения идут одной транзакцией вместе с монотонными часами. + * Пул ограничен, у соединения короткий таймаут: если БД недоступна, запрос заканчивается 503. + */ +final class PostgresStore implements AutoCloseable { + private final HikariDataSource dataSource; + private final Passwords passwords; + + PostgresStore(String jdbcUrl, String username, String password, Passwords passwords) { + HikariConfig config = new HikariConfig(); + config.setJdbcUrl(jdbcUrl); + config.setUsername(username); + config.setPassword(password); + config.setMaximumPoolSize(10); + config.setMinimumIdle(1); + config.setConnectionTimeout(2000); + config.setValidationTimeout(1000); + config.setInitializationFailTimeout(10000); + config.setConnectionInitSql("SET TIME ZONE 'UTC'"); + this.dataSource = new HikariDataSource(config); + this.passwords = passwords; + } + + void migrate() { + try (Connection conn = dataSource.getConnection()) { + conn.setAutoCommit(false); + try (Statement statement = conn.createStatement()) { + statement.execute(""" + CREATE TABLE IF NOT EXISTS schema_migrations ( + version text PRIMARY KEY, + applied_at timestamptz NOT NULL DEFAULT now() + ) + """); + } + if (!applied(conn, "V1")) { + runScript(conn, "/db/migration/V1__schema.sql"); + try (PreparedStatement insert = conn.prepareStatement( + "INSERT INTO schema_migrations (version) VALUES (?)")) { + insert.setString(1, "V1"); + insert.executeUpdate(); + } + } + conn.commit(); + } catch (SQLException | IOException e) { + throw new IllegalStateException("migration failed"); + } + } + + User createUser(String username, String displayName, String password) { + String hash = passwords.hash(password); + Connection conn = open(); + try { + conn.setAutoCommit(false); + long millis = tick(conn); + UUID id = UUID.randomUUID(); + try (PreparedStatement insert = conn.prepareStatement(""" + INSERT INTO users (id, username, display_name, password_hash, created_at) + VALUES (?, ?, ?, ?, ?) + """)) { + insert.setObject(1, id); + insert.setString(2, username); + insert.setString(3, displayName); + insert.setString(4, hash); + insert.setObject(5, timestamp(millis)); + insert.executeUpdate(); + } + User user = loadUser(conn, id).orElseThrow(ApiException::internalError); + conn.commit(); + return user; + } catch (ApiException e) { + rollback(conn); + throw e; + } catch (SQLException e) { + rollback(conn); + if ("23505".equals(e.getSQLState())) { + throw ApiException.conflict(); + } + throw map(e); + } finally { + close(conn); + } + } + + User authenticate(String username, String password) { + try (Connection conn = dataSource.getConnection(); + PreparedStatement statement = conn.prepareStatement(""" + SELECT id, username, display_name, password_hash, created_at + FROM users + WHERE username = ? + """)) { + statement.setString(1, username); + try (ResultSet rows = statement.executeQuery()) { + if (!rows.next()) { + passwords.burnMissing(password); + throw ApiException.unauthorized(null); + } + String hash = rows.getString("password_hash"); + if (!passwords.verify(password, hash)) { + throw ApiException.unauthorized(null); + } + return userFrom(rows); + } + } catch (ApiException e) { + throw e; + } catch (SQLException e) { + throw map(e); + } + } + + Optional findUser(UUID id) { + try (Connection conn = dataSource.getConnection()) { + return loadUser(conn, id); + } catch (SQLException e) { + throw map(e); + } + } + + Chat createChat(UUID callerId, String title, List memberIds) { + if (!memberIds.contains(callerId)) { + throw ApiException.invalid("Создатель чата должен входить в список участников"); + } + Connection conn = open(); + try { + conn.setAutoCommit(false); + List locked = new ArrayList<>(memberIds); + locked.sort(UUID::compareTo); + for (UUID memberId : locked) { + if (!lockUser(conn, memberId)) { + throw ApiException.invalid("Указан неизвестный участник"); + } + } + long millis = tick(conn); + UUID chatId = UUID.randomUUID(); + try (PreparedStatement insert = conn.prepareStatement(""" + INSERT INTO chats (id, title, created_at) + VALUES (?, ?, ?) + """)) { + insert.setObject(1, chatId); + insert.setString(2, title); + insert.setObject(3, timestamp(millis)); + insert.executeUpdate(); + } + try (PreparedStatement member = conn.prepareStatement(""" + INSERT INTO chat_members (chat_id, user_id, position) + VALUES (?, ?, ?) + """)) { + for (int i = 0; i < memberIds.size(); i++) { + member.setObject(1, chatId); + member.setObject(2, memberIds.get(i)); + member.setInt(3, i); + member.addBatch(); + } + member.executeBatch(); + } + Chat chat = loadChat(conn, callerId, chatId).orElseThrow(ApiException::internalError); + conn.commit(); + return chat; + } catch (ApiException e) { + rollback(conn); + throw e; + } catch (SQLException e) { + rollback(conn); + if ("23503".equals(e.getSQLState())) { + throw ApiException.invalid("Указан неизвестный участник"); + } + throw map(e); + } finally { + close(conn); + } + } + + List chats(UUID userId, int limit, Instant afterTime, UUID afterId) { + String sql = """ + SELECT c.id, c.title, c.created_at + FROM chats c + JOIN chat_members cm ON cm.chat_id = c.id AND cm.user_id = ? + """; + if (afterTime != null) { + sql += " WHERE (c.created_at, c.id) > (?, ?)"; + } + sql += " ORDER BY c.created_at, c.id LIMIT ?"; + try (Connection conn = dataSource.getConnection(); + PreparedStatement statement = conn.prepareStatement(sql)) { + int index = 1; + statement.setObject(index++, userId); + if (afterTime != null) { + statement.setObject(index++, timestamp(afterTime)); + statement.setObject(index++, afterId); + } + statement.setInt(index, limit); + List chats = new ArrayList<>(); + try (ResultSet rows = statement.executeQuery()) { + while (rows.next()) { + UUID id = rows.getObject("id", UUID.class); + chats.add(new Chat( + id, + rows.getString("title"), + members(conn, id), + instant(rows, "created_at"))); + } + } + return chats; + } catch (SQLException e) { + throw map(e); + } + } + + Optional visibleChat(UUID userId, UUID chatId) { + try (Connection conn = dataSource.getConnection()) { + return loadChat(conn, userId, chatId); + } catch (SQLException e) { + throw map(e); + } + } + + Message addMessage(UUID senderId, UUID chatId, String text) { + Connection conn = open(); + try { + conn.setAutoCommit(false); + long millis = tick(conn); + UUID id = UUID.randomUUID(); + try (PreparedStatement insert = conn.prepareStatement(""" + INSERT INTO messages (id, chat_id, sender_id, body, created_at) + SELECT ?, ?, ?, ?, ? + WHERE EXISTS ( + SELECT 1 FROM chat_members WHERE chat_id = ? AND user_id = ? + ) + RETURNING id, chat_id, sender_id, body, created_at + """)) { + insert.setObject(1, id); + insert.setObject(2, chatId); + insert.setObject(3, senderId); + insert.setString(4, text); + insert.setObject(5, timestamp(millis)); + insert.setObject(6, chatId); + insert.setObject(7, senderId); + try (ResultSet rows = insert.executeQuery()) { + if (!rows.next()) { + throw ApiException.notFound(); + } + Message message = messageFrom(rows); + conn.commit(); + return message; + } + } + } catch (ApiException e) { + rollback(conn); + throw e; + } catch (SQLException e) { + rollback(conn); + throw map(e); + } finally { + close(conn); + } + } + + List messages(UUID userId, UUID chatId, int limit, Instant afterTime, UUID afterId) { + try (Connection conn = dataSource.getConnection()) { + if (loadChat(conn, userId, chatId).isEmpty()) { + throw ApiException.notFound(); + } + String sql = """ + SELECT id, chat_id, sender_id, body, created_at + FROM messages + WHERE chat_id = ? + """; + if (afterTime != null) { + sql += " AND (created_at, id) > (?, ?)"; + } + sql += " ORDER BY created_at, id LIMIT ?"; + try (PreparedStatement statement = conn.prepareStatement(sql)) { + int index = 1; + statement.setObject(index++, chatId); + if (afterTime != null) { + statement.setObject(index++, timestamp(afterTime)); + statement.setObject(index++, afterId); + } + statement.setInt(index, limit); + List messages = new ArrayList<>(); + try (ResultSet rows = statement.executeQuery()) { + while (rows.next()) { + messages.add(messageFrom(rows)); + } + } + return messages; + } + } catch (ApiException e) { + throw e; + } catch (SQLException e) { + throw map(e); + } + } + + String explainHistory(UUID chatId, Instant afterTime, UUID afterId) { + try (Connection conn = dataSource.getConnection()) { + try (Statement analyze = conn.createStatement()) { + analyze.execute("ANALYZE messages"); + } + try (PreparedStatement statement = conn.prepareStatement(""" + EXPLAIN (ANALYZE, BUFFERS) + SELECT id, chat_id, sender_id, body, created_at + FROM messages + WHERE chat_id = ? + AND (created_at, id) > (?, ?) + ORDER BY created_at, id + LIMIT 50 + """)) { + statement.setObject(1, chatId); + statement.setObject(2, timestamp(afterTime)); + statement.setObject(3, afterId); + StringBuilder plan = new StringBuilder(); + try (ResultSet rows = statement.executeQuery()) { + while (rows.next()) { + plan.append(rows.getString(1)).append('\n'); + } + } + return plan.toString(); + } + } catch (SQLException e) { + throw map(e); + } + } + + boolean ready() { + try (Connection conn = dataSource.getConnection(); + Statement statement = conn.createStatement()) { + statement.setQueryTimeout(2); + statement.execute("SELECT 1"); + return true; + } catch (SQLException e) { + return false; + } + } + + @Override + public void close() { + dataSource.close(); + } + + private boolean applied(Connection conn, String version) throws SQLException { + try (PreparedStatement statement = conn.prepareStatement( + "SELECT 1 FROM schema_migrations WHERE version = ?")) { + statement.setString(1, version); + try (ResultSet rows = statement.executeQuery()) { + return rows.next(); + } + } + } + + private void runScript(Connection conn, String resource) throws SQLException, IOException { + String sql; + try (InputStream input = PostgresStore.class.getResourceAsStream(resource)) { + if (input == null) { + throw new IOException("missing migration"); + } + sql = new String(input.readAllBytes(), StandardCharsets.UTF_8); + } + StringBuilder current = new StringBuilder(); + for (String line : sql.split("\n", -1)) { + if (line.trim().startsWith("--")) { + continue; + } + current.append(line).append('\n'); + } + for (String statement : current.toString().split(";")) { + String trimmed = statement.trim(); + if (trimmed.isEmpty()) { + continue; + } + try (Statement sqlStatement = conn.createStatement()) { + sqlStatement.execute(trimmed); + } + } + } + + private long tick(Connection conn) throws SQLException { + try (PreparedStatement statement = conn.prepareStatement(""" + UPDATE app_clock + SET millis = GREATEST(millis + 1, (EXTRACT(EPOCH FROM clock_timestamp()) * 1000)::bigint) + WHERE id = 1 + RETURNING millis + """); + ResultSet rows = statement.executeQuery()) { + if (!rows.next()) { + throw new SQLException("clock missing", "XX000"); + } + return rows.getLong(1); + } + } + + private boolean lockUser(Connection conn, UUID id) throws SQLException { + try (PreparedStatement statement = conn.prepareStatement( + "SELECT id FROM users WHERE id = ? FOR UPDATE")) { + statement.setObject(1, id); + try (ResultSet rows = statement.executeQuery()) { + return rows.next(); + } + } + } + + private Optional loadUser(Connection conn, UUID id) throws SQLException { + try (PreparedStatement statement = conn.prepareStatement(""" + SELECT id, username, display_name, created_at + FROM users + WHERE id = ? + """)) { + statement.setObject(1, id); + try (ResultSet rows = statement.executeQuery()) { + if (!rows.next()) { + return Optional.empty(); + } + return Optional.of(userFrom(rows)); + } + } + } + + private Optional loadChat(Connection conn, UUID userId, UUID chatId) throws SQLException { + try (PreparedStatement statement = conn.prepareStatement(""" + SELECT c.id, c.title, c.created_at + FROM chats c + JOIN chat_members cm ON cm.chat_id = c.id AND cm.user_id = ? + WHERE c.id = ? + """)) { + statement.setObject(1, userId); + statement.setObject(2, chatId); + try (ResultSet rows = statement.executeQuery()) { + if (!rows.next()) { + return Optional.empty(); + } + return Optional.of(new Chat( + rows.getObject("id", UUID.class), + rows.getString("title"), + members(conn, chatId), + instant(rows, "created_at"))); + } + } + } + + private List members(Connection conn, UUID chatId) throws SQLException { + try (PreparedStatement statement = conn.prepareStatement(""" + SELECT user_id + FROM chat_members + WHERE chat_id = ? + ORDER BY position + """)) { + statement.setObject(1, chatId); + List ids = new ArrayList<>(); + try (ResultSet rows = statement.executeQuery()) { + while (rows.next()) { + ids.add(rows.getObject("user_id", UUID.class)); + } + } + return List.copyOf(ids); + } + } + + private static User userFrom(ResultSet rows) throws SQLException { + return new User( + rows.getObject("id", UUID.class), + rows.getString("username"), + rows.getString("display_name"), + instant(rows, "created_at")); + } + + private static Message messageFrom(ResultSet rows) throws SQLException { + return new Message( + rows.getObject("id", UUID.class), + rows.getObject("chat_id", UUID.class), + rows.getObject("sender_id", UUID.class), + rows.getString("body"), + instant(rows, "created_at")); + } + + private static Instant instant(ResultSet rows, String column) throws SQLException { + OffsetDateTime value = rows.getObject(column, OffsetDateTime.class); + return Instant.ofEpochMilli(value.toInstant().toEpochMilli()); + } + + private static OffsetDateTime timestamp(long millis) { + return OffsetDateTime.ofInstant(Instant.ofEpochMilli(millis), ZoneOffset.UTC); + } + + private static OffsetDateTime timestamp(Instant instant) { + return OffsetDateTime.ofInstant(instant, ZoneOffset.UTC); + } + + private Connection open() { + try { + return dataSource.getConnection(); + } catch (SQLException e) { + throw map(e); + } + } + + private static void rollback(Connection conn) { + try { + conn.rollback(); + } catch (SQLException ignored) { + // соединение уже не годится, клиенту всё равно уйдёт ошибка + } + } + + private static void close(Connection conn) { + try { + conn.close(); + } catch (SQLException ignored) { + // пул сам выкинет сломанное соединение + } + } + + private static ApiException map(SQLException e) { + String state = e.getSQLState(); + if (state != null && (state.startsWith("08") || state.startsWith("53") || state.equals("57P01"))) { + return ApiException.dependency(); + } + String name = e.getClass().getName(); + if (name.contains("SQLTransientConnectionException") || name.contains("SQLTimeoutException")) { + return ApiException.dependency(); + } + System.err.println("event=sql state=" + (state == null ? "none" : state) + + " type=" + e.getClass().getSimpleName()); + return ApiException.internalError(); + } +} diff --git a/src/main/java/ru/mtusi/lab2/ReadyProbe.java b/src/main/java/ru/mtusi/lab2/ReadyProbe.java new file mode 100644 index 00000000..ed90e6a9 --- /dev/null +++ b/src/main/java/ru/mtusi/lab2/ReadyProbe.java @@ -0,0 +1,29 @@ +package ru.mtusi.lab2; + +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.time.Duration; + +public final class ReadyProbe { + private ReadyProbe() { + } + + public static void main(String[] args) { + String port = System.getenv().getOrDefault("APP_PORT", "8080"); + try { + HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(2)).build(); + HttpRequest request = HttpRequest.newBuilder(URI.create("http://127.0.0.1:" + port + "/health/ready")) + .timeout(Duration.ofSeconds(2)) + .GET() + .build(); + HttpResponse response = client.send(request, HttpResponse.BodyHandlers.discarding()); + if (response.statusCode() != 200) { + System.exit(1); + } + } catch (Exception e) { + System.exit(1); + } + } +} diff --git a/src/main/java/ru/mtusi/lab2/SessionStore.java b/src/main/java/ru/mtusi/lab2/SessionStore.java new file mode 100644 index 00000000..c0ed62a1 --- /dev/null +++ b/src/main/java/ru/mtusi/lab2/SessionStore.java @@ -0,0 +1,75 @@ +package ru.mtusi.lab2; + +import redis.clients.jedis.Jedis; +import redis.clients.jedis.JedisPool; +import redis.clients.jedis.JedisPoolConfig; +import redis.clients.jedis.exceptions.JedisException; + +import java.net.URI; +import java.time.Duration; +import java.util.Optional; +import java.util.UUID; + +/** + * Сессии живут только в Redis. Ключ sess: хранит id пользователя и снимается по TTL. + * На стенде у Redis включён AOF, поэтому после рестарта контейнера ключи остаются на volume. + */ +final class SessionStore implements AutoCloseable { + private final JedisPool pool; + + SessionStore(String redisUrl) { + JedisPoolConfig config = new JedisPoolConfig(); + config.setMaxTotal(16); + config.setMaxWait(Duration.ofMillis(1000)); + config.setTestOnBorrow(true); + this.pool = new JedisPool(config, URI.create(redisUrl), 1000); + } + + void save(String token, UUID userId, int ttlSeconds) { + try (Jedis jedis = pool.getResource()) { + jedis.setex(key(token), ttlSeconds, userId.toString()); + } catch (JedisException e) { + throw ApiException.dependency(); + } + } + + Optional find(String token) { + try (Jedis jedis = pool.getResource()) { + String value = jedis.get(key(token)); + if (value == null) { + return Optional.empty(); + } + return Optional.of(UUID.fromString(value)); + } catch (JedisException | IllegalArgumentException e) { + if (e instanceof IllegalArgumentException) { + return Optional.empty(); + } + throw ApiException.dependency(); + } + } + + boolean revoke(String token) { + try (Jedis jedis = pool.getResource()) { + return jedis.del(key(token)) == 1L; + } catch (JedisException e) { + throw ApiException.dependency(); + } + } + + boolean ready() { + try (Jedis jedis = pool.getResource()) { + return "PONG".equals(jedis.ping()); + } catch (JedisException e) { + return false; + } + } + + @Override + public void close() { + pool.close(); + } + + private static String key(String token) { + return "sess:" + token; + } +} diff --git a/src/main/resources/db/migration/V1__schema.sql b/src/main/resources/db/migration/V1__schema.sql new file mode 100644 index 00000000..384f9c74 --- /dev/null +++ b/src/main/resources/db/migration/V1__schema.sql @@ -0,0 +1,43 @@ +CREATE TABLE users ( + id uuid PRIMARY KEY, + username text NOT NULL, + display_name text NOT NULL, + password_hash text NOT NULL, + created_at timestamptz NOT NULL, + CONSTRAINT users_username_key UNIQUE (username) +); + +CREATE TABLE chats ( + id uuid PRIMARY KEY, + title text NOT NULL, + created_at timestamptz NOT NULL +); + +CREATE TABLE chat_members ( + chat_id uuid NOT NULL REFERENCES chats (id), + user_id uuid NOT NULL REFERENCES users (id), + position integer NOT NULL, + PRIMARY KEY (chat_id, user_id) +); + +CREATE TABLE messages ( + id uuid PRIMARY KEY, + chat_id uuid NOT NULL REFERENCES chats (id), + sender_id uuid NOT NULL REFERENCES users (id), + body text NOT NULL, + created_at timestamptz NOT NULL +); + +CREATE INDEX messages_history_idx ON messages (chat_id, created_at, id); + +CREATE INDEX chat_members_user_idx ON chat_members (user_id, chat_id); + +CREATE INDEX chats_order_idx ON chats (created_at, id); + +CREATE TABLE app_clock ( + id integer PRIMARY KEY, + millis bigint NOT NULL, + CONSTRAINT app_clock_one CHECK (id = 1) +); + +INSERT INTO app_clock (id, millis) VALUES (1, 0); diff --git a/src/test/java/ru/mtusi/lab2/LabBehaviorTest.java b/src/test/java/ru/mtusi/lab2/LabBehaviorTest.java new file mode 100644 index 00000000..538fd3d0 --- /dev/null +++ b/src/test/java/ru/mtusi/lab2/LabBehaviorTest.java @@ -0,0 +1,581 @@ +package ru.mtusi.lab2; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.json.JsonMapper; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.api.Timeout; + +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.Statement; +import java.time.Duration; +import java.time.Instant; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +@Timeout(value = 4, unit = TimeUnit.MINUTES) +class LabBehaviorTest { + private static final JsonMapper JSON = new JsonMapper(); + private static final List LOGS = new CopyOnWriteArrayList<>(); + private static final HttpClient HTTP = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(3)).build(); + + private static final String POSTGRES_NAME = "mtusi-lab2-test-pg"; + private static final String REDIS_NAME = "mtusi-lab2-test-redis"; + private static final String DB_USER = "messenger"; + private static final String DB_PASSWORD = "messenger"; + + private static MessengerServer server; + private static String base; + private static String jdbcUrl; + private static int redisPort; + + @BeforeAll + static void start() throws Exception { + docker("rm", "-f", POSTGRES_NAME); + docker("rm", "-f", REDIS_NAME); + docker("run", "-d", "--name", POSTGRES_NAME, + "-e", "POSTGRES_USER=" + DB_USER, + "-e", "POSTGRES_PASSWORD=" + DB_PASSWORD, + "-e", "POSTGRES_DB=messenger", + "-p", "127.0.0.1::5432", + "postgres:16.6"); + docker("run", "-d", "--name", REDIS_NAME, + "-p", "127.0.0.1::6379", + "redis:7.4.2"); + waitUntil(POSTGRES_NAME, "pg_isready", "-U", DB_USER, "-d", "messenger"); + waitUntil(REDIS_NAME, "redis-cli", "ping"); + int pgPort = publishedPort(POSTGRES_NAME, 5432); + redisPort = publishedPort(REDIS_NAME, 6379); + jdbcUrl = "jdbc:postgresql://127.0.0.1:" + pgPort + "/messenger?connectTimeout=2&socketTimeout=2"; + String redisUrl = "redis://127.0.0.1:" + redisPort + "/0"; + Config config = new Config("127.0.0.1", 0, "test", jdbcUrl, DB_USER, DB_PASSWORD, redisUrl, 3600, 4); + server = MessengerServer.start(config, LOGS::add, LOGS::add); + base = "http://127.0.0.1:" + server.port(); + } + + @AfterAll + static void stop() { + if (server != null) { + server.stop(); + } + try { + docker("rm", "-f", POSTGRES_NAME); + docker("rm", "-f", REDIS_NAME); + } catch (Exception ignored) { + // контейнеры тестов уже сняты + } + } + + @Test + @Order(1) + void migrationCanRunAgain() throws Exception { + Passwords passwords = new Passwords(4); + try (PostgresStore again = new PostgresStore(jdbcUrl, DB_USER, DB_PASSWORD, passwords)) { + again.migrate(); + again.migrate(); + } + assertEquals(1, queryInt("SELECT count(*) FROM schema_migrations")); + assertEquals(1, queryInt("SELECT count(*) FROM app_clock")); + } + + @Test + @Order(2) + void authValidationAndHistory() throws Exception { + Resp live = call("GET", "/health/live", null, null); + assertEquals(200, live.status); + Resp ready = call("GET", "/health/ready", null, null); + assertEquals(200, ready.status); + + Resp broken = call("POST", "/api/v1/users", null, "{"); + assertEquals(400, broken.status); + Resp typed = call("POST", "/api/v1/users", null, "{\"username\":1,\"display_name\":\"Аня\",\"password\":\"password-ok-12\"}"); + assertEquals(400, typed.status); + Resp extra = call("POST", "/api/v1/users", null, + "{\"username\":\"bad_extra_user\",\"display_name\":\"Аня\",\"password\":\"password-ok-12\",\"role\":\"x\"}"); + assertEquals(400, extra.status); + Resp shortPassword = call("POST", "/api/v1/users", null, + "{\"username\":\"short_pw_user\",\"display_name\":\"Аня\",\"password\":\"short\"}"); + assertEquals(400, shortPassword.status); + Resp blankName = call("POST", "/api/v1/users", null, + "{\"username\":\"blank_name_u\",\"display_name\":\" \",\"password\":\"password-ok-12\"}"); + assertEquals(400, blankName.status); + + String suffix = UUID.randomUUID().toString().substring(0, 8); + JsonNode alice = register("alice_" + suffix, "Алиса"); + JsonNode bob = register("bob_" + suffix, "Боб 👋"); + JsonNode eve = register("eve_" + suffix, "Ева"); + assertFalse(alice.toString().contains("password")); + Resp duplicate = call("POST", "/api/v1/users", null, userBody("alice_" + suffix, "Алиса")); + assertEquals(409, duplicate.status); + + Resp noAuth = call("GET", "/api/v1/users/me", null, null); + assertEquals(401, noAuth.status); + assertTrue(noAuth.challenge.toLowerCase().startsWith("bearer")); + Resp byUserId = call("GET", "/api/v1/users/me", null, null, "X-User-Id", alice.get("id").asText()); + assertEquals(401, byUserId.status); + + String aliceBasic = basic("alice_" + suffix, "password-ok-12"); + Resp wrong = call("POST", "/api/v1/auth/sessions", null, null, "Authorization", + basic("alice_" + suffix, "wrong-password-1")); + assertEquals(401, wrong.status); + assertTrue(wrong.challenge.toLowerCase().startsWith("basic")); + Resp basicOnBusiness = call("GET", "/api/v1/users/me", null, null, "Authorization", aliceBasic); + assertEquals(401, basicOnBusiness.status); + assertTrue(basicOnBusiness.challenge.toLowerCase().startsWith("bearer")); + + String aliceToken = login("alice_" + suffix); + String bobToken = login("bob_" + suffix); + String eveToken = login("eve_" + suffix); + Resp me = call("GET", "/api/v1/users/me", aliceToken, null, "X-User-Id", eve.get("id").asText()); + assertEquals(200, me.status); + assertEquals(alice.get("id").asText(), JSON.readTree(me.body).get("id").asText()); + + String chatBody = "{\"title\":\"Демо\",\"member_ids\":[\"" + alice.get("id").asText() + + "\",\"" + bob.get("id").asText() + "\"]}"; + Resp chat = call("POST", "/api/v1/chats", aliceToken, chatBody); + assertEquals(201, chat.status); + String chatId = JSON.readTree(chat.body).get("id").asText(); + Resp outsider = call("GET", "/api/v1/chats/" + chatId, eveToken, null); + assertEquals(404, outsider.status); + Resp hidden = call("GET", "/api/v1/chats?limit=100", eveToken, null); + assertEquals(200, hidden.status); + assertFalse(hidden.body.contains(chatId)); + + String secret = "synthetic-text-" + suffix; + Resp empty = call("POST", "/api/v1/chats/" + chatId + "/messages", aliceToken, "{\"text\":\"\"}"); + assertEquals(400, empty.status); + Resp foreign = call("POST", "/api/v1/chats/" + chatId + "/messages", eveToken, "{\"text\":\"чужое\"}"); + assertEquals(404, foreign.status); + Resp badLimit = call("GET", "/api/v1/chats/" + chatId + "/messages?limit=0", aliceToken, null); + assertEquals(400, badLimit.status); + Resp first = call("POST", "/api/v1/chats/" + chatId + "/messages", aliceToken, "{\"text\":\"" + secret + " 👋\"}"); + Resp second = call("POST", "/api/v1/chats/" + chatId + "/messages", bobToken, "{\"text\":\"ответ Боба\"}"); + assertEquals(201, first.status); + assertEquals(201, second.status); + Resp page1 = call("GET", "/api/v1/chats/" + chatId + "/messages?limit=1", bobToken, null); + JsonNode page1Json = JSON.readTree(page1.body); + assertEquals(1, page1Json.get("items").size()); + assertFalse(page1Json.get("next_cursor").isNull()); + String cursor = page1Json.get("next_cursor").asText(); + Resp page2 = call("GET", "/api/v1/chats/" + chatId + "/messages?limit=1&cursor=" + encode(cursor), aliceToken, null); + JsonNode page2Json = JSON.readTree(page2.body); + assertEquals(1, page2Json.get("items").size()); + assertTrue(page2Json.get("next_cursor").isNull()); + assertEquals(JSON.readTree(first.body).get("id").asText(), page1Json.get("items").get(0).get("id").asText()); + assertEquals(JSON.readTree(second.body).get("id").asText(), page2Json.get("items").get(0).get("id").asText()); + Resp stolen = call("GET", "/api/v1/chats/" + chatId + "/messages?limit=1&cursor=" + encode(cursor), eveToken, null); + assertEquals(404, stolen.status); + String joined = String.join("\n", LOGS); + assertFalse(joined.contains(secret)); + } + + @Test + @Order(3) + void parallelMessagesStayUnique() throws Exception { + String suffix = UUID.randomUUID().toString().substring(0, 8); + JsonNode user = register("par_" + suffix, "Параллель"); + String token = login("par_" + suffix); + Resp chat = call("POST", "/api/v1/chats", token, + "{\"title\":\"Гонка\",\"member_ids\":[\"" + user.get("id").asText() + "\"]}"); + String chatId = JSON.readTree(chat.body).get("id").asText(); + ExecutorService pool = Executors.newFixedThreadPool(10); + List> futures = new ArrayList<>(); + for (int i = 0; i < 100; i++) { + int n = i; + futures.add(pool.submit(() -> call("POST", "/api/v1/chats/" + chatId + "/messages", token, + "{\"text\":\"m-" + n + "\"}"))); + } + List ids = new ArrayList<>(); + for (Future future : futures) { + Resp response = future.get(); + assertEquals(201, response.status); + ids.add(JSON.readTree(response.body).get("id").asText()); + } + pool.shutdown(); + assertEquals(100, ids.stream().distinct().count()); + assertEquals(100, queryInt("SELECT count(*) FROM messages WHERE chat_id = '" + chatId + "'")); + System.out.println("CONCURRENCY PASS clients=10 messages=100 unique=100"); + } + + @Test + @Order(4) + void duplicateUsernameRace() throws Exception { + String username = "race_" + UUID.randomUUID().toString().substring(0, 8); + String body = userBody(username, "Гонка"); + int threads = 16; + ExecutorService pool = Executors.newFixedThreadPool(threads); + CyclicBarrier barrier = new CyclicBarrier(threads); + List> futures = new ArrayList<>(); + for (int i = 0; i < threads; i++) { + futures.add(pool.submit(() -> { + barrier.await(); + return call("POST", "/api/v1/users", null, body).status; + })); + } + int created = 0; + int conflict = 0; + for (Future future : futures) { + int status = future.get(); + if (status == 201) { + created++; + } else if (status == 409) { + conflict++; + } else { + throw new AssertionError("unexpected status " + status); + } + } + pool.shutdown(); + assertEquals(1, created); + assertEquals(threads - 1, conflict); + assertEquals(1, queryInt("SELECT count(*) FROM users WHERE username = '" + username + "'")); + } + + @Test + @Order(5) + void chatCreateRollsBack() throws Exception { + String suffix = UUID.randomUUID().toString().substring(0, 8); + JsonNode alice = register("rb_a_" + suffix, "Алиса"); + JsonNode bob = register("rb_b_" + suffix, "Боб"); + String token = login("rb_a_" + suffix); + int before = queryInt("SELECT count(*) FROM chats"); + try (Connection conn = open(); Statement statement = conn.createStatement()) { + statement.execute(""" + CREATE OR REPLACE FUNCTION lab_fail_second_member() RETURNS trigger + LANGUAGE plpgsql AS $$ + BEGIN + IF NEW.position > 0 THEN + RAISE EXCEPTION 'forced rollback'; + END IF; + RETURN NEW; + END; + $$ + """); + statement.execute(""" + CREATE TRIGGER lab_fail_second_member + BEFORE INSERT ON chat_members + FOR EACH ROW EXECUTE FUNCTION lab_fail_second_member() + """); + } + try { + Resp chat = call("POST", "/api/v1/chats", token, "{\"title\":\"Сломанный\",\"member_ids\":[\"" + + alice.get("id").asText() + "\",\"" + bob.get("id").asText() + "\"]}"); + assertEquals(500, chat.status); + assertEquals(before, queryInt("SELECT count(*) FROM chats")); + assertEquals(before, queryInt("SELECT count(DISTINCT chat_id) FROM chat_members")); + } finally { + try (Connection conn = open(); Statement statement = conn.createStatement()) { + statement.execute("DROP TRIGGER IF EXISTS lab_fail_second_member ON chat_members"); + statement.execute("DROP FUNCTION IF EXISTS lab_fail_second_member()"); + } + } + Resp recovered = call("POST", "/api/v1/chats", token, "{\"title\":\"После отката\",\"member_ids\":[\"" + + alice.get("id").asText() + "\",\"" + bob.get("id").asText() + "\"]}"); + assertEquals(201, recovered.status); + } + + @Test + @Order(6) + void expiryLogoutAndWrongPassword() throws Exception { + String suffix = UUID.randomUUID().toString().substring(0, 8); + register("ttl_" + suffix, "Короткий"); + String redisUrl = "redis://127.0.0.1:" + redisPort + "/0"; + List localLogs = new CopyOnWriteArrayList<>(); + MessengerServer shortServer = MessengerServer.start(new Config( + "127.0.0.1", 0, "test", jdbcUrl, DB_USER, DB_PASSWORD, redisUrl, 2, 4), + localLogs::add, localLogs::add); + try { + String shortBase = "http://127.0.0.1:" + shortServer.port(); + Resp session = callAt(shortBase, "POST", "/api/v1/auth/sessions", null, null, "Authorization", + basic("ttl_" + suffix, "password-ok-12")); + assertEquals(201, session.status); + JsonNode body = JSON.readTree(session.body); + assertTrue(Instant.parse(body.get("expires_at").asText()).isAfter(Instant.now())); + String token = body.get("token").asText(); + Thread.sleep(3500); + Resp expired = callAt(shortBase, "GET", "/api/v1/users/me", token, null, null, null); + assertEquals(401, expired.status); + } finally { + shortServer.stop(); + } + + register("out_" + suffix, "Выход"); + String token = login("out_" + suffix); + Resp denied = call("POST", "/api/v1/auth/sessions", null, null, "Authorization", + basic("out_" + suffix, "definitely-wrong")); + assertEquals(401, denied.status); + Resp logout = call("DELETE", "/api/v1/auth/sessions/current", token, null); + assertEquals(204, logout.status); + assertTrue(logout.body.isEmpty()); + Resp again = call("GET", "/api/v1/users/me", token, null); + assertEquals(401, again.status); + Resp secondLogout = call("DELETE", "/api/v1/auth/sessions/current", token, null); + assertEquals(401, secondLogout.status); + } + + @Test + @Order(7) + void dependencyLossDoesNotTrustAnonymous() throws Exception { + String suffix = UUID.randomUUID().toString().substring(0, 8); + register("dep_" + suffix, "Зависимость"); + String token = login("dep_" + suffix); + docker("pause", REDIS_NAME); + try { + Resp ready = call("GET", "/health/ready", null, null); + assertEquals(503, ready.status); + assertTrue(ready.body.contains("unavailable")); + Resp me = call("GET", "/api/v1/users/me", token, null); + assertEquals(503, me.status); + Resp anon = call("GET", "/api/v1/users/me", null, null); + assertEquals(401, anon.status); + } finally { + docker("unpause", REDIS_NAME); + } + waitReady(); + assertEquals(200, call("GET", "/api/v1/users/me", token, null).status); + + docker("pause", POSTGRES_NAME); + try { + Resp ready = call("GET", "/health/ready", null, null); + assertEquals(503, ready.status); + Resp me = call("GET", "/api/v1/users/me", token, null); + assertEquals(503, me.status); + } finally { + docker("unpause", POSTGRES_NAME); + } + waitReady(); + assertEquals(200, call("GET", "/api/v1/users/me", token, null).status); + } + + @Test + @Order(8) + void historyIndexServesThePage() throws Exception { + String suffix = UUID.randomUUID().toString().substring(0, 8); + JsonNode user = register("hist_" + suffix, "История"); + String token = login("hist_" + suffix); + Resp chat = call("POST", "/api/v1/chats", token, + "{\"title\":\"Индекс\",\"member_ids\":[\"" + user.get("id").asText() + "\"]}"); + UUID chatId = UUID.fromString(JSON.readTree(chat.body).get("id").asText()); + UUID sender = UUID.fromString(user.get("id").asText()); + Instant start = Instant.now().minusSeconds(60); + try (Connection conn = open(); + PreparedStatement insert = conn.prepareStatement(""" + INSERT INTO messages (id, chat_id, sender_id, body, created_at) + VALUES (?, ?, ?, ?, ?) + """)) { + for (int i = 0; i < 10_000; i++) { + insert.setObject(1, UUID.randomUUID()); + insert.setObject(2, chatId); + insert.setObject(3, sender); + insert.setString(4, "row-" + i); + insert.setObject(5, OffsetDateTime.ofInstant(start.plusMillis(i), ZoneOffset.UTC)); + insert.addBatch(); + if (i % 500 == 499) { + insert.executeBatch(); + } + } + insert.executeBatch(); + } + Instant cursorTime; + UUID cursorId; + try (Connection conn = open(); + PreparedStatement statement = conn.prepareStatement(""" + SELECT id, created_at + FROM messages + WHERE chat_id = ? + ORDER BY created_at, id + OFFSET 9900 LIMIT 1 + """)) { + statement.setObject(1, chatId); + try (ResultSet rows = statement.executeQuery()) { + assertTrue(rows.next()); + cursorId = rows.getObject("id", UUID.class); + cursorTime = rows.getObject("created_at", OffsetDateTime.class).toInstant(); + } + } + String plan = server.store().explainHistory(chatId, cursorTime, cursorId); + Path evidence = Path.of("evidence", "explain-plan.txt"); + Files.createDirectories(evidence.getParent()); + Files.writeString(evidence, "messages=10000\n\n" + plan); + assertTrue(plan.contains("messages_history_idx"), plan); + assertTrue(plan.contains("Buffers:"), plan); + assertFalse(plan.contains("Seq Scan"), plan); + Resp page = call("GET", "/api/v1/chats/" + chatId + "/messages?limit=50", token, null); + assertEquals(200, page.status); + assertEquals(50, JSON.readTree(page.body).get("items").size()); + System.out.println("EXPLAIN index=messages_history_idx rows=10000"); + } + + @Test + @Order(9) + void shutdownKeepsLiveness() throws Exception { + server.refuseNewRequests(); + assertEquals(200, call("GET", "/health/live", null, null).status); + assertEquals(503, call("GET", "/health/ready", null, null).status); + Resp post = call("POST", "/api/v1/users", null, userBody("after_stop", "Стоп")); + assertEquals(503, post.status); + } + + + private static void docker(String... args) throws Exception { + java.util.ArrayList command = new java.util.ArrayList<>(); + command.add("docker"); + command.addAll(java.util.List.of(args)); + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + String output = new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8); + if (process.waitFor() != 0 && !java.util.List.of(args).contains("-f")) { + throw new IllegalStateException(String.join(" ", command) + " -> " + output); + } + } + + private static void waitUntil(String container, String... exec) throws Exception { + long deadline = System.nanoTime() + Duration.ofSeconds(40).toNanos(); + while (System.nanoTime() < deadline) { + java.util.ArrayList command = new java.util.ArrayList<>(); + command.add("docker"); + command.add("exec"); + command.add(container); + command.addAll(java.util.List.of(exec)); + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + process.getInputStream().readAllBytes(); + if (process.waitFor() == 0) { + return; + } + Thread.sleep(500); + } + throw new IllegalStateException("container not ready: " + container); + } + + private static int publishedPort(String container, int port) throws Exception { + Process process = new ProcessBuilder("docker", "port", container, port + "/tcp") + .redirectErrorStream(true) + .start(); + String output = new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8).trim(); + if (process.waitFor() != 0 || output.isEmpty()) { + throw new IllegalStateException("no published port for " + container); + } + String first = output.split("\n")[0]; + return Integer.parseInt(first.substring(first.lastIndexOf(':') + 1)); + } + + private static JsonNode register(String username, String displayName) throws Exception { + Resp response = call("POST", "/api/v1/users", null, userBody(username, displayName)); + assertEquals(201, response.status, response.body); + return JSON.readTree(response.body); + } + + private static String login(String username) throws Exception { + Resp response = call("POST", "/api/v1/auth/sessions", null, null, "Authorization", basic(username, "password-ok-12")); + assertEquals(201, response.status, response.body); + return JSON.readTree(response.body).get("token").asText(); + } + + private static String userBody(String username, String displayName) { + return "{\"username\":\"" + username + "\",\"display_name\":\"" + displayName + "\",\"password\":\"password-ok-12\"}"; + } + + private static String basic(String username, String password) { + String raw = username + ":" + password; + return "Basic " + Base64.getEncoder().encodeToString(raw.getBytes(StandardCharsets.UTF_8)); + } + + private static String encode(String value) { + return java.net.URLEncoder.encode(value, StandardCharsets.UTF_8); + } + + private static void waitReady() throws Exception { + long deadline = System.nanoTime() + Duration.ofSeconds(20).toNanos(); + while (System.nanoTime() < deadline) { + if (call("GET", "/health/ready", null, null).status == 200) { + return; + } + Thread.sleep(300); + } + throw new AssertionError("ready did not recover"); + } + + private static int queryInt(String sql) throws Exception { + try (Connection conn = open(); + Statement statement = conn.createStatement(); + ResultSet rows = statement.executeQuery(sql)) { + rows.next(); + return rows.getInt(1); + } + } + + private static Connection open() throws Exception { + String plain = jdbcUrl.replaceAll("[?].*", ""); + return DriverManager.getConnection(plain, DB_USER, DB_PASSWORD); + } + + private static Resp call(String method, String path, String token, String json) throws Exception { + return call(method, path, token, json, null, null); + } + + private static Resp call(String method, String path, String token, String json, String header, String headerValue) throws Exception { + return callAt(base, method, path, token, json, header, headerValue); + } + + private static Resp callAt( + String root, + String method, + String path, + String token, + String json, + String header, + String headerValue) throws Exception { + HttpRequest.Builder builder = HttpRequest.newBuilder(URI.create(root + path)) + .timeout(Duration.ofSeconds(12)); + if (token != null) { + builder.header("Authorization", "Bearer " + token); + } + if (header != null) { + builder.header(header, headerValue); + } + if (json != null) { + builder.header("Content-Type", "application/json"); + builder.method(method, HttpRequest.BodyPublishers.ofString(json)); + } else if ("POST".equals(method) || "DELETE".equals(method)) { + builder.method(method, HttpRequest.BodyPublishers.noBody()); + } else { + builder.method(method, HttpRequest.BodyPublishers.noBody()); + } + HttpResponse response = HTTP.send(builder.build(), HttpResponse.BodyHandlers.ofString()); + return new Resp( + response.statusCode(), + response.body(), + response.headers().firstValue("WWW-Authenticate").orElse(""), + response.headers().firstValue("X-Request-Id").orElse("")); + } + + private record Resp(int status, String body, String challenge, String requestId) { + } +} diff --git a/src/test/java/ru/mtusi/lab2/PasswordTest.java b/src/test/java/ru/mtusi/lab2/PasswordTest.java new file mode 100644 index 00000000..91c314fc --- /dev/null +++ b/src/test/java/ru/mtusi/lab2/PasswordTest.java @@ -0,0 +1,19 @@ +package ru.mtusi.lab2; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class PasswordTest { + @Test + void longPasswordsAreNotTruncated() { + Passwords passwords = new Passwords(4); + String first = "п".repeat(80); + String second = "п".repeat(79) + "я"; + String hash = passwords.hash(first); + assertTrue(passwords.verify(first, hash)); + assertFalse(passwords.verify(second, hash)); + assertFalse(passwords.verify("other-password-value", hash)); + } +}