Files
mtusi2026lab5/internal/transport/rest/router_test.go
T
2026-10-29 23:36:12 +03:00

484 lines
17 KiB
Go

package rest_test
import (
"bytes"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
"mtusi-messenger/internal/domain"
"mtusi-messenger/internal/logger"
"mtusi-messenger/internal/transport/rest"
"mtusi-messenger/internal/transport/rest/mocks"
)
const (
requestIDHeader = "X-Request-ID"
instanceIDHeader = "X-Instance-Id"
)
func basic(username, password string) string {
return base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
}
func assertError(message string) error {
return errors.New(message)
}
type httpResult struct {
status int
header http.Header
body []byte
}
type routerFixture struct {
users *mocks.MockUserService
chats *mocks.MockChatService
messages *mocks.MockMessageService
attachments *mocks.MockAttachmentService
health *mocks.MockHealthChecker
sessions *mocks.MockSessionActions
server *httptest.Server
}
// testMaxBodyBytes is small on purpose: the limit test does not need a 256 KiB body.
const testMaxBodyBytes = 64 << 10
func newRouterFixture(t *testing.T) *routerFixture {
t.Helper()
fixture := &routerFixture{
users: mocks.NewMockUserService(t),
chats: mocks.NewMockChatService(t),
messages: mocks.NewMockMessageService(t),
attachments: mocks.NewMockAttachmentService(t),
health: mocks.NewMockHealthChecker(t),
sessions: mocks.NewMockSessionActions(t),
}
router, err := rest.NewRouter(
rest.NewHandler(
fixture.users,
fixture.chats,
fixture.messages,
fixture.attachments,
fixture.health,
fixture.sessions,
),
rest.NewSecurityHandler(fixture.sessions),
nil,
logger.New(logger.WithLevel(slog.LevelError)),
testMaxBodyBytes,
testMaxBodyBytes,
)
require.NoError(t, err)
fixture.server = httptest.NewServer(router)
t.Cleanup(fixture.server.Close)
return fixture
}
func (f *routerFixture) do(t *testing.T, method, path string, body []byte, headers map[string]string) httpResult {
t.Helper()
var reader io.Reader
if body != nil {
reader = bytes.NewReader(body)
}
req, err := http.NewRequestWithContext(t.Context(), method, f.server.URL+path, reader)
require.NoError(t, err)
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
for key, value := range headers {
req.Header.Set(key, value)
}
resp, err := f.server.Client().Do(req)
require.NoError(t, err)
defer func() { _ = resp.Body.Close() }()
payload, err := io.ReadAll(resp.Body)
require.NoError(t, err)
return httpResult{status: resp.StatusCode, header: resp.Header, body: payload}
}
func TestHealthEndpoints(t *testing.T) {
fixture := newRouterFixture(t)
fixture.health.EXPECT().Ping(mock.Anything).Return(nil).Maybe()
result := fixture.do(t, http.MethodGet, "/health/live", nil, nil)
require.Equal(t, http.StatusOK, result.status)
require.NotEmpty(t, result.header.Get(requestIDHeader))
require.JSONEq(t, `{"status":"ok"}`, string(result.body))
result = fixture.do(t, http.MethodGet, "/health/ready", nil, nil)
require.Equal(t, http.StatusOK, result.status)
}
func TestReadinessReturns503WhenDependencyDown(t *testing.T) {
fixture := newRouterFixture(t)
fixture.health.EXPECT().Ping(mock.Anything).Return(assertError("down")).Maybe()
result := fixture.do(t, http.MethodGet, "/health/ready", nil, nil)
require.Equal(t, http.StatusServiceUnavailable, result.status)
var body struct {
Error struct {
Code string `json:"code"`
} `json:"error"`
}
require.NoError(t, json.Unmarshal(result.body, &body))
require.Equal(t, "unavailable", body.Error.Code)
}
func TestRequestIDEchoedFromClient(t *testing.T) {
fixture := newRouterFixture(t)
result := fixture.do(t, http.MethodGet, "/health/live", nil, map[string]string{requestIDHeader: "from-client"})
require.Equal(t, "from-client", result.header.Get(requestIDHeader))
}
func TestProtectedEndpointRequiresBearer(t *testing.T) {
tests := map[string]map[string]string{
"без заголовка": nil,
"только X-User-Id": {"X-User-Id": uuid.NewString()},
"basic вместо bearer": {"Authorization": "Basic dXNlcjpwYXNz"},
}
for name, headers := range tests {
t.Run(name, func(t *testing.T) {
fixture := newRouterFixture(t)
result := fixture.do(t, http.MethodGet, "/api/v1/users/me", nil, headers)
require.Equal(t, http.StatusUnauthorized, result.status)
require.Contains(t, result.header.Get("WWW-Authenticate"), "Bearer")
})
}
}
func TestBearerSessionIsResolvedToCaller(t *testing.T) {
fixture := newRouterFixture(t)
user := domain.User{ID: uuid.New(), Username: "alice", DisplayName: "Алиса", CreatedAt: time.Now().UTC()}
fixture.sessions.EXPECT().Resolve(mock.Anything, "opaque-token").Return(user, nil).Once()
fixture.users.EXPECT().GetByID(mock.Anything, user.ID).Return(user, nil).Once()
result := fixture.do(t, http.MethodGet, "/api/v1/users/me", nil, map[string]string{"Authorization": "Bearer opaque-token"})
require.Equal(t, http.StatusOK, result.status)
var body map[string]any
require.NoError(t, json.Unmarshal(result.body, &body))
require.Equal(t, user.ID.String(), body["id"])
}
func TestUnknownBearerIsRejected(t *testing.T) {
fixture := newRouterFixture(t)
fixture.sessions.EXPECT().Resolve(mock.Anything, "unknown").Return(domain.User{}, domain.ErrUnauthenticated).Once()
result := fixture.do(t, http.MethodGet, "/api/v1/chats", nil, map[string]string{"Authorization": "Bearer unknown"})
require.Equal(t, http.StatusUnauthorized, result.status)
require.Contains(t, result.header.Get("WWW-Authenticate"), "Bearer")
}
func TestRegisterUserReturnsContractShape(t *testing.T) {
fixture := newRouterFixture(t)
user := domain.User{ID: uuid.New(), Username: "alice", DisplayName: "Алиса", CreatedAt: time.Now().UTC()}
draft := domain.UserDraft{Username: "alice", DisplayName: "Алиса", Password: "very-secret-password"}
fixture.users.EXPECT().Register(mock.Anything, draft).Return(user, nil).Once()
body, err := json.Marshal(map[string]string{"username": "alice", "display_name": "Алиса", "password": draft.Password})
require.NoError(t, err)
result := fixture.do(t, http.MethodPost, "/api/v1/users", body, nil)
require.Equal(t, http.StatusCreated, result.status)
require.NotContains(t, string(result.body), "password")
var decoded map[string]any
require.NoError(t, json.Unmarshal(result.body, &decoded))
require.Equal(t, user.ID.String(), decoded["id"])
require.Len(t, decoded, 4)
}
func TestRegisterDuplicateUsernameConflicts(t *testing.T) {
fixture := newRouterFixture(t)
fixture.users.EXPECT().Register(mock.Anything, mock.Anything).Return(domain.User{}, domain.ErrUsernameTaken).Once()
body, err := json.Marshal(map[string]string{"username": "alice", "display_name": "Алиса", "password": "very-secret-password"})
require.NoError(t, err)
result := fixture.do(t, http.MethodPost, "/api/v1/users", body, nil)
require.Equal(t, http.StatusConflict, result.status)
}
func TestCreateSessionFromBasicAuth(t *testing.T) {
fixture := newRouterFixture(t)
user := domain.User{ID: uuid.New(), Username: "alice", DisplayName: "Алиса", CreatedAt: time.Now().UTC()}
session := domain.Session{Token: "opaque-token", ExpiresAt: time.Now().UTC().Add(time.Hour), User: user}
fixture.sessions.EXPECT().Authenticate(mock.Anything, "alice", "very-secret-password").Return(user, nil).Once()
fixture.sessions.EXPECT().Create(mock.Anything, user).Return(session, nil).Once()
result := fixture.do(t, http.MethodPost, "/api/v1/auth/sessions", nil, map[string]string{
"Authorization": "Basic " + basic("alice", "very-secret-password"),
})
require.Equal(t, http.StatusCreated, result.status)
var body struct {
Token string `json:"token"`
TokenType string `json:"token_type"`
}
require.NoError(t, json.Unmarshal(result.body, &body))
require.Equal(t, "opaque-token", body.Token)
require.Equal(t, "Bearer", body.TokenType)
}
func TestCreateSessionRejectsBadCredentials(t *testing.T) {
fixture := newRouterFixture(t)
fixture.sessions.EXPECT().Authenticate(mock.Anything, mock.Anything, mock.Anything).Return(domain.User{}, domain.ErrUnauthenticated).Once()
result := fixture.do(t, http.MethodPost, "/api/v1/auth/sessions", nil, map[string]string{
"Authorization": "Basic " + basic("alice", "wrong-password-value"),
})
require.Equal(t, http.StatusUnauthorized, result.status)
require.Contains(t, result.header.Get("WWW-Authenticate"), "Basic")
}
func TestRevokeSession(t *testing.T) {
fixture := newRouterFixture(t)
user := domain.User{ID: uuid.New(), Username: "alice", DisplayName: "Алиса", CreatedAt: time.Now().UTC()}
fixture.sessions.EXPECT().Resolve(mock.Anything, "opaque-token").Return(user, nil).Once()
fixture.sessions.EXPECT().Revoke(mock.Anything, user.ID, "opaque-token").Return(nil).Once()
result := fixture.do(t, http.MethodDelete, "/api/v1/auth/sessions/current", nil, map[string]string{"Authorization": "Bearer opaque-token"})
require.Equal(t, http.StatusNoContent, result.status)
require.Empty(t, result.body)
}
func TestCursorRoundTrip(t *testing.T) {
fixture := newRouterFixture(t)
user := domain.User{ID: uuid.New(), Username: "alice", DisplayName: "Алиса", CreatedAt: time.Now().UTC()}
chatID := uuid.New()
message := domain.Message{ID: uuid.New(), ChatID: chatID, SenderID: user.ID, Text: "первое", CreatedAt: time.Now().UTC()}
fixture.sessions.EXPECT().Resolve(mock.Anything, "opaque-token").Return(user, nil).Maybe()
fixture.messages.EXPECT().
History(mock.Anything, user.ID, chatID, (*domain.Cursor)(nil), 1).
Return(domain.Page[domain.Message]{
Items: []domain.Message{message},
Next: &domain.Cursor{Scope: chatID, CreatedAt: message.CreatedAt, ID: message.ID},
}, nil).
Once()
result := fixture.do(t, http.MethodGet, "/api/v1/chats/"+chatID.String()+"/messages?limit=1", nil, map[string]string{"Authorization": "Bearer opaque-token"})
require.Equal(t, http.StatusOK, result.status)
var body struct {
Items []json.RawMessage `json:"items"`
NextCursor *string `json:"next_cursor"`
}
require.NoError(t, json.Unmarshal(result.body, &body))
require.Len(t, body.Items, 1)
require.NotNil(t, body.NextCursor)
fixture.messages.EXPECT().
History(mock.Anything, user.ID, chatID, mock.Anything, 1).
Return(domain.Page[domain.Message]{Items: []domain.Message{}}, nil).
Once()
result = fixture.do(
t,
http.MethodGet,
"/api/v1/chats/"+chatID.String()+"/messages?limit=1&cursor="+*body.NextCursor,
nil,
map[string]string{"Authorization": "Bearer opaque-token"},
)
require.Equal(t, http.StatusOK, result.status)
}
func TestInvalidCursorIsRejected(t *testing.T) {
fixture := newRouterFixture(t)
user := domain.User{ID: uuid.New(), Username: "alice", DisplayName: "Алиса", CreatedAt: time.Now().UTC()}
fixture.sessions.EXPECT().Resolve(mock.Anything, mock.Anything).Return(user, nil).Maybe()
result := fixture.do(
t,
http.MethodGet,
"/api/v1/chats/"+uuid.NewString()+"/messages?cursor=not-a-cursor",
nil,
map[string]string{"Authorization": "Bearer opaque-token"},
)
require.Equal(t, http.StatusBadRequest, result.status)
}
func TestNotFoundAndMethodNotAllowed(t *testing.T) {
fixture := newRouterFixture(t)
result := fixture.do(t, http.MethodGet, "/nope", nil, nil)
require.Equal(t, http.StatusNotFound, result.status)
result = fixture.do(t, http.MethodDelete, "/health/live", nil, nil)
require.Equal(t, http.StatusMethodNotAllowed, result.status)
}
func TestOversizedBodyIsRejectedWithPayloadTooLarge(t *testing.T) {
fixture := newRouterFixture(t)
// Тело больше лимита не читается и не декодируется: отказ приходит сразу,
// до обращения к сервисам.
body, err := json.Marshal(map[string]string{
"username": "alice",
"display_name": "Алиса",
"password": strings.Repeat("x", testMaxBodyBytes+1),
})
require.NoError(t, err)
result := fixture.do(t, http.MethodPost, "/api/v1/users", body, nil)
require.Equal(t, http.StatusRequestEntityTooLarge, result.status)
require.NotEmpty(t, result.header.Get(instanceIDHeader), "ответ об ошибке тоже помечен репликой")
require.NotEmpty(t, result.header.Get(requestIDHeader))
var decoded struct {
Error struct {
Code string `json:"code"`
} `json:"error"`
}
require.NoError(t, json.Unmarshal(result.body, &decoded))
require.Equal(t, "payload_too_large", decoded.Error.Code)
}
func TestCreateMessageRequiresIdempotencyKey(t *testing.T) {
fixture := newRouterFixture(t)
user := domain.User{ID: uuid.New(), Username: "alice", DisplayName: "Алиса", CreatedAt: time.Now().UTC()}
fixture.sessions.EXPECT().Resolve(mock.Anything, "opaque-token").Return(user, nil).Maybe()
result := fixture.do(
t,
http.MethodPost,
"/api/v1/chats/"+uuid.NewString()+"/messages",
[]byte(`{"text":"привет"}`),
map[string]string{"Authorization": "Bearer opaque-token"},
)
require.Equal(t, http.StatusBadRequest, result.status)
require.NotEmpty(t, result.header.Get(instanceIDHeader), "ответ об ошибке тоже помечен репликой")
}
func TestCreateMessageFingerprintIgnoresJSONFormatting(t *testing.T) {
fixture := newRouterFixture(t)
user := domain.User{ID: uuid.New(), Username: "alice", DisplayName: "Алиса", CreatedAt: time.Now().UTC()}
chatID := uuid.New()
message := domain.Message{ID: uuid.New(), ChatID: chatID, SenderID: user.ID, Text: "привет", CreatedAt: time.Now().UTC()}
fixture.sessions.EXPECT().Resolve(mock.Anything, "opaque-token").Return(user, nil).Maybe()
var fingerprints [][sha256.Size]byte
fixture.messages.EXPECT().
Send(mock.Anything, mock.MatchedBy(func(draft domain.MessageDraft) bool {
if draft.ChatID != chatID || draft.SenderID != user.ID || draft.Idempotency.Key != "key-1" {
return false
}
fingerprints = append(fingerprints, draft.Idempotency.RequestHash)
return true
})).
Return(message, nil)
headers := map[string]string{"Authorization": "Bearer opaque-token", "Idempotency-Key": "key-1"}
path := "/api/v1/chats/" + chatID.String() + "/messages"
first := fixture.do(t, http.MethodPost, path, []byte(`{"text":"привет"}`), headers)
replay := fixture.do(t, http.MethodPost, path, []byte(`{ "text" : "привет" }`), headers)
other := fixture.do(t, http.MethodPost, path, []byte(`{"text":"другое"}`), headers)
require.Equal(t, http.StatusCreated, first.status)
require.Equal(t, http.StatusCreated, replay.status)
require.Equal(t, http.StatusCreated, other.status)
require.NotEmpty(t, first.header.Get(instanceIDHeader))
require.Len(t, fingerprints, 3)
require.Equal(t, fingerprints[0], fingerprints[1],
"порядок ключей и пробелы в JSON не меняют отпечаток payload")
require.NotEqual(t, fingerprints[0], fingerprints[2],
"другой payload с тем же ключом — это конфликт, отпечатки обязаны различаться")
}
func TestCreateMessageReplayConflictIsReportedAsConflict(t *testing.T) {
fixture := newRouterFixture(t)
user := domain.User{ID: uuid.New(), Username: "alice", DisplayName: "Алиса", CreatedAt: time.Now().UTC()}
fixture.sessions.EXPECT().Resolve(mock.Anything, "opaque-token").Return(user, nil).Maybe()
fixture.messages.EXPECT().
Send(mock.Anything, mock.Anything).
Return(domain.Message{}, domain.ErrIdempotency).
Once()
result := fixture.do(
t,
http.MethodPost,
"/api/v1/chats/"+uuid.NewString()+"/messages",
[]byte(`{"text":"другой"}`),
map[string]string{"Authorization": "Bearer opaque-token", "Idempotency-Key": "key-1"},
)
require.Equal(t, http.StatusConflict, result.status)
var body struct {
Error struct {
Code string `json:"code"`
} `json:"error"`
}
require.NoError(t, json.Unmarshal(result.body, &body))
require.Equal(t, "conflict", body.Error.Code)
}
func TestEveryResponseCarriesInstanceID(t *testing.T) {
fixture := newRouterFixture(t)
user := domain.User{ID: uuid.New(), Username: "alice", DisplayName: "Алиса", CreatedAt: time.Now().UTC()}
fixture.sessions.EXPECT().Resolve(mock.Anything, "opaque-token").Return(user, nil).Maybe()
tests := map[string]httpResult{
"успешный ответ": fixture.do(t, http.MethodGet, "/health/live", nil, nil),
"неизвестный маршрут": fixture.do(t, http.MethodGet, "/nope", nil, nil),
"неподдерживаемый метод": fixture.do(t, http.MethodDelete, "/health/live", nil, nil),
"ошибка валидации схемы": fixture.do(
t,
http.MethodPost,
"/api/v1/chats/"+uuid.NewString()+"/messages",
[]byte(`{"text":"привет"}`),
map[string]string{"Authorization": "Bearer opaque-token"},
),
}
for name, result := range tests {
t.Run(name, func(t *testing.T) {
require.NotEmpty(t, result.header.Get(instanceIDHeader))
})
}
}