Store public uploads in a Garage S3 bucket, with garage-webui at /garage/
Opt-in and built so Garage can never take the site down: - the backend writes to the bucket only once S3_ENDPOINT is set, and falls back to the uploads volume (with a log line) if a write fails; - nginx serves /uploads/ from the volume first and Garage's anonymous website endpoint second, so every existing URL keeps working and nginx boots with no garage container; - nothing depends_on garage and no variable is required, so a missing secret cannot fail a deploy. Private attachments stay on disk, since nginx cannot gate a bucket. garage/bootstrap.sh sets up the layout, bucket, key and website access; the runbook is "Garage" in DEPLOYMENT.md. Also lifts the body limit on the internal auth subrequest, which 413'd large uploads to gated locations, and reserves the garage and dozzle page slugs. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
@@ -226,6 +226,12 @@ dormant, which is why callers nil-check `Store.SpotifyClient` and friends.
|
||||
(Steam).
|
||||
- **python_call.go** — `CallPython`, the one way to reach the Python service's
|
||||
internal routes. See [Calling the Python service](#calling-the-python-service).
|
||||
- **file_store.go** — where public uploads are written. `NewUploadStore`
|
||||
returns the disk store (`/backend/uploads/`) when `S3_ENDPOINT` is unset,
|
||||
and otherwise the Garage bucket wrapped in `FallbackFileStore`, which logs
|
||||
a failed S3 write and retries on disk. nginx serves `/uploads/` from disk
|
||||
first and the bucket second, so either store's files work at the same URL.
|
||||
Private attachments always stay on disk (nginx cannot gate a bucket).
|
||||
- **notes.go** — path-traversal-safe file lookup for the notes directory.
|
||||
- **seed.go** — dev-only test data. Creates an admin with the password
|
||||
`password`, so it must never run in production (`SEED_DB=true` is set only
|
||||
|
||||
@@ -4,6 +4,9 @@ go 1.26
|
||||
|
||||
require (
|
||||
github.com/99designs/gqlgen v0.17.95
|
||||
github.com/aws/aws-sdk-go-v2 v1.47.3
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.20.9
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.3
|
||||
github.com/gin-gonic/gin v1.11.0
|
||||
github.com/golang-jwt/jwt/v5 v5.3.0
|
||||
github.com/gorilla/websocket v1.5.3
|
||||
@@ -18,6 +21,15 @@ require (
|
||||
|
||||
require (
|
||||
github.com/agnivade/levenshtein v1.2.1 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.22 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.6 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.6 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.6 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.21 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.7 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.6 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.6 // indirect
|
||||
github.com/aws/smithy-go v1.28.5 // indirect
|
||||
github.com/bytedance/sonic v1.14.0 // indirect
|
||||
github.com/bytedance/sonic/loader v0.3.0 // indirect
|
||||
github.com/cloudwego/base64x v0.1.6 // indirect
|
||||
|
||||
@@ -39,6 +39,30 @@ github.com/agnivade/levenshtein v1.2.1 h1:EHBY3UOn1gwdy/VbFwgo4cxecRznFk7fKWN1KO
|
||||
github.com/agnivade/levenshtein v1.2.1/go.mod h1:QVVI16kDrtSuwcpd0p1+xMC6Z/VfhtCyDIjcwga4/DU=
|
||||
github.com/arbovm/levenshtein v0.0.0-20160628152529-48b4e1c0c4d0 h1:jfIu9sQUG6Ig+0+Ap1h4unLjW6YQJpKZVmUzxsD4E/Q=
|
||||
github.com/arbovm/levenshtein v0.0.0-20160628152529-48b4e1c0c4d0/go.mod h1:t2tdKJDJF9BV14lnkjHmOQgcvEKgtqs5a1N3LNdJhGE=
|
||||
github.com/aws/aws-sdk-go-v2 v1.47.3 h1:HRoT/MkNi3bjO5xF4dCzLzvVmkvRGHj3/cLINDnJejk=
|
||||
github.com/aws/aws-sdk-go-v2 v1.47.3/go.mod h1:xSl+OSI5ZUw6bSMupWc218zE5Pl+65MCCu3ySWFY99A=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.22 h1:oiEmPz/YMMeh/JvAE8xSxNCIsvWE6lpFe4ZPlyFykQI=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.22/go.mod h1:QWUDuRi9PFjBHIU2iH1Pkldbe7zqLfXJC4wWLbF8nuQ=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.20.9 h1:SNO55PnWhaDafsOcv16lCA0kdoFMl/YlegWoVsU02s0=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.20.9/go.mod h1:+2reOTRtdD3VSBqpRDNwrZIYy8yMCYa7oK3WKTJ/I1I=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.6 h1:CqL8NN3p4I0JTwwV5MEoatIl4Y2amZ2X9dRD+0hbRL0=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.5.6/go.mod h1:exdJ32hMqXl0Wyo6NwqEC5yIhtua3+PDaKE8P29m4qE=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.6 h1:FpBq24TG6WVSObTNhQOv7Q0088rounUUlwn3zlNItkM=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.8.6/go.mod h1:ONzdPVYC95oBOu0VWNEsKEntcoemP3xVKjT+qWml1s4=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.6 h1:Qmn60RWuk9+bd2ddvJJqwf3Cpac3VvGMOdbGemtUhX4=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.5.6/go.mod h1:h/YJhe4AVyQxEUMluph10iqV7mjajH7A9L+BHF5ppis=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.21 h1:e6YW5uME30TkrElR+4/xcY7NB6CCj2dcv7vtmGXhfhQ=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.21/go.mod h1:obpHAMP693+f3/A8PkLhIqfK1C+NWWn8zXzqD3OH520=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.7 h1:CwvFlKw0uUScfgOMflXSRZa+ayXgOf6wk7lhyMemQYU=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.11.7/go.mod h1:4SbD8BB+p+QEnG0aX6DoWwrtk9SufyYXRsUv0nve8LE=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.6 h1:LHHdobjo5le1sjJdolitV7uVvYg3wkaeM1Ju2fDgeZQ=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.6/go.mod h1:CBGB0evAiaMD3Lk4wPO7LQCcCZLuhzL5Qf/wfEUHQ5w=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.6 h1:mYViDr2azcgxOpRrObZOl631bvavqILoE/L+Kxgbwys=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.6/go.mod h1:OXVdAo9jNhggB+hJRGOyy7WolGTKB6Rg7IIulDeSzPM=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.3 h1:NyeuyXkZL476uoAowNActm4XJO1QPKf7aassgXHpiqA=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.114.3/go.mod h1:GfoBeKMDJecgRUsGf/0RGdx0NJAh81ObTd922h8pQys=
|
||||
github.com/aws/smithy-go v1.28.5 h1:OqbqKtzY9NUnr2yAe9+hiTdFb20tNaK/lI0PMOGXX9k=
|
||||
github.com/aws/smithy-go v1.28.5/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
|
||||
github.com/bytedance/sonic v1.14.0 h1:/OfKt8HFw0kh2rj8N0F6C/qPGRESq0BbaNZgcNXXzQQ=
|
||||
github.com/bytedance/sonic v1.14.0/go.mod h1:WoEbx8WTcFJfzCe0hbmyTGrfjt8PzNEBdxlNUO24NhA=
|
||||
github.com/bytedance/sonic/loader v0.3.0 h1:dskwH8edlzNMctoruo8FPTJDF3vLtDT0sXZwvZJyqeA=
|
||||
|
||||
@@ -32,7 +32,7 @@ var reservedFirstSegments = map[string]bool{
|
||||
"automata": true, "hotels": true, "api": true, "py": true, "radio": true,
|
||||
"gitea": true, "notes": true, "sb": true, "jobs": true, "tracker": true,
|
||||
"usaco": true, "uploads": true, "img": true, "fonts": true, "pdf": true,
|
||||
"sound": true, "assets": true, "internal": true,
|
||||
"sound": true, "assets": true, "internal": true, "dozzle": true, "garage": true,
|
||||
}
|
||||
|
||||
func validPageKey(key string) bool {
|
||||
|
||||
@@ -3,24 +3,28 @@ package handlers
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"adam-french.co.uk/backend/services"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
// Attachment upload for the chat.
|
||||
// Attachment upload for the chat (and, through it, the canvas editors).
|
||||
//
|
||||
// Files land in one of two directories. /backend/uploads/ is served by nginx
|
||||
// at /uploads/ with no authentication, so anything written there is publicly
|
||||
// reachable by URL — which is why the extension and content checks below
|
||||
// matter. /backend/uploads/private/ holds attachments for private (admin-only)
|
||||
// Files land in one of two places. Public files go to Store.Files: the Garage
|
||||
// bucket when S3_ENDPOINT is configured, /backend/uploads/ otherwise (see
|
||||
// services/file_store.go). Either way nginx serves them at /uploads/ with no
|
||||
// authentication, so anything stored is publicly reachable by URL — which is
|
||||
// why the extension and content checks below matter.
|
||||
// /backend/uploads/private/ holds attachments for private (admin-only)
|
||||
// messages and is served at /uploads/private/ behind an nginx auth_request
|
||||
// gate; only an admin may upload there.
|
||||
// gate; only an admin may upload there. Private files always stay on disk:
|
||||
// nginx cannot sign S3 requests, so it has no way to gate a bucket.
|
||||
|
||||
// allowedExtensions is the upload allow-list, keyed by lower-cased extension.
|
||||
var allowedExtensions = map[string]bool{
|
||||
@@ -42,10 +46,23 @@ var extensionToMIMEPrefix = map[string]string{
|
||||
".pdf": "application/pdf", ".txt": "text/",
|
||||
}
|
||||
|
||||
// publicUploadDir and privateUploadDir are the two destinations; the private
|
||||
// one is created on demand because nothing else guarantees it exists.
|
||||
// extensionContentType is the Content-Type a file is stored with. It comes
|
||||
// from the (already allow-listed) extension rather than from sniffing,
|
||||
// because sniffing is unreliable for exactly the audio and gif files the
|
||||
// table above leaves unverified. It matters for the bucket: Garage serves
|
||||
// back the stored type, where nginx serving from disk inferred its own.
|
||||
var extensionContentType = map[string]string{
|
||||
".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".png": "image/png", ".gif": "image/gif", ".webp": "image/webp",
|
||||
".mp4": "video/mp4", ".webm": "video/webm", ".mp3": "audio/mpeg", ".ogg": "audio/ogg",
|
||||
".pdf": "application/pdf", ".txt": "text/plain; charset=utf-8",
|
||||
}
|
||||
|
||||
// PublicUploadDir and privateUploadDir are the two directories on the shared
|
||||
// `uploads` volume; the private one is created on demand because nothing else
|
||||
// guarantees it exists. PublicUploadDir is exported for main, which hands it
|
||||
// to services.NewUploadStore as the disk store (or the bucket's fallback).
|
||||
const (
|
||||
publicUploadDir = "/backend/uploads/"
|
||||
PublicUploadDir = "/backend/uploads/"
|
||||
privateUploadDir = "/backend/uploads/private/"
|
||||
)
|
||||
|
||||
@@ -118,20 +135,6 @@ func (store *Store) UploadMessageFile(ctx *gin.Context) {
|
||||
}
|
||||
filename := hex.EncodeToString(b) + ext
|
||||
|
||||
uploadDir := publicUploadDir
|
||||
urlPrefix := "/uploads/"
|
||||
if private {
|
||||
uploadDir = privateUploadDir
|
||||
urlPrefix = "/uploads/private/"
|
||||
// 0755 so nginx (a different user) can traverse the directory to
|
||||
// serve the files once its auth_request gate has approved.
|
||||
if err := os.MkdirAll(uploadDir, 0755); err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save file"})
|
||||
return
|
||||
}
|
||||
}
|
||||
dest := filepath.Join(uploadDir, filename)
|
||||
|
||||
// Reopened rather than rewound: the earlier handle was closed after
|
||||
// sniffing, and multipart files may be backed by either memory or a temp
|
||||
// file, so a fresh reader is the simplest correct option.
|
||||
@@ -142,14 +145,28 @@ func (store *Store) UploadMessageFile(ctx *gin.Context) {
|
||||
}
|
||||
defer src.Close()
|
||||
|
||||
out, err := os.OpenFile(dest, os.O_CREATE|os.O_WRONLY, 0644)
|
||||
if err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save file"})
|
||||
return
|
||||
var dest services.FileStore
|
||||
urlPrefix := "/uploads/"
|
||||
if private {
|
||||
urlPrefix = "/uploads/private/"
|
||||
// 0755 so nginx (a different user) can traverse the directory to
|
||||
// serve the files once its auth_request gate has approved.
|
||||
if err := os.MkdirAll(privateUploadDir, 0755); err != nil {
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save file"})
|
||||
return
|
||||
}
|
||||
dest = services.DiskFileStore{Dir: privateUploadDir}
|
||||
} else {
|
||||
dest = store.Files
|
||||
// A Store built without one (the tests, mostly) keeps the old
|
||||
// behaviour rather than panicking.
|
||||
if dest == nil {
|
||||
dest = services.DiskFileStore{Dir: PublicUploadDir}
|
||||
}
|
||||
}
|
||||
defer out.Close()
|
||||
|
||||
if _, err := io.Copy(out, src); err != nil {
|
||||
if err := dest.Put(ctx.Request.Context(), filename, extensionContentType[ext], src, file.Size); err != nil {
|
||||
log.Printf("[upload] storing %s failed: %v", filename, err)
|
||||
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save file"})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -288,6 +288,17 @@ func TestUploadAllowLists(t *testing.T) {
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("every allowed extension has a stored Content-Type", func(t *testing.T) {
|
||||
// Garage serves back the type the upload was stored with; a missing
|
||||
// entry would store an empty type and the browser would be left to
|
||||
// guess under nosniff — i.e. refuse to render it.
|
||||
for ext := range allowedExtensions {
|
||||
if extensionContentType[ext] == "" {
|
||||
t.Errorf("%q is allowed but has no Content-Type", ext)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("audio extensions are content-unverified by design", func(t *testing.T) {
|
||||
// http.DetectContentType is unreliable for these, so a missing entry
|
||||
// means "extension allowed, content not verified". Adding one would
|
||||
|
||||
@@ -38,6 +38,12 @@ type Store struct {
|
||||
// services.CallPython: reading a rowing display photo (handle_rowing.go).
|
||||
PythonURL string
|
||||
|
||||
// Where public uploads are stored: the Garage bucket with a disk
|
||||
// fallback, or the disk alone when S3 is not configured
|
||||
// (services.NewUploadStore). nil means the disk, so a Store built in a
|
||||
// test needs no setup.
|
||||
Files services.FileStore
|
||||
|
||||
// Cached "recently played" tracks, refreshed at most once a minute by the
|
||||
// GraphQL spotifyRecent resolver. A pointer to a slice so that nil can
|
||||
// mean "never fetched" distinctly from "fetched, empty".
|
||||
|
||||
+17
-1
@@ -128,11 +128,27 @@ func main() {
|
||||
}
|
||||
pythonURL := fmt.Sprintf("http://%s:%s", pythonHost, pythonPort)
|
||||
|
||||
// UPLOAD STORAGE
|
||||
// Public uploads go to the Garage bucket once S3_ENDPOINT is set, and to
|
||||
// the shared `uploads` volume until then (and whenever Garage refuses a
|
||||
// write). See services/file_store.go. Region and bucket default to what
|
||||
// garage/garage.toml and garage/bootstrap.sh set up.
|
||||
s3Region := os.Getenv("S3_REGION")
|
||||
if s3Region == "" {
|
||||
s3Region = "garage"
|
||||
}
|
||||
s3Bucket := os.Getenv("S3_BUCKET")
|
||||
if s3Bucket == "" {
|
||||
s3Bucket = "uploads"
|
||||
}
|
||||
s3Config := services.S3Config{Endpoint: os.Getenv("S3_ENDPOINT"), Region: s3Region, Bucket: s3Bucket, AccessKeyID: os.Getenv("S3_ACCESS_KEY_ID"), SecretAccessKey: os.Getenv("S3_SECRET_ACCESS_KEY")}
|
||||
files := services.NewUploadStore(s3Config, handlers.PublicUploadDir)
|
||||
|
||||
// 5 login attempts per IP per minute, applied by both the REST handler
|
||||
// and the GraphQL login mutation. Nginx rate-limits the login route too.
|
||||
loginLimiter := services.NewRateLimiter(5, time.Minute)
|
||||
|
||||
store := handlers.Store{DB: db, SpotifyAuth: spotifyAuth, SpotifyClient: spotifyClient, Auth: auth, Notes: notes, LoginLimiter: loginLimiter, GiteaHost: giteaHost, GiteaPort: giteaPort, SteamAPIKey: steamAPIKey, SteamID: steamID, PythonURL: pythonURL}
|
||||
store := handlers.Store{DB: db, SpotifyAuth: spotifyAuth, SpotifyClient: spotifyClient, Auth: auth, Notes: notes, LoginLimiter: loginLimiter, GiteaHost: giteaHost, GiteaPort: giteaPort, SteamAPIKey: steamAPIKey, SteamID: steamID, PythonURL: pythonURL, Files: files}
|
||||
|
||||
// Route groups. AdminMiddleware reads the claims AuthMiddlewear stored in
|
||||
// the Gin context, so the order in the admin group matters.
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
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}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
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))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user