Перенесите реализацию ЛР 4 на стенд ЛР 5

This commit is contained in:
2026-11-18 15:33:31 +03:00
parent 276dbdad8a
commit 911d97a77a
153 changed files with 17451 additions and 1 deletions
+99
View File
@@ -0,0 +1,99 @@
// Package app is the composition root: it builds every module with its
// stores and mounts them on one HTTP engine. Both the server binary and the
// integration tests start from here.
package app
import (
"context"
"log/slog"
"time"
"github.com/gin-gonic/gin"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/redis/go-redis/v9"
"messenger/internal/attachment"
attachmentstore "messenger/internal/attachment/store"
"messenger/internal/auth"
authstore "messenger/internal/auth/store"
"messenger/internal/chat"
chatstore "messenger/internal/chat/store"
"messenger/internal/health"
"messenger/internal/platform/httpx"
"messenger/internal/user"
userstore "messenger/internal/user/store"
)
type App struct {
Engine *gin.Engine
Health *health.Handler
// Chats is exposed for the background cleanup of idempotency keys.
Chats *chat.Service
}
// Deps are the shared resources the modules are built on; their lifetime is
// owned by the caller.
type Deps struct {
Log *slog.Logger
DB *pgxpool.Pool
Sessions *redis.Client
SessionTTL time.Duration
MaxBodyBytes int64
// Zero timeouts use the defaults below.
RequestTimeout time.Duration
BinaryRequestTimeout time.Duration
InstanceID string
// IdempotencyTTL zero means the contract's 24 hours.
IdempotencyTTL time.Duration
Blobs attachment.Blobs
AttachmentsCfg attachment.Config
}
// defaultRequestTimeout stays below the server's write timeout, so a
// request that gives up on a dependency can still write its 503.
const defaultRequestTimeout = 5 * time.Second
// Binary transfers and decoding share this budget, below the 35s socket timeout.
const defaultBinaryRequestTimeout = 30 * time.Second
const defaultIdempotencyTTL = 24 * time.Hour
func New(d Deps) *App {
users := user.NewService(userstore.NewUsers(d.DB))
keyTTL := d.IdempotencyTTL
if keyTTL == 0 {
keyTTL = defaultIdempotencyTTL
}
chatRepository := chatstore.NewChats(d.DB)
chats := chat.NewService(chatRepository, chatstore.NewMessages(d.DB), users, keyTTL)
engine := httpx.NewEngine(d.Log, d.MaxBodyBytes, d.InstanceID)
probes := health.New(
health.Check{Name: "postgres", Probe: d.DB.Ping},
health.Check{Name: "valkey", Probe: func(ctx context.Context) error { return d.Sessions.Ping(ctx).Err() }},
)
probes.Register(engine)
sessions := auth.NewService(users, authstore.NewSessions(d.Sessions), d.SessionTTL)
timeout := d.RequestTimeout
if timeout == 0 {
timeout = defaultRequestTimeout
}
public := engine.Group("/api/v1", httpx.Timeout(timeout))
protected := public.Group("", auth.RequireSession(sessions))
auth.NewHandler(sessions).Register(public, protected)
user.NewHandler(users).Register(public, protected)
chat.NewHandler(chats).Register(protected)
attachments := attachment.NewService(
attachmentstore.NewAttachments(d.DB), chatRepository, d.Blobs, d.AttachmentsCfg,
)
binaryTimeout := d.BinaryRequestTimeout
if binaryTimeout == 0 {
binaryTimeout = defaultBinaryRequestTimeout
}
binaryProtected := engine.Group("/api/v1", httpx.Timeout(binaryTimeout), auth.RequireSession(sessions))
attachment.NewHandler(attachments).Register(protected, binaryProtected)
return &App{Engine: engine, Health: probes, Chats: chats}
}
+523
View File
@@ -0,0 +1,523 @@
package app_test
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"net/url"
"os"
"reflect"
"sort"
"strings"
"sync"
"testing"
"time"
"github.com/google/uuid"
"messenger/internal/app"
"messenger/internal/chat"
"messenger/internal/platform/pagination"
"messenger/internal/testenv"
"messenger/internal/user"
)
var (
db *testenv.DB
kv *testenv.KV
)
func TestMain(m *testing.M) {
ctx := context.Background()
var err error
if db, err = testenv.StartPostgres(ctx); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
if kv, err = testenv.StartValkey(ctx); err != nil {
db.Close()
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
code := m.Run()
kv.Close()
db.Close()
os.Exit(code)
}
const testPassword = "correct-horse-battery"
const testInstance = "00000000000000a1"
// errorBody mirrors the contract error envelope.
type errorBody struct {
Error struct {
Code string `json:"code"`
Message string `json:"message"`
RequestID string `json:"request_id"`
} `json:"error"`
}
type response struct {
status int
requestID string
challenge string
raw []byte
}
// tester drives the assembled application in-process.
type tester struct {
t *testing.T
a *app.App
}
// account is a registered user with a live session.
type account struct {
user.Response
token string
}
// sessionBody mirrors the contract Session schema.
type sessionBody struct {
Token string `json:"token"`
TokenType string `json:"token_type"`
ExpiresAt string `json:"expires_at"`
User user.Response `json:"user"`
}
func newTester(t *testing.T) *tester {
t.Helper()
return newTesterWithTTL(t, time.Hour)
}
// newTesterWithTTL assembles the application over empty stores.
func newTesterWithTTL(t *testing.T, ttl time.Duration) *tester {
t.Helper()
db.Reset(t)
kv.Reset(t)
log := slog.New(slog.NewTextHandler(io.Discard, nil))
return &tester{t: t, a: app.New(app.Deps{
Log: log,
DB: db.Pool,
Sessions: kv.Client,
SessionTTL: ttl,
MaxBodyBytes: 64 * 1024,
InstanceID: testInstance,
})}
}
// do sends one request, authenticated with the bearer token when it is set.
// A string body is sent verbatim, anything else is JSON-encoded; both get a
// JSON content type. Every response is checked for X-Request-Id, error
// bodies for the contract envelope, and every 401 for the challenge of the
// scheme the route expects.
func (ts *tester) do(method, path, token string, body any, headers map[string]string) response {
ts.t.Helper()
req := httptest.NewRequest(method, path, encode(ts.t, body))
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
for k, v := range headers {
req.Header.Set(k, v)
}
rec := httptest.NewRecorder()
ts.a.Engine.ServeHTTP(rec, req)
res := response{
status: rec.Code,
requestID: rec.Header().Get("X-Request-Id"),
challenge: rec.Header().Get("WWW-Authenticate"),
raw: rec.Body.Bytes(),
}
if res.requestID == "" {
ts.t.Fatalf("%s %s: missing X-Request-Id", method, path)
}
if got := rec.Header().Get("X-Instance-Id"); got != testInstance {
ts.t.Fatalf("%s %s: X-Instance-Id = %q, want %q", method, path, got, testInstance)
}
if res.status >= 400 {
var eb errorBody
if err := json.Unmarshal(res.raw, &eb); err != nil {
ts.t.Fatalf("%s %s: error body is not the contract envelope: %v: %s", method, path, err, res.raw)
}
if eb.Error.RequestID != res.requestID || eb.Error.Code == "" || eb.Error.Message == "" {
ts.t.Fatalf("%s %s: bad error envelope: %s", method, path, res.raw)
}
}
if res.status == http.StatusUnauthorized {
scheme := "Bearer "
if path == "/api/v1/auth/sessions" {
scheme = "Basic "
}
if !strings.HasPrefix(res.challenge, scheme) {
ts.t.Fatalf("%s %s: 401 challenge = %q, want scheme %q", method, path, res.challenge, scheme)
}
}
return res
}
func encode(t *testing.T, body any) io.Reader {
t.Helper()
switch b := body.(type) {
case nil:
return nil
case string:
return strings.NewReader(b)
default:
raw, err := json.Marshal(b)
if err != nil {
t.Fatal(err)
}
return bytes.NewReader(raw)
}
}
// expect asserts the status and, for errors, the contract code.
func (ts *tester) expect(res response, status int, code string) {
ts.t.Helper()
if res.status != status {
ts.t.Fatalf("status = %d, want %d; body %s", res.status, status, res.raw)
}
if code != "" {
var eb errorBody
_ = json.Unmarshal(res.raw, &eb)
if eb.Error.Code != code {
ts.t.Fatalf("code = %q, want %q; body %s", eb.Error.Code, code, res.raw)
}
}
}
// decode parses a success body into a typed DTO and rejects unknown fields,
// which enforces the additionalProperties=false rule of the contract.
func decode[T any](t *testing.T, res response) T {
t.Helper()
var out T
dec := json.NewDecoder(bytes.NewReader(res.raw))
dec.DisallowUnknownFields()
if err := dec.Decode(&out); err != nil {
t.Fatalf("body does not match %T: %v: %s", out, err, res.raw)
}
return out
}
// user registers a user and logs it in.
func (ts *tester) user(username, display string) account {
ts.t.Helper()
body := map[string]string{"username": username, "display_name": display, "password": testPassword}
res := ts.do(http.MethodPost, "/api/v1/users", "", body, nil)
ts.expect(res, http.StatusCreated, "")
registered := decode[user.Response](ts.t, res)
return account{Response: registered, token: ts.login(username, testPassword).Token}
}
func basic(username, password string) map[string]string {
raw := base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
return map[string]string{"Authorization": "Basic " + raw}
}
func (ts *tester) login(username, password string) sessionBody {
ts.t.Helper()
res := ts.do(http.MethodPost, "/api/v1/auth/sessions", "", nil, basic(username, password))
ts.expect(res, http.StatusCreated, "")
return decode[sessionBody](ts.t, res)
}
func (ts *tester) chat(token, title string, members ...string) chat.ChatResponse {
ts.t.Helper()
res := ts.do(http.MethodPost, "/api/v1/chats", token, map[string]any{"title": title, "member_ids": members}, nil)
ts.expect(res, http.StatusCreated, "")
return decode[chat.ChatResponse](ts.t, res)
}
func (ts *tester) message(token, chatID, text string) chat.MessageResponse {
ts.t.Helper()
res := ts.do(http.MethodPost, "/api/v1/chats/"+chatID+"/messages", token, map[string]string{"text": text}, freshKey())
ts.expect(res, http.StatusCreated, "")
return decode[chat.MessageResponse](ts.t, res)
}
func freshKey() map[string]string {
return map[string]string{"Idempotency-Key": uuid.NewString()}
}
func (ts *tester) chats(token, query string) pagination.PageResponse[chat.ChatResponse] {
ts.t.Helper()
res := ts.do(http.MethodGet, "/api/v1/chats"+query, token, nil, nil)
ts.expect(res, http.StatusOK, "")
return decode[pagination.PageResponse[chat.ChatResponse]](ts.t, res)
}
func (ts *tester) history(token, chatID, query string) pagination.PageResponse[chat.MessageResponse] {
ts.t.Helper()
res := ts.do(http.MethodGet, "/api/v1/chats/"+chatID+"/messages"+query, token, nil, nil)
ts.expect(res, http.StatusOK, "")
return decode[pagination.PageResponse[chat.MessageResponse]](ts.t, res)
}
func cursorQuery(limit int, cursor *string) string {
q := fmt.Sprintf("?limit=%d", limit)
if cursor != nil {
q += "&cursor=" + url.QueryEscape(*cursor)
}
return q
}
func TestHealthEndpoints(t *testing.T) {
ts := newTester(t)
for _, path := range []string{"/health/live", "/health/ready"} {
res := ts.do(http.MethodGet, path, "", nil, nil)
ts.expect(res, http.StatusOK, "")
if strings.TrimSpace(string(res.raw)) != `{"status":"ok"}` {
t.Fatalf("%s body = %s", path, res.raw)
}
}
ts.a.Health.SetReady(false)
ts.expect(ts.do(http.MethodGet, "/health/ready", "", nil, nil), http.StatusServiceUnavailable, "unavailable")
ts.expect(ts.do(http.MethodGet, "/health/live", "", nil, nil), http.StatusOK, "")
}
func TestRegisterUserShapeAndConflicts(t *testing.T) {
ts := newTester(t)
alice := ts.user("alice", "Алиса")
if alice.ID == "" || alice.Username != "alice" || alice.DisplayName != "Алиса" {
t.Fatalf("user = %+v", alice)
}
if !strings.HasSuffix(alice.CreatedAt, "Z") || len(alice.CreatedAt) != len("2026-09-01T12:00:00.000Z") {
t.Fatalf("created_at = %q", alice.CreatedAt)
}
post := func(body any) response { return ts.do(http.MethodPost, "/api/v1/users", "", body, nil) }
ts.expect(post(map[string]string{"username": "alice", "display_name": "Other", "password": testPassword}), http.StatusConflict, "conflict")
ts.expect(post(map[string]string{"username": "bob", "display_name": "Bob"}), http.StatusBadRequest, "invalid_request")
ts.expect(post(map[string]string{"username": "Alice", "display_name": "x"}), http.StatusBadRequest, "invalid_request")
ts.expect(post(map[string]string{"username": "bob", "display_name": " "}), http.StatusBadRequest, "invalid_request")
ts.expect(post(map[string]any{"username": "bob", "display_name": "x", "password": "no"}), http.StatusBadRequest, "invalid_request")
ts.expect(post(`{"username":`), http.StatusBadRequest, "invalid_request")
ts.expect(post(map[string]any{"username": 5, "display_name": "x"}), http.StatusBadRequest, "invalid_request")
}
func TestCurrentUserIsTheTokenOwner(t *testing.T) {
ts := newTester(t)
alice := ts.user("alice", "Алиса")
ts.user("bob", "Боб")
res := ts.do(http.MethodGet, "/api/v1/users/me", alice.token, nil, nil)
ts.expect(res, http.StatusOK, "")
if got := decode[user.Response](t, res); got != alice.Response {
t.Fatalf("me = %+v, want %+v", got, alice.Response)
}
}
func TestChatCreationRules(t *testing.T) {
ts := newTester(t)
alice, bob := ts.user("alice", "A"), ts.user("bob", "B")
created := ts.chat(alice.token, "Проект по ВНП", alice.ID, bob.ID)
if created.Title != "Проект по ВНП" || len(created.MemberIDs) != 2 || created.MemberIDs[0] != alice.ID || created.MemberIDs[1] != bob.ID {
t.Fatalf("chat = %+v", created)
}
unknown := "22222222-2222-4222-8222-222222222222"
invalid := map[string]any{
"creator missing": map[string]any{"title": "t", "member_ids": []string{bob.ID}},
"duplicate": map[string]any{"title": "t", "member_ids": []string{alice.ID, alice.ID}},
"unknown member": map[string]any{"title": "t", "member_ids": []string{alice.ID, unknown}},
"malformed uuid": map[string]any{"title": "t", "member_ids": []string{alice.ID, "not-a-uuid"}},
"empty members": map[string]any{"title": "t", "member_ids": []string{}},
"blank title": map[string]any{"title": "", "member_ids": []string{alice.ID}},
"long title": map[string]any{"title": strings.Repeat("я", 101), "member_ids": []string{alice.ID}},
"missing members": map[string]any{"title": "t"},
"extra field": map[string]any{"title": "t", "member_ids": []string{alice.ID}, "owner": alice.ID},
}
for name, body := range invalid {
res := ts.do(http.MethodPost, "/api/v1/chats", alice.token, body, nil)
if res.status != http.StatusBadRequest {
t.Errorf("%s: status = %d, want 400; body %s", name, res.status, res.raw)
}
}
ts.expect(ts.do(http.MethodPost, "/api/v1/chats", "", map[string]any{"title": "t", "member_ids": []string{alice.ID}}, nil), http.StatusUnauthorized, "unauthorized")
}
func TestChatVisibilityAndListing(t *testing.T) {
ts := newTester(t)
alice, bob, eve := ts.user("alice", "A"), ts.user("bob", "B"), ts.user("eve", "E")
created := ts.chat(alice.token, "Контрактный тест", alice.ID, bob.ID)
path := "/api/v1/chats/" + created.ID
res := ts.do(http.MethodGet, path, bob.token, nil, nil)
ts.expect(res, http.StatusOK, "")
if got := decode[chat.ChatResponse](t, res); got.ID != created.ID || len(got.MemberIDs) != 2 {
t.Fatalf("GET chat = %+v", got)
}
ts.expect(ts.do(http.MethodGet, path, eve.token, nil, nil), http.StatusNotFound, "not_found")
ts.expect(ts.do(http.MethodGet, "/api/v1/chats/33333333-3333-4333-8333-333333333333", alice.token, nil, nil), http.StatusNotFound, "not_found")
ts.expect(ts.do(http.MethodGet, "/api/v1/chats/not-a-uuid", alice.token, nil, nil), http.StatusBadRequest, "invalid_request")
ts.expect(ts.do(http.MethodGet, path, "", nil, nil), http.StatusUnauthorized, "unauthorized")
listed := ts.chats(bob.token, "?limit=100")
if len(listed.Items) != 1 || listed.Items[0].ID != created.ID || listed.NextCursor != nil {
t.Fatalf("bob list = %+v", listed)
}
hidden := ts.do(http.MethodGet, "/api/v1/chats?limit=100", eve.token, nil, nil)
ts.expect(hidden, http.StatusOK, "")
if !strings.Contains(string(hidden.raw), `"items":[]`) || !strings.Contains(string(hidden.raw), `"next_cursor":null`) {
t.Fatalf("empty list must serialize items as [] and next_cursor as null: %s", hidden.raw)
}
}
func TestChatListPagination(t *testing.T) {
ts := newTester(t)
alice := ts.user("alice", "A")
var expected []string
for i := 0; i < 5; i++ {
expected = append(expected, ts.chat(alice.token, fmt.Sprintf("chat %d", i), alice.ID).ID)
}
var walked []string
var cursor *string
for pages := 0; pages < 10; pages++ {
page := ts.chats(alice.token, cursorQuery(2, cursor))
for _, c := range page.Items {
walked = append(walked, c.ID)
}
if page.NextCursor == nil {
break
}
cursor = page.NextCursor
}
if strings.Join(walked, ",") != strings.Join(expected, ",") {
t.Fatalf("walked %v, want %v", walked, expected)
}
bob := ts.user("bob", "B")
foreign := ts.chats(alice.token, "?limit=1").NextCursor
ts.expect(ts.do(http.MethodGet, "/api/v1/chats"+cursorQuery(50, foreign), bob.token, nil, nil), http.StatusBadRequest, "invalid_request")
ts.expect(ts.do(http.MethodGet, "/api/v1/chats?cursor=", alice.token, nil, nil), http.StatusBadRequest, "invalid_request")
ts.expect(ts.do(http.MethodGet, "/api/v1/chats?limit=abc", alice.token, nil, nil), http.StatusBadRequest, "invalid_request")
}
func TestMessagesEndToEnd(t *testing.T) {
ts := newTester(t)
alice, bob, eve := ts.user("alice", "A"), ts.user("bob", "B"), ts.user("eve", "E")
room := ts.chat(alice.token, "Контрактный тест", alice.ID, bob.ID)
path := "/api/v1/chats/" + room.ID + "/messages"
first := ts.message(alice.token, room.ID, "Привет, мир 👋")
second := ts.message(bob.token, room.ID, "Сообщение Боба")
if first.SenderID != alice.ID || second.SenderID != bob.ID {
t.Fatalf("sender must come from the bearer token: %+v %+v", first, second)
}
if first.ChatID != room.ID || first.Text != "Привет, мир 👋" {
t.Fatalf("message = %+v", first)
}
page1 := ts.history(bob.token, room.ID, "?limit=1")
if len(page1.Items) != 1 || page1.NextCursor == nil || !reflect.DeepEqual(page1.Items[0], first) {
t.Fatalf("page1 = %+v", page1)
}
page2 := ts.history(alice.token, room.ID, cursorQuery(1, page1.NextCursor))
if len(page2.Items) != 1 || page2.NextCursor != nil || !reflect.DeepEqual(page2.Items[0], second) {
t.Fatalf("page2 = %+v", page2)
}
post := func(actor string, body any) response { return ts.do(http.MethodPost, path, actor, body, freshKey()) }
ts.expect(post(alice.token, map[string]string{"text": ""}), http.StatusBadRequest, "invalid_request")
ts.expect(post(alice.token, map[string]string{"text": " "}), http.StatusBadRequest, "invalid_request")
ts.expect(post(alice.token, map[string]string{"text": strings.Repeat("я", 4001)}), http.StatusBadRequest, "invalid_request")
ts.expect(post(alice.token, map[string]string{"text": "x", "sender_id": bob.ID}), http.StatusBadRequest, "invalid_request")
ts.expect(post(alice.token, `{"text":`), http.StatusBadRequest, "invalid_request")
ts.expect(post(eve.token, map[string]string{"text": "чужое"}), http.StatusNotFound, "not_found")
ts.expect(post(eve.token, map[string]string{"text": ""}), http.StatusNotFound, "not_found")
ts.expect(post("", map[string]string{"text": "x"}), http.StatusUnauthorized, "unauthorized")
ts.expect(post(alice.token, map[string]string{"text": strings.Repeat("я", 4000)}), http.StatusCreated, "")
get := func(actor, query string) response { return ts.do(http.MethodGet, path+query, actor, nil, nil) }
ts.expect(get(eve.token, ""), http.StatusNotFound, "not_found")
ts.expect(get(alice.token, "?limit=0"), http.StatusBadRequest, "invalid_request")
ts.expect(get(alice.token, "?limit=101"), http.StatusBadRequest, "invalid_request")
ts.expect(get(alice.token, "?cursor=garbage"), http.StatusBadRequest, "invalid_request")
other := ts.chat(alice.token, "другой", alice.ID)
ts.expect(ts.do(http.MethodGet, "/api/v1/chats/"+other.ID+"/messages"+cursorQuery(50, page1.NextCursor), alice.token, nil, nil), http.StatusBadRequest, "invalid_request")
}
func TestMessageHistoryWalkAcrossPages(t *testing.T) {
ts := newTester(t)
alice := ts.user("alice", "A")
room := ts.chat(alice.token, "t", alice.ID)
var expected []string
for i := 0; i < 23; i++ {
expected = append(expected, ts.message(alice.token, room.ID, fmt.Sprintf("m%d", i)).ID)
}
var walked []string
var cursor *string
for {
page := ts.history(alice.token, room.ID, cursorQuery(5, cursor))
for _, m := range page.Items {
walked = append(walked, m.ID)
}
if page.NextCursor == nil {
break
}
cursor = page.NextCursor
}
if strings.Join(walked, ",") != strings.Join(expected, ",") {
t.Fatalf("walk mismatch:\n%v\n%v", walked, expected)
}
}
func TestConcurrentSendsProduceExactlyUniqueMessages(t *testing.T) {
ts := newTester(t)
const clients, perClient = 10, 10
clientsList := make([]account, 0, clients)
members := make([]string, 0, clients)
for i := 0; i < clients; i++ {
c := ts.user(fmt.Sprintf("client_%d", i), "C")
clientsList = append(clientsList, c)
members = append(members, c.ID)
}
room := ts.chat(clientsList[0].token, "нагрузка", members...)
var wg sync.WaitGroup
for n, c := range clientsList {
wg.Go(func() {
for i := 0; i < perClient; i++ {
res := ts.do(http.MethodPost, "/api/v1/chats/"+room.ID+"/messages", c.token, map[string]string{"text": fmt.Sprintf("c%d-m%d", n, i)}, freshKey())
if res.status != http.StatusCreated {
t.Errorf("client %d: status %d body %s", n, res.status, res.raw)
}
}
})
}
wg.Wait()
page := ts.history(clientsList[0].token, room.ID, "?limit=100")
if len(page.Items) != clients*perClient || page.NextCursor != nil {
t.Fatalf("got %d messages, next=%v; want %d and null", len(page.Items), page.NextCursor, clients*perClient)
}
ids := make([]string, 0, len(page.Items))
unique := make(map[string]struct{}, len(page.Items))
for _, m := range page.Items {
ids = append(ids, m.ID)
unique[m.ID] = struct{}{}
}
if !sort.StringsAreSorted(ids) {
t.Fatal("history is not ordered by id")
}
if len(unique) != clients*perClient {
t.Fatalf("%d unique ids, want %d", len(unique), clients*perClient)
}
}
func TestUnknownRouteAndMethodAreContractErrors(t *testing.T) {
ts := newTester(t)
ts.expect(ts.do(http.MethodGet, "/api/v1/nothing", "", nil, nil), http.StatusNotFound, "not_found")
ts.expect(ts.do(http.MethodDelete, "/api/v1/users", "", nil, nil), http.StatusMethodNotAllowed, "invalid_request")
ts.expect(ts.do(http.MethodPost, "/api/v1/users", "", "{}", map[string]string{"Content-Type": "text/plain"}), http.StatusUnsupportedMediaType, "unsupported_media_type")
big := map[string]string{"username": "big", "display_name": strings.Repeat("x", 70*1024)}
ts.expect(ts.do(http.MethodPost, "/api/v1/users", "", big, nil), http.StatusRequestEntityTooLarge, "payload_too_large")
}
+193
View File
@@ -0,0 +1,193 @@
package app_test
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"image"
"image/jpeg"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"net/url"
"os"
"strings"
"testing"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"messenger/internal/app"
"messenger/internal/attachment"
"messenger/internal/chat"
"messenger/internal/testenv"
)
func TestAttachmentUploadAuthenticatesBeforeParsing(t *testing.T) {
ts := newTester(t)
ts.expect(ts.do(http.MethodPost, "/api/v1/chats/not-a-uuid/attachments?filename=x.png", "", "invalid image", map[string]string{"Content-Type": "image/png"}), http.StatusUnauthorized, "unauthorized")
}
func TestAttachmentRoutesUseConfiguredDeadlines(t *testing.T) {
for _, binary := range []bool{false, true} {
name := "metadata"
requestTimeout := 40 * time.Millisecond
var binaryTimeout time.Duration
if binary {
name = "upload"
requestTimeout = time.Second
binaryTimeout = 40 * time.Millisecond
}
t.Run(name, func(t *testing.T) {
ts := newTester(t)
actor := ts.user("deadline_user", "User")
ts.a = app.New(app.Deps{
Log: slog.New(slog.NewTextHandler(io.Discard, nil)), DB: db.Pool, Sessions: kv.Client,
SessionTTL: time.Hour, MaxBodyBytes: 65536, InstanceID: testInstance,
RequestTimeout: requestTimeout, BinaryRequestTimeout: binaryTimeout,
})
var held []*pgxpool.Conn
for range db.Pool.Config().MaxConns {
conn, err := db.Pool.Acquire(context.Background())
if err != nil {
t.Fatal(err)
}
held = append(held, conn)
}
defer func() {
for _, conn := range held {
conn.Release()
}
}()
ctx, cancel := context.WithTimeout(context.Background(), 400*time.Millisecond)
defer cancel()
path := "/api/v1/attachments/11111111-1111-4111-8111-111111111111"
req := httptest.NewRequest("GET", path, nil).WithContext(ctx)
if binary {
path = "/api/v1/chats/11111111-1111-4111-8111-111111111111/attachments?filename=x.png"
req = httptest.NewRequest("POST", path, strings.NewReader("body")).WithContext(ctx)
req.Header.Set("Content-Type", "image/png")
}
req.Header.Set("Authorization", "Bearer "+actor.token)
rec := httptest.NewRecorder()
started := time.Now()
ts.a.Engine.ServeHTTP(rec, req)
if rec.Code != 503 || time.Since(started) > 200*time.Millisecond {
t.Fatalf("route exceeded configured budget: status%d elapsed%v body%s", rec.Code, time.Since(started), rec.Body.String())
}
})
}
}
func (ts *tester) binary(method, path, token, mime string, data []byte, length int64) response {
ts.t.Helper()
req := httptest.NewRequest(method, path, bytes.NewReader(data))
req.ContentLength = length
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
if mime != "" {
req.Header.Set("Content-Type", mime)
}
rec := httptest.NewRecorder()
ts.a.Engine.ServeHTTP(rec, req)
res := response{status: rec.Code, requestID: rec.Header().Get("X-Request-Id"), challenge: rec.Header().Get("WWW-Authenticate"), raw: rec.Body.Bytes()}
if res.requestID == "" || rec.Header().Get("X-Instance-Id") == "" {
ts.t.Fatal("binary response missing correlation headers")
}
return res
}
func TestAttachmentRealS3RoundTripValidationAndOutage(t *testing.T) {
ctx := context.Background()
s3, err := testenv.StartS3(ctx)
if err != nil {
t.Fatal(err)
}
defer s3.Close()
ts := newTester(t)
ts.a = app.New(app.Deps{Log: slog.New(slog.NewTextHandler(io.Discard, nil)), DB: db.Pool, Sessions: kv.Client, SessionTTL: time.Hour, MaxBodyBytes: 65536, InstanceID: testInstance, Blobs: s3.APIStore})
alice, bob, eve := ts.user("alice", "A"), ts.user("bob", "B"), ts.user("eve", "E")
room := ts.chat(alice.token, "files", alice.ID, bob.ID)
path := "/api/v1/chats/" + room.ID + "/attachments?filename=" + url.QueryEscape("фото.png")
data, err := os.ReadFile("../../tests/fixtures/sample.png")
if err != nil {
t.Fatal(err)
}
res := ts.binary("POST", path, alice.token, "image/png", data, int64(len(data)))
ts.expect(res, 201, "")
a := decode[attachment.Response](t, res)
digest := sha256.Sum256(data)
if a.SHA256 != hex.EncodeToString(digest[:]) || a.SizeBytes != int64(len(data)) || a.Filename != "фото.png" || a.Status != "ready" || a.ErrorCode != nil || len(a.Variants) != 0 {
t.Fatalf("attachment: %+v", a)
}
base := "/api/v1/attachments/" + a.ID
for _, suffix := range []string{"", "/content"} {
ts.expect(ts.do("GET", base+suffix, eve.token, nil, nil), 404, "not_found")
}
ts.expect(ts.do("GET", base, bob.token, nil, nil), 200, "")
got := ts.binary("GET", base+"/content", bob.token, "", nil, 0)
ts.expect(got, 200, "")
if !bytes.Equal(got.raw, data) {
t.Fatal("download bytes changed")
}
ts.expect(ts.do("GET", base+"/content?variant=thumbnail", bob.token, nil, nil), 400, "invalid_request")
msg := ts.do("POST", "/api/v1/chats/"+room.ID+"/messages", bob.token, map[string]any{"text": "", "attachment_ids": []string{a.ID}}, freshKey())
ts.expect(msg, 201, "")
if m := decode[chat.MessageResponse](t, msg); len(m.AttachmentIDs) != 1 || m.AttachmentIDs[0] != a.ID {
t.Fatal("lost attachment on message")
}
other := ts.chat(alice.token, "other", alice.ID)
ts.expect(ts.do("POST", "/api/v1/chats/"+other.ID+"/messages", alice.token, map[string]any{"text": "", "attachment_ids": []string{a.ID}}, freshKey()), 404, "not_found")
for _, tc := range []struct {
name, mime string
data []byte
length int64
want int
}{
{"MIME spoof", "image/jpeg", data, int64(len(data)), 415},
{"broken body", "image/png", data[:len(data)/2], int64(len(data) / 2), 415},
{"unsupported", "image/gif", data, int64(len(data)), 415},
{"oversize", "image/png", nil, 10485761, 413},
{"unknown length", "image/png", data, -1, 400},
{"empty", "image/png", nil, 0, 400},
} {
t.Run(tc.name, func(t *testing.T) {
r := ts.binary("POST", path, alice.token, tc.mime, tc.data, tc.length)
if r.status != tc.want {
t.Fatalf("got %d want %d: %s", r.status, tc.want, r.raw)
}
})
}
for _, name := range []string{"../x.png", `a\b.png`, "bad\nname", strings.Repeat("я", 256)} {
ts.expect(ts.binary("POST", "/api/v1/chats/"+room.ID+"/attachments?filename="+url.QueryEscape(name), alice.token, "image/png", data, int64(len(data))), 400, "invalid_request")
}
var j bytes.Buffer
if err := jpeg.Encode(&j, image.NewRGBA(image.Rect(0, 0, 5, 3)), nil); err != nil {
t.Fatal(err)
}
ts.expect(ts.binary("POST", path, bob.token, "image/jpeg", j.Bytes(), int64(j.Len())), 201, "")
ts.expect(ts.binary("POST", path, eve.token, "image/png", data, int64(len(data))), 404, "not_found")
// An interrupted read is never a 500 or a successfully published identity.
before := 0
if err := db.Pool.QueryRow(ctx, `SELECT count(*) FROM attachments`).Scan(&before); err != nil {
t.Fatal(err)
}
short := ts.binary("POST", path, alice.token, "image/png", data[:10], int64(len(data)))
if short.status != 400 && short.status != 503 {
t.Fatalf("interrupted body: %d %s", short.status, short.raw)
}
after := 0
if err := db.Pool.QueryRow(ctx, `SELECT count(*) FROM attachments`).Scan(&after); err != nil || before != after {
t.Fatalf("interruption published identity: %d -> %d (%v)", before, after, err)
}
if err := s3.Stop(ctx); err != nil {
t.Fatal(err)
}
ts.expect(ts.binary("POST", path, alice.token, "image/png", data, int64(len(data))), 503, "unavailable")
ts.expect(ts.do("GET", base+"/content", bob.token, nil, nil), 503, "unavailable")
ts.expect(ts.do("GET", "/health/ready", "", nil, nil), 200, "")
ts.message(alice.token, room.ID, fmt.Sprintf("text works with S3 down %d", time.Now().UnixNano()))
}
+176
View File
@@ -0,0 +1,176 @@
package app_test
import (
"encoding/base64"
"encoding/json"
"net/http"
"strings"
"testing"
"time"
"messenger/internal/user"
)
const (
basicChallenge = `Basic realm="messenger", charset="UTF-8"`
bearerChallenge = `Bearer realm="messenger"`
)
func TestLoginReturnsBearerSession(t *testing.T) {
ts := newTester(t)
alice := ts.user("alice", "Алиса")
before := time.Now()
res := ts.do(http.MethodPost, "/api/v1/auth/sessions", "", nil, basic("alice", testPassword))
ts.expect(res, http.StatusCreated, "")
s := decode[sessionBody](t, res)
if s.TokenType != "Bearer" || len(s.Token) != 43 || s.Token == alice.token {
t.Fatalf("session = %+v; want a fresh 43-character Bearer token", s)
}
if s.User != alice.Response {
t.Fatalf("user = %+v, want %+v", s.User, alice.Response)
}
expires, err := time.Parse(time.RFC3339, s.ExpiresAt)
if err != nil || !strings.HasSuffix(s.ExpiresAt, "Z") {
t.Fatalf("expires_at = %q: %v", s.ExpiresAt, err)
}
if ttl := expires.Sub(before); ttl < 59*time.Minute || ttl > 61*time.Minute {
t.Fatalf("expires_at is %v after login, want the 1h TTL", ttl)
}
if strings.Contains(string(res.raw), "password") || strings.Contains(string(res.raw), "argon2") {
t.Fatalf("session response leaks password data: %s", res.raw)
}
}
func TestLoginFailuresAreUniformBasicChallenges(t *testing.T) {
ts := newTester(t)
ts.user("alice", "Алиса")
encoded := func(s string) string { return base64.StdEncoding.EncodeToString([]byte(s)) }
cases := map[string]map[string]string{
"wrong password": basic("alice", testPassword+"!"),
"unknown user": basic("mallory", testPassword),
"no header": nil,
"bearer scheme": {"Authorization": "Bearer " + strings.Repeat("A", 43)},
"not base64": {"Authorization": "Basic !!!"},
"no colon": {"Authorization": "Basic " + encoded("alice")},
"nul username": basic("a\x00b", testPassword),
"non-utf-8 name": basic("\xff\xfe", testPassword),
}
messages := map[string]string{}
for name, headers := range cases {
res := ts.do(http.MethodPost, "/api/v1/auth/sessions", "", nil, headers)
ts.expect(res, http.StatusUnauthorized, "unauthorized")
if res.challenge != basicChallenge {
t.Errorf("%s: WWW-Authenticate = %q, want %q", name, res.challenge, basicChallenge)
}
var eb errorBody
_ = json.Unmarshal(res.raw, &eb)
messages[name] = eb.Error.Message
}
if messages["wrong password"] != messages["unknown user"] {
t.Fatalf("wrong password and unknown user must look the same: %q vs %q", messages["wrong password"], messages["unknown user"])
}
}
// The password is UTF-8 and may contain colons; only the first colon of the
// Basic credentials separates the username (contracts/README.md).
func TestLoginAcceptsColonAndUnicodePasswords(t *testing.T) {
ts := newTester(t)
const password = "пароль:с:двоеточием 👋"
body := map[string]string{"username": "alice", "display_name": "Алиса", "password": password}
ts.expect(ts.do(http.MethodPost, "/api/v1/users", "", body, nil), http.StatusCreated, "")
s := ts.login("alice", password)
if s.User.Username != "alice" {
t.Fatalf("logged in as %+v", s.User)
}
}
func TestProtectedRoutesAcceptOnlyBearer(t *testing.T) {
ts := newTester(t)
alice, eve := ts.user("alice", "A"), ts.user("eve", "E")
me := func(headers map[string]string) response {
return ts.do(http.MethodGet, "/api/v1/users/me", "", nil, headers)
}
rejected := map[string]map[string]string{
"no header": nil,
"basic with valid credentials": basic("alice", testPassword),
"x-user-id alone": {"X-User-Id": alice.ID},
"unknown token": {"Authorization": "Bearer " + strings.Repeat("A", 43)},
"empty token": {"Authorization": "Bearer "},
"scheme only": {"Authorization": "Bearer"},
"other scheme": {"Authorization": "Token " + alice.token},
"two tokens": {"Authorization": "Bearer " + alice.token + " " + eve.token},
}
for name, headers := range rejected {
res := me(headers)
ts.expect(res, http.StatusUnauthorized, "unauthorized")
if res.challenge != bearerChallenge {
t.Errorf("%s: WWW-Authenticate = %q, want %q", name, res.challenge, bearerChallenge)
}
}
accepted := map[string]map[string]string{
"lowercase scheme": {"Authorization": "bearer " + alice.token},
"several spaces": {"Authorization": "Bearer " + alice.token},
"x-user-id is ignored": {"Authorization": "Bearer " + alice.token, "X-User-Id": eve.ID},
}
for name, headers := range accepted {
res := me(headers)
ts.expect(res, http.StatusOK, "")
if got := decode[user.Response](t, res); got.ID != alice.ID {
t.Errorf("%s: caller = %s, want alice", name, got.ID)
}
}
}
func TestLogoutRevokesOnlyTheCurrentToken(t *testing.T) {
ts := newTester(t)
alice := ts.user("alice", "A")
other := ts.login("alice", testPassword)
res := ts.do(http.MethodDelete, "/api/v1/auth/sessions/current", alice.token, nil, nil)
ts.expect(res, http.StatusNoContent, "")
if len(res.raw) != 0 {
t.Fatalf("204 must have no body, got %q", res.raw)
}
for _, again := range []response{
ts.do(http.MethodGet, "/api/v1/users/me", alice.token, nil, nil),
ts.do(http.MethodDelete, "/api/v1/auth/sessions/current", alice.token, nil, nil),
} {
ts.expect(again, http.StatusUnauthorized, "unauthorized")
if again.challenge != bearerChallenge {
t.Fatalf("revoked token: WWW-Authenticate = %q, want %q", again.challenge, bearerChallenge)
}
}
ts.expect(ts.do(http.MethodGet, "/api/v1/users/me", other.Token, nil, nil), http.StatusOK, "")
}
// Valkey enforces the expiry by the Docker VM clock, which may lag this host
// by a fraction of a second, so the 401 is awaited with a tolerance.
func TestSessionExpiresAfterTTL(t *testing.T) {
const ttl, clockTolerance = 2 * time.Second, 3 * time.Second
ts := newTesterWithTTL(t, ttl)
alice := ts.user("alice", "A")
ts.expect(ts.do(http.MethodGet, "/api/v1/users/me", alice.token, nil, nil), http.StatusOK, "")
time.Sleep(ttl)
deadline := time.Now().Add(clockTolerance)
for {
res := ts.do(http.MethodGet, "/api/v1/users/me", alice.token, nil, nil)
if res.status == http.StatusUnauthorized {
ts.expect(res, http.StatusUnauthorized, "unauthorized")
return
}
if time.Now().After(deadline) {
t.Fatalf("session still valid %v after its TTL of %v", clockTolerance, ttl)
}
time.Sleep(100 * time.Millisecond)
}
}
func TestRegistrationIsPublicAndIgnoresAuthorization(t *testing.T) {
ts := newTester(t)
body := map[string]string{"username": "alice", "display_name": "A", "password": testPassword}
headers := map[string]string{"Authorization": "Bearer garbage"}
ts.expect(ts.do(http.MethodPost, "/api/v1/users", "", body, headers), http.StatusCreated, "")
}
+101
View File
@@ -0,0 +1,101 @@
package app_test
import (
"context"
"io"
"log/slog"
"net/http"
"testing"
"time"
"messenger/internal/app"
"messenger/internal/testenv"
)
// newIsolatedTester assembles the application over containers of its own,
// so a test can stop or pause them without disturbing the shared ones.
func newIsolatedTester(t *testing.T, requestTimeout time.Duration) (*tester, *testenv.DB, *testenv.KV) {
t.Helper()
ctx := context.Background()
pg, err := testenv.StartPostgres(ctx)
if err != nil {
t.Fatal(err)
}
t.Cleanup(pg.Close)
vk, err := testenv.StartValkey(ctx)
if err != nil {
t.Fatal(err)
}
t.Cleanup(vk.Close)
log := slog.New(slog.NewTextHandler(io.Discard, nil))
a := app.New(app.Deps{
Log: log,
DB: pg.Pool,
Sessions: vk.Client,
SessionTTL: time.Hour,
MaxBodyBytes: 64 * 1024,
RequestTimeout: requestTimeout,
InstanceID: testInstance,
})
return &tester{t: t, a: a}, pg, vk
}
// Without the session store no caller can be authenticated: the API answers
// 503, never 401 (the token is not at fault) and never as an anonymous user.
// Registration does not need the store and keeps working.
func TestValkeyOutageAnswers503(t *testing.T) {
ts, _, vk := newIsolatedTester(t, 5*time.Second)
alice := ts.user("alice", "Алиса")
room := ts.chat(alice.token, "t", alice.ID)
if err := vk.Stop(context.Background()); err != nil {
t.Fatal(err)
}
ts.expect(ts.do(http.MethodGet, "/api/v1/users/me", alice.token, nil, nil), http.StatusServiceUnavailable, "unavailable")
ts.expect(ts.do(http.MethodGet, "/api/v1/chats/"+room.ID, alice.token, nil, nil), http.StatusServiceUnavailable, "unavailable")
ts.expect(ts.do(http.MethodPost, "/api/v1/auth/sessions", "", nil, basic("alice", testPassword)), http.StatusServiceUnavailable, "unavailable")
ts.expect(ts.do(http.MethodDelete, "/api/v1/auth/sessions/current", alice.token, nil, nil), http.StatusServiceUnavailable, "unavailable")
ts.expect(ts.do(http.MethodGet, "/health/ready", "", nil, nil), http.StatusServiceUnavailable, "unavailable")
ts.expect(ts.do(http.MethodGet, "/health/live", "", nil, nil), http.StatusOK, "")
body := map[string]string{"username": "bob", "display_name": "Bob", "password": testPassword}
ts.expect(ts.do(http.MethodPost, "/api/v1/users", "", body, nil), http.StatusCreated, "")
}
func TestPostgresOutageAnswers503(t *testing.T) {
ts, pg, _ := newIsolatedTester(t, 5*time.Second)
alice := ts.user("alice", "Алиса")
if err := pg.Stop(context.Background()); err != nil {
t.Fatal(err)
}
ts.expect(ts.do(http.MethodGet, "/api/v1/chats", alice.token, nil, nil), http.StatusServiceUnavailable, "unavailable")
ts.expect(ts.do(http.MethodGet, "/api/v1/users/me", alice.token, nil, nil), http.StatusServiceUnavailable, "unavailable")
ts.expect(ts.do(http.MethodPost, "/api/v1/auth/sessions", "", nil, basic("alice", testPassword)), http.StatusServiceUnavailable, "unavailable")
body := map[string]string{"username": "bob", "display_name": "Bob", "password": testPassword}
ts.expect(ts.do(http.MethodPost, "/api/v1/users", "", body, nil), http.StatusServiceUnavailable, "unavailable")
ts.expect(ts.do(http.MethodGet, "/health/ready", "", nil, nil), http.StatusServiceUnavailable, "unavailable")
}
// A database that accepts connections but never answers must not hold the
// request: the request deadline turns it into a 503.
func TestHungPostgresAnswers503WithinTheRequestTimeout(t *testing.T) {
ts, pg, _ := newIsolatedTester(t, 300*time.Millisecond)
alice := ts.user("alice", "Алиса")
ctx := context.Background()
if err := pg.Pause(ctx); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = pg.Unpause(ctx) })
for _, path := range []string{"/api/v1/chats", "/health/ready"} {
start := time.Now()
ts.expect(ts.do(http.MethodGet, path, alice.token, nil, nil), http.StatusServiceUnavailable, "unavailable")
if elapsed := time.Since(start); elapsed > 2*time.Second {
t.Fatalf("%s took %v with a hung database, want it bounded", path, elapsed)
}
}
}
+153
View File
@@ -0,0 +1,153 @@
package app_test
import (
"bytes"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"messenger/internal/app"
)
func (ts *tester) send(token, chatID, key string, body any) response {
ts.t.Helper()
return ts.do(http.MethodPost, "/api/v1/chats/"+chatID+"/messages", token, body, map[string]string{"Idempotency-Key": key})
}
func TestSendIdempotencyKeyValidation(t *testing.T) {
ts := newTester(t)
alice := ts.user("alice", "A")
room := ts.chat(alice.token, "ключи", alice.ID)
path := "/api/v1/chats/" + room.ID + "/messages"
body := map[string]string{"text": "x"}
ts.expect(ts.do(http.MethodPost, path, alice.token, body, nil), http.StatusBadRequest, "invalid_request")
for name, key := range map[string]string{
"empty": "",
"too long": strings.Repeat("a", 129),
"inner space": "a b",
"non-ascii": "ключ",
"slash": "a/b",
} {
res := ts.send(alice.token, room.ID, key, body)
if res.status != http.StatusBadRequest {
t.Errorf("%s key: status %d, want 400", name, res.status)
}
}
ts.expect(ts.send(alice.token, room.ID, strings.Repeat("a", 128), body), http.StatusCreated, "")
ts.expect(ts.send(alice.token, room.ID, "Az09._:-", body), http.StatusCreated, "")
// Two Idempotency-Key headers are ambiguous: which one names the attempt?
req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(`{"text":"x"}`))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+alice.token)
req.Header.Add("Idempotency-Key", "one")
req.Header.Add("Idempotency-Key", "two")
rec := httptest.NewRecorder()
ts.a.Engine.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
t.Fatalf("two keys: status %d, want 400", rec.Code)
}
}
func TestReplayReturnsIdenticalBody(t *testing.T) {
ts := newTester(t)
alice := ts.user("alice", "A")
room := ts.chat(alice.token, "повторы", alice.ID)
first := ts.send(alice.token, room.ID, "retry-1", map[string]string{"text": "Привет 👋"})
ts.expect(first, http.StatusCreated, "")
// The same JSON with other spacing is the same request.
again := ts.send(alice.token, room.ID, "retry-1", ` { "text" : "Привет 👋" } `)
ts.expect(again, http.StatusCreated, "")
if !bytes.Equal(first.raw, again.raw) {
t.Fatalf("replay body differs:\n%s\n%s", first.raw, again.raw)
}
if page := ts.history(alice.token, room.ID, ""); len(page.Items) != 1 {
t.Fatalf("history has %d messages, want 1", len(page.Items))
}
}
func TestReplayWithDifferentBodyIs409(t *testing.T) {
ts := newTester(t)
alice := ts.user("alice", "A")
room := ts.chat(alice.token, "конфликт", alice.ID)
ts.expect(ts.send(alice.token, room.ID, "k", map[string]string{"text": "первое"}), http.StatusCreated, "")
ts.expect(ts.send(alice.token, room.ID, "k", map[string]string{"text": "второе"}), http.StatusConflict, "conflict")
}
// A replay is a new request: a revoked session cannot fetch the stored result.
func TestReplayRechecksSession(t *testing.T) {
ts := newTester(t)
alice := ts.user("alice", "A")
room := ts.chat(alice.token, "сессия", alice.ID)
ts.expect(ts.send(alice.token, room.ID, "k", map[string]string{"text": "x"}), http.StatusCreated, "")
ts.expect(ts.do(http.MethodDelete, "/api/v1/auth/sessions/current", alice.token, nil, nil), http.StatusNoContent, "")
ts.expect(ts.send(alice.token, room.ID, "k", map[string]string{"text": "x"}), http.StatusUnauthorized, "unauthorized")
}
// The header is checked before access, like the JSON syntax: the answer does
// not depend on the chat, so it reveals nothing about a foreign one.
func TestOutsiderWithoutKeyGets400AndWithKey404(t *testing.T) {
ts := newTester(t)
alice, eve := ts.user("alice", "A"), ts.user("eve", "E")
room := ts.chat(alice.token, "чужой", alice.ID)
path := "/api/v1/chats/" + room.ID + "/messages"
ts.expect(ts.do(http.MethodPost, path, eve.token, map[string]string{"text": "x"}, nil), http.StatusBadRequest, "invalid_request")
ts.expect(ts.send(eve.token, room.ID, "k", map[string]string{"text": "x"}), http.StatusNotFound, "not_found")
}
// Two applications over the same stores stand for two replicas: retries of one
// key alternate between them and still create one message.
func TestConcurrentReplaysAcrossTwoAppsCreateOneMessage(t *testing.T) {
ts := newTester(t)
alice := ts.user("alice", "A")
room := ts.chat(alice.token, "реплики", alice.ID)
other := app.New(app.Deps{
Log: slog.New(slog.NewTextHandler(io.Discard, nil)),
DB: db.Pool,
Sessions: kv.Client,
SessionTTL: time.Hour,
MaxBodyBytes: 64 * 1024,
InstanceID: "00000000000000b2",
})
engines := []http.Handler{ts.a.Engine, other.Engine}
const attempts = 10
type result struct {
status int
body string
instance string
}
results := make([]result, attempts)
var wg sync.WaitGroup
for i := range attempts {
wg.Go(func() {
req := httptest.NewRequest(http.MethodPost, "/api/v1/chats/"+room.ID+"/messages", strings.NewReader(`{"text":"один раз"}`))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+alice.token)
req.Header.Set("Idempotency-Key", "shared")
rec := httptest.NewRecorder()
engines[i%2].ServeHTTP(rec, req)
results[i] = result{rec.Code, rec.Body.String(), rec.Header().Get("X-Instance-Id")}
})
}
wg.Wait()
instances := map[string]bool{}
for i, r := range results {
if r.status != http.StatusCreated || r.body != results[0].body {
t.Fatalf("attempt %d: %d %s; want 201 %s", i, r.status, r.body, results[0].body)
}
instances[r.instance] = true
}
if len(instances) != 2 {
t.Fatalf("instances %v, want both replicas", instances)
}
if page := ts.history(alice.token, room.ID, ""); len(page.Items) != 1 {
t.Fatalf("history has %d messages, want 1: %+v", len(page.Items), page.Items)
}
}