forked from mtusi2026/mtusi2026lab3
Перенос минимума из lab2
This commit is contained in:
+22
@@ -0,0 +1,22 @@
|
||||
FROM golang:1.26-bookworm AS build
|
||||
WORKDIR /src
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
COPY messenger ./messenger
|
||||
COPY internal ./internal
|
||||
COPY migrations ./migrations
|
||||
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 \
|
||||
go build -trimpath -ldflags='-s -w' -o /out/messenger ./messenger \
|
||||
&& chmod 755 /out/messenger
|
||||
|
||||
FROM gcr.io/distroless/static-debian12:nonroot@sha256:afa5c872c891853ca7fcf1f12c3edb23f7eeef36189728842dd51042ff57f7ab
|
||||
COPY --from=build --chown=65532:65532 /out/messenger /messenger
|
||||
USER 65532:65532
|
||||
ENV APP_HOST=0.0.0.0 \
|
||||
APP_PORT=8080 \
|
||||
APP_ENV=lab \
|
||||
SHUTDOWN_TIMEOUT_SECONDS=8
|
||||
EXPOSE 8080
|
||||
HEALTHCHECK --interval=5s --timeout=3s --start-period=15s --retries=3 \
|
||||
CMD ["/messenger", "healthcheck"]
|
||||
ENTRYPOINT ["/messenger"]
|
||||
@@ -4,10 +4,10 @@ CA_FILE ?=
|
||||
ACTION_SCRIPT ?=
|
||||
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
||||
|
||||
.PHONY: help check validate test load test-persistence test-failover
|
||||
.PHONY: help check validate test load test-own test-persistence
|
||||
|
||||
help:
|
||||
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
|
||||
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes; test-own: Go tests"
|
||||
|
||||
check:
|
||||
$(PYTHON) scripts/check_contract.py
|
||||
@@ -21,10 +21,9 @@ test:
|
||||
load:
|
||||
$(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
test-persistence:
|
||||
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2)
|
||||
$(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
test-own:
|
||||
go test ./...
|
||||
|
||||
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)
|
||||
test-persistence:
|
||||
test -n "$(ACTION_SCRIPT)"
|
||||
$(PYTHON) tests/resilience.py --base-url "$(BASE_URL)" --mode persistence --action-script "$(ACTION_SCRIPT)" $(TLS_ARGS)
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
# Локальный стенд лабораторной 2. Секреты только из .env, volumes не удаляются restart-скриптом.
|
||||
name: messenger-lab2
|
||||
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16.10-bookworm
|
||||
environment:
|
||||
POSTGRES_USER: ${POSTGRES_USER}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
|
||||
POSTGRES_DB: ${POSTGRES_DB}
|
||||
command:
|
||||
- postgres
|
||||
- -c
|
||||
- synchronous_commit=on
|
||||
- -c
|
||||
- max_connections=50
|
||||
volumes:
|
||||
- pgdata:/var/lib/postgresql/data
|
||||
ports:
|
||||
- "127.0.0.1:5432:5432"
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER} -d ${POSTGRES_DB}"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 12
|
||||
start_period: 5s
|
||||
restart: unless-stopped
|
||||
|
||||
redis:
|
||||
image: redis:7.4.6-alpine
|
||||
environment:
|
||||
REDIS_PASSWORD: ${REDIS_PASSWORD}
|
||||
# exec нужен, чтобы SIGTERM пришёл самому Redis и он дописал AOF перед выходом.
|
||||
command:
|
||||
- sh
|
||||
- -c
|
||||
- exec redis-server --appendonly yes --appendfsync everysec --aof-use-rdb-preamble yes --dir /data --requirepass "$$REDIS_PASSWORD" --bind 0.0.0.0 --protected-mode yes
|
||||
volumes:
|
||||
- redisdata:/data
|
||||
ports:
|
||||
- "127.0.0.1:6379:6379"
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "redis-cli --no-auth-warning -a \"$$REDIS_PASSWORD\" ping | grep -q PONG"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 12
|
||||
start_period: 3s
|
||||
restart: unless-stopped
|
||||
|
||||
api:
|
||||
build: .
|
||||
image: messenger-api:lab2
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
redis:
|
||||
condition: service_healthy
|
||||
environment:
|
||||
APP_HOST: 0.0.0.0
|
||||
APP_PORT: "8080"
|
||||
APP_ENV: lab
|
||||
SHUTDOWN_TIMEOUT_SECONDS: ${SHUTDOWN_TIMEOUT_SECONDS:-8}
|
||||
DATABASE_URL: postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@postgres:5432/${POSTGRES_DB}?sslmode=disable
|
||||
REDIS_URL: redis://:${REDIS_PASSWORD}@redis:6379/0
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||
DB_MAX_CONNS: ${DB_MAX_CONNS:-10}
|
||||
ARGON2_TIME: ${ARGON2_TIME:-2}
|
||||
ARGON2_MEMORY_KIB: ${ARGON2_MEMORY_KIB:-19456}
|
||||
ARGON2_THREADS: ${ARGON2_THREADS:-1}
|
||||
ports:
|
||||
- "127.0.0.1:8080:8080"
|
||||
healthcheck:
|
||||
test: ["CMD", "/messenger", "healthcheck"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 12
|
||||
start_period: 10s
|
||||
restart: unless-stopped
|
||||
|
||||
volumes:
|
||||
pgdata:
|
||||
redisdata:
|
||||
@@ -0,0 +1,20 @@
|
||||
module messenger
|
||||
|
||||
go 1.26.0
|
||||
|
||||
require (
|
||||
github.com/jackc/pgx/v5 v5.11.0
|
||||
github.com/redis/go-redis/v9 v9.23.0
|
||||
golang.org/x/crypto v0.58.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.24.0 // indirect
|
||||
golang.org/x/sys v0.49.0 // indirect
|
||||
golang.org/x/text v0.43.0 // indirect
|
||||
)
|
||||
@@ -0,0 +1,41 @@
|
||||
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/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.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54=
|
||||
golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w=
|
||||
golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
|
||||
golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
|
||||
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
|
||||
golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
|
||||
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=
|
||||
@@ -0,0 +1,182 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"messenger/internal/password"
|
||||
"messenger/internal/session"
|
||||
"messenger/internal/store"
|
||||
)
|
||||
|
||||
const (
|
||||
basicChallenge = `Basic realm="messenger", charset="UTF-8"`
|
||||
bearerChallenge = `Bearer realm="messenger"`
|
||||
)
|
||||
|
||||
func (a *API) createSession(w http.ResponseWriter, r *http.Request) {
|
||||
if !emptyBody(r) {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "У входа не должно быть тела", 0)
|
||||
return
|
||||
}
|
||||
username, plain, ok := parseBasic(r)
|
||||
if !ok || !usernameRe.MatchString(username) || !validPassword(plain) {
|
||||
a.unauthorized(w, r, basicChallenge)
|
||||
return
|
||||
}
|
||||
user, hash, err := a.store.UserByUsername(r.Context(), username)
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
password.Verify(plain, a.dummyHash)
|
||||
a.unauthorized(w, r, basicChallenge)
|
||||
return
|
||||
}
|
||||
if a.writeStoreErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
if !password.Verify(plain, hash) {
|
||||
a.unauthorized(w, r, basicChallenge)
|
||||
return
|
||||
}
|
||||
token, err := newToken()
|
||||
if err != nil {
|
||||
a.fail(w, r, http.StatusInternalServerError, "internal_error", "Внутренняя ошибка", 0)
|
||||
return
|
||||
}
|
||||
expires := time.Now().UTC().Add(a.sessionTTL).Truncate(time.Microsecond)
|
||||
if err := a.sessions.Create(r.Context(), token, user.ID, expires); a.writeStoreErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, map[string]any{
|
||||
"token": token,
|
||||
"token_type": "Bearer",
|
||||
"expires_at": formatTime(expires),
|
||||
"user": asUser(user),
|
||||
})
|
||||
}
|
||||
|
||||
func (a *API) revokeSession(w http.ResponseWriter, r *http.Request) {
|
||||
token, ok := a.bearerToken(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if _, _, err := a.sessions.Lookup(r.Context(), token); err != nil {
|
||||
if errors.Is(err, session.ErrNotFound) {
|
||||
a.unauthorized(w, r, bearerChallenge)
|
||||
return
|
||||
}
|
||||
a.writeStoreErr(w, r, err)
|
||||
return
|
||||
}
|
||||
if err := a.sessions.Revoke(r.Context(), token); err != nil {
|
||||
if errors.Is(err, session.ErrNotFound) {
|
||||
a.unauthorized(w, r, bearerChallenge)
|
||||
return
|
||||
}
|
||||
a.writeStoreErr(w, r, err)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (a *API) authenticate(w http.ResponseWriter, r *http.Request) (store.User, bool) {
|
||||
token, ok := a.bearerToken(w, r)
|
||||
if !ok {
|
||||
return store.User{}, false
|
||||
}
|
||||
userID, expires, err := a.sessions.Lookup(r.Context(), token)
|
||||
if errors.Is(err, session.ErrNotFound) || (err == nil && !time.Now().Before(expires)) {
|
||||
if err == nil {
|
||||
_ = a.sessions.Revoke(r.Context(), token)
|
||||
}
|
||||
a.unauthorized(w, r, bearerChallenge)
|
||||
return store.User{}, false
|
||||
}
|
||||
if err != nil {
|
||||
a.writeStoreErr(w, r, err)
|
||||
return store.User{}, false
|
||||
}
|
||||
user, err := a.store.User(r.Context(), userID)
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
a.unauthorized(w, r, bearerChallenge)
|
||||
return store.User{}, false
|
||||
}
|
||||
if a.writeStoreErr(w, r, err) {
|
||||
return store.User{}, false
|
||||
}
|
||||
return user, true
|
||||
}
|
||||
|
||||
func (a *API) bearerToken(w http.ResponseWriter, r *http.Request) (string, bool) {
|
||||
scheme, param, ok := splitAuth(r.Header.Get("Authorization"))
|
||||
if !ok || !strings.EqualFold(scheme, "Bearer") || param == "" || len(param) > 512 || strings.Contains(param, " ") {
|
||||
a.unauthorized(w, r, bearerChallenge)
|
||||
return "", false
|
||||
}
|
||||
return param, true
|
||||
}
|
||||
|
||||
func (a *API) unauthorized(w http.ResponseWriter, r *http.Request, challenge string) {
|
||||
w.Header().Set("WWW-Authenticate", challenge)
|
||||
a.fail(w, r, http.StatusUnauthorized, "unauthorized", "Нет действительной идентификации", 0)
|
||||
}
|
||||
|
||||
func parseBasic(r *http.Request) (string, string, bool) {
|
||||
scheme, param, ok := splitAuth(r.Header.Get("Authorization"))
|
||||
if !ok || !strings.EqualFold(scheme, "Basic") || param == "" {
|
||||
return "", "", false
|
||||
}
|
||||
raw, err := base64.StdEncoding.DecodeString(param)
|
||||
if err != nil {
|
||||
raw, err = base64.RawStdEncoding.DecodeString(param)
|
||||
if err != nil {
|
||||
return "", "", false
|
||||
}
|
||||
}
|
||||
if !utf8.Valid(raw) {
|
||||
return "", "", false
|
||||
}
|
||||
username, plain, ok := strings.Cut(string(raw), ":")
|
||||
if !ok || username == "" {
|
||||
return "", "", false
|
||||
}
|
||||
return username, plain, true
|
||||
}
|
||||
|
||||
func splitAuth(header string) (string, string, bool) {
|
||||
scheme, param, ok := strings.Cut(strings.TrimSpace(header), " ")
|
||||
if !ok {
|
||||
return "", "", false
|
||||
}
|
||||
param = strings.TrimSpace(param)
|
||||
if scheme == "" || param == "" {
|
||||
return "", "", false
|
||||
}
|
||||
return scheme, param, true
|
||||
}
|
||||
|
||||
func emptyBody(r *http.Request) bool {
|
||||
if r.Body == nil || r.ContentLength == 0 {
|
||||
return true
|
||||
}
|
||||
buf := make([]byte, 1)
|
||||
n, err := r.Body.Read(buf)
|
||||
if n > 0 {
|
||||
return false
|
||||
}
|
||||
return err == io.EOF || err == nil
|
||||
}
|
||||
|
||||
func newToken() (string, error) {
|
||||
var b [32]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(b[:]), nil
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"messenger/internal/session"
|
||||
"messenger/internal/store"
|
||||
)
|
||||
|
||||
func (a *API) live(w http.ResponseWriter, _ *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
func (a *API) ready(w http.ResponseWriter, r *http.Request) {
|
||||
if a.shutting.Load() {
|
||||
a.fail(w, r, http.StatusServiceUnavailable, "unavailable", "Сервер останавливается", 1)
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 800*time.Millisecond)
|
||||
defer cancel()
|
||||
if err := a.store.Ping(ctx); err != nil || a.sessions.Ping(ctx) != nil {
|
||||
a.fail(w, r, http.StatusServiceUnavailable, "unavailable", "Сервис временно недоступен", 1)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
func (a *API) route(w http.ResponseWriter, r *http.Request) {
|
||||
path := r.URL.Path
|
||||
switch {
|
||||
case path == "/api/v1/users" && r.Method == http.MethodPost:
|
||||
a.createUser(w, r)
|
||||
case path == "/api/v1/users/me" && r.Method == http.MethodGet:
|
||||
a.currentUser(w, r)
|
||||
case path == "/api/v1/auth/sessions" && r.Method == http.MethodPost:
|
||||
a.createSession(w, r)
|
||||
case path == "/api/v1/auth/sessions/current" && r.Method == http.MethodDelete:
|
||||
a.revokeSession(w, r)
|
||||
case path == "/api/v1/chats" && r.Method == http.MethodPost:
|
||||
a.createChat(w, r)
|
||||
case path == "/api/v1/chats" && r.Method == http.MethodGet:
|
||||
a.listChats(w, r)
|
||||
default:
|
||||
chatID, messages, ok := splitChatPath(path)
|
||||
if !ok {
|
||||
if knownWrongMethod(path) {
|
||||
a.fail(w, r, http.StatusMethodNotAllowed, "invalid_request", "Метод не поддерживается", 0)
|
||||
return
|
||||
}
|
||||
a.fail(w, r, http.StatusNotFound, "not_found", "Объект не найден", 0)
|
||||
return
|
||||
}
|
||||
switch {
|
||||
case !messages && r.Method == http.MethodGet:
|
||||
a.getChat(w, r, chatID)
|
||||
case messages && r.Method == http.MethodPost:
|
||||
a.createMessage(w, r, chatID)
|
||||
case messages && r.Method == http.MethodGet:
|
||||
a.listMessages(w, r, chatID)
|
||||
default:
|
||||
a.fail(w, r, http.StatusMethodNotAllowed, "invalid_request", "Метод не поддерживается", 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func knownWrongMethod(path string) bool {
|
||||
switch path {
|
||||
case "/api/v1/users", "/api/v1/users/me", "/api/v1/chats",
|
||||
"/api/v1/auth/sessions", "/api/v1/auth/sessions/current":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func (a *API) createUser(w http.ResponseWriter, r *http.Request) {
|
||||
var body struct {
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if !a.readJSON(w, r, &body) {
|
||||
return
|
||||
}
|
||||
if !usernameRe.MatchString(body.Username) || !validText(body.DisplayName, 1, 100) || !validPassword(body.Password) {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректные поля пользователя", 0)
|
||||
return
|
||||
}
|
||||
hash, err := a.hasher.Hash(body.Password)
|
||||
if err != nil {
|
||||
a.fail(w, r, http.StatusInternalServerError, "internal_error", "Внутренняя ошибка", 0)
|
||||
return
|
||||
}
|
||||
user, err := a.store.CreateUser(r.Context(), body.Username, body.DisplayName, hash)
|
||||
if a.writeStoreErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, asUser(user))
|
||||
}
|
||||
|
||||
func (a *API) currentUser(w http.ResponseWriter, r *http.Request) {
|
||||
user, ok := a.authenticate(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, asUser(user))
|
||||
}
|
||||
|
||||
func (a *API) createChat(w http.ResponseWriter, r *http.Request) {
|
||||
caller, ok := a.authenticate(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
}
|
||||
if !a.readJSON(w, r, &body) {
|
||||
return
|
||||
}
|
||||
if !validText(body.Title, 1, 100) || len(body.MemberIDs) < 1 || len(body.MemberIDs) > 100 {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректные поля чата", 0)
|
||||
return
|
||||
}
|
||||
ids := make([]string, len(body.MemberIDs))
|
||||
seen := make(map[string]struct{}, len(body.MemberIDs))
|
||||
callerIn := false
|
||||
for i, raw := range body.MemberIDs {
|
||||
id, ok := canonicalUUID(raw)
|
||||
if !ok {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный список участников", 0)
|
||||
return
|
||||
}
|
||||
if _, dup := seen[id]; dup {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный список участников", 0)
|
||||
return
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
_, err := a.store.User(r.Context(), id)
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный список участников", 0)
|
||||
return
|
||||
}
|
||||
if a.writeStoreErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
if id == caller.ID {
|
||||
callerIn = true
|
||||
}
|
||||
ids[i] = id
|
||||
}
|
||||
if !callerIn {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный список участников", 0)
|
||||
return
|
||||
}
|
||||
chat, err := a.store.CreateChat(r.Context(), body.Title, ids, caller.ID)
|
||||
if errors.Is(err, store.ErrInvalid) {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный список участников", 0)
|
||||
return
|
||||
}
|
||||
if a.writeStoreErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, asChat(chat))
|
||||
}
|
||||
|
||||
func (a *API) listChats(w http.ResponseWriter, r *http.Request) {
|
||||
user, ok := a.authenticate(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
limit, cur, ok := a.pageQuery(w, r, "chats:"+user.ID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
items, hasMore, err := a.store.ListChats(r.Context(), user.ID, cur, limit)
|
||||
if a.writeStoreErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
out := make([]chatJSON, 0, len(items))
|
||||
for _, c := range items {
|
||||
out = append(out, asChat(c))
|
||||
}
|
||||
var next *string
|
||||
if hasMore && len(items) > 0 {
|
||||
last := items[len(items)-1]
|
||||
encoded := encodeCursor(cursorPayload{Scope: "chats:" + user.ID, ID: last.ID, At: formatTime(last.CreatedAt)})
|
||||
next = &encoded
|
||||
}
|
||||
writeJSON(w, http.StatusOK, chatPage{Items: out, NextCursor: next})
|
||||
}
|
||||
|
||||
func (a *API) getChat(w http.ResponseWriter, r *http.Request, rawID string) {
|
||||
user, ok := a.authenticate(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id, ok := a.chatID(w, r, rawID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
chat, err := a.store.ChatFor(r.Context(), id, user.ID)
|
||||
if a.writeStoreErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, asChat(chat))
|
||||
}
|
||||
|
||||
func (a *API) createMessage(w http.ResponseWriter, r *http.Request, rawID string) {
|
||||
user, ok := a.authenticate(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id, ok := a.chatID(w, r, rawID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if _, err := a.store.ChatFor(r.Context(), id, user.ID); a.writeStoreErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
if !a.readJSON(w, r, &body) {
|
||||
return
|
||||
}
|
||||
if !validText(body.Text, 1, 4000) {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный текст сообщения", 0)
|
||||
return
|
||||
}
|
||||
msg, err := a.store.AddMessage(r.Context(), id, user.ID, body.Text)
|
||||
if a.writeStoreErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, asMessage(msg))
|
||||
}
|
||||
|
||||
func (a *API) listMessages(w http.ResponseWriter, r *http.Request, rawID string) {
|
||||
user, ok := a.authenticate(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id, ok := a.chatID(w, r, rawID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if _, err := a.store.ChatFor(r.Context(), id, user.ID); a.writeStoreErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
limit, cur, ok := a.pageQuery(w, r, "msg:"+id)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
items, hasMore, err := a.store.ListMessages(r.Context(), id, user.ID, cur, limit)
|
||||
if a.writeStoreErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
out := make([]messageJSON, 0, len(items))
|
||||
for _, m := range items {
|
||||
out = append(out, asMessage(m))
|
||||
}
|
||||
var next *string
|
||||
if hasMore && len(items) > 0 {
|
||||
last := items[len(items)-1]
|
||||
encoded := encodeCursor(cursorPayload{Scope: "msg:" + id, ID: last.ID, At: formatTime(last.CreatedAt)})
|
||||
next = &encoded
|
||||
}
|
||||
writeJSON(w, http.StatusOK, messagePage{Items: out, NextCursor: next})
|
||||
}
|
||||
|
||||
func (a *API) chatID(w http.ResponseWriter, r *http.Request, raw string) (string, bool) {
|
||||
id, ok := canonicalUUID(raw)
|
||||
if !ok {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный идентификатор", 0)
|
||||
return "", false
|
||||
}
|
||||
return id, true
|
||||
}
|
||||
|
||||
func (a *API) writeStoreErr(w http.ResponseWriter, r *http.Request, err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
switch {
|
||||
case errors.Is(err, store.ErrUnavailable), errors.Is(err, session.ErrUnavailable):
|
||||
a.fail(w, r, http.StatusServiceUnavailable, "unavailable", "Сервис временно недоступен", 1)
|
||||
case errors.Is(err, store.ErrConflict):
|
||||
a.fail(w, r, http.StatusConflict, "conflict", "Имя пользователя уже занято", 0)
|
||||
case errors.Is(err, store.ErrNotFound):
|
||||
a.fail(w, r, http.StatusNotFound, "not_found", "Объект не найден", 0)
|
||||
case errors.Is(err, store.ErrInvalid):
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректные данные", 0)
|
||||
case errors.Is(err, store.ErrBadCursor):
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный cursor", 0)
|
||||
default:
|
||||
a.log.Error("store", "request_id", requestIDFrom(r))
|
||||
a.fail(w, r, http.StatusInternalServerError, "internal_error", "Внутренняя ошибка", 0)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func splitChatPath(path string) (id string, messages bool, ok bool) {
|
||||
const prefix = "/api/v1/chats/"
|
||||
if !strings.HasPrefix(path, prefix) {
|
||||
return "", false, false
|
||||
}
|
||||
rest := strings.TrimPrefix(path, prefix)
|
||||
if rest == "" || strings.Contains(rest, "/") && !strings.HasSuffix(rest, "/messages") {
|
||||
return "", false, false
|
||||
}
|
||||
if strings.HasSuffix(rest, "/messages") {
|
||||
id = strings.TrimSuffix(rest, "/messages")
|
||||
if id == "" || strings.Contains(id, "/") {
|
||||
return "", false, false
|
||||
}
|
||||
return id, true, true
|
||||
}
|
||||
return rest, false, true
|
||||
}
|
||||
@@ -0,0 +1,314 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"messenger/internal/store"
|
||||
)
|
||||
|
||||
var usernameRe = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
var uuidRe = regexp.MustCompile(`(?i)^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`)
|
||||
var limitRe = regexp.MustCompile(`^[0-9]{1,3}$`)
|
||||
var requestIDRe = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,64}$`)
|
||||
|
||||
type errorEnvelope struct {
|
||||
Error errorObject `json:"error"`
|
||||
}
|
||||
|
||||
type errorObject struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
|
||||
type userJSON struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
type chatJSON struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
type messageJSON struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
SenderID string `json:"sender_id"`
|
||||
Text string `json:"text"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
type chatPage struct {
|
||||
Items []chatJSON `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
type messagePage struct {
|
||||
Items []messageJSON `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
type cursorPayload struct {
|
||||
Scope string `json:"scope"`
|
||||
ID string `json:"id"`
|
||||
At string `json:"at"`
|
||||
}
|
||||
|
||||
type statusWriter struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
wrote bool
|
||||
}
|
||||
|
||||
func (s *statusWriter) WriteHeader(code int) {
|
||||
if s.wrote {
|
||||
return
|
||||
}
|
||||
s.status = code
|
||||
s.wrote = true
|
||||
s.ResponseWriter.WriteHeader(code)
|
||||
}
|
||||
|
||||
func (s *statusWriter) Write(b []byte) (int, error) {
|
||||
if !s.wrote {
|
||||
s.WriteHeader(http.StatusOK)
|
||||
}
|
||||
return s.ResponseWriter.Write(b)
|
||||
}
|
||||
|
||||
func (a *API) fail(w http.ResponseWriter, r *http.Request, status int, code, message string, retryAfter int) {
|
||||
if retryAfter > 0 {
|
||||
w.Header().Set("Retry-After", strconv.Itoa(retryAfter))
|
||||
}
|
||||
writeJSON(w, status, errorEnvelope{Error: errorObject{
|
||||
Code: code,
|
||||
Message: message,
|
||||
RequestID: requestIDFrom(r),
|
||||
}})
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, v any) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(status)
|
||||
enc := json.NewEncoder(w)
|
||||
enc.SetEscapeHTML(false)
|
||||
_ = enc.Encode(v)
|
||||
}
|
||||
|
||||
func (a *API) readJSON(w http.ResponseWriter, r *http.Request, dst any) bool {
|
||||
media := ""
|
||||
if ct := r.Header.Get("Content-Type"); ct != "" {
|
||||
media = strings.TrimSpace(strings.Split(ct, ";")[0])
|
||||
}
|
||||
if !strings.EqualFold(media, "application/json") {
|
||||
a.fail(w, r, http.StatusUnsupportedMediaType, "unsupported_media_type", "Нужен Content-Type application/json", 0)
|
||||
return false
|
||||
}
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil || !utf8.Valid(body) || !decodeExactJSON(body, dst) {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный JSON", 0)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// decodeExactJSON принимает один JSON-объект: точные имена полей, без хвоста и без замены битого UTF-8.
|
||||
func decodeExactJSON(body []byte, dst any) bool {
|
||||
dec := json.NewDecoder(bytes.NewReader(body))
|
||||
var fields map[string]json.RawMessage
|
||||
if err := dec.Decode(&fields); err != nil || fields == nil {
|
||||
return false
|
||||
}
|
||||
var trailing json.RawMessage
|
||||
if err := dec.Decode(&trailing); err != io.EOF {
|
||||
return false
|
||||
}
|
||||
allowed, ok := jsonFieldNames(dst)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
for name := range fields {
|
||||
if _, ok := allowed[name]; !ok {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return json.Unmarshal(body, dst) == nil
|
||||
}
|
||||
|
||||
func jsonFieldNames(dst any) (map[string]struct{}, bool) {
|
||||
t := reflect.TypeOf(dst)
|
||||
if t == nil || t.Kind() != reflect.Pointer {
|
||||
return nil, false
|
||||
}
|
||||
t = t.Elem()
|
||||
if t.Kind() != reflect.Struct {
|
||||
return nil, false
|
||||
}
|
||||
names := make(map[string]struct{}, t.NumField())
|
||||
for i := 0; i < t.NumField(); i++ {
|
||||
name, _, _ := strings.Cut(t.Field(i).Tag.Get("json"), ",")
|
||||
if name == "" || name == "-" {
|
||||
return nil, false
|
||||
}
|
||||
names[name] = struct{}{}
|
||||
}
|
||||
return names, true
|
||||
}
|
||||
|
||||
func validPassword(s string) bool {
|
||||
if !utf8.ValidString(s) {
|
||||
return false
|
||||
}
|
||||
n := utf8.RuneCountInString(s)
|
||||
return n >= 12 && n <= 128 && strings.TrimSpace(s) != ""
|
||||
}
|
||||
|
||||
func (a *API) pageQuery(w http.ResponseWriter, r *http.Request, scope string) (int, *store.Cursor, bool) {
|
||||
q := r.URL.Query()
|
||||
limit := 50
|
||||
if q.Has("limit") {
|
||||
raw := q.Get("limit")
|
||||
n, err := strconv.Atoi(raw)
|
||||
if err != nil || !limitRe.MatchString(raw) || n < 1 || n > 100 {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный limit", 0)
|
||||
return 0, nil, false
|
||||
}
|
||||
limit = n
|
||||
}
|
||||
if !q.Has("cursor") {
|
||||
return limit, nil, true
|
||||
}
|
||||
raw := q.Get("cursor")
|
||||
if raw == "" || len(raw) > 512 {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный cursor", 0)
|
||||
return 0, nil, false
|
||||
}
|
||||
payload, err := decodeCursor(raw)
|
||||
if err != nil || payload.Scope != scope || payload.ID == "" || payload.At == "" {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный cursor", 0)
|
||||
return 0, nil, false
|
||||
}
|
||||
at, err := time.Parse("2006-01-02T15:04:05.000000Z", payload.At)
|
||||
if err != nil {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный cursor", 0)
|
||||
return 0, nil, false
|
||||
}
|
||||
id, ok := canonicalUUID(payload.ID)
|
||||
if !ok {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный cursor", 0)
|
||||
return 0, nil, false
|
||||
}
|
||||
return limit, &store.Cursor{ID: id, At: at}, true
|
||||
}
|
||||
|
||||
func asUser(u store.User) userJSON {
|
||||
return userJSON{
|
||||
ID: u.ID,
|
||||
Username: u.Username,
|
||||
DisplayName: u.DisplayName,
|
||||
CreatedAt: formatTime(u.CreatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func asChat(c store.Chat) chatJSON {
|
||||
ids := c.MemberIDs
|
||||
if ids == nil {
|
||||
ids = []string{}
|
||||
}
|
||||
return chatJSON{
|
||||
ID: c.ID,
|
||||
Title: c.Title,
|
||||
MemberIDs: ids,
|
||||
CreatedAt: formatTime(c.CreatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func asMessage(m store.Message) messageJSON {
|
||||
return messageJSON{
|
||||
ID: m.ID,
|
||||
ChatID: m.ChatID,
|
||||
SenderID: m.SenderID,
|
||||
Text: m.Text,
|
||||
CreatedAt: formatTime(m.CreatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func formatTime(t time.Time) string {
|
||||
return t.UTC().Format("2006-01-02T15:04:05.000000Z")
|
||||
}
|
||||
|
||||
func canonicalUUID(s string) (string, bool) {
|
||||
if !uuidRe.MatchString(s) {
|
||||
return "", false
|
||||
}
|
||||
return strings.ToLower(s), true
|
||||
}
|
||||
|
||||
func validText(s string, min, max int) bool {
|
||||
if strings.TrimSpace(s) == "" {
|
||||
return false
|
||||
}
|
||||
n := utf8.RuneCountInString(s)
|
||||
return n >= min && n <= max
|
||||
}
|
||||
|
||||
func requestID(r *http.Request) string {
|
||||
incoming := strings.TrimSpace(r.Header.Get("X-Request-Id"))
|
||||
if requestIDRe.MatchString(incoming) {
|
||||
return incoming
|
||||
}
|
||||
var b [16]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
return strconv.FormatInt(time.Now().UnixNano(), 36)
|
||||
}
|
||||
return hex.EncodeToString(b[:])
|
||||
}
|
||||
|
||||
func encodeCursor(p cursorPayload) string {
|
||||
raw, err := json.Marshal(p)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(raw)
|
||||
}
|
||||
|
||||
func decodeCursor(s string) (cursorPayload, error) {
|
||||
b, err := base64.RawURLEncoding.DecodeString(s)
|
||||
if err != nil {
|
||||
b, err = base64.URLEncoding.DecodeString(s)
|
||||
if err != nil {
|
||||
return cursorPayload{}, err
|
||||
}
|
||||
}
|
||||
dec := json.NewDecoder(bytes.NewReader(b))
|
||||
dec.DisallowUnknownFields()
|
||||
var p cursorPayload
|
||||
if err := dec.Decode(&p); err != nil {
|
||||
return cursorPayload{}, err
|
||||
}
|
||||
var trailing json.RawMessage
|
||||
if err := dec.Decode(&trailing); err != io.EOF {
|
||||
if err == nil {
|
||||
err = io.ErrUnexpectedEOF
|
||||
}
|
||||
return cursorPayload{}, err
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"messenger/internal/password"
|
||||
"messenger/internal/session"
|
||||
"messenger/internal/store"
|
||||
)
|
||||
|
||||
type ctxKey struct{}
|
||||
|
||||
type API struct {
|
||||
store store.Repository
|
||||
sessions session.Store
|
||||
hasher password.Params
|
||||
dummyHash string
|
||||
sessionTTL time.Duration
|
||||
log *slog.Logger
|
||||
shutting atomic.Bool
|
||||
}
|
||||
|
||||
// New связывает HTTP с хранилищем и сессиями.
|
||||
// dummyHash нужен, чтобы несуществующий username тратил столько же KDF, сколько существующий.
|
||||
func New(st store.Repository, sessions session.Store, hasher password.Params, sessionTTL time.Duration, log *slog.Logger) *API {
|
||||
if log == nil {
|
||||
log = slog.Default()
|
||||
}
|
||||
if sessionTTL <= 0 {
|
||||
sessionTTL = time.Hour
|
||||
}
|
||||
dummy, err := hasher.Hash("dummy-password-not-a-login")
|
||||
if err != nil {
|
||||
// Параметры KDF проверяются на старте. Пустая строка заставит Verify сразу вернуть false.
|
||||
dummy = ""
|
||||
}
|
||||
return &API{
|
||||
store: st,
|
||||
sessions: sessions,
|
||||
hasher: hasher,
|
||||
dummyHash: dummy,
|
||||
sessionTTL: sessionTTL,
|
||||
log: log,
|
||||
}
|
||||
}
|
||||
|
||||
// BeginShutdown переводит /health/ready в 503 и говорит новым бизнес-запросам
|
||||
// отказать до закрытия слушателя. Уже принятые обработчики дорабатывают.
|
||||
func (a *API) BeginShutdown() {
|
||||
a.shutting.Store(true)
|
||||
a.log.Info("shutdown started")
|
||||
}
|
||||
|
||||
// Точка входа
|
||||
func (a *API) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
sw := &statusWriter{ResponseWriter: w, status: http.StatusOK}
|
||||
start := time.Now()
|
||||
id := requestID(r)
|
||||
sw.Header().Set("X-Request-Id", id)
|
||||
r = r.WithContext(context.WithValue(r.Context(), ctxKey{}, id))
|
||||
|
||||
defer func() {
|
||||
if p := recover(); p != nil {
|
||||
a.log.Error("panic", "request_id", id)
|
||||
if !sw.wrote {
|
||||
a.fail(sw, r, http.StatusInternalServerError, "internal_error", "Внутренняя ошибка", 0)
|
||||
}
|
||||
}
|
||||
a.log.Info("request",
|
||||
"request_id", id,
|
||||
"method", r.Method,
|
||||
"path", r.URL.Path,
|
||||
"status", sw.status,
|
||||
"duration_ms", time.Since(start).Milliseconds(),
|
||||
"bytes_in", r.ContentLength,
|
||||
)
|
||||
}()
|
||||
|
||||
switch {
|
||||
case r.Method == http.MethodGet && r.URL.Path == "/health/live":
|
||||
a.live(sw, r)
|
||||
return
|
||||
case r.Method == http.MethodGet && r.URL.Path == "/health/ready":
|
||||
a.ready(sw, r)
|
||||
return
|
||||
}
|
||||
|
||||
if a.shutting.Load() {
|
||||
a.fail(sw, r, http.StatusServiceUnavailable, "unavailable", "Сервер останавливается", 1)
|
||||
return
|
||||
}
|
||||
a.route(sw, r)
|
||||
}
|
||||
|
||||
func requestIDFrom(r *http.Request) string {
|
||||
id, _ := r.Context().Value(ctxKey{}).(string)
|
||||
if id == "" {
|
||||
return "unknown"
|
||||
}
|
||||
return id
|
||||
}
|
||||
@@ -0,0 +1,614 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"messenger/internal/password"
|
||||
"messenger/internal/session"
|
||||
"messenger/internal/store"
|
||||
)
|
||||
|
||||
const testPassword = "correct-horse-1"
|
||||
|
||||
type labServer struct {
|
||||
URL string
|
||||
tokens map[string]string
|
||||
api *API
|
||||
store store.Repository
|
||||
sess session.Store
|
||||
}
|
||||
|
||||
func newServer(t *testing.T) *labServer {
|
||||
return newServerTTL(t, time.Hour)
|
||||
}
|
||||
|
||||
func newServerTTL(t *testing.T, ttl time.Duration) *labServer {
|
||||
t.Helper()
|
||||
st := store.New()
|
||||
sess := session.NewMemory()
|
||||
application := New(st, sess, password.Params{Time: 1, Memory: 8, Threads: 1}, ttl, slog.New(slog.NewJSONHandler(io.Discard, nil)))
|
||||
srv := httptest.NewServer(application)
|
||||
t.Cleanup(srv.Close)
|
||||
return &labServer{URL: srv.URL, tokens: map[string]string{}, api: application, store: st, sess: sess}
|
||||
}
|
||||
|
||||
func (e *labServer) bearer(user string) string {
|
||||
if user == "" {
|
||||
return ""
|
||||
}
|
||||
if tok, ok := e.tokens[user]; ok {
|
||||
return tok
|
||||
}
|
||||
return "unknown-session-token"
|
||||
}
|
||||
|
||||
func do(t *testing.T, env *labServer, method, url, user string, body any, raw []byte, contentType string) (int, http.Header, []byte) {
|
||||
t.Helper()
|
||||
var rdr io.Reader
|
||||
if raw != nil {
|
||||
rdr = bytes.NewReader(raw)
|
||||
} else if body != nil {
|
||||
b, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rdr = bytes.NewReader(b)
|
||||
}
|
||||
req, err := http.NewRequest(method, url, rdr)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if body != nil || raw != nil {
|
||||
if contentType == "" {
|
||||
contentType = "application/json"
|
||||
}
|
||||
req.Header.Set("Content-Type", contentType)
|
||||
}
|
||||
if tok := env.bearer(user); tok != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+tok)
|
||||
}
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
data, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if resp.Header.Get("X-Request-Id") == "" {
|
||||
t.Fatalf("%s %s: missing X-Request-Id", method, url)
|
||||
}
|
||||
if resp.StatusCode >= 400 {
|
||||
var env errorEnvelope
|
||||
if err := json.Unmarshal(data, &env); err != nil {
|
||||
t.Fatalf("error json: %v body %s", err, data)
|
||||
}
|
||||
if env.Error.RequestID != resp.Header.Get("X-Request-Id") || env.Error.Code == "" || env.Error.Message == "" {
|
||||
t.Fatalf("bad error envelope: %+v", env)
|
||||
}
|
||||
}
|
||||
return resp.StatusCode, resp.Header, data
|
||||
}
|
||||
|
||||
func createUser(t *testing.T, env *labServer, username, display string) userJSON {
|
||||
t.Helper()
|
||||
status, _, body := do(t, env, http.MethodPost, env.URL+"/api/v1/users", "", map[string]string{
|
||||
"username": username, "display_name": display, "password": testPassword,
|
||||
}, nil, "")
|
||||
if status != http.StatusCreated {
|
||||
t.Fatalf("create user %s: %d %s", username, status, body)
|
||||
}
|
||||
if bytes.Contains(body, []byte("password")) || bytes.Contains(body, []byte("argon2")) {
|
||||
t.Fatalf("user response leaked a secret: %s", body)
|
||||
}
|
||||
var u userJSON
|
||||
if err := json.Unmarshal(body, &u); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req, err := http.NewRequest(http.MethodPost, env.URL+"/api/v1/auth/sessions", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req.SetBasicAuth(username, testPassword)
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
raw, _ := io.ReadAll(resp.Body)
|
||||
if resp.StatusCode != http.StatusCreated {
|
||||
t.Fatalf("login %s: %d %s", username, resp.StatusCode, raw)
|
||||
}
|
||||
var sess struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &sess); err != nil || len(sess.Token) < 32 {
|
||||
t.Fatalf("session: %s", raw)
|
||||
}
|
||||
env.tokens[u.ID] = sess.Token
|
||||
return u
|
||||
}
|
||||
|
||||
func createChat(t *testing.T, env *labServer, caller, title string, members ...string) chatJSON {
|
||||
t.Helper()
|
||||
status, _, body := do(t, env, http.MethodPost, env.URL+"/api/v1/chats", caller, map[string]any{
|
||||
"title": title, "member_ids": members,
|
||||
}, nil, "")
|
||||
if status != http.StatusCreated {
|
||||
t.Fatalf("create chat: %d %s", status, body)
|
||||
}
|
||||
var c chatJSON
|
||||
if err := json.Unmarshal(body, &c); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func TestInvalidJSONExtraFieldAndTypes(t *testing.T) {
|
||||
env := newServer(t)
|
||||
cases := [][]byte{
|
||||
[]byte(`{`),
|
||||
[]byte(`{"username":"abc","display_name":"Алиса","extra":1}`),
|
||||
[]byte(`{"username":1,"display_name":"Алиса"}`),
|
||||
[]byte(`null`),
|
||||
}
|
||||
for _, raw := range cases {
|
||||
status, _, body := do(t, env, http.MethodPost, env.URL+"/api/v1/users", "", nil, raw, "application/json")
|
||||
if status != http.StatusBadRequest || !bytes.Contains(body, []byte(`"invalid_request"`)) {
|
||||
t.Fatalf("body %s: %d %s", raw, status, body)
|
||||
}
|
||||
}
|
||||
status, _, _ := do(t, env, http.MethodPost, env.URL+"/api/v1/users", "", nil, []byte(`{"username":"abc","display_name":"Алиса"}`), "text/plain")
|
||||
if status != http.StatusUnsupportedMediaType {
|
||||
t.Fatalf("content type: %d", status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStrictJSONNamesUTF8AndCursorTail(t *testing.T) {
|
||||
env := newServer(t)
|
||||
bad := [][]byte{
|
||||
[]byte(`{"username":"bad_json","display_name":"Я"}]`),
|
||||
[]byte(`{"username":"bad_json","display_name":"Я"}}`),
|
||||
[]byte(`{"Username":"bad_case","display_name":"Я"}`),
|
||||
append([]byte(`{"username":"bad_utf","display_name":"`), 0xff, '"', '}'),
|
||||
}
|
||||
for _, raw := range bad {
|
||||
status, _, body := do(t, env, http.MethodPost, env.URL+"/api/v1/users", "", nil, raw, "application/json")
|
||||
if status != http.StatusBadRequest {
|
||||
t.Fatalf("user body %q: %d %s", raw, status, body)
|
||||
}
|
||||
}
|
||||
|
||||
alice := createUser(t, env, "alice", "Алиса")
|
||||
status, _, body := do(t, env, http.MethodPost, env.URL+"/api/v1/chats", alice.ID, nil, []byte(`{"Title":"чат","member_ids":["`+alice.ID+`"]}`), "application/json")
|
||||
if status != http.StatusBadRequest {
|
||||
t.Fatalf("Title: %d %s", status, body)
|
||||
}
|
||||
chat := createChat(t, env, alice.ID, "чат", alice.ID)
|
||||
|
||||
status, _, body = do(t, env, http.MethodPost, env.URL+"/api/v1/chats/"+chat.ID+"/messages", alice.ID, nil, []byte(`{"TEXT":"hi"}`), "application/json")
|
||||
if status != http.StatusBadRequest {
|
||||
t.Fatalf("TEXT: %d %s", status, body)
|
||||
}
|
||||
rawText := append([]byte(`{"text":"`), 0xff, '"', '}')
|
||||
status, _, body = do(t, env, http.MethodPost, env.URL+"/api/v1/chats/"+chat.ID+"/messages", alice.ID, nil, rawText, "application/json")
|
||||
if status != http.StatusBadRequest {
|
||||
t.Fatalf("message utf-8: %d %s", status, body)
|
||||
}
|
||||
|
||||
status, _, body = do(t, env, http.MethodPost, env.URL+"/api/v1/chats/"+chat.ID+"/messages", alice.ID, map[string]string{"text": "one"}, nil, "")
|
||||
if status != http.StatusCreated {
|
||||
t.Fatalf("seed: %d %s", status, body)
|
||||
}
|
||||
status, _, body = do(t, env, http.MethodPost, env.URL+"/api/v1/chats/"+chat.ID+"/messages", alice.ID, map[string]string{"text": "two"}, nil, "")
|
||||
if status != http.StatusCreated {
|
||||
t.Fatalf("seed2: %d %s", status, body)
|
||||
}
|
||||
status, _, body = do(t, env, http.MethodGet, env.URL+"/api/v1/chats/"+chat.ID+"/messages?limit=1", alice.ID, nil, nil, "")
|
||||
if status != http.StatusOK {
|
||||
t.Fatalf("page: %d %s", status, body)
|
||||
}
|
||||
var page messagePage
|
||||
if err := json.Unmarshal(body, &page); err != nil || page.NextCursor == nil {
|
||||
t.Fatalf("cursor: %v %s", err, body)
|
||||
}
|
||||
decoded, err := base64.RawURLEncoding.DecodeString(*page.NextCursor)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tampered := base64.RawURLEncoding.EncodeToString(append(decoded, []byte("garbage")...))
|
||||
status, _, body = do(t, env, http.MethodGet, env.URL+"/api/v1/chats/"+chat.ID+"/messages?limit=1&cursor="+url.QueryEscape(tampered), alice.ID, nil, nil, "")
|
||||
if status != http.StatusBadRequest {
|
||||
t.Fatalf("tampered cursor: %d %s", status, body)
|
||||
}
|
||||
status, _, _ = do(t, env, http.MethodGet, env.URL+"/api/v1/chats/"+chat.ID+"/messages?limit=1&cursor="+url.QueryEscape(*page.NextCursor), alice.ID, nil, nil, "")
|
||||
if status != http.StatusOK {
|
||||
t.Fatalf("valid cursor: %d", status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDuplicateUsername(t *testing.T) {
|
||||
env := newServer(t)
|
||||
createUser(t, env, "alice", "Алиса")
|
||||
status, _, body := do(t, env, http.MethodPost, env.URL+"/api/v1/users", "", map[string]string{
|
||||
"username": "alice", "display_name": "Другая", "password": testPassword,
|
||||
}, nil, "")
|
||||
if status != http.StatusConflict || !bytes.Contains(body, []byte(`"conflict"`)) {
|
||||
t.Fatalf("duplicate: %d %s", status, body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmptyMessageForeignChatAndAuth(t *testing.T) {
|
||||
env := newServer(t)
|
||||
alice := createUser(t, env, "alice", "Алиса")
|
||||
bob := createUser(t, env, "bob", "Боб")
|
||||
eve := createUser(t, env, "eve", "Ева")
|
||||
chat := createChat(t, env, alice.ID, "Контрактный тест", alice.ID, bob.ID)
|
||||
|
||||
status, _, _ := do(t, env, http.MethodGet, env.URL+"/api/v1/users/me", "", nil, nil, "")
|
||||
if status != http.StatusUnauthorized {
|
||||
t.Fatalf("missing header: %d", status)
|
||||
}
|
||||
status, _, _ = do(t, env, http.MethodGet, env.URL+"/api/v1/users/me", "11111111-1111-4111-8111-111111111111", nil, nil, "")
|
||||
if status != http.StatusUnauthorized {
|
||||
t.Fatalf("unknown user: %d", status)
|
||||
}
|
||||
meStatus, _, meBody := do(t, env, http.MethodGet, env.URL+"/api/v1/users/me", alice.ID, nil, nil, "")
|
||||
if meStatus != http.StatusOK || !bytes.Contains(meBody, []byte(alice.ID)) {
|
||||
t.Fatalf("me: %d %s", meStatus, meBody)
|
||||
}
|
||||
|
||||
status, _, _ = do(t, env, http.MethodGet, env.URL+"/api/v1/chats/"+chat.ID, eve.ID, nil, nil, "")
|
||||
if status != http.StatusNotFound {
|
||||
t.Fatalf("foreign chat: %d", status)
|
||||
}
|
||||
status, _, _ = do(t, env, http.MethodPost, env.URL+"/api/v1/chats/"+chat.ID+"/messages", eve.ID, map[string]string{"text": "чужое"}, nil, "")
|
||||
if status != http.StatusNotFound {
|
||||
t.Fatalf("foreign post: %d", status)
|
||||
}
|
||||
for _, text := range []string{"", " ", "\n\t"} {
|
||||
status, _, body := do(t, env, http.MethodPost, env.URL+"/api/v1/chats/"+chat.ID+"/messages", alice.ID, map[string]string{"text": text}, nil, "")
|
||||
if status != http.StatusBadRequest {
|
||||
t.Fatalf("empty %q: %d %s", text, status, body)
|
||||
}
|
||||
}
|
||||
status, _, _ = do(t, env, http.MethodPost, env.URL+"/api/v1/chats/"+chat.ID+"/messages", alice.ID, map[string]string{"text": "привет", "sender_id": eve.ID}, nil, "")
|
||||
if status != http.StatusBadRequest {
|
||||
t.Fatalf("sender_id must be rejected: %d", status)
|
||||
}
|
||||
|
||||
text := "Привет, мир 👋"
|
||||
status, _, body := do(t, env, http.MethodPost, env.URL+"/api/v1/chats/"+chat.ID+"/messages", alice.ID, map[string]string{"text": text}, nil, "")
|
||||
if status != http.StatusCreated {
|
||||
t.Fatalf("unicode: %d %s", status, body)
|
||||
}
|
||||
var msg messageJSON
|
||||
if err := json.Unmarshal(body, &msg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if msg.Text != text || msg.SenderID != alice.ID || msg.ChatID != chat.ID {
|
||||
t.Fatalf("message mutated: %+v", msg)
|
||||
}
|
||||
if !strings.HasSuffix(msg.CreatedAt, "Z") {
|
||||
t.Fatalf("timestamp: %s", msg.CreatedAt)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPaginationSeveralPages(t *testing.T) {
|
||||
env := newServer(t)
|
||||
alice := createUser(t, env, "alice", "Алиса")
|
||||
bob := createUser(t, env, "bob", "Боб")
|
||||
chat := createChat(t, env, alice.ID, "страницы", alice.ID, bob.ID)
|
||||
other := createChat(t, env, alice.ID, "другой", alice.ID)
|
||||
const n = 25
|
||||
ids := make([]string, 0, n)
|
||||
for i := 0; i < n; i++ {
|
||||
sender := alice.ID
|
||||
if i%2 == 1 {
|
||||
sender = bob.ID
|
||||
}
|
||||
status, _, body := do(t, env, http.MethodPost, env.URL+"/api/v1/chats/"+chat.ID+"/messages", sender, map[string]string{
|
||||
"text": "сообщение " + strings.Repeat("я", i%3) + string(rune('a'+i%26)),
|
||||
}, nil, "")
|
||||
if status != http.StatusCreated {
|
||||
t.Fatalf("post %d: %d %s", i, status, body)
|
||||
}
|
||||
var msg messageJSON
|
||||
if err := json.Unmarshal(body, &msg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ids = append(ids, msg.ID)
|
||||
}
|
||||
var got []string
|
||||
cursor := ""
|
||||
pages := 0
|
||||
for {
|
||||
pages++
|
||||
if pages > 10 {
|
||||
t.Fatal("pagination did not finish")
|
||||
}
|
||||
url := env.URL + "/api/v1/chats/" + chat.ID + "/messages?limit=10"
|
||||
if cursor != "" {
|
||||
url += "&cursor=" + cursor
|
||||
}
|
||||
status, _, body := do(t, env, http.MethodGet, url, bob.ID, nil, nil, "")
|
||||
if status != http.StatusOK {
|
||||
t.Fatalf("page: %d %s", status, body)
|
||||
}
|
||||
var page messagePage
|
||||
if err := json.Unmarshal(body, &page); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(page.Items) == 0 || len(page.Items) > 10 {
|
||||
t.Fatalf("page size %d", len(page.Items))
|
||||
}
|
||||
for _, item := range page.Items {
|
||||
got = append(got, item.ID)
|
||||
}
|
||||
if page.NextCursor == nil {
|
||||
break
|
||||
}
|
||||
cursor = *page.NextCursor
|
||||
}
|
||||
if pages < 3 {
|
||||
t.Fatalf("expected several pages, got %d", pages)
|
||||
}
|
||||
if strings.Join(got, ",") != strings.Join(ids, ",") {
|
||||
t.Fatalf("order/duplication mismatch\nwant %v\ngot %v", ids, got)
|
||||
}
|
||||
status, _, _ := do(t, env, http.MethodGet, env.URL+"/api/v1/chats/"+other.ID+"/messages?limit=10&cursor="+cursor, alice.ID, nil, nil, "")
|
||||
if status != http.StatusBadRequest {
|
||||
t.Fatalf("foreign cursor: %d", status)
|
||||
}
|
||||
status, _, _ = do(t, env, http.MethodGet, env.URL+"/api/v1/chats/"+chat.ID+"/messages?limit=0", alice.ID, nil, nil, "")
|
||||
if status != http.StatusBadRequest {
|
||||
t.Fatalf("limit 0: %d", status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConcurrentHundredMessages(t *testing.T) {
|
||||
env := newServer(t)
|
||||
users := make([]userJSON, 10)
|
||||
ids := make([]string, 10)
|
||||
for i := 0; i < 10; i++ {
|
||||
users[i] = createUser(t, env, "u"+string(rune('a'+i))+"x", "Участник")
|
||||
ids[i] = users[i].ID
|
||||
}
|
||||
chat := createChat(t, env, ids[0], "гонка", ids...)
|
||||
var wg sync.WaitGroup
|
||||
errCh := make(chan error, 100)
|
||||
for i := 0; i < 10; i++ {
|
||||
wg.Add(1)
|
||||
go func(user string) {
|
||||
defer wg.Done()
|
||||
for j := 0; j < 10; j++ {
|
||||
req, err := http.NewRequest(http.MethodPost, env.URL+"/api/v1/chats/"+chat.ID+"/messages", strings.NewReader(`{"text":"n"}`))
|
||||
if err != nil {
|
||||
errCh <- err
|
||||
return
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+env.tokens[user])
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
errCh <- err
|
||||
return
|
||||
}
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusCreated {
|
||||
errCh <- &statusErr{resp.StatusCode, body}
|
||||
}
|
||||
}
|
||||
}(ids[i])
|
||||
}
|
||||
wg.Wait()
|
||||
close(errCh)
|
||||
for err := range errCh {
|
||||
t.Fatal(err)
|
||||
}
|
||||
seen := map[string]struct{}{}
|
||||
cursor := ""
|
||||
for {
|
||||
url := env.URL + "/api/v1/chats/" + chat.ID + "/messages?limit=17"
|
||||
if cursor != "" {
|
||||
url += "&cursor=" + cursor
|
||||
}
|
||||
status, _, body := do(t, env, http.MethodGet, url, ids[3], nil, nil, "")
|
||||
if status != http.StatusOK {
|
||||
t.Fatalf("list: %d %s", status, body)
|
||||
}
|
||||
var page messagePage
|
||||
if err := json.Unmarshal(body, &page); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, item := range page.Items {
|
||||
if _, ok := seen[item.ID]; ok {
|
||||
t.Fatalf("duplicate %s", item.ID)
|
||||
}
|
||||
seen[item.ID] = struct{}{}
|
||||
}
|
||||
if page.NextCursor == nil {
|
||||
break
|
||||
}
|
||||
cursor = *page.NextCursor
|
||||
}
|
||||
if len(seen) != 100 {
|
||||
t.Fatalf("unique messages = %d, want 100", len(seen))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionWrongPasswordLogoutAndIgnoredUserHeader(t *testing.T) {
|
||||
env := newServer(t)
|
||||
alice := createUser(t, env, "alice", "Алиса")
|
||||
eve := createUser(t, env, "eve", "Ева")
|
||||
|
||||
req, err := http.NewRequest(http.MethodPost, env.URL+"/api/v1/auth/sessions", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req.SetBasicAuth("alice", "wrong-password-1")
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusUnauthorized || !strings.HasPrefix(resp.Header.Get("WWW-Authenticate"), "Basic ") {
|
||||
t.Fatalf("wrong password: %d %s %q", resp.StatusCode, body, resp.Header.Get("WWW-Authenticate"))
|
||||
}
|
||||
|
||||
status, hdr, _ := do(t, env, http.MethodGet, env.URL+"/api/v1/users/me", "", nil, nil, "")
|
||||
if status != http.StatusUnauthorized || !strings.HasPrefix(hdr.Get("WWW-Authenticate"), "Bearer ") {
|
||||
t.Fatalf("missing bearer: %d %q", status, hdr.Get("WWW-Authenticate"))
|
||||
}
|
||||
bare, err := http.NewRequest(http.MethodGet, env.URL+"/api/v1/users/me", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bare.Header.Set("X-User-Id", alice.ID)
|
||||
resp, err = http.DefaultClient.Do(bare)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusUnauthorized {
|
||||
t.Fatalf("X-User-Id alone: %d", resp.StatusCode)
|
||||
}
|
||||
over, err := http.NewRequest(http.MethodGet, env.URL+"/api/v1/users/me", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
over.Header.Set("Authorization", "Bearer "+env.tokens[alice.ID])
|
||||
over.Header.Set("X-User-Id", eve.ID)
|
||||
resp, err = http.DefaultClient.Do(over)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw, _ := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK || !bytes.Contains(raw, []byte(alice.ID)) || bytes.Contains(raw, []byte(eve.ID)) {
|
||||
t.Fatalf("X-User-Id overrode bearer: %d %s", resp.StatusCode, raw)
|
||||
}
|
||||
|
||||
basic, err := http.NewRequest(http.MethodGet, env.URL+"/api/v1/users/me", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
basic.SetBasicAuth("alice", testPassword)
|
||||
resp, err = http.DefaultClient.Do(basic)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusUnauthorized || !strings.HasPrefix(resp.Header.Get("WWW-Authenticate"), "Bearer ") {
|
||||
t.Fatalf("basic on business endpoint: %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
status, _, body = do(t, env, http.MethodDelete, env.URL+"/api/v1/auth/sessions/current", alice.ID, nil, nil, "")
|
||||
if status != http.StatusNoContent || len(body) != 0 {
|
||||
t.Fatalf("logout: %d %q", status, body)
|
||||
}
|
||||
status, _, _ = do(t, env, http.MethodGet, env.URL+"/api/v1/users/me", alice.ID, nil, nil, "")
|
||||
if status != http.StatusUnauthorized {
|
||||
t.Fatalf("revoked token: %d", status)
|
||||
}
|
||||
status, _, _ = do(t, env, http.MethodDelete, env.URL+"/api/v1/auth/sessions/current", alice.ID, nil, nil, "")
|
||||
if status != http.StatusUnauthorized {
|
||||
t.Fatalf("second logout: %d", status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionExpires(t *testing.T) {
|
||||
env := newServerTTL(t, 2*time.Second)
|
||||
alice := createUser(t, env, "alice", "Алиса")
|
||||
time.Sleep(2100 * time.Millisecond)
|
||||
status, _, _ := do(t, env, http.MethodGet, env.URL+"/api/v1/users/me", alice.ID, nil, nil, "")
|
||||
if status != http.StatusUnauthorized {
|
||||
t.Fatalf("expired session: %d", status)
|
||||
}
|
||||
}
|
||||
|
||||
type downSessions struct{ session.Store }
|
||||
|
||||
func (downSessions) Lookup(context.Context, string) (string, time.Time, error) {
|
||||
return "", time.Time{}, session.ErrUnavailable
|
||||
}
|
||||
func (downSessions) Ping(context.Context) error { return session.ErrUnavailable }
|
||||
|
||||
type downStore struct{ store.Repository }
|
||||
|
||||
func (downStore) Ping(context.Context) error { return store.ErrUnavailable }
|
||||
func (downStore) User(context.Context, string) (store.User, error) {
|
||||
return store.User{}, store.ErrUnavailable
|
||||
}
|
||||
|
||||
func TestDependencyDownDoesNotTrustAnonymous(t *testing.T) {
|
||||
env := newServer(t)
|
||||
alice := createUser(t, env, "alice", "Алиса")
|
||||
broken := New(downStore{env.store}, downSessions{env.sess}, password.Params{Time: 1, Memory: 8, Threads: 1}, time.Hour, slog.New(slog.NewJSONHandler(io.Discard, nil)))
|
||||
srv := httptest.NewServer(broken)
|
||||
defer srv.Close()
|
||||
|
||||
live, err := http.Get(srv.URL + "/health/live")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
live.Body.Close()
|
||||
if live.StatusCode != http.StatusOK {
|
||||
t.Fatalf("live: %d", live.StatusCode)
|
||||
}
|
||||
ready, err := http.Get(srv.URL + "/health/ready")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
readyBody, _ := io.ReadAll(ready.Body)
|
||||
ready.Body.Close()
|
||||
if ready.StatusCode != http.StatusServiceUnavailable || !bytes.Contains(readyBody, []byte(`"unavailable"`)) {
|
||||
t.Fatalf("ready: %d %s", ready.StatusCode, readyBody)
|
||||
}
|
||||
|
||||
anon, err := http.Get(srv.URL + "/api/v1/users/me")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
anon.Body.Close()
|
||||
if anon.StatusCode != http.StatusUnauthorized {
|
||||
t.Fatalf("anonymous while down: %d", anon.StatusCode)
|
||||
}
|
||||
authed, err := http.NewRequest(http.MethodGet, srv.URL+"/api/v1/users/me", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
authed.Header.Set("Authorization", "Bearer "+env.tokens[alice.ID])
|
||||
resp, err := http.DefaultClient.Do(authed)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusServiceUnavailable {
|
||||
t.Fatalf("bearer while session store is down: %d", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
type statusErr struct {
|
||||
code int
|
||||
body []byte
|
||||
}
|
||||
|
||||
func (e *statusErr) Error() string {
|
||||
return http.StatusText(e.code) + " " + string(e.body)
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Config — параметры процесса. Секреты приходят из окружения, не из образа.
|
||||
type Config struct {
|
||||
Host string
|
||||
Port string
|
||||
Env string
|
||||
ShutdownTimeout time.Duration
|
||||
DatabaseURL string
|
||||
RedisURL string
|
||||
SessionTTL time.Duration
|
||||
DBMaxConns int32
|
||||
Argon2Time uint32
|
||||
Argon2Memory uint32
|
||||
Argon2Threads uint8
|
||||
}
|
||||
|
||||
// Addr — адрес прослушивания. В контейнере это 0.0.0.0:8080,
|
||||
// иначе published port Docker не попадёт в процесс.
|
||||
func (c Config) Addr() string {
|
||||
return net.JoinHostPort(c.Host, c.Port)
|
||||
}
|
||||
|
||||
// Load завершает запуск ошибкой, если значение вне допустимого диапазона.
|
||||
func Load() (Config, error) {
|
||||
var c Config
|
||||
c.Host = getenv("APP_HOST", "0.0.0.0")
|
||||
c.Port = getenv("APP_PORT", "8080")
|
||||
c.Env = getenv("APP_ENV", "lab")
|
||||
if c.Host == "" {
|
||||
return Config{}, fmt.Errorf("APP_HOST is empty")
|
||||
}
|
||||
port, err := strconv.Atoi(c.Port)
|
||||
if err != nil || port < 1 || port > 65535 {
|
||||
return Config{}, fmt.Errorf("APP_PORT must be 1..65535")
|
||||
}
|
||||
|
||||
sec, err := nonNeg("SHUTDOWN_TIMEOUT_SECONDS", 8)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
if sec < 1 || sec > 10 {
|
||||
return Config{}, fmt.Errorf("SHUTDOWN_TIMEOUT_SECONDS must be 1..10")
|
||||
}
|
||||
c.ShutdownTimeout = time.Duration(sec) * time.Second
|
||||
|
||||
c.DatabaseURL = getenv("DATABASE_URL", "")
|
||||
c.RedisURL = getenv("REDIS_URL", "")
|
||||
if c.DatabaseURL == "" || c.RedisURL == "" {
|
||||
return Config{}, fmt.Errorf("DATABASE_URL and REDIS_URL are required")
|
||||
}
|
||||
ttl, err := nonNeg("SESSION_TTL_SECONDS", 3600)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
if ttl < 1 || ttl > 7*24*3600 {
|
||||
return Config{}, fmt.Errorf("SESSION_TTL_SECONDS must be 1..604800")
|
||||
}
|
||||
c.SessionTTL = time.Duration(ttl) * time.Second
|
||||
|
||||
maxConns, err := nonNeg("DB_MAX_CONNS", 10)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
if maxConns < 1 || maxConns > 50 {
|
||||
return Config{}, fmt.Errorf("DB_MAX_CONNS must be 1..50")
|
||||
}
|
||||
c.DBMaxConns = int32(maxConns)
|
||||
|
||||
argonTime, err := nonNeg("ARGON2_TIME", 2)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
argonMemory, err := nonNeg("ARGON2_MEMORY_KIB", 19456)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
argonThreads, err := nonNeg("ARGON2_THREADS", 1)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
if argonTime < 1 || argonTime > 10 || argonMemory < 8 || argonMemory > 1<<20 || argonThreads < 1 || argonThreads > 8 {
|
||||
return Config{}, fmt.Errorf("argon2 params are out of range")
|
||||
}
|
||||
c.Argon2Time = uint32(argonTime)
|
||||
c.Argon2Memory = uint32(argonMemory)
|
||||
c.Argon2Threads = uint8(argonThreads)
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func getenv(key, def string) string {
|
||||
if v, ok := os.LookupEnv(key); ok && v != "" {
|
||||
return v
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
func nonNeg(key string, def int) (int, error) {
|
||||
v, ok := os.LookupEnv(key)
|
||||
if !ok || v == "" {
|
||||
return def, nil
|
||||
}
|
||||
n, err := strconv.Atoi(v)
|
||||
if err != nil || n < 0 {
|
||||
return 0, fmt.Errorf("%s must be a non-negative integer", key)
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
// применяет SQL из бинарника ровно один раз на файл.
|
||||
package migrate
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"messenger/migrations"
|
||||
)
|
||||
|
||||
// Создаёт schema_migrations и выполняет ещё не записанные файлы.
|
||||
// Повторный запуск не исполняет уже применённый SQL и не дублирует строки.
|
||||
func Apply(ctx context.Context, pool *pgxpool.Pool) error {
|
||||
_, err := pool.Exec(ctx, `
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version text PRIMARY KEY,
|
||||
applied_at timestamptz NOT NULL DEFAULT now()
|
||||
)`)
|
||||
if err != nil {
|
||||
return fmt.Errorf("schema_migrations: %w", err)
|
||||
}
|
||||
entries, err := fs.ReadDir(migrations.FS, ".")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
names := make([]string, 0, len(entries))
|
||||
for _, entry := range entries {
|
||||
if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".sql") {
|
||||
continue
|
||||
}
|
||||
names = append(names, entry.Name())
|
||||
}
|
||||
sort.Strings(names)
|
||||
for _, name := range names {
|
||||
var applied bool
|
||||
if err := pool.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM schema_migrations WHERE version = $1)`, name).Scan(&applied); err != nil {
|
||||
return err
|
||||
}
|
||||
if applied {
|
||||
continue
|
||||
}
|
||||
body, err := fs.ReadFile(migrations.FS, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tx, err := pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Exec(ctx, string(body)); err != nil {
|
||||
_ = tx.Rollback(ctx)
|
||||
return fmt.Errorf("%s: %w", name, err)
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `INSERT INTO schema_migrations (version) VALUES ($1)`, name); err != nil {
|
||||
_ = tx.Rollback(ctx)
|
||||
return err
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
// Package password хеширует пароли Argon2id.
|
||||
package password
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
// Params — стоимость KDF. Значения пишутся в саму строку хеша,
|
||||
// поэтому старые пароли проверяются даже после смены настроек.
|
||||
type Params struct {
|
||||
Time uint32
|
||||
Memory uint32
|
||||
Threads uint8
|
||||
}
|
||||
|
||||
// Hash возвращает PHC-строку.
|
||||
func (p Params) Hash(plain string) (string, error) {
|
||||
if p.Time < 1 || p.Threads < 1 || p.Memory < 8*uint32(p.Threads) {
|
||||
return "", fmt.Errorf("argon2 params are too small")
|
||||
}
|
||||
salt := make([]byte, 16)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", err
|
||||
}
|
||||
sum := argon2.IDKey([]byte(plain), salt, p.Time, p.Memory, p.Threads, 32)
|
||||
return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
|
||||
argon2.Version,
|
||||
p.Memory, p.Time, p.Threads,
|
||||
base64.RawStdEncoding.EncodeToString(salt),
|
||||
base64.RawStdEncoding.EncodeToString(sum),
|
||||
), nil
|
||||
}
|
||||
|
||||
// Verify сравнивает пароль с PHC-строкой. Параметры берутся из строки, не из текущего конфига.
|
||||
func Verify(plain, encoded string) bool {
|
||||
parts := strings.Split(encoded, "$")
|
||||
if len(parts) != 6 || parts[1] != "argon2id" || !strings.HasPrefix(parts[2], "v=") {
|
||||
return false
|
||||
}
|
||||
var memory, timeCost, threads int
|
||||
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &memory, &timeCost, &threads); err != nil {
|
||||
return false
|
||||
}
|
||||
if memory < 8 || timeCost < 1 || threads < 1 || threads > 255 {
|
||||
return false
|
||||
}
|
||||
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
|
||||
if err != nil || len(salt) == 0 {
|
||||
return false
|
||||
}
|
||||
want, err := base64.RawStdEncoding.DecodeString(parts[5])
|
||||
if err != nil || len(want) == 0 {
|
||||
return false
|
||||
}
|
||||
got := argon2.IDKey([]byte(plain), salt, uint32(timeCost), uint32(memory), uint8(threads), uint32(len(want)))
|
||||
return subtle.ConstantTimeCompare(got, want) == 1
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package password
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestArgon2idRoundTrip(t *testing.T) {
|
||||
p := Params{Time: 1, Memory: 8, Threads: 1}
|
||||
encoded, err := p.Hash("correct-horse-1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if encoded == "correct-horse-1" || len(encoded) < 20 {
|
||||
t.Fatalf("hash is not a PHC string: %s", encoded)
|
||||
}
|
||||
if !Verify("correct-horse-1", encoded) {
|
||||
t.Fatal("matching password rejected")
|
||||
}
|
||||
if Verify("other-password-1", encoded) {
|
||||
t.Fatal("wrong password accepted")
|
||||
}
|
||||
if Verify("correct-horse-1", "sha256:deadbeef") {
|
||||
t.Fatal("non-argon string accepted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package session
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestMemoryExpiryAndRevoke(t *testing.T) {
|
||||
s := NewMemory()
|
||||
ctx := context.Background()
|
||||
exp := time.Now().Add(30 * time.Millisecond)
|
||||
if err := s.Create(ctx, "token-value-with-enough-entropy-xx", "user-1", exp); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err := s.Lookup(ctx, "token-value-with-enough-entropy-xx"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
time.Sleep(40 * time.Millisecond)
|
||||
if _, _, err := s.Lookup(ctx, "token-value-with-enough-entropy-xx"); !errors.Is(err, ErrNotFound) {
|
||||
t.Fatalf("expired: %v", err)
|
||||
}
|
||||
exp = time.Now().Add(time.Minute)
|
||||
if err := s.Create(ctx, "token-value-with-enough-entropy-yy", "user-1", exp); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Revoke(ctx, "token-value-with-enough-entropy-yy"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, err := s.Lookup(ctx, "token-value-with-enough-entropy-yy"); !errors.Is(err, ErrNotFound) {
|
||||
t.Fatalf("revoked: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRedisDown(t *testing.T) {
|
||||
s, err := OpenRedis("redis://127.0.0.1:1/0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer s.Close()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancel()
|
||||
if err := s.Ping(ctx); !errors.Is(err, ErrUnavailable) {
|
||||
t.Fatalf("ping: %v", err)
|
||||
}
|
||||
if err := s.Create(ctx, "token", "user", time.Now().Add(time.Minute)); !errors.Is(err, ErrUnavailable) {
|
||||
t.Fatalf("create: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIntegrationRedisRoundTrip(t *testing.T) {
|
||||
raw := os.Getenv("REDIS_URL")
|
||||
if raw == "" {
|
||||
t.Skip("REDIS_URL is not set")
|
||||
}
|
||||
s, err := OpenRedis(raw)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer s.Close()
|
||||
ctx := context.Background()
|
||||
token := "integration-token-" + time.Now().UTC().Format("150405.000000")
|
||||
exp := time.Now().UTC().Add(2 * time.Second).Truncate(time.Microsecond)
|
||||
if err := s.Create(ctx, token, "11111111-1111-4111-8111-111111111111", exp); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
id, got, err := s.Lookup(ctx, token)
|
||||
if err != nil || id != "11111111-1111-4111-8111-111111111111" || !got.Equal(exp) {
|
||||
t.Fatalf("lookup id=%s exp=%s err=%v", id, got, err)
|
||||
}
|
||||
time.Sleep(2200 * time.Millisecond)
|
||||
if _, _, err := s.Lookup(ctx, token); !errors.Is(err, ErrNotFound) {
|
||||
t.Fatalf("ttl did not expire: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
// Package session хранит непрозрачные Bearer-сессии.
|
||||
// В стенде это Redis: ключ живёт ровно до expires_at, рестарт TTL не сдвигает.
|
||||
package session
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrNotFound = errors.New("session not found")
|
||||
ErrUnavailable = errors.New("session store unavailable")
|
||||
)
|
||||
|
||||
// Store — срок жизни сессии задаёт вызывающий, хранилище его не продлевает.
|
||||
type Store interface {
|
||||
Create(ctx context.Context, token, userID string, expiresAt time.Time) error
|
||||
Lookup(ctx context.Context, token string) (userID string, expiresAt time.Time, err error)
|
||||
Revoke(ctx context.Context, token string) error
|
||||
Ping(ctx context.Context) error
|
||||
Close() error
|
||||
}
|
||||
|
||||
type record struct {
|
||||
UserID string `json:"user_id"`
|
||||
ExpUnix int64 `json:"exp_unix"`
|
||||
}
|
||||
|
||||
// key — хеш токена. Сам токен в Redis не пишется: утечка дампа не равна утечке Bearer.
|
||||
func key(token string) string {
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
return "sess:" + hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// Memory — сессии процесса. Нужна юнит-тестам без Docker.
|
||||
type Memory struct {
|
||||
mu sync.Mutex
|
||||
items map[string]record
|
||||
}
|
||||
|
||||
func NewMemory() *Memory {
|
||||
return &Memory{items: make(map[string]record)}
|
||||
}
|
||||
|
||||
func (m *Memory) Create(_ context.Context, token, userID string, expiresAt time.Time) error {
|
||||
if token == "" || userID == "" {
|
||||
return ErrNotFound
|
||||
}
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.items[key(token)] = record{UserID: userID, ExpUnix: expiresAt.UTC().UnixMicro()}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Memory) Lookup(_ context.Context, token string) (string, time.Time, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
rec, ok := m.items[key(token)]
|
||||
if !ok {
|
||||
return "", time.Time{}, ErrNotFound
|
||||
}
|
||||
exp := time.UnixMicro(rec.ExpUnix).UTC()
|
||||
if !time.Now().Before(exp) {
|
||||
delete(m.items, key(token))
|
||||
return "", time.Time{}, ErrNotFound
|
||||
}
|
||||
return rec.UserID, exp, nil
|
||||
}
|
||||
|
||||
func (m *Memory) Revoke(_ context.Context, token string) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
k := key(token)
|
||||
if _, ok := m.items[k]; !ok {
|
||||
return ErrNotFound
|
||||
}
|
||||
delete(m.items, k)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Memory) Ping(ctx context.Context) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Memory) Close() error { return nil }
|
||||
|
||||
// Redis — единственное хранилище сессий стенда.
|
||||
type Redis struct {
|
||||
client *redis.Client
|
||||
}
|
||||
|
||||
func OpenRedis(rawURL string) (*Redis, error) {
|
||||
opt, err := redis.ParseURL(rawURL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
opt.DialTimeout = 500 * time.Millisecond
|
||||
opt.ReadTimeout = 500 * time.Millisecond
|
||||
opt.WriteTimeout = 500 * time.Millisecond
|
||||
opt.PoolSize = 10
|
||||
opt.MinIdleConns = 1
|
||||
return &Redis{client: redis.NewClient(opt)}, nil
|
||||
}
|
||||
|
||||
func (r *Redis) Create(ctx context.Context, token, userID string, expiresAt time.Time) error {
|
||||
if token == "" || userID == "" {
|
||||
return ErrNotFound
|
||||
}
|
||||
ttl := time.Until(expiresAt)
|
||||
if ttl < time.Millisecond {
|
||||
return ErrNotFound
|
||||
}
|
||||
body, err := json.Marshal(record{UserID: userID, ExpUnix: expiresAt.UTC().UnixMicro()})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := r.client.Set(ctx, key(token), body, ttl).Err(); err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Redis) Lookup(ctx context.Context, token string) (string, time.Time, error) {
|
||||
raw, err := r.client.Get(ctx, key(token)).Bytes()
|
||||
if errors.Is(err, redis.Nil) {
|
||||
return "", time.Time{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return "", time.Time{}, ErrUnavailable
|
||||
}
|
||||
var rec record
|
||||
if err := json.Unmarshal(raw, &rec); err != nil || rec.UserID == "" {
|
||||
return "", time.Time{}, ErrNotFound
|
||||
}
|
||||
exp := time.UnixMicro(rec.ExpUnix).UTC()
|
||||
if !time.Now().Before(exp) {
|
||||
_ = r.client.Del(ctx, key(token)).Err()
|
||||
return "", time.Time{}, ErrNotFound
|
||||
}
|
||||
return rec.UserID, exp, nil
|
||||
}
|
||||
|
||||
func (r *Redis) Revoke(ctx context.Context, token string) error {
|
||||
n, err := r.client.Del(ctx, key(token)).Result()
|
||||
if err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
if n == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Redis) Ping(ctx context.Context) error {
|
||||
if err := r.client.Ping(ctx).Err(); err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Redis) Close() error {
|
||||
return r.client.Close()
|
||||
}
|
||||
@@ -0,0 +1,389 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// PG — источник истины для пользователей, чатов и сообщений.
|
||||
// Запросы только с параметрами. Пул ограничен, у сессии соединения есть statement_timeout.
|
||||
type PG struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func Open(ctx context.Context, databaseURL string, maxConns int32) (*PG, error) {
|
||||
cfg, err := pgxpool.ParseConfig(databaseURL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if maxConns < 1 {
|
||||
maxConns = 10
|
||||
}
|
||||
cfg.MaxConns = maxConns
|
||||
cfg.MinConns = 1
|
||||
cfg.MaxConnLifetime = 30 * time.Minute
|
||||
cfg.MaxConnIdleTime = 5 * time.Minute
|
||||
cfg.HealthCheckPeriod = 30 * time.Second
|
||||
cfg.ConnConfig.ConnectTimeout = 3 * time.Second
|
||||
cfg.ConnConfig.RuntimeParams["application_name"] = "messenger"
|
||||
cfg.ConnConfig.RuntimeParams["statement_timeout"] = "5000"
|
||||
cfg.ConnConfig.RuntimeParams["lock_timeout"] = "3000"
|
||||
cfg.ConnConfig.RuntimeParams["idle_in_transaction_session_timeout"] = "10000"
|
||||
pool, err := pgxpool.NewWithConfig(ctx, cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pingCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer cancel()
|
||||
if err := pool.Ping(pingCtx); err != nil {
|
||||
pool.Close()
|
||||
return nil, err
|
||||
}
|
||||
return &PG{pool: pool}, nil
|
||||
}
|
||||
|
||||
func (p *PG) Close() { p.pool.Close() }
|
||||
|
||||
func (p *PG) Pool() *pgxpool.Pool { return p.pool }
|
||||
|
||||
func (p *PG) Ping(ctx context.Context) error {
|
||||
return mapDB(p.pool.Ping(ctx))
|
||||
}
|
||||
|
||||
func (p *PG) CreateUser(ctx context.Context, username, displayName, passwordHash string) (User, error) {
|
||||
u := User{
|
||||
ID: newID(),
|
||||
Username: username,
|
||||
DisplayName: displayName,
|
||||
CreatedAt: time.Now().UTC().Truncate(time.Microsecond),
|
||||
}
|
||||
_, err := p.pool.Exec(ctx, `
|
||||
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||
VALUES ($1, $2, $3, $4, $5)`,
|
||||
u.ID, u.Username, u.DisplayName, passwordHash, u.CreatedAt)
|
||||
if err != nil {
|
||||
return User{}, mapDB(err)
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func (p *PG) User(ctx context.Context, id string) (User, error) {
|
||||
row := p.pool.QueryRow(ctx, `
|
||||
SELECT id::text, username, display_name, created_at
|
||||
FROM users WHERE id = $1`, id)
|
||||
return scanUser(row)
|
||||
}
|
||||
|
||||
func (p *PG) UserByUsername(ctx context.Context, username string) (User, string, error) {
|
||||
var u User
|
||||
var hash string
|
||||
err := p.pool.QueryRow(ctx, `
|
||||
SELECT id::text, username, display_name, created_at, password_hash
|
||||
FROM users WHERE username = $1`, username).Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt, &hash)
|
||||
if err != nil {
|
||||
return User{}, "", mapDB(err)
|
||||
}
|
||||
u.CreatedAt = u.CreatedAt.UTC()
|
||||
return u, hash, nil
|
||||
}
|
||||
|
||||
// CreateChat пишет чат и всех участников в одной транзакции.
|
||||
// Если кого-то из списка нет, COMMIT не случается и строка чата не остаётся.
|
||||
func (p *PG) CreateChat(ctx context.Context, title string, memberIDs []string, caller string) (Chat, error) {
|
||||
seen := make(map[string]struct{}, len(memberIDs))
|
||||
for _, id := range memberIDs {
|
||||
if _, dup := seen[id]; dup {
|
||||
return Chat{}, ErrInvalid
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
}
|
||||
if _, ok := seen[caller]; !ok {
|
||||
return Chat{}, ErrInvalid
|
||||
}
|
||||
tx, err := p.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return Chat{}, mapDB(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
|
||||
c := Chat{
|
||||
ID: newID(),
|
||||
Title: title,
|
||||
MemberIDs: append([]string(nil), memberIDs...),
|
||||
CreatedAt: time.Now().UTC().Truncate(time.Microsecond),
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)`, c.ID, c.Title, c.CreatedAt); err != nil {
|
||||
return Chat{}, mapDB(err)
|
||||
}
|
||||
var n int
|
||||
if err := tx.QueryRow(ctx, `SELECT count(*) FROM users WHERE id::text = ANY($1::text[])`, memberIDs).Scan(&n); err != nil {
|
||||
return Chat{}, mapDB(err)
|
||||
}
|
||||
if n != len(memberIDs) {
|
||||
return Chat{}, ErrInvalid
|
||||
}
|
||||
for i, id := range memberIDs {
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO chat_members (chat_id, user_id, position) VALUES ($1, $2, $3)`,
|
||||
c.ID, id, i); err != nil {
|
||||
return Chat{}, mapDB(err)
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return Chat{}, mapDB(err)
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (p *PG) ChatFor(ctx context.Context, chatID, userID string) (Chat, error) {
|
||||
var c Chat
|
||||
err := p.pool.QueryRow(ctx, `
|
||||
SELECT c.id::text, c.title, c.created_at
|
||||
FROM chats c
|
||||
JOIN chat_members cm ON cm.chat_id = c.id AND cm.user_id = $2
|
||||
WHERE c.id = $1`, chatID, userID).Scan(&c.ID, &c.Title, &c.CreatedAt)
|
||||
if err != nil {
|
||||
return Chat{}, mapDB(err)
|
||||
}
|
||||
c.CreatedAt = c.CreatedAt.UTC()
|
||||
ids, err := p.memberIDs(ctx, p.pool, []string{c.ID})
|
||||
if err != nil {
|
||||
return Chat{}, err
|
||||
}
|
||||
c.MemberIDs = ids[c.ID]
|
||||
if c.MemberIDs == nil {
|
||||
c.MemberIDs = []string{}
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (p *PG) ListChats(ctx context.Context, userID string, cur *Cursor, limit int) ([]Chat, bool, error) {
|
||||
hasCursor := cur != nil
|
||||
at := time.Time{}
|
||||
var id any
|
||||
if hasCursor {
|
||||
at = cur.At
|
||||
id = cur.ID
|
||||
}
|
||||
rows, err := p.pool.Query(ctx, `
|
||||
SELECT c.id::text, c.title, c.created_at
|
||||
FROM chats c
|
||||
JOIN chat_members cm ON cm.chat_id = c.id AND cm.user_id = $1
|
||||
WHERE NOT $2::bool OR (c.created_at, c.id) > ($3::timestamptz, $4::uuid)
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT $5`, userID, hasCursor, at, id, limit+1)
|
||||
if err != nil {
|
||||
return nil, false, mapDB(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
items := make([]Chat, 0)
|
||||
ids := make([]string, 0)
|
||||
for rows.Next() {
|
||||
var c Chat
|
||||
if err := rows.Scan(&c.ID, &c.Title, &c.CreatedAt); err != nil {
|
||||
return nil, false, mapDB(err)
|
||||
}
|
||||
c.CreatedAt = c.CreatedAt.UTC()
|
||||
items = append(items, c)
|
||||
ids = append(ids, c.ID)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, false, mapDB(err)
|
||||
}
|
||||
hasMore := len(items) > limit
|
||||
if hasMore {
|
||||
items = items[:limit]
|
||||
ids = ids[:limit]
|
||||
}
|
||||
members, err := p.memberIDs(ctx, p.pool, ids)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
for i := range items {
|
||||
items[i].MemberIDs = members[items[i].ID]
|
||||
if items[i].MemberIDs == nil {
|
||||
items[i].MemberIDs = []string{}
|
||||
}
|
||||
}
|
||||
return items, hasMore, nil
|
||||
}
|
||||
|
||||
func (p *PG) AddMessage(ctx context.Context, chatID, senderID, text string) (Message, error) {
|
||||
tx, err := p.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return Message{}, mapDB(err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
|
||||
// Блокировка строки чата сериализует writers одного чата.
|
||||
var exists string
|
||||
err = tx.QueryRow(ctx, `SELECT id::text FROM chats WHERE id = $1 FOR UPDATE`, chatID).Scan(&exists)
|
||||
if err != nil {
|
||||
return Message{}, mapDB(err)
|
||||
}
|
||||
var member int
|
||||
if err := tx.QueryRow(ctx, `
|
||||
SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2`, chatID, senderID).Scan(&member); err != nil {
|
||||
return Message{}, mapDB(err)
|
||||
}
|
||||
var last time.Time
|
||||
err = tx.QueryRow(ctx, `
|
||||
SELECT created_at FROM messages WHERE chat_id = $1
|
||||
ORDER BY created_at DESC LIMIT 1`, chatID).Scan(&last)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
last = time.Time{}
|
||||
} else if err != nil {
|
||||
return Message{}, mapDB(err)
|
||||
}
|
||||
now := time.Now().UTC().Truncate(time.Microsecond)
|
||||
if !last.IsZero() && !now.After(last.UTC()) {
|
||||
now = last.UTC().Add(time.Microsecond)
|
||||
}
|
||||
m := Message{
|
||||
ID: newID(),
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
Text: text,
|
||||
CreatedAt: now,
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
VALUES ($1, $2, $3, $4, $5)`, m.ID, m.ChatID, m.SenderID, m.Text, m.CreatedAt); err != nil {
|
||||
return Message{}, mapDB(err)
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return Message{}, mapDB(err)
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
func (p *PG) ListMessages(ctx context.Context, chatID, userID string, cur *Cursor, limit int) ([]Message, bool, error) {
|
||||
var member int
|
||||
err := p.pool.QueryRow(ctx, `
|
||||
SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2`, chatID, userID).Scan(&member)
|
||||
if err != nil {
|
||||
return nil, false, mapDB(err)
|
||||
}
|
||||
if cur != nil {
|
||||
var one int
|
||||
err := p.pool.QueryRow(ctx, `
|
||||
SELECT 1 FROM messages
|
||||
WHERE chat_id = $1 AND id = $2 AND created_at = $3`, chatID, cur.ID, cur.At).Scan(&one)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, false, ErrBadCursor
|
||||
}
|
||||
if err != nil {
|
||||
return nil, false, mapDB(err)
|
||||
}
|
||||
}
|
||||
hasCursor := cur != nil
|
||||
at := time.Time{}
|
||||
var id any
|
||||
if hasCursor {
|
||||
at = cur.At
|
||||
id = cur.ID
|
||||
}
|
||||
rows, err := p.pool.Query(ctx, `
|
||||
SELECT id::text, chat_id::text, sender_id::text, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1
|
||||
AND (NOT $2::bool OR (created_at, id) > ($3::timestamptz, $4::uuid))
|
||||
ORDER BY created_at, id
|
||||
LIMIT $5`, chatID, hasCursor, at, id, limit+1)
|
||||
if err != nil {
|
||||
return nil, false, mapDB(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
items := make([]Message, 0)
|
||||
for rows.Next() {
|
||||
var m Message
|
||||
if err := rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt); err != nil {
|
||||
return nil, false, mapDB(err)
|
||||
}
|
||||
m.CreatedAt = m.CreatedAt.UTC()
|
||||
items = append(items, m)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, false, mapDB(err)
|
||||
}
|
||||
hasMore := len(items) > limit
|
||||
if hasMore {
|
||||
items = items[:limit]
|
||||
}
|
||||
return items, hasMore, nil
|
||||
}
|
||||
|
||||
type queryer interface {
|
||||
Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error)
|
||||
}
|
||||
|
||||
func (p *PG) memberIDs(ctx context.Context, q queryer, chatIDs []string) (map[string][]string, error) {
|
||||
out := make(map[string][]string, len(chatIDs))
|
||||
if len(chatIDs) == 0 {
|
||||
return out, nil
|
||||
}
|
||||
rows, err := q.Query(ctx, `
|
||||
SELECT chat_id::text, user_id::text
|
||||
FROM chat_members
|
||||
WHERE chat_id::text = ANY($1::text[])
|
||||
ORDER BY chat_id, position`, chatIDs)
|
||||
if err != nil {
|
||||
return nil, mapDB(err)
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var chatID, userID string
|
||||
if err := rows.Scan(&chatID, &userID); err != nil {
|
||||
return nil, mapDB(err)
|
||||
}
|
||||
out[chatID] = append(out[chatID], userID)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, mapDB(err)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func scanUser(row pgx.Row) (User, error) {
|
||||
var u User
|
||||
err := row.Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt)
|
||||
if err != nil {
|
||||
return User{}, mapDB(err)
|
||||
}
|
||||
u.CreatedAt = u.CreatedAt.UTC()
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func mapDB(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return ErrNotFound
|
||||
}
|
||||
if errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled) {
|
||||
return ErrUnavailable
|
||||
}
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) {
|
||||
switch pgErr.Code {
|
||||
case "23505":
|
||||
return ErrConflict
|
||||
case "23503", "23514", "22P02":
|
||||
return ErrInvalid
|
||||
case "57014", "55P03":
|
||||
return ErrUnavailable
|
||||
}
|
||||
}
|
||||
var netErr net.Error
|
||||
if errors.As(err, &netErr) {
|
||||
return ErrUnavailable
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"messenger/internal/migrate"
|
||||
)
|
||||
|
||||
func openIntegration(t *testing.T) *PG {
|
||||
t.Helper()
|
||||
raw := os.Getenv("DATABASE_URL")
|
||||
if raw == "" {
|
||||
t.Skip("DATABASE_URL is not set")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
pg, err := Open(ctx, raw, 10)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(pg.Close)
|
||||
if err := migrate.Apply(ctx, pg.Pool()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return pg
|
||||
}
|
||||
|
||||
func TestIntegrationMigrationRerunKeepsRows(t *testing.T) {
|
||||
pg := openIntegration(t)
|
||||
ctx := context.Background()
|
||||
name := "mig_" + newID()[:8]
|
||||
if _, err := pg.CreateUser(ctx, name, "Миграция", "hash"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var before int
|
||||
if err := pg.Pool().QueryRow(ctx, `SELECT count(*) FROM users`).Scan(&before); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := migrate.Apply(ctx, pg.Pool()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var after int
|
||||
if err := pg.Pool().QueryRow(ctx, `SELECT count(*) FROM users`).Scan(&after); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if before != after {
|
||||
t.Fatalf("migration rerun changed users %d -> %d", before, after)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIntegrationUsernameRace(t *testing.T) {
|
||||
pg := openIntegration(t)
|
||||
ctx := context.Background()
|
||||
name := "race_" + newID()[:8]
|
||||
const n = 32
|
||||
var wg sync.WaitGroup
|
||||
wins := make(chan struct{}, n)
|
||||
fails := make(chan error, n)
|
||||
for i := 0; i < n; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
_, err := pg.CreateUser(ctx, name, "Гонка", "hash")
|
||||
if err == nil {
|
||||
wins <- struct{}{}
|
||||
return
|
||||
}
|
||||
fails <- err
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
close(wins)
|
||||
close(fails)
|
||||
got := 0
|
||||
for range wins {
|
||||
got++
|
||||
}
|
||||
if got != 1 {
|
||||
t.Fatalf("winners = %d, want 1", got)
|
||||
}
|
||||
for err := range fails {
|
||||
if !errors.Is(err, ErrConflict) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestIntegrationChatRollback(t *testing.T) {
|
||||
pg := openIntegration(t)
|
||||
ctx := context.Background()
|
||||
u, err := pg.CreateUser(ctx, "rb_"+newID()[:8], "Откат", "hash")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var before int
|
||||
if err := pg.Pool().QueryRow(ctx, `SELECT count(*) FROM chats`).Scan(&before); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = pg.CreateChat(ctx, "не должен сохраниться", []string{u.ID, "99999999-9999-4999-8999-999999999999"}, u.ID)
|
||||
if !errors.Is(err, ErrInvalid) {
|
||||
t.Fatalf("want invalid, got %v", err)
|
||||
}
|
||||
var after int
|
||||
if err := pg.Pool().QueryRow(ctx, `SELECT count(*) FROM chats`).Scan(&after); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if before != after {
|
||||
t.Fatalf("rolled-back chat stayed: %d -> %d", before, after)
|
||||
}
|
||||
var members int
|
||||
if err := pg.Pool().QueryRow(ctx, `SELECT count(*) FROM chat_members WHERE user_id = $1`, u.ID).Scan(&members); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if members != 0 {
|
||||
t.Fatalf("rolled-back membership stayed: %d", members)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostgresUnreachable(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel()
|
||||
_, err := Open(ctx, "postgres://messenger:secret@127.0.0.1:1/messenger?sslmode=disable&connect_timeout=1", 1)
|
||||
if err == nil {
|
||||
t.Fatal("closed port was accepted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,326 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrConflict = errors.New("conflict")
|
||||
ErrNotFound = errors.New("not found")
|
||||
ErrInvalid = errors.New("invalid")
|
||||
ErrBadCursor = errors.New("bad cursor")
|
||||
ErrUnavailable = errors.New("unavailable")
|
||||
)
|
||||
|
||||
// User — публичная карточка. Хеш пароля в неё не входит.
|
||||
type User struct {
|
||||
ID string
|
||||
Username string
|
||||
DisplayName string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
// Chat — неизменяемый состав участников.
|
||||
type Chat struct {
|
||||
ID string
|
||||
Title string
|
||||
MemberIDs []string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
// Message — подтверждённое сообщение. Текст после записи не меняется.
|
||||
type Message struct {
|
||||
ID string
|
||||
ChatID string
|
||||
SenderID string
|
||||
Text string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
// Cursor — позиция keyset (created_at, id). Пустые поля означают первую страницу.
|
||||
type Cursor struct {
|
||||
ID string
|
||||
At time.Time
|
||||
}
|
||||
|
||||
// Repository — пользователи, чаты и сообщения. Сессии сюда не входят.
|
||||
type Repository interface {
|
||||
Ping(ctx context.Context) error
|
||||
CreateUser(ctx context.Context, username, displayName, passwordHash string) (User, error)
|
||||
User(ctx context.Context, id string) (User, error)
|
||||
UserByUsername(ctx context.Context, username string) (User, string, error)
|
||||
CreateChat(ctx context.Context, title string, memberIDs []string, caller string) (Chat, error)
|
||||
ChatFor(ctx context.Context, chatID, userID string) (Chat, error)
|
||||
ListChats(ctx context.Context, userID string, cur *Cursor, limit int) ([]Chat, bool, error)
|
||||
AddMessage(ctx context.Context, chatID, senderID, text string) (Message, error)
|
||||
ListMessages(ctx context.Context, chatID, userID string, cur *Cursor, limit int) ([]Message, bool, error)
|
||||
}
|
||||
|
||||
type chatRec struct {
|
||||
chat Chat
|
||||
members map[string]struct{}
|
||||
}
|
||||
|
||||
// Memory сериализует записи мьютексом. Это двойник контракта для тестов без PostgreSQL.
|
||||
type Memory struct {
|
||||
mu sync.RWMutex
|
||||
users map[string]User
|
||||
byName map[string]string
|
||||
hashes map[string]string
|
||||
chats map[string]*chatRec
|
||||
chatOrder []string
|
||||
messages map[string][]Message
|
||||
msgIndex map[string]map[string]int
|
||||
last time.Time
|
||||
}
|
||||
|
||||
func New() *Memory {
|
||||
return &Memory{
|
||||
users: make(map[string]User),
|
||||
byName: make(map[string]string),
|
||||
hashes: make(map[string]string),
|
||||
chats: make(map[string]*chatRec),
|
||||
messages: make(map[string][]Message),
|
||||
msgIndex: make(map[string]map[string]int),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Memory) Ping(ctx context.Context) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Memory) CreateUser(ctx context.Context, username, displayName, passwordHash string) (User, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return User{}, ErrUnavailable
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if _, ok := s.byName[username]; ok {
|
||||
return User{}, ErrConflict
|
||||
}
|
||||
u := User{
|
||||
ID: newID(),
|
||||
Username: username,
|
||||
DisplayName: displayName,
|
||||
CreatedAt: s.nextTimeLocked(),
|
||||
}
|
||||
s.users[u.ID] = u
|
||||
s.byName[username] = u.ID
|
||||
s.hashes[u.ID] = passwordHash
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func (s *Memory) User(ctx context.Context, id string) (User, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return User{}, ErrUnavailable
|
||||
}
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
u, ok := s.users[id]
|
||||
if !ok {
|
||||
return User{}, ErrNotFound
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func (s *Memory) UserByUsername(ctx context.Context, username string) (User, string, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return User{}, "", ErrUnavailable
|
||||
}
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
id, ok := s.byName[username]
|
||||
if !ok {
|
||||
return User{}, "", ErrNotFound
|
||||
}
|
||||
return s.users[id], s.hashes[id], nil
|
||||
}
|
||||
|
||||
func (s *Memory) CreateChat(ctx context.Context, title string, memberIDs []string, caller string) (Chat, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return Chat{}, ErrUnavailable
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
seen := make(map[string]struct{}, len(memberIDs))
|
||||
for _, id := range memberIDs {
|
||||
if _, dup := seen[id]; dup {
|
||||
return Chat{}, ErrInvalid
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
if _, ok := s.users[id]; !ok {
|
||||
return Chat{}, ErrInvalid
|
||||
}
|
||||
}
|
||||
if _, ok := seen[caller]; !ok {
|
||||
return Chat{}, ErrInvalid
|
||||
}
|
||||
c := Chat{
|
||||
ID: newID(),
|
||||
Title: title,
|
||||
MemberIDs: append([]string(nil), memberIDs...),
|
||||
CreatedAt: s.nextTimeLocked(),
|
||||
}
|
||||
s.chats[c.ID] = &chatRec{chat: c, members: seen}
|
||||
s.chatOrder = append(s.chatOrder, c.ID)
|
||||
s.messages[c.ID] = nil
|
||||
s.msgIndex[c.ID] = make(map[string]int)
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (s *Memory) ChatFor(ctx context.Context, chatID, userID string) (Chat, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return Chat{}, ErrUnavailable
|
||||
}
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
rec, ok := s.chats[chatID]
|
||||
if !ok {
|
||||
return Chat{}, ErrNotFound
|
||||
}
|
||||
if _, member := rec.members[userID]; !member {
|
||||
return Chat{}, ErrNotFound
|
||||
}
|
||||
return rec.chat.clone(), nil
|
||||
}
|
||||
|
||||
func (s *Memory) ListChats(ctx context.Context, userID string, cur *Cursor, limit int) ([]Chat, bool, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, false, ErrUnavailable
|
||||
}
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
filtered := make([]Chat, 0)
|
||||
for _, id := range s.chatOrder {
|
||||
rec := s.chats[id]
|
||||
if _, ok := rec.members[userID]; ok {
|
||||
filtered = append(filtered, rec.chat.clone())
|
||||
}
|
||||
}
|
||||
start, err := indexAfter(filtered, cur, func(c Chat) (string, time.Time) {
|
||||
return c.ID, c.CreatedAt
|
||||
})
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
end := start + limit
|
||||
if end > len(filtered) {
|
||||
end = len(filtered)
|
||||
}
|
||||
return append([]Chat(nil), filtered[start:end]...), end < len(filtered), nil
|
||||
}
|
||||
|
||||
func (s *Memory) AddMessage(ctx context.Context, chatID, senderID, text string) (Message, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return Message{}, ErrUnavailable
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
rec, ok := s.chats[chatID]
|
||||
if !ok {
|
||||
return Message{}, ErrNotFound
|
||||
}
|
||||
if _, member := rec.members[senderID]; !member {
|
||||
return Message{}, ErrNotFound
|
||||
}
|
||||
m := Message{
|
||||
ID: newID(),
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
Text: text,
|
||||
CreatedAt: s.nextTimeLocked(),
|
||||
}
|
||||
idx := len(s.messages[chatID])
|
||||
s.messages[chatID] = append(s.messages[chatID], m)
|
||||
s.msgIndex[chatID][m.ID] = idx
|
||||
return m, nil
|
||||
}
|
||||
|
||||
func (s *Memory) ListMessages(ctx context.Context, chatID, userID string, cur *Cursor, limit int) ([]Message, bool, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, false, ErrUnavailable
|
||||
}
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
rec, ok := s.chats[chatID]
|
||||
if !ok {
|
||||
return nil, false, ErrNotFound
|
||||
}
|
||||
if _, member := rec.members[userID]; !member {
|
||||
return nil, false, ErrNotFound
|
||||
}
|
||||
all := s.messages[chatID]
|
||||
start := 0
|
||||
if cur != nil {
|
||||
idx, ok := s.msgIndex[chatID][cur.ID]
|
||||
if !ok || !all[idx].CreatedAt.Equal(cur.At) {
|
||||
return nil, false, ErrBadCursor
|
||||
}
|
||||
start = idx + 1
|
||||
}
|
||||
end := start + limit
|
||||
if end > len(all) {
|
||||
end = len(all)
|
||||
}
|
||||
out := append([]Message(nil), all[start:end]...)
|
||||
return out, end < len(all), nil
|
||||
}
|
||||
|
||||
// nextTimeLocked выдаёт неубывающее время фиксации.
|
||||
func (s *Memory) nextTimeLocked() time.Time {
|
||||
now := time.Now().UTC().Truncate(time.Microsecond)
|
||||
if !now.After(s.last) {
|
||||
now = s.last.Add(time.Microsecond)
|
||||
}
|
||||
s.last = now
|
||||
return now
|
||||
}
|
||||
|
||||
func indexAfter[T any](items []T, cur *Cursor, key func(T) (string, time.Time)) (int, error) {
|
||||
if cur == nil {
|
||||
return 0, nil
|
||||
}
|
||||
for i, item := range items {
|
||||
id, at := key(item)
|
||||
if id == cur.ID {
|
||||
if !at.Equal(cur.At) {
|
||||
return 0, ErrBadCursor
|
||||
}
|
||||
return i + 1, nil
|
||||
}
|
||||
}
|
||||
return 0, ErrBadCursor
|
||||
}
|
||||
|
||||
func (c Chat) clone() Chat {
|
||||
c.MemberIDs = append([]string(nil), c.MemberIDs...)
|
||||
return c
|
||||
}
|
||||
|
||||
func newID() string {
|
||||
var b [16]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
panic("crypto/rand: " + err.Error())
|
||||
}
|
||||
b[6] = (b[6] & 0x0f) | 0x40
|
||||
b[8] = (b[8] & 0x3f) | 0x80
|
||||
var buf [36]byte
|
||||
hex.Encode(buf[0:8], b[0:4])
|
||||
buf[8] = '-'
|
||||
hex.Encode(buf[9:13], b[4:6])
|
||||
buf[13] = '-'
|
||||
hex.Encode(buf[14:18], b[6:8])
|
||||
buf[18] = '-'
|
||||
hex.Encode(buf[19:23], b[8:10])
|
||||
buf[23] = '-'
|
||||
hex.Encode(buf[24:36], b[10:16])
|
||||
return string(buf[:])
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"strconv"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"messenger/internal/api"
|
||||
"messenger/internal/config"
|
||||
"messenger/internal/migrate"
|
||||
"messenger/internal/password"
|
||||
"messenger/internal/session"
|
||||
"messenger/internal/store"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if len(os.Args) > 1 && os.Args[1] == "healthcheck" {
|
||||
os.Exit(runHealthcheck())
|
||||
}
|
||||
|
||||
// Инициализация
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
slog.Error("config", "err", err.Error())
|
||||
os.Exit(2)
|
||||
}
|
||||
log := slog.New(slog.NewJSONHandler(os.Stdout, nil))
|
||||
root, stop := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
pg, err := store.Open(root, cfg.DatabaseURL, cfg.DBMaxConns)
|
||||
if err != nil {
|
||||
stop()
|
||||
log.Error("postgres", "err", "connect failed")
|
||||
os.Exit(1)
|
||||
}
|
||||
defer pg.Close()
|
||||
if err := migrate.Apply(root, pg.Pool()); err != nil {
|
||||
stop()
|
||||
log.Error("migrate", "err", "apply failed")
|
||||
os.Exit(1)
|
||||
}
|
||||
sessions, err := session.OpenRedis(cfg.RedisURL)
|
||||
if err != nil {
|
||||
stop()
|
||||
log.Error("redis", "err", "config failed")
|
||||
os.Exit(1)
|
||||
}
|
||||
defer sessions.Close()
|
||||
if err := sessions.Ping(root); err != nil {
|
||||
stop()
|
||||
log.Error("redis", "err", "ping failed")
|
||||
os.Exit(1)
|
||||
}
|
||||
stop()
|
||||
application := api.New(pg, sessions, password.Params{
|
||||
Time: cfg.Argon2Time,
|
||||
Memory: cfg.Argon2Memory,
|
||||
Threads: cfg.Argon2Threads,
|
||||
}, cfg.SessionTTL, log)
|
||||
// http сервер
|
||||
srv := &http.Server{
|
||||
Addr: cfg.Addr(),
|
||||
Handler: application,
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
ReadTimeout: 15 * time.Second,
|
||||
WriteTimeout: 15 * time.Second,
|
||||
IdleTimeout: 60 * time.Second,
|
||||
MaxHeaderBytes: 1 << 20,
|
||||
}
|
||||
|
||||
// Запуск сервера
|
||||
errCh := make(chan error, 1)
|
||||
go func() {
|
||||
log.Info("listening",
|
||||
"addr", cfg.Addr(),
|
||||
"env", cfg.Env,
|
||||
"shutdown_timeout_seconds", int(cfg.ShutdownTimeout/time.Second),
|
||||
)
|
||||
err := srv.ListenAndServe()
|
||||
if err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
errCh <- err
|
||||
}
|
||||
close(errCh)
|
||||
}()
|
||||
|
||||
// Ожидание сигнала или ошибки
|
||||
sig := make(chan os.Signal, 1)
|
||||
signal.Notify(sig, syscall.SIGTERM, syscall.SIGINT)
|
||||
select {
|
||||
case err := <-errCh:
|
||||
log.Error("server", "err", err.Error())
|
||||
os.Exit(1)
|
||||
case <-sig:
|
||||
}
|
||||
|
||||
// Плавное завершение
|
||||
application.BeginShutdown()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), cfg.ShutdownTimeout)
|
||||
defer cancel()
|
||||
if err := srv.Shutdown(ctx); err != nil {
|
||||
log.Error("shutdown timeout, closing listener", "err", err.Error())
|
||||
_ = srv.Close()
|
||||
}
|
||||
log.Info("shutdown complete")
|
||||
}
|
||||
|
||||
func runHealthcheck() int {
|
||||
port := os.Getenv("APP_PORT")
|
||||
if port == "" {
|
||||
port = "8080"
|
||||
}
|
||||
n, err := strconv.Atoi(port)
|
||||
if err != nil || n < 1 || n > 65535 {
|
||||
return 1
|
||||
}
|
||||
client := http.Client{Timeout: 2 * time.Second}
|
||||
req, err := http.NewRequest(http.MethodGet, "http://"+net.JoinHostPort("127.0.0.1", port)+"/health/ready", nil)
|
||||
if err != nil {
|
||||
return 1
|
||||
}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return 1
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
_, _ = io.Copy(io.Discard, resp.Body)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
-- Пользователи, чаты, состав и сообщения. PostgreSQL — источник истины.
|
||||
-- Сессии здесь не хранятся: их держит Redis с AOF.
|
||||
|
||||
CREATE TABLE users (
|
||||
id uuid PRIMARY KEY,
|
||||
username text NOT NULL,
|
||||
display_name text NOT NULL,
|
||||
password_hash text NOT NULL,
|
||||
created_at timestamptz NOT NULL,
|
||||
CONSTRAINT users_username_unique UNIQUE (username),
|
||||
CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9_]{3,32}$'),
|
||||
CONSTRAINT users_display_name_len CHECK (char_length(display_name) BETWEEN 1 AND 100),
|
||||
CONSTRAINT users_password_hash_present CHECK (char_length(password_hash) > 0)
|
||||
);
|
||||
|
||||
CREATE TABLE chats (
|
||||
id uuid PRIMARY KEY,
|
||||
title text NOT NULL,
|
||||
created_at timestamptz NOT NULL,
|
||||
CONSTRAINT chats_title_len CHECK (char_length(title) BETWEEN 1 AND 100)
|
||||
);
|
||||
|
||||
-- Список чатов пользователя идёт по (created_at, id).
|
||||
CREATE INDEX chats_list_idx ON chats (created_at, id);
|
||||
|
||||
CREATE TABLE chat_members (
|
||||
chat_id uuid NOT NULL REFERENCES chats (id),
|
||||
user_id uuid NOT NULL REFERENCES users (id),
|
||||
position integer NOT NULL,
|
||||
PRIMARY KEY (chat_id, user_id),
|
||||
CONSTRAINT chat_members_position_nonneg CHECK (position >= 0),
|
||||
CONSTRAINT chat_members_position_unique UNIQUE (chat_id, position)
|
||||
);
|
||||
|
||||
-- Обратный поиск: чаты конкретного пользователя.
|
||||
CREATE INDEX chat_members_user_idx ON chat_members (user_id, chat_id);
|
||||
|
||||
CREATE TABLE messages (
|
||||
id uuid PRIMARY KEY,
|
||||
chat_id uuid NOT NULL REFERENCES chats (id),
|
||||
sender_id uuid NOT NULL REFERENCES users (id),
|
||||
text text NOT NULL,
|
||||
created_at timestamptz NOT NULL,
|
||||
CONSTRAINT messages_text_len CHECK (char_length(text) BETWEEN 1 AND 4000)
|
||||
);
|
||||
|
||||
-- Keyset-страница истории: WHERE chat_id = $1 AND (created_at, id) > cursor
|
||||
-- ORDER BY created_at, id LIMIT n. Индекс покрывает фильтр и порядок,
|
||||
-- поэтому страница не читает всю историю чата.
|
||||
CREATE INDEX messages_history_idx ON messages (chat_id, created_at, id);
|
||||
@@ -0,0 +1,7 @@
|
||||
// хранит версионируемые SQL-файлы внутри бинарника.
|
||||
package migrations
|
||||
|
||||
import "embed"
|
||||
|
||||
//go:embed *.sql
|
||||
var FS embed.FS
|
||||
Executable
+83
@@ -0,0 +1,83 @@
|
||||
#!/bin/sh
|
||||
# Отказ Redis и PostgreSQL: анонимный запрос остаётся 401, живой Bearer не становится доверенным.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
mkdir -p evidence
|
||||
OUT=evidence/dependencies.txt
|
||||
: > "$OUT"
|
||||
log() { printf '%s\n' "$1" | tee -a "$OUT"; }
|
||||
|
||||
code_of() {
|
||||
# $1 name, $2 expected, $3 url, optional header in $4
|
||||
if [ "$#" -eq 4 ]; then
|
||||
got=$(curl -sS -o /tmp/lab2_dep_body -w '%{http_code}' -H "$4" "$3")
|
||||
else
|
||||
got=$(curl -sS -o /tmp/lab2_dep_body -w '%{http_code}' "$3")
|
||||
fi
|
||||
log "$1 $got"
|
||||
if [ "$got" != "$2" ]; then
|
||||
log "FAIL $1 want $2"
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
wait_ready() {
|
||||
i=0
|
||||
while [ "$i" -lt 90 ]; do
|
||||
if curl -sf -o /dev/null http://127.0.0.1:8080/health/ready; then
|
||||
return 0
|
||||
fi
|
||||
i=$((i + 1))
|
||||
sleep 0.5
|
||||
done
|
||||
log "FAIL ready did not return"
|
||||
exit 1
|
||||
}
|
||||
|
||||
trap 'rm -f /tmp/lab2_user.json /tmp/lab2_login.json /tmp/lab2_dep_body' EXIT
|
||||
wait_ready
|
||||
user="dep$(date +%s)"
|
||||
pass="Dep-check-$(date +%s)-xxxx"
|
||||
reg=$(curl -sS -o /tmp/lab2_user.json -w '%{http_code}' \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d "{\"username\":\"$user\",\"display_name\":\"Зависимость\",\"password\":\"$pass\"}" \
|
||||
http://127.0.0.1:8080/api/v1/users)
|
||||
if [ "$reg" != "201" ]; then
|
||||
log "FAIL register $reg"
|
||||
exit 1
|
||||
fi
|
||||
basic=$(printf '%s' "$user:$pass" | base64 -w 0)
|
||||
login=$(curl -sS -o /tmp/lab2_login.json -w '%{http_code}' \
|
||||
-X POST \
|
||||
-H "Authorization: Basic $basic" \
|
||||
http://127.0.0.1:8080/api/v1/auth/sessions)
|
||||
if [ "$login" != "201" ]; then
|
||||
log "FAIL login $login"
|
||||
exit 1
|
||||
fi
|
||||
token=$(python3 -c 'import json; print(json.load(open("/tmp/lab2_login.json"))["token"])')
|
||||
|
||||
log "stop redis"
|
||||
docker compose --env-file .env stop redis >> "$OUT"
|
||||
code_of live_redis_down 200 http://127.0.0.1:8080/health/live
|
||||
code_of ready_redis_down 503 http://127.0.0.1:8080/health/ready
|
||||
code_of anon_redis_down 401 http://127.0.0.1:8080/api/v1/users/me
|
||||
code_of bearer_redis_down 503 http://127.0.0.1:8080/api/v1/users/me "Authorization: Bearer $token"
|
||||
|
||||
log "start redis"
|
||||
docker compose --env-file .env start redis >> "$OUT"
|
||||
wait_ready
|
||||
|
||||
log "stop postgres"
|
||||
docker compose --env-file .env stop postgres >> "$OUT"
|
||||
code_of live_pg_down 200 http://127.0.0.1:8080/health/live
|
||||
code_of ready_pg_down 503 http://127.0.0.1:8080/health/ready
|
||||
code_of anon_pg_down 401 http://127.0.0.1:8080/api/v1/users/me
|
||||
code_of bearer_pg_down 503 http://127.0.0.1:8080/api/v1/users/me "Authorization: Bearer $token"
|
||||
|
||||
log "start postgres"
|
||||
docker compose --env-file .env start postgres >> "$OUT"
|
||||
wait_ready
|
||||
code_of bearer_after 200 http://127.0.0.1:8080/api/v1/users/me "Authorization: Bearer $token"
|
||||
log "PASS dependencies"
|
||||
rm -f /tmp/lab2_user.json /tmp/lab2_login.json /tmp/lab2_login_hdr /tmp/lab2_dep_body
|
||||
Executable
+5
@@ -0,0 +1,5 @@
|
||||
#!/bin/sh
|
||||
# Перезапуск API и всех хранилищ с сохранением volumes. Данные не сидируются заново.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
docker compose --env-file .env restart api postgres redis
|
||||
Reference in New Issue
Block a user