fix(img):Prevent thumbnail generation for large images

This commit is contained in:
jagadam97
2025-10-27 04:44:31 +05:30
committed by Henrique Dias
parent c18afcddc4
commit d00b3ea8f8
2 changed files with 19 additions and 1 deletions

View File

@@ -19,6 +19,15 @@ import (
// ErrUnsupportedFormat means the given image format is not supported.
var ErrUnsupportedFormat = errors.New("unsupported image format")
// ErrImageTooLarge means the image is too large to create a thumbnail.
var ErrImageTooLarge = errors.New("image too large for thumbnail generation")
// Maximum dimensions for thumbnail generation to prevent server crashes
const (
MaxImageWidth = 10000
MaxImageHeight = 10000
)
// Service
type Service struct {
sem semaphore.Semaphore
@@ -187,11 +196,17 @@ func (s *Service) detectFormat(in io.Reader) (Format, io.Reader, error) {
buf := &bytes.Buffer{}
r := io.TeeReader(in, buf)
_, imgFormat, err := image.DecodeConfig(r)
imgConfig, imgFormat, err := image.DecodeConfig(r)
if err != nil {
return 0, nil, fmt.Errorf("%s: %w", err.Error(), ErrUnsupportedFormat)
}
// Check if image dimensions exceed maximum allowed size
if imgConfig.Width > MaxImageWidth || imgConfig.Height > MaxImageHeight {
return 0, nil, fmt.Errorf("image dimensions %dx%d exceed maximum %dx%d: %w",
imgConfig.Width, imgConfig.Height, MaxImageWidth, MaxImageHeight, ErrImageTooLarge)
}
format, err := ParseFormat(imgFormat)
if err != nil {
return 0, nil, ErrUnsupportedFormat