package attachments import ( "bytes" "context" "image" "image/color" "image/jpeg" "image/png" "os" "path/filepath" "testing" "gitflic.ru/project/bulla-max/mtusi2026lab/internal/common" ) // writeTemp stores raw bytes in a temporary file and returns its path. The // validator works on *os.File so it can seek, sniff and decode the same body // without loading it into memory twice. func writeTemp(t *testing.T, name string, data []byte) *os.File { t.Helper() path := filepath.Join(t.TempDir(), name) if err := os.WriteFile(path, data, 0o600); err != nil { t.Fatalf("write %s: %v", path, err) } file, err := os.Open(path) if err != nil { t.Fatalf("open %s: %v", path, err) } t.Cleanup(func() { _ = file.Close() }) return file } func encodePNG(t *testing.T, width, height int) []byte { t.Helper() img := image.NewRGBA(image.Rect(0, 0, width, height)) for x := 0; x < width; x++ { for y := 0; y < height; y++ { img.Set(x, y, color.RGBA{R: uint8(x), G: uint8(y), B: 0x40, A: 0xff}) } } var buf bytes.Buffer if err := png.Encode(&buf, img); err != nil { t.Fatalf("encode png: %v", err) } return buf.Bytes() } func TestValidateAcceptsPNGAndJPEG(t *testing.T) { validator := NewValidator(40_000_000, 256<<20) ctx := context.Background() pngFile := writeTemp(t, "image.png", encodePNG(t, 8, 6)) info, err := validator.Validate(ctx, pngFile, "image/png") if err != nil { t.Fatalf("valid png rejected: %v", err) } if info.ContentType != "image/png" || info.Width != 8 || info.Height != 6 { t.Fatalf("unexpected png info: %+v", info) } img := image.NewRGBA(image.Rect(0, 0, 4, 3)) var buf bytes.Buffer if err = jpeg.Encode(&buf, img, nil); err != nil { t.Fatalf("encode jpeg: %v", err) } jpegFile := writeTemp(t, "image.jpg", buf.Bytes()) info, err = validator.Validate(ctx, jpegFile, "image/jpeg; charset=binary") if err != nil { t.Fatalf("valid jpeg rejected: %v", err) } if info.ContentType != "image/jpeg" || info.Width != 4 || info.Height != 3 { t.Fatalf("unexpected jpeg info: %+v", info) } } func TestValidateRejectsMismatchedOrBrokenContent(t *testing.T) { validator := NewValidator(40_000_000, 256<<20) ctx := context.Background() pngBytes := encodePNG(t, 8, 6) cases := []struct { name string data []byte declared string code string }{ {"png declared as jpeg", pngBytes, "image/jpeg", common.ErrorCodeUnsupportedMedia}, {"text declared as png", []byte("this is not an image at all"), "image/png", common.ErrorCodeUnsupportedMedia}, {"unsupported declared type", pngBytes, "image/gif", common.ErrorCodeUnsupportedMedia}, {"garbage declared type", pngBytes, "not a media type", common.ErrorCodeUnsupportedMedia}, {"truncated png", pngBytes[:len(pngBytes)/2], "image/png", common.ErrorCodeUnsupportedMedia}, {"empty body", nil, "image/png", common.ErrorCodeUnsupportedMedia}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { file := writeTemp(t, "upload", tc.data) if _, err := validator.Validate(ctx, file, tc.declared); !common.IsCode(err, tc.code) { t.Fatalf("Validate(%q) = %v, want code %s", tc.name, err, tc.code) } }) } } func TestValidateRejectsTooManyPixelsBeforeDecoding(t *testing.T) { validator := NewValidator(100, 256<<20) file := writeTemp(t, "big.png", encodePNG(t, 20, 20)) _, err := validator.Validate(context.Background(), file, "image/png") if !common.IsCode(err, common.ErrorCodePayloadTooLarge) { t.Fatalf("Validate = %v, want %s", err, common.ErrorCodePayloadTooLarge) } } func TestValidateRejectsImageAboveDecodeBudget(t *testing.T) { // A 100-pixel image needs ~400 bytes of RGBA memory, more than this budget. validator := NewValidator(40_000_000, 100) file := writeTemp(t, "budget.png", encodePNG(t, 10, 10)) _, err := validator.Validate(context.Background(), file, "image/png") if !common.IsCode(err, common.ErrorCodePayloadTooLarge) { t.Fatalf("Validate = %v, want %s", err, common.ErrorCodePayloadTooLarge) } } func TestSafeDecodeConvertsPanicToError(t *testing.T) { // image.Decode does not panic on arbitrary bytes, so this only guards the // contract that safeDecode always returns an error instead of crashing. file := writeTemp(t, "junk", []byte{0x89, 'P', 'N', 'G', 0x0d, 0x0a, 0x1a, 0x0a, 0xff}) if _, err := safeDecode(file); err == nil { t.Fatal("safeDecode accepted junk bytes") } }