Files
adamfandClaude Opus 5.5 4530cb8dc4
Test and deploy / test (push) Successful in 28s
Test and deploy / deploy (push) Successful in 31s
Trim comments to the non-obvious why
Drop narration, history and restated-code comments across the repo,
keep short ones for security boundaries, upstream quirks and ordering
constraints, and record the convention in CLAUDE.md.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 20:49:03 +00:00

338 lines
10 KiB
Go

package services
import (
"context"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"io"
"io/fs"
"log"
"mime/multipart"
"net/http"
"os"
"path/filepath"
"sort"
"strings"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/credentials"
"github.com/aws/aws-sdk-go-v2/service/s3"
)
// Every stored file goes through Uploads.Save. An *UploadError is the
// uploader's fault and safe to show; any other error is ours.
// Public files go to Garage, falling back to the volume; private files
// always go to the volume, because Caddy can gate a path but can't sign S3.
const MaxUploadSize = 10 << 20 // 10MB
// UploadType describes one allowed file extension.
type UploadType struct {
// Served back as-is, and Caddy sends nosniff, so it must be right.
ContentType string
// What http.DetectContentType must report. Empty skips the check, which
// is unreliable for audio and gif.
SniffPrefix string
}
// UploadTypes is the allow-list. Never add anything a browser would execute
// or render as markup: these are served from our origin. Mirrored by
// vue/src/uploads.js's ACCEPT.
var UploadTypes = map[string]UploadType{
".jpg": {ContentType: "image/jpeg", SniffPrefix: "image/"},
".jpeg": {ContentType: "image/jpeg", SniffPrefix: "image/"},
".png": {ContentType: "image/png", SniffPrefix: "image/"},
".gif": {ContentType: "image/gif"},
".webp": {ContentType: "image/webp", SniffPrefix: "image/"},
".mp4": {ContentType: "video/mp4", SniffPrefix: "video/"},
".webm": {ContentType: "video/webm", SniffPrefix: "video/"},
".mp3": {ContentType: "audio/mpeg"},
".ogg": {ContentType: "audio/ogg"},
".pdf": {ContentType: "application/pdf", SniffPrefix: "application/pdf"},
".txt": {ContentType: "text/plain; charset=utf-8", SniffPrefix: "text/"},
}
type UploadError struct{ Message string }
func (e *UploadError) Error() string { return e.Message }
var (
ErrUploadTooLarge = &UploadError{"file too large (the limit is 10MB)"}
ErrUploadType = &UploadError{"file type not allowed"}
ErrUploadContent = &UploadError{"file content does not match extension"}
ErrUploadUnreadable = &UploadError{"failed to read file content"}
)
type Uploads struct {
public FileStore
private FileStore
}
const (
publicURLPrefix = "/uploads/"
privateURLPrefix = "/uploads/private/"
)
// NewUploads falls back to the volume alone when S3 is unset or misconfigured.
func NewUploads(cfg S3Config, publicDir, privateDir string) *Uploads {
disk := DiskFileStore{Dir: publicDir}
u := &Uploads{public: disk, private: DiskFileStore{Dir: privateDir}}
switch {
case cfg.Endpoint == "":
log.Printf("[upload] S3_ENDPOINT unset; storing uploads on disk in %s", publicDir)
case cfg.AccessKeyID == "" || cfg.SecretAccessKey == "" || cfg.Bucket == "":
log.Printf("[upload] S3_ENDPOINT is set but S3_BUCKET or the S3 key is missing; storing uploads on disk in %s", publicDir)
default:
log.Printf("[upload] storing uploads in bucket %s at %s (disk fallback: %s)", cfg.Bucket, cfg.Endpoint, publicDir)
u.public = FallbackFileStore{Primary: NewS3FileStore(cfg), Fallback: disk}
}
return u
}
// Save stores one file and returns its URL. Only admins may save private files.
func (u *Uploads) Save(ctx context.Context, fh *multipart.FileHeader, private bool) (string, error) {
if fh.Size > MaxUploadSize {
return "", ErrUploadTooLarge
}
ext := strings.ToLower(filepath.Ext(fh.Filename))
kind, ok := UploadTypes[ext]
if !ok {
return "", ErrUploadType
}
f, err := fh.Open()
if err != nil {
return "", fmt.Errorf("opening upload: %w", err)
}
defer f.Close()
if kind.SniffPrefix != "" {
// A short read is fine; only an empty file fails.
buf := make([]byte, 512)
n, err := io.ReadFull(f, buf)
if n == 0 {
return "", ErrUploadUnreadable
}
if err != nil && err != io.ErrUnexpectedEOF {
return "", fmt.Errorf("reading upload: %w", err)
}
if !strings.HasPrefix(http.DetectContentType(buf[:n]), kind.SniffPrefix) {
return "", ErrUploadContent
}
if _, err := f.Seek(0, io.SeekStart); err != nil {
return "", fmt.Errorf("rewinding upload: %w", err)
}
}
// A random name rules out traversal and collisions, and makes the URL
// unguessable.
b := make([]byte, 16)
if _, err := rand.Read(b); err != nil {
return "", fmt.Errorf("generating filename: %w", err)
}
name := hex.EncodeToString(b) + ext
store, prefix := u.public, publicURLPrefix
if private {
store, prefix = u.private, privateURLPrefix
}
if err := store.Put(ctx, name, kind.ContentType, f, fh.Size); err != nil {
return "", err
}
return prefix + name, nil
}
type StoredFile struct {
Name string `json:"name"`
URL string `json:"url"`
Size int64 `json:"size"`
Modified time.Time `json:"modified"`
}
// List returns public uploads, newest first. Admin only: unguessable URLs are
// the only protection for unlinked files. Off-list extensions are dropped.
func (u *Uploads) List(ctx context.Context) ([]StoredFile, error) {
files, err := u.public.List(ctx)
if err != nil {
return nil, err
}
out := files[:0]
for _, f := range files {
if _, ok := UploadTypes[strings.ToLower(filepath.Ext(f.Name))]; ok {
f.URL = publicURLPrefix + f.Name
out = append(out, f)
}
}
sort.Slice(out, func(i, j int) bool { return out[i].Modified.After(out[j].Modified) })
return out, nil
}
// ---- Stores ----------------------------------------------------------------
// FileStore takes a ReadSeeker because S3 hashes the body before sending and
// FallbackFileStore rewinds it to retry. List returns top-level files only.
type FileStore interface {
Put(ctx context.Context, key, contentType string, r io.ReadSeeker, size int64) error
List(ctx context.Context) ([]StoredFile, error)
}
type DiskFileStore struct{ Dir string }
func (d DiskFileStore) Put(_ context.Context, key, _ string, r io.ReadSeeker, _ int64) error {
// World-readable so Caddy, in another container, can serve them.
if err := os.MkdirAll(d.Dir, 0755); err != nil {
return err
}
out, err := os.OpenFile(filepath.Join(d.Dir, key), os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return err
}
if _, err := io.Copy(out, r); err != nil {
out.Close()
return err
}
return out.Close()
}
// List skips directories, which keeps private/ out of the listing.
func (d DiskFileStore) List(_ context.Context) ([]StoredFile, error) {
entries, err := os.ReadDir(d.Dir)
if errors.Is(err, fs.ErrNotExist) {
return nil, nil
}
if err != nil {
return nil, err
}
var files []StoredFile
for _, e := range entries {
if !e.Type().IsRegular() {
continue
}
info, err := e.Info()
if err != nil {
continue // deleted between ReadDir and here
}
files = append(files, StoredFile{Name: e.Name(), Size: info.Size(), Modified: info.ModTime()})
}
return files, nil
}
type S3FileStore struct {
client *s3.Client
bucket string
}
type S3Config struct {
Endpoint string // e.g. http://garage:3900
Region string // must match garage.toml's s3_region
Bucket string
AccessKeyID string
SecretAccessKey string
}
// Garage is on the same network, so anything near this is a hang.
const s3Timeout = 30 * time.Second
func NewS3FileStore(cfg S3Config) *S3FileStore {
client := s3.New(s3.Options{
BaseEndpoint: aws.String(cfg.Endpoint),
Region: cfg.Region,
Credentials: credentials.NewStaticCredentialsProvider(cfg.AccessKeyID, cfg.SecretAccessKey, ""),
// Garage needs path-style addressing.
UsePathStyle: true,
// Default CRC32 checksums aren't reliably supported by non-AWS servers.
RequestChecksumCalculation: aws.RequestChecksumCalculationWhenRequired,
ResponseChecksumValidation: aws.ResponseChecksumValidationWhenRequired,
})
return &S3FileStore{client: client, bucket: cfg.Bucket}
}
func (s *S3FileStore) Put(ctx context.Context, key, contentType string, r io.ReadSeeker, size int64) error {
ctx, cancel := context.WithTimeout(ctx, s3Timeout)
defer cancel()
_, err := s.client.PutObject(ctx, &s3.PutObjectInput{
Bucket: aws.String(s.bucket),
Key: aws.String(key),
Body: r,
ContentLength: aws.Int64(size),
ContentType: aws.String(contentType),
})
if err != nil {
return fmt.Errorf("s3 put %s/%s: %w", s.bucket, key, err)
}
return nil
}
// List skips keys under a prefix: those were put there by hand.
func (s *S3FileStore) List(ctx context.Context) ([]StoredFile, error) {
ctx, cancel := context.WithTimeout(ctx, s3Timeout)
defer cancel()
var files []StoredFile
pages := s3.NewListObjectsV2Paginator(s.client, &s3.ListObjectsV2Input{Bucket: aws.String(s.bucket)})
for pages.HasMorePages() {
page, err := pages.NextPage(ctx)
if err != nil {
return nil, fmt.Errorf("s3 list %s: %w", s.bucket, err)
}
for _, obj := range page.Contents {
key := aws.ToString(obj.Key)
if key == "" || strings.Contains(key, "/") {
continue
}
files = append(files, StoredFile{Name: key, Size: aws.ToInt64(obj.Size), Modified: aws.ToTime(obj.LastModified)})
}
}
return files, nil
}
// FallbackFileStore writes to Fallback when Primary fails. Caddy serves from
// both, so the URL still works.
type FallbackFileStore struct {
Primary FileStore
Fallback FileStore
}
func (f FallbackFileStore) Put(ctx context.Context, key, contentType string, r io.ReadSeeker, size int64) error {
err := f.Primary.Put(ctx, key, contentType, r, size)
if err == nil {
return nil
}
log.Printf("[upload] primary store failed, writing %s to fallback: %v", key, err)
if _, seekErr := r.Seek(0, io.SeekStart); seekErr != nil {
return fmt.Errorf("rewinding for fallback after %v: %w", err, seekErr)
}
return f.Fallback.Put(ctx, key, contentType, r, size)
}
// List merges both stores, primary first, since Caddy serves from both.
func (f FallbackFileStore) List(ctx context.Context) ([]StoredFile, error) {
primary, err := f.Primary.List(ctx)
if err != nil {
log.Printf("[upload] primary store failed to list, listing fallback only: %v", err)
primary = nil
}
fallback, fbErr := f.Fallback.List(ctx)
if fbErr != nil {
if err != nil {
return nil, fmt.Errorf("listing both stores: %v; %w", err, fbErr)
}
log.Printf("[upload] fallback store failed to list: %v", fbErr)
}
seen := make(map[string]bool, len(primary))
for _, file := range primary {
seen[file.Name] = true
}
for _, file := range fallback {
if !seen[file.Name] {
primary = append(primary, file)
}
}
return primary, nil
}