forked from mtusi2026/mtusi2026lab5
66 lines
2.1 KiB
Go
66 lines
2.1 KiB
Go
package media
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/binary"
|
|
"errors"
|
|
"hash/crc32"
|
|
"image"
|
|
"image/png"
|
|
"testing"
|
|
|
|
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/service"
|
|
)
|
|
|
|
// imageBytes creates a valid independent synthetic PNG fixture.
|
|
func imageBytes(t *testing.T) []byte {
|
|
t.Helper()
|
|
var output bytes.Buffer
|
|
if err := png.Encode(&output, image.NewRGBA(image.Rect(0, 0, 3, 2))); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return output.Bytes()
|
|
}
|
|
|
|
// TestValidateImage checks file-level rejection independently of persistence.
|
|
func TestValidateImage(t *testing.T) {
|
|
valid := imageBytes(t)
|
|
cases := []struct {
|
|
name string
|
|
filename string
|
|
mime string
|
|
body []byte
|
|
want error
|
|
}{
|
|
{"valid", "test.png", "image/png", valid, nil},
|
|
{"traversal", "../test.png", "image/png", valid, service.ErrInvalid},
|
|
{"backslash", "a\\b", "image/png", valid, service.ErrInvalid},
|
|
{"control", "a\n", "image/png", valid, service.ErrInvalid},
|
|
{"empty name", "", "image/png", valid, service.ErrInvalid},
|
|
{"mime mismatch", "a.jpg", "image/jpeg", valid, service.ErrMedia},
|
|
{"unsupported", "a.png", "text/plain", valid, service.ErrMedia},
|
|
{"corrupt header", "a.png", "image/png", []byte("bad"), service.ErrMedia},
|
|
{"truncated payload", "a.png", "image/png", valid[:len(valid)-12], service.ErrMedia},
|
|
{"encoded limit", "a.png", "image/png", make([]byte, maxImageBytes+1), service.ErrTooLarge},
|
|
}
|
|
for _, tc := range cases {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
err := validateImage(tc.filename, tc.mime, tc.body)
|
|
if !errors.Is(err, tc.want) {
|
|
t.Fatalf("got %v want %v", err, tc.want)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestPixelLimitPrecedesDecode rejects a valid PNG header before allocating a huge pixel buffer.
|
|
func TestPixelLimitPrecedesDecode(t *testing.T) {
|
|
body := append([]byte{}, imageBytes(t)...)
|
|
binary.BigEndian.PutUint32(body[16:20], 10000)
|
|
binary.BigEndian.PutUint32(body[20:24], 10000)
|
|
binary.BigEndian.PutUint32(body[29:33], crc32.ChecksumIEEE(body[12:29]))
|
|
if err := validateImage("huge.png", "image/png", body); !errors.Is(err, service.ErrTooLarge) {
|
|
t.Fatalf("pixel limit: %v", err)
|
|
}
|
|
}
|