Files
mtusi2026lab4-fork/student-tests/validation_test.go
T

122 lines
4.2 KiB
Go

//go:build studentvalidation
package main
import (
"bytes"
"context"
"encoding/binary"
"encoding/json"
"errors"
"hash/crc32"
"image"
"image/jpeg"
"image/png"
"net/http/httptest"
"os"
"strings"
"testing"
"github.com/minio/minio-go/v7"
)
func TestAttachmentFilename(t *testing.T) {
for _, name := range []string{"", " ", "../file.png", "a/b", "a\\b", "a\x00b", "a\nb", "a\x7fb", strings.Repeat("я", 256), string([]byte{255})} {
if validFilename(name) {
t.Fatalf("unsafe filename accepted: %q", name)
}
}
for _, name := range []string{"photo.png", "Фотография 😀.jpg", strings.Repeat("я", 255)} {
if !validFilename(name) {
t.Fatalf("valid display name rejected: %q", name)
}
}
}
func TestAttachmentMessageValidation(t *testing.T) {
id := "12345678-1234-4234-8234-123456789abc"
for _, raw := range []string{`{}`, `{"text":null}`, `{"text":" "}`, `{"text":"ok","attachment_ids":null}`, `{"text":"ok","attachment_ids":[null]}`, `{"text":"ok","attachment_ids":["invalid"]}`, `{"text":"","attachment_ids":["` + id + `","` + strings.ToUpper(id) + `"]}`} {
var body map[string]json.RawMessage
json.Unmarshal([]byte(raw), &body)
if _, _, err := messageFields(body); err == nil {
t.Fatalf("invalid message accepted: %s", raw)
}
}
for _, raw := range []string{`{"text":"ok"}`, `{"text":"ok","attachment_ids":[]}`, `{"text":"","attachment_ids":["` + id + `"]}`} {
var body map[string]json.RawMessage
json.Unmarshal([]byte(raw), &body)
_, ids, err := messageFields(body)
if err != nil || ids == nil {
t.Fatalf("valid message rejected or null IDs: %s", raw)
}
}
}
func TestUntrustedImagesRejectedBeforeStorage(t *testing.T) {
folder := t.TempDir()
t.Setenv("TMPDIR", folder)
t.Setenv("TMP", folder)
t.Setenv("TEMP", folder)
var encoded bytes.Buffer
png.Encode(&encoded, image.NewRGBA(image.Rect(0, 0, 20, 10)))
pngBytes := append([]byte(nil), encoded.Bytes()...)
encoded.Reset()
jpeg.Encode(&encoded, image.NewRGBA(image.Rect(0, 0, 20, 10)), nil)
jpegBytes := append([]byte(nil), encoded.Bytes()...)
// Correct IHDR CRC: a valid header proves the pixel guard runs before Decode.
huge := append([]byte(nil), pngBytes...)
binary.BigEndian.PutUint32(huge[16:20], 40000001)
binary.BigEndian.PutUint32(huge[20:24], 1)
binary.BigEndian.PutUint32(huge[29:33], crc32.ChecksumIEEE(huge[12:29]))
for _, tc := range []struct {
name, mime string
data []byte
length int64
status int
}{
{"empty", "image/png", nil, 0, 415},
{"invalid bytes", "image/png", []byte("fake"), 4, 415},
{"truncated PNG", "image/png", pngBytes[:40], 40, 415},
{"truncated JPEG", "image/jpeg", jpegBytes[:len(jpegBytes)/2], -1, 415},
{"spoof PNG", "image/jpeg", pngBytes, -1, 415},
{"spoof JPEG", "image/png", jpegBytes, -1, 415},
{"unsupported MIME", "text/plain", pngBytes, -1, 415},
{"large header", "image/png", pngBytes, maxUploadBytes + 1, 413},
{"chunked bytes limit", "image/png", bytes.Repeat([]byte("x"), int(maxUploadBytes+1)), -1, 413},
{"pixel guard", "image/png", huge, -1, 413},
} {
t.Run(tc.name, func(t *testing.T) {
app := App{uploadSlots: make(chan struct{}, 2), decodeSlot: make(chan struct{}, 1)}
request := httptest.NewRequest("POST", "/attachments?filename=image.png", bytes.NewReader(tc.data))
request.ContentLength = tc.length
request.Header.Set("Content-Type", tc.mime)
_, err := app.upload(context.Background(), httptest.NewRecorder(), request, "chat", "user")
var failure apiError
if !errors.As(err, &failure) || failure.status != tc.status {
t.Fatalf("expected %d; got %v", tc.status, err)
}
entries, e := os.ReadDir(folder)
if e != nil || len(entries) != 0 {
t.Fatal("temporary upload leaked")
}
})
}
}
func TestReconcilerDistinguishesStorageFaults(t *testing.T) {
for _, tc := range []struct {
err error
absent bool
}{
{nil, false}, {minio.ErrorResponse{Code: "NoSuchKey", StatusCode: 404}, true},
{minio.ErrorResponse{Code: "AccessDenied", StatusCode: 403}, false},
{minio.ErrorResponse{Code: "NoSuchBucket", StatusCode: 404}, false},
{minio.ErrorResponse{Code: "InternalError", StatusCode: 500}, false},
{context.DeadlineExceeded, false},
} {
if absentObject(tc.err) != tc.absent {
t.Fatalf("unsafe missing inference: %v", tc.err)
}
}
}