Implement PostgreSQL storage, sessions and persistence checks
This commit is contained in:
@@ -6,6 +6,8 @@ APP_ENV=lab
|
||||
SESSION_TTL_SECONDS=3600
|
||||
# Choose credentials locally. File paths contain no secret values.
|
||||
DATABASE_URL_FILE=/run/secrets/database_url
|
||||
# Current Go connection check uses this file instead of DATABASE_URL_FILE:
|
||||
DATABASE_PASSWORD_FILE=/run/secrets/postgres_password
|
||||
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
|
||||
SESSION_STORE=postgres
|
||||
CACHE_URL_FILE=/run/secrets/cache_url
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
*.sh text eol=lf
|
||||
*.cmd text eol=crlf
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
FROM golang:1.26.3 AS build
|
||||
|
||||
WORKDIR /src
|
||||
|
||||
ENV GOTOOLCHAIN=local
|
||||
ENV CGO_ENABLED=0
|
||||
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
COPY cmd ./cmd
|
||||
COPY internal ./internal
|
||||
|
||||
RUN go vet ./... \
|
||||
&& go test ./... \
|
||||
&& go build -trimpath -ldflags="-s -w" -o /out/server ./cmd/server
|
||||
|
||||
FROM scratch
|
||||
|
||||
COPY --from=build /out/server /server
|
||||
|
||||
USER 65532:65532
|
||||
|
||||
ENV APP_HOST=0.0.0.0
|
||||
ENV APP_PORT=8080
|
||||
|
||||
EXPOSE 8080
|
||||
|
||||
STOPSIGNAL SIGTERM
|
||||
|
||||
HEALTHCHECK --interval=5s --timeout=3s --start-period=5s --retries=3 \
|
||||
CMD ["/server", "healthcheck"]
|
||||
|
||||
ENTRYPOINT ["/server"]
|
||||
@@ -1,37 +1,133 @@
|
||||
# Отчёт — лабораторная 2
|
||||
|
||||
- Автор, группа: TODO
|
||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
||||
- Commit/PR: TODO после публикации
|
||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
||||
- **Автор:** Ситникова Дарья Евгеньевна, БВТ2303.
|
||||
- **Целевая оценка:** 4; Redis и эксперименты уровня 4 ещё в работе.
|
||||
- **Ветка решения:** `solution/bvt2303-sitnikova`.
|
||||
- **Commit/PR:** будут указаны после публикации.
|
||||
- **Статус:** публичные smoke и persistence пройдены на Windows; чистый clone отдельно не проверен.
|
||||
|
||||
## Запуск из чистого clone
|
||||
## Запуск
|
||||
|
||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
||||
Нужны Docker Desktop с Linux-контейнерами, PowerShell и Python 3.9+. Команды из корня lab2:
|
||||
|
||||
```powershell
|
||||
./scripts/init-local.ps1
|
||||
# .env необязателен: Compose использует значения по умолчанию.
|
||||
docker compose config --quiet
|
||||
docker compose up -d --build --wait api
|
||||
py tests/smoke.py --base-url http://localhost:8080
|
||||
py tests/resilience.py --mode persistence --action-script scripts/restart.cmd --base-url http://localhost:8080
|
||||
```
|
||||
|
||||
| Компонент | Настройка |
|
||||
| --- | --- |
|
||||
| API | Go 1.26.3; сборка в Docker; непривилегированный пользователь; localhost:8080 |
|
||||
| PostgreSQL | `postgres:17.9-bookworm`; внутренний порт 5432 |
|
||||
| Миграции | Одноразовый сервис `migrate`; API ждёт успешного завершения |
|
||||
| Данные | Именованный volume `postgres_data` → `/var/lib/postgresql/data` |
|
||||
| Пароль БД | `scripts/init-local.ps1` создаёт `secrets/postgres_password.txt`; повторно не перезаписывает |
|
||||
| Конфигурация | `DATABASE_PASSWORD_FILE`, `SESSION_TTL_SECONDS` (по умолчанию 3600) |
|
||||
|
||||
`secrets/`, `.env` и данные исключены из Git. Изменение файла пароля не меняет пароль уже созданной роли БД. `APP_HOST`/`APP_PORT` поддерживаются Go, но Compose публикует фиксированный порт 8080. Остальные переменные исходного `.env.example` пока не используются.
|
||||
|
||||
- Остановка с сохранением данных: `docker compose down`.
|
||||
- **Намеренное удаление учебной БД:** `docker compose down --volumes`. Не использовать в проверках сохранности.
|
||||
- Linux/macOS: `chmod +x scripts/restart.sh`, затем `make test-persistence ACTION_SCRIPT=scripts/restart.sh`. Linux-hook отдельно не запускался; executable bit нужно сохранить в Git.
|
||||
|
||||
### Дополнительные проверки
|
||||
|
||||
```powershell
|
||||
py student-tests/registration.py
|
||||
py student-tests/sessions.py
|
||||
py student-tests/chat-rollback.py
|
||||
go test ./...
|
||||
go vet ./...
|
||||
```
|
||||
|
||||
Проверка expiry с восстановлением прежней настройки:
|
||||
|
||||
```powershell
|
||||
$previousSessionTTL = $env:SESSION_TTL_SECONDS
|
||||
try {
|
||||
$env:SESSION_TTL_SECONDS = '2'
|
||||
docker compose up -d --wait api
|
||||
if ($LASTEXITCODE -ne 0) { throw 'API did not start' }
|
||||
py student-tests/sessions.py --expiry
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Expiry test failed' }
|
||||
}
|
||||
finally {
|
||||
if ($null -eq $previousSessionTTL) {
|
||||
Remove-Item Env:SESSION_TTL_SECONDS -ErrorAction SilentlyContinue
|
||||
} else {
|
||||
$env:SESSION_TTL_SECONDS = $previousSessionTTL
|
||||
}
|
||||
docker compose up -d --wait api
|
||||
}
|
||||
```
|
||||
|
||||
## Архитектура и решения
|
||||
|
||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab1, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
||||
**Клиент → Go API → PostgreSQL.** Из lab1 перенесены исходники, собственные тесты, go.mod и Dockerfile. Lab1 не изменялась; контракт и публичные тесты lab2 сохранены. Старое хранилище в памяти оставлено для регрессионных тестов, сервер использует PostgreSQL.
|
||||
|
||||
| Область | Решение |
|
||||
| --- | --- |
|
||||
| Схема | users, chats, chat_members, messages, sessions; PK, FK, UNIQUE(username), CHECK |
|
||||
| Миграции | Версия в schema_migrations; SQL и запись версии в одной транзакции; advisory lock; повторный запуск пропускает версию |
|
||||
| Пароли | Библиотечный Argon2id: 64 MiB, 3 прохода, параллелизм 4, соль 16 байт, результат 32 байта; 12–128 Unicode code points |
|
||||
| Нагрузка KDF | Общие 2 слота для регистрации и входа; начатое вычисление не прерывается контекстом |
|
||||
| Сессии | Basic только для входа; случайный токен 256 бит; в БД SHA-256 токена и expires_at; защищённые запросы принимают Bearer |
|
||||
| Expiry/logout | Время проверяется в БД; срок не продлевается; logout удаляет текущую сессию; неизвестный/истёкший/отозванный токен — 401 |
|
||||
| Доступ | X-User-Id игнорируется; проверяется членство; чужой/отсутствующий чат — 404 |
|
||||
| Транзакции | Создание чата и участников атомарно; сообщение подтверждается после COMMIT; конфликт username — 409 |
|
||||
| История | Keyset по (created_at,id), индекс (chat_id,created_at,id), LIMIT limit+1; курсор привязан к чату |
|
||||
| Конкурентная запись | FOR UPDATE строки чата; время нового сообщения ≥ последнего + 1 мкс; записи одного чата последовательны |
|
||||
| Пул и таймауты | До 10 соединений; connect 3 с; statement 3 с; lock 2 с; SQL-контексты до 3 с; регистрация/вход до 5 с, кроме непрерываемого KDF |
|
||||
| Health | live — процесс; ready — Ping PostgreSQL; версия схемы в readiness не проверяется |
|
||||
| Ошибки | Ошибки БД обобщаются в 503; пароли, токены и детали SQL не выводятся |
|
||||
|
||||
Пагинация не создаёт общий snapshot между запросами. При откате часов время сообщений может временно опережать физические часы. Подробности схемы: [storage-design.md](docs/storage-design.md), [миграции](migrations/README.md).
|
||||
|
||||
## Доказательства критериев
|
||||
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||
| Проверка | Команда/сценарий | Результат | Доказательство |
|
||||
| --- | --- | --- | --- |
|
||||
| Публичный smoke | make test | TODO | TODO |
|
||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
||||
| Сборка API | `docker compose up -d --build --wait api` | go vet/test/build успешны; API и БД Healthy | [вывод](evidence/registration-http.txt) |
|
||||
| Публичный smoke | `py tests/smoke.py --base-url http://localhost:8080` | PASS, сквозной API lab2 | [вывод](evidence/postgres-chats-checks.txt) |
|
||||
| Persistence | `py tests/resilience.py --mode persistence --action-script scripts/restart.cmd --base-url http://localhost:8080` | PASS, прежние токены и подтверждённое сообщение сохранены | [вывод](evidence/persistence.txt) |
|
||||
| Область рестарта | restart.ps1: stop/start api и postgres | StartedAt обоих изменился; volume сохранился | [снимки](evidence/restart-containers.json) |
|
||||
| Миграция с нуля и повтор | `psql -f /migrations/apply.psql` внутри postgres | 6 таблиц; версия 1 одна; повтор пропущен | [вывод](evidence/postgres-migration.txt) |
|
||||
| Автомиграции | `docker compose up -d --wait api` | migrate завершился с кодом 0; API Healthy | [вывод](evidence/persistence.txt) |
|
||||
| Регистрация и гонка имени | `py student-tests/registration.py`; SQL-проверка users | 201; дубликат 409; неверные поля 400; гонка → 201/409 | [вывод](evidence/registration-http.txt) |
|
||||
| Password KDF | `go test ./internal/password -v -count=1` | PASS: Unicode, соль, неверный пароль, повреждённый хеш | [вывод](evidence/password-tests.txt) |
|
||||
| Вход и выход | `py student-tests/sessions.py` | PASS: Basic/Bearer, неверный пароль, logout; X-User-Id не даёт доступ | [вывод](evidence/sessions-http.txt) |
|
||||
| Expiry | TTL=2; `py student-tests/sessions.py --expiry` | До истечения доступ есть, после — 401 | [вывод](evidence/sessions-http.txt) |
|
||||
| Rollback | `py student-tests/chat-rollback.py` | Неизвестный второй участник → 400; строка чата не осталась | [вывод](evidence/postgres-chats-checks.txt) |
|
||||
|
||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
||||
В evidence сохранены команды и результаты проверок; дата проверок — 09.10.2026. Проверки выполнены на рабочем дереве до первого коммита решения; commit будет указан после фиксации и контрольного запуска. Smoke и persistence запущены напрямую через Python — это сценарии Makefile; сам make на Windows не запускался. Начальная миграция проверена на новом volume, автомиграции — на существующей БД.
|
||||
|
||||
## Эксперименты и отказы
|
||||
## Эксперименты и ограничения
|
||||
|
||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
||||
| Воздействие | Ожидание | Наблюдение |
|
||||
| --- | --- | --- |
|
||||
| Управляемый stop/start API и PostgreSQL | Прежние данные и сессии доступны | PASS, потерь в сценарии нет; время восстановления отдельно не измерялось |
|
||||
| TTL=2 | Токен перестаёт работать | После истечения — 401 |
|
||||
| Несуществующий участник | Создание чата отменяется целиком | Rollback подтверждён SQL |
|
||||
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||
| --- | --- | --- | --- |
|
||||
| TODO | TODO | TODO | TODO |
|
||||
- Стенд одноузловой, без HA и backup; потеря диска, удаление volume и отключение питания не проверялись.
|
||||
- Роль messenger имеет superuser-права; TCP без TLS допускается только в локальном стенде.
|
||||
- Истёкшие сессии не очищаются автоматически; доступ по ним запрещён.
|
||||
- Новый чистый clone и Linux-hook отдельно не проверены.
|
||||
|
||||
## Ограничения и следующие шаги
|
||||
## Осталось на оценку 4
|
||||
|
||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
||||
- Redis как кэш профилей: TTL 60 с, источник истины PostgreSQL, обход кэша при отказе.
|
||||
- Автотесты недоступности Redis/БД и повторный persistence со всеми хранилищами.
|
||||
- EXPLAIN (ANALYZE, BUFFERS) на ≥10 000 сообщениях и обоснование индекса.
|
||||
- Финальная проверка запуска, оформление commit/PR.
|
||||
|
||||
## Источники и помощь
|
||||
|
||||
- Задание и контракт lab2; собственная реализация lab1.
|
||||
- [pgxpool](https://pkg.go.dev/github.com/jackc/pgx/v5/pgxpool), pgx v5.7.6.
|
||||
- [RFC 9106](https://www.rfc-editor.org/rfc/rfc9106.html#section-4), Argon2id из golang.org/x/crypto v0.37.0.
|
||||
- Codex: помощь с реализацией, объяснениями, проверками и ведением отчёта.
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store"
|
||||
)
|
||||
|
||||
func checkDatabase() error {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
|
||||
defer cancel()
|
||||
|
||||
pool, err := store.OpenPostgres(ctx, envOrDefault(
|
||||
"DATABASE_PASSWORD_FILE", "/run/secrets/postgres_password",
|
||||
))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer pool.Close()
|
||||
|
||||
queryCtx, queryCancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer queryCancel()
|
||||
|
||||
var applied bool
|
||||
err = pool.QueryRow(queryCtx,
|
||||
"SELECT EXISTS (SELECT 1 FROM schema_migrations WHERE version = $1)",
|
||||
int64(1),
|
||||
).Scan(&applied)
|
||||
if err != nil {
|
||||
return errors.New("cannot read schema_migrations; check database and migrations")
|
||||
}
|
||||
if !applied {
|
||||
return errors.New("migration 000001 is not applied")
|
||||
}
|
||||
|
||||
fmt.Println("PASS: PostgreSQL connection, migration 000001; pool max_conns=10")
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strconv"
|
||||
"sync/atomic"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/httpapi"
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store"
|
||||
)
|
||||
|
||||
func main() {
|
||||
log.SetFlags(log.LstdFlags | log.LUTC)
|
||||
|
||||
if len(os.Args) == 2 && os.Args[1] == "dbcheck" {
|
||||
if err := checkDatabase(); err != nil {
|
||||
log.Print(err)
|
||||
os.Exit(1)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if len(os.Args) == 2 && os.Args[1] == "healthcheck" {
|
||||
if err := healthcheck(); err != nil {
|
||||
log.Print(err)
|
||||
os.Exit(1)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if err := run(); err != nil {
|
||||
log.Print(err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func run() error {
|
||||
host := envOrDefault("APP_HOST", "0.0.0.0")
|
||||
port := envOrDefault("APP_PORT", "8080")
|
||||
|
||||
pool, err := store.OpenPostgres(context.Background(), envOrDefault(
|
||||
"DATABASE_PASSWORD_FILE", "/run/secrets/postgres_password",
|
||||
))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer pool.Close()
|
||||
db := store.NewPostgresStore(pool)
|
||||
|
||||
var stopping atomic.Bool
|
||||
ttl, err := strconv.ParseInt(envOrDefault("SESSION_TTL_SECONDS", "3600"), 10, 64)
|
||||
if err != nil {
|
||||
return errors.New("invalid SESSION_TTL_SECONDS")
|
||||
}
|
||||
handler, err := httpapi.NewPostgresHandler(db, &stopping, ttl)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
server := &http.Server{
|
||||
Addr: net.JoinHostPort(host, port),
|
||||
Handler: handler,
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
ReadTimeout: 10 * time.Second,
|
||||
WriteTimeout: 10 * time.Second,
|
||||
IdleTimeout: 60 * time.Second,
|
||||
}
|
||||
|
||||
ctx, stop := signal.NotifyContext(
|
||||
context.Background(),
|
||||
os.Interrupt,
|
||||
syscall.SIGTERM,
|
||||
)
|
||||
defer stop()
|
||||
|
||||
serverErrors := make(chan error, 1)
|
||||
|
||||
go func() {
|
||||
log.Printf("server starting address=%s", server.Addr)
|
||||
serverErrors <- server.ListenAndServe()
|
||||
}()
|
||||
|
||||
select {
|
||||
case err := <-serverErrors:
|
||||
if errors.Is(err, http.ErrServerClosed) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
|
||||
case <-ctx.Done():
|
||||
stopping.Store(true)
|
||||
log.Print("shutdown started timeout=8s")
|
||||
}
|
||||
|
||||
started := time.Now()
|
||||
|
||||
shutdownCtx, cancel := context.WithTimeout(
|
||||
context.Background(),
|
||||
8*time.Second,
|
||||
)
|
||||
defer cancel()
|
||||
|
||||
if err := server.Shutdown(shutdownCtx); err != nil {
|
||||
_ = server.Close()
|
||||
return fmt.Errorf("shutdown forced: %w", err)
|
||||
}
|
||||
|
||||
log.Printf(
|
||||
"shutdown completed duration_ms=%d",
|
||||
time.Since(started).Milliseconds(),
|
||||
)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func healthcheck() error {
|
||||
host := envOrDefault("APP_HOST", "0.0.0.0")
|
||||
port := envOrDefault("APP_PORT", "8080")
|
||||
|
||||
switch host {
|
||||
case "0.0.0.0", "":
|
||||
host = "127.0.0.1"
|
||||
case "::":
|
||||
host = "::1"
|
||||
}
|
||||
|
||||
client := &http.Client{
|
||||
Timeout: 2 * time.Second,
|
||||
}
|
||||
|
||||
url := "http://" + net.JoinHostPort(host, port) + "/health/ready"
|
||||
|
||||
response, err := client.Get(url)
|
||||
if err != nil {
|
||||
return fmt.Errorf("healthcheck: %w", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("healthcheck: status=%d", response.StatusCode)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func envOrDefault(name string, fallback string) string {
|
||||
if value := os.Getenv(name); value != "" {
|
||||
return value
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
name: messenger-lab2
|
||||
|
||||
services:
|
||||
api:
|
||||
build: .
|
||||
environment:
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||
DATABASE_PASSWORD_FILE: /run/secrets/postgres_password
|
||||
secrets:
|
||||
- postgres_password
|
||||
ports:
|
||||
- "127.0.0.1:8080:8080"
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
stop_grace_period: 15s
|
||||
|
||||
migrate:
|
||||
image: postgres:17.9-bookworm
|
||||
environment:
|
||||
PGHOST: postgres
|
||||
PGUSER: messenger
|
||||
PGDATABASE: messenger
|
||||
PGCONNECT_TIMEOUT: "5"
|
||||
secrets:
|
||||
- postgres_password
|
||||
volumes:
|
||||
- ./migrations:/migrations:ro
|
||||
entrypoint: ["/bin/sh", "-ec"]
|
||||
command:
|
||||
- 'export PGPASSWORD="$$(cat /run/secrets/postgres_password)"; exec psql -X -f /migrations/apply.psql'
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
|
||||
dbcheck:
|
||||
profiles: [tools]
|
||||
build: .
|
||||
command: [dbcheck]
|
||||
environment:
|
||||
DATABASE_PASSWORD_FILE: /run/secrets/postgres_password
|
||||
secrets:
|
||||
- postgres_password
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
healthcheck:
|
||||
disable: true
|
||||
|
||||
postgres:
|
||||
image: postgres:17.9-bookworm
|
||||
environment:
|
||||
POSTGRES_DB: messenger
|
||||
POSTGRES_USER: messenger
|
||||
POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password
|
||||
POSTGRES_INITDB_ARGS: --encoding=UTF8
|
||||
secrets:
|
||||
- postgres_password
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
- ./migrations:/migrations:ro
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U messenger -d messenger"]
|
||||
interval: 3s
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
start_period: 10s
|
||||
stop_grace_period: 30s
|
||||
|
||||
secrets:
|
||||
postgres_password:
|
||||
file: ./secrets/postgres_password.txt
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
||||
@@ -0,0 +1,45 @@
|
||||
# План хранения lab2
|
||||
|
||||
Статус: начальная SQL-миграция `migrations/000001_initial.up.sql` применена через `apply.psql`; повторный запуск пропускает версию 1. Запросы приложения к PostgreSQL ещё не реализованы. Приложение пока использует MemoryStore.
|
||||
|
||||
## Источник истины
|
||||
|
||||
PostgreSQL хранит пользователей, чаты, членство, сообщения и сессии. Планируемая роль Redis — кэш публичного профиля пользователя по ID с ограниченным TTL. В кэш не попадают пароль, его hash или Bearer-токен. Сессия и её срок проверяются в PostgreSQL на каждом защищённом запросе; кэш профиля не даёт права доступа.
|
||||
|
||||
При недоступности Redis профиль читается из PostgreSQL после ограниченного таймаутом обращения к кэшу. При недоступности PostgreSQL защищённый запрос получает 503; успешная аутентификация только по кэшу запрещена. История сообщений не кэшируется.
|
||||
|
||||
Профиль не изменяется обязательным API lab2, поэтому инвалидация происходит по TTL (план: 60 секунд); при добавлении редактирования потребуется отдельное решение об инвалидации. При потере кэша он заполняется заново. Все обязательные данные, включая сессии, сохраняются в PostgreSQL volume.
|
||||
|
||||
## Таблицы
|
||||
|
||||
| Таблица | Поля | Ограничения |
|
||||
| --- | --- | --- |
|
||||
| users | id UUID, username TEXT, display_name TEXT, password_hash TEXT, created_at TIMESTAMPTZ | PK(id), UNIQUE(username), все поля NOT NULL |
|
||||
| chats | id UUID, title TEXT, created_at TIMESTAMPTZ | PK(id), все поля NOT NULL |
|
||||
| chat_members | chat_id UUID, user_id UUID | PK(chat_id, user_id), FK chat_id → chats.id, FK user_id → users.id |
|
||||
| messages | id UUID, chat_id UUID, sender_id UUID, text TEXT, created_at TIMESTAMPTZ | PK(id), FK(chat_id, sender_id) → chat_members(chat_id, user_id), все поля NOT NULL |
|
||||
| sessions | token_hash BYTEA, user_id UUID, created_at TIMESTAMPTZ, expires_at TIMESTAMPTZ | PK(token_hash), FK user_id → users.id, expires_at > created_at, все поля NOT NULL |
|
||||
|
||||
Ограничения длины строк и формата username добавляются в миграции по контракту. Проверка Unicode-пробелов остаётся также в Go. Создание чата требует 1–100 уникальных существующих участников и присутствия вызывающего; проверки выполняет сервис, запись всех строк — одна транзакция. Удаления пользователей и участников обязательным API не предусмотрены; каскадное удаление на этом этапе не планируется.
|
||||
|
||||
Пароль хранится как результат password KDF с солью и параметрами, планируется Argon2id. token_hash — SHA-256 от случайного токена с энтропией 256 бит; сам токен возвращается клиенту при входе. Быстрый hash случайного токена не заменяет KDF для паролей.
|
||||
|
||||
## Индексы
|
||||
|
||||
- UNIQUE(username) защищает от конкурентной регистрации одного имени; соответствующий индекс создаёт PostgreSQL.
|
||||
- PK(chat_id, user_id) исключает повторное членство и позволяет проверять доступ к чату.
|
||||
- chat_members(user_id, chat_id) нужен для поиска чатов пользователя.
|
||||
- messages(chat_id, created_at, id) нужен для истории конкретного чата в порядке (created_at, id) и keyset-пагинации. Из БД выбираем limit + 1 строку, чтобы определить next_cursor; всю историю в Go не загружаем.
|
||||
- sessions(expires_at) нужен для очистки истёкших сессий. Действительность проверяется по expires_at при запросе независимо от очистки.
|
||||
|
||||
Эффективность индекса истории пока не измерена; требуется EXPLAIN (ANALYZE, BUFFERS) на ≥10 000 сообщениях.
|
||||
|
||||
## Транзакционные границы
|
||||
|
||||
- Регистрация: вставка пользователя; конфликт UNIQUE(username) преобразуется в HTTP 409.
|
||||
- Создание чата: вставка chats и всех chat_members в одной транзакции. Любая ошибка вызывает rollback всего создания.
|
||||
- Отправка сообщения: проверка доступа и вставка в рамках транзакции; 201 выдаётся после успешного COMMIT. Составной FK дополнительно запрещает сообщение от неучастника.
|
||||
- Вход: после проверки пароля сохраняется сессия; токен возвращается только после успешного сохранения.
|
||||
- Выход: удаление текущей сессии; 204 выдаётся после успешного COMMIT. Следующий запрос с этим токеном получает 401.
|
||||
|
||||
Версия 1 учитывается в служебной таблице schema_migrations. Повторный запуск apply.psql пропускает её; это проверено на поднятом через Compose PostgreSQL. Подключение API и Redis будет реализовано следующими этапами.
|
||||
@@ -0,0 +1,11 @@
|
||||
Дата: 2026-10-09.
|
||||
Рабочий каталог: lab2/mtusi2026lab2
|
||||
Команда: go test ./...
|
||||
|
||||
? gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/cmd/server [no test files]
|
||||
ok gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/httpapi 1.414s
|
||||
? gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model [no test files]
|
||||
ok gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/service 0.560s
|
||||
ok gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store 0.559s
|
||||
|
||||
Это проверка перенесённой основы lab1, не проверка выполнения требований lab2.
|
||||
@@ -0,0 +1,19 @@
|
||||
Дата: 2026-10-09.
|
||||
Рабочий каталог: lab2/mtusi2026lab2.
|
||||
|
||||
> docker compose --profile tools run --rm --build dbcheck
|
||||
Container messenger-lab2-postgres-1 Running
|
||||
Building 43.9s (15/15) FINISHED
|
||||
[build 3/7] COPY go.mod go.sum ./
|
||||
[build 4/7] RUN go mod download
|
||||
[build 5/7] COPY cmd ./cmd
|
||||
[build 6/7] COPY internal ./internal
|
||||
[build 7/7] RUN go vet ./... && go test ./... && go build -trimpath -ldflags="-s -w" -o /out/server ./cmd/server
|
||||
[stage-1 1/1] COPY --from=build /out/server /server
|
||||
naming to docker.io/library/messenger-lab2-dbcheck:latest
|
||||
PASS: PostgreSQL connection, migration 000001; pool max_conns=10
|
||||
|
||||
Подтверждены сборка образа, успешное завершение go vet/test/build в сборке,
|
||||
подключение Go к PostgreSQL по TCP с паролем и чтение версии миграции 1.
|
||||
max_conns=10 сообщает настройку пула, а не число открытых соединений.
|
||||
Нагрузка на пул, таймауты при отказах и запись бизнес-данных этим запуском не проверены.
|
||||
@@ -0,0 +1,42 @@
|
||||
Дата: 2026-10-09.
|
||||
|
||||
> go test ./internal/password -count=1
|
||||
ok gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/password 1.014s
|
||||
|
||||
> go vet ./internal/password
|
||||
Без диагностических сообщений, код завершения 0.
|
||||
|
||||
Проверены: границы 12–128 Unicode code points, неверный UTF-8, двоеточие и пробелы,
|
||||
разные хеши одинакового пароля, правильный/неправильный пароль,
|
||||
128 кириллических символов без усечения, отклонение повреждённых записей и неподдерживаемых параметров.
|
||||
Регистрация и вход через HTTP пока не используют этот пакет.
|
||||
|
||||
Дата: 2026-10-09.
|
||||
|
||||
> go test ./internal/password -v -count=1
|
||||
=== RUN TestValidate
|
||||
=== RUN TestValidate/empty
|
||||
=== RUN TestValidate/11_characters
|
||||
=== RUN TestValidate/12_characters
|
||||
=== RUN TestValidate/128_Unicode_characters
|
||||
=== RUN TestValidate/129_Unicode_characters
|
||||
=== RUN TestValidate/invalid_UTF-8
|
||||
=== RUN TestValidate/spaces_preserved
|
||||
=== RUN TestValidate/colon_allowed
|
||||
--- PASS: TestValidate (0.00s)
|
||||
--- PASS: TestValidate/empty (0.00s)
|
||||
--- PASS: TestValidate/11_characters (0.00s)
|
||||
--- PASS: TestValidate/12_characters (0.00s)
|
||||
--- PASS: TestValidate/128_Unicode_characters (0.00s)
|
||||
--- PASS: TestValidate/129_Unicode_characters (0.00s)
|
||||
--- PASS: TestValidate/invalid_UTF-8 (0.00s)
|
||||
--- PASS: TestValidate/spaces_preserved (0.00s)
|
||||
--- PASS: TestValidate/colon_allowed (0.00s)
|
||||
=== RUN TestHashAndVerify
|
||||
--- PASS: TestHashAndVerify (0.35s)
|
||||
=== RUN TestLongUnicodePasswordIsNotTruncated
|
||||
--- PASS: TestLongUnicodePasswordIsNotTruncated (0.18s)
|
||||
=== RUN TestVerifyRejectsMalformedHash
|
||||
--- PASS: TestVerifyRejectsMalformedHash (0.00s)
|
||||
PASS
|
||||
ok gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/password 1.052s
|
||||
@@ -0,0 +1,22 @@
|
||||
Дата: 2026-10-09.
|
||||
|
||||
> docker compose up -d --wait api
|
||||
PostgreSQL Healthy; migrate Exited (код 0); API Healthy.
|
||||
|
||||
> py tests/resilience.py --mode persistence --action-script scripts/restart.cmd --base-url http://localhost:8080
|
||||
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
|
||||
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
|
||||
Код завершения: 0.
|
||||
Hook: restart.cmd -> restart.ps1 -> docker compose stop api postgres;
|
||||
docker compose up -d --wait postgres; docker compose up -d --wait api.
|
||||
Токены остаются только в памяти публичного теста. Повторного входа после рестарта нет.
|
||||
Подтверждённое до рестарта сообщение найдено без изменений после рестарта.
|
||||
|
||||
Область перезапуска подтверждена evidence/restart-containers.json:
|
||||
API StartedAt: 2026-10-09T14:25:24.608571748Z -> 2026-10-09T14:38:35.908723918Z.
|
||||
PostgreSQL StartedAt: 2026-10-09T12:43:41.128387304Z -> 2026-10-09T14:38:26.873986744Z.
|
||||
Идентификаторы контейнеров сохранились, процессы перезапущены.
|
||||
Volume до и после: messenger-lab2_postgres_data.
|
||||
|
||||
Это управляемый stop/start, не проверка аварийного отключения питания или потери диска.
|
||||
@@ -0,0 +1,17 @@
|
||||
Дата: 2026-10-09.
|
||||
|
||||
> docker compose up -d --build --wait api
|
||||
Сборка после устранения дублирующихся типов завершена успешно.
|
||||
В Docker выполнены go vet ./..., go test ./..., go build.
|
||||
PostgreSQL и API: Healthy.
|
||||
|
||||
> py tests/smoke.py --base-url http://localhost:8080
|
||||
PASS: lab2 public API scenario; infrastructure and grading evidence remain separate.
|
||||
|
||||
> py student-tests/chat-rollback.py
|
||||
PASS: unknown second member -> 400; no chat row remains in PostgreSQL (rollback)
|
||||
|
||||
Обе команды завершились с кодом 0. Тест rollback вставляет чат и первого
|
||||
существующего участника, затем вызывает нарушение FK неизвестным вторым участником.
|
||||
Отдельный SELECT подтверждает отсутствие чата с уникальным тестовым названием.
|
||||
Полный рестарт, EXPLAIN на 10 000 сообщениях и Redis этим запуском не проверены.
|
||||
@@ -0,0 +1,66 @@
|
||||
Дата: 2026-10-09.
|
||||
Рабочий каталог: lab2/mtusi2026lab2.
|
||||
Индикаторы прогресса Docker сокращены; результаты SQL сохранены.
|
||||
|
||||
> docker compose up -d --wait postgres
|
||||
postgres Pulled
|
||||
Network messenger-lab2_default Created
|
||||
Volume messenger-lab2_postgres_data Created
|
||||
Container messenger-lab2-postgres-1 Healthy
|
||||
|
||||
> docker compose exec -T postgres psql -X -U messenger -d messenger -f /migrations/apply.psql
|
||||
BEGIN
|
||||
SET
|
||||
SET
|
||||
pg_advisory_xact_lock
|
||||
-----------------------
|
||||
|
||||
(1 row)
|
||||
|
||||
CREATE TABLE
|
||||
CREATE TABLE
|
||||
CREATE TABLE
|
||||
CREATE TABLE
|
||||
CREATE INDEX
|
||||
CREATE TABLE
|
||||
CREATE INDEX
|
||||
CREATE TABLE
|
||||
CREATE INDEX
|
||||
INSERT 0 1
|
||||
Migration 000001 applied (commit follows).
|
||||
COMMIT
|
||||
|
||||
> docker compose exec -T postgres psql -X -U messenger -d messenger -f /migrations/apply.psql
|
||||
BEGIN
|
||||
SET
|
||||
SET
|
||||
pg_advisory_xact_lock
|
||||
-----------------------
|
||||
|
||||
(1 row)
|
||||
|
||||
CREATE TABLE
|
||||
psql:/migrations/apply.psql:13: NOTICE: relation "schema_migrations" already exists, skipping
|
||||
Migration 000001 already applied; skipping.
|
||||
COMMIT
|
||||
|
||||
> docker compose exec -T postgres psql -X -U messenger -d messenger -c '\dt'
|
||||
List of relations
|
||||
Schema | Name | Type | Owner
|
||||
--------+-------------------+-------+-----------
|
||||
public | chat_members | table | messenger
|
||||
public | chats | table | messenger
|
||||
public | messages | table | messenger
|
||||
public | schema_migrations | table | messenger
|
||||
public | sessions | table | messenger
|
||||
public | users | table | messenger
|
||||
(6 rows)
|
||||
|
||||
> docker compose exec -T postgres psql -X -U messenger -d messenger -c 'TABLE schema_migrations;'
|
||||
version | applied_at
|
||||
---------+-------------------------------
|
||||
1 | 2026-10-09 12:44:06.729345+00
|
||||
(1 row)
|
||||
|
||||
Подтверждены запуск PostgreSQL на новом volume, применение версии 1 и её пропуск при повторном запуске.
|
||||
Не проверены: сохранность бизнес-данных и сессий после рестарта, конкурентный запуск миграций, rollback при ошибке.
|
||||
@@ -0,0 +1,47 @@
|
||||
PS C:\Users\homur\Documents\4 курс\ВП\ЛР\lab2\mtusi2026lab2> docker compose up -d --build --wait api
|
||||
[+] Building 44.6s (15/15) FINISHED
|
||||
=> [internal] load local bake definitions 0.0s
|
||||
=> => reading from stdin 600B 0.0s
|
||||
=> [internal] load build definition from Dockerfile 0.0s
|
||||
=> => transferring dockerfile: 624B 0.0s
|
||||
=> [internal] load metadata for docker.io/library/golang:1.26.3 1.1s
|
||||
=> [internal] load .dockerignore 0.1s
|
||||
=> => transferring context: 216B 0.0s
|
||||
=> [build 1/7] FROM docker.io/library/golang:1.26.3@sha256:2d6c80227255c3112a4d08e67ba98e58efd3846daf15d9d7d4c389565d881b1a 0.0s
|
||||
=> => resolve docker.io/library/golang:1.26.3@sha256:2d6c80227255c3112a4d08e67ba98e58efd3846daf15d9d7d4c389565d881b1a 0.0s
|
||||
=> [internal] load build context 0.0s
|
||||
=> => transferring context: 22.01kB 0.0s
|
||||
=> CACHED [build 2/7] WORKDIR /src 0.0s
|
||||
=> [build 3/7] COPY go.mod go.sum ./ 0.1s
|
||||
=> [build 4/7] RUN go mod download 3.8s
|
||||
=> [build 5/7] COPY cmd ./cmd 0.1s
|
||||
=> [build 6/7] COPY internal ./internal 0.1s
|
||||
=> [build 7/7] RUN go vet ./... && go test ./... && go build -trimpath -ldflags="-s -w" -o /out/server ./cmd/server 36.7s
|
||||
=> [stage-1 1/1] COPY --from=build /out/server /server 0.1s
|
||||
=> exporting to image 1.1s
|
||||
=> => exporting layers 0.8s
|
||||
=> => exporting manifest sha256:52ada44195ec234c8c4c1105542024b2877b8b9af4e61167d638fc91ee55bd18 0.0s
|
||||
=> => exporting config sha256:da3ee279d1af92aeea052836bf8252722140c8d8b136c8a8c6577e88006c9e57 0.0s
|
||||
=> => exporting attestation manifest sha256:e04f959d85051c25533ff6239bb15156becb8db2c5c6133d9f9adb12b33d457c 0.0s
|
||||
=> => exporting manifest list sha256:3f6ec60e831046cc6cb6c9f5f18f23f95e10a9ab55a13fd9f5278d72c2997800 0.0s
|
||||
=> => naming to docker.io/library/messenger-lab2-api:latest 0.0s
|
||||
=> => unpacking to docker.io/library/messenger-lab2-api:latest 0.1s
|
||||
=> resolving provenance for metadata file 0.0s
|
||||
[+] Running 3/3
|
||||
✔ messenger-lab2-api Built 0.0s
|
||||
✔ Container messenger-lab2-postgres-1 Healthy 2.0s
|
||||
✔ Container messenger-lab2-api-1 Healthy 7.0s
|
||||
PS C:\Users\homur\Documents\4 курс\ВП\ЛР\lab2\mtusi2026lab2> py student-tests/registration.py
|
||||
PASS: registration 201, public User fields only
|
||||
PASS: duplicate username 409
|
||||
PASS: short and missing passwords 400
|
||||
PASS: concurrent same username -> 201 and 409
|
||||
Created username for SQL inspection: reg_4dfc9b8d0cf94e309580
|
||||
PS C:\Users\homur\Documents\4 курс\ВП\ЛР\lab2\mtusi2026lab2> docker compose exec -T postgres psql -X -U messenger -d messenger -c "SELECT username, display_name, split_part(password_hash, '$', 2) AS algorithm FROM users ORDER BY created_at DESC LIMIT 5;"
|
||||
username | display_name | algorithm
|
||||
---------------------------+----------------------+-----------
|
||||
race_8260ae16dbe24827b48c | Проверка регистрации | argon2id
|
||||
reg_4dfc9b8d0cf94e309580 | Проверка регистрации | argon2id
|
||||
(2 rows)
|
||||
|
||||
PS C:\Users\homur\Documents\4 курс\ВП\ЛР\lab2\mtusi2026lab2>
|
||||
@@ -0,0 +1,43 @@
|
||||
{
|
||||
"before": [
|
||||
{
|
||||
"service": "api",
|
||||
"id": "653f2221a86300afce4fffda471a0b74c9f2cd4e44f3c6dd4bbca033ce752052",
|
||||
"started_at": "2026-10-09T14:38:35.908723918Z",
|
||||
"status": "running",
|
||||
"data_volumes": [
|
||||
|
||||
]
|
||||
},
|
||||
{
|
||||
"service": "postgres",
|
||||
"id": "836bb4b071ea3cb8ed7b3bd1622898b3e5beb2bb28237616b4bca6e11d9cc55a",
|
||||
"started_at": "2026-10-09T14:38:26.873986744Z",
|
||||
"status": "running",
|
||||
"data_volumes": [
|
||||
"messenger-lab2_postgres_data"
|
||||
]
|
||||
}
|
||||
],
|
||||
"after": [
|
||||
{
|
||||
"service": "api",
|
||||
"id": "653f2221a86300afce4fffda471a0b74c9f2cd4e44f3c6dd4bbca033ce752052",
|
||||
"started_at": "2026-10-09T14:45:47.80312544Z",
|
||||
"status": "running",
|
||||
"data_volumes": [
|
||||
|
||||
]
|
||||
},
|
||||
{
|
||||
"service": "postgres",
|
||||
"id": "836bb4b071ea3cb8ed7b3bd1622898b3e5beb2bb28237616b4bca6e11d9cc55a",
|
||||
"started_at": "2026-10-09T14:45:40.411457464Z",
|
||||
"status": "running",
|
||||
"data_volumes": [
|
||||
"messenger-lab2_postgres_data"
|
||||
]
|
||||
}
|
||||
],
|
||||
"volumes_preserved": true
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
PS C:\Users\homur\Documents\4 курс\ВП\ЛР\lab2\mtusi2026lab2> docker compose up -d --build --wait api
|
||||
[+] Building 41.7s (15/15) FINISHED
|
||||
=> [internal] load local bake definitions 0.0s
|
||||
=> => reading from stdin 600B 0.0s
|
||||
=> [internal] load build definition from Dockerfile 0.0s
|
||||
=> => transferring dockerfile: 624B 0.0s
|
||||
=> [internal] load metadata for docker.io/library/golang:1.26.3 1.3s
|
||||
=> [internal] load .dockerignore 0.0s
|
||||
=> => transferring context: 216B 0.0s
|
||||
=> [build 1/7] FROM docker.io/library/golang:1.26.3@sha256:2d6c80227255c3112a4d08e67ba98e58efd3846daf15d9d7d4c389565d881b1a 0.0s
|
||||
=> => resolve docker.io/library/golang:1.26.3@sha256:2d6c80227255c3112a4d08e67ba98e58efd3846daf15d9d7d4c389565d881b1a 0.0s
|
||||
=> [internal] load build context 0.0s
|
||||
=> => transferring context: 21.58kB 0.0s
|
||||
=> CACHED [build 2/7] WORKDIR /src 0.0s
|
||||
=> CACHED [build 3/7] COPY go.mod go.sum ./ 0.0s
|
||||
=> CACHED [build 4/7] RUN go mod download 0.0s
|
||||
=> [build 5/7] COPY cmd ./cmd 0.1s
|
||||
=> [build 6/7] COPY internal ./internal 0.1s
|
||||
=> [build 7/7] RUN go vet ./... && go test ./... && go build -trimpath -ldflags="-s -w" -o /out/server ./cmd/server 37.8s
|
||||
=> [stage-1 1/1] COPY --from=build /out/server /server 0.1s
|
||||
=> exporting to image 1.1s
|
||||
=> => exporting layers 0.8s
|
||||
=> => exporting manifest sha256:1e81433b5c10873e67cf1e4a124294d94272b03c8eadede16eb7bceec5719199 0.0s
|
||||
=> => exporting config sha256:f14877115eb3a4ceb5e112742f113c35a4945a7c052ef0fd655f5f3169977a50 0.0s
|
||||
=> => exporting attestation manifest sha256:cd37f504d9dfcec071258d7052d9d452192bce1a21e094df7f23b11ec630f536 0.0s
|
||||
=> => exporting manifest list sha256:453e95559cf6bff46301c7d4b7c049c6f7f9e1a215715b248188b61fac3f8f44 0.0s
|
||||
=> => naming to docker.io/library/messenger-lab2-api:latest 0.0s
|
||||
=> => unpacking to docker.io/library/messenger-lab2-api:latest 0.1s
|
||||
=> resolving provenance for metadata file 0.0s
|
||||
[+] Running 3/3
|
||||
✔ messenger-lab2-api Built 0.0s
|
||||
✔ Container messenger-lab2-postgres-1 Healthy 2.4s
|
||||
✔ Container messenger-lab2-api-1 Healthy 7.3s
|
||||
PS C:\Users\homur\Documents\4 курс\ВП\ЛР\lab2\mtusi2026lab2> py student-tests/sessions.py
|
||||
PASS: wrong/missing credentials 401; login JSON body 400
|
||||
PASS: Bearer identifies user; X-User-Id and Basic give no access
|
||||
PASS: logout 204; revoked token 401; other session remains valid
|
||||
PS C:\Users\homur\Documents\4 курс\ВП\ЛР\lab2\mtusi2026lab2> $previousSessionTTL = $env:SESSION_TTL_SECONDS
|
||||
PS C:\Users\homur\Documents\4 курс\ВП\ЛР\lab2\mtusi2026lab2>
|
||||
PS C:\Users\homur\Documents\4 курс\ВП\ЛР\lab2\mtusi2026lab2> try {
|
||||
>> $env:SESSION_TTL_SECONDS = '2'
|
||||
>> docker compose up -d --wait api
|
||||
>> if ($LASTEXITCODE -ne 0) { throw 'API did not start' }
|
||||
>>
|
||||
>> py student-tests/sessions.py --expiry
|
||||
>> if ($LASTEXITCODE -ne 0) { throw 'Expiry test failed' }
|
||||
>> }
|
||||
>> finally {
|
||||
>> if ($null -eq $previousSessionTTL) {
|
||||
>> Remove-Item Env:SESSION_TTL_SECONDS -ErrorAction SilentlyContinue
|
||||
>> } else {
|
||||
>> $env:SESSION_TTL_SECONDS = $previousSessionTTL
|
||||
>> }
|
||||
>>
|
||||
>> docker compose up -d --wait api
|
||||
>> }
|
||||
[+] Running 2/2
|
||||
✔ Container messenger-lab2-postgres-1 Healthy 2.7s
|
||||
✔ Container messenger-lab2-api-1 Healthy 7.7s
|
||||
PASS: wrong/missing credentials 401; login JSON body 400
|
||||
PASS: short TTL session works before expiry and returns 401 after expiry
|
||||
[+] Running 2/2
|
||||
✔ Container messenger-lab2-postgres-1 Healthy 2.5s
|
||||
✔ Container messenger-lab2-api-1 Healthy 7.5s
|
||||
PS C:\Users\homur\Documents\4 курс\ВП\ЛР\lab2\mtusi2026lab2>
|
||||
@@ -0,0 +1,17 @@
|
||||
module gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork
|
||||
|
||||
go 1.26.3
|
||||
|
||||
require (
|
||||
github.com/jackc/pgx/v5 v5.7.6
|
||||
golang.org/x/crypto v0.37.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.13.0 // indirect
|
||||
golang.org/x/sys v0.32.0 // indirect
|
||||
golang.org/x/text v0.24.0 // indirect
|
||||
)
|
||||
@@ -0,0 +1,30 @@
|
||||
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/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||
github.com/jackc/pgx/v5 v5.7.6 h1:rWQc5FwZSPX58r1OQmkuaNicxdmExaEz5A2DO2hUuTk=
|
||||
github.com/jackc/pgx/v5 v5.7.6/go.mod h1:aruU7o91Tc2q2cFp5h4uP3f6ztExVpyVv88Xl/8Vl8M=
|
||||
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/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.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
|
||||
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
golang.org/x/crypto v0.37.0 h1:kJNSjF/Xp7kU0iB2Z+9viTPMW4EqqsrywMXLJOOsXSE=
|
||||
golang.org/x/crypto v0.37.0/go.mod h1:vg+k43peMZ0pUMhYmVAWysMK35e6ioLh3wB8ZCAfbVc=
|
||||
golang.org/x/sync v0.13.0 h1:AauUjRAJ9OSnvULf/ARrrVywoJDy0YS2AwQ98I37610=
|
||||
golang.org/x/sync v0.13.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
|
||||
golang.org/x/sys v0.32.0 h1:s77OFDvIQeibCmezSnk/q6iAfkdiQaJi4VzroCFrN20=
|
||||
golang.org/x/sys v0.32.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
||||
golang.org/x/text v0.24.0 h1:dd5Bzh4yt5KYA8f9CJHCP4FB4D51c2c6JvN37xJJkJ0=
|
||||
golang.org/x/text v0.24.0/go.mod h1:L8rBsPeo2pSS+xqN0d5u2ikmjtmoJbDBT1b7nHvFCdU=
|
||||
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,27 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model"
|
||||
)
|
||||
|
||||
type userContextKey struct{}
|
||||
|
||||
func (api *API) authenticate(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
user, err := api.messenger.CurrentUser(r.Header.Get("X-User-Id"))
|
||||
if err != nil {
|
||||
writeAppError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
ctx := context.WithValue(r.Context(), userContextKey{}, user)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
func userFromContext(ctx context.Context) model.User {
|
||||
return ctx.Value(userContextKey{}).(model.User)
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/service"
|
||||
)
|
||||
|
||||
type createChatRequest struct {
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
}
|
||||
|
||||
type createMessageRequest struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
func (api *API) chatRoutes(w http.ResponseWriter, r *http.Request) {
|
||||
actor := userFromContext(r.Context())
|
||||
|
||||
if r.URL.Path == "/api/v1/chats" {
|
||||
switch r.Method {
|
||||
case http.MethodPost:
|
||||
var body createChatRequest
|
||||
if !readJSON(w, r, &body, "title", "member_ids") {
|
||||
return
|
||||
}
|
||||
|
||||
chat, err := api.messenger.CreateChat(
|
||||
actor.ID, body.Title, body.MemberIDs,
|
||||
)
|
||||
if err != nil {
|
||||
writeAppError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusCreated, chat)
|
||||
|
||||
case http.MethodGet:
|
||||
limit, cursor, ok := pageParams(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
page, err := api.messenger.ListChats(actor.ID, limit, cursor)
|
||||
if err != nil {
|
||||
writeAppError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, page)
|
||||
|
||||
default:
|
||||
requireMethod(w, r, "GET, POST")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
path := strings.TrimPrefix(r.URL.Path, "/api/v1/chats/")
|
||||
parts := strings.Split(path, "/")
|
||||
|
||||
if len(parts) == 1 && parts[0] != "" {
|
||||
if !requireMethod(w, r, http.MethodGet) {
|
||||
return
|
||||
}
|
||||
|
||||
chat, err := api.messenger.GetChat(actor.ID, parts[0])
|
||||
if err != nil {
|
||||
writeAppError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, chat)
|
||||
return
|
||||
}
|
||||
|
||||
if len(parts) != 2 || parts[0] == "" || parts[1] != "messages" {
|
||||
writeError(w, http.StatusNotFound, "not_found", "Resource not found")
|
||||
return
|
||||
}
|
||||
|
||||
chat, err := api.messenger.GetChat(actor.ID, parts[0])
|
||||
if err != nil {
|
||||
writeAppError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
switch r.Method {
|
||||
case http.MethodPost:
|
||||
var body createMessageRequest
|
||||
if !readJSON(w, r, &body, "text") {
|
||||
return
|
||||
}
|
||||
|
||||
message, err := api.messenger.CreateMessage(
|
||||
actor.ID, chat.ID, body.Text,
|
||||
)
|
||||
if err != nil {
|
||||
writeAppError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusCreated, message)
|
||||
|
||||
case http.MethodGet:
|
||||
limit, cursor, ok := pageParams(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
page, err := api.messenger.ListMessages(
|
||||
actor.ID, chat.ID, limit, cursor,
|
||||
)
|
||||
if err != nil {
|
||||
writeAppError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, page)
|
||||
|
||||
default:
|
||||
requireMethod(w, r, "GET, POST")
|
||||
}
|
||||
}
|
||||
|
||||
func pageParams(
|
||||
w http.ResponseWriter,
|
||||
r *http.Request,
|
||||
) (int, string, bool) {
|
||||
invalid := func() (int, string, bool) {
|
||||
writeAppError(w, service.ErrInvalidRequest)
|
||||
return 0, "", false
|
||||
}
|
||||
|
||||
query := r.URL.Query()
|
||||
limit := 50
|
||||
|
||||
if values, exists := query["limit"]; exists {
|
||||
if len(values) != 1 || values[0] == "" {
|
||||
return invalid()
|
||||
}
|
||||
|
||||
for _, char := range values[0] {
|
||||
if char < '0' || char > '9' {
|
||||
return invalid()
|
||||
}
|
||||
}
|
||||
|
||||
value, err := strconv.Atoi(values[0])
|
||||
if err != nil || value < 1 || value > 100 {
|
||||
return invalid()
|
||||
}
|
||||
|
||||
limit = value
|
||||
}
|
||||
|
||||
cursor := ""
|
||||
|
||||
if values, exists := query["cursor"]; exists {
|
||||
if len(values) != 1 || values[0] == "" {
|
||||
return invalid()
|
||||
}
|
||||
cursor = values[0]
|
||||
}
|
||||
|
||||
return limit, cursor, true
|
||||
}
|
||||
@@ -0,0 +1,502 @@
|
||||
package httpapi_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model"
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/service"
|
||||
)
|
||||
|
||||
type chatTestClient struct {
|
||||
base string
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
func newChatTestClient(t *testing.T) *chatTestClient {
|
||||
t.Helper()
|
||||
|
||||
server := httptest.NewServer(newAPI())
|
||||
t.Cleanup(server.Close)
|
||||
|
||||
client := server.Client()
|
||||
client.Timeout = 10 * time.Second
|
||||
|
||||
return &chatTestClient{
|
||||
base: server.URL,
|
||||
client: client,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *chatTestClient) call(
|
||||
method string,
|
||||
path string,
|
||||
actorID string,
|
||||
body any,
|
||||
wantStatus int,
|
||||
result any,
|
||||
) error {
|
||||
var encoded []byte
|
||||
var err error
|
||||
|
||||
if body != nil {
|
||||
encoded, err = json.Marshal(body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
req, err := http.NewRequest(
|
||||
method,
|
||||
c.base+path,
|
||||
bytes.NewReader(encoded),
|
||||
)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if body != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
if actorID != "" {
|
||||
req.Header.Set("X-User-Id", actorID)
|
||||
}
|
||||
|
||||
response, err := c.client.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
data, err := io.ReadAll(response.Body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if response.StatusCode != wantStatus {
|
||||
return fmt.Errorf(
|
||||
"%s %s: status=%d, want=%d, body=%s",
|
||||
method, path, response.StatusCode, wantStatus, data,
|
||||
)
|
||||
}
|
||||
|
||||
requestID := response.Header.Get("X-Request-Id")
|
||||
if requestID == "" {
|
||||
return fmt.Errorf("%s %s: missing request ID", method, path)
|
||||
}
|
||||
|
||||
if wantStatus >= 400 {
|
||||
var problem struct {
|
||||
Error struct {
|
||||
Code string `json:"code"`
|
||||
RequestID string `json:"request_id"`
|
||||
} `json:"error"`
|
||||
}
|
||||
|
||||
if err := json.Unmarshal(data, &problem); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if problem.Error.Code == "" ||
|
||||
problem.Error.RequestID != requestID {
|
||||
return fmt.Errorf("invalid error response: %s", data)
|
||||
}
|
||||
}
|
||||
|
||||
if result != nil {
|
||||
return json.Unmarshal(data, result)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func mustCall(
|
||||
t *testing.T,
|
||||
c *chatTestClient,
|
||||
method string,
|
||||
path string,
|
||||
actorID string,
|
||||
body any,
|
||||
status int,
|
||||
result any,
|
||||
) {
|
||||
t.Helper()
|
||||
|
||||
if err := c.call(method, path, actorID, body, status, result); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func createTestUser(
|
||||
t *testing.T,
|
||||
c *chatTestClient,
|
||||
username string,
|
||||
) model.User {
|
||||
t.Helper()
|
||||
|
||||
var user model.User
|
||||
mustCall(
|
||||
t, c, http.MethodPost, "/api/v1/users", "",
|
||||
map[string]any{
|
||||
"username": username,
|
||||
"display_name": username,
|
||||
},
|
||||
http.StatusCreated, &user,
|
||||
)
|
||||
|
||||
return user
|
||||
}
|
||||
|
||||
func createTestChat(
|
||||
t *testing.T,
|
||||
c *chatTestClient,
|
||||
actorID string,
|
||||
members []string,
|
||||
) model.Chat {
|
||||
t.Helper()
|
||||
|
||||
var chat model.Chat
|
||||
mustCall(
|
||||
t, c, http.MethodPost, "/api/v1/chats", actorID,
|
||||
map[string]any{
|
||||
"title": "Test chat",
|
||||
"member_ids": members,
|
||||
},
|
||||
http.StatusCreated, &chat,
|
||||
)
|
||||
|
||||
return chat
|
||||
}
|
||||
|
||||
func readAllMessages(
|
||||
t *testing.T,
|
||||
c *chatTestClient,
|
||||
actorID string,
|
||||
chatID string,
|
||||
limit int,
|
||||
) ([]model.Message, int) {
|
||||
t.Helper()
|
||||
|
||||
var messages []model.Message
|
||||
cursor := ""
|
||||
pages := 0
|
||||
seenCursors := make(map[string]bool)
|
||||
|
||||
for {
|
||||
path := fmt.Sprintf(
|
||||
"/api/v1/chats/%s/messages?limit=%d",
|
||||
chatID, limit,
|
||||
)
|
||||
|
||||
if cursor != "" {
|
||||
path += "&cursor=" + url.QueryEscape(cursor)
|
||||
}
|
||||
|
||||
var page service.Page[model.Message]
|
||||
mustCall(
|
||||
t, c, http.MethodGet, path, actorID,
|
||||
nil, http.StatusOK, &page,
|
||||
)
|
||||
|
||||
pages++
|
||||
|
||||
if page.Items == nil {
|
||||
t.Fatal("items must be an array, not null")
|
||||
}
|
||||
if len(page.Items) > limit {
|
||||
t.Fatal("page exceeds requested limit")
|
||||
}
|
||||
|
||||
messages = append(messages, page.Items...)
|
||||
|
||||
if page.NextCursor == nil {
|
||||
break
|
||||
}
|
||||
|
||||
cursor = *page.NextCursor
|
||||
if cursor == "" || seenCursors[cursor] || pages > 100 {
|
||||
t.Fatal("invalid or repeating pagination cursor")
|
||||
}
|
||||
seenCursors[cursor] = true
|
||||
}
|
||||
|
||||
return messages, pages
|
||||
}
|
||||
|
||||
func TestChatAccessAndValidation(t *testing.T) {
|
||||
c := newChatTestClient(t)
|
||||
|
||||
alice := createTestUser(t, c, "alice")
|
||||
bob := createTestUser(t, c, "bob")
|
||||
eve := createTestUser(t, c, "eve")
|
||||
|
||||
chat := createTestChat(
|
||||
t, c, alice.ID, []string{alice.ID, bob.ID},
|
||||
)
|
||||
path := "/api/v1/chats/" + chat.ID
|
||||
|
||||
mustCall(
|
||||
t, c, http.MethodGet, path, eve.ID,
|
||||
nil, http.StatusNotFound, nil,
|
||||
)
|
||||
mustCall(
|
||||
t, c, http.MethodGet, path+"/messages", eve.ID,
|
||||
nil, http.StatusNotFound, nil,
|
||||
)
|
||||
mustCall(
|
||||
t, c, http.MethodPost, path+"/messages", eve.ID,
|
||||
map[string]any{"text": "not allowed"},
|
||||
http.StatusNotFound, nil,
|
||||
)
|
||||
|
||||
var hidden service.Page[model.Chat]
|
||||
mustCall(
|
||||
t, c, http.MethodGet, "/api/v1/chats", eve.ID,
|
||||
nil, http.StatusOK, &hidden,
|
||||
)
|
||||
if len(hidden.Items) != 0 {
|
||||
t.Fatal("outsider sees a private chat")
|
||||
}
|
||||
|
||||
for _, text := range []string{"", " \t\n"} {
|
||||
mustCall(
|
||||
t, c, http.MethodPost, path+"/messages", alice.ID,
|
||||
map[string]any{"text": text},
|
||||
http.StatusBadRequest, nil,
|
||||
)
|
||||
}
|
||||
|
||||
mustCall(
|
||||
t, c, http.MethodPost, path+"/messages", alice.ID,
|
||||
map[string]any{
|
||||
"text": "hello",
|
||||
"sender_id": bob.ID,
|
||||
},
|
||||
http.StatusBadRequest, nil,
|
||||
)
|
||||
|
||||
for _, members := range [][]string{
|
||||
{alice.ID, alice.ID},
|
||||
{bob.ID},
|
||||
{alice.ID, "00000000-0000-4000-8000-000000000000"},
|
||||
} {
|
||||
mustCall(
|
||||
t, c, http.MethodPost, "/api/v1/chats", alice.ID,
|
||||
map[string]any{
|
||||
"title": "Invalid chat",
|
||||
"member_ids": members,
|
||||
},
|
||||
http.StatusBadRequest, nil,
|
||||
)
|
||||
}
|
||||
|
||||
var chats service.Page[model.Chat]
|
||||
mustCall(
|
||||
t, c, http.MethodGet, "/api/v1/chats", alice.ID,
|
||||
nil, http.StatusOK, &chats,
|
||||
)
|
||||
if len(chats.Items) != 1 {
|
||||
t.Fatalf("expected one chat, got %d", len(chats.Items))
|
||||
}
|
||||
|
||||
messages, _ := readAllMessages(t, c, alice.ID, chat.ID, 10)
|
||||
if len(messages) != 0 {
|
||||
t.Fatal("rejected messages were saved")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessagePagination(t *testing.T) {
|
||||
c := newChatTestClient(t)
|
||||
alice := createTestUser(t, c, "alice")
|
||||
|
||||
chat := createTestChat(t, c, alice.ID, []string{alice.ID})
|
||||
other := createTestChat(t, c, alice.ID, []string{alice.ID})
|
||||
path := "/api/v1/chats/" + chat.ID + "/messages"
|
||||
|
||||
var sent []model.Message
|
||||
|
||||
for i := 0; i < 7; i++ {
|
||||
var message model.Message
|
||||
mustCall(
|
||||
t, c, http.MethodPost, path, alice.ID,
|
||||
map[string]any{"text": fmt.Sprintf("Сообщение %d 👋", i)},
|
||||
http.StatusCreated, &message,
|
||||
)
|
||||
sent = append(sent, message)
|
||||
}
|
||||
|
||||
got, pages := readAllMessages(t, c, alice.ID, chat.ID, 2)
|
||||
|
||||
if len(got) != len(sent) || pages != 4 {
|
||||
t.Fatalf("got %d messages on %d pages", len(got), pages)
|
||||
}
|
||||
|
||||
for i := range sent {
|
||||
if got[i] != sent[i] {
|
||||
t.Fatalf("message %d differs or is out of order", i)
|
||||
}
|
||||
}
|
||||
|
||||
var first service.Page[model.Message]
|
||||
mustCall(
|
||||
t, c, http.MethodGet, path+"?limit=2", alice.ID,
|
||||
nil, http.StatusOK, &first,
|
||||
)
|
||||
|
||||
if first.NextCursor == nil {
|
||||
t.Fatal("expected next cursor")
|
||||
}
|
||||
|
||||
cursor := url.QueryEscape(*first.NextCursor)
|
||||
|
||||
var next service.Page[model.Message]
|
||||
mustCall(
|
||||
t, c, http.MethodGet,
|
||||
path+"?limit=3&cursor="+cursor, alice.ID,
|
||||
nil, http.StatusOK, &next,
|
||||
)
|
||||
|
||||
if len(next.Items) != 3 || next.Items[0].ID != sent[2].ID {
|
||||
t.Fatal("changing page size lost or repeated a message")
|
||||
}
|
||||
|
||||
mustCall(
|
||||
t, c, http.MethodGet,
|
||||
"/api/v1/chats/"+other.ID+"/messages?cursor="+cursor,
|
||||
alice.ID, nil, http.StatusBadRequest, nil,
|
||||
)
|
||||
|
||||
for _, query := range []string{
|
||||
"limit=0",
|
||||
"limit=101",
|
||||
"limit=abc",
|
||||
"cursor=invalid",
|
||||
} {
|
||||
mustCall(
|
||||
t, c, http.MethodGet, path+"?"+query, alice.ID,
|
||||
nil, http.StatusBadRequest, nil,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConcurrentMessages100From10Clients(t *testing.T) {
|
||||
c := newChatTestClient(t)
|
||||
|
||||
const clients = 10
|
||||
const messagesPerClient = 10
|
||||
const total = clients * messagesPerClient
|
||||
|
||||
users := make([]model.User, clients)
|
||||
memberIDs := make([]string, clients)
|
||||
|
||||
for i := range users {
|
||||
users[i] = createTestUser(t, c, fmt.Sprintf("user_%02d", i))
|
||||
memberIDs[i] = users[i].ID
|
||||
}
|
||||
|
||||
chat := createTestChat(t, c, users[0].ID, memberIDs)
|
||||
path := "/api/v1/chats/" + chat.ID + "/messages"
|
||||
|
||||
type outcome struct {
|
||||
message model.Message
|
||||
err error
|
||||
}
|
||||
|
||||
results := make(chan outcome, total)
|
||||
start := make(chan struct{})
|
||||
var wg sync.WaitGroup
|
||||
|
||||
for clientIndex := 0; clientIndex < clients; clientIndex++ {
|
||||
wg.Add(1)
|
||||
|
||||
go func(index int) {
|
||||
defer wg.Done()
|
||||
<-start
|
||||
|
||||
for j := 0; j < messagesPerClient; j++ {
|
||||
text := fmt.Sprintf("client-%d-message-%d", index, j)
|
||||
var message model.Message
|
||||
|
||||
err := c.call(
|
||||
http.MethodPost,
|
||||
path,
|
||||
users[index].ID,
|
||||
map[string]any{"text": text},
|
||||
http.StatusCreated,
|
||||
&message,
|
||||
)
|
||||
|
||||
if err == nil &&
|
||||
(message.SenderID != users[index].ID ||
|
||||
message.Text != text ||
|
||||
message.ChatID != chat.ID) {
|
||||
err = fmt.Errorf("incorrect message response")
|
||||
}
|
||||
|
||||
results <- outcome{message: message, err: err}
|
||||
}
|
||||
}(clientIndex)
|
||||
}
|
||||
|
||||
close(start)
|
||||
wg.Wait()
|
||||
close(results)
|
||||
|
||||
expected := make(map[string]model.Message, total)
|
||||
|
||||
for result := range results {
|
||||
if result.err != nil {
|
||||
t.Errorf("send failed: %v", result.err)
|
||||
continue
|
||||
}
|
||||
|
||||
if _, exists := expected[result.message.ID]; exists {
|
||||
t.Errorf("duplicate response ID: %s", result.message.ID)
|
||||
}
|
||||
|
||||
expected[result.message.ID] = result.message
|
||||
}
|
||||
|
||||
if t.Failed() {
|
||||
t.FailNow()
|
||||
}
|
||||
|
||||
if len(expected) != total {
|
||||
t.Fatalf("expected %d unique responses, got %d", total, len(expected))
|
||||
}
|
||||
|
||||
history, pages := readAllMessages(
|
||||
t, c, users[0].ID, chat.ID, 17,
|
||||
)
|
||||
|
||||
if len(history) != total {
|
||||
t.Fatalf("expected %d stored messages, got %d", total, len(history))
|
||||
}
|
||||
|
||||
seen := make(map[string]bool, total)
|
||||
|
||||
for _, message := range history {
|
||||
if seen[message.ID] {
|
||||
t.Fatalf("duplicate history ID: %s", message.ID)
|
||||
}
|
||||
seen[message.ID] = true
|
||||
|
||||
want, exists := expected[message.ID]
|
||||
if !exists || want != message {
|
||||
t.Fatalf("missing or changed message: %s", message.ID)
|
||||
}
|
||||
}
|
||||
|
||||
t.Logf(
|
||||
"clients=%d sent=%d unique_responses=%d stored=%d unique_stored=%d pages=%d",
|
||||
clients, total, len(expected), len(history), len(seen), pages,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/service"
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store"
|
||||
)
|
||||
|
||||
type errorResponse struct {
|
||||
Error errorDetails `json:"error"`
|
||||
}
|
||||
|
||||
type errorDetails struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
|
||||
func writeAppError(w http.ResponseWriter, err error) {
|
||||
switch {
|
||||
case errors.Is(err, store.ErrUnavailable):
|
||||
writeError(w, http.StatusServiceUnavailable, "unavailable", "Service temporarily unavailable")
|
||||
|
||||
case errors.Is(err, service.ErrInvalidRequest):
|
||||
writeError(
|
||||
w, http.StatusBadRequest,
|
||||
"invalid_request", "Invalid request fields",
|
||||
)
|
||||
|
||||
case errors.Is(err, service.ErrUnauthorized):
|
||||
writeError(
|
||||
w, http.StatusUnauthorized,
|
||||
"unauthorized", "Valid X-User-Id is required",
|
||||
)
|
||||
|
||||
case errors.Is(err, store.ErrUsernameTaken):
|
||||
writeError(
|
||||
w, http.StatusConflict,
|
||||
"conflict", "Username already exists",
|
||||
)
|
||||
|
||||
case errors.Is(err, store.ErrInvalidMembers):
|
||||
writeError(
|
||||
w, http.StatusBadRequest,
|
||||
"invalid_request", "Invalid chat members",
|
||||
)
|
||||
|
||||
case errors.Is(err, store.ErrNotFound):
|
||||
writeError(
|
||||
w, http.StatusNotFound,
|
||||
"not_found", "Resource not found",
|
||||
)
|
||||
|
||||
default:
|
||||
log.Printf(
|
||||
"internal error request_id=%s: %v",
|
||||
w.Header().Get("X-Request-Id"),
|
||||
err,
|
||||
)
|
||||
|
||||
writeError(
|
||||
w, http.StatusInternalServerError,
|
||||
"internal_error", "Internal server error",
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func writeError(
|
||||
w http.ResponseWriter,
|
||||
status int,
|
||||
code string,
|
||||
message string,
|
||||
) {
|
||||
writeJSON(w, status, errorResponse{
|
||||
Error: errorDetails{
|
||||
Code: code,
|
||||
Message: message,
|
||||
RequestID: w.Header().Get("X-Request-Id"),
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package httpapi
|
||||
|
||||
import "net/http"
|
||||
|
||||
func handleHealth(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
w.Header().Set("Allow", http.MethodGet)
|
||||
|
||||
writeError(
|
||||
w,
|
||||
http.StatusMethodNotAllowed,
|
||||
"invalid_request",
|
||||
"Method not allowed",
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, struct {
|
||||
Status string `json:"status"`
|
||||
}{
|
||||
Status: "ok",
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"log"
|
||||
"mime"
|
||||
"net/http"
|
||||
"slices"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
const maxJSONBody = 1 << 20 // 1 MiB
|
||||
|
||||
func readJSON(
|
||||
w http.ResponseWriter,
|
||||
r *http.Request,
|
||||
dst any,
|
||||
requiredFields ...string,
|
||||
) bool {
|
||||
mediaType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
if err != nil || mediaType != "application/json" {
|
||||
writeError(
|
||||
w,
|
||||
http.StatusUnsupportedMediaType,
|
||||
"unsupported_media_type",
|
||||
"Content-Type must be application/json",
|
||||
)
|
||||
return false
|
||||
}
|
||||
|
||||
defer r.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(io.LimitReader(r.Body, maxJSONBody+1))
|
||||
if err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid_request", "Cannot read body")
|
||||
return false
|
||||
}
|
||||
|
||||
if len(body) > maxJSONBody {
|
||||
writeError(
|
||||
w,
|
||||
http.StatusRequestEntityTooLarge,
|
||||
"payload_too_large",
|
||||
"JSON body is too large",
|
||||
)
|
||||
return false
|
||||
}
|
||||
|
||||
invalid := func() bool {
|
||||
writeError(
|
||||
w,
|
||||
http.StatusBadRequest,
|
||||
"invalid_request",
|
||||
"Invalid JSON body",
|
||||
)
|
||||
return false
|
||||
}
|
||||
|
||||
if !utf8.Valid(body) {
|
||||
return invalid()
|
||||
}
|
||||
|
||||
var fields map[string]json.RawMessage
|
||||
if err := json.Unmarshal(body, &fields); err != nil || fields == nil {
|
||||
return invalid()
|
||||
}
|
||||
|
||||
for name := range fields {
|
||||
if !slices.Contains(requiredFields, name) {
|
||||
return invalid()
|
||||
}
|
||||
}
|
||||
|
||||
for _, name := range requiredFields {
|
||||
value, exists := fields[name]
|
||||
if !exists || bytes.Equal(bytes.TrimSpace(value), []byte("null")) {
|
||||
return invalid()
|
||||
}
|
||||
}
|
||||
|
||||
decoder := json.NewDecoder(bytes.NewReader(body))
|
||||
decoder.DisallowUnknownFields()
|
||||
|
||||
if err := decoder.Decode(dst); err != nil {
|
||||
return invalid()
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, body any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
|
||||
if err := json.NewEncoder(w).Encode(body); err != nil {
|
||||
log.Printf("cannot write JSON response: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package httpapi_test
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model"
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/service"
|
||||
)
|
||||
|
||||
func TestJSONFieldNamesAreCaseSensitive(t *testing.T) {
|
||||
handler := newAPI()
|
||||
|
||||
t.Run("registration", func(t *testing.T) {
|
||||
for _, body := range []string{
|
||||
`{"username":"alice","display_name":"Original","Display_Name":"Changed"}`,
|
||||
`{"Display_Name":"Changed","username":"alice","display_name":"Original"}`,
|
||||
`{"username":"alice","display_name":"Original","Username":"bob"}`,
|
||||
`{"username":"alice","Display_Name":"Changed"}`,
|
||||
} {
|
||||
checkError(t, request(handler, http.MethodPost, "/api/v1/users", body, ""),
|
||||
http.StatusBadRequest, "invalid_request")
|
||||
}
|
||||
})
|
||||
|
||||
created := request(handler, http.MethodPost, "/api/v1/users",
|
||||
`{"username":"alice","display_name":"Original"}`, "")
|
||||
if created.Code != http.StatusCreated {
|
||||
t.Fatalf("valid registration: %d %s", created.Code, created.Body.String())
|
||||
}
|
||||
var user model.User
|
||||
if err := json.Unmarshal(created.Body.Bytes(), &user); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if user.DisplayName != "Original" {
|
||||
t.Fatalf("display name changed: %q", user.DisplayName)
|
||||
}
|
||||
|
||||
t.Run("chat", func(t *testing.T) {
|
||||
for _, body := range []string{
|
||||
fmt.Sprintf(`{"title":"Original","Title":"Changed","member_ids":[%q]}`, user.ID),
|
||||
fmt.Sprintf(`{"Title":"Changed","title":"Original","member_ids":[%q]}`, user.ID),
|
||||
fmt.Sprintf(`{"title":"Original","member_ids":[%q],"Member_Ids":[]}`, user.ID),
|
||||
fmt.Sprintf(`{"Title":"Changed","member_ids":[%q]}`, user.ID),
|
||||
} {
|
||||
checkError(t, request(handler, http.MethodPost, "/api/v1/chats", body, user.ID),
|
||||
http.StatusBadRequest, "invalid_request")
|
||||
}
|
||||
response := request(handler, http.MethodGet, "/api/v1/chats", "", user.ID)
|
||||
var page service.Page[model.Chat]
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &page); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if response.Code != http.StatusOK || len(page.Items) != 0 {
|
||||
t.Fatalf("rejected chats were saved: %d %s", response.Code, response.Body.String())
|
||||
}
|
||||
})
|
||||
|
||||
created = request(handler, http.MethodPost, "/api/v1/chats",
|
||||
fmt.Sprintf(`{"title":"Original","member_ids":[%q]}`, user.ID), user.ID)
|
||||
if created.Code != http.StatusCreated {
|
||||
t.Fatalf("valid chat: %d %s", created.Code, created.Body.String())
|
||||
}
|
||||
var chat model.Chat
|
||||
if err := json.Unmarshal(created.Body.Bytes(), &chat); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
path := "/api/v1/chats/" + chat.ID + "/messages"
|
||||
|
||||
t.Run("message", func(t *testing.T) {
|
||||
for _, body := range []string{
|
||||
`{"text":"Original","Text":"Changed"}`,
|
||||
`{"Text":"Changed","text":"Original"}`,
|
||||
`{"text":"Original","TEXT":"Changed"}`,
|
||||
`{"Text":"Changed"}`,
|
||||
} {
|
||||
checkError(t, request(handler, http.MethodPost, path, body, user.ID),
|
||||
http.StatusBadRequest, "invalid_request")
|
||||
}
|
||||
response := request(handler, http.MethodGet, path, "", user.ID)
|
||||
var page service.Page[model.Message]
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &page); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if response.Code != http.StatusOK || len(page.Items) != 0 {
|
||||
t.Fatalf("rejected messages were saved: %d %s", response.Code, response.Body.String())
|
||||
}
|
||||
response = request(handler, http.MethodPost, path, `{"text":"Original"}`, user.ID)
|
||||
var message model.Message
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &message); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if response.Code != http.StatusCreated || message.Text != "Original" {
|
||||
t.Fatalf("valid message: %d %s", response.Code, response.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
func withRequestID(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
var randomBytes [16]byte
|
||||
|
||||
if _, err := rand.Read(randomBytes[:]); err != nil {
|
||||
panic("cannot generate request ID")
|
||||
}
|
||||
|
||||
requestID := hex.EncodeToString(randomBytes[:])
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
type statusWriter struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
}
|
||||
|
||||
func (w *statusWriter) WriteHeader(status int) {
|
||||
if w.status != 0 {
|
||||
return
|
||||
}
|
||||
|
||||
w.status = status
|
||||
w.ResponseWriter.WriteHeader(status)
|
||||
}
|
||||
|
||||
func (w *statusWriter) Write(body []byte) (int, error) {
|
||||
if w.status == 0 {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
|
||||
return w.ResponseWriter.Write(body)
|
||||
}
|
||||
|
||||
func (w *statusWriter) Unwrap() http.ResponseWriter {
|
||||
return w.ResponseWriter
|
||||
}
|
||||
|
||||
func withAccessLog(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
started := time.Now()
|
||||
writer := &statusWriter{ResponseWriter: w}
|
||||
|
||||
defer func() {
|
||||
if recovered := recover(); recovered != nil {
|
||||
log.Printf(
|
||||
"handler panic request_id=%s",
|
||||
writer.Header().Get("X-Request-Id"),
|
||||
)
|
||||
|
||||
if writer.status == 0 {
|
||||
writeError(
|
||||
writer,
|
||||
http.StatusInternalServerError,
|
||||
"internal_error",
|
||||
"Internal server error",
|
||||
)
|
||||
} else {
|
||||
panic(http.ErrAbortHandler)
|
||||
}
|
||||
}
|
||||
|
||||
status := writer.status
|
||||
if status == 0 {
|
||||
status = http.StatusOK
|
||||
}
|
||||
|
||||
log.Printf(
|
||||
"request_id=%s method=%s path=%q status=%d duration_ms=%d",
|
||||
writer.Header().Get("X-Request-Id"),
|
||||
r.Method,
|
||||
r.URL.Path,
|
||||
status,
|
||||
time.Since(started).Milliseconds(),
|
||||
)
|
||||
}()
|
||||
|
||||
next.ServeHTTP(writer, r)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/service"
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store"
|
||||
)
|
||||
|
||||
func NewPostgresHandler(db *store.PostgresStore, stopping *atomic.Bool, ttl int64) (http.Handler, error) {
|
||||
registration := service.NewRegistration(db)
|
||||
sessions, err := service.NewSessions(db, registration, ttl)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
chats := &persistentAPI{messenger: service.NewPersistentMessenger(db)}
|
||||
return withRequestID(withAccessLog(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if stopping.Load() && r.URL.Path != "/health/live" {
|
||||
writeAppError(w, store.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
if r.URL.Path == "/api/v1/chats" || strings.HasPrefix(r.URL.Path, "/api/v1/chats/") {
|
||||
token, err := bearerToken(r)
|
||||
if err != nil {
|
||||
sessionError(w, err, false)
|
||||
return
|
||||
}
|
||||
user, err := sessions.CurrentUser(r.Context(), token)
|
||||
if err != nil {
|
||||
sessionError(w, err, false)
|
||||
return
|
||||
}
|
||||
ctx := context.WithValue(r.Context(), userContextKey{}, user)
|
||||
chats.chatRoutes(w, r.WithContext(ctx))
|
||||
return
|
||||
}
|
||||
switch r.URL.Path {
|
||||
case "/api/v1/auth/sessions":
|
||||
loginSession(w, r, sessions)
|
||||
case "/api/v1/auth/sessions/current":
|
||||
currentSession(w, r, sessions, true)
|
||||
case "/api/v1/users/me":
|
||||
currentSession(w, r, sessions, false)
|
||||
case "/health/live":
|
||||
handleHealth(w, r)
|
||||
case "/health/ready":
|
||||
if !requireMethod(w, r, http.MethodGet) {
|
||||
return
|
||||
}
|
||||
if err := db.Ping(r.Context()); err != nil {
|
||||
writeAppError(w, err)
|
||||
return
|
||||
}
|
||||
handleHealth(w, r)
|
||||
case "/api/v1/users":
|
||||
if !requireMethod(w, r, http.MethodPost) {
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if !readJSON(w, r, &body, "username", "display_name", "password") {
|
||||
return
|
||||
}
|
||||
user, err := registration.Register(r.Context(), body.Username, body.DisplayName, body.Password)
|
||||
if err != nil {
|
||||
writeAppError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, user)
|
||||
default:
|
||||
writeError(w, http.StatusNotFound, "not_found", "Resource not found")
|
||||
}
|
||||
}))), nil
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"strings"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/service"
|
||||
)
|
||||
|
||||
type persistentAPI struct{ messenger *service.PersistentMessenger }
|
||||
|
||||
func (api *persistentAPI) chatRoutes(w http.ResponseWriter, r *http.Request) {
|
||||
actor := userFromContext(r.Context())
|
||||
|
||||
if r.URL.Path == "/api/v1/chats" {
|
||||
switch r.Method {
|
||||
case http.MethodPost:
|
||||
var body createChatRequest
|
||||
if !readJSON(w, r, &body, "title", "member_ids") {
|
||||
return
|
||||
}
|
||||
|
||||
chat, err := api.messenger.CreateChat(r.Context(),
|
||||
actor.ID, body.Title, body.MemberIDs,
|
||||
)
|
||||
if err != nil {
|
||||
writeAppError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusCreated, chat)
|
||||
|
||||
case http.MethodGet:
|
||||
limit, cursor, ok := pageParams(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
page, err := api.messenger.ListChats(r.Context(), actor.ID, limit, cursor)
|
||||
if err != nil {
|
||||
writeAppError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, page)
|
||||
|
||||
default:
|
||||
requireMethod(w, r, "GET, POST")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
path := strings.TrimPrefix(r.URL.Path, "/api/v1/chats/")
|
||||
parts := strings.Split(path, "/")
|
||||
|
||||
if len(parts) == 1 && parts[0] != "" {
|
||||
if !requireMethod(w, r, http.MethodGet) {
|
||||
return
|
||||
}
|
||||
|
||||
chat, err := api.messenger.GetChat(r.Context(), actor.ID, parts[0])
|
||||
if err != nil {
|
||||
writeAppError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, chat)
|
||||
return
|
||||
}
|
||||
|
||||
if len(parts) != 2 || parts[0] == "" || parts[1] != "messages" {
|
||||
writeError(w, http.StatusNotFound, "not_found", "Resource not found")
|
||||
return
|
||||
}
|
||||
|
||||
chat, err := api.messenger.GetChat(r.Context(), actor.ID, parts[0])
|
||||
if err != nil {
|
||||
writeAppError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
switch r.Method {
|
||||
case http.MethodPost:
|
||||
var body createMessageRequest
|
||||
if !readJSON(w, r, &body, "text") {
|
||||
return
|
||||
}
|
||||
|
||||
message, err := api.messenger.CreateMessage(r.Context(),
|
||||
actor.ID, chat.ID, body.Text,
|
||||
)
|
||||
if err != nil {
|
||||
writeAppError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusCreated, message)
|
||||
|
||||
case http.MethodGet:
|
||||
limit, cursor, ok := pageParams(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
page, err := api.messenger.ListMessages(r.Context(),
|
||||
actor.ID, chat.ID, limit, cursor,
|
||||
)
|
||||
if err != nil {
|
||||
writeAppError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, page)
|
||||
|
||||
default:
|
||||
requireMethod(w, r, "GET, POST")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/service"
|
||||
)
|
||||
|
||||
type API struct {
|
||||
messenger *service.Messenger
|
||||
}
|
||||
|
||||
func NewHandler(
|
||||
messenger *service.Messenger,
|
||||
stoppingFlags ...*atomic.Bool,
|
||||
) http.Handler {
|
||||
api := &API{messenger: messenger}
|
||||
|
||||
var stopping *atomic.Bool
|
||||
|
||||
if len(stoppingFlags) > 0 {
|
||||
stopping = stoppingFlags[0]
|
||||
}
|
||||
|
||||
if stopping == nil {
|
||||
stopping = &atomic.Bool{}
|
||||
}
|
||||
|
||||
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if stopping.Load() && r.URL.Path != "/health/live" {
|
||||
writeError(
|
||||
w,
|
||||
http.StatusServiceUnavailable,
|
||||
"unavailable",
|
||||
"Server is shutting down",
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
api.route(w, r)
|
||||
})
|
||||
|
||||
return withRequestID(withAccessLog(handler))
|
||||
}
|
||||
|
||||
func (api *API) route(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/api/v1/chats" ||
|
||||
strings.HasPrefix(r.URL.Path, "/api/v1/chats/") {
|
||||
api.authenticate(http.HandlerFunc(api.chatRoutes)).ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
switch r.URL.Path {
|
||||
case "/health/live", "/health/ready":
|
||||
handleHealth(w, r)
|
||||
|
||||
case "/api/v1/users":
|
||||
if !requireMethod(w, r, http.MethodPost) {
|
||||
return
|
||||
}
|
||||
api.createUser(w, r)
|
||||
|
||||
case "/api/v1/users/me":
|
||||
if !requireMethod(w, r, http.MethodGet) {
|
||||
return
|
||||
}
|
||||
api.authenticate(http.HandlerFunc(api.currentUser)).ServeHTTP(w, r)
|
||||
|
||||
default:
|
||||
writeError(w, http.StatusNotFound, "not_found", "Resource not found")
|
||||
}
|
||||
}
|
||||
|
||||
func requireMethod(w http.ResponseWriter, r *http.Request, method string) bool {
|
||||
if r.Method == method {
|
||||
return true
|
||||
}
|
||||
|
||||
w.Header().Set("Allow", method)
|
||||
writeError(
|
||||
w,
|
||||
http.StatusMethodNotAllowed,
|
||||
"invalid_request",
|
||||
"Method not allowed",
|
||||
)
|
||||
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/service"
|
||||
)
|
||||
|
||||
func sessionError(w http.ResponseWriter, err error, basic bool) {
|
||||
if errors.Is(err, service.ErrUnauthorized) {
|
||||
challenge := `Bearer realm="messenger"`
|
||||
if basic {
|
||||
challenge = `Basic realm="messenger", charset="UTF-8"`
|
||||
}
|
||||
w.Header().Set("WWW-Authenticate", challenge)
|
||||
writeError(w, http.StatusUnauthorized, "unauthorized", "Invalid credentials")
|
||||
return
|
||||
}
|
||||
writeAppError(w, err)
|
||||
}
|
||||
|
||||
func loginSession(w http.ResponseWriter, r *http.Request, sessions *service.Sessions) {
|
||||
if !requireMethod(w, r, http.MethodPost) {
|
||||
return
|
||||
}
|
||||
username, secret, ok := r.BasicAuth()
|
||||
if !ok || len(r.Header.Values("Authorization")) != 1 {
|
||||
sessionError(w, service.ErrUnauthorized, true)
|
||||
return
|
||||
}
|
||||
body, err := io.ReadAll(io.LimitReader(r.Body, 1))
|
||||
if err != nil || len(body) != 0 {
|
||||
writeAppError(w, service.ErrInvalidRequest)
|
||||
return
|
||||
}
|
||||
result, err := sessions.Login(r.Context(), username, secret)
|
||||
if err != nil {
|
||||
sessionError(w, err, true)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
writeJSON(w, http.StatusCreated, result)
|
||||
}
|
||||
|
||||
func bearerToken(r *http.Request) (string, error) {
|
||||
if len(r.Header.Values("Authorization")) != 1 {
|
||||
return "", service.ErrUnauthorized
|
||||
}
|
||||
fields := strings.Fields(r.Header.Get("Authorization"))
|
||||
if len(fields) != 2 || !strings.EqualFold(fields[0], "Bearer") {
|
||||
return "", service.ErrUnauthorized
|
||||
}
|
||||
return fields[1], nil
|
||||
}
|
||||
|
||||
func currentSession(w http.ResponseWriter, r *http.Request, sessions *service.Sessions, logout bool) {
|
||||
method := http.MethodGet
|
||||
if logout {
|
||||
method = http.MethodDelete
|
||||
}
|
||||
if !requireMethod(w, r, method) {
|
||||
return
|
||||
}
|
||||
token, err := bearerToken(r)
|
||||
if err != nil {
|
||||
sessionError(w, err, false)
|
||||
return
|
||||
}
|
||||
if logout {
|
||||
if err := sessions.Logout(r.Context(), token); err != nil {
|
||||
sessionError(w, err, false)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
user, err := sessions.CurrentUser(r.Context(), token)
|
||||
if err != nil {
|
||||
sessionError(w, err, false)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
writeJSON(w, http.StatusOK, user)
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package httpapi
|
||||
|
||||
import "net/http"
|
||||
|
||||
type createUserRequest struct {
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
}
|
||||
|
||||
func (api *API) createUser(w http.ResponseWriter, r *http.Request) {
|
||||
var body createUserRequest
|
||||
|
||||
if !readJSON(w, r, &body, "username", "display_name") {
|
||||
return
|
||||
}
|
||||
|
||||
user, err := api.messenger.RegisterUser(body.Username, body.DisplayName)
|
||||
if err != nil {
|
||||
writeAppError(w, err)
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusCreated, user)
|
||||
}
|
||||
|
||||
func (api *API) currentUser(w http.ResponseWriter, r *http.Request) {
|
||||
user := userFromContext(r.Context())
|
||||
writeJSON(w, http.StatusOK, user)
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package httpapi_test
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/httpapi"
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model"
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/service"
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store"
|
||||
)
|
||||
|
||||
func newAPI() http.Handler {
|
||||
return httpapi.NewHandler(
|
||||
service.NewMessenger(store.NewMemoryStore()),
|
||||
)
|
||||
}
|
||||
|
||||
func request(
|
||||
handler http.Handler,
|
||||
method string,
|
||||
path string,
|
||||
body string,
|
||||
userID string,
|
||||
) *httptest.ResponseRecorder {
|
||||
req := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
if userID != "" {
|
||||
req.Header.Set("X-User-Id", userID)
|
||||
}
|
||||
|
||||
response := httptest.NewRecorder()
|
||||
handler.ServeHTTP(response, req)
|
||||
return response
|
||||
}
|
||||
|
||||
func checkError(
|
||||
t *testing.T,
|
||||
response *httptest.ResponseRecorder,
|
||||
status int,
|
||||
code string,
|
||||
) {
|
||||
t.Helper()
|
||||
|
||||
if response.Code != status {
|
||||
t.Fatalf(
|
||||
"status: got %d, want %d; body=%s",
|
||||
response.Code, status, response.Body.String(),
|
||||
)
|
||||
}
|
||||
|
||||
var body struct {
|
||||
Error struct {
|
||||
Code string `json:"code"`
|
||||
RequestID string `json:"request_id"`
|
||||
} `json:"error"`
|
||||
}
|
||||
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil {
|
||||
t.Fatalf("decode error response: %v", err)
|
||||
}
|
||||
|
||||
if body.Error.Code != code {
|
||||
t.Errorf("error code: got %q, want %q", body.Error.Code, code)
|
||||
}
|
||||
|
||||
id := response.Header().Get("X-Request-Id")
|
||||
if id == "" || body.Error.RequestID != id {
|
||||
t.Error("missing or mismatched request ID")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserHTTPFlow(t *testing.T) {
|
||||
handler := newAPI()
|
||||
|
||||
body := `{"username":"alice","display_name":"Алиса 👋"}`
|
||||
|
||||
created := request(handler, http.MethodPost, "/api/v1/users", body, "")
|
||||
if created.Code != http.StatusCreated {
|
||||
t.Fatalf("registration: %d %s", created.Code, created.Body.String())
|
||||
}
|
||||
|
||||
if created.Header().Get("X-Request-Id") == "" {
|
||||
t.Fatal("registration response has no request ID")
|
||||
}
|
||||
|
||||
var user model.User
|
||||
if err := json.Unmarshal(created.Body.Bytes(), &user); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if user.ID == "" || user.CreatedAt.IsZero() ||
|
||||
user.Username != "alice" || user.DisplayName != "Алиса 👋" {
|
||||
t.Fatalf("invalid user: %+v", user)
|
||||
}
|
||||
|
||||
me := request(handler, http.MethodGet, "/api/v1/users/me", "", user.ID)
|
||||
if me.Code != http.StatusOK {
|
||||
t.Fatalf("current user: %d %s", me.Code, me.Body.String())
|
||||
}
|
||||
|
||||
var current model.User
|
||||
if err := json.Unmarshal(me.Body.Bytes(), ¤t); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if current != user {
|
||||
t.Fatalf("current user differs: %+v", current)
|
||||
}
|
||||
|
||||
duplicate := request(handler, http.MethodPost, "/api/v1/users", body, "")
|
||||
checkError(t, duplicate, http.StatusConflict, "conflict")
|
||||
|
||||
for _, id := range []string{
|
||||
"",
|
||||
"invalid",
|
||||
"00000000-0000-4000-8000-000000000000",
|
||||
} {
|
||||
response := request(
|
||||
handler, http.MethodGet, "/api/v1/users/me", "", id,
|
||||
)
|
||||
checkError(t, response, http.StatusUnauthorized, "unauthorized")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistrationInvalidJSON(t *testing.T) {
|
||||
cases := []string{
|
||||
``,
|
||||
`{`,
|
||||
`null`,
|
||||
`[]`,
|
||||
`{}`,
|
||||
`{"username":"alice"}`,
|
||||
`{"username":null,"display_name":"Alice"}`,
|
||||
`{"username":123,"display_name":"Alice"}`,
|
||||
`{"username":"alice","display_name":"Alice","extra":true}`,
|
||||
`{"username":"alice","display_name":"Alice"} {}`,
|
||||
`{"username":"Alice","display_name":"Alice"}`,
|
||||
`{"username":"alice","display_name":" "}`,
|
||||
}
|
||||
|
||||
for _, body := range cases {
|
||||
t.Run(body, func(t *testing.T) {
|
||||
response := request(
|
||||
newAPI(), http.MethodPost, "/api/v1/users", body, "",
|
||||
)
|
||||
checkError(t, response, http.StatusBadRequest, "invalid_request")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistrationContentType(t *testing.T) {
|
||||
req := httptest.NewRequest(
|
||||
http.MethodPost,
|
||||
"/api/v1/users",
|
||||
strings.NewReader(`{"username":"alice","display_name":"Alice"}`),
|
||||
)
|
||||
req.Header.Set("Content-Type", "text/plain")
|
||||
|
||||
response := httptest.NewRecorder()
|
||||
newAPI().ServeHTTP(response, req)
|
||||
|
||||
checkError(
|
||||
t, response,
|
||||
http.StatusUnsupportedMediaType, "unsupported_media_type",
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package model
|
||||
|
||||
import "time"
|
||||
|
||||
type User struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type Chat struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type Message struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
SenderID string `json:"sender_id"`
|
||||
Text string `json:"text"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package password
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
const (
|
||||
memoryKiB uint32 = 64 * 1024
|
||||
iterations uint32 = 3
|
||||
parallelism uint8 = 4
|
||||
saltLength = 16
|
||||
keyLength uint32 = 32
|
||||
)
|
||||
|
||||
var (
|
||||
ErrInvalidPassword = errors.New("password must contain 12 to 128 UTF-8 code points")
|
||||
ErrInvalidHash = errors.New("invalid or unsupported password hash")
|
||||
encoding = base64.RawStdEncoding.Strict()
|
||||
profile = fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$",
|
||||
argon2.Version, memoryKiB, iterations, parallelism)
|
||||
)
|
||||
|
||||
func Validate(value string) error {
|
||||
if !utf8.ValidString(value) {
|
||||
return ErrInvalidPassword
|
||||
}
|
||||
length := utf8.RuneCountInString(value)
|
||||
if length < 12 || length > 128 {
|
||||
return ErrInvalidPassword
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func Hash(value string) (string, error) {
|
||||
if err := Validate(value); err != nil {
|
||||
return "", err
|
||||
}
|
||||
salt := make([]byte, saltLength)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", fmt.Errorf("generate password salt: %w", err)
|
||||
}
|
||||
key := argon2.IDKey([]byte(value), salt, iterations, memoryKiB, parallelism, keyLength)
|
||||
return profile + encoding.EncodeToString(salt) + "$" + encoding.EncodeToString(key), nil
|
||||
}
|
||||
|
||||
func Verify(value, encoded string) (bool, error) {
|
||||
if len(encoded) != len(profile)+encoding.EncodedLen(saltLength)+1+encoding.EncodedLen(int(keyLength)) ||
|
||||
!strings.HasPrefix(encoded, profile) {
|
||||
return false, ErrInvalidHash
|
||||
}
|
||||
parts := strings.Split(strings.TrimPrefix(encoded, profile), "$")
|
||||
if len(parts) != 2 {
|
||||
return false, ErrInvalidHash
|
||||
}
|
||||
salt, err := encoding.DecodeString(parts[0])
|
||||
if err != nil || len(salt) != saltLength {
|
||||
return false, ErrInvalidHash
|
||||
}
|
||||
expected, err := encoding.DecodeString(parts[1])
|
||||
if err != nil || len(expected) != int(keyLength) {
|
||||
return false, ErrInvalidHash
|
||||
}
|
||||
if err := Validate(value); err != nil {
|
||||
return false, nil
|
||||
}
|
||||
actual := argon2.IDKey([]byte(value), salt, iterations, memoryKiB, parallelism, keyLength)
|
||||
return subtle.ConstantTimeCompare(actual, expected) == 1, nil
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package password
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestValidate(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
value string
|
||||
valid bool
|
||||
}{
|
||||
{"empty", "", false},
|
||||
{"11 characters", strings.Repeat("a", 11), false},
|
||||
{"12 characters", strings.Repeat("a", 12), true},
|
||||
{"128 Unicode characters", strings.Repeat("я", 128), true},
|
||||
{"129 Unicode characters", strings.Repeat("я", 129), false},
|
||||
{"invalid UTF-8", strings.Repeat("a", 12) + string([]byte{0xff}), false},
|
||||
{"spaces preserved", strings.Repeat(" ", 12), true},
|
||||
{"colon allowed", "пароль:секрет", true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
err := Validate(tc.value)
|
||||
if (err == nil) != tc.valid {
|
||||
t.Fatalf("valid=%v, error=%v", tc.valid, err)
|
||||
}
|
||||
if !tc.valid {
|
||||
if _, err := Hash(tc.value); !errors.Is(err, ErrInvalidPassword) {
|
||||
t.Fatalf("Hash error=%v", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestHashAndVerify(t *testing.T) {
|
||||
value := " пароль:секрет "
|
||||
first, err := Hash(value)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
second, err := Hash(value)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if first == second {
|
||||
t.Fatal("independent salts produced identical records")
|
||||
}
|
||||
for _, encoded := range []string{first, second} {
|
||||
ok, err := Verify(value, encoded)
|
||||
if err != nil || !ok {
|
||||
t.Fatalf("correct password: match=%v error=%v", ok, err)
|
||||
}
|
||||
}
|
||||
for _, wrong := range []string{"другой:пароль", strings.TrimSpace(value), "short"} {
|
||||
ok, err := Verify(wrong, first)
|
||||
if err != nil || ok {
|
||||
t.Fatalf("wrong password: match=%v error=%v", ok, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLongUnicodePasswordIsNotTruncated(t *testing.T) {
|
||||
value := strings.Repeat("я", 128)
|
||||
encoded, err := Hash(value)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ok, err := Verify(value, encoded)
|
||||
if err != nil || !ok {
|
||||
t.Fatalf("match=%v error=%v", ok, err)
|
||||
}
|
||||
ok, err = Verify(strings.Repeat("я", 127)+"ю", encoded)
|
||||
if err != nil || ok {
|
||||
t.Fatalf("last character ignored: match=%v error=%v", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyRejectsMalformedHash(t *testing.T) {
|
||||
encoded := profile + encoding.EncodeToString(make([]byte, saltLength)) + "$" + encoding.EncodeToString(make([]byte, keyLength))
|
||||
for _, broken := range []string{
|
||||
"", "plaintext", encoded[:len(encoded)-1], encoded + "$extra",
|
||||
strings.Replace(encoded, "v=19", "v=18", 1),
|
||||
strings.Replace(encoded, "m=65536", "m=999999999", 1),
|
||||
strings.Replace(encoded, "t=3", "t=0", 1),
|
||||
strings.Replace(encoded, "p=4", "p=0", 1),
|
||||
profile + "!" + encoded[len(profile)+1:],
|
||||
} {
|
||||
ok, err := Verify("пароль:секрет", broken)
|
||||
if ok || !errors.Is(err, ErrInvalidHash) {
|
||||
t.Fatalf("match=%v error=%v", ok, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model"
|
||||
)
|
||||
|
||||
func validText(value string, maxLength int) bool {
|
||||
return utf8.ValidString(value) &&
|
||||
strings.TrimSpace(value) != "" &&
|
||||
utf8.RuneCountInString(value) <= maxLength
|
||||
}
|
||||
|
||||
func (m *Messenger) CreateChat(
|
||||
actorID string,
|
||||
title string,
|
||||
memberIDs []string,
|
||||
) (model.Chat, error) {
|
||||
if !validText(title, 100) ||
|
||||
len(memberIDs) < 1 ||
|
||||
len(memberIDs) > 100 {
|
||||
return model.Chat{}, ErrInvalidRequest
|
||||
}
|
||||
|
||||
normalized := make([]string, len(memberIDs))
|
||||
|
||||
for i, id := range memberIDs {
|
||||
if !uuidPattern.MatchString(id) {
|
||||
return model.Chat{}, ErrInvalidRequest
|
||||
}
|
||||
normalized[i] = strings.ToLower(id)
|
||||
}
|
||||
|
||||
return m.store.CreateChat(actorID, title, normalized)
|
||||
}
|
||||
|
||||
func (m *Messenger) GetChat(
|
||||
actorID string,
|
||||
chatID string,
|
||||
) (model.Chat, error) {
|
||||
if !uuidPattern.MatchString(chatID) {
|
||||
return model.Chat{}, ErrInvalidRequest
|
||||
}
|
||||
|
||||
return m.store.GetChat(actorID, strings.ToLower(chatID))
|
||||
}
|
||||
|
||||
func (m *Messenger) ListChats(
|
||||
actorID string,
|
||||
limit int,
|
||||
cursor string,
|
||||
) (Page[model.Chat], error) {
|
||||
chats := m.store.ListChats(actorID)
|
||||
|
||||
return paginate(
|
||||
chats,
|
||||
"chats:"+actorID,
|
||||
limit,
|
||||
cursor,
|
||||
func(chat model.Chat) position {
|
||||
return position{CreatedAt: chat.CreatedAt, ID: chat.ID}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
func (m *Messenger) CreateMessage(
|
||||
actorID string,
|
||||
chatID string,
|
||||
text string,
|
||||
) (model.Message, error) {
|
||||
chat, err := m.GetChat(actorID, chatID)
|
||||
if err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
|
||||
if !validText(text, 4000) {
|
||||
return model.Message{}, ErrInvalidRequest
|
||||
}
|
||||
|
||||
return m.store.CreateMessage(actorID, chat.ID, text)
|
||||
}
|
||||
|
||||
func (m *Messenger) ListMessages(
|
||||
actorID string,
|
||||
chatID string,
|
||||
limit int,
|
||||
cursor string,
|
||||
) (Page[model.Message], error) {
|
||||
if !uuidPattern.MatchString(chatID) {
|
||||
return Page[model.Message]{}, ErrInvalidRequest
|
||||
}
|
||||
|
||||
chatID = strings.ToLower(chatID)
|
||||
|
||||
messages, err := m.store.ListMessages(actorID, chatID)
|
||||
if err != nil {
|
||||
return Page[model.Message]{}, err
|
||||
}
|
||||
|
||||
return paginate(
|
||||
messages,
|
||||
"messages:"+chatID,
|
||||
limit,
|
||||
cursor,
|
||||
func(message model.Message) position {
|
||||
return position{CreatedAt: message.CreatedAt, ID: message.ID}
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model"
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrInvalidRequest = errors.New("invalid request")
|
||||
ErrUnauthorized = errors.New("unauthorized")
|
||||
)
|
||||
|
||||
var (
|
||||
usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
uuidPattern = regexp.MustCompile(
|
||||
`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$`,
|
||||
)
|
||||
)
|
||||
|
||||
type Messenger struct {
|
||||
store *store.MemoryStore
|
||||
}
|
||||
|
||||
func NewMessenger(memory *store.MemoryStore) *Messenger {
|
||||
return &Messenger{
|
||||
store: memory,
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Messenger) RegisterUser(
|
||||
username string,
|
||||
displayName string,
|
||||
) (model.User, error) {
|
||||
if !usernamePattern.MatchString(username) {
|
||||
return model.User{}, ErrInvalidRequest
|
||||
}
|
||||
|
||||
if !utf8.ValidString(displayName) {
|
||||
return model.User{}, ErrInvalidRequest
|
||||
}
|
||||
|
||||
length := utf8.RuneCountInString(displayName)
|
||||
|
||||
if length < 1 || length > 100 {
|
||||
return model.User{}, ErrInvalidRequest
|
||||
}
|
||||
|
||||
if strings.TrimSpace(displayName) == "" {
|
||||
return model.User{}, ErrInvalidRequest
|
||||
}
|
||||
|
||||
return m.store.CreateUser(username, displayName)
|
||||
}
|
||||
|
||||
func (m *Messenger) CurrentUser(id string) (model.User, error) {
|
||||
if !uuidPattern.MatchString(id) {
|
||||
return model.User{}, ErrUnauthorized
|
||||
}
|
||||
|
||||
user, err := m.store.GetUser(strings.ToLower(id))
|
||||
|
||||
if errors.Is(err, store.ErrUserNotFound) {
|
||||
return model.User{}, ErrUnauthorized
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return model.User{}, err
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
package service_test
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/service"
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store"
|
||||
)
|
||||
|
||||
func TestRegisterUserValidation(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
username string
|
||||
displayName string
|
||||
valid bool
|
||||
}{
|
||||
{
|
||||
name: "valid Unicode name",
|
||||
username: "alice_01",
|
||||
displayName: "Алиса 👋",
|
||||
valid: true,
|
||||
},
|
||||
{
|
||||
name: "100 Unicode code points",
|
||||
username: "alice",
|
||||
displayName: strings.Repeat("👋", 100),
|
||||
valid: true,
|
||||
},
|
||||
{
|
||||
name: "101 Unicode code points",
|
||||
username: "alice",
|
||||
displayName: strings.Repeat("👋", 101),
|
||||
},
|
||||
{
|
||||
name: "short username",
|
||||
username: "ab",
|
||||
displayName: "Алиса",
|
||||
},
|
||||
{
|
||||
name: "long username",
|
||||
username: strings.Repeat("a", 33),
|
||||
displayName: "Алиса",
|
||||
},
|
||||
{
|
||||
name: "uppercase username",
|
||||
username: "Alice",
|
||||
displayName: "Алиса",
|
||||
},
|
||||
{
|
||||
name: "non ASCII username",
|
||||
username: "алиса",
|
||||
displayName: "Алиса",
|
||||
},
|
||||
{
|
||||
name: "empty display name",
|
||||
username: "alice",
|
||||
displayName: "",
|
||||
},
|
||||
{
|
||||
name: "whitespace display name",
|
||||
username: "alice",
|
||||
displayName: " \t\n",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
m := service.NewMessenger(store.NewMemoryStore())
|
||||
|
||||
user, err := m.RegisterUser(tt.username, tt.displayName)
|
||||
|
||||
if !tt.valid {
|
||||
if !errors.Is(err, service.ErrInvalidRequest) {
|
||||
t.Fatalf("expected ErrInvalidRequest, got %v", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("RegisterUser: %v", err)
|
||||
}
|
||||
|
||||
if user.Username != tt.username ||
|
||||
user.DisplayName != tt.displayName {
|
||||
t.Fatalf("user fields changed: %+v", user)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegisterDuplicateUsername(t *testing.T) {
|
||||
m := service.NewMessenger(store.NewMemoryStore())
|
||||
|
||||
if _, err := m.RegisterUser("alice", "Алиса"); err != nil {
|
||||
t.Fatalf("first registration: %v", err)
|
||||
}
|
||||
|
||||
_, err := m.RegisterUser("alice", "Другое имя")
|
||||
if !errors.Is(err, store.ErrUsernameTaken) {
|
||||
t.Fatalf("expected ErrUsernameTaken, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCurrentUser(t *testing.T) {
|
||||
m := service.NewMessenger(store.NewMemoryStore())
|
||||
|
||||
created, err := m.RegisterUser("alice", "Алиса")
|
||||
if err != nil {
|
||||
t.Fatalf("RegisterUser: %v", err)
|
||||
}
|
||||
|
||||
for _, id := range []string{
|
||||
created.ID,
|
||||
strings.ToUpper(created.ID),
|
||||
} {
|
||||
found, err := m.CurrentUser(id)
|
||||
if err != nil {
|
||||
t.Fatalf("CurrentUser(%q): %v", id, err)
|
||||
}
|
||||
|
||||
if found != created {
|
||||
t.Fatalf("got %+v, want %+v", found, created)
|
||||
}
|
||||
}
|
||||
|
||||
for _, id := range []string{
|
||||
"",
|
||||
"not-a-uuid",
|
||||
"00000000-0000-4000-8000-000000000000",
|
||||
} {
|
||||
_, err := m.CurrentUser(id)
|
||||
|
||||
if !errors.Is(err, service.ErrUnauthorized) {
|
||||
t.Errorf(
|
||||
"CurrentUser(%q): expected ErrUnauthorized, got %v",
|
||||
id,
|
||||
err,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"sort"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Page[T any] struct {
|
||||
Items []T `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
type position struct {
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
ID string `json:"id"`
|
||||
}
|
||||
|
||||
type cursorData struct {
|
||||
Scope string `json:"scope"`
|
||||
After position `json:"after"`
|
||||
}
|
||||
|
||||
func less(a, b position) bool {
|
||||
if a.CreatedAt.Equal(b.CreatedAt) {
|
||||
return a.ID < b.ID
|
||||
}
|
||||
return a.CreatedAt.Before(b.CreatedAt)
|
||||
}
|
||||
|
||||
func paginate[T any](
|
||||
items []T,
|
||||
scope string,
|
||||
limit int,
|
||||
cursor string,
|
||||
key func(T) position,
|
||||
) (Page[T], error) {
|
||||
if limit < 1 || limit > 100 {
|
||||
return Page[T]{}, ErrInvalidRequest
|
||||
}
|
||||
|
||||
var after *position
|
||||
|
||||
if cursor != "" {
|
||||
raw, err := base64.RawURLEncoding.DecodeString(cursor)
|
||||
if err != nil {
|
||||
return Page[T]{}, ErrInvalidRequest
|
||||
}
|
||||
|
||||
var decoded cursorData
|
||||
if err := json.Unmarshal(raw, &decoded); err != nil {
|
||||
return Page[T]{}, ErrInvalidRequest
|
||||
}
|
||||
|
||||
if decoded.Scope != scope ||
|
||||
decoded.After.CreatedAt.IsZero() ||
|
||||
!uuidPattern.MatchString(decoded.After.ID) {
|
||||
return Page[T]{}, ErrInvalidRequest
|
||||
}
|
||||
|
||||
after = &decoded.After
|
||||
}
|
||||
|
||||
sort.Slice(items, func(i, j int) bool {
|
||||
return less(key(items[i]), key(items[j]))
|
||||
})
|
||||
|
||||
start := 0
|
||||
|
||||
if after != nil {
|
||||
start = sort.Search(len(items), func(i int) bool {
|
||||
return less(*after, key(items[i]))
|
||||
})
|
||||
}
|
||||
|
||||
end := min(start+limit, len(items))
|
||||
|
||||
page := Page[T]{
|
||||
Items: make([]T, end-start),
|
||||
}
|
||||
copy(page.Items, items[start:end])
|
||||
|
||||
if end < len(items) {
|
||||
raw, err := json.Marshal(cursorData{
|
||||
Scope: scope,
|
||||
After: key(items[end-1]),
|
||||
})
|
||||
if err != nil {
|
||||
return Page[T]{}, err
|
||||
}
|
||||
|
||||
next := base64.RawURLEncoding.EncodeToString(raw)
|
||||
page.NextCursor = &next
|
||||
}
|
||||
|
||||
return page, nil
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model"
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type PersistentMessenger struct{ db *store.PostgresStore }
|
||||
|
||||
func NewPersistentMessenger(db *store.PostgresStore) *PersistentMessenger {
|
||||
return &PersistentMessenger{db: db}
|
||||
}
|
||||
|
||||
func (m *PersistentMessenger) CreateChat(ctx context.Context, actor, title string, members []string) (model.Chat, error) {
|
||||
if !validText(title, 100) || len(members) < 1 || len(members) > 100 {
|
||||
return model.Chat{}, ErrInvalidRequest
|
||||
}
|
||||
normalized := make([]string, len(members))
|
||||
seen := make(map[string]bool)
|
||||
for i, id := range members {
|
||||
if !uuidPattern.MatchString(id) {
|
||||
return model.Chat{}, ErrInvalidRequest
|
||||
}
|
||||
id = strings.ToLower(id)
|
||||
if seen[id] {
|
||||
return model.Chat{}, store.ErrInvalidMembers
|
||||
}
|
||||
seen[id] = true
|
||||
normalized[i] = id
|
||||
}
|
||||
if !seen[actor] {
|
||||
return model.Chat{}, store.ErrInvalidMembers
|
||||
}
|
||||
return m.db.CreateChat(ctx, title, normalized)
|
||||
}
|
||||
func (m *PersistentMessenger) GetChat(ctx context.Context, actor, id string) (model.Chat, error) {
|
||||
if !uuidPattern.MatchString(id) {
|
||||
return model.Chat{}, ErrInvalidRequest
|
||||
}
|
||||
return m.db.GetChat(ctx, actor, strings.ToLower(id))
|
||||
}
|
||||
func decodePosition(cursor, scope string, limit int) (*store.Position, error) {
|
||||
if limit < 1 || limit > 100 {
|
||||
return nil, ErrInvalidRequest
|
||||
}
|
||||
if cursor == "" {
|
||||
return nil, nil
|
||||
}
|
||||
if len(cursor) > 2048 {
|
||||
return nil, ErrInvalidRequest
|
||||
}
|
||||
raw, err := base64.RawURLEncoding.DecodeString(cursor)
|
||||
if err != nil {
|
||||
return nil, ErrInvalidRequest
|
||||
}
|
||||
var data cursorData
|
||||
if json.Unmarshal(raw, &data) != nil || data.Scope != scope || data.After.CreatedAt.IsZero() || !uuidPattern.MatchString(data.After.ID) {
|
||||
return nil, ErrInvalidRequest
|
||||
}
|
||||
if data.After.CreatedAt.Year() < 1 || data.After.CreatedAt.Year() > 9999 {
|
||||
return nil, ErrInvalidRequest
|
||||
}
|
||||
return &store.Position{CreatedAt: data.After.CreatedAt, ID: strings.ToLower(data.After.ID)}, nil
|
||||
}
|
||||
func databasePage[T any](items []T, limit int, scope string, key func(T) position) (Page[T], error) {
|
||||
page := Page[T]{Items: items}
|
||||
if len(items) <= limit {
|
||||
return page, nil
|
||||
}
|
||||
page.Items = items[:limit]
|
||||
raw, err := json.Marshal(cursorData{Scope: scope, After: key(page.Items[limit-1])})
|
||||
if err != nil {
|
||||
return Page[T]{}, err
|
||||
}
|
||||
cursor := base64.RawURLEncoding.EncodeToString(raw)
|
||||
page.NextCursor = &cursor
|
||||
return page, nil
|
||||
}
|
||||
func (m *PersistentMessenger) ListChats(ctx context.Context, actor string, limit int, cursor string) (Page[model.Chat], error) {
|
||||
scope := "chats:" + actor
|
||||
after, err := decodePosition(cursor, scope, limit)
|
||||
if err != nil {
|
||||
return Page[model.Chat]{}, err
|
||||
}
|
||||
items, err := m.db.ChatPage(ctx, actor, limit+1, after)
|
||||
if err != nil {
|
||||
return Page[model.Chat]{}, err
|
||||
}
|
||||
return databasePage(items, limit, scope, func(c model.Chat) position { return position{CreatedAt: c.CreatedAt, ID: c.ID} })
|
||||
}
|
||||
func (m *PersistentMessenger) CreateMessage(ctx context.Context, actor, chatID, text string) (model.Message, error) {
|
||||
if !uuidPattern.MatchString(chatID) || !validText(text, 4000) {
|
||||
return model.Message{}, ErrInvalidRequest
|
||||
}
|
||||
return m.db.CreateMessage(ctx, actor, strings.ToLower(chatID), text)
|
||||
}
|
||||
func (m *PersistentMessenger) ListMessages(ctx context.Context, actor, chatID string, limit int, cursor string) (Page[model.Message], error) {
|
||||
chat, err := m.GetChat(ctx, actor, chatID)
|
||||
if err != nil {
|
||||
return Page[model.Message]{}, err
|
||||
}
|
||||
scope := "messages:" + chat.ID
|
||||
after, err := decodePosition(cursor, scope, limit)
|
||||
if err != nil {
|
||||
return Page[model.Message]{}, err
|
||||
}
|
||||
items, err := m.db.MessagePage(ctx, chat.ID, limit+1, after)
|
||||
if err != nil {
|
||||
return Page[model.Message]{}, err
|
||||
}
|
||||
return databasePage(items, limit, scope, func(message model.Message) position { return position{CreatedAt: message.CreatedAt, ID: message.ID} })
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model"
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/password"
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store"
|
||||
)
|
||||
|
||||
type UserWriter interface {
|
||||
CreateUser(context.Context, string, string, string) (model.User, error)
|
||||
}
|
||||
|
||||
type Registration struct {
|
||||
users UserWriter
|
||||
hashSlots chan struct{}
|
||||
}
|
||||
|
||||
func NewRegistration(users UserWriter) *Registration {
|
||||
return &Registration{users: users, hashSlots: make(chan struct{}, 2)}
|
||||
}
|
||||
|
||||
func (s *Registration) Register(ctx context.Context, username, displayName, secret string) (model.User, error) {
|
||||
if !usernamePattern.MatchString(username) || !validText(displayName, 100) || password.Validate(secret) != nil {
|
||||
return model.User{}, ErrInvalidRequest
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
select {
|
||||
case s.hashSlots <- struct{}{}:
|
||||
case <-ctx.Done():
|
||||
return model.User{}, store.ErrUnavailable
|
||||
}
|
||||
hash, err := password.Hash(secret)
|
||||
<-s.hashSlots
|
||||
if err != nil {
|
||||
return model.User{}, err
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return model.User{}, store.ErrUnavailable
|
||||
}
|
||||
return s.users.CreateUser(ctx, username, displayName, hash)
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model"
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/password"
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store"
|
||||
)
|
||||
|
||||
type registrationWriter struct {
|
||||
calls int
|
||||
hash string
|
||||
err error
|
||||
}
|
||||
|
||||
func (w *registrationWriter) CreateUser(_ context.Context, username, displayName, hash string) (model.User, error) {
|
||||
w.calls++
|
||||
w.hash = hash
|
||||
return model.User{Username: username, DisplayName: displayName}, w.err
|
||||
}
|
||||
|
||||
func TestRegistrationHashesBeforeStorage(t *testing.T) {
|
||||
w := ®istrationWriter{}
|
||||
s := NewRegistration(w)
|
||||
user, err := s.Register(context.Background(), "alice", "Алиса", "учебный:пароль")
|
||||
if err != nil || user.Username != "alice" || w.calls != 1 {
|
||||
t.Fatalf("registration failed: %v", err)
|
||||
}
|
||||
ok, err := password.Verify("учебный:пароль", w.hash)
|
||||
if err != nil || !ok {
|
||||
t.Fatalf("stored value is not a valid password hash: %v", err)
|
||||
}
|
||||
w.err = store.ErrUsernameTaken
|
||||
_, err = s.Register(context.Background(), "alice", "Алиса", "учебный:пароль")
|
||||
if !errors.Is(err, store.ErrUsernameTaken) {
|
||||
t.Fatalf("conflict lost: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistrationRejectsBeforeStorage(t *testing.T) {
|
||||
w := ®istrationWriter{}
|
||||
s := NewRegistration(w)
|
||||
for _, fields := range [][3]string{{"Alice", "Алиса", "учебный:пароль"}, {"alice", " ", "учебный:пароль"}, {"alice", "Алиса", "short"}} {
|
||||
_, err := s.Register(context.Background(), fields[0], fields[1], fields[2])
|
||||
if !errors.Is(err, ErrInvalidRequest) {
|
||||
t.Fatalf("invalid input accepted: %v", err)
|
||||
}
|
||||
}
|
||||
if w.calls != 0 {
|
||||
t.Fatal("invalid data reached storage")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model"
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/password"
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store"
|
||||
)
|
||||
|
||||
type SessionStore interface {
|
||||
Credentials(context.Context, string) (model.User, string, error)
|
||||
CreateSession(context.Context, []byte, string, int64) (time.Time, error)
|
||||
SessionUser(context.Context, []byte) (model.User, error)
|
||||
DeleteSession(context.Context, []byte) error
|
||||
}
|
||||
|
||||
type Sessions struct {
|
||||
db SessionStore
|
||||
ttl int64
|
||||
hashSlots chan struct{}
|
||||
dummyHash string
|
||||
}
|
||||
|
||||
type SessionResponse struct {
|
||||
Token string `json:"token"`
|
||||
TokenType string `json:"token_type"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
User model.User `json:"user"`
|
||||
}
|
||||
|
||||
func NewSessions(db SessionStore, registration *Registration, ttl int64) (*Sessions, error) {
|
||||
if ttl < 1 || ttl > 31536000 {
|
||||
return nil, errors.New("SESSION_TTL_SECONDS must be between 1 and 31536000")
|
||||
}
|
||||
dummy, err := password.Hash("dummy-password-for-missing-user")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Sessions{db: db, ttl: ttl, hashSlots: registration.hashSlots, dummyHash: dummy}, nil
|
||||
}
|
||||
|
||||
func (s *Sessions) Login(ctx context.Context, username, secret string) (SessionResponse, error) {
|
||||
if !usernamePattern.MatchString(username) || password.Validate(secret) != nil {
|
||||
return SessionResponse{}, ErrUnauthorized
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
user, hash, err := s.db.Credentials(ctx, username)
|
||||
missing := errors.Is(err, store.ErrUserNotFound)
|
||||
if err != nil && !missing {
|
||||
return SessionResponse{}, err
|
||||
}
|
||||
if missing {
|
||||
hash = s.dummyHash
|
||||
}
|
||||
select {
|
||||
case s.hashSlots <- struct{}{}:
|
||||
case <-ctx.Done():
|
||||
return SessionResponse{}, store.ErrUnavailable
|
||||
}
|
||||
matches, err := password.Verify(secret, hash)
|
||||
<-s.hashSlots
|
||||
if err != nil {
|
||||
return SessionResponse{}, errors.New("stored password hash is invalid")
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return SessionResponse{}, store.ErrUnavailable
|
||||
}
|
||||
if missing || !matches {
|
||||
return SessionResponse{}, ErrUnauthorized
|
||||
}
|
||||
raw := make([]byte, 32)
|
||||
if _, err := rand.Read(raw); err != nil {
|
||||
return SessionResponse{}, errors.New("cannot generate session token")
|
||||
}
|
||||
token := base64.RawURLEncoding.EncodeToString(raw)
|
||||
digest := sha256.Sum256([]byte(token))
|
||||
expires, err := s.db.CreateSession(ctx, digest[:], user.ID, s.ttl)
|
||||
if err != nil {
|
||||
return SessionResponse{}, err
|
||||
}
|
||||
return SessionResponse{Token: token, TokenType: "Bearer", ExpiresAt: expires, User: user}, nil
|
||||
}
|
||||
|
||||
func tokenDigest(token string) ([]byte, error) {
|
||||
if len(token) != 43 {
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
raw, err := base64.RawURLEncoding.Strict().DecodeString(token)
|
||||
if err != nil || len(raw) != 32 {
|
||||
return nil, ErrUnauthorized
|
||||
}
|
||||
digest := sha256.Sum256([]byte(token))
|
||||
return digest[:], nil
|
||||
}
|
||||
|
||||
func (s *Sessions) CurrentUser(ctx context.Context, token string) (model.User, error) {
|
||||
digest, err := tokenDigest(token)
|
||||
if err != nil {
|
||||
return model.User{}, err
|
||||
}
|
||||
user, err := s.db.SessionUser(ctx, digest)
|
||||
if errors.Is(err, store.ErrSessionNotFound) {
|
||||
return model.User{}, ErrUnauthorized
|
||||
}
|
||||
return user, err
|
||||
}
|
||||
|
||||
func (s *Sessions) Logout(ctx context.Context, token string) error {
|
||||
digest, err := tokenDigest(token)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = s.db.DeleteSession(ctx, digest)
|
||||
if errors.Is(err, store.ErrSessionNotFound) {
|
||||
return ErrUnauthorized
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model"
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/password"
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store"
|
||||
)
|
||||
|
||||
type sessionFake struct {
|
||||
hash string
|
||||
stored []byte
|
||||
writes int
|
||||
unavailable bool
|
||||
}
|
||||
|
||||
func (f *sessionFake) Credentials(_ context.Context, username string) (model.User, string, error) {
|
||||
if f.unavailable {
|
||||
return model.User{}, "", store.ErrUnavailable
|
||||
}
|
||||
if username != "alice" {
|
||||
return model.User{}, "", store.ErrUserNotFound
|
||||
}
|
||||
return model.User{ID: "user-id", Username: username}, f.hash, nil
|
||||
}
|
||||
func (f *sessionFake) CreateSession(_ context.Context, hash []byte, _ string, _ int64) (time.Time, error) {
|
||||
f.writes++
|
||||
f.stored = append([]byte(nil), hash...)
|
||||
return time.Now().UTC().Add(time.Hour), nil
|
||||
}
|
||||
func (f *sessionFake) SessionUser(_ context.Context, hash []byte) (model.User, error) {
|
||||
if f.unavailable {
|
||||
return model.User{}, store.ErrUnavailable
|
||||
}
|
||||
if string(hash) != string(f.stored) || f.stored == nil {
|
||||
return model.User{}, store.ErrSessionNotFound
|
||||
}
|
||||
return model.User{ID: "user-id", Username: "alice"}, nil
|
||||
}
|
||||
func (f *sessionFake) DeleteSession(_ context.Context, hash []byte) error {
|
||||
if _, err := f.SessionUser(context.Background(), hash); err != nil {
|
||||
return err
|
||||
}
|
||||
f.stored = nil
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestSessionLifecycle(t *testing.T) {
|
||||
hash, err := password.Hash("учебный:пароль")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
db := &sessionFake{hash: hash}
|
||||
s, err := NewSessions(db, NewRegistration(nil), 3600)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, username := range []string{"alice", "missing"} {
|
||||
if _, err := s.Login(context.Background(), username, "неверный:пароль"); !errors.Is(err, ErrUnauthorized) {
|
||||
t.Fatalf("bad credentials: %v", err)
|
||||
}
|
||||
}
|
||||
if db.writes != 0 {
|
||||
t.Fatal("invalid login created a session")
|
||||
}
|
||||
session, err := s.Login(context.Background(), "alice", "учебный:пароль")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
digest := sha256.Sum256([]byte(session.Token))
|
||||
if len(session.Token) != 43 || string(db.stored) != string(digest[:]) {
|
||||
t.Fatal("must store digest of random token")
|
||||
}
|
||||
if _, err := s.CurrentUser(context.Background(), session.Token); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
db.unavailable = true
|
||||
if _, err := s.CurrentUser(context.Background(), session.Token); !errors.Is(err, store.ErrUnavailable) {
|
||||
t.Fatalf("outage: %v", err)
|
||||
}
|
||||
db.unavailable = false
|
||||
if err := s.Logout(context.Background(), session.Token); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.CurrentUser(context.Background(), session.Token); !errors.Is(err, ErrUnauthorized) {
|
||||
t.Fatalf("revoked: %v", err)
|
||||
}
|
||||
if err := s.Logout(context.Background(), session.Token); !errors.Is(err, ErrUnauthorized) {
|
||||
t.Fatalf("repeated logout: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrNotFound = errors.New("resource not found")
|
||||
ErrInvalidMembers = errors.New("invalid chat members")
|
||||
)
|
||||
|
||||
func cloneChat(chat model.Chat) model.Chat {
|
||||
chat.MemberIDs = slices.Clone(chat.MemberIDs)
|
||||
return chat
|
||||
}
|
||||
|
||||
func (s *MemoryStore) CreateChat(
|
||||
actorID string,
|
||||
title string,
|
||||
memberIDs []string,
|
||||
) (model.Chat, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
seen := make(map[string]bool, len(memberIDs))
|
||||
|
||||
for _, id := range memberIDs {
|
||||
if seen[id] {
|
||||
return model.Chat{}, ErrInvalidMembers
|
||||
}
|
||||
|
||||
if _, exists := s.usersByID[id]; !exists {
|
||||
return model.Chat{}, ErrInvalidMembers
|
||||
}
|
||||
|
||||
seen[id] = true
|
||||
}
|
||||
|
||||
if !seen[actorID] {
|
||||
return model.Chat{}, ErrInvalidMembers
|
||||
}
|
||||
|
||||
id, err := newUUID()
|
||||
if err != nil {
|
||||
return model.Chat{}, err
|
||||
}
|
||||
|
||||
for {
|
||||
if _, exists := s.chatsByID[id]; !exists {
|
||||
break
|
||||
}
|
||||
id, err = newUUID()
|
||||
if err != nil {
|
||||
return model.Chat{}, err
|
||||
}
|
||||
}
|
||||
|
||||
chat := model.Chat{
|
||||
ID: id,
|
||||
Title: title,
|
||||
MemberIDs: slices.Clone(memberIDs),
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
|
||||
s.chatsByID[id] = chat
|
||||
s.messagesByChat[id] = []model.Message{}
|
||||
|
||||
return cloneChat(chat), nil
|
||||
}
|
||||
|
||||
func (s *MemoryStore) GetChat(
|
||||
actorID string,
|
||||
chatID string,
|
||||
) (model.Chat, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
chat, exists := s.chatsByID[chatID]
|
||||
if !exists || !slices.Contains(chat.MemberIDs, actorID) {
|
||||
return model.Chat{}, ErrNotFound
|
||||
}
|
||||
|
||||
return cloneChat(chat), nil
|
||||
}
|
||||
|
||||
func (s *MemoryStore) ListChats(actorID string) []model.Chat {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
result := make([]model.Chat, 0)
|
||||
|
||||
for _, chat := range s.chatsByID {
|
||||
if slices.Contains(chat.MemberIDs, actorID) {
|
||||
result = append(result, cloneChat(chat))
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
func (s *MemoryStore) CreateMessage(
|
||||
actorID string,
|
||||
chatID string,
|
||||
text string,
|
||||
) (model.Message, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
chat, exists := s.chatsByID[chatID]
|
||||
if !exists || !slices.Contains(chat.MemberIDs, actorID) {
|
||||
return model.Message{}, ErrNotFound
|
||||
}
|
||||
|
||||
id, err := newUUID()
|
||||
if err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
|
||||
history := s.messagesByChat[chatID]
|
||||
|
||||
for slices.ContainsFunc(history, func(message model.Message) bool {
|
||||
return message.ID == id
|
||||
}) {
|
||||
id, err = newUUID()
|
||||
if err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
}
|
||||
|
||||
createdAt := time.Now().UTC()
|
||||
|
||||
if len(history) > 0 {
|
||||
last := history[len(history)-1].CreatedAt
|
||||
if !createdAt.After(last) {
|
||||
createdAt = last.Add(time.Nanosecond)
|
||||
}
|
||||
}
|
||||
|
||||
message := model.Message{
|
||||
ID: id,
|
||||
ChatID: chatID,
|
||||
SenderID: actorID,
|
||||
Text: text,
|
||||
CreatedAt: createdAt,
|
||||
}
|
||||
|
||||
s.messagesByChat[chatID] = append(history, message)
|
||||
return message, nil
|
||||
}
|
||||
|
||||
func (s *MemoryStore) ListMessages(
|
||||
actorID string,
|
||||
chatID string,
|
||||
) ([]model.Message, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
chat, exists := s.chatsByID[chatID]
|
||||
if !exists || !slices.Contains(chat.MemberIDs, actorID) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
|
||||
result := make([]model.Message, len(s.messagesByChat[chatID]))
|
||||
copy(result, s.messagesByChat[chatID])
|
||||
|
||||
return result, nil
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrUsernameTaken = errors.New("username already exists")
|
||||
ErrUserNotFound = errors.New("user not found")
|
||||
)
|
||||
|
||||
type MemoryStore struct {
|
||||
mu sync.RWMutex
|
||||
|
||||
usersByID map[string]model.User
|
||||
userIDsByName map[string]string
|
||||
chatsByID map[string]model.Chat
|
||||
messagesByChat map[string][]model.Message
|
||||
}
|
||||
|
||||
func NewMemoryStore() *MemoryStore {
|
||||
return &MemoryStore{
|
||||
usersByID: make(map[string]model.User),
|
||||
userIDsByName: make(map[string]string),
|
||||
chatsByID: make(map[string]model.Chat),
|
||||
messagesByChat: make(map[string][]model.Message),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *MemoryStore) CreateUser(
|
||||
username string,
|
||||
displayName string,
|
||||
) (model.User, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
if _, exists := s.userIDsByName[username]; exists {
|
||||
return model.User{}, ErrUsernameTaken
|
||||
}
|
||||
|
||||
id, err := newUUID()
|
||||
if err != nil {
|
||||
return model.User{}, fmt.Errorf("generate user ID: %w", err)
|
||||
}
|
||||
|
||||
for {
|
||||
if _, exists := s.usersByID[id]; !exists {
|
||||
break
|
||||
}
|
||||
|
||||
id, err = newUUID()
|
||||
if err != nil {
|
||||
return model.User{}, fmt.Errorf("generate user ID: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
user := model.User{
|
||||
ID: id,
|
||||
Username: username,
|
||||
DisplayName: displayName,
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
|
||||
s.usersByID[user.ID] = user
|
||||
s.userIDsByName[user.Username] = user.ID
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (s *MemoryStore) GetUser(id string) (model.User, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
user, exists := s.usersByID[id]
|
||||
if !exists {
|
||||
return model.User{}, ErrUserNotFound
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func newUUID() (string, error) {
|
||||
var value [16]byte
|
||||
|
||||
if _, err := rand.Read(value[:]); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
value[6] = (value[6] & 0x0f) | 0x40
|
||||
value[8] = (value[8] & 0x3f) | 0x80
|
||||
|
||||
return fmt.Sprintf(
|
||||
"%x-%x-%x-%x-%x",
|
||||
value[0:4],
|
||||
value[4:6],
|
||||
value[6:8],
|
||||
value[8:10],
|
||||
value[10:16],
|
||||
), nil
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package store_test
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/store"
|
||||
)
|
||||
|
||||
func TestCreateAndGetUser(t *testing.T) {
|
||||
s := store.NewMemoryStore()
|
||||
|
||||
created, err := s.CreateUser("alice", "Алиса")
|
||||
if err != nil {
|
||||
t.Fatalf("CreateUser: %v", err)
|
||||
}
|
||||
|
||||
if created.ID == "" {
|
||||
t.Fatal("user ID is empty")
|
||||
}
|
||||
|
||||
if created.CreatedAt.IsZero() {
|
||||
t.Fatal("creation time is empty")
|
||||
}
|
||||
|
||||
found, err := s.GetUser(created.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetUser: %v", err)
|
||||
}
|
||||
|
||||
if found != created {
|
||||
t.Fatalf("stored user differs: got %+v, want %+v", found, created)
|
||||
}
|
||||
|
||||
_, err = s.GetUser("00000000-0000-4000-8000-000000000000")
|
||||
if !errors.Is(err, store.ErrUserNotFound) {
|
||||
t.Fatalf("expected ErrUserNotFound, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConcurrentDuplicateUsername(t *testing.T) {
|
||||
s := store.NewMemoryStore()
|
||||
|
||||
const clients = 10
|
||||
|
||||
start := make(chan struct{})
|
||||
results := make(chan error, clients)
|
||||
|
||||
var wg sync.WaitGroup
|
||||
|
||||
for i := 0; i < clients; i++ {
|
||||
wg.Add(1)
|
||||
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
|
||||
<-start
|
||||
_, err := s.CreateUser("alice", "Алиса")
|
||||
results <- err
|
||||
}()
|
||||
}
|
||||
|
||||
close(start)
|
||||
wg.Wait()
|
||||
close(results)
|
||||
|
||||
var created, conflicts int
|
||||
|
||||
for err := range results {
|
||||
switch {
|
||||
case err == nil:
|
||||
created++
|
||||
case errors.Is(err, store.ErrUsernameTaken):
|
||||
conflicts++
|
||||
default:
|
||||
t.Errorf("unexpected error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
if created != 1 || conflicts != clients-1 {
|
||||
t.Fatalf(
|
||||
"expected 1 creation and %d conflicts; got %d creations and %d conflicts",
|
||||
clients-1,
|
||||
created,
|
||||
conflicts,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
func OpenPostgres(ctx context.Context, passwordFile string) (*pgxpool.Pool, error) {
|
||||
password, err := os.ReadFile(passwordFile)
|
||||
if err != nil {
|
||||
return nil, errors.New("cannot read PostgreSQL password file")
|
||||
}
|
||||
secret := strings.TrimRight(string(password), "\r\n")
|
||||
if secret == "" {
|
||||
return nil, errors.New("PostgreSQL password file is empty")
|
||||
}
|
||||
|
||||
config, err := pgxpool.ParseConfig(
|
||||
"host=postgres port=5432 dbname=messenger user=messenger sslmode=disable",
|
||||
)
|
||||
if err != nil {
|
||||
return nil, errors.New("invalid PostgreSQL configuration")
|
||||
}
|
||||
config.ConnConfig.Password = secret
|
||||
config.ConnConfig.ConnectTimeout = 3 * time.Second
|
||||
config.ConnConfig.RuntimeParams["statement_timeout"] = "3000"
|
||||
config.ConnConfig.RuntimeParams["lock_timeout"] = "2000"
|
||||
config.ConnConfig.RuntimeParams["application_name"] = "messenger-lab2"
|
||||
config.MaxConns = 10
|
||||
config.MinConns = 0
|
||||
config.MaxConnLifetime = 30 * time.Minute
|
||||
config.MaxConnIdleTime = 5 * time.Minute
|
||||
|
||||
connectCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(connectCtx, config)
|
||||
if err != nil {
|
||||
return nil, errors.New("cannot create PostgreSQL pool")
|
||||
}
|
||||
if err := pool.Ping(connectCtx); err != nil {
|
||||
pool.Close()
|
||||
return nil, errors.New("PostgreSQL connection check failed")
|
||||
}
|
||||
return pool, nil
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Position struct {
|
||||
CreatedAt time.Time
|
||||
ID string
|
||||
}
|
||||
|
||||
func (s *PostgresStore) CreateChat(ctx context.Context, title string, members []string) (model.Chat, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer cancel()
|
||||
id, err := newUUID()
|
||||
if err != nil {
|
||||
return model.Chat{}, ErrUnavailable
|
||||
}
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return model.Chat{}, ErrUnavailable
|
||||
}
|
||||
defer tx.Rollback(context.Background())
|
||||
chat := model.Chat{ID: id, Title: title, MemberIDs: members}
|
||||
err = tx.QueryRow(ctx, `INSERT INTO chats(id,title) VALUES($1,$2) RETURNING created_at`, id, title).Scan(&chat.CreatedAt)
|
||||
if err != nil {
|
||||
return model.Chat{}, ErrUnavailable
|
||||
}
|
||||
for _, member := range members {
|
||||
_, err = tx.Exec(ctx, `INSERT INTO chat_members(chat_id,user_id) VALUES($1,$2)`, id, member)
|
||||
if err != nil {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && (pgErr.Code == "23503" || pgErr.Code == "23505") {
|
||||
return model.Chat{}, ErrInvalidMembers
|
||||
}
|
||||
return model.Chat{}, ErrUnavailable
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return model.Chat{}, ErrUnavailable
|
||||
}
|
||||
chat.CreatedAt = chat.CreatedAt.UTC()
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
const chatColumns = `c.id::text,c.title,c.created_at,ARRAY(SELECT m.user_id::text FROM chat_members m WHERE m.chat_id=c.id ORDER BY m.user_id)`
|
||||
|
||||
func (s *PostgresStore) GetChat(ctx context.Context, actor, id string) (model.Chat, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer cancel()
|
||||
var chat model.Chat
|
||||
err := s.pool.QueryRow(ctx, `SELECT `+chatColumns+` FROM chats c WHERE c.id=$1 AND EXISTS(SELECT 1 FROM chat_members WHERE chat_id=c.id AND user_id=$2)`, id, actor).Scan(&chat.ID, &chat.Title, &chat.CreatedAt, &chat.MemberIDs)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.Chat{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return model.Chat{}, ErrUnavailable
|
||||
}
|
||||
chat.CreatedAt = chat.CreatedAt.UTC()
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) ChatPage(ctx context.Context, actor string, limit int, after *Position) ([]model.Chat, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer cancel()
|
||||
query := `SELECT ` + chatColumns + ` FROM chats c WHERE EXISTS(SELECT 1 FROM chat_members WHERE chat_id=c.id AND user_id=$1)`
|
||||
args := []any{actor, limit}
|
||||
if after != nil {
|
||||
query += ` AND (c.created_at,c.id)>($3,$4::uuid)`
|
||||
args = append(args, after.CreatedAt, after.ID)
|
||||
}
|
||||
query += ` ORDER BY c.created_at,c.id LIMIT $2`
|
||||
rows, err := s.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
defer rows.Close()
|
||||
items := make([]model.Chat, 0)
|
||||
for rows.Next() {
|
||||
var chat model.Chat
|
||||
if err := rows.Scan(&chat.ID, &chat.Title, &chat.CreatedAt, &chat.MemberIDs); err != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
chat.CreatedAt = chat.CreatedAt.UTC()
|
||||
items = append(items, chat)
|
||||
}
|
||||
if rows.Err() != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) CreateMessage(ctx context.Context, actor, chatID, text string) (model.Message, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer cancel()
|
||||
id, err := newUUID()
|
||||
if err != nil {
|
||||
return model.Message{}, ErrUnavailable
|
||||
}
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return model.Message{}, ErrUnavailable
|
||||
}
|
||||
defer tx.Rollback(context.Background())
|
||||
// Serialize writers within a chat; timestamps strictly increase even if the clock moves backwards.
|
||||
var locked string
|
||||
err = tx.QueryRow(ctx, `SELECT c.id::text FROM chats c WHERE c.id=$1 AND EXISTS(SELECT 1 FROM chat_members WHERE chat_id=c.id AND user_id=$2) FOR UPDATE OF c`, chatID, actor).Scan(&locked)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.Message{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return model.Message{}, ErrUnavailable
|
||||
}
|
||||
var message model.Message
|
||||
err = tx.QueryRow(ctx, `INSERT INTO messages(id,chat_id,sender_id,text,created_at)
|
||||
VALUES($1,$2,$3,$4,GREATEST(clock_timestamp(),
|
||||
COALESCE((SELECT created_at + INTERVAL '1 microsecond' FROM messages WHERE chat_id=$2 ORDER BY created_at DESC,id DESC LIMIT 1),clock_timestamp())))
|
||||
RETURNING id::text,chat_id::text,sender_id::text,text,created_at`, id, chatID, actor, text).Scan(&message.ID, &message.ChatID, &message.SenderID, &message.Text, &message.CreatedAt)
|
||||
if err != nil {
|
||||
return model.Message{}, ErrUnavailable
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return model.Message{}, ErrUnavailable
|
||||
}
|
||||
message.CreatedAt = message.CreatedAt.UTC()
|
||||
return message, nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) MessagePage(ctx context.Context, chatID string, limit int, after *Position) ([]model.Message, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer cancel()
|
||||
query := `SELECT id::text,chat_id::text,sender_id::text,text,created_at FROM messages WHERE chat_id=$1`
|
||||
args := []any{chatID, limit}
|
||||
if after != nil {
|
||||
query += ` AND (created_at,id)>($3,$4::uuid)`
|
||||
args = append(args, after.CreatedAt, after.ID)
|
||||
}
|
||||
query += ` ORDER BY created_at,id LIMIT $2`
|
||||
rows, err := s.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
defer rows.Close()
|
||||
items := make([]model.Message, 0)
|
||||
for rows.Next() {
|
||||
var m model.Message
|
||||
if err := rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt); err != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
m.CreatedAt = m.CreatedAt.UTC()
|
||||
items = append(items, m)
|
||||
}
|
||||
if rows.Err() != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
var ErrSessionNotFound = errors.New("session not found")
|
||||
|
||||
func (s *PostgresStore) Credentials(ctx context.Context, username string) (model.User, string, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer cancel()
|
||||
var user model.User
|
||||
var hash string
|
||||
err := s.pool.QueryRow(ctx, `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, &hash)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.User{}, "", ErrUserNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return model.User{}, "", ErrUnavailable
|
||||
}
|
||||
user.CreatedAt = user.CreatedAt.UTC()
|
||||
return user, hash, nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) CreateSession(ctx context.Context, hash []byte, userID string, ttlSeconds int64) (time.Time, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer cancel()
|
||||
var expires time.Time
|
||||
err := s.pool.QueryRow(ctx, `INSERT INTO sessions (token_hash, user_id, expires_at)
|
||||
VALUES ($1, $2, CURRENT_TIMESTAMP + $3::bigint * INTERVAL '1 second') RETURNING expires_at`, hash, userID, ttlSeconds).Scan(&expires)
|
||||
if err != nil {
|
||||
return time.Time{}, ErrUnavailable
|
||||
}
|
||||
return expires.UTC(), nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) SessionUser(ctx context.Context, hash []byte) (model.User, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer cancel()
|
||||
var user model.User
|
||||
err := s.pool.QueryRow(ctx, `SELECT u.id::text, u.username, u.display_name, u.created_at
|
||||
FROM sessions s JOIN users u ON u.id=s.user_id
|
||||
WHERE s.token_hash=$1 AND s.expires_at > clock_timestamp()`, hash).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.User{}, ErrSessionNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return model.User{}, ErrUnavailable
|
||||
}
|
||||
user.CreatedAt = user.CreatedAt.UTC()
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) DeleteSession(ctx context.Context, hash []byte) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer cancel()
|
||||
tag, err := s.pool.Exec(ctx, `DELETE FROM sessions WHERE token_hash=$1 AND expires_at > clock_timestamp()`, hash)
|
||||
if err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return ErrSessionNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"gitflic.ru/project/d-sotnikova5/mtusi2026lab1-fork/internal/model"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
var ErrUnavailable = errors.New("storage unavailable")
|
||||
|
||||
type PostgresStore struct{ pool *pgxpool.Pool }
|
||||
|
||||
func NewPostgresStore(pool *pgxpool.Pool) *PostgresStore {
|
||||
return &PostgresStore{pool: pool}
|
||||
}
|
||||
|
||||
func (s *PostgresStore) CreateUser(ctx context.Context, username, displayName, passwordHash string) (model.User, error) {
|
||||
id, err := newUUID()
|
||||
if err != nil {
|
||||
return model.User{}, errors.New("cannot generate user ID")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer cancel()
|
||||
var user model.User
|
||||
err = s.pool.QueryRow(ctx, `
|
||||
INSERT INTO users (id, username, display_name, password_hash)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING id::text, username, display_name, created_at`,
|
||||
id, username, displayName, passwordHash,
|
||||
).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt)
|
||||
if err != nil {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Code == "23505" && pgErr.ConstraintName == "users_username_key" {
|
||||
return model.User{}, ErrUsernameTaken
|
||||
}
|
||||
return model.User{}, ErrUnavailable
|
||||
}
|
||||
user.CreatedAt = user.CreatedAt.UTC()
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (s *PostgresStore) Ping(ctx context.Context) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, time.Second)
|
||||
defer cancel()
|
||||
if err := s.pool.Ping(ctx); err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
CREATE TABLE users (
|
||||
id UUID PRIMARY KEY,
|
||||
username TEXT NOT NULL UNIQUE,
|
||||
display_name TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
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_password_hash_not_empty CHECK (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)
|
||||
);
|
||||
|
||||
CREATE TABLE chat_members (
|
||||
chat_id UUID NOT NULL REFERENCES chats(id),
|
||||
user_id UUID NOT NULL REFERENCES users(id),
|
||||
PRIMARY KEY (chat_id, user_id)
|
||||
);
|
||||
|
||||
CREATE INDEX chat_members_user_chat_idx ON chat_members (user_id, chat_id);
|
||||
|
||||
CREATE TABLE messages (
|
||||
id UUID PRIMARY KEY,
|
||||
chat_id UUID NOT NULL,
|
||||
sender_id UUID NOT NULL,
|
||||
text TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT messages_sender_membership_fk
|
||||
FOREIGN KEY (chat_id, sender_id) REFERENCES chat_members(chat_id, user_id),
|
||||
CONSTRAINT messages_text_length CHECK (char_length(text) BETWEEN 1 AND 4000)
|
||||
);
|
||||
|
||||
CREATE INDEX messages_chat_history_idx ON messages (chat_id, created_at, id);
|
||||
|
||||
CREATE TABLE sessions (
|
||||
token_hash BYTEA PRIMARY KEY,
|
||||
user_id UUID NOT NULL REFERENCES users(id),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
expires_at TIMESTAMPTZ NOT NULL,
|
||||
CONSTRAINT sessions_token_hash_length CHECK (octet_length(token_hash) = 32),
|
||||
CONSTRAINT sessions_expiry_after_creation CHECK (expires_at > created_at)
|
||||
);
|
||||
|
||||
CREATE INDEX sessions_expiry_idx ON sessions (expires_at);
|
||||
@@ -0,0 +1,23 @@
|
||||
# Миграции
|
||||
|
||||
`000001_initial.up.sql` создаёт начальную схему PostgreSQL: пять таблиц и индексы из проекта хранения. `apply.psql` применяет её через psql в контейнере. Применение на новом volume и пропуск версии при повторном запуске подтверждены [выводом пользователя](../evidence/postgres-migration.txt) от 09.10.2026. Конкурентное применение и откат при ошибке ещё не проверены.
|
||||
|
||||
`apply.psql` открывает транзакцию, получает advisory lock, применяет SQL и записывает версию в служебную таблицу в той же транзакции. При ошибке psql завершает работу благодаря ON_ERROR_STOP; незавершённая транзакция откатывается при закрытии соединения. Повторный запуск пропускает применённую версию. Конкурентные запуски используют общий ключ блокировки (2026, 2); ожидание ограничено lock_timeout. Сейчас runner явно знает только версию 1; следующую миграцию нужно будет добавить в последовательность применения.
|
||||
|
||||
Запуск из корня lab2 после готовности PostgreSQL:
|
||||
|
||||
```powershell
|
||||
docker compose exec -T postgres psql -X -U messenger -d messenger -f /migrations/apply.psql
|
||||
```
|
||||
|
||||
Локальный psql подключается внутри контейнера через Unix socket. Для будущего API будет отдельное TCP-подключение с паролем. POSTGRES_USER создаётся официальным образом как bootstrap-superuser — учебное упрощение текущего этапа.
|
||||
|
||||
Поэтому в SQL нет собственных BEGIN/COMMIT и нет CREATE TABLE IF NOT EXISTS: ответственность за однократное применение лежит на runner. IF NOT EXISTS не проверяет соответствие существующей таблицы ожидаемой схеме. После применения версии дальнейшие изменения оформляются новой миграцией.
|
||||
|
||||
UUID передаёт приложение. created_at имеет значение по умолчанию CURRENT_TIMESTAMP (время начала транзакции PostgreSQL); при равном времени порядок задаёт id. TIMESTAMPTZ хранит момент времени, формат UTC для API задаёт приложение. База должна использовать UTF-8, чтобы char_length соответствовал подсчёту Unicode code points в контракте.
|
||||
|
||||
CHECK ограничивает длины строк, но не заменяет проверку строк из одних Unicode-пробелов в Go. Проверка password_hash на непустоту не доказывает применение KDF; формирование и проверка Argon2id будут реализованы в приложении. token_hash хранит 32 байта SHA-256, не строку из 64 шестнадцатеричных символов.
|
||||
|
||||
Внешний ключ messages(chat_id, sender_id) гарантирует существование членства отправителя. Он не заменяет проверку прав пользователя HTTP-запроса. Каскадное удаление не включено; удаления пользователей, чатов и участников обязательным API lab2 не предусмотрены.
|
||||
|
||||
CHECK expires_at > created_at проверяет корректность срока, но не делает сессию автоматически недействительной: каждый защищённый запрос должен проверять expires_at относительно текущего времени. Удаление истёкших строк — отдельная очистка.
|
||||
@@ -0,0 +1,27 @@
|
||||
\set ON_ERROR_STOP on
|
||||
|
||||
BEGIN;
|
||||
SET LOCAL lock_timeout = '10s';
|
||||
SET LOCAL statement_timeout = '30s';
|
||||
|
||||
-- All migration runners for this application must use this same lock key.
|
||||
SELECT pg_advisory_xact_lock(2026, 2);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version BIGINT PRIMARY KEY,
|
||||
applied_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
SELECT EXISTS (
|
||||
SELECT 1 FROM schema_migrations WHERE version = 1
|
||||
) AS initial_applied \gset
|
||||
|
||||
\if :initial_applied
|
||||
\echo 'Migration 000001 already applied; skipping.'
|
||||
\else
|
||||
\ir 000001_initial.up.sql
|
||||
INSERT INTO schema_migrations (version) VALUES (1);
|
||||
\echo 'Migration 000001 applied (commit follows).'
|
||||
\endif
|
||||
|
||||
COMMIT;
|
||||
@@ -0,0 +1,27 @@
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
$repoRoot = Split-Path -Parent $PSScriptRoot
|
||||
$secretsDirectory = Join-Path $repoRoot 'secrets'
|
||||
$passwordPath = Join-Path $secretsDirectory 'postgres_password.txt'
|
||||
|
||||
New-Item -ItemType Directory -Path $secretsDirectory -Force | Out-Null
|
||||
|
||||
if (Test-Path -LiteralPath $passwordPath) {
|
||||
if ((Get-Item -LiteralPath $passwordPath).Length -eq 0) {
|
||||
throw 'Existing password file is empty. Supply a local password before starting PostgreSQL.'
|
||||
}
|
||||
Write-Output 'Existing PostgreSQL password preserved.'
|
||||
exit 0
|
||||
}
|
||||
|
||||
$randomBytes = New-Object byte[] 32
|
||||
$generator = [System.Security.Cryptography.RandomNumberGenerator]::Create()
|
||||
try {
|
||||
$generator.GetBytes($randomBytes)
|
||||
} finally {
|
||||
$generator.Dispose()
|
||||
}
|
||||
|
||||
$password = [Convert]::ToBase64String($randomBytes)
|
||||
[System.IO.File]::WriteAllText($passwordPath, $password, [System.Text.Encoding]::ASCII)
|
||||
Write-Output 'Local PostgreSQL password created in secrets/ (value not printed).'
|
||||
@@ -0,0 +1,3 @@
|
||||
@echo off
|
||||
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0restart.ps1"
|
||||
exit /b %errorlevel%
|
||||
@@ -0,0 +1,44 @@
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Set-Location (Split-Path -Parent $PSScriptRoot)
|
||||
|
||||
function Read-Containers {
|
||||
$result = @()
|
||||
foreach ($service in @('api', 'postgres')) {
|
||||
$containerID = docker compose ps -q $service
|
||||
if ($LASTEXITCODE -ne 0 -or -not $containerID) { throw "Cannot find $service container" }
|
||||
$json = docker inspect --format '{{json .}}' $containerID
|
||||
if ($LASTEXITCODE -ne 0) { throw "Cannot inspect $service container" }
|
||||
$container = $json | ConvertFrom-Json
|
||||
# Only retain safe lifecycle fields; never write Config.Env or secrets.
|
||||
$result += [pscustomobject]@{
|
||||
service = $service
|
||||
id = $container.Id
|
||||
started_at = $container.State.StartedAt
|
||||
status = $container.State.Status
|
||||
data_volumes = @($container.Mounts | Where-Object Type -eq 'volume' | ForEach-Object Name)
|
||||
}
|
||||
}
|
||||
return $result
|
||||
}
|
||||
|
||||
$before = @(Read-Containers)
|
||||
docker compose stop api postgres
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Stop failed' }
|
||||
docker compose up -d --wait postgres
|
||||
if ($LASTEXITCODE -ne 0) { throw 'PostgreSQL restart failed' }
|
||||
docker compose up -d --wait api
|
||||
if ($LASTEXITCODE -ne 0) { throw 'API restart failed' }
|
||||
$after = @(Read-Containers)
|
||||
foreach ($old in $before) {
|
||||
$new = $after | Where-Object service -eq $old.service
|
||||
if ($new.started_at -eq $old.started_at -or $new.status -ne 'running') {
|
||||
throw "Restart not confirmed for $($old.service)"
|
||||
}
|
||||
if (($new.data_volumes -join ',') -ne ($old.data_volumes -join ',')) {
|
||||
throw "Volume changed for $($old.service)"
|
||||
}
|
||||
}
|
||||
$evidence = [ordered]@{ before = $before; after = $after; volumes_preserved = $true }
|
||||
$path = Join-Path $PWD 'evidence/restart-containers.json'
|
||||
[System.IO.File]::WriteAllText($path, ($evidence | ConvertTo-Json -Depth 5), [System.Text.UTF8Encoding]::new($false))
|
||||
Write-Output 'PASS: API and PostgreSQL restarted; named volumes preserved.'
|
||||
Executable
+18
@@ -0,0 +1,18 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
snapshot() {
|
||||
for service in api postgres; do
|
||||
id=$(docker compose ps -q "$service")
|
||||
test -n "$id"
|
||||
docker inspect --format '{{.Name}} {{.Id}} {{.State.StartedAt}} {{.State.Status}} {{range .Mounts}}{{if eq .Type "volume"}}{{.Name}} {{end}}{{end}}' "$id"
|
||||
done
|
||||
}
|
||||
|
||||
snapshot > evidence/restart-containers-before.txt
|
||||
docker compose stop api postgres
|
||||
docker compose up -d --wait postgres
|
||||
docker compose up -d --wait api
|
||||
snapshot > evidence/restart-containers-after.txt
|
||||
printf '%s\n' 'API and PostgreSQL restarted without removing volumes.'
|
||||
@@ -0,0 +1,21 @@
|
||||
import subprocess
|
||||
import uuid
|
||||
from sessions import request, basic
|
||||
|
||||
suffix = uuid.uuid4().hex[:20]
|
||||
username = "rollback_" + suffix
|
||||
secret = "учебный:пароль:rollback"
|
||||
user = request("POST", "/users", 201, {"username": username, "display_name": "Rollback", "password": secret})
|
||||
session = request("POST", "/auth/sessions", 201, headers=basic(username, secret))
|
||||
headers = {"Authorization": "Bearer " + session["token"]}
|
||||
title = "rollback_" + suffix
|
||||
request("POST", "/chats", 400, {"title": title, "member_ids": [user["id"], str(uuid.uuid4())]}, headers)
|
||||
# title contains only a fixed prefix and locally generated hex characters.
|
||||
sql = "SELECT count(*) FROM chats WHERE title='" + title + "';"
|
||||
result = subprocess.run(
|
||||
["docker", "compose", "exec", "-T", "postgres", "psql", "-X", "-U", "messenger", "-d", "messenger", "-At", "-c", sql],
|
||||
check=True, capture_output=True, text=True,
|
||||
)
|
||||
assert result.stdout.strip() == "0", "failed chat creation left a row in PostgreSQL"
|
||||
request("DELETE", "/auth/sessions/current", 204, headers=headers)
|
||||
print("PASS: unknown second member -> 400; no chat row remains in PostgreSQL (rollback)")
|
||||
@@ -0,0 +1,54 @@
|
||||
import concurrent.futures
|
||||
import json
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
BASE = "http://localhost:8080"
|
||||
|
||||
|
||||
def register(body):
|
||||
request = urllib.request.Request(
|
||||
BASE + "/api/v1/users",
|
||||
data=json.dumps(body).encode("utf-8"),
|
||||
headers={"Content-Type": "application/json"},
|
||||
method="POST",
|
||||
)
|
||||
try:
|
||||
response = urllib.request.urlopen(request, timeout=15)
|
||||
except urllib.error.HTTPError as error:
|
||||
response = error
|
||||
with response:
|
||||
data = json.load(response)
|
||||
assert response.headers.get("X-Request-Id"), "missing request ID"
|
||||
assert "password" not in data and "password_hash" not in data, "secret in response"
|
||||
return response.status, data
|
||||
|
||||
|
||||
def main():
|
||||
username = "reg_" + uuid.uuid4().hex[:20]
|
||||
body = {"username": username, "display_name": "Проверка регистрации", "password": "учебный:пароль"}
|
||||
status, user = register(body)
|
||||
assert status == 201, f"registration status={status}"
|
||||
assert set(user) == {"id", "username", "display_name", "created_at"}
|
||||
assert user["username"] == username and user["display_name"] == body["display_name"]
|
||||
uuid.UUID(user["id"])
|
||||
assert user["created_at"].endswith("Z"), "created_at must be UTC"
|
||||
print("PASS: registration 201, public User fields only")
|
||||
assert register(body)[0] == 409, "duplicate username must return 409"
|
||||
print("PASS: duplicate username 409")
|
||||
invalid = dict(body, username="bad_" + uuid.uuid4().hex[:20], password="short")
|
||||
assert register(invalid)[0] == 400, "short password must return 400"
|
||||
del invalid["password"]
|
||||
assert register(invalid)[0] == 400, "missing password must return 400"
|
||||
print("PASS: short and missing passwords 400")
|
||||
concurrent_body = dict(body, username="race_" + uuid.uuid4().hex[:20])
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
|
||||
results = list(executor.map(register, [concurrent_body, concurrent_body]))
|
||||
assert sorted(status for status, _ in results) == [201, 409], "registration race failed"
|
||||
print("PASS: concurrent same username -> 201 and 409")
|
||||
print("Created username for SQL inspection:", username)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,92 @@
|
||||
import argparse
|
||||
import base64
|
||||
import datetime
|
||||
import json
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
|
||||
def request(method, path, expected, body=None, headers=None):
|
||||
outgoing = dict(headers or {})
|
||||
data = None
|
||||
if body is not None:
|
||||
outgoing["Content-Type"] = "application/json"
|
||||
data = json.dumps(body).encode("utf-8")
|
||||
req = urllib.request.Request("http://localhost:8080/api/v1" + path, data=data, headers=outgoing, method=method)
|
||||
try:
|
||||
response = urllib.request.urlopen(req, timeout=15)
|
||||
except urllib.error.HTTPError as error:
|
||||
response = error
|
||||
with response:
|
||||
raw = response.read()
|
||||
assert response.status == expected, f"{method} {path}: expected {expected}, got {response.status}"
|
||||
request_id = response.headers.get("X-Request-Id")
|
||||
assert request_id, "missing request ID"
|
||||
result = json.loads(raw) if raw else None
|
||||
if expected == 401:
|
||||
challenge = 'Basic realm="messenger", charset="UTF-8"' if path == "/auth/sessions" else 'Bearer realm="messenger"'
|
||||
assert response.headers.get("WWW-Authenticate") == challenge, "wrong auth challenge"
|
||||
assert result["error"]["request_id"] == request_id
|
||||
if expected == 204:
|
||||
assert raw == b"", "logout must have empty body"
|
||||
return result
|
||||
|
||||
|
||||
def basic(username, password):
|
||||
encoded = base64.b64encode((username + ":" + password).encode("utf-8")).decode("ascii")
|
||||
return {"Authorization": "Basic " + encoded}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--expiry", action="store_true", help="Requires API SESSION_TTL_SECONDS=2")
|
||||
args = parser.parse_args()
|
||||
username = "session_" + uuid.uuid4().hex[:20]
|
||||
password = "учебный:пароль:сессии"
|
||||
user = request("POST", "/users", 201, {"username": username, "display_name": "Сессии", "password": password})
|
||||
credentials = basic(username, password)
|
||||
request("POST", "/auth/sessions", 401, headers=basic(username, "неправильный:пароль"))
|
||||
request("POST", "/auth/sessions", 401, headers=basic("missing_" + uuid.uuid4().hex[:20], password))
|
||||
request("POST", "/auth/sessions", 401)
|
||||
request("POST", "/auth/sessions", 400, body={}, headers=credentials)
|
||||
print("PASS: wrong/missing credentials 401; login JSON body 400")
|
||||
|
||||
session = request("POST", "/auth/sessions", 201, headers=credentials)
|
||||
assert set(session) == {"token", "token_type", "expires_at", "user"}
|
||||
assert session["token_type"] == "Bearer" and session["user"] == user
|
||||
assert len(base64.urlsafe_b64decode(session["token"] + "=")) == 32
|
||||
assert session["expires_at"].endswith("Z")
|
||||
bearer = {"Authorization": "Bearer " + session["token"]}
|
||||
if args.expiry:
|
||||
expires = datetime.datetime.fromisoformat(session["expires_at"].replace("Z", "+00:00"))
|
||||
remaining = (expires - datetime.datetime.now(datetime.timezone.utc)).total_seconds()
|
||||
assert 0 < remaining <= 3, "Run API with SESSION_TTL_SECONDS=2"
|
||||
request("GET", "/users/me", 200, headers=bearer)
|
||||
time.sleep(remaining + 0.3)
|
||||
request("GET", "/users/me", 401, headers=bearer)
|
||||
request("DELETE", "/auth/sessions/current", 401, headers=bearer)
|
||||
print("PASS: short TTL session works before expiry and returns 401 after expiry")
|
||||
return
|
||||
|
||||
assert request("GET", "/users/me", 200, headers=bearer) == user
|
||||
spoofed = dict(bearer, **{"X-User-Id": str(uuid.uuid4())})
|
||||
assert request("GET", "/users/me", 200, headers=spoofed) == user
|
||||
request("GET", "/users/me", 401, headers={"X-User-Id": user["id"]})
|
||||
request("GET", "/users/me", 401, headers=credentials)
|
||||
request("GET", "/users/me", 401, headers={"Authorization": "Bearer " + "A" * 43})
|
||||
print("PASS: Bearer identifies user; X-User-Id and Basic give no access")
|
||||
other = request("POST", "/auth/sessions", 201, headers=credentials)
|
||||
assert other["token"] != session["token"]
|
||||
request("DELETE", "/auth/sessions/current", 204, headers=bearer)
|
||||
request("GET", "/users/me", 401, headers=bearer)
|
||||
request("DELETE", "/auth/sessions/current", 401, headers=bearer)
|
||||
other_bearer = {"Authorization": "Bearer " + other["token"]}
|
||||
request("GET", "/users/me", 200, headers=other_bearer)
|
||||
request("DELETE", "/auth/sessions/current", 204, headers=other_bearer)
|
||||
print("PASS: logout 204; revoked token 401; other session remains valid")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user