forked from mtusi2026/mtusi2026lab7
на оценку 4
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
package student_tests
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"mtusi2026lab7/internal/application"
|
||||
)
|
||||
|
||||
const testCursorSigningKey = "student-tests-cursor-signing-key-at-least-32-bytes"
|
||||
|
||||
func newTestService(
|
||||
repository application.Repository,
|
||||
sessionTTL time.Duration,
|
||||
options ...application.ServiceOption,
|
||||
) *application.Service {
|
||||
if sessionTTL <= 0 {
|
||||
sessionTTL = time.Hour
|
||||
}
|
||||
codec, err := application.NewCursorCodec(testCursorSigningKey)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
service, err := application.NewService(repository, codec, sessionTTL, options...)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return service
|
||||
}
|
||||
|
||||
func newTestCursorCodec() *application.CursorCodec {
|
||||
codec, err := application.NewCursorCodec(testCursorSigningKey)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return codec
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
package student_tests
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/png"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
store "mtusi2026lab7/internal/adapter/memory"
|
||||
"mtusi2026lab7/internal/application"
|
||||
"mtusi2026lab7/internal/domain"
|
||||
"mtusi2026lab7/internal/transport/http/dto"
|
||||
"mtusi2026lab7/internal/transport/http/handlers"
|
||||
"mtusi2026lab7/internal/transport/http/middleware"
|
||||
)
|
||||
|
||||
type httpFakeObjectStore struct {
|
||||
mu sync.Mutex
|
||||
objects map[string][]byte
|
||||
}
|
||||
|
||||
func (store *httpFakeObjectStore) Put(_ context.Context, object application.ObjectPut) error {
|
||||
payload, err := io.ReadAll(object.Body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
store.mu.Lock()
|
||||
store.objects[object.Key] = payload
|
||||
store.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (store *httpFakeObjectStore) Get(_ context.Context, key string) (application.ObjectContent, error) {
|
||||
store.mu.Lock()
|
||||
defer store.mu.Unlock()
|
||||
payload, exists := store.objects[key]
|
||||
if !exists {
|
||||
return application.ObjectContent{}, domain.ErrNotFound
|
||||
}
|
||||
copyOfPayload := append([]byte(nil), payload...)
|
||||
return application.ObjectContent{
|
||||
Body: io.NopCloser(bytes.NewReader(copyOfPayload)),
|
||||
SizeBytes: int64(len(copyOfPayload)),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (store *httpFakeObjectStore) Delete(_ context.Context, key string) error {
|
||||
store.mu.Lock()
|
||||
delete(store.objects, key)
|
||||
store.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
func setupAttachmentUploadServer(
|
||||
t *testing.T,
|
||||
) (*httptest.Server, *store.MemoryStore, *httpFakeObjectStore) {
|
||||
t.Helper()
|
||||
memoryStore := store.NewMemoryStore()
|
||||
repository := store.NewMemoryRepository(memoryStore)
|
||||
objectStore := &httpFakeObjectStore{objects: make(map[string][]byte)}
|
||||
service := newTestService(
|
||||
repository,
|
||||
time.Hour,
|
||||
application.WithObjectStore(objectStore),
|
||||
)
|
||||
handler := handlers.NewHandler(service)
|
||||
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc(
|
||||
"POST /api/v1/chats/{chat_id}/attachments",
|
||||
requireLegacyAuth(memoryStore, handler.UploadAttachment),
|
||||
)
|
||||
mux.HandleFunc(
|
||||
"GET /api/v1/attachments/{attachment_id}",
|
||||
requireLegacyAuth(memoryStore, handler.GetAttachment),
|
||||
)
|
||||
mux.HandleFunc(
|
||||
"GET /api/v1/attachments/{attachment_id}/content",
|
||||
requireLegacyAuth(memoryStore, handler.DownloadAttachment),
|
||||
)
|
||||
var root http.Handler = mux
|
||||
root = middleware.Recovery(root)
|
||||
root = middleware.RequestID(root)
|
||||
return httptest.NewServer(root), memoryStore, objectStore
|
||||
}
|
||||
|
||||
func pngPayload(t *testing.T) []byte {
|
||||
t.Helper()
|
||||
var payload bytes.Buffer
|
||||
img := image.NewRGBA(image.Rect(0, 0, 2, 2))
|
||||
img.Set(0, 0, color.RGBA{R: 255, A: 255})
|
||||
if err := png.Encode(&payload, img); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return payload.Bytes()
|
||||
}
|
||||
|
||||
func uploadRequest(
|
||||
t *testing.T,
|
||||
baseURL string,
|
||||
chatID string,
|
||||
userID string,
|
||||
filename string,
|
||||
contentType string,
|
||||
payload []byte,
|
||||
) *http.Response {
|
||||
t.Helper()
|
||||
requestURL := baseURL + "/api/v1/chats/" + chatID +
|
||||
"/attachments?filename=" + url.QueryEscape(filename)
|
||||
request, err := http.NewRequest(http.MethodPost, requestURL, bytes.NewReader(payload))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
request.Header.Set("Content-Type", contentType)
|
||||
request.Header.Set("X-User-Id", userID)
|
||||
response, err := http.DefaultClient.Do(request)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
func attachmentGetRequest(t *testing.T, requestURL string, userID string) *http.Response {
|
||||
t.Helper()
|
||||
request, err := http.NewRequest(http.MethodGet, requestURL, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
request.Header.Set("X-User-Id", userID)
|
||||
response, err := http.DefaultClient.Do(request)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
func TestUploadAttachmentHTTPContract(t *testing.T) {
|
||||
server, memoryStore, objectStore := setupAttachmentUploadServer(t)
|
||||
defer server.Close()
|
||||
user, err := memoryStore.CreateUser("attachment_user", "Attachment User")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
outsider, err := memoryStore.CreateUser("attachment_outsider", "Attachment Outsider")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
chat, err := memoryStore.CreateChat("Images", []string{user.ID})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
payload := pngPayload(t)
|
||||
response := uploadRequest(t, server.URL, chat.ID, user.ID, "кот.png", "image/png", payload)
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode != http.StatusAccepted {
|
||||
body, _ := io.ReadAll(response.Body)
|
||||
t.Fatalf("status = %d, want 202: %s", response.StatusCode, body)
|
||||
}
|
||||
var attachment dto.AttachmentResponse
|
||||
if err = json.NewDecoder(response.Body).Decode(&attachment); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if attachment.Status != domain.AttachmentStatusQueued || attachment.Filename != "кот.png" {
|
||||
t.Fatalf("unexpected response: %+v", attachment)
|
||||
}
|
||||
if attachment.Variants == nil || len(attachment.Variants) != 0 || attachment.ErrorCode != nil {
|
||||
t.Fatalf("contract arrays/nulls differ: %+v", attachment)
|
||||
}
|
||||
objectStore.mu.Lock()
|
||||
storedObjects := len(objectStore.objects)
|
||||
objectStore.mu.Unlock()
|
||||
if storedObjects != 1 {
|
||||
t.Fatalf("stored objects = %d, want 1", storedObjects)
|
||||
}
|
||||
|
||||
metadataResponse := attachmentGetRequest(t, server.URL+"/api/v1/attachments/"+attachment.ID, user.ID)
|
||||
defer metadataResponse.Body.Close()
|
||||
if metadataResponse.StatusCode != http.StatusOK {
|
||||
t.Fatalf("metadata status = %d, want 200", metadataResponse.StatusCode)
|
||||
}
|
||||
|
||||
contentResponse := attachmentGetRequest(t,
|
||||
server.URL+"/api/v1/attachments/"+attachment.ID+"/content", user.ID)
|
||||
defer contentResponse.Body.Close()
|
||||
if contentResponse.StatusCode != http.StatusConflict {
|
||||
t.Fatalf("queued content status=%d, want 409", contentResponse.StatusCode)
|
||||
}
|
||||
|
||||
for _, suffix := range []string{"", "/content"} {
|
||||
outsiderResponse := attachmentGetRequest(t,
|
||||
server.URL+"/api/v1/attachments/"+attachment.ID+suffix, outsider.ID)
|
||||
_ = outsiderResponse.Body.Close()
|
||||
if outsiderResponse.StatusCode != http.StatusNotFound {
|
||||
t.Fatalf("outsider %q status = %d, want 404", suffix, outsiderResponse.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
missingVariant := attachmentGetRequest(t,
|
||||
server.URL+"/api/v1/attachments/"+attachment.ID+"/content?variant=thumbnail", user.ID)
|
||||
_ = missingVariant.Body.Close()
|
||||
if missingVariant.StatusCode != http.StatusConflict {
|
||||
t.Fatalf("queued variant status = %d, want 409", missingVariant.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUploadAttachmentHTTPErrorMapping(t *testing.T) {
|
||||
server, memoryStore, _ := setupAttachmentUploadServer(t)
|
||||
defer server.Close()
|
||||
user, _ := memoryStore.CreateUser("attachment_errors", "Attachment Errors")
|
||||
chat, _ := memoryStore.CreateChat("Images", []string{user.ID})
|
||||
validPNG := pngPayload(t)
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
chatID string
|
||||
filename string
|
||||
contentType string
|
||||
payload []byte
|
||||
wantStatus int
|
||||
}{
|
||||
{name: "unsafe filename", chatID: chat.ID, filename: "../image.png", contentType: "image/png", payload: validPNG, wantStatus: http.StatusBadRequest},
|
||||
{name: "unsupported content type", chatID: chat.ID, filename: "image.gif", contentType: "image/gif", payload: []byte("GIF89a"), wantStatus: http.StatusUnsupportedMediaType},
|
||||
{name: "MIME substitution", chatID: chat.ID, filename: "image.jpg", contentType: "image/jpeg", payload: validPNG, wantStatus: http.StatusUnsupportedMediaType},
|
||||
{name: "corrupt image", chatID: chat.ID, filename: "image.png", contentType: "image/png", payload: []byte("bad"), wantStatus: http.StatusUnsupportedMediaType},
|
||||
{name: "too large", chatID: chat.ID, filename: "image.png", contentType: "image/png", payload: bytes.Repeat([]byte{0}, domain.MaxAttachmentSizeBytes+1), wantStatus: http.StatusRequestEntityTooLarge},
|
||||
{name: "unknown chat", chatID: "11111111-1111-4111-8111-111111111111", filename: "image.png", contentType: "image/png", payload: validPNG, wantStatus: http.StatusNotFound},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
response := uploadRequest(t, server.URL, testCase.chatID, user.ID,
|
||||
testCase.filename, testCase.contentType, testCase.payload)
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode != testCase.wantStatus {
|
||||
body, _ := io.ReadAll(response.Body)
|
||||
t.Fatalf("status = %d, want %d: %s", response.StatusCode, testCase.wantStatus, body)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,379 @@
|
||||
package student_tests
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
store "mtusi2026lab7/internal/adapter/memory"
|
||||
"mtusi2026lab7/internal/security"
|
||||
"mtusi2026lab7/internal/transport/http/dto"
|
||||
"mtusi2026lab7/internal/transport/http/handlers"
|
||||
"mtusi2026lab7/internal/transport/http/middleware"
|
||||
)
|
||||
|
||||
const testPassword = "Test-password-123"
|
||||
|
||||
func setupSessionTestServer(
|
||||
t *testing.T,
|
||||
sessionTTL time.Duration,
|
||||
) (*httptest.Server, *store.MemoryRepository) {
|
||||
t.Helper()
|
||||
|
||||
repository := store.NewMemoryRepository(store.NewMemoryStore())
|
||||
service := newTestService(repository, sessionTTL)
|
||||
handler := handlers.NewHandler(service)
|
||||
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("POST /api/v1/users", handler.CreateUser)
|
||||
mux.HandleFunc("POST /api/v1/auth/sessions", handler.CreateSession)
|
||||
mux.HandleFunc(
|
||||
"GET /api/v1/users/me",
|
||||
middleware.RequireAuth(service, handler.GetMe),
|
||||
)
|
||||
mux.HandleFunc(
|
||||
"DELETE /api/v1/auth/sessions/current",
|
||||
middleware.RequireAuth(service, handler.DeleteCurrentSession),
|
||||
)
|
||||
|
||||
var root http.Handler = mux
|
||||
root = middleware.Recovery(root)
|
||||
root = middleware.RequestID(root)
|
||||
|
||||
return httptest.NewServer(root), repository
|
||||
}
|
||||
|
||||
func registerSessionTestUser(
|
||||
t *testing.T,
|
||||
baseURL string,
|
||||
username string,
|
||||
) dto.UserResponse {
|
||||
t.Helper()
|
||||
|
||||
payload, err := json.Marshal(map[string]string{
|
||||
"username": username,
|
||||
"display_name": "Session test user",
|
||||
"password": testPassword,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("marshal registration request: %v", err)
|
||||
}
|
||||
|
||||
response, err := http.Post(
|
||||
baseURL+"/api/v1/users",
|
||||
"application/json",
|
||||
bytes.NewReader(payload),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("register user: %v", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
if response.StatusCode != http.StatusCreated {
|
||||
body, _ := io.ReadAll(response.Body)
|
||||
t.Fatalf("expected registration status 201, got %d: %s", response.StatusCode, body)
|
||||
}
|
||||
|
||||
var user dto.UserResponse
|
||||
if err := json.NewDecoder(response.Body).Decode(&user); err != nil {
|
||||
t.Fatalf("decode registered user: %v", err)
|
||||
}
|
||||
|
||||
return user
|
||||
}
|
||||
|
||||
func createSessionRequest(
|
||||
t *testing.T,
|
||||
baseURL string,
|
||||
username string,
|
||||
password string,
|
||||
) *http.Response {
|
||||
t.Helper()
|
||||
|
||||
credentials := base64.StdEncoding.EncodeToString(
|
||||
[]byte(username + ":" + password),
|
||||
)
|
||||
|
||||
request, err := http.NewRequest(
|
||||
http.MethodPost,
|
||||
baseURL+"/api/v1/auth/sessions",
|
||||
nil,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("create login request: %v", err)
|
||||
}
|
||||
request.Header.Set("Authorization", "Basic "+credentials)
|
||||
|
||||
response, err := http.DefaultClient.Do(request)
|
||||
if err != nil {
|
||||
t.Fatalf("send login request: %v", err)
|
||||
}
|
||||
|
||||
return response
|
||||
}
|
||||
|
||||
func TestSessionAuthenticationLifecycle(t *testing.T) {
|
||||
testServer, repository := setupSessionTestServer(t, time.Hour)
|
||||
defer testServer.Close()
|
||||
|
||||
alice := registerSessionTestUser(t, testServer.URL, "session_alice")
|
||||
eve := registerSessionTestUser(t, testServer.URL, "session_eve")
|
||||
|
||||
_, passwordHash, err := repository.GetUserByUsername(
|
||||
t.Context(),
|
||||
alice.Username,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("read registered user credentials: %v", err)
|
||||
}
|
||||
if passwordHash == testPassword || bytes.Contains(
|
||||
[]byte(passwordHash),
|
||||
[]byte(testPassword),
|
||||
) {
|
||||
t.Fatal("repository contains plaintext password")
|
||||
}
|
||||
passwordMatches, err := security.VerifyPassword(testPassword, passwordHash)
|
||||
if err != nil || !passwordMatches {
|
||||
t.Fatalf("stored password hash does not verify: matches=%v err=%v", passwordMatches, err)
|
||||
}
|
||||
|
||||
wrongPasswordResponse := createSessionRequest(
|
||||
t,
|
||||
testServer.URL,
|
||||
alice.Username,
|
||||
"Wrong-password-123",
|
||||
)
|
||||
wrongPasswordBody, err := io.ReadAll(wrongPasswordResponse.Body)
|
||||
wrongPasswordResponse.Body.Close()
|
||||
if err != nil {
|
||||
t.Fatalf("read wrong-password response: %v", err)
|
||||
}
|
||||
if wrongPasswordResponse.StatusCode != http.StatusUnauthorized {
|
||||
t.Fatalf("expected 401 for wrong password, got %d", wrongPasswordResponse.StatusCode)
|
||||
}
|
||||
if got := wrongPasswordResponse.Header.Get("WWW-Authenticate"); got != `Basic realm="messenger", charset="UTF-8"` {
|
||||
t.Fatalf("unexpected Basic challenge: %q", got)
|
||||
}
|
||||
|
||||
unknownUserResponse := createSessionRequest(
|
||||
t,
|
||||
testServer.URL,
|
||||
"unknown_session_user",
|
||||
"Wrong-password-123",
|
||||
)
|
||||
unknownUserBody, err := io.ReadAll(unknownUserResponse.Body)
|
||||
unknownUserResponse.Body.Close()
|
||||
if err != nil {
|
||||
t.Fatalf("read unknown-user response: %v", err)
|
||||
}
|
||||
if unknownUserResponse.StatusCode != http.StatusUnauthorized {
|
||||
t.Fatalf("expected 401 for unknown username, got %d", unknownUserResponse.StatusCode)
|
||||
}
|
||||
if got := unknownUserResponse.Header.Get("WWW-Authenticate"); got != `Basic realm="messenger", charset="UTF-8"` {
|
||||
t.Fatalf("unexpected Basic challenge for unknown username: %q", got)
|
||||
}
|
||||
type credentialFailure struct {
|
||||
Error struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
} `json:"error"`
|
||||
}
|
||||
var wrongFailure, unknownFailure credentialFailure
|
||||
if err = json.Unmarshal(wrongPasswordBody, &wrongFailure); err != nil {
|
||||
t.Fatalf("decode wrong-password response: %v", err)
|
||||
}
|
||||
if err = json.Unmarshal(unknownUserBody, &unknownFailure); err != nil {
|
||||
t.Fatalf("decode unknown-user response: %v", err)
|
||||
}
|
||||
if wrongFailure != unknownFailure || len(wrongPasswordBody) != len(unknownUserBody) {
|
||||
t.Fatalf("credential failure responses disclose whether a username exists: wrong=%q unknown=%q", wrongPasswordBody, unknownUserBody)
|
||||
}
|
||||
|
||||
loginResponse := createSessionRequest(
|
||||
t,
|
||||
testServer.URL,
|
||||
alice.Username,
|
||||
testPassword,
|
||||
)
|
||||
defer loginResponse.Body.Close()
|
||||
if loginResponse.StatusCode != http.StatusCreated {
|
||||
body, _ := io.ReadAll(loginResponse.Body)
|
||||
t.Fatalf("expected login status 201, got %d: %s", loginResponse.StatusCode, body)
|
||||
}
|
||||
|
||||
var session dto.SessionResponse
|
||||
if err := json.NewDecoder(loginResponse.Body).Decode(&session); err != nil {
|
||||
t.Fatalf("decode session: %v", err)
|
||||
}
|
||||
if session.Token == "" || session.TokenType != "Bearer" {
|
||||
t.Fatalf("unexpected session token response: type=%q empty=%v", session.TokenType, session.Token == "")
|
||||
}
|
||||
if session.User != alice {
|
||||
t.Fatalf("session belongs to another user: got %s, want %s", session.User.ID, alice.ID)
|
||||
}
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
authorization string
|
||||
userIDHeader string
|
||||
wantStatus int
|
||||
}{
|
||||
{
|
||||
name: "X-User-Id alone is rejected",
|
||||
userIDHeader: alice.ID,
|
||||
wantStatus: http.StatusUnauthorized,
|
||||
},
|
||||
{
|
||||
name: "Basic is rejected on business endpoint",
|
||||
authorization: "Basic " + base64.StdEncoding.EncodeToString([]byte(alice.Username+":"+testPassword)),
|
||||
wantStatus: http.StatusUnauthorized,
|
||||
},
|
||||
{
|
||||
name: "non-ASCII Bearer is rejected without panic",
|
||||
authorization: "Bearer é",
|
||||
wantStatus: http.StatusUnauthorized,
|
||||
},
|
||||
{
|
||||
name: "Bearer identity wins over X-User-Id",
|
||||
authorization: "Bearer " + session.Token,
|
||||
userIDHeader: eve.ID,
|
||||
wantStatus: http.StatusOK,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
request, err := http.NewRequest(
|
||||
http.MethodGet,
|
||||
testServer.URL+"/api/v1/users/me",
|
||||
nil,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("create authenticated request: %v", err)
|
||||
}
|
||||
if testCase.authorization != "" {
|
||||
request.Header.Set("Authorization", testCase.authorization)
|
||||
}
|
||||
if testCase.userIDHeader != "" {
|
||||
request.Header.Set("X-User-Id", testCase.userIDHeader)
|
||||
}
|
||||
|
||||
response, err := http.DefaultClient.Do(request)
|
||||
if err != nil {
|
||||
t.Fatalf("send authenticated request: %v", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
if response.StatusCode != testCase.wantStatus {
|
||||
t.Fatalf("expected status %d, got %d", testCase.wantStatus, response.StatusCode)
|
||||
}
|
||||
|
||||
if testCase.wantStatus == http.StatusUnauthorized {
|
||||
if got := response.Header.Get("WWW-Authenticate"); got != `Bearer realm="messenger"` {
|
||||
t.Fatalf("unexpected Bearer challenge: %q", got)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
var currentUser dto.UserResponse
|
||||
if err := json.NewDecoder(response.Body).Decode(¤tUser); err != nil {
|
||||
t.Fatalf("decode current user: %v", err)
|
||||
}
|
||||
if currentUser.ID != alice.ID {
|
||||
t.Fatalf("X-User-Id overrode Bearer identity: got %s, want %s", currentUser.ID, alice.ID)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
logoutRequest, err := http.NewRequest(
|
||||
http.MethodDelete,
|
||||
testServer.URL+"/api/v1/auth/sessions/current",
|
||||
nil,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("create logout request: %v", err)
|
||||
}
|
||||
logoutRequest.Header.Set("Authorization", "Bearer "+session.Token)
|
||||
|
||||
logoutResponse, err := http.DefaultClient.Do(logoutRequest)
|
||||
if err != nil {
|
||||
t.Fatalf("send logout request: %v", err)
|
||||
}
|
||||
logoutBody, err := io.ReadAll(logoutResponse.Body)
|
||||
logoutResponse.Body.Close()
|
||||
if err != nil {
|
||||
t.Fatalf("read logout response: %v", err)
|
||||
}
|
||||
if logoutResponse.StatusCode != http.StatusNoContent {
|
||||
t.Fatalf("expected logout status 204, got %d", logoutResponse.StatusCode)
|
||||
}
|
||||
if len(logoutBody) != 0 {
|
||||
t.Fatalf("logout response contains a body: %q", logoutBody)
|
||||
}
|
||||
|
||||
revokedRequest, err := http.NewRequest(
|
||||
http.MethodGet,
|
||||
testServer.URL+"/api/v1/users/me",
|
||||
nil,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("create revoked-token request: %v", err)
|
||||
}
|
||||
revokedRequest.Header.Set("Authorization", "Bearer "+session.Token)
|
||||
|
||||
revokedResponse, err := http.DefaultClient.Do(revokedRequest)
|
||||
if err != nil {
|
||||
t.Fatalf("send revoked-token request: %v", err)
|
||||
}
|
||||
revokedResponse.Body.Close()
|
||||
if revokedResponse.StatusCode != http.StatusUnauthorized {
|
||||
t.Fatalf("expected 401 for revoked token, got %d", revokedResponse.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionExpiry(t *testing.T) {
|
||||
testServer, _ := setupSessionTestServer(t, 25*time.Millisecond)
|
||||
defer testServer.Close()
|
||||
|
||||
user := registerSessionTestUser(t, testServer.URL, "session_expiry")
|
||||
loginResponse := createSessionRequest(
|
||||
t,
|
||||
testServer.URL,
|
||||
user.Username,
|
||||
testPassword,
|
||||
)
|
||||
|
||||
var session dto.SessionResponse
|
||||
if err := json.NewDecoder(loginResponse.Body).Decode(&session); err != nil {
|
||||
loginResponse.Body.Close()
|
||||
t.Fatalf("decode session: %v", err)
|
||||
}
|
||||
loginResponse.Body.Close()
|
||||
|
||||
time.Sleep(75 * time.Millisecond)
|
||||
|
||||
request, err := http.NewRequest(
|
||||
http.MethodGet,
|
||||
testServer.URL+"/api/v1/users/me",
|
||||
nil,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("create expired-token request: %v", err)
|
||||
}
|
||||
request.Header.Set("Authorization", "Bearer "+session.Token)
|
||||
|
||||
response, err := http.DefaultClient.Do(request)
|
||||
if err != nil {
|
||||
t.Fatalf("send expired-token request: %v", err)
|
||||
}
|
||||
response.Body.Close()
|
||||
|
||||
if response.StatusCode != http.StatusUnauthorized {
|
||||
t.Fatalf("expected 401 for expired token, got %d", response.StatusCode)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,406 @@
|
||||
package student_tests
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"runtime"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab7/internal/domain"
|
||||
"mtusi2026lab7/internal/transport/http/dto"
|
||||
)
|
||||
|
||||
func fetchCursorPage(
|
||||
t *testing.T,
|
||||
baseURL, chatID, userID string,
|
||||
limit int,
|
||||
cursor string,
|
||||
) dto.MessagePageResponse {
|
||||
t.Helper()
|
||||
|
||||
endpoint := fmt.Sprintf(
|
||||
"%s/api/v1/chats/%s/messages?limit=%d",
|
||||
baseURL,
|
||||
chatID,
|
||||
limit,
|
||||
)
|
||||
if cursor != "" {
|
||||
endpoint += "&cursor=" + url.QueryEscape(cursor)
|
||||
}
|
||||
|
||||
req, err := http.NewRequest(http.MethodGet, endpoint, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req.Header.Set("X-User-Id", userID)
|
||||
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer res.Body.Close()
|
||||
|
||||
if res.StatusCode != http.StatusOK {
|
||||
body, _ := io.ReadAll(res.Body)
|
||||
t.Fatalf("expected 200, got %d: %s", res.StatusCode, body)
|
||||
}
|
||||
|
||||
var page dto.MessagePageResponse
|
||||
if err := json.NewDecoder(res.Body).Decode(&page); err != nil {
|
||||
t.Fatalf("decode message page: %v", err)
|
||||
}
|
||||
return page
|
||||
}
|
||||
|
||||
func TestCursorTraversalAfterConcurrentWrites(t *testing.T) {
|
||||
ts, st := setupTestServer()
|
||||
defer ts.Close()
|
||||
|
||||
const (
|
||||
clients = 10
|
||||
messagesPerClient = 100
|
||||
expectedMessages = clients * messagesPerClient
|
||||
)
|
||||
|
||||
memberIDs := make([]string, 0, clients)
|
||||
for client := 0; client < clients; client++ {
|
||||
user, err := st.CreateUser(
|
||||
fmt.Sprintf("cursor_client_%d", client),
|
||||
fmt.Sprintf("Cursor client %d", client),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
memberIDs = append(memberIDs, user.ID)
|
||||
}
|
||||
|
||||
chat, err := st.CreateChat("Concurrent cursor test", memberIDs)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
start := make(chan struct{})
|
||||
var writers sync.WaitGroup
|
||||
for client := 0; client < clients; client++ {
|
||||
writers.Add(1)
|
||||
go func(client int) {
|
||||
defer writers.Done()
|
||||
<-start
|
||||
for message := 0; message < messagesPerClient; message++ {
|
||||
_, err := st.CreateMessage(
|
||||
chat.ID,
|
||||
memberIDs[client],
|
||||
fmt.Sprintf("client=%d message=%d", client, message),
|
||||
)
|
||||
if err != nil {
|
||||
t.Errorf("create message: %v", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}(client)
|
||||
}
|
||||
|
||||
close(start)
|
||||
writers.Wait()
|
||||
|
||||
seen := make(map[string]struct{}, expectedMessages)
|
||||
duplicateCount := 0
|
||||
var previous *dto.MessageResponse
|
||||
firstOrderingViolation := ""
|
||||
cursor := ""
|
||||
pageCount := 0
|
||||
|
||||
for {
|
||||
pageCount++
|
||||
if pageCount > expectedMessages {
|
||||
t.Fatal("pagination did not terminate")
|
||||
}
|
||||
|
||||
page := fetchCursorPage(t, ts.URL, chat.ID, memberIDs[0], 17, cursor)
|
||||
for index := range page.Items {
|
||||
message := page.Items[index]
|
||||
if _, duplicate := seen[message.ID]; duplicate {
|
||||
duplicateCount++
|
||||
}
|
||||
seen[message.ID] = struct{}{}
|
||||
|
||||
if previous != nil {
|
||||
outOfOrder := message.CreatedAt.Before(previous.CreatedAt) ||
|
||||
(message.CreatedAt.Equal(previous.CreatedAt) && message.ID <= previous.ID)
|
||||
if outOfOrder && firstOrderingViolation == "" {
|
||||
firstOrderingViolation = fmt.Sprintf(
|
||||
"previous=(%s,%s), current=(%s,%s)",
|
||||
previous.CreatedAt.Format("15:04:05.999999999"), previous.ID,
|
||||
message.CreatedAt.Format("15:04:05.999999999"), message.ID,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
messageCopy := message
|
||||
previous = &messageCopy
|
||||
}
|
||||
|
||||
if page.NextCursor == nil {
|
||||
break
|
||||
}
|
||||
cursor = *page.NextCursor
|
||||
}
|
||||
|
||||
if len(seen) != expectedMessages || duplicateCount != 0 {
|
||||
t.Fatalf(
|
||||
"cursor traversal returned %d unique messages of %d and %d duplicates; first ordering violation: %s",
|
||||
len(seen), expectedMessages, duplicateCount, firstOrderingViolation,
|
||||
)
|
||||
}
|
||||
if firstOrderingViolation != "" {
|
||||
t.Fatalf("history is not ordered: %s", firstOrderingViolation)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCursorTraversalDuringConcurrentWrites(t *testing.T) {
|
||||
ts, st := setupTestServer()
|
||||
defer ts.Close()
|
||||
|
||||
const (
|
||||
clients = 16
|
||||
messagesPerClient = 100
|
||||
seedMessages = 100
|
||||
pageLimit = 7
|
||||
expectedTotal = seedMessages + clients*messagesPerClient
|
||||
)
|
||||
|
||||
memberIDs := make([]string, 0, clients)
|
||||
for client := 0; client < clients; client++ {
|
||||
user, err := st.CreateUser(
|
||||
fmt.Sprintf("live_cursor_client_%d", client),
|
||||
fmt.Sprintf("Live cursor client %d", client),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("create user %d: %v", client, err)
|
||||
}
|
||||
memberIDs = append(memberIDs, user.ID)
|
||||
}
|
||||
|
||||
chat, err := st.CreateChat("Live concurrent cursor test", memberIDs)
|
||||
if err != nil {
|
||||
t.Fatalf("create chat: %v", err)
|
||||
}
|
||||
|
||||
// Начальные сообщения нужны, чтобы читатель сразу начал
|
||||
// двигать курсор, пока остальные сообщения ещё записываются.
|
||||
expectedIDs := make(map[string]struct{}, expectedTotal)
|
||||
for index := 0; index < seedMessages; index++ {
|
||||
message, err := st.CreateMessage(
|
||||
chat.ID,
|
||||
memberIDs[0],
|
||||
fmt.Sprintf("seed message=%d", index),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("create seed message %d: %v", index, err)
|
||||
}
|
||||
expectedIDs[message.ID] = struct{}{}
|
||||
}
|
||||
|
||||
var expectedMu sync.Mutex
|
||||
var writers sync.WaitGroup
|
||||
var ready sync.WaitGroup
|
||||
|
||||
start := make(chan struct{})
|
||||
writerErrors := make(chan error, clients)
|
||||
|
||||
for client := 0; client < clients; client++ {
|
||||
writers.Add(1)
|
||||
ready.Add(1)
|
||||
|
||||
go func(client int) {
|
||||
defer writers.Done()
|
||||
|
||||
ready.Done()
|
||||
<-start
|
||||
|
||||
for index := 0; index < messagesPerClient; index++ {
|
||||
// Отдаём планировщику возможность чаще переключать
|
||||
// конкурентные горутины.
|
||||
runtime.Gosched()
|
||||
|
||||
message, err := st.CreateMessage(
|
||||
chat.ID,
|
||||
memberIDs[client],
|
||||
fmt.Sprintf("client=%d message=%d", client, index),
|
||||
)
|
||||
if err != nil {
|
||||
writerErrors <- fmt.Errorf(
|
||||
"client %d, message %d: %w",
|
||||
client,
|
||||
index,
|
||||
err,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
expectedMu.Lock()
|
||||
expectedIDs[message.ID] = struct{}{}
|
||||
expectedMu.Unlock()
|
||||
|
||||
// Не даём всем писателям завершиться до того,
|
||||
// как читатель успеет продвинуть курсор.
|
||||
time.Sleep(50 * time.Microsecond)
|
||||
}
|
||||
}(client)
|
||||
}
|
||||
|
||||
// Сначала убеждаемся, что все горутины готовы,
|
||||
// и только потом одновременно разрешаем запись.
|
||||
ready.Wait()
|
||||
|
||||
writersDone := make(chan struct{})
|
||||
go func() {
|
||||
writers.Wait()
|
||||
close(writersDone)
|
||||
}()
|
||||
|
||||
close(start)
|
||||
|
||||
seen := make(map[string]struct{}, expectedTotal)
|
||||
cursor := ""
|
||||
var previous *dto.MessageResponse
|
||||
|
||||
const maxPageRequests = expectedTotal * 4
|
||||
finished := false
|
||||
|
||||
for requestNumber := 0; requestNumber < maxPageRequests; requestNumber++ {
|
||||
page := fetchCursorPage(
|
||||
t,
|
||||
ts.URL,
|
||||
chat.ID,
|
||||
memberIDs[0],
|
||||
pageLimit,
|
||||
cursor,
|
||||
)
|
||||
|
||||
for index := range page.Items {
|
||||
message := page.Items[index]
|
||||
|
||||
if _, duplicate := seen[message.ID]; duplicate {
|
||||
t.Fatalf(
|
||||
"message %s was returned more than once",
|
||||
message.ID,
|
||||
)
|
||||
}
|
||||
|
||||
if previous != nil {
|
||||
outOfOrder :=
|
||||
message.CreatedAt.Before(previous.CreatedAt) ||
|
||||
(message.CreatedAt.Equal(previous.CreatedAt) &&
|
||||
message.ID <= previous.ID)
|
||||
|
||||
if outOfOrder {
|
||||
t.Fatalf(
|
||||
"messages are out of order: previous=(%s,%s), current=(%s,%s)",
|
||||
previous.CreatedAt.Format(time.RFC3339Nano),
|
||||
previous.ID,
|
||||
message.CreatedAt.Format(time.RFC3339Nano),
|
||||
message.ID,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
seen[message.ID] = struct{}{}
|
||||
messageCopy := message
|
||||
previous = &messageCopy
|
||||
}
|
||||
|
||||
// Для продолжающегося чтения строим курсор по последнему
|
||||
// фактически полученному сообщению. Это позволяет опрашивать
|
||||
// историю, даже если в промежуточный момент сервер вернул
|
||||
// NextCursor=nil.
|
||||
if len(page.Items) > 0 {
|
||||
last := page.Items[len(page.Items)-1]
|
||||
var encodeErr error
|
||||
cursor, encodeErr = newTestCursorCodec().EncodeMessage(domain.MessageCursor{
|
||||
CreatedAt: last.CreatedAt,
|
||||
MessageID: last.ID,
|
||||
ChatID: chat.ID,
|
||||
})
|
||||
if encodeErr != nil {
|
||||
t.Fatalf("encode traversal cursor: %v", encodeErr)
|
||||
}
|
||||
}
|
||||
|
||||
select {
|
||||
case <-writersDone:
|
||||
finished = true
|
||||
default:
|
||||
}
|
||||
|
||||
// Все писатели завершились, а после текущего курсора
|
||||
// больше ничего нет: обход закончен.
|
||||
if finished && len(page.Items) == 0 {
|
||||
break
|
||||
}
|
||||
|
||||
if len(page.Items) == 0 {
|
||||
runtime.Gosched()
|
||||
}
|
||||
|
||||
if requestNumber == maxPageRequests-1 {
|
||||
t.Fatalf(
|
||||
"pagination did not terminate after %d requests",
|
||||
maxPageRequests,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
<-writersDone
|
||||
close(writerErrors)
|
||||
|
||||
for writerErr := range writerErrors {
|
||||
t.Errorf("create message: %v", writerErr)
|
||||
}
|
||||
|
||||
expectedMu.Lock()
|
||||
missingIDs := make([]string, 0)
|
||||
for id := range expectedIDs {
|
||||
if _, found := seen[id]; !found {
|
||||
missingIDs = append(missingIDs, id)
|
||||
}
|
||||
}
|
||||
expectedCount := len(expectedIDs)
|
||||
expectedMu.Unlock()
|
||||
|
||||
if expectedCount != expectedTotal {
|
||||
t.Fatalf(
|
||||
"writers confirmed %d messages, expected %d",
|
||||
expectedCount,
|
||||
expectedTotal,
|
||||
)
|
||||
}
|
||||
|
||||
if len(missingIDs) != 0 {
|
||||
const displayedMissingIDs = 5
|
||||
if len(missingIDs) > displayedMissingIDs {
|
||||
missingIDs = missingIDs[:displayedMissingIDs]
|
||||
}
|
||||
|
||||
t.Fatalf(
|
||||
"cursor traversal returned %d of %d confirmed messages; "+
|
||||
"examples of missing IDs: %v",
|
||||
len(seen),
|
||||
expectedTotal,
|
||||
missingIDs,
|
||||
)
|
||||
}
|
||||
|
||||
if len(seen) != expectedTotal {
|
||||
t.Fatalf(
|
||||
"cursor traversal returned %d messages, expected %d",
|
||||
len(seen),
|
||||
expectedTotal,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,313 @@
|
||||
package student_tests
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
store "mtusi2026lab7/internal/adapter/memory"
|
||||
"mtusi2026lab7/internal/domain"
|
||||
"mtusi2026lab7/internal/transport/http/dto"
|
||||
)
|
||||
|
||||
func sendMessageRequest(
|
||||
t *testing.T,
|
||||
serverURL string,
|
||||
chatID string,
|
||||
actorID string,
|
||||
key string,
|
||||
body string,
|
||||
) (int, []byte) {
|
||||
t.Helper()
|
||||
|
||||
request, err := http.NewRequest(
|
||||
http.MethodPost,
|
||||
fmt.Sprintf("%s/api/v1/chats/%s/messages", serverURL, chatID),
|
||||
bytes.NewBufferString(body),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("create message request: %v", err)
|
||||
}
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
request.Header.Set("X-User-Id", actorID)
|
||||
if key != "" {
|
||||
request.Header.Set("Idempotency-Key", key)
|
||||
}
|
||||
|
||||
response, err := http.DefaultClient.Do(request)
|
||||
if err != nil {
|
||||
t.Fatalf("send message request: %v", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
payload, err := io.ReadAll(response.Body)
|
||||
if err != nil {
|
||||
t.Fatalf("read message response: %v", err)
|
||||
}
|
||||
return response.StatusCode, payload
|
||||
}
|
||||
|
||||
func decodeMessageResponse(t *testing.T, payload []byte) dto.MessageResponse {
|
||||
t.Helper()
|
||||
|
||||
var message dto.MessageResponse
|
||||
if err := json.Unmarshal(payload, &message); err != nil {
|
||||
t.Fatalf("decode message response: %v; body=%s", err, payload)
|
||||
}
|
||||
return message
|
||||
}
|
||||
|
||||
func createMessageFixture(t *testing.T) (*store.MemoryStore, string, domain.User, string) {
|
||||
t.Helper()
|
||||
|
||||
server, memoryStore := setupTestServer()
|
||||
t.Cleanup(server.Close)
|
||||
|
||||
user, err := memoryStore.CreateUser("idempotency_user", "Idempotency User")
|
||||
if err != nil {
|
||||
t.Fatalf("create fixture user: %v", err)
|
||||
}
|
||||
chat, err := memoryStore.CreateChat("Idempotency Chat", []string{user.ID})
|
||||
if err != nil {
|
||||
t.Fatalf("create fixture chat: %v", err)
|
||||
}
|
||||
|
||||
return memoryStore, server.URL, user, chat.ID
|
||||
}
|
||||
|
||||
func TestMessageIdempotencyKeyValidation(t *testing.T) {
|
||||
_, serverURL, user, chatID := createMessageFixture(t)
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
key string
|
||||
}{
|
||||
{name: "missing", key: ""},
|
||||
{name: "space", key: "invalid key"},
|
||||
{name: "non ascii", key: "ключ"},
|
||||
{name: "too long", key: string(bytes.Repeat([]byte{'a'}, 129))},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
status, _ := sendMessageRequest(
|
||||
t,
|
||||
serverURL,
|
||||
chatID,
|
||||
user.ID,
|
||||
testCase.key,
|
||||
`{"text":"hello"}`,
|
||||
)
|
||||
if status != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400, got %d", status)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageIdempotencyReplayAndConflict(t *testing.T) {
|
||||
memoryStore, serverURL, user, chatID := createMessageFixture(t)
|
||||
|
||||
status, firstPayload := sendMessageRequest(
|
||||
t, serverURL, chatID, user.ID, "replay-key", `{"text":"hello"}`,
|
||||
)
|
||||
if status != http.StatusCreated {
|
||||
t.Fatalf("first request: expected 201, got %d: %s", status, firstPayload)
|
||||
}
|
||||
|
||||
status, replayPayload := sendMessageRequest(
|
||||
t,
|
||||
serverURL,
|
||||
chatID,
|
||||
user.ID,
|
||||
"replay-key",
|
||||
"{\n \"text\": \"hello\"\n}",
|
||||
)
|
||||
if status != http.StatusCreated {
|
||||
t.Fatalf("replay: expected 201, got %d: %s", status, replayPayload)
|
||||
}
|
||||
|
||||
first := decodeMessageResponse(t, firstPayload)
|
||||
replay := decodeMessageResponse(t, replayPayload)
|
||||
if !reflect.DeepEqual(first, replay) {
|
||||
t.Fatalf("replay changed message: first=%+v replay=%+v", first, replay)
|
||||
}
|
||||
|
||||
status, _ = sendMessageRequest(
|
||||
t, serverURL, chatID, user.ID, "replay-key", `{"text":"different"}`,
|
||||
)
|
||||
if status != http.StatusConflict {
|
||||
t.Fatalf("different body: expected 409, got %d", status)
|
||||
}
|
||||
|
||||
messages, _, err := memoryStore.GetMessages(chatID, user.ID, 10, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("list messages: %v", err)
|
||||
}
|
||||
if len(messages) != 1 {
|
||||
t.Fatalf("expected one stored message, got %d", len(messages))
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageIdempotencyScopesAreIndependent(t *testing.T) {
|
||||
server, memoryStore := setupTestServer()
|
||||
t.Cleanup(server.Close)
|
||||
|
||||
alice, _ := memoryStore.CreateUser("scope_alice", "Alice")
|
||||
bob, _ := memoryStore.CreateUser("scope_bob", "Bob")
|
||||
firstChat, _ := memoryStore.CreateChat("First", []string{alice.ID, bob.ID})
|
||||
secondChat, _ := memoryStore.CreateChat("Second", []string{alice.ID, bob.ID})
|
||||
|
||||
testCases := []struct {
|
||||
actorID string
|
||||
chatID string
|
||||
text string
|
||||
}{
|
||||
{actorID: alice.ID, chatID: firstChat.ID, text: "alice first"},
|
||||
{actorID: bob.ID, chatID: firstChat.ID, text: "bob first"},
|
||||
{actorID: alice.ID, chatID: secondChat.ID, text: "alice second"},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
status, payload := sendMessageRequest(
|
||||
t,
|
||||
server.URL,
|
||||
testCase.chatID,
|
||||
testCase.actorID,
|
||||
"shared-key",
|
||||
fmt.Sprintf(`{"text":%q}`, testCase.text),
|
||||
)
|
||||
if status != http.StatusCreated {
|
||||
t.Fatalf("independent scope: expected 201, got %d: %s", status, payload)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestConcurrentMessageIdempotencyCreatesExactlyOneMessage(t *testing.T) {
|
||||
memoryStore, serverURL, user, chatID := createMessageFixture(t)
|
||||
|
||||
const clients = 32
|
||||
start := make(chan struct{})
|
||||
results := make(chan dto.MessageResponse, clients)
|
||||
errors := make(chan error, clients)
|
||||
|
||||
var waitGroup sync.WaitGroup
|
||||
for index := 0; index < clients; index++ {
|
||||
waitGroup.Add(1)
|
||||
go func() {
|
||||
defer waitGroup.Done()
|
||||
<-start
|
||||
|
||||
request, err := http.NewRequest(
|
||||
http.MethodPost,
|
||||
fmt.Sprintf("%s/api/v1/chats/%s/messages", serverURL, chatID),
|
||||
bytes.NewBufferString(`{"text":"concurrent replay"}`),
|
||||
)
|
||||
if err != nil {
|
||||
errors <- err
|
||||
return
|
||||
}
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
request.Header.Set("X-User-Id", user.ID)
|
||||
request.Header.Set("Idempotency-Key", "one-concurrent-key")
|
||||
|
||||
response, err := http.DefaultClient.Do(request)
|
||||
if err != nil {
|
||||
errors <- err
|
||||
return
|
||||
}
|
||||
defer response.Body.Close()
|
||||
payload, err := io.ReadAll(response.Body)
|
||||
if err != nil {
|
||||
errors <- err
|
||||
return
|
||||
}
|
||||
if response.StatusCode != http.StatusCreated {
|
||||
errors <- fmt.Errorf("expected 201, got %d: %s", response.StatusCode, payload)
|
||||
return
|
||||
}
|
||||
|
||||
var message dto.MessageResponse
|
||||
if err = json.Unmarshal(payload, &message); err != nil {
|
||||
errors <- err
|
||||
return
|
||||
}
|
||||
results <- message
|
||||
}()
|
||||
}
|
||||
|
||||
close(start)
|
||||
waitGroup.Wait()
|
||||
close(results)
|
||||
close(errors)
|
||||
|
||||
for err := range errors {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
var expected dto.MessageResponse
|
||||
count := 0
|
||||
for message := range results {
|
||||
if count == 0 {
|
||||
expected = message
|
||||
} else if !reflect.DeepEqual(message, expected) {
|
||||
t.Fatalf("concurrent replay returned different message: %+v != %+v", message, expected)
|
||||
}
|
||||
count++
|
||||
}
|
||||
if count != clients {
|
||||
t.Fatalf("expected %d successful responses, got %d", clients, count)
|
||||
}
|
||||
|
||||
messages, _, err := memoryStore.GetMessages(chatID, user.ID, clients+1, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("list messages: %v", err)
|
||||
}
|
||||
if len(messages) != 1 {
|
||||
t.Fatalf("expected exactly one stored message, got %d", len(messages))
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageIdempotencyTreatsMissingAndEmptyAttachmentsEqually(t *testing.T) {
|
||||
_, serverURL, user, chatID := createMessageFixture(t)
|
||||
|
||||
status, firstPayload := sendMessageRequest(
|
||||
t,
|
||||
serverURL,
|
||||
chatID,
|
||||
user.ID,
|
||||
"default-attachments",
|
||||
`{"text":"same semantic request"}`,
|
||||
)
|
||||
if status != http.StatusCreated {
|
||||
t.Fatalf("first request: expected 201, got %d: %s", status, firstPayload)
|
||||
}
|
||||
|
||||
status, replayPayload := sendMessageRequest(
|
||||
t,
|
||||
serverURL,
|
||||
chatID,
|
||||
user.ID,
|
||||
"default-attachments",
|
||||
`{"attachment_ids":[],"text":"same semantic request"}`,
|
||||
)
|
||||
if status != http.StatusCreated {
|
||||
t.Fatalf("replay: expected 201, got %d: %s", status, replayPayload)
|
||||
}
|
||||
|
||||
first := decodeMessageResponse(t, firstPayload)
|
||||
replay := decodeMessageResponse(t, replayPayload)
|
||||
if !reflect.DeepEqual(first, replay) {
|
||||
t.Fatalf("missing attachment_ids and [] must replay identically")
|
||||
}
|
||||
if first.AttachmentIDs == nil || len(first.AttachmentIDs) != 0 {
|
||||
t.Fatalf("response must contain attachment_ids: [], got %#v", first.AttachmentIDs)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package student_tests
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"mtusi2026lab7/internal/domain"
|
||||
)
|
||||
|
||||
func TestMessageAttachmentContract(t *testing.T) {
|
||||
memoryStore, serverURL, user, chatID := createMessageFixture(t)
|
||||
|
||||
readyID := "11111111-1111-4111-8111-111111111111"
|
||||
if err := memoryStore.PutAttachment(domain.Attachment{
|
||||
ID: readyID,
|
||||
ChatID: chatID,
|
||||
OwnerID: user.ID,
|
||||
Status: domain.AttachmentStatusReady,
|
||||
}); err != nil {
|
||||
t.Fatalf("seed ready attachment: %v", err)
|
||||
}
|
||||
|
||||
status, payload := sendMessageRequest(
|
||||
t,
|
||||
serverURL,
|
||||
chatID,
|
||||
user.ID,
|
||||
"attachment-only",
|
||||
fmt.Sprintf(`{"text":"","attachment_ids":[%q]}`, readyID),
|
||||
)
|
||||
if status != http.StatusCreated {
|
||||
t.Fatalf("attachment-only message: expected 201, got %d: %s", status, payload)
|
||||
}
|
||||
|
||||
message := decodeMessageResponse(t, payload)
|
||||
if message.Text != "" {
|
||||
t.Fatalf("attachment-only message changed text: %q", message.Text)
|
||||
}
|
||||
if !reflect.DeepEqual(message.AttachmentIDs, []string{readyID}) {
|
||||
t.Fatalf("attachment_ids changed: %#v", message.AttachmentIDs)
|
||||
}
|
||||
|
||||
items, _, err := memoryStore.GetMessages(chatID, user.ID, 10, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("read stored messages: %v", err)
|
||||
}
|
||||
if len(items) != 1 || !reflect.DeepEqual(items[0].AttachmentIDs, []string{readyID}) {
|
||||
t.Fatalf("stored attachment relation differs: %#v", items)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageAttachmentValidationAndAccess(t *testing.T) {
|
||||
memoryStore, serverURL, user, chatID := createMessageFixture(t)
|
||||
otherChat, err := memoryStore.CreateChat("Other chat", []string{user.ID})
|
||||
if err != nil {
|
||||
t.Fatalf("create other chat: %v", err)
|
||||
}
|
||||
|
||||
pendingID := "22222222-2222-4222-8222-222222222222"
|
||||
if err = memoryStore.PutAttachment(domain.Attachment{
|
||||
ID: pendingID,
|
||||
ChatID: chatID,
|
||||
OwnerID: user.ID,
|
||||
Status: domain.AttachmentStatusPending,
|
||||
}); err != nil {
|
||||
t.Fatalf("seed pending attachment: %v", err)
|
||||
}
|
||||
|
||||
foreignID := "33333333-3333-4333-8333-333333333333"
|
||||
if err = memoryStore.PutAttachment(domain.Attachment{
|
||||
ID: foreignID,
|
||||
ChatID: otherChat.ID,
|
||||
OwnerID: user.ID,
|
||||
Status: domain.AttachmentStatusReady,
|
||||
}); err != nil {
|
||||
t.Fatalf("seed foreign attachment: %v", err)
|
||||
}
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
body string
|
||||
wantStatus int
|
||||
}{
|
||||
{
|
||||
name: "empty without attachments",
|
||||
body: `{"text":"","attachment_ids":[]}`,
|
||||
wantStatus: http.StatusBadRequest,
|
||||
},
|
||||
{
|
||||
name: "invalid attachment uuid",
|
||||
body: `{"text":"hello","attachment_ids":["not-a-uuid"]}`,
|
||||
wantStatus: http.StatusBadRequest,
|
||||
},
|
||||
{
|
||||
name: "duplicate attachment",
|
||||
body: fmt.Sprintf(`{"text":"hello","attachment_ids":[%q,%q]}`, pendingID, pendingID),
|
||||
wantStatus: http.StatusBadRequest,
|
||||
},
|
||||
{
|
||||
name: "unknown attachment",
|
||||
body: `{"text":"hello","attachment_ids":["44444444-4444-4444-8444-444444444444"]}`,
|
||||
wantStatus: http.StatusNotFound,
|
||||
},
|
||||
{
|
||||
name: "attachment from another chat",
|
||||
body: fmt.Sprintf(`{"text":"hello","attachment_ids":[%q]}`, foreignID),
|
||||
wantStatus: http.StatusNotFound,
|
||||
},
|
||||
{
|
||||
name: "attachment not ready",
|
||||
body: fmt.Sprintf(`{"text":"hello","attachment_ids":[%q]}`, pendingID),
|
||||
wantStatus: http.StatusConflict,
|
||||
},
|
||||
}
|
||||
|
||||
for index, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
status, payload := sendMessageRequest(
|
||||
t,
|
||||
serverURL,
|
||||
chatID,
|
||||
user.ID,
|
||||
fmt.Sprintf("attachment-validation-%d", index),
|
||||
testCase.body,
|
||||
)
|
||||
if status != testCase.wantStatus {
|
||||
t.Fatalf("expected %d, got %d: %s", testCase.wantStatus, status, payload)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,667 @@
|
||||
package student_tests
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"sort"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
store "mtusi2026lab7/internal/adapter/memory"
|
||||
"mtusi2026lab7/internal/domain"
|
||||
"mtusi2026lab7/internal/transport/http/dto"
|
||||
"mtusi2026lab7/internal/transport/http/handlers"
|
||||
"mtusi2026lab7/internal/transport/http/middleware"
|
||||
)
|
||||
|
||||
func requireLegacyAuth(
|
||||
memoryStore *store.MemoryStore,
|
||||
next http.HandlerFunc,
|
||||
) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
userID := r.Header.Get("X-User-Id")
|
||||
|
||||
user, err := memoryStore.GetUserByID(userID)
|
||||
if err != nil {
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
ctx := context.WithValue(
|
||||
r.Context(),
|
||||
middleware.UserContextKey,
|
||||
user,
|
||||
)
|
||||
|
||||
next(w, r.WithContext(ctx))
|
||||
}
|
||||
}
|
||||
|
||||
// изолированный серв для тестов
|
||||
func setupTestServer() (*httptest.Server, *store.MemoryStore) {
|
||||
memoryStore := store.NewMemoryStore()
|
||||
repository := store.NewMemoryRepository(memoryStore)
|
||||
handler := handlers.NewHandler(newTestService(repository, time.Hour))
|
||||
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("POST /api/v1/users", handler.CreateUser)
|
||||
mux.HandleFunc(
|
||||
"GET /api/v1/users/me",
|
||||
requireLegacyAuth(memoryStore, handler.GetMe),
|
||||
)
|
||||
mux.HandleFunc(
|
||||
"POST /api/v1/chats",
|
||||
requireLegacyAuth(memoryStore, handler.CreateChat),
|
||||
)
|
||||
mux.HandleFunc(
|
||||
"GET /api/v1/chats",
|
||||
requireLegacyAuth(memoryStore, handler.ListChats),
|
||||
)
|
||||
mux.HandleFunc(
|
||||
"GET /api/v1/chats/{chat_id}",
|
||||
requireLegacyAuth(memoryStore, handler.GetChat),
|
||||
)
|
||||
mux.HandleFunc(
|
||||
"POST /api/v1/chats/{chat_id}/messages",
|
||||
requireLegacyAuth(memoryStore, handler.CreateMessage),
|
||||
)
|
||||
mux.HandleFunc(
|
||||
"GET /api/v1/chats/{chat_id}/messages",
|
||||
requireLegacyAuth(memoryStore, handler.GetMessages),
|
||||
)
|
||||
|
||||
var root http.Handler = mux
|
||||
root = middleware.Recovery(root)
|
||||
root = middleware.RequestID(root)
|
||||
|
||||
return httptest.NewServer(root), memoryStore
|
||||
}
|
||||
|
||||
// 1 тест на дубликат username -> 409 Conflict
|
||||
func TestDuplicateUsername(t *testing.T) {
|
||||
ts, _ := setupTestServer()
|
||||
defer ts.Close()
|
||||
|
||||
body := `{
|
||||
"username":"bob_the_builder",
|
||||
"display_name":"Боб",
|
||||
"password":"Test-password-123"}`
|
||||
|
||||
// Первый раз — 201 Created
|
||||
res1, _ := http.Post(ts.URL+"/api/v1/users", "application/json", bytes.NewBufferString(body))
|
||||
if res1.StatusCode != http.StatusCreated {
|
||||
t.Fatalf("expected 201, got %d", res1.StatusCode)
|
||||
}
|
||||
|
||||
// Второй раз тот же username — 409 Conflict
|
||||
res2, _ := http.Post(ts.URL+"/api/v1/users", "application/json", bytes.NewBufferString(body))
|
||||
if res2.StatusCode != http.StatusConflict {
|
||||
t.Fatalf("expected 409 Conflict for duplicate username, got %d", res2.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
// 2 тест на неверный JSON и лишние поля -> 400 Invalid Request
|
||||
func TestInvalidAndExtraJSON(t *testing.T) {
|
||||
ts, _ := setupTestServer()
|
||||
defer ts.Close()
|
||||
|
||||
// Кривой JSON (malformed)
|
||||
res1, _ := http.Post(ts.URL+"/api/v1/users", "application/json", bytes.NewBufferString(`{"username": "bad"`))
|
||||
if res1.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400 for malformed json, got %d", res1.StatusCode)
|
||||
}
|
||||
|
||||
// Лишнее поле "age" (проверка DisallowUnknownFields)
|
||||
res2, _ := http.Post(ts.URL+"/api/v1/users", "application/json", bytes.NewBufferString(`{"username":"valid_user","display_name":"User","age":25}`))
|
||||
if res2.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400 for extra fields, got %d", res2.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
// 3 тст на пустое сообщение и сообщение из одних пробелов -> 400 Invalid Request
|
||||
func TestEmptyMessageValidation(t *testing.T) {
|
||||
ts, st := setupTestServer()
|
||||
defer ts.Close()
|
||||
|
||||
u, _ := st.CreateUser("user_msg_test", "Tester")
|
||||
chat, _ := st.CreateChat("Test Chat", []string{u.ID})
|
||||
|
||||
// Пустой текст
|
||||
req, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/api/v1/chats/%s/messages", ts.URL, chat.ID), bytes.NewBufferString(`{"text":""}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("X-User-Id", u.ID)
|
||||
req.Header.Set("Idempotency-Key", "empty-text")
|
||||
|
||||
res, _ := http.DefaultClient.Do(req)
|
||||
if res.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400 for empty text, got %d", res.StatusCode)
|
||||
}
|
||||
|
||||
// Текст только из пробелов
|
||||
reqSpaces, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/api/v1/chats/%s/messages", ts.URL, chat.ID), bytes.NewBufferString(`{"text":" "}`))
|
||||
reqSpaces.Header.Set("Content-Type", "application/json")
|
||||
reqSpaces.Header.Set("X-User-Id", u.ID)
|
||||
reqSpaces.Header.Set("Idempotency-Key", "spaces-text")
|
||||
|
||||
resSpaces, _ := http.DefaultClient.Do(reqSpaces)
|
||||
if resSpaces.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400 for whitespace-only text, got %d", resSpaces.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
// 4 тест: чужой чат для постороннего -> 404 Not Found (не 403!)
|
||||
func TestOutsiderChatAccess(t *testing.T) {
|
||||
ts, st := setupTestServer()
|
||||
defer ts.Close()
|
||||
|
||||
alice, _ := st.CreateUser("alice_secret", "Алиса")
|
||||
eve, _ := st.CreateUser("eve_eavesdropper", "Ева")
|
||||
|
||||
chat, _ := st.CreateChat("Секретный чат", []string{alice.ID})
|
||||
|
||||
// Ева пытается прочитать чат Алисы
|
||||
req, _ := http.NewRequest(http.MethodGet, fmt.Sprintf("%s/api/v1/chats/%s", ts.URL, chat.ID), nil)
|
||||
req.Header.Set("X-User-Id", eve.ID)
|
||||
|
||||
res, _ := http.DefaultClient.Do(req)
|
||||
if res.StatusCode != http.StatusNotFound {
|
||||
t.Fatalf("expected 404 Not Found (no leak via 403), got %d", res.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
// 5 Тест: пагинация по нескольким страницам с курсором
|
||||
func TestCursorPaginationMultiplePages(t *testing.T) {
|
||||
ts, st := setupTestServer()
|
||||
defer ts.Close()
|
||||
|
||||
u, _ := st.CreateUser("paging_user", "Пейджер")
|
||||
chat, _ := st.CreateChat("Чат пагинации", []string{u.ID})
|
||||
|
||||
// Отправляем 5 сообщений
|
||||
for i := 1; i <= 5; i++ {
|
||||
st.CreateMessage(chat.ID, u.ID, fmt.Sprintf("Message %d", i))
|
||||
}
|
||||
|
||||
// Запрашиваем порциями по limit=2
|
||||
var allReceived []string
|
||||
cursor := ""
|
||||
|
||||
for {
|
||||
url := fmt.Sprintf("%s/api/v1/chats/%s/messages?limit=2", ts.URL, chat.ID)
|
||||
if cursor != "" {
|
||||
url += "&cursor=" + cursor
|
||||
}
|
||||
|
||||
req, _ := http.NewRequest(http.MethodGet, url, nil)
|
||||
req.Header.Set("X-User-Id", u.ID)
|
||||
res, _ := http.DefaultClient.Do(req)
|
||||
|
||||
var page dto.MessagePageResponse
|
||||
body, _ := io.ReadAll(res.Body)
|
||||
json.Unmarshal(body, &page)
|
||||
res.Body.Close()
|
||||
|
||||
for _, m := range page.Items {
|
||||
allReceived = append(allReceived, m.Text)
|
||||
}
|
||||
|
||||
if page.NextCursor == nil {
|
||||
break
|
||||
}
|
||||
cursor = *page.NextCursor
|
||||
}
|
||||
|
||||
if len(allReceived) != 5 {
|
||||
t.Fatalf("expected 5 messages total across pages, got %d", len(allReceived))
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatCursorPaginationMultiplePages(t *testing.T) {
|
||||
ts, st := setupTestServer()
|
||||
defer ts.Close()
|
||||
|
||||
user, err := st.CreateUser("chat_paging_user", "Пейджер чатов")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create user: %v", err)
|
||||
}
|
||||
|
||||
outsider, err := st.CreateUser("chat_paging_outsider", "Посторонний")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create outsider: %v", err)
|
||||
}
|
||||
|
||||
createdChats := make([]domain.Chat, 0, 5)
|
||||
|
||||
for i := 1; i <= 5; i++ {
|
||||
chat, createErr := st.CreateChat(
|
||||
fmt.Sprintf("Chat %d", i),
|
||||
[]string{user.ID},
|
||||
)
|
||||
if createErr != nil {
|
||||
t.Fatalf("failed to create chat %d: %v", i, createErr)
|
||||
}
|
||||
|
||||
createdChats = append(createdChats, chat)
|
||||
|
||||
// Чужой чат создаётся между доступными чатами и не должен
|
||||
// влиять на размер страницы или next_cursor пользователя.
|
||||
if i == 3 {
|
||||
if _, createErr = st.CreateChat(
|
||||
"Outsider chat",
|
||||
[]string{outsider.ID},
|
||||
); createErr != nil {
|
||||
t.Fatalf("failed to create outsider chat: %v", createErr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sort.Slice(createdChats, func(i, j int) bool {
|
||||
if createdChats[i].CreatedAt.Equal(createdChats[j].CreatedAt) {
|
||||
return createdChats[i].ID < createdChats[j].ID
|
||||
}
|
||||
|
||||
return createdChats[i].CreatedAt.Before(createdChats[j].CreatedAt)
|
||||
})
|
||||
|
||||
var receivedIDs []string
|
||||
seenIDs := make(map[string]bool)
|
||||
seenCursors := make(map[string]bool)
|
||||
cursor := ""
|
||||
finished := false
|
||||
|
||||
for pageNumber := 1; pageNumber <= 10; pageNumber++ {
|
||||
requestURL := ts.URL + "/api/v1/chats?limit=2"
|
||||
if cursor != "" {
|
||||
requestURL += "&cursor=" + url.QueryEscape(cursor)
|
||||
}
|
||||
|
||||
req, err := http.NewRequest(http.MethodGet, requestURL, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create request: %v", err)
|
||||
}
|
||||
req.Header.Set("X-User-Id", user.ID)
|
||||
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to list chats: %v", err)
|
||||
}
|
||||
|
||||
var page dto.ChatPageResponse
|
||||
decodeErr := json.NewDecoder(res.Body).Decode(&page)
|
||||
res.Body.Close()
|
||||
|
||||
if res.StatusCode != http.StatusOK {
|
||||
t.Fatalf("expected 200, got %d", res.StatusCode)
|
||||
}
|
||||
if decodeErr != nil {
|
||||
t.Fatalf("failed to decode chat page: %v", decodeErr)
|
||||
}
|
||||
if len(page.Items) > 2 {
|
||||
t.Fatalf("page contains %d chats with limit=2", len(page.Items))
|
||||
}
|
||||
|
||||
for _, chat := range page.Items {
|
||||
if seenIDs[chat.ID] {
|
||||
t.Fatalf("chat %s was returned more than once", chat.ID)
|
||||
}
|
||||
|
||||
seenIDs[chat.ID] = true
|
||||
receivedIDs = append(receivedIDs, chat.ID)
|
||||
}
|
||||
|
||||
if page.NextCursor == nil {
|
||||
finished = true
|
||||
break
|
||||
}
|
||||
|
||||
if seenCursors[*page.NextCursor] {
|
||||
t.Fatalf("cursor cycle detected")
|
||||
}
|
||||
|
||||
seenCursors[*page.NextCursor] = true
|
||||
cursor = *page.NextCursor
|
||||
}
|
||||
|
||||
if !finished {
|
||||
t.Fatal("chat pagination did not finish")
|
||||
}
|
||||
|
||||
if len(receivedIDs) != len(createdChats) {
|
||||
t.Fatalf(
|
||||
"expected %d chats across all pages, got %d",
|
||||
len(createdChats),
|
||||
len(receivedIDs),
|
||||
)
|
||||
}
|
||||
|
||||
for i, chat := range createdChats {
|
||||
if receivedIDs[i] != chat.ID {
|
||||
t.Fatalf(
|
||||
"chat order differs at position %d: expected %s, got %s",
|
||||
i,
|
||||
chat.ID,
|
||||
receivedIDs[i],
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatCursorValidation(t *testing.T) {
|
||||
ts, st := setupTestServer()
|
||||
defer ts.Close()
|
||||
|
||||
alice, err := st.CreateUser("chat_cursor_alice", "Алиса")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create Alice: %v", err)
|
||||
}
|
||||
|
||||
bob, err := st.CreateUser("chat_cursor_bob", "Боб")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create Bob: %v", err)
|
||||
}
|
||||
|
||||
for i := 1; i <= 2; i++ {
|
||||
if _, err = st.CreateChat(
|
||||
fmt.Sprintf("Alice chat %d", i),
|
||||
[]string{alice.ID},
|
||||
); err != nil {
|
||||
t.Fatalf("failed to create Alice chat: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
if _, err = st.CreateChat("Bob chat", []string{bob.ID}); err != nil {
|
||||
t.Fatalf("failed to create Bob chat: %v", err)
|
||||
}
|
||||
|
||||
firstRequest, err := http.NewRequest(
|
||||
http.MethodGet,
|
||||
ts.URL+"/api/v1/chats?limit=1",
|
||||
nil,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create first request: %v", err)
|
||||
}
|
||||
firstRequest.Header.Set("X-User-Id", alice.ID)
|
||||
|
||||
firstResponse, err := http.DefaultClient.Do(firstRequest)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to request first page: %v", err)
|
||||
}
|
||||
|
||||
var firstPage dto.ChatPageResponse
|
||||
decodeErr := json.NewDecoder(firstResponse.Body).Decode(&firstPage)
|
||||
firstResponse.Body.Close()
|
||||
|
||||
if firstResponse.StatusCode != http.StatusOK {
|
||||
t.Fatalf("expected first page status 200, got %d", firstResponse.StatusCode)
|
||||
}
|
||||
if decodeErr != nil {
|
||||
t.Fatalf("failed to decode first page: %v", decodeErr)
|
||||
}
|
||||
if firstPage.NextCursor == nil {
|
||||
t.Fatal("expected next_cursor for Alice")
|
||||
}
|
||||
|
||||
foreignRequest, err := http.NewRequest(
|
||||
http.MethodGet,
|
||||
ts.URL+"/api/v1/chats?limit=1&cursor="+
|
||||
url.QueryEscape(*firstPage.NextCursor),
|
||||
nil,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create foreign cursor request: %v", err)
|
||||
}
|
||||
foreignRequest.Header.Set("X-User-Id", bob.ID)
|
||||
|
||||
foreignResponse, err := http.DefaultClient.Do(foreignRequest)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to send foreign cursor request: %v", err)
|
||||
}
|
||||
foreignResponse.Body.Close()
|
||||
|
||||
if foreignResponse.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf(
|
||||
"expected 400 for another user's cursor, got %d",
|
||||
foreignResponse.StatusCode,
|
||||
)
|
||||
}
|
||||
|
||||
malformedRequest, err := http.NewRequest(
|
||||
http.MethodGet,
|
||||
ts.URL+"/api/v1/chats?cursor=not-valid-base64!",
|
||||
nil,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create malformed cursor request: %v", err)
|
||||
}
|
||||
malformedRequest.Header.Set("X-User-Id", alice.ID)
|
||||
|
||||
malformedResponse, err := http.DefaultClient.Do(malformedRequest)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to send malformed cursor request: %v", err)
|
||||
}
|
||||
malformedResponse.Body.Close()
|
||||
|
||||
if malformedResponse.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf(
|
||||
"expected 400 for malformed cursor, got %d",
|
||||
malformedResponse.StatusCode,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// 6 тест: 100 сообщений от 10 клиентов одновременно, защита от гонок
|
||||
func TestConcurrent100MessagesFrom10Clients(t *testing.T) {
|
||||
ts, st := setupTestServer()
|
||||
defer ts.Close()
|
||||
|
||||
// Создаем 10 пользователей
|
||||
var memberIDs []string
|
||||
for i := 0; i < 10; i++ {
|
||||
u, _ := st.CreateUser(fmt.Sprintf("client_%d", i), fmt.Sprintf("Client %d", i))
|
||||
memberIDs = append(memberIDs, u.ID)
|
||||
}
|
||||
|
||||
chat, err := st.CreateChat("Highload Chat", memberIDs)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create chat: %v", err)
|
||||
}
|
||||
|
||||
var wg sync.WaitGroup
|
||||
totalClients := 10
|
||||
messagesPerClient := 10
|
||||
|
||||
for i := 0; i < totalClients; i++ {
|
||||
wg.Add(1)
|
||||
clientID := memberIDs[i]
|
||||
|
||||
go func(senderID string, clientIndex int) {
|
||||
defer wg.Done()
|
||||
|
||||
for m := 0; m < messagesPerClient; m++ {
|
||||
text := fmt.Sprintf("Client %d - Message %d", clientIndex, m)
|
||||
payload := fmt.Sprintf(`{"text":"%s"}`, text)
|
||||
|
||||
req, _ := http.NewRequest(
|
||||
http.MethodPost,
|
||||
fmt.Sprintf("%s/api/v1/chats/%s/messages", ts.URL, chat.ID),
|
||||
bytes.NewBufferString(payload),
|
||||
)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("X-User-Id", senderID)
|
||||
req.Header.Set(
|
||||
"Idempotency-Key",
|
||||
fmt.Sprintf("concurrent-%d-%d", clientIndex, m),
|
||||
)
|
||||
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
if err != nil || res.StatusCode != http.StatusCreated {
|
||||
t.Errorf("failed to send concurrent message: %v", err)
|
||||
}
|
||||
if res != nil {
|
||||
res.Body.Close()
|
||||
}
|
||||
}
|
||||
}(clientID, i)
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
|
||||
// должно быть 100 сообщений в чате
|
||||
items, _, err := st.GetMessages(chat.ID, memberIDs[0], 200, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to get messages: %v", err)
|
||||
}
|
||||
|
||||
if len(items) != 100 {
|
||||
t.Fatalf("RACE CONDITION DETECTED: expected exactly 100 messages, got %d", len(items))
|
||||
}
|
||||
|
||||
// уникальность ID
|
||||
seenIDs := make(map[string]bool)
|
||||
for _, m := range items {
|
||||
if seenIDs[m.ID] {
|
||||
t.Fatalf("duplicate message ID found: %s", m.ID)
|
||||
}
|
||||
seenIDs[m.ID] = true
|
||||
}
|
||||
}
|
||||
|
||||
// 7 тест: защита от подделки курсора (чужой чат или битый Base64) -> 400
|
||||
func TestForeignAndMalformedCursor(t *testing.T) {
|
||||
ts, st := setupTestServer()
|
||||
defer ts.Close()
|
||||
|
||||
u, _ := st.CreateUser("cursor_tester", "Tester")
|
||||
chatA, _ := st.CreateChat("Chat A", []string{u.ID})
|
||||
chatB, _ := st.CreateChat("Chat B", []string{u.ID})
|
||||
|
||||
// В Чат А кладем несколько сообщений, чтобы при limit=1 появился NextCursor
|
||||
st.CreateMessage(chatA.ID, u.ID, "Message 1 in A")
|
||||
st.CreateMessage(chatA.ID, u.ID, "Message 2 in A")
|
||||
st.CreateMessage(chatA.ID, u.ID, "Message 3 in A")
|
||||
st.CreateMessage(chatA.ID, u.ID, "Message 4 in A")
|
||||
st.CreateMessage(chatA.ID, u.ID, "Message 5 in A")
|
||||
|
||||
st.CreateMessage(chatB.ID, u.ID, "Message 1 in B")
|
||||
st.CreateMessage(chatB.ID, u.ID, "Message 2 in B")
|
||||
|
||||
// Получаем валидный курсор из Чата А (запрашиваем 1 из 2)
|
||||
itemsA, hasMore, err := st.GetMessages(chatA.ID, u.ID, 1, nil)
|
||||
if err != nil || !hasMore || len(itemsA) != 1 {
|
||||
t.Fatalf("expected next_cursor in Chat A, err: %v", err)
|
||||
}
|
||||
nextCursor, err := newTestCursorCodec().EncodeMessage(domain.MessageCursor{
|
||||
CreatedAt: itemsA[0].CreatedAt,
|
||||
MessageID: itemsA[0].ID,
|
||||
ChatID: chatA.ID,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("encode test cursor: %v", err)
|
||||
}
|
||||
|
||||
// 1. Пытаемся применить курсор от Чата А к Чату Б -> строго 400!
|
||||
urlForeign := fmt.Sprintf("%s/api/v1/chats/%s/messages?cursor=%s", ts.URL, chatB.ID, nextCursor)
|
||||
reqForeign, _ := http.NewRequest(http.MethodGet, urlForeign, nil)
|
||||
reqForeign.Header.Set("X-User-Id", u.ID)
|
||||
resForeign, _ := http.DefaultClient.Do(reqForeign)
|
||||
|
||||
if resForeign.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400 for foreign chat cursor, got %d", resForeign.StatusCode)
|
||||
}
|
||||
|
||||
// 2. Битый (невалидный) Base64 -> 400
|
||||
urlBad := fmt.Sprintf("%s/api/v1/chats/%s/messages?cursor=not-a-valid-base64!@#", ts.URL, chatB.ID)
|
||||
reqBad, _ := http.NewRequest(http.MethodGet, urlBad, nil)
|
||||
reqBad.Header.Set("X-User-Id", u.ID)
|
||||
resBad, _ := http.DefaultClient.Do(reqBad)
|
||||
|
||||
if resBad.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400 for malformed cursor, got %d", resBad.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
// 8 тест валидации создания чата (создателя нет в списке / несуществующий юзер / дубликат) -> 400
|
||||
func TestChatCreationValidation(t *testing.T) {
|
||||
ts, st := setupTestServer()
|
||||
defer ts.Close()
|
||||
|
||||
alice, _ := st.CreateUser("alice_chat_val", "Alice")
|
||||
bob, _ := st.CreateUser("bob_chat_val", "Bob")
|
||||
|
||||
// 1. Создатель (Alice) забыла добавить себя в member_ids
|
||||
bodyNoCaller := fmt.Sprintf(`{"title":"No Caller Chat","member_ids":["%s"]}`, bob.ID)
|
||||
req1, _ := http.NewRequest(http.MethodPost, ts.URL+"/api/v1/chats", bytes.NewBufferString(bodyNoCaller))
|
||||
req1.Header.Set("Content-Type", "application/json")
|
||||
req1.Header.Set("X-User-Id", alice.ID)
|
||||
res1, _ := http.DefaultClient.Do(req1)
|
||||
if res1.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400 when caller is not in member_ids, got %d", res1.StatusCode)
|
||||
}
|
||||
|
||||
// 2. В участниках передан несуществующий UUID
|
||||
bodyFakeUser := fmt.Sprintf(`{"title":"Fake User Chat","member_ids":["%s","00000000-0000-0000-0000-000000000000"]}`, alice.ID)
|
||||
req2, _ := http.NewRequest(http.MethodPost, ts.URL+"/api/v1/chats", bytes.NewBufferString(bodyFakeUser))
|
||||
req2.Header.Set("Content-Type", "application/json")
|
||||
req2.Header.Set("X-User-Id", alice.ID)
|
||||
res2, _ := http.DefaultClient.Do(req2)
|
||||
if res2.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400 for non-existent member_id, got %d", res2.StatusCode)
|
||||
}
|
||||
|
||||
// 3. Дубликат участника в списке
|
||||
bodyDuplicate := fmt.Sprintf(`{"title":"Duplicate Member","member_ids":["%s","%s"]}`, alice.ID, alice.ID)
|
||||
req3, _ := http.NewRequest(http.MethodPost, ts.URL+"/api/v1/chats", bytes.NewBufferString(bodyDuplicate))
|
||||
req3.Header.Set("Content-Type", "application/json")
|
||||
req3.Header.Set("X-User-Id", alice.ID)
|
||||
res3, _ := http.DefaultClient.Do(req3)
|
||||
if res3.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400 for duplicate member_ids, got %d", res3.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
// 9 тест лимитов символов Unicode (длина до 4000 рун и отказ при >4000)
|
||||
func TestUnicodeLimits(t *testing.T) {
|
||||
ts, st := setupTestServer()
|
||||
defer ts.Close()
|
||||
|
||||
u, _ := st.CreateUser("unicode_master", "Иван 🚀")
|
||||
chat, _ := st.CreateChat("Unicode Chat", []string{u.ID})
|
||||
|
||||
// Ровно 4000 смайликов (в байтах это 16000 байт, но в рунах — ровно 4000!)
|
||||
validRunes := make([]rune, 4000)
|
||||
for i := range validRunes {
|
||||
validRunes[i] = '🔥'
|
||||
}
|
||||
bodyValid := fmt.Sprintf(`{"text":"%s"}`, string(validRunes))
|
||||
req1, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/api/v1/chats/%s/messages", ts.URL, chat.ID), bytes.NewBufferString(bodyValid))
|
||||
req1.Header.Set("Content-Type", "application/json")
|
||||
req1.Header.Set("X-User-Id", u.ID)
|
||||
req1.Header.Set("Idempotency-Key", "unicode-valid")
|
||||
res1, _ := http.DefaultClient.Do(req1)
|
||||
if res1.StatusCode != http.StatusCreated {
|
||||
t.Fatalf("expected 201 for 4000 unicode runes, got %d", res1.StatusCode)
|
||||
}
|
||||
|
||||
// 4001 символ -> строго 400 Invalid Request!
|
||||
tooLongRunes := make([]rune, 4001)
|
||||
for i := range tooLongRunes {
|
||||
tooLongRunes[i] = 'a'
|
||||
}
|
||||
bodyTooLong := fmt.Sprintf(`{"text":"%s"}`, string(tooLongRunes))
|
||||
req2, _ := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/api/v1/chats/%s/messages", ts.URL, chat.ID), bytes.NewBufferString(bodyTooLong))
|
||||
req2.Header.Set("Content-Type", "application/json")
|
||||
req2.Header.Set("X-User-Id", u.ID)
|
||||
req2.Header.Set("Idempotency-Key", "unicode-too-long")
|
||||
res2, _ := http.DefaultClient.Do(req2)
|
||||
if res2.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400 for 4001 runes, got %d", res2.StatusCode)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package student_tests
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab7/internal/security"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
func legacyPasswordHash(password string) string {
|
||||
salt := []byte("legacy-salt-1234")
|
||||
hash := argon2.IDKey([]byte(password), salt, 1, 8*1024, 1, 32)
|
||||
return fmt.Sprintf(
|
||||
"$argon2id$v=%d$m=8192,t=1,p=1$%s$%s",
|
||||
argon2.Version,
|
||||
base64.RawStdEncoding.EncodeToString(salt),
|
||||
base64.RawStdEncoding.EncodeToString(hash),
|
||||
)
|
||||
}
|
||||
|
||||
func TestSuccessfulLoginRehashesLegacyPassword(t *testing.T) {
|
||||
testServer, repository := setupSessionTestServer(t, time.Hour)
|
||||
defer testServer.Close()
|
||||
|
||||
user := registerSessionTestUser(t, testServer.URL, "rehash_user")
|
||||
_, currentHash, err := repository.GetUserByUsername(t.Context(), user.Username)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
legacyHash := legacyPasswordHash(testPassword)
|
||||
if err = repository.UpdatePasswordHash(t.Context(), user.ID, currentHash, legacyHash); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
response := createSessionRequest(t, testServer.URL, user.Username, testPassword)
|
||||
response.Body.Close()
|
||||
if response.StatusCode != http.StatusCreated {
|
||||
t.Fatalf("expected successful login, got %d", response.StatusCode)
|
||||
}
|
||||
|
||||
_, upgradedHash, err := repository.GetUserByUsername(t.Context(), user.Username)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if upgradedHash == legacyHash {
|
||||
t.Fatal("successful login did not replace the legacy hash")
|
||||
}
|
||||
matches, err := security.VerifyPassword(testPassword, upgradedHash)
|
||||
if err != nil || !matches {
|
||||
t.Fatalf("upgraded hash does not verify: matches=%v err=%v", matches, err)
|
||||
}
|
||||
needsRehash, err := security.NeedsPasswordRehash(upgradedHash)
|
||||
if err != nil || needsRehash {
|
||||
t.Fatalf("upgraded hash still needs rehash: needs=%v err=%v", needsRehash, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
package student_tests
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type contractErrorResponse struct {
|
||||
Error struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
} `json:"error"`
|
||||
}
|
||||
|
||||
func requireContractError(
|
||||
t *testing.T,
|
||||
response *http.Response,
|
||||
wantStatus int,
|
||||
wantCode string,
|
||||
) {
|
||||
t.Helper()
|
||||
defer response.Body.Close()
|
||||
|
||||
if response.StatusCode != wantStatus {
|
||||
body, _ := io.ReadAll(response.Body)
|
||||
t.Fatalf(
|
||||
"expected status %d, got %d: %s",
|
||||
wantStatus,
|
||||
response.StatusCode,
|
||||
body,
|
||||
)
|
||||
}
|
||||
|
||||
requestID := response.Header.Get("X-Request-Id")
|
||||
if requestID == "" {
|
||||
t.Fatal("error response has no X-Request-Id")
|
||||
}
|
||||
if contentType := response.Header.Get("Content-Type"); contentType != "application/json; charset=utf-8" {
|
||||
t.Fatalf("unexpected error Content-Type: %q", contentType)
|
||||
}
|
||||
|
||||
var payload contractErrorResponse
|
||||
if err := json.NewDecoder(response.Body).Decode(&payload); err != nil {
|
||||
t.Fatalf("decode error response: %v", err)
|
||||
}
|
||||
if payload.Error.Code != wantCode {
|
||||
t.Fatalf(
|
||||
"expected error code %q, got %q",
|
||||
wantCode,
|
||||
payload.Error.Code,
|
||||
)
|
||||
}
|
||||
if payload.Error.Message == "" {
|
||||
t.Fatal("error response has an empty message")
|
||||
}
|
||||
if payload.Error.RequestID != requestID {
|
||||
t.Fatal("body request_id differs from X-Request-Id")
|
||||
}
|
||||
}
|
||||
|
||||
func sendRegistration(
|
||||
t *testing.T,
|
||||
baseURL string,
|
||||
contentType string,
|
||||
body []byte,
|
||||
) *http.Response {
|
||||
t.Helper()
|
||||
|
||||
request, err := http.NewRequest(
|
||||
http.MethodPost,
|
||||
baseURL+"/api/v1/users",
|
||||
bytes.NewReader(body),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("create registration request: %v", err)
|
||||
}
|
||||
if contentType != "" {
|
||||
request.Header.Set("Content-Type", contentType)
|
||||
}
|
||||
|
||||
response, err := http.DefaultClient.Do(request)
|
||||
if err != nil {
|
||||
t.Fatalf("send registration request: %v", err)
|
||||
}
|
||||
|
||||
return response
|
||||
}
|
||||
|
||||
func TestJSONRequestRequiresApplicationJSON(t *testing.T) {
|
||||
testServer, _ := setupTestServer()
|
||||
defer testServer.Close()
|
||||
|
||||
body := []byte(
|
||||
`{"username":"mime_probe","display_name":"Test",` +
|
||||
`"password":"123456789012"}`,
|
||||
)
|
||||
|
||||
for _, contentType := range []string{
|
||||
"",
|
||||
"text/plain",
|
||||
"application/xml",
|
||||
"application/json; charset=iso-8859-1",
|
||||
} {
|
||||
contentType := contentType
|
||||
t.Run(contentType, func(t *testing.T) {
|
||||
response := sendRegistration(
|
||||
t,
|
||||
testServer.URL,
|
||||
contentType,
|
||||
body,
|
||||
)
|
||||
requireContractError(
|
||||
t,
|
||||
response,
|
||||
http.StatusUnsupportedMediaType,
|
||||
"unsupported_media_type",
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
response := sendRegistration(
|
||||
t,
|
||||
testServer.URL,
|
||||
"application/json; charset=UTF-8",
|
||||
body,
|
||||
)
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode != http.StatusCreated {
|
||||
responseBody, _ := io.ReadAll(response.Body)
|
||||
t.Fatalf(
|
||||
"expected application/json with UTF-8 charset to be accepted, "+
|
||||
"got %d: %s",
|
||||
response.StatusCode,
|
||||
responseBody,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func TestJSONRequestRejectsInvalidUTF8WithoutMutation(t *testing.T) {
|
||||
testServer, _ := setupTestServer()
|
||||
defer testServer.Close()
|
||||
|
||||
body := append(
|
||||
[]byte(
|
||||
`{"username":"utf8_probe","display_name":"Test",`+
|
||||
`"password":"12345678901`,
|
||||
),
|
||||
0xff,
|
||||
)
|
||||
body = append(body, []byte(`"}`)...)
|
||||
|
||||
response := sendRegistration(
|
||||
t,
|
||||
testServer.URL,
|
||||
"application/json",
|
||||
body,
|
||||
)
|
||||
requireContractError(
|
||||
t,
|
||||
response,
|
||||
http.StatusBadRequest,
|
||||
"invalid_request",
|
||||
)
|
||||
|
||||
validBody := []byte(
|
||||
`{"username":"utf8_probe","display_name":"Test",` +
|
||||
`"password":"12345678901�"}`,
|
||||
)
|
||||
validResponse := sendRegistration(
|
||||
t,
|
||||
testServer.URL,
|
||||
"application/json",
|
||||
validBody,
|
||||
)
|
||||
defer validResponse.Body.Close()
|
||||
if validResponse.StatusCode != http.StatusCreated {
|
||||
responseBody, _ := io.ReadAll(validResponse.Body)
|
||||
t.Fatalf(
|
||||
"invalid UTF-8 request mutated storage; expected subsequent "+
|
||||
"valid registration 201, got %d: %s",
|
||||
validResponse.StatusCode,
|
||||
responseBody,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func TestJSONRequestRejectsOversizedBody(t *testing.T) {
|
||||
testServer, _ := setupTestServer()
|
||||
defer testServer.Close()
|
||||
|
||||
response := sendRegistration(
|
||||
t,
|
||||
testServer.URL,
|
||||
"application/json",
|
||||
bytes.Repeat([]byte(" "), (1<<20)+1),
|
||||
)
|
||||
requireContractError(
|
||||
t,
|
||||
response,
|
||||
http.StatusRequestEntityTooLarge,
|
||||
"payload_too_large",
|
||||
)
|
||||
}
|
||||
|
||||
func TestBasicAuthRejectsInvalidUTF8(t *testing.T) {
|
||||
testServer, _ := setupSessionTestServer(t, 0)
|
||||
defer testServer.Close()
|
||||
|
||||
credentials := append([]byte("unknown:"), 0xff)
|
||||
request, err := http.NewRequest(
|
||||
http.MethodPost,
|
||||
testServer.URL+"/api/v1/auth/sessions",
|
||||
nil,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("create session request: %v", err)
|
||||
}
|
||||
request.Header.Set(
|
||||
"Authorization",
|
||||
"Basic "+base64.StdEncoding.EncodeToString(credentials),
|
||||
)
|
||||
|
||||
response, err := http.DefaultClient.Do(request)
|
||||
if err != nil {
|
||||
t.Fatalf("send session request: %v", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
if response.StatusCode != http.StatusUnauthorized {
|
||||
body, _ := io.ReadAll(response.Body)
|
||||
t.Fatalf(
|
||||
"expected invalid UTF-8 Basic credentials to return 401, "+
|
||||
"got %d: %s",
|
||||
response.StatusCode,
|
||||
body,
|
||||
)
|
||||
}
|
||||
if got := response.Header.Get("WWW-Authenticate"); got != `Basic realm="messenger", charset="UTF-8"` {
|
||||
t.Fatalf("unexpected Basic challenge: %q", got)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user