1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
package main

import (
	"bytes"
	"encoding/binary"
	"image"
	"image/color"
	"image/jpeg"
	"testing"
)

// buildJPEGWithOrientation encodes a JPEG and splices in an APP1 EXIF segment
// carrying the given orientation, so the parser is exercised against a real
// JPEG structure rather than a synthetic byte string.
func buildJPEGWithOrientation(t *testing.T, img image.Image, orientation int, bigEndian bool) []byte {
	t.Helper()
	var raw bytes.Buffer
	if err := jpeg.Encode(&raw, img, nil); err != nil {
		t.Fatalf("encode jpeg: %v", err)
	}
	data := raw.Bytes()

	// TIFF block: header (8 bytes) + one-entry IFD.
	var tiff bytes.Buffer
	var bo binary.ByteOrder
	if bigEndian {
		bo = binary.BigEndian
		tiff.WriteString("MM")
	} else {
		bo = binary.LittleEndian
		tiff.WriteString("II")
	}
	write16 := func(b *bytes.Buffer, v uint16) {
		var tmp [2]byte
		bo.PutUint16(tmp[:], v)
		b.Write(tmp[:])
	}
	write32 := func(b *bytes.Buffer, v uint32) {
		var tmp [4]byte
		bo.PutUint32(tmp[:], v)
		b.Write(tmp[:])
	}
	write16(&tiff, 42)
	write32(&tiff, 8) // IFD0 immediately follows the header
	write16(&tiff, 1) // one entry
	write16(&tiff, exifOrientationTag)
	write16(&tiff, 3) // type SHORT
	write32(&tiff, 1) // count
	write16(&tiff, uint16(orientation))
	write16(&tiff, 0) // padding of the 4-byte value field
	write32(&tiff, 0) // next-IFD offset

	payload := append([]byte("Exif\x00\x00"), tiff.Bytes()...)
	seg := []byte{0xFF, 0xE1}
	var length [2]byte
	binary.BigEndian.PutUint16(length[:], uint16(len(payload)+2))
	seg = append(seg, length[:]...)
	seg = append(seg, payload...)

	// Insert right after the SOI marker.
	out := append([]byte{}, data[:2]...)
	out = append(out, seg...)
	out = append(out, data[2:]...)
	return out
}

func testImage(w, h int) *image.NRGBA {
	img := image.NewNRGBA(image.Rect(0, 0, w, h))
	for y := 0; y < h; y++ {
		for x := 0; x < w; x++ {
			img.Set(x, y, color.NRGBA{uint8(x * 8), uint8(y * 8), 128, 255})
		}
	}
	return img
}

func TestJPEGOrientationAllValues(t *testing.T) {
	img := testImage(8, 8)
	for o := 1; o <= orientMax; o++ {
		for _, bigEndian := range []bool{false, true} {
			data := buildJPEGWithOrientation(t, img, o, bigEndian)
			if got := jpegOrientation(data); got != o {
				t.Errorf("orientation %d (bigEndian=%v): got %d", o, bigEndian, got)
			}
		}
	}
}

// Anything that is not a JPEG with a readable orientation must degrade to
// "normal" rather than erroring, because displaying a photo unrotated is a far
// better failure than rejecting the upload.
func TestJPEGOrientationDegradesToNormal(t *testing.T) {
	var plain bytes.Buffer
	if err := jpeg.Encode(&plain, testImage(4, 4), nil); err != nil {
		t.Fatal(err)
	}
	cases := map[string][]byte{
		"no exif":     plain.Bytes(),
		"empty":       {},
		"not a jpeg":  []byte("\x89PNG\r\n\x1a\n and then some"),
		"truncated":   plain.Bytes()[:10],
		"soi only":    {0xFF, 0xD8},
		"bad segment": {0xFF, 0xD8, 0xFF, 0xE1, 0x00, 0x02},
	}
	for name, data := range cases {
		t.Run(name, func(t *testing.T) {
			if got := jpegOrientation(data); got != orientNormal {
				t.Errorf("got %d, want %d", got, orientNormal)
			}
		})
	}
}

// Orientations 5–8 exchange the axes, which is the case most likely to be got
// wrong and the one that visibly breaks a page's layout.
func TestApplyOrientationDimensions(t *testing.T) {
	src := testImage(6, 10) // deliberately non-square
	for o := 1; o <= orientMax; o++ {
		got := applyOrientation(src, o)
		b := got.Bounds()
		wantW, wantH := 6, 10
		if o >= orientTransposed {
			wantW, wantH = 10, 6
		}
		if b.Dx() != wantW || b.Dy() != wantH {
			t.Errorf("orientation %d: got %dx%d, want %dx%d", o, b.Dx(), b.Dy(), wantW, wantH)
		}
	}
}

// Rotating by 90° clockwise must move the top-left pixel to the top-right.
// Checking a corner catches a transform that is transposed but mirrored.
func TestApplyOrientationRotate90(t *testing.T) {
	src := image.NewNRGBA(image.Rect(0, 0, 2, 3))
	mark := color.NRGBA{255, 0, 0, 255}
	src.Set(0, 0, mark)

	got := applyOrientation(src, orientRotate90)
	b := got.Bounds()
	if b.Dx() != 3 || b.Dy() != 2 {
		t.Fatalf("got %dx%d, want 3x2", b.Dx(), b.Dy())
	}
	r, g, bb, a := got.At(2, 0).RGBA()
	if r>>8 != 255 || g>>8 != 0 || bb>>8 != 0 || a>>8 != 255 {
		t.Errorf("top-left pixel did not land top-right: got %v", got.At(2, 0))
	}
}

// The normal orientation must not copy the image, since it is the case that
// runs for practically every upload.
func TestApplyOrientationNormalIsIdentity(t *testing.T) {
	src := testImage(4, 4)
	if got := applyOrientation(src, orientNormal); got != image.Image(src) {
		t.Error("normal orientation returned a copy instead of the source")
	}
}