lab3
This commit is contained in:
@@ -2,6 +2,7 @@ package rest_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
@@ -9,6 +10,7 @@ import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -22,7 +24,10 @@ import (
|
||||
"mtusi-messenger/internal/transport/rest/mocks"
|
||||
)
|
||||
|
||||
const requestIDHeader = "X-Request-ID"
|
||||
const (
|
||||
requestIDHeader = "X-Request-ID"
|
||||
instanceIDHeader = "X-Instance-Id"
|
||||
)
|
||||
|
||||
func basic(username, password string) string {
|
||||
return base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
|
||||
@@ -48,6 +53,9 @@ type routerFixture struct {
|
||||
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()
|
||||
|
||||
@@ -63,6 +71,7 @@ func newRouterFixture(t *testing.T) *routerFixture {
|
||||
rest.NewHandler(fixture.users, fixture.chats, fixture.messages, fixture.health, fixture.sessions),
|
||||
rest.NewSecurityHandler(fixture.sessions),
|
||||
logger.New(logger.WithLevel(slog.LevelError)),
|
||||
testMaxBodyBytes,
|
||||
)
|
||||
require.NoError(t, err)
|
||||
|
||||
@@ -324,3 +333,140 @@ func TestNotFoundAndMethodNotAllowed(t *testing.T) {
|
||||
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))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user