package attach import ( "bytes" "encoding/binary" "errors" "hash/crc32" "image" "image/color" "image/jpeg" "image/png" "os" "strings" "testing" "amadan.net/rastrillo/rastrillo/budget" ) func TestMain(m *testing.M) { os.Exit(budget.Main(m)) } func pngOf(t *testing.T, w, h int) []byte { t.Helper() img := image.NewRGBA(image.Rect(0, 0, w, h)) for y := 0; y < h; y++ { for x := 0; x < w; x++ { img.Set(x, y, color.RGBA{uint8(x), uint8(y), 90, 255}) } } var b bytes.Buffer if err := png.Encode(&b, img); err != nil { t.Fatal(err) } return b.Bytes() } func jpegOf(t *testing.T, w, h int) []byte { t.Helper() img := image.NewRGBA(image.Rect(0, 0, w, h)) for y := 0; y < h; y++ { for x := 0; x < w; x++ { // Left half red, right half blue: an orientation test can see // which way it turned. c := color.RGBA{220, 20, 20, 255} if x >= w/2 { c = color.RGBA{20, 20, 220, 255} } img.Set(x, y, c) } } var b bytes.Buffer if err := jpeg.Encode(&b, img, &jpeg.Options{Quality: 90}); err != nil { t.Fatal(err) } return b.Bytes() } // gpsMark is the latitude's numerators: bytes no image data contains by // chance in these small fixtures. var gpsMark = []uint32{424242, 171717, 999999} // exifWithGPS is a little-endian TIFF block: IFD0 with an orientation and // a GPS pointer; the GPS IFD with a latitude reference and three rationals. func exifWithGPS(orientation uint16) []byte { le := binary.LittleEndian b := []byte("II*\x00") b = le.AppendUint32(b, 8) // IFD0 at 8: two entries, then the next-IFD offset. b = le.AppendUint16(b, 2) b = le.AppendUint16(b, tagOrientation) b = le.AppendUint16(b, 3) b = le.AppendUint32(b, 1) b = le.AppendUint16(b, orientation) b = le.AppendUint16(b, 0) gpsAt := uint32(8 + 2 + 2*12 + 4) b = le.AppendUint16(b, tagGPS) b = le.AppendUint16(b, 4) b = le.AppendUint32(b, 1) b = le.AppendUint32(b, gpsAt) b = le.AppendUint32(b, 0) // GPS IFD: LatitudeRef "N", Latitude (3 rationals out of line). dataAt := gpsAt + 2 + 2*12 + 4 b = le.AppendUint16(b, 2) b = le.AppendUint16(b, 1) b = le.AppendUint16(b, 2) b = le.AppendUint32(b, 2) b = append(b, 'N', 0, 0, 0) b = le.AppendUint16(b, 2) b = le.AppendUint16(b, 5) b = le.AppendUint32(b, 3) b = le.AppendUint32(b, dataAt) b = le.AppendUint32(b, 0) for _, n := range gpsMark { b = le.AppendUint32(b, n) b = le.AppendUint32(b, 1) } return b } func segment(marker byte, payload []byte) []byte { out := []byte{0xff, marker} out = binary.BigEndian.AppendUint16(out, uint16(len(payload)+2)) return append(out, payload...) } // photo is a JPEG as a phone writes it: EXIF with orientation and GPS, // XMP naming the place too. func photo(t *testing.T, w, h int, orientation uint16) []byte { t.Helper() raw := jpegOf(t, w, h) exif := segment(0xe1, append([]byte("Exif\x00\x00"), exifWithGPS(orientation)...)) xmp := segment(0xe1, []byte("http://ns.adobe.com/xap/1.0/\x00")) iptc := segment(0xed, []byte("Photoshop 3.0\x008BIM\x04\x04City: Dublin")) out := append([]byte{}, raw[:2]...) out = append(out, exif...) out = append(out, xmp...) out = append(out, iptc...) return append(out, raw[2:]...) } func hasGPSMark(b []byte) bool { for _, n := range gpsMark { if bytes.Contains(b, binary.LittleEndian.AppendUint32(nil, n)) { return true } } return false } func chunk(kind string, data []byte) []byte { out := binary.BigEndian.AppendUint32(nil, uint32(len(data))) out = append(out, kind...) out = append(out, data...) return binary.BigEndian.AppendUint32(out, crc32.ChecksumIEEE(append([]byte(kind), data...))) } // webp is a VP8X WebP whose image chunk is VP8L-shaped, with EXIF and XMP // chunks and their flags set. func webp(w, h int) []byte { le := binary.LittleEndian riff := func(kind string, data []byte) []byte { out := append([]byte(kind), le.AppendUint32(nil, uint32(len(data)))...) out = append(out, data...) if len(data)%2 == 1 { out = append(out, 0) } return out } x := make([]byte, 10) x[0] = 0x08 | 0x04 x[4], x[5], x[6] = byte(w-1), byte((w-1)>>8), byte((w-1)>>16) x[7], x[8], x[9] = byte(h-1), byte((h-1)>>8), byte((h-1)>>16) vp8l := append([]byte{0x2f}, le.AppendUint32(nil, uint32(w-1)|uint32(h-1)<<14)...) body := []byte("WEBP") body = append(body, riff("VP8X", x)...) body = append(body, riff("VP8L", append(vp8l, 1, 2, 3))...) body = append(body, riff("EXIF", append([]byte{}, exifWithGPS(1)...))...) body = append(body, riff("XMP ", []byte("exif:GPSLatitude"))...) return append(append([]byte("RIFF"), le.AppendUint32(nil, uint32(len(body)))...), body...) } func TestInspectTypes(t *testing.T) { jsonDoc := []byte(`{"a": 1}`) big := bytes.Repeat([]byte("a"), MaxBytes+1) for _, tc := range []struct { name, declared string data []byte kind, media string err error }{ {"screen.png", "image/png", pngOf(t, 30, 20), KindImage, PNG, nil}, {"photo.JPG", "", jpegOf(t, 30, 20), KindImage, JPEG, nil}, {"", "", jpegOf(t, 30, 20), KindImage, JPEG, nil}, {"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}, {"pic.webp", "image/webp", webp(64, 48), KindImage, WebP, nil}, {"spec.pdf", "application/pdf", []byte("%PDF-1.7\n1 0 obj\n"), KindFile, PDF, nil}, {"notes.md", "text/markdown", []byte("# Notes\n\nhello"), KindFile, Markdown, nil}, {"rows.csv", "", []byte("a,b\n1,2\n"), KindFile, CSV, nil}, {"data.json", "application/json", jsonDoc, KindFile, JSON, nil}, {"broken.json", "", []byte(`{"a":`), KindFile, Text, nil}, {"build.log", "", []byte("2026-11-08 error: boom\n"), KindFile, Text, nil}, {"README", "", []byte("plain words"), KindFile, Text, nil}, {"tool.bin", "", []byte{0, 1, 2, 3, 0xff}, "", "", ErrType}, {"latin1.txt", "", []byte{'c', 'a', 'f', 0xe9}, "", "", ErrType}, {"photo.heic", "image/heic", []byte("\x00\x00\x00\x18ftypheic\x00\x00\x00\x00mif1heic"), "", "", ErrHEIC}, {"photo.HEIC", "", []byte{1, 2, 3}, "", "", ErrHEIC}, {"fake.txt", "", pngOf(t, 4, 4), "", "", ErrType}, {"fake.png", "", []byte("not an image"), "", "", ErrType}, {"lying.jpg", "", pngOf(t, 4, 4), "", "", ErrType}, {"declared.png", "image/jpeg", pngOf(t, 4, 4), "", "", ErrType}, {"doc.pdf", "", []byte("hello"), "", "", ErrType}, {"big.txt", "", big, "", "", ErrTooLarge}, {"empty.txt", "", nil, "", "", ErrEmpty}, } { info, _, err := Inspect(tc.name, tc.declared, tc.data) if !errors.Is(err, tc.err) || err == nil && (info.Kind != tc.kind || info.MediaType != tc.media) { t.Errorf("%s: got %+v, %v; want %s %s %v", tc.name, info, err, tc.kind, tc.media, tc.err) } if err == nil && info.Name == "" { t.Errorf("%s: no name", tc.name) } } info, _, _ := Inspect("pic.webp", "", webp(640, 480)) if info.Width != 640 || info.Height != 480 { t.Fatalf("webp size %dx%d", info.Width, info.Height) } if info, _, _ := Inspect("", "", jpegOf(t, 30, 20)); info.Name != "image.jpg" { t.Fatalf("nameless image named %q", info.Name) } } func TestStripLocationJPEG(t *testing.T) { raw := photo(t, 40, 20, 6) if !hasGPSMark(raw) || !bytes.Contains(raw, []byte("GPSLatitude")) || !bytes.Contains(raw, []byte("Dublin")) { t.Fatal("fixture has no location to strip") } info, clean, err := Inspect("IMG_0001.jpg", "image/jpeg", raw) if err != nil { t.Fatal(err) } if hasGPSMark(clean) || bytes.Contains(clean, []byte("GPSLatitude")) || bytes.Contains(clean, []byte("Dublin")) { t.Fatal("location survived") } if Orientation(clean) != 6 { t.Fatalf("orientation %d, want it kept", Orientation(clean)) } if info.Width != 20 || info.Height != 40 { t.Fatalf("upright size %dx%d, want 20x40", info.Width, info.Height) } if _, err := jpeg.Decode(bytes.NewReader(clean)); err != nil { t.Fatalf("stripped JPEG no longer decodes: %v", err) } // Big-endian EXIF too. be := exifWithGPS(1) 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 { t.Fatal(err) } // A truncated file is refused, not passed through. if _, _, err := Inspect("cut.jpg", "", raw[:len(raw)/3]); err == nil { t.Fatal("a truncated JPEG was accepted") } } func TestStripLocationPNGAndWebP(t *testing.T) { p := pngOf(t, 10, 10) end := len(p) - 12 // before IEND tagged := append(append(append([]byte{}, p[:end]...), chunk("eXIf", exifWithGPS(1))...), chunk("iTXt", []byte("XML:com.adobe.xmp\x00\x00\x00\x00\x00exif:GPSLatitude"))...) tagged = append(tagged, p[end:]...) _, clean, err := Inspect("s.png", "", tagged) if err != nil { t.Fatal(err) } if hasGPSMark(clean) || bytes.Contains(clean, []byte("GPSLatitude")) { t.Fatal("PNG location survived") } if _, err := png.Decode(bytes.NewReader(clean)); err != nil { t.Fatalf("stripped PNG no longer decodes: %v", err) } w := webp(30, 30) _, clean, err = Inspect("w.webp", "", w) if err != nil { t.Fatal(err) } if hasGPSMark(clean) || bytes.Contains(clean, []byte("GPSLatitude")) || !bytes.Contains(clean, []byte("VP8L")) { t.Fatal("WebP location survived or its image went") } if clean[20]&0x0c != 0 { t.Fatal("WebP still flags EXIF or XMP") } if got := binary.LittleEndian.Uint32(clean[4:]); int(got) != len(clean)-8 { t.Fatalf("RIFF size %d for %d bytes", got, len(clean)) } } func TestSafeName(t *testing.T) { for in, want := range map[string]string{ "../../etc/passwd": "passwd", `C:\Users\me\a b.txt`: "a b.txt", "we\x00ird\n\"name\".md": "weirdname.md", "...": "", " spaced out .log ": "spaced out .log", strings.Repeat("é", 100) + ".txt": strings.Repeat("é", 58) + ".txt", } { if got := SafeName(in); got != want { t.Errorf("SafeName(%q) = %q, want %q", in, got, want) } } } func TestRenditions(t *testing.T) { small := pngOf(t, 200, 100) if out, typ, ok := ForModel(PNG, small); !ok || typ != PNG || !bytes.Equal(out, small) { t.Fatal("a small upright image is sent as it is") } big := pngOf(t, 3000, 1000) out, typ, ok := ForModel(PNG, big) if !ok || typ != JPEG { t.Fatalf("a large image was not scaled: %v %s", ok, typ) } if w, h := Dimensions(JPEG, out); w != ModelEdge || h != 522 { t.Fatalf("model image %dx%d", w, h) } if _, _, ok := ForModel(WebP, webp(4000, 3000)); ok { t.Fatal("a WebP too large to scale was offered as an image") } // Upright: orientation 6 turns the left (red) half to the top. turned := photo(t, 40, 20, 6) _, clean, _ := Inspect("p.jpg", "", turned) out, _, ok = ForModel(JPEG, clean) if !ok { t.Fatal("a turned photo was not prepared") } img, err := jpeg.Decode(bytes.NewReader(out)) if err != nil { t.Fatal(err) } if b := img.Bounds(); b.Dx() != 20 || b.Dy() != 40 { t.Fatalf("upright size %v", b) } r, _, bl, _ := img.At(10, 5).RGBA() if r < bl { t.Fatal("orientation 6 put the wrong half on top") } if _, ok, _ := Preview(PNG, small); ok { t.Fatal("a small image needs no preview") } prev, ok, err := Preview(PNG, big) if err != nil || !ok { t.Fatal(err) } if w, _ := Dimensions(JPEG, prev); w != PreviewEdge { t.Fatalf("preview width %d", w) } } // pngHeader is a PNG that claims w by h: a signature, IHDR and IEND, // which is all a header read looks at. func pngHeader(w, h uint32) []byte { ihdr := binary.BigEndian.AppendUint32(nil, w) ihdr = binary.BigEndian.AppendUint32(ihdr, h) ihdr = append(ihdr, 8, 6, 0, 0, 0) out := []byte("\x89PNG\r\n\x1a\n") out = append(out, chunk("IHDR", ihdr)...) return append(out, chunk("IEND", nil)...) } // Astra round 1: a small file may claim a canvas that decoding would // allocate in full. The header is read first; more than 12,000 px on a // side or 40 megapixels is refused before anything decodes. func TestPixelCap(t *testing.T) { for _, size := range [][2]uint32{{100000, 100000}, {12001, 10}, {10, 12001}, {8000, 6000}} { if _, _, err := Inspect("huge.png", "image/png", pngHeader(size[0], size[1])); !errors.Is(err, ErrPixels) { t.Fatalf("%dx%d: %v, want refused for its pixels", size[0], size[1], err) } if _, _, err := Preview(PNG, pngHeader(size[0], size[1])); !errors.Is(err, ErrPixels) { t.Fatalf("%dx%d: a preview was attempted: %v", size[0], size[1], err) } if _, _, ok := ForModel(PNG, pngHeader(size[0], size[1])); ok { t.Fatalf("%dx%d: a model image was attempted", size[0], size[1]) } } if !TooBig(12000, 3334) || TooBig(12000, 3333) { t.Fatal("the 40 megapixel line moved") } } // Astra round 1: GPS placed after the scan, or after the end of the // image, survived. Every segment is walked through EOI; metadata after a // scan and anything after EOI are dropped. func TestStripLocationAfterScan(t *testing.T) { raw := jpegOf(t, 40, 20) exif := segment(0xe1, append([]byte("Exif\x00\x00"), exifWithGPS(1)...)) eoi := len(raw) - 2 late := append(append(append([]byte{}, raw[:eoi]...), exif...), raw[eoi:]...) trailing := append(append([]byte{}, raw...), exif...) for name, b := range map[string][]byte{"after the scan": late, "after EOI": trailing} { if !hasGPSMark(b) { t.Fatalf("%s: fixture has no GPS", name) } _, clean, err := Inspect("late.jpg", "", b) if err != nil { t.Fatalf("%s: %v", name, err) } if hasGPSMark(clean) { t.Fatalf("%s: location survived", name) } if img, err := jpeg.Decode(bytes.NewReader(clean)); err != nil || img.Bounds().Dx() != 40 { t.Fatalf("%s: no longer decodes: %v", name, err) } } }