From 727ea6efa01054a307b5ed175628b760423a949b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=93=D0=BE=D0=BB=D0=B8=D0=BA=D0=BE=D0=B2=20Maximillian?= =?UTF-8?q?=20=D0=90=D0=BD=D1=82=D0=BE=D0=BD?= Date: Sat, 24 Oct 2026 15:26:21 +0300 Subject: [PATCH] fix(service):lab4 full decode catches truncated images under semaphore --- backend/internal/service/attachment.go | 31 +++++++++++++++++++++++--- 1 file changed, 28 insertions(+), 3 deletions(-) diff --git a/backend/internal/service/attachment.go b/backend/internal/service/attachment.go index f666fd5..a9b1273 100644 --- a/backend/internal/service/attachment.go +++ b/backend/internal/service/attachment.go @@ -25,6 +25,7 @@ type AttachmentService struct { storage domain.ObjectStorage maxBytes int64 maxPixels int64 + decodeSem chan struct{} } func NewAttachmentService( @@ -39,6 +40,9 @@ func NewAttachmentService( storage: storage, maxBytes: maxBytes, maxPixels: maxPixels, + // 40M pixels × 4 bytes (RGBA8) = 160 MB per full decode. + // API_MEMORY=256M → только один decode безопасен. + decodeSem: make(chan struct{}, 1), } } @@ -81,7 +85,7 @@ func (s *AttachmentService) Upload( if err != nil { return nil, &domain.UnsupportedMediaTypeError{ MediaType: contentType, - Expected: "image/png или image/jpeg", + Expected: "целостный image/png или image/jpeg", } } if int64(cfg.Width)*int64(cfg.Height) > s.maxPixels { @@ -91,6 +95,10 @@ func (s *AttachmentService) Upload( } } + if err := s.verifyIntegrity(ctx, buf, contentType); err != nil { + return nil, err + } + sha := sha256.Sum256(buf) id := uuid.NewString() objectKey := "chats/" + chatID + "/" + id @@ -127,6 +135,23 @@ func (s *AttachmentService) Upload( return a, nil } +func (s *AttachmentService) verifyIntegrity(ctx context.Context, buf []byte, contentType string) error { + select { + case s.decodeSem <- struct{}{}: + case <-ctx.Done(): + return &domain.UnavailableError{Reason: "ожидание декодирования"} + } + defer func() { <-s.decodeSem }() + + if _, _, err := image.Decode(bytes.NewReader(buf)); err != nil { + return &domain.UnsupportedMediaTypeError{ + MediaType: contentType, + Expected: "целостный " + contentType + " (без обрезки/повреждений)", + } + } + return nil +} + func (s *AttachmentService) Get(ctx context.Context, userID, attachmentID string) (*domain.Attachment, error) { a, err := s.attachments.GetByID(ctx, attachmentID) if err != nil { @@ -166,8 +191,8 @@ func (s *AttachmentService) ensureMember(ctx context.Context, userID, chatID str } func validateFilename(name string) error { - if name == "" { - return &domain.ValidationError{Field: "filename", Message: "не может быть пустым"} + if strings.TrimSpace(name) == "" { + return &domain.ValidationError{Field: "filename", Message: "не может быть пустым или состоять только из пробелов"} } if utf8.RuneCountInString(name) > 255 { return &domain.ValidationError{Field: "filename", Message: "не более 255 символов"}