package httpapi import ( "context" "errors" "fmt" "io" "log/slog" "net/http" "net/http/httptest" "strings" "testing" "time" "github.com/stretchr/testify/suite" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/messenger/attachment" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/model" "gitea.privcloud.tech/dizi/mtusi2026lab7/internal/password" ) var errDependency = errors.New("dependency unavailable") type MessengerSuite struct { suite.Suite logger *slog.Logger } func TestMessengerSuite(t *testing.T) { suite.Run(t, new(MessengerSuite)) } func (s *MessengerSuite) SetupTest() { s.logger = slog.New(slog.NewTextHandler(io.Discard, nil)) } type messengerStoreStub struct { pingErr error userByID model.User userByIDErr error credentials model.UserCredentials credentialsErr error message model.Message messageReplay bool messageErr error updatePasswordHash func(context.Context, string, string, string) (bool, error) } func (s messengerStoreStub) Ping(context.Context) error { return s.pingErr } func (messengerStoreStub) CreateUser(context.Context, string, string, string) (model.User, error) { return model.User{}, nil } func (s messengerStoreStub) UserByID(context.Context, string) (model.User, error) { return s.userByID, s.userByIDErr } func (s messengerStoreStub) UserByUsername(context.Context, string) (model.UserCredentials, error) { return s.credentials, s.credentialsErr } func (s messengerStoreStub) UpdatePasswordHash(ctx context.Context, userID, previousHash, passwordHash string) (bool, error) { if s.updatePasswordHash == nil { return false, nil } return s.updatePasswordHash(ctx, userID, previousHash, passwordHash) } func (messengerStoreStub) CreateChat(context.Context, string, []string, string) (model.Chat, error) { return model.Chat{}, nil } func (messengerStoreStub) ChatForUser(context.Context, string, string) (model.Chat, error) { return model.Chat{}, nil } func (messengerStoreStub) ListChats(context.Context, string, *model.Position, int) ([]model.Chat, bool, error) { return nil, false, nil } func (s messengerStoreStub) CreateMessage(context.Context, string, string, string, []string, string, time.Duration) (model.Message, bool, error) { return s.message, s.messageReplay, s.messageErr } func (messengerStoreStub) ListMessages(context.Context, string, string, *model.Position, int) ([]model.Message, bool, error) { return nil, false, nil } type objectStoreStub struct { pingErr error } func (s objectStoreStub) Ping(context.Context) error { return s.pingErr } type attachmentServiceStub struct { uploaded model.Attachment err error } func (s attachmentServiceStub) Upload(context.Context, attachment.Upload) (model.Attachment, error) { return s.uploaded, s.err } func (s attachmentServiceStub) Metadata(context.Context, string, string) (model.Attachment, error) { return s.uploaded, s.err } func (s attachmentServiceStub) Content(context.Context, string, string, string) (attachment.Content, error) { return attachment.Content{ Attachment: s.uploaded, Variant: model.Variant{ContentType: s.uploaded.ContentType, SizeBytes: s.uploaded.SizeBytes}, Body: io.NopCloser(strings.NewReader("content")), }, s.err } type sessionStub struct { pingErr error userID string userIDErr error } func (s sessionStub) Ping(context.Context) error { return s.pingErr } func (sessionStub) Create(context.Context, string, time.Duration) (string, time.Time, error) { return "token", time.Now().Add(time.Hour), nil } func (s sessionStub) UserID(context.Context, string) (string, error) { return s.userID, s.userIDErr } func (sessionStub) Delete(context.Context, string) error { return nil } type passwordsStub struct { verified bool err error hash string hashErr error needsRehash bool needsRehashErr error } func (s passwordsStub) Hash(string) (string, error) { if s.hash == "" { return "hash", s.hashErr } return s.hash, s.hashErr } func (passwordsStub) DummyHash() string { return "hash" } func (s passwordsStub) Verify(string, string) (bool, error) { return s.verified, s.err } func (s passwordsStub) NeedsRehash(string) (bool, error) { return s.needsRehash, s.needsRehashErr } type loginLimiterStub struct { allowed bool retryAfter time.Duration err error } func (s loginLimiterStub) Allow(context.Context, string, string) (bool, time.Duration, error) { return s.allowed, s.retryAfter, s.err } func (s *MessengerSuite) TestReadinessReturnsUnavailableForDependencyFailure() { t := s.T() tests := []struct { name string store messengerStoreStub sessions sessionStub objects objectStoreStub }{ {name: "postgres", store: messengerStoreStub{pingErr: errDependency}}, {name: "valkey", sessions: sessionStub{pingErr: errDependency}}, {name: "s3", objects: objectStoreStub{pingErr: errDependency}}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { server := s.server(tt.store, tt.sessions, passwordsStub{}, tt.objects, attachmentServiceStub{}) response := serveHealthRequest(server, http.MethodGet, "/health/ready") if response.Code != http.StatusServiceUnavailable { t.Fatalf("status = %d, want %d", response.Code, http.StatusServiceUnavailable) } }) } } func (s *MessengerSuite) TestHealthHandlerDoesNotExposeBusinessAPI() { server := s.newTestServer(messengerStoreStub{}, sessionStub{}, passwordsStub{}) response := serveHealthRequest(server, http.MethodGet, "/api/v1/users/me") s.Equal(http.StatusNotFound, response.Code) } func (s *MessengerSuite) TestMetricsHandlerOnlyExposesMetrics() { server := s.newTestServer(messengerStoreStub{}, sessionStub{}, passwordsStub{}) server.metrics.handler = http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNoContent) }) metrics := httptest.NewRecorder() server.MetricsHandler().ServeHTTP(metrics, httptest.NewRequest(http.MethodGet, "/metrics", nil)) s.Equal(http.StatusNoContent, metrics.Code) for _, path := range []string{"/health/ready", "/api/v1/users/me"} { response := httptest.NewRecorder() server.MetricsHandler().ServeHTTP(response, httptest.NewRequest(http.MethodGet, path, nil)) s.Equal(http.StatusNotFound, response.Code, path) } s.Equal(http.StatusNotFound, serveRequest(server, http.MethodGet, "/metrics", "").Code) } func (s *MessengerSuite) TestBusinessRequestReturnsUnavailableForDependencyFailure() { t := s.T() tests := []struct { name string store messengerStoreStub sessions sessionStub }{ {name: "valkey", sessions: sessionStub{userIDErr: errDependency}}, {name: "postgres", store: messengerStoreStub{userByIDErr: errDependency}, sessions: sessionStub{userID: "user-id"}}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { server := s.newTestServer(tt.store, tt.sessions, passwordsStub{}) request := httptest.NewRequest(http.MethodGet, "/api/v1/users/me", nil) request.Header.Set("Authorization", "Bearer valid-token") response := httptest.NewRecorder() server.Handler().ServeHTTP(response, request) if response.Code != http.StatusServiceUnavailable { t.Fatalf("status = %d, want %d", response.Code, http.StatusServiceUnavailable) } }) } } func (s *MessengerSuite) TestAuthenticationChallenges() { t := s.T() server := s.newTestServer(messengerStoreStub{}, sessionStub{}, passwordsStub{}) bearer := serveRequest(server, http.MethodGet, "/api/v1/users/me", "") if bearer.Code != http.StatusUnauthorized || bearer.Header().Get("WWW-Authenticate") != `Bearer realm="messenger"` { t.Fatalf("business challenge = %d %q", bearer.Code, bearer.Header().Get("WWW-Authenticate")) } store := messengerStoreStub{credentials: model.UserCredentials{PasswordHash: "hash"}} server = s.newTestServer(store, sessionStub{}, passwordsStub{verified: false}) request := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", nil) request.SetBasicAuth("user", "wrong-password") response := httptest.NewRecorder() server.Handler().ServeHTTP(response, request) if response.Code != http.StatusUnauthorized || response.Header().Get("WWW-Authenticate") != `Basic realm="messenger", charset="UTF-8"` { t.Fatalf("session challenge = %d %q", response.Code, response.Header().Get("WWW-Authenticate")) } } func (s *MessengerSuite) TestSessionCreationReturnsRateLimitWithRetryAfter() { server := s.serverWithLoginLimiter( messengerStoreStub{}, sessionStub{}, passwordsStub{}, loginLimiterStub{retryAfter: 1500 * time.Millisecond}, ) request := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", nil) request.SetBasicAuth("student", "T3st-password-123") response := httptest.NewRecorder() server.Handler().ServeHTTP(response, request) s.Equal(http.StatusTooManyRequests, response.Code) s.Equal("2", response.Header().Get("Retry-After")) s.Contains(response.Body.String(), `"code":"rate_limited"`) } func (s *MessengerSuite) TestPasswordOperationLimitReturnsRateLimit() { registration := s.newTestServer(messengerStoreStub{}, sessionStub{}, passwordsStub{hashErr: password.ErrBusy}) response := serveRequest(registration, http.MethodPost, "/api/v1/users", `{"username":"student","display_name":"Student","password":"T3st-password-123"}`) s.Equal(http.StatusTooManyRequests, response.Code) s.Equal("1", response.Header().Get("Retry-After")) store := messengerStoreStub{credentials: model.UserCredentials{PasswordHash: "hash"}} login := s.newTestServer(store, sessionStub{}, passwordsStub{err: password.ErrBusy}) request := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", nil) request.SetBasicAuth("student", "T3st-password-123") response = httptest.NewRecorder() login.Handler().ServeHTTP(response, request) s.Equal(http.StatusTooManyRequests, response.Code) s.Equal("1", response.Header().Get("Retry-After")) } func (s *MessengerSuite) TestSessionCreationRehashesPasswordWithCompareAndSwap() { var updated []string store := messengerStoreStub{ credentials: model.UserCredentials{User: model.User{ID: "user-id"}, PasswordHash: "old-hash"}, updatePasswordHash: func(_ context.Context, userID, previousHash, passwordHash string) (bool, error) { updated = []string{userID, previousHash, passwordHash} return true, nil }, } server := s.newTestServer(store, sessionStub{}, passwordsStub{ verified: true, needsRehash: true, hash: "new-hash", }) request := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", nil) request.SetBasicAuth("student", "T3st-password-123") response := httptest.NewRecorder() server.Handler().ServeHTTP(response, request) s.Equal(http.StatusCreated, response.Code) s.Equal([]string{"user-id", "old-hash", "new-hash"}, updated) } func (s *MessengerSuite) TestLoginSourceUsesAddressAppendedByIngress() { request := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", nil) request.Header.Set("X-Forwarded-For", "203.0.113.9, 198.51.100.7") s.Equal("198.51.100.7", loginSource(request)) } func (s *MessengerSuite) TestAttachmentContentAuthenticatesBeforeVariantValidation() { server := s.newTestServer(messengerStoreStub{}, sessionStub{}, passwordsStub{}) response := serveRequest( server, http.MethodGet, "/api/v1/attachments/00000000-0000-0000-0000-000000000001/content?variant=invalid", "", ) s.Equal(http.StatusUnauthorized, response.Code) s.Equal(`Bearer realm="messenger"`, response.Header().Get("WWW-Authenticate")) } func (s *MessengerSuite) TestSessionCreationRejectsChunkedBody() { t := s.T() server := s.newTestServer(messengerStoreStub{}, sessionStub{}, passwordsStub{}) request := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", strings.NewReader("{}")) request.ContentLength = -1 request.SetBasicAuth("user", "password") response := httptest.NewRecorder() server.Handler().ServeHTTP(response, request) if response.Code != http.StatusBadRequest { t.Fatalf("status = %d, want %d", response.Code, http.StatusBadRequest) } } func (s *MessengerSuite) TestRegistrationRejectsWhitespacePassword() { t := s.T() server := s.newTestServer(messengerStoreStub{}, sessionStub{}, passwordsStub{}) response := serveRequest(server, http.MethodPost, "/api/v1/users", `{"username":"student","display_name":"Student","password":" "}`) if response.Code != http.StatusBadRequest { t.Fatalf("status = %d, want %d", response.Code, http.StatusBadRequest) } } func (s *MessengerSuite) TestInstanceHeaderIsSetOnSuccessAndError() { t := s.T() server := s.newTestServer(messengerStoreStub{}, sessionStub{}, passwordsStub{}) for _, response := range []*httptest.ResponseRecorder{ serveRequest(server, http.MethodGet, "/health/live", ""), serveRequest(server, http.MethodGet, "/api/v1/users/me", ""), } { if value := response.Header().Get("X-Instance-Id"); value != "test-instance" { t.Fatalf("X-Instance-Id = %q, want test-instance", value) } } } func (s *MessengerSuite) TestMessageCreationValidatesIdempotencyKey() { t := s.T() store := messengerStoreStub{userByID: model.User{ID: "user-id"}} server := s.newTestServer(store, sessionStub{userID: "user-id"}, passwordsStub{}) tests := []struct { name string key string }{ {name: "missing"}, {name: "invalid", key: "invalid key"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { request := httptest.NewRequest(http.MethodPost, "/api/v1/chats/00000000-0000-0000-0000-000000000001/messages", strings.NewReader(`{"text":"message"}`)) request.Header.Set("Authorization", "Bearer valid-token") request.Header.Set("Content-Type", "application/json") if tt.key != "" { request.Header.Set("Idempotency-Key", tt.key) } response := httptest.NewRecorder() server.Handler().ServeHTTP(response, request) if response.Code != http.StatusBadRequest { t.Fatalf("status = %d, want %d", response.Code, http.StatusBadRequest) } }) } } func (s *MessengerSuite) TestMessageCreationValidatesFieldPresenceAndTypes() { store := messengerStoreStub{userByID: model.User{ID: "user-id"}} server := s.newTestServer(store, sessionStub{userID: "user-id"}, passwordsStub{}) attachmentID := "00000000-0000-0000-0000-000000000002" invalidBodies := []string{ `{"attachment_ids":["` + attachmentID + `"]}`, `{"text":null,"attachment_ids":["` + attachmentID + `"]}`, `{"text":"x","attachment_ids":null}`, `{"text":1}`, `{"text":"x","attachment_ids":{}}`, } for _, body := range invalidBodies { response := createMessageRequestResponse(server, body) s.Equal(http.StatusBadRequest, response.Code, body) } validBodies := []string{ `{"text":"message"}`, `{"text":"message","attachment_ids":[]}`, `{"text":"","attachment_ids":["` + attachmentID + `"]}`, } for _, body := range validBodies { response := createMessageRequestResponse(server, body) s.Equal(http.StatusCreated, response.Code, body) } } func createMessageRequestResponse(server *Server, body string) *httptest.ResponseRecorder { request := httptest.NewRequest( http.MethodPost, "/api/v1/chats/00000000-0000-0000-0000-000000000001/messages", strings.NewReader(body), ) request.Header.Set("Authorization", "Bearer valid-token") request.Header.Set("Content-Type", "application/json") request.Header.Set("Idempotency-Key", "message-key") response := httptest.NewRecorder() server.Handler().ServeHTTP(response, request) return response } func (s *MessengerSuite) TestMessageCreationReturnsConflictForReusedKeyWithDifferentBody() { t := s.T() store := messengerStoreStub{ userByID: model.User{ID: "user-id"}, messageErr: fmt.Errorf("create message: %w", model.ErrIdempotencyConflict), } server := s.newTestServer(store, sessionStub{userID: "user-id"}, passwordsStub{}) request := httptest.NewRequest(http.MethodPost, "/api/v1/chats/00000000-0000-0000-0000-000000000001/messages", strings.NewReader(`{"text":"different"}`)) request.Header.Set("Authorization", "Bearer valid-token") request.Header.Set("Content-Type", "application/json") request.Header.Set("Idempotency-Key", "same-key") response := httptest.NewRecorder() server.Handler().ServeHTTP(response, request) if response.Code != http.StatusConflict { t.Fatalf("status = %d, want %d", response.Code, http.StatusConflict) } } func (s *MessengerSuite) TestAttachmentFilenameValidation() { for _, filename := range []string{"", " ", "../photo.png", "dir\\photo.png", "photo\x00.png", "photo\n.png"} { _, valid := attachmentFilename(map[string][]string{"filename": {filename}}) s.False(valid, filename) } filename, valid := attachmentFilename(map[string][]string{"filename": {"фото.png"}}) s.True(valid) s.Equal("фото.png", filename) } func (s *MessengerSuite) TestUploadRejectsMalformedQuery() { store := messengerStoreStub{userByID: model.User{ID: "user-id"}} server := s.newTestServer(store, sessionStub{userID: "user-id"}, passwordsStub{}) request := httptest.NewRequest( http.MethodPost, "/api/v1/chats/00000000-0000-0000-0000-000000000002/attachments?filename=photo.png&junk=%GG", strings.NewReader("image"), ) request.Header.Set("Authorization", "Bearer valid-token") request.Header.Set("Content-Type", "image/png") response := httptest.NewRecorder() server.Handler().ServeHTTP(response, request) s.Equal(http.StatusBadRequest, response.Code) } func (s *MessengerSuite) newTestServer(store messengerStoreStub, sessions SessionStore, passwords PasswordService) *Server { return s.server(store, sessions, passwords, objectStoreStub{}, attachmentServiceStub{}) } func (s *MessengerSuite) server( store messengerStoreStub, sessions SessionStore, passwords PasswordService, objects objectStoreStub, attachments AttachmentService, ) *Server { return s.serverWithDependencies( store, sessions, passwords, loginLimiterStub{allowed: true}, objects, attachments, ) } func (s *MessengerSuite) serverWithLoginLimiter( store messengerStoreStub, sessions SessionStore, passwords PasswordService, limiter LoginLimiter, ) *Server { return s.serverWithDependencies( store, sessions, passwords, limiter, objectStoreStub{}, attachmentServiceStub{}, ) } func (s *MessengerSuite) serverWithDependencies( store messengerStoreStub, sessions SessionStore, passwords PasswordService, limiter LoginLimiter, objects objectStoreStub, attachments AttachmentService, ) *Server { return NewServer(s.logger, Dependencies{ Users: store, Chats: store, Messages: store, Attachments: attachments, Sessions: sessions, Passwords: passwords, LoginLimiter: limiter, Database: store, Objects: objects, }, Config{ SessionTTL: time.Hour, IdempotencyTTL: 24 * time.Hour, RequestTTL: time.Second, InstanceID: "test-instance", SwaggerPort: "8081", }) } func serveRequest(server *Server, method, path, body string) *httptest.ResponseRecorder { request := httptest.NewRequest(method, path, strings.NewReader(body)) if body != "" { request.Header.Set("Content-Type", "application/json") } response := httptest.NewRecorder() server.Handler().ServeHTTP(response, request) return response } func serveHealthRequest(server *Server, method, path string) *httptest.ResponseRecorder { request := httptest.NewRequest(method, path, nil) response := httptest.NewRecorder() server.HealthHandler().ServeHTTP(response, request) return response }