Files
summercms/modules/album/http.go

280 lines
8.8 KiB
Go

package album
import (
"encoding/json"
"errors"
"io"
"mime"
"net/http"
"regexp"
"strings"
"git.golem15.com/golem15/summercms/modules/backpack"
"git.golem15.com/golem15/summercms/modules/compass"
"git.golem15.com/golem15/summercms/modules/lagoon/attach"
"gocloud.dev/blob"
"gorm.io/gorm"
)
const (
// MediaCacheControl is sent on every immutable /media/<short-id>/<file> response.
MediaCacheControl = "public, max-age=31536000, immutable"
// MediaContentSecurityPolicy sandboxes media files if opened directly as a document.
MediaContentSecurityPolicy = "default-src 'none'; img-src 'self'; media-src 'self'; sandbox"
defaultStaticContentType = "application/octet-stream"
)
var (
shortIDSegmentPattern = regexp.MustCompile(`^[a-z0-9]{10,16}$`)
fileSegmentPattern = regexp.MustCompile(`^[a-z0-9][a-z0-9._-]{0,120}\.[a-z0-9]{1,10}$`)
)
// StaticHandler serves GET and HEAD requests for <prefix>/<short-id>/<file>
// directly from bucket with zero database queries.
//
// Segments are strictly validated before touching bucket: short-id must match
// ^[a-z0-9]{10,16}$ and file must match ^[a-z0-9][a-z0-9._-]{0,120}\.[a-z0-9]{1,10}$
// with no "..", "/", or "\\".
//
// Every response sets X-Content-Type-Options: nosniff and MediaContentSecurityPolicy.
// Successful responses also set Cache-Control: public, max-age=31536000, immutable,
// the stored Content-Type, and Content-Disposition: attachment whenever
// !attach.IsInlineContentType(contentType).
func StaticHandler(bucket *blob.Bucket, prefix string) http.Handler {
prefix = strings.TrimSuffix(strings.TrimSpace(prefix), "/")
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet && r.Method != http.MethodHead {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("Content-Security-Policy", MediaContentSecurityPolicy)
if bucket == nil {
http.NotFound(w, r)
return
}
rel, ok := stripMediaPrefix(r.URL.Path, prefix)
if !ok {
http.NotFound(w, r)
return
}
key, ok := ParsePublicMediaPath(rel)
if !ok {
http.NotFound(w, r)
return
}
attrs, err := bucket.Attributes(r.Context(), key)
if err != nil {
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())
if ct == "" {
ct = defaultStaticContentType
}
w.Header().Set("Cache-Control", MediaCacheControl)
w.Header().Set("Content-Type", ct)
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 {
return
}
_, _ = io.Copy(w, reader)
})
}
// ParsePublicMediaPath validates a relative "<short-id>/<file>" path and returns
// the canonical bucket key "media/<short-id>/<file>".
func ParsePublicMediaPath(rel string) (string, bool) {
if rel == "" || strings.Contains(rel, "\\") || strings.Contains(rel, "..") || strings.Contains(rel, "//") {
return "", false
}
parts := strings.Split(rel, "/")
if len(parts) != 2 {
return "", false
}
shortID, file := parts[0], parts[1]
if !shortIDSegmentPattern.MatchString(shortID) || !fileSegmentPattern.MatchString(file) {
return "", false
}
return BlobKeyPrefix + "/" + shortID + "/" + file, true
}
func stripMediaPrefix(reqPath, prefix string) (string, bool) {
if prefix == "" {
return strings.TrimPrefix(reqPath, "/"), true
}
if reqPath == prefix {
return "", false
}
if strings.HasPrefix(reqPath, prefix+"/") {
return reqPath[len(prefix)+1:], true
}
return "", false
}
func safeDisposition(raw string) string {
v := strings.TrimSpace(raw)
if v == "" {
return ""
}
if _, _, err := mime.ParseMediaType(v); err != nil {
return "attachment"
}
return v
}
// ItemResponse is the JSON representation of an uploaded or fetched media item,
// including resolved public URL and responsive srcset string.
type ItemResponse struct {
ID uint `json:"id"`
ShortID string `json:"short_id"`
FolderID *uint `json:"folder_id"`
BlobKey string `json:"blob_key"`
Slug string `json:"slug"`
FileName string `json:"file_name"`
ContentType string `json:"content_type"`
FileSize int64 `json:"file_size"`
Width *int `json:"width"`
Height *int `json:"height"`
SHA256 string `json:"sha256"`
Alt string `json:"alt"`
Title string `json:"title"`
Caption string `json:"caption"`
URL string `json:"url"`
Srcset string `json:"srcset"`
Variants []Variant `json:"variants"`
UploadedBy *uint `json:"uploaded_by,omitempty"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
// NewItemResponse builds an ItemResponse with resolved URLs and srcset for item.
func NewItemResponse(cfg *compass.Config, item *Item) ItemResponse {
if item == nil {
return ItemResponse{Variants: []Variant{}}
}
variants := make([]Variant, len(item.Variants))
for i, v := range item.Variants {
if v.Key != "" {
v.URL = blobKeyPublicURL(cfg, v.Key)
}
variants[i] = v
}
return ItemResponse{
ID: item.ID,
ShortID: item.ShortID,
FolderID: item.FolderID,
BlobKey: item.BlobKey,
Slug: item.Slug,
FileName: item.FileName,
ContentType: item.ContentType,
FileSize: item.FileSize,
Width: item.Width,
Height: item.Height,
SHA256: item.SHA256,
Alt: item.Alt,
Title: item.Title,
Caption: item.Caption,
URL: item.PublicURL(cfg),
Srcset: item.Srcset(cfg),
Variants: variants,
UploadedBy: item.UploadedBy,
CreatedAt: item.CreatedAt.UTC().Format("2006-01-02T15:04:05Z07:00"),
UpdatedAt: item.UpdatedAt.UTC().Format("2006-01-02T15:04:05Z07:00"),
}
}
// SignedUploadHandler handles raw PUT and POST uploads to <prefix>/upload/{token}.
// It atomically consumes the single-use token before reading bytes, caps the
// request body with http.MaxBytesReader, runs svc.Upload, and responds with
// 201 Created JSON {"data": ItemResponse}.
func SignedUploadHandler(app *backpack.App, svc *Service) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPut && r.Method != http.MethodPost {
writeJSONError(w, http.StatusMethodNotAllowed, "method not allowed")
return
}
if app == nil || svc == nil {
writeJSONError(w, http.StatusServiceUnavailable, "media service unavailable")
return
}
db, ok := app.Lookup[*gorm.DB]()
if !ok || db == nil {
writeJSONError(w, http.StatusServiceUnavailable, "database unavailable")
return
}
bucket, ok := app.Lookup[*blob.Bucket]()
if !ok || bucket == nil {
writeJSONError(w, http.StatusServiceUnavailable, "storage bucket unavailable")
return
}
rawToken := strings.TrimSpace(r.PathValue("token"))
tok, err := svc.ConsumeUploadToken(r.Context(), db, rawToken)
if err != nil {
if errors.Is(err, ErrInvalidUploadToken) {
writeJSONError(w, http.StatusUnauthorized, "upload token is invalid, expired, or already used")
return
}
writeJSONError(w, http.StatusInternalServerError, "failed to verify upload token")
return
}
limit := tok.MaxBytes
cfgMax := MaxBytes(svc.Config())
if limit <= 0 || limit > cfgMax {
limit = cfgMax
}
r.Body = http.MaxBytesReader(w, r.Body, limit)
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,
})
if err != nil {
var maxErr *http.MaxBytesError
switch {
case errors.Is(err, ErrTooLarge) || errors.As(err, &maxErr):
writeJSONError(w, http.StatusRequestEntityTooLarge, "file exceeds maximum allowed size")
case errors.Is(err, ErrFileType) || errors.Is(err, ErrNotImage):
writeJSONError(w, http.StatusUnprocessableEntity, err.Error())
case errors.Is(err, ErrFolderNotFound):
writeJSONError(w, http.StatusNotFound, "folder not found")
default:
writeJSONError(w, http.StatusInternalServerError, "upload failed")
}
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
_ = json.NewEncoder(w).Encode(map[string]any{
"data": NewItemResponse(svc.Config(), item),
})
})
}
func writeJSONError(w http.ResponseWriter, status int, msg string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(map[string]string{"error": msg})
}