From 13ee5a0e56b23765d666491ab8165b9be6dc3f88 Mon Sep 17 00:00:00 2001 From: d1frend Date: Sun, 18 Oct 2026 15:05:51 +0300 Subject: [PATCH] =?UTF-8?q?=D0=BF=D0=B5=D1=80=D0=B5=D0=BD=D0=BE=D1=81=20?= =?UTF-8?q?=D0=BB=D0=B0=D0=B1=D1=8B=202?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env.example | 39 +- Dockerfile | 33 + Makefile | 106 ++- cmd/server/main.go | 193 ++++++ compose.yaml | 160 +++++ go.mod | 21 + go.sum | 43 ++ internal/cache/chat.go | 175 +++++ internal/config/config.go | 343 +++++++++ internal/database/postgres.go | 40 ++ internal/domain/models.go | 256 +++++++ internal/security/password.go | 164 +++++ internal/security/password_test.go | 105 +++ internal/security/token.go | 32 + internal/security/token_test.go | 35 + internal/store/cached_repository.go | 98 +++ internal/store/cached_repository_test.go | 181 +++++ internal/store/errors.go | 9 + internal/store/memory.go | 345 ++++++++++ internal/store/memory_repository.go | 247 +++++++ internal/store/postgres.go | 40 ++ internal/store/postgres_chats.go | 306 +++++++++ internal/store/postgres_messages.go | 220 ++++++ internal/store/postgres_sessions.go | 108 +++ internal/store/postgres_users.go | 144 ++++ internal/store/repository.go | 80 +++ internal/transport/http/handlers/chats.go | 168 +++++ internal/transport/http/handlers/handler.go | 149 ++++ internal/transport/http/handlers/health.go | 62 ++ internal/transport/http/handlers/messages.go | 159 +++++ internal/transport/http/handlers/sessions.go | 165 +++++ internal/transport/http/handlers/users.go | 113 +++ internal/transport/http/middleware/auth.go | 117 ++++ internal/transport/http/middleware/logger.go | 44 ++ .../transport/http/middleware/recovery.go | 28 + .../transport/http/middleware/request_id.go | 35 + internal/transport/http/response/response.go | 63 ++ migrations/000001_initial.down.sql | 9 + migrations/000001_initial.up.sql | 112 +++ scripts/restart.sh | 15 + student_tests/auth_test.go | 352 ++++++++++ student_tests/cursor_concurrency_test.go | 401 +++++++++++ student_tests/messenger_test.go | 649 ++++++++++++++++++ student_tests/request_validation_test.go | 246 +++++++ 44 files changed, 6402 insertions(+), 8 deletions(-) create mode 100644 Dockerfile create mode 100644 cmd/server/main.go create mode 100644 compose.yaml create mode 100644 go.mod create mode 100644 go.sum create mode 100644 internal/cache/chat.go create mode 100644 internal/config/config.go create mode 100644 internal/database/postgres.go create mode 100644 internal/domain/models.go create mode 100644 internal/security/password.go create mode 100644 internal/security/password_test.go create mode 100644 internal/security/token.go create mode 100644 internal/security/token_test.go create mode 100644 internal/store/cached_repository.go create mode 100644 internal/store/cached_repository_test.go create mode 100644 internal/store/errors.go create mode 100644 internal/store/memory.go create mode 100644 internal/store/memory_repository.go create mode 100644 internal/store/postgres.go create mode 100644 internal/store/postgres_chats.go create mode 100644 internal/store/postgres_messages.go create mode 100644 internal/store/postgres_sessions.go create mode 100644 internal/store/postgres_users.go create mode 100644 internal/store/repository.go create mode 100644 internal/transport/http/handlers/chats.go create mode 100644 internal/transport/http/handlers/handler.go create mode 100644 internal/transport/http/handlers/health.go create mode 100644 internal/transport/http/handlers/messages.go create mode 100644 internal/transport/http/handlers/sessions.go create mode 100644 internal/transport/http/handlers/users.go create mode 100644 internal/transport/http/middleware/auth.go create mode 100644 internal/transport/http/middleware/logger.go create mode 100644 internal/transport/http/middleware/recovery.go create mode 100644 internal/transport/http/middleware/request_id.go create mode 100644 internal/transport/http/response/response.go create mode 100644 migrations/000001_initial.down.sql create mode 100644 migrations/000001_initial.up.sql create mode 100755 scripts/restart.sh create mode 100644 student_tests/auth_test.go create mode 100644 student_tests/cursor_concurrency_test.go create mode 100644 student_tests/messenger_test.go create mode 100644 student_tests/request_validation_test.go diff --git a/.env.example b/.env.example index d32b9be..b5f876f 100644 --- a/.env.example +++ b/.env.example @@ -1,13 +1,42 @@ # Copy to .env for your LOCAL synthetic test environment; never commit .env. -# These are logical interface suggestions; map actual framework names in REPORT.md. +# The transferred lab2 baseline still needs its Compose topology adapted to lab3. + APP_HOST=0.0.0.0 APP_PORT=8080 APP_ENV=lab + +POSTGRES_USER=messenger +POSTGRES_DB=messenger + SESSION_TTL_SECONDS=3600 -# Choose credentials locally. File paths contain no secret values. -DATABASE_URL_FILE=/run/secrets/database_url -# Optional on 3, required use on 4 in lab2; Redis OR Valkey: SESSION_STORE=postgres -CACHE_URL_FILE=/run/secrets/cache_url + API_REPLICAS=2 IDEMPOTENCY_TTL_SECONDS=86400 + +# File paths contain no secret values. Create the referenced local secret files +# according to REPORT.md; never commit their contents. +DATABASE_URL_FILE=/run/secrets/database_url + +DB_MAX_CONNS=10 +DB_MIN_CONNS=2 +DB_MAX_CONN_LIFETIME=30m +DB_MAX_CONN_IDLE_TIME=5m +DB_HEALTH_CHECK_PERIOD=30s +DB_CONNECT_TIMEOUT=5s +DB_QUERY_TIMEOUT=3s + +READINESS_TIMEOUT=2s +SHUTDOWN_TIMEOUT=10s + +# Redis stores a disposable shared chat cache; PostgreSQL remains authoritative. +# The Go config accepts CACHE_URL or CACHE_URL_FILE, but never both. The +# transferred Compose baseline currently passes CACHE_URL directly. +CACHE_URL=redis://redis:6379/0 +# CACHE_URL_FILE=/run/secrets/cache_url +CACHE_TTL=5m +CACHE_OPERATION_TIMEOUT=250ms +CACHE_POOL_SIZE=10 + +# Optional Redis Insight profile from the transferred baseline. +REDIS_INSIGHT_PORT=5540 diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..a62b7bc --- /dev/null +++ b/Dockerfile @@ -0,0 +1,33 @@ +FROM golang:1.27.1-alpine@sha256:8a5910f31396cd4d89662f56c68b3ae31d374308270a1c3bd96672ee5ed43414 AS builder + +WORKDIR /build + +COPY go.mod go.sum ./ +RUN go mod download + +COPY cmd/ ./cmd/ +COPY internal/ ./internal/ + + +RUN CGO_ENABLED=0 GOOS=linux go build -trimpath -ldflags="-w -s" -o /build/server ./cmd/server/main.go + +FROM alpine:3.24@sha256:294b683cb724975bec92580e1e685676bd4b50bda910ddb8c51d4cabeaec77e6 + +RUN addgroup -g 1000 appgroup && \ + adduser -u 1000 -G appgroup -s /bin/sh -D appuser + +WORKDIR /app + +COPY --from=builder /build/server /app/server + +RUN chown -R appuser:appgroup /app + +USER appuser:appgroup + +EXPOSE 8080 + +HEALTHCHECK --interval=5s --timeout=3s --start-period=5s --retries=10 \ + CMD wget -qO- http://127.0.0.1:8080/health/ready || exit 1 + + +ENTRYPOINT ["/app/server"] \ No newline at end of file diff --git a/Makefile b/Makefile index 5d86d17..b39d9e0 100644 --- a/Makefile +++ b/Makefile @@ -1,13 +1,93 @@ +GO ?= go PYTHON ?= python3 +COMPOSE ?= docker compose + +ENV_FILE ?= .env BASE_URL ?= http://localhost:8080 CA_FILE ?= ACTION_SCRIPT ?= -TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",) -.PHONY: help check validate test load test-persistence test-failover +TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",) +COMPOSE_CMD = $(COMPOSE) --env-file "$(ENV_FILE)" + +.PHONY: \ + help \ + init-env \ + fmt \ + fmt-check \ + build \ + go-test \ + go-race \ + go-vet \ + go-check \ + check \ + validate \ + test \ + load \ + test-persistence \ + test-failover \ + compose-config \ + compose-build \ + compose-up \ + compose-down \ + compose-ps \ + compose-logs help: - @echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes" + @echo "init-env: create local .env from .env.example if missing" + @echo "fmt: format Go source files" + @echo "fmt-check: report unformatted Go source files" + @echo "build: compile the API" + @echo "go-test: run Go tests" + @echo "go-race: run Go tests with race detector" + @echo "go-vet: run static Go analysis" + @echo "go-check: run formatting, tests, race detector and vet" + @echo "check: run offline skeleton checks" + @echo "validate: validate the OpenAPI contract" + @echo "test: run public smoke test against the LB entrypoint" + @echo "load: run synthetic writes against the LB entrypoint" + @echo "test-persistence: run persistence test with ACTION_SCRIPT" + @echo "test-failover: run replica failover test with ACTION_SCRIPT" + @echo "compose-config: validate resolved Compose configuration" + @echo "compose-build: build application images" + @echo "compose-up: start the stack" + @echo "compose-down: stop the stack without deleting volumes" + @echo "compose-ps: show stack containers" + @echo "compose-logs: follow stack logs" + +init-env: + @if [ -f "$(ENV_FILE)" ]; then \ + echo "$(ENV_FILE) already exists; leaving it unchanged"; \ + else \ + cp .env.example "$(ENV_FILE)"; \ + echo "Created $(ENV_FILE) from .env.example"; \ + fi + +fmt: + $(GO) fmt ./... + +fmt-check: + @files="$$(find cmd internal student_tests -type f -name '*.go' -print)"; \ + unformatted="$$(gofmt -l $$files)"; \ + if [ -n "$$unformatted" ]; then \ + echo "Unformatted Go files:"; \ + echo "$$unformatted"; \ + exit 1; \ + fi + +build: + $(GO) build ./cmd/server + +go-test: + $(GO) test ./... + +go-race: + $(GO) test -race ./... + +go-vet: + $(GO) vet ./... + +go-check: fmt-check go-test go-race go-vet check: $(PYTHON) scripts/check_contract.py @@ -28,3 +108,23 @@ test-persistence: test-failover: @test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable stop-one hook"; exit 2) $(PYTHON) tests/resilience.py --mode failover --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS) + +compose-config: + @test -f "$(ENV_FILE)" || \ + (echo "$(ENV_FILE) is missing; run: make init-env"; exit 2) + $(COMPOSE_CMD) config --quiet + +compose-build: + $(COMPOSE_CMD) build + +compose-up: + $(COMPOSE_CMD) up -d --build + +compose-down: + $(COMPOSE_CMD) down + +compose-ps: + $(COMPOSE_CMD) ps + +compose-logs: + $(COMPOSE_CMD) logs --follow diff --git a/cmd/server/main.go b/cmd/server/main.go new file mode 100644 index 0000000..6fea252 --- /dev/null +++ b/cmd/server/main.go @@ -0,0 +1,193 @@ +package main + +import ( + "context" + "errors" + "log" + "net/http" + "os" + "os/signal" + "syscall" + "time" + + applicationCache "mtusi2026lab3/internal/cache" + "mtusi2026lab3/internal/config" + "mtusi2026lab3/internal/database" + "mtusi2026lab3/internal/store" + "mtusi2026lab3/internal/transport/http/handlers" + "mtusi2026lab3/internal/transport/http/middleware" +) + +func main() { + cfg, err := config.Load() + if err != nil { + log.Fatalf("[FATAL] Invalid configuration: %v", err) + } + + startupContext, startupCancel := context.WithTimeout( + context.Background(), + cfg.DatabaseConnectTimeout, + ) + + databasePool, err := database.Open(startupContext, cfg) + startupCancel() + + if err != nil { + log.Fatalf("[FATAL] PostgreSQL initialization failed: %v", err) + } + defer databasePool.Close() + + postgresStore := store.NewPostgreSQLStore( + databasePool, + cfg.DatabaseQueryTimeout, + ) + + var applicationStore store.Repository = postgresStore + + if cfg.RedisURL != "" { + redisChatCache, cacheError := applicationCache.NewRedisChatCache( + cfg.RedisURL, + cfg.RedisCacheTTL, + cfg.RedisOperationTimeout, + cfg.RedisPoolSize, + ) + if cacheError != nil { + log.Fatalf("[FATAL] Invalid Redis configuration: %v", cacheError) + } + defer func() { + if closeError := redisChatCache.Close(); closeError != nil { + log.Printf("[WARN] Redis client close failed: %v", closeError) + } + }() + + cacheContext, cacheCancel := context.WithTimeout( + context.Background(), + cfg.RedisOperationTimeout, + ) + if cacheError = redisChatCache.Ping(cacheContext); cacheError != nil { + log.Printf("[WARN] Redis unavailable at startup; PostgreSQL fallback is active: %v", cacheError) + } else { + log.Println("[INFO] Redis chat cache is available") + } + cacheCancel() + + applicationStore = store.NewCachedRepository( + postgresStore, + redisChatCache, + log.Default(), + ) + } + + handler := handlers.NewHandler( + applicationStore, + handlers.WithReadiness( + databasePool, + cfg.ReadinessTimeout, + ), + handlers.WithSessionTTL(cfg.SessionTTL), + ) + + mux := http.NewServeMux() + + mux.HandleFunc("GET /health/live", handler.HealthLive) + mux.HandleFunc("GET /health/ready", handler.HealthReady) + + mux.HandleFunc( + "POST /api/v1/auth/sessions", + handler.CreateSession, + ) + + mux.HandleFunc("POST /api/v1/users", handler.CreateUser) + + requireAuth := func(next http.HandlerFunc) http.HandlerFunc { + return middleware.RequireAuth(postgresStore, next) + } + + mux.HandleFunc( + "GET /api/v1/users/me", + requireAuth(handler.GetMe), + ) + + mux.HandleFunc( + "DELETE /api/v1/auth/sessions/current", + requireAuth(handler.DeleteCurrentSession), + ) + + mux.HandleFunc( + "POST /api/v1/chats", + requireAuth(handler.CreateChat), + ) + mux.HandleFunc( + "GET /api/v1/chats", + requireAuth(handler.ListChats), + ) + mux.HandleFunc( + "GET /api/v1/chats/{chat_id}", + requireAuth(handler.GetChat), + ) + mux.HandleFunc( + "POST /api/v1/chats/{chat_id}/messages", + requireAuth(handler.CreateMessage), + ) + mux.HandleFunc( + "GET /api/v1/chats/{chat_id}/messages", + requireAuth(handler.GetMessages), + ) + + var rootHandler http.Handler = mux + rootHandler = middleware.Recovery(rootHandler) + rootHandler = middleware.Logger(rootHandler) + rootHandler = middleware.RequestID(rootHandler) + + server := &http.Server{ + Addr: cfg.HTTPAddress(), + Handler: rootHandler, + ReadTimeout: 15 * time.Second, + WriteTimeout: 15 * time.Second, + IdleTimeout: 60 * time.Second, + } + + serverErrors := make(chan error, 1) + + go func() { + log.Printf("[INFO] Server starting on %s", server.Addr) + serverErrors <- server.ListenAndServe() + }() + + shutdownSignals := make(chan os.Signal, 1) + signal.Notify( + shutdownSignals, + os.Interrupt, + syscall.SIGTERM, + ) + defer signal.Stop(shutdownSignals) + + select { + case serverError := <-serverErrors: + if !errors.Is(serverError, http.ErrServerClosed) { + log.Fatalf("[FATAL] Server crashed: %v", serverError) + } + + case signalValue := <-shutdownSignals: + log.Printf( + "[INFO] Signal %v received. Starting graceful shutdown...", + signalValue, + ) + + shutdownContext, shutdownCancel := context.WithTimeout( + context.Background(), + cfg.ShutdownTimeout, + ) + defer shutdownCancel() + + if err := server.Shutdown(shutdownContext); err != nil { + log.Printf( + "[WARN] Graceful shutdown failed: %v. Forcing close.", + err, + ) + _ = server.Close() + } + + log.Println("[INFO] Server stopped gracefully.") + } +} diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 0000000..5d8c855 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,160 @@ +services: + postgres: + image: postgres:16.15-alpine3.24@sha256:721873c34ceb9f8d8fc265984940dc982404c105f19ad51be9fdc5970a6080ea + environment: + POSTGRES_USER: ${POSTGRES_USER:-messenger} + POSTGRES_DB: ${POSTGRES_DB:-messenger} + POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password + secrets: + - postgres_password + volumes: + - postgres_data:/var/lib/postgresql/data + healthcheck: + test: + [ + "CMD-SHELL", + "pg_isready -U ${POSTGRES_USER:-messenger} -d ${POSTGRES_DB:-messenger}", + ] + interval: 5s + timeout: 3s + retries: 10 + start_period: 5s + restart: unless-stopped + + redis: + image: redis:8.10.2-alpine3.23@sha256:3811787313eba226a2ef38658c6ccb91cd5e110edc89c37767de373120a0e5a0 + command: + [ + "redis-server", + "--save", + "", + "--appendonly", + "no", + "--maxmemory", + "64mb", + "--maxmemory-policy", + "allkeys-lru", + ] + healthcheck: + test: ["CMD", "redis-cli", "ping"] + interval: 5s + timeout: 3s + retries: 10 + start_period: 3s + stop_grace_period: 10s + restart: unless-stopped + + migrate: + image: migrate/migrate:v4.20.1@sha256:76cc2074cb6642631f34a898ced71e6aeaa6b1a4d78c4daa743275a22e0c5be7 + entrypoint: ["/bin/sh", "-ec"] + command: + - > + exec migrate + -path=/migrations + -database="$$(cat /run/secrets/database_url)" + up + secrets: + - database_url + volumes: + - ./migrations:/migrations:ro + depends_on: + postgres: + condition: service_healthy + restart: "no" + + api: + build: + context: . + dockerfile: Dockerfile + environment: + APP_HOST: ${APP_HOST:-0.0.0.0} + APP_PORT: ${APP_PORT:-8080} + APP_ENV: ${APP_ENV:-lab} + + SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} + SESSION_STORE: ${SESSION_STORE:-postgres} + + CACHE_URL: ${CACHE_URL:-redis://redis:6379/0} + CACHE_TTL: ${CACHE_TTL:-5m} + CACHE_OPERATION_TIMEOUT: ${CACHE_OPERATION_TIMEOUT:-250ms} + CACHE_POOL_SIZE: ${CACHE_POOL_SIZE:-10} + + DATABASE_URL_FILE: ${DATABASE_URL_FILE:-/run/secrets/database_url} + + DB_MAX_CONNS: ${DB_MAX_CONNS:-10} + DB_MIN_CONNS: ${DB_MIN_CONNS:-2} + DB_MAX_CONN_LIFETIME: ${DB_MAX_CONN_LIFETIME:-30m} + DB_MAX_CONN_IDLE_TIME: ${DB_MAX_CONN_IDLE_TIME:-5m} + DB_HEALTH_CHECK_PERIOD: ${DB_HEALTH_CHECK_PERIOD:-30s} + DB_CONNECT_TIMEOUT: ${DB_CONNECT_TIMEOUT:-5s} + DB_QUERY_TIMEOUT: ${DB_QUERY_TIMEOUT:-3s} + + READINESS_TIMEOUT: ${READINESS_TIMEOUT:-2s} + SHUTDOWN_TIMEOUT: ${SHUTDOWN_TIMEOUT:-10s} + secrets: + - database_url + ports: + - "${APP_PORT:-8080}:${APP_PORT:-8080}" + depends_on: + postgres: + condition: service_healthy + migrate: + condition: service_completed_successfully + healthcheck: + test: + [ + "CMD-SHELL", + "wget -qO- http://127.0.0.1:$${APP_PORT:-8080}/health/ready || exit 1", + ] + interval: 5s + timeout: 3s + retries: 10 + start_period: 5s + stop_grace_period: 15s + restart: unless-stopped + + redis-insight: + image: redis/redisinsight:3.8.0@sha256:b5e19ee240abef6edb435871b90ff8a210995422e8e018ab61c0339d318a1f84 + profiles: ["tools"] + ports: + - "127.0.0.1:${REDIS_INSIGHT_PORT:-5540}:5540" + volumes: + - redis_insight_data:/data + depends_on: + redis: + condition: service_healthy + restart: unless-stopped + + postgres-restore: + image: postgres:16.15-alpine3.24@sha256:721873c34ceb9f8d8fc265984940dc982404c105f19ad51be9fdc5970a6080ea + profiles: ["recovery"] + environment: + POSTGRES_USER: ${POSTGRES_USER:-messenger} + POSTGRES_DB: ${POSTGRES_RESTORE_DB:-messenger_restore_admin} + POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password + secrets: + - postgres_password + volumes: + - postgres_restore_data:/var/lib/postgresql/data + healthcheck: + test: + [ + "CMD-SHELL", + "pg_isready -U ${POSTGRES_USER:-messenger} -d ${POSTGRES_RESTORE_DB:-messenger_restore_admin}", + ] + interval: 5s + timeout: 3s + retries: 10 + start_period: 5s + restart: "no" + +volumes: + postgres_data: + redis_insight_data: + postgres_restore_data: + +secrets: + postgres_password: + file: ./secrets/postgres_password.txt + database_url: + file: ./secrets/database_url.txt diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..2cfba92 --- /dev/null +++ b/go.mod @@ -0,0 +1,21 @@ +module mtusi2026lab3 + +go 1.27.1 + +require ( + github.com/google/uuid v1.6.0 + github.com/jackc/pgx/v5 v5.11.0 + github.com/redis/go-redis/v9 v9.23.0 + golang.org/x/crypto v0.57.0 +) + +require ( + github.com/cespare/xxhash/v2 v2.3.0 // indirect + github.com/jackc/pgpassfile v1.0.0 // indirect + github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect + github.com/jackc/puddle/v2 v2.2.2 // indirect + go.uber.org/atomic v1.12.0 // indirect + golang.org/x/sync v0.23.0 // indirect + golang.org/x/sys v0.48.0 // indirect + golang.org/x/text v0.42.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..409359b --- /dev/null +++ b/go.sum @@ -0,0 +1,43 @@ +github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs= +github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c= +github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA= +github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0= +github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= +github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= +github.com/jackc/pgx/v5 v5.11.0 h1:IzBBtyK9AHqf98cctWFifYSci2hgQR/cd56wB4p+ogg= +github.com/jackc/pgx/v5 v5.11.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4= +github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= +github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= +github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw= +github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/redis/go-redis/v9 v9.23.0 h1:/TTVdJa8BRNsybwwGGnmiYktHNlUXtbOQxlWpHBPL3s= +github.com/redis/go-redis/v9 v9.23.0/go.mod h1:EWP2UUk+XDaI1s5nQB5mablZN6vccXlmBQTyfnF87D0= +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.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= +github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= +github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs= +github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s= +go.uber.org/atomic v1.12.0 h1:BvcXdFKuviU4fTL/f+SxdQ5qJX/Jix8pAkgdUcb3XOE= +go.uber.org/atomic v1.12.0/go.mod h1:I6c4cg+6HCxRjfjSsYtApoFILnpc0CGUdGkXVqbYVNk= +go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= +go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= +golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M= +golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA= +golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk= +golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= +golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo= +golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI= +golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/internal/cache/chat.go b/internal/cache/chat.go new file mode 100644 index 0000000..780abae --- /dev/null +++ b/internal/cache/chat.go @@ -0,0 +1,175 @@ +package cache + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "strings" + "time" + + "mtusi2026lab3/internal/domain" + + "github.com/google/uuid" + "github.com/redis/go-redis/v9" +) + +const chatKeyPrefix = "chat:v1:" + +var ErrMiss = errors.New("cache miss") + +// ChatCache хранит только производную копию неизменяемых данных чата. +// PostgreSQL остаётся источником истины. +type ChatCache interface { + Get(ctx context.Context, chatID string) (domain.Chat, error) + Set(ctx context.Context, chat domain.Chat) error +} + +type RedisChatCache struct { + client *redis.Client + ttl time.Duration + operationTimeout time.Duration +} + +func NewRedisChatCache( + redisURL string, + ttl time.Duration, + operationTimeout time.Duration, + poolSize int, +) (*RedisChatCache, error) { + options, err := redis.ParseURL(strings.TrimSpace(redisURL)) + if err != nil { + return nil, fmt.Errorf("parse Redis URL: %w", err) + } + + options.DialTimeout = operationTimeout + options.ReadTimeout = operationTimeout + options.WriteTimeout = operationTimeout + options.PoolTimeout = operationTimeout + options.PoolSize = poolSize + options.MaxRetries = -1 + + return &RedisChatCache{ + client: redis.NewClient(options), + ttl: ttl, + operationTimeout: operationTimeout, + }, nil +} + +func (c *RedisChatCache) Ping(ctx context.Context) error { + operationContext, cancel := c.withTimeout(ctx) + defer cancel() + + if err := c.client.Ping(operationContext).Err(); err != nil { + return fmt.Errorf("ping Redis: %w", err) + } + + return nil +} + +func (c *RedisChatCache) Close() error { + return c.client.Close() +} + +func (c *RedisChatCache) Get( + ctx context.Context, + chatID string, +) (domain.Chat, error) { + operationContext, cancel := c.withTimeout(ctx) + defer cancel() + + payload, err := c.client.Get( + operationContext, + chatKey(chatID), + ).Bytes() + if errors.Is(err, redis.Nil) { + return domain.Chat{}, ErrMiss + } + if err != nil { + return domain.Chat{}, fmt.Errorf("get cached chat: %w", err) + } + + var chat domain.Chat + if err = json.Unmarshal(payload, &chat); err != nil { + c.deleteInvalidValue(operationContext, chatID) + return domain.Chat{}, fmt.Errorf("decode cached chat: %w", err) + } + + if err = validateCachedChat(chat, chatID); err != nil { + c.deleteInvalidValue(operationContext, chatID) + return domain.Chat{}, err + } + + return chat, nil +} + +func (c *RedisChatCache) Set( + ctx context.Context, + chat domain.Chat, +) error { + payload, err := json.Marshal(chat) + if err != nil { + return fmt.Errorf("encode chat for cache: %w", err) + } + + operationContext, cancel := c.withTimeout(ctx) + defer cancel() + + if err = c.client.Set( + operationContext, + chatKey(chat.ID), + payload, + c.ttl, + ).Err(); err != nil { + return fmt.Errorf("cache chat: %w", err) + } + + return nil +} + +func (c *RedisChatCache) withTimeout( + ctx context.Context, +) (context.Context, context.CancelFunc) { + return context.WithTimeout(ctx, c.operationTimeout) +} + +func (c *RedisChatCache) deleteInvalidValue( + ctx context.Context, + chatID string, +) { + _ = c.client.Del(ctx, chatKey(chatID)).Err() +} + +func chatKey(chatID string) string { + return chatKeyPrefix + chatID +} + +func validateCachedChat(chat domain.Chat, expectedID string) error { + if chat.ID != expectedID { + return errors.New("cached chat id does not match cache key") + } + if _, err := uuid.Parse(chat.ID); err != nil { + return errors.New("cached chat contains invalid id") + } + if strings.TrimSpace(chat.Title) == "" || chat.CreatedAt.IsZero() { + return errors.New("cached chat is incomplete") + } + if len(chat.MemberIDs) == 0 { + return errors.New("cached chat has no members") + } + + seenMembers := make(map[string]struct{}, len(chat.MemberIDs)) + for _, memberID := range chat.MemberIDs { + if _, err := uuid.Parse(memberID); err != nil { + return errors.New("cached chat contains invalid member id") + } + if _, exists := seenMembers[memberID]; exists { + return errors.New("cached chat contains duplicate member id") + } + seenMembers[memberID] = struct{}{} + } + + return nil +} + +var _ ChatCache = (*RedisChatCache)(nil) diff --git a/internal/config/config.go b/internal/config/config.go new file mode 100644 index 0000000..a02b1e9 --- /dev/null +++ b/internal/config/config.go @@ -0,0 +1,343 @@ +package config + +import ( + "errors" + "fmt" + "net" + "os" + "strconv" + "strings" + "time" +) + +type Config struct { + HTTPHost string + HTTPPort string + + SessionTTL time.Duration + + DatabaseURL string + DatabaseMaxConns int32 + DatabaseMinConns int32 + DatabaseMaxConnLifetime time.Duration + DatabaseMaxConnIdleTime time.Duration + DatabaseHealthCheckPeriod time.Duration + DatabaseConnectTimeout time.Duration + DatabaseQueryTimeout time.Duration + + RedisURL string + RedisCacheTTL time.Duration + RedisOperationTimeout time.Duration + RedisPoolSize int + + ReadinessTimeout time.Duration + ShutdownTimeout time.Duration +} + +func Load() (Config, error) { + sessionTTL, err := secondsDurationFromEnv( + "SESSION_TTL_SECONDS", + 3600, + ) + if err != nil { + return Config{}, err + } + + databaseURL, err := requiredValueOrFile( + "DATABASE_URL", + "DATABASE_URL_FILE", + ) + if err != nil { + return Config{}, err + } + + databaseMaxConns, err := int32FromEnv("DB_MAX_CONNS", 10, 1) + if err != nil { + return Config{}, err + } + + databaseMinConns, err := int32FromEnv("DB_MIN_CONNS", 2, 0) + if err != nil { + return Config{}, err + } + + databaseMaxConnLifetime, err := durationFromEnv( + "DB_MAX_CONN_LIFETIME", + 30*time.Minute, + ) + if err != nil { + return Config{}, err + } + + databaseMaxConnIdleTime, err := durationFromEnv( + "DB_MAX_CONN_IDLE_TIME", + 5*time.Minute, + ) + if err != nil { + return Config{}, err + } + + databaseHealthCheckPeriod, err := durationFromEnv( + "DB_HEALTH_CHECK_PERIOD", + 30*time.Second, + ) + if err != nil { + return Config{}, err + } + + databaseConnectTimeout, err := durationFromEnv( + "DB_CONNECT_TIMEOUT", + 5*time.Second, + ) + if err != nil { + return Config{}, err + } + + databaseQueryTimeout, err := durationFromEnv( + "DB_QUERY_TIMEOUT", + 3*time.Second, + ) + if err != nil { + return Config{}, err + } + + redisURL, err := optionalValueOrFile("CACHE_URL", "CACHE_URL_FILE") + if err != nil { + return Config{}, err + } + + redisCacheTTL, err := durationFromEnv( + "CACHE_TTL", + 5*time.Minute, + ) + if err != nil { + return Config{}, err + } + + redisOperationTimeout, err := durationFromEnv( + "CACHE_OPERATION_TIMEOUT", + 250*time.Millisecond, + ) + if err != nil { + return Config{}, err + } + + redisPoolSize, err := int32FromEnv("CACHE_POOL_SIZE", 10, 1) + if err != nil { + return Config{}, err + } + + readinessTimeout, err := durationFromEnv( + "READINESS_TIMEOUT", + 2*time.Second, + ) + if err != nil { + return Config{}, err + } + + shutdownTimeout, err := durationFromEnv( + "SHUTDOWN_TIMEOUT", + 10*time.Second, + ) + if err != nil { + return Config{}, err + } + + if databaseMinConns > databaseMaxConns { + return Config{}, errors.New( + "DB_MIN_CONNS must not be greater than DB_MAX_CONNS", + ) + } + + return Config{ + HTTPHost: envOrDefault("APP_HOST", "0.0.0.0"), + HTTPPort: envOrDefault("APP_PORT", "8080"), + SessionTTL: sessionTTL, + + DatabaseURL: databaseURL, + DatabaseMaxConns: databaseMaxConns, + DatabaseMinConns: databaseMinConns, + DatabaseMaxConnLifetime: databaseMaxConnLifetime, + DatabaseMaxConnIdleTime: databaseMaxConnIdleTime, + DatabaseHealthCheckPeriod: databaseHealthCheckPeriod, + DatabaseConnectTimeout: databaseConnectTimeout, + DatabaseQueryTimeout: databaseQueryTimeout, + + RedisURL: redisURL, + RedisCacheTTL: redisCacheTTL, + RedisOperationTimeout: redisOperationTimeout, + RedisPoolSize: int(redisPoolSize), + + ReadinessTimeout: readinessTimeout, + ShutdownTimeout: shutdownTimeout, + }, nil +} + +func (c Config) HTTPAddress() string { + return net.JoinHostPort(c.HTTPHost, c.HTTPPort) +} + +func requiredValueOrFile(valueEnv, fileEnv string) (string, error) { + value, valueExists := os.LookupEnv(valueEnv) + filePath, fileExists := os.LookupEnv(fileEnv) + + if valueExists && fileExists { + return "", fmt.Errorf( + "%s and %s must not be set at the same time", + valueEnv, + fileEnv, + ) + } + + if valueExists { + value = strings.TrimSpace(value) + if value == "" { + return "", fmt.Errorf("%s must not be empty", valueEnv) + } + + return value, nil + } + + if fileExists { + filePath = strings.TrimSpace(filePath) + if filePath == "" { + return "", fmt.Errorf("%s must not be empty", fileEnv) + } + + data, err := os.ReadFile(filePath) + if err != nil { + return "", fmt.Errorf("read %s: %w", fileEnv, err) + } + + value = strings.TrimSpace(string(data)) + if value == "" { + return "", fmt.Errorf("file from %s must not be empty", fileEnv) + } + + return value, nil + } + + return "", fmt.Errorf("%s or %s must be set", valueEnv, fileEnv) +} + +func optionalValueOrFile(valueEnv, fileEnv string) (string, error) { + value, valueExists := os.LookupEnv(valueEnv) + filePath, fileExists := os.LookupEnv(fileEnv) + + if valueExists && fileExists { + return "", fmt.Errorf( + "%s and %s must not be set at the same time", + valueEnv, + fileEnv, + ) + } + + if valueExists { + value = strings.TrimSpace(value) + if value == "" { + return "", fmt.Errorf("%s must not be empty", valueEnv) + } + + return value, nil + } + + if fileExists { + filePath = strings.TrimSpace(filePath) + if filePath == "" { + return "", fmt.Errorf("%s must not be empty", fileEnv) + } + + data, err := os.ReadFile(filePath) + if err != nil { + return "", fmt.Errorf("read %s: %w", fileEnv, err) + } + + value = strings.TrimSpace(string(data)) + if value == "" { + return "", fmt.Errorf("file from %s must not be empty", fileEnv) + } + + return value, nil + } + + return "", nil +} + +func envOrDefault(name, fallback string) string { + value := strings.TrimSpace(os.Getenv(name)) + if value == "" { + return fallback + } + + return value +} + +func int32FromEnv(name string, fallback, minimum int32) (int32, error) { + raw := strings.TrimSpace(os.Getenv(name)) + if raw == "" { + return fallback, nil + } + + value, err := strconv.ParseInt(raw, 10, 32) + if err != nil { + return 0, fmt.Errorf("%s must be an integer: %w", name, err) + } + + if value < int64(minimum) { + return 0, fmt.Errorf("%s must be at least %d", name, minimum) + } + + return int32(value), nil +} + +func durationFromEnv(name string, fallback time.Duration) (time.Duration, error) { + raw := strings.TrimSpace(os.Getenv(name)) + if raw == "" { + return fallback, nil + } + + value, err := time.ParseDuration(raw) + if err != nil { + return 0, fmt.Errorf( + "%s must be a Go duration such as 3s or 5m: %w", + name, + err, + ) + } + + if value <= 0 { + return 0, fmt.Errorf("%s must be positive", name) + } + + return value, nil +} + +func secondsDurationFromEnv( + name string, + fallbackSeconds int64, +) (time.Duration, error) { + raw := strings.TrimSpace(os.Getenv(name)) + if raw == "" { + raw = strconv.FormatInt(fallbackSeconds, 10) + } + + seconds, err := strconv.ParseInt(raw, 10, 64) + if err != nil { + return 0, fmt.Errorf( + "%s must be an integer number of seconds: %w", + name, + err, + ) + } + + if seconds <= 0 { + return 0, fmt.Errorf("%s must be positive", name) + } + + duration, err := time.ParseDuration(raw + "s") + if err != nil { + return 0, fmt.Errorf("%s is too large: %w", name, err) + } + + return duration, nil +} diff --git a/internal/database/postgres.go b/internal/database/postgres.go new file mode 100644 index 0000000..0a1be4c --- /dev/null +++ b/internal/database/postgres.go @@ -0,0 +1,40 @@ +package database + +import ( + "context" + "fmt" + + "mtusi2026lab3/internal/config" + + "github.com/jackc/pgx/v5/pgxpool" +) + +func Open( + ctx context.Context, + cfg config.Config, +) (*pgxpool.Pool, error) { + poolConfig, err := pgxpool.ParseConfig(cfg.DatabaseURL) + if err != nil { + return nil, fmt.Errorf("parse PostgreSQL configuration: %w", err) + } + + poolConfig.MaxConns = cfg.DatabaseMaxConns + poolConfig.MinConns = cfg.DatabaseMinConns + poolConfig.MaxConnLifetime = cfg.DatabaseMaxConnLifetime + poolConfig.MaxConnIdleTime = cfg.DatabaseMaxConnIdleTime + poolConfig.HealthCheckPeriod = cfg.DatabaseHealthCheckPeriod + + pool, err := pgxpool.NewWithConfig(ctx, poolConfig) + if err != nil { + return nil, fmt.Errorf("create PostgreSQL pool: %w", err) + } + + // NewWithConfig создаёт структуру пула, но не гарантирует, + // что PostgreSQL уже доступен. Ping обеспечивает fail-fast. + if err := pool.Ping(ctx); err != nil { + pool.Close() + return nil, fmt.Errorf("ping PostgreSQL: %w", err) + } + + return pool, nil +} diff --git a/internal/domain/models.go b/internal/domain/models.go new file mode 100644 index 0000000..b32c5a0 --- /dev/null +++ b/internal/domain/models.go @@ -0,0 +1,256 @@ +package domain + +import ( + "encoding/base64" + "fmt" + "regexp" + "strings" + "time" + "unicode/utf8" + + "github.com/google/uuid" +) + +var ( + //регулярка по контракту + usernameRegex = regexp.MustCompile(`^[a-z0-9_]{3,32}$`) +) + +type User struct { + ID string `json:"id"` + Username string `json:"username"` + DisplayName string `json:"display_name"` + CreatedAt time.Time `json:"created_at"` +} + +type Session struct { + Token string `json:"token"` + TokenType string `json:"token_type"` + ExpiresAt time.Time `json:"expires_at"` + User User `json:"user"` +} + +type Chat struct { + 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"` +} + +// страница выдачи истории сообщений +type MessagePage struct { + Items []Message `json:"items"` + NextCursor *string `json:"next_cursor"` +} + +func (u *User) Validate() error { + if !usernameRegex.MatchString(u.Username) { + return fmt.Errorf("username must match [a-z0-9_]{3,32}") + } + + nameRunes := utf8.RuneCountInString(u.DisplayName) + if nameRunes < 1 || nameRunes > 100 { + return fmt.Errorf("display_name length must be between 1 and 100 code points") + } + + if strings.TrimSpace(u.DisplayName) == "" { + return fmt.Errorf("display_name cannot be only whitespace") + } + + return nil +} + +func ValidateChatInput(title string, memberIDs []string, callerID string) error { + titleRunes := utf8.RuneCountInString(title) + if titleRunes < 1 || titleRunes > 100 || strings.TrimSpace(title) == "" { + return fmt.Errorf("invalid chat title") + } + + if len(memberIDs) == 0 { + return fmt.Errorf("member_ids cannot be empty") + } + + if len(memberIDs) > 100 { + return fmt.Errorf("member_ids must contain at most 100 users") + } + + hasCaller := false + seen := make(map[string]bool) + + for _, id := range memberIDs { + if _, err := uuid.Parse(id); err != nil { + return fmt.Errorf("invalid member uuid: %s", id) + } + + if seen[id] { + return fmt.Errorf("duplicate member_id: %s", id) + } + seen[id] = true + + if id == callerID { + hasCaller = true + } + } + + if !hasCaller { + return fmt.Errorf("caller must be in member_ids") + } + + return nil +} + +func ValidateMessageText(text string) error { + textRunes := utf8.RuneCountInString(text) + if textRunes < 1 || textRunes > 4000 { + return fmt.Errorf("message text length must be between 1 and 4000 code points") + } + if strings.TrimSpace(text) == "" { + return fmt.Errorf("message text cannot be only whitespace") + } + return nil +} + +type CursorData struct { + CreatedAt time.Time + MessageID string + ChatID string +} + +const messageCursorVersion = "v1" + +func EncodeCursor(createdAt time.Time, messageID, chatID string) string { + raw := fmt.Sprintf( + "%s|%s|%s|%s", + messageCursorVersion, + createdAt.UTC().Format(time.RFC3339Nano), + messageID, + chatID, + ) + + return base64.RawURLEncoding.EncodeToString([]byte(raw)) +} + +func DecodeCursor( + cursorStr string, + expectedChatID string, +) (*CursorData, error) { + raw, err := base64.RawURLEncoding.DecodeString(cursorStr) + if err != nil { + return nil, fmt.Errorf("invalid base64 cursor") + } + + parts := strings.Split(string(raw), "|") + if len(parts) != 4 { + return nil, fmt.Errorf("malformed cursor") + } + + if parts[0] != messageCursorVersion { + return nil, fmt.Errorf("unsupported cursor version") + } + + createdAt, err := time.Parse(time.RFC3339Nano, parts[1]) + if err != nil { + return nil, fmt.Errorf("invalid cursor timestamp") + } + + messageID := parts[2] + chatID := parts[3] + + if _, err := uuid.Parse(messageID); err != nil { + return nil, fmt.Errorf("invalid cursor message_id") + } + if _, err := uuid.Parse(chatID); err != nil { + return nil, fmt.Errorf("invalid cursor chat_id") + } + if chatID != expectedChatID { + return nil, fmt.Errorf("cursor belongs to another chat") + } + + return &CursorData{ + CreatedAt: createdAt.UTC(), + MessageID: messageID, + ChatID: chatID, + }, nil +} + +// страница со списком чатов пользователя +type ChatPage struct { + Items []Chat `json:"items"` + NextCursor *string `json:"next_cursor"` +} + +const chatCursorVersion = "v1" + +type ChatCursorData struct { + CreatedAt time.Time + ChatID string + UserID string +} + +// EncodeChatCursor создаёт непрозрачную границу списка чатов. +// Версия позволяет в будущем изменить внутренний формат курсора. +func EncodeChatCursor(createdAt time.Time, chatID, userID string) string { + raw := fmt.Sprintf( + "%s|%s|%s|%s", + chatCursorVersion, + createdAt.UTC().Format(time.RFC3339Nano), + chatID, + userID, + ) + + // RawURLEncoding не использует символы +, / и завершающий =, + // поэтому курсор безопаснее передавать в query string. + return base64.RawURLEncoding.EncodeToString([]byte(raw)) +} + +func DecodeChatCursor( + cursorStr string, + expectedUserID string, +) (*ChatCursorData, error) { + decoded, err := base64.RawURLEncoding.DecodeString(cursorStr) + if err != nil { + return nil, fmt.Errorf("invalid base64 chat cursor") + } + + parts := strings.Split(string(decoded), "|") + if len(parts) != 4 { + return nil, fmt.Errorf("malformed chat cursor") + } + + if parts[0] != chatCursorVersion { + return nil, fmt.Errorf("unsupported chat cursor version") + } + + createdAt, err := time.Parse(time.RFC3339Nano, parts[1]) + if err != nil { + return nil, fmt.Errorf("invalid chat cursor timestamp") + } + + chatID := parts[2] + if _, err = uuid.Parse(chatID); err != nil { + return nil, fmt.Errorf("invalid chat cursor chat_id") + } + + userID := parts[3] + if _, err = uuid.Parse(userID); err != nil { + return nil, fmt.Errorf("invalid chat cursor user_id") + } + + if userID != expectedUserID { + return nil, fmt.Errorf("chat cursor belongs to another user") + } + + return &ChatCursorData{ + CreatedAt: createdAt, + ChatID: chatID, + UserID: userID, + }, nil +} diff --git a/internal/security/password.go b/internal/security/password.go new file mode 100644 index 0000000..875b3f3 --- /dev/null +++ b/internal/security/password.go @@ -0,0 +1,164 @@ +package security + +import ( + "crypto/rand" + "crypto/subtle" + "encoding/base64" + "errors" + "fmt" + "strings" + "unicode/utf8" + + "golang.org/x/crypto/argon2" +) + +const ( + argonMemory uint32 = 19 * 1024 + argonIterations uint32 = 2 + argonParallelism uint8 = 1 + argonSaltLength = 16 + argonKeyLength uint32 = 32 + + minPasswordLength = 12 + maxPasswordLength = 128 +) + +var ErrInvalidPasswordHash = errors.New("invalid password hash") + +func ValidatePassword(password string) error { + if !utf8.ValidString(password) { + return errors.New("password must be valid UTF-8") + } + + length := utf8.RuneCountInString(password) + if length < minPasswordLength || length > maxPasswordLength { + return fmt.Errorf( + "password length must be between %d and %d code points", + minPasswordLength, + maxPasswordLength, + ) + } + + return nil +} + +func HashPassword(password string) (string, error) { + if err := ValidatePassword(password); err != nil { + return "", err + } + + salt := make([]byte, argonSaltLength) + if _, err := rand.Read(salt); err != nil { + return "", fmt.Errorf("generate password salt: %w", err) + } + + hash := argon2.IDKey( + []byte(password), + salt, + argonIterations, + argonMemory, + argonParallelism, + argonKeyLength, + ) + + encodedSalt := base64.RawStdEncoding.EncodeToString(salt) + encodedHash := base64.RawStdEncoding.EncodeToString(hash) + + encoded := fmt.Sprintf( + "$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s", + argon2.Version, + argonMemory, + argonIterations, + argonParallelism, + encodedSalt, + encodedHash, + ) + + return encoded, nil +} + +func VerifyPassword( + password string, + encodedHash string, +) (bool, error) { + parameters, salt, expectedHash, err := decodePasswordHash(encodedHash) + if err != nil { + return false, err + } + + actualHash := argon2.IDKey( + []byte(password), + salt, + parameters.iterations, + parameters.memory, + parameters.parallelism, + uint32(len(expectedHash)), + ) + + matches := subtle.ConstantTimeCompare( + actualHash, + expectedHash, + ) == 1 + + return matches, nil +} + +type argonParameters struct { + memory uint32 + iterations uint32 + parallelism uint8 +} + +func decodePasswordHash( + encodedHash string, +) (argonParameters, []byte, []byte, error) { + parts := strings.Split(encodedHash, "$") + if len(parts) != 6 || + parts[0] != "" || + parts[1] != "argon2id" { + return argonParameters{}, nil, nil, ErrInvalidPasswordHash + } + + var version int + if _, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil { + return argonParameters{}, nil, nil, ErrInvalidPasswordHash + } + + if version != argon2.Version { + return argonParameters{}, nil, nil, ErrInvalidPasswordHash + } + + var parameters argonParameters + if _, err := fmt.Sscanf( + parts[3], + "m=%d,t=%d,p=%d", + ¶meters.memory, + ¶meters.iterations, + ¶meters.parallelism, + ); err != nil { + return argonParameters{}, nil, nil, ErrInvalidPasswordHash + } + + // Ограничения не позволяют повреждённой строке из БД запросить + // гигантский объём памяти или процессорного времени. + if parameters.memory < 8*1024 || + parameters.memory > 256*1024 || + parameters.iterations < 1 || + parameters.iterations > 10 || + parameters.parallelism < 1 || + parameters.parallelism > 8 { + return argonParameters{}, nil, nil, ErrInvalidPasswordHash + } + + salt, err := base64.RawStdEncoding.DecodeString(parts[4]) + if err != nil || len(salt) < 16 || len(salt) > 64 { + return argonParameters{}, nil, nil, ErrInvalidPasswordHash + } + + hash, err := base64.RawStdEncoding.DecodeString(parts[5]) + if err != nil || len(hash) < 16 || len(hash) > 64 { + return argonParameters{}, nil, nil, ErrInvalidPasswordHash + } + + return parameters, salt, hash, nil +} diff --git a/internal/security/password_test.go b/internal/security/password_test.go new file mode 100644 index 0000000..f02c027 --- /dev/null +++ b/internal/security/password_test.go @@ -0,0 +1,105 @@ +package security + +import ( + "strings" + "testing" +) + +func TestPasswordHashAndVerify(t *testing.T) { + password := "Correct-password-123" + + encodedHash, err := HashPassword(password) + if err != nil { + t.Fatalf("HashPassword returned error: %v", err) + } + + if strings.Contains(encodedHash, password) { + t.Fatal("encoded hash contains plaintext password") + } + + matches, err := VerifyPassword(password, encodedHash) + if err != nil { + t.Fatalf("VerifyPassword returned error: %v", err) + } + if !matches { + t.Fatal("correct password did not match") + } + + matches, err = VerifyPassword("Wrong-password-123", encodedHash) + if err != nil { + t.Fatalf("VerifyPassword returned error: %v", err) + } + if matches { + t.Fatal("wrong password matched") + } +} + +func TestPasswordHashesUseDifferentSalts(t *testing.T) { + password := "Correct-password-123" + + firstHash, err := HashPassword(password) + if err != nil { + t.Fatalf("first HashPassword returned error: %v", err) + } + + secondHash, err := HashPassword(password) + if err != nil { + t.Fatalf("second HashPassword returned error: %v", err) + } + + if firstHash == secondHash { + t.Fatal("equal passwords produced equal encoded hashes") + } +} + +func TestPasswordValidation(t *testing.T) { + testCases := []struct { + name string + password string + wantErr bool + }{ + { + name: "minimum length", + password: "123456789012", + wantErr: false, + }, + { + name: "unicode", + password: "пароль-проверка-123", + wantErr: false, + }, + { + name: "colon is allowed", + password: "password:with:colon", + wantErr: false, + }, + { + name: "too short", + password: "short", + wantErr: true, + }, + } + + for _, testCase := range testCases { + t.Run(testCase.name, func(t *testing.T) { + err := ValidatePassword(testCase.password) + + if testCase.wantErr && err == nil { + t.Fatal("expected validation error") + } + if !testCase.wantErr && err != nil { + t.Fatalf("unexpected validation error: %v", err) + } + }) + } +} + +func TestMalformedPasswordHash(t *testing.T) { + _, err := VerifyPassword( + "Correct-password-123", + "not-an-argon2-hash", + ) + if err == nil { + t.Fatal("expected malformed hash error") + } +} diff --git a/internal/security/token.go b/internal/security/token.go new file mode 100644 index 0000000..aae7300 --- /dev/null +++ b/internal/security/token.go @@ -0,0 +1,32 @@ +package security + +import ( + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "fmt" +) + +const sessionTokenBytes = 32 + +func GenerateSessionToken() (string, []byte, error) { + randomBytes := make([]byte, sessionTokenBytes) + + if _, err := rand.Read(randomBytes); err != nil { + return "", nil, fmt.Errorf("generate session token: %w", err) + } + + token := base64.RawURLEncoding.EncodeToString(randomBytes) + tokenHash := HashSessionToken(token) + + return token, tokenHash, nil +} + +func HashSessionToken(token string) []byte { + digest := sha256.Sum256([]byte(token)) + + hash := make([]byte, len(digest)) + copy(hash, digest[:]) + + return hash +} diff --git a/internal/security/token_test.go b/internal/security/token_test.go new file mode 100644 index 0000000..14e2ecf --- /dev/null +++ b/internal/security/token_test.go @@ -0,0 +1,35 @@ +package security + +import ( + "bytes" + "testing" +) + +func TestGenerateSessionToken(t *testing.T) { + firstToken, firstHash, err := GenerateSessionToken() + if err != nil { + t.Fatalf("GenerateSessionToken returned error: %v", err) + } + + secondToken, secondHash, err := GenerateSessionToken() + if err != nil { + t.Fatalf("GenerateSessionToken returned error: %v", err) + } + + if firstToken == secondToken { + t.Fatal("generated session tokens are equal") + } + + if bytes.Equal(firstHash, secondHash) { + t.Fatal("generated session token hashes are equal") + } + + if len(firstHash) != 32 { + t.Fatalf("expected 32-byte token hash, got %d", len(firstHash)) + } + + recalculatedHash := HashSessionToken(firstToken) + if !bytes.Equal(firstHash, recalculatedHash) { + t.Fatal("token hash is not reproducible") + } +} diff --git a/internal/store/cached_repository.go b/internal/store/cached_repository.go new file mode 100644 index 0000000..10d3f30 --- /dev/null +++ b/internal/store/cached_repository.go @@ -0,0 +1,98 @@ +package store + +import ( + "context" + "errors" + "log" + + applicationCache "mtusi2026lab3/internal/cache" + "mtusi2026lab3/internal/domain" +) + +// CachedRepository декорирует основной Repository. Все операции, кроме чтения +// и создания чата, автоматически делегируются встроенному Repository. +type CachedRepository struct { + Repository + chatCache applicationCache.ChatCache + logger *log.Logger +} + +func NewCachedRepository( + repository Repository, + chatCache applicationCache.ChatCache, + logger *log.Logger, +) *CachedRepository { + if logger == nil { + logger = log.Default() + } + + return &CachedRepository{ + Repository: repository, + chatCache: chatCache, + logger: logger, + } +} + +func (r *CachedRepository) CreateChat( + ctx context.Context, + title string, + memberIDs []string, +) (domain.Chat, error) { + chat, err := r.Repository.CreateChat(ctx, title, memberIDs) + if err != nil { + return domain.Chat{}, err + } + + // Запись в PostgreSQL уже подтверждена. Ошибка необязательного кэша не + // должна превращать успешную бизнес-операцию в 503. + if err = r.chatCache.Set(ctx, chat); err != nil { + r.logger.Printf("[WARN] Redis chat cache write failed: %v", err) + } + + return chat, nil +} + +func (r *CachedRepository) GetChatByID( + ctx context.Context, + chatID string, + callerID string, +) (domain.Chat, error) { + chat, err := r.chatCache.Get(ctx, chatID) + if err == nil { + if !containsMember(chat.MemberIDs, callerID) { + return domain.Chat{}, ErrNotFound + } + + return chat, nil + } + + shouldFillCache := errors.Is(err, applicationCache.ErrMiss) + if !shouldFillCache { + r.logger.Printf("[WARN] Redis chat cache read failed: %v", err) + } + + chat, err = r.Repository.GetChatByID(ctx, chatID, callerID) + if err != nil { + return domain.Chat{}, err + } + + if shouldFillCache { + if err = r.chatCache.Set(ctx, chat); err != nil { + r.logger.Printf("[WARN] Redis chat cache fill failed: %v", err) + } + } + + return chat, nil +} + +func containsMember(memberIDs []string, callerID string) bool { + for _, memberID := range memberIDs { + if memberID == callerID { + return true + } + } + + return false +} + +var _ Repository = (*CachedRepository)(nil) diff --git a/internal/store/cached_repository_test.go b/internal/store/cached_repository_test.go new file mode 100644 index 0000000..ba13f50 --- /dev/null +++ b/internal/store/cached_repository_test.go @@ -0,0 +1,181 @@ +package store + +import ( + "context" + "errors" + "io" + "log" + "testing" + + applicationCache "mtusi2026lab3/internal/cache" + "mtusi2026lab3/internal/domain" +) + +type fakeChatCache struct { + chats map[string]domain.Chat + getErr error + setErr error + sets int +} + +func (c *fakeChatCache) Get( + _ context.Context, + chatID string, +) (domain.Chat, error) { + if c.getErr != nil { + return domain.Chat{}, c.getErr + } + + chat, exists := c.chats[chatID] + if !exists { + return domain.Chat{}, applicationCache.ErrMiss + } + + return chat, nil +} + +func (c *fakeChatCache) Set( + _ context.Context, + chat domain.Chat, +) error { + c.sets++ + if c.setErr != nil { + return c.setErr + } + c.chats[chat.ID] = chat + + return nil +} + +type countingRepository struct { + Repository + getChatCalls int +} + +func (r *countingRepository) GetChatByID( + ctx context.Context, + chatID string, + callerID string, +) (domain.Chat, error) { + r.getChatCalls++ + return r.Repository.GetChatByID(ctx, chatID, callerID) +} + +func cachedRepositoryFixture( + t *testing.T, +) (*countingRepository, *fakeChatCache, domain.User, domain.User, domain.Chat) { + t.Helper() + + legacy := NewMemoryStore() + member, err := legacy.CreateUser("cache_member", "Участник") + if err != nil { + t.Fatalf("create member: %v", err) + } + outsider, err := legacy.CreateUser("cache_outsider", "Посторонний") + if err != nil { + t.Fatalf("create outsider: %v", err) + } + chat, err := legacy.CreateChat("Кешируемый чат", []string{member.ID}) + if err != nil { + t.Fatalf("create chat: %v", err) + } + + repository := &countingRepository{ + Repository: NewMemoryRepository(legacy), + } + chatCache := &fakeChatCache{ + chats: make(map[string]domain.Chat), + } + + return repository, chatCache, member, outsider, chat +} + +func TestCachedRepositoryMissThenHit(t *testing.T) { + repository, chatCache, member, _, expected := cachedRepositoryFixture(t) + cached := NewCachedRepository( + repository, + chatCache, + log.New(io.Discard, "", 0), + ) + + first, err := cached.GetChatByID(context.Background(), expected.ID, member.ID) + if err != nil { + t.Fatalf("first read: %v", err) + } + second, err := cached.GetChatByID(context.Background(), expected.ID, member.ID) + if err != nil { + t.Fatalf("second read: %v", err) + } + + if repository.getChatCalls != 1 { + t.Fatalf("expected one source read, got %d", repository.getChatCalls) + } + if chatCache.sets != 1 { + t.Fatalf("expected one cache fill, got %d", chatCache.sets) + } + if first.ID != expected.ID || second.ID != expected.ID { + t.Fatal("cache changed chat identity") + } +} + +func TestCachedRepositoryFallsBackWhenCacheUnavailable(t *testing.T) { + repository, chatCache, member, _, expected := cachedRepositoryFixture(t) + chatCache.getErr = errors.New("redis unavailable") + chatCache.setErr = errors.New("redis unavailable") + cached := NewCachedRepository( + repository, + chatCache, + log.New(io.Discard, "", 0), + ) + + chat, err := cached.GetChatByID(context.Background(), expected.ID, member.ID) + if err != nil { + t.Fatalf("fallback read: %v", err) + } + if chat.ID != expected.ID || repository.getChatCalls != 1 { + t.Fatal("source repository was not used after cache failure") + } + if chatCache.sets != 0 { + t.Fatal("failed cache read must not trigger another cache operation") + } +} + +func TestCachedRepositoryChecksMembershipOnHit(t *testing.T) { + repository, chatCache, _, outsider, expected := cachedRepositoryFixture(t) + chatCache.chats[expected.ID] = expected + cached := NewCachedRepository( + repository, + chatCache, + log.New(io.Discard, "", 0), + ) + + _, err := cached.GetChatByID(context.Background(), expected.ID, outsider.ID) + if !errors.Is(err, ErrNotFound) { + t.Fatalf("expected ErrNotFound for outsider, got %v", err) + } + if repository.getChatCalls != 0 { + t.Fatal("cache hit unexpectedly queried source repository") + } +} + +func TestCachedRepositoryIgnoresWriteFailure(t *testing.T) { + repository, chatCache, member, _, _ := cachedRepositoryFixture(t) + chatCache.setErr = errors.New("redis unavailable") + cached := NewCachedRepository( + repository, + chatCache, + log.New(io.Discard, "", 0), + ) + + chat, err := cached.CreateChat( + context.Background(), + "Новый чат", + []string{member.ID}, + ) + if err != nil { + t.Fatalf("create chat with unavailable cache: %v", err) + } + if chat.ID == "" || chatCache.sets != 1 { + t.Fatal("chat was not created before best-effort cache write") + } +} diff --git a/internal/store/errors.go b/internal/store/errors.go new file mode 100644 index 0000000..939a2b2 --- /dev/null +++ b/internal/store/errors.go @@ -0,0 +1,9 @@ +package store + +import "errors" + +var ( + ErrNotFound = errors.New("not found") + ErrConflict = errors.New("conflict") + ErrInvalidCursor = errors.New("invalid cursor") +) diff --git a/internal/store/memory.go b/internal/store/memory.go new file mode 100644 index 0000000..405efd1 --- /dev/null +++ b/internal/store/memory.go @@ -0,0 +1,345 @@ +package store + +import ( + "fmt" + "sort" + "sync" + "time" + + "mtusi2026lab3/internal/domain" + + "github.com/google/uuid" +) + +type MemoryStore struct { + mu sync.RWMutex + + usersByID map[string]domain.User //key = user UUID + usersByUsername map[string]string //key = username для быстрой проверки уникальности + + chatsByID map[string]domain.Chat //key = chat UUID + + messagesByChatID map[string][]domain.Message // key = chat UUID, value = слайс сообщений +} + +func NewMemoryStore() *MemoryStore { + return &MemoryStore{ + usersByID: make(map[string]domain.User), + usersByUsername: make(map[string]string), + chatsByID: make(map[string]domain.Chat), + messagesByChatID: make(map[string][]domain.Message), + } +} + +// ---пользователи--- + +func (s *MemoryStore) CreateUser(username, displayName string) (domain.User, error) { + s.mu.Lock() + defer s.mu.Unlock() + + // дубликат username -> 409 Conflict + if _, exists := s.usersByUsername[username]; exists { + return domain.User{}, ErrConflict + } + + user := domain.User{ + ID: uuid.NewString(), + Username: username, + DisplayName: displayName, + CreatedAt: time.Now().UTC(), + } + + s.usersByID[user.ID] = user + s.usersByUsername[user.Username] = user.ID + + return user, nil +} + +func (s *MemoryStore) GetUserByID(id string) (domain.User, error) { + s.mu.RLock() + defer s.mu.RUnlock() + + user, exists := s.usersByID[id] + if !exists { + return domain.User{}, ErrNotFound + } + return user, nil +} + +// ---чаты--- + +func (s *MemoryStore) CreateChat(title string, memberIDs []string) (domain.Chat, error) { + s.mu.Lock() + defer s.mu.Unlock() + + //все участники рил существуют + for _, memberID := range memberIDs { + if _, exists := s.usersByID[memberID]; !exists { + return domain.Chat{}, fmt.Errorf( + "%w: member %s", + ErrNotFound, + memberID, + ) + } + } + + chat := domain.Chat{ + ID: uuid.NewString(), + Title: title, + MemberIDs: append([]string(nil), memberIDs...), //копирую слайс для изоляции + CreatedAt: time.Now().UTC(), + } + + s.chatsByID[chat.ID] = chat + s.messagesByChatID[chat.ID] = make([]domain.Message, 0) + + return chat, nil +} + +func (s *MemoryStore) GetChatByID(chatID, callerID string) (domain.Chat, error) { + s.mu.RLock() + defer s.mu.RUnlock() + + chat, exists := s.chatsByID[chatID] + if !exists { + return domain.Chat{}, ErrNotFound + } + + // Требование безопасности: посторонний получает 404, а не 403 + isMember := false + for _, m := range chat.MemberIDs { + if m == callerID { + isMember = true + break + } + } + + if !isMember { + return domain.Chat{}, ErrNotFound + } + + return chat, nil +} + +func (s *MemoryStore) GetChatsForUser( + userID string, + limit int, + cursorStr string, +) (domain.ChatPage, error) { + var cursorData *domain.ChatCursorData + + if cursorStr != "" { + decodedCursor, err := domain.DecodeChatCursor(cursorStr, userID) + if err != nil { + return domain.ChatPage{}, + fmt.Errorf("%w: %v", ErrInvalidCursor, err) + } + + cursorData = decodedCursor + } + + s.mu.RLock() + defer s.mu.RUnlock() + + chats := make([]domain.Chat, 0) + + for _, chat := range s.chatsByID { + for _, memberID := range chat.MemberIDs { + if memberID == userID { + chats = append(chats, chat) + break + } + } + } + + sort.Slice(chats, func(i, j int) bool { + if chats[i].CreatedAt.Equal(chats[j].CreatedAt) { + return chats[i].ID < chats[j].ID + } + + return chats[i].CreatedAt.Before(chats[j].CreatedAt) + }) + + start := 0 + + if cursorData != nil { + start = sort.Search(len(chats), func(index int) bool { + chat := chats[index] + + if chat.CreatedAt.After(cursorData.CreatedAt) { + return true + } + + return chat.CreatedAt.Equal(cursorData.CreatedAt) && + chat.ID > cursorData.ChatID + }) + } + + page := domain.ChatPage{ + Items: make([]domain.Chat, 0), + NextCursor: nil, + } + + if start >= len(chats) { + return page, nil + } + + end := start + limit + if end > len(chats) { + end = len(chats) + } + + page.Items = make([]domain.Chat, end-start) + copy(page.Items, chats[start:end]) + + if end < len(chats) { + lastChat := page.Items[len(page.Items)-1] + nextCursor := domain.EncodeChatCursor( + lastChat.CreatedAt, + lastChat.ID, + userID, + ) + page.NextCursor = &nextCursor + } + + return page, nil +} + +// ---Сообщения--- + +func (s *MemoryStore) CreateMessage( + chatID, senderID, text string, +) (domain.Message, error) { + messageID := uuid.NewString() + + s.mu.Lock() + defer s.mu.Unlock() + + chat, exists := s.chatsByID[chatID] + if !exists { + return domain.Message{}, ErrNotFound + } + + isMember := false + for _, memberID := range chat.MemberIDs { + if memberID == senderID { + isMember = true + break + } + } + if !isMember { + return domain.Message{}, ErrNotFound + } + + createdAt := time.Now().UTC() + + messages := s.messagesByChatID[chatID] + if len(messages) > 0 { + lastCreatedAt := messages[len(messages)-1].CreatedAt + + // Обеспечиваем строго возрастающее время внутри каждого чата. + if !createdAt.After(lastCreatedAt) { + createdAt = lastCreatedAt.Add(time.Nanosecond) + } + } + + message := domain.Message{ + ID: messageID, + ChatID: chatID, + SenderID: senderID, + Text: text, + CreatedAt: createdAt, + } + + s.messagesByChatID[chatID] = append(messages, message) + + return message, nil +} + +func (s *MemoryStore) GetMessages( + chatID, callerID string, + limit int, + cursorStr string, +) (domain.MessagePage, error) { + s.mu.RLock() + defer s.mu.RUnlock() + + chat, exists := s.chatsByID[chatID] + if !exists { + return domain.MessagePage{}, ErrNotFound + } + + isMember := false + for _, memberID := range chat.MemberIDs { + if memberID == callerID { + isMember = true + break + } + } + if !isMember { + return domain.MessagePage{}, ErrNotFound + } + + var cursorData *domain.CursorData + if cursorStr != "" { + decodedCursor, err := domain.DecodeCursor(cursorStr, chatID) + if err != nil { + return domain.MessagePage{}, fmt.Errorf( + "%w: %v", + ErrInvalidCursor, + err, + ) + } + + cursorData = decodedCursor + } + + messages := s.messagesByChatID[chatID] + + start := 0 + + if cursorData != nil { + // Срез уже упорядочен во время записи, поэтому вместо + // полного прохода используем бинарный поиск. + start = sort.Search(len(messages), func(index int) bool { + message := messages[index] + + if message.CreatedAt.After(cursorData.CreatedAt) { + return true + } + + return message.CreatedAt.Equal(cursorData.CreatedAt) && + message.ID > cursorData.MessageID + }) + } + + page := domain.MessagePage{ + Items: make([]domain.Message, 0), + NextCursor: nil, + } + + if start >= len(messages) { + return page, nil + } + + end := len(messages) + if limit > 0 && end-start > limit { + end = start + limit + } + + // копируем только возвращаемую страницу, а не всю историю, изменяя внутренний срез + page.Items = make([]domain.Message, end-start) + copy(page.Items, messages[start:end]) + + if end < len(messages) { + lastItem := page.Items[len(page.Items)-1] + nextCursor := domain.EncodeCursor( + lastItem.CreatedAt, + lastItem.ID, + chatID, + ) + page.NextCursor = &nextCursor + } + + return page, nil +} diff --git a/internal/store/memory_repository.go b/internal/store/memory_repository.go new file mode 100644 index 0000000..72c330f --- /dev/null +++ b/internal/store/memory_repository.go @@ -0,0 +1,247 @@ +package store + +import ( + "context" + "fmt" + "sync" + "time" + + "mtusi2026lab3/internal/domain" +) + +type memorySession struct { + userID string + expiresAt time.Time +} + +type MemoryRepository struct { + legacy *MemoryStore + + mu sync.RWMutex + passwordByUserID map[string]string + userIDByUsername map[string]string + sessionsByHashKey map[[32]byte]memorySession +} + +func NewMemoryRepository(legacy *MemoryStore) *MemoryRepository { + return &MemoryRepository{ + legacy: legacy, + passwordByUserID: make(map[string]string), + userIDByUsername: make(map[string]string), + sessionsByHashKey: make(map[[32]byte]memorySession), + } +} + +func (r *MemoryRepository) CreateUser( + ctx context.Context, + username string, + displayName string, + passwordHash string, +) (domain.User, error) { + if err := ctx.Err(); err != nil { + return domain.User{}, err + } + + user, err := r.legacy.CreateUser(username, displayName) + if err != nil { + return domain.User{}, err + } + + r.mu.Lock() + r.passwordByUserID[user.ID] = passwordHash + r.userIDByUsername[user.Username] = user.ID + r.mu.Unlock() + + return user, nil +} + +func (r *MemoryRepository) GetUserByID( + ctx context.Context, + userID string, +) (domain.User, error) { + if err := ctx.Err(); err != nil { + return domain.User{}, err + } + + return r.legacy.GetUserByID(userID) +} + +func (r *MemoryRepository) GetUserByUsername( + ctx context.Context, + username string, +) (domain.User, string, error) { + if err := ctx.Err(); err != nil { + return domain.User{}, "", err + } + + r.mu.RLock() + userID, exists := r.userIDByUsername[username] + passwordHash := r.passwordByUserID[userID] + r.mu.RUnlock() + + if !exists { + return domain.User{}, "", ErrNotFound + } + + user, err := r.legacy.GetUserByID(userID) + if err != nil { + return domain.User{}, "", err + } + + return user, passwordHash, nil +} + +func (r *MemoryRepository) CreateChat( + ctx context.Context, + title string, + memberIDs []string, +) (domain.Chat, error) { + if err := ctx.Err(); err != nil { + return domain.Chat{}, err + } + + return r.legacy.CreateChat(title, memberIDs) +} + +func (r *MemoryRepository) GetChatByID( + ctx context.Context, + chatID string, + callerID string, +) (domain.Chat, error) { + if err := ctx.Err(); err != nil { + return domain.Chat{}, err + } + + return r.legacy.GetChatByID(chatID, callerID) +} + +func (r *MemoryRepository) GetChatsForUser( + ctx context.Context, + userID string, + limit int, + cursor string, +) (domain.ChatPage, error) { + if err := ctx.Err(); err != nil { + return domain.ChatPage{}, err + } + + return r.legacy.GetChatsForUser(userID, limit, cursor) +} + +func (r *MemoryRepository) CreateMessage( + ctx context.Context, + chatID string, + senderID string, + text string, +) (domain.Message, error) { + if err := ctx.Err(); err != nil { + return domain.Message{}, err + } + + return r.legacy.CreateMessage(chatID, senderID, text) +} + +func (r *MemoryRepository) GetMessages( + ctx context.Context, + chatID string, + callerID string, + limit int, + cursor string, +) (domain.MessagePage, error) { + if err := ctx.Err(); err != nil { + return domain.MessagePage{}, err + } + + return r.legacy.GetMessages( + chatID, + callerID, + limit, + cursor, + ) +} + +func (r *MemoryRepository) CreateSession( + ctx context.Context, + tokenHash []byte, + userID string, + expiresAt time.Time, +) error { + if err := ctx.Err(); err != nil { + return err + } + + key, err := memoryTokenHashKey(tokenHash) + if err != nil { + return err + } + + r.mu.Lock() + r.sessionsByHashKey[key] = memorySession{ + userID: userID, + expiresAt: expiresAt, + } + r.mu.Unlock() + + return nil +} + +func (r *MemoryRepository) GetUserBySession( + ctx context.Context, + tokenHash []byte, +) (domain.User, error) { + if err := ctx.Err(); err != nil { + return domain.User{}, err + } + + key, err := memoryTokenHashKey(tokenHash) + if err != nil { + return domain.User{}, ErrNotFound + } + + r.mu.RLock() + session, exists := r.sessionsByHashKey[key] + r.mu.RUnlock() + + if !exists || !session.expiresAt.After(time.Now().UTC()) { + return domain.User{}, ErrNotFound + } + + return r.legacy.GetUserByID(session.userID) +} + +func (r *MemoryRepository) DeleteSession( + ctx context.Context, + tokenHash []byte, +) error { + if err := ctx.Err(); err != nil { + return err + } + + key, err := memoryTokenHashKey(tokenHash) + if err != nil { + return err + } + + r.mu.Lock() + delete(r.sessionsByHashKey, key) + r.mu.Unlock() + + return nil +} + +func memoryTokenHashKey(tokenHash []byte) ([32]byte, error) { + var key [32]byte + + if len(tokenHash) != len(key) { + return key, fmt.Errorf( + "session token hash must contain %d bytes", + len(key), + ) + } + + copy(key[:], tokenHash) + + return key, nil +} + +var _ Repository = (*MemoryRepository)(nil) diff --git a/internal/store/postgres.go b/internal/store/postgres.go new file mode 100644 index 0000000..a40f5ad --- /dev/null +++ b/internal/store/postgres.go @@ -0,0 +1,40 @@ +package store + +import ( + "context" + "time" + + "github.com/jackc/pgx/v5/pgxpool" +) + +type PostgreSQLStore struct { + pool *pgxpool.Pool + queryTimeout time.Duration +} + +func NewPostgreSQLStore( + pool *pgxpool.Pool, + queryTimeout time.Duration, +) *PostgreSQLStore { + return &PostgreSQLStore{ + pool: pool, + queryTimeout: queryTimeout, + } +} + +func (s *PostgreSQLStore) Ping(ctx context.Context) error { + queryContext, cancel := s.withTimeout(ctx) + defer cancel() + + return s.pool.Ping(queryContext) +} + +func (s *PostgreSQLStore) Close() { + s.pool.Close() +} + +func (s *PostgreSQLStore) withTimeout( + ctx context.Context, +) (context.Context, context.CancelFunc) { + return context.WithTimeout(ctx, s.queryTimeout) +} diff --git a/internal/store/postgres_chats.go b/internal/store/postgres_chats.go new file mode 100644 index 0000000..8f5b568 --- /dev/null +++ b/internal/store/postgres_chats.go @@ -0,0 +1,306 @@ +package store + +import ( + "context" + "errors" + "fmt" + + "mtusi2026lab3/internal/domain" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" +) + +func (s *PostgreSQLStore) CreateChat( + ctx context.Context, + title string, + memberIDs []string, +) (domain.Chat, error) { + queryContext, cancel := s.withTimeout(ctx) + defer cancel() + + transaction, err := s.pool.Begin(queryContext) + if err != nil { + return domain.Chat{}, fmt.Errorf( + "begin create chat transaction: %w", + err, + ) + } + + defer func() { + _ = transaction.Rollback(queryContext) + }() + + chat := domain.Chat{ + ID: uuid.NewString(), + Title: title, + MemberIDs: append([]string(nil), memberIDs...), + } + + err = transaction.QueryRow( + queryContext, + ` + INSERT INTO chats ( + id, + title + ) + VALUES ($1, $2) + RETURNING created_at + `, + chat.ID, + chat.Title, + ).Scan(&chat.CreatedAt) + if err != nil { + return domain.Chat{}, fmt.Errorf("insert chat: %w", err) + } + + for position, memberID := range memberIDs { + commandTag, insertErr := transaction.Exec( + queryContext, + ` + INSERT INTO chat_members ( + chat_id, + user_id, + position + ) + SELECT + $1, + id, + $3 + FROM users + WHERE id = $2 + `, + chat.ID, + memberID, + position, + ) + if insertErr != nil { + return domain.Chat{}, fmt.Errorf( + "insert chat member %s: %w", + memberID, + insertErr, + ) + } + + // INSERT ... SELECT не вставляет строку, если пользователя нет. + // Возврат из функции активирует deferred Rollback: уже созданные + // chat и предыдущие membership-строки не останутся в базе. + if commandTag.RowsAffected() != 1 { + return domain.Chat{}, fmt.Errorf( + "%w: member %s", + ErrNotFound, + memberID, + ) + } + } + + if err = transaction.Commit(queryContext); err != nil { + return domain.Chat{}, fmt.Errorf( + "commit create chat transaction: %w", + err, + ) + } + + return chat, nil +} + +func (s *PostgreSQLStore) GetChatByID( + ctx context.Context, + chatID string, + callerID string, +) (domain.Chat, error) { + queryContext, cancel := s.withTimeout(ctx) + defer cancel() + + var chat domain.Chat + + err := s.pool.QueryRow( + queryContext, + ` + SELECT + chat.id::text, + chat.title, + chat.created_at, + array_agg( + member.user_id::text + ORDER BY member.position + ) + FROM chats AS chat + JOIN chat_members AS caller + ON caller.chat_id = chat.id + AND caller.user_id = $2 + JOIN chat_members AS member + ON member.chat_id = chat.id + WHERE chat.id = $1 + GROUP BY + chat.id, + chat.title, + chat.created_at + `, + chatID, + callerID, + ).Scan( + &chat.ID, + &chat.Title, + &chat.CreatedAt, + &chat.MemberIDs, + ) + + if errors.Is(err, pgx.ErrNoRows) { + return domain.Chat{}, ErrNotFound + } + if err != nil { + return domain.Chat{}, fmt.Errorf("select chat by id: %w", err) + } + + return chat, nil +} + +func (s *PostgreSQLStore) GetChatsForUser( + ctx context.Context, + userID string, + limit int, + cursorString string, +) (domain.ChatPage, error) { + var cursor *domain.ChatCursorData + + if cursorString != "" { + decodedCursor, err := domain.DecodeChatCursor( + cursorString, + userID, + ) + if err != nil { + return domain.ChatPage{}, fmt.Errorf( + "%w: %v", + ErrInvalidCursor, + err, + ) + } + + cursor = decodedCursor + } + + queryContext, cancel := s.withTimeout(ctx) + defer cancel() + + var ( + rows pgx.Rows + err error + ) + + if cursor == nil { + rows, err = s.pool.Query( + queryContext, + ` + SELECT + chat.id::text, + chat.title, + chat.created_at, + array_agg( + member.user_id::text + ORDER BY member.position + ) + FROM chat_members AS own_membership + JOIN chats AS chat + ON chat.id = own_membership.chat_id + JOIN chat_members AS member + ON member.chat_id = chat.id + WHERE own_membership.user_id = $1 + GROUP BY + chat.id, + chat.title, + chat.created_at + ORDER BY + chat.created_at, + chat.id + LIMIT $2 + `, + userID, + limit+1, + ) + } else { + rows, err = s.pool.Query( + queryContext, + ` + SELECT + chat.id::text, + chat.title, + chat.created_at, + array_agg( + member.user_id::text + ORDER BY member.position + ) + FROM chat_members AS own_membership + JOIN chats AS chat + ON chat.id = own_membership.chat_id + JOIN chat_members AS member + ON member.chat_id = chat.id + WHERE own_membership.user_id = $1 + AND (chat.created_at, chat.id) > ($2, $3) + GROUP BY + chat.id, + chat.title, + chat.created_at + ORDER BY + chat.created_at, + chat.id + LIMIT $4 + `, + userID, + cursor.CreatedAt, + cursor.ChatID, + limit+1, + ) + } + + if err != nil { + return domain.ChatPage{}, fmt.Errorf( + "query chats for user: %w", + err, + ) + } + defer rows.Close() + + page := domain.ChatPage{ + Items: make([]domain.Chat, 0, limit), + } + + for rows.Next() { + var chat domain.Chat + + if err := rows.Scan( + &chat.ID, + &chat.Title, + &chat.CreatedAt, + &chat.MemberIDs, + ); err != nil { + return domain.ChatPage{}, fmt.Errorf( + "scan chat page: %w", + err, + ) + } + + page.Items = append(page.Items, chat) + } + + if err := rows.Err(); err != nil { + return domain.ChatPage{}, fmt.Errorf( + "iterate chat page: %w", + err, + ) + } + + if len(page.Items) > limit { + page.Items = page.Items[:limit] + + lastChat := page.Items[len(page.Items)-1] + nextCursor := domain.EncodeChatCursor( + lastChat.CreatedAt, + lastChat.ID, + userID, + ) + page.NextCursor = &nextCursor + } + + return page, nil +} diff --git a/internal/store/postgres_messages.go b/internal/store/postgres_messages.go new file mode 100644 index 0000000..fda090c --- /dev/null +++ b/internal/store/postgres_messages.go @@ -0,0 +1,220 @@ +package store + +import ( + "context" + "errors" + "fmt" + + "mtusi2026lab3/internal/domain" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" +) + +func (s *PostgreSQLStore) CreateMessage( + ctx context.Context, + chatID string, + senderID string, + text string, +) (domain.Message, error) { + queryContext, cancel := s.withTimeout(ctx) + defer cancel() + + message := domain.Message{ + ID: uuid.NewString(), + ChatID: chatID, + SenderID: senderID, + Text: text, + } + + err := s.pool.QueryRow( + queryContext, + ` + INSERT INTO messages ( + id, + chat_id, + sender_id, + text + ) + SELECT + $1, + $2, + $3, + $4 + FROM chat_members + WHERE chat_id = $2 + AND user_id = $3 + RETURNING created_at + `, + message.ID, + message.ChatID, + message.SenderID, + message.Text, + ).Scan(&message.CreatedAt) + + if err == nil { + return message, nil + } + + // INSERT ... SELECT возвращает zero rows, если отправитель + // не является участником указанного чата. + if errors.Is(err, pgx.ErrNoRows) { + return domain.Message{}, ErrNotFound + } + + return domain.Message{}, fmt.Errorf("insert message: %w", err) +} + +func (s *PostgreSQLStore) GetMessages( + ctx context.Context, + chatID string, + callerID string, + limit int, + cursorString string, +) (domain.MessagePage, error) { + queryContext, cancel := s.withTimeout(ctx) + defer cancel() + + var isMember bool + + err := s.pool.QueryRow( + queryContext, + ` + SELECT EXISTS ( + SELECT 1 + FROM chat_members + WHERE chat_id = $1 + AND user_id = $2 + ) + `, + chatID, + callerID, + ).Scan(&isMember) + if err != nil { + return domain.MessagePage{}, fmt.Errorf( + "check chat membership: %w", + err, + ) + } + + if !isMember { + return domain.MessagePage{}, ErrNotFound + } + + var cursor *domain.CursorData + + if cursorString != "" { + decodedCursor, err := domain.DecodeCursor( + cursorString, + chatID, + ) + if err != nil { + return domain.MessagePage{}, fmt.Errorf( + "%w: %v", + ErrInvalidCursor, + err, + ) + } + + cursor = decodedCursor + } + + var rows pgx.Rows + + if cursor == nil { + rows, err = s.pool.Query( + queryContext, + ` + SELECT + id::text, + chat_id::text, + sender_id::text, + text, + created_at + FROM messages + WHERE chat_id = $1 + ORDER BY + created_at, + id + LIMIT $2 + `, + chatID, + limit+1, + ) + } else { + rows, err = s.pool.Query( + queryContext, + ` + SELECT + id::text, + chat_id::text, + sender_id::text, + text, + created_at + FROM messages + WHERE chat_id = $1 + AND (created_at, id) > ($2, $3) + ORDER BY + created_at, + id + LIMIT $4 + `, + chatID, + cursor.CreatedAt, + cursor.MessageID, + limit+1, + ) + } + + if err != nil { + return domain.MessagePage{}, fmt.Errorf( + "query messages: %w", + err, + ) + } + defer rows.Close() + + page := domain.MessagePage{ + Items: make([]domain.Message, 0, limit), + } + + for rows.Next() { + var message domain.Message + + if err := rows.Scan( + &message.ID, + &message.ChatID, + &message.SenderID, + &message.Text, + &message.CreatedAt, + ); err != nil { + return domain.MessagePage{}, fmt.Errorf( + "scan message page: %w", + err, + ) + } + + page.Items = append(page.Items, message) + } + + if err := rows.Err(); err != nil { + return domain.MessagePage{}, fmt.Errorf( + "iterate message page: %w", + err, + ) + } + + if len(page.Items) > limit { + page.Items = page.Items[:limit] + + lastMessage := page.Items[len(page.Items)-1] + nextCursor := domain.EncodeCursor( + lastMessage.CreatedAt, + lastMessage.ID, + chatID, + ) + page.NextCursor = &nextCursor + } + + return page, nil +} diff --git a/internal/store/postgres_sessions.go b/internal/store/postgres_sessions.go new file mode 100644 index 0000000..050b0e1 --- /dev/null +++ b/internal/store/postgres_sessions.go @@ -0,0 +1,108 @@ +package store + +import ( + "context" + "errors" + "fmt" + "time" + + "mtusi2026lab3/internal/domain" + + "github.com/jackc/pgx/v5" +) + +func (s *PostgreSQLStore) CreateSession( + ctx context.Context, + tokenHash []byte, + userID string, + expiresAt time.Time, +) error { + queryContext, cancel := s.withTimeout(ctx) + defer cancel() + + _, err := s.pool.Exec( + queryContext, + ` + INSERT INTO sessions ( + token_hash, + user_id, + expires_at + ) + VALUES ($1, $2, $3) + `, + tokenHash, + userID, + expiresAt, + ) + if err != nil { + return fmt.Errorf("insert session: %w", err) + } + + return nil +} + +func (s *PostgreSQLStore) GetUserBySession( + ctx context.Context, + tokenHash []byte, +) (domain.User, error) { + queryContext, cancel := s.withTimeout(ctx) + defer cancel() + + var user domain.User + + err := s.pool.QueryRow( + queryContext, + ` + SELECT + app_user.id::text, + app_user.username, + app_user.display_name, + app_user.created_at + FROM sessions AS session + JOIN users AS app_user + ON app_user.id = session.user_id + WHERE session.token_hash = $1 + AND session.expires_at > CURRENT_TIMESTAMP + `, + tokenHash, + ).Scan( + &user.ID, + &user.Username, + &user.DisplayName, + &user.CreatedAt, + ) + + if errors.Is(err, pgx.ErrNoRows) { + return domain.User{}, ErrNotFound + } + if err != nil { + return domain.User{}, fmt.Errorf( + "select user by session: %w", + err, + ) + } + + return user, nil +} + +func (s *PostgreSQLStore) DeleteSession( + ctx context.Context, + tokenHash []byte, +) error { + queryContext, cancel := s.withTimeout(ctx) + defer cancel() + + _, err := s.pool.Exec( + queryContext, + ` + DELETE FROM sessions + WHERE token_hash = $1 + `, + tokenHash, + ) + if err != nil { + return fmt.Errorf("delete session: %w", err) + } + + return nil +} diff --git a/internal/store/postgres_users.go b/internal/store/postgres_users.go new file mode 100644 index 0000000..3bf9da4 --- /dev/null +++ b/internal/store/postgres_users.go @@ -0,0 +1,144 @@ +package store + +import ( + "context" + "errors" + "fmt" + + "mtusi2026lab3/internal/domain" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" +) + +func (s *PostgreSQLStore) CreateUser( + ctx context.Context, + username string, + displayName string, + passwordHash string, +) (domain.User, error) { + queryContext, cancel := s.withTimeout(ctx) + defer cancel() + + user := domain.User{ + ID: uuid.NewString(), + Username: username, + DisplayName: displayName, + } + + err := s.pool.QueryRow( + queryContext, + ` + INSERT INTO users ( + id, + username, + display_name, + password_hash + ) + VALUES ($1, $2, $3, $4) + RETURNING created_at + `, + user.ID, + user.Username, + user.DisplayName, + passwordHash, + ).Scan(&user.CreatedAt) + + if err == nil { + return user, nil + } + + var postgresError *pgconn.PgError + if errors.As(err, &postgresError) && + postgresError.Code == "23505" && + postgresError.ConstraintName == "users_username_unique" { + return domain.User{}, ErrConflict + } + + return domain.User{}, fmt.Errorf("insert user: %w", err) +} + +func (s *PostgreSQLStore) GetUserByID( + ctx context.Context, + userID string, +) (domain.User, error) { + queryContext, cancel := s.withTimeout(ctx) + defer cancel() + + var user domain.User + + err := s.pool.QueryRow( + queryContext, + ` + SELECT + id::text, + username, + display_name, + created_at + FROM users + WHERE id = $1 + `, + userID, + ).Scan( + &user.ID, + &user.Username, + &user.DisplayName, + &user.CreatedAt, + ) + + if errors.Is(err, pgx.ErrNoRows) { + return domain.User{}, ErrNotFound + } + if err != nil { + return domain.User{}, fmt.Errorf("select user by id: %w", err) + } + + return user, nil +} + +func (s *PostgreSQLStore) GetUserByUsername( + ctx context.Context, + username string, +) (domain.User, string, error) { + queryContext, cancel := s.withTimeout(ctx) + defer cancel() + + var ( + user domain.User + passwordHash string + ) + + err := s.pool.QueryRow( + queryContext, + ` + SELECT + id::text, + username, + display_name, + created_at, + password_hash + FROM users + WHERE username = $1 + `, + username, + ).Scan( + &user.ID, + &user.Username, + &user.DisplayName, + &user.CreatedAt, + &passwordHash, + ) + + if errors.Is(err, pgx.ErrNoRows) { + return domain.User{}, "", ErrNotFound + } + if err != nil { + return domain.User{}, "", fmt.Errorf( + "select user by username: %w", + err, + ) + } + + return user, passwordHash, nil +} diff --git a/internal/store/repository.go b/internal/store/repository.go new file mode 100644 index 0000000..e400069 --- /dev/null +++ b/internal/store/repository.go @@ -0,0 +1,80 @@ +package store + +import ( + "context" + "time" + + "mtusi2026lab3/internal/domain" +) + +type Repository interface { + CreateUser( + ctx context.Context, + username string, + displayName string, + passwordHash string, + ) (domain.User, error) + + GetUserByID( + ctx context.Context, + userID string, + ) (domain.User, error) + + GetUserByUsername( + ctx context.Context, + username string, + ) (domain.User, string, error) + + CreateChat( + ctx context.Context, + title string, + memberIDs []string, + ) (domain.Chat, error) + + GetChatByID( + ctx context.Context, + chatID string, + callerID string, + ) (domain.Chat, error) + + GetChatsForUser( + ctx context.Context, + userID string, + limit int, + cursor string, + ) (domain.ChatPage, error) + + CreateMessage( + ctx context.Context, + chatID string, + senderID string, + text string, + ) (domain.Message, error) + + GetMessages( + ctx context.Context, + chatID string, + callerID string, + limit int, + cursor string, + ) (domain.MessagePage, error) + + CreateSession( + ctx context.Context, + tokenHash []byte, + userID string, + expiresAt time.Time, + ) error + + GetUserBySession( + ctx context.Context, + tokenHash []byte, + ) (domain.User, error) + + DeleteSession( + ctx context.Context, + tokenHash []byte, + ) error +} + +var _ Repository = (*PostgreSQLStore)(nil) diff --git a/internal/transport/http/handlers/chats.go b/internal/transport/http/handlers/chats.go new file mode 100644 index 0000000..988aba9 --- /dev/null +++ b/internal/transport/http/handlers/chats.go @@ -0,0 +1,168 @@ +package handlers + +import ( + "errors" + "net/http" + "strconv" + + "mtusi2026lab3/internal/domain" + "mtusi2026lab3/internal/store" + "mtusi2026lab3/internal/transport/http/middleware" + "mtusi2026lab3/internal/transport/http/response" + + "github.com/google/uuid" +) + +type CreateChatRequest struct { + Title string `json:"title"` + MemberIDs []string `json:"member_ids"` +} + +func (h *Handler) CreateChat(w http.ResponseWriter, r *http.Request) { + reqID := middleware.GetRequestID(r.Context()) + currentUser := middleware.GetCurrentUser(r.Context()) + + var req CreateChatRequest + if err := decodeJSON(r, &req); err != nil { + writeDecodeJSONError(w, reqID, err) + return + } + + //вызывающий есть в списке, нет дубликатов, валидные UUID + if err := domain.ValidateChatInput(req.Title, req.MemberIDs, currentUser.ID); err != nil { + response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, err.Error(), reqID) + return + } + + chat, err := h.store.CreateChat( + r.Context(), + req.Title, + req.MemberIDs, + ) + if errors.Is(err, store.ErrNotFound) { + response.WriteError( + w, + http.StatusBadRequest, + response.CodeInvalidRequest, + "one or more members do not exist", + reqID, + ) + return + } + if err != nil { + response.WriteError( + w, + http.StatusServiceUnavailable, + response.CodeUnavailable, + "service is temporarily unavailable", + reqID, + ) + return + } + + response.WriteJSON(w, http.StatusCreated, chat, reqID) +} + +// инфа о чате +func (h *Handler) GetChat(w http.ResponseWriter, r *http.Request) { + reqID := middleware.GetRequestID(r.Context()) + currentUser := middleware.GetCurrentUser(r.Context()) + + chatID := r.PathValue("chat_id") + if _, err := uuid.Parse(chatID); err != nil { + response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, "invalid chat_id uuid", reqID) + return + } + + chat, err := h.store.GetChatByID( + r.Context(), + chatID, + currentUser.ID, + ) + if err != nil { + if errors.Is(err, store.ErrNotFound) { + //посторонний или несуществующий чат -> 404 + response.WriteError(w, http.StatusNotFound, response.CodeNotFound, "chat not found", reqID) + return + } + response.WriteError( + w, + http.StatusServiceUnavailable, + response.CodeUnavailable, + "service is temporarily unavailable", + reqID, + ) + return + } + + response.WriteJSON(w, http.StatusOK, chat, reqID) +} + +// список всех чатов текущего пользователя +func (h *Handler) ListChats(w http.ResponseWriter, r *http.Request) { + reqID := middleware.GetRequestID(r.Context()) + currentUser := middleware.GetCurrentUser(r.Context()) + query := r.URL.Query() + + limit := 50 + + if query.Has("limit") { + limitStr := query.Get("limit") + val, err := strconv.Atoi(limitStr) + + if err != nil || val < 1 || val > 100 { + response.WriteError( + w, + http.StatusBadRequest, + response.CodeInvalidRequest, + "limit must be an integer between 1 and 100", + reqID, + ) + return + } + + limit = val + } + + cursor := query.Get("cursor") + if query.Has("cursor") && cursor == "" { + response.WriteError( + w, + http.StatusBadRequest, + response.CodeInvalidRequest, + "cursor must not be empty", + reqID, + ) + return + } + + page, err := h.store.GetChatsForUser( + r.Context(), + currentUser.ID, + limit, + cursor, + ) + if err != nil { + if errors.Is(err, store.ErrInvalidCursor) { + response.WriteError( + w, + http.StatusBadRequest, + response.CodeInvalidRequest, + "invalid cursor", + reqID, + ) + return + } + + response.WriteError( + w, + http.StatusServiceUnavailable, + response.CodeUnavailable, + "service is temporarily unavailable", + reqID, + ) + return + } + + response.WriteJSON(w, http.StatusOK, page, reqID) +} diff --git a/internal/transport/http/handlers/handler.go b/internal/transport/http/handlers/handler.go new file mode 100644 index 0000000..dbb1764 --- /dev/null +++ b/internal/transport/http/handlers/handler.go @@ -0,0 +1,149 @@ +package handlers + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "io" + "mime" + "net/http" + "strings" + "time" + "unicode/utf8" + + "mtusi2026lab3/internal/store" + "mtusi2026lab3/internal/transport/http/response" +) + +const maxJSONBodyBytes = 1 << 20 + +var ( + errUnsupportedMediaType = errors.New("unsupported media type") + errJSONBodyTooLarge = errors.New("JSON body exceeds 1 MiB") +) + +type ReadinessChecker interface { + Ping(ctx context.Context) error +} + +type Option func(*Handler) + +type Handler struct { + store store.Repository + readinessChecker ReadinessChecker + readinessTimeout time.Duration + sessionTTL time.Duration +} + +func NewHandler( + repository store.Repository, + options ...Option, +) *Handler { + handler := &Handler{ + store: repository, + readinessTimeout: 2 * time.Second, + sessionTTL: time.Hour, + } + + for _, option := range options { + option(handler) + } + + return handler +} + +func WithReadiness( + checker ReadinessChecker, + timeout time.Duration, +) Option { + return func(handler *Handler) { + handler.readinessChecker = checker + handler.readinessTimeout = timeout + } +} + +func WithSessionTTL(ttl time.Duration) Option { + return func(handler *Handler) { + handler.sessionTTL = ttl + } +} + +func decodeJSON(r *http.Request, destination any) error { + mediaType, parameters, err := mime.ParseMediaType( + r.Header.Get("Content-Type"), + ) + if err != nil || mediaType != "application/json" { + return errUnsupportedMediaType + } + if charset, exists := parameters["charset"]; exists && + !strings.EqualFold(charset, "utf-8") { + return errUnsupportedMediaType + } + + if r.Body == nil { + return errors.New("request body is empty") + } + defer r.Body.Close() + + payload, err := io.ReadAll(io.LimitReader( + r.Body, + maxJSONBodyBytes+1, + )) + if err != nil { + return errors.New("read request body") + } + if len(payload) > maxJSONBodyBytes { + return errJSONBodyTooLarge + } + if !utf8.Valid(payload) { + return errors.New("request body must be valid UTF-8") + } + + decoder := json.NewDecoder(bytes.NewReader(payload)) + decoder.DisallowUnknownFields() + + if err := decoder.Decode(destination); err != nil { + return err + } + + var extra json.RawMessage + if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) { + return errors.New("extra data after JSON") + } + + return nil +} + +func writeDecodeJSONError( + w http.ResponseWriter, + requestID string, + err error, +) { + switch { + case errors.Is(err, errUnsupportedMediaType): + response.WriteError( + w, + http.StatusUnsupportedMediaType, + response.CodeUnsupportedMediaType, + "Content-Type must be application/json", + requestID, + ) + case errors.Is(err, errJSONBodyTooLarge): + response.WriteError( + w, + http.StatusRequestEntityTooLarge, + response.CodePayloadTooLarge, + err.Error(), + requestID, + ) + default: + response.WriteError( + w, + http.StatusBadRequest, + response.CodeInvalidRequest, + "malformed or invalid JSON: "+err.Error(), + requestID, + ) + } +} diff --git a/internal/transport/http/handlers/health.go b/internal/transport/http/handlers/health.go new file mode 100644 index 0000000..ce63879 --- /dev/null +++ b/internal/transport/http/handlers/health.go @@ -0,0 +1,62 @@ +package handlers + +import ( + "context" + "net/http" + + "mtusi2026lab3/internal/transport/http/middleware" + "mtusi2026lab3/internal/transport/http/response" +) + +// HealthLive проверяет только то, что HTTP-процесс работает. +func (h *Handler) HealthLive(w http.ResponseWriter, r *http.Request) { + requestID := middleware.GetRequestID(r.Context()) + + response.WriteJSON( + w, + http.StatusOK, + map[string]string{"status": "ok"}, + requestID, + ) +} + +// HealthReady проверяет зависимости, без которых API не может обслуживать трафик. +func (h *Handler) HealthReady(w http.ResponseWriter, r *http.Request) { + requestID := middleware.GetRequestID(r.Context()) + + // Этот вариант сохраняет работоспособность изолированных unit-тестов, + // в которых PostgreSQL намеренно не создаётся. + if h.readinessChecker == nil { + response.WriteJSON( + w, + http.StatusOK, + map[string]string{"status": "ok"}, + requestID, + ) + return + } + + ctx, cancel := context.WithTimeout( + r.Context(), + h.readinessTimeout, + ) + defer cancel() + + if err := h.readinessChecker.Ping(ctx); err != nil { + response.WriteError( + w, + http.StatusServiceUnavailable, + response.CodeUnavailable, + "service is not ready", + requestID, + ) + return + } + + response.WriteJSON( + w, + http.StatusOK, + map[string]string{"status": "ok"}, + requestID, + ) +} diff --git a/internal/transport/http/handlers/messages.go b/internal/transport/http/handlers/messages.go new file mode 100644 index 0000000..25bdd9c --- /dev/null +++ b/internal/transport/http/handlers/messages.go @@ -0,0 +1,159 @@ +package handlers + +import ( + "errors" + "net/http" + "strconv" + + "mtusi2026lab3/internal/domain" + "mtusi2026lab3/internal/store" + "mtusi2026lab3/internal/transport/http/middleware" + "mtusi2026lab3/internal/transport/http/response" + + "github.com/google/uuid" +) + +type CreateMessageRequest struct { + Text string `json:"text"` +} + +// CreateMessage отправляет сообщение в чат +func (h *Handler) CreateMessage(w http.ResponseWriter, r *http.Request) { + reqID := middleware.GetRequestID(r.Context()) + currentUser := middleware.GetCurrentUser(r.Context()) + + chatID := r.PathValue("chat_id") + if _, err := uuid.Parse(chatID); err != nil { + response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, "invalid chat_id uuid", reqID) + return + } + + var req CreateMessageRequest + if err := decodeJSON(r, &req); err != nil { + writeDecodeJSONError(w, reqID, err) + return + } + + //не пустой, не только пробелы, до 4000 рун + if err := domain.ValidateMessageText(req.Text); err != nil { + response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, err.Error(), reqID) + return + } + + //автор сообщения строго выводится из сессии (currentUser.ID) + msg, err := h.store.CreateMessage( + r.Context(), + chatID, + currentUser.ID, + req.Text, + ) + if err != nil { + if errors.Is(err, store.ErrNotFound) { + // чата нет/пользователь не участник -> 404 + response.WriteError(w, http.StatusNotFound, response.CodeNotFound, "chat not found", reqID) + return + } + response.WriteError( + w, + http.StatusServiceUnavailable, + response.CodeUnavailable, + "service is temporarily unavailable", + reqID, + ) + return + } + + response.WriteJSON(w, http.StatusCreated, msg, reqID) +} + +// GetMessages возвращает историю сообщений чата с пагинацией по курсору +func (h *Handler) GetMessages(w http.ResponseWriter, r *http.Request) { + reqID := middleware.GetRequestID(r.Context()) + currentUser := middleware.GetCurrentUser(r.Context()) + + chatID := r.PathValue("chat_id") + if _, err := uuid.Parse(chatID); err != nil { + response.WriteError(w, http.StatusBadRequest, response.CodeInvalidRequest, "invalid chat_id uuid", reqID) + return + } + + query := r.URL.Query() + + limit := 50 + if query.Has("limit") { + limitString := query.Get("limit") + + parsedLimit, err := strconv.Atoi(limitString) + if err != nil || parsedLimit < 1 || parsedLimit > 100 { + response.WriteError( + w, + http.StatusBadRequest, + response.CodeInvalidRequest, + "limit must be an integer between 1 and 100", + reqID, + ) + return + } + + limit = parsedLimit + } + + cursor := query.Get("cursor") + if query.Has("cursor") && cursor == "" { + response.WriteError( + w, + http.StatusBadRequest, + response.CodeInvalidRequest, + "cursor must not be empty", + reqID, + ) + return + } + + page, err := h.store.GetMessages( + r.Context(), + chatID, + currentUser.ID, + limit, + cursor, + ) + if errors.Is(err, store.ErrNotFound) { + response.WriteError( + w, + http.StatusNotFound, + response.CodeNotFound, + "chat not found", + reqID, + ) + return + } + + if errors.Is(err, store.ErrInvalidCursor) { + response.WriteError( + w, + http.StatusBadRequest, + response.CodeInvalidRequest, + "invalid cursor", + reqID, + ) + return + } + + if err != nil { + response.WriteError( + w, + http.StatusServiceUnavailable, + response.CodeUnavailable, + "service is temporarily unavailable", + reqID, + ) + return + } + + // сообщений нет, [] вместо null + if page.Items == nil { + page.Items = make([]domain.Message, 0) + } + + response.WriteJSON(w, http.StatusOK, page, reqID) +} diff --git a/internal/transport/http/handlers/sessions.go b/internal/transport/http/handlers/sessions.go new file mode 100644 index 0000000..412f5d0 --- /dev/null +++ b/internal/transport/http/handlers/sessions.go @@ -0,0 +1,165 @@ +package handlers + +import ( + "errors" + "net/http" + "time" + "unicode/utf8" + + "mtusi2026lab3/internal/domain" + "mtusi2026lab3/internal/security" + "mtusi2026lab3/internal/store" + "mtusi2026lab3/internal/transport/http/middleware" + "mtusi2026lab3/internal/transport/http/response" +) + +const basicChallenge = `Basic realm="messenger", charset="UTF-8"` + +// dummyPasswordHash keeps the expensive Argon2id path for an unknown username. +// The all-zero digest is intentionally not a real user's credential; only the +// encoded parameters and lengths need to be valid for constant-cost checking. +const dummyPasswordHash = "$argon2id$v=19$m=19456,t=2,p=1$" + + "AAAAAAAAAAAAAAAAAAAAAA$" + + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + +func (h *Handler) CreateSession( + w http.ResponseWriter, + r *http.Request, +) { + requestID := middleware.GetRequestID(r.Context()) + + username, password, ok := r.BasicAuth() + if !ok || username == "" || + !utf8.ValidString(username) || !utf8.ValidString(password) { + writeBasicUnauthorized(w, requestID) + return + } + + user, passwordHash, err := h.store.GetUserByUsername( + r.Context(), + username, + ) + userNotFound := errors.Is(err, store.ErrNotFound) + if userNotFound { + passwordHash = dummyPasswordHash + } + if err != nil { + if !userNotFound { + response.WriteError( + w, + http.StatusServiceUnavailable, + response.CodeUnavailable, + "service is temporarily unavailable", + requestID, + ) + return + } + } + + passwordMatches, err := security.VerifyPassword( + password, + passwordHash, + ) + if err != nil { + response.WriteError( + w, + http.StatusInternalServerError, + response.CodeInternalError, + "stored password hash is invalid", + requestID, + ) + return + } + if userNotFound || !passwordMatches { + writeBasicUnauthorized(w, requestID) + return + } + + token, tokenHash, err := security.GenerateSessionToken() + if err != nil { + response.WriteError( + w, + http.StatusInternalServerError, + response.CodeInternalError, + "failed to create session", + requestID, + ) + return + } + + expiresAt := time.Now().UTC().Add(h.sessionTTL) + + if err := h.store.CreateSession( + r.Context(), + tokenHash, + user.ID, + expiresAt, + ); err != nil { + response.WriteError( + w, + http.StatusServiceUnavailable, + response.CodeUnavailable, + "service is temporarily unavailable", + requestID, + ) + return + } + + session := domain.Session{ + Token: token, + TokenType: "Bearer", + ExpiresAt: expiresAt, + User: user, + } + + response.WriteJSON( + w, + http.StatusCreated, + session, + requestID, + ) +} + +func (h *Handler) DeleteCurrentSession( + w http.ResponseWriter, + r *http.Request, +) { + requestID := middleware.GetRequestID(r.Context()) + tokenHash := middleware.GetCurrentSessionTokenHash(r.Context()) + + if err := h.store.DeleteSession( + r.Context(), + tokenHash, + ); err != nil { + response.WriteError( + w, + http.StatusServiceUnavailable, + response.CodeUnavailable, + "service is temporarily unavailable", + requestID, + ) + return + } + + response.WriteJSON( + w, + http.StatusNoContent, + nil, + requestID, + ) +} + +func writeBasicUnauthorized( + w http.ResponseWriter, + requestID string, +) { + w.Header().Set("WWW-Authenticate", basicChallenge) + + response.WriteError( + w, + http.StatusUnauthorized, + response.CodeUnauthorized, + "invalid username or password", + requestID, + ) +} diff --git a/internal/transport/http/handlers/users.go b/internal/transport/http/handlers/users.go new file mode 100644 index 0000000..cde4af7 --- /dev/null +++ b/internal/transport/http/handlers/users.go @@ -0,0 +1,113 @@ +package handlers + +import ( + "errors" + "net/http" + + "mtusi2026lab3/internal/domain" + "mtusi2026lab3/internal/security" + "mtusi2026lab3/internal/store" + "mtusi2026lab3/internal/transport/http/middleware" + "mtusi2026lab3/internal/transport/http/response" +) + +type CreateUserRequest struct { + Username string `json:"username"` + DisplayName string `json:"display_name"` + Password string `json:"password"` +} + +func (h *Handler) CreateUser(w http.ResponseWriter, r *http.Request) { + requestID := middleware.GetRequestID(r.Context()) + + var request CreateUserRequest + if err := decodeJSON(r, &request); err != nil { + writeDecodeJSONError(w, requestID, err) + return + } + + userCandidate := domain.User{ + Username: request.Username, + DisplayName: request.DisplayName, + } + + if err := userCandidate.Validate(); err != nil { + response.WriteError( + w, + http.StatusBadRequest, + response.CodeInvalidRequest, + err.Error(), + requestID, + ) + return + } + + if err := security.ValidatePassword(request.Password); err != nil { + response.WriteError( + w, + http.StatusBadRequest, + response.CodeInvalidRequest, + err.Error(), + requestID, + ) + return + } + + passwordHash, err := security.HashPassword(request.Password) + if err != nil { + response.WriteError( + w, + http.StatusInternalServerError, + response.CodeInternalError, + "failed to process password", + requestID, + ) + return + } + + createdUser, err := h.store.CreateUser( + r.Context(), + request.Username, + request.DisplayName, + passwordHash, + ) + if errors.Is(err, store.ErrConflict) { + response.WriteError( + w, + http.StatusConflict, + response.CodeConflict, + "username already exists", + requestID, + ) + return + } + if err != nil { + response.WriteError( + w, + http.StatusServiceUnavailable, + response.CodeUnavailable, + "service is temporarily unavailable", + requestID, + ) + return + } + + response.WriteJSON( + w, + http.StatusCreated, + createdUser, + requestID, + ) +} + +func (h *Handler) GetMe(w http.ResponseWriter, r *http.Request) { + requestID := middleware.GetRequestID(r.Context()) + currentUser := middleware.GetCurrentUser(r.Context()) + + response.WriteJSON( + w, + http.StatusOK, + currentUser, + requestID, + ) +} diff --git a/internal/transport/http/middleware/auth.go b/internal/transport/http/middleware/auth.go new file mode 100644 index 0000000..827e0c8 --- /dev/null +++ b/internal/transport/http/middleware/auth.go @@ -0,0 +1,117 @@ +package middleware + +import ( + "context" + "errors" + "net/http" + "strings" + + "mtusi2026lab3/internal/domain" + "mtusi2026lab3/internal/security" + "mtusi2026lab3/internal/store" + "mtusi2026lab3/internal/transport/http/response" +) + +const bearerChallenge = `Bearer realm="messenger"` + +const ( + UserContextKey contextKey = "current_user" + sessionTokenHashKey contextKey = "session_token_hash" +) + +type SessionAuthenticator interface { + GetUserBySession( + ctx context.Context, + tokenHash []byte, + ) (domain.User, error) +} + +func RequireAuth( + authenticator SessionAuthenticator, + next http.HandlerFunc, +) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + requestID := GetRequestID(r.Context()) + + token, ok := bearerToken(r.Header.Get("Authorization")) + if !ok { + writeBearerUnauthorized(w, requestID) + return + } + + tokenHash := security.HashSessionToken(token) + + user, err := authenticator.GetUserBySession( + r.Context(), + tokenHash, + ) + if errors.Is(err, store.ErrNotFound) { + writeBearerUnauthorized(w, requestID) + return + } + if err != nil { + response.WriteError( + w, + http.StatusServiceUnavailable, + response.CodeUnavailable, + "service is temporarily unavailable", + requestID, + ) + return + } + + ctx := context.WithValue( + r.Context(), + UserContextKey, + user, + ) + ctx = context.WithValue( + ctx, + sessionTokenHashKey, + tokenHash, + ) + + next(w, r.WithContext(ctx)) + } +} + +func GetCurrentUser(ctx context.Context) domain.User { + user, _ := ctx.Value(UserContextKey).(domain.User) + return user +} + +func GetCurrentSessionTokenHash(ctx context.Context) []byte { + tokenHash, _ := ctx.Value(sessionTokenHashKey).([]byte) + + result := make([]byte, len(tokenHash)) + copy(result, tokenHash) + + return result +} + +func bearerToken(authorization string) (string, bool) { + parts := strings.Fields(authorization) + + if len(parts) != 2 || + !strings.EqualFold(parts[0], "Bearer") || + parts[1] == "" { + return "", false + } + + return parts[1], true +} + +func writeBearerUnauthorized( + w http.ResponseWriter, + requestID string, +) { + w.Header().Set("WWW-Authenticate", bearerChallenge) + + response.WriteError( + w, + http.StatusUnauthorized, + response.CodeUnauthorized, + "invalid or expired bearer token", + requestID, + ) +} diff --git a/internal/transport/http/middleware/logger.go b/internal/transport/http/middleware/logger.go new file mode 100644 index 0000000..93c405b --- /dev/null +++ b/internal/transport/http/middleware/logger.go @@ -0,0 +1,44 @@ +package middleware + +import ( + "log" + "net/http" + "time" +) + +// responseWriterInterceptor перехватывает статус-код ответа для логов +type responseWriterInterceptor struct { + http.ResponseWriter + statusCode int +} + +func (w *responseWriterInterceptor) WriteHeader(code int) { + w.statusCode = code + w.ResponseWriter.WriteHeader(code) +} + +func Logger(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + start := time.Now() + + interceptor := &responseWriterInterceptor{ + ResponseWriter: w, + statusCode: http.StatusOK, // дефолтный статус если WriteHeader не вызывался + } + + next.ServeHTTP(interceptor, r) + + reqID := GetRequestID(r.Context()) + duration := time.Since(start) + + // метаданные без r.Body + log.Printf( + "[HTTP] %s %s | status: %d | duration: %v | request_id: %s", + r.Method, + r.URL.Path, + interceptor.statusCode, + duration, + reqID, + ) + }) +} diff --git a/internal/transport/http/middleware/recovery.go b/internal/transport/http/middleware/recovery.go new file mode 100644 index 0000000..8a59a74 --- /dev/null +++ b/internal/transport/http/middleware/recovery.go @@ -0,0 +1,28 @@ +package middleware + +import ( + "net/http" + + "mtusi2026lab3/internal/transport/http/response" +) + +// Recovery перехватывает панику и возвращает клиенту валидный JSON 500 +func Recovery(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + defer func() { + if err := recover(); err != nil { + reqID := GetRequestID(r.Context()) + //из контракта: не раскрывать stack trace и внутренности + response.WriteError( + w, + http.StatusInternalServerError, + response.CodeInternalError, + "internal server error", + reqID, + ) + } + }() + + next.ServeHTTP(w, r) + }) +} diff --git a/internal/transport/http/middleware/request_id.go b/internal/transport/http/middleware/request_id.go new file mode 100644 index 0000000..228a77a --- /dev/null +++ b/internal/transport/http/middleware/request_id.go @@ -0,0 +1,35 @@ +package middleware + +import ( + "context" + "net/http" + + "github.com/google/uuid" +) + +type contextKey string + +const RequestIDKey contextKey = "request_id" + +// RequestID извлекает или генерирует X-Request-Id и кладет его в контекст и заголовок ответа +func RequestID(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + reqID := r.Header.Get("X-Request-Id") + if reqID == "" { + reqID = uuid.NewString() + } + + w.Header().Set("X-Request-Id", reqID) + + ctx := context.WithValue(r.Context(), RequestIDKey, reqID) + next.ServeHTTP(w, r.WithContext(ctx)) + }) +} + +// GetRequestID достает ID запроса из контекста +func GetRequestID(ctx context.Context) string { + if val, ok := ctx.Value(RequestIDKey).(string); ok { + return val + } + return uuid.NewString() +} diff --git a/internal/transport/http/response/response.go b/internal/transport/http/response/response.go new file mode 100644 index 0000000..8947468 --- /dev/null +++ b/internal/transport/http/response/response.go @@ -0,0 +1,63 @@ +package response + +import ( + "encoding/json" + "net/http" +) + +// коды ошибок по контракту +const ( + CodeInvalidRequest = "invalid_request" + CodePayloadTooLarge = "payload_too_large" + CodeUnsupportedMediaType = "unsupported_media_type" + CodeUnauthorized = "unauthorized" + CodeNotFound = "not_found" + CodeConflict = "conflict" + CodeUnavailable = "unavailable" + CodeInternalError = "internal_error" +) + +type ErrorPayload struct { + Code string `json:"code"` + Message string `json:"message"` + RequestID string `json:"request_id"` +} + +// ErrorResponse — строгое тело ответа при любой ошибке +type ErrorResponse struct { + Error ErrorPayload `json:"error"` +} + +// WriteJSON отправляет любой успешный ответ с правильными заголовками +func WriteJSON(w http.ResponseWriter, statusCode int, data any, requestID string) { + w.Header().Set("Content-Type", "application/json; charset=utf-8") + if requestID != "" { + w.Header().Set("X-Request-Id", requestID) + } + + w.WriteHeader(statusCode) + + if data != nil { + _ = json.NewEncoder(w).Encode(data) + } +} + +// WriteError формирует стандартизированную ошибку с совпадением request_id в теле и заголовке +func WriteError(w http.ResponseWriter, statusCode int, code string, message string, requestID string) { + w.Header().Set("Content-Type", "application/json; charset=utf-8") + if requestID != "" { + w.Header().Set("X-Request-Id", requestID) + } + + w.WriteHeader(statusCode) + + resp := ErrorResponse{ + Error: ErrorPayload{ + Code: code, + Message: message, + RequestID: requestID, + }, + } + + _ = json.NewEncoder(w).Encode(resp) +} diff --git a/migrations/000001_initial.down.sql b/migrations/000001_initial.down.sql new file mode 100644 index 0000000..33c67e4 --- /dev/null +++ b/migrations/000001_initial.down.sql @@ -0,0 +1,9 @@ +BEGIN; + +DROP TABLE sessions; +DROP TABLE messages; +DROP TABLE chat_members; +DROP TABLE chats; +DROP TABLE users; + +COMMIT; \ No newline at end of file diff --git a/migrations/000001_initial.up.sql b/migrations/000001_initial.up.sql new file mode 100644 index 0000000..36b1a59 --- /dev/null +++ b/migrations/000001_initial.up.sql @@ -0,0 +1,112 @@ +BEGIN; + +CREATE TABLE users ( + id UUID PRIMARY KEY, + username VARCHAR(32) NOT NULL, + display_name TEXT NOT NULL, + password_hash TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT users_username_unique + UNIQUE (username), + + CONSTRAINT users_username_format + CHECK (username ~ '^[a-z0-9_]{3,32}$'), + + CONSTRAINT users_display_name_length + CHECK (char_length(display_name) BETWEEN 1 AND 100), + + CONSTRAINT users_display_name_not_blank + CHECK (btrim(display_name) <> ''), + + CONSTRAINT users_password_hash_not_blank + CHECK (btrim(password_hash) <> '') +); + +CREATE TABLE chats ( + id UUID PRIMARY KEY, + title TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT chats_title_length + CHECK (char_length(title) BETWEEN 1 AND 100), + + CONSTRAINT chats_title_not_blank + CHECK (btrim(title) <> '') +); + +CREATE INDEX chats_created_at_id_idx + ON chats (created_at, id); + +CREATE TABLE chat_members ( + chat_id UUID NOT NULL, + user_id UUID NOT NULL, + position SMALLINT NOT NULL, + + CONSTRAINT chat_members_primary_key + PRIMARY KEY (chat_id, user_id), + + CONSTRAINT chat_members_position_unique + UNIQUE (chat_id, position), + + CONSTRAINT chat_members_position_range + CHECK (position BETWEEN 0 AND 99), + + CONSTRAINT chat_members_chat_foreign_key + FOREIGN KEY (chat_id) + REFERENCES chats (id) + ON DELETE RESTRICT, + + CONSTRAINT chat_members_user_foreign_key + FOREIGN KEY (user_id) + REFERENCES users (id) + ON DELETE RESTRICT +); + +CREATE INDEX chat_members_user_chat_idx + ON chat_members (user_id, chat_id); + +CREATE TABLE messages ( + id UUID PRIMARY KEY, + chat_id UUID NOT NULL, + sender_id UUID NOT NULL, + text TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT messages_text_length + CHECK (char_length(text) BETWEEN 1 AND 4000), + + CONSTRAINT messages_text_not_blank + CHECK (btrim(text) <> ''), + + CONSTRAINT messages_sender_membership_foreign_key + FOREIGN KEY (chat_id, sender_id) + REFERENCES chat_members (chat_id, user_id) + ON DELETE RESTRICT +); + +CREATE INDEX messages_chat_created_at_id_idx + ON messages (chat_id, created_at, id); + +CREATE TABLE sessions ( + token_hash BYTEA PRIMARY KEY, + user_id UUID NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, + expires_at TIMESTAMPTZ NOT NULL, + + CONSTRAINT sessions_user_foreign_key + FOREIGN KEY (user_id) + REFERENCES users (id) + ON DELETE RESTRICT, + + CONSTRAINT sessions_token_hash_length + CHECK (octet_length(token_hash) = 32), + + CONSTRAINT sessions_expiry_after_creation + CHECK (expires_at > created_at) +); + +CREATE INDEX sessions_expires_at_idx + ON sessions (expires_at); + +COMMIT; \ No newline at end of file diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100755 index 0000000..8ecf62c --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,15 @@ +#!/bin/sh +set -eu + +project_root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +cd "$project_root" + +env_file=${ENV_FILE:-.env} + +# PostgreSQL хранит все обязательные данные и сессии в named volume. +# Redis содержит только восстанавливаемый кеш и намеренно не имеет volume. +docker compose --env-file "$env_file" restart postgres redis +docker compose --env-file "$env_file" up -d --wait postgres redis + +# API перезапускается после восстановления обязательной БД и кеша. +docker compose --env-file "$env_file" restart api diff --git a/student_tests/auth_test.go b/student_tests/auth_test.go new file mode 100644 index 0000000..49c3930 --- /dev/null +++ b/student_tests/auth_test.go @@ -0,0 +1,352 @@ +package student_tests + +import ( + "bytes" + "encoding/base64" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "testing" + "time" + + "mtusi2026lab3/internal/domain" + "mtusi2026lab3/internal/security" + "mtusi2026lab3/internal/store" + "mtusi2026lab3/internal/transport/http/handlers" + "mtusi2026lab3/internal/transport/http/middleware" +) + +const testPassword = "Test-password-123" + +func setupSessionTestServer( + t *testing.T, + sessionTTL time.Duration, +) (*httptest.Server, *store.MemoryRepository) { + t.Helper() + + repository := store.NewMemoryRepository(store.NewMemoryStore()) + handler := handlers.NewHandler( + repository, + handlers.WithSessionTTL(sessionTTL), + ) + + mux := http.NewServeMux() + mux.HandleFunc("POST /api/v1/users", handler.CreateUser) + mux.HandleFunc("POST /api/v1/auth/sessions", handler.CreateSession) + mux.HandleFunc( + "GET /api/v1/users/me", + middleware.RequireAuth(repository, handler.GetMe), + ) + mux.HandleFunc( + "DELETE /api/v1/auth/sessions/current", + middleware.RequireAuth(repository, handler.DeleteCurrentSession), + ) + + var root http.Handler = mux + root = middleware.Recovery(root) + root = middleware.RequestID(root) + + return httptest.NewServer(root), repository +} + +func registerSessionTestUser( + t *testing.T, + baseURL string, + username string, +) domain.User { + t.Helper() + + payload, err := json.Marshal(map[string]string{ + "username": username, + "display_name": "Session test user", + "password": testPassword, + }) + if err != nil { + t.Fatalf("marshal registration request: %v", err) + } + + response, err := http.Post( + baseURL+"/api/v1/users", + "application/json", + bytes.NewReader(payload), + ) + if err != nil { + t.Fatalf("register user: %v", err) + } + defer response.Body.Close() + + if response.StatusCode != http.StatusCreated { + body, _ := io.ReadAll(response.Body) + t.Fatalf("expected registration status 201, got %d: %s", response.StatusCode, body) + } + + var user domain.User + if err := json.NewDecoder(response.Body).Decode(&user); err != nil { + t.Fatalf("decode registered user: %v", err) + } + + return user +} + +func createSessionRequest( + t *testing.T, + baseURL string, + username string, + password string, +) *http.Response { + t.Helper() + + credentials := base64.StdEncoding.EncodeToString( + []byte(username + ":" + password), + ) + + request, err := http.NewRequest( + http.MethodPost, + baseURL+"/api/v1/auth/sessions", + nil, + ) + if err != nil { + t.Fatalf("create login request: %v", err) + } + request.Header.Set("Authorization", "Basic "+credentials) + + response, err := http.DefaultClient.Do(request) + if err != nil { + t.Fatalf("send login request: %v", err) + } + + return response +} + +func TestSessionAuthenticationLifecycle(t *testing.T) { + testServer, repository := setupSessionTestServer(t, time.Hour) + defer testServer.Close() + + alice := registerSessionTestUser(t, testServer.URL, "session_alice") + eve := registerSessionTestUser(t, testServer.URL, "session_eve") + + _, passwordHash, err := repository.GetUserByUsername( + t.Context(), + alice.Username, + ) + if err != nil { + t.Fatalf("read registered user credentials: %v", err) + } + if passwordHash == testPassword || bytes.Contains( + []byte(passwordHash), + []byte(testPassword), + ) { + t.Fatal("repository contains plaintext password") + } + passwordMatches, err := security.VerifyPassword(testPassword, passwordHash) + if err != nil || !passwordMatches { + t.Fatalf("stored password hash does not verify: matches=%v err=%v", passwordMatches, err) + } + + wrongPasswordResponse := createSessionRequest( + t, + testServer.URL, + alice.Username, + "Wrong-password-123", + ) + wrongPasswordResponse.Body.Close() + if wrongPasswordResponse.StatusCode != http.StatusUnauthorized { + t.Fatalf("expected 401 for wrong password, got %d", wrongPasswordResponse.StatusCode) + } + if got := wrongPasswordResponse.Header.Get("WWW-Authenticate"); got != `Basic realm="messenger", charset="UTF-8"` { + t.Fatalf("unexpected Basic challenge: %q", got) + } + + unknownUserResponse := createSessionRequest( + t, + testServer.URL, + "unknown_session_user", + "Wrong-password-123", + ) + unknownUserResponse.Body.Close() + if unknownUserResponse.StatusCode != http.StatusUnauthorized { + t.Fatalf("expected 401 for unknown username, got %d", unknownUserResponse.StatusCode) + } + if got := unknownUserResponse.Header.Get("WWW-Authenticate"); got != `Basic realm="messenger", charset="UTF-8"` { + t.Fatalf("unexpected Basic challenge for unknown username: %q", got) + } + + loginResponse := createSessionRequest( + t, + testServer.URL, + alice.Username, + testPassword, + ) + defer loginResponse.Body.Close() + if loginResponse.StatusCode != http.StatusCreated { + body, _ := io.ReadAll(loginResponse.Body) + t.Fatalf("expected login status 201, got %d: %s", loginResponse.StatusCode, body) + } + + var session domain.Session + if err := json.NewDecoder(loginResponse.Body).Decode(&session); err != nil { + t.Fatalf("decode session: %v", err) + } + if session.Token == "" || session.TokenType != "Bearer" { + t.Fatalf("unexpected session token response: type=%q empty=%v", session.TokenType, session.Token == "") + } + if session.User != alice { + t.Fatalf("session belongs to another user: got %s, want %s", session.User.ID, alice.ID) + } + + testCases := []struct { + name string + authorization string + userIDHeader string + wantStatus int + }{ + { + name: "X-User-Id alone is rejected", + userIDHeader: alice.ID, + wantStatus: http.StatusUnauthorized, + }, + { + name: "Basic is rejected on business endpoint", + authorization: "Basic " + base64.StdEncoding.EncodeToString([]byte(alice.Username+":"+testPassword)), + wantStatus: http.StatusUnauthorized, + }, + { + name: "Bearer identity wins over X-User-Id", + authorization: "Bearer " + session.Token, + userIDHeader: eve.ID, + wantStatus: http.StatusOK, + }, + } + + for _, testCase := range testCases { + t.Run(testCase.name, func(t *testing.T) { + request, err := http.NewRequest( + http.MethodGet, + testServer.URL+"/api/v1/users/me", + nil, + ) + if err != nil { + t.Fatalf("create authenticated request: %v", err) + } + if testCase.authorization != "" { + request.Header.Set("Authorization", testCase.authorization) + } + if testCase.userIDHeader != "" { + request.Header.Set("X-User-Id", testCase.userIDHeader) + } + + response, err := http.DefaultClient.Do(request) + if err != nil { + t.Fatalf("send authenticated request: %v", err) + } + defer response.Body.Close() + + if response.StatusCode != testCase.wantStatus { + t.Fatalf("expected status %d, got %d", testCase.wantStatus, response.StatusCode) + } + + if testCase.wantStatus == http.StatusUnauthorized { + if got := response.Header.Get("WWW-Authenticate"); got != `Bearer realm="messenger"` { + t.Fatalf("unexpected Bearer challenge: %q", got) + } + return + } + + var currentUser domain.User + if err := json.NewDecoder(response.Body).Decode(¤tUser); err != nil { + t.Fatalf("decode current user: %v", err) + } + if currentUser.ID != alice.ID { + t.Fatalf("X-User-Id overrode Bearer identity: got %s, want %s", currentUser.ID, alice.ID) + } + }) + } + + logoutRequest, err := http.NewRequest( + http.MethodDelete, + testServer.URL+"/api/v1/auth/sessions/current", + nil, + ) + if err != nil { + t.Fatalf("create logout request: %v", err) + } + logoutRequest.Header.Set("Authorization", "Bearer "+session.Token) + + logoutResponse, err := http.DefaultClient.Do(logoutRequest) + if err != nil { + t.Fatalf("send logout request: %v", err) + } + logoutBody, err := io.ReadAll(logoutResponse.Body) + logoutResponse.Body.Close() + if err != nil { + t.Fatalf("read logout response: %v", err) + } + if logoutResponse.StatusCode != http.StatusNoContent { + t.Fatalf("expected logout status 204, got %d", logoutResponse.StatusCode) + } + if len(logoutBody) != 0 { + t.Fatalf("logout response contains a body: %q", logoutBody) + } + + revokedRequest, err := http.NewRequest( + http.MethodGet, + testServer.URL+"/api/v1/users/me", + nil, + ) + if err != nil { + t.Fatalf("create revoked-token request: %v", err) + } + revokedRequest.Header.Set("Authorization", "Bearer "+session.Token) + + revokedResponse, err := http.DefaultClient.Do(revokedRequest) + if err != nil { + t.Fatalf("send revoked-token request: %v", err) + } + revokedResponse.Body.Close() + if revokedResponse.StatusCode != http.StatusUnauthorized { + t.Fatalf("expected 401 for revoked token, got %d", revokedResponse.StatusCode) + } +} + +func TestSessionExpiry(t *testing.T) { + testServer, _ := setupSessionTestServer(t, 25*time.Millisecond) + defer testServer.Close() + + user := registerSessionTestUser(t, testServer.URL, "session_expiry") + loginResponse := createSessionRequest( + t, + testServer.URL, + user.Username, + testPassword, + ) + + var session domain.Session + if err := json.NewDecoder(loginResponse.Body).Decode(&session); err != nil { + loginResponse.Body.Close() + t.Fatalf("decode session: %v", err) + } + loginResponse.Body.Close() + + time.Sleep(75 * time.Millisecond) + + request, err := http.NewRequest( + http.MethodGet, + testServer.URL+"/api/v1/users/me", + nil, + ) + if err != nil { + t.Fatalf("create expired-token request: %v", err) + } + request.Header.Set("Authorization", "Bearer "+session.Token) + + response, err := http.DefaultClient.Do(request) + if err != nil { + t.Fatalf("send expired-token request: %v", err) + } + response.Body.Close() + + if response.StatusCode != http.StatusUnauthorized { + t.Fatalf("expected 401 for expired token, got %d", response.StatusCode) + } +} diff --git a/student_tests/cursor_concurrency_test.go b/student_tests/cursor_concurrency_test.go new file mode 100644 index 0000000..f68e4b9 --- /dev/null +++ b/student_tests/cursor_concurrency_test.go @@ -0,0 +1,401 @@ +package student_tests + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "runtime" + "sync" + "testing" + "time" + + "mtusi2026lab3/internal/domain" +) + +func fetchCursorPage( + t *testing.T, + baseURL, chatID, userID string, + limit int, + cursor string, +) domain.MessagePage { + t.Helper() + + endpoint := fmt.Sprintf( + "%s/api/v1/chats/%s/messages?limit=%d", + baseURL, + chatID, + limit, + ) + if cursor != "" { + endpoint += "&cursor=" + url.QueryEscape(cursor) + } + + req, err := http.NewRequest(http.MethodGet, endpoint, nil) + if err != nil { + t.Fatal(err) + } + req.Header.Set("X-User-Id", userID) + + res, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer res.Body.Close() + + if res.StatusCode != http.StatusOK { + body, _ := io.ReadAll(res.Body) + t.Fatalf("expected 200, got %d: %s", res.StatusCode, body) + } + + var page domain.MessagePage + if err := json.NewDecoder(res.Body).Decode(&page); err != nil { + t.Fatalf("decode message page: %v", err) + } + return page +} + +func TestCursorTraversalAfterConcurrentWrites(t *testing.T) { + ts, st := setupTestServer() + defer ts.Close() + + const ( + clients = 10 + messagesPerClient = 100 + expectedMessages = clients * messagesPerClient + ) + + memberIDs := make([]string, 0, clients) + for client := 0; client < clients; client++ { + user, err := st.CreateUser( + fmt.Sprintf("cursor_client_%d", client), + fmt.Sprintf("Cursor client %d", client), + ) + if err != nil { + t.Fatal(err) + } + memberIDs = append(memberIDs, user.ID) + } + + chat, err := st.CreateChat("Concurrent cursor test", memberIDs) + if err != nil { + t.Fatal(err) + } + + start := make(chan struct{}) + var writers sync.WaitGroup + for client := 0; client < clients; client++ { + writers.Add(1) + go func(client int) { + defer writers.Done() + <-start + for message := 0; message < messagesPerClient; message++ { + _, err := st.CreateMessage( + chat.ID, + memberIDs[client], + fmt.Sprintf("client=%d message=%d", client, message), + ) + if err != nil { + t.Errorf("create message: %v", err) + return + } + } + }(client) + } + + close(start) + writers.Wait() + + seen := make(map[string]struct{}, expectedMessages) + duplicateCount := 0 + var previous *domain.Message + firstOrderingViolation := "" + cursor := "" + pageCount := 0 + + for { + pageCount++ + if pageCount > expectedMessages { + t.Fatal("pagination did not terminate") + } + + page := fetchCursorPage(t, ts.URL, chat.ID, memberIDs[0], 17, cursor) + for index := range page.Items { + message := page.Items[index] + if _, duplicate := seen[message.ID]; duplicate { + duplicateCount++ + } + seen[message.ID] = struct{}{} + + if previous != nil { + outOfOrder := message.CreatedAt.Before(previous.CreatedAt) || + (message.CreatedAt.Equal(previous.CreatedAt) && message.ID <= previous.ID) + if outOfOrder && firstOrderingViolation == "" { + firstOrderingViolation = fmt.Sprintf( + "previous=(%s,%s), current=(%s,%s)", + previous.CreatedAt.Format("15:04:05.999999999"), previous.ID, + message.CreatedAt.Format("15:04:05.999999999"), message.ID, + ) + } + } + + messageCopy := message + previous = &messageCopy + } + + if page.NextCursor == nil { + break + } + cursor = *page.NextCursor + } + + if len(seen) != expectedMessages || duplicateCount != 0 { + t.Fatalf( + "cursor traversal returned %d unique messages of %d and %d duplicates; first ordering violation: %s", + len(seen), expectedMessages, duplicateCount, firstOrderingViolation, + ) + } + if firstOrderingViolation != "" { + t.Fatalf("history is not ordered: %s", firstOrderingViolation) + } +} + +func TestCursorTraversalDuringConcurrentWrites(t *testing.T) { + ts, st := setupTestServer() + defer ts.Close() + + const ( + clients = 16 + messagesPerClient = 100 + seedMessages = 100 + pageLimit = 7 + expectedTotal = seedMessages + clients*messagesPerClient + ) + + memberIDs := make([]string, 0, clients) + for client := 0; client < clients; client++ { + user, err := st.CreateUser( + fmt.Sprintf("live_cursor_client_%d", client), + fmt.Sprintf("Live cursor client %d", client), + ) + if err != nil { + t.Fatalf("create user %d: %v", client, err) + } + memberIDs = append(memberIDs, user.ID) + } + + chat, err := st.CreateChat("Live concurrent cursor test", memberIDs) + if err != nil { + t.Fatalf("create chat: %v", err) + } + + // Начальные сообщения нужны, чтобы читатель сразу начал + // двигать курсор, пока остальные сообщения ещё записываются. + expectedIDs := make(map[string]struct{}, expectedTotal) + for index := 0; index < seedMessages; index++ { + message, err := st.CreateMessage( + chat.ID, + memberIDs[0], + fmt.Sprintf("seed message=%d", index), + ) + if err != nil { + t.Fatalf("create seed message %d: %v", index, err) + } + expectedIDs[message.ID] = struct{}{} + } + + var expectedMu sync.Mutex + var writers sync.WaitGroup + var ready sync.WaitGroup + + start := make(chan struct{}) + writerErrors := make(chan error, clients) + + for client := 0; client < clients; client++ { + writers.Add(1) + ready.Add(1) + + go func(client int) { + defer writers.Done() + + ready.Done() + <-start + + for index := 0; index < messagesPerClient; index++ { + // Отдаём планировщику возможность чаще переключать + // конкурентные горутины. + runtime.Gosched() + + message, err := st.CreateMessage( + chat.ID, + memberIDs[client], + fmt.Sprintf("client=%d message=%d", client, index), + ) + if err != nil { + writerErrors <- fmt.Errorf( + "client %d, message %d: %w", + client, + index, + err, + ) + return + } + + expectedMu.Lock() + expectedIDs[message.ID] = struct{}{} + expectedMu.Unlock() + + // Не даём всем писателям завершиться до того, + // как читатель успеет продвинуть курсор. + time.Sleep(50 * time.Microsecond) + } + }(client) + } + + // Сначала убеждаемся, что все горутины готовы, + // и только потом одновременно разрешаем запись. + ready.Wait() + + writersDone := make(chan struct{}) + go func() { + writers.Wait() + close(writersDone) + }() + + close(start) + + seen := make(map[string]struct{}, expectedTotal) + cursor := "" + var previous *domain.Message + + const maxPageRequests = expectedTotal * 4 + finished := false + + for requestNumber := 0; requestNumber < maxPageRequests; requestNumber++ { + page := fetchCursorPage( + t, + ts.URL, + chat.ID, + memberIDs[0], + pageLimit, + cursor, + ) + + for index := range page.Items { + message := page.Items[index] + + if _, duplicate := seen[message.ID]; duplicate { + t.Fatalf( + "message %s was returned more than once", + message.ID, + ) + } + + if previous != nil { + outOfOrder := + message.CreatedAt.Before(previous.CreatedAt) || + (message.CreatedAt.Equal(previous.CreatedAt) && + message.ID <= previous.ID) + + if outOfOrder { + t.Fatalf( + "messages are out of order: previous=(%s,%s), current=(%s,%s)", + previous.CreatedAt.Format(time.RFC3339Nano), + previous.ID, + message.CreatedAt.Format(time.RFC3339Nano), + message.ID, + ) + } + } + + seen[message.ID] = struct{}{} + messageCopy := message + previous = &messageCopy + } + + // Для продолжающегося чтения строим курсор по последнему + // фактически полученному сообщению. Это позволяет опрашивать + // историю, даже если в промежуточный момент сервер вернул + // NextCursor=nil. + if len(page.Items) > 0 { + last := page.Items[len(page.Items)-1] + cursor = domain.EncodeCursor( + last.CreatedAt, + last.ID, + chat.ID, + ) + } + + select { + case <-writersDone: + finished = true + default: + } + + // Все писатели завершились, а после текущего курсора + // больше ничего нет: обход закончен. + if finished && len(page.Items) == 0 { + break + } + + if len(page.Items) == 0 { + runtime.Gosched() + } + + if requestNumber == maxPageRequests-1 { + t.Fatalf( + "pagination did not terminate after %d requests", + maxPageRequests, + ) + } + } + + <-writersDone + close(writerErrors) + + for writerErr := range writerErrors { + t.Errorf("create message: %v", writerErr) + } + + expectedMu.Lock() + missingIDs := make([]string, 0) + for id := range expectedIDs { + if _, found := seen[id]; !found { + missingIDs = append(missingIDs, id) + } + } + expectedCount := len(expectedIDs) + expectedMu.Unlock() + + if expectedCount != expectedTotal { + t.Fatalf( + "writers confirmed %d messages, expected %d", + expectedCount, + expectedTotal, + ) + } + + if len(missingIDs) != 0 { + const displayedMissingIDs = 5 + if len(missingIDs) > displayedMissingIDs { + missingIDs = missingIDs[:displayedMissingIDs] + } + + t.Fatalf( + "cursor traversal returned %d of %d confirmed messages; "+ + "examples of missing IDs: %v", + len(seen), + expectedTotal, + missingIDs, + ) + } + + if len(seen) != expectedTotal { + t.Fatalf( + "cursor traversal returned %d messages, expected %d", + len(seen), + expectedTotal, + ) + } +} diff --git a/student_tests/messenger_test.go b/student_tests/messenger_test.go new file mode 100644 index 0000000..221a44a --- /dev/null +++ b/student_tests/messenger_test.go @@ -0,0 +1,649 @@ +package student_tests + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "net/url" + "sort" + "sync" + "testing" + + "mtusi2026lab3/internal/domain" + "mtusi2026lab3/internal/store" + "mtusi2026lab3/internal/transport/http/handlers" + "mtusi2026lab3/internal/transport/http/middleware" +) + +func requireLegacyAuth( + memoryStore *store.MemoryStore, + next http.HandlerFunc, +) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + userID := r.Header.Get("X-User-Id") + + user, err := memoryStore.GetUserByID(userID) + if err != nil { + http.Error(w, "unauthorized", http.StatusUnauthorized) + return + } + + ctx := context.WithValue( + r.Context(), + middleware.UserContextKey, + user, + ) + + next(w, r.WithContext(ctx)) + } +} + +// изолированный серв для тестов +func setupTestServer() (*httptest.Server, *store.MemoryStore) { + memoryStore := store.NewMemoryStore() + repository := store.NewMemoryRepository(memoryStore) + handler := handlers.NewHandler(repository) + + mux := http.NewServeMux() + mux.HandleFunc("POST /api/v1/users", handler.CreateUser) + mux.HandleFunc( + "GET /api/v1/users/me", + requireLegacyAuth(memoryStore, handler.GetMe), + ) + mux.HandleFunc( + "POST /api/v1/chats", + requireLegacyAuth(memoryStore, handler.CreateChat), + ) + mux.HandleFunc( + "GET /api/v1/chats", + requireLegacyAuth(memoryStore, handler.ListChats), + ) + mux.HandleFunc( + "GET /api/v1/chats/{chat_id}", + requireLegacyAuth(memoryStore, handler.GetChat), + ) + mux.HandleFunc( + "POST /api/v1/chats/{chat_id}/messages", + requireLegacyAuth(memoryStore, handler.CreateMessage), + ) + mux.HandleFunc( + "GET /api/v1/chats/{chat_id}/messages", + requireLegacyAuth(memoryStore, handler.GetMessages), + ) + + var root http.Handler = mux + root = middleware.Recovery(root) + root = middleware.RequestID(root) + + return httptest.NewServer(root), memoryStore +} + +// 1 тест на дубликат username -> 409 Conflict +func TestDuplicateUsername(t *testing.T) { + ts, _ := setupTestServer() + defer ts.Close() + + body := `{ + "username":"bob_the_builder", + "display_name":"Боб", + "password":"Test-password-123"}` + + // Первый раз — 201 Created + res1, _ := http.Post(ts.URL+"/api/v1/users", "application/json", bytes.NewBufferString(body)) + if res1.StatusCode != http.StatusCreated { + t.Fatalf("expected 201, got %d", res1.StatusCode) + } + + // Второй раз тот же username — 409 Conflict + res2, _ := http.Post(ts.URL+"/api/v1/users", "application/json", bytes.NewBufferString(body)) + if res2.StatusCode != http.StatusConflict { + t.Fatalf("expected 409 Conflict for duplicate username, got %d", res2.StatusCode) + } +} + +// 2 тест на неверный JSON и лишние поля -> 400 Invalid Request +func TestInvalidAndExtraJSON(t *testing.T) { + ts, _ := setupTestServer() + defer ts.Close() + + // Кривой JSON (malformed) + res1, _ := http.Post(ts.URL+"/api/v1/users", "application/json", bytes.NewBufferString(`{"username": "bad"`)) + if res1.StatusCode != http.StatusBadRequest { + t.Fatalf("expected 400 for malformed json, got %d", res1.StatusCode) + } + + // Лишнее поле "age" (проверка DisallowUnknownFields) + res2, _ := http.Post(ts.URL+"/api/v1/users", "application/json", bytes.NewBufferString(`{"username":"valid_user","display_name":"User","age":25}`)) + if res2.StatusCode != http.StatusBadRequest { + t.Fatalf("expected 400 for extra fields, got %d", res2.StatusCode) + } +} + +// 3 тст на пустое сообщение и сообщение из одних пробелов -> 400 Invalid Request +func TestEmptyMessageValidation(t *testing.T) { + ts, st := setupTestServer() + defer ts.Close() + + u, _ := st.CreateUser("user_msg_test", "Tester") + chat, _ := st.CreateChat("Test Chat", []string{u.ID}) + + // Пустой текст + req, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/api/v1/chats/%s/messages", ts.URL, chat.ID), bytes.NewBufferString(`{"text":""}`)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-User-Id", u.ID) + + res, _ := http.DefaultClient.Do(req) + if res.StatusCode != http.StatusBadRequest { + t.Fatalf("expected 400 for empty text, got %d", res.StatusCode) + } + + // Текст только из пробелов + reqSpaces, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/api/v1/chats/%s/messages", ts.URL, chat.ID), bytes.NewBufferString(`{"text":" "}`)) + reqSpaces.Header.Set("Content-Type", "application/json") + reqSpaces.Header.Set("X-User-Id", u.ID) + + resSpaces, _ := http.DefaultClient.Do(reqSpaces) + if resSpaces.StatusCode != http.StatusBadRequest { + t.Fatalf("expected 400 for whitespace-only text, got %d", resSpaces.StatusCode) + } +} + +// 4 тест: чужой чат для постороннего -> 404 Not Found (не 403!) +func TestOutsiderChatAccess(t *testing.T) { + ts, st := setupTestServer() + defer ts.Close() + + alice, _ := st.CreateUser("alice_secret", "Алиса") + eve, _ := st.CreateUser("eve_eavesdropper", "Ева") + + chat, _ := st.CreateChat("Секретный чат", []string{alice.ID}) + + // Ева пытается прочитать чат Алисы + req, _ := http.NewRequest(http.MethodGet, fmt.Sprintf("%s/api/v1/chats/%s", ts.URL, chat.ID), nil) + req.Header.Set("X-User-Id", eve.ID) + + res, _ := http.DefaultClient.Do(req) + if res.StatusCode != http.StatusNotFound { + t.Fatalf("expected 404 Not Found (no leak via 403), got %d", res.StatusCode) + } +} + +// 5 Тест: пагинация по нескольким страницам с курсором +func TestCursorPaginationMultiplePages(t *testing.T) { + ts, st := setupTestServer() + defer ts.Close() + + u, _ := st.CreateUser("paging_user", "Пейджер") + chat, _ := st.CreateChat("Чат пагинации", []string{u.ID}) + + // Отправляем 5 сообщений + for i := 1; i <= 5; i++ { + st.CreateMessage(chat.ID, u.ID, fmt.Sprintf("Message %d", i)) + } + + // Запрашиваем порциями по limit=2 + var allReceived []string + cursor := "" + + for { + url := fmt.Sprintf("%s/api/v1/chats/%s/messages?limit=2", ts.URL, chat.ID) + if cursor != "" { + url += "&cursor=" + cursor + } + + req, _ := http.NewRequest(http.MethodGet, url, nil) + req.Header.Set("X-User-Id", u.ID) + res, _ := http.DefaultClient.Do(req) + + var page domain.MessagePage + body, _ := io.ReadAll(res.Body) + json.Unmarshal(body, &page) + res.Body.Close() + + for _, m := range page.Items { + allReceived = append(allReceived, m.Text) + } + + if page.NextCursor == nil { + break + } + cursor = *page.NextCursor + } + + if len(allReceived) != 5 { + t.Fatalf("expected 5 messages total across pages, got %d", len(allReceived)) + } +} + +func TestChatCursorPaginationMultiplePages(t *testing.T) { + ts, st := setupTestServer() + defer ts.Close() + + user, err := st.CreateUser("chat_paging_user", "Пейджер чатов") + if err != nil { + t.Fatalf("failed to create user: %v", err) + } + + outsider, err := st.CreateUser("chat_paging_outsider", "Посторонний") + if err != nil { + t.Fatalf("failed to create outsider: %v", err) + } + + createdChats := make([]domain.Chat, 0, 5) + + for i := 1; i <= 5; i++ { + chat, createErr := st.CreateChat( + fmt.Sprintf("Chat %d", i), + []string{user.ID}, + ) + if createErr != nil { + t.Fatalf("failed to create chat %d: %v", i, createErr) + } + + createdChats = append(createdChats, chat) + + // Чужой чат создаётся между доступными чатами и не должен + // влиять на размер страницы или next_cursor пользователя. + if i == 3 { + if _, createErr = st.CreateChat( + "Outsider chat", + []string{outsider.ID}, + ); createErr != nil { + t.Fatalf("failed to create outsider chat: %v", createErr) + } + } + } + + sort.Slice(createdChats, func(i, j int) bool { + if createdChats[i].CreatedAt.Equal(createdChats[j].CreatedAt) { + return createdChats[i].ID < createdChats[j].ID + } + + return createdChats[i].CreatedAt.Before(createdChats[j].CreatedAt) + }) + + var receivedIDs []string + seenIDs := make(map[string]bool) + seenCursors := make(map[string]bool) + cursor := "" + finished := false + + for pageNumber := 1; pageNumber <= 10; pageNumber++ { + requestURL := ts.URL + "/api/v1/chats?limit=2" + if cursor != "" { + requestURL += "&cursor=" + url.QueryEscape(cursor) + } + + req, err := http.NewRequest(http.MethodGet, requestURL, nil) + if err != nil { + t.Fatalf("failed to create request: %v", err) + } + req.Header.Set("X-User-Id", user.ID) + + res, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatalf("failed to list chats: %v", err) + } + + var page domain.ChatPage + decodeErr := json.NewDecoder(res.Body).Decode(&page) + res.Body.Close() + + if res.StatusCode != http.StatusOK { + t.Fatalf("expected 200, got %d", res.StatusCode) + } + if decodeErr != nil { + t.Fatalf("failed to decode chat page: %v", decodeErr) + } + if len(page.Items) > 2 { + t.Fatalf("page contains %d chats with limit=2", len(page.Items)) + } + + for _, chat := range page.Items { + if seenIDs[chat.ID] { + t.Fatalf("chat %s was returned more than once", chat.ID) + } + + seenIDs[chat.ID] = true + receivedIDs = append(receivedIDs, chat.ID) + } + + if page.NextCursor == nil { + finished = true + break + } + + if seenCursors[*page.NextCursor] { + t.Fatalf("cursor cycle detected") + } + + seenCursors[*page.NextCursor] = true + cursor = *page.NextCursor + } + + if !finished { + t.Fatal("chat pagination did not finish") + } + + if len(receivedIDs) != len(createdChats) { + t.Fatalf( + "expected %d chats across all pages, got %d", + len(createdChats), + len(receivedIDs), + ) + } + + for i, chat := range createdChats { + if receivedIDs[i] != chat.ID { + t.Fatalf( + "chat order differs at position %d: expected %s, got %s", + i, + chat.ID, + receivedIDs[i], + ) + } + } +} + +func TestChatCursorValidation(t *testing.T) { + ts, st := setupTestServer() + defer ts.Close() + + alice, err := st.CreateUser("chat_cursor_alice", "Алиса") + if err != nil { + t.Fatalf("failed to create Alice: %v", err) + } + + bob, err := st.CreateUser("chat_cursor_bob", "Боб") + if err != nil { + t.Fatalf("failed to create Bob: %v", err) + } + + for i := 1; i <= 2; i++ { + if _, err = st.CreateChat( + fmt.Sprintf("Alice chat %d", i), + []string{alice.ID}, + ); err != nil { + t.Fatalf("failed to create Alice chat: %v", err) + } + } + + if _, err = st.CreateChat("Bob chat", []string{bob.ID}); err != nil { + t.Fatalf("failed to create Bob chat: %v", err) + } + + firstRequest, err := http.NewRequest( + http.MethodGet, + ts.URL+"/api/v1/chats?limit=1", + nil, + ) + if err != nil { + t.Fatalf("failed to create first request: %v", err) + } + firstRequest.Header.Set("X-User-Id", alice.ID) + + firstResponse, err := http.DefaultClient.Do(firstRequest) + if err != nil { + t.Fatalf("failed to request first page: %v", err) + } + + var firstPage domain.ChatPage + decodeErr := json.NewDecoder(firstResponse.Body).Decode(&firstPage) + firstResponse.Body.Close() + + if firstResponse.StatusCode != http.StatusOK { + t.Fatalf("expected first page status 200, got %d", firstResponse.StatusCode) + } + if decodeErr != nil { + t.Fatalf("failed to decode first page: %v", decodeErr) + } + if firstPage.NextCursor == nil { + t.Fatal("expected next_cursor for Alice") + } + + foreignRequest, err := http.NewRequest( + http.MethodGet, + ts.URL+"/api/v1/chats?limit=1&cursor="+ + url.QueryEscape(*firstPage.NextCursor), + nil, + ) + if err != nil { + t.Fatalf("failed to create foreign cursor request: %v", err) + } + foreignRequest.Header.Set("X-User-Id", bob.ID) + + foreignResponse, err := http.DefaultClient.Do(foreignRequest) + if err != nil { + t.Fatalf("failed to send foreign cursor request: %v", err) + } + foreignResponse.Body.Close() + + if foreignResponse.StatusCode != http.StatusBadRequest { + t.Fatalf( + "expected 400 for another user's cursor, got %d", + foreignResponse.StatusCode, + ) + } + + malformedRequest, err := http.NewRequest( + http.MethodGet, + ts.URL+"/api/v1/chats?cursor=not-valid-base64!", + nil, + ) + if err != nil { + t.Fatalf("failed to create malformed cursor request: %v", err) + } + malformedRequest.Header.Set("X-User-Id", alice.ID) + + malformedResponse, err := http.DefaultClient.Do(malformedRequest) + if err != nil { + t.Fatalf("failed to send malformed cursor request: %v", err) + } + malformedResponse.Body.Close() + + if malformedResponse.StatusCode != http.StatusBadRequest { + t.Fatalf( + "expected 400 for malformed cursor, got %d", + malformedResponse.StatusCode, + ) + } +} + +// 6 тест: 100 сообщений от 10 клиентов одновременно, защита от гонок +func TestConcurrent100MessagesFrom10Clients(t *testing.T) { + ts, st := setupTestServer() + defer ts.Close() + + // Создаем 10 пользователей + var memberIDs []string + for i := 0; i < 10; i++ { + u, _ := st.CreateUser(fmt.Sprintf("client_%d", i), fmt.Sprintf("Client %d", i)) + memberIDs = append(memberIDs, u.ID) + } + + chat, err := st.CreateChat("Highload Chat", memberIDs) + if err != nil { + t.Fatalf("failed to create chat: %v", err) + } + + var wg sync.WaitGroup + totalClients := 10 + messagesPerClient := 10 + + for i := 0; i < totalClients; i++ { + wg.Add(1) + clientID := memberIDs[i] + + go func(senderID string, clientIndex int) { + defer wg.Done() + + for m := 0; m < messagesPerClient; m++ { + text := fmt.Sprintf("Client %d - Message %d", clientIndex, m) + payload := fmt.Sprintf(`{"text":"%s"}`, text) + + req, _ := http.NewRequest( + http.MethodPost, + fmt.Sprintf("%s/api/v1/chats/%s/messages", ts.URL, chat.ID), + bytes.NewBufferString(payload), + ) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-User-Id", senderID) + + res, err := http.DefaultClient.Do(req) + if err != nil || res.StatusCode != http.StatusCreated { + t.Errorf("failed to send concurrent message: %v", err) + } + if res != nil { + res.Body.Close() + } + } + }(clientID, i) + } + + wg.Wait() + + // должно быть 100 сообщений в чате + page, err := st.GetMessages(chat.ID, memberIDs[0], 200, "") + if err != nil { + t.Fatalf("failed to get messages: %v", err) + } + + if len(page.Items) != 100 { + t.Fatalf("RACE CONDITION DETECTED: expected exactly 100 messages, got %d", len(page.Items)) + } + + // уникальность ID + seenIDs := make(map[string]bool) + for _, m := range page.Items { + if seenIDs[m.ID] { + t.Fatalf("duplicate message ID found: %s", m.ID) + } + seenIDs[m.ID] = true + } +} + +// 7 тест: защита от подделки курсора (чужой чат или битый Base64) -> 400 +func TestForeignAndMalformedCursor(t *testing.T) { + ts, st := setupTestServer() + defer ts.Close() + + u, _ := st.CreateUser("cursor_tester", "Tester") + chatA, _ := st.CreateChat("Chat A", []string{u.ID}) + chatB, _ := st.CreateChat("Chat B", []string{u.ID}) + + // В Чат А кладем несколько сообщений, чтобы при limit=1 появился NextCursor + st.CreateMessage(chatA.ID, u.ID, "Message 1 in A") + st.CreateMessage(chatA.ID, u.ID, "Message 2 in A") + st.CreateMessage(chatA.ID, u.ID, "Message 3 in A") + st.CreateMessage(chatA.ID, u.ID, "Message 4 in A") + st.CreateMessage(chatA.ID, u.ID, "Message 5 in A") + + st.CreateMessage(chatB.ID, u.ID, "Message 1 in B") + st.CreateMessage(chatB.ID, u.ID, "Message 2 in B") + + // Получаем валидный курсор из Чата А (запрашиваем 1 из 2) + pageA, err := st.GetMessages(chatA.ID, u.ID, 1, "") + if err != nil || pageA.NextCursor == nil { + t.Fatalf("expected next_cursor in Chat A, err: %v", err) + } + + // 1. Пытаемся применить курсор от Чата А к Чату Б -> строго 400! + urlForeign := fmt.Sprintf("%s/api/v1/chats/%s/messages?cursor=%s", ts.URL, chatB.ID, *pageA.NextCursor) + reqForeign, _ := http.NewRequest(http.MethodGet, urlForeign, nil) + reqForeign.Header.Set("X-User-Id", u.ID) + resForeign, _ := http.DefaultClient.Do(reqForeign) + + if resForeign.StatusCode != http.StatusBadRequest { + t.Fatalf("expected 400 for foreign chat cursor, got %d", resForeign.StatusCode) + } + + // 2. Битый (невалидный) Base64 -> 400 + urlBad := fmt.Sprintf("%s/api/v1/chats/%s/messages?cursor=not-a-valid-base64!@#", ts.URL, chatB.ID) + reqBad, _ := http.NewRequest(http.MethodGet, urlBad, nil) + reqBad.Header.Set("X-User-Id", u.ID) + resBad, _ := http.DefaultClient.Do(reqBad) + + if resBad.StatusCode != http.StatusBadRequest { + t.Fatalf("expected 400 for malformed cursor, got %d", resBad.StatusCode) + } +} + +// 8 тест валидации создания чата (создателя нет в списке / несуществующий юзер / дубликат) -> 400 +func TestChatCreationValidation(t *testing.T) { + ts, st := setupTestServer() + defer ts.Close() + + alice, _ := st.CreateUser("alice_chat_val", "Alice") + bob, _ := st.CreateUser("bob_chat_val", "Bob") + + // 1. Создатель (Alice) забыла добавить себя в member_ids + bodyNoCaller := fmt.Sprintf(`{"title":"No Caller Chat","member_ids":["%s"]}`, bob.ID) + req1, _ := http.NewRequest(http.MethodPost, ts.URL+"/api/v1/chats", bytes.NewBufferString(bodyNoCaller)) + req1.Header.Set("Content-Type", "application/json") + req1.Header.Set("X-User-Id", alice.ID) + res1, _ := http.DefaultClient.Do(req1) + if res1.StatusCode != http.StatusBadRequest { + t.Fatalf("expected 400 when caller is not in member_ids, got %d", res1.StatusCode) + } + + // 2. В участниках передан несуществующий UUID + bodyFakeUser := fmt.Sprintf(`{"title":"Fake User Chat","member_ids":["%s","00000000-0000-0000-0000-000000000000"]}`, alice.ID) + req2, _ := http.NewRequest(http.MethodPost, ts.URL+"/api/v1/chats", bytes.NewBufferString(bodyFakeUser)) + req2.Header.Set("Content-Type", "application/json") + req2.Header.Set("X-User-Id", alice.ID) + res2, _ := http.DefaultClient.Do(req2) + if res2.StatusCode != http.StatusBadRequest { + t.Fatalf("expected 400 for non-existent member_id, got %d", res2.StatusCode) + } + + // 3. Дубликат участника в списке + bodyDuplicate := fmt.Sprintf(`{"title":"Duplicate Member","member_ids":["%s","%s"]}`, alice.ID, alice.ID) + req3, _ := http.NewRequest(http.MethodPost, ts.URL+"/api/v1/chats", bytes.NewBufferString(bodyDuplicate)) + req3.Header.Set("Content-Type", "application/json") + req3.Header.Set("X-User-Id", alice.ID) + res3, _ := http.DefaultClient.Do(req3) + if res3.StatusCode != http.StatusBadRequest { + t.Fatalf("expected 400 for duplicate member_ids, got %d", res3.StatusCode) + } +} + +// 9 тест лимитов символов Unicode (длина до 4000 рун и отказ при >4000) +func TestUnicodeLimits(t *testing.T) { + ts, st := setupTestServer() + defer ts.Close() + + u, _ := st.CreateUser("unicode_master", "Иван 🚀") + chat, _ := st.CreateChat("Unicode Chat", []string{u.ID}) + + // Ровно 4000 смайликов (в байтах это 16000 байт, но в рунах — ровно 4000!) + validRunes := make([]rune, 4000) + for i := range validRunes { + validRunes[i] = '🔥' + } + bodyValid := fmt.Sprintf(`{"text":"%s"}`, string(validRunes)) + req1, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/api/v1/chats/%s/messages", ts.URL, chat.ID), bytes.NewBufferString(bodyValid)) + req1.Header.Set("Content-Type", "application/json") + req1.Header.Set("X-User-Id", u.ID) + res1, _ := http.DefaultClient.Do(req1) + if res1.StatusCode != http.StatusCreated { + t.Fatalf("expected 201 for 4000 unicode runes, got %d", res1.StatusCode) + } + + // 4001 символ -> строго 400 Invalid Request! + tooLongRunes := make([]rune, 4001) + for i := range tooLongRunes { + tooLongRunes[i] = 'a' + } + bodyTooLong := fmt.Sprintf(`{"text":"%s"}`, string(tooLongRunes)) + req2, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/api/v1/chats/%s/messages", ts.URL, chat.ID), bytes.NewBufferString(bodyTooLong)) + req2.Header.Set("Content-Type", "application/json") + req2.Header.Set("X-User-Id", u.ID) + res2, _ := http.DefaultClient.Do(req2) + if res2.StatusCode != http.StatusBadRequest { + t.Fatalf("expected 400 for 4001 runes, got %d", res2.StatusCode) + } +} diff --git a/student_tests/request_validation_test.go b/student_tests/request_validation_test.go new file mode 100644 index 0000000..70251df --- /dev/null +++ b/student_tests/request_validation_test.go @@ -0,0 +1,246 @@ +package student_tests + +import ( + "bytes" + "encoding/base64" + "encoding/json" + "io" + "net/http" + "testing" +) + +type contractErrorResponse struct { + Error struct { + Code string `json:"code"` + Message string `json:"message"` + RequestID string `json:"request_id"` + } `json:"error"` +} + +func requireContractError( + t *testing.T, + response *http.Response, + wantStatus int, + wantCode string, +) { + t.Helper() + defer response.Body.Close() + + if response.StatusCode != wantStatus { + body, _ := io.ReadAll(response.Body) + t.Fatalf( + "expected status %d, got %d: %s", + wantStatus, + response.StatusCode, + body, + ) + } + + requestID := response.Header.Get("X-Request-Id") + if requestID == "" { + t.Fatal("error response has no X-Request-Id") + } + if contentType := response.Header.Get("Content-Type"); contentType != "application/json; charset=utf-8" { + t.Fatalf("unexpected error Content-Type: %q", contentType) + } + + var payload contractErrorResponse + if err := json.NewDecoder(response.Body).Decode(&payload); err != nil { + t.Fatalf("decode error response: %v", err) + } + if payload.Error.Code != wantCode { + t.Fatalf( + "expected error code %q, got %q", + wantCode, + payload.Error.Code, + ) + } + if payload.Error.Message == "" { + t.Fatal("error response has an empty message") + } + if payload.Error.RequestID != requestID { + t.Fatal("body request_id differs from X-Request-Id") + } +} + +func sendRegistration( + t *testing.T, + baseURL string, + contentType string, + body []byte, +) *http.Response { + t.Helper() + + request, err := http.NewRequest( + http.MethodPost, + baseURL+"/api/v1/users", + bytes.NewReader(body), + ) + if err != nil { + t.Fatalf("create registration request: %v", err) + } + if contentType != "" { + request.Header.Set("Content-Type", contentType) + } + + response, err := http.DefaultClient.Do(request) + if err != nil { + t.Fatalf("send registration request: %v", err) + } + + return response +} + +func TestJSONRequestRequiresApplicationJSON(t *testing.T) { + testServer, _ := setupTestServer() + defer testServer.Close() + + body := []byte( + `{"username":"mime_probe","display_name":"Test",` + + `"password":"123456789012"}`, + ) + + for _, contentType := range []string{ + "", + "text/plain", + "application/xml", + "application/json; charset=iso-8859-1", + } { + contentType := contentType + t.Run(contentType, func(t *testing.T) { + response := sendRegistration( + t, + testServer.URL, + contentType, + body, + ) + requireContractError( + t, + response, + http.StatusUnsupportedMediaType, + "unsupported_media_type", + ) + }) + } + + response := sendRegistration( + t, + testServer.URL, + "application/json; charset=UTF-8", + body, + ) + defer response.Body.Close() + if response.StatusCode != http.StatusCreated { + responseBody, _ := io.ReadAll(response.Body) + t.Fatalf( + "expected application/json with UTF-8 charset to be accepted, "+ + "got %d: %s", + response.StatusCode, + responseBody, + ) + } +} + +func TestJSONRequestRejectsInvalidUTF8WithoutMutation(t *testing.T) { + testServer, _ := setupTestServer() + defer testServer.Close() + + body := append( + []byte( + `{"username":"utf8_probe","display_name":"Test",`+ + `"password":"12345678901`, + ), + 0xff, + ) + body = append(body, []byte(`"}`)...) + + response := sendRegistration( + t, + testServer.URL, + "application/json", + body, + ) + requireContractError( + t, + response, + http.StatusBadRequest, + "invalid_request", + ) + + validBody := []byte( + `{"username":"utf8_probe","display_name":"Test",` + + `"password":"12345678901�"}`, + ) + validResponse := sendRegistration( + t, + testServer.URL, + "application/json", + validBody, + ) + defer validResponse.Body.Close() + if validResponse.StatusCode != http.StatusCreated { + responseBody, _ := io.ReadAll(validResponse.Body) + t.Fatalf( + "invalid UTF-8 request mutated storage; expected subsequent "+ + "valid registration 201, got %d: %s", + validResponse.StatusCode, + responseBody, + ) + } +} + +func TestJSONRequestRejectsOversizedBody(t *testing.T) { + testServer, _ := setupTestServer() + defer testServer.Close() + + response := sendRegistration( + t, + testServer.URL, + "application/json", + bytes.Repeat([]byte(" "), (1<<20)+1), + ) + requireContractError( + t, + response, + http.StatusRequestEntityTooLarge, + "payload_too_large", + ) +} + +func TestBasicAuthRejectsInvalidUTF8(t *testing.T) { + testServer, _ := setupSessionTestServer(t, 0) + defer testServer.Close() + + credentials := append([]byte("unknown:"), 0xff) + request, err := http.NewRequest( + http.MethodPost, + testServer.URL+"/api/v1/auth/sessions", + nil, + ) + if err != nil { + t.Fatalf("create session request: %v", err) + } + request.Header.Set( + "Authorization", + "Basic "+base64.StdEncoding.EncodeToString(credentials), + ) + + response, err := http.DefaultClient.Do(request) + if err != nil { + t.Fatalf("send session request: %v", err) + } + defer response.Body.Close() + + if response.StatusCode != http.StatusUnauthorized { + body, _ := io.ReadAll(response.Body) + t.Fatalf( + "expected invalid UTF-8 Basic credentials to return 401, "+ + "got %d: %s", + response.StatusCode, + body, + ) + } + if got := response.Header.Get("WWW-Authenticate"); got != `Basic realm="messenger", charset="UTF-8"` { + t.Fatalf("unexpected Basic challenge: %q", got) + } +}