package service import ( "context" "crypto/sha256" "encoding/hex" "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 } key := attachmentObjectPrefix + uuid.NewString() 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) } params := repository.CreateAttachmentParams{ ChatID: chat.ID, OwnerID: userID, Filename: filename, ObjectKey: key, ContentType: mimeType, Sha256: sumString, SizeBytes: size, } attachment, err = tx.CreateAttachment(ctx, params) if err != nil { return err } return nil } 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 string) (*model.Attachment, io.ReadCloser, error) { attachment, err := s.GetAttachment(ctx, userID, attachmentID) if err != nil { return nil, nil, err } contentReader, err := s.objects.Get(ctx, attachment.ObjectKey) if err != nil { return nil, nil, convertStorageError(err) } return attachment, 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 }