package services import ( "bytes" "context" "crypto/sha256" "encoding/hex" "errors" "image" _ "image/jpeg" _ "image/png" "io" "messenger/src/backend/repositories" "mime" "os" "strings" "time" "unicode" "unicode/utf8" "github.com/google/uuid" "github.com/jackc/pgx/v5" ) const MaxUploadBytes int64 = 10485760 const MaxImagePixels int64 = 40000000 var ErrPayloadTooLarge = errors.New("payload too large") var ErrUnsupportedMedia = errors.New("unsupported image") var ErrAttachmentNotFound = errors.New("attachment not found") type AttachmentService struct { metadata *repositories.AttachmentStore objects AttachmentObjects uploadSlot chan struct{} } type AttachmentObjects interface { Put(context.Context, string, io.Reader, int64, string) error Get(context.Context, string) (io.ReadCloser, error) } func NewAttachmentService(metadata *repositories.AttachmentStore, objects AttachmentObjects) *AttachmentService { return &AttachmentService{metadata: metadata, objects: objects, uploadSlot: make(chan struct{}, 1)} } func ValidateFilename(name string) error { if !utf8.ValidString(name) || strings.TrimSpace(name) == "" || utf8.RuneCountInString(name) > 255 { return InvalidInput{"filename must contain 1-255 characters"} } for _, r := range name { if r == '/' || r == '\\' || unicode.IsControl(r) { return InvalidInput{"invalid filename"} } } return nil } func ValidateImage(data []byte, declared string) (string, error) { return ValidateImageReader(bytes.NewReader(data), declared) } func ValidateImageReader(reader io.ReadSeeker, declared string) (string, error) { contentType, _, err := mime.ParseMediaType(declared) if err != nil || (contentType != "image/png" && contentType != "image/jpeg") { return "", ErrUnsupportedMedia } config, format, err := image.DecodeConfig(reader) if err != nil { return "", ErrUnsupportedMedia } actual := "image/" + format if actual != contentType { return "", ErrUnsupportedMedia } if config.Width <= 0 || config.Height <= 0 || int64(config.Width) > MaxImagePixels/int64(config.Height) { return "", ErrPayloadTooLarge } // DecodeConfig alone accepts truncated headers; decode only after bounding pixels. if _, err = reader.Seek(0, io.SeekStart); err != nil { return "", err } decoded, _, err := image.Decode(reader) if err != nil { return "", ErrUnsupportedMedia } _ = decoded return actual, nil } func (s *AttachmentService) Upload(ctx context.Context, userID, chatID, filename, contentType string, body io.Reader) (repositories.Attachment, error) { select { case s.uploadSlot <- struct{}{}: defer func() { <-s.uploadSlot }() case <-ctx.Done(): return repositories.Attachment{}, ctx.Err() } grace, err := repositories.UploadCleanupGrace() if err != nil { return repositories.Attachment{}, err } directory := os.Getenv("UPLOAD_TMP_DIR") file, err := os.CreateTemp(directory, "upload-*") if err != nil { return repositories.Attachment{}, err } defer file.Close() // Linux keeps the open descriptor usable; no abandoned pathname survives a crash. if err = os.Remove(file.Name()); err != nil { return repositories.Attachment{}, err } hash := sha256.New() size, err := io.CopyBuffer(io.MultiWriter(file, hash), io.LimitReader(body, MaxUploadBytes+1), make([]byte, 32*1024)) if err != nil { return repositories.Attachment{}, err } if size > MaxUploadBytes { return repositories.Attachment{}, ErrPayloadTooLarge } if err = ctx.Err(); err != nil { return repositories.Attachment{}, err } if _, err = file.Seek(0, io.SeekStart); err != nil { return repositories.Attachment{}, err } actual, err := ValidateImageReader(file, contentType) if err != nil { return repositories.Attachment{}, err } if err = ctx.Err(); err != nil { return repositories.Attachment{}, err } if _, err = file.Seek(0, io.SeekStart); err != nil { return repositories.Attachment{}, err } now := time.Now().UTC().Truncate(time.Microsecond) a := repositories.Attachment{ID: uuid.NewString(), ChatID: chatID, OwnerID: userID, Filename: filename, ContentType: actual, SizeBytes: size, SHA256: hex.EncodeToString(hash.Sum(nil)), Status: "ready", Variants: []any{}, CreatedAt: now, UpdatedAt: now} a.ObjectKey = "originals/" + a.ID if err = s.metadata.ReserveUpload(ctx, a, grace); err != nil { return repositories.Attachment{}, err } err = s.metadata.PublishUpload(ctx, a, func(ctx context.Context) error { return s.objects.Put(ctx, a.ObjectKey, file, a.SizeBytes, a.ContentType) }) // On any uncertainty leave the durable reservation to the cleanup worker. if err != nil { return repositories.Attachment{}, err } return a, nil } func (s *AttachmentService) Get(ctx context.Context, id, userID string) (repositories.Attachment, error) { a, err := s.metadata.GetForMember(ctx, id, userID) if errors.Is(err, pgx.ErrNoRows) { return a, ErrAttachmentNotFound } return a, err } func (s *AttachmentService) Content(ctx context.Context, a repositories.Attachment) (io.ReadCloser, error) { return s.objects.Get(ctx, a.ObjectKey) } func NormalizeAttachmentIDs(ids []string) ([]string, error) { if len(ids) > 10 { return nil, InvalidInput{"at most 10 attachments are allowed"} } result := make([]string, 0, len(ids)) seen := map[string]bool{} for _, id := range ids { parsed, err := uuid.Parse(id) if err != nil { return nil, InvalidInput{"invalid attachment id"} } id = strings.ToLower(parsed.String()) if seen[id] { return nil, InvalidInput{"duplicate attachment id"} } seen[id] = true result = append(result, id) } return result, nil }