328 lines
10 KiB
Go
328 lines
10 KiB
Go
package album_test
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/binary"
|
|
"hash/crc32"
|
|
"image"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
|
|
"git.golem15.com/golem15/summercms/modules/album"
|
|
"git.golem15.com/golem15/summercms/modules/backpack"
|
|
"git.golem15.com/golem15/summercms/modules/compass"
|
|
"git.golem15.com/golem15/summercms/modules/lagoon/attach"
|
|
"git.golem15.com/golem15/summercms/modules/lagoon/attach/webp"
|
|
"gocloud.dev/blob/memblob"
|
|
)
|
|
|
|
func TestSlugAndShortID(t *testing.T) {
|
|
seen := make(map[string]struct{}, 64)
|
|
for i := 0; i < 64; i++ {
|
|
id, err := album.GenerateShortID()
|
|
if err != nil {
|
|
t.Fatalf("GenerateShortID: %v", err)
|
|
}
|
|
if len(id) != 12 {
|
|
t.Fatalf("short_id %q length = %d, want 12", id, len(id))
|
|
}
|
|
for _, r := range id {
|
|
if !((r >= '0' && r <= '9') || (r >= 'a' && r <= 'z')) {
|
|
t.Fatalf("short_id %q contains non-alphanumeric rune %q", id, r)
|
|
}
|
|
}
|
|
if _, dup := seen[id]; dup {
|
|
t.Fatalf("duplicate short_id %q", id)
|
|
}
|
|
seen[id] = struct{}{}
|
|
}
|
|
|
|
cases := []struct {
|
|
in string
|
|
want string
|
|
}{
|
|
{"Hero Banner 2026!.png", "hero-banner-2026-png"},
|
|
{" ", "file"},
|
|
{"---___...", "file"},
|
|
{"Zażółć gęślą jaźń", "za-gl-ja"},
|
|
{"alpha---beta___gamma", "alpha-beta-gamma"},
|
|
{strings.Repeat("a", 120), strings.Repeat("a", 80)},
|
|
}
|
|
for _, tc := range cases {
|
|
if got := album.SanitizeSlug(tc.in); got != tc.want {
|
|
t.Errorf("SanitizeSlug(%q) = %q, want %q", tc.in, got, tc.want)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestWebPVariants(t *testing.T) {
|
|
ctx := context.Background()
|
|
|
|
t.Run("large_image_generates_480_960_1600", func(t *testing.T) {
|
|
bucket := memblob.OpenBucket(nil)
|
|
defer bucket.Close()
|
|
|
|
img := makeTestPNG(t, 2000, 1000)
|
|
variants, keys, err := album.GenerateWebPVariants(ctx, nil, bucket, "abc123456789", "hero", img, "png")
|
|
if err != nil {
|
|
t.Fatalf("GenerateWebPVariants: %v", err)
|
|
}
|
|
wantDims := [][2]int{{480, 240}, {960, 480}, {1600, 800}}
|
|
if len(variants) != len(wantDims) || len(keys) != len(wantDims) {
|
|
t.Fatalf("got %d variants (%d keys), want %d", len(variants), len(keys), len(wantDims))
|
|
}
|
|
for i, want := range wantDims {
|
|
v := variants[i]
|
|
if v.Width != want[0] || v.Height != want[1] {
|
|
t.Errorf("variant[%d] = %dx%d, want %dx%d", i, v.Width, v.Height, want[0], want[1])
|
|
}
|
|
if v.ContentType != webp.ContentType {
|
|
t.Errorf("variant[%d] content_type = %q, want %q", i, v.ContentType, webp.ContentType)
|
|
}
|
|
if v.Size <= 0 {
|
|
t.Errorf("variant[%d] size = %d, want > 0", i, v.Size)
|
|
}
|
|
exists, err := bucket.Exists(ctx, keys[i])
|
|
if err != nil || !exists {
|
|
t.Errorf("variant blob %q missing (err=%v)", keys[i], err)
|
|
}
|
|
}
|
|
|
|
item := album.Item{
|
|
ShortID: "abc123456789",
|
|
BlobKey: "media/abc123456789/hero.png",
|
|
Variants: album.Variants(variants),
|
|
}
|
|
if got := len(item.AllBlobKeys()); got != 4 {
|
|
t.Fatalf("AllBlobKeys len = %d, want 4", got)
|
|
}
|
|
srcset := item.Srcset(nil)
|
|
for _, want := range []string{"480w", "960w", "1600w"} {
|
|
if !strings.Contains(srcset, want) {
|
|
t.Errorf("srcset %q missing %s", srcset, want)
|
|
}
|
|
}
|
|
})
|
|
|
|
t.Run("small_png_does_not_upscale", func(t *testing.T) {
|
|
bucket := memblob.OpenBucket(nil)
|
|
defer bucket.Close()
|
|
|
|
img := makeTestPNG(t, 300, 150)
|
|
variants, keys, err := album.GenerateWebPVariants(ctx, nil, bucket, "abc123456789", "thumb", img, "png")
|
|
if err != nil {
|
|
t.Fatalf("GenerateWebPVariants: %v", err)
|
|
}
|
|
if len(variants) != 1 || len(keys) != 1 {
|
|
t.Fatalf("got %d variants, want 1 original-width webp", len(variants))
|
|
}
|
|
if variants[0].Width != 300 || variants[0].Height != 150 {
|
|
t.Fatalf("variant = %dx%d, want 300x150 (no upscaling)", variants[0].Width, variants[0].Height)
|
|
}
|
|
})
|
|
|
|
t.Run("small_webp_generates_zero_redundant_variants", func(t *testing.T) {
|
|
bucket := memblob.OpenBucket(nil)
|
|
defer bucket.Close()
|
|
|
|
img := makeTestPNG(t, 300, 150)
|
|
variants, keys, err := album.GenerateWebPVariants(ctx, nil, bucket, "abc123456789", "icon", img, webp.Format)
|
|
if err != nil {
|
|
t.Fatalf("GenerateWebPVariants: %v", err)
|
|
}
|
|
if len(variants) != 0 || len(keys) != 0 {
|
|
t.Fatalf("small webp generated %d variants, want 0", len(variants))
|
|
}
|
|
})
|
|
}
|
|
|
|
func TestStaticHandlerSecurity(t *testing.T) {
|
|
ctx := context.Background()
|
|
bucket := memblob.OpenBucket(nil)
|
|
defer bucket.Close()
|
|
|
|
pngBytes := encodeTestPNG(t, makeTestPNG(t, 16, 16))
|
|
if err := bucket.WriteAll(ctx, "media/abc123456789/photo.png", pngBytes, attach.UploadWriterOptions("image/png")); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := bucket.WriteAll(ctx, "media/abc123456789/guide.pdf", []byte("%PDF-1.4\nhello"), attach.UploadWriterOptions("application/pdf")); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
h := album.StaticHandler(bucket, "/assets")
|
|
|
|
t.Run("head_returns_headers_without_body", func(t *testing.T) {
|
|
rec := httptest.NewRecorder()
|
|
h.ServeHTTP(rec, httptest.NewRequest(http.MethodHead, "/assets/abc123456789/photo.png", nil))
|
|
if rec.Code != http.StatusOK {
|
|
t.Fatalf("HEAD status = %d, want 200", rec.Code)
|
|
}
|
|
if rec.Body.Len() != 0 {
|
|
t.Fatalf("HEAD body len = %d, want 0", rec.Body.Len())
|
|
}
|
|
if got := rec.Header().Get("Cache-Control"); got != album.MediaCacheControl {
|
|
t.Fatalf("Cache-Control = %q, want %q", got, album.MediaCacheControl)
|
|
}
|
|
if got := rec.Header().Get("X-Content-Type-Options"); got != "nosniff" {
|
|
t.Fatalf("X-Content-Type-Options = %q", got)
|
|
}
|
|
if got := rec.Header().Get("Content-Security-Policy"); got != album.MediaContentSecurityPolicy {
|
|
t.Fatalf("CSP = %q", got)
|
|
}
|
|
})
|
|
|
|
t.Run("non_get_method_returns_405", func(t *testing.T) {
|
|
rec := httptest.NewRecorder()
|
|
h.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/assets/abc123456789/photo.png", nil))
|
|
if rec.Code != http.StatusMethodNotAllowed {
|
|
t.Fatalf("POST status = %d, want 405", rec.Code)
|
|
}
|
|
})
|
|
|
|
t.Run("pdf_serves_as_attachment", func(t *testing.T) {
|
|
rec := httptest.NewRecorder()
|
|
h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/assets/abc123456789/guide.pdf", nil))
|
|
if rec.Code != http.StatusOK {
|
|
t.Fatalf("GET pdf status = %d, want 200", rec.Code)
|
|
}
|
|
if got := rec.Header().Get("Content-Disposition"); got != "attachment" {
|
|
t.Fatalf("Content-Disposition = %q, want attachment", got)
|
|
}
|
|
})
|
|
|
|
t.Run("traversal_and_malformed_paths_rejected", func(t *testing.T) {
|
|
bad := []string{
|
|
"/assets",
|
|
"/assets/",
|
|
"/wrong/abc123456789/photo.png",
|
|
"/assets/abc123456789/../../etc/passwd",
|
|
"/assets/abc123456789/a\\b.png",
|
|
"/assets/abc123456789//photo.png",
|
|
"/assets/abc123456789/Photo.png",
|
|
}
|
|
for _, p := range bad {
|
|
rec := httptest.NewRecorder()
|
|
h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, p, nil))
|
|
if rec.Code != http.StatusNotFound {
|
|
t.Errorf("GET %q status = %d, want 404", p, rec.Code)
|
|
}
|
|
if rec.Header().Get("X-Content-Type-Options") != "nosniff" {
|
|
t.Errorf("GET %q missing nosniff", p)
|
|
}
|
|
}
|
|
})
|
|
}
|
|
|
|
func TestDecompressionBombAndPolyglotGuards(t *testing.T) {
|
|
// Construct a valid PNG header claiming 20000x20000 pixels (400M > MaxImagePixels).
|
|
bomb := makeSyntheticPNGHeader(20000, 20000)
|
|
if attach.IsAllowedImage(bomb) {
|
|
t.Fatal("IsAllowedImage accepted 20000x20000 decompression bomb PNG")
|
|
}
|
|
|
|
// HTML/SVG/JS bytes masquerading as .png must be rejected by IsAllowedImage.
|
|
polyglots := [][]byte{
|
|
[]byte(`<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>`),
|
|
[]byte(`<!doctype html><html><body><script>alert(1)</script></body></html>`),
|
|
[]byte(`console.log("not a png")`),
|
|
}
|
|
for i, payload := range polyglots {
|
|
if attach.IsAllowedImage(payload) {
|
|
t.Errorf("polyglot[%d] unexpectedly accepted by IsAllowedImage", i)
|
|
}
|
|
}
|
|
|
|
// Normal small PNG passes.
|
|
okPNG := encodeTestPNG(t, makeTestPNG(t, 32, 32))
|
|
if !attach.IsAllowedImage(okPNG) {
|
|
t.Fatal("valid 32x32 PNG rejected by IsAllowedImage")
|
|
}
|
|
var _ image.Image
|
|
}
|
|
|
|
func TestConfigAndInstallHelpers(t *testing.T) {
|
|
cfg, err := compass.Open(compass.Options{Dir: t.TempDir()})
|
|
if err != nil {
|
|
t.Fatalf("compass.Open: %v", err)
|
|
}
|
|
if got := album.MaxBytes(cfg); got != album.DefaultMaxBytes {
|
|
t.Fatalf("default MaxBytes = %d, want %d", got, album.DefaultMaxBytes)
|
|
}
|
|
if got := album.Base64MaxBytes(cfg); got != album.DefaultBase64MaxBytes {
|
|
t.Fatalf("default Base64MaxBytes = %d, want %d", got, album.DefaultBase64MaxBytes)
|
|
}
|
|
if got := album.PublicPathPrefix(cfg); got != album.DefaultPublicPathPrefix {
|
|
t.Fatalf("default PublicPathPrefix = %q, want %q", got, album.DefaultPublicPathPrefix)
|
|
}
|
|
if album.ServeEnabled(cfg) {
|
|
t.Fatal("ServeEnabled on empty config = true, want false")
|
|
}
|
|
|
|
_ = cfg.Set(album.ConfigMaxBytes, 10<<20)
|
|
_ = cfg.Set(album.ConfigBase64MaxBytes, 2<<20)
|
|
_ = cfg.Set(album.ConfigPublicPathPrefix, "/cdn-media/")
|
|
_ = cfg.Set("storage.uploads.serve", true)
|
|
if got := album.MaxBytes(cfg); got != 10<<20 {
|
|
t.Fatalf("MaxBytes = %d, want %d", got, 10<<20)
|
|
}
|
|
if got := album.Base64MaxBytes(cfg); got != 2<<20 {
|
|
t.Fatalf("Base64MaxBytes = %d, want %d", got, 2<<20)
|
|
}
|
|
if got := album.PublicPathPrefix(cfg); got != "/cdn-media" {
|
|
t.Fatalf("PublicPathPrefix = %q, want /cdn-media", got)
|
|
}
|
|
if !album.ServeEnabled(cfg) {
|
|
t.Fatal("ServeEnabled should inherit storage.uploads.serve=true")
|
|
}
|
|
_ = cfg.Set(album.ConfigServe, false)
|
|
if album.ServeEnabled(cfg) {
|
|
t.Fatal("explicit media.serve=false must override storage.uploads.serve=true")
|
|
}
|
|
|
|
app := backpack.New(cfg)
|
|
svc1, err := album.Install(app)
|
|
if err != nil {
|
|
t.Fatalf("Install: %v", err)
|
|
}
|
|
svc2, err := album.Install(app)
|
|
if err != nil {
|
|
t.Fatalf("Install idempotent: %v", err)
|
|
}
|
|
if svc1 != svc2 {
|
|
t.Fatal("Install returned distinct *Service instances on second call")
|
|
}
|
|
gotSvc, ok := album.ServiceFrom(app)
|
|
if !ok || gotSvc != svc1 {
|
|
t.Fatal("ServiceFrom did not return installed *Service")
|
|
}
|
|
}
|
|
|
|
// makeSyntheticPNGHeader builds a minimal PNG byte sequence whose IHDR chunk
|
|
// declares the given width and height (for testing decompression-bomb guards).
|
|
func makeSyntheticPNGHeader(width, height uint32) []byte {
|
|
var buf bytes.Buffer
|
|
// PNG signature
|
|
buf.Write([]byte{0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a})
|
|
// IHDR chunk: 13 bytes payload
|
|
var ihdr [13]byte
|
|
binary.BigEndian.PutUint32(ihdr[0:4], width)
|
|
binary.BigEndian.PutUint32(ihdr[4:8], height)
|
|
ihdr[8] = 8 // bit depth
|
|
ihdr[9] = 6 // RGBA
|
|
var lenBuf [4]byte
|
|
binary.BigEndian.PutUint32(lenBuf[:], 13)
|
|
buf.Write(lenBuf[:])
|
|
buf.WriteString("IHDR")
|
|
buf.Write(ihdr[:])
|
|
crc := crc32.NewIEEE()
|
|
_, _ = crc.Write([]byte("IHDR"))
|
|
_, _ = crc.Write(ihdr[:])
|
|
var crcBuf [4]byte
|
|
binary.BigEndian.PutUint32(crcBuf[:], crc.Sum32())
|
|
buf.Write(crcBuf[:])
|
|
return buf.Bytes()
|
|
}
|