Give uploads one path end to end, and serve /uploads/ from Garage first
Frontend: src/uploads.js is the one way to store or show a file (uploadFile, ACCEPT, kindOf, isUploadUrl, tagFor, mediaSize). Chat, the box editor, canvas drops and the background editor all use it; views/home3/upload.js and the chat store's own axios call are gone. Backend: POST /api/uploads (was /messages/upload) is a thin wrapper over services.Uploads.Save, which owns validation, naming and storage. The three per-extension maps are now one UploadTypes table, and a refused file is an *UploadError whose message is safe to show. nginx now fetches /uploads/ from Garage first and falls back to the volume on a 404 or any 5xx, so the bucket is the source of truth and deleting a file in garage-webui unpublishes it, while a Garage outage still only affects bucket-only files. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
@@ -1,146 +0,0 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"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"
|
||||
)
|
||||
|
||||
// Where uploaded files are written. The upload handler
|
||||
// (handlers/handle_message_upload.go) validates a file and picks its name; a
|
||||
// FileStore only stores the bytes under that name.
|
||||
//
|
||||
// Public uploads go to the Garage bucket when S3_ENDPOINT is set, and to the
|
||||
// local `uploads` volume otherwise. Either way they are served at
|
||||
// /uploads/<name>: nginx looks on the volume first and falls back to the
|
||||
// bucket (see the /uploads/ location in nginx.conf.template). That ordering
|
||||
// is what makes every failure here survivable: if Garage is down or
|
||||
// misconfigured, FallbackFileStore writes to disk instead, and nginx finds
|
||||
// the file there without anyone having to know which store took it.
|
||||
|
||||
// FileStore stores one file under key. r is a ReadSeeker because the S3
|
||||
// client must hash the body before sending it over plain HTTP, and because
|
||||
// FallbackFileStore rewinds it to retry; a multipart.File satisfies it.
|
||||
type FileStore interface {
|
||||
Put(ctx context.Context, key, contentType string, r io.ReadSeeker, size int64) error
|
||||
}
|
||||
|
||||
// DiskFileStore writes files into Dir, which must exist.
|
||||
type DiskFileStore struct{ Dir string }
|
||||
|
||||
func (d DiskFileStore) Put(_ context.Context, key, _ string, r io.ReadSeeker, _ int64) error {
|
||||
// 0644 so nginx, a different user, can read what the backend wrote.
|
||||
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()
|
||||
}
|
||||
|
||||
// S3FileStore writes files into one bucket of an S3-compatible server.
|
||||
type S3FileStore struct {
|
||||
client *s3.Client
|
||||
bucket string
|
||||
}
|
||||
|
||||
// S3Config is the S3_* block of .env.
|
||||
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
|
||||
}
|
||||
|
||||
// s3Timeout bounds one upload. Uploads are capped at 10MB and Garage is on
|
||||
// the same Docker network, so anything near this is a hang, and the fallback
|
||||
// to disk is better than holding the request open.
|
||||
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 addresses buckets by path (/bucket/key); virtual-host style
|
||||
// would need a DNS name per bucket.
|
||||
UsePathStyle: true,
|
||||
// Recent SDKs add CRC32 checksums to every PUT by default. Only send
|
||||
// them where S3 requires them, which is what third-party servers
|
||||
// handle reliably.
|
||||
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()
|
||||
|
||||
// ContentType matters: Garage serves back exactly what is stored here,
|
||||
// and nginx no longer infers a type from the extension for files it
|
||||
// fetches from the bucket.
|
||||
_, 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
|
||||
}
|
||||
|
||||
// FallbackFileStore tries Primary and, if that fails, logs it and writes to
|
||||
// Fallback instead. The upload still succeeds and its URL still works, so a
|
||||
// Garage outage costs a log line rather than broken uploads.
|
||||
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)
|
||||
}
|
||||
|
||||
// NewUploadStore picks the store for public uploads. With no S3 endpoint
|
||||
// configured it is the disk alone, exactly the behaviour before Garage, so
|
||||
// deploying this code changes nothing until .env opts in. An endpoint with
|
||||
// missing credentials is a configuration mistake: it is logged and the disk
|
||||
// is used rather than failing every upload.
|
||||
func NewUploadStore(cfg S3Config, diskDir string) FileStore {
|
||||
disk := DiskFileStore{Dir: diskDir}
|
||||
if cfg.Endpoint == "" {
|
||||
log.Printf("[upload] S3_ENDPOINT unset; storing uploads on disk in %s", diskDir)
|
||||
return disk
|
||||
}
|
||||
if 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", diskDir)
|
||||
return disk
|
||||
}
|
||||
log.Printf("[upload] storing uploads in bucket %s at %s (disk fallback: %s)", cfg.Bucket, cfg.Endpoint, diskDir)
|
||||
return FallbackFileStore{Primary: NewS3FileStore(cfg), Fallback: disk}
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Covered here: which store NewUploadStore picks, the disk store, and the
|
||||
// fallback path — including against a real S3 client talking to a server
|
||||
// that refuses the write, since "Garage said no" is the case the fallback
|
||||
// exists for.
|
||||
//
|
||||
// Not covered: a successful PutObject against Garage. That needs the garage
|
||||
// container; it is checked by hand in the stack (see DEPLOYMENT.md, "Garage").
|
||||
|
||||
func TestNewUploadStore(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
|
||||
if _, ok := NewUploadStore(S3Config{}, dir).(DiskFileStore); !ok {
|
||||
t.Error("no S3 endpoint should mean the disk store")
|
||||
}
|
||||
if _, ok := NewUploadStore(S3Config{Endpoint: "http://garage:3900", Bucket: "uploads"}, dir).(DiskFileStore); !ok {
|
||||
t.Error("an endpoint without credentials should fall back to the disk store")
|
||||
}
|
||||
full := S3Config{Endpoint: "http://garage:3900", Region: "garage", Bucket: "uploads", AccessKeyID: "GK0", SecretAccessKey: "s"}
|
||||
if _, ok := NewUploadStore(full, dir).(FallbackFileStore); !ok {
|
||||
t.Error("a full S3 config should mean the bucket with a disk fallback")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiskFileStorePut(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
body := []byte("hello")
|
||||
if err := (DiskFileStore{Dir: dir}).Put(context.Background(), "a.txt", "text/plain", bytes.NewReader(body), int64(len(body))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := os.ReadFile(filepath.Join(dir, "a.txt"))
|
||||
if err != nil || !bytes.Equal(got, body) {
|
||||
t.Fatalf("read back %q, %v; want %q", got, err, body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFallbackWhenBucketRefuses(t *testing.T) {
|
||||
// 403 rather than 500: the SDK retries 5xx with backoff, which would only
|
||||
// make the test slow. Either way PutObject returns an error.
|
||||
var hits int
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
hits++
|
||||
// Drain the body so a test failure can't be a half-read request.
|
||||
_, _ = io.Copy(io.Discard, r.Body)
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
dir := t.TempDir()
|
||||
store := NewUploadStore(S3Config{Endpoint: srv.URL, Region: "garage", Bucket: "uploads", AccessKeyID: "GK0", SecretAccessKey: "s"}, dir)
|
||||
|
||||
body := bytes.Repeat([]byte("x"), 4096)
|
||||
if err := store.Put(context.Background(), "f.bin", "application/octet-stream", bytes.NewReader(body), int64(len(body))); err != nil {
|
||||
t.Fatalf("Put should succeed through the fallback, got %v", err)
|
||||
}
|
||||
if hits == 0 {
|
||||
t.Fatal("the bucket was never tried")
|
||||
}
|
||||
// The whole file, not just what was left after the S3 attempt read it:
|
||||
// this is what the rewind in FallbackFileStore is for.
|
||||
got, err := os.ReadFile(filepath.Join(dir, "f.bin"))
|
||||
if err != nil || !bytes.Equal(got, body) {
|
||||
t.Fatalf("fallback file has %d bytes (%v), want %d", len(got), err, len(body))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"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"
|
||||
)
|
||||
|
||||
// Uploaded files: everything the site stores from a user and serves back at
|
||||
// /uploads/. One entry point for any handler that takes a file:
|
||||
//
|
||||
// url, err := store.Uploads.Save(ctx, fileHeader, private)
|
||||
//
|
||||
// Save validates the file against UploadTypes and MaxUploadSize, gives it a
|
||||
// random name, stores it, and returns the URL to put in the page. An
|
||||
// *UploadError is the uploader's fault and its message is safe to show them;
|
||||
// any other error is ours (log it, answer 500).
|
||||
//
|
||||
// WHERE FILES GO
|
||||
// Public files go to the Garage bucket `uploads` (garage/garage.toml), with
|
||||
// the `uploads` volume as a fallback for when Garage refuses a write. nginx
|
||||
// mirrors that: /uploads/<name> is fetched from the bucket first and the
|
||||
// volume second (nginx.conf.template), so the URL is the same wherever the
|
||||
// file landed. With S3_ENDPOINT unset there is no bucket and the volume is
|
||||
// the only store.
|
||||
// Private files (admin-only chat attachments) always go to the volume, under
|
||||
// /uploads/private/, which nginx gates behind an admin check. nginx can't
|
||||
// sign S3 requests, so it has no way to gate a bucket.
|
||||
//
|
||||
// Everything public is reachable by anyone who has the URL, with no login.
|
||||
// That is why the type checks below are strict, and why names are random.
|
||||
|
||||
// MaxUploadSize caps one upload. It bounds how fast one account can fill the
|
||||
// disk or the bucket; nginx rate-limits the route as well.
|
||||
const MaxUploadSize = 10 << 20 // 10MB
|
||||
|
||||
// UploadType describes one allowed file extension.
|
||||
type UploadType struct {
|
||||
// ContentType is stored with the file and served back with it. Garage
|
||||
// returns exactly this, and the browser renders by it: nginx adds
|
||||
// `nosniff`, so a wrong type means the file doesn't display.
|
||||
ContentType string
|
||||
// SniffPrefix is what http.DetectContentType must report for the file's
|
||||
// first 512 bytes, so that e.g. HTML can't be uploaded as a .png. Empty
|
||||
// means "not checked": DetectContentType is too unreliable for audio and
|
||||
// gif files, and checking would reject legitimate ones.
|
||||
SniffPrefix string
|
||||
}
|
||||
|
||||
// UploadTypes is the allow-list, keyed by lower-cased extension with its dot.
|
||||
// Nothing a browser would execute or render as markup (.html, .svg, .js, ...)
|
||||
// may ever be added: these files are served from our own origin. The
|
||||
// frontend's file pickers (vue/src/uploads.js, ACCEPT) list the same types.
|
||||
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/"},
|
||||
}
|
||||
|
||||
// UploadError is a rejected upload: the uploader's mistake, with a message
|
||||
// meant for them. The handler answers 400 with it.
|
||||
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"}
|
||||
)
|
||||
|
||||
// Uploads stores files. Build it with NewUploads.
|
||||
type Uploads struct {
|
||||
public FileStore
|
||||
private FileStore
|
||||
}
|
||||
|
||||
// URL prefixes the files are served under; nginx owns both paths.
|
||||
const (
|
||||
publicURLPrefix = "/uploads/"
|
||||
privateURLPrefix = "/uploads/private/"
|
||||
)
|
||||
|
||||
// NewUploads picks the stores. publicDir and privateDir are directories on the
|
||||
// shared `uploads` volume (/backend/uploads/ and its private/ subdirectory in
|
||||
// the container).
|
||||
//
|
||||
// With no S3 endpoint the public store is the volume alone, the behaviour
|
||||
// before Garage. An endpoint with missing credentials is a configuration
|
||||
// mistake: it is logged and the volume is used rather than failing every
|
||||
// upload.
|
||||
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 validates and stores one uploaded file and returns its URL
|
||||
// (/uploads/<name>, or /uploads/private/<name>). Authorisation is the
|
||||
// caller's job: only an admin may save a private file.
|
||||
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 != "" {
|
||||
// 512 bytes is all http.DetectContentType looks at. A short read is
|
||||
// fine; sniffing works on a prefix, so only an empty file is an error.
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
// The uploaded name is thrown away for 16 random bytes. That rules out
|
||||
// path traversal and collisions in one go, and makes the URL unguessable.
|
||||
// Only the extension survives, and it is on the allow-list.
|
||||
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
|
||||
}
|
||||
|
||||
// ---- Stores ----------------------------------------------------------------
|
||||
|
||||
// FileStore stores one file under key. r is a ReadSeeker because the S3
|
||||
// client must hash the body before sending it over plain HTTP, and because
|
||||
// FallbackFileStore rewinds it to retry; a multipart.File satisfies it.
|
||||
type FileStore interface {
|
||||
Put(ctx context.Context, key, contentType string, r io.ReadSeeker, size int64) error
|
||||
}
|
||||
|
||||
// DiskFileStore writes files into Dir, creating it if needed.
|
||||
type DiskFileStore struct{ Dir string }
|
||||
|
||||
func (d DiskFileStore) Put(_ context.Context, key, _ string, r io.ReadSeeker, _ int64) error {
|
||||
// 0755 and 0644 so nginx, a different user, can reach and read the files.
|
||||
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()
|
||||
}
|
||||
|
||||
// S3FileStore writes files into one bucket of an S3-compatible server.
|
||||
type S3FileStore struct {
|
||||
client *s3.Client
|
||||
bucket string
|
||||
}
|
||||
|
||||
// S3Config is the S3_* block of .env.
|
||||
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
|
||||
}
|
||||
|
||||
// s3Timeout bounds one upload. Uploads are capped at 10MB and Garage is on
|
||||
// the same Docker network, so anything near this is a hang, and the fallback
|
||||
// to disk is better than holding the request open.
|
||||
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 addresses buckets by path (/bucket/key); virtual-host style
|
||||
// would need a DNS name per bucket.
|
||||
UsePathStyle: true,
|
||||
// Recent SDKs add CRC32 checksums to every PUT by default. Only send
|
||||
// them where S3 requires them, which is what third-party servers
|
||||
// handle reliably.
|
||||
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
|
||||
}
|
||||
|
||||
// FallbackFileStore tries Primary and, if that fails, logs it and writes to
|
||||
// Fallback instead. The upload still succeeds and its URL still works (nginx
|
||||
// looks in both places), so a Garage outage costs a log line rather than
|
||||
// broken uploads.
|
||||
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)
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"image"
|
||||
"image/png"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Covered here: the type table (the upload trust boundary's data), Save's
|
||||
// validation, naming and routing, which store NewUploads picks, and the
|
||||
// fallback — including against a real S3 client talking to a server that
|
||||
// refuses the write, since "Garage said no" is the case it exists for.
|
||||
//
|
||||
// Not covered: a successful PutObject against Garage. That needs the garage
|
||||
// container; it is checked by hand in the stack (DEPLOYMENT.md, "Garage").
|
||||
|
||||
// fileHeader builds the *multipart.FileHeader a handler would get from
|
||||
// ctx.FormFile, by round-tripping a real multipart body.
|
||||
func fileHeader(t *testing.T, name string, content []byte) *multipart.FileHeader {
|
||||
t.Helper()
|
||||
var body bytes.Buffer
|
||||
w := multipart.NewWriter(&body)
|
||||
part, _ := w.CreateFormFile("file", name)
|
||||
part.Write(content)
|
||||
w.Close()
|
||||
form, err := multipart.NewReader(&body, w.Boundary()).ReadForm(32 << 20)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { form.RemoveAll() })
|
||||
return form.File["file"][0]
|
||||
}
|
||||
|
||||
func pngBytes() []byte {
|
||||
var b bytes.Buffer
|
||||
png.Encode(&b, image.NewRGBA(image.Rect(0, 0, 2, 2)))
|
||||
return b.Bytes()
|
||||
}
|
||||
|
||||
// recordingStore remembers what it was asked to store.
|
||||
type recordingStore struct {
|
||||
key, contentType string
|
||||
body []byte
|
||||
}
|
||||
|
||||
func (r *recordingStore) Put(_ context.Context, key, contentType string, rd io.ReadSeeker, _ int64) error {
|
||||
r.key, r.contentType = key, contentType
|
||||
r.body, _ = io.ReadAll(rd)
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestUploadTypes(t *testing.T) {
|
||||
t.Run("nothing executable or markup is allowed", func(t *testing.T) {
|
||||
// Served from our own origin with no login, so anything a browser
|
||||
// would run or render as a page must never be storable.
|
||||
for _, ext := range []string{".html", ".htm", ".svg", ".js", ".mjs", ".php", ".exe", ".sh", ".xml", ".xhtml", ""} {
|
||||
if _, ok := UploadTypes[ext]; ok {
|
||||
t.Errorf("%q must not be an allowed upload type", ext)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
for ext, kind := range UploadTypes {
|
||||
if ext == "" || ext[0] != '.' || ext != strings.ToLower(ext) {
|
||||
t.Errorf("key %q: Save looks up the lower-cased extension with its dot, so this is unreachable", ext)
|
||||
}
|
||||
if kind.ContentType == "" {
|
||||
// Stored and served as-is; under nosniff an empty type renders nothing.
|
||||
t.Errorf("%q has no ContentType", ext)
|
||||
}
|
||||
}
|
||||
|
||||
t.Run("audio and gif are not sniffed", func(t *testing.T) {
|
||||
// DetectContentType misreads these; checking them would reject
|
||||
// legitimate files.
|
||||
for _, ext := range []string{".mp3", ".ogg", ".gif"} {
|
||||
if UploadTypes[ext].SniffPrefix != "" {
|
||||
t.Errorf("%q should not be content-checked", ext)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestUploadsSave(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
public, private := &recordingStore{}, &recordingStore{}
|
||||
u := &Uploads{public: public, private: private}
|
||||
|
||||
t.Run("public file", func(t *testing.T) {
|
||||
img := pngBytes()
|
||||
url, err := u.Save(ctx, fileHeader(t, "Holiday Photo.PNG", img), false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// The name is replaced by 32 hex chars; the lower-cased extension stays.
|
||||
if !strings.HasPrefix(url, "/uploads/") || len(strings.TrimPrefix(url, "/uploads/")) != 32+len(".png") || !strings.HasSuffix(url, ".png") {
|
||||
t.Errorf("url = %q, want /uploads/<32 hex>.png", url)
|
||||
}
|
||||
if public.key != strings.TrimPrefix(url, "/uploads/") || public.contentType != "image/png" {
|
||||
t.Errorf("stored as %q (%q)", public.key, public.contentType)
|
||||
}
|
||||
// The whole file, not just what was left after sniffing.
|
||||
if !bytes.Equal(public.body, img) {
|
||||
t.Errorf("stored %d bytes, want %d", len(public.body), len(img))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("private file goes to the private store", func(t *testing.T) {
|
||||
url, err := u.Save(ctx, fileHeader(t, "note.txt", []byte("hello")), true)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.HasPrefix(url, "/uploads/private/") || private.key == "" {
|
||||
t.Errorf("url = %q, private store got %q", url, private.key)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("rejections", func(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
file string
|
||||
content []byte
|
||||
want error
|
||||
}{
|
||||
{"disallowed type", "page.html", []byte("<html></html>"), ErrUploadType},
|
||||
{"markup dressed as an image", "evil.png", []byte("<html><script>alert(1)</script></html>"), ErrUploadContent},
|
||||
{"empty sniffed file", "empty.png", nil, ErrUploadUnreadable},
|
||||
{"too large", "big.mp3", make([]byte, MaxUploadSize+1), ErrUploadTooLarge},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
_, err := u.Save(ctx, fileHeader(t, c.file, c.content), false)
|
||||
if !errors.Is(err, c.want) {
|
||||
t.Errorf("err = %v, want %v", err, c.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestNewUploads(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
|
||||
if _, ok := NewUploads(S3Config{}, dir, dir).public.(DiskFileStore); !ok {
|
||||
t.Error("no S3 endpoint should mean the disk store")
|
||||
}
|
||||
if _, ok := NewUploads(S3Config{Endpoint: "http://garage:3900", Bucket: "uploads"}, dir, dir).public.(DiskFileStore); !ok {
|
||||
t.Error("an endpoint without credentials should fall back to the disk store")
|
||||
}
|
||||
full := S3Config{Endpoint: "http://garage:3900", Region: "garage", Bucket: "uploads", AccessKeyID: "GK0", SecretAccessKey: "s"}
|
||||
u := NewUploads(full, dir, dir)
|
||||
if _, ok := u.public.(FallbackFileStore); !ok {
|
||||
t.Error("a full S3 config should mean the bucket with a disk fallback")
|
||||
}
|
||||
if _, ok := u.private.(DiskFileStore); !ok {
|
||||
t.Error("private files must always stay on disk")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDiskFileStorePut(t *testing.T) {
|
||||
// A directory that doesn't exist yet: the private one is created on demand.
|
||||
dir := filepath.Join(t.TempDir(), "private")
|
||||
body := []byte("hello")
|
||||
if err := (DiskFileStore{Dir: dir}).Put(context.Background(), "a.txt", "text/plain", bytes.NewReader(body), int64(len(body))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := os.ReadFile(filepath.Join(dir, "a.txt"))
|
||||
if err != nil || !bytes.Equal(got, body) {
|
||||
t.Fatalf("read back %q, %v; want %q", got, err, body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFallbackWhenBucketRefuses(t *testing.T) {
|
||||
// 403 rather than 500: the SDK retries 5xx with backoff, which would only
|
||||
// make the test slow. Either way PutObject returns an error.
|
||||
var hits int
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
hits++
|
||||
_, _ = io.Copy(io.Discard, r.Body)
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
dir := t.TempDir()
|
||||
u := NewUploads(S3Config{Endpoint: srv.URL, Region: "garage", Bucket: "uploads", AccessKeyID: "GK0", SecretAccessKey: "s"}, dir, filepath.Join(dir, "private"))
|
||||
|
||||
img := pngBytes()
|
||||
url, err := u.Save(context.Background(), fileHeader(t, "pic.png", img), false)
|
||||
if err != nil {
|
||||
t.Fatalf("Save should succeed through the fallback, got %v", err)
|
||||
}
|
||||
if hits == 0 {
|
||||
t.Fatal("the bucket was never tried")
|
||||
}
|
||||
// The whole file, not just what the S3 attempt left unread: this is what
|
||||
// the rewind in FallbackFileStore is for.
|
||||
got, err := os.ReadFile(filepath.Join(dir, strings.TrimPrefix(url, "/uploads/")))
|
||||
if err != nil || !bytes.Equal(got, img) {
|
||||
t.Fatalf("fallback file has %d bytes (%v), want %d", len(got), err, len(img))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user