test(album,cabana,pier,surf,admin): add Phase 37 test suites and fail-closed check-phase37.sh gate
This commit is contained in:
610
modules/album/album_postgres_test.go
Normal file
610
modules/album/album_postgres_test.go
Normal file
@@ -0,0 +1,610 @@
|
||||
package album_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"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"
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon/attach"
|
||||
"github.com/go-gormigrate/gormigrate/v2"
|
||||
_ "github.com/jackc/pgx/v5/stdlib"
|
||||
"github.com/testcontainers/testcontainers-go"
|
||||
"github.com/testcontainers/testcontainers-go/modules/postgres"
|
||||
"gocloud.dev/blob"
|
||||
"gocloud.dev/blob/memblob"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
var (
|
||||
pgTestDSN string
|
||||
pgTestTerm func()
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
flag.Parse()
|
||||
if !testing.Short() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
|
||||
ctr, err := postgres.Run(ctx,
|
||||
"postgres:16-alpine",
|
||||
postgres.WithDatabase("album_test"),
|
||||
postgres.WithUsername("album"),
|
||||
postgres.WithPassword("album"),
|
||||
postgres.BasicWaitStrategies(),
|
||||
)
|
||||
cancel()
|
||||
if err == nil {
|
||||
dsnCtx, dsnCancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
dsn, dsnErr := ctr.ConnectionString(dsnCtx, "sslmode=disable")
|
||||
dsnCancel()
|
||||
if dsnErr == nil {
|
||||
pgTestDSN = dsn
|
||||
pgTestTerm = func() {
|
||||
_ = testcontainers.TerminateContainer(ctr)
|
||||
}
|
||||
} else {
|
||||
_ = testcontainers.TerminateContainer(ctr)
|
||||
}
|
||||
}
|
||||
}
|
||||
code := m.Run()
|
||||
if pgTestTerm != nil {
|
||||
pgTestTerm()
|
||||
}
|
||||
os.Exit(code)
|
||||
}
|
||||
|
||||
func openAlbumDB(t *testing.T) *gorm.DB {
|
||||
t.Helper()
|
||||
if testing.Short() {
|
||||
t.Skip("requires testcontainers postgres")
|
||||
}
|
||||
if pgTestDSN == "" {
|
||||
t.Fatal("postgres testcontainer did not start; ensure Docker is reachable")
|
||||
}
|
||||
ctx := context.Background()
|
||||
raw, err := sql.Open("pgx", pgTestDSN)
|
||||
if err != nil {
|
||||
t.Fatalf("sql.Open: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = raw.Close() })
|
||||
gdb, err := lagoon.Use(ctx, raw)
|
||||
if err != nil {
|
||||
t.Fatalf("lagoon.Use: %v", err)
|
||||
}
|
||||
if err := lagoon.Migrate(gdb, nil); err != nil {
|
||||
t.Fatalf("lagoon.Migrate: %v", err)
|
||||
}
|
||||
// Reset album and system_files tables between tests for isolation.
|
||||
if err := gdb.Exec(`TRUNCATE TABLE summer_media_upload_tokens, summer_media_items, summer_media_folders, system_files RESTART IDENTITY CASCADE`).Error; err != nil {
|
||||
t.Fatalf("truncate tables: %v", err)
|
||||
}
|
||||
return gdb
|
||||
}
|
||||
|
||||
func TestMigrationsUpDown(t *testing.T) {
|
||||
gdb := openAlbumDB(t)
|
||||
|
||||
// Run album migrations inside an isolated schema so rolling them down and
|
||||
// back up does not disturb the shared public tables.
|
||||
const schema = "album_mig_test"
|
||||
if err := gdb.Exec("DROP SCHEMA IF EXISTS " + schema + " CASCADE").Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := gdb.Exec("CREATE SCHEMA " + schema).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = gdb.Exec("DROP SCHEMA IF EXISTS " + schema + " CASCADE").Error })
|
||||
|
||||
tx := gdb.Begin()
|
||||
defer tx.Rollback()
|
||||
if err := tx.Exec("SET LOCAL search_path TO " + schema).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
opts := gormigrate.DefaultOptions
|
||||
opts.TableName = "album_mig_history"
|
||||
m := gormigrate.New(tx, opts, album.Migrations)
|
||||
if err := m.Migrate(); err != nil {
|
||||
t.Fatalf("Migrate up: %v", err)
|
||||
}
|
||||
for _, tbl := range []string{album.FoldersTable, album.ItemsTable, album.UploadTokensTable} {
|
||||
if !tx.Migrator().HasTable(tbl) {
|
||||
t.Fatalf("expected table %s after Migrate up", tbl)
|
||||
}
|
||||
}
|
||||
|
||||
// Roll back every migration down to the beginning.
|
||||
for range album.Migrations {
|
||||
if err := m.RollbackLast(); err != nil {
|
||||
t.Fatalf("RollbackLast: %v", err)
|
||||
}
|
||||
}
|
||||
for _, tbl := range []string{album.FoldersTable, album.ItemsTable, album.UploadTokensTable} {
|
||||
if tx.Migrator().HasTable(tbl) {
|
||||
t.Fatalf("expected table %s to be dropped after rollback", tbl)
|
||||
}
|
||||
}
|
||||
|
||||
// Re-apply cleanly.
|
||||
if err := m.Migrate(); err != nil {
|
||||
t.Fatalf("re-Migrate up: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFolderCRUDAndNonEmptyDelete(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
gdb := openAlbumDB(t)
|
||||
bucket := memblob.OpenBucket(nil)
|
||||
defer bucket.Close()
|
||||
svc := album.NewService(nil)
|
||||
|
||||
root, err := svc.CreateFolder(ctx, gdb, "Press Kit", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("CreateFolder root: %v", err)
|
||||
}
|
||||
if root.Slug != "press-kit" {
|
||||
t.Fatalf("root.Slug = %q, want press-kit", root.Slug)
|
||||
}
|
||||
|
||||
// EnsureFolder is idempotent.
|
||||
ensured, err := svc.EnsureFolder(ctx, gdb, "press-kit", "Press Kit", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("EnsureFolder: %v", err)
|
||||
}
|
||||
if ensured.ID != root.ID {
|
||||
t.Fatalf("EnsureFolder created duplicate id %d != %d", ensured.ID, root.ID)
|
||||
}
|
||||
|
||||
// Duplicate sibling slug fails unique index.
|
||||
if _, err := svc.CreateFolder(ctx, gdb, "Press Kit", nil); err == nil {
|
||||
t.Fatal("expected duplicate sibling folder error")
|
||||
}
|
||||
|
||||
child, err := svc.CreateFolder(ctx, gdb, "Logos", &root.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("CreateFolder child: %v", err)
|
||||
}
|
||||
|
||||
// Cycle prevention: root cannot become a child of its own descendant.
|
||||
if _, err := svc.UpdateFolder(ctx, gdb, root.ID, "", &child.ID, true); !errors.Is(err, album.ErrInvalidFolder) {
|
||||
t.Fatalf("cycle UpdateFolder err = %v, want ErrInvalidFolder", err)
|
||||
}
|
||||
|
||||
// Deleting a folder with a child folder returns ErrFolderNotEmpty.
|
||||
if err := svc.DeleteFolder(ctx, gdb, root.ID); !errors.Is(err, album.ErrFolderNotEmpty) {
|
||||
t.Fatalf("DeleteFolder with child err = %v, want ErrFolderNotEmpty", err)
|
||||
}
|
||||
|
||||
// Upload an item into child folder -> deleting child returns ErrFolderNotEmpty.
|
||||
item, err := svc.Upload(ctx, gdb, bucket, album.UploadInput{
|
||||
FileName: "logo.png",
|
||||
Body: bytes.NewReader(encodeTestPNG(t, makeTestPNG(t, 100, 100))),
|
||||
FolderID: &child.ID,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Upload into child: %v", err)
|
||||
}
|
||||
if err := svc.DeleteFolder(ctx, gdb, child.ID); !errors.Is(err, album.ErrFolderNotEmpty) {
|
||||
t.Fatalf("DeleteFolder with item err = %v, want ErrFolderNotEmpty", err)
|
||||
}
|
||||
|
||||
// Move item to root, delete child, then delete root.
|
||||
if _, err := svc.UpdateItem(ctx, gdb, item.ID, album.UpdatePatch{ClearFolder: true}); err != nil {
|
||||
t.Fatalf("UpdateItem ClearFolder: %v", err)
|
||||
}
|
||||
if err := svc.DeleteFolder(ctx, gdb, child.ID); err != nil {
|
||||
t.Fatalf("DeleteFolder empty child: %v", err)
|
||||
}
|
||||
if err := svc.DeleteFolder(ctx, gdb, root.ID); err != nil {
|
||||
t.Fatalf("DeleteFolder empty root: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUploadAndNoDedup(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
gdb := openAlbumDB(t)
|
||||
bucket := memblob.OpenBucket(nil)
|
||||
defer bucket.Close()
|
||||
svc := album.NewService(nil)
|
||||
|
||||
pngBytes := encodeTestPNG(t, makeTestPNG(t, 1200, 600))
|
||||
sum := sha256.Sum256(pngBytes)
|
||||
wantSHA := hex.EncodeToString(sum[:])
|
||||
|
||||
first, err := svc.Upload(ctx, gdb, bucket, album.UploadInput{
|
||||
FileName: "Hero Photo.PNG",
|
||||
Body: bytes.NewReader(pngBytes),
|
||||
Alt: "Hero",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Upload first: %v", err)
|
||||
}
|
||||
if first.SHA256 != wantSHA {
|
||||
t.Fatalf("first.SHA256 = %q, want %q", first.SHA256, wantSHA)
|
||||
}
|
||||
if first.Width == nil || *first.Width != 1200 || first.Height == nil || *first.Height != 600 {
|
||||
t.Fatalf("dimensions = %v x %v, want 1200x600", first.Width, first.Height)
|
||||
}
|
||||
if len(first.Variants) != 2 {
|
||||
t.Fatalf("variants = %d, want 2 (480w, 960w)", len(first.Variants))
|
||||
}
|
||||
|
||||
// Uploading identical bytes again must NOT deduplicate: distinct row & blob key.
|
||||
second, err := svc.Upload(ctx, gdb, bucket, album.UploadInput{
|
||||
FileName: "Hero Photo.PNG",
|
||||
Body: bytes.NewReader(pngBytes),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Upload second: %v", err)
|
||||
}
|
||||
if second.ID == first.ID || second.ShortID == first.ShortID || second.BlobKey == first.BlobKey {
|
||||
t.Fatalf("duplicate upload was deduplicated: first=%+v second=%+v", first, second)
|
||||
}
|
||||
if second.SHA256 != wantSHA {
|
||||
t.Fatalf("second.SHA256 = %q, want %q", second.SHA256, wantSHA)
|
||||
}
|
||||
|
||||
// Non-image PDF upload stores Content-Disposition: attachment and zero variants.
|
||||
pdf, err := svc.Upload(ctx, gdb, bucket, album.UploadInput{
|
||||
FileName: "manual.pdf",
|
||||
Body: bytes.NewReader([]byte("%PDF-1.4\nhello world")),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Upload pdf: %v", err)
|
||||
}
|
||||
if len(pdf.Variants) != 0 {
|
||||
t.Fatalf("pdf variants = %d, want 0", len(pdf.Variants))
|
||||
}
|
||||
attrs, err := bucket.Attributes(ctx, pdf.BlobKey)
|
||||
if err != nil {
|
||||
t.Fatalf("bucket.Attributes(pdf): %v", err)
|
||||
}
|
||||
if attrs.ContentDisposition != "attachment" {
|
||||
t.Fatalf("pdf ContentDisposition = %q, want attachment", attrs.ContentDisposition)
|
||||
}
|
||||
|
||||
// Disallowed types (SVG, HTML, JS) and fake PNG rejected with no DB row.
|
||||
badInputs := []album.UploadInput{
|
||||
{FileName: "vector.svg", Body: strings.NewReader(`<svg xmlns="http://www.w3.org/2000/svg"></svg>`)},
|
||||
{FileName: "page.html", Body: strings.NewReader(`<html><body>hi</body></html>`)},
|
||||
{FileName: "app.js", Body: strings.NewReader(`alert(1)`)},
|
||||
{FileName: "fake.png", Body: strings.NewReader(`<html>not a png</html>`)},
|
||||
}
|
||||
for _, in := range badInputs {
|
||||
if _, err := svc.Upload(ctx, gdb, bucket, in); err == nil {
|
||||
t.Errorf("Upload(%q) unexpectedly succeeded", in.FileName)
|
||||
}
|
||||
}
|
||||
|
||||
// Oversized upload returns ErrTooLarge.
|
||||
if _, err := svc.Upload(ctx, gdb, bucket, album.UploadInput{
|
||||
FileName: "big.pdf",
|
||||
Body: bytes.NewReader(append([]byte("%PDF-1.4\n"), bytes.Repeat([]byte("x"), 2048)...)),
|
||||
MaxBytes: 512,
|
||||
}); !errors.Is(err, album.ErrTooLarge) {
|
||||
t.Fatalf("oversized Upload err = %v, want ErrTooLarge", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConsumeUploadTokenSingleUse(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
gdb := openAlbumDB(t)
|
||||
bucket := memblob.OpenBucket(nil)
|
||||
defer bucket.Close()
|
||||
|
||||
cfg, err := compass.Open(compass.Options{Dir: t.TempDir()})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
app := backpack.New(cfg)
|
||||
sqlDB, err := gdb.DB()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := lagoon.Publish(app, sqlDB, gdb); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := app.Publish[*blob.Bucket](bucket); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
svc, err := album.Install(app)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// 1. PrepareUpload stores only SHA-256 hash, never plaintext token.
|
||||
prep, err := svc.PrepareUpload(ctx, gdb, album.PrepareUploadInput{
|
||||
CreatedBy: 7,
|
||||
ExpectedFilename: "signed-photo.png",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("PrepareUpload: %v", err)
|
||||
}
|
||||
var stored album.UploadToken
|
||||
if err := gdb.First(&stored, prep.TokenID).Error; err != nil {
|
||||
t.Fatalf("load upload token row: %v", err)
|
||||
}
|
||||
if stored.TokenHash == prep.Token || len(stored.TokenHash) != 64 {
|
||||
t.Fatalf("stored TokenHash = %q, want 64-char sha256 hash distinct from plaintext", stored.TokenHash)
|
||||
}
|
||||
|
||||
// 2. Concurrent consumption allows exactly one winner.
|
||||
const workers = 6
|
||||
var wg sync.WaitGroup
|
||||
var wins int
|
||||
var mu sync.Mutex
|
||||
wg.Add(workers)
|
||||
for i := 0; i < workers; i++ {
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
if _, cErr := svc.ConsumeUploadToken(ctx, gdb, prep.Token); cErr == nil {
|
||||
mu.Lock()
|
||||
wins++
|
||||
mu.Unlock()
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
if wins != 1 {
|
||||
t.Fatalf("concurrent ConsumeUploadToken wins = %d, want 1", wins)
|
||||
}
|
||||
|
||||
// 3. Replay returns ErrInvalidUploadToken.
|
||||
if _, err := svc.ConsumeUploadToken(ctx, gdb, prep.Token); !errors.Is(err, album.ErrInvalidUploadToken) {
|
||||
t.Fatalf("replay ConsumeUploadToken err = %v, want ErrInvalidUploadToken", err)
|
||||
}
|
||||
|
||||
// 4. Expired token returns ErrInvalidUploadToken.
|
||||
expired, err := svc.PrepareUpload(ctx, gdb, album.PrepareUploadInput{
|
||||
CreatedBy: 7,
|
||||
ExpectedFilename: "expired.png",
|
||||
TTL: time.Minute,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := gdb.Model(&album.UploadToken{}).Where("id = ?", expired.TokenID).
|
||||
Update("expires_at", time.Now().UTC().Add(-time.Minute)).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := svc.ConsumeUploadToken(ctx, gdb, expired.Token); !errors.Is(err, album.ErrInvalidUploadToken) {
|
||||
t.Fatalf("expired ConsumeUploadToken err = %v, want ErrInvalidUploadToken", err)
|
||||
}
|
||||
|
||||
// 5. SignedUploadHandler end-to-end PUT succeeds once and rejects replay with 401.
|
||||
prep2, err := svc.PrepareUpload(ctx, gdb, album.PrepareUploadInput{
|
||||
CreatedBy: 7,
|
||||
ExpectedFilename: "put-banner.png",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mux := http.NewServeMux()
|
||||
mux.Handle("PUT /media/upload/{token}", album.SignedUploadHandler(app, svc))
|
||||
|
||||
pngBytes := encodeTestPNG(t, makeTestPNG(t, 600, 300))
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodPut, "/media/upload/"+prep2.Token+"?alt=Banner", bytes.NewReader(pngBytes))
|
||||
mux.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusCreated {
|
||||
t.Fatalf("PUT signed upload status = %d, want 201, body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var resp struct {
|
||||
Data album.ItemResponse `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("decode response: %v", err)
|
||||
}
|
||||
if resp.Data.ID == 0 || resp.Data.Alt != "Banner" || len(resp.Data.Variants) != 1 {
|
||||
t.Fatalf("unexpected ItemResponse: %+v", resp.Data)
|
||||
}
|
||||
|
||||
// Replay PUT returns 401.
|
||||
rec2 := httptest.NewRecorder()
|
||||
mux.ServeHTTP(rec2, httptest.NewRequest(http.MethodPut, "/media/upload/"+prep2.Token, bytes.NewReader(pngBytes)))
|
||||
if rec2.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("replay PUT status = %d, want 401", rec2.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteItemInTxAfterCommit(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
gdb := openAlbumDB(t)
|
||||
bucket := memblob.OpenBucket(nil)
|
||||
defer bucket.Close()
|
||||
svc := album.NewService(nil)
|
||||
|
||||
item, err := svc.Upload(ctx, gdb, bucket, album.UploadInput{
|
||||
FileName: "sunset.png",
|
||||
Body: bytes.NewReader(encodeTestPNG(t, makeTestPNG(t, 1000, 500))),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Upload: %v", err)
|
||||
}
|
||||
allKeys := item.AllBlobKeys()
|
||||
if len(allKeys) != 3 { // original + 480w + 960w
|
||||
t.Fatalf("AllBlobKeys = %v, want 3 keys", allKeys)
|
||||
}
|
||||
|
||||
// Rolled-back transaction must NOT delete blobs or DB row.
|
||||
sentinel := errors.New("abort tx")
|
||||
err = lagoon.Transaction(ctx, gdb, func(txCtx context.Context, tx *gorm.DB) error {
|
||||
keys, txErr := svc.DeleteItemInTx(txCtx, tx, item.ID)
|
||||
if txErr != nil {
|
||||
return txErr
|
||||
}
|
||||
lagoon.AfterCommit(txCtx, tx, func(acCtx context.Context, _ *gorm.DB) {
|
||||
_ = album.DeleteBlobs(context.WithoutCancel(acCtx), bucket, keys)
|
||||
})
|
||||
return sentinel
|
||||
})
|
||||
if !errors.Is(err, sentinel) {
|
||||
t.Fatalf("rolled-back Transaction err = %v, want sentinel", err)
|
||||
}
|
||||
if _, err := svc.GetItem(ctx, gdb, item.ID); err != nil {
|
||||
t.Fatalf("item missing after rollback: %v", err)
|
||||
}
|
||||
for _, k := range allKeys {
|
||||
exists, bErr := bucket.Exists(ctx, k)
|
||||
if bErr != nil || !exists {
|
||||
t.Fatalf("blob %q was deleted on rollback (err=%v)", k, bErr)
|
||||
}
|
||||
}
|
||||
|
||||
// Committed transaction deletes DB row + original + all WebP variant blobs.
|
||||
err = lagoon.Transaction(ctx, gdb, func(txCtx context.Context, tx *gorm.DB) error {
|
||||
keys, txErr := svc.DeleteItemInTx(txCtx, tx, item.ID)
|
||||
if txErr != nil {
|
||||
return txErr
|
||||
}
|
||||
lagoon.AfterCommit(txCtx, tx, func(acCtx context.Context, _ *gorm.DB) {
|
||||
_ = album.DeleteBlobs(context.WithoutCancel(acCtx), bucket, keys)
|
||||
})
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("committed Transaction: %v", err)
|
||||
}
|
||||
if _, err := svc.GetItem(ctx, gdb, item.ID); !errors.Is(err, album.ErrNotFound) {
|
||||
t.Fatalf("GetItem after commit err = %v, want ErrNotFound", err)
|
||||
}
|
||||
for _, k := range allKeys {
|
||||
exists, bErr := bucket.Exists(ctx, k)
|
||||
if bErr != nil {
|
||||
t.Fatalf("bucket.Exists(%q): %v", k, bErr)
|
||||
}
|
||||
if exists {
|
||||
t.Fatalf("blob %q still exists after committed delete", k)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetItemsByShortIDsAndListFilters(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
gdb := openAlbumDB(t)
|
||||
bucket := memblob.OpenBucket(nil)
|
||||
defer bucket.Close()
|
||||
svc := album.NewService(nil)
|
||||
|
||||
folder, err := svc.CreateFolder(ctx, gdb, "Journal", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
imgItem, err := svc.Upload(ctx, gdb, bucket, album.UploadInput{
|
||||
FileName: "cover.png",
|
||||
Body: bytes.NewReader(encodeTestPNG(t, makeTestPNG(t, 600, 400))),
|
||||
FolderID: &folder.ID,
|
||||
Title: "Cover Art",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pdfItem, err := svc.Upload(ctx, gdb, bucket, album.UploadInput{
|
||||
FileName: "report.pdf",
|
||||
Body: bytes.NewReader([]byte("%PDF-1.4\ncontent")),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
byID, err := svc.GetItemsByShortIDs(ctx, gdb, []string{imgItem.ShortID, pdfItem.ShortID, imgItem.ShortID, "nonexistent1"})
|
||||
if err != nil {
|
||||
t.Fatalf("GetItemsByShortIDs: %v", err)
|
||||
}
|
||||
if len(byID) != 2 || byID[imgItem.ShortID].ID != imgItem.ID || byID[pdfItem.ShortID].ID != pdfItem.ID {
|
||||
t.Fatalf("unexpected GetItemsByShortIDs result: %+v", byID)
|
||||
}
|
||||
|
||||
imgs, total, err := svc.ListItems(ctx, gdb, album.ListFilter{Type: "image"})
|
||||
if err != nil || total != 1 || len(imgs) != 1 || imgs[0].ID != imgItem.ID {
|
||||
t.Fatalf("ListItems(type=image) = %d/%d err=%v", len(imgs), total, err)
|
||||
}
|
||||
files, total, err := svc.ListItems(ctx, gdb, album.ListFilter{Type: "file", RootOnly: true})
|
||||
if err != nil || total != 1 || len(files) != 1 || files[0].ID != pdfItem.ID {
|
||||
t.Fatalf("ListItems(type=file,root) = %d/%d err=%v", len(files), total, err)
|
||||
}
|
||||
bySHA, total, err := svc.ListItems(ctx, gdb, album.ListFilter{SHA256: imgItem.SHA256})
|
||||
if err != nil || total != 1 || len(bySHA) != 1 || bySHA[0].ID != imgItem.ID {
|
||||
t.Fatalf("ListItems(sha256) = %d/%d err=%v", len(bySHA), total, err)
|
||||
}
|
||||
|
||||
// Updating metadata & folder never changes short_id, blob_key, or public URL.
|
||||
origURL := imgItem.PublicURL(nil)
|
||||
newAlt := "Updated alt"
|
||||
updated, err := svc.UpdateItem(ctx, gdb, imgItem.ID, album.UpdatePatch{Alt: &newAlt, ClearFolder: true})
|
||||
if err != nil {
|
||||
t.Fatalf("UpdateItem: %v", err)
|
||||
}
|
||||
if updated.ShortID != imgItem.ShortID || updated.BlobKey != imgItem.BlobKey || updated.PublicURL(nil) != origURL {
|
||||
t.Fatalf("UpdateItem mutated immutable URL/key: before=%q after=%q", origURL, updated.PublicURL(nil))
|
||||
}
|
||||
if updated.Alt != newAlt || updated.FolderID != nil {
|
||||
t.Fatalf("UpdateItem did not apply patch: %+v", updated)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBackfillMailImages(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
gdb := openAlbumDB(t)
|
||||
|
||||
title := "Brand Logo"
|
||||
isPublic := true
|
||||
legacy := attach.File{
|
||||
DiskName: "abc123def456.png",
|
||||
FileName: "brand-logo.png",
|
||||
FileSize: 1024,
|
||||
ContentType: "image/png",
|
||||
Title: &title,
|
||||
Field: "images",
|
||||
AttachmentType: album.MailImageLibraryMorph,
|
||||
IsPublic: &isPublic,
|
||||
}
|
||||
if err := gdb.Create(&legacy).Error; err != nil {
|
||||
t.Fatalf("seed legacy mail image: %v", err)
|
||||
}
|
||||
|
||||
n1, err := album.BackfillMailImages(ctx, gdb, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("BackfillMailImages first run: %v", err)
|
||||
}
|
||||
if n1 != 1 {
|
||||
t.Fatalf("BackfillMailImages first run = %d, want 1", n1)
|
||||
}
|
||||
|
||||
// Second run is completely idempotent.
|
||||
n2, err := album.BackfillMailImages(ctx, gdb, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("BackfillMailImages second run: %v", err)
|
||||
}
|
||||
if n2 != 0 {
|
||||
t.Fatalf("BackfillMailImages second run = %d, want 0", n2)
|
||||
}
|
||||
|
||||
var item album.Item
|
||||
if err := gdb.Where("legacy_file_id = ?", legacy.ID).First(&item).Error; err != nil {
|
||||
t.Fatalf("load backfilled item: %v", err)
|
||||
}
|
||||
wantLegacyURL := attach.PublicURL(attach.BlobKey(legacy.DiskName))
|
||||
if item.LegacyURL != wantLegacyURL || item.PublicURL(nil) != wantLegacyURL {
|
||||
t.Fatalf("backfilled URL = %q / %q, want %q", item.LegacyURL, item.PublicURL(nil), wantLegacyURL)
|
||||
}
|
||||
if item.FolderID == nil {
|
||||
t.Fatal("expected backfilled item to belong to virtual 'mail' folder")
|
||||
}
|
||||
}
|
||||
327
modules/album/album_test.go
Normal file
327
modules/album/album_test.go
Normal file
@@ -0,0 +1,327 @@
|
||||
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()
|
||||
}
|
||||
278
modules/cabana/media_postgres_test.go
Normal file
278
modules/cabana/media_postgres_test.go
Normal file
@@ -0,0 +1,278 @@
|
||||
package cabana_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/png"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/album"
|
||||
"git.golem15.com/golem15/summercms/modules/cabana"
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon/attach"
|
||||
"gocloud.dev/blob"
|
||||
)
|
||||
|
||||
func mediaTestPNG(t *testing.T, w, h int) []byte {
|
||||
t.Helper()
|
||||
img := image.NewRGBA(image.Rect(0, 0, w, h))
|
||||
for y := 0; y < h; y++ {
|
||||
for x := 0; x < w; x++ {
|
||||
img.Set(x, y, color.RGBA{R: 120, G: 180, B: 220, A: 255})
|
||||
}
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
if err := png.Encode(&buf, img); err != nil {
|
||||
t.Fatalf("encode png: %v", err)
|
||||
}
|
||||
return buf.Bytes()
|
||||
}
|
||||
|
||||
func mediaMultipartUpload(t *testing.T, h http.Handler, token string, data []byte, filename string, fields map[string]string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
var buf bytes.Buffer
|
||||
mw := multipart.NewWriter(&buf)
|
||||
fw, err := mw.CreateFormFile("file", filename)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := fw.Write(data); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for k, v := range fields {
|
||||
if err := mw.WriteField(k, v); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := mw.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req := httptest.NewRequest(http.MethodPost, "/backend/api/v1/media/items", &buf)
|
||||
req.Header.Set("Content-Type", mw.FormDataContentType())
|
||||
if token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
|
||||
func mintPersonalToken(t *testing.T, env *mailEnv, jwtToken, name string, scopes []string) string {
|
||||
t.Helper()
|
||||
body := env.expect(t, http.StatusCreated, http.MethodPost, "/account/tokens", jwtToken, map[string]any{
|
||||
"name": name,
|
||||
"scopes": scopes,
|
||||
})
|
||||
tok, _ := dataOf(body)["token"].(string)
|
||||
if tok == "" {
|
||||
t.Fatalf("expected plaintext token in response: %v", body)
|
||||
}
|
||||
return tok
|
||||
}
|
||||
|
||||
func TestMediaPermissionsMatrix(t *testing.T) {
|
||||
env := newMailScreensEnv(t, nil)
|
||||
if err := env.gdb.Exec(`TRUNCATE TABLE summer_media_upload_tokens, summer_media_items, summer_media_folders RESTART IDENTITY CASCADE`).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
_, viewerTok := env.admin(t, "media-viewer", false, `{"media.view_media":1}`)
|
||||
_, managerTok := env.admin(t, "media-manager", false, `{"media.manage_media":1}`)
|
||||
_, superTok := env.admin(t, "media-super", true, "")
|
||||
_, noneTok := env.admin(t, "media-none", false, `{"acme.demo.access":1}`)
|
||||
|
||||
// Create a folder as manager so GET/PUT/DELETE have a target.
|
||||
created := env.expect(t, http.StatusCreated, http.MethodPost, "/media/folders", managerTok, map[string]any{"name": "Campaigns"})
|
||||
folderID := uint(dataOf(created)["id"].(float64))
|
||||
|
||||
// Viewer can read, cannot write.
|
||||
env.expect(t, http.StatusOK, http.MethodGet, "/media/folders", viewerTok, nil)
|
||||
env.expect(t, http.StatusOK, http.MethodGet, "/media/items", viewerTok, nil)
|
||||
env.expect(t, http.StatusForbidden, http.MethodPost, "/media/folders", viewerTok, map[string]any{"name": "Blocked"})
|
||||
env.expect(t, http.StatusForbidden, http.MethodPut, fmt.Sprintf("/media/folders/%d", folderID), viewerTok, map[string]any{"name": "Blocked"})
|
||||
env.expect(t, http.StatusForbidden, http.MethodDelete, fmt.Sprintf("/media/folders/%d", folderID), viewerTok, nil)
|
||||
env.expect(t, http.StatusForbidden, http.MethodPost, "/media/uploads/prepare", viewerTok, map[string]any{"filename": "x.png"})
|
||||
if rec := mediaMultipartUpload(t, env.h, viewerTok, tinyPNG(), "v.png", nil); rec.Code != http.StatusForbidden {
|
||||
t.Fatalf("viewer upload status = %d, want 403", rec.Code)
|
||||
}
|
||||
|
||||
// None principal is denied read & write.
|
||||
env.expect(t, http.StatusForbidden, http.MethodGet, "/media/folders", noneTok, nil)
|
||||
env.expect(t, http.StatusForbidden, http.MethodGet, "/media/items", noneTok, nil)
|
||||
|
||||
// Manager and superuser can read and write.
|
||||
env.expect(t, http.StatusOK, http.MethodGet, "/media/items", managerTok, nil)
|
||||
env.expect(t, http.StatusOK, http.MethodGet, "/media/items", superTok, nil)
|
||||
|
||||
// Verify media permissions have no default role grants.
|
||||
var granted int64
|
||||
if err := env.gdb.Raw(`SELECT COUNT(*) FROM backend_user_roles WHERE permissions LIKE '%media.%' AND code NOT LIKE 'code-%'`).Scan(&granted).Error; err != nil || granted != 0 {
|
||||
t.Fatalf("default roles granted media permissions: %d err=%v", granted, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMediaTokenScopes(t *testing.T) {
|
||||
env := newMailScreensEnv(t, nil)
|
||||
if err := env.gdb.Exec(`TRUNCATE TABLE summer_media_upload_tokens, summer_media_items, summer_media_folders RESTART IDENTITY CASCADE`).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
_, superTok := env.admin(t, "media-scope-super", true, "")
|
||||
readToken := mintPersonalToken(t, env, superTok, "media-read-tok", []string{"media:read"})
|
||||
writeToken := mintPersonalToken(t, env, superTok, "media-write-tok", []string{"media"})
|
||||
|
||||
// media:read allows GET, blocks POST/PUT/DELETE.
|
||||
env.expect(t, http.StatusOK, http.MethodGet, "/media/folders", readToken, nil)
|
||||
env.expect(t, http.StatusOK, http.MethodGet, "/media/items", readToken, nil)
|
||||
env.expect(t, http.StatusForbidden, http.MethodPost, "/media/folders", readToken, map[string]any{"name": "Denied"})
|
||||
env.expect(t, http.StatusForbidden, http.MethodPost, "/media/uploads/prepare", readToken, map[string]any{"filename": "x.png"})
|
||||
|
||||
// media scope allows GET, POST, PUT, DELETE.
|
||||
folder := env.expect(t, http.StatusCreated, http.MethodPost, "/media/folders", writeToken, map[string]any{"name": "Scoped"})
|
||||
fid := uint(dataOf(folder)["id"].(float64))
|
||||
env.expect(t, http.StatusOK, http.MethodPut, fmt.Sprintf("/media/folders/%d", fid), writeToken, map[string]any{"name": "Scoped Renamed"})
|
||||
env.expect(t, http.StatusOK, http.MethodDelete, fmt.Sprintf("/media/folders/%d", fid), writeToken, nil)
|
||||
}
|
||||
|
||||
func TestMediaUploadLifecycleAndAfterCommitDelete(t *testing.T) {
|
||||
env := newMailScreensEnv(t, nil)
|
||||
if err := env.gdb.Exec(`TRUNCATE TABLE summer_media_upload_tokens, summer_media_items, summer_media_folders RESTART IDENTITY CASCADE`).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
_, managerTok := env.admin(t, "media-life-mgr", false, `{"media.manage_media":1}`)
|
||||
bucket, ok := env.app.Lookup[*blob.Bucket]()
|
||||
if !ok || bucket == nil {
|
||||
t.Fatal("expected *blob.Bucket on app")
|
||||
}
|
||||
|
||||
// 1. Create folder and upload a 1000x500 PNG via multipart.
|
||||
folder := env.expect(t, http.StatusCreated, http.MethodPost, "/media/folders", managerTok, map[string]any{"name": "Heroes"})
|
||||
fid := uint(dataOf(folder)["id"].(float64))
|
||||
|
||||
rec := mediaMultipartUpload(t, env.h, managerTok, mediaTestPNG(t, 1000, 500), "Hero Banner.png", map[string]string{
|
||||
"folder_id": fmt.Sprintf("%d", fid),
|
||||
"alt": "Initial alt",
|
||||
})
|
||||
if rec.Code != http.StatusCreated {
|
||||
t.Fatalf("multipart upload status = %d, want 201, body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var upResp struct {
|
||||
Data cabana.AdminMediaItem `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &upResp); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
item := upResp.Data
|
||||
if item.ID == 0 || len(item.Variants) != 2 || !strings.Contains(item.Srcset, "480w") || !strings.Contains(item.Srcset, "960w") {
|
||||
t.Fatalf("unexpected uploaded item: %+v", item)
|
||||
}
|
||||
|
||||
// 2. Non-empty folder delete returns 409 Conflict.
|
||||
env.expect(t, http.StatusConflict, http.MethodDelete, fmt.Sprintf("/media/folders/%d", fid), managerTok, nil)
|
||||
|
||||
// 3. Metadata update keeps URL immutable.
|
||||
updated := env.expect(t, http.StatusOK, http.MethodPut, fmt.Sprintf("/media/items/%d", item.ID), managerTok, map[string]any{
|
||||
"alt": "Updated alt",
|
||||
"title": "Hero",
|
||||
"clear_folder": true,
|
||||
})
|
||||
if dataOf(updated)["url"] != item.URL {
|
||||
t.Fatalf("URL changed on update: before=%q after=%v", item.URL, dataOf(updated)["url"])
|
||||
}
|
||||
|
||||
// 4. Base64 upload succeeds within 5 MB cap and rejects >5 MB with 413.
|
||||
b64Small := base64.StdEncoding.EncodeToString(tinyPNG())
|
||||
env.expect(t, http.StatusCreated, http.MethodPost, "/media/items/base64", managerTok, map[string]any{
|
||||
"filename": "pixel.png",
|
||||
"content_base64": b64Small,
|
||||
})
|
||||
// >5 MiB decoded payload -> 413 Payload Too Large.
|
||||
bigDecoded := bytes.Repeat([]byte("a"), int(album.DefaultBase64MaxBytes)+1024)
|
||||
b64TooBig := base64.StdEncoding.EncodeToString(bigDecoded)
|
||||
env.expect(t, http.StatusRequestEntityTooLarge, http.MethodPost, "/media/items/base64", managerTok, map[string]any{
|
||||
"filename": "huge.pdf",
|
||||
"content_base64": b64TooBig,
|
||||
})
|
||||
|
||||
// 5. Delete item removes DB row and original + WebP variant blobs via AfterCommit.
|
||||
var stored album.Item
|
||||
if err := env.gdb.First(&stored, item.ID).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
keysBeforeDelete := stored.AllBlobKeys()
|
||||
env.expect(t, http.StatusOK, http.MethodDelete, fmt.Sprintf("/media/items/%d", item.ID), managerTok, nil)
|
||||
for _, k := range keysBeforeDelete {
|
||||
exists, err := bucket.Exists(context.Background(), k)
|
||||
if err != nil {
|
||||
t.Fatalf("bucket.Exists(%q): %v", k, err)
|
||||
}
|
||||
if exists {
|
||||
t.Fatalf("blob %q still exists after DELETE /media/items/%d", k, item.ID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMailImagesUnifiedOverAlbum(t *testing.T) {
|
||||
env := newMailScreensEnv(t, nil)
|
||||
if err := env.gdb.Exec(`TRUNCATE TABLE summer_media_upload_tokens, summer_media_items, summer_media_folders, system_files RESTART IDENTITY CASCADE`).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, layoutsTok := env.admin(t, "mail-album-lay", false, `{"system.manage_mail_layouts":1}`)
|
||||
|
||||
// Seed a legacy Phase 35 system_files mail image.
|
||||
title := "Legacy Logo"
|
||||
isPublic := true
|
||||
legacy := attach.File{
|
||||
DiskName: "leg123456789.png",
|
||||
FileName: "legacy-logo.png",
|
||||
FileSize: 123,
|
||||
ContentType: "image/png",
|
||||
Title: &title,
|
||||
Field: "images",
|
||||
AttachmentType: album.MailImageLibraryMorph,
|
||||
IsPublic: &isPublic,
|
||||
}
|
||||
if err := env.gdb.Create(&legacy).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Upload a new mail image via POST /mail/images -> stored in album's "mail" folder.
|
||||
rec := mailUpload(t, env.h, layoutsTok, mediaTestPNG(t, 600, 300), "new-header.png")
|
||||
if rec.Code != http.StatusOK && rec.Code != http.StatusCreated {
|
||||
t.Fatalf("POST /mail/images status = %d, body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var postResp struct {
|
||||
Data cabana.AdminMailImage `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &postResp); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if postResp.Data.ID == 0 || !strings.Contains(postResp.Data.URL, "/media/") || len(postResp.Data.Variants) != 1 {
|
||||
t.Fatalf("expected album-backed mail image with variants, got %+v", postResp.Data)
|
||||
}
|
||||
|
||||
// GET /mail/images returns both the newly uploaded album item and the backfilled legacy item.
|
||||
list := env.expect(t, http.StatusOK, http.MethodGet, "/mail/images", layoutsTok, nil)
|
||||
rows, _ := list["data"].([]any)
|
||||
if len(rows) != 2 {
|
||||
t.Fatalf("GET /mail/images count = %d, want 2 (new + backfilled legacy)", len(rows))
|
||||
}
|
||||
|
||||
// GET /mail/images/{id} resolves both the new album ID and the legacy system_files ID.
|
||||
env.expect(t, http.StatusOK, http.MethodGet, fmt.Sprintf("/mail/images/%d", postResp.Data.ID), layoutsTok, nil)
|
||||
env.expect(t, http.StatusOK, http.MethodGet, fmt.Sprintf("/mail/images/%d", legacy.ID), layoutsTok, nil)
|
||||
|
||||
// MailBrandSetting.LogoFileID accepts the new album item ID.
|
||||
env.expect(t, http.StatusOK, http.MethodPut, "/settings/mail_brand", layoutsTok, map[string]any{
|
||||
"logo_file_id": postResp.Data.ID,
|
||||
})
|
||||
}
|
||||
162
modules/cabana/media_routes_test.go
Normal file
162
modules/cabana/media_routes_test.go
Normal file
@@ -0,0 +1,162 @@
|
||||
package cabana_test
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/bouncer"
|
||||
"git.golem15.com/golem15/summercms/modules/cabana"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
)
|
||||
|
||||
func TestMediaFinderFieldSchema(t *testing.T) {
|
||||
t.Run("valid_defaults_and_options", func(t *testing.T) {
|
||||
yaml := datepickerFields(` cover:
|
||||
label: Cover
|
||||
type: mediafinder
|
||||
gallery:
|
||||
label: Gallery
|
||||
type: mediafinder
|
||||
mode: file
|
||||
multiple: true
|
||||
folder: journal
|
||||
`)
|
||||
form, err := cabana.CompileForm("acme.conform", conformController{}, datepickerFS(yaml))
|
||||
if err != nil {
|
||||
t.Fatalf("CompileForm: %v", err)
|
||||
}
|
||||
raw, err := form.CanonicalJSON()
|
||||
if err != nil {
|
||||
t.Fatalf("CanonicalJSON: %v", err)
|
||||
}
|
||||
var doc struct {
|
||||
Fields []map[string]any `json:"fields"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &doc); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
byName := map[string]map[string]any{}
|
||||
for _, f := range doc.Fields {
|
||||
byName[f["name"].(string)] = f
|
||||
}
|
||||
cover := byName["cover"]
|
||||
if cover == nil || cover["type"] != "mediafinder" || cover["mode"] != "image" {
|
||||
t.Fatalf("cover field = %v, want type=mediafinder mode=image", cover)
|
||||
}
|
||||
gallery := byName["gallery"]
|
||||
if gallery == nil || gallery["type"] != "mediafinder" || gallery["mode"] != "file" || gallery["multiple"] != true || gallery["folder"] != "journal" {
|
||||
t.Fatalf("gallery field = %v, want type=mediafinder mode=file multiple=true folder=journal", gallery)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("invalid_options_rejected", func(t *testing.T) {
|
||||
cases := map[string]struct {
|
||||
field string
|
||||
want string
|
||||
}{
|
||||
"invalid mode": {" cover:\n type: mediafinder\n mode: video\n", "must be image or file on type: mediafinder"},
|
||||
"traversal folder": {" cover:\n type: mediafinder\n folder: ../etc\n", "must be a single folder slug"},
|
||||
"nested slash folder": {" cover:\n type: mediafinder\n folder: a/b\n", "must be a single folder slug"},
|
||||
"multiple on text": {" title:\n type: text\n multiple: true\n", "multiple is only valid on type: mediafinder"},
|
||||
"folder on text": {" title:\n type: text\n folder: mail\n", "folder is only valid on type: mediafinder"},
|
||||
"non-bool multiple": {" cover:\n type: mediafinder\n multiple: yes-please\n", "multiple:"},
|
||||
}
|
||||
for name, tc := range cases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
err := activateFields(t, datepickerFields(tc.field))
|
||||
if err == nil || !strings.Contains(err.Error(), tc.want) {
|
||||
t.Fatalf("err = %v, want substring %q", err, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestMediaMCPPluginSurfaceAndScopes(t *testing.T) {
|
||||
plugin := cabana.MediaMCPPlugin("/admin")
|
||||
if plugin.ID() != "summercms.media" {
|
||||
t.Fatalf("ID = %q, want summercms.media", plugin.ID())
|
||||
}
|
||||
|
||||
hasPerms, ok := plugin.(pact.HasPermissions)
|
||||
if !ok {
|
||||
t.Fatal("MediaMCPPlugin must implement pact.HasPermissions")
|
||||
}
|
||||
permCodes := map[string]bool{}
|
||||
for _, p := range hasPerms.Permissions() {
|
||||
permCodes[p.Code] = true
|
||||
if len(p.Roles) > 0 {
|
||||
t.Fatalf("media permission %q must not have default role grants: %v", p.Code, p.Roles)
|
||||
}
|
||||
}
|
||||
if !permCodes[cabana.PermissionViewMedia] || !permCodes[cabana.PermissionManageMedia] {
|
||||
t.Fatalf("missing media permissions: %v", permCodes)
|
||||
}
|
||||
|
||||
hasScopes, ok := plugin.(pact.HasTokenScopes)
|
||||
if !ok {
|
||||
t.Fatal("MediaMCPPlugin must implement pact.HasTokenScopes")
|
||||
}
|
||||
scopes := map[string]pact.TokenScope{}
|
||||
for _, s := range hasScopes.TokenScopes() {
|
||||
scopes[s.Name] = s
|
||||
}
|
||||
readScope, ok := scopes["media:read"]
|
||||
if !ok || readScope.Group != "backend::lang.api_tokens.group_media" {
|
||||
t.Fatalf("media:read scope = %+v", readScope)
|
||||
}
|
||||
writeScope, ok := scopes["media"]
|
||||
if !ok || writeScope.Group != "backend::lang.api_tokens.group_media" {
|
||||
t.Fatalf("media scope = %+v", writeScope)
|
||||
}
|
||||
|
||||
hasMCP, ok := plugin.(pact.HasMCP)
|
||||
if !ok {
|
||||
t.Fatal("MediaMCPPlugin must implement pact.HasMCP")
|
||||
}
|
||||
tools := hasMCP.MCP().Tools
|
||||
if len(tools) != 7 {
|
||||
t.Fatalf("MediaMCPPlugin tools = %d, want 7", len(tools))
|
||||
}
|
||||
wantTools := map[string]bool{
|
||||
"prepare_upload": false,
|
||||
"upload": false,
|
||||
"list": false,
|
||||
"get": false,
|
||||
"update": false,
|
||||
"delete": false,
|
||||
"create_folder": false,
|
||||
}
|
||||
for _, tool := range tools {
|
||||
if _, exists := wantTools[tool.Name]; !exists {
|
||||
t.Errorf("unexpected MCP tool %q", tool.Name)
|
||||
}
|
||||
wantTools[tool.Name] = true
|
||||
if tool.Guard != "backend" {
|
||||
t.Errorf("tool %q Guard = %q, want backend", tool.Name, tool.Guard)
|
||||
}
|
||||
if tool.Name == "delete" && (tool.Destructive == nil || !*tool.Destructive) {
|
||||
t.Errorf("delete tool must be marked Destructive=true")
|
||||
}
|
||||
}
|
||||
for name, seen := range wantTools {
|
||||
if !seen {
|
||||
t.Errorf("missing expected MCP tool %q", name)
|
||||
}
|
||||
}
|
||||
|
||||
// Verify Allows helper respects media.view_media vs media.manage_media.
|
||||
viewer := &bouncer.Principal{ID: 1, Backend: true, PermissionGrants: map[string]bool{cabana.PermissionViewMedia: true}}
|
||||
manager := &bouncer.Principal{ID: 2, Backend: true, PermissionGrants: map[string]bool{cabana.PermissionManageMedia: true}}
|
||||
none := &bouncer.Principal{ID: 3, Backend: true, PermissionGrants: map[string]bool{"acme.demo.access": true}}
|
||||
if !cabana.Allows(viewer, []string{cabana.PermissionViewMedia}) || cabana.Allows(viewer, []string{cabana.PermissionManageMedia}) {
|
||||
t.Fatal("viewer permission check mismatch")
|
||||
}
|
||||
if !cabana.Allows(manager, []string{cabana.PermissionManageMedia}) {
|
||||
t.Fatal("manager permission check mismatch")
|
||||
}
|
||||
if cabana.Allows(none, []string{cabana.PermissionViewMedia}) || cabana.Allows(none, []string{cabana.PermissionManageMedia}) {
|
||||
t.Fatal("none principal unexpectedly allowed media permissions")
|
||||
}
|
||||
}
|
||||
@@ -1167,9 +1167,9 @@ func newConformEnv(t *testing.T) *conformEnv {
|
||||
login := "conform-" + stamp
|
||||
insertAdmin(t, gdb, login, login+"@example.test", adminTestPassword, true, false)
|
||||
// The Plugins screen needs backend.view_plugins, which no role holds.
|
||||
// Mail image routes need either mail permission (conform is not a superuser).
|
||||
// Mail image and Media Library routes need their respective permissions (conform is not a superuser).
|
||||
if err := gdb.Exec(`UPDATE backend_users SET permissions = ? WHERE login = ?`,
|
||||
`{"backend.view_plugins":1,"system.manage_mail_templates":1,"system.manage_mail_layouts":1}`, login).Error; err != nil {
|
||||
`{"backend.view_plugins":1,"system.manage_mail_templates":1,"system.manage_mail_layouts":1,"media.view_media":1,"media.manage_media":1}`, login).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
|
||||
519
modules/pier/media_mcp_test.go
Normal file
519
modules/pier/media_mcp_test.go
Normal file
@@ -0,0 +1,519 @@
|
||||
//go:build summercms_mcp
|
||||
|
||||
package pier_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/album"
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/bouncer"
|
||||
"git.golem15.com/golem15/summercms/modules/cabana"
|
||||
"git.golem15.com/golem15/summercms/modules/compass"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
"git.golem15.com/golem15/summercms/modules/party"
|
||||
"github.com/modelcontextprotocol/go-sdk/mcp"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
// mediaBackendGuard implements pact.MCPGuardProvider for the "backend" guard
|
||||
// with real scope-to-permission enforcement (media:read vs media) matching cabana.
|
||||
type mediaBackendGuard struct{}
|
||||
|
||||
func (mediaBackendGuard) MCPGuardName() string { return "backend" }
|
||||
|
||||
func (mediaBackendGuard) MCPTokenGuarded(mw []string) bool {
|
||||
return slices.Contains(mw, "backend")
|
||||
}
|
||||
|
||||
func (mediaBackendGuard) MCPRequirements(perms []string) (pact.MCPRequirements, error) {
|
||||
return pact.MCPRequirements{Permissions: perms}, nil
|
||||
}
|
||||
|
||||
func (mediaBackendGuard) MCPAllows(_ context.Context, subject pact.MCPSubject, _ pact.MCPRequirements, permissions []string) (bool, error) {
|
||||
if slices.Contains(subject.Scopes, "media") {
|
||||
return true, nil
|
||||
}
|
||||
if slices.Contains(subject.Scopes, "media:read") {
|
||||
for _, p := range permissions {
|
||||
if p != cabana.PermissionViewMedia {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
func (mediaBackendGuard) MCPDispatch(_ context.Context, subject pact.MCPSubject, _ string) (pact.MCPDispatch, error) {
|
||||
return pact.MCPDispatch{
|
||||
Principal: &bouncer.Principal{
|
||||
ID: subject.UserID,
|
||||
Backend: true,
|
||||
PermissionGrants: map[string]bool{
|
||||
cabana.PermissionViewMedia: true,
|
||||
cabana.PermissionManageMedia: true,
|
||||
},
|
||||
},
|
||||
Guards: []string{"backend"},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// mediaTokenVerifier issues two bearer tokens: one with "media:read" and one with "media".
|
||||
type mediaTokenVerifier struct{}
|
||||
|
||||
func (mediaTokenVerifier) MCPVerifyToken(_ context.Context, raw string) (pact.MCPGrant, error) {
|
||||
switch raw {
|
||||
case "oas_at_media_read":
|
||||
return pact.MCPGrant{
|
||||
Subject: pact.MCPGrantSubjectBackend,
|
||||
BackendUserID: 11,
|
||||
ClientID: "c-read",
|
||||
TokenID: 1,
|
||||
Scopes: []string{"media:read"},
|
||||
ExpiresAt: time.Now().Add(time.Hour),
|
||||
}, nil
|
||||
case "oas_at_media_write":
|
||||
return pact.MCPGrant{
|
||||
Subject: pact.MCPGrantSubjectBackend,
|
||||
BackendUserID: 12,
|
||||
ClientID: "c-write",
|
||||
TokenID: 2,
|
||||
Scopes: []string{"media"},
|
||||
ExpiresAt: time.Now().Add(time.Hour),
|
||||
}, nil
|
||||
default:
|
||||
return pact.MCPGrant{}, pact.ErrMCPTokenInvalid
|
||||
}
|
||||
}
|
||||
|
||||
func (mediaTokenVerifier) MCPResource() string { return "http://acme.test/mcp" }
|
||||
|
||||
// mediaStubRoutesPlugin mounts the /admin/api/v1/media/* routes behind the
|
||||
// "backend" middleware plus raw PUT /media/upload/{token} in memory so
|
||||
// TestMediaMCPTools exercises all 7 media_* tools, signed PUT upload, and the
|
||||
// 5 MB base64 cap end-to-end without requiring Docker.
|
||||
type mediaStubRoutesPlugin struct {
|
||||
mu sync.Mutex
|
||||
nextID uint
|
||||
folders map[uint]map[string]any
|
||||
items map[uint]map[string]any
|
||||
tokens map[string]string // token -> filename
|
||||
baseURL string
|
||||
}
|
||||
|
||||
func newMediaStubRoutesPlugin() *mediaStubRoutesPlugin {
|
||||
return &mediaStubRoutesPlugin{
|
||||
nextID: 1,
|
||||
folders: map[uint]map[string]any{},
|
||||
items: map[uint]map[string]any{},
|
||||
tokens: map[string]string{},
|
||||
}
|
||||
}
|
||||
|
||||
func (*mediaStubRoutesPlugin) ID() string { return "test.media_stub" }
|
||||
func (*mediaStubRoutesPlugin) Requires() []string { return nil }
|
||||
func (*mediaStubRoutesPlugin) Register(*backpack.App) error { return nil }
|
||||
func (*mediaStubRoutesPlugin) Boot(*backpack.App) error { return nil }
|
||||
|
||||
func (*mediaStubRoutesPlugin) Middlewares() map[string]pact.Middleware {
|
||||
return map[string]pact.Middleware{
|
||||
"backend": func(next http.Handler) http.Handler { return next },
|
||||
}
|
||||
}
|
||||
|
||||
func (p *mediaStubRoutesPlugin) Routes(r pact.Router) error {
|
||||
r.Group("/admin/api/v1", []string{"backend"}, func(g pact.Router) {
|
||||
g.Post("/media/folders", p.createFolder)
|
||||
g.Post("/media/uploads/prepare", p.prepareUpload)
|
||||
g.Post("/media/items/base64", p.uploadBase64)
|
||||
g.Get("/media/items", p.listItems)
|
||||
g.Get("/media/items/{id}", p.getItem)
|
||||
g.Put("/media/items/{id}", p.updateItem)
|
||||
g.Delete("/media/items/{id}", p.deleteItem)
|
||||
})
|
||||
r.GroupRaw("/media", nil, func(g pact.Router) {
|
||||
g.Put("/upload/{token}", p.signedUpload)
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *mediaStubRoutesPlugin) createFolder(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Name string `json:"name"`
|
||||
ParentID *uint `json:"parent_id"`
|
||||
}
|
||||
_ = json.NewDecoder(r.Body).Decode(&req)
|
||||
p.mu.Lock()
|
||||
id := p.nextID
|
||||
p.nextID++
|
||||
f := map[string]any{"id": id, "name": req.Name, "slug": album.SanitizeSlug(req.Name), "parent_id": req.ParentID}
|
||||
p.folders[id] = f
|
||||
p.mu.Unlock()
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"data": f})
|
||||
}
|
||||
|
||||
func (p *mediaStubRoutesPlugin) prepareUpload(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Filename string `json:"filename"`
|
||||
}
|
||||
_ = json.NewDecoder(r.Body).Decode(&req)
|
||||
p.mu.Lock()
|
||||
tok := fmt.Sprintf("tok-%d", p.nextID)
|
||||
p.nextID++
|
||||
p.tokens[tok] = req.Filename
|
||||
base := p.baseURL
|
||||
p.mu.Unlock()
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"data": map[string]any{
|
||||
"upload_url": base + "/media/upload/" + tok,
|
||||
"method": http.MethodPut,
|
||||
"expires_at": time.Now().Add(5 * time.Minute).UTC().Format(time.RFC3339),
|
||||
"max_bytes": album.DefaultMaxBytes,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (p *mediaStubRoutesPlugin) signedUpload(w http.ResponseWriter, r *http.Request) {
|
||||
tok := r.PathValue("token")
|
||||
p.mu.Lock()
|
||||
filename, ok := p.tokens[tok]
|
||||
if ok {
|
||||
delete(p.tokens, tok)
|
||||
}
|
||||
p.mu.Unlock()
|
||||
if !ok {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
_, _ = w.Write([]byte(`{"error":"invalid token"}`))
|
||||
return
|
||||
}
|
||||
raw, _ := io.ReadAll(r.Body)
|
||||
p.mu.Lock()
|
||||
id := p.nextID
|
||||
p.nextID++
|
||||
item := map[string]any{
|
||||
"id": id,
|
||||
"file_name": filename,
|
||||
"file_size": len(raw),
|
||||
"url": fmt.Sprintf("/media/abc123456789/%s", filename),
|
||||
"alt": "",
|
||||
}
|
||||
p.items[id] = item
|
||||
p.mu.Unlock()
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"data": item})
|
||||
}
|
||||
|
||||
func (p *mediaStubRoutesPlugin) uploadBase64(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Filename string `json:"filename"`
|
||||
ContentBase64 string `json:"content_base64"`
|
||||
Alt string `json:"alt"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
w.WriteHeader(http.StatusUnprocessableEntity)
|
||||
_, _ = w.Write([]byte(`{"error":{"code":"validation_failed","message":"invalid json"}}`))
|
||||
return
|
||||
}
|
||||
decoded, err := base64.StdEncoding.DecodeString(req.ContentBase64)
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusUnprocessableEntity)
|
||||
_, _ = w.Write([]byte(`{"error":{"code":"validation_failed","message":"invalid base64"}}`))
|
||||
return
|
||||
}
|
||||
if int64(len(decoded)) > album.DefaultBase64MaxBytes {
|
||||
w.WriteHeader(http.StatusRequestEntityTooLarge)
|
||||
_, _ = w.Write([]byte(`{"error":{"code":"payload_too_large","message":"file exceeds 5 MB base64 cap"}}`))
|
||||
return
|
||||
}
|
||||
p.mu.Lock()
|
||||
id := p.nextID
|
||||
p.nextID++
|
||||
item := map[string]any{
|
||||
"id": id,
|
||||
"file_name": req.Filename,
|
||||
"file_size": len(decoded),
|
||||
"alt": req.Alt,
|
||||
"url": fmt.Sprintf("/media/def123456789/%s", req.Filename),
|
||||
}
|
||||
p.items[id] = item
|
||||
p.mu.Unlock()
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"data": item})
|
||||
}
|
||||
|
||||
func (p *mediaStubRoutesPlugin) listItems(w http.ResponseWriter, _ *http.Request) {
|
||||
p.mu.Lock()
|
||||
out := make([]map[string]any, 0, len(p.items))
|
||||
for _, it := range p.items {
|
||||
out = append(out, it)
|
||||
}
|
||||
p.mu.Unlock()
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"data": out, "meta": map[string]any{"total": len(out)}})
|
||||
}
|
||||
|
||||
func (p *mediaStubRoutesPlugin) getItem(w http.ResponseWriter, r *http.Request) {
|
||||
id, _ := strconv.Atoi(r.PathValue("id"))
|
||||
p.mu.Lock()
|
||||
it, ok := p.items[uint(id)]
|
||||
p.mu.Unlock()
|
||||
if !ok {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
_, _ = w.Write([]byte(`{"error":{"code":"not_found"}}`))
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"data": it})
|
||||
}
|
||||
|
||||
func (p *mediaStubRoutesPlugin) updateItem(w http.ResponseWriter, r *http.Request) {
|
||||
id, _ := strconv.Atoi(r.PathValue("id"))
|
||||
var req map[string]any
|
||||
_ = json.NewDecoder(r.Body).Decode(&req)
|
||||
p.mu.Lock()
|
||||
it, ok := p.items[uint(id)]
|
||||
if ok {
|
||||
if alt, has := req["alt"].(string); has {
|
||||
it["alt"] = alt
|
||||
}
|
||||
}
|
||||
p.mu.Unlock()
|
||||
if !ok {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"data": it})
|
||||
}
|
||||
|
||||
func (p *mediaStubRoutesPlugin) deleteItem(w http.ResponseWriter, r *http.Request) {
|
||||
id, _ := strconv.Atoi(r.PathValue("id"))
|
||||
p.mu.Lock()
|
||||
_, ok := p.items[uint(id)]
|
||||
delete(p.items, uint(id))
|
||||
p.mu.Unlock()
|
||||
if !ok {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"data": map[string]any{"deleted": true}})
|
||||
}
|
||||
|
||||
func callMCPToolJSON(t *testing.T, session *mcp.ClientSession, name string, args map[string]any) (map[string]any, bool) {
|
||||
t.Helper()
|
||||
res, err := session.CallTool(context.Background(), &mcp.CallToolParams{
|
||||
Name: name,
|
||||
Arguments: args,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("CallTool(%s): %v", name, err)
|
||||
}
|
||||
var text string
|
||||
for _, c := range res.Content {
|
||||
if tc, ok := c.(*mcp.TextContent); ok {
|
||||
text += tc.Text
|
||||
}
|
||||
}
|
||||
var out map[string]any
|
||||
_ = json.Unmarshal([]byte(text), &out)
|
||||
return out, res.IsError
|
||||
}
|
||||
|
||||
func TestMediaMCPTools(t *testing.T) {
|
||||
logBuf := captureLogs(t)
|
||||
stub := newMediaStubRoutesPlugin()
|
||||
dir := t.TempDir()
|
||||
for name, body := range map[string]string{
|
||||
"app.yaml": "name: acme\nurl: http://acme.test\n",
|
||||
"http.yaml": "body_limits:\n default_bytes: 10485760\n upload_bytes: 10485760\n",
|
||||
"mcp.yaml": "enabled: false\n",
|
||||
} {
|
||||
if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
cfg, err := compass.Open(compass.Options{Dir: dir, Environ: []string{"SUMMER_ENV=development"}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
app := backpack.New(cfg)
|
||||
if err := app.Publish[pact.MCPTokenVerifier](mediaTokenVerifier{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reg := pact.NewMCPGuards()
|
||||
if err := reg.Register(mediaBackendGuard{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := app.Publish(reg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
plugins := []party.Plugin{stub, cabana.MediaMCPPlugin("/admin")}
|
||||
host, err := mountPier(t, app, plugins)
|
||||
if err != nil {
|
||||
t.Fatalf("mountPier: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = host.pier.Close() })
|
||||
|
||||
// Assert zero warnUncoveredBackendWriteTools warnings at boot.
|
||||
if n := countWarningLines(logBuf.String()); n != 0 {
|
||||
t.Fatalf("expected 0 uncovered-write-tool boot warnings, got %d:\n%s", n, logBuf.String())
|
||||
}
|
||||
|
||||
// Serve both MCP endpoints (host) and raw /media/upload/{token} (stub router).
|
||||
uploadHandler, ok := host.r.Handler(http.MethodPut, "/media/upload/{token}")
|
||||
if !ok {
|
||||
t.Fatal("expected PUT /media/upload/{token} on router")
|
||||
}
|
||||
uploadMux := http.NewServeMux()
|
||||
uploadMux.Handle("PUT /media/upload/{token}", uploadHandler)
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if strings.HasPrefix(r.URL.Path, "/media/upload/") {
|
||||
uploadMux.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
host.ServeHTTP(w, r)
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
stub.baseURL = srv.URL
|
||||
|
||||
// 1. Scope filtering: media:read sees only media_list and media_get.
|
||||
readSession := sdkClient(t, context.Background(), srv.URL+host.path, "oas_at_media_read", clientOpts{})
|
||||
readTools, err := readSession.ListTools(context.Background(), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("ListTools(media:read): %v", err)
|
||||
}
|
||||
var readNames []string
|
||||
for _, tool := range readTools.Tools {
|
||||
readNames = append(readNames, tool.Name)
|
||||
}
|
||||
slices.Sort(readNames)
|
||||
if !slices.Equal(readNames, []string{"media_get", "media_list"}) {
|
||||
t.Fatalf("media:read tools = %v, want [media_get media_list]", readNames)
|
||||
}
|
||||
|
||||
// 2. Scope filtering: media sees all 7 media_* tools.
|
||||
writeSession := sdkClient(t, context.Background(), srv.URL+host.path, "oas_at_media_write", clientOpts{})
|
||||
writeTools, err := writeSession.ListTools(context.Background(), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("ListTools(media): %v", err)
|
||||
}
|
||||
var writeNames []string
|
||||
for _, tool := range writeTools.Tools {
|
||||
writeNames = append(writeNames, tool.Name)
|
||||
}
|
||||
slices.Sort(writeNames)
|
||||
wantAll := []string{
|
||||
"media_create_folder",
|
||||
"media_delete",
|
||||
"media_get",
|
||||
"media_list",
|
||||
"media_prepare_upload",
|
||||
"media_update",
|
||||
"media_upload",
|
||||
}
|
||||
if !slices.Equal(writeNames, wantAll) {
|
||||
t.Fatalf("media tools = %v, want %v", writeNames, wantAll)
|
||||
}
|
||||
|
||||
// 3. media_create_folder
|
||||
folderRes, isErr := callMCPToolJSON(t, writeSession, "media_create_folder", map[string]any{"name": "Editorial"})
|
||||
if isErr {
|
||||
t.Fatalf("media_create_folder error: %v", folderRes)
|
||||
}
|
||||
|
||||
// 4. media_prepare_upload -> HTTP PUT /media/upload/{token} end-to-end
|
||||
prepRes, isErr := callMCPToolJSON(t, writeSession, "media_prepare_upload", map[string]any{"filename": "hero.png"})
|
||||
if isErr {
|
||||
t.Fatalf("media_prepare_upload error: %v", prepRes)
|
||||
}
|
||||
dataMap, _ := prepRes["data"].(map[string]any)
|
||||
uploadURL, _ := dataMap["upload_url"].(string)
|
||||
if !strings.Contains(uploadURL, "/media/upload/") {
|
||||
t.Fatalf("unexpected upload_url: %q", uploadURL)
|
||||
}
|
||||
putReq, err := http.NewRequest(http.MethodPut, uploadURL, bytes.NewReader([]byte("binary-image-bytes")))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
putResp, err := http.DefaultClient.Do(putReq)
|
||||
if err != nil {
|
||||
t.Fatalf("PUT signed upload: %v", err)
|
||||
}
|
||||
_ = putResp.Body.Close()
|
||||
if putResp.StatusCode != http.StatusCreated {
|
||||
t.Fatalf("PUT %s status = %d, want 201", uploadURL, putResp.StatusCode)
|
||||
}
|
||||
// Replay of same signed URL returns 401.
|
||||
putReq2, _ := http.NewRequest(http.MethodPut, uploadURL, bytes.NewReader([]byte("replay")))
|
||||
putResp2, err := http.DefaultClient.Do(putReq2)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = putResp2.Body.Close()
|
||||
if putResp2.StatusCode != http.StatusUnauthorized {
|
||||
t.Fatalf("replay PUT status = %d, want 401", putResp2.StatusCode)
|
||||
}
|
||||
|
||||
// 5. media_upload base64: exact 5 MB payload succeeds (proves 8 MiB pier.maxRequestBody).
|
||||
fiveMB := bytes.Repeat([]byte("A"), int(album.DefaultBase64MaxBytes))
|
||||
upRes, isErr := callMCPToolJSON(t, writeSession, "media_upload", map[string]any{
|
||||
"filename": "exact-5mb.pdf",
|
||||
"content_base64": base64.StdEncoding.EncodeToString(fiveMB),
|
||||
"alt": "Five MB",
|
||||
})
|
||||
if isErr {
|
||||
t.Fatalf("5 MB media_upload failed: %v", upRes)
|
||||
}
|
||||
itemData, _ := upRes["data"].(map[string]any)
|
||||
itemID := uint(itemData["id"].(float64))
|
||||
|
||||
// >5 MB decoded payload is rejected.
|
||||
overFiveMB := bytes.Repeat([]byte("B"), int(album.DefaultBase64MaxBytes)+1024)
|
||||
if _, isErr := callMCPToolJSON(t, writeSession, "media_upload", map[string]any{
|
||||
"filename": "over-5mb.pdf",
|
||||
"content_base64": base64.StdEncoding.EncodeToString(overFiveMB),
|
||||
}); !isErr {
|
||||
t.Fatal(">5 MB decoded media_upload must fail")
|
||||
}
|
||||
|
||||
// 6. media_list, media_get, media_update, media_delete
|
||||
listRes, isErr := callMCPToolJSON(t, readSession, "media_list", map[string]any{})
|
||||
if isErr {
|
||||
t.Fatalf("media_list error: %v", listRes)
|
||||
}
|
||||
getRes, isErr := callMCPToolJSON(t, readSession, "media_get", map[string]any{"id": itemID})
|
||||
if isErr {
|
||||
t.Fatalf("media_get error: %v", getRes)
|
||||
}
|
||||
updRes, isErr := callMCPToolJSON(t, writeSession, "media_update", map[string]any{"id": itemID, "alt": "New Alt"})
|
||||
if isErr {
|
||||
t.Fatalf("media_update error: %v", updRes)
|
||||
}
|
||||
delRes, isErr := callMCPToolJSON(t, writeSession, "media_delete", map[string]any{"id": itemID})
|
||||
if isErr {
|
||||
t.Fatalf("media_delete error: %v", delRes)
|
||||
}
|
||||
}
|
||||
174
modules/surf/media_test.go
Normal file
174
modules/surf/media_test.go
Normal file
@@ -0,0 +1,174 @@
|
||||
package surf
|
||||
|
||||
import (
|
||||
"context"
|
||||
"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/party"
|
||||
"gocloud.dev/blob"
|
||||
"gocloud.dev/blob/memblob"
|
||||
)
|
||||
|
||||
func mediaConfig(t *testing.T, keys map[string]any) *compass.Config {
|
||||
t.Helper()
|
||||
cfg := writeHTTPConfig(t, "body_limits:\n default_bytes: 1024\n upload_bytes: 1024\n")
|
||||
for k, v := range keys {
|
||||
if err := cfg.Set(k, v); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
return cfg
|
||||
}
|
||||
|
||||
func mediaRoutes(t *testing.T, app *backpack.App, plugins []party.Plugin) []RouteInfo {
|
||||
t.Helper()
|
||||
rt, err := BuildRouter(app, plugins)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var out []RouteInfo
|
||||
for _, info := range rt.Routes() {
|
||||
if info.PluginID == mediaPluginID {
|
||||
out = append(out, info)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestMediaMount(t *testing.T) {
|
||||
t.Run("off_registers_no_static_route", func(t *testing.T) {
|
||||
app := backpack.New(mediaConfig(t, map[string]any{"media.serve": false}))
|
||||
routes := mediaRoutes(t, app, nil)
|
||||
for _, rt := range routes {
|
||||
if rt.Method == http.MethodGet {
|
||||
t.Fatalf("unexpected static GET route when media.serve=false: %+v", rt)
|
||||
}
|
||||
}
|
||||
if _, ok := album.ServiceFrom(app); !ok {
|
||||
t.Fatal("expected *album.Service to be published on app")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("static_zero_db_serving_and_headers", func(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
bucket := memblob.OpenBucket(nil)
|
||||
defer bucket.Close()
|
||||
|
||||
if err := bucket.WriteAll(ctx, "media/abc123456789/hero.png", []byte("png-data"), attach.UploadWriterOptions("image/png")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := bucket.WriteAll(ctx, "media/abc123456789/spec.pdf", []byte("%PDF-1.4\n"), attach.UploadWriterOptions("application/pdf")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Intentionally do NOT publish *gorm.DB: proves zero-DB-hit serving.
|
||||
app := backpack.New(mediaConfig(t, map[string]any{"media.serve": true}))
|
||||
if err := app.Publish[*blob.Bucket](bucket); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h, err := Assemble(app, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("Assemble: %v", err)
|
||||
}
|
||||
|
||||
// Raster image served inline with immutable Cache-Control, nosniff, CSP.
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/media/abc123456789/hero.png", nil))
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("GET image status = %d, want 200", rec.Code)
|
||||
}
|
||||
if rec.Body.String() != "png-data" {
|
||||
t.Fatalf("body = %q, want png-data", rec.Body.String())
|
||||
}
|
||||
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)
|
||||
}
|
||||
if got := rec.Header().Get("Content-Disposition"); got != "" {
|
||||
t.Fatalf("image Content-Disposition = %q, want empty", got)
|
||||
}
|
||||
|
||||
// PDF served with Content-Disposition: attachment.
|
||||
rec = httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/media/abc123456789/spec.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("pdf Content-Disposition = %q, want attachment", got)
|
||||
}
|
||||
|
||||
// Traversal path rejected with 404.
|
||||
rec = httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/media/abc123456789/..%2Fsecret.png", nil))
|
||||
if rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("traversal status = %d, want 404", rec.Code)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("prefix_collision_rejected", func(t *testing.T) {
|
||||
app := backpack.New(mediaConfig(t, map[string]any{"media.serve": true}))
|
||||
_, err := BuildRouter(app, []party.Plugin{uploadsPathPlugin{path: "/media/custom"}})
|
||||
if err == nil || !strings.Contains(err.Error(), "media prefix") {
|
||||
t.Fatalf("BuildRouter collision err = %v, want media prefix collision", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("invalid_prefix_rejected", func(t *testing.T) {
|
||||
app := backpack.New(mediaConfig(t, map[string]any{
|
||||
"media.serve": true,
|
||||
"media.public_path_prefix": "https://cdn.example.com/media",
|
||||
}))
|
||||
if _, err := BuildRouter(app, nil); err == nil {
|
||||
t.Fatal("expected invalid media.public_path_prefix to fail BuildRouter")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("signed_upload_route_mounted_raw_without_admin_cookie", func(t *testing.T) {
|
||||
app := backpack.New(mediaConfig(t, map[string]any{"media.serve": true}))
|
||||
routes := mediaRoutes(t, app, nil)
|
||||
var sawPut, sawPost bool
|
||||
for _, rt := range routes {
|
||||
if rt.Pattern == "/media/upload/{token}" {
|
||||
if rt.Method == http.MethodPut {
|
||||
sawPut = true
|
||||
}
|
||||
if rt.Method == http.MethodPost {
|
||||
sawPost = true
|
||||
}
|
||||
for _, mw := range rt.Middleware {
|
||||
if mw == "backend" || mw == "csrf" {
|
||||
t.Fatalf("signed upload route must not require %q middleware: %+v", mw, rt.Middleware)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !sawPut || !sawPost {
|
||||
t.Fatalf("expected PUT and POST /media/upload/{token}, got routes: %+v", routes)
|
||||
}
|
||||
|
||||
// Calling PUT /media/upload/tok without any cookie/CSRF reaches the handler
|
||||
// (returns 503 because no DB is published, rather than 401/403 CSRF).
|
||||
h, err := Assemble(app, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, httptest.NewRequest(http.MethodPut, "/media/upload/some-token", strings.NewReader("bytes")))
|
||||
if rec.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("PUT /media/upload/some-token without DB status = %d, want 503", rec.Code)
|
||||
}
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user