Give uploads one path end to end, and serve /uploads/ from Garage first
Test and deploy / deploy (push) Successful in 3m48s
Test and deploy / test (push) Successful in 37s

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:
2026-10-15 21:04:37 +01:00
co-authored by Claude Opus 5.5
parent 422cde4708
commit 65fddfcfa2
26 changed files with 848 additions and 668 deletions
-195
View File
@@ -1,195 +0,0 @@
package handlers
import (
"crypto/rand"
"encoding/hex"
"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 (and, through it, the canvas editors).
//
// 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. 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{
".jpg": true, ".jpeg": true, ".png": true, ".gif": true, ".webp": true,
".mp4": true, ".webm": true, ".mp3": true, ".ogg": true,
".pdf": true, ".txt": true,
}
// extensionToMIMEPrefix cross-checks the sniffed content type against the
// claimed extension, to stop e.g. HTML being served from a .png URL.
//
// The audio extensions (.mp3, .ogg) and .gif are deliberately absent:
// http.DetectContentType's answers for them are unreliable enough to reject
// legitimate files, so a missing entry means "extension allowed, content not
// verified".
var extensionToMIMEPrefix = map[string]string{
".jpg": "image/", ".jpeg": "image/", ".png": "image/", ".gif": "image/", ".webp": "image/",
".mp4": "video/", ".webm": "video/",
".pdf": "application/pdf", ".txt": "text/",
}
// 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/"
privateUploadDir = "/backend/uploads/private/"
)
// UploadMessageFile backs POST /messages/upload (login required) and returns
// the URL of the stored file, which the client then sends over the WebSocket
// as a message's fileUrl.
//
// The multipart form takes an optional "private" field: "true" stores the file
// under /uploads/private/ for use as a private message's attachment. That is
// admin-only, because private messages themselves are — an attachment URL
// leaking out is the same disclosure as the message leaking out.
func (store *Store) UploadMessageFile(ctx *gin.Context) {
private := ctx.PostForm("private") == "true"
if private && !requestIsAdmin(ctx) {
ctx.JSON(http.StatusForbidden, gin.H{"error": "admin access required"})
return
}
file, err := ctx.FormFile("file")
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "file is required"})
return
}
const maxSize = 10 << 20 // 10MB
if file.Size > maxSize {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "file too large"})
return
}
ext := strings.ToLower(filepath.Ext(file.Filename))
if !allowedExtensions[ext] {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "file type not allowed"})
return
}
// Validate actual content type matches extension
f, err := file.Open()
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to read file"})
return
}
// 512 bytes is exactly what http.DetectContentType inspects; reading more
// would be wasted. A single Read may return fewer bytes than asked for,
// which is fine — sniffing works on a short prefix — so only a read that
// produced nothing at all is an error.
buf := make([]byte, 512)
n, err := f.Read(buf)
f.Close()
if err != nil && n == 0 {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "failed to read file content"})
return
}
detectedType := http.DetectContentType(buf[:n])
expectedPrefix, ok := extensionToMIMEPrefix[ext]
if ok && !strings.HasPrefix(detectedType, expectedPrefix) {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "file content does not match extension"})
return
}
// The uploaded name is discarded entirely in favour of 16 random bytes
// from crypto/rand. That kills path traversal and collisions in one go,
// and makes the resulting URL unguessable. Only the extension is carried
// over, and it has already been checked against the allow-list.
b := make([]byte, 16)
if _, err := rand.Read(b); err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate filename"})
return
}
filename := hex.EncodeToString(b) + ext
// 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.
src, err := file.Open()
if err != nil {
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to read file"})
return
}
defer src.Close()
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}
}
}
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
}
ctx.JSON(http.StatusOK, gin.H{"url": urlPrefix + filename})
}
// requestIsAdmin reports whether the caller's access token carries admin=true.
//
// This route sits in the `protected` group, which runs AuthMiddlewear but not
// AdminMiddleware — the endpoint has to stay usable by any signed-in user for
// public attachments — so the admin check is made here from the same
// "userClaims" value AdminMiddleware would have read.
func requestIsAdmin(ctx *gin.Context) bool {
claims, exists := ctx.Get("userClaims")
if !exists {
return false
}
mapClaims, ok := claims.(*jwt.MapClaims)
if !ok {
return false
}
admin, ok := (*mapClaims)["admin"].(bool)
return ok && admin
}
+70
View File
@@ -0,0 +1,70 @@
package handlers
import (
"errors"
"log"
"net/http"
"adam-french.co.uk/backend/services"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
)
// Upload backs POST /uploads (login required): the one endpoint the frontend
// stores a file through (vue/src/uploads.js). Multipart form:
//
// file the file (required)
// private "true" to store it as an admin-only chat attachment
//
// It answers {"url": "/uploads/<name>"}, or {"error": "..."} with 400 when
// the file was refused (wrong type, too large) and 500 when storing failed.
// Validation, naming and storage are all services.Uploads.Save; this handler
// only reads the form and decides who may use `private`.
//
// `private` is admin-only because private messages themselves are: an
// attachment URL leaking out is the same disclosure as the message leaking.
func (store *Store) Upload(ctx *gin.Context) {
private := ctx.PostForm("private") == "true"
if private && !requestIsAdmin(ctx) {
ctx.JSON(http.StatusForbidden, gin.H{"error": "admin access required"})
return
}
file, err := ctx.FormFile("file")
if err != nil {
ctx.JSON(http.StatusBadRequest, gin.H{"error": "file is required"})
return
}
url, err := store.Uploads.Save(ctx.Request.Context(), file, private)
var rejected *services.UploadError
switch {
case errors.As(err, &rejected):
ctx.JSON(http.StatusBadRequest, gin.H{"error": rejected.Message})
case err != nil:
log.Printf("[upload] storing %s failed: %v", file.Filename, err)
ctx.JSON(http.StatusInternalServerError, gin.H{"error": "failed to save file"})
default:
ctx.JSON(http.StatusOK, gin.H{"url": url})
}
}
// requestIsAdmin reports whether the caller's access token carries admin=true.
//
// This route sits in the `protected` group, which runs AuthMiddlewear but not
// AdminMiddleware — the endpoint has to stay usable by any signed-in user for
// public attachments — so the admin check is made here from the same
// "userClaims" value AdminMiddleware would have read.
func requestIsAdmin(ctx *gin.Context) bool {
claims, exists := ctx.Get("userClaims")
if !exists {
return false
}
mapClaims, ok := claims.(*jwt.MapClaims)
if !ok {
return false
}
admin, ok := (*mapClaims)["admin"].(bool)
return ok && admin
}
+19 -69
View File
@@ -14,23 +14,21 @@ import (
// What is deliberately NOT covered here, and why:
//
// - Every handler method (Login, UploadMessageFile, the radio file movers,
// - Every handler method (Login, Upload, the radio file movers,
// the Spotify and email endpoints). They all need a live *gorm.DB, a real
// multipart request, the container's /backend/... directories, or a paid
// Claude call. Only postgres is in go.mod, so a DB would mean a server in
// CI.
// - The radio/chat upload filename sanitisation itself. It is written inline
// inside the handler bodies rather than in a helper, so testing it would
// mean either driving a full multipart upload against the real upload
// directories or refactoring production code. Neither was in scope, so the
// part that *is* extractable — the extension allow-lists those handlers
// gate on — is covered as a table contract below instead.
// - The radio upload's filename sanitisation. It is written inline in the
// handler, so only the extension allow-list it gates on is covered, as a
// table contract below. (The site's general uploads — validation, naming,
// storage — are services.Uploads, tested in services/uploads_test.go.)
// - Store.isAdminRequest and the refresh fallback in ValidateAdmin: both
// reach the database on the refresh path.
//
// What is covered: the Spotify OAuth CSRF nonce store, the TTL rules of the
// three shared caches, the admin claim check on the upload trust boundary, and
// the upload allow-list tables.
// the radio allow-list.
// --- Spotify OAuth CSRF nonces -------------------------------------------
@@ -253,68 +251,20 @@ func TestRequestIsAdmin(t *testing.T) {
}
}
// The allow-list tables are the upload trust boundary's data. Testing them as
// data catches the realistic failure: someone adding an executable or markup
// extension, or adding an extension to the MIME map without allowing it (which
// would be dead configuration).
func TestUploadAllowLists(t *testing.T) {
t.Run("dangerous extensions stay off the chat allow-list", func(t *testing.T) {
// Served by nginx from a public directory with no auth, so anything
// the browser will execute or render as markup must not be storable.
for _, ext := range []string{".html", ".htm", ".svg", ".js", ".php", ".exe", ".sh", ".xml", ""} {
if allowedExtensions[ext] {
t.Errorf("%q must not be an allowed chat upload extension", ext)
}
}
})
t.Run("allow-list keys are lower-cased with a leading dot", func(t *testing.T) {
// The handlers look up strings.ToLower(filepath.Ext(...)), so a key in
// The radio allow-list is the radio upload's trust boundary. Testing it as
// data catches the realistic failure: someone adding a non-audio or malformed
// extension.
func TestRadioAllowList(t *testing.T) {
for ext := range allowedAudioExtensions {
// The handler looks up strings.ToLower(filepath.Ext(...)), so a key in
// any other shape is unreachable.
for _, m := range []map[string]bool{allowedExtensions, allowedAudioExtensions} {
for ext := range m {
if ext == "" || ext[0] != '.' || ext != strings.ToLower(ext) {
t.Errorf("malformed allow-list key %q", ext)
}
}
if ext == "" || ext[0] != '.' || ext != strings.ToLower(ext) {
t.Errorf("malformed allow-list key %q", ext)
}
})
t.Run("every MIME-checked extension is also allowed", func(t *testing.T) {
for ext := range extensionToMIMEPrefix {
if !allowedExtensions[ext] {
t.Errorf("%q has a MIME prefix but is not an allowed extension, so the check never runs", ext)
}
}
for _, ext := range []string{".mp4", ".webm", ".pdf", ".txt", ".png", ".html"} {
if allowedAudioExtensions[ext] {
t.Errorf("%q must not be an allowed radio upload extension", ext)
}
})
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
// start rejecting legitimate uploads.
for _, ext := range []string{".mp3", ".ogg"} {
if _, ok := extensionToMIMEPrefix[ext]; ok {
t.Errorf("%q should not be MIME-checked", ext)
}
}
})
t.Run("radio allow-list is audio only", func(t *testing.T) {
for _, ext := range []string{".mp4", ".webm", ".pdf", ".txt", ".png", ".html"} {
if allowedAudioExtensions[ext] {
t.Errorf("%q must not be an allowed radio upload extension", ext)
}
}
})
}
}
+3 -5
View File
@@ -38,11 +38,9 @@ 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
// Stores uploaded files and says where they are served
// (services.Uploads.Save). Used by the Upload handler.
Uploads *services.Uploads
// Cached "recently played" tracks, refreshed at most once a minute by the
// GraphQL spotifyRecent resolver. A pointer to a slice so that nil can