ЛР 6 — БПИ2302 — Нурлыгаянова — на 3

This commit is contained in:
Nurlygayanova Ekaterina
2026-11-13 11:32:45 +03:00
parent 470d9d6f1e
commit 69a190be0e
164 changed files with 25947 additions and 29 deletions
+115
View File
@@ -0,0 +1,115 @@
package http
import (
"bytes"
"io"
"net/http"
"strings"
"testing"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto"
)
func TestAccess_ForeignChat(t *testing.T) {
r := newTestRig(t)
_, _, eve, chat := bootstrap(r)
base := "/api/v1/chats/" + chat.ID
cases := []struct {
method, path string
body any
}{
{http.MethodGet, base, nil},
{http.MethodGet, base + "/messages?limit=10", nil},
{http.MethodPost, base + "/messages", textMessage("вторжение")},
}
for _, tc := range cases {
var resp *http.Response
if tc.body == nil {
resp = r.do(tc.method, tc.path, eve.ID, nil, nil)
} else {
resp = r.doJSON(tc.method, tc.path, eve.ID, tc.body)
}
if resp.StatusCode != http.StatusNotFound {
data, _ := io.ReadAll(resp.Body)
resp.Body.Close()
t.Fatalf("%s %s expected 404, got %d; body=%s", tc.method, tc.path, resp.StatusCode, string(data))
}
e := readError(t, resp)
if e.Error.Code != CodeNotFound {
t.Fatalf("%s %s expected code %q, got %q", tc.method, tc.path, CodeNotFound, e.Error.Code)
}
}
resp := r.do(http.MethodGet, "/api/v1/chats?limit=100", eve.ID, nil, nil)
expectStatus(t, resp, http.StatusOK)
var page dto.ChatsPageResponse
readJSON(t, resp, &page)
for _, item := range page.Items {
if item.ID == chat.ID {
t.Fatalf("чат утёк в список чужого пользователя")
}
}
}
func TestAccess_AuthBeforeContentType(t *testing.T) {
r := newTestRig(t)
resp := r.do(http.MethodPost, "/api/v1/chats", "",
map[string]string{"Content-Type": "text/plain"}, strings.NewReader("x"))
expectStatus(t, resp, http.StatusUnauthorized)
resp.Body.Close()
resp = r.do(http.MethodPost, "/api/v1/nope", "", nil, strings.NewReader("x"))
expectStatus(t, resp, http.StatusNotFound)
if resp.Header.Get("X-Request-Id") == "" {
t.Fatal("404 without X-Request-Id")
}
resp.Body.Close()
}
func TestAccess_RouterErrors(t *testing.T) {
r := newTestRig(t)
alice, _, _, chat := bootstrap(r)
chatPath := "/api/v1/chats/" + chat.ID
cases := []struct {
method, path, actor string
status int
code, message string
}{
{http.MethodGet, "/nope", "", http.StatusNotFound, CodeNotFound, "Object not found"},
{http.MethodGet, "/health/live/", "", http.StatusNotFound, CodeNotFound, "Object not found"},
{http.MethodGet, "/api/v1/nope", alice.ID, http.StatusNotFound, CodeNotFound, "Object not found"},
{http.MethodPost, "/health/live", "", http.StatusMethodNotAllowed, CodeInvalidRequest, "Method not allowed"},
{http.MethodGet, "/api/v1/users", "", http.StatusMethodNotAllowed, CodeInvalidRequest, "Method not allowed"},
{http.MethodPost, "/api/v1/users/me", "", http.StatusMethodNotAllowed, CodeInvalidRequest, "Method not allowed"},
{http.MethodDelete, "/api/v1/users/me", alice.ID, http.StatusMethodNotAllowed, CodeInvalidRequest, "Method not allowed"},
{http.MethodDelete, "/api/v1/chats", alice.ID, http.StatusMethodNotAllowed, CodeInvalidRequest, "Method not allowed"},
{http.MethodPut, chatPath, alice.ID, http.StatusMethodNotAllowed, CodeInvalidRequest, "Method not allowed"},
{http.MethodPatch, chatPath + "/messages", alice.ID, http.StatusMethodNotAllowed, CodeInvalidRequest, "Method not allowed"},
}
for _, tc := range cases {
var body io.Reader
headers := map[string]string{}
if tc.method == http.MethodPost || tc.method == http.MethodPut || tc.method == http.MethodPatch {
body = bytes.NewReader([]byte(`{}`))
headers["Content-Type"] = "application/json"
}
resp := r.do(tc.method, tc.path, tc.actor, headers, body)
if resp.StatusCode != tc.status {
data, _ := io.ReadAll(resp.Body)
resp.Body.Close()
t.Fatalf("%s %s: expected %d, got %d; body=%s", tc.method, tc.path, tc.status, resp.StatusCode, string(data))
}
if tc.status == http.StatusMethodNotAllowed && resp.Header.Get("Allow") == "" {
t.Fatalf("%s %s: 405 без заголовка Allow", tc.method, tc.path)
}
e := readError(t, resp)
if e.Error.Code != tc.code || e.Error.Message != tc.message {
t.Fatalf("%s %s: expected %q/%q, got %q/%q", tc.method, tc.path, tc.code, tc.message, e.Error.Code, e.Error.Message)
}
if e.Error.RequestID == "" || e.Error.RequestID != resp.Header.Get("X-Request-Id") {
t.Fatalf("%s %s: request_id %q не совпадает с заголовком %q", tc.method, tc.path, e.Error.RequestID, resp.Header.Get("X-Request-Id"))
}
}
}
+134
View File
@@ -0,0 +1,134 @@
package http
import (
"context"
"io"
"mime"
"net/http"
"strconv"
"time"
"github.com/labstack/echo/v4"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/middleware"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/service"
)
// routeUploadAttachment освобождён от общего лимита тела: свой лимит применяется в сервисе, после
// аутентификации и проверки доступа.
const routeUploadAttachment = "/api/v1/chats/:chat_id/attachments"
// transferTimeout — предел на передачу одного файла. Общие таймауты сервера (10 с) рассчитаны на
// JSON и оборвали бы загрузку 10 МиБ на медленном канале. Предел обязателен: иначе медленный клиент
// занимал бы слот загрузки неограниченно долго.
const transferTimeout = 60 * time.Second
type attachmentsHandler struct {
attachments service.AttachmentsService
}
// rejectedBodyDrainLimit — сколько байт отклонённой загрузки дочитывается впустую. Клиент обычно
// сначала отправляет всё тело и только потом читает ответ: если перестать читать, он зависнет и
// вместо 413 получит обрыв. Дочитывание идёт в никуда, поэтому память не расходует, а его время
// ограничено transferTimeout. Тело больше этого предела приводит к закрытию соединения.
const rejectedBodyDrainLimit = 64 << 20
func extendDeadlines(c echo.Context) {
rc := http.NewResponseController(c.Response())
deadline := time.Now().Add(transferTimeout)
// Ошибка значит, что соединение не поддерживает дедлайны: тогда действуют общие таймауты.
_ = rc.SetReadDeadline(deadline)
_ = rc.SetWriteDeadline(deadline)
}
// uploadTransfer стоит снаружи аутентификации, поэтому покрывает и отказы 401. Небольшой ответ об
// ошибке остаётся в буфере сервера и уходит клиенту после дочитывания.
func uploadTransfer(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
extendDeadlines(c)
err := next(c)
_, _ = io.CopyN(io.Discard, c.Request().Body, rejectedBodyDrainLimit)
return err
}
}
func (h *attachmentsHandler) upload(c echo.Context) error {
req := c.Request()
// Несколько filename неоднозначны: пустое значение сервис отклонит как неверное имя.
var filename string
if values := c.QueryParams()["filename"]; len(values) == 1 {
filename = values[0]
}
att, err := h.attachments.Upload(req.Context(), service.UploadInput{
CallerID: c.Get(middleware.AuthUserIDKey).(string),
ChatID: c.Param("chat_id"),
Filename: filename,
ContentType: req.Header.Get(echo.HeaderContentType),
ContentLength: req.ContentLength,
Body: req.Body,
})
if err != nil {
return WriteError(c, err)
}
return c.JSON(http.StatusAccepted, toAttachmentResponse(att))
}
func (h *attachmentsHandler) get(c echo.Context) error {
att, err := h.attachments.Get(c.Request().Context(), c.Get(middleware.AuthUserIDKey).(string), c.Param("attachment_id"))
if err != nil {
return WriteError(c, err)
}
return c.JSON(http.StatusOK, toAttachmentResponse(att))
}
func (h *attachmentsHandler) content(c echo.Context) error {
extendDeadlines(c)
variant := service.VariantOriginal
if values, ok := c.QueryParams()["variant"]; ok {
variant = values[0]
}
ctx, cancel := context.WithTimeout(c.Request().Context(), transferTimeout)
defer cancel()
att, body, err := h.attachments.Content(ctx, c.Get(middleware.AuthUserIDKey).(string), c.Param("attachment_id"), variant)
if err != nil {
return WriteError(c, err)
}
defer body.Close()
header := c.Response().Header()
header.Set(echo.HeaderContentLength, strconv.FormatInt(att.SizeBytes, 10))
// Файл загрузил пользователь: браузер не должен угадывать тип или показывать его как страницу.
header.Set("X-Content-Type-Options", "nosniff")
header.Set("Cache-Control", "private, no-store")
if cd := mime.FormatMediaType("attachment", map[string]string{"filename": att.Filename}); cd != "" {
header.Set(echo.HeaderContentDisposition, cd)
} else {
header.Set(echo.HeaderContentDisposition, "attachment")
}
// Обрыв после начала передачи клиент увидит как неполный ответ: длина объявлена заранее.
return c.Stream(http.StatusOK, att.ContentType, body)
}
func toAttachmentResponse(a domain.Attachment) dto.AttachmentResponse {
variants := make([]dto.VariantResponse, 0, len(a.Variants))
for _, v := range a.Variants {
variants = append(variants, dto.VariantResponse{Name: v.Name, ContentType: v.ContentType, SizeBytes: v.SizeBytes, Width: v.Width, Height: v.Height, SHA256: v.SHA256})
}
return dto.AttachmentResponse{
ID: a.ID,
ChatID: a.ChatID,
OwnerID: a.OwnerID,
Filename: a.Filename,
ContentType: a.ContentType,
SizeBytes: a.SizeBytes,
SHA256: a.SHA256,
Status: a.Status,
Variants: variants,
ErrorCode: a.ErrorCode,
CreatedAt: dto.NewTimestamp(a.CreatedAt),
UpdatedAt: dto.NewTimestamp(a.UpdatedAt),
}
}
+546
View File
@@ -0,0 +1,546 @@
package http
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"image"
"image/jpeg"
"image/png"
"io"
"log/slog"
"net/http"
"net/url"
"os"
"strings"
"testing"
"github.com/google/uuid"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/objectstore"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/service"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate"
)
func testPNG(t *testing.T, w, h int) []byte {
t.Helper()
var b bytes.Buffer
if err := png.Encode(&b, image.NewRGBA(image.Rect(0, 0, w, h))); err != nil {
t.Fatal(err)
}
return b.Bytes()
}
func testJPEG(t *testing.T) []byte {
t.Helper()
var b bytes.Buffer
if err := jpeg.Encode(&b, image.NewRGBA(image.Rect(0, 0, 8, 8)), nil); err != nil {
t.Fatal(err)
}
return b.Bytes()
}
func (r *testRig) upload(actor, chatID, filename, contentType string, data []byte) *http.Response {
r.t.Helper()
return r.do(http.MethodPost, "/api/v1/chats/"+chatID+"/attachments?filename="+url.QueryEscape(filename), actor,
map[string]string{"Content-Type": contentType}, bytes.NewReader(data))
}
func (r *testRig) uploadOK(actor, chatID string, data []byte) dto.AttachmentResponse {
r.t.Helper()
resp := r.upload(actor, chatID, "photo.png", "image/png", data)
expectStatus(r.t, resp, http.StatusAccepted)
var att dto.AttachmentResponse
readJSON(r.t, resp, &att)
return att
}
func TestAttachment_QueuedIsDurableAndNotDownloadable(t *testing.T) {
r := newTestRig(t)
alice, bob, eve, chat := bootstrap(r)
data := testPNG(t, 16, 16)
att := r.uploadOK(alice.ID, chat.ID, data)
sum := sha256.Sum256(data)
if att.Status != "queued" || att.SHA256 != hex.EncodeToString(sum[:]) || att.SizeBytes != int64(len(data)) ||
att.OwnerID != alice.ID || att.ChatID != chat.ID || att.ErrorCode != nil || att.Variants == nil {
t.Errorf("metadata = %+v", att)
}
resp := r.do(http.MethodGet, "/api/v1/attachments/"+att.ID+"/content", bob.ID, nil, nil)
expectStatus(t, resp, http.StatusConflict)
resp.Body.Close()
// Queued data is already in durable staging; API has not published final objects.
stored, _, err := r.objects.Get(context.Background(), "staging/"+att.ID)
if err != nil {
t.Fatal(err)
}
defer stored.Close()
got, _ := io.ReadAll(stored)
if !bytes.Equal(got, data) {
t.Fatal("staging bytes differ")
}
for _, suffix := range []string{"", "/content"} {
resp := r.do(http.MethodGet, "/api/v1/attachments/"+att.ID+suffix, eve.ID, nil, nil)
expectStatus(t, resp, http.StatusNotFound)
resp.Body.Close()
}
}
func TestAttachment_ObjectKeyIsServerAssignedAndHidden(t *testing.T) {
r := newTestRig(t)
alice, _, _, chat := bootstrap(r)
resp := r.upload(alice.ID, chat.ID, "evil..name.png", "image/png", testPNG(t, 2, 2))
expectStatus(t, resp, http.StatusAccepted)
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
keys := r.objects.Keys()
if len(keys) != 1 || strings.Contains(keys[0], "evil") {
t.Fatalf("object keys = %v", keys)
}
if bytes.Contains(body, []byte(keys[0])) || bytes.Contains(body, []byte("object_key")) {
t.Errorf("response exposes object key: %s", body)
}
}
func TestAttachment_Rejections(t *testing.T) {
r := newTestRig(t)
alice, _, eve, chat := bootstrap(r)
valid := testPNG(t, 4, 4)
oversized := append(bytes.Clone(valid), make([]byte, testMaxUploadBytes)...)
cases := []struct {
name string
actor string
chat string
filename string
contentType string
data []byte
want int
}{
{"outsider", eve.ID, chat.ID, "a.png", "image/png", valid, 404},
{"outsider sees 404 before size check", eve.ID, chat.ID, "a.png", "image/png", oversized, 404},
{"unknown chat", alice.ID, uuid.NewString(), "a.png", "image/png", valid, 404},
{"bad chat id", alice.ID, "nope", "a.png", "image/png", valid, 400},
{"path in filename", alice.ID, chat.ID, "../a.png", "image/png", valid, 400},
{"backslash in filename", alice.ID, chat.ID, `a\b.png`, "image/png", valid, 400},
{"NUL in filename", alice.ID, chat.ID, "a\x00.png", "image/png", valid, 400},
{"empty filename", alice.ID, chat.ID, "", "image/png", valid, 400},
{"too many bytes", alice.ID, chat.ID, "a.png", "image/png", oversized, 413},
{"too many pixels", alice.ID, chat.ID, "a.png", "image/png", testPNG(t, 101, 100), 413},
{"wrong declared type", alice.ID, chat.ID, "a.png", "application/json", valid, 415},
{"no declared type", alice.ID, chat.ID, "a.png", "", valid, 415},
{"declared jpeg, actual png", alice.ID, chat.ID, "a.jpg", "image/jpeg", valid, 415},
{"declared png, actual jpeg", alice.ID, chat.ID, "a.png", "image/png", testJPEG(t), 415},
{"not an image", alice.ID, chat.ID, "a.png", "image/png", []byte("<html>"), 415},
{"truncated", alice.ID, chat.ID, "a.png", "image/png", valid[:len(valid)/2], 415},
{"empty body", alice.ID, chat.ID, "a.png", "image/png", nil, 415},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
resp := r.upload(tc.actor, tc.chat, tc.filename, tc.contentType, tc.data)
defer resp.Body.Close()
if resp.StatusCode != tc.want {
body, _ := io.ReadAll(resp.Body)
t.Fatalf("status = %d, want %d, body = %s", resp.StatusCode, tc.want, body)
}
})
}
if keys := r.objects.Keys(); len(keys) != 0 {
t.Errorf("rejected uploads left objects: %v", keys)
}
}
func TestAttachment_RequiresAuthentication(t *testing.T) {
r := newTestRig(t)
_, _, _, chat := bootstrap(r)
resp := r.upload("", chat.ID, "a.png", "image/png", testPNG(t, 2, 2))
expectStatus(t, resp, http.StatusUnauthorized)
resp.Body.Close()
}
func TestAttachment_S3UnavailableGives503AndKeepsMessagesWorking(t *testing.T) {
r := newTestRig(t)
alice, _, _, chat := bootstrap(r)
data := testPNG(t, 2, 2)
att := r.uploadOK(alice.ID, chat.ID, data)
r.objects.Down.Store(true)
resp := r.upload(alice.ID, chat.ID, "b.png", "image/png", data)
expectStatus(t, resp, http.StatusServiceUnavailable)
if code := readError(t, resp).Error.Code; code != "unavailable" {
t.Errorf("code = %q", code)
}
resp = r.do(http.MethodGet, "/api/v1/attachments/"+att.ID+"/content", alice.ID, nil, nil)
expectStatus(t, resp, http.StatusConflict)
resp.Body.Close()
// Метаданные лежат в БД и остаются доступными.
resp = r.do(http.MethodGet, "/api/v1/attachments/"+att.ID, alice.ID, nil, nil)
expectStatus(t, resp, http.StatusOK)
resp.Body.Close()
if code, _ := r.send(alice, chat.ID, "текст без S3"); code != http.StatusCreated {
t.Errorf("message status = %d", code)
}
r.objects.Down.Store(false)
resp = r.do(http.MethodGet, "/api/v1/attachments/"+att.ID+"/content", alice.ID, nil, nil)
expectStatus(t, resp, http.StatusConflict)
resp.Body.Close()
}
func TestAttachment_UnknownVariant(t *testing.T) {
r := newTestRig(t)
alice, _, _, chat := bootstrap(r)
att := r.uploadOK(alice.ID, chat.ID, testPNG(t, 2, 2))
for query, want := range map[string]int{"?variant=original": 409, "?variant=thumbnail": 409, "?variant=../x": 400, "?variant=": 400} {
resp := r.do(http.MethodGet, "/api/v1/attachments/"+att.ID+"/content"+query, alice.ID, nil, nil)
if resp.StatusCode != want {
t.Errorf("%s: status = %d, want %d", query, resp.StatusCode, want)
}
resp.Body.Close()
}
}
func TestMessage_AttachmentRules(t *testing.T) {
r := newTestRig(t)
alice, bob, _, chat := bootstrap(r)
other := r.createChat(alice, "другой", alice.ID)
data := testPNG(t, 2, 2)
att := r.uploadOK(alice.ID, chat.ID, data)
foreign := r.uploadOK(alice.ID, other.ID, data)
path := "/api/v1/chats/" + chat.ID + "/messages"
post := func(body string) *http.Response {
return r.do(http.MethodPost, path, bob.ID, map[string]string{"Content-Type": "application/json"}, strings.NewReader(body))
}
cases := []struct {
name string
body string
want int
}{
{"empty text with attachment", `{"text":"","attachment_ids":["` + att.ID + `"]}`, 201},
{"spaces with attachment", `{"text":" ","attachment_ids":["` + att.ID + `"]}`, 201},
{"empty attachment list is the old form", `{"text":"x","attachment_ids":[]}`, 201},
{"empty text without attachments", `{"text":"","attachment_ids":[]}`, 400},
{"text is still required", `{"attachment_ids":["` + att.ID + `"]}`, 400},
{"null list", `{"text":"x","attachment_ids":null}`, 400},
{"wrong type", `{"text":"x","attachment_ids":"` + att.ID + `"}`, 400},
{"invalid id", `{"text":"x","attachment_ids":["nope"]}`, 400},
{"duplicate", `{"text":"x","attachment_ids":["` + att.ID + `","` + strings.ToUpper(att.ID) + `"]}`, 400},
{"unknown attachment", `{"text":"x","attachment_ids":["` + uuid.NewString() + `"]}`, 404},
{"attachment of another chat", `{"text":"x","attachment_ids":["` + foreign.ID + `"]}`, 404},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
resp := post(tc.body)
defer resp.Body.Close()
if resp.StatusCode != tc.want {
body, _ := io.ReadAll(resp.Body)
t.Fatalf("status = %d, want %d, body = %s", resp.StatusCode, tc.want, body)
}
})
}
items, _ := r.listMessages(alice, chat.ID, 100)
if len(items) != 3 || len(items[0].AttachmentIDs) != 1 || items[0].AttachmentIDs[0] != att.ID {
t.Errorf("history = %+v", items)
}
if items[2].AttachmentIDs == nil {
t.Error("message without attachments must have [] rather than null")
}
}
func TestMessage_IdempotencyCoversAttachments(t *testing.T) {
r := newTestRig(t)
alice, _, _, chat := bootstrap(r)
a := r.uploadOK(alice.ID, chat.ID, testPNG(t, 2, 2)).ID
b := r.uploadOK(alice.ID, chat.ID, testPNG(t, 3, 3)).ID
key := uuid.NewString()
code, first := r.postKeyed(alice.ID, chat.ID, key, `{"text":"x","attachment_ids":["`+a+`","`+b+`"]}`)
if code != http.StatusCreated {
t.Fatalf("first: %d %s", code, first)
}
code, replay := r.postKeyed(alice.ID, chat.ID, key, `{"attachment_ids":["`+a+`","`+b+`"],"text":"x"}`)
if code != http.StatusCreated || !bytes.Equal(first, replay) {
t.Errorf("replay: %d %s", code, replay)
}
if code, body := r.postKeyed(alice.ID, chat.ID, key, `{"text":"x","attachment_ids":["`+b+`"]}`); code != http.StatusConflict {
t.Errorf("other attachments: %d %s", code, body)
}
// Отсутствующий attachment_ids равен пустому списку.
plain := uuid.NewString()
if code, _ := r.postKeyed(alice.ID, chat.ID, plain, `{"text":"y"}`); code != http.StatusCreated {
t.Fatalf("plain: %d", code)
}
if code, body := r.postKeyed(alice.ID, chat.ID, plain, `{"text":"y","attachment_ids":[]}`); code != http.StatusCreated {
t.Errorf("plain replay: %d %s", code, body)
}
}
// failingMetadata имитирует отказ БД между записью в S3 и записью метаданных.
type failingMetadata struct{ *store.Memory }
func (f failingMetadata) CreateAttachment(context.Context, domain.Attachment) (domain.Attachment, error) {
return domain.Attachment{}, domain.ErrUnavailable
}
func TestAttachment_MetadataFailureRemovesObject(t *testing.T) {
r := newTestRig(t)
alice, _, _, chat := bootstrap(r)
objects := objectstore.NewMemory()
svc := service.NewAttachments(failingMetadata{r.memory}, objects, service.AttachmentLimits{
MaxUploadBytes: testMaxUploadBytes, MaxImagePixels: testMaxImagePixels, MaxConcurrentUploads: 1,
}, slog.New(slog.NewTextHandler(io.Discard, nil)))
data := testPNG(t, 2, 2)
_, err := svc.Upload(context.Background(), service.UploadInput{
CallerID: alice.ID, ChatID: chat.ID, Filename: "a.png", ContentType: "image/png",
ContentLength: int64(len(data)), Body: bytes.NewReader(data),
})
if !errors.Is(err, domain.ErrUnavailable) {
t.Fatalf("err = %v", err)
}
if keys := objects.Keys(); len(keys) != 0 {
t.Errorf("object left without metadata: %v", keys)
}
}
// lostCommit имитирует потерю ответа: строка сохранилась, а INSERT вернул ошибку.
type lostCommit struct{ *store.Memory }
func (l lostCommit) CreateAttachment(ctx context.Context, att domain.Attachment) (domain.Attachment, error) {
if _, err := l.Memory.CreateAttachment(ctx, att); err != nil {
return domain.Attachment{}, err
}
return domain.Attachment{}, domain.ErrUnavailable
}
// metadataDown имитирует БД, недоступную и для записи, и для проверки перед компенсацией.
type metadataDown struct{ failingMetadata }
func (metadataDown) AttachmentExists(context.Context, string) (bool, error) {
return false, domain.ErrUnavailable
}
func uploadVia(t *testing.T, svc *service.Attachments, caller, chatID string, body io.Reader, size int64) error {
t.Helper()
_, err := svc.Upload(context.Background(), service.UploadInput{
CallerID: caller, ChatID: chatID, Filename: "a.png", ContentType: "image/png", ContentLength: size, Body: body,
})
return err
}
// Строка в БД не должна остаться без файла: при потерянном ответе объект удалять нельзя.
func TestAttachment_LostCommitKeepsObject(t *testing.T) {
r := newTestRig(t)
alice, _, _, chat := bootstrap(r)
objects := objectstore.NewMemory()
svc := service.NewAttachments(lostCommit{r.memory}, objects, service.AttachmentLimits{
MaxUploadBytes: testMaxUploadBytes, MaxImagePixels: testMaxImagePixels, MaxConcurrentUploads: 1,
}, slog.New(slog.NewTextHandler(io.Discard, nil)))
data := testPNG(t, 2, 2)
if err := uploadVia(t, svc, alice.ID, chat.ID, bytes.NewReader(data), int64(len(data))); !errors.Is(err, domain.ErrUnavailable) {
t.Fatalf("err = %v", err)
}
if keys := objects.Keys(); len(keys) != 1 {
t.Errorf("object of a committed row was deleted: %v", keys)
}
}
// Если проверить нельзя, объект остаётся очистителю, а не удаляется вслепую.
func TestAttachment_UncheckableMetadataLeavesObjectToJanitor(t *testing.T) {
r := newTestRig(t)
alice, _, _, chat := bootstrap(r)
objects := objectstore.NewMemory()
svc := service.NewAttachments(metadataDown{failingMetadata{r.memory}}, objects, service.AttachmentLimits{
MaxUploadBytes: testMaxUploadBytes, MaxImagePixels: testMaxImagePixels, MaxConcurrentUploads: 1,
}, slog.New(slog.NewTextHandler(io.Discard, nil)))
data := testPNG(t, 2, 2)
if err := uploadVia(t, svc, alice.ID, chat.ID, bytes.NewReader(data), int64(len(data))); !errors.Is(err, domain.ErrUnavailable) {
t.Fatalf("err = %v", err)
}
if keys := objects.Keys(); len(keys) != 1 {
t.Errorf("object deleted without a metadata check: %v", keys)
}
}
// brokenBody отдаёт начало файла и обрывается: так выглядит отключившийся клиент.
type brokenBody struct{ data []byte }
func (b *brokenBody) Read(p []byte) (int, error) {
if len(b.data) == 0 {
return 0, io.ErrUnexpectedEOF
}
n := copy(p, b.data)
b.data = b.data[n:]
return n, nil
}
func spoolFiles(t *testing.T, dir string) []string {
t.Helper()
entries, err := os.ReadDir(dir)
if err != nil {
t.Fatal(err)
}
names := make([]string, 0, len(entries))
for _, entry := range entries {
names = append(names, entry.Name())
}
return names
}
func TestAttachment_InterruptedUploadLeavesNothing(t *testing.T) {
dir := t.TempDir()
t.Setenv("TMPDIR", dir)
r := newTestRig(t)
alice, _, _, chat := bootstrap(r)
svc := service.NewAttachments(r.memory, r.objects, service.AttachmentLimits{
MaxUploadBytes: testMaxUploadBytes, MaxImagePixels: testMaxImagePixels, MaxConcurrentUploads: 1,
}, slog.New(slog.NewTextHandler(io.Discard, nil)))
data := testPNG(t, 8, 8)
err := uploadVia(t, svc, alice.ID, chat.ID, &brokenBody{data: bytes.Clone(data[:len(data)/2])}, int64(len(data)))
var invalid *validate.Error
if !errors.As(err, &invalid) {
t.Fatalf("err = %v, want a client error rather than 500", err)
}
if keys := r.objects.Keys(); len(keys) != 0 {
t.Errorf("interrupted upload reached S3: %v", keys)
}
if files := spoolFiles(t, dir); len(files) != 0 {
t.Errorf("temporary files left: %v", files)
}
// Слот освобождён: следующая загрузка проходит при лимите в один файл.
if err := uploadVia(t, svc, alice.ID, chat.ID, bytes.NewReader(data), int64(len(data))); err != nil {
t.Errorf("slot was not released: %v", err)
}
}
func TestAttachment_TemporaryFileIsRemovedWhileUploadIsRunning(t *testing.T) {
dir := t.TempDir()
t.Setenv("TMPDIR", dir)
r := newTestRig(t)
alice, _, _, chat := bootstrap(r)
svc := service.NewAttachments(r.memory, r.objects, service.AttachmentLimits{
MaxUploadBytes: testMaxUploadBytes, MaxImagePixels: testMaxImagePixels, MaxConcurrentUploads: 1,
}, slog.New(slog.NewTextHandler(io.Discard, nil)))
blocked := &blockingReader{release: make(chan struct{}), started: make(chan struct{})}
done := make(chan error, 1)
go func() { done <- uploadVia(t, svc, alice.ID, chat.ID, blocked, -1) }()
<-blocked.started
// Файл уже открыт и убран из каталога: падение процесса в этот момент ничего не оставит.
if files := spoolFiles(t, dir); len(files) != 0 {
t.Errorf("temporary file is visible during upload: %v", files)
}
close(blocked.release)
<-done
}
// Тело без Content-Length не должно обойти лимит размера.
func TestAttachment_ChunkedOverLimitGives413(t *testing.T) {
r := newTestRig(t)
alice, _, _, chat := bootstrap(r)
big := append(testPNG(t, 2, 2), make([]byte, testMaxUploadBytes)...)
req, err := http.NewRequest(http.MethodPost, r.server.URL+"/api/v1/chats/"+chat.ID+"/attachments?filename=a.png", io.MultiReader(bytes.NewReader(big)))
if err != nil {
t.Fatal(err)
}
req.ContentLength = -1
req.Header.Set("Content-Type", "image/png")
r.setAuth(req, alice.ID)
resp, err := r.client.Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
expectStatus(t, resp, http.StatusRequestEntityTooLarge)
if keys := r.objects.Keys(); len(keys) != 0 {
t.Errorf("oversized upload reached S3: %v", keys)
}
}
// blockingReader держит загрузку открытой, пока тест не разрешит продолжить.
type blockingReader struct {
release chan struct{}
started chan struct{}
}
func (b *blockingReader) Read([]byte) (int, error) {
close(b.started)
<-b.release
return 0, io.EOF
}
func TestAttachment_ConcurrentUploadLimitGives429(t *testing.T) {
r := newTestRig(t)
alice, _, _, chat := bootstrap(r)
objects := objectstore.NewMemory()
svc := service.NewAttachments(r.memory, objects, service.AttachmentLimits{
MaxUploadBytes: testMaxUploadBytes, MaxImagePixels: testMaxImagePixels, MaxConcurrentUploads: 1,
}, slog.New(slog.NewTextHandler(io.Discard, nil)))
blocked := &blockingReader{release: make(chan struct{}), started: make(chan struct{})}
done := make(chan error, 1)
go func() {
_, err := svc.Upload(context.Background(), service.UploadInput{
CallerID: alice.ID, ChatID: chat.ID, Filename: "a.png", ContentType: "image/png", Body: blocked,
})
done <- err
}()
<-blocked.started
data := testPNG(t, 2, 2)
_, err := svc.Upload(context.Background(), service.UploadInput{
CallerID: alice.ID, ChatID: chat.ID, Filename: "b.png", ContentType: "image/png", Body: bytes.NewReader(data),
})
if !errors.Is(err, domain.ErrRateLimited) {
t.Errorf("second upload: %v", err)
}
close(blocked.release)
<-done
}
// Клиент, который читает ответ только после отправки всего тела, должен получить код, а не обрыв.
func TestAttachment_RejectedBodyIsDrainedSoClientGetsStatus(t *testing.T) {
r := newTestRig(t)
alice, _, eve, chat := bootstrap(r)
big := make([]byte, 8*testMaxUploadBytes)
path := "/api/v1/chats/" + chat.ID + "/attachments?filename=a.png"
cases := []struct {
name string
actor string
want int
}{
{"too large", alice.ID, http.StatusRequestEntityTooLarge},
{"outsider", eve.ID, http.StatusNotFound},
{"no session", "", http.StatusUnauthorized},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
for _, length := range []int64{int64(len(big)), -1} { // с Content-Length и chunked
req, err := http.NewRequest(http.MethodPost, r.server.URL+path, io.MultiReader(bytes.NewReader(big)))
if err != nil {
t.Fatal(err)
}
req.ContentLength = length
req.Header.Set("Content-Type", "image/png")
r.setAuth(req, tc.actor)
resp, err := r.client.Do(req)
if err != nil {
t.Fatalf("length %d: %v", length, err)
}
resp.Body.Close()
if resp.StatusCode != tc.want {
t.Errorf("length %d: status = %d, want %d", length, resp.StatusCode, tc.want)
}
}
})
}
}
+73
View File
@@ -0,0 +1,73 @@
package http
import (
"encoding/base64"
"errors"
"io"
"net/http"
"strings"
"unicode/utf8"
"github.com/labstack/echo/v4"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/middleware"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/service"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate"
)
type authHandler struct {
auth service.AuthService
}
func (h *authHandler) createSession(c echo.Context) error {
// Read at most one byte: chunked requests have no known Content-Length.
var first [1]byte
n, err := io.ReadFull(c.Request().Body, first[:])
if n != 0 || (err != nil && !errors.Is(err, io.EOF)) {
return WriteError(c, &validate.Error{Field: "body", Reason: "must be empty, credentials go in Authorization: Basic"})
}
username, password, ok := parseBasic(c.Request().Header.Get(echo.HeaderAuthorization))
if !ok {
return middleware.Unauthorized(c, middleware.BasicChallenge, "Invalid credentials")
}
s, err := h.auth.Login(c.Request().Context(), username, password)
if err != nil {
if errors.Is(err, domain.ErrUnauthorized) {
return middleware.Unauthorized(c, middleware.BasicChallenge, "Invalid credentials")
}
return WriteError(c, err)
}
return c.JSON(http.StatusCreated, dto.SessionResponse{
Token: s.Token,
TokenType: "Bearer",
ExpiresAt: dto.NewTimestamp(s.ExpiresAt),
User: toUserResponse(s.User),
})
}
func (h *authHandler) revokeSession(c echo.Context) error {
tok := c.Get(middleware.AuthTokenKey).(string)
if err := h.auth.Logout(c.Request().Context(), tok); err != nil {
return WriteError(c, err)
}
return c.NoContent(http.StatusNoContent)
}
func parseBasic(header string) (username, password string, ok bool) {
scheme, encoded, found := strings.Cut(header, " ")
if !found || !strings.EqualFold(scheme, "Basic") {
return "", "", false
}
raw, err := base64.StdEncoding.DecodeString(strings.TrimSpace(encoded))
if err != nil || !utf8.Valid(raw) {
return "", "", false
}
username, password, found = strings.Cut(string(raw), ":")
if !found || username == "" || password == "" {
return "", "", false
}
return username, password, true
}
+242
View File
@@ -0,0 +1,242 @@
package http
import (
"context"
"encoding/base64"
"io"
"net/http"
"strings"
"testing"
"time"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/session"
)
const (
basicChallenge = `Basic realm="messenger", charset="UTF-8"`
bearerChallenge = `Bearer realm="messenger"`
)
func expectUnauthorized(t *testing.T, resp *http.Response, challenge string) {
t.Helper()
defer resp.Body.Close()
if resp.StatusCode != http.StatusUnauthorized {
data, _ := io.ReadAll(resp.Body)
t.Fatalf("expected 401, got %d; body=%s", resp.StatusCode, string(data))
}
if got := resp.Header.Get("WWW-Authenticate"); got != challenge {
t.Fatalf("WWW-Authenticate = %q, want %q", got, challenge)
}
e := readError(t, resp)
if e.Error.Code != CodeUnauthorized || e.Error.RequestID == "" {
t.Fatalf("unexpected error body: %+v", e)
}
}
func (r *testRig) withHeaders(method, path string, headers map[string]string) *http.Response {
r.t.Helper()
return r.do(method, path, "", headers, nil)
}
func TestAuth_LoginReturnsSession(t *testing.T) {
r := newTestRig(t)
alice := r.createUser("login_"+randomSuffix(), "Алиса")
before := time.Now()
s := r.login(alice.Username, testPassword)
if s.TokenType != "Bearer" || len(s.Token) < 32 {
t.Fatalf("bad session: type=%q len(token)=%d", s.TokenType, len(s.Token))
}
if s.User.ID != alice.ID || s.User.Username != alice.Username {
t.Fatalf("session user = %+v, want %s", s.User, alice.ID)
}
if strings.Contains(s.Token, alice.ID) || strings.Contains(s.Token, alice.Username) {
t.Fatal("token is derived from user identity")
}
if !s.ExpiresAt.After(before.Add(59*time.Minute)) || s.ExpiresAt.After(before.Add(61*time.Minute)) {
t.Fatalf("expires_at = %s, want ~now+1h", s.ExpiresAt)
}
if again := r.login(alice.Username, testPassword); again.Token == s.Token {
t.Fatal("second login returned the same token")
}
}
func TestAuth_LoginRejectsBadCredentialsUniformly(t *testing.T) {
r := newTestRig(t)
alice := r.createUser("bad_"+randomSuffix(), "Алиса")
expectUnauthorized(t, r.basicLogin(alice.Username, "wrong-password-123"), basicChallenge)
expectUnauthorized(t, r.basicLogin("nobody_"+randomSuffix(), testPassword), basicChallenge)
b64 := func(s string) string { return base64.StdEncoding.EncodeToString([]byte(s)) }
for _, h := range []string{
"",
"Bearer " + b64(alice.Username+":"+testPassword),
"Basic not-base64!!!",
"Basic " + b64(alice.Username),
"Basic " + b64(alice.Username+":"),
"Basic " + b64(":"+testPassword),
"Basic " + b64(alice.Username+":\xff\xfe"),
} {
headers := map[string]string{}
if h != "" {
headers["Authorization"] = h
}
expectUnauthorized(t, r.withHeaders(http.MethodPost, "/api/v1/auth/sessions", headers), basicChallenge)
}
}
func TestAuth_PasswordWithColonAndUnicode(t *testing.T) {
r := newTestRig(t)
username := "colon_" + randomSuffix()
pw := "пароль:с:двоеточиями🙂"
resp := r.doJSON(http.MethodPost, "/api/v1/users", "", dto.CreateUserRequest{
Username: username, DisplayName: "Двоеточие", Password: pw,
})
expectStatus(t, resp, http.StatusCreated)
resp.Body.Close()
r.login(username, pw)
expectUnauthorized(t, r.basicLogin(username, "пароль"), basicChallenge)
}
func TestAuth_LoginRejectsBody(t *testing.T) {
r := newTestRig(t)
alice := r.createUser("body_"+randomSuffix(), "Алиса")
req, _ := http.NewRequest(http.MethodPost, r.server.URL+"/api/v1/auth/sessions",
strings.NewReader(`{"username":"`+alice.Username+`"}`))
req.Header.Set("Content-Type", "application/json")
req.SetBasicAuth(alice.Username, testPassword)
resp, err := r.client.Do(req)
if err != nil {
t.Fatal(err)
}
expectStatus(t, resp, http.StatusBadRequest)
resp.Body.Close()
}
func TestAuth_LoginChunkedBody(t *testing.T) {
r := newTestRig(t)
alice := r.createUser("chunked_"+randomSuffix(), "Алиса")
for _, body := range []string{"", " ", `{"extra":1}`} {
t.Run(body, func(t *testing.T) {
req, err := http.NewRequest(http.MethodPost, r.server.URL+"/api/v1/auth/sessions", io.NopCloser(strings.NewReader(body)))
if err != nil {
t.Fatal(err)
}
req.TransferEncoding = []string{"chunked"}
req.SetBasicAuth(alice.Username, testPassword)
resp, err := r.client.Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
want := http.StatusBadRequest
if body == "" {
want = http.StatusCreated
}
expectStatus(t, resp, want)
})
}
}
func TestAuth_BearerRequired(t *testing.T) {
r := newTestRig(t)
alice, _, eve, _ := bootstrap(r)
expectUnauthorized(t, r.withHeaders(http.MethodGet, "/api/v1/users/me", nil), bearerChallenge)
expectUnauthorized(t, r.withHeaders(http.MethodGet, "/api/v1/users/me",
map[string]string{"X-User-Id": alice.ID}), bearerChallenge)
basic := base64.StdEncoding.EncodeToString([]byte(alice.Username + ":" + testPassword))
expectUnauthorized(t, r.withHeaders(http.MethodGet, "/api/v1/users/me",
map[string]string{"Authorization": "Basic " + basic}), bearerChallenge)
expectUnauthorized(t, r.withHeaders(http.MethodGet, "/api/v1/users/me",
map[string]string{"Authorization": "Bearer " + strings.Repeat("A", 43)}), bearerChallenge)
expectUnauthorized(t, r.withHeaders(http.MethodGet, "/api/v1/users/me",
map[string]string{"Authorization": "Bearer " + alice.ID}), bearerChallenge)
resp := r.do(http.MethodGet, "/api/v1/users/me", alice.ID, map[string]string{"X-User-Id": eve.ID}, nil)
expectStatus(t, resp, http.StatusOK)
var me dto.UserResponse
readJSON(t, resp, &me)
if me.ID != alice.ID {
t.Fatalf("X-User-Id overrode bearer identity: got %s", me.ID)
}
tok := r.tokens[alice.ID]
resp = r.withHeaders(http.MethodGet, "/api/v1/users/me", map[string]string{"Authorization": "bearer " + tok})
expectStatus(t, resp, http.StatusOK)
resp.Body.Close()
}
func TestAuth_Logout(t *testing.T) {
r := newTestRig(t)
alice := r.createUser("logout_"+randomSuffix(), "Алиса")
other := r.login(alice.Username, testPassword)
resp := r.do(http.MethodDelete, "/api/v1/auth/sessions/current", alice.ID, nil, nil)
expectStatus(t, resp, http.StatusNoContent)
body, _ := io.ReadAll(resp.Body)
resp.Body.Close()
if len(body) != 0 {
t.Fatalf("204 with body %q", body)
}
expectUnauthorized(t, r.do(http.MethodGet, "/api/v1/users/me", alice.ID, nil, nil), bearerChallenge)
expectUnauthorized(t, r.do(http.MethodDelete, "/api/v1/auth/sessions/current", alice.ID, nil, nil), bearerChallenge)
resp = r.withHeaders(http.MethodGet, "/api/v1/users/me", map[string]string{"Authorization": "Bearer " + other.Token})
expectStatus(t, resp, http.StatusOK)
resp.Body.Close()
}
func TestAuth_SessionExpires(t *testing.T) {
r := newRig(t, defaultTestLimits, session.NewMemory(), 2*time.Second)
alice := r.createUser("ttl_"+randomSuffix(), "Алиса")
resp := r.do(http.MethodGet, "/api/v1/users/me", alice.ID, nil, nil)
expectStatus(t, resp, http.StatusOK)
resp.Body.Close()
time.Sleep(2100 * time.Millisecond)
expectUnauthorized(t, r.do(http.MethodGet, "/api/v1/users/me", alice.ID, nil, nil), bearerChallenge)
}
type brokenSessions struct {
*session.Memory
down bool
}
func (b *brokenSessions) Get(ctx context.Context, h []byte) (session.Session, error) {
if b.down {
return session.Session{}, domain.ErrUnavailable
}
return b.Memory.Get(ctx, h)
}
func (b *brokenSessions) Save(ctx context.Context, h []byte, s session.Session) error {
if b.down {
return domain.ErrUnavailable
}
return b.Memory.Save(ctx, h, s)
}
func TestAuth_SessionStoreDownIs503NotAnonymous(t *testing.T) {
store := &brokenSessions{Memory: session.NewMemory()}
r := newRig(t, defaultTestLimits, store, time.Hour)
alice := r.createUser("down_"+randomSuffix(), "Алиса")
store.down = true
resp := r.do(http.MethodGet, "/api/v1/users/me", alice.ID, nil, nil)
expectStatus(t, resp, http.StatusServiceUnavailable)
if e := readError(t, resp); e.Error.Code != CodeUnavailable {
t.Fatalf("code = %q, want %q", e.Error.Code, CodeUnavailable)
}
resp = r.basicLogin(alice.Username, testPassword)
expectStatus(t, resp, http.StatusServiceUnavailable)
resp.Body.Close()
}
+103
View File
@@ -0,0 +1,103 @@
package http
import (
"net/http"
"strconv"
"github.com/labstack/echo/v4"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/middleware"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/service"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate"
)
type chatsHandler struct {
chats service.ChatsService
}
func (h *chatsHandler) create(c echo.Context) error {
callerID := c.Get(middleware.AuthUserIDKey).(string)
var req dto.CreateChatRequest
if err := decodeJSON(c.Request().Body, &req); err != nil {
return WriteError(c, err)
}
chat, err := h.chats.Create(c.Request().Context(), callerID, req.Title, req.MemberIDs)
if err != nil {
return WriteError(c, err)
}
return c.JSON(http.StatusCreated, toChatResponse(chat))
}
func (h *chatsHandler) get(c echo.Context) error {
callerID := c.Get(middleware.AuthUserIDKey).(string)
chatID := c.Param("chat_id")
chat, err := h.chats.Get(c.Request().Context(), callerID, chatID)
if err != nil {
return WriteError(c, err)
}
return c.JSON(http.StatusOK, toChatResponse(chat))
}
func (h *chatsHandler) list(c echo.Context) error {
callerID := c.Get(middleware.AuthUserIDKey).(string)
limit, cursor, err := parsePageParams(c)
if err != nil {
return WriteError(c, err)
}
page, err := h.chats.List(c.Request().Context(), callerID, cursor, limit)
if err != nil {
return WriteError(c, err)
}
return c.JSON(http.StatusOK, toChatsPage(page))
}
func toChatResponse(ch domain.Chat) dto.ChatResponse {
members := make([]string, len(ch.MemberIDs))
copy(members, ch.MemberIDs)
return dto.ChatResponse{
ID: ch.ID,
Title: ch.Title,
MemberIDs: members,
CreatedAt: dto.NewTimestamp(ch.CreatedAt),
}
}
func toChatsPage(p domain.Page[domain.Chat]) dto.ChatsPageResponse {
items := make([]dto.ChatResponse, 0, len(p.Items))
for _, ch := range p.Items {
items = append(items, toChatResponse(ch))
}
var next *string
if p.NextCursor != "" {
s := p.NextCursor
next = &s
}
return dto.ChatsPageResponse{Items: items, NextCursor: next}
}
func parsePageParams(c echo.Context) (int, string, error) {
q := c.QueryParams()
limit := validate.LimitDefault
if vals, ok := q["limit"]; ok {
n, err := strconv.Atoi(vals[0])
if err != nil {
return 0, "", &validate.Error{Field: "limit", Reason: "must be an integer"}
}
limit = n
}
cursor := ""
if vals, ok := q["cursor"]; ok {
if vals[0] == "" {
return 0, "", &validate.Error{Field: "cursor", Reason: "must not be empty"}
}
cursor = vals[0]
}
return limit, cursor, nil
}
+84
View File
@@ -0,0 +1,84 @@
package http
import (
"fmt"
"net/http"
"sync"
"testing"
)
func TestConcurrency_100MessagesFrom10Clients(t *testing.T) {
const clients = 10
const perClient = 10
const total = clients * perClient
r := newTestRig(t)
users := make([]testUser, clients)
memberIDs := make([]string, clients)
for i := range users {
users[i] = r.createUser(fmt.Sprintf("race_%02d_%s", i, randomSuffix()), fmt.Sprintf("Клиент %d", i))
memberIDs[i] = users[i].ID
}
chat := r.createChat(users[0], "Гонка", memberIDs...)
type result struct {
id, text string
err error
}
results := make(chan result, total)
start := make(chan struct{})
var wg sync.WaitGroup
for i, actor := range users {
wg.Add(1)
go func() {
defer wg.Done()
<-start
for j := 0; j < perClient; j++ {
text := fmt.Sprintf("race-c%02d-m%02d", i, j)
status, msg, body := r.sendRaw(actor, chat.ID, mustJSON(map[string]string{"text": text}))
if status != http.StatusCreated {
results <- result{err: fmt.Errorf("%s: status %d: %s", text, status, body)}
continue
}
results <- result{id: msg.ID, text: msg.Text}
}
}()
}
close(start)
wg.Wait()
close(results)
sentIDs := make(map[string]string, total)
for res := range results {
if res.err != nil {
t.Fatal(res.err)
}
if _, dup := sentIDs[res.id]; dup {
t.Fatalf("сервер выдал один id %s двум сообщениям", res.id)
}
sentIDs[res.id] = res.text
}
if len(sentIDs) != total {
t.Fatalf("подтверждено %d сообщений, ожидалось %d", len(sentIDs), total)
}
history, _ := r.listMessages(users[0], chat.ID, 100)
if len(history) != total {
t.Fatalf("в истории %d сообщений, ожидалось ровно %d", len(history), total)
}
seen := make(map[string]struct{}, total)
for i, m := range history {
if _, dup := seen[m.ID]; dup {
t.Fatalf("id %s встречается в истории дважды", m.ID)
}
seen[m.ID] = struct{}{}
if text, ok := sentIDs[m.ID]; !ok || text != m.Text {
t.Fatalf("сообщение %s (%q) в истории не совпадает с подтверждённым", m.ID, m.Text)
}
if i > 0 && !history[i-1].CreatedAt.Before(m.CreatedAt.Time) {
t.Fatalf("порядок (created_at) нарушен на индексе %d", i)
}
}
t.Logf("%d клиентов × %d сообщений = %d уникальных сообщений в истории, 0 дубликатов",
clients, perClient, total)
}
+54
View File
@@ -0,0 +1,54 @@
package http
import (
"context"
"net/http"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/middleware"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/service"
"github.com/labstack/echo/v4"
)
// Optional extension keeps the mandatory proxy contract unchanged.
type directAttachments interface {
InitDirect(context.Context, string, string, service.DirectInput) (service.DirectUpload, error)
CompleteDirect(context.Context, string, string, string) (domain.Attachment, error)
}
func (h *attachmentsHandler) directInit(c echo.Context) error {
svc, ok := h.attachments.(directAttachments)
if !ok {
return WriteError(c, domain.ErrUnavailable)
}
var in service.DirectInput
if err := decodeJSON(c.Request().Body, &in); err != nil {
return WriteError(c, domain.ErrInvalidArgument)
}
out, err := svc.InitDirect(c.Request().Context(), c.Get(middleware.AuthUserIDKey).(string), c.Param("chat_id"), in)
if err != nil {
return WriteError(c, err)
}
c.Response().Header().Set("Cache-Control", "no-store")
return c.JSON(http.StatusCreated, out)
}
func (h *attachmentsHandler) directComplete(c echo.Context) error {
svc, ok := h.attachments.(directAttachments)
if !ok {
return WriteError(c, domain.ErrUnavailable)
}
var in struct {
Token string `json:"token"`
}
if err := decodeJSON(c.Request().Body, &in); err != nil {
return WriteError(c, domain.ErrInvalidArgument)
}
ctx, cancel := context.WithTimeout(c.Request().Context(), transferTimeout)
defer cancel()
att, err := svc.CompleteDirect(ctx, c.Get(middleware.AuthUserIDKey).(string), c.Param("chat_id"), in.Token)
if err != nil {
return WriteError(c, err)
}
return c.JSON(http.StatusCreated, toAttachmentResponse(att))
}
+27
View File
@@ -0,0 +1,27 @@
package dto
// VariantResponse — преобразованная копия. В lab4 вариантов нет, список всегда пуст.
type VariantResponse struct {
Name string `json:"name"`
ContentType string `json:"content_type"`
SizeBytes int64 `json:"size_bytes"`
Width int `json:"width"`
Height int `json:"height"`
SHA256 string `json:"sha256"`
}
// AttachmentResponse намеренно не содержит object key: он внутренний.
type AttachmentResponse struct {
ID string `json:"id"`
ChatID string `json:"chat_id"`
OwnerID string `json:"owner_id"`
Filename string `json:"filename"`
ContentType string `json:"content_type"`
SizeBytes int64 `json:"size_bytes"`
SHA256 string `json:"sha256"`
Status string `json:"status"`
Variants []VariantResponse `json:"variants"`
ErrorCode *string `json:"error_code"`
CreatedAt Timestamp `json:"created_at"`
UpdatedAt Timestamp `json:"updated_at"`
}
+18
View File
@@ -0,0 +1,18 @@
package dto
type CreateChatRequest struct {
Title string `json:"title"`
MemberIDs []string `json:"member_ids"`
}
type ChatResponse struct {
ID string `json:"id"`
Title string `json:"title"`
MemberIDs []string `json:"member_ids"`
CreatedAt Timestamp `json:"created_at"`
}
type ChatsPageResponse struct {
Items []ChatResponse `json:"items"`
NextCursor *string `json:"next_cursor"`
}
+37
View File
@@ -0,0 +1,37 @@
package dto
import (
"encoding/json"
"errors"
)
// AttachmentIDList — необязательное поле: отсутствие равно [], но явный null по контракту неверен.
// Обычный срез принял бы null молча, поэтому разбор свой.
type AttachmentIDList []string
func (l *AttachmentIDList) UnmarshalJSON(data []byte) error {
if string(data) == "null" {
return errors.New("attachment_ids must be an array")
}
return json.Unmarshal(data, (*[]string)(l))
}
type CreateMessageRequest struct {
// Text — указатель: поле обязательно и при наличии вложений, а "" допустим только с ними.
Text *string `json:"text"`
AttachmentIDs AttachmentIDList `json:"attachment_ids"`
}
type MessageResponse struct {
ID string `json:"id"`
ChatID string `json:"chat_id"`
SenderID string `json:"sender_id"`
Text string `json:"text"`
CreatedAt Timestamp `json:"created_at"`
AttachmentIDs []string `json:"attachment_ids"`
}
type MessagesPageResponse struct {
Items []MessageResponse `json:"items"`
NextCursor *string `json:"next_cursor"`
}
+20
View File
@@ -0,0 +1,20 @@
package dto
import "time"
const timestampLayout = "2006-01-02T15:04:05.000000Z"
// Timestamp сериализуется в UTC всегда с 6 цифрами дробной части. Стандартный формат
// time.Time отбрасывает нули в конце (…17.95188Z): это корректный RFC 3339, но такое значение
// не разбирает datetime.fromisoformat в Python 3.9–3.10, на которых идут публичные тесты.
type Timestamp struct {
time.Time
}
func NewTimestamp(t time.Time) Timestamp {
return Timestamp{Time: t}
}
func (t Timestamp) MarshalJSON() ([]byte, error) {
return []byte(`"` + t.UTC().Format(timestampLayout) + `"`), nil
}
@@ -0,0 +1,48 @@
package dto
import (
"encoding/json"
"testing"
"time"
)
func TestTimestampAlwaysHasSixFractionalDigits(t *testing.T) {
moscow := time.FixedZone("MSK", 3*60*60)
cases := []struct {
name string
in time.Time
want string
}{
{"нули в конце", time.Date(2026, 11, 4, 9, 47, 17, 951880000, time.UTC), `"2026-11-04T09:47:17.951880Z"`},
{"без дробной части", time.Date(2026, 11, 4, 9, 47, 17, 0, time.UTC), `"2026-11-04T09:47:17.000000Z"`},
{"шесть цифр", time.Date(2026, 11, 4, 9, 47, 17, 123456000, time.UTC), `"2026-11-04T09:47:17.123456Z"`},
{"наносекунды отбрасываются", time.Date(2026, 11, 4, 9, 47, 17, 123456789, time.UTC), `"2026-11-04T09:47:17.123456Z"`},
{"приводится к UTC", time.Date(2026, 11, 4, 12, 47, 17, 500000000, moscow), `"2026-11-04T09:47:17.500000Z"`},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
got, err := json.Marshal(NewTimestamp(c.in))
if err != nil {
t.Fatal(err)
}
if string(got) != c.want {
t.Fatalf("got %s, want %s", got, c.want)
}
})
}
}
func TestTimestampRoundTrip(t *testing.T) {
want := time.Date(2026, 11, 4, 9, 47, 17, 951880000, time.UTC)
data, err := json.Marshal(MessageResponse{CreatedAt: NewTimestamp(want)})
if err != nil {
t.Fatal(err)
}
var got MessageResponse
if err := json.Unmarshal(data, &got); err != nil {
t.Fatal(err)
}
if !got.CreatedAt.Equal(want) {
t.Fatalf("got %s, want %s", got.CreatedAt, want)
}
}
+21
View File
@@ -0,0 +1,21 @@
package dto
type CreateUserRequest struct {
Username string `json:"username"`
DisplayName string `json:"display_name"`
Password string `json:"password"`
}
type UserResponse struct {
ID string `json:"id"`
Username string `json:"username"`
DisplayName string `json:"display_name"`
CreatedAt Timestamp `json:"created_at"`
}
type SessionResponse struct {
Token string `json:"token"`
TokenType string `json:"token_type"`
ExpiresAt Timestamp `json:"expires_at"`
User UserResponse `json:"user"`
}
+83
View File
@@ -0,0 +1,83 @@
package http
import (
"errors"
"net/http"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate"
"github.com/labstack/echo/v4"
)
const (
CodeInvalidRequest = "invalid_request"
CodeUnauthorized = "unauthorized"
CodeNotFound = "not_found"
CodeConflict = "conflict"
CodePayloadTooLarge = "payload_too_large"
CodeUnsupportedMedia = "unsupported_media_type"
CodeRateLimited = "rate_limited"
CodeUnavailable = "unavailable"
CodeInternalError = "internal_error"
)
type errorBody struct {
Error errorPayload `json:"error"`
}
type errorPayload struct {
Code string `json:"code"`
Message string `json:"message"`
RequestID string `json:"request_id"`
}
var (
ErrUnauthorized = errors.New("unauthorized")
ErrUnsupportedMedia = errors.New("unsupported media type")
)
func Classify(err error) (status int, code, message string) {
switch {
case errors.Is(err, domain.ErrIdempotencyConflict):
return http.StatusConflict, CodeConflict, "Idempotency-Key was already used with a different request"
case errors.Is(err, domain.ErrNotFound):
return http.StatusNotFound, CodeNotFound, "Object not found"
case errors.Is(err, domain.ErrConflict):
return http.StatusConflict, CodeConflict, "Resource already exists"
case errors.Is(err, domain.ErrInvalidArgument):
return http.StatusBadRequest, CodeInvalidRequest, "Invalid request arguments"
case errors.Is(err, domain.ErrUnavailable):
return http.StatusServiceUnavailable, CodeUnavailable, "Service temporarily unavailable"
case errors.Is(err, domain.ErrPayloadTooLarge):
return http.StatusRequestEntityTooLarge, CodePayloadTooLarge, "Request body too large"
case errors.Is(err, domain.ErrRateLimited):
return http.StatusTooManyRequests, CodeRateLimited, "Too many concurrent requests"
case errors.Is(err, ErrUnauthorized), errors.Is(err, domain.ErrUnauthorized):
return http.StatusUnauthorized, CodeUnauthorized, "Identification required"
case errors.Is(err, domain.ErrUnsupportedMedia):
return http.StatusUnsupportedMediaType, CodeUnsupportedMedia, "Expected a valid PNG or JPEG image"
case errors.Is(err, ErrUnsupportedMedia):
return http.StatusUnsupportedMediaType, CodeUnsupportedMedia, "Expected Content-Type: application/json"
}
var vErr *validate.Error
if errors.As(err, &vErr) {
return http.StatusBadRequest, CodeInvalidRequest, vErr.Error()
}
return http.StatusInternalServerError, CodeInternalError, "Internal server error"
}
func WriteError(c echo.Context, err error) error {
status, code, msg := Classify(err)
if status == http.StatusTooManyRequests {
c.Response().Header().Set("Retry-After", "1")
}
return c.JSON(status, errorBody{
Error: errorPayload{
Code: code,
Message: msg,
RequestID: c.Response().Header().Get(echo.HeaderXRequestID),
},
})
}
+24
View File
@@ -0,0 +1,24 @@
package http
import (
"net/http"
"github.com/labstack/echo/v4"
)
type healthResponse struct {
Status string `json:"status"`
}
func healthLive(c echo.Context) error {
return c.JSON(http.StatusOK, healthResponse{Status: "ok"})
}
func healthReady(isReady func() bool) echo.HandlerFunc {
return func(c echo.Context) error {
if !isReady() {
return echo.NewHTTPError(http.StatusServiceUnavailable, "Service unavailable")
}
return c.JSON(http.StatusOK, healthResponse{Status: "ok"})
}
}
+358
View File
@@ -0,0 +1,358 @@
package http
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"sync"
"testing"
"time"
"github.com/google/uuid"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/config"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/objectstore"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/password"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/service"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/session"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store"
)
type testRig struct {
t *testing.T
server *httptest.Server
srv *Server
memory *store.Memory
objects *objectstore.Memory
sessions session.Store
client *http.Client
mu sync.Mutex
tokens map[string]string
}
func newTestRig(t *testing.T) *testRig {
return newTestRigWithLimits(t, config.Limits{
MaxBodyBytes: 1 << 20,
MaxInFlight: 256,
MaxMessagesGlobal: 100000,
MaxHeapBytes: 1 << 40,
})
}
func newTestRigWithLimits(t *testing.T, limits config.Limits) *testRig {
t.Helper()
return newRig(t, limits, session.NewMemory(), time.Hour)
}
const testInstanceID = "test-instance"
var defaultTestLimits = config.Limits{
MaxBodyBytes: 1 << 20,
MaxInFlight: 256,
MaxMessagesGlobal: 100000,
MaxHeapBytes: 1 << 40,
}
func newRig(t *testing.T, limits config.Limits, sessions session.Store, ttl time.Duration) *testRig {
t.Helper()
cfg := &config.Config{
Env: "test",
Version: "test",
InstanceID: testInstanceID,
HTTP: config.HTTP{
Addr: "127.0.0.1:0",
ReadTimeoutMs: 10000,
WriteTimeoutMs: 10000,
IdleTimeoutMs: 60000,
ShutdownTimeoutMs: 1000,
},
Limits: limits,
}
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
memory := store.NewWithLimit(limits.MaxMessagesGlobal)
hasher := password.NewHasher(testHashParams, 8)
auth, err := service.NewAuth(memory, sessions, hasher, ttl)
if err != nil {
t.Fatal(err)
}
objects := objectstore.NewMemory()
srv := NewServer(Deps{
Config: cfg,
Logger: logger,
Store: memory,
Auth: auth,
Users: service.NewUsers(memory, hasher),
Chats: service.NewChats(memory),
Messages: service.NewMessages(memory),
Attachments: service.NewAttachments(memory, objects, service.AttachmentLimits{
MaxUploadBytes: testMaxUploadBytes,
MaxImagePixels: testMaxImagePixels,
MaxConcurrentUploads: testMaxConcurrentUploads,
}, logger),
})
ts := httptest.NewServer(srv.e)
t.Cleanup(ts.Close)
return &testRig{
t: t,
server: ts,
srv: srv,
memory: memory,
objects: objects,
sessions: sessions,
client: &http.Client{Timeout: 10 * time.Second},
tokens: make(map[string]string),
}
}
type testUser struct {
ID string
Username string
DisplayName string
}
type errorResp struct {
Error struct {
Code string `json:"code"`
Message string `json:"message"`
RequestID string `json:"request_id"`
} `json:"error"`
}
func (r *testRig) do(method, path string, actorID string, headers map[string]string, body io.Reader) *http.Response {
r.t.Helper()
req, err := http.NewRequest(method, r.server.URL+path, body)
if err != nil {
r.t.Fatalf("new request %s %s: %v", method, path, err)
}
req.Header.Set("Accept", "application/json")
r.setAuth(req, actorID)
if method == http.MethodPost && strings.HasSuffix(path, "/messages") {
req.Header.Set("Idempotency-Key", uuid.NewString())
}
for k, v := range headers {
req.Header.Set(k, v)
}
resp, err := r.client.Do(req)
if err != nil {
r.t.Fatalf("do %s %s: %v", method, path, err)
}
return resp
}
func (r *testRig) doJSON(method, path string, actorID string, payload any) *http.Response {
r.t.Helper()
var body io.Reader
if payload != nil {
body = bytes.NewReader(mustJSON(payload))
}
return r.do(method, path, actorID, map[string]string{"Content-Type": "application/json"}, body)
}
func readJSON(t *testing.T, resp *http.Response, dst any) {
t.Helper()
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("read body: %v", err)
}
if len(data) == 0 {
return
}
if err := json.Unmarshal(data, dst); err != nil {
t.Fatalf("decode body (%s): %v", string(data), err)
}
}
func readError(t *testing.T, resp *http.Response) errorResp {
t.Helper()
var e errorResp
readJSON(t, resp, &e)
return e
}
func expectStatus(t *testing.T, resp *http.Response, want int) {
t.Helper()
if resp.StatusCode != want {
data, _ := io.ReadAll(resp.Body)
resp.Body.Close()
t.Fatalf("expected status %d, got %d; body=%s", want, resp.StatusCode, string(data))
}
}
const testPassword = "test-password-123"
var testHashParams = password.Params{MemoryKiB: 64, Iterations: 1, Parallelism: 1, SaltLen: 16, KeyLen: 32}
func (r *testRig) createUser(username, displayName string) testUser {
r.t.Helper()
resp := r.doJSON(http.MethodPost, "/api/v1/users", "", dto.CreateUserRequest{
Username: username,
DisplayName: displayName,
Password: testPassword,
})
expectStatus(r.t, resp, http.StatusCreated)
var u dto.UserResponse
readJSON(r.t, resp, &u)
s := r.login(username, testPassword)
r.mu.Lock()
r.tokens[u.ID] = s.Token
r.mu.Unlock()
return testUser{ID: u.ID, Username: u.Username, DisplayName: u.DisplayName}
}
// login входит по Basic и возвращает сессию; ожидает 201.
func (r *testRig) login(username, pw string) dto.SessionResponse {
r.t.Helper()
resp := r.basicLogin(username, pw)
expectStatus(r.t, resp, http.StatusCreated)
var s dto.SessionResponse
readJSON(r.t, resp, &s)
return s
}
func (r *testRig) basicLogin(username, pw string) *http.Response {
r.t.Helper()
req, _ := http.NewRequest(http.MethodPost, r.server.URL+"/api/v1/auth/sessions", nil)
req.SetBasicAuth(username, pw)
resp, err := r.client.Do(req)
if err != nil {
r.t.Fatalf("login: %v", err)
}
return resp
}
func (r *testRig) setAuth(req *http.Request, actorID string) {
if actorID == "" {
return
}
r.mu.Lock()
tok, ok := r.tokens[strings.ToLower(actorID)]
r.mu.Unlock()
if !ok {
tok = "unknown-" + actorID
}
req.Header.Set("Authorization", "Bearer "+tok)
}
func (r *testRig) createChat(owner testUser, title string, members ...string) dto.ChatResponse {
r.t.Helper()
resp := r.doJSON(http.MethodPost, "/api/v1/chats", owner.ID, dto.CreateChatRequest{
Title: title,
MemberIDs: members,
})
expectStatus(r.t, resp, http.StatusCreated)
var ch dto.ChatResponse
readJSON(r.t, resp, &ch)
return ch
}
func (r *testRig) sendMessage(actor testUser, chatID, text string) (*http.Response, dto.MessageResponse) {
r.t.Helper()
resp := r.doJSON(http.MethodPost, "/api/v1/chats/"+chatID+"/messages", actor.ID, textMessage(text))
if resp.StatusCode != http.StatusCreated {
return resp, dto.MessageResponse{}
}
var m dto.MessageResponse
readJSON(r.t, resp, &m)
return resp, m
}
func (r *testRig) sendRaw(actor testUser, chatID string, body []byte) (int, dto.MessageResponse, []byte) {
r.t.Helper()
resp := r.do(http.MethodPost, "/api/v1/chats/"+chatID+"/messages", actor.ID,
map[string]string{"Content-Type": "application/json"}, bytes.NewReader(body))
defer resp.Body.Close()
data, _ := io.ReadAll(resp.Body)
if resp.StatusCode != http.StatusCreated {
return resp.StatusCode, dto.MessageResponse{}, data
}
var m dto.MessageResponse
if err := json.Unmarshal(data, &m); err != nil {
r.t.Fatalf("decode message: %v", err)
}
return resp.StatusCode, m, data
}
func (r *testRig) send(actor testUser, chatID, text string) (int, dto.MessageResponse) {
r.t.Helper()
status, msg, _ := r.sendRaw(actor, chatID, mustJSON(textMessage(text)))
return status, msg
}
func (r *testRig) listMessages(actor testUser, chatID string, pageSize int) ([]dto.MessageResponse, int) {
r.t.Helper()
collected := []dto.MessageResponse{}
cursor := ""
for pages := 1; ; pages++ {
q := fmt.Sprintf("/api/v1/chats/%s/messages?limit=%d", chatID, pageSize)
if cursor != "" {
q += "&cursor=" + url.QueryEscape(cursor)
}
resp := r.do(http.MethodGet, q, actor.ID, nil, nil)
expectStatus(r.t, resp, http.StatusOK)
var page dto.MessagesPageResponse
readJSON(r.t, resp, &page)
collected = append(collected, page.Items...)
if page.NextCursor == nil {
return collected, pages
}
cursor = *page.NextCursor
if pages > 100_000 {
r.t.Fatalf("пагинация не сходится: next_cursor не исчезает")
}
}
}
func bootstrap(r *testRig) (alice, bob, eve testUser, chat dto.ChatResponse) {
alice = r.createUser("own_alice_"+randomSuffix(), "Алиса")
bob = r.createUser("own_bob_"+randomSuffix(), "Боб")
eve = r.createUser("own_eve_"+randomSuffix(), "Ева")
chat = r.createChat(alice, "Контрактный тест", alice.ID, bob.ID)
return
}
var suffixMu sync.Mutex
var suffixSeq int
func randomSuffix() string {
suffixMu.Lock()
defer suffixMu.Unlock()
suffixSeq++
return fmt.Sprintf("%09d_%d", time.Now().UnixNano()%1_000_000_000, suffixSeq)
}
func mustJSON(v any) []byte {
data, err := json.Marshal(v)
if err != nil {
panic(err)
}
return data
}
func extractErrorCode(t *testing.T, data []byte) string {
t.Helper()
var e errorResp
if err := json.Unmarshal(data, &e); err != nil {
t.Fatalf("decode error body: %v; raw=%s", err, string(data))
}
return e.Error.Code
}
const (
testMaxUploadBytes = 2 << 20
testMaxImagePixels = 10_000
testMaxConcurrentUploads = 4
)
// textMessage — тело POST сообщения без вложений.
func textMessage(text string) map[string]string {
return map[string]string{"text": text}
}
+119
View File
@@ -0,0 +1,119 @@
package http
import (
"bytes"
"io"
"net/http"
"sync"
"testing"
"github.com/google/uuid"
)
func (r *testRig) postKeyed(actorID, chatID, key, body string) (int, []byte) {
r.t.Helper()
resp := r.do(http.MethodPost, "/api/v1/chats/"+chatID+"/messages", actorID,
map[string]string{"Content-Type": "application/json", "Idempotency-Key": key},
bytes.NewReader([]byte(body)))
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
r.t.Fatal(err)
}
return resp.StatusCode, data
}
func TestIdempotency_ReplayReturnsSameBody(t *testing.T) {
r := newTestRig(t)
alice := r.createUser("alice_"+randomSuffix(), "Alice")
chat := r.createChat(alice, "replay", alice.ID)
key := uuid.NewString()
code, first := r.postKeyed(alice.ID, chat.ID, key, `{"text":"привет"}`)
if code != http.StatusCreated {
t.Fatalf("first: status = %d, body = %s", code, first)
}
// Иное форматирование JSON — тот же запрос.
code, replay := r.postKeyed(alice.ID, chat.ID, key, "{ \"text\" : \"привет\" }")
if code != http.StatusCreated {
t.Fatalf("replay: status = %d, body = %s", code, replay)
}
if !bytes.Equal(first, replay) {
t.Errorf("replay differs:\n%s\n%s", first, replay)
}
if items, _ := r.listMessages(alice, chat.ID, 100); len(items) != 1 {
t.Errorf("messages = %d, want 1", len(items))
}
}
func TestIdempotency_DifferentBodyConflicts(t *testing.T) {
r := newTestRig(t)
alice := r.createUser("alice_"+randomSuffix(), "Alice")
chat := r.createChat(alice, "conflict", alice.ID)
key := uuid.NewString()
if code, body := r.postKeyed(alice.ID, chat.ID, key, `{"text":"раз"}`); code != http.StatusCreated {
t.Fatalf("first: status = %d, body = %s", code, body)
}
if code, body := r.postKeyed(alice.ID, chat.ID, key, `{"text":"два"}`); code != http.StatusConflict {
t.Fatalf("conflict: status = %d, body = %s", code, body)
}
if items, _ := r.listMessages(alice, chat.ID, 100); len(items) != 1 {
t.Errorf("messages = %d, want 1", len(items))
}
}
func TestIdempotency_ScopeAndAccess(t *testing.T) {
r := newTestRig(t)
alice := r.createUser("alice_"+randomSuffix(), "Alice")
bob := r.createUser("bob_"+randomSuffix(), "Bob")
eve := r.createUser("eve_"+randomSuffix(), "Eve")
chat := r.createChat(alice, "shared", alice.ID, bob.ID)
other := r.createChat(alice, "other", alice.ID)
key := uuid.NewString()
if code, body := r.postKeyed(alice.ID, chat.ID, key, `{"text":"от alice"}`); code != http.StatusCreated {
t.Fatalf("alice: status = %d, body = %s", code, body)
}
if code, body := r.postKeyed(bob.ID, chat.ID, key, `{"text":"от bob"}`); code != http.StatusCreated {
t.Fatalf("bob: status = %d, body = %s", code, body)
}
if code, body := r.postKeyed(alice.ID, other.ID, key, `{"text":"другой чат"}`); code != http.StatusCreated {
t.Fatalf("other chat: status = %d, body = %s", code, body)
}
if code, body := r.postKeyed(eve.ID, chat.ID, key, `{"text":"от alice"}`); code != http.StatusNotFound {
t.Fatalf("stranger: status = %d, body = %s", code, body)
}
}
func TestIdempotency_ConcurrentCreatesOne(t *testing.T) {
r := newTestRig(t)
alice := r.createUser("alice_"+randomSuffix(), "Alice")
chat := r.createChat(alice, "race", alice.ID)
key := uuid.NewString()
const workers = 20
bodies := make([][]byte, workers)
codes := make([]int, workers)
var wg sync.WaitGroup
for i := range workers {
wg.Add(1)
go func() {
defer wg.Done()
codes[i], bodies[i] = r.postKeyed(alice.ID, chat.ID, key, `{"text":"гонка"}`)
}()
}
wg.Wait()
for i := range workers {
if codes[i] != http.StatusCreated {
t.Fatalf("worker %d: status = %d, body = %s", i, codes[i], bodies[i])
}
if !bytes.Equal(bodies[i], bodies[0]) {
t.Errorf("worker %d: body differs", i)
}
}
if items, _ := r.listMessages(alice, chat.ID, 100); len(items) != 1 {
t.Errorf("messages = %d, want 1", len(items))
}
}
+121
View File
@@ -0,0 +1,121 @@
package http
import (
"bytes"
"net/http"
"strings"
"testing"
"time"
"github.com/google/uuid"
)
func TestInstanceID_OnEveryResponse(t *testing.T) {
r := newTestRig(t)
cases := []struct {
name, method, path string
want int
}{
{"live", http.MethodGet, "/health/live", http.StatusOK},
{"ready", http.MethodGet, "/health/ready", http.StatusOK},
{"unauthorized", http.MethodGet, "/api/v1/users/me", http.StatusUnauthorized},
{"unknown route", http.MethodGet, "/api/v1/nope", http.StatusNotFound},
{"wrong method", http.MethodPatch, "/api/v1/users", http.StatusMethodNotAllowed},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
resp := r.do(tc.method, tc.path, "", nil, nil)
defer resp.Body.Close()
if resp.StatusCode != tc.want {
t.Fatalf("status = %d, want %d", resp.StatusCode, tc.want)
}
if got := resp.Header.Get("X-Instance-Id"); got != testInstanceID {
t.Errorf("X-Instance-Id = %q, want %q", got, testInstanceID)
}
})
}
}
func TestIdempotencyKey_Validation(t *testing.T) {
r := newTestRig(t)
alice := r.createUser("alice_key", "Alice")
chat := r.createChat(alice, "keys", alice.ID)
url := r.server.URL + "/api/v1/chats/" + chat.ID + "/messages"
post := func(setKey func(http.Header)) int {
t.Helper()
req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader([]byte(`{"text":"hi"}`)))
if err != nil {
t.Fatal(err)
}
req.Header.Set("Content-Type", "application/json")
r.setAuth(req, alice.ID)
setKey(req.Header)
resp, err := r.client.Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
return resp.StatusCode
}
withKey := func(key string) func(http.Header) {
return func(h http.Header) { h.Set("Idempotency-Key", key) }
}
if got := post(func(http.Header) {}); got != http.StatusBadRequest {
t.Errorf("missing key: status = %d, want 400", got)
}
for name, key := range map[string]string{
"empty": "",
"too long": strings.Repeat("a", 129),
"space": "a b",
"unicode": "ключ",
"slash": "a/b",
} {
if got := post(withKey(key)); got != http.StatusBadRequest {
t.Errorf("%s: status = %d, want 400", name, got)
}
}
for name, key := range map[string]string{
"all allowed chars": "aZ09._:-",
"max length": strings.Repeat("a", 128),
"uuid": uuid.NewString(),
} {
if got := post(withKey(key)); got != http.StatusCreated {
t.Errorf("%s: status = %d, want 201", name, got)
}
}
}
func TestDrain_NotReadyButStillServing(t *testing.T) {
r := newTestRig(t)
status := func(path string) int {
t.Helper()
resp := r.do(http.MethodGet, path, "", nil, nil)
defer resp.Body.Close()
return resp.StatusCode
}
if got := status("/health/ready"); got != http.StatusOK {
t.Fatalf("ready before drain = %d", got)
}
done := make(chan struct{})
go func() {
defer close(done)
r.srv.Drain(500 * time.Millisecond)
}()
deadline := time.Now().Add(400 * time.Millisecond)
for status("/health/ready") != http.StatusServiceUnavailable {
if time.Now().After(deadline) {
t.Fatal("readiness did not become 503 during drain")
}
time.Sleep(5 * time.Millisecond)
}
if got := status("/health/live"); got != http.StatusOK {
t.Errorf("live during drain = %d, want 200", got)
}
if got := status("/api/v1/users/me"); got != http.StatusUnauthorized {
t.Errorf("API during drain = %d, want 401: запросы должны обслуживаться", got)
}
<-done
}
+318
View File
@@ -0,0 +1,318 @@
package http
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/google/uuid"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/config"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/session"
)
func TestLimits_PayloadTooLarge(t *testing.T) {
r := newTestRigWithLimits(t, config.Limits{
MaxBodyBytes: 256,
MaxInFlight: 16,
MaxMessagesGlobal: 100,
MaxHeapBytes: 1 << 40,
})
alice := r.createUser("a_"+randomSuffix(), "Алиса")
bob := r.createUser("b_"+randomSuffix(), "Боб")
chat := r.createChat(alice, "Деградация", alice.ID, bob.ID)
ok, _, _ := r.sendRaw(alice, chat.ID, mustJSON(textMessage("ok")))
if ok != http.StatusCreated {
t.Fatalf("baseline send expected 201, got %d", ok)
}
stored := r.memory.MessagesTotal()
if stored != 1 {
t.Fatalf("baseline total expected 1, got %d", stored)
}
big := strings.Repeat("x", 512)
status, _, body := r.sendRaw(alice, chat.ID, mustJSON(textMessage(big)))
if status != http.StatusRequestEntityTooLarge {
t.Fatalf("expected 413 by content-length, got %d body=%s", status, string(body))
}
code := extractErrorCode(t, body)
if code != CodePayloadTooLarge {
t.Fatalf("expected code %q, got %q", CodePayloadTooLarge, code)
}
if got := r.memory.MessagesTotal(); got != stored {
t.Fatalf("после 413 store изменился: было %d, стало %d", stored, got)
}
}
func TestLimits_PayloadBoundaries(t *testing.T) {
const limit = 256
r := newTestRigWithLimits(t, config.Limits{
MaxBodyBytes: limit,
MaxInFlight: 16,
MaxMessagesGlobal: 100,
MaxHeapBytes: 1 << 40,
})
alice := r.createUser("a_"+randomSuffix(), "Алиса")
bob := r.createUser("b_"+randomSuffix(), "Боб")
chat := r.createChat(alice, "Деградация", alice.ID, bob.ID)
exact := []byte(`{"text":"` + strings.Repeat("x", limit-len(`{"text":""}`)) + `"}`)
if len(exact) != limit {
t.Fatalf("test bug: body is %d bytes, want %d", len(exact), limit)
}
post := func(body io.Reader) (int, []byte) {
req, _ := http.NewRequest(http.MethodPost,
r.server.URL+"/api/v1/chats/"+chat.ID+"/messages", body)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Idempotency-Key", uuid.NewString())
r.setAuth(req, alice.ID)
resp, err := r.client.Do(req)
if err != nil {
t.Fatalf("send: %v", err)
}
defer resp.Body.Close()
data, _ := io.ReadAll(resp.Body)
return resp.StatusCode, data
}
chunked := func(b []byte) io.Reader { return io.MultiReader(bytes.NewReader(b)) }
if status, body := post(bytes.NewReader(exact)); status != http.StatusCreated {
t.Fatalf("body ровно %d байт с Content-Length: expected 201, got %d body=%s", limit, status, body)
}
if status, body := post(chunked(exact)); status != http.StatusCreated {
t.Fatalf("body ровно %d байт без Content-Length: expected 201, got %d body=%s", limit, status, body)
}
stored := r.memory.MessagesTotal()
over := []byte(`{"text":"` + strings.Repeat("x", limit) + `"}`)
status, body := post(chunked(over))
if status != http.StatusRequestEntityTooLarge {
t.Fatalf("body %d байт без Content-Length: expected 413, got %d body=%s", len(over), status, body)
}
if code := extractErrorCode(t, body); code != CodePayloadTooLarge {
t.Fatalf("expected code %q, got %q", CodePayloadTooLarge, code)
}
if got := r.memory.MessagesTotal(); got != stored {
t.Fatalf("после 413 store изменился: было %d, стало %d", stored, got)
}
}
type slowSessions struct {
*session.Memory
delay atomic.Int64
}
func (s *slowSessions) Get(ctx context.Context, h []byte) (session.Session, error) {
time.Sleep(time.Duration(s.delay.Load()))
return s.Memory.Get(ctx, h)
}
func TestLimits_RateLimited(t *testing.T) {
sessions := &slowSessions{Memory: session.NewMemory()}
r := newRig(t, config.Limits{
MaxBodyBytes: 1 << 16,
MaxInFlight: 2,
MaxMessagesGlobal: 10000,
MaxHeapBytes: 1 << 40,
}, sessions, time.Hour)
alice := r.createUser("c_"+randomSuffix(), "Алиса")
bob := r.createUser("d_"+randomSuffix(), "Боб")
chat := r.createChat(alice, "Деградация", alice.ID, bob.ID)
sessions.delay.Store(int64(20 * time.Millisecond))
const total = 50
var (
ok atomic.Int32
throttled atomic.Int32
errs atomic.Int32
wg sync.WaitGroup
)
wg.Add(total)
start := make(chan struct{})
for i := 0; i < total; i++ {
i := i
go func() {
defer wg.Done()
<-start
client := &http.Client{Timeout: 10 * time.Second}
body, _ := json.Marshal(textMessage(fmt.Sprintf("flood-%d", i)))
req, _ := http.NewRequest(http.MethodPost,
r.server.URL+"/api/v1/chats/"+chat.ID+"/messages",
bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Idempotency-Key", uuid.NewString())
r.setAuth(req, alice.ID)
resp, err := client.Do(req)
if err != nil {
errs.Add(1)
return
}
switch resp.StatusCode {
case http.StatusCreated:
ok.Add(1)
case http.StatusTooManyRequests:
throttled.Add(1)
if resp.Header.Get("Retry-After") != "1" {
errs.Add(1)
}
default:
errs.Add(1)
}
resp.Body.Close()
}()
}
close(start)
wg.Wait()
sessions.delay.Store(0)
if errs.Load() != 0 {
t.Fatalf("неожиданные ошибки/статусы под нагрузкой: %d", errs.Load())
}
if throttled.Load() == 0 {
t.Fatalf("ожидался хотя бы один 429 при maxInFlight=2 и %d параллельных запросах", total)
}
if ok.Load() == 0 {
t.Fatalf("ни одного 201 — лимит не пропускает валидный трафик")
}
if int(ok.Load()+throttled.Load()) != total {
t.Fatalf("ok=%d throttled=%d не покрывают total=%d", ok.Load(), throttled.Load(), total)
}
deadline := time.Now().Add(3 * time.Second)
for time.Now().Before(deadline) {
status, _ := r.send(alice, chat.ID, "после-пика "+randomSuffix())
if status == http.StatusCreated {
break
}
time.Sleep(20 * time.Millisecond)
}
status, _ := r.send(alice, chat.ID, "после-пика-2 "+randomSuffix())
if status != http.StatusCreated {
t.Fatalf("после отступления нагрузки сервис не восстановился: %d", status)
}
collected, _ := r.listMessages(alice, chat.ID, 100)
if int32(len(collected)) < ok.Load() {
t.Fatalf("часть подтверждённых сообщений потеряна: подтверждено %d, в истории %d",
ok.Load(), len(collected))
}
t.Logf("ok=%d throttled=%d errors=%d; history=%d", ok.Load(), throttled.Load(), errs.Load(), len(collected))
}
func TestLimits_MessageQuota(t *testing.T) {
const quota = 10
r := newTestRigWithLimits(t, config.Limits{
MaxBodyBytes: 1 << 16,
MaxInFlight: 16,
MaxMessagesGlobal: quota,
MaxHeapBytes: 1 << 40,
})
alice := r.createUser("e_"+randomSuffix(), "Алиса")
bob := r.createUser("f_"+randomSuffix(), "Боб")
chat := r.createChat(alice, "Деградация", alice.ID, bob.ID)
var saved []string
for i := 0; i < quota; i++ {
status, msg := r.send(alice, chat.ID, fmt.Sprintf("saved-%02d", i))
if status != http.StatusCreated {
t.Fatalf("send %d: expected 201, got %d", i, status)
}
saved = append(saved, msg.ID)
}
status, _, body := r.sendRaw(alice, chat.ID, mustJSON(textMessage("overflow")))
if status != http.StatusServiceUnavailable {
t.Fatalf("expected 503 after quota exhausted, got %d body=%s", status, string(body))
}
if code := extractErrorCode(t, body); code != CodeUnavailable {
t.Fatalf("expected code %q, got %q", CodeUnavailable, code)
}
collected, _ := r.listMessages(alice, chat.ID, 100)
if len(collected) != quota {
t.Fatalf("после 503 история чата %d, ожидалось %d", len(collected), quota)
}
gotIDs := make(map[string]struct{}, len(collected))
for _, m := range collected {
gotIDs[m.ID] = struct{}{}
}
for _, id := range saved {
if _, ok := gotIDs[id]; !ok {
t.Fatalf("подтверждённое сообщение %s исчезло из истории", id)
}
}
for i := 0; i < 5; i++ {
s, _, _ := r.sendRaw(alice, chat.ID, mustJSON(textMessage("still-over")))
if s != http.StatusServiceUnavailable {
t.Fatalf("повторный 503 ожидался, получен %d", s)
}
}
req, _ := http.NewRequest(http.MethodGet, r.server.URL+"/health/live", nil)
resp, err := r.client.Do(req)
if err != nil {
t.Fatalf("health/live: %v", err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Fatalf("health/live под перегрузкой: ожидали 200, получили %d", resp.StatusCode)
}
}
func TestLimits_NoSilentLoss(t *testing.T) {
const quota = 20
r := newTestRigWithLimits(t, config.Limits{
MaxBodyBytes: 1 << 16,
MaxInFlight: 8,
MaxMessagesGlobal: quota,
MaxHeapBytes: 1 << 40,
})
alice := r.createUser("g_"+randomSuffix(), "Алиса")
bob := r.createUser("h_"+randomSuffix(), "Боб")
chat := r.createChat(alice, "Деградация", alice.ID, bob.ID)
const attempts = quota * 3
acked := make([]string, 0, quota)
codes := make(map[int]int)
for i := 0; i < attempts; i++ {
status, msg, _ := r.sendRaw(alice, chat.ID, mustJSON(textMessage(fmt.Sprintf("loss-%03d", i))))
codes[status]++
if status == http.StatusCreated {
acked = append(acked, msg.ID)
}
}
if len(acked) != quota {
t.Fatalf("ожидалось ровно %d подтверждённых записей, получено %d; codes=%v", quota, len(acked), codes)
}
if codes[http.StatusServiceUnavailable] == 0 {
t.Fatalf("ни одного 503 — лимит не сработал")
}
collected, _ := r.listMessages(alice, chat.ID, 100)
gotIDs := make(map[string]struct{}, len(collected))
for _, m := range collected {
gotIDs[m.ID] = struct{}{}
}
for _, id := range acked {
if _, ok := gotIDs[id]; !ok {
t.Fatalf("подтверждённое сообщение %s исчезло из истории — незаметная потеря данных", id)
}
}
if len(collected) != len(acked) {
t.Fatalf("история чата содержит %d сообщений, подтверждено %d — скрытое отличие",
len(collected), len(acked))
}
t.Logf("codes=%v acked=%d history=%d", codes, len(acked), len(collected))
}
+80
View File
@@ -0,0 +1,80 @@
package http
import (
"net/http"
"github.com/labstack/echo/v4"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/middleware"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/service"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate"
)
const headerIdempotencyKey = "Idempotency-Key"
type messagesHandler struct {
messages service.MessagesService
}
func (h *messagesHandler) send(c echo.Context) error {
callerID := c.Get(middleware.AuthUserIDKey).(string)
chatID := c.Param("chat_id")
var req dto.CreateMessageRequest
if err := decodeJSON(c.Request().Body, &req); err != nil {
return WriteError(c, err)
}
if req.Text == nil {
return WriteError(c, &validate.Error{Field: "text", Reason: "is required"})
}
msg, err := h.messages.Send(c.Request().Context(), callerID, chatID, c.Request().Header.Get(headerIdempotencyKey), *req.Text, req.AttachmentIDs)
if err != nil {
return WriteError(c, err)
}
return c.JSON(http.StatusCreated, toMessageResponse(msg))
}
func (h *messagesHandler) list(c echo.Context) error {
callerID := c.Get(middleware.AuthUserIDKey).(string)
chatID := c.Param("chat_id")
limit, cursor, err := parsePageParams(c)
if err != nil {
return WriteError(c, err)
}
page, err := h.messages.List(c.Request().Context(), callerID, chatID, cursor, limit)
if err != nil {
return WriteError(c, err)
}
return c.JSON(http.StatusOK, toMessagesPage(page))
}
func toMessageResponse(m domain.Message) dto.MessageResponse {
return dto.MessageResponse{
ID: m.ID,
ChatID: m.ChatID,
SenderID: m.AuthorID,
Text: m.Text,
CreatedAt: dto.NewTimestamp(m.CreatedAt),
// Без вложений в JSON должен быть [], а не null.
AttachmentIDs: append([]string{}, m.AttachmentIDs...),
}
}
func toMessagesPage(p domain.Page[domain.Message]) dto.MessagesPageResponse {
items := make([]dto.MessageResponse, 0, len(p.Items))
for _, m := range p.Items {
items = append(items, toMessageResponse(m))
}
var next *string
if p.NextCursor != "" {
s := p.NextCursor
next = &s
}
return dto.MessagesPageResponse{Items: items, NextCursor: next}
}
+61
View File
@@ -0,0 +1,61 @@
package middleware
import (
"context"
"errors"
"net/http"
"strings"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
"github.com/labstack/echo/v4"
)
const AuthTokenKey = "auth_token"
const (
BearerChallenge = `Bearer realm="messenger"`
BasicChallenge = `Basic realm="messenger", charset="UTF-8"`
)
type Authenticator interface {
Authenticate(ctx context.Context, token string) (userID string, err error)
}
func Bearer(auth Authenticator) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
tok, ok := BearerToken(c.Request().Header.Get(echo.HeaderAuthorization))
if !ok {
return unauthorized(c, BearerChallenge, "Bearer token required")
}
userID, err := auth.Authenticate(c.Request().Context(), tok)
if err != nil {
if errors.Is(err, domain.ErrUnauthorized) {
return unauthorized(c, BearerChallenge, "Invalid or expired session")
}
return err
}
c.Set(AuthUserIDKey, userID)
c.Set(AuthTokenKey, tok)
return next(c)
}
}
}
func BearerToken(header string) (string, bool) {
scheme, tok, found := strings.Cut(header, " ")
if !found || !strings.EqualFold(scheme, "Bearer") {
return "", false
}
tok = strings.TrimSpace(tok)
return tok, tok != ""
}
func unauthorized(c echo.Context, challenge, msg string) error {
c.Response().Header().Set(echo.HeaderWWWAuthenticate, challenge)
return echo.NewHTTPError(http.StatusUnauthorized, msg)
}
func Unauthorized(c echo.Context, challenge, msg string) error {
return unauthorized(c, challenge, msg)
}
@@ -0,0 +1,42 @@
package middleware
import (
"mime"
"net/http"
"strings"
"github.com/labstack/echo/v4"
)
func ContentType() echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
if !methodHasBody(c.Request().Method) {
return next(c)
}
if !isApplicationJSON(c.Request().Header.Get(echo.HeaderContentType)) {
return echo.NewHTTPError(http.StatusUnsupportedMediaType, "Expected Content-Type: application/json")
}
return next(c)
}
}
}
func methodHasBody(method string) bool {
switch method {
case http.MethodPost, http.MethodPut, http.MethodPatch:
return true
}
return false
}
func isApplicationJSON(ct string) bool {
if ct == "" {
return false
}
mediatype, _, err := mime.ParseMediaType(ct)
if err != nil {
return false
}
return strings.EqualFold(mediatype, "application/json")
}
@@ -0,0 +1,14 @@
package middleware
import "github.com/labstack/echo/v4"
const HeaderInstanceID = "X-Instance-Id"
func InstanceID(id string) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
c.Response().Header().Set(HeaderInstanceID, id)
return next(c)
}
}
}
+112
View File
@@ -0,0 +1,112 @@
package middleware
import (
"io"
"runtime"
"slices"
"sync/atomic"
"time"
"github.com/labstack/echo/v4"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
)
// BodyLimit ограничивает тело запроса. Маршруты из exemptRoutes применяют собственный лимит.
func BodyLimit(maxBytes int64, exemptRoutes ...string) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
if !methodHasBody(c.Request().Method) || slices.Contains(exemptRoutes, c.Path()) {
return next(c)
}
if cl := c.Request().ContentLength; cl > maxBytes {
return domain.ErrPayloadTooLarge
}
c.Request().Body = &limitedBody{
raw: c.Request().Body,
maxLeft: maxBytes,
}
return next(c)
}
}
}
type limitedBody struct {
raw io.ReadCloser
maxLeft int64
}
func (b *limitedBody) Read(p []byte) (int, error) {
if int64(len(p)) > b.maxLeft+1 {
p = p[:b.maxLeft+1]
}
n, err := b.raw.Read(p)
b.maxLeft -= int64(n)
if b.maxLeft < 0 {
return n, domain.ErrPayloadTooLarge
}
return n, err
}
func (b *limitedBody) Close() error {
return b.raw.Close()
}
func InFlight(maxInFlight int) echo.MiddlewareFunc {
sem := make(chan struct{}, maxInFlight)
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
if isHealthPath(c.Request().URL.Path) {
return next(c)
}
select {
case sem <- struct{}{}:
defer func() { <-sem }()
return next(c)
default:
return domain.ErrRateLimited
}
}
}
}
func MemoryGuard(maxHeapBytes uint64, poll time.Duration) echo.MiddlewareFunc {
var sample atomic.Uint64
readOnce := func() {
var m runtime.MemStats
runtime.ReadMemStats(&m)
if m.HeapInuse > maxHeapBytes {
runtime.GC()
runtime.ReadMemStats(&m)
}
sample.Store(m.HeapInuse)
}
readOnce()
if poll > 0 {
go func() {
t := time.NewTicker(poll)
defer t.Stop()
for range t.C {
readOnce()
}
}()
}
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
if !methodHasBody(c.Request().Method) || isHealthPath(c.Request().URL.Path) {
return next(c)
}
if sample.Load() > maxHeapBytes {
return domain.ErrUnavailable
}
return next(c)
}
}
}
func isHealthPath(path string) bool {
return path == "/health/live" || path == "/health/ready"
}
@@ -0,0 +1,48 @@
package middleware
import (
"log/slog"
"time"
"github.com/labstack/echo/v4"
"go.opentelemetry.io/otel/trace"
)
const AuthUserIDKey = "caller_id"
func Logger(logger *slog.Logger) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
start := time.Now()
if err := next(c); err != nil {
c.Error(err)
}
status := c.Response().Status
rid, _ := c.Get(RequestIDKey).(string)
sc := trace.SpanContextFromContext(c.Request().Context())
attrs := []slog.Attr{
slog.String("request_id", rid),
slog.String("method", c.Request().Method),
slog.String("route", c.Path()),
slog.Int("status", status),
slog.Int64("duration_ms", time.Since(start).Milliseconds()),
slog.String("event", "http.request"),
slog.String("trace_id", sc.TraceID().String()),
slog.String("span_id", sc.SpanID().String()),
}
level := slog.LevelInfo
switch {
case status >= 500:
level = slog.LevelError
case status >= 400:
level = slog.LevelWarn
}
logger.LogAttrs(c.Request().Context(), level, "http request", attrs...)
return nil
}
}
}
@@ -0,0 +1,32 @@
package middleware
import (
"log/slog"
"net/http"
"runtime/debug"
"github.com/labstack/echo/v4"
)
func Recover(logger *slog.Logger) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) (err error) {
defer func() {
r := recover()
if r == nil {
return
}
rid, _ := c.Get(RequestIDKey).(string)
logger.Error("panic recovered",
slog.String("request_id", rid),
slog.String("method", c.Request().Method),
slog.String("path", c.Request().URL.Path),
slog.Any("panic", r),
slog.String("stack", string(debug.Stack())),
)
err = echo.NewHTTPError(http.StatusInternalServerError, "Internal server error")
}()
return next(c)
}
}
}
@@ -0,0 +1,22 @@
package middleware
import (
"github.com/google/uuid"
"github.com/labstack/echo/v4"
)
const RequestIDKey = "request_id"
func RequestID() echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
rid := c.Request().Header.Get(echo.HeaderXRequestID)
if rid == "" {
rid = uuid.NewString()
}
c.Response().Header().Set(echo.HeaderXRequestID, rid)
c.Set(RequestIDKey, rid)
return next(c)
}
}
}
+126
View File
@@ -0,0 +1,126 @@
package http
import (
"encoding/base64"
"fmt"
"net/http"
"net/url"
"testing"
)
func TestPagination_MultiPageWalk(t *testing.T) {
r := newTestRig(t)
alice, bob, _, chat := bootstrap(r)
const total = 7
var sentIDs []string
for i := 0; i < total; i++ {
actor := alice
if i%2 == 1 {
actor = bob
}
_, msg := r.sendMessage(actor, chat.ID, fmt.Sprintf("page-%02d", i))
if msg.ID == "" {
t.Fatalf("send message %d failed", i)
}
sentIDs = append(sentIDs, msg.ID)
}
history, pages := r.listMessages(alice, chat.ID, 3)
if pages != 3 {
t.Fatalf("ожидалось 3 страницы (3+3+1), получено %d", pages)
}
if len(history) != total {
t.Fatalf("собрано %d сообщений, ожидалось %d", len(history), total)
}
for i, m := range history {
if m.ID != sentIDs[i] {
t.Fatalf("позиция %d: ожидался %s, получен %s (повтор, пропуск или нарушен порядок)", i, sentIDs[i], m.ID)
}
}
}
func TestPagination_ExactPageAndEmptyChat(t *testing.T) {
r := newTestRig(t)
alice, _, _, chat := bootstrap(r)
history, pages := r.listMessages(alice, chat.ID, 5)
if len(history) != 0 || pages != 1 {
t.Fatalf("пустой чат: items=%d pages=%d", len(history), pages)
}
for i := 0; i < 4; i++ {
r.send(alice, chat.ID, fmt.Sprintf("m%d", i))
}
if _, pages := r.listMessages(alice, chat.ID, 4); pages != 1 {
t.Fatalf("4 сообщения при limit=4: ожидалась 1 страница, получено %d", pages)
}
if _, pages := r.listMessages(alice, chat.ID, 2); pages != 2 {
t.Fatalf("4 сообщения при limit=2: ожидалось 2 страницы, получено %d", pages)
}
}
func TestPagination_CursorBoundToChat(t *testing.T) {
r := newTestRig(t)
alice, bob, _, chat := bootstrap(r)
other := r.createChat(alice, "Другой", alice.ID, bob.ID)
for i := 0; i < 3; i++ {
r.send(alice, chat.ID, fmt.Sprintf("m%d", i))
}
resp := r.do(http.MethodGet, "/api/v1/chats/"+chat.ID+"/messages?limit=1", alice.ID, nil, nil)
expectStatus(t, resp, http.StatusOK)
var page struct {
NextCursor *string `json:"next_cursor"`
}
readJSON(t, resp, &page)
if page.NextCursor == nil {
t.Fatal("ожидался next_cursor")
}
for _, path := range []string{
"/api/v1/chats/" + other.ID + "/messages?cursor=" + url.QueryEscape(*page.NextCursor),
"/api/v1/chats?cursor=" + url.QueryEscape(*page.NextCursor),
"/api/v1/chats/" + chat.ID + "/messages?cursor=not-a-cursor",
} {
resp := r.do(http.MethodGet, path, alice.ID, nil, nil)
expectStatus(t, resp, http.StatusBadRequest)
resp.Body.Close()
}
}
func TestPagination_IncompleteCursor(t *testing.T) {
r := newTestRig(t)
alice, _, _, chat := bootstrap(r)
r.send(alice, chat.ID, "m0")
enc := func(s string) string { return base64.RawURLEncoding.EncodeToString([]byte(s)) }
msgScope := `"s":"chat:` + chat.ID + `"`
chatsScope := `"s":"chats:` + alice.ID + `"`
ts := `"t":"2026-01-01T00:00:00Z"`
id := `"i":"` + chat.ID + `"`
cases := map[string]string{
"только scope": enc(`{` + msgScope + `}`),
"без i": enc(`{` + ts + `,` + msgScope + `}`),
"без t": enc(`{` + id + `,` + msgScope + `}`),
"i не UUID": enc(`{` + ts + `,"i":"zzz",` + msgScope + `}`),
"нулевое t": enc(`{"t":"0001-01-01T00:00:00Z",` + id + `,` + msgScope + `}`),
"лишнее поле": enc(`{` + ts + `,` + id + `,` + msgScope + `,"x":1}`),
"данные после объекта": enc(`{` + ts + `,` + id + `,` + msgScope + `}}`),
"base64 с паддингом": base64.URLEncoding.EncodeToString([]byte(`{` + ts + `,` + id + `,` + msgScope + `}`)),
"пустой объект": enc(`{}`),
"null": enc(`null`),
}
for name, cur := range cases {
resp := r.do(http.MethodGet, "/api/v1/chats/"+chat.ID+"/messages?cursor="+url.QueryEscape(cur), alice.ID, nil, nil)
if resp.StatusCode != http.StatusBadRequest {
t.Errorf("messages, %s: ожидался 400, получен %d", name, resp.StatusCode)
}
resp.Body.Close()
}
resp := r.do(http.MethodGet, "/api/v1/chats?cursor="+url.QueryEscape(enc(`{`+chatsScope+`}`)), alice.ID, nil, nil)
expectStatus(t, resp, http.StatusBadRequest)
resp.Body.Close()
}
+37
View File
@@ -0,0 +1,37 @@
package http
import (
"github.com/labstack/echo/v4"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/middleware"
)
func registerRoutes(e *echo.Echo, d Deps, isReady func() bool) {
e.GET("/health/live", healthLive)
e.GET("/health/ready", healthReady(isReady))
usersH := &usersHandler{users: d.Users}
chatsH := &chatsHandler{chats: d.Chats}
messagesH := &messagesHandler{messages: d.Messages}
authH := &authHandler{auth: d.Auth}
attachmentsH := &attachmentsHandler{attachments: d.Attachments}
auth := middleware.Bearer(d.Auth)
jsonBody := middleware.ContentType()
v1 := e.Group("/api/v1")
v1.POST("/users", usersH.create, jsonBody)
v1.POST("/auth/sessions", authH.createSession)
v1.DELETE("/auth/sessions/current", authH.revokeSession, auth)
v1.GET("/users/me", usersH.me, auth)
v1.POST("/chats", chatsH.create, auth, jsonBody)
v1.GET("/chats", chatsH.list, auth)
v1.GET("/chats/:chat_id", chatsH.get, auth)
v1.POST("/chats/:chat_id/messages", messagesH.send, auth, jsonBody)
v1.GET("/chats/:chat_id/messages", messagesH.list, auth)
// Тело здесь не JSON: Content-Type и размер проверяет сервис, после проверки доступа.
v1.POST("/chats/:chat_id/attachments", attachmentsH.upload, uploadTransfer, auth)
v1.GET("/attachments/:attachment_id", attachmentsH.get, auth)
v1.GET("/attachments/:attachment_id/content", attachmentsH.content, auth)
}
+176
View File
@@ -0,0 +1,176 @@
package http
import (
"context"
"errors"
"log/slog"
nethttp "net/http"
"sync/atomic"
"time"
"github.com/labstack/echo/v4"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/middleware"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/config"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/service"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/store"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/telemetry"
)
type Deps struct {
Config *config.Config
Logger *slog.Logger
Store store.Store
Auth service.AuthService
Users service.UsersService
Chats service.ChatsService
Messages service.MessagesService
Attachments service.AttachmentsService
Ready func(ctx context.Context) error
}
type Server struct {
e *echo.Echo
cfg config.HTTP
logger *slog.Logger
shutting atomic.Bool
ready func(ctx context.Context) error
}
func NewServer(d Deps) *Server {
s := &Server{
e: echo.New(),
cfg: d.Config.HTTP,
logger: d.Logger,
ready: d.Ready,
}
s.e.HideBanner = true
s.e.HidePort = true
s.e.HTTPErrorHandler = s.httpErrorHandler
s.e.Server.ReadTimeout = time.Duration(s.cfg.ReadTimeoutMs) * time.Millisecond
s.e.Server.WriteTimeout = time.Duration(s.cfg.WriteTimeoutMs) * time.Millisecond
s.e.Server.IdleTimeout = time.Duration(s.cfg.IdleTimeoutMs) * time.Millisecond
s.e.Use(middleware.InstanceID(d.Config.InstanceID))
s.e.Use(middleware.Recover(d.Logger))
s.e.Use(middleware.RequestID())
s.e.Use(telemetry.Middleware)
s.e.Use(middleware.Logger(d.Logger))
s.e.Use(middleware.InFlight(d.Config.Limits.MaxInFlight))
s.e.Use(middleware.BodyLimit(d.Config.Limits.MaxBodyBytes, routeUploadAttachment))
s.e.Use(middleware.MemoryGuard(d.Config.Limits.MaxHeapBytes, 100*time.Millisecond))
registerRoutes(s.e, d, s.IsReady)
return s
}
func (s *Server) Start() error {
s.logger.Info("http server starting", slog.String("addr", s.cfg.Addr))
err := s.e.Start(s.cfg.Addr)
if errors.Is(err, nethttp.ErrServerClosed) {
return nil
}
return err
}
// Drain переводит readiness в 503 и ждёт d, продолжая обслуживать запросы: за это время
// балансировщик выводит реплику, и новые запросы не попадают на закрытый listener.
func (s *Server) Drain(d time.Duration) {
s.shutting.Store(true)
s.logger.Info("http server draining", slog.Duration("for", d))
time.Sleep(d)
}
func (s *Server) Shutdown(ctx context.Context) error {
s.shutting.Store(true)
s.logger.Info("http server shutting down")
return s.e.Shutdown(ctx)
}
func (s *Server) IsReady() bool {
if s.shutting.Load() {
return false
}
if s.ready == nil {
return true
}
ctx, cancel := context.WithTimeout(context.Background(), readyTimeout)
defer cancel()
return s.ready(ctx) == nil
}
const readyTimeout = time.Second
func (s *Server) Handler() nethttp.Handler {
return s.e
}
func (s *Server) httpErrorHandler(err error, c echo.Context) {
if c.Response().Committed {
return
}
var httpErr *echo.HTTPError
if errors.As(err, &httpErr) {
code := codeFromStatus(httpErr.Code)
msg, _ := httpErr.Message.(string)
if msg == "" || msg == nethttp.StatusText(httpErr.Code) {
msg = messageFor(httpErr.Code, code)
}
_ = c.JSON(httpErr.Code, errorBody{
Error: errorPayload{
Code: code,
Message: msg,
RequestID: c.Response().Header().Get(echo.HeaderXRequestID),
},
})
return
}
_ = WriteError(c, err)
}
var codesByStatus = map[int]string{
nethttp.StatusBadRequest: CodeInvalidRequest,
nethttp.StatusUnauthorized: CodeUnauthorized,
nethttp.StatusNotFound: CodeNotFound,
nethttp.StatusMethodNotAllowed: CodeInvalidRequest,
nethttp.StatusConflict: CodeConflict,
nethttp.StatusRequestEntityTooLarge: CodePayloadTooLarge,
nethttp.StatusUnsupportedMediaType: CodeUnsupportedMedia,
nethttp.StatusTooManyRequests: CodeRateLimited,
nethttp.StatusServiceUnavailable: CodeUnavailable,
}
func codeFromStatus(status int) string {
if c, ok := codesByStatus[status]; ok {
return c
}
return CodeInternalError
}
var messagesByStatus = map[int]string{
nethttp.StatusMethodNotAllowed: "Method not allowed",
}
func messageFor(status int, code string) string {
if m, ok := messagesByStatus[status]; ok {
return m
}
return defaultMessages[code]
}
var defaultMessages = map[string]string{
CodeInvalidRequest: "Invalid request",
CodeUnauthorized: "Identification required",
CodeNotFound: "Object not found",
CodeConflict: "Conflict",
CodePayloadTooLarge: "Request body too large",
CodeUnsupportedMedia: "Unsupported Content-Type",
CodeRateLimited: "Too many requests",
CodeUnavailable: "Service unavailable",
CodeInternalError: "Internal server error",
}
+114
View File
@@ -0,0 +1,114 @@
package http
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"reflect"
"strings"
"unicode/utf8"
"github.com/labstack/echo/v4"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/middleware"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/domain"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/service"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/validate"
)
type usersHandler struct {
users service.UsersService
}
func (h *usersHandler) create(c echo.Context) error {
var req dto.CreateUserRequest
if err := decodeJSON(c.Request().Body, &req); err != nil {
return WriteError(c, err)
}
user, err := h.users.Register(c.Request().Context(), req.Username, req.DisplayName, req.Password)
if err != nil {
return WriteError(c, err)
}
return c.JSON(http.StatusCreated, toUserResponse(user))
}
func (h *usersHandler) me(c echo.Context) error {
callerID := c.Get(middleware.AuthUserIDKey).(string)
user, err := h.users.Me(c.Request().Context(), callerID)
if err != nil {
return WriteError(c, err)
}
return c.JSON(http.StatusOK, toUserResponse(user))
}
func toUserResponse(u domain.User) dto.UserResponse {
return dto.UserResponse{
ID: u.ID,
Username: u.Username,
DisplayName: u.DisplayName,
CreatedAt: dto.NewTimestamp(u.CreatedAt),
}
}
func decodeJSON(body io.Reader, dst any) error {
data, err := io.ReadAll(body)
if err != nil {
if errors.Is(err, domain.ErrPayloadTooLarge) {
return err
}
return &validate.Error{Field: "body", Reason: "cannot read body"}
}
if !utf8.Valid(data) {
return &validate.Error{Field: "body", Reason: "invalid UTF-8"}
}
dec := json.NewDecoder(bytes.NewReader(data))
dec.DisallowUnknownFields()
if err := dec.Decode(dst); err != nil {
return &validate.Error{Field: "body", Reason: jsonErrorReason(err)}
}
if _, err := dec.Token(); !errors.Is(err, io.EOF) {
return &validate.Error{Field: "body", Reason: "unexpected data after JSON object"}
}
return checkExactKeys(data, dst)
}
func checkExactKeys(data []byte, dst any) error {
var obj map[string]json.RawMessage
if err := json.Unmarshal(data, &obj); err != nil {
return nil
}
allowed := make(map[string]struct{})
t := reflect.TypeOf(dst).Elem()
for i := 0; i < t.NumField(); i++ {
name, _, _ := strings.Cut(t.Field(i).Tag.Get("json"), ",")
allowed[name] = struct{}{}
}
for key := range obj {
if _, ok := allowed[key]; !ok {
return &validate.Error{Field: "body", Reason: fmt.Sprintf("unknown field %q", key)}
}
}
return nil
}
func jsonErrorReason(err error) string {
if errors.Is(err, io.EOF) {
return "empty body"
}
var typeErr *json.UnmarshalTypeError
if errors.As(err, &typeErr) {
if typeErr.Field == "" {
return "expected a JSON object"
}
return fmt.Sprintf("field %q: invalid type", typeErr.Field)
}
if name, ok := strings.CutPrefix(err.Error(), "json: unknown field "); ok {
return "unknown field " + name
}
return "invalid JSON"
}
+230
View File
@@ -0,0 +1,230 @@
package http
import (
"bytes"
"io"
"net/http"
"strings"
"testing"
"gitflic.ru/project/relationskatie/mtusi2026lab1-ashchkl/internal/api/http/dto"
)
func TestValidation_InvalidJSON(t *testing.T) {
r := newTestRig(t)
alice, _, _, chat := bootstrap(r)
path := "/api/v1/chats/" + chat.ID + "/messages"
bad := [][]byte{
[]byte(`{"text":`),
[]byte(`not json at all`),
[]byte(`{"text": 123,}`),
[]byte(``),
[]byte(`{"text": "ok"}{"text":"bonus"}`),
[]byte(`{"text": "ok"}}`),
[]byte(`{"text": "ok"}]`),
[]byte(`{"text": "ok"} }`),
[]byte(`{"text": "ok"} x`),
[]byte("{\"text\":\"\xff\xfe bad utf8\"}"),
}
for _, payload := range bad {
resp := r.do(http.MethodPost, path, alice.ID,
map[string]string{"Content-Type": "application/json"},
bytes.NewReader(payload))
if resp.StatusCode != http.StatusBadRequest {
data, _ := io.ReadAll(resp.Body)
resp.Body.Close()
t.Fatalf("payload %q: expected 400, got %d; body=%s", payload, resp.StatusCode, string(data))
}
e := readError(t, resp)
if e.Error.Code != CodeInvalidRequest {
t.Fatalf("payload %q: expected code %q, got %q", payload, CodeInvalidRequest, e.Error.Code)
}
if e.Error.RequestID == "" {
t.Fatalf("payload %q: missing request_id in body", payload)
}
}
}
func TestValidation_InvalidUTF8(t *testing.T) {
r := newTestRig(t)
alice, bob, _, _ := bootstrap(r)
cases := []struct {
path, actor string
payload []byte
}{
{"/api/v1/users", "", []byte("{\"username\":\"u_" + randomSuffix()[:8] + "\",\"display_name\":\"\xc3\x28\"}")},
{"/api/v1/chats", alice.ID, []byte("{\"title\":\"\xe2\x82\",\"member_ids\":[\"" + alice.ID + "\",\"" + bob.ID + "\"]}")},
}
for _, tc := range cases {
resp := r.do(http.MethodPost, tc.path, tc.actor,
map[string]string{"Content-Type": "application/json"},
bytes.NewReader(tc.payload))
if resp.StatusCode != http.StatusBadRequest {
data, _ := io.ReadAll(resp.Body)
resp.Body.Close()
t.Fatalf("%s %q: expected 400, got %d; body=%s", tc.path, tc.payload, resp.StatusCode, string(data))
}
e := readError(t, resp)
if e.Error.Code != CodeInvalidRequest {
t.Fatalf("%s: expected code %q, got %q", tc.path, CodeInvalidRequest, e.Error.Code)
}
}
}
func TestValidation_JSONKeysAreCaseSensitive(t *testing.T) {
r := newTestRig(t)
resp := r.do(http.MethodPost, "/api/v1/users", "",
map[string]string{"Content-Type": "application/json"},
strings.NewReader(`{"USERNAME":"case_bob","Display_Name":"B"}`))
expectStatus(t, resp, http.StatusBadRequest)
resp.Body.Close()
}
func TestValidation_ErrorMessages(t *testing.T) {
r := newTestRig(t)
alice, bob, _, chat := bootstrap(r)
msgs := "/api/v1/chats/" + chat.ID + "/messages"
cases := []struct {
method, path, actor, body, message string
}{
{http.MethodPost, "/api/v1/users", "", `{"username":"ab","display_name":"x"}`,
"username: must match [a-z0-9_]{3,32}"},
{http.MethodPost, "/api/v1/users", "", `{"username":"abc_` + randomSuffix()[:6] + `","display_name":" "}`,
"display_name: must not be empty or whitespace only"},
{http.MethodPost, "/api/v1/users", "", `{"username":123,"display_name":"x"}`,
`body: field "username": invalid type`},
{http.MethodPost, "/api/v1/users", "", `{"username":"abc","display_name":"x","password":"p"}`,
"password: length must be in [12, 128] code points"},
{http.MethodPost, "/api/v1/users", "", `{"username":"abc","display_name":"x"}`,
"password: must not be empty or whitespace only"},
{http.MethodPost, "/api/v1/users", "", `{"username":"abc","display_name":"x","password":"` + strings.Repeat("я", 129) + `"}`,
"password: length must be in [12, 128] code points"},
{http.MethodPost, "/api/v1/users", "", `{"username":"abc","display_name":"x","password":"long-enough-pw","password_hash":"h"}`,
`body: unknown field "password_hash"`},
{http.MethodPost, "/api/v1/users", "", `{"username":`, "body: invalid JSON"},
{http.MethodPost, "/api/v1/users", "", ``, "body: empty body"},
{http.MethodPost, "/api/v1/users", "", `[]`, "body: expected a JSON object"},
{http.MethodPost, "/api/v1/users", "", `{"username":"abc","display_name":"x"} {}`, "body: unexpected data after JSON object"},
{http.MethodPost, "/api/v1/users", "", `{"username":"abc","display_name":"x"}}`, "body: unexpected data after JSON object"},
{http.MethodPost, "/api/v1/users", "", "{\"username\":\"abc\",\"display_name\":\"\xff\"}",
"body: invalid UTF-8"},
{http.MethodPost, "/api/v1/chats", alice.ID, `{"title":"t","member_ids":["` + bob.ID + `"]}`,
"member_ids: must contain caller"},
{http.MethodPost, "/api/v1/chats", alice.ID, `{"title":"t","member_ids":["` + alice.ID + `","x"]}`,
"member_ids[1]: must be a valid UUID"},
{http.MethodPost, msgs, alice.ID, `{"text":" "}`, "text: must not be empty or whitespace only"},
{http.MethodGet, msgs + "?limit=abc", alice.ID, "", "limit: must be an integer"},
{http.MethodGet, msgs + "?limit=0", alice.ID, "", "limit: must be in [1, 100]"},
{http.MethodGet, msgs + "?limit=", alice.ID, "", "limit: must be an integer"},
{http.MethodGet, msgs + "?cursor=", alice.ID, "", "cursor: must not be empty"},
{http.MethodGet, msgs + "?limit=10&cursor=", alice.ID, "", "cursor: must not be empty"},
{http.MethodGet, "/api/v1/chats?limit=", alice.ID, "", "limit: must be an integer"},
{http.MethodGet, "/api/v1/chats?cursor=", alice.ID, "", "cursor: must not be empty"},
}
for _, tc := range cases {
headers := map[string]string{}
var body io.Reader
if tc.method == http.MethodPost {
headers["Content-Type"] = "application/json"
body = bytes.NewReader([]byte(tc.body))
}
resp := r.do(tc.method, tc.path, tc.actor, headers, body)
if resp.StatusCode != http.StatusBadRequest {
data, _ := io.ReadAll(resp.Body)
resp.Body.Close()
t.Fatalf("%s %s %q: expected 400, got %d; body=%s", tc.method, tc.path, tc.body, resp.StatusCode, string(data))
}
e := readError(t, resp)
if e.Error.Message != tc.message {
t.Fatalf("%s %s %q:\n want %q\n got %q", tc.method, tc.path, tc.body, tc.message, e.Error.Message)
}
}
}
func TestValidation_EmptyMessage(t *testing.T) {
r := newTestRig(t)
alice, _, _, chat := bootstrap(r)
path := "/api/v1/chats/" + chat.ID + "/messages"
for _, text := range []string{"", " ", "\n\t "} {
resp := r.doJSON(http.MethodPost, path, alice.ID, textMessage(text))
if resp.StatusCode != http.StatusBadRequest {
data, _ := io.ReadAll(resp.Body)
resp.Body.Close()
t.Fatalf("text %q: expected 400, got %d; body=%s", text, resp.StatusCode, string(data))
}
e := readError(t, resp)
if e.Error.Code != CodeInvalidRequest {
t.Fatalf("text %q: expected code %q, got %q", text, CodeInvalidRequest, e.Error.Code)
}
}
}
func TestValidation_DuplicateUsername(t *testing.T) {
r := newTestRig(t)
username := "own_dup_" + randomSuffix()
first := r.doJSON(http.MethodPost, "/api/v1/users", "", dto.CreateUserRequest{
Username: username,
DisplayName: "Первый",
Password: testPassword,
})
expectStatus(t, first, http.StatusCreated)
first.Body.Close()
second := r.doJSON(http.MethodPost, "/api/v1/users", "", dto.CreateUserRequest{
Username: username,
DisplayName: "Второй",
Password: testPassword,
})
if second.StatusCode != http.StatusConflict {
data, _ := io.ReadAll(second.Body)
second.Body.Close()
t.Fatalf("second POST same username: expected 409, got %d; body=%s", second.StatusCode, string(data))
}
e := readError(t, second)
if e.Error.Code != CodeConflict {
t.Fatalf("expected code %q, got %q", CodeConflict, e.Error.Code)
}
third := r.doJSON(http.MethodPost, "/api/v1/users", "", dto.CreateUserRequest{
Username: username,
DisplayName: "Первый",
Password: testPassword,
})
if third.StatusCode != http.StatusConflict {
data, _ := io.ReadAll(third.Body)
third.Body.Close()
t.Fatalf("third POST same username/display_name: expected 409, got %d; body=%s", third.StatusCode, string(data))
}
third.Body.Close()
}
func TestValidation_UUIDForms(t *testing.T) {
r := newTestRig(t)
alice, bob, _, chat := bootstrap(r)
upper := strings.ToUpper(alice.ID)
resp := r.do(http.MethodGet, "/api/v1/users/me", upper, nil, nil)
expectStatus(t, resp, http.StatusOK)
resp.Body.Close()
resp = r.do(http.MethodGet, "/api/v1/chats/"+strings.ToUpper(chat.ID), alice.ID, nil, nil)
expectStatus(t, resp, http.StatusOK)
resp.Body.Close()
resp = r.do(http.MethodGet, "/api/v1/users/me", "{"+alice.ID+"}", nil, nil)
expectStatus(t, resp, http.StatusUnauthorized)
resp.Body.Close()
resp = r.do(http.MethodGet, "/api/v1/chats/"+strings.ReplaceAll(chat.ID, "-", ""), alice.ID, nil, nil)
expectStatus(t, resp, http.StatusBadRequest)
resp.Body.Close()
resp = r.doJSON(http.MethodPost, "/api/v1/chats", alice.ID, map[string]any{
"title": "dup", "member_ids": []string{alice.ID, upper, bob.ID},
})
expectStatus(t, resp, http.StatusBadRequest)
resp.Body.Close()
}