Let the canvas panels choose from files already uploaded
Test and deploy / deploy (push) Has been cancelled
Test and deploy / test (push) Successful in 2m4s

The Background panel, the Box editor and the canvas admin bar could only
take a new upload, so reusing a picture meant uploading it again or
pasting its URL. Each now has a picker (UploadPicker.vue): a grid of the
public uploads, newest first, filterable by name.

It lists through a new admin-only GET /api/uploads (Uploads.List), the
union of the Garage bucket and the disk fallback, since nginx serves
from both; a bucket that can't list falls back to the disk's files.
Admin-only because upload URLs are public but unguessable, and a public
listing would give every one away. Private files and anything off the
UploadTypes allow-list are never listed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-23 19:59:03 +01:00
co-authored by Claude Opus 5.5
parent 1ddaff0690
commit 3fa456a063
12 changed files with 498 additions and 40 deletions
+124 -3
View File
@@ -4,13 +4,16 @@ import (
"context"
"crypto/rand"
"encoding/hex"
"errors"
"fmt"
"io"
"io/fs"
"log"
"mime/multipart"
"net/http"
"os"
"path/filepath"
"sort"
"strings"
"time"
@@ -184,13 +187,51 @@ 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"`
Size int64 `json:"size"`
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.
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 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.
// 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).
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.
@@ -212,6 +253,31 @@ 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.
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
}
// S3FileStore writes files into one bucket of an S3-compatible server.
type S3FileStore struct {
client *s3.Client
@@ -266,6 +332,31 @@ 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 nginx's /uploads/<name> only ever serves a top-level name anyway.
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 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
@@ -286,3 +377,33 @@ 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 nginx 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.
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
}
+98 -1
View File
@@ -14,6 +14,7 @@ import (
"path/filepath"
"strings"
"testing"
"time"
)
// Covered here: the type table (the upload trust boundary's data), Save's
@@ -21,7 +22,7 @@ import (
// 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
// Not covered: a successful PutObject or ListObjectsV2 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
@@ -59,6 +60,17 @@ func (r *recordingStore) Put(_ context.Context, key, contentType string, rd io.R
return nil
}
func (r *recordingStore) List(context.Context) ([]StoredFile, error) { return nil, nil }
// listStore lists a fixed set of files, or fails.
type listStore struct {
files []StoredFile
err error
}
func (l listStore) Put(context.Context, string, string, io.ReadSeeker, int64) error { return nil }
func (l listStore) List(context.Context) ([]StoredFile, error) { return l.files, l.err }
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
@@ -209,3 +221,88 @@ func TestFallbackWhenBucketRefuses(t *testing.T) {
t.Fatalf("fallback file has %d bytes (%v), want %d", len(got), err, len(img))
}
}
func TestDiskFileStoreList(t *testing.T) {
if files, err := (DiskFileStore{Dir: filepath.Join(t.TempDir(), "missing")}).List(context.Background()); err != nil || len(files) != 0 {
t.Fatalf("missing dir: got %v, %v; want nothing and no error", files, err)
}
dir := t.TempDir()
os.WriteFile(filepath.Join(dir, "a.png"), []byte("abc"), 0644)
os.MkdirAll(filepath.Join(dir, "private"), 0755)
os.WriteFile(filepath.Join(dir, "private", "secret.png"), []byte("x"), 0644)
files, err := (DiskFileStore{Dir: dir}).List(context.Background())
if err != nil {
t.Fatal(err)
}
if len(files) != 1 || files[0].Name != "a.png" || files[0].Size != 3 {
t.Fatalf("got %+v, want just a.png (3 bytes): private/ must not be listed", files)
}
}
func TestFallbackFileStoreList(t *testing.T) {
ctx := context.Background()
bucket := listStore{files: []StoredFile{{Name: "a.png", Size: 1}, {Name: "b.png"}}}
disk := listStore{files: []StoredFile{{Name: "a.png", Size: 2}, {Name: "c.png"}}}
files, err := FallbackFileStore{Primary: bucket, Fallback: disk}.List(ctx)
if err != nil {
t.Fatal(err)
}
names := map[string]int64{}
for _, f := range files {
names[f.Name] = f.Size
}
if len(files) != 3 || names["a.png"] != 1 || len(names) != 3 {
t.Errorf("got %+v, want a (from the bucket), b and c once each", files)
}
t.Run("bucket down", func(t *testing.T) {
files, err := FallbackFileStore{Primary: listStore{err: errors.New("down")}, Fallback: disk}.List(ctx)
if err != nil || len(files) != 2 {
t.Errorf("got %+v, %v; want the disk's two files", files, err)
}
})
t.Run("both down", func(t *testing.T) {
_, err := FallbackFileStore{Primary: listStore{err: errors.New("down")}, Fallback: listStore{err: errors.New("gone")}}.List(ctx)
if err == nil {
t.Error("want an error when neither store can list")
}
})
}
func TestFallbackListWhenBucketRefuses(t *testing.T) {
// The real S3 client against a server that refuses: the listing still
// comes back, from disk.
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusForbidden)
}))
defer srv.Close()
dir := t.TempDir()
os.WriteFile(filepath.Join(dir, "on-disk.png"), pngBytes(), 0644)
u := NewUploads(S3Config{Endpoint: srv.URL, Region: "garage", Bucket: "uploads", AccessKeyID: "GK0", SecretAccessKey: "s"}, dir, filepath.Join(dir, "private"))
files, err := u.List(context.Background())
if err != nil || len(files) != 1 || files[0].URL != "/uploads/on-disk.png" {
t.Fatalf("got %+v, %v; want the one disk file", files, err)
}
}
func TestUploadsList(t *testing.T) {
now := time.Now()
u := &Uploads{public: listStore{files: []StoredFile{
{Name: "old.png", Modified: now.Add(-time.Hour)},
{Name: "page.html", Modified: now},
{Name: "new.JPG", Modified: now.Add(-time.Minute)},
{Name: "noext", Modified: now},
}}}
files, err := u.List(context.Background())
if err != nil {
t.Fatal(err)
}
if len(files) != 2 || files[0].URL != "/uploads/new.JPG" || files[1].URL != "/uploads/old.png" {
t.Fatalf("got %+v, want new.JPG then old.png, nothing off the allow-list", files)
}
}