forked from mtusi2026/mtusi2026lab2
реализован уровень 3
This commit is contained in:
+22
-4
@@ -1,11 +1,29 @@
|
|||||||
# Copy to .env for your LOCAL synthetic test environment; never commit .env.
|
# Copy to .env for your LOCAL synthetic test environment; never commit .env.
|
||||||
# These are logical interface suggestions; map actual framework names in REPORT.md.
|
# Compose uses these values for interpolation in compose.yaml.
|
||||||
|
|
||||||
APP_HOST=0.0.0.0
|
APP_HOST=0.0.0.0
|
||||||
APP_PORT=8080
|
APP_PORT=8080
|
||||||
APP_ENV=lab
|
APP_ENV=lab
|
||||||
|
|
||||||
|
POSTGRES_USER=messenger
|
||||||
|
POSTGRES_DB=messenger
|
||||||
|
|
||||||
SESSION_TTL_SECONDS=3600
|
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=postgres
|
||||||
|
|
||||||
|
# File paths contain no secret values.
|
||||||
|
DATABASE_URL_FILE=/run/secrets/database_url
|
||||||
|
|
||||||
|
DB_MAX_CONNS=10
|
||||||
|
DB_MIN_CONNS=2
|
||||||
|
DB_MAX_CONN_LIFETIME=30m
|
||||||
|
DB_MAX_CONN_IDLE_TIME=5m
|
||||||
|
DB_HEALTH_CHECK_PERIOD=30s
|
||||||
|
DB_CONNECT_TIMEOUT=5s
|
||||||
|
DB_QUERY_TIMEOUT=3s
|
||||||
|
|
||||||
|
READINESS_TIMEOUT=2s
|
||||||
|
SHUTDOWN_TIMEOUT=10s
|
||||||
|
|
||||||
|
# Redis will be added for grade 4.
|
||||||
CACHE_URL_FILE=/run/secrets/cache_url
|
CACHE_URL_FILE=/run/secrets/cache_url
|
||||||
+4
-5
@@ -1,4 +1,4 @@
|
|||||||
FROM golang:1.27.1-alpine AS builder
|
FROM golang:1.27.1-alpine@sha256:8a5910f31396cd4d89662f56c68b3ae31d374308270a1c3bd96672ee5ed43414 AS builder
|
||||||
|
|
||||||
WORKDIR /build
|
WORKDIR /build
|
||||||
|
|
||||||
@@ -11,7 +11,7 @@ COPY internal/ ./internal/
|
|||||||
|
|
||||||
RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-w -s" -o /build/server ./cmd/server/main.go
|
RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-w -s" -o /build/server ./cmd/server/main.go
|
||||||
|
|
||||||
FROM alpine:3.24
|
FROM alpine:3.24@sha256:294b683cb724975bec92580e1e685676bd4b50bda910ddb8c51d4cabeaec77e6
|
||||||
|
|
||||||
RUN addgroup -g 1000 appgroup && \
|
RUN addgroup -g 1000 appgroup && \
|
||||||
adduser -u 1000 -G appgroup -s /bin/sh -D appuser
|
adduser -u 1000 -G appgroup -s /bin/sh -D appuser
|
||||||
@@ -26,9 +26,8 @@ USER appuser:appgroup
|
|||||||
|
|
||||||
EXPOSE 8080
|
EXPOSE 8080
|
||||||
|
|
||||||
# Проверка здоровья контейнера через /health/live и wget
|
HEALTHCHECK --interval=5s --timeout=3s --start-period=5s --retries=10 \
|
||||||
HEALTHCHECK --interval=5s --timeout=3s --start-period=2s --retries=3 \
|
CMD wget -qO- http://127.0.0.1:8080/health/ready || exit 1
|
||||||
CMD wget -qO- http://127.0.0.1:8080/health/live || exit 1
|
|
||||||
|
|
||||||
|
|
||||||
ENTRYPOINT ["/app/server"]
|
ENTRYPOINT ["/app/server"]
|
||||||
@@ -1,13 +1,91 @@
|
|||||||
|
GO ?= go
|
||||||
PYTHON ?= python3
|
PYTHON ?= python3
|
||||||
|
COMPOSE ?= docker compose
|
||||||
|
|
||||||
|
ENV_FILE ?= .env
|
||||||
BASE_URL ?= http://localhost:8080
|
BASE_URL ?= http://localhost:8080
|
||||||
CA_FILE ?=
|
CA_FILE ?=
|
||||||
ACTION_SCRIPT ?=
|
ACTION_SCRIPT ?=
|
||||||
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
|
||||||
|
|
||||||
.PHONY: help check validate test load test-persistence
|
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
||||||
|
COMPOSE_CMD = $(COMPOSE) --env-file "$(ENV_FILE)"
|
||||||
|
|
||||||
|
.PHONY: \
|
||||||
|
help \
|
||||||
|
init-env \
|
||||||
|
fmt \
|
||||||
|
fmt-check \
|
||||||
|
build \
|
||||||
|
go-test \
|
||||||
|
go-race \
|
||||||
|
go-vet \
|
||||||
|
go-check \
|
||||||
|
check \
|
||||||
|
validate \
|
||||||
|
test \
|
||||||
|
load \
|
||||||
|
test-persistence \
|
||||||
|
compose-config \
|
||||||
|
compose-build \
|
||||||
|
compose-up \
|
||||||
|
compose-down \
|
||||||
|
compose-ps \
|
||||||
|
compose-logs
|
||||||
|
|
||||||
help:
|
help:
|
||||||
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
|
@echo "init-env: create local .env from .env.example if missing"
|
||||||
|
@echo "fmt: format Go source files"
|
||||||
|
@echo "fmt-check: report unformatted Go source files"
|
||||||
|
@echo "build: compile the API"
|
||||||
|
@echo "go-test: run Go tests"
|
||||||
|
@echo "go-race: run Go tests with race detector"
|
||||||
|
@echo "go-vet: run static Go analysis"
|
||||||
|
@echo "go-check: run formatting, tests, race detector and vet"
|
||||||
|
@echo "check: run offline skeleton checks"
|
||||||
|
@echo "validate: validate the OpenAPI contract"
|
||||||
|
@echo "test: run public smoke test against a running API"
|
||||||
|
@echo "load: run synthetic load against a running API"
|
||||||
|
@echo "test-persistence: run persistence test with ACTION_SCRIPT"
|
||||||
|
@echo "compose-config: validate resolved Compose configuration"
|
||||||
|
@echo "compose-build: build application images"
|
||||||
|
@echo "compose-up: start the stack"
|
||||||
|
@echo "compose-down: stop the stack without deleting volumes"
|
||||||
|
@echo "compose-ps: show stack containers"
|
||||||
|
@echo "compose-logs: follow stack logs"
|
||||||
|
|
||||||
|
init-env:
|
||||||
|
@if [ -f "$(ENV_FILE)" ]; then \
|
||||||
|
echo "$(ENV_FILE) already exists; leaving it unchanged"; \
|
||||||
|
else \
|
||||||
|
cp .env.example "$(ENV_FILE)"; \
|
||||||
|
echo "Created $(ENV_FILE) from .env.example"; \
|
||||||
|
fi
|
||||||
|
|
||||||
|
fmt:
|
||||||
|
$(GO) fmt ./...
|
||||||
|
|
||||||
|
fmt-check:
|
||||||
|
@files="$$(find cmd internal student_tests -type f -name '*.go' -print)"; \
|
||||||
|
unformatted="$$(gofmt -l $$files)"; \
|
||||||
|
if [ -n "$$unformatted" ]; then \
|
||||||
|
echo "Unformatted Go files:"; \
|
||||||
|
echo "$$unformatted"; \
|
||||||
|
exit 1; \
|
||||||
|
fi
|
||||||
|
|
||||||
|
build:
|
||||||
|
$(GO) build ./cmd/server
|
||||||
|
|
||||||
|
go-test:
|
||||||
|
$(GO) test ./...
|
||||||
|
|
||||||
|
go-race:
|
||||||
|
$(GO) test -race ./...
|
||||||
|
|
||||||
|
go-vet:
|
||||||
|
$(GO) vet ./...
|
||||||
|
|
||||||
|
go-check: fmt-check go-test go-race go-vet
|
||||||
|
|
||||||
check:
|
check:
|
||||||
$(PYTHON) scripts/check_contract.py
|
$(PYTHON) scripts/check_contract.py
|
||||||
@@ -22,5 +100,30 @@ load:
|
|||||||
$(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
$(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||||
|
|
||||||
test-persistence:
|
test-persistence:
|
||||||
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2)
|
@test -n "$(ACTION_SCRIPT)" || \
|
||||||
$(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
|
(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)
|
||||||
|
|
||||||
|
compose-config:
|
||||||
|
@test -f "$(ENV_FILE)" || \
|
||||||
|
(echo "$(ENV_FILE) is missing; run: make init-env"; exit 2)
|
||||||
|
$(COMPOSE_CMD) config --quiet
|
||||||
|
|
||||||
|
compose-build:
|
||||||
|
$(COMPOSE_CMD) build
|
||||||
|
|
||||||
|
compose-up:
|
||||||
|
$(COMPOSE_CMD) up -d --build
|
||||||
|
|
||||||
|
compose-down:
|
||||||
|
$(COMPOSE_CMD) down
|
||||||
|
|
||||||
|
compose-ps:
|
||||||
|
$(COMPOSE_CMD) ps
|
||||||
|
|
||||||
|
compose-logs:
|
||||||
|
$(COMPOSE_CMD) logs --follow
|
||||||
@@ -1,37 +1,180 @@
|
|||||||
# Отчёт — лабораторная 2
|
# Отчёт — лабораторная 2
|
||||||
|
|
||||||
- Автор, группа: TODO
|
- Автор, группа: Чурилин, БВТ2301
|
||||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
- Целевая оценка: 5; выбран Track 2 «План запроса и восстановление»
|
||||||
- Commit/PR: TODO после публикации
|
- Commit/PR: уровень 3 подготовлен в рабочем дереве поверх `10b5842`; итоговые ссылки будут добавлены после публикации
|
||||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
- Использованные библиотеки: `pgx/v5`, `google/uuid`, `x/crypto/argon2`, `golang-migrate`
|
||||||
|
- Использованные источники: документация PostgreSQL, Go, Docker Compose и Redis; при проектировании, реализации и проверке использовался ИИ-ассистент
|
||||||
|
|
||||||
## Запуск из чистого clone
|
## Запуск из чистого clone
|
||||||
|
|
||||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
Проверенное окружение: Ubuntu 26.04 в WSL2, Go 1.27.1, Python 3.14.4,
|
||||||
|
Docker Engine 29.7.2, Docker Compose 5.5.0, PostgreSQL 16.15.
|
||||||
|
|
||||||
|
Создать локальную конфигурацию и секреты с синтетическими значениями:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cp .env.example .env
|
||||||
|
mkdir -p secrets
|
||||||
|
chmod 700 secrets
|
||||||
|
umask 077
|
||||||
|
|
||||||
|
LAB_DB_PASSWORD="$(openssl rand -hex 24)"
|
||||||
|
printf '%s\n' "$LAB_DB_PASSWORD" > secrets/postgres_password.txt
|
||||||
|
printf 'postgresql://messenger:%s@postgres:5432/messenger?sslmode=disable\n' \
|
||||||
|
"$LAB_DB_PASSWORD" > secrets/database_url.txt
|
||||||
|
unset LAB_DB_PASSWORD
|
||||||
|
|
||||||
|
chmod 600 secrets/postgres_password.txt secrets/database_url.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
`.env`, `.venv/` и `secrets/` исключены из Git. PostgreSQL не публикует порт на
|
||||||
|
host; API доступен на `http://localhost:8080`.
|
||||||
|
|
||||||
|
Проверить конфигурацию и запустить стенд:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
docker compose --env-file .env config --quiet
|
||||||
|
docker compose --env-file .env up -d --build
|
||||||
|
docker compose --env-file .env ps
|
||||||
|
```
|
||||||
|
|
||||||
|
Выполнить проверки:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
make go-check
|
||||||
|
make check
|
||||||
|
|
||||||
|
python3 -m venv .venv
|
||||||
|
.venv/bin/python -m pip install -r requirements-dev.txt
|
||||||
|
make validate PYTHON=.venv/bin/python
|
||||||
|
|
||||||
|
make test
|
||||||
|
docker compose run --rm migrate
|
||||||
|
make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
Безопасная остановка сохраняет named volume:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
docker compose --env-file .env down
|
||||||
|
```
|
||||||
|
|
||||||
|
Команда ниже намеренно и необратимо удаляет локальные учебные данные; она не
|
||||||
|
используется в persistence-сценарии:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
docker compose --env-file .env down --volumes
|
||||||
|
```
|
||||||
|
|
||||||
## Архитектура и решения
|
## Архитектура и решения
|
||||||
|
|
||||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab1, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
```text
|
||||||
|
HTTP client
|
||||||
|
-> request ID / logger / recovery
|
||||||
|
-> Basic login или Bearer authentication
|
||||||
|
-> HTTP handler
|
||||||
|
-> Repository
|
||||||
|
-> PostgreSQL
|
||||||
|
```
|
||||||
|
|
||||||
|
PostgreSQL является источником истины для пользователей, password hashes,
|
||||||
|
чатов, участников, сообщений и действующих сессий. `MemoryStore` сохранён
|
||||||
|
только для быстрых unit/regression-тестов и не используется production-сервером.
|
||||||
|
|
||||||
|
Стенд состоит из трёх Compose-сервисов:
|
||||||
|
|
||||||
|
- `postgres` — PostgreSQL 16.15 с named volume `postgres_data`;
|
||||||
|
- `migrate` — одноразовое применение версионированных миграций;
|
||||||
|
- `api` — собранное из исходников Go-приложение без постоянного локального состояния.
|
||||||
|
|
||||||
|
Образы закреплены одновременно версией и digest. Dockerfile использует
|
||||||
|
multi-stage build, а runtime-процесс запускается от непривилегированного
|
||||||
|
пользователя.
|
||||||
|
|
||||||
|
### Схема и транзакционные границы
|
||||||
|
|
||||||
|
Миграция создаёт `users`, `chats`, `chat_members`, `messages` и `sessions`.
|
||||||
|
Ограничения PostgreSQL окончательно обеспечивают уникальность username,
|
||||||
|
валидные длины строк, максимум 100 участников, внешние ключи и членство
|
||||||
|
отправителя в чате.
|
||||||
|
|
||||||
|
Создание чата и всех строк членства выполняется одной транзакцией. Любая ошибка
|
||||||
|
до `COMMIT` приводит к rollback. Сообщение вставляется через
|
||||||
|
`INSERT ... SELECT ... WHERE EXISTS`, поэтому проверка членства и вставка не
|
||||||
|
разделены окном гонки.
|
||||||
|
|
||||||
|
Чаты и сообщения упорядочены по `(created_at, id)`. Keyset cursor содержит
|
||||||
|
версию, timestamp, UUID объекта и UUID владельца запроса/чата. Запрос читает
|
||||||
|
`limit + 1`, чтобы определить `next_cursor` без отдельного `COUNT(*)`.
|
||||||
|
|
||||||
|
### Аутентификация и сессии
|
||||||
|
|
||||||
|
Регистрация требует пароль длиной 12–128 Unicode code points. Пароль хранится
|
||||||
|
как PHC-строка Argon2id с индивидуальной случайной солью. Неизвестный username
|
||||||
|
при login проходит фиктивную Argon2id-проверку, чтобы убрать очевидную разницу
|
||||||
|
во времени между неизвестным пользователем и неправильным паролем.
|
||||||
|
|
||||||
|
`POST /api/v1/auth/sessions` принимает Basic Auth и возвращает непрозрачный
|
||||||
|
Bearer-токен с 256 битами случайности. В PostgreSQL хранится только SHA-256
|
||||||
|
digest токена. Сессия имеет абсолютный `expires_at`, не продлевается при
|
||||||
|
использовании и физически удаляется при logout.
|
||||||
|
|
||||||
|
Остальные бизнес-endpoint принимают только Bearer. Заголовок `X-User-Id`
|
||||||
|
игнорируется. Неизвестный или чужой чат возвращает одинаковый 404, чтобы не
|
||||||
|
раскрывать существование объекта.
|
||||||
|
|
||||||
|
### Надёжность и конфигурация
|
||||||
|
|
||||||
|
`pgxpool` ограничен параметрами `DB_MIN_CONNS`/`DB_MAX_CONNS`; запросы,
|
||||||
|
подключение, readiness и graceful shutdown имеют отдельные timeout. Startup
|
||||||
|
выполняет PostgreSQL `Ping` и завершается с ошибкой, если обязательная БД
|
||||||
|
недоступна.
|
||||||
|
|
||||||
|
`/health/live` проверяет жизнь HTTP-процесса. `/health/ready` проверяет
|
||||||
|
PostgreSQL. Request ID присутствует в успешных ответах и ошибках, а logger не
|
||||||
|
записывает body, пароль, Bearer-токен или заголовок Authorization.
|
||||||
|
|
||||||
|
`scripts/restart.sh` перезапускает PostgreSQL с сохранением volume, ждёт его
|
||||||
|
healthcheck и затем перезапускает API. Миграции при этом не выполняются заново и
|
||||||
|
данные не seed-ятся.
|
||||||
|
|
||||||
## Доказательства критериев
|
## Доказательства критериев
|
||||||
|
|
||||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| Публичный smoke | make test | TODO | TODO |
|
| Компиляция, unit/regression и race | `make go-check` | PASS: tests, race detector и vet | `evidence/level3.md` |
|
||||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
| Структура skeleton | `make check` | PASS | `evidence/level3.md` |
|
||||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
| OpenAPI 3.1 и JSON Schema | `make validate PYTHON=.venv/bin/python` | PASS | `evidence/level3.md` |
|
||||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
| Compose-конфигурация | `make compose-config` | PASS | `evidence/level3.md` |
|
||||||
|
| Публичный API smoke | `make test` | PASS: lab2 public API scenario | `evidence/level3.md` |
|
||||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
| Повторный запуск миграций | `docker compose run --rm migrate` | `no change`, версия 1, `dirty=false` | `evidence/level3.md` |
|
||||||
|
| Persistence данных и сессии | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | PASS с прежним Bearer-токеном | `evidence/level3.md` |
|
||||||
|
| Схема PostgreSQL | запросы к `pg_catalog` | 5 прикладных таблиц, 12 индексов, 23 ограничения | `evidence/level3.md` |
|
||||||
|
| Защита локальных секретов | `git check-ignore` и `git ls-files` | `.env`, `.venv/`, `secrets/` игнорируются и не отслеживаются | `evidence/level3.md` |
|
||||||
|
|
||||||
## Эксперименты и отказы
|
## Эксперименты и отказы
|
||||||
|
|
||||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
|
||||||
|
|
||||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| TODO | TODO | TODO | TODO |
|
| Повторное применение мигратора | Схема и данные не дублируются | `no change`, migration version 1, `dirty=false` | Без простоя API; потерь нет |
|
||||||
|
| Restart API и PostgreSQL | Сохранить пользователей, чат, сообщение и действующую сессию | Public persistence test завершился PASS с токеном, хранившимся только в памяти теста | В пределах 90-секундного бюджета теста; потерь подтверждённых данных нет |
|
||||||
|
|
||||||
|
Проверка выполнялась на синтетических данных. После нескольких smoke и
|
||||||
|
persistence-запусков PostgreSQL содержал 18 пользователей, 6 чатов, 12 строк
|
||||||
|
членства, 9 сообщений и 15 действующих/неочищенных строк сессий.
|
||||||
|
|
||||||
## Ограничения и следующие шаги
|
## Ограничения и следующие шаги
|
||||||
|
|
||||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
- Уровень 4 ещё не реализован: Redis будет добавлен как необязательный
|
||||||
|
cache-aside кэш неизменяемых данных чата; PostgreSQL останется источником истины.
|
||||||
|
- Redis failure должен приводить к fallback в PostgreSQL, а не к потере данных
|
||||||
|
или отказу readiness.
|
||||||
|
- Нужны отдельные интеграционные проверки конкурентной регистрации, rollback
|
||||||
|
создания чата, короткого expiry и отказов Redis/PostgreSQL.
|
||||||
|
- Для уровня 4 требуется `EXPLAIN (ANALYZE, BUFFERS)` минимум на 10 000
|
||||||
|
сообщениях.
|
||||||
|
- Track 2 уровня 5 ещё не выполнен: нужны не менее 100 000 неравномерно
|
||||||
|
распределённых сообщений, сравнение вариантов индексов/запросов, стоимость
|
||||||
|
записи и проверенный backup/restore.
|
||||||
|
- Стенд учебный и одноузловой: он не обеспечивает HA PostgreSQL или API.
|
||||||
|
|||||||
+100
-39
@@ -10,86 +10,147 @@ import (
|
|||||||
"syscall"
|
"syscall"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"mtusi2026lab2/internal/config"
|
||||||
|
"mtusi2026lab2/internal/database"
|
||||||
"mtusi2026lab2/internal/store"
|
"mtusi2026lab2/internal/store"
|
||||||
"mtusi2026lab2/internal/transport/http/handlers"
|
"mtusi2026lab2/internal/transport/http/handlers"
|
||||||
"mtusi2026lab2/internal/transport/http/middleware"
|
"mtusi2026lab2/internal/transport/http/middleware"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
addr := os.Getenv("HTTP_ADDR")
|
cfg, err := config.Load()
|
||||||
if addr == "" {
|
if err != nil {
|
||||||
port := os.Getenv("PORT")
|
log.Fatalf("[FATAL] Invalid configuration: %v", err)
|
||||||
if port == "" {
|
|
||||||
port = "8080"
|
|
||||||
}
|
|
||||||
addr = "0.0.0.0:" + port
|
|
||||||
}
|
}
|
||||||
|
|
||||||
memStore := store.NewMemoryStore()
|
startupContext, startupCancel := context.WithTimeout(
|
||||||
h := handlers.NewHandler(memStore)
|
context.Background(),
|
||||||
|
cfg.DatabaseConnectTimeout,
|
||||||
|
)
|
||||||
|
|
||||||
|
databasePool, err := database.Open(startupContext, cfg)
|
||||||
|
startupCancel()
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("[FATAL] PostgreSQL initialization failed: %v", err)
|
||||||
|
}
|
||||||
|
defer databasePool.Close()
|
||||||
|
|
||||||
|
postgresStore := store.NewPostgreSQLStore(
|
||||||
|
databasePool,
|
||||||
|
cfg.DatabaseQueryTimeout,
|
||||||
|
)
|
||||||
|
|
||||||
|
handler := handlers.NewHandler(
|
||||||
|
postgresStore,
|
||||||
|
handlers.WithReadiness(
|
||||||
|
databasePool,
|
||||||
|
cfg.ReadinessTimeout,
|
||||||
|
),
|
||||||
|
handlers.WithSessionTTL(cfg.SessionTTL),
|
||||||
|
)
|
||||||
|
|
||||||
mux := http.NewServeMux()
|
mux := http.NewServeMux()
|
||||||
|
|
||||||
//паблик систем ручки
|
mux.HandleFunc("GET /health/live", handler.HealthLive)
|
||||||
mux.HandleFunc("GET /health/live", h.HealthLive)
|
mux.HandleFunc("GET /health/ready", handler.HealthReady)
|
||||||
mux.HandleFunc("GET /health/ready", h.HealthReady)
|
|
||||||
|
|
||||||
// паблик рег юзера
|
mux.HandleFunc(
|
||||||
mux.HandleFunc("POST /api/v1/users", h.CreateUser)
|
"POST /api/v1/auth/sessions",
|
||||||
|
handler.CreateSession,
|
||||||
|
)
|
||||||
|
|
||||||
//защищенные через мидлварьки
|
mux.HandleFunc("POST /api/v1/users", handler.CreateUser)
|
||||||
mux.HandleFunc("GET /api/v1/users/me", middleware.RequireAuth(memStore, h.GetMe))
|
|
||||||
|
|
||||||
mux.HandleFunc("POST /api/v1/chats", middleware.RequireAuth(memStore, h.CreateChat))
|
requireAuth := func(next http.HandlerFunc) http.HandlerFunc {
|
||||||
mux.HandleFunc("GET /api/v1/chats", middleware.RequireAuth(memStore, h.ListChats))
|
return middleware.RequireAuth(postgresStore, next)
|
||||||
mux.HandleFunc("GET /api/v1/chats/{chat_id}", middleware.RequireAuth(memStore, h.GetChat))
|
}
|
||||||
|
|
||||||
mux.HandleFunc("POST /api/v1/chats/{chat_id}/messages", middleware.RequireAuth(memStore, h.CreateMessage))
|
mux.HandleFunc(
|
||||||
mux.HandleFunc("GET /api/v1/chats/{chat_id}/messages", middleware.RequireAuth(memStore, h.GetMessages))
|
"GET /api/v1/users/me",
|
||||||
|
requireAuth(handler.GetMe),
|
||||||
|
)
|
||||||
|
|
||||||
|
mux.HandleFunc(
|
||||||
|
"DELETE /api/v1/auth/sessions/current",
|
||||||
|
requireAuth(handler.DeleteCurrentSession),
|
||||||
|
)
|
||||||
|
|
||||||
|
mux.HandleFunc(
|
||||||
|
"POST /api/v1/chats",
|
||||||
|
requireAuth(handler.CreateChat),
|
||||||
|
)
|
||||||
|
mux.HandleFunc(
|
||||||
|
"GET /api/v1/chats",
|
||||||
|
requireAuth(handler.ListChats),
|
||||||
|
)
|
||||||
|
mux.HandleFunc(
|
||||||
|
"GET /api/v1/chats/{chat_id}",
|
||||||
|
requireAuth(handler.GetChat),
|
||||||
|
)
|
||||||
|
mux.HandleFunc(
|
||||||
|
"POST /api/v1/chats/{chat_id}/messages",
|
||||||
|
requireAuth(handler.CreateMessage),
|
||||||
|
)
|
||||||
|
mux.HandleFunc(
|
||||||
|
"GET /api/v1/chats/{chat_id}/messages",
|
||||||
|
requireAuth(handler.GetMessages),
|
||||||
|
)
|
||||||
|
|
||||||
//конвейер
|
|
||||||
var rootHandler http.Handler = mux
|
var rootHandler http.Handler = mux
|
||||||
rootHandler = middleware.Recovery(rootHandler)
|
rootHandler = middleware.Recovery(rootHandler)
|
||||||
rootHandler = middleware.Logger(rootHandler)
|
rootHandler = middleware.Logger(rootHandler)
|
||||||
rootHandler = middleware.RequestID(rootHandler)
|
rootHandler = middleware.RequestID(rootHandler)
|
||||||
|
|
||||||
//конф сервака
|
|
||||||
server := &http.Server{
|
server := &http.Server{
|
||||||
Addr: addr,
|
Addr: cfg.HTTPAddress(),
|
||||||
Handler: rootHandler,
|
Handler: rootHandler,
|
||||||
ReadTimeout: 15 * time.Second,
|
ReadTimeout: 15 * time.Second,
|
||||||
WriteTimeout: 15 * time.Second,
|
WriteTimeout: 15 * time.Second,
|
||||||
IdleTimeout: 60 * time.Second,
|
IdleTimeout: 60 * time.Second,
|
||||||
}
|
}
|
||||||
|
|
||||||
//серв в рутине запущен
|
|
||||||
serverErrors := make(chan error, 1)
|
serverErrors := make(chan error, 1)
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
log.Printf("[INFO] Server starting on %s", addr)
|
log.Printf("[INFO] Server starting on %s", server.Addr)
|
||||||
serverErrors <- server.ListenAndServe()
|
serverErrors <- server.ListenAndServe()
|
||||||
}()
|
}()
|
||||||
|
|
||||||
shutdown := make(chan os.Signal, 1)
|
shutdownSignals := make(chan os.Signal, 1)
|
||||||
signal.Notify(shutdown, os.Interrupt, syscall.SIGTERM)
|
signal.Notify(
|
||||||
|
shutdownSignals,
|
||||||
|
os.Interrupt,
|
||||||
|
syscall.SIGTERM,
|
||||||
|
)
|
||||||
|
defer signal.Stop(shutdownSignals)
|
||||||
|
|
||||||
//падение/сигнал на выкл
|
|
||||||
select {
|
select {
|
||||||
case err := <-serverErrors:
|
case serverError := <-serverErrors:
|
||||||
if !errors.Is(err, http.ErrServerClosed) {
|
if !errors.Is(serverError, http.ErrServerClosed) {
|
||||||
log.Fatalf("[FATAL] Server crashed: %v", err)
|
log.Fatalf("[FATAL] Server crashed: %v", serverError)
|
||||||
}
|
}
|
||||||
|
|
||||||
case sig := <-shutdown:
|
case signalValue := <-shutdownSignals:
|
||||||
log.Printf("[INFO] Signal %v received. Starting graceful shutdown...", sig)
|
log.Printf(
|
||||||
|
"[INFO] Signal %v received. Starting graceful shutdown...",
|
||||||
|
signalValue,
|
||||||
|
)
|
||||||
|
|
||||||
// завершение не более чем за 10 секунд
|
shutdownContext, shutdownCancel := context.WithTimeout(
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
context.Background(),
|
||||||
defer cancel()
|
cfg.ShutdownTimeout,
|
||||||
|
)
|
||||||
|
defer shutdownCancel()
|
||||||
|
|
||||||
if err := server.Shutdown(ctx); err != nil {
|
if err := server.Shutdown(shutdownContext); err != nil {
|
||||||
log.Printf("[WARN] Graceful shutdown failed: %v. Forcing close.", err)
|
log.Printf(
|
||||||
|
"[WARN] Graceful shutdown failed: %v. Forcing close.",
|
||||||
|
err,
|
||||||
|
)
|
||||||
_ = server.Close()
|
_ = server.Close()
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Println("[INFO] Server stopped gracefully.")
|
log.Println("[INFO] Server stopped gracefully.")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,95 @@
|
|||||||
|
services:
|
||||||
|
postgres:
|
||||||
|
image: postgres:16.15-alpine3.24@sha256:721873c34ceb9f8d8fc265984940dc982404c105f19ad51be9fdc5970a6080ea
|
||||||
|
environment:
|
||||||
|
POSTGRES_USER: ${POSTGRES_USER:-messenger}
|
||||||
|
POSTGRES_DB: ${POSTGRES_DB:-messenger}
|
||||||
|
POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password
|
||||||
|
secrets:
|
||||||
|
- postgres_password
|
||||||
|
volumes:
|
||||||
|
- postgres_data:/var/lib/postgresql/data
|
||||||
|
healthcheck:
|
||||||
|
test:
|
||||||
|
[
|
||||||
|
"CMD-SHELL",
|
||||||
|
"pg_isready -U ${POSTGRES_USER:-messenger} -d ${POSTGRES_DB:-messenger}",
|
||||||
|
]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 10
|
||||||
|
start_period: 5s
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
migrate:
|
||||||
|
image: migrate/migrate:v4.20.1@sha256:76cc2074cb6642631f34a898ced71e6aeaa6b1a4d78c4daa743275a22e0c5be7
|
||||||
|
entrypoint: ["/bin/sh", "-ec"]
|
||||||
|
command:
|
||||||
|
- >
|
||||||
|
exec migrate
|
||||||
|
-path=/migrations
|
||||||
|
-database="$$(cat /run/secrets/database_url)"
|
||||||
|
up
|
||||||
|
secrets:
|
||||||
|
- database_url
|
||||||
|
volumes:
|
||||||
|
- ./migrations:/migrations:ro
|
||||||
|
depends_on:
|
||||||
|
postgres:
|
||||||
|
condition: service_healthy
|
||||||
|
restart: "no"
|
||||||
|
|
||||||
|
api:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
environment:
|
||||||
|
APP_HOST: ${APP_HOST:-0.0.0.0}
|
||||||
|
APP_PORT: ${APP_PORT:-8080}
|
||||||
|
APP_ENV: ${APP_ENV:-lab}
|
||||||
|
|
||||||
|
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||||
|
SESSION_STORE: ${SESSION_STORE:-postgres}
|
||||||
|
|
||||||
|
DATABASE_URL_FILE: ${DATABASE_URL_FILE:-/run/secrets/database_url}
|
||||||
|
|
||||||
|
DB_MAX_CONNS: ${DB_MAX_CONNS:-10}
|
||||||
|
DB_MIN_CONNS: ${DB_MIN_CONNS:-2}
|
||||||
|
DB_MAX_CONN_LIFETIME: ${DB_MAX_CONN_LIFETIME:-30m}
|
||||||
|
DB_MAX_CONN_IDLE_TIME: ${DB_MAX_CONN_IDLE_TIME:-5m}
|
||||||
|
DB_HEALTH_CHECK_PERIOD: ${DB_HEALTH_CHECK_PERIOD:-30s}
|
||||||
|
DB_CONNECT_TIMEOUT: ${DB_CONNECT_TIMEOUT:-5s}
|
||||||
|
DB_QUERY_TIMEOUT: ${DB_QUERY_TIMEOUT:-3s}
|
||||||
|
|
||||||
|
READINESS_TIMEOUT: ${READINESS_TIMEOUT:-2s}
|
||||||
|
SHUTDOWN_TIMEOUT: ${SHUTDOWN_TIMEOUT:-10s}
|
||||||
|
secrets:
|
||||||
|
- database_url
|
||||||
|
ports:
|
||||||
|
- "${APP_PORT:-8080}:${APP_PORT:-8080}"
|
||||||
|
depends_on:
|
||||||
|
postgres:
|
||||||
|
condition: service_healthy
|
||||||
|
migrate:
|
||||||
|
condition: service_completed_successfully
|
||||||
|
healthcheck:
|
||||||
|
test:
|
||||||
|
[
|
||||||
|
"CMD-SHELL",
|
||||||
|
"wget -qO- http://127.0.0.1:$${APP_PORT:-8080}/health/ready || exit 1",
|
||||||
|
]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 10
|
||||||
|
start_period: 5s
|
||||||
|
stop_grace_period: 15s
|
||||||
|
restart: unless-stopped
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
postgres_data:
|
||||||
|
|
||||||
|
secrets:
|
||||||
|
postgres_password:
|
||||||
|
file: ./secrets/postgres_password.txt
|
||||||
|
database_url:
|
||||||
|
file: ./secrets/database_url.txt
|
||||||
@@ -0,0 +1,233 @@
|
|||||||
|
# Проект хранения данных
|
||||||
|
|
||||||
|
## Источники истины
|
||||||
|
|
||||||
|
PostgreSQL является источником истины для пользователей, чатов, участников,
|
||||||
|
сообщений и сессий.
|
||||||
|
|
||||||
|
Redis будет использоваться как cache-aside кэш чатов, но не как источник
|
||||||
|
истины. Потеря Redis не должна приводить к потере данных.
|
||||||
|
|
||||||
|
## Общие решения
|
||||||
|
|
||||||
|
- Идентификаторы создаются приложением как UUID.
|
||||||
|
- Время назначается PostgreSQL и хранится как `TIMESTAMPTZ`.
|
||||||
|
- API возвращает время в UTC в формате RFC 3339.
|
||||||
|
- Чаты и сообщения упорядочиваются по `(created_at, id)`.
|
||||||
|
- Используется уровень изоляции `READ COMMITTED`.
|
||||||
|
- Все SQL-запросы параметризованы и выполняются с timeout.
|
||||||
|
- Snapshot между несколькими HTTP-запросами не гарантируется.
|
||||||
|
|
||||||
|
## Таблицы
|
||||||
|
|
||||||
|
### `users`
|
||||||
|
|
||||||
|
```text
|
||||||
|
id UUID PRIMARY KEY
|
||||||
|
username VARCHAR(32) NOT NULL UNIQUE
|
||||||
|
display_name TEXT NOT NULL
|
||||||
|
password_hash TEXT NOT NULL
|
||||||
|
created_at TIMESTAMPTZ NOT NULL
|
||||||
|
```
|
||||||
|
|
||||||
|
Ограничения:
|
||||||
|
|
||||||
|
- `username` соответствует `^[a-z0-9_]{3,32}$`;
|
||||||
|
- `display_name` содержит 1–100 символов и не состоит только из пробелов;
|
||||||
|
- `password_hash` содержит PHC-строку Argon2id;
|
||||||
|
- исходный пароль не хранится и не записывается в логи.
|
||||||
|
|
||||||
|
Уникальность `username` окончательно обеспечивает PostgreSQL. При конкурентной
|
||||||
|
регистрации нарушение уникальности преобразуется в HTTP 409.
|
||||||
|
|
||||||
|
### `chats`
|
||||||
|
|
||||||
|
```text
|
||||||
|
id UUID PRIMARY KEY
|
||||||
|
title TEXT NOT NULL
|
||||||
|
created_at TIMESTAMPTZ NOT NULL
|
||||||
|
```
|
||||||
|
|
||||||
|
Ограничения:
|
||||||
|
|
||||||
|
- `title` содержит 1–100 символов;
|
||||||
|
- `title` не состоит только из пробелов.
|
||||||
|
|
||||||
|
Индекс порядка:
|
||||||
|
|
||||||
|
```text
|
||||||
|
(created_at, id)
|
||||||
|
```
|
||||||
|
|
||||||
|
### `chat_members`
|
||||||
|
|
||||||
|
```text
|
||||||
|
chat_id UUID NOT NULL REFERENCES chats(id)
|
||||||
|
user_id UUID NOT NULL REFERENCES users(id)
|
||||||
|
position SMALLINT NOT NULL
|
||||||
|
```
|
||||||
|
|
||||||
|
Ограничения:
|
||||||
|
|
||||||
|
```text
|
||||||
|
PRIMARY KEY (chat_id, user_id)
|
||||||
|
UNIQUE (chat_id, position)
|
||||||
|
CHECK (position BETWEEN 0 AND 99)
|
||||||
|
```
|
||||||
|
|
||||||
|
`position` сохраняет порядок `member_ids` и ограничивает число участников
|
||||||
|
чата сотней.
|
||||||
|
|
||||||
|
Индекс для поиска чатов пользователя:
|
||||||
|
|
||||||
|
```text
|
||||||
|
(user_id, chat_id)
|
||||||
|
```
|
||||||
|
|
||||||
|
### `messages`
|
||||||
|
|
||||||
|
```text
|
||||||
|
id UUID PRIMARY KEY
|
||||||
|
chat_id UUID NOT NULL
|
||||||
|
sender_id UUID NOT NULL
|
||||||
|
text TEXT NOT NULL
|
||||||
|
created_at TIMESTAMPTZ NOT NULL
|
||||||
|
```
|
||||||
|
|
||||||
|
Ограничения:
|
||||||
|
|
||||||
|
- `text` содержит 1–4000 символов;
|
||||||
|
- `text` не состоит только из пробелов;
|
||||||
|
- `(chat_id, sender_id)` ссылается на
|
||||||
|
`chat_members(chat_id, user_id)`.
|
||||||
|
|
||||||
|
Составной внешний ключ гарантирует, что отправитель является участником чата.
|
||||||
|
|
||||||
|
Индекс истории:
|
||||||
|
|
||||||
|
```text
|
||||||
|
(chat_id, created_at, id)
|
||||||
|
```
|
||||||
|
|
||||||
|
### `sessions`
|
||||||
|
|
||||||
|
```text
|
||||||
|
token_hash BYTEA PRIMARY KEY
|
||||||
|
user_id UUID NOT NULL REFERENCES users(id)
|
||||||
|
created_at TIMESTAMPTZ NOT NULL
|
||||||
|
expires_at TIMESTAMPTZ NOT NULL
|
||||||
|
```
|
||||||
|
|
||||||
|
Ограничения:
|
||||||
|
|
||||||
|
```text
|
||||||
|
CHECK (octet_length(token_hash) = 32)
|
||||||
|
CHECK (expires_at > created_at)
|
||||||
|
```
|
||||||
|
|
||||||
|
Клиент получает непрозрачный токен с энтропией не менее 256 бит. В PostgreSQL
|
||||||
|
хранится только его SHA-256 digest.
|
||||||
|
|
||||||
|
Сессия действительна, пока строка существует и `expires_at` больше текущего
|
||||||
|
времени. Logout физически удаляет строку сессии.
|
||||||
|
|
||||||
|
Индекс для очистки истёкших сессий:
|
||||||
|
|
||||||
|
```text
|
||||||
|
(expires_at)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Транзакционные границы
|
||||||
|
|
||||||
|
### Регистрация
|
||||||
|
|
||||||
|
Хеш Argon2id вычисляется до обращения к БД. Пользователь создаётся одним
|
||||||
|
`INSERT`. Уникальное ограничение защищает от конкурентной регистрации
|
||||||
|
одинакового `username`.
|
||||||
|
|
||||||
|
### Создание чата
|
||||||
|
|
||||||
|
Одна транзакция:
|
||||||
|
|
||||||
|
1. Проверить существование всех участников.
|
||||||
|
2. Вставить чат.
|
||||||
|
3. Вставить всех участников с позициями.
|
||||||
|
4. Выполнить COMMIT.
|
||||||
|
|
||||||
|
Любая ошибка приводит к ROLLBACK всей операции.
|
||||||
|
|
||||||
|
### Отправка сообщения
|
||||||
|
|
||||||
|
Проверка членства и вставка сообщения выполняются согласованно. Предпочтительно
|
||||||
|
использовать один `INSERT ... SELECT ... WHERE EXISTS`.
|
||||||
|
|
||||||
|
Отсутствующий и чужой чат возвращают одинаковый HTTP 404.
|
||||||
|
|
||||||
|
### Сессии
|
||||||
|
|
||||||
|
При входе приложение проверяет Argon2id, создаёт случайный токен и сохраняет
|
||||||
|
его digest с абсолютным `expires_at`.
|
||||||
|
|
||||||
|
Аутентификация ищет digest токена и проверяет срок действия. Logout удаляет
|
||||||
|
текущую сессию. После COMMIT новый запрос с этим токеном получает HTTP 401.
|
||||||
|
|
||||||
|
## Курсорная пагинация
|
||||||
|
|
||||||
|
### Сообщения
|
||||||
|
|
||||||
|
Курсор содержит:
|
||||||
|
|
||||||
|
```text
|
||||||
|
version, created_at, message_id, chat_id
|
||||||
|
```
|
||||||
|
|
||||||
|
SQL-граница:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
WHERE chat_id = $1
|
||||||
|
AND (created_at, id) > ($2, $3)
|
||||||
|
ORDER BY created_at, id
|
||||||
|
LIMIT $4
|
||||||
|
```
|
||||||
|
|
||||||
|
### Чаты
|
||||||
|
|
||||||
|
Курсор содержит:
|
||||||
|
|
||||||
|
```text
|
||||||
|
version, created_at, chat_id, user_id
|
||||||
|
```
|
||||||
|
|
||||||
|
SQL-граница:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
WHERE member.user_id = $1
|
||||||
|
AND (chat.created_at, chat.id) > ($2, $3)
|
||||||
|
ORDER BY chat.created_at, chat.id
|
||||||
|
LIMIT $4
|
||||||
|
```
|
||||||
|
|
||||||
|
В обоих запросах передаётся `limit + 1`. Дополнительная строка определяет,
|
||||||
|
нужно ли возвращать `next_cursor`, без отдельного `COUNT(*)`.
|
||||||
|
|
||||||
|
## Миграции
|
||||||
|
|
||||||
|
Первая миграция создаёт таблицы в порядке:
|
||||||
|
|
||||||
|
1. `users`;
|
||||||
|
2. `chats`;
|
||||||
|
3. `chat_members`;
|
||||||
|
4. `messages`;
|
||||||
|
5. `sessions`.
|
||||||
|
|
||||||
|
Откат удаляет таблицы в обратном порядке.
|
||||||
|
|
||||||
|
Применённые миграции учитываются в отдельной таблице версий. Повторный запуск
|
||||||
|
не должен повторно создавать схему, дублировать или удалять данные.
|
||||||
|
|
||||||
|
Для применения используется `golang-migrate` версии `v4.20.1` как отдельный
|
||||||
|
Compose-сервис. Миграции не запускаются автоматически каждой API-репликой.
|
||||||
|
|
||||||
|
Инструмент хранит текущую версию и состояние применения в служебной таблице
|
||||||
|
`schema_migrations`. Неуспешная миграция останавливает запуск API и требует
|
||||||
|
явного разбора причины, а не автоматического `force`.
|
||||||
@@ -0,0 +1,145 @@
|
|||||||
|
# Доказательства уровня 3
|
||||||
|
|
||||||
|
Состояние: рабочее дерево поверх commit `10b5842`; итоговый commit уровня 3
|
||||||
|
создаётся после проверки staged diff.
|
||||||
|
|
||||||
|
## Окружение
|
||||||
|
|
||||||
|
```text
|
||||||
|
Ubuntu 26.04 LTS, WSL2
|
||||||
|
Go 1.27.1 linux/amd64
|
||||||
|
Python 3.14.4
|
||||||
|
Docker Engine 29.7.2
|
||||||
|
Docker Compose 5.5.0
|
||||||
|
PostgreSQL 16.15
|
||||||
|
8 логических CPU
|
||||||
|
MemTotal: 3905144 kB
|
||||||
|
```
|
||||||
|
|
||||||
|
Использованы локальные синтетические пользователи и сообщения. Session tokens,
|
||||||
|
пароли, database URL и содержимое secret-файлов в evidence не сохранялись.
|
||||||
|
|
||||||
|
## Статические и Go-проверки
|
||||||
|
|
||||||
|
```sh
|
||||||
|
make go-check
|
||||||
|
make check
|
||||||
|
make validate PYTHON=.venv/bin/python
|
||||||
|
make compose-config
|
||||||
|
git diff --check
|
||||||
|
```
|
||||||
|
|
||||||
|
Результат:
|
||||||
|
|
||||||
|
```text
|
||||||
|
go test ./... PASS
|
||||||
|
go test -race ./... PASS
|
||||||
|
go vet ./... PASS
|
||||||
|
check_contract.py PASS
|
||||||
|
validate_openapi.py PASS
|
||||||
|
docker compose config PASS
|
||||||
|
git diff --check PASS
|
||||||
|
```
|
||||||
|
|
||||||
|
## Публичный smoke
|
||||||
|
|
||||||
|
```sh
|
||||||
|
make test
|
||||||
|
```
|
||||||
|
|
||||||
|
```text
|
||||||
|
PASS: lab2 public API scenario; infrastructure and grading evidence remain separate.
|
||||||
|
```
|
||||||
|
|
||||||
|
Проверены регистрация, Basic login, Bearer authentication, запрет одного
|
||||||
|
`X-User-Id`, защита чужого чата, создание/чтение сообщений, cursor pagination,
|
||||||
|
ошибки входных данных и logout.
|
||||||
|
|
||||||
|
## Миграции
|
||||||
|
|
||||||
|
Повторный запуск:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
docker compose run --rm migrate
|
||||||
|
```
|
||||||
|
|
||||||
|
```text
|
||||||
|
no change
|
||||||
|
```
|
||||||
|
|
||||||
|
Состояние `schema_migrations`:
|
||||||
|
|
||||||
|
```text
|
||||||
|
version = 1
|
||||||
|
dirty = false
|
||||||
|
```
|
||||||
|
|
||||||
|
Фактически созданы прикладные таблицы `users`, `chats`, `chat_members`,
|
||||||
|
`messages`, `sessions`, а также служебная `schema_migrations`.
|
||||||
|
|
||||||
|
Каталог PostgreSQL подтвердил 12 индексов и 23 ограничения, включая:
|
||||||
|
|
||||||
|
- `users_username_unique`;
|
||||||
|
- `chat_members_primary_key`;
|
||||||
|
- `chat_members_position_unique`;
|
||||||
|
- `messages_sender_membership_foreign_key`;
|
||||||
|
- `messages_chat_created_at_id_idx`;
|
||||||
|
- `sessions_token_hash_length`;
|
||||||
|
- `sessions_expiry_after_creation`;
|
||||||
|
- `sessions_expires_at_idx`.
|
||||||
|
|
||||||
|
## Persistence
|
||||||
|
|
||||||
|
```sh
|
||||||
|
make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
```text
|
||||||
|
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
|
||||||
|
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||||
|
```
|
||||||
|
|
||||||
|
Hook последовательно перезапускает `postgres`, ждёт его healthcheck и
|
||||||
|
перезапускает `api`. `docker compose ps` после сценария показывал оба сервиса в
|
||||||
|
состоянии `healthy`. Named volume:
|
||||||
|
|
||||||
|
```text
|
||||||
|
mtusi2026lab2_postgres_data
|
||||||
|
```
|
||||||
|
|
||||||
|
После повторных smoke/persistence-проверок в volume находились только
|
||||||
|
синтетические данные:
|
||||||
|
|
||||||
|
```text
|
||||||
|
users=18 chats=6 memberships=12 messages=9 sessions=15
|
||||||
|
```
|
||||||
|
|
||||||
|
## Образы
|
||||||
|
|
||||||
|
```text
|
||||||
|
golang:1.27.1-alpine
|
||||||
|
sha256:8a5910f31396cd4d89662f56c68b3ae31d374308270a1c3bd96672ee5ed43414
|
||||||
|
alpine:3.24
|
||||||
|
sha256:294b683cb724975bec92580e1e685676bd4b50bda910ddb8c51d4cabeaec77e6
|
||||||
|
postgres:16.15-alpine3.24
|
||||||
|
sha256:721873c34ceb9f8d8fc265984940dc982404c105f19ad51be9fdc5970a6080ea
|
||||||
|
migrate/migrate:v4.20.1
|
||||||
|
sha256:76cc2074cb6642631f34a898ced71e6aeaa6b1a4d78c4daa743275a22e0c5be7
|
||||||
|
```
|
||||||
|
|
||||||
|
В Dockerfile и Compose используются ссылки `tag@digest`.
|
||||||
|
|
||||||
|
## Секреты и Git
|
||||||
|
|
||||||
|
`git check-ignore` подтвердил исключение:
|
||||||
|
|
||||||
|
```text
|
||||||
|
.env
|
||||||
|
.venv/
|
||||||
|
secrets/postgres_password.txt
|
||||||
|
secrets/database_url.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
`git ls-files` не обнаружил среди tracked-файлов `.env`, `.venv/`, `secrets/`
|
||||||
|
или временный `CONTEXT.md`. Поиск credential-паттернов нашёл только явно
|
||||||
|
обозначенный placeholder в `examples/requests.http`.
|
||||||
@@ -2,4 +2,17 @@ module mtusi2026lab2
|
|||||||
|
|
||||||
go 1.27.1
|
go 1.27.1
|
||||||
|
|
||||||
require github.com/google/uuid v1.6.0
|
require (
|
||||||
|
github.com/google/uuid v1.6.0
|
||||||
|
github.com/jackc/pgx/v5 v5.11.0
|
||||||
|
golang.org/x/crypto v0.57.0
|
||||||
|
)
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||||
|
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||||
|
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||||
|
golang.org/x/sync v0.23.0 // indirect
|
||||||
|
golang.org/x/sys v0.48.0 // indirect
|
||||||
|
golang.org/x/text v0.42.0 // indirect
|
||||||
|
)
|
||||||
|
|||||||
@@ -1,2 +1,32 @@
|
|||||||
|
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
|
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||||
|
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||||
|
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||||
|
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||||
|
github.com/jackc/pgx/v5 v5.11.0 h1:IzBBtyK9AHqf98cctWFifYSci2hgQR/cd56wB4p+ogg=
|
||||||
|
github.com/jackc/pgx/v5 v5.11.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
|
||||||
|
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||||
|
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
|
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||||
|
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
|
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||||
|
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||||
|
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
|
||||||
|
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
|
||||||
|
golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=
|
||||||
|
golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||||
|
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
|
||||||
|
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||||
|
golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI=
|
||||||
|
golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E=
|
||||||
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
|||||||
@@ -0,0 +1,264 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"os"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Config struct {
|
||||||
|
HTTPHost string
|
||||||
|
HTTPPort string
|
||||||
|
|
||||||
|
SessionTTL time.Duration
|
||||||
|
|
||||||
|
DatabaseURL string
|
||||||
|
DatabaseMaxConns int32
|
||||||
|
DatabaseMinConns int32
|
||||||
|
DatabaseMaxConnLifetime time.Duration
|
||||||
|
DatabaseMaxConnIdleTime time.Duration
|
||||||
|
DatabaseHealthCheckPeriod time.Duration
|
||||||
|
DatabaseConnectTimeout time.Duration
|
||||||
|
DatabaseQueryTimeout time.Duration
|
||||||
|
|
||||||
|
ReadinessTimeout time.Duration
|
||||||
|
ShutdownTimeout time.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
func Load() (Config, error) {
|
||||||
|
sessionTTL, err := secondsDurationFromEnv(
|
||||||
|
"SESSION_TTL_SECONDS",
|
||||||
|
3600,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return Config{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
databaseURL, err := requiredValueOrFile(
|
||||||
|
"DATABASE_URL",
|
||||||
|
"DATABASE_URL_FILE",
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return Config{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
databaseMaxConns, err := int32FromEnv("DB_MAX_CONNS", 10, 1)
|
||||||
|
if err != nil {
|
||||||
|
return Config{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
databaseMinConns, err := int32FromEnv("DB_MIN_CONNS", 2, 0)
|
||||||
|
if err != nil {
|
||||||
|
return Config{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
databaseMaxConnLifetime, err := durationFromEnv(
|
||||||
|
"DB_MAX_CONN_LIFETIME",
|
||||||
|
30*time.Minute,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return Config{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
databaseMaxConnIdleTime, err := durationFromEnv(
|
||||||
|
"DB_MAX_CONN_IDLE_TIME",
|
||||||
|
5*time.Minute,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return Config{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
databaseHealthCheckPeriod, err := durationFromEnv(
|
||||||
|
"DB_HEALTH_CHECK_PERIOD",
|
||||||
|
30*time.Second,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return Config{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
databaseConnectTimeout, err := durationFromEnv(
|
||||||
|
"DB_CONNECT_TIMEOUT",
|
||||||
|
5*time.Second,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return Config{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
databaseQueryTimeout, err := durationFromEnv(
|
||||||
|
"DB_QUERY_TIMEOUT",
|
||||||
|
3*time.Second,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return Config{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
readinessTimeout, err := durationFromEnv(
|
||||||
|
"READINESS_TIMEOUT",
|
||||||
|
2*time.Second,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return Config{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
shutdownTimeout, err := durationFromEnv(
|
||||||
|
"SHUTDOWN_TIMEOUT",
|
||||||
|
10*time.Second,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return Config{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if databaseMinConns > databaseMaxConns {
|
||||||
|
return Config{}, errors.New(
|
||||||
|
"DB_MIN_CONNS must not be greater than DB_MAX_CONNS",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return Config{
|
||||||
|
HTTPHost: envOrDefault("APP_HOST", "0.0.0.0"),
|
||||||
|
HTTPPort: envOrDefault("APP_PORT", "8080"),
|
||||||
|
SessionTTL: sessionTTL,
|
||||||
|
|
||||||
|
DatabaseURL: databaseURL,
|
||||||
|
DatabaseMaxConns: databaseMaxConns,
|
||||||
|
DatabaseMinConns: databaseMinConns,
|
||||||
|
DatabaseMaxConnLifetime: databaseMaxConnLifetime,
|
||||||
|
DatabaseMaxConnIdleTime: databaseMaxConnIdleTime,
|
||||||
|
DatabaseHealthCheckPeriod: databaseHealthCheckPeriod,
|
||||||
|
DatabaseConnectTimeout: databaseConnectTimeout,
|
||||||
|
DatabaseQueryTimeout: databaseQueryTimeout,
|
||||||
|
|
||||||
|
ReadinessTimeout: readinessTimeout,
|
||||||
|
ShutdownTimeout: shutdownTimeout,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c Config) HTTPAddress() string {
|
||||||
|
return net.JoinHostPort(c.HTTPHost, c.HTTPPort)
|
||||||
|
}
|
||||||
|
|
||||||
|
func requiredValueOrFile(valueEnv, fileEnv string) (string, error) {
|
||||||
|
value, valueExists := os.LookupEnv(valueEnv)
|
||||||
|
filePath, fileExists := os.LookupEnv(fileEnv)
|
||||||
|
|
||||||
|
if valueExists && fileExists {
|
||||||
|
return "", fmt.Errorf(
|
||||||
|
"%s and %s must not be set at the same time",
|
||||||
|
valueEnv,
|
||||||
|
fileEnv,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if valueExists {
|
||||||
|
value = strings.TrimSpace(value)
|
||||||
|
if value == "" {
|
||||||
|
return "", fmt.Errorf("%s must not be empty", valueEnv)
|
||||||
|
}
|
||||||
|
|
||||||
|
return value, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if fileExists {
|
||||||
|
filePath = strings.TrimSpace(filePath)
|
||||||
|
if filePath == "" {
|
||||||
|
return "", fmt.Errorf("%s must not be empty", fileEnv)
|
||||||
|
}
|
||||||
|
|
||||||
|
data, err := os.ReadFile(filePath)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("read %s: %w", fileEnv, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
value = strings.TrimSpace(string(data))
|
||||||
|
if value == "" {
|
||||||
|
return "", fmt.Errorf("file from %s must not be empty", fileEnv)
|
||||||
|
}
|
||||||
|
|
||||||
|
return value, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return "", fmt.Errorf("%s or %s must be set", valueEnv, fileEnv)
|
||||||
|
}
|
||||||
|
|
||||||
|
func envOrDefault(name, fallback string) string {
|
||||||
|
value := strings.TrimSpace(os.Getenv(name))
|
||||||
|
if value == "" {
|
||||||
|
return fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
|
||||||
|
func int32FromEnv(name string, fallback, minimum int32) (int32, error) {
|
||||||
|
raw := strings.TrimSpace(os.Getenv(name))
|
||||||
|
if raw == "" {
|
||||||
|
return fallback, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
value, err := strconv.ParseInt(raw, 10, 32)
|
||||||
|
if err != nil {
|
||||||
|
return 0, fmt.Errorf("%s must be an integer: %w", name, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if value < int64(minimum) {
|
||||||
|
return 0, fmt.Errorf("%s must be at least %d", name, minimum)
|
||||||
|
}
|
||||||
|
|
||||||
|
return int32(value), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func durationFromEnv(name string, fallback time.Duration) (time.Duration, error) {
|
||||||
|
raw := strings.TrimSpace(os.Getenv(name))
|
||||||
|
if raw == "" {
|
||||||
|
return fallback, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
value, err := time.ParseDuration(raw)
|
||||||
|
if err != nil {
|
||||||
|
return 0, fmt.Errorf(
|
||||||
|
"%s must be a Go duration such as 3s or 5m: %w",
|
||||||
|
name,
|
||||||
|
err,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if value <= 0 {
|
||||||
|
return 0, fmt.Errorf("%s must be positive", name)
|
||||||
|
}
|
||||||
|
|
||||||
|
return value, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func secondsDurationFromEnv(
|
||||||
|
name string,
|
||||||
|
fallbackSeconds int64,
|
||||||
|
) (time.Duration, error) {
|
||||||
|
raw := strings.TrimSpace(os.Getenv(name))
|
||||||
|
if raw == "" {
|
||||||
|
raw = strconv.FormatInt(fallbackSeconds, 10)
|
||||||
|
}
|
||||||
|
|
||||||
|
seconds, err := strconv.ParseInt(raw, 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
return 0, fmt.Errorf(
|
||||||
|
"%s must be an integer number of seconds: %w",
|
||||||
|
name,
|
||||||
|
err,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if seconds <= 0 {
|
||||||
|
return 0, fmt.Errorf("%s must be positive", name)
|
||||||
|
}
|
||||||
|
|
||||||
|
duration, err := time.ParseDuration(raw + "s")
|
||||||
|
if err != nil {
|
||||||
|
return 0, fmt.Errorf("%s is too large: %w", name, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return duration, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
package database
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"mtusi2026lab2/internal/config"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
)
|
||||||
|
|
||||||
|
func Open(
|
||||||
|
ctx context.Context,
|
||||||
|
cfg config.Config,
|
||||||
|
) (*pgxpool.Pool, error) {
|
||||||
|
poolConfig, err := pgxpool.ParseConfig(cfg.DatabaseURL)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("parse PostgreSQL configuration: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
poolConfig.MaxConns = cfg.DatabaseMaxConns
|
||||||
|
poolConfig.MinConns = cfg.DatabaseMinConns
|
||||||
|
poolConfig.MaxConnLifetime = cfg.DatabaseMaxConnLifetime
|
||||||
|
poolConfig.MaxConnIdleTime = cfg.DatabaseMaxConnIdleTime
|
||||||
|
poolConfig.HealthCheckPeriod = cfg.DatabaseHealthCheckPeriod
|
||||||
|
|
||||||
|
pool, err := pgxpool.NewWithConfig(ctx, poolConfig)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("create PostgreSQL pool: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewWithConfig создаёт структуру пула, но не гарантирует,
|
||||||
|
// что PostgreSQL уже доступен. Ping обеспечивает fail-fast.
|
||||||
|
if err := pool.Ping(ctx); err != nil {
|
||||||
|
pool.Close()
|
||||||
|
return nil, fmt.Errorf("ping PostgreSQL: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return pool, nil
|
||||||
|
}
|
||||||
+46
-13
@@ -23,6 +23,13 @@ type User struct {
|
|||||||
CreatedAt time.Time `json:"created_at"`
|
CreatedAt time.Time `json:"created_at"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type Session struct {
|
||||||
|
Token string `json:"token"`
|
||||||
|
TokenType string `json:"token_type"`
|
||||||
|
ExpiresAt time.Time `json:"expires_at"`
|
||||||
|
User User `json:"user"`
|
||||||
|
}
|
||||||
|
|
||||||
type Chat struct {
|
type Chat struct {
|
||||||
ID string `json:"id"`
|
ID string `json:"id"`
|
||||||
Title string `json:"title"`
|
Title string `json:"title"`
|
||||||
@@ -71,6 +78,10 @@ func ValidateChatInput(title string, memberIDs []string, callerID string) error
|
|||||||
return fmt.Errorf("member_ids cannot be empty")
|
return fmt.Errorf("member_ids cannot be empty")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if len(memberIDs) > 100 {
|
||||||
|
return fmt.Errorf("member_ids must contain at most 100 users")
|
||||||
|
}
|
||||||
|
|
||||||
hasCaller := false
|
hasCaller := false
|
||||||
seen := make(map[string]bool)
|
seen := make(map[string]bool)
|
||||||
|
|
||||||
@@ -78,6 +89,7 @@ func ValidateChatInput(title string, memberIDs []string, callerID string) error
|
|||||||
if _, err := uuid.Parse(id); err != nil {
|
if _, err := uuid.Parse(id); err != nil {
|
||||||
return fmt.Errorf("invalid member uuid: %s", id)
|
return fmt.Errorf("invalid member uuid: %s", id)
|
||||||
}
|
}
|
||||||
|
|
||||||
if seen[id] {
|
if seen[id] {
|
||||||
return fmt.Errorf("duplicate member_id: %s", id)
|
return fmt.Errorf("duplicate member_id: %s", id)
|
||||||
}
|
}
|
||||||
@@ -112,38 +124,59 @@ type CursorData struct {
|
|||||||
ChatID string
|
ChatID string
|
||||||
}
|
}
|
||||||
|
|
||||||
// EncodeCursor превращает время, message_id и chat_id в непрозрачную base64 строку
|
const messageCursorVersion = "v1"
|
||||||
|
|
||||||
func EncodeCursor(createdAt time.Time, messageID, chatID string) string {
|
func EncodeCursor(createdAt time.Time, messageID, chatID string) string {
|
||||||
raw := fmt.Sprintf("%s|%s|%s", createdAt.Format(time.RFC3339Nano), messageID, chatID)
|
raw := fmt.Sprintf(
|
||||||
return base64.StdEncoding.EncodeToString([]byte(raw))
|
"%s|%s|%s|%s",
|
||||||
|
messageCursorVersion,
|
||||||
|
createdAt.UTC().Format(time.RFC3339Nano),
|
||||||
|
messageID,
|
||||||
|
chatID,
|
||||||
|
)
|
||||||
|
|
||||||
|
return base64.RawURLEncoding.EncodeToString([]byte(raw))
|
||||||
}
|
}
|
||||||
|
|
||||||
// DecodeCursor декодирует строку курсора и проверяет, что он принадлежит именно этому чату
|
func DecodeCursor(
|
||||||
func DecodeCursor(cursorStr string, expectedChatID string) (*CursorData, error) {
|
cursorStr string,
|
||||||
bytes, err := base64.StdEncoding.DecodeString(cursorStr)
|
expectedChatID string,
|
||||||
|
) (*CursorData, error) {
|
||||||
|
raw, err := base64.RawURLEncoding.DecodeString(cursorStr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("invalid base64 cursor")
|
return nil, fmt.Errorf("invalid base64 cursor")
|
||||||
}
|
}
|
||||||
|
|
||||||
parts := strings.Split(string(bytes), "|")
|
parts := strings.Split(string(raw), "|")
|
||||||
if len(parts) != 3 {
|
if len(parts) != 4 {
|
||||||
return nil, fmt.Errorf("malformed cursor")
|
return nil, fmt.Errorf("malformed cursor")
|
||||||
}
|
}
|
||||||
|
|
||||||
t, err := time.Parse(time.RFC3339Nano, parts[0])
|
if parts[0] != messageCursorVersion {
|
||||||
|
return nil, fmt.Errorf("unsupported cursor version")
|
||||||
|
}
|
||||||
|
|
||||||
|
createdAt, err := time.Parse(time.RFC3339Nano, parts[1])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("invalid cursor timestamp")
|
return nil, fmt.Errorf("invalid cursor timestamp")
|
||||||
}
|
}
|
||||||
|
|
||||||
chatID := parts[2]
|
messageID := parts[2]
|
||||||
//защита из контракта: курсор от другого чата должен давать 400
|
chatID := parts[3]
|
||||||
|
|
||||||
|
if _, err := uuid.Parse(messageID); err != nil {
|
||||||
|
return nil, fmt.Errorf("invalid cursor message_id")
|
||||||
|
}
|
||||||
|
if _, err := uuid.Parse(chatID); err != nil {
|
||||||
|
return nil, fmt.Errorf("invalid cursor chat_id")
|
||||||
|
}
|
||||||
if chatID != expectedChatID {
|
if chatID != expectedChatID {
|
||||||
return nil, fmt.Errorf("cursor belongs to another chat")
|
return nil, fmt.Errorf("cursor belongs to another chat")
|
||||||
}
|
}
|
||||||
|
|
||||||
return &CursorData{
|
return &CursorData{
|
||||||
CreatedAt: t,
|
CreatedAt: createdAt.UTC(),
|
||||||
MessageID: parts[1],
|
MessageID: messageID,
|
||||||
ChatID: chatID,
|
ChatID: chatID,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,164 @@
|
|||||||
|
package security
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/subtle"
|
||||||
|
"encoding/base64"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"golang.org/x/crypto/argon2"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
argonMemory uint32 = 19 * 1024
|
||||||
|
argonIterations uint32 = 2
|
||||||
|
argonParallelism uint8 = 1
|
||||||
|
argonSaltLength = 16
|
||||||
|
argonKeyLength uint32 = 32
|
||||||
|
|
||||||
|
minPasswordLength = 12
|
||||||
|
maxPasswordLength = 128
|
||||||
|
)
|
||||||
|
|
||||||
|
var ErrInvalidPasswordHash = errors.New("invalid password hash")
|
||||||
|
|
||||||
|
func ValidatePassword(password string) error {
|
||||||
|
if !utf8.ValidString(password) {
|
||||||
|
return errors.New("password must be valid UTF-8")
|
||||||
|
}
|
||||||
|
|
||||||
|
length := utf8.RuneCountInString(password)
|
||||||
|
if length < minPasswordLength || length > maxPasswordLength {
|
||||||
|
return fmt.Errorf(
|
||||||
|
"password length must be between %d and %d code points",
|
||||||
|
minPasswordLength,
|
||||||
|
maxPasswordLength,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func HashPassword(password string) (string, error) {
|
||||||
|
if err := ValidatePassword(password); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
salt := make([]byte, argonSaltLength)
|
||||||
|
if _, err := rand.Read(salt); err != nil {
|
||||||
|
return "", fmt.Errorf("generate password salt: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
hash := argon2.IDKey(
|
||||||
|
[]byte(password),
|
||||||
|
salt,
|
||||||
|
argonIterations,
|
||||||
|
argonMemory,
|
||||||
|
argonParallelism,
|
||||||
|
argonKeyLength,
|
||||||
|
)
|
||||||
|
|
||||||
|
encodedSalt := base64.RawStdEncoding.EncodeToString(salt)
|
||||||
|
encodedHash := base64.RawStdEncoding.EncodeToString(hash)
|
||||||
|
|
||||||
|
encoded := fmt.Sprintf(
|
||||||
|
"$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
|
||||||
|
argon2.Version,
|
||||||
|
argonMemory,
|
||||||
|
argonIterations,
|
||||||
|
argonParallelism,
|
||||||
|
encodedSalt,
|
||||||
|
encodedHash,
|
||||||
|
)
|
||||||
|
|
||||||
|
return encoded, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func VerifyPassword(
|
||||||
|
password string,
|
||||||
|
encodedHash string,
|
||||||
|
) (bool, error) {
|
||||||
|
parameters, salt, expectedHash, err := decodePasswordHash(encodedHash)
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
|
||||||
|
actualHash := argon2.IDKey(
|
||||||
|
[]byte(password),
|
||||||
|
salt,
|
||||||
|
parameters.iterations,
|
||||||
|
parameters.memory,
|
||||||
|
parameters.parallelism,
|
||||||
|
uint32(len(expectedHash)),
|
||||||
|
)
|
||||||
|
|
||||||
|
matches := subtle.ConstantTimeCompare(
|
||||||
|
actualHash,
|
||||||
|
expectedHash,
|
||||||
|
) == 1
|
||||||
|
|
||||||
|
return matches, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type argonParameters struct {
|
||||||
|
memory uint32
|
||||||
|
iterations uint32
|
||||||
|
parallelism uint8
|
||||||
|
}
|
||||||
|
|
||||||
|
func decodePasswordHash(
|
||||||
|
encodedHash string,
|
||||||
|
) (argonParameters, []byte, []byte, error) {
|
||||||
|
parts := strings.Split(encodedHash, "$")
|
||||||
|
if len(parts) != 6 ||
|
||||||
|
parts[0] != "" ||
|
||||||
|
parts[1] != "argon2id" {
|
||||||
|
return argonParameters{}, nil, nil, ErrInvalidPasswordHash
|
||||||
|
}
|
||||||
|
|
||||||
|
var version int
|
||||||
|
if _, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil {
|
||||||
|
return argonParameters{}, nil, nil, ErrInvalidPasswordHash
|
||||||
|
}
|
||||||
|
|
||||||
|
if version != argon2.Version {
|
||||||
|
return argonParameters{}, nil, nil, ErrInvalidPasswordHash
|
||||||
|
}
|
||||||
|
|
||||||
|
var parameters argonParameters
|
||||||
|
if _, err := fmt.Sscanf(
|
||||||
|
parts[3],
|
||||||
|
"m=%d,t=%d,p=%d",
|
||||||
|
¶meters.memory,
|
||||||
|
¶meters.iterations,
|
||||||
|
¶meters.parallelism,
|
||||||
|
); err != nil {
|
||||||
|
return argonParameters{}, nil, nil, ErrInvalidPasswordHash
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ограничения не позволяют повреждённой строке из БД запросить
|
||||||
|
// гигантский объём памяти или процессорного времени.
|
||||||
|
if parameters.memory < 8*1024 ||
|
||||||
|
parameters.memory > 256*1024 ||
|
||||||
|
parameters.iterations < 1 ||
|
||||||
|
parameters.iterations > 10 ||
|
||||||
|
parameters.parallelism < 1 ||
|
||||||
|
parameters.parallelism > 8 {
|
||||||
|
return argonParameters{}, nil, nil, ErrInvalidPasswordHash
|
||||||
|
}
|
||||||
|
|
||||||
|
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
|
||||||
|
if err != nil || len(salt) < 16 || len(salt) > 64 {
|
||||||
|
return argonParameters{}, nil, nil, ErrInvalidPasswordHash
|
||||||
|
}
|
||||||
|
|
||||||
|
hash, err := base64.RawStdEncoding.DecodeString(parts[5])
|
||||||
|
if err != nil || len(hash) < 16 || len(hash) > 64 {
|
||||||
|
return argonParameters{}, nil, nil, ErrInvalidPasswordHash
|
||||||
|
}
|
||||||
|
|
||||||
|
return parameters, salt, hash, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
package security
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestPasswordHashAndVerify(t *testing.T) {
|
||||||
|
password := "Correct-password-123"
|
||||||
|
|
||||||
|
encodedHash, err := HashPassword(password)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("HashPassword returned error: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if strings.Contains(encodedHash, password) {
|
||||||
|
t.Fatal("encoded hash contains plaintext password")
|
||||||
|
}
|
||||||
|
|
||||||
|
matches, err := VerifyPassword(password, encodedHash)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("VerifyPassword returned error: %v", err)
|
||||||
|
}
|
||||||
|
if !matches {
|
||||||
|
t.Fatal("correct password did not match")
|
||||||
|
}
|
||||||
|
|
||||||
|
matches, err = VerifyPassword("Wrong-password-123", encodedHash)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("VerifyPassword returned error: %v", err)
|
||||||
|
}
|
||||||
|
if matches {
|
||||||
|
t.Fatal("wrong password matched")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPasswordHashesUseDifferentSalts(t *testing.T) {
|
||||||
|
password := "Correct-password-123"
|
||||||
|
|
||||||
|
firstHash, err := HashPassword(password)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("first HashPassword returned error: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
secondHash, err := HashPassword(password)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("second HashPassword returned error: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if firstHash == secondHash {
|
||||||
|
t.Fatal("equal passwords produced equal encoded hashes")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPasswordValidation(t *testing.T) {
|
||||||
|
testCases := []struct {
|
||||||
|
name string
|
||||||
|
password string
|
||||||
|
wantErr bool
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "minimum length",
|
||||||
|
password: "123456789012",
|
||||||
|
wantErr: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "unicode",
|
||||||
|
password: "пароль-проверка-123",
|
||||||
|
wantErr: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "colon is allowed",
|
||||||
|
password: "password:with:colon",
|
||||||
|
wantErr: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "too short",
|
||||||
|
password: "short",
|
||||||
|
wantErr: true,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, testCase := range testCases {
|
||||||
|
t.Run(testCase.name, func(t *testing.T) {
|
||||||
|
err := ValidatePassword(testCase.password)
|
||||||
|
|
||||||
|
if testCase.wantErr && err == nil {
|
||||||
|
t.Fatal("expected validation error")
|
||||||
|
}
|
||||||
|
if !testCase.wantErr && err != nil {
|
||||||
|
t.Fatalf("unexpected validation error: %v", err)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMalformedPasswordHash(t *testing.T) {
|
||||||
|
_, err := VerifyPassword(
|
||||||
|
"Correct-password-123",
|
||||||
|
"not-an-argon2-hash",
|
||||||
|
)
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected malformed hash error")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
package security
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/base64"
|
||||||
|
"fmt"
|
||||||
|
)
|
||||||
|
|
||||||
|
const sessionTokenBytes = 32
|
||||||
|
|
||||||
|
func GenerateSessionToken() (string, []byte, error) {
|
||||||
|
randomBytes := make([]byte, sessionTokenBytes)
|
||||||
|
|
||||||
|
if _, err := rand.Read(randomBytes); err != nil {
|
||||||
|
return "", nil, fmt.Errorf("generate session token: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
token := base64.RawURLEncoding.EncodeToString(randomBytes)
|
||||||
|
tokenHash := HashSessionToken(token)
|
||||||
|
|
||||||
|
return token, tokenHash, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func HashSessionToken(token string) []byte {
|
||||||
|
digest := sha256.Sum256([]byte(token))
|
||||||
|
|
||||||
|
hash := make([]byte, len(digest))
|
||||||
|
copy(hash, digest[:])
|
||||||
|
|
||||||
|
return hash
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
package security
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestGenerateSessionToken(t *testing.T) {
|
||||||
|
firstToken, firstHash, err := GenerateSessionToken()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("GenerateSessionToken returned error: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
secondToken, secondHash, err := GenerateSessionToken()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("GenerateSessionToken returned error: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if firstToken == secondToken {
|
||||||
|
t.Fatal("generated session tokens are equal")
|
||||||
|
}
|
||||||
|
|
||||||
|
if bytes.Equal(firstHash, secondHash) {
|
||||||
|
t.Fatal("generated session token hashes are equal")
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(firstHash) != 32 {
|
||||||
|
t.Fatalf("expected 32-byte token hash, got %d", len(firstHash))
|
||||||
|
}
|
||||||
|
|
||||||
|
recalculatedHash := HashSessionToken(firstToken)
|
||||||
|
if !bytes.Equal(firstHash, recalculatedHash) {
|
||||||
|
t.Fatal("token hash is not reproducible")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
package store
|
||||||
|
|
||||||
|
import "errors"
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrNotFound = errors.New("not found")
|
||||||
|
ErrConflict = errors.New("conflict")
|
||||||
|
ErrInvalidCursor = errors.New("invalid cursor")
|
||||||
|
)
|
||||||
@@ -11,12 +11,6 @@ import (
|
|||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
|
||||||
ErrNotFound = fmt.Errorf("not found")
|
|
||||||
ErrConflict = fmt.Errorf("conflict")
|
|
||||||
ErrInvalidCursor = fmt.Errorf("invalid cursor")
|
|
||||||
)
|
|
||||||
|
|
||||||
type MemoryStore struct {
|
type MemoryStore struct {
|
||||||
mu sync.RWMutex
|
mu sync.RWMutex
|
||||||
|
|
||||||
@@ -81,7 +75,11 @@ func (s *MemoryStore) CreateChat(title string, memberIDs []string) (domain.Chat,
|
|||||||
//все участники рил существуют
|
//все участники рил существуют
|
||||||
for _, memberID := range memberIDs {
|
for _, memberID := range memberIDs {
|
||||||
if _, exists := s.usersByID[memberID]; !exists {
|
if _, exists := s.usersByID[memberID]; !exists {
|
||||||
return domain.Chat{}, fmt.Errorf("member not found: %s", memberID)
|
return domain.Chat{}, fmt.Errorf(
|
||||||
|
"%w: member %s",
|
||||||
|
ErrNotFound,
|
||||||
|
memberID,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -286,9 +284,13 @@ func (s *MemoryStore) GetMessages(
|
|||||||
if cursorStr != "" {
|
if cursorStr != "" {
|
||||||
decodedCursor, err := domain.DecodeCursor(cursorStr, chatID)
|
decodedCursor, err := domain.DecodeCursor(cursorStr, chatID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return domain.MessagePage{},
|
return domain.MessagePage{}, fmt.Errorf(
|
||||||
fmt.Errorf("invalid cursor: %w", err)
|
"%w: %v",
|
||||||
|
ErrInvalidCursor,
|
||||||
|
err,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
cursorData = decodedCursor
|
cursorData = decodedCursor
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,247 @@
|
|||||||
|
package store
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"mtusi2026lab2/internal/domain"
|
||||||
|
)
|
||||||
|
|
||||||
|
type memorySession struct {
|
||||||
|
userID string
|
||||||
|
expiresAt time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
type MemoryRepository struct {
|
||||||
|
legacy *MemoryStore
|
||||||
|
|
||||||
|
mu sync.RWMutex
|
||||||
|
passwordByUserID map[string]string
|
||||||
|
userIDByUsername map[string]string
|
||||||
|
sessionsByHashKey map[[32]byte]memorySession
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewMemoryRepository(legacy *MemoryStore) *MemoryRepository {
|
||||||
|
return &MemoryRepository{
|
||||||
|
legacy: legacy,
|
||||||
|
passwordByUserID: make(map[string]string),
|
||||||
|
userIDByUsername: make(map[string]string),
|
||||||
|
sessionsByHashKey: make(map[[32]byte]memorySession),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *MemoryRepository) CreateUser(
|
||||||
|
ctx context.Context,
|
||||||
|
username string,
|
||||||
|
displayName string,
|
||||||
|
passwordHash string,
|
||||||
|
) (domain.User, error) {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return domain.User{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
user, err := r.legacy.CreateUser(username, displayName)
|
||||||
|
if err != nil {
|
||||||
|
return domain.User{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
r.mu.Lock()
|
||||||
|
r.passwordByUserID[user.ID] = passwordHash
|
||||||
|
r.userIDByUsername[user.Username] = user.ID
|
||||||
|
r.mu.Unlock()
|
||||||
|
|
||||||
|
return user, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *MemoryRepository) GetUserByID(
|
||||||
|
ctx context.Context,
|
||||||
|
userID string,
|
||||||
|
) (domain.User, error) {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return domain.User{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return r.legacy.GetUserByID(userID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *MemoryRepository) GetUserByUsername(
|
||||||
|
ctx context.Context,
|
||||||
|
username string,
|
||||||
|
) (domain.User, string, error) {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return domain.User{}, "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
r.mu.RLock()
|
||||||
|
userID, exists := r.userIDByUsername[username]
|
||||||
|
passwordHash := r.passwordByUserID[userID]
|
||||||
|
r.mu.RUnlock()
|
||||||
|
|
||||||
|
if !exists {
|
||||||
|
return domain.User{}, "", ErrNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
user, err := r.legacy.GetUserByID(userID)
|
||||||
|
if err != nil {
|
||||||
|
return domain.User{}, "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
return user, passwordHash, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *MemoryRepository) CreateChat(
|
||||||
|
ctx context.Context,
|
||||||
|
title string,
|
||||||
|
memberIDs []string,
|
||||||
|
) (domain.Chat, error) {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return domain.Chat{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return r.legacy.CreateChat(title, memberIDs)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *MemoryRepository) GetChatByID(
|
||||||
|
ctx context.Context,
|
||||||
|
chatID string,
|
||||||
|
callerID string,
|
||||||
|
) (domain.Chat, error) {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return domain.Chat{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return r.legacy.GetChatByID(chatID, callerID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *MemoryRepository) GetChatsForUser(
|
||||||
|
ctx context.Context,
|
||||||
|
userID string,
|
||||||
|
limit int,
|
||||||
|
cursor string,
|
||||||
|
) (domain.ChatPage, error) {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return domain.ChatPage{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return r.legacy.GetChatsForUser(userID, limit, cursor)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *MemoryRepository) CreateMessage(
|
||||||
|
ctx context.Context,
|
||||||
|
chatID string,
|
||||||
|
senderID string,
|
||||||
|
text string,
|
||||||
|
) (domain.Message, error) {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return domain.Message{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return r.legacy.CreateMessage(chatID, senderID, text)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *MemoryRepository) GetMessages(
|
||||||
|
ctx context.Context,
|
||||||
|
chatID string,
|
||||||
|
callerID string,
|
||||||
|
limit int,
|
||||||
|
cursor string,
|
||||||
|
) (domain.MessagePage, error) {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return domain.MessagePage{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return r.legacy.GetMessages(
|
||||||
|
chatID,
|
||||||
|
callerID,
|
||||||
|
limit,
|
||||||
|
cursor,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *MemoryRepository) CreateSession(
|
||||||
|
ctx context.Context,
|
||||||
|
tokenHash []byte,
|
||||||
|
userID string,
|
||||||
|
expiresAt time.Time,
|
||||||
|
) error {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
key, err := memoryTokenHashKey(tokenHash)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
r.mu.Lock()
|
||||||
|
r.sessionsByHashKey[key] = memorySession{
|
||||||
|
userID: userID,
|
||||||
|
expiresAt: expiresAt,
|
||||||
|
}
|
||||||
|
r.mu.Unlock()
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *MemoryRepository) GetUserBySession(
|
||||||
|
ctx context.Context,
|
||||||
|
tokenHash []byte,
|
||||||
|
) (domain.User, error) {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return domain.User{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
key, err := memoryTokenHashKey(tokenHash)
|
||||||
|
if err != nil {
|
||||||
|
return domain.User{}, ErrNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
r.mu.RLock()
|
||||||
|
session, exists := r.sessionsByHashKey[key]
|
||||||
|
r.mu.RUnlock()
|
||||||
|
|
||||||
|
if !exists || !session.expiresAt.After(time.Now().UTC()) {
|
||||||
|
return domain.User{}, ErrNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
return r.legacy.GetUserByID(session.userID)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *MemoryRepository) DeleteSession(
|
||||||
|
ctx context.Context,
|
||||||
|
tokenHash []byte,
|
||||||
|
) error {
|
||||||
|
if err := ctx.Err(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
key, err := memoryTokenHashKey(tokenHash)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
r.mu.Lock()
|
||||||
|
delete(r.sessionsByHashKey, key)
|
||||||
|
r.mu.Unlock()
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func memoryTokenHashKey(tokenHash []byte) ([32]byte, error) {
|
||||||
|
var key [32]byte
|
||||||
|
|
||||||
|
if len(tokenHash) != len(key) {
|
||||||
|
return key, fmt.Errorf(
|
||||||
|
"session token hash must contain %d bytes",
|
||||||
|
len(key),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
copy(key[:], tokenHash)
|
||||||
|
|
||||||
|
return key, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ Repository = (*MemoryRepository)(nil)
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
package store
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
)
|
||||||
|
|
||||||
|
type PostgreSQLStore struct {
|
||||||
|
pool *pgxpool.Pool
|
||||||
|
queryTimeout time.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewPostgreSQLStore(
|
||||||
|
pool *pgxpool.Pool,
|
||||||
|
queryTimeout time.Duration,
|
||||||
|
) *PostgreSQLStore {
|
||||||
|
return &PostgreSQLStore{
|
||||||
|
pool: pool,
|
||||||
|
queryTimeout: queryTimeout,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *PostgreSQLStore) Ping(ctx context.Context) error {
|
||||||
|
queryContext, cancel := s.withTimeout(ctx)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
return s.pool.Ping(queryContext)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *PostgreSQLStore) Close() {
|
||||||
|
s.pool.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *PostgreSQLStore) withTimeout(
|
||||||
|
ctx context.Context,
|
||||||
|
) (context.Context, context.CancelFunc) {
|
||||||
|
return context.WithTimeout(ctx, s.queryTimeout)
|
||||||
|
}
|
||||||
@@ -0,0 +1,324 @@
|
|||||||
|
package store
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"mtusi2026lab2/internal/domain"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (s *PostgreSQLStore) CreateChat(
|
||||||
|
ctx context.Context,
|
||||||
|
title string,
|
||||||
|
memberIDs []string,
|
||||||
|
) (domain.Chat, error) {
|
||||||
|
queryContext, cancel := s.withTimeout(ctx)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
transaction, err := s.pool.Begin(queryContext)
|
||||||
|
if err != nil {
|
||||||
|
return domain.Chat{}, fmt.Errorf(
|
||||||
|
"begin create chat transaction: %w",
|
||||||
|
err,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
defer func() {
|
||||||
|
_ = transaction.Rollback(queryContext)
|
||||||
|
}()
|
||||||
|
|
||||||
|
// Проверяем участников внутри той же транзакции, в которой
|
||||||
|
// создаются чат и строки членства.
|
||||||
|
for _, memberID := range memberIDs {
|
||||||
|
var exists bool
|
||||||
|
|
||||||
|
err = transaction.QueryRow(
|
||||||
|
queryContext,
|
||||||
|
`
|
||||||
|
SELECT EXISTS (
|
||||||
|
SELECT 1
|
||||||
|
FROM users
|
||||||
|
WHERE id = $1
|
||||||
|
)
|
||||||
|
`,
|
||||||
|
memberID,
|
||||||
|
).Scan(&exists)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return domain.Chat{}, fmt.Errorf(
|
||||||
|
"check chat member %s: %w",
|
||||||
|
memberID,
|
||||||
|
err,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if !exists {
|
||||||
|
return domain.Chat{}, fmt.Errorf(
|
||||||
|
"%w: member %s",
|
||||||
|
ErrNotFound,
|
||||||
|
memberID,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
chat := domain.Chat{
|
||||||
|
ID: uuid.NewString(),
|
||||||
|
Title: title,
|
||||||
|
MemberIDs: append([]string(nil), memberIDs...),
|
||||||
|
}
|
||||||
|
|
||||||
|
err = transaction.QueryRow(
|
||||||
|
queryContext,
|
||||||
|
`
|
||||||
|
INSERT INTO chats (
|
||||||
|
id,
|
||||||
|
title
|
||||||
|
)
|
||||||
|
VALUES ($1, $2)
|
||||||
|
RETURNING created_at
|
||||||
|
`,
|
||||||
|
chat.ID,
|
||||||
|
chat.Title,
|
||||||
|
).Scan(&chat.CreatedAt)
|
||||||
|
if err != nil {
|
||||||
|
return domain.Chat{}, fmt.Errorf("insert chat: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
for position, memberID := range memberIDs {
|
||||||
|
_, err = transaction.Exec(
|
||||||
|
queryContext,
|
||||||
|
`
|
||||||
|
INSERT INTO chat_members (
|
||||||
|
chat_id,
|
||||||
|
user_id,
|
||||||
|
position
|
||||||
|
)
|
||||||
|
VALUES ($1, $2, $3)
|
||||||
|
`,
|
||||||
|
chat.ID,
|
||||||
|
memberID,
|
||||||
|
position,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return domain.Chat{}, fmt.Errorf(
|
||||||
|
"insert chat member %s: %w",
|
||||||
|
memberID,
|
||||||
|
err,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err = transaction.Commit(queryContext); err != nil {
|
||||||
|
return domain.Chat{}, fmt.Errorf(
|
||||||
|
"commit create chat transaction: %w",
|
||||||
|
err,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return chat, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *PostgreSQLStore) GetChatByID(
|
||||||
|
ctx context.Context,
|
||||||
|
chatID string,
|
||||||
|
callerID string,
|
||||||
|
) (domain.Chat, error) {
|
||||||
|
queryContext, cancel := s.withTimeout(ctx)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
var chat domain.Chat
|
||||||
|
|
||||||
|
err := s.pool.QueryRow(
|
||||||
|
queryContext,
|
||||||
|
`
|
||||||
|
SELECT
|
||||||
|
chat.id::text,
|
||||||
|
chat.title,
|
||||||
|
chat.created_at,
|
||||||
|
array_agg(
|
||||||
|
member.user_id::text
|
||||||
|
ORDER BY member.position
|
||||||
|
)
|
||||||
|
FROM chats AS chat
|
||||||
|
JOIN chat_members AS caller
|
||||||
|
ON caller.chat_id = chat.id
|
||||||
|
AND caller.user_id = $2
|
||||||
|
JOIN chat_members AS member
|
||||||
|
ON member.chat_id = chat.id
|
||||||
|
WHERE chat.id = $1
|
||||||
|
GROUP BY
|
||||||
|
chat.id,
|
||||||
|
chat.title,
|
||||||
|
chat.created_at
|
||||||
|
`,
|
||||||
|
chatID,
|
||||||
|
callerID,
|
||||||
|
).Scan(
|
||||||
|
&chat.ID,
|
||||||
|
&chat.Title,
|
||||||
|
&chat.CreatedAt,
|
||||||
|
&chat.MemberIDs,
|
||||||
|
)
|
||||||
|
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
return domain.Chat{}, ErrNotFound
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return domain.Chat{}, fmt.Errorf("select chat by id: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return chat, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *PostgreSQLStore) GetChatsForUser(
|
||||||
|
ctx context.Context,
|
||||||
|
userID string,
|
||||||
|
limit int,
|
||||||
|
cursorString string,
|
||||||
|
) (domain.ChatPage, error) {
|
||||||
|
var cursor *domain.ChatCursorData
|
||||||
|
|
||||||
|
if cursorString != "" {
|
||||||
|
decodedCursor, err := domain.DecodeChatCursor(
|
||||||
|
cursorString,
|
||||||
|
userID,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return domain.ChatPage{}, fmt.Errorf(
|
||||||
|
"%w: %v",
|
||||||
|
ErrInvalidCursor,
|
||||||
|
err,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
cursor = decodedCursor
|
||||||
|
}
|
||||||
|
|
||||||
|
queryContext, cancel := s.withTimeout(ctx)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
var (
|
||||||
|
rows pgx.Rows
|
||||||
|
err error
|
||||||
|
)
|
||||||
|
|
||||||
|
if cursor == nil {
|
||||||
|
rows, err = s.pool.Query(
|
||||||
|
queryContext,
|
||||||
|
`
|
||||||
|
SELECT
|
||||||
|
chat.id::text,
|
||||||
|
chat.title,
|
||||||
|
chat.created_at,
|
||||||
|
array_agg(
|
||||||
|
member.user_id::text
|
||||||
|
ORDER BY member.position
|
||||||
|
)
|
||||||
|
FROM chat_members AS own_membership
|
||||||
|
JOIN chats AS chat
|
||||||
|
ON chat.id = own_membership.chat_id
|
||||||
|
JOIN chat_members AS member
|
||||||
|
ON member.chat_id = chat.id
|
||||||
|
WHERE own_membership.user_id = $1
|
||||||
|
GROUP BY
|
||||||
|
chat.id,
|
||||||
|
chat.title,
|
||||||
|
chat.created_at
|
||||||
|
ORDER BY
|
||||||
|
chat.created_at,
|
||||||
|
chat.id
|
||||||
|
LIMIT $2
|
||||||
|
`,
|
||||||
|
userID,
|
||||||
|
limit+1,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
rows, err = s.pool.Query(
|
||||||
|
queryContext,
|
||||||
|
`
|
||||||
|
SELECT
|
||||||
|
chat.id::text,
|
||||||
|
chat.title,
|
||||||
|
chat.created_at,
|
||||||
|
array_agg(
|
||||||
|
member.user_id::text
|
||||||
|
ORDER BY member.position
|
||||||
|
)
|
||||||
|
FROM chat_members AS own_membership
|
||||||
|
JOIN chats AS chat
|
||||||
|
ON chat.id = own_membership.chat_id
|
||||||
|
JOIN chat_members AS member
|
||||||
|
ON member.chat_id = chat.id
|
||||||
|
WHERE own_membership.user_id = $1
|
||||||
|
AND (chat.created_at, chat.id) > ($2, $3)
|
||||||
|
GROUP BY
|
||||||
|
chat.id,
|
||||||
|
chat.title,
|
||||||
|
chat.created_at
|
||||||
|
ORDER BY
|
||||||
|
chat.created_at,
|
||||||
|
chat.id
|
||||||
|
LIMIT $4
|
||||||
|
`,
|
||||||
|
userID,
|
||||||
|
cursor.CreatedAt,
|
||||||
|
cursor.ChatID,
|
||||||
|
limit+1,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return domain.ChatPage{}, fmt.Errorf(
|
||||||
|
"query chats for user: %w",
|
||||||
|
err,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
page := domain.ChatPage{
|
||||||
|
Items: make([]domain.Chat, 0, limit),
|
||||||
|
}
|
||||||
|
|
||||||
|
for rows.Next() {
|
||||||
|
var chat domain.Chat
|
||||||
|
|
||||||
|
if err := rows.Scan(
|
||||||
|
&chat.ID,
|
||||||
|
&chat.Title,
|
||||||
|
&chat.CreatedAt,
|
||||||
|
&chat.MemberIDs,
|
||||||
|
); err != nil {
|
||||||
|
return domain.ChatPage{}, fmt.Errorf(
|
||||||
|
"scan chat page: %w",
|
||||||
|
err,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
page.Items = append(page.Items, chat)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return domain.ChatPage{}, fmt.Errorf(
|
||||||
|
"iterate chat page: %w",
|
||||||
|
err,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(page.Items) > limit {
|
||||||
|
page.Items = page.Items[:limit]
|
||||||
|
|
||||||
|
lastChat := page.Items[len(page.Items)-1]
|
||||||
|
nextCursor := domain.EncodeChatCursor(
|
||||||
|
lastChat.CreatedAt,
|
||||||
|
lastChat.ID,
|
||||||
|
userID,
|
||||||
|
)
|
||||||
|
page.NextCursor = &nextCursor
|
||||||
|
}
|
||||||
|
|
||||||
|
return page, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,220 @@
|
|||||||
|
package store
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"mtusi2026lab2/internal/domain"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (s *PostgreSQLStore) CreateMessage(
|
||||||
|
ctx context.Context,
|
||||||
|
chatID string,
|
||||||
|
senderID string,
|
||||||
|
text string,
|
||||||
|
) (domain.Message, error) {
|
||||||
|
queryContext, cancel := s.withTimeout(ctx)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
message := domain.Message{
|
||||||
|
ID: uuid.NewString(),
|
||||||
|
ChatID: chatID,
|
||||||
|
SenderID: senderID,
|
||||||
|
Text: text,
|
||||||
|
}
|
||||||
|
|
||||||
|
err := s.pool.QueryRow(
|
||||||
|
queryContext,
|
||||||
|
`
|
||||||
|
INSERT INTO messages (
|
||||||
|
id,
|
||||||
|
chat_id,
|
||||||
|
sender_id,
|
||||||
|
text
|
||||||
|
)
|
||||||
|
SELECT
|
||||||
|
$1,
|
||||||
|
$2,
|
||||||
|
$3,
|
||||||
|
$4
|
||||||
|
FROM chat_members
|
||||||
|
WHERE chat_id = $2
|
||||||
|
AND user_id = $3
|
||||||
|
RETURNING created_at
|
||||||
|
`,
|
||||||
|
message.ID,
|
||||||
|
message.ChatID,
|
||||||
|
message.SenderID,
|
||||||
|
message.Text,
|
||||||
|
).Scan(&message.CreatedAt)
|
||||||
|
|
||||||
|
if err == nil {
|
||||||
|
return message, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// INSERT ... SELECT возвращает zero rows, если отправитель
|
||||||
|
// не является участником указанного чата.
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
return domain.Message{}, ErrNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
return domain.Message{}, fmt.Errorf("insert message: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *PostgreSQLStore) GetMessages(
|
||||||
|
ctx context.Context,
|
||||||
|
chatID string,
|
||||||
|
callerID string,
|
||||||
|
limit int,
|
||||||
|
cursorString string,
|
||||||
|
) (domain.MessagePage, error) {
|
||||||
|
queryContext, cancel := s.withTimeout(ctx)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
var isMember bool
|
||||||
|
|
||||||
|
err := s.pool.QueryRow(
|
||||||
|
queryContext,
|
||||||
|
`
|
||||||
|
SELECT EXISTS (
|
||||||
|
SELECT 1
|
||||||
|
FROM chat_members
|
||||||
|
WHERE chat_id = $1
|
||||||
|
AND user_id = $2
|
||||||
|
)
|
||||||
|
`,
|
||||||
|
chatID,
|
||||||
|
callerID,
|
||||||
|
).Scan(&isMember)
|
||||||
|
if err != nil {
|
||||||
|
return domain.MessagePage{}, fmt.Errorf(
|
||||||
|
"check chat membership: %w",
|
||||||
|
err,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if !isMember {
|
||||||
|
return domain.MessagePage{}, ErrNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
var cursor *domain.CursorData
|
||||||
|
|
||||||
|
if cursorString != "" {
|
||||||
|
decodedCursor, err := domain.DecodeCursor(
|
||||||
|
cursorString,
|
||||||
|
chatID,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return domain.MessagePage{}, fmt.Errorf(
|
||||||
|
"%w: %v",
|
||||||
|
ErrInvalidCursor,
|
||||||
|
err,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
cursor = decodedCursor
|
||||||
|
}
|
||||||
|
|
||||||
|
var rows pgx.Rows
|
||||||
|
|
||||||
|
if cursor == nil {
|
||||||
|
rows, err = s.pool.Query(
|
||||||
|
queryContext,
|
||||||
|
`
|
||||||
|
SELECT
|
||||||
|
id::text,
|
||||||
|
chat_id::text,
|
||||||
|
sender_id::text,
|
||||||
|
text,
|
||||||
|
created_at
|
||||||
|
FROM messages
|
||||||
|
WHERE chat_id = $1
|
||||||
|
ORDER BY
|
||||||
|
created_at,
|
||||||
|
id
|
||||||
|
LIMIT $2
|
||||||
|
`,
|
||||||
|
chatID,
|
||||||
|
limit+1,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
rows, err = s.pool.Query(
|
||||||
|
queryContext,
|
||||||
|
`
|
||||||
|
SELECT
|
||||||
|
id::text,
|
||||||
|
chat_id::text,
|
||||||
|
sender_id::text,
|
||||||
|
text,
|
||||||
|
created_at
|
||||||
|
FROM messages
|
||||||
|
WHERE chat_id = $1
|
||||||
|
AND (created_at, id) > ($2, $3)
|
||||||
|
ORDER BY
|
||||||
|
created_at,
|
||||||
|
id
|
||||||
|
LIMIT $4
|
||||||
|
`,
|
||||||
|
chatID,
|
||||||
|
cursor.CreatedAt,
|
||||||
|
cursor.MessageID,
|
||||||
|
limit+1,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return domain.MessagePage{}, fmt.Errorf(
|
||||||
|
"query messages: %w",
|
||||||
|
err,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
page := domain.MessagePage{
|
||||||
|
Items: make([]domain.Message, 0, limit),
|
||||||
|
}
|
||||||
|
|
||||||
|
for rows.Next() {
|
||||||
|
var message domain.Message
|
||||||
|
|
||||||
|
if err := rows.Scan(
|
||||||
|
&message.ID,
|
||||||
|
&message.ChatID,
|
||||||
|
&message.SenderID,
|
||||||
|
&message.Text,
|
||||||
|
&message.CreatedAt,
|
||||||
|
); err != nil {
|
||||||
|
return domain.MessagePage{}, fmt.Errorf(
|
||||||
|
"scan message page: %w",
|
||||||
|
err,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
page.Items = append(page.Items, message)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return domain.MessagePage{}, fmt.Errorf(
|
||||||
|
"iterate message page: %w",
|
||||||
|
err,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(page.Items) > limit {
|
||||||
|
page.Items = page.Items[:limit]
|
||||||
|
|
||||||
|
lastMessage := page.Items[len(page.Items)-1]
|
||||||
|
nextCursor := domain.EncodeCursor(
|
||||||
|
lastMessage.CreatedAt,
|
||||||
|
lastMessage.ID,
|
||||||
|
chatID,
|
||||||
|
)
|
||||||
|
page.NextCursor = &nextCursor
|
||||||
|
}
|
||||||
|
|
||||||
|
return page, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
package store
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"mtusi2026lab2/internal/domain"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (s *PostgreSQLStore) CreateSession(
|
||||||
|
ctx context.Context,
|
||||||
|
tokenHash []byte,
|
||||||
|
userID string,
|
||||||
|
expiresAt time.Time,
|
||||||
|
) error {
|
||||||
|
queryContext, cancel := s.withTimeout(ctx)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
_, err := s.pool.Exec(
|
||||||
|
queryContext,
|
||||||
|
`
|
||||||
|
INSERT INTO sessions (
|
||||||
|
token_hash,
|
||||||
|
user_id,
|
||||||
|
expires_at
|
||||||
|
)
|
||||||
|
VALUES ($1, $2, $3)
|
||||||
|
`,
|
||||||
|
tokenHash,
|
||||||
|
userID,
|
||||||
|
expiresAt,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("insert session: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *PostgreSQLStore) GetUserBySession(
|
||||||
|
ctx context.Context,
|
||||||
|
tokenHash []byte,
|
||||||
|
) (domain.User, error) {
|
||||||
|
queryContext, cancel := s.withTimeout(ctx)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
var user domain.User
|
||||||
|
|
||||||
|
err := s.pool.QueryRow(
|
||||||
|
queryContext,
|
||||||
|
`
|
||||||
|
SELECT
|
||||||
|
app_user.id::text,
|
||||||
|
app_user.username,
|
||||||
|
app_user.display_name,
|
||||||
|
app_user.created_at
|
||||||
|
FROM sessions AS session
|
||||||
|
JOIN users AS app_user
|
||||||
|
ON app_user.id = session.user_id
|
||||||
|
WHERE session.token_hash = $1
|
||||||
|
AND session.expires_at > CURRENT_TIMESTAMP
|
||||||
|
`,
|
||||||
|
tokenHash,
|
||||||
|
).Scan(
|
||||||
|
&user.ID,
|
||||||
|
&user.Username,
|
||||||
|
&user.DisplayName,
|
||||||
|
&user.CreatedAt,
|
||||||
|
)
|
||||||
|
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
return domain.User{}, ErrNotFound
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return domain.User{}, fmt.Errorf(
|
||||||
|
"select user by session: %w",
|
||||||
|
err,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return user, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *PostgreSQLStore) DeleteSession(
|
||||||
|
ctx context.Context,
|
||||||
|
tokenHash []byte,
|
||||||
|
) error {
|
||||||
|
queryContext, cancel := s.withTimeout(ctx)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
_, err := s.pool.Exec(
|
||||||
|
queryContext,
|
||||||
|
`
|
||||||
|
DELETE FROM sessions
|
||||||
|
WHERE token_hash = $1
|
||||||
|
`,
|
||||||
|
tokenHash,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("delete session: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,144 @@
|
|||||||
|
package store
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"mtusi2026lab2/internal/domain"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
"github.com/jackc/pgx/v5/pgconn"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (s *PostgreSQLStore) CreateUser(
|
||||||
|
ctx context.Context,
|
||||||
|
username string,
|
||||||
|
displayName string,
|
||||||
|
passwordHash string,
|
||||||
|
) (domain.User, error) {
|
||||||
|
queryContext, cancel := s.withTimeout(ctx)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
user := domain.User{
|
||||||
|
ID: uuid.NewString(),
|
||||||
|
Username: username,
|
||||||
|
DisplayName: displayName,
|
||||||
|
}
|
||||||
|
|
||||||
|
err := s.pool.QueryRow(
|
||||||
|
queryContext,
|
||||||
|
`
|
||||||
|
INSERT INTO users (
|
||||||
|
id,
|
||||||
|
username,
|
||||||
|
display_name,
|
||||||
|
password_hash
|
||||||
|
)
|
||||||
|
VALUES ($1, $2, $3, $4)
|
||||||
|
RETURNING created_at
|
||||||
|
`,
|
||||||
|
user.ID,
|
||||||
|
user.Username,
|
||||||
|
user.DisplayName,
|
||||||
|
passwordHash,
|
||||||
|
).Scan(&user.CreatedAt)
|
||||||
|
|
||||||
|
if err == nil {
|
||||||
|
return user, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var postgresError *pgconn.PgError
|
||||||
|
if errors.As(err, &postgresError) &&
|
||||||
|
postgresError.Code == "23505" &&
|
||||||
|
postgresError.ConstraintName == "users_username_unique" {
|
||||||
|
return domain.User{}, ErrConflict
|
||||||
|
}
|
||||||
|
|
||||||
|
return domain.User{}, fmt.Errorf("insert user: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *PostgreSQLStore) GetUserByID(
|
||||||
|
ctx context.Context,
|
||||||
|
userID string,
|
||||||
|
) (domain.User, error) {
|
||||||
|
queryContext, cancel := s.withTimeout(ctx)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
var user domain.User
|
||||||
|
|
||||||
|
err := s.pool.QueryRow(
|
||||||
|
queryContext,
|
||||||
|
`
|
||||||
|
SELECT
|
||||||
|
id::text,
|
||||||
|
username,
|
||||||
|
display_name,
|
||||||
|
created_at
|
||||||
|
FROM users
|
||||||
|
WHERE id = $1
|
||||||
|
`,
|
||||||
|
userID,
|
||||||
|
).Scan(
|
||||||
|
&user.ID,
|
||||||
|
&user.Username,
|
||||||
|
&user.DisplayName,
|
||||||
|
&user.CreatedAt,
|
||||||
|
)
|
||||||
|
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
return domain.User{}, ErrNotFound
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return domain.User{}, fmt.Errorf("select user by id: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return user, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *PostgreSQLStore) GetUserByUsername(
|
||||||
|
ctx context.Context,
|
||||||
|
username string,
|
||||||
|
) (domain.User, string, error) {
|
||||||
|
queryContext, cancel := s.withTimeout(ctx)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
var (
|
||||||
|
user domain.User
|
||||||
|
passwordHash string
|
||||||
|
)
|
||||||
|
|
||||||
|
err := s.pool.QueryRow(
|
||||||
|
queryContext,
|
||||||
|
`
|
||||||
|
SELECT
|
||||||
|
id::text,
|
||||||
|
username,
|
||||||
|
display_name,
|
||||||
|
created_at,
|
||||||
|
password_hash
|
||||||
|
FROM users
|
||||||
|
WHERE username = $1
|
||||||
|
`,
|
||||||
|
username,
|
||||||
|
).Scan(
|
||||||
|
&user.ID,
|
||||||
|
&user.Username,
|
||||||
|
&user.DisplayName,
|
||||||
|
&user.CreatedAt,
|
||||||
|
&passwordHash,
|
||||||
|
)
|
||||||
|
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
return domain.User{}, "", ErrNotFound
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return domain.User{}, "", fmt.Errorf(
|
||||||
|
"select user by username: %w",
|
||||||
|
err,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return user, passwordHash, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
package store
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"mtusi2026lab2/internal/domain"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Repository interface {
|
||||||
|
CreateUser(
|
||||||
|
ctx context.Context,
|
||||||
|
username string,
|
||||||
|
displayName string,
|
||||||
|
passwordHash string,
|
||||||
|
) (domain.User, error)
|
||||||
|
|
||||||
|
GetUserByID(
|
||||||
|
ctx context.Context,
|
||||||
|
userID string,
|
||||||
|
) (domain.User, error)
|
||||||
|
|
||||||
|
GetUserByUsername(
|
||||||
|
ctx context.Context,
|
||||||
|
username string,
|
||||||
|
) (domain.User, string, error)
|
||||||
|
|
||||||
|
CreateChat(
|
||||||
|
ctx context.Context,
|
||||||
|
title string,
|
||||||
|
memberIDs []string,
|
||||||
|
) (domain.Chat, error)
|
||||||
|
|
||||||
|
GetChatByID(
|
||||||
|
ctx context.Context,
|
||||||
|
chatID string,
|
||||||
|
callerID string,
|
||||||
|
) (domain.Chat, error)
|
||||||
|
|
||||||
|
GetChatsForUser(
|
||||||
|
ctx context.Context,
|
||||||
|
userID string,
|
||||||
|
limit int,
|
||||||
|
cursor string,
|
||||||
|
) (domain.ChatPage, error)
|
||||||
|
|
||||||
|
CreateMessage(
|
||||||
|
ctx context.Context,
|
||||||
|
chatID string,
|
||||||
|
senderID string,
|
||||||
|
text string,
|
||||||
|
) (domain.Message, error)
|
||||||
|
|
||||||
|
GetMessages(
|
||||||
|
ctx context.Context,
|
||||||
|
chatID string,
|
||||||
|
callerID string,
|
||||||
|
limit int,
|
||||||
|
cursor string,
|
||||||
|
) (domain.MessagePage, error)
|
||||||
|
|
||||||
|
CreateSession(
|
||||||
|
ctx context.Context,
|
||||||
|
tokenHash []byte,
|
||||||
|
userID string,
|
||||||
|
expiresAt time.Time,
|
||||||
|
) error
|
||||||
|
|
||||||
|
GetUserBySession(
|
||||||
|
ctx context.Context,
|
||||||
|
tokenHash []byte,
|
||||||
|
) (domain.User, error)
|
||||||
|
|
||||||
|
DeleteSession(
|
||||||
|
ctx context.Context,
|
||||||
|
tokenHash []byte,
|
||||||
|
) error
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ Repository = (*PostgreSQLStore)(nil)
|
||||||
@@ -34,10 +34,29 @@ func (h *Handler) CreateChat(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
chat, err := h.store.CreateChat(req.Title, req.MemberIDs)
|
chat, err := h.store.CreateChat(
|
||||||
|
r.Context(),
|
||||||
|
req.Title,
|
||||||
|
req.MemberIDs,
|
||||||
|
)
|
||||||
|
if errors.Is(err, store.ErrNotFound) {
|
||||||
|
response.WriteError(
|
||||||
|
w,
|
||||||
|
http.StatusBadRequest,
|
||||||
|
response.CodeInvalidRequest,
|
||||||
|
"one or more members do not exist",
|
||||||
|
reqID,
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
//участник не существует -> 400
|
response.WriteError(
|
||||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, err.Error(), reqID)
|
w,
|
||||||
|
http.StatusServiceUnavailable,
|
||||||
|
response.CodeUnavailable,
|
||||||
|
"service is temporarily unavailable",
|
||||||
|
reqID,
|
||||||
|
)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -55,14 +74,24 @@ func (h *Handler) GetChat(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
chat, err := h.store.GetChatByID(chatID, currentUser.ID)
|
chat, err := h.store.GetChatByID(
|
||||||
|
r.Context(),
|
||||||
|
chatID,
|
||||||
|
currentUser.ID,
|
||||||
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.Is(err, store.ErrNotFound) {
|
if errors.Is(err, store.ErrNotFound) {
|
||||||
//посторонний или несуществующий чат -> 404
|
//посторонний или несуществующий чат -> 404
|
||||||
response.WriteError(w, http.StatusNotFound, response.CodeNotFound, "chat not found", reqID)
|
response.WriteError(w, http.StatusNotFound, response.CodeNotFound, "chat not found", reqID)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
response.WriteError(w, http.StatusInternalServerError, response.CodeInternalError, "internal error", reqID)
|
response.WriteError(
|
||||||
|
w,
|
||||||
|
http.StatusServiceUnavailable,
|
||||||
|
response.CodeUnavailable,
|
||||||
|
"service is temporarily unavailable",
|
||||||
|
reqID,
|
||||||
|
)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -108,6 +137,7 @@ func (h *Handler) ListChats(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
page, err := h.store.GetChatsForUser(
|
page, err := h.store.GetChatsForUser(
|
||||||
|
r.Context(),
|
||||||
currentUser.ID,
|
currentUser.ID,
|
||||||
limit,
|
limit,
|
||||||
cursor,
|
cursor,
|
||||||
@@ -126,9 +156,9 @@ func (h *Handler) ListChats(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
response.WriteError(
|
response.WriteError(
|
||||||
w,
|
w,
|
||||||
http.StatusInternalServerError,
|
http.StatusServiceUnavailable,
|
||||||
response.CodeInternalError,
|
response.CodeUnavailable,
|
||||||
"internal error",
|
"service is temporarily unavailable",
|
||||||
reqID,
|
reqID,
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -1,42 +1,77 @@
|
|||||||
package handlers
|
package handlers
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"time"
|
||||||
|
|
||||||
"mtusi2026lab2/internal/store"
|
"mtusi2026lab2/internal/store"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
type ReadinessChecker interface {
|
||||||
|
Ping(ctx context.Context) error
|
||||||
|
}
|
||||||
|
|
||||||
|
type Option func(*Handler)
|
||||||
|
|
||||||
type Handler struct {
|
type Handler struct {
|
||||||
store *store.MemoryStore
|
store store.Repository
|
||||||
|
readinessChecker ReadinessChecker
|
||||||
|
readinessTimeout time.Duration
|
||||||
|
sessionTTL time.Duration
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewHandler(st *store.MemoryStore) *Handler {
|
func NewHandler(
|
||||||
return &Handler{store: st}
|
repository store.Repository,
|
||||||
|
options ...Option,
|
||||||
|
) *Handler {
|
||||||
|
handler := &Handler{
|
||||||
|
store: repository,
|
||||||
|
readinessTimeout: 2 * time.Second,
|
||||||
|
sessionTTL: time.Hour,
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, option := range options {
|
||||||
|
option(handler)
|
||||||
|
}
|
||||||
|
|
||||||
|
return handler
|
||||||
}
|
}
|
||||||
|
|
||||||
// декодирует тело запроса:
|
func WithReadiness(
|
||||||
// Запрещает неизвестные/лишние поля (DisallowUnknownFields) -> 400
|
checker ReadinessChecker,
|
||||||
// Ловит синтаксические ошибки JSON -> 400
|
timeout time.Duration,
|
||||||
// Проверяет, что после валидного JSON нет мусора
|
) Option {
|
||||||
func decodeJSON(r *http.Request, dst any) error {
|
return func(handler *Handler) {
|
||||||
|
handler.readinessChecker = checker
|
||||||
|
handler.readinessTimeout = timeout
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func WithSessionTTL(ttl time.Duration) Option {
|
||||||
|
return func(handler *Handler) {
|
||||||
|
handler.sessionTTL = ttl
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func decodeJSON(r *http.Request, destination any) error {
|
||||||
if r.Body == nil {
|
if r.Body == nil {
|
||||||
return errors.New("request body is empty")
|
return errors.New("request body is empty")
|
||||||
}
|
}
|
||||||
defer r.Body.Close()
|
defer r.Body.Close()
|
||||||
|
|
||||||
dec := json.NewDecoder(r.Body)
|
decoder := json.NewDecoder(r.Body)
|
||||||
dec.DisallowUnknownFields()
|
decoder.DisallowUnknownFields()
|
||||||
|
|
||||||
if err := dec.Decode(dst); err != nil {
|
if err := decoder.Decode(destination); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// два JSON подряд или мусор в конце — ошибка
|
|
||||||
var extra json.RawMessage
|
var extra json.RawMessage
|
||||||
if err := dec.Decode(&extra); !errors.Is(err, io.EOF) {
|
if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) {
|
||||||
return errors.New("extra data after JSON")
|
return errors.New("extra data after JSON")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,20 +1,62 @@
|
|||||||
package handlers
|
package handlers
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"mtusi2026lab2/internal/transport/http/middleware"
|
"mtusi2026lab2/internal/transport/http/middleware"
|
||||||
"mtusi2026lab2/internal/transport/http/response"
|
"mtusi2026lab2/internal/transport/http/response"
|
||||||
)
|
)
|
||||||
|
|
||||||
// HealthLive проверяет, что процесс сервера запущен
|
// HealthLive проверяет только то, что HTTP-процесс работает.
|
||||||
func (h *Handler) HealthLive(w http.ResponseWriter, r *http.Request) {
|
func (h *Handler) HealthLive(w http.ResponseWriter, r *http.Request) {
|
||||||
reqID := middleware.GetRequestID(r.Context())
|
requestID := middleware.GetRequestID(r.Context())
|
||||||
response.WriteJSON(w, http.StatusOK, map[string]string{"status": "ok"}, reqID)
|
|
||||||
|
response.WriteJSON(
|
||||||
|
w,
|
||||||
|
http.StatusOK,
|
||||||
|
map[string]string{"status": "ok"},
|
||||||
|
requestID,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// HealthReady проверяет, что сервер готов принимать входящие запросы
|
// HealthReady проверяет зависимости, без которых API не может обслуживать трафик.
|
||||||
func (h *Handler) HealthReady(w http.ResponseWriter, r *http.Request) {
|
func (h *Handler) HealthReady(w http.ResponseWriter, r *http.Request) {
|
||||||
reqID := middleware.GetRequestID(r.Context())
|
requestID := middleware.GetRequestID(r.Context())
|
||||||
response.WriteJSON(w, http.StatusOK, map[string]string{"status": "ok"}, reqID)
|
|
||||||
|
// Этот вариант сохраняет работоспособность изолированных unit-тестов,
|
||||||
|
// в которых PostgreSQL намеренно не создаётся.
|
||||||
|
if h.readinessChecker == nil {
|
||||||
|
response.WriteJSON(
|
||||||
|
w,
|
||||||
|
http.StatusOK,
|
||||||
|
map[string]string{"status": "ok"},
|
||||||
|
requestID,
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx, cancel := context.WithTimeout(
|
||||||
|
r.Context(),
|
||||||
|
h.readinessTimeout,
|
||||||
|
)
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
|
if err := h.readinessChecker.Ping(ctx); err != nil {
|
||||||
|
response.WriteError(
|
||||||
|
w,
|
||||||
|
http.StatusServiceUnavailable,
|
||||||
|
response.CodeUnavailable,
|
||||||
|
"service is not ready",
|
||||||
|
requestID,
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
response.WriteJSON(
|
||||||
|
w,
|
||||||
|
http.StatusOK,
|
||||||
|
map[string]string{"status": "ok"},
|
||||||
|
requestID,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -41,14 +41,25 @@ func (h *Handler) CreateMessage(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
//автор сообщения строго выводится из сессии (currentUser.ID)
|
//автор сообщения строго выводится из сессии (currentUser.ID)
|
||||||
msg, err := h.store.CreateMessage(chatID, currentUser.ID, req.Text)
|
msg, err := h.store.CreateMessage(
|
||||||
|
r.Context(),
|
||||||
|
chatID,
|
||||||
|
currentUser.ID,
|
||||||
|
req.Text,
|
||||||
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.Is(err, store.ErrNotFound) {
|
if errors.Is(err, store.ErrNotFound) {
|
||||||
// чата нет/пользователь не участник -> 404
|
// чата нет/пользователь не участник -> 404
|
||||||
response.WriteError(w, http.StatusNotFound, response.CodeNotFound, "chat not found", reqID)
|
response.WriteError(w, http.StatusNotFound, response.CodeNotFound, "chat not found", reqID)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
response.WriteError(w, http.StatusInternalServerError, response.CodeInternalError, "internal error", reqID)
|
response.WriteError(
|
||||||
|
w,
|
||||||
|
http.StatusServiceUnavailable,
|
||||||
|
response.CodeUnavailable,
|
||||||
|
"service is temporarily unavailable",
|
||||||
|
reqID,
|
||||||
|
)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -66,28 +77,76 @@ func (h *Handler) GetMessages(w http.ResponseWriter, r *http.Request) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
query := r.URL.Query()
|
||||||
|
|
||||||
limit := 50
|
limit := 50
|
||||||
limitStr := r.URL.Query().Get("limit")
|
if query.Has("limit") {
|
||||||
if limitStr != "" {
|
limitString := query.Get("limit")
|
||||||
val, err := strconv.Atoi(limitStr)
|
|
||||||
// Если передан limit=0 или >100 -> 400 invalid_request
|
parsedLimit, err := strconv.Atoi(limitString)
|
||||||
if err != nil || val < 1 || val > 100 {
|
if err != nil || parsedLimit < 1 || parsedLimit > 100 {
|
||||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, "limit must be an integer between 1 and 100", reqID)
|
response.WriteError(
|
||||||
|
w,
|
||||||
|
http.StatusBadRequest,
|
||||||
|
response.CodeInvalidRequest,
|
||||||
|
"limit must be an integer between 1 and 100",
|
||||||
|
reqID,
|
||||||
|
)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
limit = val
|
|
||||||
|
limit = parsedLimit
|
||||||
}
|
}
|
||||||
|
|
||||||
cursor := r.URL.Query().Get("cursor")
|
cursor := query.Get("cursor")
|
||||||
|
if query.Has("cursor") && cursor == "" {
|
||||||
|
response.WriteError(
|
||||||
|
w,
|
||||||
|
http.StatusBadRequest,
|
||||||
|
response.CodeInvalidRequest,
|
||||||
|
"cursor must not be empty",
|
||||||
|
reqID,
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
page, err := h.store.GetMessages(
|
||||||
|
r.Context(),
|
||||||
|
chatID,
|
||||||
|
currentUser.ID,
|
||||||
|
limit,
|
||||||
|
cursor,
|
||||||
|
)
|
||||||
|
if errors.Is(err, store.ErrNotFound) {
|
||||||
|
response.WriteError(
|
||||||
|
w,
|
||||||
|
http.StatusNotFound,
|
||||||
|
response.CodeNotFound,
|
||||||
|
"chat not found",
|
||||||
|
reqID,
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if errors.Is(err, store.ErrInvalidCursor) {
|
||||||
|
response.WriteError(
|
||||||
|
w,
|
||||||
|
http.StatusBadRequest,
|
||||||
|
response.CodeInvalidRequest,
|
||||||
|
"invalid cursor",
|
||||||
|
reqID,
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
page, err := h.store.GetMessages(chatID, currentUser.ID, limit, cursor)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.Is(err, store.ErrNotFound) {
|
response.WriteError(
|
||||||
response.WriteError(w, http.StatusNotFound, response.CodeNotFound, "chat not found", reqID)
|
w,
|
||||||
return
|
http.StatusServiceUnavailable,
|
||||||
}
|
response.CodeUnavailable,
|
||||||
//если курсор кривой или от другого чата -> 400 invalid_request
|
"service is temporarily unavailable",
|
||||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, err.Error(), reqID)
|
reqID,
|
||||||
|
)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,163 @@
|
|||||||
|
package handlers
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"mtusi2026lab2/internal/domain"
|
||||||
|
"mtusi2026lab2/internal/security"
|
||||||
|
"mtusi2026lab2/internal/store"
|
||||||
|
"mtusi2026lab2/internal/transport/http/middleware"
|
||||||
|
"mtusi2026lab2/internal/transport/http/response"
|
||||||
|
)
|
||||||
|
|
||||||
|
const basicChallenge = `Basic realm="messenger", charset="UTF-8"`
|
||||||
|
|
||||||
|
// dummyPasswordHash keeps the expensive Argon2id path for an unknown username.
|
||||||
|
// The all-zero digest is intentionally not a real user's credential; only the
|
||||||
|
// encoded parameters and lengths need to be valid for constant-cost checking.
|
||||||
|
const dummyPasswordHash = "$argon2id$v=19$m=19456,t=2,p=1$" +
|
||||||
|
"AAAAAAAAAAAAAAAAAAAAAA$" +
|
||||||
|
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
|
||||||
|
|
||||||
|
func (h *Handler) CreateSession(
|
||||||
|
w http.ResponseWriter,
|
||||||
|
r *http.Request,
|
||||||
|
) {
|
||||||
|
requestID := middleware.GetRequestID(r.Context())
|
||||||
|
|
||||||
|
username, password, ok := r.BasicAuth()
|
||||||
|
if !ok || username == "" {
|
||||||
|
writeBasicUnauthorized(w, requestID)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
user, passwordHash, err := h.store.GetUserByUsername(
|
||||||
|
r.Context(),
|
||||||
|
username,
|
||||||
|
)
|
||||||
|
userNotFound := errors.Is(err, store.ErrNotFound)
|
||||||
|
if userNotFound {
|
||||||
|
passwordHash = dummyPasswordHash
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
if !userNotFound {
|
||||||
|
response.WriteError(
|
||||||
|
w,
|
||||||
|
http.StatusServiceUnavailable,
|
||||||
|
response.CodeUnavailable,
|
||||||
|
"service is temporarily unavailable",
|
||||||
|
requestID,
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
passwordMatches, err := security.VerifyPassword(
|
||||||
|
password,
|
||||||
|
passwordHash,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
response.WriteError(
|
||||||
|
w,
|
||||||
|
http.StatusInternalServerError,
|
||||||
|
response.CodeInternalError,
|
||||||
|
"stored password hash is invalid",
|
||||||
|
requestID,
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if userNotFound || !passwordMatches {
|
||||||
|
writeBasicUnauthorized(w, requestID)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
token, tokenHash, err := security.GenerateSessionToken()
|
||||||
|
if err != nil {
|
||||||
|
response.WriteError(
|
||||||
|
w,
|
||||||
|
http.StatusInternalServerError,
|
||||||
|
response.CodeInternalError,
|
||||||
|
"failed to create session",
|
||||||
|
requestID,
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
expiresAt := time.Now().UTC().Add(h.sessionTTL)
|
||||||
|
|
||||||
|
if err := h.store.CreateSession(
|
||||||
|
r.Context(),
|
||||||
|
tokenHash,
|
||||||
|
user.ID,
|
||||||
|
expiresAt,
|
||||||
|
); err != nil {
|
||||||
|
response.WriteError(
|
||||||
|
w,
|
||||||
|
http.StatusServiceUnavailable,
|
||||||
|
response.CodeUnavailable,
|
||||||
|
"service is temporarily unavailable",
|
||||||
|
requestID,
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
session := domain.Session{
|
||||||
|
Token: token,
|
||||||
|
TokenType: "Bearer",
|
||||||
|
ExpiresAt: expiresAt,
|
||||||
|
User: user,
|
||||||
|
}
|
||||||
|
|
||||||
|
response.WriteJSON(
|
||||||
|
w,
|
||||||
|
http.StatusCreated,
|
||||||
|
session,
|
||||||
|
requestID,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) DeleteCurrentSession(
|
||||||
|
w http.ResponseWriter,
|
||||||
|
r *http.Request,
|
||||||
|
) {
|
||||||
|
requestID := middleware.GetRequestID(r.Context())
|
||||||
|
tokenHash := middleware.GetCurrentSessionTokenHash(r.Context())
|
||||||
|
|
||||||
|
if err := h.store.DeleteSession(
|
||||||
|
r.Context(),
|
||||||
|
tokenHash,
|
||||||
|
); err != nil {
|
||||||
|
response.WriteError(
|
||||||
|
w,
|
||||||
|
http.StatusServiceUnavailable,
|
||||||
|
response.CodeUnavailable,
|
||||||
|
"service is temporarily unavailable",
|
||||||
|
requestID,
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
response.WriteJSON(
|
||||||
|
w,
|
||||||
|
http.StatusNoContent,
|
||||||
|
nil,
|
||||||
|
requestID,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeBasicUnauthorized(
|
||||||
|
w http.ResponseWriter,
|
||||||
|
requestID string,
|
||||||
|
) {
|
||||||
|
w.Header().Set("WWW-Authenticate", basicChallenge)
|
||||||
|
|
||||||
|
response.WriteError(
|
||||||
|
w,
|
||||||
|
http.StatusUnauthorized,
|
||||||
|
response.CodeUnauthorized,
|
||||||
|
"invalid username or password",
|
||||||
|
requestID,
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -5,6 +5,7 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"mtusi2026lab2/internal/domain"
|
"mtusi2026lab2/internal/domain"
|
||||||
|
"mtusi2026lab2/internal/security"
|
||||||
"mtusi2026lab2/internal/store"
|
"mtusi2026lab2/internal/store"
|
||||||
"mtusi2026lab2/internal/transport/http/middleware"
|
"mtusi2026lab2/internal/transport/http/middleware"
|
||||||
"mtusi2026lab2/internal/transport/http/response"
|
"mtusi2026lab2/internal/transport/http/response"
|
||||||
@@ -13,47 +14,106 @@ import (
|
|||||||
type CreateUserRequest struct {
|
type CreateUserRequest struct {
|
||||||
Username string `json:"username"`
|
Username string `json:"username"`
|
||||||
DisplayName string `json:"display_name"`
|
DisplayName string `json:"display_name"`
|
||||||
|
Password string `json:"password"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// CreateUser создает нового пользователя
|
|
||||||
func (h *Handler) CreateUser(w http.ResponseWriter, r *http.Request) {
|
func (h *Handler) CreateUser(w http.ResponseWriter, r *http.Request) {
|
||||||
reqID := middleware.GetRequestID(r.Context())
|
requestID := middleware.GetRequestID(r.Context())
|
||||||
|
|
||||||
var req CreateUserRequest
|
var request CreateUserRequest
|
||||||
if err := decodeJSON(r, &req); err != nil {
|
if err := decodeJSON(r, &request); err != nil {
|
||||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, "malformed or invalid JSON: "+err.Error(), reqID)
|
response.WriteError(
|
||||||
|
w,
|
||||||
|
http.StatusBadRequest,
|
||||||
|
response.CodeInvalidRequest,
|
||||||
|
"malformed or invalid JSON: "+err.Error(),
|
||||||
|
requestID,
|
||||||
|
)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
userCandidate := domain.User{
|
userCandidate := domain.User{
|
||||||
Username: req.Username,
|
Username: request.Username,
|
||||||
DisplayName: req.DisplayName,
|
DisplayName: request.DisplayName,
|
||||||
}
|
}
|
||||||
|
|
||||||
//правила Unicode, длину и пробелы из domain
|
|
||||||
if err := userCandidate.Validate(); err != nil {
|
if err := userCandidate.Validate(); err != nil {
|
||||||
response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, err.Error(), reqID)
|
response.WriteError(
|
||||||
|
w,
|
||||||
|
http.StatusBadRequest,
|
||||||
|
response.CodeInvalidRequest,
|
||||||
|
err.Error(),
|
||||||
|
requestID,
|
||||||
|
)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
createdUser, err := h.store.CreateUser(userCandidate.Username, userCandidate.DisplayName)
|
if err := security.ValidatePassword(request.Password); err != nil {
|
||||||
|
response.WriteError(
|
||||||
|
w,
|
||||||
|
http.StatusBadRequest,
|
||||||
|
response.CodeInvalidRequest,
|
||||||
|
err.Error(),
|
||||||
|
requestID,
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
passwordHash, err := security.HashPassword(request.Password)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// юзернейм занят — 409
|
response.WriteError(
|
||||||
if errors.Is(err, store.ErrConflict) {
|
w,
|
||||||
response.WriteError(w, http.StatusConflict, response.CodeConflict, "username already exists", reqID)
|
http.StatusInternalServerError,
|
||||||
return
|
response.CodeInternalError,
|
||||||
}
|
"failed to process password",
|
||||||
response.WriteError(w, http.StatusInternalServerError, response.CodeInternalError, "failed to create user", reqID)
|
requestID,
|
||||||
|
)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
response.WriteJSON(w, http.StatusCreated, createdUser, reqID)
|
createdUser, err := h.store.CreateUser(
|
||||||
|
r.Context(),
|
||||||
|
request.Username,
|
||||||
|
request.DisplayName,
|
||||||
|
passwordHash,
|
||||||
|
)
|
||||||
|
if errors.Is(err, store.ErrConflict) {
|
||||||
|
response.WriteError(
|
||||||
|
w,
|
||||||
|
http.StatusConflict,
|
||||||
|
response.CodeConflict,
|
||||||
|
"username already exists",
|
||||||
|
requestID,
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
response.WriteError(
|
||||||
|
w,
|
||||||
|
http.StatusServiceUnavailable,
|
||||||
|
response.CodeUnavailable,
|
||||||
|
"service is temporarily unavailable",
|
||||||
|
requestID,
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
response.WriteJSON(
|
||||||
|
w,
|
||||||
|
http.StatusCreated,
|
||||||
|
createdUser,
|
||||||
|
requestID,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetMe возвращает профиль текущего пользователя
|
|
||||||
func (h *Handler) GetMe(w http.ResponseWriter, r *http.Request) {
|
func (h *Handler) GetMe(w http.ResponseWriter, r *http.Request) {
|
||||||
reqID := middleware.GetRequestID(r.Context())
|
requestID := middleware.GetRequestID(r.Context())
|
||||||
currentUser := middleware.GetCurrentUser(r.Context())
|
currentUser := middleware.GetCurrentUser(r.Context())
|
||||||
|
|
||||||
response.WriteJSON(w, http.StatusOK, currentUser, reqID)
|
response.WriteJSON(
|
||||||
|
w,
|
||||||
|
http.StatusOK,
|
||||||
|
currentUser,
|
||||||
|
requestID,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,42 +2,116 @@ package middleware
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"errors"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
|
||||||
"mtusi2026lab2/internal/domain"
|
"mtusi2026lab2/internal/domain"
|
||||||
|
"mtusi2026lab2/internal/security"
|
||||||
"mtusi2026lab2/internal/store"
|
"mtusi2026lab2/internal/store"
|
||||||
"mtusi2026lab2/internal/transport/http/response"
|
"mtusi2026lab2/internal/transport/http/response"
|
||||||
)
|
)
|
||||||
|
|
||||||
const UserContextKey contextKey = "current_user"
|
const bearerChallenge = `Bearer realm="messenger"`
|
||||||
|
|
||||||
// RequireAuth проверяет наличие и валидность X-User-Id
|
const (
|
||||||
func RequireAuth(st *store.MemoryStore, next http.HandlerFunc) http.HandlerFunc {
|
UserContextKey contextKey = "current_user"
|
||||||
|
sessionTokenHashKey contextKey = "session_token_hash"
|
||||||
|
)
|
||||||
|
|
||||||
|
type SessionAuthenticator interface {
|
||||||
|
GetUserBySession(
|
||||||
|
ctx context.Context,
|
||||||
|
tokenHash []byte,
|
||||||
|
) (domain.User, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
func RequireAuth(
|
||||||
|
authenticator SessionAuthenticator,
|
||||||
|
next http.HandlerFunc,
|
||||||
|
) http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
reqID := GetRequestID(r.Context())
|
requestID := GetRequestID(r.Context())
|
||||||
userID := r.Header.Get("X-User-Id")
|
|
||||||
|
|
||||||
if userID == "" {
|
token, ok := bearerToken(r.Header.Get("Authorization"))
|
||||||
response.WriteError(w, http.StatusUnauthorized, response.CodeUnauthorized, "missing X-User-Id header", reqID)
|
if !ok {
|
||||||
|
writeBearerUnauthorized(w, requestID)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
//существует ли чел
|
tokenHash := security.HashSessionToken(token)
|
||||||
user, err := st.GetUserByID(userID)
|
|
||||||
|
user, err := authenticator.GetUserBySession(
|
||||||
|
r.Context(),
|
||||||
|
tokenHash,
|
||||||
|
)
|
||||||
|
if errors.Is(err, store.ErrNotFound) {
|
||||||
|
writeBearerUnauthorized(w, requestID)
|
||||||
|
return
|
||||||
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
response.WriteError(w, http.StatusUnauthorized, response.CodeUnauthorized, "user not found", reqID)
|
response.WriteError(
|
||||||
|
w,
|
||||||
|
http.StatusServiceUnavailable,
|
||||||
|
response.CodeUnavailable,
|
||||||
|
"service is temporarily unavailable",
|
||||||
|
requestID,
|
||||||
|
)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
ctx := context.WithValue(r.Context(), UserContextKey, user)
|
ctx := context.WithValue(
|
||||||
|
r.Context(),
|
||||||
|
UserContextKey,
|
||||||
|
user,
|
||||||
|
)
|
||||||
|
ctx = context.WithValue(
|
||||||
|
ctx,
|
||||||
|
sessionTokenHashKey,
|
||||||
|
tokenHash,
|
||||||
|
)
|
||||||
|
|
||||||
next(w, r.WithContext(ctx))
|
next(w, r.WithContext(ctx))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// чисто чтоб зареганного получить из контекста
|
|
||||||
func GetCurrentUser(ctx context.Context) domain.User {
|
func GetCurrentUser(ctx context.Context) domain.User {
|
||||||
if val, ok := ctx.Value(UserContextKey).(domain.User); ok {
|
user, _ := ctx.Value(UserContextKey).(domain.User)
|
||||||
return val
|
return user
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetCurrentSessionTokenHash(ctx context.Context) []byte {
|
||||||
|
tokenHash, _ := ctx.Value(sessionTokenHashKey).([]byte)
|
||||||
|
|
||||||
|
result := make([]byte, len(tokenHash))
|
||||||
|
copy(result, tokenHash)
|
||||||
|
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
func bearerToken(authorization string) (string, bool) {
|
||||||
|
parts := strings.Fields(authorization)
|
||||||
|
|
||||||
|
if len(parts) != 2 ||
|
||||||
|
!strings.EqualFold(parts[0], "Bearer") ||
|
||||||
|
parts[1] == "" {
|
||||||
|
return "", false
|
||||||
}
|
}
|
||||||
return domain.User{}
|
|
||||||
|
return parts[1], true
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeBearerUnauthorized(
|
||||||
|
w http.ResponseWriter,
|
||||||
|
requestID string,
|
||||||
|
) {
|
||||||
|
w.Header().Set("WWW-Authenticate", bearerChallenge)
|
||||||
|
|
||||||
|
response.WriteError(
|
||||||
|
w,
|
||||||
|
http.StatusUnauthorized,
|
||||||
|
response.CodeUnauthorized,
|
||||||
|
"invalid or expired bearer token",
|
||||||
|
requestID,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ const (
|
|||||||
CodeUnauthorized = "unauthorized"
|
CodeUnauthorized = "unauthorized"
|
||||||
CodeNotFound = "not_found"
|
CodeNotFound = "not_found"
|
||||||
CodeConflict = "conflict"
|
CodeConflict = "conflict"
|
||||||
|
CodeUnavailable = "unavailable"
|
||||||
CodeInternalError = "internal_error"
|
CodeInternalError = "internal_error"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,9 @@
|
|||||||
|
BEGIN;
|
||||||
|
|
||||||
|
DROP TABLE sessions;
|
||||||
|
DROP TABLE messages;
|
||||||
|
DROP TABLE chat_members;
|
||||||
|
DROP TABLE chats;
|
||||||
|
DROP TABLE users;
|
||||||
|
|
||||||
|
COMMIT;
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
BEGIN;
|
||||||
|
|
||||||
|
CREATE TABLE users (
|
||||||
|
id UUID PRIMARY KEY,
|
||||||
|
username VARCHAR(32) NOT NULL,
|
||||||
|
display_name TEXT NOT NULL,
|
||||||
|
password_hash TEXT NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT users_username_unique
|
||||||
|
UNIQUE (username),
|
||||||
|
|
||||||
|
CONSTRAINT users_username_format
|
||||||
|
CHECK (username ~ '^[a-z0-9_]{3,32}$'),
|
||||||
|
|
||||||
|
CONSTRAINT users_display_name_length
|
||||||
|
CHECK (char_length(display_name) BETWEEN 1 AND 100),
|
||||||
|
|
||||||
|
CONSTRAINT users_display_name_not_blank
|
||||||
|
CHECK (btrim(display_name) <> ''),
|
||||||
|
|
||||||
|
CONSTRAINT users_password_hash_not_blank
|
||||||
|
CHECK (btrim(password_hash) <> '')
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE chats (
|
||||||
|
id UUID PRIMARY KEY,
|
||||||
|
title TEXT NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT chats_title_length
|
||||||
|
CHECK (char_length(title) BETWEEN 1 AND 100),
|
||||||
|
|
||||||
|
CONSTRAINT chats_title_not_blank
|
||||||
|
CHECK (btrim(title) <> '')
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX chats_created_at_id_idx
|
||||||
|
ON chats (created_at, id);
|
||||||
|
|
||||||
|
CREATE TABLE chat_members (
|
||||||
|
chat_id UUID NOT NULL,
|
||||||
|
user_id UUID NOT NULL,
|
||||||
|
position SMALLINT NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT chat_members_primary_key
|
||||||
|
PRIMARY KEY (chat_id, user_id),
|
||||||
|
|
||||||
|
CONSTRAINT chat_members_position_unique
|
||||||
|
UNIQUE (chat_id, position),
|
||||||
|
|
||||||
|
CONSTRAINT chat_members_position_range
|
||||||
|
CHECK (position BETWEEN 0 AND 99),
|
||||||
|
|
||||||
|
CONSTRAINT chat_members_chat_foreign_key
|
||||||
|
FOREIGN KEY (chat_id)
|
||||||
|
REFERENCES chats (id)
|
||||||
|
ON DELETE RESTRICT,
|
||||||
|
|
||||||
|
CONSTRAINT chat_members_user_foreign_key
|
||||||
|
FOREIGN KEY (user_id)
|
||||||
|
REFERENCES users (id)
|
||||||
|
ON DELETE RESTRICT
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX chat_members_user_chat_idx
|
||||||
|
ON chat_members (user_id, chat_id);
|
||||||
|
|
||||||
|
CREATE TABLE messages (
|
||||||
|
id UUID PRIMARY KEY,
|
||||||
|
chat_id UUID NOT NULL,
|
||||||
|
sender_id UUID NOT NULL,
|
||||||
|
text TEXT NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
CONSTRAINT messages_text_length
|
||||||
|
CHECK (char_length(text) BETWEEN 1 AND 4000),
|
||||||
|
|
||||||
|
CONSTRAINT messages_text_not_blank
|
||||||
|
CHECK (btrim(text) <> ''),
|
||||||
|
|
||||||
|
CONSTRAINT messages_sender_membership_foreign_key
|
||||||
|
FOREIGN KEY (chat_id, sender_id)
|
||||||
|
REFERENCES chat_members (chat_id, user_id)
|
||||||
|
ON DELETE RESTRICT
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX messages_chat_created_at_id_idx
|
||||||
|
ON messages (chat_id, created_at, id);
|
||||||
|
|
||||||
|
CREATE TABLE sessions (
|
||||||
|
token_hash BYTEA PRIMARY KEY,
|
||||||
|
user_id UUID NOT NULL,
|
||||||
|
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
expires_at TIMESTAMPTZ NOT NULL,
|
||||||
|
|
||||||
|
CONSTRAINT sessions_user_foreign_key
|
||||||
|
FOREIGN KEY (user_id)
|
||||||
|
REFERENCES users (id)
|
||||||
|
ON DELETE RESTRICT,
|
||||||
|
|
||||||
|
CONSTRAINT sessions_token_hash_length
|
||||||
|
CHECK (octet_length(token_hash) = 32),
|
||||||
|
|
||||||
|
CONSTRAINT sessions_expiry_after_creation
|
||||||
|
CHECK (expires_at > created_at)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX sessions_expires_at_idx
|
||||||
|
ON sessions (expires_at);
|
||||||
|
|
||||||
|
COMMIT;
|
||||||
Executable
+15
@@ -0,0 +1,15 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
|
||||||
|
project_root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
|
||||||
|
cd "$project_root"
|
||||||
|
|
||||||
|
env_file=${ENV_FILE:-.env}
|
||||||
|
|
||||||
|
# PostgreSQL хранит все обязательные данные и сессии в named volume.
|
||||||
|
# Обычный restart не удаляет volume и не применяет миграции повторно.
|
||||||
|
docker compose --env-file "$env_file" restart postgres
|
||||||
|
docker compose --env-file "$env_file" up -d --wait postgres
|
||||||
|
|
||||||
|
# API перезапускается после восстановления готовности PostgreSQL.
|
||||||
|
docker compose --env-file "$env_file" restart api
|
||||||
@@ -0,0 +1,352 @@
|
|||||||
|
package student_tests
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/json"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"net/http/httptest"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"mtusi2026lab2/internal/domain"
|
||||||
|
"mtusi2026lab2/internal/security"
|
||||||
|
"mtusi2026lab2/internal/store"
|
||||||
|
"mtusi2026lab2/internal/transport/http/handlers"
|
||||||
|
"mtusi2026lab2/internal/transport/http/middleware"
|
||||||
|
)
|
||||||
|
|
||||||
|
const testPassword = "Test-password-123"
|
||||||
|
|
||||||
|
func setupSessionTestServer(
|
||||||
|
t *testing.T,
|
||||||
|
sessionTTL time.Duration,
|
||||||
|
) (*httptest.Server, *store.MemoryRepository) {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
repository := store.NewMemoryRepository(store.NewMemoryStore())
|
||||||
|
handler := handlers.NewHandler(
|
||||||
|
repository,
|
||||||
|
handlers.WithSessionTTL(sessionTTL),
|
||||||
|
)
|
||||||
|
|
||||||
|
mux := http.NewServeMux()
|
||||||
|
mux.HandleFunc("POST /api/v1/users", handler.CreateUser)
|
||||||
|
mux.HandleFunc("POST /api/v1/auth/sessions", handler.CreateSession)
|
||||||
|
mux.HandleFunc(
|
||||||
|
"GET /api/v1/users/me",
|
||||||
|
middleware.RequireAuth(repository, handler.GetMe),
|
||||||
|
)
|
||||||
|
mux.HandleFunc(
|
||||||
|
"DELETE /api/v1/auth/sessions/current",
|
||||||
|
middleware.RequireAuth(repository, handler.DeleteCurrentSession),
|
||||||
|
)
|
||||||
|
|
||||||
|
var root http.Handler = mux
|
||||||
|
root = middleware.Recovery(root)
|
||||||
|
root = middleware.RequestID(root)
|
||||||
|
|
||||||
|
return httptest.NewServer(root), repository
|
||||||
|
}
|
||||||
|
|
||||||
|
func registerSessionTestUser(
|
||||||
|
t *testing.T,
|
||||||
|
baseURL string,
|
||||||
|
username string,
|
||||||
|
) domain.User {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
payload, err := json.Marshal(map[string]string{
|
||||||
|
"username": username,
|
||||||
|
"display_name": "Session test user",
|
||||||
|
"password": testPassword,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("marshal registration request: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
response, err := http.Post(
|
||||||
|
baseURL+"/api/v1/users",
|
||||||
|
"application/json",
|
||||||
|
bytes.NewReader(payload),
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("register user: %v", err)
|
||||||
|
}
|
||||||
|
defer response.Body.Close()
|
||||||
|
|
||||||
|
if response.StatusCode != http.StatusCreated {
|
||||||
|
body, _ := io.ReadAll(response.Body)
|
||||||
|
t.Fatalf("expected registration status 201, got %d: %s", response.StatusCode, body)
|
||||||
|
}
|
||||||
|
|
||||||
|
var user domain.User
|
||||||
|
if err := json.NewDecoder(response.Body).Decode(&user); err != nil {
|
||||||
|
t.Fatalf("decode registered user: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return user
|
||||||
|
}
|
||||||
|
|
||||||
|
func createSessionRequest(
|
||||||
|
t *testing.T,
|
||||||
|
baseURL string,
|
||||||
|
username string,
|
||||||
|
password string,
|
||||||
|
) *http.Response {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
credentials := base64.StdEncoding.EncodeToString(
|
||||||
|
[]byte(username + ":" + password),
|
||||||
|
)
|
||||||
|
|
||||||
|
request, err := http.NewRequest(
|
||||||
|
http.MethodPost,
|
||||||
|
baseURL+"/api/v1/auth/sessions",
|
||||||
|
nil,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("create login request: %v", err)
|
||||||
|
}
|
||||||
|
request.Header.Set("Authorization", "Basic "+credentials)
|
||||||
|
|
||||||
|
response, err := http.DefaultClient.Do(request)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("send login request: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSessionAuthenticationLifecycle(t *testing.T) {
|
||||||
|
testServer, repository := setupSessionTestServer(t, time.Hour)
|
||||||
|
defer testServer.Close()
|
||||||
|
|
||||||
|
alice := registerSessionTestUser(t, testServer.URL, "session_alice")
|
||||||
|
eve := registerSessionTestUser(t, testServer.URL, "session_eve")
|
||||||
|
|
||||||
|
_, passwordHash, err := repository.GetUserByUsername(
|
||||||
|
t.Context(),
|
||||||
|
alice.Username,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("read registered user credentials: %v", err)
|
||||||
|
}
|
||||||
|
if passwordHash == testPassword || bytes.Contains(
|
||||||
|
[]byte(passwordHash),
|
||||||
|
[]byte(testPassword),
|
||||||
|
) {
|
||||||
|
t.Fatal("repository contains plaintext password")
|
||||||
|
}
|
||||||
|
passwordMatches, err := security.VerifyPassword(testPassword, passwordHash)
|
||||||
|
if err != nil || !passwordMatches {
|
||||||
|
t.Fatalf("stored password hash does not verify: matches=%v err=%v", passwordMatches, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
wrongPasswordResponse := createSessionRequest(
|
||||||
|
t,
|
||||||
|
testServer.URL,
|
||||||
|
alice.Username,
|
||||||
|
"Wrong-password-123",
|
||||||
|
)
|
||||||
|
wrongPasswordResponse.Body.Close()
|
||||||
|
if wrongPasswordResponse.StatusCode != http.StatusUnauthorized {
|
||||||
|
t.Fatalf("expected 401 for wrong password, got %d", wrongPasswordResponse.StatusCode)
|
||||||
|
}
|
||||||
|
if got := wrongPasswordResponse.Header.Get("WWW-Authenticate"); got != `Basic realm="messenger", charset="UTF-8"` {
|
||||||
|
t.Fatalf("unexpected Basic challenge: %q", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
unknownUserResponse := createSessionRequest(
|
||||||
|
t,
|
||||||
|
testServer.URL,
|
||||||
|
"unknown_session_user",
|
||||||
|
"Wrong-password-123",
|
||||||
|
)
|
||||||
|
unknownUserResponse.Body.Close()
|
||||||
|
if unknownUserResponse.StatusCode != http.StatusUnauthorized {
|
||||||
|
t.Fatalf("expected 401 for unknown username, got %d", unknownUserResponse.StatusCode)
|
||||||
|
}
|
||||||
|
if got := unknownUserResponse.Header.Get("WWW-Authenticate"); got != `Basic realm="messenger", charset="UTF-8"` {
|
||||||
|
t.Fatalf("unexpected Basic challenge for unknown username: %q", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
loginResponse := createSessionRequest(
|
||||||
|
t,
|
||||||
|
testServer.URL,
|
||||||
|
alice.Username,
|
||||||
|
testPassword,
|
||||||
|
)
|
||||||
|
defer loginResponse.Body.Close()
|
||||||
|
if loginResponse.StatusCode != http.StatusCreated {
|
||||||
|
body, _ := io.ReadAll(loginResponse.Body)
|
||||||
|
t.Fatalf("expected login status 201, got %d: %s", loginResponse.StatusCode, body)
|
||||||
|
}
|
||||||
|
|
||||||
|
var session domain.Session
|
||||||
|
if err := json.NewDecoder(loginResponse.Body).Decode(&session); err != nil {
|
||||||
|
t.Fatalf("decode session: %v", err)
|
||||||
|
}
|
||||||
|
if session.Token == "" || session.TokenType != "Bearer" {
|
||||||
|
t.Fatalf("unexpected session token response: type=%q empty=%v", session.TokenType, session.Token == "")
|
||||||
|
}
|
||||||
|
if session.User != alice {
|
||||||
|
t.Fatalf("session belongs to another user: got %s, want %s", session.User.ID, alice.ID)
|
||||||
|
}
|
||||||
|
|
||||||
|
testCases := []struct {
|
||||||
|
name string
|
||||||
|
authorization string
|
||||||
|
userIDHeader string
|
||||||
|
wantStatus int
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "X-User-Id alone is rejected",
|
||||||
|
userIDHeader: alice.ID,
|
||||||
|
wantStatus: http.StatusUnauthorized,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Basic is rejected on business endpoint",
|
||||||
|
authorization: "Basic " + base64.StdEncoding.EncodeToString([]byte(alice.Username+":"+testPassword)),
|
||||||
|
wantStatus: http.StatusUnauthorized,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Bearer identity wins over X-User-Id",
|
||||||
|
authorization: "Bearer " + session.Token,
|
||||||
|
userIDHeader: eve.ID,
|
||||||
|
wantStatus: http.StatusOK,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, testCase := range testCases {
|
||||||
|
t.Run(testCase.name, func(t *testing.T) {
|
||||||
|
request, err := http.NewRequest(
|
||||||
|
http.MethodGet,
|
||||||
|
testServer.URL+"/api/v1/users/me",
|
||||||
|
nil,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("create authenticated request: %v", err)
|
||||||
|
}
|
||||||
|
if testCase.authorization != "" {
|
||||||
|
request.Header.Set("Authorization", testCase.authorization)
|
||||||
|
}
|
||||||
|
if testCase.userIDHeader != "" {
|
||||||
|
request.Header.Set("X-User-Id", testCase.userIDHeader)
|
||||||
|
}
|
||||||
|
|
||||||
|
response, err := http.DefaultClient.Do(request)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("send authenticated request: %v", err)
|
||||||
|
}
|
||||||
|
defer response.Body.Close()
|
||||||
|
|
||||||
|
if response.StatusCode != testCase.wantStatus {
|
||||||
|
t.Fatalf("expected status %d, got %d", testCase.wantStatus, response.StatusCode)
|
||||||
|
}
|
||||||
|
|
||||||
|
if testCase.wantStatus == http.StatusUnauthorized {
|
||||||
|
if got := response.Header.Get("WWW-Authenticate"); got != `Bearer realm="messenger"` {
|
||||||
|
t.Fatalf("unexpected Bearer challenge: %q", got)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var currentUser domain.User
|
||||||
|
if err := json.NewDecoder(response.Body).Decode(¤tUser); err != nil {
|
||||||
|
t.Fatalf("decode current user: %v", err)
|
||||||
|
}
|
||||||
|
if currentUser.ID != alice.ID {
|
||||||
|
t.Fatalf("X-User-Id overrode Bearer identity: got %s, want %s", currentUser.ID, alice.ID)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
logoutRequest, err := http.NewRequest(
|
||||||
|
http.MethodDelete,
|
||||||
|
testServer.URL+"/api/v1/auth/sessions/current",
|
||||||
|
nil,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("create logout request: %v", err)
|
||||||
|
}
|
||||||
|
logoutRequest.Header.Set("Authorization", "Bearer "+session.Token)
|
||||||
|
|
||||||
|
logoutResponse, err := http.DefaultClient.Do(logoutRequest)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("send logout request: %v", err)
|
||||||
|
}
|
||||||
|
logoutBody, err := io.ReadAll(logoutResponse.Body)
|
||||||
|
logoutResponse.Body.Close()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("read logout response: %v", err)
|
||||||
|
}
|
||||||
|
if logoutResponse.StatusCode != http.StatusNoContent {
|
||||||
|
t.Fatalf("expected logout status 204, got %d", logoutResponse.StatusCode)
|
||||||
|
}
|
||||||
|
if len(logoutBody) != 0 {
|
||||||
|
t.Fatalf("logout response contains a body: %q", logoutBody)
|
||||||
|
}
|
||||||
|
|
||||||
|
revokedRequest, err := http.NewRequest(
|
||||||
|
http.MethodGet,
|
||||||
|
testServer.URL+"/api/v1/users/me",
|
||||||
|
nil,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("create revoked-token request: %v", err)
|
||||||
|
}
|
||||||
|
revokedRequest.Header.Set("Authorization", "Bearer "+session.Token)
|
||||||
|
|
||||||
|
revokedResponse, err := http.DefaultClient.Do(revokedRequest)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("send revoked-token request: %v", err)
|
||||||
|
}
|
||||||
|
revokedResponse.Body.Close()
|
||||||
|
if revokedResponse.StatusCode != http.StatusUnauthorized {
|
||||||
|
t.Fatalf("expected 401 for revoked token, got %d", revokedResponse.StatusCode)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSessionExpiry(t *testing.T) {
|
||||||
|
testServer, _ := setupSessionTestServer(t, 25*time.Millisecond)
|
||||||
|
defer testServer.Close()
|
||||||
|
|
||||||
|
user := registerSessionTestUser(t, testServer.URL, "session_expiry")
|
||||||
|
loginResponse := createSessionRequest(
|
||||||
|
t,
|
||||||
|
testServer.URL,
|
||||||
|
user.Username,
|
||||||
|
testPassword,
|
||||||
|
)
|
||||||
|
|
||||||
|
var session domain.Session
|
||||||
|
if err := json.NewDecoder(loginResponse.Body).Decode(&session); err != nil {
|
||||||
|
loginResponse.Body.Close()
|
||||||
|
t.Fatalf("decode session: %v", err)
|
||||||
|
}
|
||||||
|
loginResponse.Body.Close()
|
||||||
|
|
||||||
|
time.Sleep(75 * time.Millisecond)
|
||||||
|
|
||||||
|
request, err := http.NewRequest(
|
||||||
|
http.MethodGet,
|
||||||
|
testServer.URL+"/api/v1/users/me",
|
||||||
|
nil,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("create expired-token request: %v", err)
|
||||||
|
}
|
||||||
|
request.Header.Set("Authorization", "Bearer "+session.Token)
|
||||||
|
|
||||||
|
response, err := http.DefaultClient.Do(request)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("send expired-token request: %v", err)
|
||||||
|
}
|
||||||
|
response.Body.Close()
|
||||||
|
|
||||||
|
if response.StatusCode != http.StatusUnauthorized {
|
||||||
|
t.Fatalf("expected 401 for expired token, got %d", response.StatusCode)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@ package student_tests
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
@@ -18,25 +19,67 @@ import (
|
|||||||
"mtusi2026lab2/internal/transport/http/middleware"
|
"mtusi2026lab2/internal/transport/http/middleware"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func requireLegacyAuth(
|
||||||
|
memoryStore *store.MemoryStore,
|
||||||
|
next http.HandlerFunc,
|
||||||
|
) http.HandlerFunc {
|
||||||
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
userID := r.Header.Get("X-User-Id")
|
||||||
|
|
||||||
|
user, err := memoryStore.GetUserByID(userID)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx := context.WithValue(
|
||||||
|
r.Context(),
|
||||||
|
middleware.UserContextKey,
|
||||||
|
user,
|
||||||
|
)
|
||||||
|
|
||||||
|
next(w, r.WithContext(ctx))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// изолированный серв для тестов
|
// изолированный серв для тестов
|
||||||
func setupTestServer() (*httptest.Server, *store.MemoryStore) {
|
func setupTestServer() (*httptest.Server, *store.MemoryStore) {
|
||||||
st := store.NewMemoryStore()
|
memoryStore := store.NewMemoryStore()
|
||||||
h := handlers.NewHandler(st)
|
repository := store.NewMemoryRepository(memoryStore)
|
||||||
|
handler := handlers.NewHandler(repository)
|
||||||
|
|
||||||
mux := http.NewServeMux()
|
mux := http.NewServeMux()
|
||||||
mux.HandleFunc("POST /api/v1/users", h.CreateUser)
|
mux.HandleFunc("POST /api/v1/users", handler.CreateUser)
|
||||||
mux.HandleFunc("GET /api/v1/users/me", middleware.RequireAuth(st, h.GetMe))
|
mux.HandleFunc(
|
||||||
mux.HandleFunc("POST /api/v1/chats", middleware.RequireAuth(st, h.CreateChat))
|
"GET /api/v1/users/me",
|
||||||
mux.HandleFunc("GET /api/v1/chats", middleware.RequireAuth(st, h.ListChats))
|
requireLegacyAuth(memoryStore, handler.GetMe),
|
||||||
mux.HandleFunc("GET /api/v1/chats/{chat_id}", middleware.RequireAuth(st, h.GetChat))
|
)
|
||||||
mux.HandleFunc("POST /api/v1/chats/{chat_id}/messages", middleware.RequireAuth(st, h.CreateMessage))
|
mux.HandleFunc(
|
||||||
mux.HandleFunc("GET /api/v1/chats/{chat_id}/messages", middleware.RequireAuth(st, h.GetMessages))
|
"POST /api/v1/chats",
|
||||||
|
requireLegacyAuth(memoryStore, handler.CreateChat),
|
||||||
|
)
|
||||||
|
mux.HandleFunc(
|
||||||
|
"GET /api/v1/chats",
|
||||||
|
requireLegacyAuth(memoryStore, handler.ListChats),
|
||||||
|
)
|
||||||
|
mux.HandleFunc(
|
||||||
|
"GET /api/v1/chats/{chat_id}",
|
||||||
|
requireLegacyAuth(memoryStore, handler.GetChat),
|
||||||
|
)
|
||||||
|
mux.HandleFunc(
|
||||||
|
"POST /api/v1/chats/{chat_id}/messages",
|
||||||
|
requireLegacyAuth(memoryStore, handler.CreateMessage),
|
||||||
|
)
|
||||||
|
mux.HandleFunc(
|
||||||
|
"GET /api/v1/chats/{chat_id}/messages",
|
||||||
|
requireLegacyAuth(memoryStore, handler.GetMessages),
|
||||||
|
)
|
||||||
|
|
||||||
var root http.Handler = mux
|
var root http.Handler = mux
|
||||||
root = middleware.Recovery(root)
|
root = middleware.Recovery(root)
|
||||||
root = middleware.RequestID(root)
|
root = middleware.RequestID(root)
|
||||||
|
|
||||||
return httptest.NewServer(root), st
|
return httptest.NewServer(root), memoryStore
|
||||||
}
|
}
|
||||||
|
|
||||||
// 1 тест на дубликат username -> 409 Conflict
|
// 1 тест на дубликат username -> 409 Conflict
|
||||||
@@ -44,7 +87,10 @@ func TestDuplicateUsername(t *testing.T) {
|
|||||||
ts, _ := setupTestServer()
|
ts, _ := setupTestServer()
|
||||||
defer ts.Close()
|
defer ts.Close()
|
||||||
|
|
||||||
body := `{"username":"bob_the_builder","display_name":"Боб"}`
|
body := `{
|
||||||
|
"username":"bob_the_builder",
|
||||||
|
"display_name":"Боб",
|
||||||
|
"password":"Test-password-123"}`
|
||||||
|
|
||||||
// Первый раз — 201 Created
|
// Первый раз — 201 Created
|
||||||
res1, _ := http.Post(ts.URL+"/api/v1/users", "application/json", bytes.NewBufferString(body))
|
res1, _ := http.Post(ts.URL+"/api/v1/users", "application/json", bytes.NewBufferString(body))
|
||||||
|
|||||||
Reference in New Issue
Block a user