package service import ( "context" "crypto/sha256" "encoding/hex" "highload/internal/fault" "highload/internal/model" "highload/internal/repository" "highload/internal/storage" "image" _ "image/jpeg" _ "image/png" "io" "strings" "unicode/utf8" "github.com/google/uuid" ) const MaxAttachmentBytes = 10 * 1024 * 1024 const maxImagePixels = 40_000_000 const attachmentObjectPrefix = "attachments/" type AttachmentService struct { repo repository.AttachmentRepository chatService *ChatService objects storage.ObjectWriter } func NewAttachmentService(repo repository.AttachmentRepository, chatService *ChatService, objects storage.ObjectWriter) *AttachmentService { return &AttachmentService{repo: repo, chatService: chatService, objects: objects} } func (s *AttachmentService) CreateAttachment(ctx context.Context, chatID, userID, filename, declaredContentType string, body io.ReadSeeker, size int64) (*model.Attachment, error) { chat, err := s.chatService.GetChatByID(ctx, chatID, userID) if err != nil { return nil, err } mimeType, err := validateAttachment(filename, declaredContentType, body, size) if err != nil { return nil, err } id := uuid.NewString() key := "staging/" + id + "/original" if err := ctx.Err(); err != nil { return nil, err } sum := sha256.New() n, err := io.Copy(sum, io.LimitReader(body, size+1)) if err != nil || n != size { return nil, ErrServerError } if _, err := body.Seek(0, io.SeekStart); err != nil { return nil, ErrServerError } sumString := hex.EncodeToString(sum.Sum(nil)) var attachment *model.Attachment fn := func(ctx context.Context, tx repository.AttachmentTx) error { err := s.objects.Put(ctx, key, mimeType, body, size) if err != nil { return convertStorageError(err) } if err := fault.Pause(ctx, "after_staging", id); err != nil { return err } attachment, err = tx.CreateQueued(ctx, id, chat.ID, userID, mimeType, sumString, key, filename, size) return err } acquired, err := s.repo.WithObjectKeyLock(ctx, key, fn) if err != nil { return nil, convertRepoError(err) } if !acquired { return nil, ErrServiceUnavailable } return attachment, nil } func (s *AttachmentService) GetAttachment(ctx context.Context, userID, attachmentID string) (*model.Attachment, error) { _, err := uuid.Parse(attachmentID) if err != nil { return nil, ErrInvalidInput } _, err = uuid.Parse(userID) if err != nil { return nil, ErrInvalidInput } attachment, err := s.repo.GetAttachmentForUser(ctx, userID, attachmentID) if err != nil { return nil, convertRepoError(err) } return attachment, nil } func (s *AttachmentService) GetAttachmentContent(ctx context.Context, userID, attachmentID, variant string) (string, io.ReadCloser, error) { attachment, err := s.GetAttachment(ctx, userID, attachmentID) if err != nil { return "", nil, err } if attachment.Status != "ready" { return "", nil, ErrConflict } key, mime := attachment.ObjectKey, attachment.ContentType if variant != "" && variant != "original" { key = "" for _, candidate := range attachment.Variants { if candidate.Name == variant { key, mime = candidate.ObjectKey, candidate.ContentType break } } } if key == "" { return "", nil, ErrNotFound } contentReader, err := s.objects.Get(ctx, key) if err != nil { return "", nil, convertStorageError(err) } return mime, contentReader, nil } func validateAttachment(filename, declaredContentType string, body io.ReadSeeker, size int64) (string, error) { if !utf8.ValidString(filename) || strings.TrimSpace(filename) == "" || utf8.RuneCountInString(filename) > 255 { return "", ErrInvalidInput } if strings.ContainsAny(filename, "/\\") || containsControlChars(filename) { return "", ErrInvalidInput } if size > MaxAttachmentBytes { return "", ErrPayloadTooLarge } if size <= 0 { return "", ErrUnsupportMediaType } if _, err := body.Seek(0, io.SeekStart); err != nil { return "", ErrServerError } imageConfig, format, err := image.DecodeConfig(io.LimitReader(body, size)) if err != nil { return "", ErrUnsupportMediaType } if imageConfig.Height <= 0 || imageConfig.Width <= 0 { return "", ErrUnsupportMediaType } if imageConfig.Width > maxImagePixels/imageConfig.Height { return "", ErrPayloadTooLarge } var mimeType string switch format { case "png": mimeType = "image/png" case "jpeg": mimeType = "image/jpeg" default: return "", ErrUnsupportMediaType } if mimeType != declaredContentType { return "", ErrUnsupportMediaType } if _, err := body.Seek(0, io.SeekStart); err != nil { return "", ErrServerError } _, _, err = image.Decode(io.LimitReader(body, size)) if err != nil { return "", ErrUnsupportMediaType } if _, err := body.Seek(0, io.SeekStart); err != nil { return "", ErrServerError } return mimeType, nil } func containsControlChars(s string) bool { for _, r := range s { if (r >= 0 && r <= 31) || r == 127 { return true } } return false }