Files
mtusi2026lab6/service/tests/attachments_test.go
T
2026-11-17 13:08:13 +03:00

227 lines
7.8 KiB
Go

package tests
import (
"bytes"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"encoding/json"
"hash/crc32"
"image"
"image/jpeg"
"io"
"net/http"
"net/url"
"os"
"strings"
"sync"
"testing"
"time"
"github.com/google/uuid"
)
func (api *apiClient) upload(t *testing.T, chat, user, name, mime string, data []byte, chunked bool) apiResponse {
t.Helper()
req, e := http.NewRequest("POST", api.baseURL+"/api/v1/chats/"+chat+"/attachments?filename="+url.QueryEscape(name), bytes.NewReader(data))
if e != nil {
t.Fatal(e)
}
if chunked {
req.ContentLength = -1
}
req.Header.Set("Content-Type", mime)
if user != "" {
req.Header.Set("Authorization", "Bearer "+api.tokens[user])
}
resp, e := (&http.Client{Timeout: 20 * time.Second}).Do(req)
if e != nil {
t.Fatal(e)
}
defer resp.Body.Close()
body, e := io.ReadAll(resp.Body)
if e != nil {
t.Fatal(e)
}
if resp.Header.Get("X-Instance-Id") == "" {
t.Fatal("missing instance id")
}
return apiResponse{status: resp.StatusCode, body: body, requestID: resp.Header.Get("X-Request-Id"), instanceID: resp.Header.Get("X-Instance-Id")}
}
func fixturePNG(t *testing.T) []byte {
t.Helper()
b, e := os.ReadFile("../../tests/fixtures/sample.png")
if e != nil {
t.Fatal(e)
}
return b
}
func TestAttachmentContractAndErrors(t *testing.T) {
api := newAPI(t)
alice := api.createUser(t, "alice")
bob := api.createUser(t, "bob")
eve := api.createUser(t, "eve")
chat := api.createChat(t, alice, alice, bob)
other := api.createChat(t, alice, alice)
data := fixturePNG(t)
var att struct {
ID string `json:"id"`
Sha string `json:"sha256"`
Size int `json:"size_bytes"`
}
decodeOK(t, api.upload(t, chat, alice, "Файл.png", "image/png", data, false), 202, &att)
hash := sha256.Sum256(data)
if att.Sha != hex.EncodeToString(hash[:]) || att.Size != len(data) {
t.Fatal("original metadata mismatch")
}
waitAttachmentReady(t, api, alice, att.ID)
content := "/api/v1/attachments/" + att.ID + "/content"
got := api.request(t, "GET", content, bob, "")
if got.status != 200 || !bytes.Equal(got.body, data) {
t.Fatal("download changed bytes")
}
for _, suffix := range []string{"", "/content"} {
assertError(t, api.request(t, "GET", "/api/v1/attachments/"+att.ID+suffix, eve, ""), 404, "not_found")
}
assertError(t, api.upload(t, chat, eve, "file.png", "image/png", data, false), 404, "not_found")
assertError(t, api.upload(t, chat, "", "file.png", "image/png", data, false), 401, "unauthorized")
for _, name := range []string{"", " ", "../a.png", "a/b.png", "a\\b.png", "bad\x00.png", "bad\n.png", strings.Repeat("я", 256)} {
assertError(t, api.upload(t, chat, alice, name, "image/png", data, false), 400, "invalid_request")
}
for _, tc := range []struct {
name, mime string
data []byte
}{
{"fake", "image/png", []byte("not an image")},
{"mime mismatch", "image/jpeg", data},
{"wrong type", "application/octet-stream", data},
{"truncated", "image/png", data[:80]},
} {
t.Run(tc.name, func(t *testing.T) {
assertError(t, api.upload(t, chat, alice, "test.png", tc.mime, tc.data, false), 415, "unsupported_media_type")
})
}
bomb := bytes.Clone(data)
binary.BigEndian.PutUint32(bomb[16:20], 40000001)
binary.BigEndian.PutUint32(bomb[20:24], 1)
binary.BigEndian.PutUint32(bomb[29:33], crc32.ChecksumIEEE(bomb[12:29]))
assertError(t, api.upload(t, chat, alice, "bomb.png", "image/png", bomb, false), 413, "payload_too_large")
// A syntactically valid ancillary PNG chunk reaches the exact byte boundary
// without allocating an enormous decoded image.
padding := make([]byte, 10485760-len(data)-12)
chunk := append([]byte("paDd"), padding...)
boundary := append([]byte{}, data[:len(data)-12]...)
boundary = binary.BigEndian.AppendUint32(boundary, uint32(len(padding)))
boundary = append(boundary, chunk...)
boundary = binary.BigEndian.AppendUint32(boundary, crc32.ChecksumIEEE(chunk))
boundary = append(boundary, data[len(data)-12:]...)
var boundaryAtt map[string]any
decodeOK(t, api.upload(t, chat, alice, "boundary.png", "image/png", boundary, false), 202, &boundaryAtt)
oversized := make([]byte, 10485761)
copy(oversized, data)
for _, chunked := range []bool{false, true} {
assertError(t, api.upload(t, chat, alice, "large.png", "image/png", oversized, chunked), 413, "payload_too_large")
}
var jpg bytes.Buffer
if e := jpeg.Encode(&jpg, image.NewRGBA(image.Rect(0, 0, 32, 24)), nil); e != nil {
t.Fatal(e)
}
var jpegAtt map[string]any
decodeOK(t, api.upload(t, chat, bob, "file.jpg", "image/jpeg", jpg.Bytes(), false), 202, &jpegAtt)
imageOnly := `{"text":"","attachment_ids":["` + att.ID + `"]}`
var message map[string]any
key := uuid.NewString()
decodeOK(t, api.requestKey(t, "POST", "/api/v1/chats/"+chat+"/messages", bob, imageOnly, key), 201, &message)
var replay map[string]any
decodeOK(t, api.requestKey(t, "POST", "/api/v1/chats/"+chat+"/messages", bob, imageOnly, key), 201, &replay)
if jsonString(t, message) != jsonString(t, replay) {
t.Fatal("attachment retry changed message")
}
assertError(t, api.requestKey(t, "POST", "/api/v1/chats/"+chat+"/messages", bob, `{"text":"changed","attachment_ids":["`+att.ID+`"]}`, key), 409, "conflict")
assertError(t, api.request(t, "POST", "/api/v1/chats/"+other+"/messages", alice, imageOnly), 404, "not_found")
for _, body := range []string{`{"text":"","attachment_ids":["` + uuid.NewString() + `"]}`} {
assertError(t, api.request(t, "POST", "/api/v1/chats/"+chat+"/messages", alice, body), 404, "not_found")
}
for _, body := range []string{`{"text":""}`, `{"text":" "}`, `{"attachment_ids":["` + att.ID + `"]}`, `{"text":"ok","attachment_ids":null}`, `{"text":"ok","attachment_ids":"bad"}`, `{"text":"ok","attachment_ids":["` + att.ID + `","` + att.ID + `"]}`} {
assertError(t, api.request(t, "POST", "/api/v1/chats/"+chat+"/messages", alice, body), 400, "invalid_request")
}
if got := api.request(t, "GET", content+"?variant=thumbnail", bob, ""); got.status != 200 {
t.Fatal("thumbnail unavailable")
}
}
func TestConcurrentAttachmentMessage(t *testing.T) {
api := newAPI(t)
user := api.createUser(t, "alice")
chat := api.createChat(t, user, user)
var att struct {
ID string `json:"id"`
}
decodeOK(t, api.upload(t, chat, user, "sample.png", "image/png", fixturePNG(t), false), 202, &att)
key := uuid.NewString()
body := `{"text":"","attachment_ids":["` + att.ID + `"]}`
type result struct {
resp apiResponse
err error
}
ch := make(chan result, 16)
var wg sync.WaitGroup
for range 16 {
wg.Go(func() {
resp, e := api.send("POST", "/api/v1/chats/"+chat+"/messages", user, body, key)
ch <- result{resp, e}
})
}
wg.Wait()
close(ch)
seen := map[string]bool{}
var id string
for item := range ch {
if item.err != nil {
t.Fatal(item.err)
}
var msg struct {
ID string `json:"id"`
IDs []string `json:"attachment_ids"`
}
decodeOK(t, item.resp, 201, &msg)
if id != "" && id != msg.ID {
t.Fatal("duplicate attachment message")
}
id = msg.ID
seen[item.resp.instanceID] = true
if len(msg.IDs) != 1 || msg.IDs[0] != att.ID {
t.Fatal("lost attachment")
}
}
if len(seen) < 2 {
t.Fatal("did not exercise two replicas")
}
var page struct {
Items []json.RawMessage `json:"items"`
}
decodeOK(t, api.request(t, "GET", "/api/v1/chats/"+chat+"/messages", user, ""), 200, &page)
if len(page.Items) != 1 {
t.Fatal("duplicate history")
}
}
func waitAttachmentReady(t *testing.T, api *apiClient, user, id string) {
t.Helper()
deadline := time.Now().Add(60 * time.Second)
for time.Now().Before(deadline) {
var att struct {
Status string `json:"status"`
}
decodeOK(t, api.request(t, "GET", "/api/v1/attachments/"+id, user, ""), 200, &att)
if att.Status == "ready" {
return
}
if att.Status == "failed" {
t.Fatal("attachment failed")
}
time.Sleep(100 * time.Millisecond)
}
t.Fatal("attachment readiness deadline")
}