feat: add S3 attachments and reconciliation

This commit is contained in:
2026-10-02 19:55:52 +03:00
parent 7e60f099d3
commit efaeb593e8
21 changed files with 1623 additions and 85 deletions
+260
View File
@@ -0,0 +1,260 @@
package messenger
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"image"
_ "image/jpeg"
_ "image/png"
"io"
"mime"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"unicode"
"unicode/utf8"
"golang.org/x/sync/semaphore"
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/model"
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/objectstore"
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/postgres"
)
func (s *Server) uploadAttachment(w http.ResponseWriter, r *http.Request) *apiError {
started := time.Now()
result := "client_error"
defer func() {
s.metrics.attachmentUploads.WithLabelValues(result).Inc()
s.metrics.attachmentDuration.Observe(time.Since(started).Seconds())
}()
if r.Method != http.MethodPost {
return methodNotAllowed(w, http.MethodPost)
}
user, _, authErr := s.authenticate(r)
if authErr != nil {
return authErr
}
chatID, valid := canonicalID(strings.Split(r.URL.Path, "/")[4])
if !valid {
return invalidRequest()
}
filename, valid := attachmentFilename(r.URL.Query())
if !valid {
return invalidRequest()
}
if _, err := s.messengerStore.ChatForUser(r.Context(), chatID, user.ID); errors.Is(err, postgres.ErrNotFound) {
return notFound()
} else if err != nil {
result = "dependency_error"
return unavailable()
}
data, contentType, readErr := readImage(w, r, s.maxUploadBytes, s.maxImagePixels, s.decodeMemory)
if readErr != nil {
return readErr
}
attachmentID, err := newID()
if err != nil {
result = "dependency_error"
return internalError()
}
objectID, err := newID()
if err != nil {
result = "dependency_error"
return internalError()
}
objectKey := "attachments/" + objectID + "/original"
if err := s.objects.Put(r.Context(), objectKey, contentType, data); err != nil {
result = "dependency_error"
return unavailable()
}
digest := sha256.Sum256(data)
attachment, err := s.messengerStore.CreateAttachment(r.Context(), model.Attachment{
ID: attachmentID, ChatID: chatID, OwnerID: user.ID, Filename: filename,
ContentType: contentType, SizeBytes: int64(len(data)), SHA256: hex.EncodeToString(digest[:]), ObjectKey: objectKey,
})
if err != nil {
result = "dependency_error"
cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(r.Context()), s.requestTTL)
defer cancel()
stored, lookupErr := s.messengerStore.AttachmentByStorage(cleanupCtx, attachmentID, objectKey)
if lookupErr == nil {
result = "success"
s.metrics.attachmentBytes.Add(float64(len(data)))
writeJSON(w, http.StatusCreated, stored)
return nil
}
if !errors.Is(lookupErr, postgres.ErrNotFound) {
s.logger.Error("attachment outcome is unknown", "attachment_id", attachmentID, "error", lookupErr)
return unavailable()
}
if cleanupErr := s.objects.Delete(cleanupCtx, objectKey); cleanupErr != nil {
s.logger.Error("attachment compensation failed", "object_key", objectKey, "error", cleanupErr)
}
if errors.Is(err, postgres.ErrNotFound) {
return notFound()
}
return unavailable()
}
result = "success"
s.metrics.attachmentBytes.Add(float64(len(data)))
writeJSON(w, http.StatusCreated, attachment)
return nil
}
func attachmentFilename(query url.Values) (string, bool) {
if len(query) != 1 || len(query["filename"]) != 1 {
return "", false
}
filename := query["filename"][0]
length := utf8.RuneCountInString(filename)
if !utf8.ValidString(filename) || strings.TrimSpace(filename) == "" || length < 1 || length > 255 {
return "", false
}
for _, char := range filename {
if char == '/' || char == '\\' || char == 0 || unicode.IsControl(char) {
return "", false
}
}
return filename, true
}
func readImage(
w http.ResponseWriter,
r *http.Request,
maxBytes int64,
maxPixels int64,
decodeMemory *semaphore.Weighted,
) ([]byte, string, *apiError) {
mediaType, parameters, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil || len(parameters) != 0 || mediaType != "image/png" && mediaType != "image/jpeg" {
return nil, "", &apiError{http.StatusUnsupportedMediaType, errorCodeUnsupportedMediaType, "unsupported image type"}
}
if r.ContentLength > maxBytes {
return nil, "", &apiError{http.StatusRequestEntityTooLarge, errorCodePayloadTooLarge, "image is too large"}
}
r.Body = http.MaxBytesReader(w, r.Body, maxBytes)
data, err := io.ReadAll(r.Body)
if err != nil {
var tooLarge *http.MaxBytesError
if errors.As(err, &tooLarge) {
return nil, "", &apiError{http.StatusRequestEntityTooLarge, errorCodePayloadTooLarge, "image is too large"}
}
return nil, "", invalidRequest()
}
if len(data) == 0 {
return nil, "", &apiError{http.StatusUnsupportedMediaType, errorCodeUnsupportedMediaType, "invalid image"}
}
detected := http.DetectContentType(data)
if detected != mediaType {
return nil, "", &apiError{http.StatusUnsupportedMediaType, errorCodeUnsupportedMediaType, "content type does not match image"}
}
imageConfig, format, err := image.DecodeConfig(bytes.NewReader(data))
if err != nil || imageContentType(format) != mediaType {
return nil, "", &apiError{http.StatusUnsupportedMediaType, errorCodeUnsupportedMediaType, "invalid image"}
}
pixels := int64(imageConfig.Width) * int64(imageConfig.Height)
if imageConfig.Width < 1 || imageConfig.Height < 1 || pixels > maxPixels {
return nil, "", &apiError{http.StatusRequestEntityTooLarge, errorCodePayloadTooLarge, "image dimensions are too large"}
}
decodeBytes := pixels*8 + int64(len(data))
if !decodeMemory.TryAcquire(decodeBytes) {
w.Header().Set("Retry-After", "1")
return nil, "", &apiError{http.StatusTooManyRequests, errorCodeRateLimited, "image capacity is temporarily exhausted"}
}
defer decodeMemory.Release(decodeBytes)
if _, format, err := image.Decode(bytes.NewReader(data)); err != nil || imageContentType(format) != mediaType {
return nil, "", &apiError{http.StatusUnsupportedMediaType, errorCodeUnsupportedMediaType, "invalid image"}
}
return data, mediaType, nil
}
func imageContentType(format string) string {
switch format {
case "png":
return "image/png"
case "jpeg":
return "image/jpeg"
default:
return ""
}
}
func (s *Server) attachmentMetadata(w http.ResponseWriter, r *http.Request) *apiError {
if r.Method != http.MethodGet {
return methodNotAllowed(w, http.MethodGet)
}
user, _, authErr := s.authenticate(r)
if authErr != nil {
return authErr
}
attachment, apiErr := s.attachmentForUser(r, user.ID)
if apiErr != nil {
return apiErr
}
writeJSON(w, http.StatusOK, attachment)
return nil
}
func (s *Server) attachmentContent(w http.ResponseWriter, r *http.Request) *apiError {
if r.Method != http.MethodGet {
return methodNotAllowed(w, http.MethodGet)
}
user, _, authErr := s.authenticate(r)
if authErr != nil {
return authErr
}
if !originalVariant(r.URL.Query()) {
return invalidRequest()
}
attachment, apiErr := s.attachmentForUser(r, user.ID)
if apiErr != nil {
return apiErr
}
content, err := s.objects.Get(r.Context(), attachment.ObjectKey)
if errors.Is(err, objectstore.ErrNotFound) {
return unavailable()
}
if err != nil {
return unavailable()
}
defer func() { _ = content.Close() }()
w.Header().Set("Content-Type", attachment.ContentType)
w.Header().Set("Content-Length", strconv.FormatInt(attachment.SizeBytes, 10))
w.Header().Set("Content-Disposition", mime.FormatMediaType("inline", map[string]string{"filename": attachment.Filename}))
w.WriteHeader(http.StatusOK)
if _, err := io.Copy(w, content); err != nil {
s.logger.Warn("attachment download interrupted", "attachment_id", attachment.ID, "error", err)
}
return nil
}
func originalVariant(query url.Values) bool {
if len(query) == 0 {
return true
}
return len(query) == 1 && len(query["variant"]) == 1 && query["variant"][0] == "original"
}
func (s *Server) attachmentForUser(r *http.Request, userID string) (Attachment, *apiError) {
parts := strings.Split(strings.Trim(r.URL.Path, "/"), "/")
attachmentID, valid := canonicalID(parts[3])
if !valid {
return Attachment{}, invalidRequest()
}
attachment, err := s.messengerStore.AttachmentForUser(r.Context(), attachmentID, userID)
if errors.Is(err, postgres.ErrNotFound) {
return Attachment{}, notFound()
}
if err != nil {
return Attachment{}, unavailable()
}
return attachment, nil
}
+1
View File
@@ -14,6 +14,7 @@ const (
errorCodePayloadTooLarge = "payload_too_large"
errorCodeUnavailable = "unavailable"
errorCodeConflict = "conflict"
errorCodeRateLimited = "rate_limited"
)
type apiError struct {
+33 -3
View File
@@ -38,6 +38,9 @@ func (s *Server) readiness(w http.ResponseWriter, r *http.Request) *apiError {
if err := s.sessions.Ping(ctx); err != nil {
return unavailable()
}
if err := s.objects.Ping(ctx); err != nil {
return unavailable()
}
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
return nil
}
@@ -207,16 +210,17 @@ func (s *Server) messages(w http.ResponseWriter, r *http.Request) *apiError {
return invalidRequest()
}
var input struct {
Text string `json:"text"`
Text string `json:"text"`
AttachmentIDs []string `json:"attachment_ids"`
}
if err := readJSON(w, r, &input); err != nil {
return err
}
if !validText(input.Text, 4000) {
if !validMessage(input.Text, input.AttachmentIDs) || !canonicalAttachmentIDs(input.AttachmentIDs) {
return invalidRequest()
}
message, replay, err := s.messengerStore.CreateMessage(
r.Context(), chatID, user.ID, input.Text, key, s.idempotencyTTL,
r.Context(), chatID, user.ID, input.Text, input.AttachmentIDs, key, s.idempotencyTTL,
)
if errors.Is(err, postgres.ErrNotFound) {
return notFound()
@@ -234,6 +238,32 @@ func (s *Server) messages(w http.ResponseWriter, r *http.Request) *apiError {
return nil
}
func validMessage(text string, attachmentIDs []string) bool {
if !utf8.ValidString(text) || utf8.RuneCountInString(text) > 4000 {
return false
}
return len(attachmentIDs) > 0 || strings.TrimSpace(text) != ""
}
func canonicalAttachmentIDs(attachmentIDs []string) bool {
if len(attachmentIDs) > 10 {
return false
}
seen := make(map[string]struct{}, len(attachmentIDs))
for index, attachmentID := range attachmentIDs {
canonical, valid := canonicalID(attachmentID)
if !valid {
return false
}
if _, duplicate := seen[canonical]; duplicate {
return false
}
seen[canonical] = struct{}{}
attachmentIDs[index] = canonical
}
return true
}
func (s *Server) listMessages(w http.ResponseWriter, r *http.Request, user User, chatID string) *apiError {
limit, cursor, err := pageParams(r, "message", chatID)
if err != nil {
+12 -1
View File
@@ -2,6 +2,7 @@ package messenger
import (
"context"
"io"
"time"
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/model"
@@ -15,8 +16,18 @@ type MessengerStore interface {
CreateChat(context.Context, string, []string, string) (model.Chat, error)
ChatForUser(context.Context, string, string) (model.Chat, error)
ListChats(context.Context, string, *model.Position, int) ([]model.Chat, bool, error)
CreateMessage(context.Context, string, string, string, string, time.Duration) (model.Message, bool, error)
CreateMessage(context.Context, string, string, string, []string, string, time.Duration) (model.Message, bool, error)
ListMessages(context.Context, string, string, *model.Position, int) ([]model.Message, bool, error)
CreateAttachment(context.Context, model.Attachment) (model.Attachment, error)
AttachmentByStorage(context.Context, string, string) (model.Attachment, error)
AttachmentForUser(context.Context, string, string) (model.Attachment, error)
}
type ObjectStore interface {
Ping(context.Context) error
Put(context.Context, string, string, []byte) error
Get(context.Context, string) (io.ReadCloser, error)
Delete(context.Context, string) error
}
type SessionStore interface {
+36 -5
View File
@@ -12,11 +12,14 @@ import (
)
type metrics struct {
requests *prometheus.CounterVec
duration *prometheus.HistogramVec
inFlight prometheus.Gauge
replays prometheus.Counter
handler http.Handler
requests *prometheus.CounterVec
duration *prometheus.HistogramVec
inFlight prometheus.Gauge
replays prometheus.Counter
attachmentUploads *prometheus.CounterVec
attachmentDuration prometheus.Histogram
attachmentBytes prometheus.Counter
handler http.Handler
}
func newMetrics() *metrics {
@@ -47,12 +50,31 @@ func newMetrics() *metrics {
Name: "idempotency_replays_total",
Help: "Message requests served from an idempotency record.",
}),
attachmentUploads: prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: "messenger",
Name: "attachment_uploads_total",
Help: "Completed attachment uploads by result.",
}, []string{"result"}),
attachmentDuration: prometheus.NewHistogram(prometheus.HistogramOpts{
Namespace: "messenger",
Name: "attachment_upload_duration_seconds",
Help: "Attachment upload duration in seconds.",
Buckets: prometheus.DefBuckets,
}),
attachmentBytes: prometheus.NewCounter(prometheus.CounterOpts{
Namespace: "messenger",
Name: "attachment_upload_bytes_total",
Help: "Bytes accepted by successful attachment uploads.",
}),
}
registry.MustRegister(
result.requests,
result.duration,
result.inFlight,
result.replays,
result.attachmentUploads,
result.attachmentDuration,
result.attachmentBytes,
collectors.NewGoCollector(),
collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}),
)
@@ -79,5 +101,14 @@ func routeTemplate(path string) string {
if len(parts) == 5 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "chats" && parts[4] == "messages" {
return "/api/v1/chats/{chat_id}/messages"
}
if len(parts) == 5 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "chats" && parts[4] == "attachments" {
return "/api/v1/chats/{chat_id}/attachments"
}
if len(parts) == 4 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "attachments" {
return "/api/v1/attachments/{attachment_id}"
}
if len(parts) == 5 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "attachments" && parts[4] == "content" {
return "/api/v1/attachments/{attachment_id}/content"
}
return "unknown"
}
+1
View File
@@ -8,6 +8,7 @@ import (
type User = model.User
type Chat = model.Chat
type Message = model.Message
type Attachment = model.Attachment
func newID() (string, error) {
id, err := uuid.NewRandom()
+6
View File
@@ -33,6 +33,12 @@ func (s *Server) route(w http.ResponseWriter, r *http.Request) *apiError {
handler = s.chat
} else if len(parts) == 5 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "chats" && parts[4] == "messages" {
handler = s.messages
} else if len(parts) == 5 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "chats" && parts[4] == "attachments" {
handler = s.uploadAttachment
} else if len(parts) == 4 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "attachments" {
handler = s.attachmentMetadata
} else if len(parts) == 5 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "attachments" && parts[4] == "content" {
handler = s.attachmentContent
} else {
return notFound()
}
+14 -2
View File
@@ -6,18 +6,24 @@ import (
"net/http"
"sync/atomic"
"time"
"golang.org/x/sync/semaphore"
)
type Server struct {
messengerStore MessengerStore
sessions SessionStore
passwords PasswordService
objects ObjectStore
sessionTTL time.Duration
idempotencyTTL time.Duration
requestTTL time.Duration
instanceID string
logger *slog.Logger
swaggerPort string
maxUploadBytes int64
maxImagePixels int64
decodeMemory *semaphore.Weighted
metrics *metrics
ready atomic.Bool
}
@@ -37,16 +43,22 @@ func NewServer(
messages MessengerStore,
sessions SessionStore,
passwords PasswordService,
objects ObjectStore,
sessionTTL time.Duration,
idempotencyTTL time.Duration,
requestTTL time.Duration,
instanceID string,
swaggerPort string,
maxUploadBytes int64,
maxImagePixels int64,
decodeMemoryBytes int64,
) *Server {
s := &Server{
messengerStore: messages, sessions: sessions, passwords: passwords,
messengerStore: messages, sessions: sessions, passwords: passwords, objects: objects,
sessionTTL: sessionTTL, idempotencyTTL: idempotencyTTL, requestTTL: requestTTL,
instanceID: instanceID, logger: logger, swaggerPort: swaggerPort, metrics: newMetrics(),
instanceID: instanceID, logger: logger, swaggerPort: swaggerPort,
maxUploadBytes: maxUploadBytes, maxImagePixels: maxImagePixels,
decodeMemory: semaphore.NewWeighted(decodeMemoryBytes), metrics: newMetrics(),
}
s.ready.Store(true)
return s
+210 -11
View File
@@ -1,9 +1,13 @@
package messenger
import (
"bytes"
"context"
"errors"
"fmt"
"image"
"image/color"
"image/png"
"io"
"log/slog"
"net/http"
@@ -13,6 +17,7 @@ import (
"time"
"github.com/stretchr/testify/suite"
"golang.org/x/sync/semaphore"
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/model"
"gitea.privcloud.tech/dizi/mtusi2026lab4/internal/postgres"
@@ -34,14 +39,19 @@ func (s *MessengerSuite) SetupTest() {
}
type messengerStoreStub struct {
pingErr error
userByID model.User
userByIDErr error
credentials model.UserCredentials
credentialsErr error
message model.Message
messageReplay bool
messageErr error
pingErr error
userByID model.User
userByIDErr error
credentials model.UserCredentials
credentialsErr error
message model.Message
messageReplay bool
messageErr error
attachment model.Attachment
attachmentErr error
storedAttachment model.Attachment
storedAttachmentExists bool
storedAttachmentErr error
}
func (s messengerStoreStub) Ping(context.Context) error { return s.pingErr }
@@ -63,12 +73,57 @@ func (messengerStoreStub) ChatForUser(context.Context, string, string) (model.Ch
func (messengerStoreStub) ListChats(context.Context, string, *model.Position, int) ([]model.Chat, bool, error) {
return nil, false, nil
}
func (s messengerStoreStub) CreateMessage(context.Context, string, string, string, string, time.Duration) (model.Message, bool, error) {
func (s messengerStoreStub) CreateMessage(context.Context, string, string, string, []string, string, time.Duration) (model.Message, bool, error) {
return s.message, s.messageReplay, s.messageErr
}
func (messengerStoreStub) ListMessages(context.Context, string, string, *model.Position, int) ([]model.Message, bool, error) {
return nil, false, nil
}
func (s messengerStoreStub) CreateAttachment(context.Context, model.Attachment) (model.Attachment, error) {
return s.attachment, s.attachmentErr
}
func (s messengerStoreStub) AttachmentByStorage(context.Context, string, string) (model.Attachment, error) {
if s.storedAttachmentErr != nil {
return model.Attachment{}, s.storedAttachmentErr
}
if !s.storedAttachmentExists {
return model.Attachment{}, postgres.ErrNotFound
}
return s.storedAttachment, nil
}
func (s messengerStoreStub) AttachmentForUser(context.Context, string, string) (model.Attachment, error) {
return s.attachment, s.attachmentErr
}
type objectStoreStub struct {
pingErr error
putErr error
getData []byte
getErr error
deleteErr error
putKey *string
deletedKey *string
}
func (s objectStoreStub) Ping(context.Context) error { return s.pingErr }
func (s objectStoreStub) Put(_ context.Context, key string, _ string, _ []byte) error {
if s.putKey != nil {
*s.putKey = key
}
return s.putErr
}
func (s objectStoreStub) Get(context.Context, string) (io.ReadCloser, error) {
if s.getErr != nil {
return nil, s.getErr
}
return io.NopCloser(bytes.NewReader(s.getData)), nil
}
func (s objectStoreStub) Delete(_ context.Context, key string) error {
if s.deletedKey != nil {
*s.deletedKey = key
}
return s.deleteErr
}
type sessionStub struct {
pingErr error
@@ -100,14 +155,19 @@ func (s *MessengerSuite) TestReadinessReturnsUnavailableForDependencyFailure() {
name string
store messengerStoreStub
sessions sessionStub
objects objectStoreStub
}{
{name: "postgres", store: messengerStoreStub{pingErr: errDependency}},
{name: "valkey", sessions: sessionStub{pingErr: errDependency}},
{name: "s3", objects: objectStoreStub{pingErr: errDependency}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
server := s.newTestServer(tt.store, tt.sessions, passwordsStub{})
server := NewServer(
s.logger, tt.store, tt.sessions, passwordsStub{}, tt.objects, time.Hour, 24*time.Hour,
time.Second, "test-instance", "8081", 10*1024*1024, 40_000_000, 384*1024*1024,
)
response := serveRequest(server, http.MethodGet, "/health/ready", "")
if response.Code != http.StatusServiceUnavailable {
t.Fatalf("status = %d, want %d", response.Code, http.StatusServiceUnavailable)
@@ -160,6 +220,18 @@ func (s *MessengerSuite) TestAuthenticationChallenges() {
}
}
func (s *MessengerSuite) TestAttachmentContentAuthenticatesBeforeVariantValidation() {
server := s.newTestServer(messengerStoreStub{}, sessionStub{}, passwordsStub{})
response := serveRequest(
server,
http.MethodGet,
"/api/v1/attachments/00000000-0000-0000-0000-000000000001/content?variant=invalid",
"",
)
s.Equal(http.StatusUnauthorized, response.Code)
s.Equal(`Bearer realm="messenger"`, response.Header().Get("WWW-Authenticate"))
}
func (s *MessengerSuite) TestSessionCreationRejectsChunkedBody() {
t := s.T()
server := s.newTestServer(messengerStoreStub{}, sessionStub{}, passwordsStub{})
@@ -242,8 +314,135 @@ func (s *MessengerSuite) TestMessageCreationReturnsConflictForReusedKeyWithDiffe
}
}
func (s *MessengerSuite) TestImageValidation() {
data := testPNG(s.T(), 2, 2)
tests := []struct {
name string
contentType string
data []byte
maxBytes int64
maxPixels int64
wantStatus int
}{
{name: "valid", contentType: "image/png", data: data, maxBytes: 1024, maxPixels: 4},
{name: "spoofed MIME", contentType: "image/jpeg", data: data, maxBytes: 1024, maxPixels: 4, wantStatus: http.StatusUnsupportedMediaType},
{name: "too many pixels", contentType: "image/png", data: data, maxBytes: 1024, maxPixels: 3, wantStatus: http.StatusRequestEntityTooLarge},
{name: "too many bytes", contentType: "image/png", data: data, maxBytes: int64(len(data) - 1), maxPixels: 4, wantStatus: http.StatusRequestEntityTooLarge},
{name: "damaged", contentType: "image/png", data: data[:16], maxBytes: 1024, maxPixels: 4, wantStatus: http.StatusUnsupportedMediaType},
}
for _, tt := range tests {
s.Run(tt.name, func() {
request := httptest.NewRequest(http.MethodPost, "/upload", bytes.NewReader(tt.data))
request.Header.Set("Content-Type", tt.contentType)
response := httptest.NewRecorder()
actual, _, apiErr := readImage(
response, request, tt.maxBytes, tt.maxPixels, semaphore.NewWeighted(384*1024*1024),
)
if tt.wantStatus == 0 {
s.Require().Nil(apiErr)
s.Equal(tt.data, actual)
return
}
s.Require().NotNil(apiErr)
s.Equal(tt.wantStatus, apiErr.status)
})
}
}
func (s *MessengerSuite) TestImageValidationLimitsConcurrentDecodeMemory() {
data := testPNG(s.T(), 2, 2)
request := httptest.NewRequest(http.MethodPost, "/upload", bytes.NewReader(data))
request.Header.Set("Content-Type", "image/png")
response := httptest.NewRecorder()
_, _, apiErr := readImage(response, request, 1024, 4, semaphore.NewWeighted(1))
s.Require().NotNil(apiErr)
s.Equal(http.StatusTooManyRequests, apiErr.status)
s.Equal("1", response.Header().Get("Retry-After"))
}
func (s *MessengerSuite) TestAttachmentFilenameValidation() {
for _, filename := range []string{"", " ", "../photo.png", "dir\\photo.png", "photo\x00.png", "photo\n.png"} {
_, valid := attachmentFilename(map[string][]string{"filename": {filename}})
s.False(valid, filename)
}
filename, valid := attachmentFilename(map[string][]string{"filename": {"фото.png"}})
s.True(valid)
s.Equal("фото.png", filename)
}
func (s *MessengerSuite) TestUploadCompensatesObjectWhenMetadataWriteFails() {
var putKey, deletedKey string
store := messengerStoreStub{
userByID: model.User{ID: "00000000-0000-0000-0000-000000000001"},
attachmentErr: errDependency,
}
objects := objectStoreStub{putKey: &putKey, deletedKey: &deletedKey}
server := NewServer(
s.logger, store, sessionStub{userID: store.userByID.ID}, passwordsStub{}, objects,
time.Hour, 24*time.Hour, time.Second, "test-instance", "8081", 10*1024*1024, 40_000_000, 384*1024*1024,
)
data := testPNG(s.T(), 2, 2)
request := httptest.NewRequest(
http.MethodPost,
"/api/v1/chats/00000000-0000-0000-0000-000000000002/attachments?filename=photo.png",
bytes.NewReader(data),
)
request.Header.Set("Authorization", "Bearer valid-token")
request.Header.Set("Content-Type", "image/png")
response := httptest.NewRecorder()
server.Handler().ServeHTTP(response, request)
s.Equal(http.StatusServiceUnavailable, response.Code)
s.NotEmpty(putKey)
s.Equal(putKey, deletedKey)
}
func (s *MessengerSuite) TestUploadKeepsObjectWhenMetadataCommitSucceeded() {
var deletedKey string
stored := model.Attachment{
ID: "00000000-0000-0000-0000-000000000003",
ChatID: "00000000-0000-0000-0000-000000000002",
OwnerID: "00000000-0000-0000-0000-000000000001",
Filename: "photo.png", ContentType: "image/png", SizeBytes: 1, SHA256: strings.Repeat("0", 64),
Status: "ready", Variants: []model.Variant{}, CreatedAt: time.Now(), UpdatedAt: time.Now(),
}
store := messengerStoreStub{
userByID: model.User{ID: stored.OwnerID}, attachmentErr: errDependency,
storedAttachment: stored, storedAttachmentExists: true,
}
server := NewServer(
s.logger, store, sessionStub{userID: stored.OwnerID}, passwordsStub{}, objectStoreStub{deletedKey: &deletedKey},
time.Hour, 24*time.Hour, time.Second, "test-instance", "8081", 10*1024*1024, 40_000_000, 384*1024*1024,
)
data := testPNG(s.T(), 2, 2)
request := httptest.NewRequest(
http.MethodPost,
"/api/v1/chats/00000000-0000-0000-0000-000000000002/attachments?filename=photo.png",
bytes.NewReader(data),
)
request.Header.Set("Authorization", "Bearer valid-token")
request.Header.Set("Content-Type", "image/png")
response := httptest.NewRecorder()
server.Handler().ServeHTTP(response, request)
s.Equal(http.StatusCreated, response.Code)
s.Empty(deletedKey)
}
func testPNG(t *testing.T, width, height int) []byte {
t.Helper()
var data bytes.Buffer
imageData := image.NewRGBA(image.Rect(0, 0, width, height))
imageData.Set(0, 0, color.White)
if err := png.Encode(&data, imageData); err != nil {
t.Fatalf("encode PNG: %v", err)
}
return data.Bytes()
}
func (s *MessengerSuite) newTestServer(messages MessengerStore, sessions SessionStore, passwords PasswordService) *Server {
return NewServer(s.logger, messages, sessions, passwords, time.Hour, 24*time.Hour, time.Second, "test-instance", "8081")
return NewServer(
s.logger, messages, sessions, passwords, objectStoreStub{}, time.Hour, 24*time.Hour,
time.Second, "test-instance", "8081", 10*1024*1024, 40_000_000, 384*1024*1024,
)
}
func serveRequest(server *Server, method, path, body string) *httptest.ResponseRecorder {