Open platform to collect and prioritize feedback
Close decode budget bypasses and bound decode waits (GHSA-7cw3-7xh9-529r)
Matt Robertsb3d63661f3c0
diff --git a/app/handlers/images.go b/app/handlers/images.goindex 91dfa5eea..5fbbe48d3 100644--- a/app/handlers/images.go+++ b/app/handlers/images.go@@ -2,6 +2,8 @@ package handlersimport ("bytes"+ "context"+ "errors""fmt""image/color""image/png"@@ -155,15 +157,12 @@ func Favicon() web.HandlerFunc {if bkey == "" {// Bundled favicon is a trusted asset, no need to check the decode budget- bytes, err = validate.ApplyTrusted(c, bytes, opts...)- } else {- bytes, err = applyOrServeOriginal(c, bytes, opts...)- }- if err != nil {- return c.Failure(err)+ result, err := validate.ApplyTrusted(c, bytes, opts...)+ return serveProcessedImage(c, contentType, bytes, result, err)}- return c.Image(contentType, bytes)+ result, err := validate.SafeApply(c, bytes, opts...)+ return serveProcessedImage(c, contentType, bytes, result, err)}}@@ -185,26 +184,38 @@ func ViewUploadedImage() web.HandlerFunc {return c.Failure(err)}- bytes := q.Result.Content- if size > 0 {- bytes, err = applyOrServeOriginal(c, bytes, imagic.Resize(size))- if err != nil {- return c.Failure(err)- }+ if size == 0 {+ return c.Image(q.Result.ContentType, q.Result.Content)}- return c.Image(q.Result.ContentType, bytes)+ // Returns the original content without decoding it if it's already within size+ result, err := validate.SafeResize(c, q.Result.Content, size)+ return serveProcessedImage(c, q.Result.ContentType, q.Result.Content, result, err)}}-// applyOrServeOriginal applies the operations to a stored (user uploaded) image.-// Images that are too large to be safely decoded (e.g. decompression bombs stored before-// uploads were validated) or in a format we don't process are returned unchanged-// instead of being decoded.-func applyOrServeOriginal(c *web.Context, content []byte, operations ...imagic.ImageOperation) ([]byte, error) {- result, err := validate.SafeApply(c, content, operations...)- if err == validate.ErrImageTooLarge || err == imagic.ErrNotSupported {- return content, nil+// serveProcessedImage responds with the result of processing (resizing etc) an image.+// - If the request was cancelled, nothing is logged or written.+// - If too many images are being processed, responds with a (non cached) 503, rather+// than the original image, which would be cached by clients/CDNs as the resized one.+// - Otherwise, if the image couldn't be processed (too large to be safely decoded, a+// format we don't process, or corrupt pixel data after a valid header), the original+// image is served unchanged. These are properties of the image itself, so caching is fine.+func serveProcessedImage(c *web.Context, contentType string, original, result []byte, err error) error {+ if err == nil {+ return c.Image(contentType, result)+ }+ if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {+ return nil+ }+ if errors.Is(err, validate.ErrDecodeBusy) {+ c.Response.Header().Set("Retry-After", "5")+ return c.Blob(http.StatusServiceUnavailable, "text/plain; charset=utf-8", []byte(http.StatusText(http.StatusServiceUnavailable)))+ }+ if !errors.Is(err, validate.ErrImageTooLarge) && !errors.Is(err, imagic.ErrNotSupported) {+ log.Debugf(c, "Failed to process image, serving original: @{Error}", dto.Props{+ "Error": err.Error(),+ })}- return result, err+ return c.Image(contentType, original)}diff --git a/app/handlers/images_internal_test.go b/app/handlers/images_internal_test.gonew file mode 100644index 000000000..bbbf9dbbe--- /dev/null+++ b/app/handlers/images_internal_test.go@@ -0,0 +1,55 @@+package handlers++import (+ "context"+ "errors"+ "fmt"+ "net/http"+ "testing"++ . "github.com/getfider/fider/app/pkg/assert"+ "github.com/getfider/fider/app/pkg/mock"+ "github.com/getfider/fider/app/pkg/validate"+ "github.com/getfider/fider/app/pkg/web"+ "github.com/goenning/imagic"+)++func TestServeProcessedImage(t *testing.T) {+ RegisterT(t)++ original := []byte("original")+ result := []byte("result")++ serve := func(err error) (int, http.Header, string) {+ code, response := mock.NewServer().+ OnTenant(mock.DemoTenant).+ Execute(func(c *web.Context) error {+ return serveProcessedImage(c, "image/png", original, result, err)+ })+ return code, response.Header(), response.Body.String()+ }++ code, _, body := serve(nil)+ Expect(code).Equals(http.StatusOK)+ Expect(body).Equals("result")++ // Cancelled requests: nothing is written, and no error is returned (so nothing is logged)+ for _, err := range []error{context.Canceled, context.DeadlineExceeded, fmt.Errorf("wrapped: %w", context.Canceled)} {+ code, _, body = serve(err)+ Expect(code).Equals(http.StatusOK)+ Expect(body).Equals("")+ }++ // Busy: a non cached 503, so the original isn't cached as the resized image+ code, header, _ := serve(validate.ErrDecodeBusy)+ Expect(code).Equals(http.StatusServiceUnavailable)+ Expect(header.Get("Retry-After")).Equals("5")+ Expect(header.Get("Cache-Control")).Equals("no-cache, no-store")++ // Anything else about the image itself (too large, unsupported, corrupt pixel data): the original+ for _, err := range []error{validate.ErrImageTooLarge, imagic.ErrNotSupported, errors.New("gif: missing image data")} {+ code, _, body = serve(err)+ Expect(code).Equals(http.StatusOK)+ Expect(body).Equals("original")+ }+}diff --git a/app/handlers/images_test.go b/app/handlers/images_test.goindex 2f978e6b0..df627b72b 100644--- a/app/handlers/images_test.go+++ b/app/handlers/images_test.go@@ -189,6 +189,43 @@ func TestViewUploadedImage_UnsupportedFormat_ServedAsIs(t *testing.T) {Expect(response.Body.Bytes()).Equals(content)}+func TestViewUploadedImage_CorruptPixelData_ServedAsIs(t *testing.T) {+ RegisterT(t)+ bus.Init()+ // Valid header, but no image data+ content := mock.GIFHeader(100, 100)+ mockBlob(content, "image/gif")++ server := mock.NewServer()+ code, response := server.+ WithURL("https://demo.test.fider.io/?size=50").+ OnTenant(mock.DemoTenant).+ AddParam("bkey", "attachments/image.gif").+ Execute(handlers.ViewUploadedImage())++ Expect(code).Equals(http.StatusOK)+ Expect(response.Body.Bytes()).Equals(content)+}++func TestViewUploadedImage_AlreadyWithinSize_ServedAsIs(t *testing.T) {+ RegisterT(t)+ bus.Init()+ content := mock.UniformPNG(800, 600)+ mockBlob(content, "image/png")++ for _, size := range []string{"800", "1000", "2000"} {+ server := mock.NewServer()+ code, response := server.+ WithURL("https://demo.test.fider.io/?size="+size).+ OnTenant(mock.DemoTenant).+ AddParam("bkey", "attachments/image.png").+ Execute(handlers.ViewUploadedImage())++ Expect(code).Equals(http.StatusOK)+ Expect(response.Body.Bytes()).Equals(content)+ }+}+func TestFavicon_Bundled(t *testing.T) {RegisterT(t)bus.Init()diff --git a/app/pkg/mock/image.go b/app/pkg/mock/image.goindex ef5395dbb..de8bd7d80 100644--- a/app/pkg/mock/image.go+++ b/app/pkg/mock/image.go@@ -16,19 +16,28 @@ var uniformPNGCache sync.Map// "decompression bomb" images in tests (e.g. 12000x12000 is only a few KB).// Results are cached, callers must not modify the returned slice.func UniformPNG(width, height int) []byte {- key := [2]int{width, height}+ return UniformGrayPNG(width, height, 1, false)+}++// UniformGrayPNG is like UniformPNG, with the given bit depth (1, 2, 4, 8 or 16), and a+// tRNS chunk (making one gray level transparent) when transparent is true.+func UniformGrayPNG(width, height, bitDepth int, transparent bool) []byte {+ key := [4]int{width, height, bitDepth, 0}+ if transparent {+ key[3] = 1+ }if cached, ok := uniformPNGCache.Load(key); ok {return cached.([]byte)}- content := uniformPNG(width, height)+ content := uniformGrayPNG(width, height, bitDepth, transparent)uniformPNGCache.Store(key, content)return content}-func uniformPNG(width, height int) []byte {+func uniformGrayPNG(width, height, bitDepth int, transparent bool) []byte {var idat bytes.Bufferzw, _ := zlib.NewWriterLevel(&idat, zlib.BestCompression)- row := make([]byte, 1+(width+7)/8) // filter byte (0 = none) + packed 1-bit pixels+ row := make([]byte, 1+(width*bitDepth+7)/8) // filter byte (0 = none) + packed pixelsfor i := 0; i < height; i++ {_, _ = zw.Write(row)}@@ -37,12 +46,15 @@ func uniformPNG(width, height int) []byte {ihdr := make([]byte, 13)binary.BigEndian.PutUint32(ihdr[0:4], uint32(width))binary.BigEndian.PutUint32(ihdr[4:8], uint32(height))- ihdr[8] = 1 // bit depth+ ihdr[8] = byte(bitDepth)ihdr[9] = 0 // color type: grayscalevar out bytes.Bufferout.Write([]byte{0x89, 'P', 'N', 'G', '\r', '\n', 0x1a, '\n'})writePNGChunk(&out, "IHDR", ihdr)+ if transparent {+ writePNGChunk(&out, "tRNS", []byte{0, 0}) // gray level 0 is transparent+ }writePNGChunk(&out, "IDAT", idat.Bytes())writePNGChunk(&out, "IEND", nil)return out.Bytes()diff --git a/app/pkg/validate/image.go b/app/pkg/validate/image.goindex 987fa017e..03aa6b640 100644--- a/app/pkg/validate/image.go+++ b/app/pkg/validate/image.go@@ -6,6 +6,7 @@ import ("errors""image""image/color"+ "time"// Register the decoders for every format imagic accepts, so image.DecodeConfig// can read their headers regardless of which other packages are imported.@@ -17,16 +18,17 @@ import ()// MaxDecodeBytes is the estimated worst case amount of memory a single image decode-// (plus one full-size intermediate image) may use. Images over this are never decoded.+// (plus the intermediate images created by the operations applied to it) may use.+// Images over this are never decoded.//// A decode allocates memory proportional to width*height, regardless of how small the// compressed file is, so a tiny file can be a "decompression bomb". See-// EstimateDecodeBytes for the per-format estimates. With 256MB the largest images that-// can be decoded are roughly:-// - JPEG (colour, baseline): ~38 megapixels-// - JPEG (colour, progressive): ~14 megapixels-// - PNG (8-bit RGB/RGBA): ~22 megapixels-// - PNG (8-bit gray/paletted): ~44 megapixels+// ImageHeader.EstimateBytes for the per-format estimates. With 256MB and a single+// operation (e.g. a resize) the largest images that can be decoded are roughly:+// - JPEG (colour, baseline): ~24 megapixels+// - JPEG (colour, progressive): ~11.7 megapixels+// - PNG (8-bit RGB/RGBA/gray): ~22 megapixels+// - PNG (paletted): ~44 megapixels// - GIF: ~53 megapixelsconst MaxDecodeBytes int64 = 256 << 20@@ -39,86 +41,145 @@ const MaxImageSide = 16384// whole process, so parallel requests can't multiply the peak memory usage.const maxConcurrentDecodes = 2-// fullSizeIntermediateBytesPerPixel accounts for one full-size RGBA copy of the image made by-// an operation before the resize (e.g. imagic.Padding in the Favicon handler).-const fullSizeIntermediateBytesPerPixel = 4+// decodeWaitTimeout is how long a request waits for a decode slot before giving up with+// ErrDecodeBusy. Requests may hold a DB connection while waiting, so this must be bounded.+var decodeWaitTimeout = 5 * time.Second++// intermediateBytesPerPixel is the memory each operation (imagic.Padding, imagic.Resize,+// imagic.ChangeBackground) may allocate, per source pixel: at most one full-size RGBA+// image (Padding/ChangeBackground), or the horizontal pass of a resize, which is never+// larger than the source.+const intermediateBytesPerPixel = 4var decodeSemaphore = make(chan struct{}, maxConcurrentDecodes)// ErrImageTooLarge is returned when an image is estimated to need too much memory to decodevar ErrImageTooLarge = errors.New("image is too large to be decoded")-// EstimateDecodeBytes estimates the worst case memory needed to decode an image with-// the given header info (format and color model as returned by image.DecodeConfig) and-// to create one full-size intermediate copy of it. progressive is only used for JPEGs-// (see isProgressiveJPEG).+// ErrDecodeBusy is returned when no decode slot became available in time+var ErrDecodeBusy = errors.New("too many images are being processed, try again later")++// ImageHeader is the information about an image that can be read without decoding it+type ImageHeader struct {+ Width int+ Height int+ // Format is "png", "gif" or "jpeg"+ Format string+ ColorModel color.Model+ // Progressive is true for JPEGs that aren't (or might not be) baseline/extended sequential+ Progressive bool+}++// ReadImageHeader reads the image header without decoding the pixel data.+// Returns imagic.ErrNotSupported for anything imagic can't process.+func ReadImageHeader(content []byte) (*ImageHeader, error) {+ // Same logic as imagic.Parse (so uploads and serving accept the same formats), which+ // we can't use directly because it doesn't expose the color model we need to+ // estimate the memory needed to decode the image.+ cfg, format, err := image.DecodeConfig(bytes.NewReader(content))+ if err != nil || (format != "png" && format != "gif" && format != "jpeg") {+ return nil, imagic.ErrNotSupported+ }+ return &ImageHeader{+ Width: cfg.Width,+ Height: cfg.Height,+ Format: format,+ ColorModel: cfg.ColorModel,+ Progressive: format == "jpeg" && isProgressiveJPEG(content),+ }, nil+}++// EstimateBytes estimates the worst case memory needed to decode the image and then apply+// the given number of operations to it.// Returns -1 if the dimensions are invalid or beyond MaxImageSide.-func EstimateDecodeBytes(width, height int, format string, model color.Model, progressive bool) int64 {+func (h *ImageHeader) EstimateBytes(operations int) int64 {+ width, height := h.Width, h.Heightif width <= 0 || height <= 0 || width > MaxImageSide || height > MaxImageSide {return -1}var decodeBytesPerPixel int64- switch format {+ switch h.Format {case "jpeg":// Go's jpeg decoder allocates whole MCUs (up to 32x32 pixels with 4x sampling factors)width, height = roundUp(width, 32), roundUp(height, 32)// Buffers allocated by image/jpeg, per pixel, assuming no chroma subsampling (worst case):- // - Gray: the image.Gray (1)- // - YCbCr: the image.YCbCr (3)- // - Adobe RGB (RGBAModel): the image.YCbCr (3), converted into an image.RGBA (4)- // - CMYK (or unknown): the image.YCbCr (3) + black channel (1), converted into an image.CMYK (4)+ // - Gray (1 component): the image.Gray (1)+ // - 3 components: the image.YCbCr (3), converted into an image.RGBA (4) when the+ // image is Adobe RGB. That can be decided by an APP14 segment after the first+ // SOS, which image.DecodeConfig never sees, so always assume it.+ // - 4 components (CMYK/YCCK): the image.YCbCr (3) + black channel (1), converted+ // into an image.CMYK (4)// A progressive decode additionally keeps all DCT coefficients until the end// (64 x int32 per 8x8 block, i.e. 4 bytes per pixel per component).var imageBytes, components int64- switch model {+ switch h.ColorModel {case color.GrayModel:imageBytes, components = 1, 1- case color.YCbCrModel:- imageBytes, components = 3, 3- case color.RGBAModel:+ case color.YCbCrModel, color.RGBAModel:imageBytes, components = 3+4, 3default:imageBytes, components = 3+1+4, 4}decodeBytesPerPixel = imageBytes- if progressive {+ if h.Progressive {decodeBytesPerPixel += 4 * components}case "png":// Interlaced PNGs decode each pass into its own image before merging, so// assume twice the size of the final image.- decodeBytesPerPixel = 2 * bytesPerPixel(model)+ decodeBytesPerPixel = 2 * pngDecodedBytesPerPixel(h.ColorModel)case "gif":- // Only the first frame is decoded, and Go rejects frames larger than the logical screen- decodeBytesPerPixel = bytesPerPixel(model)+ // Only the first frame is decoded (as an image.Paletted), and Go rejects frames+ // larger than the logical screen+ decodeBytesPerPixel = 1default:- decodeBytesPerPixel = 2 * bytesPerPixel(model)+ return -1+ }++ if operations < 0 {+ operations = 0}- // Can't overflow: at most 16416 * 16416 * (24 + 4)- return int64(width) * int64(height) * (decodeBytesPerPixel + fullSizeIntermediateBytesPerPixel)+ // Can't overflow: at most 16416 * 16416 * (28 + 4 * operations)+ return int64(width) * int64(height) * (decodeBytesPerPixel + int64(operations)*intermediateBytesPerPixel)+}++// pngDecodedBytesPerPixel returns the size of each pixel of the image created by image/png+// for the given color model (as returned by image.DecodeConfig).+func pngDecodedBytesPerPixel(model color.Model) int64 {+ if _, ok := model.(color.Palette); ok {+ return 1 // image.Paletted+ }+ switch model {+ case color.GrayModel:+ // 1/2/4/8-bit gray is decoded to an image.Gray, but to an image.NRGBA if there's a+ // tRNS chunk, which image.DecodeConfig doesn't read for non paletted images.+ return 4+ case color.Gray16Model:+ // image.Gray16, or image.NRGBA64 with tRNS+ return 8+ case color.RGBAModel, color.NRGBAModel:+ // 8-bit RGB (image.RGBA, image.NRGBA with tRNS), gray+alpha and RGBA (image.NRGBA)+ return 4+ default:+ // 16-bit RGB (image.RGBA64, image.NRGBA64 with tRNS), gray+alpha and RGBA (image.NRGBA64)+ return 8+ }}func roundUp(n, multiple int) int {return (n + multiple - 1) / multiple * multiple}-// maxJPEGHeaderScan limits how many bytes isProgressiveJPEG looks at to find the SOF marker.-// Only metadata segments (EXIF, ICC profile, etc) come before it, each at most 64KB.-const maxJPEGHeaderScan = 1 << 20-// isProgressiveJPEG walks the JPEG segments up to the first Start Of Frame marker and// reports whether it's anything other than baseline/extended sequential (SOF0/SOF1).// Anything unexpected, malformed or truncated is reported as progressive, so that the// decode budget falls back to the worst case. When this returns false, image/jpeg follows// the exact same segments and sees the same SOF0/SOF1 marker (it rejects multiple SOFs).-func isProgressiveJPEG(content []byte) bool {- data := content- if len(data) > maxJPEGHeaderScan {- data = data[:maxJPEGHeaderScan]- }+// Segments are skipped by their length, so this is cheap even for large files.+func isProgressiveJPEG(data []byte) bool {if len(data) < 2 || data[0] != 0xFF || data[1] != 0xD8 { // SOIreturn true}@@ -162,71 +223,70 @@ func isProgressiveJPEG(content []byte) bool {}}-func bytesPerPixel(model color.Model) int64 {- if _, ok := model.(color.Palette); ok {- return 1- }- switch model {- case color.GrayModel, color.AlphaModel:- return 1- case color.Gray16Model, color.Alpha16Model:- return 2- case color.RGBAModel, color.NRGBAModel, color.CMYKModel:- return 4- case color.RGBA64Model, color.NRGBA64Model:- return 8- default:- return 8- }-}--// CheckDecodeBudget reads only the image header and checks that decoding the image-// stays within MaxDecodeBytes and MaxImageSide.-// Returns imagic.ErrNotSupported for unsupported formats and ErrImageTooLarge when over budget.-func CheckDecodeBudget(content []byte) error {- // imagic.Parse decides which formats are supported, so uploads and serving agree- file, err := imagic.Parse(content)- if err != nil {- return err- }-- // imagic.Parse doesn't expose the color model, which we need to estimate the- // bytes per pixel, so read the header again (this does not decode pixel data).- cfg, format, err := image.DecodeConfig(bytes.NewReader(content))+// CheckDecodeBudget reads only the image header and checks that decoding the image and+// applying the given number of operations stays within MaxDecodeBytes and MaxImageSide.+// Returns imagic.ErrNotSupported for unsupported formats, and ErrImageTooLarge (with the+// header) when over budget.+func CheckDecodeBudget(content []byte, operations int) (*ImageHeader, error) {+ header, err := ReadImageHeader(content)if err != nil {- return imagic.ErrNotSupported+ return nil, err}- progressive := format == "jpeg" && isProgressiveJPEG(content)- estimate := EstimateDecodeBytes(file.Width, file.Height, format, cfg.ColorModel, progressive)+ estimate := header.EstimateBytes(operations)if estimate < 0 || estimate > MaxDecodeBytes {- return ErrImageTooLarge+ return header, ErrImageTooLarge}- return nil+ return header, nil}-// SafeApply is the only way images should be decoded: it checks the decode budget+// SafeApply is the way user images should be decoded: it checks the decode budget// (returning ErrImageTooLarge without decoding if exceeded) and then applies the given-// operations, limiting how many decodes happen concurrently.+// operations, limiting how many decodes happen concurrently (see decodeWithinBudget).func SafeApply(ctx context.Context, content []byte, operations ...imagic.ImageOperation) ([]byte, error) {- if err := CheckDecodeBudget(content); err != nil {+ if _, err := CheckDecodeBudget(content, len(operations)); err != nil {+ return nil, err+ }+ return decodeWithinBudget(ctx, content, operations...)+}++// SafeResize is like SafeApply with imagic.Resize(size), but returns the content unchanged+// (without decoding it) when the image is already within size.+func SafeResize(ctx context.Context, content []byte, size int) ([]byte, error) {+ header, err := CheckDecodeBudget(content, 1)+ if err != nil {return nil, err}- return applyWithSemaphore(ctx, content, operations...)+ if size >= header.Width && size >= header.Height {+ return content, nil+ }+ return decodeWithinBudget(ctx, content, imagic.Resize(size))}// ApplyTrusted applies the operations without checking the decode budget. Only use it for// trusted images bundled with Fider, never for user content.func ApplyTrusted(ctx context.Context, content []byte, operations ...imagic.ImageOperation) ([]byte, error) {- return applyWithSemaphore(ctx, content, operations...)+ return decodeWithinBudget(ctx, content, operations...)}-func applyWithSemaphore(ctx context.Context, content []byte, operations ...imagic.ImageOperation) ([]byte, error) {+// decodeWithinBudget applies the operations once a decode slot is available. The caller+// must have checked the decode budget. Returns ErrDecodeBusy if no slot becomes available+// within decodeWaitTimeout, or the context error if the request is cancelled.+func decodeWithinBudget(ctx context.Context, content []byte, operations ...imagic.ImageOperation) ([]byte, error) {+ if err := ctx.Err(); err != nil {+ return nil, err+ }++ timer := time.NewTimer(decodeWaitTimeout)+ defer timer.Stop()+select {case decodeSemaphore <- struct{}{}:defer func() { <-decodeSemaphore }()case <-ctx.Done():return nil, ctx.Err()+ case <-timer.C:+ return nil, ErrDecodeBusy}return imagic.Apply(content, operations...)}diff --git a/app/pkg/validate/image_internal_test.go b/app/pkg/validate/image_internal_test.goindex 89c0769c1..85a3ca7bd 100644--- a/app/pkg/validate/image_internal_test.go+++ b/app/pkg/validate/image_internal_test.go@@ -7,34 +7,86 @@ import ("image/jpeg""image/png""testing"+ "time"+ "github.com/getfider/fider/app/models/dto". "github.com/getfider/fider/app/pkg/assert""github.com/goenning/imagic")-func TestSafeApply_LimitsConcurrentDecodes(t *testing.T) {- RegisterT(t)+func encodePNG(width, height int) []byte {+ var buf bytes.Buffer+ Expect(png.Encode(&buf, image.NewGray(image.Rect(0, 0, width, height)))).IsNil()+ return buf.Bytes()+}- // Occupy every decode slot+// occupyDecodeSlots takes every decode slot, and returns a function to release them+func occupyDecodeSlots() func() {for i := 0; i < maxConcurrentDecodes; i++ {decodeSemaphore <- struct{}{}}- defer func() {+ return func() {for i := 0; i < maxConcurrentDecodes; i++ {<-decodeSemaphore}- }()+ }+}++func withDecodeWaitTimeout(timeout time.Duration) func() {+ previous := decodeWaitTimeout+ decodeWaitTimeout = timeout+ return func() { decodeWaitTimeout = previous }+}++func TestSafeApply_LimitsConcurrentDecodes(t *testing.T) {+ RegisterT(t)+ defer withDecodeWaitTimeout(50 * time.Millisecond)()+ defer occupyDecodeSlots()()+ content := encodePNG(100, 100)++ // A new decode has to wait for a slot, and gives up after decodeWaitTimeout+ start := time.Now()+ result, err := SafeApply(context.Background(), content, imagic.Resize(50))+ Expect(err).Equals(ErrDecodeBusy)+ Expect(result).IsNil()+ Expect(time.Since(start) >= 50*time.Millisecond).IsTrue()- // A new decode has to wait for a slot, and gives up when the request is cancelled+ // ... or when the request is cancelled while waiting+ decodeWaitTimeout = time.Minutectx, cancel := context.WithCancel(context.Background())- cancel()- var buf bytes.Buffer- Expect(png.Encode(&buf, image.NewGray(image.Rect(0, 0, 100, 100)))).IsNil()- result, err := SafeApply(ctx, buf.Bytes(), imagic.Resize(50))+ time.AfterFunc(20*time.Millisecond, cancel)+ result, err = SafeApply(ctx, content, imagic.Resize(50))Expect(err).Equals(context.Canceled)Expect(result).IsNil()}+func TestSafeApply_CancelledRequestNeverDecodes(t *testing.T) {+ RegisterT(t)+ content := encodePNG(100, 100)++ // Even with free slots (where select would pick randomly), a cancelled request never decodes+ ctx, cancel := context.WithCancel(context.Background())+ cancel()+ for i := 0; i < 50; i++ {+ result, err := SafeApply(ctx, content, imagic.Resize(50))+ Expect(err).Equals(context.Canceled)+ Expect(result).IsNil()+ }+ Expect(len(decodeSemaphore)).Equals(0)+}++func TestImageUpload_DecodeBusy(t *testing.T) {+ RegisterT(t)+ defer withDecodeWaitTimeout(10 * time.Millisecond)()+ defer occupyDecodeSlots()()++ // Needs a resize (both dimensions over MaxDimensionSize)+ upload := &dto.ImageUpload{Upload: &dto.ImageUploadData{Content: encodePNG(1600, 1600)}}+ messages, err := ImageUpload(context.Background(), upload, ImageUploadOpts{MaxKilobytes: 5120})+ Expect(err).IsNil()+ Expect(messages).Equals([]string{"The server is busy processing other images. Please try again in a moment."})+}+// encodeJPEG returns a small JPEG. Go's encoder always writes baseline (SOF0) JPEGs.func encodeJPEG() []byte {var buf bytes.Buffer@@ -88,12 +140,14 @@ func TestIsProgressiveJPEG(t *testing.T) {Expect(isProgressiveJPEG([]byte{0xFF, 0xD8, 0xFF, 0xD9})).IsTrue() // EOI before SOFExpect(isProgressiveJPEG([]byte{0xFF, 0xD8, 0xFF, 0xE0, 0xFF, 0xFF, 0xFF, 0xC0})).IsTrue() // segment runs past the end- // SOF beyond the scan limit+ // Baseline photos with lots of metadata (over 2MB of APPn segments) before the SOFpadded := []byte{0xFF, 0xD8}- for len(padded) < maxJPEGHeaderScan {+ for len(padded) < 2<<20 {padded = append(padded, 0xFF, 0xE1, 0xFF, 0xFF)padded = append(padded, make([]byte, 0xFFFF-2)...)}- padded = append(padded, baseline[2:]...)+ Expect(isProgressiveJPEG(append(padded, baseline[2:]...))).IsFalse()+ Expect(isProgressiveJPEG(append(padded, withSOF(baseline, 0xC2)[2:]...))).IsTrue()+ // ... and truncated before the SOFExpect(isProgressiveJPEG(padded)).IsTrue()}diff --git a/app/pkg/validate/upload.go b/app/pkg/validate/upload.goindex 823d3bed6..6f25d9dcd 100644--- a/app/pkg/validate/upload.go+++ b/app/pkg/validate/upload.go@@ -84,39 +84,27 @@ func ImageUpload(ctx context.Context, upload *dto.ImageUpload, opts ImageUploadO}if upload != nil && upload.Upload != nil && len(upload.Upload.Content) > 0 {- logo, err := imagic.Parse(upload.Upload.Content)- if err != nil {- if err == imagic.ErrNotSupported {- messages = append(messages, i18n.T(ctx, "validation.custom.unsupportedfileformat"))- } else {- return nil, err- }- } else {- // imagic.Parse only reads the image header, so width/height are known without- // decoding. Reject decompression bombs before anything decodes the pixel data.- if err := CheckDecodeBudget(upload.Upload.Content); err != nil {- if err == ErrImageTooLarge {- messages = append(messages, imageTooLargeMessage(ctx))- return messages, nil- }- if err == imagic.ErrNotSupported {- messages = append(messages, i18n.T(ctx, "validation.custom.unsupportedfileformat"))- return messages, nil- }- return nil, err- }-- if logo.Width < opts.MinWidth || logo.Height < opts.MinHeight {+ // Only reads the image header, so decompression bombs are rejected before anything+ // decodes the pixel data. Budgeted for one operation: the resize below.+ header, err := CheckDecodeBudget(upload.Upload.Content, 1)+ switch err {+ case imagic.ErrNotSupported:+ messages = append(messages, i18n.T(ctx, "validation.custom.unsupportedfileformat"))+ case ErrImageTooLarge:+ messages = append(messages, i18n.T(ctx, "validation.custom.maximagepixels"))+ return messages, nil+ case nil:+ if header.Width < opts.MinWidth || header.Height < opts.MinHeight {messages = append(messages, i18n.T(ctx, "validation.custom.minimagedimensions",i18n.Params{"width": opts.MinWidth, "height": opts.MinHeight},))}- if opts.ExactRatio && logo.Width != logo.Height {+ if opts.ExactRatio && header.Width != header.Height {messages = append(messages, i18n.T(ctx, "validation.custom.imagesquareratio"))}- if logo.Size > (opts.MaxKilobytes * 1024) {+ if len(upload.Upload.Content) > (opts.MaxKilobytes * 1024) {messages = append(messages, i18n.T(ctx, "validation.custom.maximagesize",i18n.Params{"kilobytes": opts.MaxKilobytes},))@@ -127,10 +115,11 @@ func ImageUpload(ctx context.Context, upload *dto.ImageUpload, opts ImageUploadOreturn messages, nil}- if logo.Height > MaxDimensionSize && logo.Width > MaxDimensionSize {- newImageBytes, err := SafeApply(ctx, upload.Upload.Content, imagic.Resize(MaxDimensionSize))- if err == ErrImageTooLarge {- messages = append(messages, imageTooLargeMessage(ctx))+ if header.Height > MaxDimensionSize && header.Width > MaxDimensionSize {+ // The decode budget was already checked above+ newImageBytes, err := decodeWithinBudget(ctx, upload.Upload.Content, imagic.Resize(MaxDimensionSize))+ if err == ErrDecodeBusy {+ messages = append(messages, i18n.T(ctx, "validation.custom.imageprocessingbusy"))return messages, nil}if err != nil {@@ -138,12 +127,10 @@ func ImageUpload(ctx context.Context, upload *dto.ImageUpload, opts ImageUploadO}upload.Upload.Content = newImageBytes}+ default:+ return nil, err}}return messages, nil}--func imageTooLargeMessage(ctx context.Context) string {- return i18n.T(ctx, "validation.custom.maximagepixels")-}diff --git a/app/pkg/validate/upload_test.go b/app/pkg/validate/upload_test.goindex 4f48501e6..8942b919e 100644--- a/app/pkg/validate/upload_test.go+++ b/app/pkg/validate/upload_test.go@@ -4,11 +4,13 @@ import ("bytes""context""encoding/binary"+ "fmt""image""image/color""image/jpeg""math""os"+ "path/filepath""runtime""testing"@@ -236,6 +238,8 @@ func TestValidateImageUpload_DecompressionBomb(t *testing.T) {{"gif 40000x40000", mock.GIFHeader(40000, 40000)},// Small pixel count, but extreme aspect ratio{"png 100000x1", mock.UniformPNG(100000, 1)},+ // 6000x6000 8-bit gray with tRNS: decodes to NRGBA+ {"png gray+tRNS 6000x6000", mock.UniformGrayPNG(6000, 6000, 8, true)},// 4000x4000 progressive colour JPEG{"jpeg 4000x4000", jpegHeaderWithDimensions(t, 4000, 4000, true)},// 8000x8000 baseline colour JPEG@@ -331,72 +335,201 @@ func TestValidateImageUpload_Resize(t *testing.T) {}}-func TestEstimateDecodeBytes(t *testing.T) {+func header(width, height int, format string, model color.Model, progressive bool) *validate.ImageHeader {+ return &validate.ImageHeader{Width: width, Height: height, Format: format, ColorModel: model, Progressive: progressive}+}++func TestImageHeader_EstimateBytes(t *testing.T) {RegisterT(t)// Invalid or over the per-side cap- Expect(validate.EstimateDecodeBytes(0, 100, "png", color.GrayModel, false)).Equals(int64(-1))- Expect(validate.EstimateDecodeBytes(100, 0, "png", color.GrayModel, false)).Equals(int64(-1))- Expect(validate.EstimateDecodeBytes(-100, -100, "png", color.GrayModel, false)).Equals(int64(-1))- Expect(validate.EstimateDecodeBytes(validate.MaxImageSide+1, 1, "png", color.GrayModel, false)).Equals(int64(-1))- Expect(validate.EstimateDecodeBytes(1, validate.MaxImageSide+1, "png", color.GrayModel, false)).Equals(int64(-1))- Expect(validate.EstimateDecodeBytes(40_000_000, 1, "gif", color.Palette{}, false)).Equals(int64(-1))- Expect(validate.EstimateDecodeBytes(math.MaxInt, math.MaxInt, "png", color.GrayModel, false)).Equals(int64(-1))-- // Bytes per pixel include 4 bytes for a full-size RGBA intermediate+ Expect(header(0, 100, "png", color.GrayModel, false).EstimateBytes(1)).Equals(int64(-1))+ Expect(header(100, 0, "png", color.GrayModel, false).EstimateBytes(1)).Equals(int64(-1))+ Expect(header(-100, -100, "png", color.GrayModel, false).EstimateBytes(1)).Equals(int64(-1))+ Expect(header(validate.MaxImageSide+1, 1, "png", color.GrayModel, false).EstimateBytes(1)).Equals(int64(-1))+ Expect(header(1, validate.MaxImageSide+1, "png", color.GrayModel, false).EstimateBytes(1)).Equals(int64(-1))+ Expect(header(40_000_000, 1, "gif", color.Palette{}, false).EstimateBytes(1)).Equals(int64(-1))+ Expect(header(math.MaxInt, math.MaxInt, "png", color.GrayModel, false).EstimateBytes(1)).Equals(int64(-1))+ Expect(header(100, 100, "bmp", color.RGBAModel, false).EstimateBytes(1)).Equals(int64(-1))++ // With one operation: bytes per pixel include 4 bytes for the operation's intermediate imageconst mp = 1000 * 1000- Expect(validate.EstimateDecodeBytes(1000, 1000, "gif", color.Palette{}, false)).Equals(int64(5 * mp))- Expect(validate.EstimateDecodeBytes(1000, 1000, "png", color.Palette{}, false)).Equals(int64(6 * mp))- Expect(validate.EstimateDecodeBytes(1000, 1000, "png", color.GrayModel, false)).Equals(int64(6 * mp))- Expect(validate.EstimateDecodeBytes(1000, 1000, "png", color.Gray16Model, false)).Equals(int64(8 * mp))- Expect(validate.EstimateDecodeBytes(1000, 1000, "png", color.NRGBAModel, false)).Equals(int64(12 * mp))- Expect(validate.EstimateDecodeBytes(1000, 1000, "png", color.NRGBA64Model, false)).Equals(int64(20 * mp))+ Expect(header(1000, 1000, "gif", color.Palette{}, false).EstimateBytes(1)).Equals(int64(5 * mp))+ Expect(header(1000, 1000, "png", color.Palette{}, false).EstimateBytes(1)).Equals(int64(6 * mp))+ // Gray PNGs might have a tRNS chunk, decoding to NRGBA/NRGBA64+ Expect(header(1000, 1000, "png", color.GrayModel, false).EstimateBytes(1)).Equals(int64(12 * mp))+ Expect(header(1000, 1000, "png", color.Gray16Model, false).EstimateBytes(1)).Equals(int64(20 * mp))+ Expect(header(1000, 1000, "png", color.RGBAModel, false).EstimateBytes(1)).Equals(int64(12 * mp))+ Expect(header(1000, 1000, "png", color.NRGBAModel, false).EstimateBytes(1)).Equals(int64(12 * mp))+ Expect(header(1000, 1000, "png", color.RGBA64Model, false).EstimateBytes(1)).Equals(int64(20 * mp))+ Expect(header(1000, 1000, "png", color.NRGBA64Model, false).EstimateBytes(1)).Equals(int64(20 * mp))+// JPEG images are allocated in whole MCUs (up to 32x32), so 1000 is rounded up to 1024const jpegPixels = 1024 * 1024- Expect(validate.EstimateDecodeBytes(1000, 1000, "jpeg", color.GrayModel, false)).Equals(int64(5 * jpegPixels))- Expect(validate.EstimateDecodeBytes(1000, 1000, "jpeg", color.YCbCrModel, false)).Equals(int64(7 * jpegPixels))- Expect(validate.EstimateDecodeBytes(1000, 1000, "jpeg", color.RGBAModel, false)).Equals(int64(11 * jpegPixels))- Expect(validate.EstimateDecodeBytes(1000, 1000, "jpeg", color.CMYKModel, false)).Equals(int64(12 * jpegPixels))- Expect(validate.EstimateDecodeBytes(1000, 1000, "jpeg", color.GrayModel, true)).Equals(int64(9 * jpegPixels))- Expect(validate.EstimateDecodeBytes(1000, 1000, "jpeg", color.YCbCrModel, true)).Equals(int64(19 * jpegPixels))- Expect(validate.EstimateDecodeBytes(1000, 1000, "jpeg", color.RGBAModel, true)).Equals(int64(23 * jpegPixels))- Expect(validate.EstimateDecodeBytes(1000, 1000, "jpeg", color.CMYKModel, true)).Equals(int64(28 * jpegPixels))- Expect(validate.EstimateDecodeBytes(1024, 1024, "jpeg", color.YCbCrModel, false)).Equals(int64(7 * jpegPixels))+ Expect(header(1000, 1000, "jpeg", color.GrayModel, false).EstimateBytes(1)).Equals(int64(5 * jpegPixels))+ // 3 component JPEGs might be converted to RGBA by a late Adobe APP14 segment+ Expect(header(1000, 1000, "jpeg", color.YCbCrModel, false).EstimateBytes(1)).Equals(int64(11 * jpegPixels))+ Expect(header(1000, 1000, "jpeg", color.RGBAModel, false).EstimateBytes(1)).Equals(int64(11 * jpegPixels))+ Expect(header(1000, 1000, "jpeg", color.CMYKModel, false).EstimateBytes(1)).Equals(int64(12 * jpegPixels))+ Expect(header(1000, 1000, "jpeg", color.GrayModel, true).EstimateBytes(1)).Equals(int64(9 * jpegPixels))+ Expect(header(1000, 1000, "jpeg", color.YCbCrModel, true).EstimateBytes(1)).Equals(int64(23 * jpegPixels))+ Expect(header(1000, 1000, "jpeg", color.RGBAModel, true).EstimateBytes(1)).Equals(int64(23 * jpegPixels))+ Expect(header(1000, 1000, "jpeg", color.CMYKModel, true).EstimateBytes(1)).Equals(int64(28 * jpegPixels))+ Expect(header(1024, 1024, "jpeg", color.YCbCrModel, false).EstimateBytes(1)).Equals(int64(11 * jpegPixels))// progressive is ignored for other formats- Expect(validate.EstimateDecodeBytes(1000, 1000, "png", color.NRGBAModel, true)).Equals(int64(12 * mp))+ Expect(header(1000, 1000, "png", color.NRGBAModel, true).EstimateBytes(1)).Equals(int64(12 * mp))++ // Each operation adds 4 bytes per pixel+ Expect(header(1000, 1000, "png", color.GrayModel, false).EstimateBytes(0)).Equals(int64(8 * mp))+ Expect(header(1000, 1000, "png", color.GrayModel, false).EstimateBytes(3)).Equals(int64(20 * mp))// Worst case at the per-side cap doesn't overflow- Expect(validate.EstimateDecodeBytes(validate.MaxImageSide, validate.MaxImageSide, "jpeg", color.CMYKModel, true) > 0).IsTrue()+ Expect(header(validate.MaxImageSide, validate.MaxImageSide, "jpeg", color.CMYKModel, true).EstimateBytes(3) > 0).IsTrue()+}++// decodeAllocations decodes the image and returns it with the bytes allocated to decode it+func decodeAllocations(content []byte) (image.Image, int64) {+ var before, after runtime.MemStats+ runtime.GC()+ runtime.ReadMemStats(&before)+ img, _, err := image.Decode(bytes.NewReader(content))+ runtime.ReadMemStats(&after)+ Expect(err).IsNil()+ return img, int64(after.TotalAlloc - before.TotalAlloc)+}++func TestImageHeader_EstimateCoversPNGWithTransparency(t *testing.T) {+ RegisterT(t)++ var testCases = []struct {+ bitDepth int+ transparent bool+ decodedType string+ }{+ {1, false, "*image.Gray"},+ {8, false, "*image.Gray"},+ // image.DecodeConfig doesn't see the tRNS chunk, but image/png decodes to NRGBA/NRGBA64+ {1, true, "*image.NRGBA"},+ {8, true, "*image.NRGBA"},+ {16, false, "*image.Gray16"},+ {16, true, "*image.NRGBA64"},+ }++ for _, testCase := range testCases {+ content := mock.UniformGrayPNG(1000, 1000, testCase.bitDepth, testCase.transparent)+ header, err := validate.ReadImageHeader(content)+ Expect(err).IsNil()++ img, allocated := decodeAllocations(content)+ Expect(fmt.Sprintf("%T", img)).Equals(testCase.decodedType)+ Expect(header.EstimateBytes(0) >= allocated).IsTrue()+ }++ // A 36MP gray+tRNS PNG decodes to 144MB of NRGBA (288MB if interlaced), but is only a few KB+ content := mock.UniformGrayPNG(6000, 6000, 8, true)+ Expect(len(content) < 100*1024).IsTrue()+ _, err := validate.CheckDecodeBudget(content, 1)+ Expect(err).Equals(validate.ErrImageTooLarge)+}++// withLateAdobeAPP14 inserts an Adobe APP14 segment with transform=0 (RGB) just before EOI.+// image.DecodeConfig stops at the first SOS so never sees it, but a full decode+// converts the image to *image.RGBA.+func withLateAdobeAPP14(content []byte) []byte {+ Expect(bytes.HasSuffix(content, []byte{0xFF, 0xD9})).IsTrue()+ app14 := []byte{0xFF, 0xEE, 0x00, 0x0E, 'A', 'd', 'o', 'b', 'e', 0, 100, 0, 0, 0, 0, 0}+ result := append([]byte{}, content[:len(content)-2]...)+ result = append(result, app14...)+ return append(result, 0xFF, 0xD9)+}++func TestImageHeader_EstimateCoversJPEGWithLateAdobeAPP14(t *testing.T) {+ RegisterT(t)++ var buf bytes.Buffer+ Expect(jpeg.Encode(&buf, image.NewRGBA(image.Rect(0, 0, 1000, 1000)), nil)).IsNil()+ content := withLateAdobeAPP14(buf.Bytes())++ header, err := validate.ReadImageHeader(content)+ Expect(err).IsNil()+ Expect(header.ColorModel).Equals(color.YCbCrModel)+ Expect(header.Progressive).IsFalse()++ img, allocated := decodeAllocations(content)+ Expect(fmt.Sprintf("%T", img)).Equals("*image.RGBA")+ Expect(header.EstimateBytes(0) >= allocated).IsTrue()++ // Without the APP14 segment, still decoded as YCbCr+ img, allocated = decodeAllocations(buf.Bytes())+ Expect(fmt.Sprintf("%T", img)).Equals("*image.YCbCr")+ Expect(header.EstimateBytes(0) >= allocated).IsTrue()}func TestCheckDecodeBudget(t *testing.T) {RegisterT(t)- Expect(validate.CheckDecodeBudget(mock.UniformPNG(2000, 1000))).IsNil()- // 36MP * 6 bytes = 216MB- Expect(validate.CheckDecodeBudget(mock.UniformPNG(6000, 6000))).IsNil()- // 49MP * 6 bytes = 294MB- Expect(validate.CheckDecodeBudget(mock.UniformPNG(7000, 7000))).Equals(validate.ErrImageTooLarge)- Expect(validate.CheckDecodeBudget(mock.UniformPNG(12000, 12000))).Equals(validate.ErrImageTooLarge)- Expect(validate.CheckDecodeBudget(mock.UniformPNG(100000, 1))).Equals(validate.ErrImageTooLarge)- Expect(validate.CheckDecodeBudget(mock.GIFHeader(40000, 40000))).Equals(validate.ErrImageTooLarge)-- // 24MP baseline colour JPEG: 24MP * 7 bytes = 168MB- Expect(validate.CheckDecodeBudget(jpegHeaderWithDimensions(t, 6000, 4000, false))).IsNil()- // Same dimensions, but progressive: 24MP * 19 bytes = 457MB- Expect(validate.CheckDecodeBudget(jpegHeaderWithDimensions(t, 6000, 4000, true))).Equals(validate.ErrImageTooLarge)- // 12MP progressive phone photo: 12.2MP * 19 bytes = 233MB- Expect(validate.CheckDecodeBudget(jpegHeaderWithDimensions(t, 4032, 3024, true))).IsNil()- // 40MP baseline: 280MB- Expect(validate.CheckDecodeBudget(jpegHeaderWithDimensions(t, 8000, 5000, false))).Equals(validate.ErrImageTooLarge)+ check := func(content []byte, operations int) error {+ _, err := validate.CheckDecodeBudget(content, operations)+ return err+ }++ h, err := validate.CheckDecodeBudget(mock.UniformPNG(2000, 1000), 1)+ Expect(err).IsNil()+ Expect(h.Width).Equals(2000)+ Expect(h.Height).Equals(1000)+ Expect(h.Format).Equals("png")++ // 16MP * 12 bytes = 192MB+ Expect(check(mock.UniformPNG(4000, 4000), 1)).IsNil()+ // ... but not with 3 operations (Favicon with background): 16MP * 20 bytes = 320MB+ Expect(check(mock.UniformPNG(4000, 4000), 3)).Equals(validate.ErrImageTooLarge)+ // 25MP * 12 bytes = 300MB+ Expect(check(mock.UniformPNG(5000, 5000), 1)).Equals(validate.ErrImageTooLarge)+ Expect(check(mock.UniformPNG(12000, 12000), 1)).Equals(validate.ErrImageTooLarge)+ Expect(check(mock.UniformPNG(100000, 1), 1)).Equals(validate.ErrImageTooLarge)+ Expect(check(mock.GIFHeader(40000, 40000), 1)).Equals(validate.ErrImageTooLarge)++ // The header is returned when over budget+ h, err = validate.CheckDecodeBudget(mock.UniformPNG(12000, 12000), 1)+ Expect(err).Equals(validate.ErrImageTooLarge)+ Expect(h.Width).Equals(12000)++ // 24MP baseline colour JPEG: 6016x4000 * 11 bytes = 265MB+ Expect(check(jpegHeaderWithDimensions(t, 6000, 4000, false), 1)).IsNil()+ // Same dimensions, but progressive: 24MP * 23 bytes = 553MB+ Expect(check(jpegHeaderWithDimensions(t, 6000, 4000, true), 1)).Equals(validate.ErrImageTooLarge)+ // 9MP progressive: 3008x3008 * 23 bytes = 208MB+ Expect(check(jpegHeaderWithDimensions(t, 3000, 3000, true), 1)).IsNil()+ // 12MP progressive phone photo: 4032x3040 * 23 bytes = 282MB+ Expect(check(jpegHeaderWithDimensions(t, 4032, 3024, true), 1)).Equals(validate.ErrImageTooLarge)+ // 40MP baseline: 8000x5024 * 11 bytes = 442MB+ Expect(check(jpegHeaderWithDimensions(t, 8000, 5000, false), 1)).Equals(validate.ErrImageTooLarge)img, _ := os.ReadFile(env.Path("/app/pkg/web/testdata/logo2.jpg"))- Expect(validate.CheckDecodeBudget(img)).IsNil()+ Expect(check(img, 1)).IsNil()- Expect(validate.CheckDecodeBudget([]byte("not an image"))).Equals(imagic.ErrNotSupported)+ h, err = validate.CheckDecodeBudget([]byte("not an image"), 1)+ Expect(err).Equals(imagic.ErrNotSupported)+ Expect(h).IsNil()favicon, _ := os.ReadFile(env.Path("/app/pkg/web/testdata/favicon.ico"))- Expect(validate.CheckDecodeBudget(favicon)).Equals(imagic.ErrNotSupported)+ Expect(check(favicon, 1)).Equals(imagic.ErrNotSupported)+}++func TestReadImageHeader_SameFormatsAsImagic(t *testing.T) {+ RegisterT(t)++ files, err := filepath.Glob(env.Path("/app/pkg/web/testdata/*"))+ Expect(err).IsNil()+ Expect(len(files) > 5).IsTrue()+ files = append(files, env.Path("/README.md"), env.Path("/favicon.png"))++ for _, file := range files {+ content, _ := os.ReadFile(file)+ _, parseErr := imagic.Parse(content)+ _, headerErr := validate.ReadImageHeader(content)+ Expect(headerErr == nil).Equals(parseErr == nil)+ }}func TestSafeApply(t *testing.T) {@@ -419,4 +552,34 @@ func TestSafeApply(t *testing.T) {_, err = validate.SafeApply(context.Background(), []byte("not an image"), imagic.Resize(500))Expect(err).Equals(imagic.ErrNotSupported)++ // A valid header but corrupt pixel data fails to decode+ _, err = validate.SafeApply(context.Background(), mock.GIFHeader(100, 100), imagic.Resize(50))+ Expect(err).IsNotNil()+}++func TestSafeResize(t *testing.T) {+ RegisterT(t)++ content := mock.UniformPNG(2000, 1000)+ resized, err := validate.SafeResize(context.Background(), content, 500)+ Expect(err).IsNil()+ width, height := imageDimensions(t, resized)+ Expect(width).Equals(500)+ Expect(height).Equals(250)++ // Already within size: the original content is returned, without decoding it+ for _, size := range []int{2000, 3000} {+ var before, after runtime.MemStats+ runtime.GC()+ runtime.ReadMemStats(&before)+ result, err := validate.SafeResize(context.Background(), content, size)+ runtime.ReadMemStats(&after)+ Expect(err).IsNil()+ Expect(&result[0] == &content[0]).IsTrue()+ Expect(after.TotalAlloc-before.TotalAlloc < 1024*1024).IsTrue()+ }++ _, err = validate.SafeResize(context.Background(), mock.UniformPNG(12000, 12000), 500)+ Expect(err).Equals(validate.ErrImageTooLarge)}diff --git a/locale/en/server.json b/locale/en/server.jsonindex be6e2b427..059d52d99 100644--- a/locale/en/server.json+++ b/locale/en/server.json@@ -30,6 +30,7 @@"validation.custom.imagesquareratio": "The image must have an aspect ratio of 1:1.","validation.custom.maximagesize": "The image size must be smaller than {kilobytes}KB.","validation.custom.maximagepixels": "The image dimensions are too large. Please upload an image with a lower resolution.",+ "validation.custom.imageprocessingbusy": "The server is busy processing other images. Please try again in a moment.","validation.custom.invalidemoji": "Invalid reaction emoji.","enum.poststatus.open": "Open","enum.poststatus.started": "Started",