From 5f3efc63a084f97f92ce981ce76aaf1a70edaf87 Mon Sep 17 00:00:00 2001 From: kk10 Date: Tue, 3 Nov 2026 12:35:11 +0300 Subject: [PATCH] test(attachments): add upload tests --- deploy/nginx.conf | 2 + internal/handler/attachment.go | 6 +- student-tests/attachment_test.go | 197 +++++++++++++++++++++++++++++++ 3 files changed, 202 insertions(+), 3 deletions(-) create mode 100644 student-tests/attachment_test.go diff --git a/deploy/nginx.conf b/deploy/nginx.conf index 7b22fe90..f73980c5 100644 --- a/deploy/nginx.conf +++ b/deploy/nginx.conf @@ -8,6 +8,8 @@ http { server { listen 8080; + client_max_body_size 11m; + location ~ ^/api/v1/chats/[^/]+/messages$ { set $backend http://api:8080; proxy_pass $backend; diff --git a/internal/handler/attachment.go b/internal/handler/attachment.go index d9f1aa33..cc6e9a0e 100644 --- a/internal/handler/attachment.go +++ b/internal/handler/attachment.go @@ -51,7 +51,7 @@ func (h *AttachmentHandler) Upload(w http.ResponseWriter, r *http.Request) { if err != nil { var maxBytesErr *http.MaxBytesError if errors.As(err, &maxBytesErr) { - httpx.WriteError(w, http.StatusRequestEntityTooLarge, dto.ErrorCodeInvalidRequest, "file too large", requestID) + httpx.WriteError(w, http.StatusRequestEntityTooLarge, dto.ErrorCodePayloadTooLarge, "file too large", requestID) return } @@ -62,10 +62,10 @@ func (h *AttachmentHandler) Upload(w http.ResponseWriter, r *http.Request) { att, err := h.service.Upload(r.Context(), userID, chatID, req.Filename, body, contentType) switch { case errors.Is(err, service.ErrInvalidSize): - httpx.WriteError(w, http.StatusRequestEntityTooLarge, dto.ErrorCodeInvalidRequest, "file too large", requestID) + httpx.WriteError(w, http.StatusRequestEntityTooLarge, dto.ErrorCodePayloadTooLarge, "file too large", requestID) return case errors.Is(err, service.ErrInvalidImage): - httpx.WriteError(w, http.StatusUnsupportedMediaType, dto.ErrorCodeInvalidRequest, "invalid image", requestID) + httpx.WriteError(w, http.StatusUnsupportedMediaType, dto.ErrorCodeUnsupportedMediaType, "invalid image", requestID) return case errors.Is(err, service.ErrAttachmentNotFound): httpx.WriteError(w, http.StatusNotFound, dto.ErrorCodeNotFound, "not found", requestID) diff --git a/student-tests/attachment_test.go b/student-tests/attachment_test.go new file mode 100644 index 00000000..7a1dc616 --- /dev/null +++ b/student-tests/attachment_test.go @@ -0,0 +1,197 @@ +//go:build contract + +package studenttests_test + +import ( + "bytes" + "encoding/json" + "image" + "image/color" + "image/png" + "net/http" + "net/url" + "testing" + + "github.com/google/uuid" + + "mtusi2026-messenger/internal/dto" +) + +const maxUploadBytes = 10 * 1024 * 1024 + +func makePNG(t *testing.T, width, height int) []byte { + t.Helper() + + img := image.NewRGBA(image.Rect(0, 0, width, height)) + for y := 0; y < height; y++ { + for x := 0; x < width; x++ { + img.Set(x, y, color.RGBA{ + R: uint8((x * 7) % 256), + G: uint8((y * 13) % 256), + B: uint8((x + y) % 256), + A: 255, + }) + } + } + + var buf bytes.Buffer + if err := png.Encode(&buf, img); err != nil { + t.Fatalf("encode png: %v", err) + } + + return buf.Bytes() +} + +func uploadAttachment( + t *testing.T, + actor testUser, + chatID uuid.UUID, + filename string, + contentType string, + body []byte, +) *http.Response { + t.Helper() + + req, err := http.NewRequest( + http.MethodPost, + *baseURL+"/api/v1/chats/"+chatID.String()+"/attachments?filename="+url.QueryEscape(filename), + bytes.NewReader(body), + ) + if err != nil { + t.Fatalf("build upload request: %v", err) + } + req.Header.Set("Content-Type", contentType) + req.Header.Set("Authorization", "Bearer "+actor.Token) + + resp, err := httpClient.Do(req) + if err != nil { + t.Fatalf("upload request failed: %v", err) + } + + return resp +} + +func uploadPNG(t *testing.T, actor testUser, chatID uuid.UUID) dto.AttachmentResponse { + t.Helper() + + resp := uploadAttachment(t, actor, chatID, "sample.png", "image/png", makePNG(t, 32, 32)) + requireStatus(t, resp, http.StatusCreated) + + var att dto.AttachmentResponse + mustDecode(t, resp, &att) + + return att +} + +func postMessage( + t *testing.T, + actor testUser, + chatID uuid.UUID, + text string, + attachmentIDs []uuid.UUID, +) *http.Response { + t.Helper() + + body, err := json.Marshal(map[string]any{ + "text": text, + "attachment_ids": attachmentIDs, + }) + if err != nil { + t.Fatalf("marshal message: %v", err) + } + + req, err := http.NewRequest( + http.MethodPost, + *baseURL+"/api/v1/chats/"+chatID.String()+"/messages", + bytes.NewReader(body), + ) + if err != nil { + t.Fatalf("build message request: %v", err) + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Authorization", "Bearer "+actor.Token) + req.Header.Set("Idempotency-Key", uuid.NewString()) + + resp, err := httpClient.Do(req) + if err != nil { + t.Fatalf("message request failed: %v", err) + } + + return resp +} + +func requireErrorCode(t *testing.T, resp *http.Response, code dto.ErrorCode) { + t.Helper() + + var apiErr dto.ErrorResponse + mustDecode(t, resp, &apiErr) + + if apiErr.Error.Code != code { + t.Errorf("expected error code %q, got %q", code, apiErr.Error.Code) + } +} + +func TestAttachmentTooLarge(t *testing.T) { + user := createUser(t) + chat := createChat(t, user, user.ID) + + body := bytes.Repeat([]byte{0x00}, maxUploadBytes+1) + + resp := uploadAttachment(t, user, chat.ID, "big.png", "image/png", body) + requireStatus(t, resp, http.StatusRequestEntityTooLarge) + requireErrorCode(t, resp, dto.ErrorCodePayloadTooLarge) +} + +func TestAttachmentCorruptedImage(t *testing.T) { + user := createUser(t) + chat := createChat(t, user, user.ID) + + body := []byte("this is definitely not a png or jpeg image") + + resp := uploadAttachment(t, user, chat.ID, "broken.png", "image/png", body) + requireStatus(t, resp, http.StatusUnsupportedMediaType) + requireErrorCode(t, resp, dto.ErrorCodeUnsupportedMediaType) +} + +func TestAttachmentMimeSubstitution(t *testing.T) { + user := createUser(t) + chat := createChat(t, user, user.ID) + + resp := uploadAttachment(t, user, chat.ID, "actually-png.jpg", "image/jpeg", makePNG(t, 32, 32)) + requireStatus(t, resp, http.StatusUnsupportedMediaType) + requireErrorCode(t, resp, dto.ErrorCodeUnsupportedMediaType) +} + +func TestAttachmentForeignID(t *testing.T) { + user := createUser(t) + chat := createChat(t, user, user.ID) + + foreign := uuid.New() + + resp := doRequest(t, http.MethodGet, "/api/v1/attachments/"+foreign.String(), user.Token, nil) + requireStatus(t, resp, http.StatusNotFound) + requireErrorCode(t, resp, dto.ErrorCodeNotFound) + + resp = doRequest(t, http.MethodGet, "/api/v1/attachments/"+foreign.String()+"/content", user.Token, nil) + requireStatus(t, resp, http.StatusNotFound) + requireErrorCode(t, resp, dto.ErrorCodeNotFound) + + resp = postMessage(t, user, chat.ID, "", []uuid.UUID{foreign}) + requireStatus(t, resp, http.StatusNotFound) + requireErrorCode(t, resp, dto.ErrorCodeNotFound) +} + +func TestAttachmentFromAnotherChat(t *testing.T) { + user := createUser(t) + member := createUser(t) + + chatA := createChat(t, user, user.ID, member.ID) + chatB := createChat(t, user, user.ID) + + att := uploadPNG(t, user, chatA.ID) + + // The attachment belongs to chatA; linking it to a chatB message must fail. + resp := postMessage(t, user, chatB.ID, "", []uuid.UUID{att.ID}) + requireStatus(t, resp, http.StatusNotFound) + requireErrorCode(t, resp, dto.ErrorCodeNotFound) +}