Files
mtusi2026lab4/student-tests/attachments_test.go
T
Mlvn 7cbb75c897 Реализовать lab4: вложения S3/MinIO, уровень 4 и трек 2 reconciler.
Метаданные в PostgreSQL, байты в приватном bucket; sync upload 201 ready;
компенсация orphan и cmd/reconcile с dry-run/apply и grace period.
2026-11-12 18:08:47 +03:00

245 lines
8.0 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package studenttests
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"testing"
"time"
"mtusi2026lab4/internal/api"
"mtusi2026lab4/internal/blob"
"mtusi2026lab4/internal/session"
)
// 1×1 PNG (valid IHDR + IDAT + IEND, CRC проверены).
var tinyPNG = []byte{
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01,
0x08, 0x02, 0x00, 0x00, 0x00, 0x90, 0x77, 0x53,
0xde, 0x00, 0x00, 0x00, 0x0c, 0x49, 0x44, 0x41,
0x54, 0x78, 0xda, 0x63, 0xf8, 0xcf, 0xc0, 0x00,
0x00, 0x03, 0x01, 0x01, 0x00, 0xf7, 0x03, 0x41,
0x43, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e,
0x44, 0xae, 0x42, 0x60, 0x82,
}
func TestAttachmentUploadDownloadAndACL(t *testing.T) {
mem := blob.NewMemory()
srv := newAPIBlob(t, time.Hour, mem)
defer srv.Close()
logStep(t, "upload PNG → 201 ready → download checksum; посторонний — 404")
owner := register(t, srv, "att_owner")
ownerTok := login(t, srv, owner.username, owner.password)
stranger := register(t, srv, "att_stranger")
strangerTok := login(t, srv, stranger.username, stranger.password)
chat := createChat(t, srv, ownerTok, owner.id, "Вложения")
attID, sha := uploadPNG(t, srv, ownerTok, chat, "pic.png", tinyPNG)
status, body := do(t, srv, http.MethodGet, "/api/v1/attachments/"+attID, map[string]string{
"Authorization": "Bearer " + ownerTok,
}, "")
logResult(t, status, body)
if status != http.StatusOK {
t.Fatalf("meta: %d %s", status, body)
}
meta := decode(t, body)
if meta["status"] != "ready" || meta["sha256"] != sha {
t.Fatalf("meta unexpected: %+v", meta)
}
statusCode, raw, hdr := downloadBytes(t, srv, ownerTok, attID)
if statusCode != http.StatusOK {
t.Fatalf("download: %d", statusCode)
}
if hdr.Get("Content-Type") != "image/png" {
t.Fatalf("content-type: %q", hdr.Get("Content-Type"))
}
sum := sha256.Sum256(raw)
if hex.EncodeToString(sum[:]) != sha {
t.Fatalf("checksum mismatch")
}
status, body = do(t, srv, http.MethodGet, "/api/v1/attachments/"+attID, map[string]string{
"Authorization": "Bearer " + strangerTok,
}, "")
logResult(t, status, body)
if status != http.StatusNotFound {
t.Fatalf("stranger meta: %d", status)
}
statusCode, _, _ = downloadBytes(t, srv, strangerTok, attID)
if statusCode != http.StatusNotFound {
t.Fatalf("stranger download: %d", statusCode)
}
status, body = do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", map[string]string{
"Authorization": "Bearer " + ownerTok,
}, fmt.Sprintf(`{"text":"с файлом","attachment_ids":[%q]}`, attID))
logResult(t, status, body)
if status != http.StatusCreated {
t.Fatalf("message with att: %d %s", status, body)
}
msg := decode(t, body)
ids, _ := msg["attachment_ids"].([]any)
if len(ids) != 1 || ids[0] != attID {
t.Fatalf("attachment_ids: %+v", msg["attachment_ids"])
}
logOK(t, "upload/download/ACL и message.attachment_ids")
}
func TestAttachmentRejectsBadInput(t *testing.T) {
mem := blob.NewMemory()
srv := newAPIBlob(t, time.Hour, mem)
defer srv.Close()
logStep(t, "битый PNG, подмена MIME, опасный filename, чужой чат → 4xx не 500")
user := register(t, srv, "att_bad")
tok := login(t, srv, user.username, user.password)
chat := createChat(t, srv, tok, user.id, "Отказы")
status, body := uploadRaw(t, srv, tok, chat, "../x.png", "image/png", tinyPNG)
logResult(t, status, body)
if status != http.StatusBadRequest {
t.Fatalf("bad filename: %d", status)
}
status, body = uploadRaw(t, srv, tok, chat, "x.jpg", "image/jpeg", tinyPNG)
logResult(t, status, body)
if status != http.StatusUnsupportedMediaType {
t.Fatalf("mime mismatch: %d", status)
}
status, body = uploadRaw(t, srv, tok, chat, "bad.png", "image/png", tinyPNG[:20])
logResult(t, status, body)
if status != http.StatusUnsupportedMediaType {
t.Fatalf("truncated: %d", status)
}
// Отдельный сервер с маленьким лимитом: реально шлём 2 KiB, ожидаем 413.
small := blob.NewMemory()
sessions, err := session.Open(sharedRedisURL, time.Hour)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = sessions.Close() })
apiSrv := api.New(sharedStore, sessions, small, "test-small-limit")
apiSrv.MaxUploadBytes = 1024
limSrv := httptest.NewServer(apiSrv.Handler())
defer limSrv.Close()
status, body = uploadRaw(t, limSrv, tok, chat, "huge.png", "image/png", make([]byte, 2048))
logResult(t, status, body)
if status != http.StatusRequestEntityTooLarge {
t.Fatalf("too large body: %d", status)
}
other := register(t, srv, "att_other")
otherTok := login(t, srv, other.username, other.password)
otherChat := createChat(t, srv, otherTok, other.id, "Чужой")
status, body = uploadRaw(t, srv, tok, otherChat, "x.png", "image/png", tinyPNG)
logResult(t, status, body)
if status != http.StatusNotFound {
t.Fatalf("foreign chat upload: %d", status)
}
attID, _ := uploadPNG(t, srv, otherTok, otherChat, "o.png", tinyPNG)
status, body = do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", map[string]string{
"Authorization": "Bearer " + tok,
}, fmt.Sprintf(`{"text":"steal","attachment_ids":[%q]}`, attID))
logResult(t, status, body)
if status != http.StatusNotFound {
t.Fatalf("foreign attachment_id: %d %s", status, body)
}
logOK(t, "негативные сценарии вложений → клиентские 4xx")
}
func TestAttachmentS3DownIs503(t *testing.T) {
mem := blob.NewMemory()
mem.SetUnavailable(true)
srv := newAPIBlob(t, time.Hour, mem)
defer srv.Close()
logStep(t, "S3 недоступен: ready и upload → 503")
status, body := do(t, srv, http.MethodGet, "/health/ready", nil, "")
logResult(t, status, body)
if status != http.StatusServiceUnavailable {
t.Fatalf("ready: %d", status)
}
user := register(t, srv, "s3_down")
tok := login(t, srv, user.username, user.password)
chat := createChat(t, srv, tok, user.id, "S3 down")
status, body = uploadRaw(t, srv, tok, chat, "x.png", "image/png", tinyPNG)
logResult(t, status, body)
if status != http.StatusServiceUnavailable {
t.Fatalf("upload with s3 down: %d %s", status, body)
}
logOK(t, "падение S3 → 503")
}
func uploadPNG(t *testing.T, srv *httptest.Server, token, chatID, filename string, data []byte) (id, sha string) {
t.Helper()
status, body := uploadRaw(t, srv, token, chatID, filename, "image/png", data)
if status != http.StatusCreated {
t.Fatalf("upload: %d %s", status, body)
}
var att struct {
ID string `json:"id"`
SHA256 string `json:"sha256"`
Status string `json:"status"`
}
if err := json.Unmarshal([]byte(body), &att); err != nil {
t.Fatal(err)
}
if att.Status != "ready" || att.ID == "" {
t.Fatalf("upload body: %s", body)
}
sum := sha256.Sum256(data)
want := hex.EncodeToString(sum[:])
if att.SHA256 != want {
t.Fatalf("sha got=%s want=%s", att.SHA256, want)
}
return att.ID, att.SHA256
}
func uploadRaw(t *testing.T, srv *httptest.Server, token, chatID, filename, ctype string, data []byte) (int, string) {
t.Helper()
u := srv.URL + "/api/v1/chats/" + chatID + "/attachments?filename=" + url.QueryEscape(filename)
req, err := http.NewRequest(http.MethodPost, u, bytes.NewReader(data))
if err != nil {
t.Fatal(err)
}
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Content-Type", ctype)
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
b, _ := io.ReadAll(resp.Body)
return resp.StatusCode, string(b)
}
func downloadBytes(t *testing.T, srv *httptest.Server, token, attID string) (int, []byte, http.Header) {
t.Helper()
req, err := http.NewRequest(http.MethodGet, srv.URL+"/api/v1/attachments/"+attID+"/content", nil)
if err != nil {
t.Fatal(err)
}
req.Header.Set("Authorization", "Bearer "+token)
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
b, _ := io.ReadAll(resp.Body)
return resp.StatusCode, b, resp.Header.Clone()
}