| 1 | package control |
| 2 | |
| 3 | import ( |
| 4 | "encoding/base64" |
| 5 | "errors" |
| 6 | "runtime" |
| 7 | "strings" |
| 8 | "testing" |
| 9 | ) |
| 10 | |
| 11 | func TestBase64DecodedCeilingBoundsEveryValidPayload(t *testing.T) { |
| 12 | for n := range 64 { |
| 13 | enc := base64.StdEncoding.EncodedLen(n) |
| 14 | if got := base64DecodedCeiling(enc); got < n-2 || got > n+2 { |
| 15 | t.Fatalf("n=%d encoded=%d ceiling=%d", n, enc, got) |
| 16 | } |
| 17 | } |
| 18 | } |
| 19 | |
| 20 | func TestOversizeDataURLIsRefusedBeforeDecoding(t *testing.T) { |
| 21 | dir := t.TempDir() |
| 22 | payload := strings.Repeat("A", base64.StdEncoding.EncodedLen(maxFileAttachmentBytes)+4096) |
| 23 | url := "data:application/octet-stream;base64," + payload |
| 24 | var before, after runtime.MemStats |
| 25 | runtime.GC() |
| 26 | runtime.ReadMemStats(&before) |
| 27 | _, err := SaveAttachmentDataURLInRoot(dir, "pack.mrpack", url) |
| 28 | runtime.ReadMemStats(&after) |
| 29 | if !errors.Is(err, ErrAttachmentTooLarge) { |
| 30 | t.Fatalf("err = %v, want ErrAttachmentTooLarge", err) |
| 31 | } |
| 32 | // A decode would allocate ~25 MB. |
| 33 | if grew := after.TotalAlloc - before.TotalAlloc; grew > 8<<20 { |
| 34 | t.Fatalf("refusal allocated %d bytes", grew) |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | func TestOversizeImageDataURLIsRefusedBeforeDecoding(t *testing.T) { |
| 39 | payload := strings.Repeat("A", base64.StdEncoding.EncodedLen(maxImageAttachmentBytes)+4096) |
| 40 | _, err := SaveImageDataURLInRoot(t.TempDir(), "data:image/png;base64,"+payload) |
| 41 | if !errors.Is(err, ErrImageTooLarge) { |
| 42 | t.Fatalf("err = %v, want ErrImageTooLarge", err) |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | func TestAttachmentAtTheLimitStillSaves(t *testing.T) { |
| 47 | raw := make([]byte, maxFileAttachmentBytes) |
| 48 | raw[0] = 'P' |
| 49 | url := "data:application/zip;base64," + base64.StdEncoding.EncodeToString(raw) |
| 50 | if _, err := SaveAttachmentDataURLInRoot(t.TempDir(), "edge.zip", url); err != nil { |
| 51 | t.Fatalf("limit-sized attachment refused: %v", err) |
| 52 | } |
| 53 | } |
| 54 |