Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8859: fix(storage): disable legacy local file entry (#10252)
Multica Eve4d8cdc3d01f4
diff --git a/SELF_HOSTING_ADVANCED.md b/SELF_HOSTING_ADVANCED.mdindex ddbb25a209..075b5908a5 100644--- a/SELF_HOSTING_ADVANCED.md+++ b/SELF_HOSTING_ADVANCED.md@@ -639,7 +639,7 @@ NEXT_PUBLIC_API_URL=https://api.example.comNEXT_PUBLIC_WS_URL=wss://api.example.com/ws```-> **`NEXT_PUBLIC_API_URL` and `REMOTE_API_URL` take the backend's origin — scheme + host (+ port) — and no path.** Write `https://api.example.com`, never `https://api.example.com/api`. The browser client appends its own prefixes, so a path is doubled: requests go to `/api/api/...` and every avatar, image and attachment resolves under `<your-path>/uploads/...`, which the backend does not serve — the app loads but data calls and images 404. A trailing `/api` is now stripped defensively, but any other path is kept, because a reverse proxy may legitimately mount the whole backend under a prefix.+> **`NEXT_PUBLIC_API_URL` and `REMOTE_API_URL` take the backend's origin — scheme + host (+ port) — and no path.** Write `https://api.example.com`, never `https://api.example.com/api`. The browser client appends its own prefixes, so an `/api` suffix is doubled: requests go to `/api/api/...` instead of the backend's `/api/...` endpoints, breaking data calls and avatar loads. A trailing `/api` is now stripped defensively, but any other path is kept, because a reverse proxy may legitimately mount the whole backend under a prefix.>> This bites on upgrade: before v0.4.10 `NEXT_PUBLIC_API_URL` was inert in the published images, so a wrong value sat in `.env` doing nothing. v0.4.10 wired it through, and the stale value took effect. If you upgraded and the UI loads but nothing else does, check this variable first, then recreate the frontend container (`docker compose ... up -d --force-recreate frontend`) so the new value is picked up.@@ -669,10 +669,10 @@ COOKIE_DOMAIN= # empty: cookies are host-only on app.examp# FrontendNEXT_PUBLIC_API_URL= # empty: the client uses relative /api paths on the page originNEXT_PUBLIC_WS_URL= # empty-REMOTE_API_URL=http://backend:8080 # target the Next.js rewrites proxy /v1, /api, /auth and /uploads to+REMOTE_API_URL=http://backend:8080 # upstream for /v1, /api, /auth and /health```-Serve everything from the single `app.example.com` vhost. HTTP works out of the box, because Next.js rewrites forward `/v1`, `/api`, `/auth` and `/uploads` to `REMOTE_API_URL`. WebSockets do **not** go through those rewrites, so add a `/ws` block to the frontend vhost that reaches the backend directly:+Serve everything from the single `app.example.com` vhost. HTTP works out of the box, because the frontend forwards `/v1`, `/api`, `/auth` and `/health` to `REMOTE_API_URL`. WebSockets do **not** go through those rewrites, so add a `/ws` block to the frontend vhost that reaches the backend directly:```nginx# Add to the app.example.com server block above@@ -708,7 +708,7 @@ docker compose -f docker-compose.selfhost.yml up -d### WebSocket for LAN / Non-localhost Access-HTTP requests (Plugin API, issues, comments, uploads) work on LAN out of the box — Next.js rewrites proxy `/v1`, `/api`, `/auth`, and `/uploads` to the backend. **WebSockets do not**: Next.js rewrites only forward HTTP requests, not the `Upgrade` handshake a WebSocket needs. If you open the app on `http://<lan-ip>:3000`, real-time features (chat streaming, live issue updates, notifications) will fail to connect until you do one of the following:+HTTP requests (Plugin API, issues, comments, file uploads) work on LAN out of the box — the frontend forwards `/v1`, `/api`, `/auth`, and `/health` to the backend. **WebSockets do not**: Next.js rewrites only forward HTTP requests, not the `Upgrade` handshake a WebSocket needs. If you open the app on `http://<lan-ip>:3000`, real-time features (chat streaming, live issue updates, notifications) will fail to connect until you do one of the following:1. **Put a reverse proxy in front of the stack (recommended).** Nginx or Caddy terminates the WebSocket upgrade and forwards it to the backend on port 8080. See the [Reverse Proxy](#reverse-proxy) section above — the Nginx example already includes a `location /ws { ... }` block with the correct `Upgrade` / `Connection` headers. Once a proxy is in place the browser connects directly through it, so no frontend rebuild is needed.diff --git a/apps/web/config/runtime-urls.test.ts b/apps/web/config/runtime-urls.test.tsindex 462e3c8660..8b7064f4ee 100644--- a/apps/web/config/runtime-urls.test.ts+++ b/apps/web/config/runtime-urls.test.ts@@ -52,7 +52,7 @@ describe("resolveRemoteApiUrl", () => {});// Same defect as the browser base, same fix: the rewrite target already- // appends the full incoming pathname (`/api/**`, `/uploads/**`, `/ws`), so a+ // appends the full incoming pathname (`/api/**`, `/ws`), so a// configured `/api` suffix would double it (MUL-5922).it("strips a trailing /api from server-side rewrite targets", () => {expect(@@ -64,10 +64,10 @@ describe("resolveRemoteApiUrl", () => {}),).toBe("https://app.example.com/api/config");expect(- runtimeRewriteDestination("/uploads/workspaces/a.png", {+ runtimeRewriteDestination("/api/avatars/signature/avatar.png", {NEXT_PUBLIC_API_URL: "https://app.example.com/api",}),- ).toBe("https://app.example.com/uploads/workspaces/a.png");+ ).toBe("https://app.example.com/api/avatars/signature/avatar.png");});it("ignores whitespace-only or invalid backend URL values", () => {@@ -112,8 +112,7 @@ describe("browser runtime URLs", () => {});// #6619: these two values used to reach the browser untouched and became the- // XHR base, so every request went to `/api/api/**` and every avatar to- // `<base>/uploads/**` — which the backend serves at the root, hence 404.+ // XHR base, so every request went to `/api/api/**` instead of `/api/**`.it("rejects a relative public API URL so the browser stays same-origin", () => {expect(resolveBrowserApiBaseUrl({ NEXT_PUBLIC_API_URL: "/api" }),@@ -145,32 +144,32 @@ describe("browser runtime URLs", () => {).toBe("http://api:8080");});- // The XHR base doubles as the base for `/uploads/**` (avatars, attachment- // previews) via resolvePublicFileUrlWithBase in packages/core. Assert the+ // The XHR base doubles as the base for `/api/avatars/**` via+ // resolvePublicFileUrlWithBase in packages/core. Assert the// joined result, not just the base, because that join is what users saw fail.- it("produces working /api and /uploads targets for every supported value", () => {+ it("produces working API and avatar targets for every supported value", () => {const cases: Array<[string | undefined, string, string]> = [- [undefined, "/api/issues", "/uploads/avatars/a.png"],- ["/api", "/api/issues", "/uploads/avatars/a.png"],+ [undefined, "/api/issues", "/api/avatars/signature/a.png"],+ ["/api", "/api/issues", "/api/avatars/signature/a.png"],["https://app.example.com/api","https://app.example.com/api/issues",- "https://app.example.com/uploads/avatars/a.png",+ "https://app.example.com/api/avatars/signature/a.png",],["https://api.example.com","https://api.example.com/api/issues",- "https://api.example.com/uploads/avatars/a.png",+ "https://api.example.com/api/avatars/signature/a.png",],];- for (const [configured, expectedApi, expectedUpload] of cases) {+ for (const [configured, expectedApi, expectedAvatar] of cases) {// Mirrors the browser: CoreProvider defaults an absent base to "" and the// api client concatenates `${baseUrl}${path}`.const base =resolveBrowserApiBaseUrl({ NEXT_PUBLIC_API_URL: configured }) ?? "";expect(`${base}/api/issues`).toBe(expectedApi);- expect(`${base}/uploads/avatars/a.png`).toBe(expectedUpload);+ expect(`${base}/api/avatars/signature/a.png`).toBe(expectedAvatar);}});@@ -211,6 +210,17 @@ describe("browser runtime URLs", () => {});describe("runtimeRewriteDestination", () => {+ it.each(["/uploads", "/uploads/", "/uploads/workspaces/a.png"])(+ "does not forward the retired file entry: %s",+ (pathname) => {+ expect(+ runtimeRewriteDestination(pathname, {+ REMOTE_API_URL: "http://backend:8080",+ }),+ ).toBeUndefined();+ },+ );+it("keeps same-origin fallback when no runtime upstreams are configured", () => {expect(runtimeRewriteDestination("/api/config", {})).toBeUndefined();expect(runtimeRewriteDestination("/v1/context", {})).toBeUndefined();@@ -255,10 +265,10 @@ describe("runtimeRewriteDestination", () => {}),).toBe("http://backend:8080/auth/send-code");expect(- runtimeRewriteDestination("/uploads/workspaces/a.png", {+ runtimeRewriteDestination("/api/avatars/signature/a.png", {REMOTE_API_URL: "http://backend:8080",}),- ).toBe("http://backend:8080/uploads/workspaces/a.png");+ ).toBe("http://backend:8080/api/avatars/signature/a.png");});it("does not rewrite frontend auth callback pages", () => {diff --git a/apps/web/config/runtime-urls.ts b/apps/web/config/runtime-urls.tsindex 779cf9ba9e..c4d6b9ffb9 100644--- a/apps/web/config/runtime-urls.ts+++ b/apps/web/config/runtime-urls.ts@@ -22,11 +22,11 @@ function cleanHttpUrl(raw: string | undefined): string | undefined {// The API base names the backend ORIGIN, never its `/api` endpoint: every// caller already carries its own prefix (`packages/core/api/client.ts` sends-// `/api/**`, avatars resolve `/uploads/**`, realtime connects `/ws`), and the-// backend serves all three at the root (server/cmd/server/router.go). A base-// ending in `/api` therefore yields `/api/api/**` requests and 404s every-// upload — the most common self-hosting mistake (#6619, MUL-5922). Strip that-// one suffix instead of honouring it. Any other path is preserved: a reverse+// `/api/**`, avatars resolve `/api/avatars/**`, realtime connects `/ws`), and+// the backend serves these at the root (server/cmd/server/router.go). A base+// ending in `/api` therefore yields `/api/api/**` requests — the most common+// self-hosting mistake (#6619, MUL-5922). Strip that one suffix instead of+// honouring it. Any other path is preserved: a reverse// proxy may legitimately mount the whole backend under a prefix such as// `https://host/multica`.function stripApiPathSuffix(value: string): string {@@ -92,7 +92,7 @@ export function resolveDevDocsUrl(env: RuntimeEnv): string {// Same strictness as the server-side resolver above. A relative or otherwise// non-http value used to pass through untouched and became the XHR base, so-// `NEXT_PUBLIC_API_URL=/api` produced `/api/api/**` and `/api/uploads/**`+// `NEXT_PUBLIC_API_URL=/api` produced `/api/api/**`// (#6619). Returning undefined instead makes the browser fall back to// same-origin relative paths, which is what an unset value already does.export function resolveBrowserApiBaseUrl(env: RuntimeEnv): string | undefined {@@ -128,9 +128,6 @@ export function runtimeRewriteDestination(if (pathname === "/api" || pathname.startsWith("/api/")) {return appendPath(remoteApiUrl, pathname);}- if (pathname === "/uploads" || pathname.startsWith("/uploads/")) {- return appendPath(remoteApiUrl, pathname);- }if (pathname === "/ws") {return appendPath(remoteApiUrl, "/ws");}diff --git a/apps/web/next.config.test.ts b/apps/web/next.config.test.tsnew file mode 100644index 0000000000..93d1683d5f--- /dev/null+++ b/apps/web/next.config.test.ts@@ -0,0 +1,28 @@+// @vitest-environment node+import { describe, expect, it, vi } from "vitest";+import { hasLocalMatch } from "next/dist/shared/lib/match-local-pattern";++vi.mock("dotenv", () => ({ config: vi.fn() }));+vi.mock("fumadocs-mdx/next", () => ({+ createMDX: () => (config: unknown) => config,+}));++import nextConfig from "./next.config";++describe("image optimization paths", () => {+ it.each([+ "/uploads/workspaces/workspace/attachment.png",+ "/api/attachments/attachment/download",+ "/api/attachments/attachment/signed-download?exp=1&sig=signature",+ "/images/hero.png?url=/uploads/workspaces/workspace/attachment.png",+ ])("rejects private or unexpected sources: %s", (url) => {+ expect(hasLocalMatch(nextConfig.images?.localPatterns, url)).toBe(false);+ });++ it.each(["/images/hero.png", "/usecases/team/screenshot.webp"])(+ "keeps landing images available: %s",+ (url) => {+ expect(hasLocalMatch(nextConfig.images?.localPatterns, url)).toBe(true);+ },+ );+});diff --git a/apps/web/next.config.ts b/apps/web/next.config.tsindex 4e1b2e03c9..65a4182f65 100644--- a/apps/web/next.config.ts+++ b/apps/web/next.config.ts@@ -47,6 +47,10 @@ const nextConfig: NextConfig = {images: {formats: ["image/avif", "image/webp"],qualities: [75, 80, 85],+ localPatterns: [+ { pathname: "/images/**", search: "" },+ { pathname: "/usecases/**", search: "" },+ ],},async rewrites() {return {@@ -86,10 +90,6 @@ const nextConfig: NextConfig = {source: "/auth/:path*",destination: `${remoteApiUrl}/auth/:path*`,},- {- source: "/uploads/:path*",- destination: `${remoteApiUrl}/uploads/:path*`,- },]: [],fallback: [],diff --git a/apps/web/proxy.ts b/apps/web/proxy.tsindex 3097d9cf6d..f8f6ac4795 100644--- a/apps/web/proxy.ts+++ b/apps/web/proxy.ts@@ -122,7 +122,6 @@ export const config = {"/api","/api/((?!upload-file(?:/|$)).*)","/auth/:path*",- "/uploads/:path*","/docs/:path*","/ws","/((?!api|v1|_next/static|_next/image|favicon.ico|.*\\.).*)",diff --git a/deploy/helm/multica/values.yaml b/deploy/helm/multica/values.yamlindex 2acd48196d..8da494238d 100644--- a/deploy/helm/multica/values.yaml+++ b/deploy/helm/multica/values.yaml@@ -194,7 +194,7 @@ frontend:replicas: 1config:# Backend origin used by the frontend runtime proxy for /v1, /api, /auth,- # /uploads, and /ws. Empty defaults to this release's backend Service.+ # /health, and /ws. Empty defaults to this release's backend Service.remoteApiUrl: ""# Optional docs origin used by the frontend runtime proxy for /docs.docsUrl: ""diff --git a/server/cmd/server/local_uploads_test.go b/server/cmd/server/local_uploads_test.gonew file mode 100644index 0000000000..0ced4749cd--- /dev/null+++ b/server/cmd/server/local_uploads_test.go@@ -0,0 +1,119 @@+package main++import (+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "strings"+ "testing"++ "github.com/google/uuid"++ "github.com/multica-ai/multica/server/internal/analytics"+ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/realtime"+ "github.com/multica-ai/multica/server/internal/testutil"+)++func TestLocalUploadEntryIsDisabled(t *testing.T) {+ t.Setenv("S3_BUCKET", "")+ t.Setenv("LOCAL_UPLOAD_BASE_URL", "")+ dir := t.TempDir()+ t.Setenv("LOCAL_UPLOAD_DIR", dir)+ key := "workspaces/" + testWorkspaceID + "/" + uuid.NewString() + ".png"+ full := filepath.Join(dir, filepath.FromSlash(key))+ if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil {+ t.Fatal(err)+ }+ for _, name := range []string{full, full + ".meta.json"} {+ if err := os.WriteFile(name, []byte("PRIVATE"), 0o600); err != nil {+ t.Fatal(err)+ }+ }+ router := NewRouter(testPool, realtime.NewHub(), events.New(), analytics.NoopClient{}, nil)+ for _, path := range []string{+ "/uploads",+ "/uploads/",+ "/uploads/workspaces/",+ "/uploads/workspaces/" + testWorkspaceID + "/",+ "/uploads/" + key,+ "/uploads/" + key + ".meta.json/",+ } {+ for _, token := range []string{"", testToken} {+ for _, method := range []string{http.MethodGet, http.MethodHead} {+ req := httptest.NewRequest(method, path, nil)+ if token != "" {+ req.Header.Set("Authorization", "Bearer "+token)+ }+ w := httptest.NewRecorder()+ router.ServeHTTP(w, req)+ if w.Code != http.StatusNotFound {+ t.Errorf("%s %s (authenticated=%t) = %d, want 404", method, path, token != "", w.Code)+ }+ }+ }+ }+}++func TestLocalAttachmentAPIStillRequiresMembership(t *testing.T) {+ t.Setenv("CORS_ALLOWED_ORIGINS", "https://app.example.test")+ t.Setenv("S3_BUCKET", "")+ t.Setenv("LOCAL_UPLOAD_BASE_URL", "")+ dir := t.TempDir()+ t.Setenv("LOCAL_UPLOAD_DIR", dir)+ id := uuid.NewString()+ key := "workspaces/" + testWorkspaceID + "/" + id + ".png"+ full := filepath.Join(dir, filepath.FromSlash(key))+ if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil {+ t.Fatal(err)+ }+ const body = "PRIVATE IMAGE"+ if err := os.WriteFile(full, []byte(body), 0o600); err != nil {+ t.Fatal(err)+ }+ fixture := testutil.New(testPool, testWorkspaceID, testUserID)+ fixture.Insert(t, "attachment", testutil.Cols{+ "id": id, "workspace_id": testWorkspaceID,+ "uploader_type": "member", "uploader_id": testUserID,+ "filename": "private.png", "url": "/uploads/" + key,+ "content_type": "image/png", "size_bytes": len(body),+ })+ foreignToken, err := generateTestJWT(uuid.NewString(), "[email protected]", "Outsider")+ if err != nil {+ t.Fatal(err)+ }+ router := NewRouter(testPool, realtime.NewHub(), events.New(), analytics.NoopClient{}, nil)+ for _, tc := range []struct {+ name string+ token string+ code int+ }{+ {"anonymous", "", http.StatusUnauthorized},+ {"non-member", foreignToken, http.StatusNotFound},+ {"member", testToken, http.StatusOK},+ } {+ t.Run(tc.name, func(t *testing.T) {+ req := httptest.NewRequest(http.MethodGet, "/api/attachments/"+id+"/download", nil)+ if tc.token != "" {+ req.Header.Set("Authorization", "Bearer "+tc.token)+ }+ w := httptest.NewRecorder()+ router.ServeHTTP(w, req)+ if w.Code != tc.code {+ t.Fatalf("status = %d, want %d; body=%s", w.Code, tc.code, w.Body.String())+ }+ if tc.code == http.StatusOK {+ if got := w.Body.String(); got != body {+ t.Fatalf("body = %q, want %q", got, body)+ }+ if got := w.Header().Get("Content-Disposition"); got != `inline; filename="private.png"` {+ t.Errorf("Content-Disposition = %q, want original filename", got)+ }+ if got := w.Header().Get("Content-Security-Policy"); !strings.Contains(got, "frame-ancestors 'self' https://app.example.test") {+ t.Errorf("Content-Security-Policy = %q, want configured preview origin", got)+ }+ }+ })+ }+}diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 17762043a8..816786c76d 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -1546,16 +1546,6 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busrealtime.HandleWebSocket(hub, mc, pr, slugResolver, w, r)})- // Local file serving (when using local storage). Served through the- // handler so /uploads/* carries the same preview security headers as the- // /api/attachments download endpoint; self-hosted split-origin/same-origin- // clients can then iframe-preview PDFs/HTML fetched straight from the- // static route instead of hitting the global frame-ancestors 'none' CSP.- // See MUL-3821 / #4477.- if _, ok := store.(*storage.LocalStorage); ok {- r.Get("/uploads/*", h.ServeLocalUpload)- }-// Capability-authenticated attachment download (MUL-5292). Public by// necessity: a native download (Electron's webContents.downloadURL, a// cross-site webview <img>) carries neither Authorization nor a sessiondiff --git a/server/internal/handler/avatar.go b/server/internal/handler/avatar.goindex 817034bf73..80d88afd19 100644--- a/server/internal/handler/avatar.go+++ b/server/internal/handler/avatar.go@@ -303,10 +303,9 @@ func (h *Handler) ownedStorageKey(rawURL string) string {// already loadable by an unauthenticated browser fetch, in which case// rewriting it would only add a pointless hop through the API.func (h *Handler) avatarObjectLoadsUnauthenticated(rawURL string) bool {- // LocalStorage objects are served by the public /uploads/* route, whether- // the stored URL is site-relative or absolute via LOCAL_UPLOAD_BASE_URL.+ // Direct local-file serving is disabled, even when a base URL is configured.if _, ok := h.Storage.(*storage.LocalStorage); ok {- return true+ return false}// Otherwise: a public CDN domain with no per-request CloudFront signing.// In signed-CloudFront mode the same domain serves private content and thediff --git a/server/internal/handler/avatar_test.go b/server/internal/handler/avatar_test.goindex 883329b504..4d50e7ff97 100644--- a/server/internal/handler/avatar_test.go+++ b/server/internal/handler/avatar_test.go@@ -12,6 +12,7 @@ import ("github.com/go-chi/chi/v5""github.com/google/uuid""github.com/multica-ai/multica/server/internal/storage"+ "github.com/multica-ai/multica/server/internal/testutil")// withAvatarStorage swaps the handler's storage/config for one test and@@ -79,18 +80,38 @@ func TestResolveAvatarURL_CloudFrontSignedRewrites(t *testing.T) {}}-// TestResolveAvatarURL_LocalStorageUnchanged — LocalStorage objects are served-// by the public /uploads/* route, so they are already loadable as-is.-func TestResolveAvatarURL_LocalStorageUnchanged(t *testing.T) {- local := storage.NewLocalStorageFromEnv()- if local == nil {- t.Skip("local storage unavailable")- }- withAvatarStorage(t, local, "")-- raw := local.ObjectURL(testAvatarKey)- if got := testHandler.resolveAvatarURL(raw); got != raw {- t.Fatalf("resolveAvatarURL = %q, want unchanged %q", got, raw)+func TestResolveAvatarURL_LocalStorageUsesSignedEndpoint(t *testing.T) {+ for _, baseURL := range []string{"", "https://files.example.test"} {+ t.Run("storage base="+baseURL, func(t *testing.T) {+ t.Setenv("LOCAL_UPLOAD_DIR", t.TempDir())+ t.Setenv("LOCAL_UPLOAD_BASE_URL", baseURL)+ local := storage.NewLocalStorageFromEnv()+ if local == nil {+ t.Fatal("local storage unavailable")+ }+ withAvatarStorage(t, local, "https://api.example.test")+ id := uuid.NewString()+ key := "workspaces/" + testWorkspaceID + "/" + id + ".png"+ const body = "AVATAR BYTES"+ raw, err := local.Upload(context.Background(), key, []byte(body), "image/png", "avatar.png")+ if err != nil {+ t.Fatal(err)+ }+ dbfx.Insert(t, "attachment", testutil.Cols{+ "id": id, "workspace_id": testWorkspaceID,+ "uploader_type": "member", "uploader_id": testUserID,+ "filename": "avatar.png", "url": raw,+ "content_type": "image/png", "size_bytes": len(body),+ })+ want := "https://api.example.test" + avatarURLPath(key)+ if got := testHandler.resolveAvatarURL(raw); got != want {+ t.Fatalf("resolveAvatarURL = %q, want %q", got, want)+ }+ w := serveAvatarRequest(t, signAvatarKey(key), key)+ if w.Code != http.StatusOK || w.Body.String() != body {+ t.Fatalf("signed avatar: status=%d body=%q, want 200 %q", w.Code, w.Body.String(), body)+ }+ })}}diff --git a/server/internal/handler/file.go b/server/internal/handler/file.goindex 9959e55e02..cda64e73bc 100644--- a/server/internal/handler/file.go+++ b/server/internal/handler/file.go@@ -807,10 +807,8 @@ func (h *Handler) loadAttachmentForRequest(w http.ResponseWriter, r *http.Reques// workspace. This helper keeps the URL clean (`/api/attachments/{id}/download`)// and treats the attachment id + cookie/Bearer auth as sufficient.//-// Membership uses the same 404-on-deny shape as ServeLocalUpload so the-// route does not act as an IDOR oracle for attachment IDs that happen to-// belong to a different workspace. The membership cache fast path mirrors-// canReadWorkspaceUpload exactly.+// A denied membership check returns 404 so the route does not reveal+// attachment IDs belonging to a different workspace.func (h *Handler) loadAttachmentForDownload(w http.ResponseWriter, r *http.Request) (db.Attachment, bool) {attachmentID := chi.URLParam(r, "id")attUUID, ok := parseUUIDOrBadRequest(w, attachmentID, "attachment id")@@ -819,9 +817,7 @@ func (h *Handler) loadAttachmentForDownload(w http.ResponseWriter, r *http.Reque}att, err := h.Queries.GetAttachmentByIDOnly(r.Context(), attUUID)if err != nil {- // 404 (not 403/401) so non-member and non-existent look identical- // to outside callers. Same shape as ServeLocalUpload's- // canReadWorkspaceUpload deny path.+ // Non-member and non-existent look identical to outside callers.writeError(w, http.StatusNotFound, "attachment not found")return db.Attachment{}, false}@@ -967,24 +963,6 @@ func shouldProxyAttachmentURL(rawURL string) bool {return false}-// ServeLocalUpload serves a local-disk object from the public /uploads/*-// route. It carries the same preview security headers as the authenticated-// download endpoint so self-hosted deployments — same-origin or split-// frontend/backend origins — can inline-render images and iframe-preview-// documents (PDF/HTML) fetched straight from the static route. Without these-// headers the global "frame-ancestors 'none'" policy blocks those previews.-// See MUL-3821 / #4477.-func (h *Handler) ServeLocalUpload(w http.ResponseWriter, r *http.Request) {- local, ok := h.Storage.(*storage.LocalStorage)- if !ok {- http.NotFound(w, r)- return- }- h.setAttachmentPreviewSecurityHeaders(w)- key := strings.TrimPrefix(r.URL.Path, "/uploads/")- local.ServeFile(w, r, key)-}-// proxyAttachmentDownload streams an attachment through the API instead of// redirecting to a signed storage URL (used for local-disk / private-host// backends, see resolveAttachmentDownloadMode).diff --git a/server/internal/handler/file_test.go b/server/internal/handler/file_test.goindex f283a318cc..d91391cdb5 100644--- a/server/internal/handler/file_test.go+++ b/server/internal/handler/file_test.go@@ -15,8 +15,6 @@ import ("net/http""net/http/httptest""net/url"- "os"- "path/filepath""strings""sync""testing"@@ -1006,7 +1004,7 @@ func TestDownloadAttachment_BareNavigationServesMemberWithoutWorkspaceHeaders(t// IDOR boundary: a stray attachment ID belonging to a workspace the// requester is NOT a member of must return 404, not 200 (would leak// bytes) and not 403 (would confirm the ID exists). Mirrors-// ServeLocalUpload's deny shape.+// the non-existent attachment response.func TestDownloadAttachment_BareNavigationDeniesNonMemberWith404(t *testing.T) {if testPool == nil {t.Skip("test database not available")@@ -2006,63 +2004,3 @@ func TestIsDurablePublicURL(t *testing.T) {})}}--// TestServeLocalUpload_RelaxesFrameAncestorsForPreview covers the self-hosted-// local-disk case where document previews (PDF/HTML) are fetched straight from-// the public /uploads/* static route. That route inherits the global-// "frame-ancestors 'none'" CSP from the middleware, which blocks iframe-// previews; ServeLocalUpload must overwrite it with the same relaxed preview-// policy the /api/attachments download endpoint uses. See MUL-3821 / #4477.-func TestServeLocalUpload_RelaxesFrameAncestorsForPreview(t *testing.T) {- dir := t.TempDir()- key := "workspaces/ws-1/preview.pdf"- full := filepath.Join(dir, filepath.FromSlash(key))- if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil {- t.Fatalf("mkdir: %v", err)- }- const body = "%PDF-1.7 local-disk preview"- if err := os.WriteFile(full, []byte(body), 0o644); err != nil {- t.Fatalf("write file: %v", err)- }-- t.Setenv("LOCAL_UPLOAD_DIR", dir)- t.Setenv("LOCAL_UPLOAD_BASE_URL", "")- local := storage.NewLocalStorageFromEnv()- if local == nil {- t.Fatal("NewLocalStorageFromEnv returned nil")- }-- h := &Handler{- Storage: local,- cfg: Config{AttachmentFrameAncestors: []string{"https://app.example.test"}},- }-- req := httptest.NewRequest(http.MethodGet, "/uploads/"+key, nil)- w := httptest.NewRecorder()- // Simulate the global CSP middleware having already stamped the strict- // policy on the response before the static route runs.- w.Header().Set("Content-Security-Policy", "default-src 'self'; frame-ancestors 'none'")-- h.ServeLocalUpload(w, req)-- if w.Code != http.StatusOK {- t.Fatalf("status = %d, want 200; body=%q", w.Code, w.Body.String())- }- if got := w.Body.String(); got != body {- t.Fatalf("body = %q, want %q", got, body)- }- requireAttachmentPreviewCSP(t, w.Header(), "https://app.example.test")-}--// TestServeLocalUpload_NonLocalStorage404 guards the defensive branch: the-// /uploads/* route is only registered under local storage, but the handler-// must not serve anything when the backing store is not local disk.-func TestServeLocalUpload_NonLocalStorage404(t *testing.T) {- h := &Handler{Storage: &mockStorage{}}- req := httptest.NewRequest(http.MethodGet, "/uploads/workspaces/ws-1/x.png", nil)- w := httptest.NewRecorder()- h.ServeLocalUpload(w, req)- if w.Code != http.StatusNotFound {- t.Fatalf("status = %d, want 404", w.Code)- }-}diff --git a/server/internal/storage/local.go b/server/internal/storage/local.goindex 4dab8403db..974f9a5b7b 100644--- a/server/internal/storage/local.go+++ b/server/internal/storage/local.go@@ -7,7 +7,6 @@ import ("fmt""io""log/slog"- "net/http""net/url""os""path/filepath"@@ -19,11 +18,8 @@ type LocalStorage struct {baseURL string}-// metaSuffix is the on-disk extension for the sidecar JSON file that-// captures an upload's original filename and sniffed content type. The-// sidecar exists so ServeFile can set Content-Disposition the way S3's-// PutObject path already does, instead of letting the browser fall back-// to the storage-key basename for the download filename.+// metaSuffix identifies legacy sidecar metadata. Uploads retain this on-disk+// format; HTTP readers use the attachment record for filenames and types.const metaSuffix = ".meta.json"// tempSuffix is the on-disk extension of the staging file writeAtomic renames@@ -156,12 +152,7 @@ func (s *LocalStorage) Upload(ctx context.Context, key string, data []byte, contif err := writeAtomic(dest, bytes.NewReader(data)); err != nil {return "", err}- // Best-effort sidecar so ServeFile can restore the original filename in- // Content-Disposition. A failure here is logged but does not fail the- // upload — the file is still usable, just without the human-readable- // download name. Skip when there's no filename to preserve: a sidecar- // without a filename is dead weight, since ServeFile only reads it for- // that field.+ // Retain legacy sidecar metadata without failing an otherwise valid upload.if filename != "" {body, _ := json.Marshal(localMeta{Filename: filename, ContentType: contentType})if err := os.WriteFile(dest+metaSuffix, body, 0644); err != nil {@@ -247,8 +238,8 @@ func tempPath(dest string) string {// isInternalLocalPath reports whether key names one of the local backend's own// files — the .meta.json sidecar or a .<name>.tmp staging file — rather than an-// object. Read paths take the key straight from the request URL, so both must-// be unreachable: a staging file would otherwise expose a half-written body.+// object. Both must be unreachable through readers: a staging file would+// otherwise expose a half-written body.// Object keys are server-generated (UUID or hash basenames) and never start// with a dot, so a user uploading "notes.tmp" (key "<uuid>.tmp") is unaffected.func isInternalLocalPath(key string) bool {@@ -263,44 +254,6 @@ 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) {- // The sidecar and the staging file are implementation details of the local- // backend; refuse to serve them directly so /uploads/<key>.meta.json (or a- // half-written .<key>.tmp) doesn't become a stable read API. Comes before- // any disk work so a path-traversal attempt at a sibling can't trigger an- // out-of-tree read.- if isInternalLocalPath(filename) {- http.NotFound(w, r)- return- }-- filePath := filepath.Join(s.uploadDir, filename)- // filepath.Join cleans the path but doesn't enforce containment, so a- // caller passing "../etc/passwd" lands outside uploadDir. http.ServeFile- // rejects such requests on r.URL.Path, but readLocalMeta runs first —- // without this guard a crafted path could trigger a stray disk read on- // an arbitrary <some-path>.meta.json before the 400 lands.- if !isUnder(s.uploadDir, filePath) {- http.NotFound(w, r)- return- }- slog.Info("serving file", "filename", filename, "filepath", filePath)-- // Mirror the S3 Upload path: when sidecar metadata exists for this key,- // set Content-Disposition with the original uploaded filename. Without- // it, browsers download the file under the storage-key basename (the- // UUID + extension) instead of the human-readable name the uploader- // chose. Uploads from before the sidecar landed have no .meta.json on- // disk and fall through to the existing behavior.- if meta, ok := readLocalMeta(filePath); ok && meta.Filename != "" {- w.Header().Set("Content-Disposition", ContentDisposition(meta.ContentType, meta.Filename))- }-- // 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)-}-// isUnder reports whether target resolves to a path inside dir (or equal to// it). Both inputs are passed through filepath.Clean so trailing slashes and// "." segments don't fool the comparison.@@ -312,18 +265,6 @@ func isUnder(dir, target string) bool {return rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator))}-func readLocalMeta(filePath string) (localMeta, bool) {- body, err := os.ReadFile(filePath + metaSuffix)- if err != nil {- return localMeta{}, false- }- var meta localMeta- if err := json.Unmarshal(body, &meta); err != nil {- return localMeta{}, false- }- return meta, true-}-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 {diff --git a/server/internal/storage/local_test.go b/server/internal/storage/local_test.goindex 0a5ae23a16..17dbbb74ca 100644--- a/server/internal/storage/local_test.go+++ b/server/internal/storage/local_test.go@@ -3,8 +3,6 @@ package storageimport ("context""io"- "net/http"- "net/http/httptest""os""path/filepath""testing"@@ -217,178 +215,8 @@ func TestLocalStorage_KeyFromURL_Empty(t *testing.T) {}}-// TestLocalStorage_ServeFile_ContentDispositionFromSidecar verifies the fix-// for issue #2442: downloads served from /uploads/* must carry the original-// uploaded filename in Content-Disposition, mirroring the S3 Upload path's-// existing ContentDisposition behavior. Without this, browsers fall back to-// the storage-key basename (UUID + ext) for the download filename.-func TestLocalStorage_ServeFile_ContentDispositionFromSidecar(t *testing.T) {- tmpDir := t.TempDir()- t.Setenv("LOCAL_UPLOAD_DIR", tmpDir)-- store := NewLocalStorageFromEnv()- if store == nil {- t.Fatal("NewLocalStorageFromEnv returned nil")- }-- cases := []struct {- name string- key string- contentType string- filename string- wantHeader string- }{- {- name: "attachment for non-inline type",- key: "workspaces/ws-1/abc.xlsx",- contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",- filename: "Bwave JE_V1.xlsx",- wantHeader: `attachment; filename="Bwave JE_V1.xlsx"`,- },- {- name: "inline for image",- key: "workspaces/ws-1/def.png",- contentType: "image/png",- filename: "screenshot 2026-05-11.png",- wantHeader: `inline; filename="screenshot 2026-05-11.png"`,- },- {- name: "filename with header-injection characters is sanitized",- key: "workspaces/ws-1/ghi.txt",- contentType: "text/plain",- filename: "weird\";name.txt",- wantHeader: `attachment; filename="weird__name.txt"`,- },- {- // SVG can carry <script>/onload — never serve inline.- name: "attachment for svg (stored-XSS prevention)",- key: "workspaces/ws-1/jkl.svg",- contentType: "image/svg+xml",- filename: "logo.svg",- wantHeader: `attachment; filename="logo.svg"`,- },- }-- for _, tc := range cases {- t.Run(tc.name, func(t *testing.T) {- ctx := context.Background()- if _, err := store.Upload(ctx, tc.key, []byte("body"), tc.contentType, tc.filename); err != nil {- t.Fatalf("Upload failed: %v", err)- }-- req := httptest.NewRequest(http.MethodGet, "/uploads/"+tc.key, nil)- rec := httptest.NewRecorder()- store.ServeFile(rec, req, tc.key)-- got := rec.Header().Get("Content-Disposition")- if got != tc.wantHeader {- t.Errorf("Content-Disposition = %q, want %q", got, tc.wantHeader)- }- })- }-}--// TestLocalStorage_ServeFile_NoSidecarFallback documents the graceful-// degradation path: files uploaded before the sidecar landed (or written-// out-of-band) have no .meta.json on disk and ServeFile must not set-// Content-Disposition — leaving the existing pre-fix behavior intact.-func TestLocalStorage_ServeFile_NoSidecarFallback(t *testing.T) {- tmpDir := t.TempDir()- t.Setenv("LOCAL_UPLOAD_DIR", tmpDir)-- store := NewLocalStorageFromEnv()- if store == nil {- t.Fatal("NewLocalStorageFromEnv returned nil")- }-- key := "legacy-no-sidecar.txt"- if err := os.WriteFile(filepath.Join(tmpDir, key), []byte("body"), 0644); err != nil {- t.Fatalf("seed write failed: %v", err)- }-- req := httptest.NewRequest(http.MethodGet, "/uploads/"+key, nil)- rec := httptest.NewRecorder()- store.ServeFile(rec, req, key)-- if got := rec.Header().Get("Content-Disposition"); got != "" {- t.Errorf("Content-Disposition = %q, want empty (no sidecar fallback)", got)- }-}--// TestLocalStorage_ServeFile_RejectsSidecarSuffix verifies that the sidecar-// JSON itself is not addressable via /uploads/*. The sidecar is an-// implementation detail; exposing it would turn the filename + content-type-// pair into a stable read API and make any future ACL change leakier than-// the data file it sits next to.-func TestLocalStorage_ServeFile_RejectsSidecarSuffix(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()- if _, err := store.Upload(ctx, "abc.xlsx", []byte("body"), "text/plain", "real.xlsx"); err != nil {- t.Fatalf("Upload failed: %v", err)- }-- sidecarKey := "abc.xlsx" + metaSuffix- req := httptest.NewRequest(http.MethodGet, "/uploads/"+sidecarKey, nil)- rec := httptest.NewRecorder()- store.ServeFile(rec, req, sidecarKey)-- if rec.Code != http.StatusNotFound {- t.Errorf("status = %d, want 404", rec.Code)- }- if got := rec.Header().Get("Content-Disposition"); got != "" {- t.Errorf("Content-Disposition = %q, want empty", got)- }-}--// TestLocalStorage_ServeFile_RejectsPathTraversal documents that a key-// pointing outside uploadDir is rejected before any sidecar read. Without-// this guard, readLocalMeta would attempt a disk read at <some-path>.meta.json-// before http.ServeFile's own ".." check fires on r.URL.Path.-func TestLocalStorage_ServeFile_RejectsPathTraversal(t *testing.T) {- tmpDir := t.TempDir()- t.Setenv("LOCAL_UPLOAD_DIR", tmpDir)-- store := NewLocalStorageFromEnv()- if store == nil {- t.Fatal("NewLocalStorageFromEnv returned nil")- }-- // Seed a sidecar OUTSIDE uploadDir so we'd notice if it were read: the- // header would carry "leaked.xlsx". Locating the sibling inside the- // per-test TempDir keeps the test self-contained — no real /etc reads.- parentDir := filepath.Dir(tmpDir)- leakedBase := filepath.Join(parentDir, "leaked-target")- if err := os.WriteFile(leakedBase+metaSuffix, []byte(`{"filename":"leaked.xlsx","content_type":"text/plain"}`), 0644); err != nil {- t.Fatalf("seed leaked sidecar failed: %v", err)- }- t.Cleanup(func() {- os.Remove(leakedBase + metaSuffix)- })-- traversal := "../" + filepath.Base(leakedBase)- req := httptest.NewRequest(http.MethodGet, "/uploads/"+traversal, nil)- rec := httptest.NewRecorder()- store.ServeFile(rec, req, traversal)-- if rec.Code != http.StatusNotFound {- t.Errorf("status = %d, want 404", rec.Code)- }- if got := rec.Header().Get("Content-Disposition"); got != "" {- t.Errorf("Content-Disposition = %q, want empty (sidecar must not leak)", got)- }-}--// TestLocalStorage_Upload_SkipsSidecarWhenFilenameEmpty verifies the tighter-// Upload gate: a write with no filename has nothing useful to preserve, so-// we shouldn't litter the upload directory with content-type-only sidecars-// that ServeFile would ignore anyway.+// TestLocalStorage_Upload_SkipsSidecarWhenFilenameEmpty verifies that uploads+// without a filename do not create content-type-only sidecars.func TestLocalStorage_Upload_SkipsSidecarWhenFilenameEmpty(t *testing.T) {tmpDir := t.TempDir()t.Setenv("LOCAL_UPLOAD_DIR", tmpDir)