oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package attach
2
3import (
4 "bytes"
5 "encoding/binary"
6 "errors"
7 "hash/crc32"
8 "image"
9 "image/color"
10 "image/jpeg"
11 "image/png"
12 "os"
13 "strings"
14 "testing"
15
16 "amadan.net/rastrillo/rastrillo/budget"
17)
18
19func TestMain(m *testing.M) { os.Exit(budget.Main(m)) }
20
21func pngOf(t *testing.T, w, h int) []byte {
22 t.Helper()
23 img := image.NewRGBA(image.Rect(0, 0, w, h))
24 for y := 0; y < h; y++ {
25 for x := 0; x < w; x++ {
26 img.Set(x, y, color.RGBA{uint8(x), uint8(y), 90, 255})
27 }
28 }
29 var b bytes.Buffer
30 if err := png.Encode(&b, img); err != nil {
31 t.Fatal(err)
32 }
33 return b.Bytes()
34}
35
36func jpegOf(t *testing.T, w, h int) []byte {
37 t.Helper()
38 img := image.NewRGBA(image.Rect(0, 0, w, h))
39 for y := 0; y < h; y++ {
40 for x := 0; x < w; x++ {
41 // Left half red, right half blue: an orientation test can see
42 // which way it turned.
43 c := color.RGBA{220, 20, 20, 255}
44 if x >= w/2 {
45 c = color.RGBA{20, 20, 220, 255}
46 }
47 img.Set(x, y, c)
48 }
49 }
50 var b bytes.Buffer
51 if err := jpeg.Encode(&b, img, &jpeg.Options{Quality: 90}); err != nil {
52 t.Fatal(err)
53 }
54 return b.Bytes()
55}
56
57// gpsMark is the latitude's numerators: bytes no image data contains by
58// chance in these small fixtures.
59var gpsMark = []uint32{424242, 171717, 999999}
60
61// exifWithGPS is a little-endian TIFF block: IFD0 with an orientation and
62// a GPS pointer; the GPS IFD with a latitude reference and three rationals.
63func exifWithGPS(orientation uint16) []byte {
64 le := binary.LittleEndian
65 b := []byte("II*\x00")
66 b = le.AppendUint32(b, 8)
67 // IFD0 at 8: two entries, then the next-IFD offset.
68 b = le.AppendUint16(b, 2)
69 b = le.AppendUint16(b, tagOrientation)
70 b = le.AppendUint16(b, 3)
71 b = le.AppendUint32(b, 1)
72 b = le.AppendUint16(b, orientation)
73 b = le.AppendUint16(b, 0)
74 gpsAt := uint32(8 + 2 + 2*12 + 4)
75 b = le.AppendUint16(b, tagGPS)
76 b = le.AppendUint16(b, 4)
77 b = le.AppendUint32(b, 1)
78 b = le.AppendUint32(b, gpsAt)
79 b = le.AppendUint32(b, 0)
80 // GPS IFD: LatitudeRef "N", Latitude (3 rationals out of line).
81 dataAt := gpsAt + 2 + 2*12 + 4
82 b = le.AppendUint16(b, 2)
83 b = le.AppendUint16(b, 1)
84 b = le.AppendUint16(b, 2)
85 b = le.AppendUint32(b, 2)
86 b = append(b, 'N', 0, 0, 0)
87 b = le.AppendUint16(b, 2)
88 b = le.AppendUint16(b, 5)
89 b = le.AppendUint32(b, 3)
90 b = le.AppendUint32(b, dataAt)
91 b = le.AppendUint32(b, 0)
92 for _, n := range gpsMark {
93 b = le.AppendUint32(b, n)
94 b = le.AppendUint32(b, 1)
95 }
96 return b
97}
98
99func segment(marker byte, payload []byte) []byte {
100 out := []byte{0xff, marker}
101 out = binary.BigEndian.AppendUint16(out, uint16(len(payload)+2))
102 return append(out, payload...)
103}
104
105// photo is a JPEG as a phone writes it: EXIF with orientation and GPS,
106// XMP naming the place too.
107func photo(t *testing.T, w, h int, orientation uint16) []byte {
108 t.Helper()
109 raw := jpegOf(t, w, h)
110 exif := segment(0xe1, append([]byte("Exif\x00\x00"), exifWithGPS(orientation)...))
111 xmp := segment(0xe1, []byte("http://ns.adobe.com/xap/1.0/\x00<x:xmpmeta><rdf:Description exif:GPSLatitude=\"51,30.0N\"/></x:xmpmeta>"))
112 iptc := segment(0xed, []byte("Photoshop 3.0\x008BIM\x04\x04City: Dublin"))
113 out := append([]byte{}, raw[:2]...)
114 out = append(out, exif...)
115 out = append(out, xmp...)
116 out = append(out, iptc...)
117 return append(out, raw[2:]...)
118}
119
120func hasGPSMark(b []byte) bool {
121 for _, n := range gpsMark {
122 if bytes.Contains(b, binary.LittleEndian.AppendUint32(nil, n)) {
123 return true
124 }
125 }
126 return false
127}
128
129func chunk(kind string, data []byte) []byte {
130 out := binary.BigEndian.AppendUint32(nil, uint32(len(data)))
131 out = append(out, kind...)
132 out = append(out, data...)
133 return binary.BigEndian.AppendUint32(out, crc32.ChecksumIEEE(append([]byte(kind), data...)))
134}
135
136// webp is a VP8X WebP whose image chunk is VP8L-shaped, with EXIF and XMP
137// chunks and their flags set.
138func webp(w, h int) []byte {
139 le := binary.LittleEndian
140 riff := func(kind string, data []byte) []byte {
141 out := append([]byte(kind), le.AppendUint32(nil, uint32(len(data)))...)
142 out = append(out, data...)
143 if len(data)%2 == 1 {
144 out = append(out, 0)
145 }
146 return out
147 }
148 x := make([]byte, 10)
149 x[0] = 0x08 | 0x04
150 x[4], x[5], x[6] = byte(w-1), byte((w-1)>>8), byte((w-1)>>16)
151 x[7], x[8], x[9] = byte(h-1), byte((h-1)>>8), byte((h-1)>>16)
152 vp8l := append([]byte{0x2f}, le.AppendUint32(nil, uint32(w-1)|uint32(h-1)<<14)...)
153 body := []byte("WEBP")
154 body = append(body, riff("VP8X", x)...)
155 body = append(body, riff("VP8L", append(vp8l, 1, 2, 3))...)
156 body = append(body, riff("EXIF", append([]byte{}, exifWithGPS(1)...))...)
157 body = append(body, riff("XMP ", []byte("exif:GPSLatitude"))...)
158 return append(append([]byte("RIFF"), le.AppendUint32(nil, uint32(len(body)))...), body...)
159}
160
161func TestInspectTypes(t *testing.T) {
162 jsonDoc := []byte(`{"a": 1}`)
163 big := bytes.Repeat([]byte("a"), MaxBytes+1)
164 for _, tc := range []struct {
165 name, declared string
166 data []byte
167 kind, media string
168 err error
169 }{
170 {"screen.png", "image/png", pngOf(t, 30, 20), KindImage, PNG, nil},
171 {"photo.JPG", "", jpegOf(t, 30, 20), KindImage, JPEG, nil},
172 {"", "", jpegOf(t, 30, 20), KindImage, JPEG, nil},
173 {"a.gif", "image/gif", []byte("GIF89a\x05\x00\x03\x00\x80\x00\x00\x00\x00\x00\xff\xff\xff!\xf9\x04\x00\x00\x00\x00\x00,\x00\x00\x00\x00\x05\x00\x03\x00\x00\x02\x03\x84\x8f\x05\x00;"), KindImage, GIF, nil},
174 {"pic.webp", "image/webp", webp(64, 48), KindImage, WebP, nil},
175 {"spec.pdf", "application/pdf", []byte("%PDF-1.7\n1 0 obj\n"), KindFile, PDF, nil},
176 {"notes.md", "text/markdown", []byte("# Notes\n\nhello"), KindFile, Markdown, nil},
177 {"rows.csv", "", []byte("a,b\n1,2\n"), KindFile, CSV, nil},
178 {"data.json", "application/json", jsonDoc, KindFile, JSON, nil},
179 {"broken.json", "", []byte(`{"a":`), KindFile, Text, nil},
180 {"build.log", "", []byte("2026-11-08 error: boom\n"), KindFile, Text, nil},
181 {"README", "", []byte("plain words"), KindFile, Text, nil},
182 {"tool.bin", "", []byte{0, 1, 2, 3, 0xff}, "", "", ErrType},
183 {"latin1.txt", "", []byte{'c', 'a', 'f', 0xe9}, "", "", ErrType},
184 {"photo.heic", "image/heic", []byte("\x00\x00\x00\x18ftypheic\x00\x00\x00\x00mif1heic"), "", "", ErrHEIC},
185 {"photo.HEIC", "", []byte{1, 2, 3}, "", "", ErrHEIC},
186 {"fake.txt", "", pngOf(t, 4, 4), "", "", ErrType},
187 {"fake.png", "", []byte("not an image"), "", "", ErrType},
188 {"lying.jpg", "", pngOf(t, 4, 4), "", "", ErrType},
189 {"declared.png", "image/jpeg", pngOf(t, 4, 4), "", "", ErrType},
190 {"doc.pdf", "", []byte("hello"), "", "", ErrType},
191 {"big.txt", "", big, "", "", ErrTooLarge},
192 {"empty.txt", "", nil, "", "", ErrEmpty},
193 } {
194 info, _, err := Inspect(tc.name, tc.declared, tc.data)
195 if !errors.Is(err, tc.err) || err == nil && (info.Kind != tc.kind || info.MediaType != tc.media) {
196 t.Errorf("%s: got %+v, %v; want %s %s %v", tc.name, info, err, tc.kind, tc.media, tc.err)
197 }
198 if err == nil && info.Name == "" {
199 t.Errorf("%s: no name", tc.name)
200 }
201 }
202 info, _, _ := Inspect("pic.webp", "", webp(640, 480))
203 if info.Width != 640 || info.Height != 480 {
204 t.Fatalf("webp size %dx%d", info.Width, info.Height)
205 }
206 if info, _, _ := Inspect("", "", jpegOf(t, 30, 20)); info.Name != "image.jpg" {
207 t.Fatalf("nameless image named %q", info.Name)
208 }
209}
210
211func TestStripLocationJPEG(t *testing.T) {
212 raw := photo(t, 40, 20, 6)
213 if !hasGPSMark(raw) || !bytes.Contains(raw, []byte("GPSLatitude")) || !bytes.Contains(raw, []byte("Dublin")) {
214 t.Fatal("fixture has no location to strip")
215 }
216 info, clean, err := Inspect("IMG_0001.jpg", "image/jpeg", raw)
217 if err != nil {
218 t.Fatal(err)
219 }
220 if hasGPSMark(clean) || bytes.Contains(clean, []byte("GPSLatitude")) || bytes.Contains(clean, []byte("Dublin")) {
221 t.Fatal("location survived")
222 }
223 if Orientation(clean) != 6 {
224 t.Fatalf("orientation %d, want it kept", Orientation(clean))
225 }
226 if info.Width != 20 || info.Height != 40 {
227 t.Fatalf("upright size %dx%d, want 20x40", info.Width, info.Height)
228 }
229 if _, err := jpeg.Decode(bytes.NewReader(clean)); err != nil {
230 t.Fatalf("stripped JPEG no longer decodes: %v", err)
231 }
232 // Big-endian EXIF too.
233 be := exifWithGPS(1)
234 if _, _, err := Inspect("x.jpg", "", append(append([]byte{0xff, 0xd8}, segment(0xe1, append([]byte("Exif\x00\x00"), be...))...), jpegOf(t, 8, 8)[2:]...)); err != nil {
235 t.Fatal(err)
236 }
237 // A truncated file is refused, not passed through.
238 if _, _, err := Inspect("cut.jpg", "", raw[:len(raw)/3]); err == nil {
239 t.Fatal("a truncated JPEG was accepted")
240 }
241}
242
243func TestStripLocationPNGAndWebP(t *testing.T) {
244 p := pngOf(t, 10, 10)
245 end := len(p) - 12 // before IEND
246 tagged := append(append(append([]byte{}, p[:end]...), chunk("eXIf", exifWithGPS(1))...), chunk("iTXt", []byte("XML:com.adobe.xmp\x00\x00\x00\x00\x00exif:GPSLatitude"))...)
247 tagged = append(tagged, p[end:]...)
248 _, clean, err := Inspect("s.png", "", tagged)
249 if err != nil {
250 t.Fatal(err)
251 }
252 if hasGPSMark(clean) || bytes.Contains(clean, []byte("GPSLatitude")) {
253 t.Fatal("PNG location survived")
254 }
255 if _, err := png.Decode(bytes.NewReader(clean)); err != nil {
256 t.Fatalf("stripped PNG no longer decodes: %v", err)
257 }
258 w := webp(30, 30)
259 _, clean, err = Inspect("w.webp", "", w)
260 if err != nil {
261 t.Fatal(err)
262 }
263 if hasGPSMark(clean) || bytes.Contains(clean, []byte("GPSLatitude")) || !bytes.Contains(clean, []byte("VP8L")) {
264 t.Fatal("WebP location survived or its image went")
265 }
266 if clean[20]&0x0c != 0 {
267 t.Fatal("WebP still flags EXIF or XMP")
268 }
269 if got := binary.LittleEndian.Uint32(clean[4:]); int(got) != len(clean)-8 {
270 t.Fatalf("RIFF size %d for %d bytes", got, len(clean))
271 }
272}
273
274func TestSafeName(t *testing.T) {
275 for in, want := range map[string]string{
276 "../../etc/passwd": "passwd",
277 `C:\Users\me\a b.txt`: "a b.txt",
278 "we\x00ird\n\"name\".md": "weirdname.md",
279 "...": "",
280 " spaced out .log ": "spaced out .log",
281 strings.Repeat("é", 100) + ".txt": strings.Repeat("é", 58) + ".txt",
282 } {
283 if got := SafeName(in); got != want {
284 t.Errorf("SafeName(%q) = %q, want %q", in, got, want)
285 }
286 }
287}
288
289func TestRenditions(t *testing.T) {
290 small := pngOf(t, 200, 100)
291 if out, typ, ok := ForModel(PNG, small); !ok || typ != PNG || !bytes.Equal(out, small) {
292 t.Fatal("a small upright image is sent as it is")
293 }
294 big := pngOf(t, 3000, 1000)
295 out, typ, ok := ForModel(PNG, big)
296 if !ok || typ != JPEG {
297 t.Fatalf("a large image was not scaled: %v %s", ok, typ)
298 }
299 if w, h := Dimensions(JPEG, out); w != ModelEdge || h != 522 {
300 t.Fatalf("model image %dx%d", w, h)
301 }
302 if _, _, ok := ForModel(WebP, webp(4000, 3000)); ok {
303 t.Fatal("a WebP too large to scale was offered as an image")
304 }
305 // Upright: orientation 6 turns the left (red) half to the top.
306 turned := photo(t, 40, 20, 6)
307 _, clean, _ := Inspect("p.jpg", "", turned)
308 out, _, ok = ForModel(JPEG, clean)
309 if !ok {
310 t.Fatal("a turned photo was not prepared")
311 }
312 img, err := jpeg.Decode(bytes.NewReader(out))
313 if err != nil {
314 t.Fatal(err)
315 }
316 if b := img.Bounds(); b.Dx() != 20 || b.Dy() != 40 {
317 t.Fatalf("upright size %v", b)
318 }
319 r, _, bl, _ := img.At(10, 5).RGBA()
320 if r < bl {
321 t.Fatal("orientation 6 put the wrong half on top")
322 }
323 if _, ok, _ := Preview(PNG, small); ok {
324 t.Fatal("a small image needs no preview")
325 }
326 prev, ok, err := Preview(PNG, big)
327 if err != nil || !ok {
328 t.Fatal(err)
329 }
330 if w, _ := Dimensions(JPEG, prev); w != PreviewEdge {
331 t.Fatalf("preview width %d", w)
332 }
333}
334
335// pngHeader is a PNG that claims w by h: a signature, IHDR and IEND,
336// which is all a header read looks at.
337func pngHeader(w, h uint32) []byte {
338 ihdr := binary.BigEndian.AppendUint32(nil, w)
339 ihdr = binary.BigEndian.AppendUint32(ihdr, h)
340 ihdr = append(ihdr, 8, 6, 0, 0, 0)
341 out := []byte("\x89PNG\r\n\x1a\n")
342 out = append(out, chunk("IHDR", ihdr)...)
343 return append(out, chunk("IEND", nil)...)
344}
345
346// Astra round 1: a small file may claim a canvas that decoding would
347// allocate in full. The header is read first; more than 12,000 px on a
348// side or 40 megapixels is refused before anything decodes.
349func TestPixelCap(t *testing.T) {
350 for _, size := range [][2]uint32{{100000, 100000}, {12001, 10}, {10, 12001}, {8000, 6000}} {
351 if _, _, err := Inspect("huge.png", "image/png", pngHeader(size[0], size[1])); !errors.Is(err, ErrPixels) {
352 t.Fatalf("%dx%d: %v, want refused for its pixels", size[0], size[1], err)
353 }
354 if _, _, err := Preview(PNG, pngHeader(size[0], size[1])); !errors.Is(err, ErrPixels) {
355 t.Fatalf("%dx%d: a preview was attempted: %v", size[0], size[1], err)
356 }
357 if _, _, ok := ForModel(PNG, pngHeader(size[0], size[1])); ok {
358 t.Fatalf("%dx%d: a model image was attempted", size[0], size[1])
359 }
360 }
361 if !TooBig(12000, 3334) || TooBig(12000, 3333) {
362 t.Fatal("the 40 megapixel line moved")
363 }
364}
365
366// Astra round 1: GPS placed after the scan, or after the end of the
367// image, survived. Every segment is walked through EOI; metadata after a
368// scan and anything after EOI are dropped.
369func TestStripLocationAfterScan(t *testing.T) {
370 raw := jpegOf(t, 40, 20)
371 exif := segment(0xe1, append([]byte("Exif\x00\x00"), exifWithGPS(1)...))
372 eoi := len(raw) - 2
373 late := append(append(append([]byte{}, raw[:eoi]...), exif...), raw[eoi:]...)
374 trailing := append(append([]byte{}, raw...), exif...)
375 for name, b := range map[string][]byte{"after the scan": late, "after EOI": trailing} {
376 if !hasGPSMark(b) {
377 t.Fatalf("%s: fixture has no GPS", name)
378 }
379 _, clean, err := Inspect("late.jpg", "", b)
380 if err != nil {
381 t.Fatalf("%s: %v", name, err)
382 }
383 if hasGPSMark(clean) {
384 t.Fatalf("%s: location survived", name)
385 }
386 if img, err := jpeg.Decode(bytes.NewReader(clean)); err != nil || img.Bounds().Dx() != 40 {
387 t.Fatalf("%s: no longer decodes: %v", name, err)
388 }
389 }
390}
391