Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(storage): add local file storage fallback (#710)

Antar Dasd32c419b6dd2
diff --git a/.env.example b/.env.example
index 3cfd7eb6e5..d4a8e6ed24 100644
--- a/.env.example
+++ b/.env.example
@@ -42,6 +42,10 @@ CLOUDFRONT_PRIVATE_KEY=
CLOUDFRONT_DOMAIN=
COOKIE_DOMAIN=
+# Local file storage (fallback when S3_BUCKET is not set)
+LOCAL_UPLOAD_DIR=./data/uploads
+LOCAL_UPLOAD_BASE_URL=http://localhost:8080
+
# Frontend
FRONTEND_PORT=3000
FRONTEND_ORIGIN=http://localhost:3000
diff --git a/.gitignore b/.gitignore
index ab25a6a644..9fba95f14f 100644
--- a/.gitignore
+++ b/.gitignore
@@ -48,3 +48,5 @@ _features/
*.dmg
*.app
server/server
+data/
+.kilo
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 3c11dc0972..9b69a5512f 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -56,9 +56,21 @@ func allowedOrigins() []string {
func NewRouter(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus) chi.Router {
queries := db.New(pool)
emailSvc := service.NewEmailService()
+
+ // Initialize storage with S3 as primary, fallback to local
+ var store storage.Storage
s3 := storage.NewS3StorageFromEnv()
+ if s3 != nil {
+ store = s3
+ } else {
+ local := storage.NewLocalStorageFromEnv()
+ if local != nil {
+ store = local
+ }
+ }
+
cfSigner := auth.NewCloudFrontSignerFromEnv()
- h := handler.New(queries, pool, hub, bus, emailSvc, s3, cfSigner)
+ h := handler.New(queries, pool, hub, bus, emailSvc, store, cfSigner)
r := chi.NewRouter()
@@ -87,6 +99,14 @@ func NewRouter(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus) chi.Route
realtime.HandleWebSocket(hub, mc, pr, w, r)
})
+ // Local file serving (when using local storage)
+ if local, ok := store.(*storage.LocalStorage); ok {
+ r.Get("/uploads/*", func(w http.ResponseWriter, r *http.Request) {
+ file := strings.TrimPrefix(r.URL.Path, "/uploads/")
+ local.ServeFile(w, r, file)
+ })
+ }
+
// Auth (public)
r.Post("/auth/send-code", h.SendCode)
r.Post("/auth/verify-code", h.VerifyCode)
diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.go
index 48f0dabc32..b000dc9f38 100644
--- a/server/internal/handler/handler.go
+++ b/server/internal/handler/handler.go
@@ -11,7 +11,6 @@ import (
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgtype"
- db "github.com/multica-ai/multica/server/pkg/db/generated"
"github.com/multica-ai/multica/server/internal/auth"
"github.com/multica-ai/multica/server/internal/events"
"github.com/multica-ai/multica/server/internal/middleware"
@@ -19,6 +18,7 @@ import (
"github.com/multica-ai/multica/server/internal/service"
"github.com/multica-ai/multica/server/internal/storage"
"github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
)
type txStarter interface {
@@ -41,11 +41,11 @@ type Handler struct {
EmailService *service.EmailService
PingStore *PingStore
UpdateStore *UpdateStore
- Storage *storage.S3Storage
+ Storage storage.Storage
CFSigner *auth.CloudFrontSigner
}
-func New(queries *db.Queries, txStarter txStarter, hub *realtime.Hub, bus *events.Bus, emailService *service.EmailService, s3 *storage.S3Storage, cfSigner *auth.CloudFrontSigner) *Handler {
+func New(queries *db.Queries, txStarter txStarter, hub *realtime.Hub, bus *events.Bus, emailService *service.EmailService, store storage.Storage, cfSigner *auth.CloudFrontSigner) *Handler {
var executor dbExecutor
if candidate, ok := txStarter.(dbExecutor); ok {
executor = candidate
@@ -61,7 +61,7 @@ func New(queries *db.Queries, txStarter txStarter, hub *realtime.Hub, bus *event
EmailService: emailService,
PingStore: NewPingStore(),
UpdateStore: NewUpdateStore(),
- Storage: s3,
+ Storage: store,
CFSigner: cfSigner,
}
}
@@ -77,14 +77,14 @@ func writeError(w http.ResponseWriter, status int, msg string) {
}
// Thin wrappers around util functions (preserve existing handler code unchanged).
-func parseUUID(s string) pgtype.UUID { return util.ParseUUID(s) }
-func uuidToString(u pgtype.UUID) string { return util.UUIDToString(u) }
-func textToPtr(t pgtype.Text) *string { return util.TextToPtr(t) }
-func ptrToText(s *string) pgtype.Text { return util.PtrToText(s) }
-func strToText(s string) pgtype.Text { return util.StrToText(s) }
+func parseUUID(s string) pgtype.UUID { return util.ParseUUID(s) }
+func uuidToString(u pgtype.UUID) string { return util.UUIDToString(u) }
+func textToPtr(t pgtype.Text) *string { return util.TextToPtr(t) }
+func ptrToText(s *string) pgtype.Text { return util.PtrToText(s) }
+func strToText(s string) pgtype.Text { return util.StrToText(s) }
func timestampToString(t pgtype.Timestamptz) string { return util.TimestampToString(t) }
func timestampToPtr(t pgtype.Timestamptz) *string { return util.TimestampToPtr(t) }
-func uuidToPtr(u pgtype.UUID) *string { return util.UUIDToPtr(u) }
+func uuidToPtr(u pgtype.UUID) *string { return util.UUIDToPtr(u) }
// publish sends a domain event through the event bus.
func (h *Handler) publish(eventType, workspaceID, actorType, actorID string, payload any) {
diff --git a/server/internal/storage/local.go b/server/internal/storage/local.go
new file mode 100644
index 0000000000..ada8f4d921
--- /dev/null
+++ b/server/internal/storage/local.go
@@ -0,0 +1,114 @@
+package storage
+
+import (
+ "context"
+ "fmt"
+ "io"
+ "log/slog"
+ "net/http"
+ "os"
+ "path/filepath"
+ "strings"
+)
+
+type LocalStorage struct {
+ uploadDir string
+ baseURL string
+}
+
+// NewLocalStorageFromEnv creates a LocalStorage from environment variables.
+// Returns nil if upload directory cannot be created.
+//
+// Environment variables:
+// - LOCAL_UPLOAD_DIR (default: "./data/uploads")
+// - LOCAL_UPLOAD_BASE_URL (optional, e.g., "http://localhost:8080")
+func NewLocalStorageFromEnv() *LocalStorage {
+ uploadDir := os.Getenv("LOCAL_UPLOAD_DIR")
+ if uploadDir == "" {
+ uploadDir = "./data/uploads"
+ }
+
+ if err := os.MkdirAll(uploadDir, 0755); err != nil {
+ slog.Error("failed to create upload directory", "dir", uploadDir, "error", err)
+ return nil
+ }
+
+ baseURL := strings.TrimSuffix(os.Getenv("LOCAL_UPLOAD_BASE_URL"), "/")
+
+ slog.Info("local storage initialized", "dir", uploadDir, "baseURL", baseURL)
+ return &LocalStorage{
+ uploadDir: uploadDir,
+ baseURL: baseURL,
+ }
+}
+
+func (s *LocalStorage) KeyFromURL(rawURL string) string {
+ if s.baseURL != "" && strings.HasPrefix(rawURL, s.baseURL) {
+ rawURL = strings.TrimPrefix(rawURL, s.baseURL)
+ }
+
+ prefix := "/uploads/"
+ if strings.HasPrefix(rawURL, prefix) {
+ filename := strings.TrimPrefix(rawURL, prefix)
+ if i := strings.LastIndex(filename, "/"); i >= 0 {
+ return filename[i+1:]
+ }
+ return filename
+ }
+ if i := strings.LastIndex(rawURL, "/"); i >= 0 {
+ return rawURL[i+1:]
+ }
+ return rawURL
+}
+
+func (s *LocalStorage) Delete(ctx context.Context, key string) {
+ if key == "" {
+ return
+ }
+ filePath := filepath.Join(s.uploadDir, key)
+ if err := os.Remove(filePath); err != nil {
+ if !os.IsNotExist(err) {
+ slog.Error("local storage Delete failed", "key", key, "error", err)
+ }
+ }
+}
+
+func (s *LocalStorage) DeleteKeys(ctx context.Context, keys []string) {
+ for _, key := range keys {
+ s.Delete(ctx, key)
+ }
+}
+
+func (s *LocalStorage) Upload(ctx context.Context, key string, data []byte, contentType string, filename string) (string, error) {
+ filepath := filepath.Join(s.uploadDir, key)
+ if err := os.WriteFile(filepath, data, 0644); err != nil {
+ return "", fmt.Errorf("local storage WriteFile: %w", err)
+ }
+
+ if s.baseURL != "" {
+ return fmt.Sprintf("%s/uploads/%s", s.baseURL, key), nil
+ }
+ return fmt.Sprintf("/uploads/%s", key), nil
+}
+
+func (s *LocalStorage) GetFilePath(key string) string {
+ return filepath.Join(s.uploadDir, key)
+}
+
+func (s *LocalStorage) ServeFile(w http.ResponseWriter, r *http.Request, filename string) {
+ filePath := filepath.Join(s.uploadDir, filename)
+ slog.Info("serving file", "filename", filename, "filepath", filePath)
+
+ // Use http.ServeFile which has built-in path traversal protection
+ // It sanitizes the path and prevents access outside the directory
+ http.ServeFile(w, r, filePath)
+}
+
+func (s *LocalStorage) UploadFromReader(ctx context.Context, key string, reader io.Reader, contentType string, filename string) (string, error) {
+ data, err := io.ReadAll(reader)
+ if err != nil {
+ return "", fmt.Errorf("local storage ReadAll: %w", err)
+ }
+
+ return s.Upload(ctx, key, data, contentType, filename)
+}
diff --git a/server/internal/storage/local_test.go b/server/internal/storage/local_test.go
new file mode 100644
index 0000000000..d3b7ff4871
--- /dev/null
+++ b/server/internal/storage/local_test.go
@@ -0,0 +1,214 @@
+package storage
+
+import (
+ "context"
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+func TestLocalStorage_Upload(t *testing.T) {
+ tmpDir := t.TempDir()
+ t.Setenv("LOCAL_UPLOAD_DIR", tmpDir)
+ os.Unsetenv("LOCAL_UPLOAD_BASE_URL")
+ // No LOCAL_UPLOAD_BASE_URL set - should return relative path
+
+ store := NewLocalStorageFromEnv()
+ if store == nil {
+ t.Fatal("NewLocalStorageFromEnv returned nil")
+ }
+
+ ctx := context.Background()
+ data := []byte("hello world")
+ contentType := "text/plain"
+ filename := "test.txt"
+
+ link, err := store.Upload(ctx, "test-key.txt", data, contentType, filename)
+ if err != nil {
+ t.Fatalf("Upload failed: %v", err)
+ }
+
+ expectedLink := "/uploads/test-key.txt"
+ if link != expectedLink {
+ t.Errorf("link = %q, want %q", link, expectedLink)
+ }
+
+ filePath := filepath.Join(tmpDir, "test-key.txt")
+ stored, err := os.ReadFile(filePath)
+ if err != nil {
+ t.Fatalf("failed to read uploaded file: %v", err)
+ }
+ if string(stored) != string(data) {
+ t.Errorf("stored data = %q, want %q", stored, data)
+ }
+}
+
+func TestLocalStorage_Upload_WithBaseURL(t *testing.T) {
+ tmpDir := t.TempDir()
+ t.Setenv("LOCAL_UPLOAD_DIR", tmpDir)
+ t.Setenv("LOCAL_UPLOAD_BASE_URL", "http://localhost:8080")
+
+ store := NewLocalStorageFromEnv()
+ if store == nil {
+ t.Fatal("NewLocalStorageFromEnv returned nil")
+ }
+
+ ctx := context.Background()
+ data := []byte("hello world")
+ contentType := "text/plain"
+ filename := "test.txt"
+
+ link, err := store.Upload(ctx, "test-key.txt", data, contentType, filename)
+ if err != nil {
+ t.Fatalf("Upload failed: %v", err)
+ }
+
+ // When LOCAL_UPLOAD_BASE_URL is set, should return full URL
+ expectedLink := "http://localhost:8080/uploads/test-key.txt"
+ if link != expectedLink {
+ t.Errorf("link = %q, want %q", link, expectedLink)
+ }
+
+ filePath := filepath.Join(tmpDir, "test-key.txt")
+ stored, err := os.ReadFile(filePath)
+ if err != nil {
+ t.Fatalf("failed to read uploaded file: %v", err)
+ }
+ if string(stored) != string(data) {
+ t.Errorf("stored data = %q, want %q", stored, data)
+ }
+}
+
+func TestLocalStorage_Delete(t *testing.T) {
+ tmpDir := t.TempDir()
+ t.Setenv("LOCAL_UPLOAD_DIR", tmpDir)
+
+ store := NewLocalStorageFromEnv()
+ if store == nil {
+ t.Fatal("NewLocalStorageFromEnv returned nil")
+ }
+
+ ctx := context.Background()
+ data := []byte("hello world")
+
+ _, err := store.Upload(ctx, "delete-me.txt", data, "text/plain", "delete-me.txt")
+ if err != nil {
+ t.Fatalf("Upload failed: %v", err)
+ }
+
+ filePath := filepath.Join(tmpDir, "delete-me.txt")
+ if _, err := os.ReadFile(filePath); err != nil {
+ t.Fatalf("file should exist: %v", err)
+ }
+
+ store.Delete(ctx, "delete-me.txt")
+
+ if _, err := os.ReadFile(filePath); !os.IsNotExist(err) {
+ t.Errorf("file should be deleted")
+ }
+}
+
+func TestLocalStorage_KeyFromURL(t *testing.T) {
+ tmpDir := t.TempDir()
+ t.Setenv("LOCAL_UPLOAD_DIR", tmpDir)
+ // No baseURL set
+
+ store := NewLocalStorageFromEnv()
+ if store == nil {
+ t.Fatal("NewLocalStorageFromEnv returned nil")
+ }
+
+ tests := []struct {
+ name string
+ rawURL string
+ expected string
+ }{
+ {"local URL format", "/uploads/abc123.png", "abc123.png"},
+ {"local URL with subdir", "/uploads/2024/01/image.jpg", "image.jpg"},
+ {"just filename", "abc123.png", "abc123.png"},
+ {"full path", "/some/path/to/file.pdf", "file.pdf"},
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ got := store.KeyFromURL(tc.rawURL)
+ if got != tc.expected {
+ t.Errorf("KeyFromURL(%q) = %q, want %q", tc.rawURL, got, tc.expected)
+ }
+ })
+ }
+}
+
+func TestLocalStorage_KeyFromURL_WithBaseURL(t *testing.T) {
+ tmpDir := t.TempDir()
+ t.Setenv("LOCAL_UPLOAD_DIR", tmpDir)
+ t.Setenv("LOCAL_UPLOAD_BASE_URL", "http://localhost:8080")
+
+ store := NewLocalStorageFromEnv()
+ if store == nil {
+ t.Fatal("NewLocalStorageFromEnv returned nil")
+ }
+
+ tests := []struct {
+ name string
+ rawURL string
+ expected string
+ }{
+ {"full URL format", "http://localhost:8080/uploads/abc123.png", "abc123.png"},
+ {"full URL with subdir", "http://localhost:8080/uploads/2024/01/image.jpg", "image.jpg"},
+ {"local URL format still works", "/uploads/abc123.png", "abc123.png"},
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ got := store.KeyFromURL(tc.rawURL)
+ if got != tc.expected {
+ t.Errorf("KeyFromURL(%q) = %q, want %q", tc.rawURL, got, tc.expected)
+ }
+ })
+ }
+}
+
+func TestLocalStorage_DeleteKeys(t *testing.T) {
+ tmpDir := t.TempDir()
+ t.Setenv("LOCAL_UPLOAD_DIR", tmpDir)
+
+ store := NewLocalStorageFromEnv()
+ if store == nil {
+ t.Fatal("NewLocalStorageFromEnv returned nil")
+ }
+
+ ctx := context.Background()
+ data := []byte("hello world")
+
+ keys := []string{"file1.txt", "file2.txt", "file3.txt"}
+ for _, key := range keys {
+ _, err := store.Upload(ctx, key, data, "text/plain", key)
+ if err != nil {
+ t.Fatalf("Upload %s failed: %v", key, err)
+ }
+ }
+
+ store.DeleteKeys(ctx, keys)
+
+ for _, key := range keys {
+ filePath := filepath.Join(tmpDir, key)
+ if _, err := os.ReadFile(filePath); !os.IsNotExist(err) {
+ t.Errorf("file %s should be deleted", key)
+ }
+ }
+}
+
+func TestLocalStorage_KeyFromURL_Empty(t *testing.T) {
+ tmpDir := t.TempDir()
+ t.Setenv("LOCAL_UPLOAD_DIR", tmpDir)
+
+ store := NewLocalStorageFromEnv()
+ if store == nil {
+ t.Fatal("NewLocalStorageFromEnv returned nil")
+ }
+
+ if got := store.KeyFromURL(""); got != "" {
+ t.Errorf("KeyFromURL(\"\") = %q, want empty string", got)
+ }
+}
diff --git a/server/internal/storage/s3.go b/server/internal/storage/s3.go
index b032ccac0b..6ac13e537a 100644
--- a/server/internal/storage/s3.go
+++ b/server/internal/storage/s3.go
@@ -32,7 +32,7 @@ type S3Storage struct {
func NewS3StorageFromEnv() *S3Storage {
bucket := os.Getenv("S3_BUCKET")
if bucket == "" {
- slog.Info("S3_BUCKET not set, file upload disabled")
+ slog.Info("S3_BUCKET not set, cloud upload disabled")
return nil
}
@@ -88,21 +88,6 @@ func (s *S3Storage) storageClass() types.StorageClass {
return types.StorageClassIntelligentTiering
}
-// sanitizeFilename removes characters that could cause header injection in Content-Disposition.
-func sanitizeFilename(name string) string {
- var b strings.Builder
- b.Grow(len(name))
- for _, r := range name {
- // Strip control chars, newlines, null bytes, quotes, semicolons, backslashes
- if r < 0x20 || r == 0x7f || r == '"' || r == ';' || r == '\\' || r == '\x00' {
- b.WriteRune('_')
- } else {
- b.WriteRune(r)
- }
- }
- return b.String()
-}
-
// KeyFromURL extracts the S3 object key from a CDN or bucket URL.
// e.g. "https://multica-static.copilothub.ai/abc123.png" → "abc123.png"
func (s *S3Storage) KeyFromURL(rawURL string) string {
@@ -150,16 +135,6 @@ func (s *S3Storage) DeleteKeys(ctx context.Context, keys []string) {
}
}
-// isInlineContentType returns true for media types that browsers should
-// display inline (images, video, audio, PDF). Everything else triggers a
-// download via Content-Disposition: attachment.
-func isInlineContentType(ct string) bool {
- return strings.HasPrefix(ct, "image/") ||
- strings.HasPrefix(ct, "video/") ||
- strings.HasPrefix(ct, "audio/") ||
- ct == "application/pdf"
-}
-
func (s *S3Storage) Upload(ctx context.Context, key string, data []byte, contentType string, filename string) (string, error) {
safe := sanitizeFilename(filename)
disposition := "attachment"
diff --git a/server/internal/storage/storage.go b/server/internal/storage/storage.go
new file mode 100644
index 0000000000..b35fd222c3
--- /dev/null
+++ b/server/internal/storage/storage.go
@@ -0,0 +1,12 @@
+package storage
+
+import (
+ "context"
+)
+
+type Storage interface {
+ Upload(ctx context.Context, key string, data []byte, contentType string, filename string) (string, error)
+ Delete(ctx context.Context, key string)
+ DeleteKeys(ctx context.Context, keys []string)
+ KeyFromURL(rawURL string) string
+}
diff --git a/server/internal/storage/util.go b/server/internal/storage/util.go
new file mode 100644
index 0000000000..3fd8f06702
--- /dev/null
+++ b/server/internal/storage/util.go
@@ -0,0 +1,60 @@
+package storage
+
+import (
+ "net/http"
+ "path"
+ "strings"
+)
+
+// sanitizeFilename removes characters that could cause header injection in Content-Disposition.
+func sanitizeFilename(name string) string {
+ var b strings.Builder
+ b.Grow(len(name))
+ for _, r := range name {
+ // Strip control chars, newlines, null bytes, quotes, semicolons, backslashes
+ if r < 0x20 || r == 0x7f || r == '"' || r == ';' || r == '\\' || r == '\x00' {
+ b.WriteRune('_')
+ } else {
+ b.WriteRune(r)
+ }
+ }
+ return b.String()
+}
+
+// detectContentType determines the content type for a file.
+// Uses http.DetectContentType as base, with overrides for common extensions.
+func detectContentType(data []byte, filename string) string {
+ contentType := http.DetectContentType(data)
+ ext := strings.ToLower(path.Ext(filename))
+ if ct := overrideContentType(ext); ct != "" {
+ return ct
+ }
+ return contentType
+}
+
+// overrideContentType returns content type overrides for extensions that http.DetectContentType gets wrong.
+func overrideContentType(ext string) string {
+ switch ext {
+ case ".svg":
+ return "image/svg+xml"
+ case ".css":
+ return "text/css"
+ case ".js", ".mjs":
+ return "application/javascript"
+ case ".json":
+ return "application/json"
+ case ".wasm":
+ return "application/wasm"
+ }
+ return ""
+}
+
+// isInlineContentType returns true for media types that browsers should
+// display inline (images, video, audio, PDF). Everything else triggers a
+// download via Content-Disposition: attachment.
+func isInlineContentType(ct string) bool {
+ return strings.HasPrefix(ct, "image/") ||
+ strings.HasPrefix(ct, "video/") ||
+ strings.HasPrefix(ct, "audio/") ||
+ ct == "application/pdf"
+}