Единый бинарник с objectstore/reconcile, pinned MinIO при недоступности Docker Hub, автотесты и evidence на оценку 5.
744 lines
32 KiB
Go
744 lines
32 KiB
Go
// Собственные проверки lab4: вложения (S3 + PostgreSQL).
|
||
//
|
||
// Покрыто (требования уровня «4»): слишком большой файл, повреждённое изображение,
|
||
// подмена MIME, чужое attachment_id, вложение другого чата, недоступный S3,
|
||
// компенсация при отказе PG после PUT, параллельные загрузки.
|
||
// Реальные PNG/JPEG генерируются на лету (стандартная библиотека), внешних фикстур нет.
|
||
package studenttests
|
||
|
||
import (
|
||
"bytes"
|
||
"compress/zlib"
|
||
"context"
|
||
"crypto/sha256"
|
||
"encoding/binary"
|
||
"encoding/hex"
|
||
"errors"
|
||
"fmt"
|
||
"hash/crc32"
|
||
"image"
|
||
"image/color"
|
||
"image/jpeg"
|
||
"image/png"
|
||
"io"
|
||
"math/rand"
|
||
"net/http"
|
||
"net/http/httptest"
|
||
"net/url"
|
||
"strings"
|
||
"sync"
|
||
"testing"
|
||
"time"
|
||
|
||
"github.com/google/uuid"
|
||
|
||
"mtusi2026lab4/internal/api"
|
||
"mtusi2026lab4/internal/auth"
|
||
"mtusi2026lab4/internal/objectstore"
|
||
"mtusi2026lab4/internal/session"
|
||
"mtusi2026lab4/internal/store"
|
||
)
|
||
|
||
const maxUpload = 10 << 20 // 10 MiB — лимит контракта
|
||
|
||
// ---------------------------------------------------------------- генераторы файлов
|
||
|
||
// noisePNG — настоящий PNG из псевдослучайного шума (плохо сжимается → размер ≈ w*h*4).
|
||
func noisePNG(t *testing.T, w, h int) []byte {
|
||
t.Helper()
|
||
rng := rand.New(rand.NewSource(int64(w*100003 + h)))
|
||
img := image.NewNRGBA(image.Rect(0, 0, w, h))
|
||
rng.Read(img.Pix)
|
||
var buf bytes.Buffer
|
||
if err := png.Encode(&buf, img); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
return buf.Bytes()
|
||
}
|
||
|
||
// smallJPEG — настоящий JPEG.
|
||
func smallJPEG(t *testing.T, w, h int) []byte {
|
||
t.Helper()
|
||
img := image.NewRGBA(image.Rect(0, 0, w, h))
|
||
for y := 0; y < h; y++ {
|
||
for x := 0; x < w; x++ {
|
||
img.Set(x, y, color.RGBA{uint8(x * 3), uint8(y * 5), uint8(x ^ y), 255})
|
||
}
|
||
}
|
||
var buf bytes.Buffer
|
||
if err := jpeg.Encode(&buf, img, &jpeg.Options{Quality: 80}); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
return buf.Bytes()
|
||
}
|
||
|
||
// craftPNG собирает ВАЛИДНЫЙ 1-битный серый PNG заданных размеров вручную: данные —
|
||
// нули, сжимаются до пары КБ даже для десятков миллионов пикселей. Нужен для проверки
|
||
// лимита пикселей без гигабайтных буферов в тесте.
|
||
func craftPNG(w, h int) []byte {
|
||
var idat bytes.Buffer
|
||
zw := zlib.NewWriter(&idat)
|
||
row := make([]byte, 1+(w+7)/8) // фильтр 0 + биты строки
|
||
for y := 0; y < h; y++ {
|
||
_, _ = zw.Write(row)
|
||
}
|
||
_ = zw.Close()
|
||
|
||
var out bytes.Buffer
|
||
out.WriteString("\x89PNG\r\n\x1a\n")
|
||
chunk := func(typ string, data []byte) {
|
||
var l [4]byte
|
||
binary.BigEndian.PutUint32(l[:], uint32(len(data)))
|
||
out.Write(l[:])
|
||
out.WriteString(typ)
|
||
out.Write(data)
|
||
var c [4]byte
|
||
binary.BigEndian.PutUint32(c[:], crc32.ChecksumIEEE(append([]byte(typ), data...)))
|
||
out.Write(c[:])
|
||
}
|
||
ihdr := make([]byte, 13)
|
||
binary.BigEndian.PutUint32(ihdr[0:], uint32(w))
|
||
binary.BigEndian.PutUint32(ihdr[4:], uint32(h))
|
||
ihdr[8], ihdr[9] = 1, 0 // глубина 1 бит, grayscale
|
||
chunk("IHDR", ihdr)
|
||
chunk("IDAT", idat.Bytes())
|
||
chunk("IEND", nil)
|
||
return out.Bytes()
|
||
}
|
||
|
||
// ---------------------------------------------------------------- HTTP-хелперы
|
||
|
||
type chatCtx struct {
|
||
srv *httptest.Server
|
||
owner account
|
||
token string
|
||
chat string
|
||
}
|
||
|
||
func newChatCtx(t *testing.T, prefix string) chatCtx {
|
||
t.Helper()
|
||
srv := newAPI(t, time.Hour)
|
||
t.Cleanup(srv.Close)
|
||
u := register(t, srv, prefix)
|
||
tok := login(t, srv, u.username, u.password)
|
||
return chatCtx{srv: srv, owner: u, token: tok, chat: createChat(t, srv, tok, u.id, "Вложения "+prefix)}
|
||
}
|
||
|
||
// upload отправляет сырой binary. contentType "" → заголовок не ставится.
|
||
func upload(t *testing.T, srv *httptest.Server, token, chat, filename, contentType string, body []byte) (int, []byte, http.Header) {
|
||
t.Helper()
|
||
u := srv.URL + "/api/v1/chats/" + chat + "/attachments?filename=" + url.QueryEscape(filename)
|
||
req, err := http.NewRequest(http.MethodPost, u, bytes.NewReader(body))
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if token != "" {
|
||
req.Header.Set("Authorization", "Bearer "+token)
|
||
}
|
||
if contentType != "" {
|
||
req.Header.Set("Content-Type", contentType)
|
||
}
|
||
resp, err := http.DefaultClient.Do(req)
|
||
if err != nil {
|
||
t.Fatalf("upload transport error (ждали HTTP-ответ): %v", err)
|
||
}
|
||
defer resp.Body.Close()
|
||
b, _ := io.ReadAll(resp.Body)
|
||
return resp.StatusCode, b, resp.Header
|
||
}
|
||
|
||
func mustUpload(t *testing.T, c chatCtx, filename, ctype string, body []byte) map[string]any {
|
||
t.Helper()
|
||
status, b, _ := upload(t, c.srv, c.token, c.chat, filename, ctype, body)
|
||
if status != http.StatusCreated {
|
||
t.Fatalf("upload %s: status=%d body=%s", filename, status, string(b))
|
||
}
|
||
return decode(t, string(b))
|
||
}
|
||
|
||
// get без следования редиректам: контракт требует отдавать байты самим API.
|
||
func getNoRedirect(t *testing.T, srv *httptest.Server, token, path string) (int, []byte, http.Header) {
|
||
t.Helper()
|
||
client := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
|
||
req, _ := http.NewRequest(http.MethodGet, srv.URL+path, nil)
|
||
req.Header.Set("Authorization", "Bearer "+token)
|
||
resp, err := client.Do(req)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
defer resp.Body.Close()
|
||
b, _ := io.ReadAll(resp.Body)
|
||
return resp.StatusCode, b, resp.Header
|
||
}
|
||
|
||
func createChatWith(t *testing.T, srv *httptest.Server, token, title string, ids ...string) string {
|
||
t.Helper()
|
||
quoted := make([]string, len(ids))
|
||
for i, id := range ids {
|
||
quoted[i] = fmt.Sprintf("%q", id)
|
||
}
|
||
raw := fmt.Sprintf(`{"title":%q,"member_ids":[%s]}`, title, strings.Join(quoted, ","))
|
||
status, body := do(t, srv, http.MethodPost, "/api/v1/chats", map[string]string{"Authorization": "Bearer " + token}, raw)
|
||
if status != http.StatusCreated {
|
||
t.Fatalf("chat: %d %s", status, body)
|
||
}
|
||
return decode(t, body)["id"].(string)
|
||
}
|
||
|
||
func postMessage(t *testing.T, srv *httptest.Server, token, chat, key, rawJSON string) (int, string) {
|
||
t.Helper()
|
||
return do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", map[string]string{
|
||
"Authorization": "Bearer " + token,
|
||
"Idempotency-Key": key,
|
||
}, rawJSON)
|
||
}
|
||
|
||
func hexSHA(b []byte) string { s := sha256.Sum256(b); return hex.EncodeToString(s[:]) }
|
||
|
||
// ---------------------------------------------------------------- тесты
|
||
|
||
// Полный путь: upload → метаданные → байты → сообщение с вложением → чтение вторым
|
||
// участником → 404 постороннему. Заодно: идемпотентный replay сохраняет attachment_ids.
|
||
func TestAttachmentRoundTripAndAccessControl(t *testing.T) {
|
||
logStep(t, "PNG и JPEG: 201 ready, sha256/size, download без redirect, доступ только участникам")
|
||
srv := newAPI(t, time.Hour)
|
||
defer srv.Close()
|
||
alice := register(t, srv, "att_alice")
|
||
bob := register(t, srv, "att_bob")
|
||
eve := register(t, srv, "att_eve")
|
||
tokA := login(t, srv, alice.username, alice.password)
|
||
tokB := login(t, srv, bob.username, bob.password)
|
||
tokE := login(t, srv, eve.username, eve.password)
|
||
chat := createChatWith(t, srv, tokA, "Общий", alice.id, bob.id)
|
||
c := chatCtx{srv: srv, owner: alice, token: tokA, chat: chat}
|
||
|
||
pngData := noisePNG(t, 120, 90)
|
||
meta := mustUpload(t, c, "фото.png", "image/png", pngData)
|
||
if meta["status"] != "ready" || meta["error_code"] != nil || meta["content_type"] != "image/png" {
|
||
t.Fatalf("метаданные: %v", meta)
|
||
}
|
||
if v, ok := meta["variants"].([]any); !ok || len(v) != 0 {
|
||
t.Fatalf("variants должен быть []: %v", meta["variants"])
|
||
}
|
||
if meta["sha256"] != hexSHA(pngData) || int(meta["size_bytes"].(float64)) != len(pngData) {
|
||
t.Fatalf("sha256/size не совпали: %v", meta)
|
||
}
|
||
if meta["owner_id"] != alice.id || meta["chat_id"] != chat || meta["filename"] != "фото.png" {
|
||
t.Fatalf("owner/chat/filename: %v", meta)
|
||
}
|
||
for _, k := range []string{"object_key", "bucket", "key"} {
|
||
if _, leaked := meta[k]; leaked {
|
||
t.Fatalf("в публичном ответе утёк внутренний ключ %q", k)
|
||
}
|
||
}
|
||
id := meta["id"].(string)
|
||
|
||
// Метаданные и байты — участнику Bob (не загрузившему).
|
||
status, body, _ := getNoRedirect(t, srv, tokB, "/api/v1/attachments/"+id)
|
||
if status != http.StatusOK || decode(t, string(body))["sha256"] != hexSHA(pngData) {
|
||
t.Fatalf("meta by bob: %d %s", status, body)
|
||
}
|
||
status, got, hdr := getNoRedirect(t, srv, tokB, "/api/v1/attachments/"+id+"/content")
|
||
if status != http.StatusOK || hdr.Get("Content-Type") != "image/png" || hexSHA(got) != hexSHA(pngData) {
|
||
t.Fatalf("download: status=%d ct=%q sha=%s", status, hdr.Get("Content-Type"), hexSHA(got))
|
||
}
|
||
if hdr.Get("Location") != "" {
|
||
t.Fatal("download не должен быть redirect")
|
||
}
|
||
|
||
// JPEG тем же путём.
|
||
jpgData := smallJPEG(t, 64, 48)
|
||
jmeta := mustUpload(t, c, "pic.jpg", "image/jpeg", jpgData)
|
||
if jmeta["content_type"] != "image/jpeg" || jmeta["sha256"] != hexSHA(jpgData) {
|
||
t.Fatalf("jpeg meta: %v", jmeta)
|
||
}
|
||
|
||
// Посторонний: метаданные, байты, загрузка — всё 404 (не 403, не раскрываем существование).
|
||
for _, path := range []string{"/api/v1/attachments/" + id, "/api/v1/attachments/" + id + "/content"} {
|
||
status, body, _ := getNoRedirect(t, srv, tokE, path)
|
||
logResult(t, status, string(body))
|
||
if status != http.StatusNotFound {
|
||
t.Fatalf("outsider GET %s: %d", path, status)
|
||
}
|
||
}
|
||
status, body, _ = upload(t, srv, tokE, chat, "x.png", "image/png", pngData)
|
||
if status != http.StatusNotFound {
|
||
t.Fatalf("outsider upload: %d %s", status, body)
|
||
}
|
||
// Без токена — 401.
|
||
status, _, _ = upload(t, srv, "", chat, "x.png", "image/png", pngData)
|
||
if status != http.StatusUnauthorized {
|
||
t.Fatalf("upload без токена: %d", status)
|
||
}
|
||
// Неизвестный вариант и несуществующее вложение.
|
||
status, _, _ = getNoRedirect(t, srv, tokB, "/api/v1/attachments/"+id+"/content?variant=thumbnail")
|
||
if status != http.StatusNotFound {
|
||
t.Fatalf("variant=thumbnail у ready-объекта: %d", status)
|
||
}
|
||
status, _, _ = getNoRedirect(t, srv, tokB, "/api/v1/attachments/"+uuid.NewString())
|
||
if status != http.StatusNotFound {
|
||
t.Fatalf("unknown attachment: %d", status)
|
||
}
|
||
|
||
// Сообщение с двумя вложениями (порядок сохраняется), затем чтение Bob'ом.
|
||
jid := jmeta["id"].(string)
|
||
key := "msg-" + uuid.NewString()
|
||
raw := fmt.Sprintf(`{"text":"смотри","attachment_ids":[%q,%q]}`, jid, id)
|
||
status, mbody := postMessage(t, srv, tokA, chat, key, raw)
|
||
logResult(t, status, mbody)
|
||
if status != http.StatusCreated {
|
||
t.Fatalf("message with attachments: %d %s", status, mbody)
|
||
}
|
||
msg := decode(t, mbody)
|
||
ids := msg["attachment_ids"].([]any)
|
||
if len(ids) != 2 || ids[0] != jid || ids[1] != id {
|
||
t.Fatalf("порядок/состав attachment_ids: %v", ids)
|
||
}
|
||
// Replay с тем же ключом → то же сообщение И те же attachment_ids.
|
||
status, body2 := postMessage(t, srv, tokA, chat, key, raw)
|
||
if status != http.StatusCreated || decode(t, body2)["id"] != msg["id"] {
|
||
t.Fatalf("replay: %d %s", status, body2)
|
||
}
|
||
if rid := decode(t, body2)["attachment_ids"].([]any); len(rid) != 2 || rid[0] != jid {
|
||
t.Fatalf("replay потерял attachment_ids: %v", rid)
|
||
}
|
||
// Тот же ключ, другой набор вложений → 409.
|
||
status, _ = postMessage(t, srv, tokA, chat, key, fmt.Sprintf(`{"text":"смотри","attachment_ids":[%q]}`, id))
|
||
if status != http.StatusConflict {
|
||
t.Fatalf("тот же ключ, другие вложения: %d", status)
|
||
}
|
||
|
||
status, body, _ = getNoRedirect(t, srv, tokB, "/api/v1/chats/"+chat+"/messages")
|
||
if status != http.StatusOK || !strings.Contains(string(body), jid) {
|
||
t.Fatalf("история Bob: %d %s", status, body)
|
||
}
|
||
status, _, _ = getNoRedirect(t, srv, tokE, "/api/v1/chats/"+chat+"/messages")
|
||
if status != http.StatusNotFound {
|
||
t.Fatalf("история постороннего: %d", status)
|
||
}
|
||
logOK(t, "upload/download/доступ/replay работают, внутренние ключи не раскрываются")
|
||
}
|
||
|
||
// Слишком большой файл → 413 (границу проверяем с точностью до байта).
|
||
func TestAttachmentTooLarge(t *testing.T) {
|
||
logStep(t, "ровно 10 MiB проходит лимит размера (дальше 415 как не-картинка), 10 MiB+1 → 413")
|
||
c := newChatCtx(t, "att_big")
|
||
header := noisePNG(t, 8, 8)[:8] // валидная сигнатура PNG, чтобы тело «похоже» на картинку
|
||
|
||
atLimit := append(append([]byte{}, header...), make([]byte, maxUpload-len(header))...)
|
||
status, b, _ := upload(t, c.srv, c.token, c.chat, "limit.png", "image/png", atLimit)
|
||
logResult(t, status, string(b))
|
||
if status != http.StatusUnsupportedMediaType {
|
||
t.Fatalf("ровно 10 MiB мусора: ждали 415 (размер допустим), got %d", status)
|
||
}
|
||
|
||
over := append(append([]byte{}, header...), make([]byte, maxUpload-len(header)+1)...)
|
||
status, b, _ = upload(t, c.srv, c.token, c.chat, "big.png", "image/png", over)
|
||
logResult(t, status, string(b))
|
||
if status != http.StatusRequestEntityTooLarge || !strings.Contains(string(b), "payload_too_large") {
|
||
t.Fatalf("10 MiB+1: ждали 413, got %d %s", status, b)
|
||
}
|
||
|
||
// Заметно больше лимита: клиент должен получить именно 413, а не сброс соединения.
|
||
huge := make([]byte, 14<<20)
|
||
copy(huge, header)
|
||
status, b, _ = upload(t, c.srv, c.token, c.chat, "huge.png", "image/png", huge)
|
||
if status != http.StatusRequestEntityTooLarge {
|
||
t.Fatalf("14 MiB: ждали 413, got %d %s", status, b)
|
||
}
|
||
|
||
// chunked без Content-Length: лимит всё равно обязан сработать (MaxBytesReader).
|
||
req, _ := http.NewRequest(http.MethodPost, c.srv.URL+"/api/v1/chats/"+c.chat+"/attachments?filename=chunked.png",
|
||
io.NopCloser(bytes.NewReader(over)))
|
||
req.ContentLength = -1
|
||
req.Header.Set("Authorization", "Bearer "+c.token)
|
||
req.Header.Set("Content-Type", "image/png")
|
||
resp, err := http.DefaultClient.Do(req)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
resp.Body.Close()
|
||
if resp.StatusCode != http.StatusRequestEntityTooLarge {
|
||
t.Fatalf("chunked >10 MiB: ждали 413, got %d", resp.StatusCode)
|
||
}
|
||
logOK(t, "лимит байтов: граница точная, работает и для chunked")
|
||
}
|
||
|
||
// Лимит пикселей: ровно 40 млн можно, на один ряд больше — 413 (до распаковки).
|
||
func TestAttachmentPixelLimit(t *testing.T) {
|
||
logStep(t, "8000x5000 (=40 млн) принимается, 8000x5001 → 413")
|
||
c := newChatCtx(t, "att_px")
|
||
|
||
ok := craftPNG(8000, 5000)
|
||
t.Logf("PNG 8000x5000 занимает %d байт на проводе", len(ok))
|
||
meta := mustUpload(t, c, "forty-million.png", "image/png", ok)
|
||
if meta["status"] != "ready" {
|
||
t.Fatalf("40 Мпикс: %v", meta)
|
||
}
|
||
|
||
tooMany := craftPNG(8000, 5001)
|
||
status, b, _ := upload(t, c.srv, c.token, c.chat, "bomb.png", "image/png", tooMany)
|
||
logResult(t, status, string(b))
|
||
if status != http.StatusRequestEntityTooLarge {
|
||
t.Fatalf("40 Мпикс + 1 ряд: ждали 413, got %d %s", status, b)
|
||
}
|
||
logOK(t, "лимит пикселей по заголовку, без полного декода")
|
||
}
|
||
|
||
// Повреждённые файлы, чужие форматы и подмена MIME → 415, никогда не 500.
|
||
func TestAttachmentCorruptAndMimeSpoof(t *testing.T) {
|
||
logStep(t, "мусор, усечённые PNG/JPEG, битый CRC, GIF под видом PNG, подмена Content-Type")
|
||
c := newChatCtx(t, "att_bad")
|
||
validPNG := noisePNG(t, 40, 40)
|
||
validJPG := smallJPEG(t, 40, 40)
|
||
|
||
flipped := append([]byte{}, validPNG...)
|
||
flipped[len(flipped)/2] ^= 0xFF // портим данные IDAT → не сойдётся CRC
|
||
|
||
gif := []byte("GIF89a\x01\x00\x01\x00\x80\x00\x00\x00\x00\x00\xff\xff\xff!\xf9\x04\x01\x00\x00\x00\x00,\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02D\x01\x00;")
|
||
|
||
cases := []struct {
|
||
name string
|
||
ctype string
|
||
body []byte
|
||
}{
|
||
{"случайные байты как png", "image/png", bytes.Repeat([]byte("не картинка "), 500)},
|
||
{"пустое тело", "image/png", nil},
|
||
{"усечённый PNG", "image/png", validPNG[:len(validPNG)-20]},
|
||
{"усечённый JPEG", "image/jpeg", validJPG[:len(validJPG)-30]},
|
||
{"PNG с битым CRC", "image/png", flipped},
|
||
{"GIF под видом PNG", "image/png", gif},
|
||
{"PNG под видом JPEG (спуфинг)", "image/jpeg", validPNG},
|
||
{"JPEG под видом PNG (спуфинг)", "image/png", validJPG},
|
||
{"валидный PNG, но Content-Type text/plain", "text/plain", validPNG},
|
||
{"валидный PNG без Content-Type", "", validPNG},
|
||
{"валидный PNG, Content-Type image/gif", "image/gif", validPNG},
|
||
}
|
||
for _, tc := range cases {
|
||
status, b, _ := upload(t, c.srv, c.token, c.chat, "bad.bin", tc.ctype, tc.body)
|
||
t.Logf("%-45s → %d", tc.name, status)
|
||
if status != http.StatusUnsupportedMediaType {
|
||
t.Fatalf("%s: ждали 415, got %d body=%s", tc.name, status, b)
|
||
}
|
||
if !strings.Contains(string(b), "unsupported_media_type") {
|
||
t.Fatalf("%s: код ошибки: %s", tc.name, b)
|
||
}
|
||
}
|
||
// После всех отказов в чате не появилось ни одной строки вложения.
|
||
n, err := sharedStore.CountAttachmentsInChat(context.Background(), uuid.MustParse(c.chat))
|
||
if err != nil || n != 0 {
|
||
t.Fatalf("после отказов в БД осталось %d вложений (err=%v)", n, err)
|
||
}
|
||
// Контрольный: Content-Type с параметрами и в другом регистре допустим.
|
||
meta := mustUpload(t, c, "ok.png", "Image/PNG; charset=binary", validPNG)
|
||
if meta["content_type"] != "image/png" {
|
||
t.Fatalf("content_type по содержимому: %v", meta)
|
||
}
|
||
logOK(t, "все повреждённые/подменённые файлы → 415, строки в БД не создаются")
|
||
}
|
||
|
||
func TestAttachmentFilenameValidation(t *testing.T) {
|
||
logStep(t, "filename: '/', '\\', NUL, управляющие, пустое, >255 → 400; unicode и пробелы допустимы")
|
||
c := newChatCtx(t, "att_name")
|
||
data := noisePNG(t, 16, 16)
|
||
bad := []string{
|
||
"a/b.png", "..\\evil.png", "nul\x00byte.png", "line\nbreak.png", "tab\tname.png",
|
||
"del\x7f.png", "", " ", strings.Repeat("я", 256), "bidi\u202eexe.png",
|
||
}
|
||
for _, name := range bad {
|
||
status, b, _ := upload(t, c.srv, c.token, c.chat, name, "image/png", data)
|
||
if status != http.StatusBadRequest {
|
||
t.Fatalf("filename %q: ждали 400, got %d %s", name, status, b)
|
||
}
|
||
}
|
||
// Без параметра filename вообще.
|
||
req, _ := http.NewRequest(http.MethodPost, c.srv.URL+"/api/v1/chats/"+c.chat+"/attachments", bytes.NewReader(data))
|
||
req.Header.Set("Authorization", "Bearer "+c.token)
|
||
req.Header.Set("Content-Type", "image/png")
|
||
resp, err := http.DefaultClient.Do(req)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
resp.Body.Close()
|
||
if resp.StatusCode != http.StatusBadRequest {
|
||
t.Fatalf("без filename: %d", resp.StatusCode)
|
||
}
|
||
for _, name := range []string{"отчёт 2026 (финал).png", strings.Repeat("я", 255), "a b.png"} {
|
||
meta := mustUpload(t, c, name, "image/png", data)
|
||
if meta["filename"] != name {
|
||
t.Fatalf("filename искажён: %q vs %q", meta["filename"], name)
|
||
}
|
||
}
|
||
logOK(t, "опасные имена отклоняются, обычные Unicode-имена сохраняются как есть")
|
||
}
|
||
|
||
// Правила attachment_ids в сообщениях: чужое/неизвестное/другой чат → 404,
|
||
// >10 и дубли → 400, пустой текст допустим только с вложением.
|
||
func TestMessageAttachmentRules(t *testing.T) {
|
||
logStep(t, "foreign attachment_id, вложение другого чата, неизвестный id, лимиты и пустой текст")
|
||
srv := newAPI(t, time.Hour)
|
||
defer srv.Close()
|
||
alice := register(t, srv, "rule_alice")
|
||
mallory := register(t, srv, "rule_mal")
|
||
tokA := login(t, srv, alice.username, alice.password)
|
||
tokM := login(t, srv, mallory.username, mallory.password)
|
||
|
||
chatA1 := createChat(t, srv, tokA, alice.id, "A1")
|
||
chatA2 := createChat(t, srv, tokA, alice.id, "A2")
|
||
chatM := createChat(t, srv, tokM, mallory.id, "M")
|
||
data := noisePNG(t, 20, 20)
|
||
a1 := mustUpload(t, chatCtx{srv: srv, token: tokA, chat: chatA1}, "a1.png", "image/png", data)["id"].(string)
|
||
mine := mustUpload(t, chatCtx{srv: srv, token: tokM, chat: chatM}, "m.png", "image/png", data)["id"].(string)
|
||
|
||
post := func(chat, tok, raw string) (int, string) {
|
||
return postMessage(t, srv, tok, chat, "k-"+uuid.NewString(), raw)
|
||
}
|
||
|
||
// 1. Вложение ЧУЖОГО пользователя (другой чат, Alice не участник) → 404.
|
||
status, body := post(chatA1, tokA, fmt.Sprintf(`{"text":"x","attachment_ids":[%q]}`, mine))
|
||
logResult(t, status, body)
|
||
if status != http.StatusNotFound {
|
||
t.Fatalf("чужое attachment_id: %d %s", status, body)
|
||
}
|
||
// 2. Своё вложение, но из ДРУГОГО чата того же пользователя → 404 (файл привязан к чату).
|
||
status, body = post(chatA2, tokA, fmt.Sprintf(`{"text":"x","attachment_ids":[%q]}`, a1))
|
||
logResult(t, status, body)
|
||
if status != http.StatusNotFound {
|
||
t.Fatalf("вложение другого чата: %d %s", status, body)
|
||
}
|
||
// 3. Неизвестный UUID → 404; одно плохое среди хороших портит весь запрос атомарно.
|
||
status, _ = post(chatA1, tokA, fmt.Sprintf(`{"text":"x","attachment_ids":[%q]}`, uuid.NewString()))
|
||
if status != http.StatusNotFound {
|
||
t.Fatalf("неизвестный id: %d", status)
|
||
}
|
||
status, _ = post(chatA1, tokA, fmt.Sprintf(`{"text":"x","attachment_ids":[%q,%q]}`, a1, uuid.NewString()))
|
||
if status != http.StatusNotFound {
|
||
t.Fatalf("хороший+неизвестный: %d", status)
|
||
}
|
||
// Ни одно из сообщений выше не должно было записаться.
|
||
status, body = do(t, srv, http.MethodGet, "/api/v1/chats/"+chatA1+"/messages", map[string]string{"Authorization": "Bearer " + tokA}, "")
|
||
if status != http.StatusOK || strings.Contains(body, `"text":"x"`) {
|
||
t.Fatalf("отклонённое сообщение просочилось в историю: %s", body)
|
||
}
|
||
// 4. Не UUID → 400, дубли → 400, больше 10 → 400.
|
||
status, _ = post(chatA1, tokA, `{"text":"x","attachment_ids":["not-a-uuid"]}`)
|
||
if status != http.StatusBadRequest {
|
||
t.Fatalf("не uuid: %d", status)
|
||
}
|
||
status, _ = post(chatA1, tokA, fmt.Sprintf(`{"text":"x","attachment_ids":[%q,%q]}`, a1, a1))
|
||
if status != http.StatusBadRequest {
|
||
t.Fatalf("дубли: %d", status)
|
||
}
|
||
eleven := make([]string, 11)
|
||
for i := range eleven {
|
||
eleven[i] = fmt.Sprintf("%q", uuid.NewString())
|
||
}
|
||
status, _ = post(chatA1, tokA, fmt.Sprintf(`{"text":"x","attachment_ids":[%s]}`, strings.Join(eleven, ",")))
|
||
if status != http.StatusBadRequest {
|
||
t.Fatalf("11 вложений: %d", status)
|
||
}
|
||
// 5. Пустой текст: без вложений 400, с вложением 201; ровно 10 вложений допустимо.
|
||
status, _ = post(chatA1, tokA, `{"text":"","attachment_ids":[]}`)
|
||
if status != http.StatusBadRequest {
|
||
t.Fatalf("пусто без вложений: %d", status)
|
||
}
|
||
status, body = post(chatA1, tokA, fmt.Sprintf(`{"text":"","attachment_ids":[%q]}`, a1))
|
||
if status != http.StatusCreated {
|
||
t.Fatalf("пустой текст с вложением: %d %s", status, body)
|
||
}
|
||
if m := decode(t, body); m["text"] != "" {
|
||
t.Fatalf("text: %v", m["text"])
|
||
}
|
||
ten := make([]string, 10)
|
||
for i := range ten {
|
||
ten[i] = fmt.Sprintf("%q", mustUpload(t, chatCtx{srv: srv, token: tokA, chat: chatA1}, fmt.Sprintf("t%d.png", i), "image/png", data)["id"].(string))
|
||
}
|
||
status, body = post(chatA1, tokA, fmt.Sprintf(`{"text":"ровно десять","attachment_ids":[%s]}`, strings.Join(ten, ",")))
|
||
if status != http.StatusCreated || len(decode(t, body)["attachment_ids"].([]any)) != 10 {
|
||
t.Fatalf("10 вложений: %d %s", status, body)
|
||
}
|
||
// 6. Обычное сообщение без attachment_ids → в ответе attachment_ids == [].
|
||
status, body = post(chatA1, tokA, `{"text":"просто текст"}`)
|
||
if status != http.StatusCreated || !strings.Contains(body, `"attachment_ids":[]`) {
|
||
t.Fatalf("attachment_ids по умолчанию []: %d %s", status, body)
|
||
}
|
||
logOK(t, "чужое/другой чат/неизвестное → 404, лимиты → 400, пустой текст только с вложением")
|
||
}
|
||
|
||
// S3 недоступен: загрузка → контролируемый 503 (не 500, без деталей), readiness → 503,
|
||
// в БД не остаётся строки метаданных.
|
||
func TestS3DownGivesLimitedError(t *testing.T) {
|
||
logStep(t, "API с недоступным S3: upload/ready → 503, без утечек и полуфабрикатов в БД")
|
||
dead, err := objectstore.New(objectstore.Config{
|
||
Endpoint: "http://127.0.0.1:1", Region: "us-east-1", Bucket: "messenger",
|
||
AccessKey: "x", SecretKey: "yyyyyyyy", ForcePathStyle: true,
|
||
})
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
// Пользователь и чат — через нормальный API; недоступный S3 подсовываем второй реплике.
|
||
good := newChatCtx(t, "att_down")
|
||
sessions, err := session.Open(sharedRedisURL, time.Hour)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
defer sessions.Close()
|
||
srv := httptest.NewServer(api.New(sharedStore, sessions, dead, "dead-s3").Handler())
|
||
defer srv.Close()
|
||
|
||
start := time.Now()
|
||
status, b, _ := upload(t, srv, good.token, good.chat, "p.png", "image/png", noisePNG(t, 16, 16))
|
||
t.Logf("upload при лежащем S3: status=%d за %s body=%s", status, time.Since(start).Round(time.Millisecond), b)
|
||
if status != http.StatusServiceUnavailable || !strings.Contains(string(b), `"unavailable"`) {
|
||
t.Fatalf("ждали 503 unavailable, got %d %s", status, b)
|
||
}
|
||
for _, leak := range []string{"127.0.0.1", "messenger", "dial", "connection refused", "amazonaws"} {
|
||
if strings.Contains(strings.ToLower(string(b)), leak) {
|
||
t.Fatalf("ответ раскрывает внутренние детали (%q): %s", leak, b)
|
||
}
|
||
}
|
||
if time.Since(start) > 10*time.Second {
|
||
t.Fatalf("отказ должен быть быстрым, занял %s", time.Since(start))
|
||
}
|
||
|
||
status, b, _ = doRaw2(t, srv, "/health/ready")
|
||
if status != http.StatusServiceUnavailable {
|
||
t.Fatalf("/health/ready при лежащем S3: %d %s", status, b)
|
||
}
|
||
status, _, _ = doRaw2(t, srv, "/health/live")
|
||
if status != http.StatusOK {
|
||
t.Fatalf("/health/live обязан оставаться 200: %d", status)
|
||
}
|
||
n, err := sharedStore.CountAttachmentsInChat(context.Background(), uuid.MustParse(good.chat))
|
||
if err != nil || n != 0 {
|
||
t.Fatalf("в БД осталось %d строк вложений после отказа S3 (err=%v)", n, err)
|
||
}
|
||
logOK(t, "лежащий S3 → 503 без деталей, ready=503, live=200, БД чиста")
|
||
}
|
||
|
||
func doRaw2(t *testing.T, srv *httptest.Server, path string) (int, []byte, http.Header) {
|
||
t.Helper()
|
||
resp, err := http.Get(srv.URL + path)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
defer resp.Body.Close()
|
||
b, _ := io.ReadAll(resp.Body)
|
||
return resp.StatusCode, b, resp.Header
|
||
}
|
||
|
||
// Компенсация: PUT в S3 прошёл, INSERT в PG не удался → объект удаляется сразу,
|
||
// клиент получает ошибку, строки нет.
|
||
func TestCompensationWhenPostgresFailsAfterPut(t *testing.T) {
|
||
logStep(t, "отказ PG после успешного PUT: объект удаляется компенсацией")
|
||
ctx := context.Background()
|
||
good := newChatCtx(t, "att_comp")
|
||
|
||
hasher, err := auth.NewHasher()
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
// Отдельный пул, который «умрёт» ровно между PUT и INSERT.
|
||
dsn := getenv("DATABASE_URL", "postgres://messenger:messenger@127.0.0.1:5432/messenger?sslmode=disable")
|
||
doomed, err := store.Open(ctx, dsn, hasher, 2)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
defer doomed.Close()
|
||
sessions, err := session.Open(sharedRedisURL, time.Hour)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
defer sessions.Close()
|
||
|
||
server := api.New(doomed, sessions, sharedObjects, "compensation")
|
||
var putKey string
|
||
server.AfterObjectPut = func(key string) {
|
||
putKey = key
|
||
// До компенсации убеждаемся, что объект РЕАЛЬНО лежит в S3.
|
||
if _, err := sharedObjects.Head(ctx, key); err != nil {
|
||
t.Errorf("после PUT объекта нет в S3: %v", err)
|
||
}
|
||
doomed.Close() // INSERT дальше упадёт: пул закрыт
|
||
}
|
||
srv := httptest.NewServer(server.Handler())
|
||
defer srv.Close()
|
||
|
||
status, b, _ := upload(t, srv, good.token, good.chat, "doomed.png", "image/png", noisePNG(t, 24, 24))
|
||
t.Logf("status=%d body=%s key=%s", status, b, putKey)
|
||
if status < 500 || status > 503 {
|
||
t.Fatalf("ждали ошибку сервера (отказ PG), got %d %s", status, b)
|
||
}
|
||
if putKey == "" {
|
||
t.Fatal("hook не вызывался: PUT не был выполнен")
|
||
}
|
||
if _, err := sharedObjects.Head(ctx, putKey); !errors.Is(err, objectstore.ErrNotFound) {
|
||
t.Fatalf("объект должен быть удалён компенсацией, Head err=%v", err)
|
||
}
|
||
n, err := sharedStore.CountAttachmentsInChat(ctx, uuid.MustParse(good.chat))
|
||
if err != nil || n != 0 {
|
||
t.Fatalf("строк вложений: %d (err=%v)", n, err)
|
||
}
|
||
logOK(t, "orphan после отказа PG удалён сразу; если бы удаление не удалось — его уберёт reconciler")
|
||
}
|
||
|
||
// ≥10 одновременных загрузок: все 201 (лишние ждут слот), все объекты разные и читаются.
|
||
func TestConcurrentUploads(t *testing.T) {
|
||
logStep(t, "12 параллельных загрузок: все 201, уникальные id, sha256 совпадает")
|
||
c := newChatCtx(t, "att_conc")
|
||
const n = 12
|
||
type res struct {
|
||
id, sha string
|
||
data []byte
|
||
}
|
||
results := make([]res, n)
|
||
var wg sync.WaitGroup
|
||
for i := 0; i < n; i++ {
|
||
wg.Add(1)
|
||
go func(i int) {
|
||
defer wg.Done()
|
||
data := noisePNG(t, 150+i, 150) // разные байты у каждой загрузки
|
||
status, b, _ := upload(t, c.srv, c.token, c.chat, fmt.Sprintf("c%d.png", i), "image/png", data)
|
||
if status != http.StatusCreated {
|
||
t.Errorf("worker %d: %d %s", i, status, b)
|
||
return
|
||
}
|
||
m := decode(t, string(b))
|
||
results[i] = res{id: m["id"].(string), sha: m["sha256"].(string), data: data}
|
||
}(i)
|
||
}
|
||
wg.Wait()
|
||
seen := map[string]bool{}
|
||
for i, r := range results {
|
||
if r.id == "" || seen[r.id] {
|
||
t.Fatalf("worker %d: пустой/повторный id %q", i, r.id)
|
||
}
|
||
seen[r.id] = true
|
||
status, got, _ := getNoRedirect(t, c.srv, c.token, "/api/v1/attachments/"+r.id+"/content")
|
||
if status != http.StatusOK || hexSHA(got) != r.sha || r.sha != hexSHA(r.data) {
|
||
t.Fatalf("worker %d: download %d sha mismatch", i, status)
|
||
}
|
||
}
|
||
logOK(t, "параллельные загрузки целы")
|
||
}
|
||
|
||
// Ключ объекта назначает сервер и не содержит filename.
|
||
func TestObjectKeyIsServerAssigned(t *testing.T) {
|
||
logStep(t, "ключ объекта = attachments/{chat}/{id}; filename в ключ не попадает")
|
||
c := newChatCtx(t, "att_key")
|
||
meta := mustUpload(t, c, "секрет-имя.png", "image/png", noisePNG(t, 16, 16))
|
||
id := uuid.MustParse(meta["id"].(string))
|
||
key := store.AttachmentObjectKey(uuid.MustParse(c.chat), id)
|
||
info, err := sharedObjects.Head(context.Background(), key)
|
||
if err != nil {
|
||
t.Fatalf("объект по ожидаемому ключу %s не найден: %v", key, err)
|
||
}
|
||
if info.ContentType != "image/png" || info.Size != int64(meta["size_bytes"].(float64)) {
|
||
t.Fatalf("объект в S3: %+v", info)
|
||
}
|
||
if strings.Contains(key, "секрет") {
|
||
t.Fatal("filename попал в ключ")
|
||
}
|
||
logOK(t, "ключ серверный: "+key)
|
||
}
|