fix(album): enforce signed upload MIME, map duplicate folders, and optimize HEAD
This commit is contained in:
@@ -171,9 +171,19 @@ func TestFolderCRUDAndNonEmptyDelete(t *testing.T) {
|
||||
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")
|
||||
// Duplicate sibling slug returns ErrFolderExists.
|
||||
if _, err := svc.CreateFolder(ctx, gdb, "Press Kit", nil); !errors.Is(err, album.ErrFolderExists) {
|
||||
t.Fatalf("duplicate CreateFolder err = %v, want ErrFolderExists", err)
|
||||
}
|
||||
other, err := svc.CreateFolder(ctx, gdb, "Archive", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("CreateFolder other: %v", err)
|
||||
}
|
||||
if _, err := svc.UpdateFolder(ctx, gdb, other.ID, "press-kit", nil, false); !errors.Is(err, album.ErrFolderExists) {
|
||||
t.Fatalf("duplicate rename UpdateFolder err = %v, want ErrFolderExists", err)
|
||||
}
|
||||
if err := svc.DeleteFolder(ctx, gdb, other.ID); err != nil {
|
||||
t.Fatalf("DeleteFolder other: %v", err)
|
||||
}
|
||||
|
||||
child, err := svc.CreateFolder(ctx, gdb, "Logos", &root.ID)
|
||||
@@ -421,6 +431,21 @@ func TestConsumeUploadTokenSingleUse(t *testing.T) {
|
||||
if rec2.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("replay PUT status = %d, want 401", rec2.Code)
|
||||
}
|
||||
|
||||
// 6. ExpectedContentType mismatch is rejected with 422.
|
||||
prep3, err := svc.PrepareUpload(ctx, gdb, album.PrepareUploadInput{
|
||||
CreatedBy: 7,
|
||||
ExpectedFilename: "expected-jpeg.png",
|
||||
ExpectedContentType: "image/jpeg",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec3 := httptest.NewRecorder()
|
||||
mux.ServeHTTP(rec3, httptest.NewRequest(http.MethodPut, "/media/upload/"+prep3.Token, bytes.NewReader(pngBytes)))
|
||||
if rec3.Code != http.StatusUnprocessableEntity {
|
||||
t.Fatalf("mismatched content type PUT status = %d, want 422, body=%s", rec3.Code, rec3.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteItemInTxAfterCommit(t *testing.T) {
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"hash/crc32"
|
||||
"image"
|
||||
"net/http"
|
||||
@@ -163,6 +164,12 @@ func TestStaticHandlerSecurity(t *testing.T) {
|
||||
if rec.Body.Len() != 0 {
|
||||
t.Fatalf("HEAD body len = %d, want 0", rec.Body.Len())
|
||||
}
|
||||
if got := rec.Header().Get("Content-Type"); got != "image/png" {
|
||||
t.Fatalf("Content-Type = %q, want image/png", got)
|
||||
}
|
||||
if got := rec.Header().Get("Content-Length"); got != fmt.Sprintf("%d", len(pngBytes)) {
|
||||
t.Fatalf("Content-Length = %q, want %d", got, len(pngBytes))
|
||||
}
|
||||
if got := rec.Header().Get("Cache-Control"); got != album.MediaCacheControl {
|
||||
t.Fatalf("Cache-Control = %q, want %q", got, album.MediaCacheControl)
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"mime"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
@@ -68,27 +69,30 @@ func StaticHandler(bucket *blob.Bucket, prefix string) http.Handler {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
reader, err := bucket.NewReader(r.Context(), key, nil)
|
||||
if err != nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
defer reader.Close()
|
||||
|
||||
ct := strings.TrimSpace(reader.ContentType())
|
||||
ct := strings.TrimSpace(attrs.ContentType)
|
||||
if ct == "" {
|
||||
ct = defaultStaticContentType
|
||||
}
|
||||
w.Header().Set("Cache-Control", MediaCacheControl)
|
||||
w.Header().Set("Content-Type", ct)
|
||||
if attrs.Size >= 0 {
|
||||
w.Header().Set("Content-Length", strconv.FormatInt(attrs.Size, 10))
|
||||
}
|
||||
if !attach.IsInlineContentType(ct) {
|
||||
w.Header().Set("Content-Disposition", "attachment")
|
||||
} else if cd := safeDisposition(attrs.ContentDisposition); cd != "" {
|
||||
w.Header().Set("Content-Disposition", cd)
|
||||
}
|
||||
if r.Method == http.MethodHead {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
return
|
||||
}
|
||||
reader, err := bucket.NewReader(r.Context(), key, nil)
|
||||
if err != nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
defer reader.Close()
|
||||
_, _ = io.Copy(w, reader)
|
||||
})
|
||||
}
|
||||
@@ -240,14 +244,15 @@ func SignedUploadHandler(app *backpack.App, svc *Service) http.Handler {
|
||||
|
||||
uploadedBy := tok.CreatedBy
|
||||
item, err := svc.Upload(r.Context(), db, bucket, UploadInput{
|
||||
FileName: tok.ExpectedFilename,
|
||||
Body: r.Body,
|
||||
FolderID: tok.FolderID,
|
||||
Alt: r.URL.Query().Get("alt"),
|
||||
Title: r.URL.Query().Get("title"),
|
||||
Caption: r.URL.Query().Get("caption"),
|
||||
UploadedBy: &uploadedBy,
|
||||
MaxBytes: limit,
|
||||
FileName: tok.ExpectedFilename,
|
||||
Body: r.Body,
|
||||
FolderID: tok.FolderID,
|
||||
Alt: r.URL.Query().Get("alt"),
|
||||
Title: r.URL.Query().Get("title"),
|
||||
Caption: r.URL.Query().Get("caption"),
|
||||
UploadedBy: &uploadedBy,
|
||||
MaxBytes: limit,
|
||||
ExpectedContentType: tok.ExpectedContentType,
|
||||
})
|
||||
if err != nil {
|
||||
var maxErr *http.MaxBytesError
|
||||
|
||||
@@ -52,6 +52,8 @@ var (
|
||||
ErrFolderNotFound = errors.New("album: folder not found")
|
||||
// ErrFolderNotEmpty is returned when attempting to delete a folder that still has items or child folders.
|
||||
ErrFolderNotEmpty = errors.New("album: folder is not empty")
|
||||
// ErrFolderExists is returned when creating or renaming a folder collides with an existing sibling slug.
|
||||
ErrFolderExists = errors.New("album: folder already exists")
|
||||
// ErrInvalidFolder is returned when a folder name or parent hierarchy is invalid.
|
||||
ErrInvalidFolder = errors.New("album: invalid folder")
|
||||
// ErrInvalidUploadToken is returned when an upload token is missing, unknown, expired, or already used.
|
||||
@@ -108,9 +110,11 @@ type UploadInput struct {
|
||||
Title string
|
||||
Caption string
|
||||
UploadedBy *uint
|
||||
ImageOnly bool
|
||||
ImageOnly bool
|
||||
// MaxBytes caps this upload; 0 uses MaxBytes(cfg).
|
||||
MaxBytes int64
|
||||
// ExpectedContentType, when non-empty, requires the sniffed/resolved MIME type to match.
|
||||
ExpectedContentType string
|
||||
}
|
||||
|
||||
// Upload validates, stores, generates synchronous WebP variants for raster images,
|
||||
@@ -189,6 +193,9 @@ func (s *Service) Upload(ctx context.Context, db *gorm.DB, bucket *blob.Bucket,
|
||||
if slices.Contains(disallowedSniffed, contentType) {
|
||||
return nil, fmt.Errorf("%w: %s", ErrFileType, contentType)
|
||||
}
|
||||
if expected := baseMediaType(in.ExpectedContentType); expected != "" && contentType != expected {
|
||||
return nil, fmt.Errorf("%w: expected %s, got %s", ErrFileType, expected, contentType)
|
||||
}
|
||||
|
||||
diskExt := attach.DiskExtension(sniffed, ext)
|
||||
shortID, err := generateUniqueShortID(ctx, db)
|
||||
@@ -391,17 +398,56 @@ func (s *Service) CreateFolder(ctx context.Context, db *gorm.DB, name string, pa
|
||||
return nil, ErrFolderNotFound
|
||||
}
|
||||
}
|
||||
slug := SanitizeSlug(cleanName)
|
||||
exists, err := folderSlugExists(ctx, db, parentID, slug, 0)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("album: check sibling folder: %w", err)
|
||||
}
|
||||
if exists {
|
||||
return nil, ErrFolderExists
|
||||
}
|
||||
f := &Folder{
|
||||
ParentID: parentID,
|
||||
Name: cleanName,
|
||||
Slug: SanitizeSlug(cleanName),
|
||||
Slug: slug,
|
||||
}
|
||||
if err := db.WithContext(ctx).Create(f).Error; err != nil {
|
||||
if isFolderUniqueViolation(err) {
|
||||
return nil, ErrFolderExists
|
||||
}
|
||||
return nil, fmt.Errorf("album: create folder: %w", err)
|
||||
}
|
||||
return f, nil
|
||||
}
|
||||
|
||||
func folderSlugExists(ctx context.Context, db *gorm.DB, parentID *uint, slug string, excludeID uint) (bool, error) {
|
||||
q := db.WithContext(ctx).Model(&Folder{}).Where("slug = ?", slug)
|
||||
if parentID == nil {
|
||||
q = q.Where("parent_id IS NULL")
|
||||
} else {
|
||||
q = q.Where("parent_id = ?", *parentID)
|
||||
}
|
||||
if excludeID > 0 {
|
||||
q = q.Where("id <> ?", excludeID)
|
||||
}
|
||||
var count int64
|
||||
if err := q.Count(&count).Error; err != nil {
|
||||
return false, err
|
||||
}
|
||||
return count > 0, nil
|
||||
}
|
||||
|
||||
func isFolderUniqueViolation(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
if errors.Is(err, gorm.ErrDuplicatedKey) {
|
||||
return true
|
||||
}
|
||||
msg := err.Error()
|
||||
return strings.Contains(msg, "23505") || strings.Contains(msg, "summer_media_folders_parent_slug_uidx")
|
||||
}
|
||||
|
||||
// UpdateFolder renames or moves an existing virtual folder.
|
||||
func (s *Service) UpdateFolder(ctx context.Context, db *gorm.DB, id uint, name string, parentID *uint, setParent bool) (*Folder, error) {
|
||||
if ctx == nil {
|
||||
@@ -452,7 +498,25 @@ func (s *Service) UpdateFolder(ctx context.Context, db *gorm.DB, id uint, name s
|
||||
if len(updates) == 0 {
|
||||
return &f, nil
|
||||
}
|
||||
nextSlug := f.Slug
|
||||
if sVal, ok := updates["slug"].(string); ok {
|
||||
nextSlug = sVal
|
||||
}
|
||||
nextParentID := f.ParentID
|
||||
if setParent {
|
||||
nextParentID = parentID
|
||||
}
|
||||
exists, err := folderSlugExists(ctx, db, nextParentID, nextSlug, f.ID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("album: check sibling folder: %w", err)
|
||||
}
|
||||
if exists {
|
||||
return nil, ErrFolderExists
|
||||
}
|
||||
if err := db.WithContext(ctx).Model(&f).Updates(updates).Error; err != nil {
|
||||
if isFolderUniqueViolation(err) {
|
||||
return nil, ErrFolderExists
|
||||
}
|
||||
return nil, fmt.Errorf("album: update folder: %w", err)
|
||||
}
|
||||
if err := db.WithContext(ctx).First(&f, id).Error; err != nil {
|
||||
|
||||
Reference in New Issue
Block a user