172 lines
6.8 KiB
Go
172 lines
6.8 KiB
Go
package app_test
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"fmt"
|
|
"image"
|
|
"image/jpeg"
|
|
"io"
|
|
"log/slog"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"net/url"
|
|
"os"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
"messenger/internal/app"
|
|
"messenger/internal/attachment"
|
|
"messenger/internal/chat"
|
|
"messenger/internal/testenv"
|
|
)
|
|
|
|
func TestAttachmentUploadAuthenticatesBeforeParsing(t *testing.T) {
|
|
ts := newTester(t)
|
|
ts.expect(ts.do(http.MethodPost, "/api/v1/chats/not-a-uuid/attachments?filename=x.png", "", "invalid image", map[string]string{"Content-Type": "image/png"}), http.StatusUnauthorized, "unauthorized")
|
|
}
|
|
|
|
func TestAttachmentMetadataUsesOrdinaryRequestDeadline(t *testing.T) {
|
|
ts := newTester(t)
|
|
actor := ts.user("deadline_user", "User")
|
|
ts.a = app.New(app.Deps{Log: slog.New(slog.NewTextHandler(io.Discard, nil)), DB: db.Pool, Sessions: kv.Client, SessionTTL: time.Hour, MaxBodyBytes: 65536, InstanceID: testInstance, RequestTimeout: 40 * time.Millisecond})
|
|
var held []*pgxpool.Conn
|
|
for range db.Pool.Config().MaxConns {
|
|
conn, err := db.Pool.Acquire(context.Background())
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
held = append(held, conn)
|
|
}
|
|
defer func() {
|
|
for _, conn := range held {
|
|
conn.Release()
|
|
}
|
|
}()
|
|
ctx, cancel := context.WithTimeout(context.Background(), 400*time.Millisecond)
|
|
defer cancel()
|
|
req := httptest.NewRequest("GET", "/api/v1/attachments/11111111-1111-4111-8111-111111111111", nil).WithContext(ctx)
|
|
req.Header.Set("Authorization", "Bearer "+actor.token)
|
|
rec := httptest.NewRecorder()
|
|
started := time.Now()
|
|
ts.a.Engine.ServeHTTP(rec, req)
|
|
if rec.Code != 503 || time.Since(started) > 200*time.Millisecond {
|
|
t.Fatalf("metadata exceeded ordinary budget: status%d elapsed%v body%s", rec.Code, time.Since(started), rec.Body.String())
|
|
}
|
|
}
|
|
|
|
func (ts *tester) binary(method, path, token, mime string, data []byte, length int64) response {
|
|
ts.t.Helper()
|
|
req := httptest.NewRequest(method, path, bytes.NewReader(data))
|
|
req.ContentLength = length
|
|
if token != "" {
|
|
req.Header.Set("Authorization", "Bearer "+token)
|
|
}
|
|
if mime != "" {
|
|
req.Header.Set("Content-Type", mime)
|
|
}
|
|
rec := httptest.NewRecorder()
|
|
ts.a.Engine.ServeHTTP(rec, req)
|
|
res := response{status: rec.Code, requestID: rec.Header().Get("X-Request-Id"), challenge: rec.Header().Get("WWW-Authenticate"), raw: rec.Body.Bytes()}
|
|
if res.requestID == "" || rec.Header().Get("X-Instance-Id") == "" {
|
|
ts.t.Fatal("binary response missing correlation headers")
|
|
}
|
|
return res
|
|
}
|
|
|
|
func TestAttachmentRealS3RoundTripValidationAndOutage(t *testing.T) {
|
|
ctx := context.Background()
|
|
s3, err := testenv.StartS3(ctx)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer s3.Close()
|
|
ts := newTester(t)
|
|
ts.a = app.New(app.Deps{Log: slog.New(slog.NewTextHandler(io.Discard, nil)), DB: db.Pool, Sessions: kv.Client, SessionTTL: time.Hour, MaxBodyBytes: 65536, InstanceID: testInstance, Blobs: s3.APIStore})
|
|
alice, bob, eve := ts.user("alice", "A"), ts.user("bob", "B"), ts.user("eve", "E")
|
|
room := ts.chat(alice.token, "files", alice.ID, bob.ID)
|
|
path := "/api/v1/chats/" + room.ID + "/attachments?filename=" + url.QueryEscape("фото.png")
|
|
data, err := os.ReadFile("../../tests/fixtures/sample.png")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
res := ts.binary("POST", path, alice.token, "image/png", data, int64(len(data)))
|
|
ts.expect(res, 201, "")
|
|
a := decode[attachment.Response](t, res)
|
|
digest := sha256.Sum256(data)
|
|
if a.SHA256 != hex.EncodeToString(digest[:]) || a.SizeBytes != int64(len(data)) || a.Filename != "фото.png" || a.Status != "ready" || a.ErrorCode != nil || len(a.Variants) != 0 {
|
|
t.Fatalf("attachment: %+v", a)
|
|
}
|
|
base := "/api/v1/attachments/" + a.ID
|
|
for _, suffix := range []string{"", "/content"} {
|
|
ts.expect(ts.do("GET", base+suffix, eve.token, nil, nil), 404, "not_found")
|
|
}
|
|
ts.expect(ts.do("GET", base, bob.token, nil, nil), 200, "")
|
|
got := ts.binary("GET", base+"/content", bob.token, "", nil, 0)
|
|
ts.expect(got, 200, "")
|
|
if !bytes.Equal(got.raw, data) {
|
|
t.Fatal("download bytes changed")
|
|
}
|
|
ts.expect(ts.do("GET", base+"/content?variant=thumbnail", bob.token, nil, nil), 400, "invalid_request")
|
|
msg := ts.do("POST", "/api/v1/chats/"+room.ID+"/messages", bob.token, map[string]any{"text": "", "attachment_ids": []string{a.ID}}, freshKey())
|
|
ts.expect(msg, 201, "")
|
|
if m := decode[chat.MessageResponse](t, msg); len(m.AttachmentIDs) != 1 || m.AttachmentIDs[0] != a.ID {
|
|
t.Fatal("lost attachment on message")
|
|
}
|
|
other := ts.chat(alice.token, "other", alice.ID)
|
|
ts.expect(ts.do("POST", "/api/v1/chats/"+other.ID+"/messages", alice.token, map[string]any{"text": "", "attachment_ids": []string{a.ID}}, freshKey()), 404, "not_found")
|
|
for _, tc := range []struct {
|
|
name, mime string
|
|
data []byte
|
|
length int64
|
|
want int
|
|
}{
|
|
{"MIME spoof", "image/jpeg", data, int64(len(data)), 415},
|
|
{"broken body", "image/png", data[:len(data)/2], int64(len(data) / 2), 415},
|
|
{"unsupported", "image/gif", data, int64(len(data)), 415},
|
|
{"oversize", "image/png", nil, 10485761, 413},
|
|
{"unknown length", "image/png", data, -1, 400},
|
|
{"empty", "image/png", nil, 0, 400},
|
|
} {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
r := ts.binary("POST", path, alice.token, tc.mime, tc.data, tc.length)
|
|
if r.status != tc.want {
|
|
t.Fatalf("got %d want %d: %s", r.status, tc.want, r.raw)
|
|
}
|
|
})
|
|
}
|
|
for _, name := range []string{"../x.png", `a\b.png`, "bad\nname", strings.Repeat("я", 256)} {
|
|
ts.expect(ts.binary("POST", "/api/v1/chats/"+room.ID+"/attachments?filename="+url.QueryEscape(name), alice.token, "image/png", data, int64(len(data))), 400, "invalid_request")
|
|
}
|
|
var j bytes.Buffer
|
|
if err := jpeg.Encode(&j, image.NewRGBA(image.Rect(0, 0, 5, 3)), nil); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
ts.expect(ts.binary("POST", path, bob.token, "image/jpeg", j.Bytes(), int64(j.Len())), 201, "")
|
|
ts.expect(ts.binary("POST", path, eve.token, "image/png", data, int64(len(data))), 404, "not_found")
|
|
// An interrupted read is never a 500 or a successfully published identity.
|
|
before := 0
|
|
if err := db.Pool.QueryRow(ctx, `SELECT count(*) FROM attachments`).Scan(&before); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
short := ts.binary("POST", path, alice.token, "image/png", data[:10], int64(len(data)))
|
|
if short.status != 400 && short.status != 503 {
|
|
t.Fatalf("interrupted body: %d %s", short.status, short.raw)
|
|
}
|
|
after := 0
|
|
if err := db.Pool.QueryRow(ctx, `SELECT count(*) FROM attachments`).Scan(&after); err != nil || before != after {
|
|
t.Fatalf("interruption published identity: %d -> %d (%v)", before, after, err)
|
|
}
|
|
if err := s3.Stop(ctx); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
ts.expect(ts.binary("POST", path, alice.token, "image/png", data, int64(len(data))), 503, "unavailable")
|
|
ts.expect(ts.do("GET", base+"/content", bob.token, nil, nil), 503, "unavailable")
|
|
ts.expect(ts.do("GET", "/health/ready", "", nil, nil), 200, "")
|
|
ts.message(alice.token, room.ID, fmt.Sprintf("text works with S3 down %d", time.Now().UnixNano()))
|
|
}
|