157 lines
4.7 KiB
Go
157 lines
4.7 KiB
Go
package album
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"crypto/sha256"
|
|
"encoding/base64"
|
|
"encoding/hex"
|
|
"fmt"
|
|
"path"
|
|
"slices"
|
|
"strings"
|
|
"time"
|
|
|
|
"git.golem15.com/golem15/summercms/modules/lagoon/attach"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
// PrepareUploadInput describes a request to mint a single-use upload token.
|
|
type PrepareUploadInput struct {
|
|
CreatedBy uint
|
|
FolderID *uint
|
|
ExpectedFilename string
|
|
ExpectedContentType string
|
|
// MaxBytes caps the upload for this token; 0 defaults to MaxBytes(cfg).
|
|
// Values larger than MaxBytes(cfg) are rejected with ErrTooLarge.
|
|
MaxBytes int64
|
|
// TTL overrides DefaultUploadTokenTTL (5 minutes) when positive.
|
|
TTL time.Duration
|
|
}
|
|
|
|
// PreparedUpload is returned by PrepareUpload and contains the opaque one-time
|
|
// token (never stored in plaintext in Postgres) and its constraints.
|
|
type PreparedUpload struct {
|
|
Token string `json:"token"`
|
|
TokenID uint `json:"token_id"`
|
|
ExpiresAt time.Time `json:"expires_at"`
|
|
MaxBytes int64 `json:"max_bytes"`
|
|
ExpectedFilename string `json:"expected_filename"`
|
|
ExpectedContentType string `json:"expected_content_type,omitempty"`
|
|
FolderID *uint `json:"folder_id,omitempty"`
|
|
}
|
|
|
|
// PrepareUpload validates the expected filename/type/size constraints, generates
|
|
// a 32-byte cryptographically random base64url token, stores only its SHA-256
|
|
// hex hash in summer_media_upload_tokens, and returns the opaque token.
|
|
func (s *Service) PrepareUpload(ctx context.Context, db *gorm.DB, in PrepareUploadInput) (*PreparedUpload, error) {
|
|
if ctx == nil {
|
|
ctx = context.Background()
|
|
}
|
|
if db == nil {
|
|
return nil, fmt.Errorf("album: db is nil")
|
|
}
|
|
|
|
name := clientBaseName(in.ExpectedFilename)
|
|
ext := strings.ToLower(strings.TrimPrefix(path.Ext(name), "."))
|
|
if !extPattern.MatchString(ext) || !slices.Contains(attach.DefaultFileExtensions, ext) {
|
|
return nil, fmt.Errorf("%w: %q", ErrFileType, ext)
|
|
}
|
|
|
|
expectedCT := baseMediaType(in.ExpectedContentType)
|
|
if expectedCT != "" && slices.Contains(disallowedSniffed, expectedCT) {
|
|
return nil, fmt.Errorf("%w: %s", ErrFileType, expectedCT)
|
|
}
|
|
|
|
cfgMax := MaxBytes(s.Config())
|
|
maxBytes := in.MaxBytes
|
|
if maxBytes <= 0 {
|
|
maxBytes = cfgMax
|
|
}
|
|
if maxBytes > cfgMax {
|
|
return nil, ErrTooLarge
|
|
}
|
|
|
|
if in.FolderID != nil {
|
|
var count int64
|
|
if err := db.WithContext(ctx).Model(&Folder{}).Where("id = ?", *in.FolderID).Count(&count).Error; err != nil {
|
|
return nil, fmt.Errorf("album: check folder: %w", err)
|
|
}
|
|
if count == 0 {
|
|
return nil, ErrFolderNotFound
|
|
}
|
|
}
|
|
|
|
ttl := in.TTL
|
|
if ttl <= 0 {
|
|
ttl = DefaultUploadTokenTTL
|
|
}
|
|
|
|
rawBytes := make([]byte, 32)
|
|
if _, err := rand.Read(rawBytes); err != nil {
|
|
return nil, fmt.Errorf("album: generate upload token: %w", err)
|
|
}
|
|
rawToken := base64.RawURLEncoding.EncodeToString(rawBytes)
|
|
expiresAt := time.Now().UTC().Add(ttl)
|
|
|
|
row := &UploadToken{
|
|
TokenHash: hashUploadToken(rawToken),
|
|
CreatedBy: in.CreatedBy,
|
|
FolderID: in.FolderID,
|
|
ExpectedFilename: name,
|
|
ExpectedContentType: expectedCT,
|
|
MaxBytes: maxBytes,
|
|
ExpiresAt: expiresAt,
|
|
}
|
|
if err := db.WithContext(ctx).Create(row).Error; err != nil {
|
|
return nil, fmt.Errorf("album: insert upload token: %w", err)
|
|
}
|
|
|
|
return &PreparedUpload{
|
|
Token: rawToken,
|
|
TokenID: row.ID,
|
|
ExpiresAt: row.ExpiresAt,
|
|
MaxBytes: row.MaxBytes,
|
|
ExpectedFilename: row.ExpectedFilename,
|
|
ExpectedContentType: row.ExpectedContentType,
|
|
FolderID: row.FolderID,
|
|
}, nil
|
|
}
|
|
|
|
// ConsumeUploadToken atomically marks a matching unused, unexpired upload token
|
|
// as used (used_at = NOW()) in a single SQL UPDATE ... RETURNING statement so
|
|
// concurrent or replayed requests cannot consume the same token twice.
|
|
func (s *Service) ConsumeUploadToken(ctx context.Context, db *gorm.DB, rawToken string) (*UploadToken, error) {
|
|
if ctx == nil {
|
|
ctx = context.Background()
|
|
}
|
|
if db == nil {
|
|
return nil, fmt.Errorf("album: db is nil")
|
|
}
|
|
rawToken = strings.TrimSpace(rawToken)
|
|
if rawToken == "" {
|
|
return nil, ErrInvalidUploadToken
|
|
}
|
|
|
|
var tok UploadToken
|
|
res := db.WithContext(ctx).Raw(
|
|
`UPDATE `+UploadTokensTable+`
|
|
SET used_at = NOW()
|
|
WHERE token_hash = ? AND used_at IS NULL AND expires_at > NOW()
|
|
RETURNING id, token_hash, created_by, folder_id, expected_filename, expected_content_type, max_bytes, expires_at, used_at, created_at`,
|
|
hashUploadToken(rawToken),
|
|
).Scan(&tok)
|
|
if res.Error != nil {
|
|
return nil, fmt.Errorf("album: consume upload token: %w", res.Error)
|
|
}
|
|
if res.RowsAffected == 0 || tok.ID == 0 {
|
|
return nil, ErrInvalidUploadToken
|
|
}
|
|
return &tok, nil
|
|
}
|
|
|
|
func hashUploadToken(raw string) string {
|
|
sum := sha256.Sum256([]byte(raw))
|
|
return hex.EncodeToString(sum[:])
|
|
}
|