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]>
This commit is contained in:
+28
-100
@@ -22,51 +22,25 @@ import (
|
||||
"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. Caddy
|
||||
// mirrors that: /uploads/<name> is fetched from the bucket first and the
|
||||
// volume second (caddy/routes.caddy), 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 Caddy gates behind an admin check. Caddy 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.
|
||||
// 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.
|
||||
|
||||
// MaxUploadSize caps one upload. It bounds how fast one account can fill the
|
||||
// disk or the bucket; Caddy 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: Caddy adds
|
||||
// `nosniff`, so a wrong type means the file doesn't display.
|
||||
// Served back as-is, and Caddy sends nosniff, so it must be right.
|
||||
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.
|
||||
// What http.DetectContentType must report. Empty skips the check, which
|
||||
// is unreliable for audio and gif.
|
||||
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.
|
||||
// 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/"},
|
||||
@@ -81,8 +55,6 @@ var UploadTypes = map[string]UploadType{
|
||||
".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 }
|
||||
@@ -94,26 +66,17 @@ var (
|
||||
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; Caddy 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.
|
||||
// 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}}
|
||||
@@ -130,9 +93,7 @@ func NewUploads(cfg S3Config, publicDir, privateDir string) *Uploads {
|
||||
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.
|
||||
// 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
|
||||
@@ -150,8 +111,7 @@ func (u *Uploads) Save(ctx context.Context, fh *multipart.FileHeader, private bo
|
||||
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.
|
||||
// A short read is fine; only an empty file fails.
|
||||
buf := make([]byte, 512)
|
||||
n, err := io.ReadFull(f, buf)
|
||||
if n == 0 {
|
||||
@@ -168,9 +128,8 @@ func (u *Uploads) Save(ctx context.Context, fh *multipart.FileHeader, private bo
|
||||
}
|
||||
}
|
||||
|
||||
// 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.
|
||||
// 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)
|
||||
@@ -187,7 +146,6 @@ func (u *Uploads) Save(ctx context.Context, fh *multipart.FileHeader, private bo
|
||||
return prefix + name, nil
|
||||
}
|
||||
|
||||
// StoredFile is one public upload, as listed for the admin's upload picker.
|
||||
type StoredFile struct {
|
||||
Name string `json:"name"`
|
||||
URL string `json:"url"`
|
||||
@@ -195,16 +153,8 @@ type StoredFile struct {
|
||||
Modified time.Time `json:"modified"`
|
||||
}
|
||||
|
||||
// List returns every public upload, newest first. Private files are never
|
||||
// listed: they live in their own store, which this doesn't touch.
|
||||
//
|
||||
// The caller must be an admin. An upload's URL is public but unguessable, and
|
||||
// that is the only thing keeping a file nobody linked to from being found; a
|
||||
// listing anyone could read would hand every one of them out.
|
||||
//
|
||||
// Only names with an extension on the allow-list are returned, so anything
|
||||
// else that ends up in the bucket or the directory (by hand, through
|
||||
// garage-webui) never reaches a page through the picker.
|
||||
// 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 {
|
||||
@@ -223,22 +173,17 @@ func (u *Uploads) List(ctx context.Context) ([]StoredFile, error) {
|
||||
|
||||
// ---- Stores ----------------------------------------------------------------
|
||||
|
||||
// FileStore stores one file under key, and lists what it holds. 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.
|
||||
//
|
||||
// List returns top-level files only, with URL unset (Uploads.List fills it).
|
||||
// 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)
|
||||
}
|
||||
|
||||
// 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 the edge, in another container, can reach and read the files.
|
||||
// World-readable so Caddy, in another container, can serve them.
|
||||
if err := os.MkdirAll(d.Dir, 0755); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -253,9 +198,7 @@ func (d DiskFileStore) Put(_ context.Context, key, _ string, r io.ReadSeeker, _
|
||||
return out.Close()
|
||||
}
|
||||
|
||||
// List skips subdirectories, which is what keeps the private/ directory
|
||||
// (inside the public one on the volume) out of the listing. A directory that
|
||||
// doesn't exist yet just holds nothing.
|
||||
// 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) {
|
||||
@@ -278,13 +221,11 @@ func (d DiskFileStore) List(_ context.Context) ([]StoredFile, error) {
|
||||
return files, nil
|
||||
}
|
||||
|
||||
// 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
|
||||
@@ -293,9 +234,7 @@ type S3Config struct {
|
||||
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.
|
||||
// Garage is on the same network, so anything near this is a hang.
|
||||
const s3Timeout = 30 * time.Second
|
||||
|
||||
func NewS3FileStore(cfg S3Config) *S3FileStore {
|
||||
@@ -303,12 +242,9 @@ func NewS3FileStore(cfg S3Config) *S3FileStore {
|
||||
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.
|
||||
// Garage needs path-style addressing.
|
||||
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.
|
||||
// Default CRC32 checksums aren't reliably supported by non-AWS servers.
|
||||
RequestChecksumCalculation: aws.RequestChecksumCalculationWhenRequired,
|
||||
ResponseChecksumValidation: aws.ResponseChecksumValidationWhenRequired,
|
||||
})
|
||||
@@ -332,9 +268,7 @@ func (s *S3FileStore) Put(ctx context.Context, key, contentType string, r io.Rea
|
||||
return nil
|
||||
}
|
||||
|
||||
// List pages through the whole bucket. Keys containing "/" are skipped: they
|
||||
// are not uploads (Save never makes one) but something put under a prefix by
|
||||
// hand, and Caddy's /uploads/<name> only ever serves a top-level name anyway.
|
||||
// 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()
|
||||
@@ -357,10 +291,8 @@ func (s *S3FileStore) List(ctx context.Context) ([]StoredFile, error) {
|
||||
return files, nil
|
||||
}
|
||||
|
||||
// FallbackFileStore tries Primary and, if that fails, logs it and writes to
|
||||
// Fallback instead. The upload still succeeds and its URL still works (Caddy
|
||||
// looks in both places), so a Garage outage costs a log line rather than
|
||||
// broken uploads.
|
||||
// FallbackFileStore writes to Fallback when Primary fails. Caddy serves from
|
||||
// both, so the URL still works.
|
||||
type FallbackFileStore struct {
|
||||
Primary FileStore
|
||||
Fallback FileStore
|
||||
@@ -378,11 +310,7 @@ func (f FallbackFileStore) Put(ctx context.Context, key, contentType string, r i
|
||||
return f.Fallback.Put(ctx, key, contentType, r, size)
|
||||
}
|
||||
|
||||
// List is the union of both stores, since Caddy serves from both: the
|
||||
// fallback holds whatever was written while the primary was down (and, on
|
||||
// the live volume, the pre-Garage copies). A name in both is listed once,
|
||||
// with the primary's details. A primary that can't list is logged and the
|
||||
// fallback's files are returned alone, as for Put.
|
||||
// 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 {
|
||||
|
||||
Reference in New Issue
Block a user