Handle PNG EXIF and distinguish transient encoder crashes from invalid images

This commit is contained in:
2026-11-21 00:58:18 +03:00
parent a9203f677d
commit 8bd25a1321
13 changed files with 690 additions and 85 deletions
+15 -5
View File
@@ -306,7 +306,8 @@ func (p *Pipeline) process(parent context.Context, j Job) (bool, error) {
return true, nil
}
var errInvalidImage = errors.New("invalid_image")
var ErrInvalidImage = errors.New("invalid_image")
var errInvalidImage = ErrInvalidImage
func resultPrefix(j Job) string {
return "originals/" + j.AttachmentID + "/v" + strconv.Itoa(j.Version) + "/"
@@ -346,10 +347,7 @@ func (p *Pipeline) perform(ctx context.Context, j Job, key, sha, contentType str
// an orphan encoder outliving the transform deadline (Linux container only).
configureChild(cmd)
if e = cmd.Run(); e != nil {
if transformCtx.Err() != nil {
return nil, transformCtx.Err()
}
return nil, errInvalidImage
return nil, classifyTransformFailure(transformCtx.Err(), e)
}
raw, e := os.ReadFile(filepath.Join(dir, "variants.json"))
if e != nil {
@@ -397,3 +395,15 @@ func faultPoint(point string) {
}
}
}
// A killed/crashed encoder is not evidence of an invalid source image.
func classifyTransformFailure(deadline, errorResult error) error {
if deadline != nil {
return deadline
}
var exited *exec.ExitError
if errors.As(errorResult, &exited) && exited.ExitCode() == 65 {
return ErrInvalidImage
}
return fmt.Errorf("transform temporarily unavailable")
}
+101
View File
@@ -0,0 +1,101 @@
package messenger
import (
"encoding/binary"
"github.com/disintegration/imaging"
"image"
"io"
"os"
)
// imaging handles JPEG APP1 orientation. PNG stores the same TIFF data in eXIf.
// Read only inside the already capped upload, with bounds checks on every IFD.
func pngOrientation(path string) int {
f, e := os.Open(path)
if e != nil {
return 1
}
defer f.Close()
if _, e = f.Seek(8, io.SeekStart); e != nil {
return 1
}
for {
var h [8]byte
if _, e = io.ReadFull(f, h[:]); e != nil {
return 1
}
n := binary.BigEndian.Uint32(h[:4])
if n > maxUpload {
return 1
}
if string(h[4:]) == "eXIf" {
b := make([]byte, n)
if _, e = io.ReadFull(f, b); e != nil {
return 1
}
return tiffOrientation(b)
}
if string(h[4:]) == "IEND" {
return 1
}
if _, e = f.Seek(int64(n)+4, io.SeekCurrent); e != nil {
return 1
}
}
}
func tiffOrientation(b []byte) int {
if len(b) < 8 {
return 1
}
var order binary.ByteOrder
switch string(b[:2]) {
case "II":
order = binary.LittleEndian
case "MM":
order = binary.BigEndian
default:
return 1
}
if order.Uint16(b[2:4]) != 42 {
return 1
}
offset := uint64(order.Uint32(b[4:8]))
if offset+2 > uint64(len(b)) {
return 1
}
count := int(order.Uint16(b[offset : offset+2]))
for i := 0; i < count; i++ {
pos := offset + 2 + uint64(i)*12
if pos+12 > uint64(len(b)) {
return 1
}
entry := b[pos : pos+12]
if order.Uint16(entry[:2]) == 0x112 && order.Uint16(entry[2:4]) == 3 && order.Uint32(entry[4:8]) == 1 {
v := int(order.Uint16(entry[8:10]))
if v >= 1 && v <= 8 {
return v
}
return 1
}
}
return 1
}
func orientPNG(img image.Image, orientation int) image.Image {
switch orientation {
case 2:
return imaging.FlipH(img)
case 3:
return imaging.Rotate180(img)
case 4:
return imaging.FlipV(img)
case 5:
return imaging.Transpose(img)
case 6:
return imaging.Rotate270(img)
case 7:
return imaging.Transverse(img)
case 8:
return imaging.Rotate90(img)
}
return img
}
+9 -5
View File
@@ -47,19 +47,23 @@ func Transform(input, dir string, versions ...int) error {
if e != nil {
return e
}
c, _, e := image.DecodeConfig(f)
c, format, e := image.DecodeConfig(f)
f.Close()
if e != nil || c.Width < 1 || c.Height < 1 || int64(c.Width)*int64(c.Height) > maxPixels {
return fmt.Errorf("invalid_image")
return ErrInvalidImage
}
img, e := imaging.Open(input, imaging.AutoOrientation(true))
if e != nil {
return fmt.Errorf("invalid_image")
return ErrInvalidImage
}
bounds := img.Bounds()
var oriented image.Image = img
if format == "png" {
oriented = orientPNG(img, pngOrientation(input))
}
bounds := oriented.Bounds()
white := image.NewNRGBA(bounds)
draw.Draw(white, bounds, &image.Uniform{C: color.White}, image.Point{}, draw.Src)
draw.Draw(white, bounds, img, bounds.Min, draw.Over)
draw.Draw(white, bounds, oriented, bounds.Min, draw.Over)
w, h := fitDimensions(bounds.Dx(), bounds.Dy(), 256)
thumbnail := imaging.Resize(white, w, h, imaging.Lanczos)
crop := imaging.Fill(white, 128, 128, imaging.Center, imaging.Lanczos)
@@ -0,0 +1,23 @@
package messenger
import (
"context"
"errors"
"os/exec"
"testing"
)
func TestTransformFailureClassification(t *testing.T) {
for _, c := range []struct {
command string
invalid bool
}{{"exit 65", true}, {"exit 2", false}, {"kill -KILL $$", false}} {
e := exec.Command("sh", "-c", c.command).Run()
if errors.Is(classifyTransformFailure(nil, e), ErrInvalidImage) != c.invalid {
t.Fatalf("misclassified encoder termination %q", c.command)
}
}
if !errors.Is(classifyTransformFailure(context.DeadlineExceeded, nil), context.DeadlineExceeded) {
t.Fatal("deadline lost")
}
}
+46
View File
@@ -3,6 +3,7 @@ package messenger
import (
"bytes"
"encoding/binary"
"hash/crc32"
"image"
"image/color"
"image/jpeg"
@@ -70,3 +71,48 @@ func TestTransformAlphaAndEXIF(t *testing.T) {
t.Fatalf("EXIF ignored: %v", img.Bounds())
}
}
func TestPNGEXIFAndMalformedIFD(t *testing.T) {
tiff := []byte{'I', 'I', 42, 0, 8, 0, 0, 0, 1, 0, 0x12, 1, 3, 0, 1, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0}
if tiffOrientation(tiff) != 6 {
t.Fatal("TIFF orientation")
}
for i := 0; i < len(tiff); i++ {
_ = tiffOrientation(tiff[:i])
}
bad := append([]byte{}, tiff...)
for i := 4; i < 8; i++ {
bad[i] = 255
}
if tiffOrientation(bad) != 1 {
t.Fatal("bad IFD offset")
}
var raw bytes.Buffer
png.Encode(&raw, image.NewNRGBA(image.Rect(0, 0, 320, 200)))
var chunk bytes.Buffer
binary.Write(&chunk, binary.BigEndian, uint32(len(tiff)))
chunk.WriteString("eXIf")
chunk.Write(tiff)
binary.Write(&chunk, binary.BigEndian, crc32.ChecksumIEEE(chunk.Bytes()[4:]))
data := append(append(append([]byte{}, raw.Bytes()[:33]...), chunk.Bytes()...), raw.Bytes()[33:]...)
dir := t.TempDir()
input := filepath.Join(dir, "input.png")
os.WriteFile(input, data, 0600)
if pngOrientation(input) != 6 {
t.Fatal("PNG eXIf orientation")
}
if _, e := exec.LookPath("cwebp"); e != nil {
return
}
if e := Transform(input, dir); e != nil {
t.Fatal(e)
}
b, _ := os.ReadFile(filepath.Join(dir, "thumbnail"))
img, e := jpeg.Decode(bytes.NewReader(b))
if e != nil {
t.Fatal(e)
}
if img.Bounds().Dx() != 160 || img.Bounds().Dy() != 256 {
t.Fatal("PNG orientation not applied", img.Bounds())
}
}