forked from mtusi2026/mtusi2026lab5
49 lines
1.3 KiB
Go
49 lines
1.3 KiB
Go
package media
|
|
|
|
import (
|
|
"bytes"
|
|
"image"
|
|
|
|
// Register the only accepted original image decoders.
|
|
_ "image/jpeg"
|
|
// Register PNG for content validation before storage.
|
|
_ "image/png"
|
|
"strings"
|
|
"unicode"
|
|
"unicode/utf8"
|
|
|
|
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/service"
|
|
)
|
|
|
|
const maxImageBytes = 10 << 20
|
|
const maxImagePixels = 40_000_000
|
|
|
|
// validateImage checks encoded size, display name, actual format and complete decoding.
|
|
func validateImage(filename, mime string, body []byte) error {
|
|
if len(body) > maxImageBytes {
|
|
return service.ErrTooLarge
|
|
}
|
|
if !utf8.ValidString(filename) || strings.TrimSpace(filename) == "" || utf8.RuneCountInString(filename) > 255 {
|
|
return service.ErrInvalid
|
|
}
|
|
for _, r := range filename {
|
|
if r == '/' || r == '\\' || unicode.IsControl(r) {
|
|
return service.ErrInvalid
|
|
}
|
|
}
|
|
if mime != "image/png" && mime != "image/jpeg" {
|
|
return service.ErrMedia
|
|
}
|
|
dimensions, format, err := image.DecodeConfig(bytes.NewReader(body))
|
|
if err != nil || "image/"+format != mime {
|
|
return service.ErrMedia
|
|
}
|
|
if dimensions.Width < 1 || dimensions.Height < 1 || int64(dimensions.Width)*int64(dimensions.Height) > maxImagePixels {
|
|
return service.ErrTooLarge
|
|
}
|
|
if _, _, err := image.Decode(bytes.NewReader(body)); err != nil {
|
|
return service.ErrMedia
|
|
}
|
|
return nil
|
|
}
|