Реализовать lab4: вложения S3/MinIO, уровень 4 и трек 2 reconciler.
Метаданные в PostgreSQL, байты в приватном bucket; sync upload 201 ready; компенсация orphan и cmd/reconcile с dry-run/apply и grace period.
This commit is contained in:
@@ -0,0 +1,664 @@
|
||||
// Собственные проверки lab3 (плюс регрессия lab2). Им нужен уже поднятый
|
||||
// PostgreSQL и Redis (docker compose up / scripts/up.sh): контракт требует
|
||||
// настоящую БД, а не sqlmock. HTTP бьём в httptest.Server поверх того же Store,
|
||||
// что и реплики — идемпотентность и гонки видны без обхода LB.
|
||||
//
|
||||
// Каждый тест пишет в лог, что именно проверяет и какой статус получил.
|
||||
package studenttests
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi2026lab4/internal/api"
|
||||
"mtusi2026lab4/internal/auth"
|
||||
"mtusi2026lab4/internal/blob"
|
||||
"mtusi2026lab4/internal/session"
|
||||
"mtusi2026lab4/internal/store"
|
||||
)
|
||||
|
||||
var (
|
||||
sharedStore *store.Store
|
||||
sharedSessions *session.Store
|
||||
sharedRedisURL string
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
ctx := context.Background()
|
||||
dsn := getenv("DATABASE_URL", "postgres://messenger:messenger@127.0.0.1:5432/messenger?sslmode=disable")
|
||||
sharedRedisURL = getenv("REDIS_URL", "redis://127.0.0.1:6379/0")
|
||||
hasher, err := auth.NewHasher()
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "hasher:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
sharedStore, err = store.Open(ctx, dsn, hasher, 5)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "postgres:", err)
|
||||
fmt.Fprintln(os.Stderr, "подсказка: docker compose --env-file .env up -d --build")
|
||||
os.Exit(1)
|
||||
}
|
||||
defer sharedStore.Close()
|
||||
if err := sharedStore.Migrate(ctx); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "migrate:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
// Повтор миграции не должен падать и не должен дублировать данные.
|
||||
if err := sharedStore.Migrate(ctx); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "migrate second:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
sharedSessions, err = session.Open(sharedRedisURL, time.Hour)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "redis:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
defer sharedSessions.Close()
|
||||
os.Exit(m.Run())
|
||||
}
|
||||
|
||||
func TestMalformedJSONAndValidation(t *testing.T) {
|
||||
srv := newAPI(t, time.Hour)
|
||||
defer srv.Close()
|
||||
logStep(t, "битый JSON, хвост после объекта, лишнее поле, пустой текст, чужой чат")
|
||||
|
||||
status, body := do(t, srv, http.MethodPost, "/api/v1/users", nil, "{")
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusBadRequest || !strings.Contains(body, "invalid_request") {
|
||||
t.Fatalf("malformed json: status=%d body=%s", status, body)
|
||||
}
|
||||
|
||||
status, body = do(t, srv, http.MethodPost, "/api/v1/users", nil,
|
||||
`{"username":"abc","display_name":"Имя","password":"correct-horse-1","extra":1}`)
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusBadRequest {
|
||||
t.Fatalf("extra field: status=%d", status)
|
||||
}
|
||||
|
||||
user := register(t, srv, "ok_user")
|
||||
token := login(t, srv, user.username, user.password)
|
||||
chat := createChat(t, srv, token, user.id, "Чат проверки")
|
||||
auth := map[string]string{"Authorization": "Bearer " + token}
|
||||
|
||||
// Decoder.More() это не ловит: один объект декодируется, лишняя скобка остаётся.
|
||||
for _, raw := range []string{`{"text":"valid"}}`, `{"text":"valid"}]`} {
|
||||
status, body = do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", auth, raw)
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusBadRequest {
|
||||
t.Fatalf("trailing garbage %q: status=%d body=%s", raw, status, body)
|
||||
}
|
||||
}
|
||||
|
||||
status, body = do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", auth, `{"text":" "}`)
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusBadRequest {
|
||||
t.Fatalf("blank message: status=%d", status)
|
||||
}
|
||||
|
||||
outsider := register(t, srv, "outsider")
|
||||
outTok := login(t, srv, outsider.username, outsider.password)
|
||||
status, body = do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", map[string]string{"Authorization": "Bearer " + outTok}, `{"text":"чужое"}`)
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusNotFound {
|
||||
t.Fatalf("foreign chat: status=%d body=%s", status, body)
|
||||
}
|
||||
logOK(t, "валидация JSON, хвоста, пустого текста и чужого чата")
|
||||
}
|
||||
|
||||
func TestMessageTextPreservedAndLengthOnOriginal(t *testing.T) {
|
||||
srv := newAPI(t, time.Hour)
|
||||
defer srv.Close()
|
||||
logStep(t, "пробелы по краям сохраняются; длина считается по исходному тексту")
|
||||
user := register(t, srv, "text_user")
|
||||
token := login(t, srv, user.username, user.password)
|
||||
chat := createChat(t, srv, token, user.id, "Текст")
|
||||
auth := map[string]string{"Authorization": "Bearer " + token}
|
||||
|
||||
original := " строка\nс пробелами "
|
||||
status, body := do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", auth,
|
||||
fmt.Sprintf(`{"text":%q}`, original))
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusCreated {
|
||||
t.Fatalf("preserve spaces: status=%d", status)
|
||||
}
|
||||
got := decode(t, body)
|
||||
if got["text"] != original {
|
||||
t.Fatalf("text mutated: got %q want %q", got["text"], original)
|
||||
}
|
||||
|
||||
tooLong := " " + strings.Repeat("a", 4000) // 4001 code points
|
||||
status, body = do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", auth,
|
||||
fmt.Sprintf(`{"text":%q}`, tooLong))
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusBadRequest {
|
||||
t.Fatalf("length after trim bypass: status=%d body=%s", status, body)
|
||||
}
|
||||
logOK(t, "текст сохранён целиком, обход лимита через TrimSpace закрыт")
|
||||
}
|
||||
|
||||
func TestSessionRejectsJSONBody(t *testing.T) {
|
||||
srv := newAPI(t, time.Hour)
|
||||
defer srv.Close()
|
||||
logStep(t, "POST /auth/sessions с телом должен быть 400 даже при верном Basic")
|
||||
user := register(t, srv, "body_user")
|
||||
status, body := do(t, srv, http.MethodPost, "/api/v1/auth/sessions", map[string]string{
|
||||
"Authorization": "Basic " + basic(user.username, user.password),
|
||||
}, `{"extra":1}`)
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusBadRequest {
|
||||
t.Fatalf("session with body: status=%d body=%s", status, body)
|
||||
}
|
||||
logOK(t, "вход без JSON body")
|
||||
}
|
||||
|
||||
func TestWrongPasswordLogoutAndIgnoredUserHeader(t *testing.T) {
|
||||
srv := newAPI(t, time.Hour)
|
||||
defer srv.Close()
|
||||
logStep(t, "неверный пароль, Basic на бизнес-методе, X-User-Id, logout")
|
||||
user := register(t, srv, "auth_user")
|
||||
other := register(t, srv, "auth_other")
|
||||
|
||||
status, body, hdr := doRaw(t, srv, http.MethodPost, "/api/v1/auth/sessions", map[string]string{
|
||||
"Authorization": "Basic " + basic(user.username, "wrong-password-1"),
|
||||
}, "")
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusUnauthorized || !strings.HasPrefix(hdr.Get("WWW-Authenticate"), "Basic") {
|
||||
t.Fatalf("wrong password: status=%d www=%q", status, hdr.Get("WWW-Authenticate"))
|
||||
}
|
||||
|
||||
token := login(t, srv, user.username, user.password)
|
||||
status, body, hdr = doRaw(t, srv, http.MethodGet, "/api/v1/users/me", map[string]string{
|
||||
"Authorization": "Basic " + basic(user.username, user.password),
|
||||
}, "")
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusUnauthorized || !strings.HasPrefix(hdr.Get("WWW-Authenticate"), "Bearer") {
|
||||
t.Fatalf("basic on business endpoint: status=%d www=%q", status, hdr.Get("WWW-Authenticate"))
|
||||
}
|
||||
|
||||
status, body = do(t, srv, http.MethodGet, "/api/v1/users/me", map[string]string{"X-User-Id": user.id}, "")
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusUnauthorized {
|
||||
t.Fatalf("X-User-Id alone: status=%d", status)
|
||||
}
|
||||
|
||||
status, body = do(t, srv, http.MethodGet, "/api/v1/users/me", map[string]string{
|
||||
"Authorization": "Bearer " + token,
|
||||
"X-User-Id": other.id,
|
||||
}, "")
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusOK || !strings.Contains(body, user.id) || strings.Contains(body, other.id) {
|
||||
t.Fatalf("X-User-Id overrode bearer: status=%d body=%s", status, body)
|
||||
}
|
||||
|
||||
status, _ = do(t, srv, http.MethodDelete, "/api/v1/auth/sessions/current", map[string]string{"Authorization": "Bearer " + token}, "")
|
||||
t.Logf("logout status=%d", status)
|
||||
if status != http.StatusNoContent {
|
||||
t.Fatalf("logout status=%d", status)
|
||||
}
|
||||
status, _ = do(t, srv, http.MethodGet, "/api/v1/users/me", map[string]string{"Authorization": "Bearer " + token}, "")
|
||||
if status != http.StatusUnauthorized {
|
||||
t.Fatalf("token still valid after logout: %d", status)
|
||||
}
|
||||
status, _ = do(t, srv, http.MethodDelete, "/api/v1/auth/sessions/current", map[string]string{"Authorization": "Bearer " + token}, "")
|
||||
if status != http.StatusUnauthorized {
|
||||
t.Fatalf("second logout status=%d", status)
|
||||
}
|
||||
logOK(t, "пароль, заголовки и отзыв сессии")
|
||||
}
|
||||
|
||||
func TestSessionExpiry(t *testing.T) {
|
||||
srv := newAPI(t, 2*time.Second)
|
||||
defer srv.Close()
|
||||
logStep(t, "SESSION_TTL=2s: тот же токен после паузы должен стать 401, TTL рестартом API не продлевается")
|
||||
user := register(t, srv, "ttl_user")
|
||||
token := login(t, srv, user.username, user.password)
|
||||
time.Sleep(2500 * time.Millisecond)
|
||||
status, body := do(t, srv, http.MethodGet, "/api/v1/users/me", map[string]string{"Authorization": "Bearer " + token}, "")
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusUnauthorized {
|
||||
t.Fatalf("expired token status=%d body=%s", status, body)
|
||||
}
|
||||
logOK(t, "истёкшая сессия отклонена")
|
||||
}
|
||||
|
||||
func TestDuplicateUsernameRace(t *testing.T) {
|
||||
srv := newAPI(t, time.Hour)
|
||||
defer srv.Close()
|
||||
name := "race_" + uuid.NewString()[:8]
|
||||
logStep(t, "8 параллельных регистраций username="+name)
|
||||
const n = 8
|
||||
codes := make([]int, n)
|
||||
var wg sync.WaitGroup
|
||||
body := fmt.Sprintf(`{"username":%q,"display_name":"Гонка","password":"correct-horse-1"}`, name)
|
||||
for i := 0; i < n; i++ {
|
||||
wg.Add(1)
|
||||
go func(i int) {
|
||||
defer wg.Done()
|
||||
status, _ := do(t, srv, http.MethodPost, "/api/v1/users", nil, body)
|
||||
codes[i] = status
|
||||
}(i)
|
||||
}
|
||||
wg.Wait()
|
||||
ok, conflict := 0, 0
|
||||
for _, c := range codes {
|
||||
switch c {
|
||||
case http.StatusCreated:
|
||||
ok++
|
||||
case http.StatusConflict:
|
||||
conflict++
|
||||
default:
|
||||
t.Errorf("unexpected status %d", c)
|
||||
}
|
||||
}
|
||||
t.Logf("created=%d conflict=%d", ok, conflict)
|
||||
if ok != 1 || conflict != n-1 {
|
||||
t.Fatalf("race result created=%d conflict=%d", ok, conflict)
|
||||
}
|
||||
logOK(t, "UNIQUE username выдержал гонку")
|
||||
}
|
||||
|
||||
func TestChatCreateRollsBack(t *testing.T) {
|
||||
srv := newAPI(t, time.Hour)
|
||||
defer srv.Close()
|
||||
user := register(t, srv, "roll_user")
|
||||
token := login(t, srv, user.username, user.password)
|
||||
title := "rollback-" + uuid.NewString()
|
||||
missing := uuid.NewString()
|
||||
logStep(t, "создание чата с несуществующим участником должно откатиться, title="+title)
|
||||
raw := fmt.Sprintf(`{"title":%q,"member_ids":[%q,%q]}`, title, user.id, missing)
|
||||
status, body := do(t, srv, http.MethodPost, "/api/v1/chats", map[string]string{"Authorization": "Bearer " + token}, raw)
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusBadRequest {
|
||||
t.Fatalf("status=%d", status)
|
||||
}
|
||||
n, err := sharedStore.CountChatsByTitle(context.Background(), title)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Logf("строк chats с этим title после ошибки: %d", n)
|
||||
if n != 0 {
|
||||
t.Fatalf("chat row survived rollback: %d", n)
|
||||
}
|
||||
logOK(t, "транзакция создания чата откатилась")
|
||||
}
|
||||
|
||||
func TestPaginationPages(t *testing.T) {
|
||||
srv := newAPI(t, time.Hour)
|
||||
defer srv.Close()
|
||||
logStep(t, "три сообщения, две страницы limit=2, затем последняя")
|
||||
user := register(t, srv, "page_user")
|
||||
token := login(t, srv, user.username, user.password)
|
||||
chat := createChat(t, srv, token, user.id, "Страницы")
|
||||
auth := map[string]string{"Authorization": "Bearer " + token}
|
||||
for _, text := range []string{"раз", "два", "три"} {
|
||||
status, body := do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", auth, fmt.Sprintf(`{"text":%q}`, text))
|
||||
if status != http.StatusCreated {
|
||||
t.Fatalf("post message %s: %d %s", text, status, body)
|
||||
}
|
||||
}
|
||||
status, body := do(t, srv, http.MethodGet, "/api/v1/chats/"+chat+"/messages?limit=2", auth, "")
|
||||
logResult(t, status, body)
|
||||
page := decode(t, body)
|
||||
items, _ := page["items"].([]any)
|
||||
if status != http.StatusOK || len(items) != 2 || page["next_cursor"] == nil {
|
||||
t.Fatalf("page1: %+v", page)
|
||||
}
|
||||
cursor, _ := page["next_cursor"].(string)
|
||||
status, body = do(t, srv, http.MethodGet, "/api/v1/chats/"+chat+"/messages?limit=2&cursor="+cursor, auth, "")
|
||||
logResult(t, status, body)
|
||||
page = decode(t, body)
|
||||
items, _ = page["items"].([]any)
|
||||
if len(items) != 1 || page["next_cursor"] != nil {
|
||||
t.Fatalf("page2: %+v", page)
|
||||
}
|
||||
logOK(t, "keyset обошёл историю без зависания cursor")
|
||||
}
|
||||
|
||||
func TestRedisDownIsNotAnonymous(t *testing.T) {
|
||||
logStep(t, "закрытый клиент Redis: вход и Bearer дают 503, а не 200 от анонима")
|
||||
closed, err := session.Open(sharedRedisURL, time.Hour)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := closed.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
srv := httptest.NewServer(api.New(sharedStore, closed, blob.NewMemory(), "test-closed-redis").Handler())
|
||||
defer srv.Close()
|
||||
regSrv := newAPI(t, time.Hour)
|
||||
defer regSrv.Close()
|
||||
user := register(t, regSrv, "redis_down")
|
||||
status, body := do(t, srv, http.MethodPost, "/api/v1/auth/sessions", map[string]string{
|
||||
"Authorization": "Basic " + basic(user.username, user.password),
|
||||
}, "")
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusServiceUnavailable {
|
||||
t.Fatalf("login with dead redis: status=%d body=%s", status, body)
|
||||
}
|
||||
status, body = do(t, srv, http.MethodGet, "/api/v1/users/me", map[string]string{
|
||||
"Authorization": "Bearer " + strings.Repeat("ab", 32),
|
||||
}, "")
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusServiceUnavailable {
|
||||
t.Fatalf("bearer with dead redis: status=%d body=%s", status, body)
|
||||
}
|
||||
logOK(t, "сбой Redis не стал анонимным доступом")
|
||||
}
|
||||
|
||||
func TestPostgresDownIsNotAnonymous(t *testing.T) {
|
||||
logStep(t, "закрытый пул PostgreSQL: ready/me/login дают 503, без тела пользователя")
|
||||
regSrv := newAPI(t, time.Hour)
|
||||
defer regSrv.Close()
|
||||
user := register(t, regSrv, "pg_down")
|
||||
token := login(t, regSrv, user.username, user.password)
|
||||
|
||||
hasher, err := auth.NewHasher()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dsn := getenv("DATABASE_URL", "postgres://messenger:messenger@127.0.0.1:5432/messenger?sslmode=disable")
|
||||
broken, err := store.Open(context.Background(), dsn, hasher, 5)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
broken.Close()
|
||||
sessions, err := session.Open(sharedRedisURL, time.Hour)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = sessions.Close() })
|
||||
srv := httptest.NewServer(api.New(broken, sessions, blob.NewMemory(), "test-broken-pg").Handler())
|
||||
defer srv.Close()
|
||||
|
||||
status, body := do(t, srv, http.MethodGet, "/health/ready", nil, "")
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusServiceUnavailable {
|
||||
t.Fatalf("ready with dead postgres: %d", status)
|
||||
}
|
||||
status, body = do(t, srv, http.MethodGet, "/api/v1/users/me", map[string]string{
|
||||
"Authorization": "Bearer " + token,
|
||||
}, "")
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusServiceUnavailable || strings.Contains(body, `"username"`) {
|
||||
t.Fatalf("me with dead postgres: status=%d body=%s", status, body)
|
||||
}
|
||||
status, body = do(t, srv, http.MethodPost, "/api/v1/auth/sessions", map[string]string{
|
||||
"Authorization": "Basic " + basic(user.username, user.password),
|
||||
}, "")
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusServiceUnavailable {
|
||||
t.Fatalf("login with dead postgres: status=%d body=%s", status, body)
|
||||
}
|
||||
logOK(t, "сбой PostgreSQL не стал анонимным доступом")
|
||||
}
|
||||
|
||||
|
||||
func TestIdempotencyReplayAndConflict(t *testing.T) {
|
||||
srv := newAPI(t, time.Hour)
|
||||
defer srv.Close()
|
||||
logStep(t, "повтор того же Idempotency-Key возвращает то же сообщение; другой body — 409")
|
||||
user := register(t, srv, "idem_user")
|
||||
token := login(t, srv, user.username, user.password)
|
||||
chat := createChat(t, srv, token, user.id, "Идемпотентность")
|
||||
key := "key-" + uuid.NewString()
|
||||
auth := map[string]string{
|
||||
"Authorization": "Bearer " + token,
|
||||
"Idempotency-Key": key,
|
||||
}
|
||||
status, body := do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", auth, `{"text":"один раз"}`)
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusCreated {
|
||||
t.Fatalf("first: %d %s", status, body)
|
||||
}
|
||||
first := decode(t, body)
|
||||
status, body = do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", auth, `{"text":"один раз"}`)
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusCreated {
|
||||
t.Fatalf("replay: %d %s", status, body)
|
||||
}
|
||||
second := decode(t, body)
|
||||
if first["id"] != second["id"] || first["text"] != second["text"] {
|
||||
t.Fatalf("replay differs: first=%v second=%v", first, second)
|
||||
}
|
||||
status, body = do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", auth, `{"text":"другой body"}`)
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusConflict {
|
||||
t.Fatalf("conflict: %d %s", status, body)
|
||||
}
|
||||
logOK(t, "replay и conflict по Idempotency-Key")
|
||||
}
|
||||
|
||||
func TestIdempotencyKeyRequiredAndConcurrent(t *testing.T) {
|
||||
srv := newAPI(t, time.Hour)
|
||||
defer srv.Close()
|
||||
logStep(t, "нет ключа → 400; 8 параллельных POST с одним ключом → ровно одно сообщение")
|
||||
user := register(t, srv, "idem_race")
|
||||
token := login(t, srv, user.username, user.password)
|
||||
chat := createChat(t, srv, token, user.id, "Гонка ключа")
|
||||
|
||||
// Явно без ключа: хелпер doRaw подставляет ключ только если заголовок пуст —
|
||||
// поэтому бьём в doRaw с пустым Idempotency-Key, переопределив после...
|
||||
// Проще: отдельный raw-запрос.
|
||||
req, err := http.NewRequest(http.MethodPost, srv.URL+"/api/v1/chats/"+chat+"/messages", strings.NewReader(`{"text":"без ключа"}`))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, _ := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
logResult(t, resp.StatusCode, string(b))
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("missing key: %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
key := "race-" + uuid.NewString()
|
||||
const n = 8
|
||||
ids := make([]string, n)
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < n; i++ {
|
||||
wg.Add(1)
|
||||
go func(i int) {
|
||||
defer wg.Done()
|
||||
status, body := do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", map[string]string{
|
||||
"Authorization": "Bearer " + token,
|
||||
"Idempotency-Key": key,
|
||||
}, `{"text":"параллельно"}`)
|
||||
if status != http.StatusCreated {
|
||||
t.Errorf("worker %d status=%d body=%s", i, status, body)
|
||||
return
|
||||
}
|
||||
ids[i] = decode(t, body)["id"].(string)
|
||||
}(i)
|
||||
}
|
||||
wg.Wait()
|
||||
uniq := map[string]struct{}{}
|
||||
for _, id := range ids {
|
||||
if id == "" {
|
||||
t.Fatalf("empty id in race")
|
||||
}
|
||||
uniq[id] = struct{}{}
|
||||
}
|
||||
t.Logf("unique message ids=%d", len(uniq))
|
||||
if len(uniq) != 1 {
|
||||
t.Fatalf("expected 1 message, got %d ids=%v", len(uniq), ids)
|
||||
}
|
||||
logOK(t, "ключ обязателен; конкурентный повтор не плодит дубли")
|
||||
}
|
||||
|
||||
func TestInstanceIDHeaderPresent(t *testing.T) {
|
||||
srv := newAPI(t, time.Hour)
|
||||
defer srv.Close()
|
||||
logStep(t, "каждый ответ содержит непустой X-Instance-Id")
|
||||
status, body, hdr := doRaw(t, srv, http.MethodGet, "/health/live", nil, "")
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusOK || hdr.Get("X-Instance-Id") == "" {
|
||||
t.Fatalf("live instance header missing: %q status=%d", hdr.Get("X-Instance-Id"), status)
|
||||
}
|
||||
logOK(t, "X-Instance-Id="+hdr.Get("X-Instance-Id"))
|
||||
}
|
||||
|
||||
type account struct {
|
||||
id string
|
||||
username string
|
||||
password string
|
||||
}
|
||||
|
||||
func newAPI(t *testing.T, ttl time.Duration) *httptest.Server {
|
||||
t.Helper()
|
||||
sessions, err := session.Open(sharedRedisURL, ttl)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = sessions.Close() })
|
||||
return httptest.NewServer(api.New(sharedStore, sessions, blob.NewMemory(), "test-instance").Handler())
|
||||
}
|
||||
|
||||
func newAPIBlob(t *testing.T, ttl time.Duration, bl api.BlobStore) *httptest.Server {
|
||||
t.Helper()
|
||||
sessions, err := session.Open(sharedRedisURL, ttl)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = sessions.Close() })
|
||||
return httptest.NewServer(api.New(sharedStore, sessions, bl, "test-instance").Handler())
|
||||
}
|
||||
|
||||
func register(t *testing.T, srv *httptest.Server, prefix string) account {
|
||||
t.Helper()
|
||||
username := prefix + "_" + uuid.NewString()[:8]
|
||||
password := "correct-horse-1"
|
||||
raw := fmt.Sprintf(`{"username":%q,"display_name":"Студент","password":%q}`, username, password)
|
||||
status, body := do(t, srv, http.MethodPost, "/api/v1/users", nil, raw)
|
||||
if status != http.StatusCreated {
|
||||
t.Fatalf("register %s: %d %s", username, status, body)
|
||||
}
|
||||
var u struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(body), &u); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Logf("создан %s id=%s", username, u.ID)
|
||||
return account{id: u.ID, username: username, password: password}
|
||||
}
|
||||
|
||||
func login(t *testing.T, srv *httptest.Server, username, password string) string {
|
||||
t.Helper()
|
||||
status, body := do(t, srv, http.MethodPost, "/api/v1/auth/sessions", map[string]string{
|
||||
"Authorization": "Basic " + basic(username, password),
|
||||
}, "")
|
||||
if status != http.StatusCreated {
|
||||
t.Fatalf("login %s: %d %s", username, status, body)
|
||||
}
|
||||
var s struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(body), &s); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(s.Token) < 32 {
|
||||
t.Fatalf("token too short: %d", len(s.Token))
|
||||
}
|
||||
t.Logf("сессия выпущена, длина токена=%d (значение не печатаем)", len(s.Token))
|
||||
return s.Token
|
||||
}
|
||||
|
||||
func createChat(t *testing.T, srv *httptest.Server, token, userID, title string) string {
|
||||
t.Helper()
|
||||
raw := fmt.Sprintf(`{"title":%q,"member_ids":[%q]}`, title, userID)
|
||||
status, body := do(t, srv, http.MethodPost, "/api/v1/chats", map[string]string{"Authorization": "Bearer " + token}, raw)
|
||||
if status != http.StatusCreated {
|
||||
t.Fatalf("chat: %d %s", status, body)
|
||||
}
|
||||
var c struct {
|
||||
ID string `json:"id"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(body), &c); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return c.ID
|
||||
}
|
||||
|
||||
func do(t *testing.T, srv *httptest.Server, method, path string, headers map[string]string, raw string) (int, string) {
|
||||
t.Helper()
|
||||
status, body, _ := doRaw(t, srv, method, path, headers, raw)
|
||||
return status, body
|
||||
}
|
||||
|
||||
func doRaw(t *testing.T, srv *httptest.Server, method, path string, headers map[string]string, raw string) (int, string, http.Header) {
|
||||
t.Helper()
|
||||
var rdr io.Reader
|
||||
if raw != "" {
|
||||
rdr = bytes.NewBufferString(raw)
|
||||
}
|
||||
req, err := http.NewRequest(method, srv.URL+path, rdr)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if raw != "" && method != http.MethodGet {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
for k, v := range headers {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
// Lab3: POST сообщений без ключа — 400. В хелперах подставляем уникальный ключ,
|
||||
// если тест сам его не задал (негативные проверки ключа делают это явно).
|
||||
if method == http.MethodPost && strings.Contains(path, "/messages") && req.Header.Get("Idempotency-Key") == "" {
|
||||
req.Header.Set("Idempotency-Key", uuid.NewString())
|
||||
}
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
b, _ := io.ReadAll(resp.Body)
|
||||
return resp.StatusCode, string(b), resp.Header
|
||||
}
|
||||
|
||||
func decode(t *testing.T, body string) map[string]any {
|
||||
t.Helper()
|
||||
var m map[string]any
|
||||
if err := json.Unmarshal([]byte(body), &m); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func basic(user, pass string) string {
|
||||
return base64.StdEncoding.EncodeToString([]byte(user + ":" + pass))
|
||||
}
|
||||
|
||||
func logStep(t *testing.T, msg string) { t.Helper(); t.Logf("→ %s", msg) }
|
||||
func logOK(t *testing.T, msg string) { t.Helper(); t.Logf("✓ %s", msg) }
|
||||
func logResult(t *testing.T, status int, body string) {
|
||||
t.Helper()
|
||||
if len(body) > 400 {
|
||||
body = body[:400] + "..."
|
||||
}
|
||||
t.Logf("status=%d body=%s", status, body)
|
||||
}
|
||||
|
||||
func getenv(k, def string) string {
|
||||
if v := os.Getenv(k); v != "" {
|
||||
return v
|
||||
}
|
||||
return def
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
package studenttests
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab4/internal/api"
|
||||
"mtusi2026lab4/internal/blob"
|
||||
"mtusi2026lab4/internal/session"
|
||||
)
|
||||
|
||||
// 1×1 PNG (valid IHDR + IDAT + IEND, CRC проверены).
|
||||
var tinyPNG = []byte{
|
||||
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
|
||||
0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
|
||||
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01,
|
||||
0x08, 0x02, 0x00, 0x00, 0x00, 0x90, 0x77, 0x53,
|
||||
0xde, 0x00, 0x00, 0x00, 0x0c, 0x49, 0x44, 0x41,
|
||||
0x54, 0x78, 0xda, 0x63, 0xf8, 0xcf, 0xc0, 0x00,
|
||||
0x00, 0x03, 0x01, 0x01, 0x00, 0xf7, 0x03, 0x41,
|
||||
0x43, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e,
|
||||
0x44, 0xae, 0x42, 0x60, 0x82,
|
||||
}
|
||||
|
||||
func TestAttachmentUploadDownloadAndACL(t *testing.T) {
|
||||
mem := blob.NewMemory()
|
||||
srv := newAPIBlob(t, time.Hour, mem)
|
||||
defer srv.Close()
|
||||
logStep(t, "upload PNG → 201 ready → download checksum; посторонний — 404")
|
||||
|
||||
owner := register(t, srv, "att_owner")
|
||||
ownerTok := login(t, srv, owner.username, owner.password)
|
||||
stranger := register(t, srv, "att_stranger")
|
||||
strangerTok := login(t, srv, stranger.username, stranger.password)
|
||||
chat := createChat(t, srv, ownerTok, owner.id, "Вложения")
|
||||
|
||||
attID, sha := uploadPNG(t, srv, ownerTok, chat, "pic.png", tinyPNG)
|
||||
status, body := do(t, srv, http.MethodGet, "/api/v1/attachments/"+attID, map[string]string{
|
||||
"Authorization": "Bearer " + ownerTok,
|
||||
}, "")
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusOK {
|
||||
t.Fatalf("meta: %d %s", status, body)
|
||||
}
|
||||
meta := decode(t, body)
|
||||
if meta["status"] != "ready" || meta["sha256"] != sha {
|
||||
t.Fatalf("meta unexpected: %+v", meta)
|
||||
}
|
||||
|
||||
statusCode, raw, hdr := downloadBytes(t, srv, ownerTok, attID)
|
||||
if statusCode != http.StatusOK {
|
||||
t.Fatalf("download: %d", statusCode)
|
||||
}
|
||||
if hdr.Get("Content-Type") != "image/png" {
|
||||
t.Fatalf("content-type: %q", hdr.Get("Content-Type"))
|
||||
}
|
||||
sum := sha256.Sum256(raw)
|
||||
if hex.EncodeToString(sum[:]) != sha {
|
||||
t.Fatalf("checksum mismatch")
|
||||
}
|
||||
|
||||
status, body = do(t, srv, http.MethodGet, "/api/v1/attachments/"+attID, map[string]string{
|
||||
"Authorization": "Bearer " + strangerTok,
|
||||
}, "")
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusNotFound {
|
||||
t.Fatalf("stranger meta: %d", status)
|
||||
}
|
||||
statusCode, _, _ = downloadBytes(t, srv, strangerTok, attID)
|
||||
if statusCode != http.StatusNotFound {
|
||||
t.Fatalf("stranger download: %d", statusCode)
|
||||
}
|
||||
|
||||
status, body = do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", map[string]string{
|
||||
"Authorization": "Bearer " + ownerTok,
|
||||
}, fmt.Sprintf(`{"text":"с файлом","attachment_ids":[%q]}`, attID))
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusCreated {
|
||||
t.Fatalf("message with att: %d %s", status, body)
|
||||
}
|
||||
msg := decode(t, body)
|
||||
ids, _ := msg["attachment_ids"].([]any)
|
||||
if len(ids) != 1 || ids[0] != attID {
|
||||
t.Fatalf("attachment_ids: %+v", msg["attachment_ids"])
|
||||
}
|
||||
logOK(t, "upload/download/ACL и message.attachment_ids")
|
||||
}
|
||||
|
||||
func TestAttachmentRejectsBadInput(t *testing.T) {
|
||||
mem := blob.NewMemory()
|
||||
srv := newAPIBlob(t, time.Hour, mem)
|
||||
defer srv.Close()
|
||||
logStep(t, "битый PNG, подмена MIME, опасный filename, чужой чат → 4xx не 500")
|
||||
|
||||
user := register(t, srv, "att_bad")
|
||||
tok := login(t, srv, user.username, user.password)
|
||||
chat := createChat(t, srv, tok, user.id, "Отказы")
|
||||
|
||||
status, body := uploadRaw(t, srv, tok, chat, "../x.png", "image/png", tinyPNG)
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusBadRequest {
|
||||
t.Fatalf("bad filename: %d", status)
|
||||
}
|
||||
|
||||
status, body = uploadRaw(t, srv, tok, chat, "x.jpg", "image/jpeg", tinyPNG)
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusUnsupportedMediaType {
|
||||
t.Fatalf("mime mismatch: %d", status)
|
||||
}
|
||||
|
||||
status, body = uploadRaw(t, srv, tok, chat, "bad.png", "image/png", tinyPNG[:20])
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusUnsupportedMediaType {
|
||||
t.Fatalf("truncated: %d", status)
|
||||
}
|
||||
|
||||
// Отдельный сервер с маленьким лимитом: реально шлём 2 KiB, ожидаем 413.
|
||||
small := blob.NewMemory()
|
||||
sessions, err := session.Open(sharedRedisURL, time.Hour)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = sessions.Close() })
|
||||
apiSrv := api.New(sharedStore, sessions, small, "test-small-limit")
|
||||
apiSrv.MaxUploadBytes = 1024
|
||||
limSrv := httptest.NewServer(apiSrv.Handler())
|
||||
defer limSrv.Close()
|
||||
status, body = uploadRaw(t, limSrv, tok, chat, "huge.png", "image/png", make([]byte, 2048))
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusRequestEntityTooLarge {
|
||||
t.Fatalf("too large body: %d", status)
|
||||
}
|
||||
|
||||
other := register(t, srv, "att_other")
|
||||
otherTok := login(t, srv, other.username, other.password)
|
||||
otherChat := createChat(t, srv, otherTok, other.id, "Чужой")
|
||||
status, body = uploadRaw(t, srv, tok, otherChat, "x.png", "image/png", tinyPNG)
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusNotFound {
|
||||
t.Fatalf("foreign chat upload: %d", status)
|
||||
}
|
||||
|
||||
attID, _ := uploadPNG(t, srv, otherTok, otherChat, "o.png", tinyPNG)
|
||||
status, body = do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", map[string]string{
|
||||
"Authorization": "Bearer " + tok,
|
||||
}, fmt.Sprintf(`{"text":"steal","attachment_ids":[%q]}`, attID))
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusNotFound {
|
||||
t.Fatalf("foreign attachment_id: %d %s", status, body)
|
||||
}
|
||||
logOK(t, "негативные сценарии вложений → клиентские 4xx")
|
||||
}
|
||||
|
||||
func TestAttachmentS3DownIs503(t *testing.T) {
|
||||
mem := blob.NewMemory()
|
||||
mem.SetUnavailable(true)
|
||||
srv := newAPIBlob(t, time.Hour, mem)
|
||||
defer srv.Close()
|
||||
logStep(t, "S3 недоступен: ready и upload → 503")
|
||||
|
||||
status, body := do(t, srv, http.MethodGet, "/health/ready", nil, "")
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusServiceUnavailable {
|
||||
t.Fatalf("ready: %d", status)
|
||||
}
|
||||
|
||||
user := register(t, srv, "s3_down")
|
||||
tok := login(t, srv, user.username, user.password)
|
||||
chat := createChat(t, srv, tok, user.id, "S3 down")
|
||||
status, body = uploadRaw(t, srv, tok, chat, "x.png", "image/png", tinyPNG)
|
||||
logResult(t, status, body)
|
||||
if status != http.StatusServiceUnavailable {
|
||||
t.Fatalf("upload with s3 down: %d %s", status, body)
|
||||
}
|
||||
logOK(t, "падение S3 → 503")
|
||||
}
|
||||
|
||||
func uploadPNG(t *testing.T, srv *httptest.Server, token, chatID, filename string, data []byte) (id, sha string) {
|
||||
t.Helper()
|
||||
status, body := uploadRaw(t, srv, token, chatID, filename, "image/png", data)
|
||||
if status != http.StatusCreated {
|
||||
t.Fatalf("upload: %d %s", status, body)
|
||||
}
|
||||
var att struct {
|
||||
ID string `json:"id"`
|
||||
SHA256 string `json:"sha256"`
|
||||
Status string `json:"status"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(body), &att); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if att.Status != "ready" || att.ID == "" {
|
||||
t.Fatalf("upload body: %s", body)
|
||||
}
|
||||
sum := sha256.Sum256(data)
|
||||
want := hex.EncodeToString(sum[:])
|
||||
if att.SHA256 != want {
|
||||
t.Fatalf("sha got=%s want=%s", att.SHA256, want)
|
||||
}
|
||||
return att.ID, att.SHA256
|
||||
}
|
||||
|
||||
func uploadRaw(t *testing.T, srv *httptest.Server, token, chatID, filename, ctype string, data []byte) (int, string) {
|
||||
t.Helper()
|
||||
u := srv.URL + "/api/v1/chats/" + chatID + "/attachments?filename=" + url.QueryEscape(filename)
|
||||
req, err := http.NewRequest(http.MethodPost, u, bytes.NewReader(data))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
req.Header.Set("Content-Type", ctype)
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
b, _ := io.ReadAll(resp.Body)
|
||||
return resp.StatusCode, string(b)
|
||||
}
|
||||
|
||||
func downloadBytes(t *testing.T, srv *httptest.Server, token, attID string) (int, []byte, http.Header) {
|
||||
t.Helper()
|
||||
req, err := http.NewRequest(http.MethodGet, srv.URL+"/api/v1/attachments/"+attID+"/content", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
b, _ := io.ReadAll(resp.Body)
|
||||
return resp.StatusCode, b, resp.Header.Clone()
|
||||
}
|
||||
Reference in New Issue
Block a user