Skip to content

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

Go

fix(attachments): serve proxy-mode downloads with a scoped capability URL (MUL-5292) (#6092)

Bohan Jiangbdae0d2a0322
diff --git a/packages/views/editor/use-download-attachment.test.tsx b/packages/views/editor/use-download-attachment.test.tsx
index 6238740556..877983e44e 100644
--- a/packages/views/editor/use-download-attachment.test.tsx
+++ b/packages/views/editor/use-download-attachment.test.tsx
@@ -267,6 +267,34 @@ describe("useDownloadAttachment (desktop)", () => {
);
});
+ // MUL-5292: in proxy mode the backend now answers with a capability URL —
+ // still server-relative, but carrying `?exp=&sig=`. The query is what makes
+ // the request authenticate itself, so it must survive the resolve step and
+ // reach the native downloader intact.
+ it("preserves the capability query when resolving a relative proxy-mode download_url", async () => {
+ const downloadURL = vi.fn();
+ (window as unknown as { desktopAPI: { downloadURL: typeof downloadURL } }).desktopAPI = {
+ downloadURL,
+ };
+ getBaseUrlMock.mockReturnValue("https://api.example.test");
+ getAttachmentMock.mockResolvedValueOnce({
+ id: "att-1",
+ url: "https://static.example.test/file.md",
+ download_url: "/api/attachments/att-1/signed-download?exp=1800000060&sig=deadbeef",
+ filename: "file.md",
+ });
+
+ const { result } = renderHook(() => useDownloadAttachment());
+
+ await act(async () => {
+ await result.current("att-1");
+ });
+
+ expect(downloadURL).toHaveBeenCalledWith(
+ "https://api.example.test/api/attachments/att-1/signed-download?exp=1800000060&sig=deadbeef",
+ );
+ });
+
it("trims a trailing slash on the API base when resolving a relative download_url", async () => {
const downloadURL = vi.fn();
(window as unknown as { desktopAPI: { downloadURL: typeof downloadURL } }).desktopAPI = {
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 857d7af5c3..06b5a3a272 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -748,6 +748,17 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
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 session
+ // cookie, so there is nothing here for middleware.Auth to read. The
+ // short-lived, single-attachment signature in the query is the credential,
+ // and it is only ever minted by the AUTHENTICATED GET
+ // /api/attachments/{id} after that request's membership check passed.
+ // The authenticated /api/attachments/{id}/download route below is
+ // unchanged — this one is purely additive.
+ r.Get("/api/attachments/{id}/signed-download", h.DownloadAttachmentWithCapability)
+
// Auth (public) — per-IP rate limiting.
if rdb == nil {
slog.Warn("rate limiting disabled: REDIS_URL not configured")
diff --git a/server/internal/handler/attachment_capability.go b/server/internal/handler/attachment_capability.go
new file mode 100644
index 0000000000..9307e15d14
--- /dev/null
+++ b/server/internal/handler/attachment_capability.go
@@ -0,0 +1,186 @@
+package handler
+
+import (
+ "crypto/hmac"
+ "crypto/sha256"
+ "encoding/hex"
+ "net/http"
+ "strconv"
+ "sync"
+ "time"
+
+ "github.com/go-chi/chi/v5"
+ "github.com/multica-ai/multica/server/internal/auth"
+)
+
+// Attachment download capabilities — MUL-5292.
+//
+// A native download is a browser-level request: Electron's
+// webContents.downloadURL (and an <img> in a cross-site webview) carries
+// neither the desktop client's Authorization header nor a session cookie, so
+// the authenticated /api/attachments/{id}/download endpoint answers 401 and
+// the user never gets a file.
+//
+// CloudFront and presign deployments already sidestep this — the
+// authenticated GetAttachmentByID hands those clients a signed storage URL
+// that needs no credentials of ours. Proxy mode (local disk, private object
+// host) had no equivalent and kept returning the auth-gated API path, which
+// is the entirety of the bug: one unfinished branch of an otherwise correct
+// design, not a missing Electron feature.
+//
+// A capability closes that branch the same way the other two modes do. The
+// ALREADY-AUTHENTICATED GetAttachmentByID mints a short-lived signature
+// granting read on exactly one attachment; a separate public route accepts
+// it. Membership is verified when the capability is minted and never at
+// redemption — the signature is the proof that the check happened.
+//
+// Deliberately NOT a general-purpose credential:
+// - bound to a single attachment id, so it cannot be replayed against another
+// - 60-second TTL, because the download it feeds starts immediately
+// - signed with a key domain-separated from the JWT secret, so it can be
+// neither forged from nor used to forge a session token
+// - never persisted, and never emitted into list responses
+
+const (
+ // attachmentCapabilityVersion is part of the signed message so the
+ // message format can change later without a v1 signature verifying
+ // against a v2 verifier.
+ attachmentCapabilityVersion = "v1"
+
+ // attachmentCapabilityTTL is short by design. The client mints a
+ // capability and hands it to the native downloader in the same tick;
+ // anything longer only widens the window in which a leaked URL is
+ // still redeemable.
+ attachmentCapabilityTTL = 60 * time.Second
+
+ // attachmentCapabilityKeyDomain separates this signing domain from
+ // every other HMAC the deployment derives from the same root secret.
+ attachmentCapabilityKeyDomain = "attachment-download-capability:"
+)
+
+var (
+ attachmentCapabilityKeyOnce sync.Once
+ attachmentCapabilityKey []byte
+)
+
+// attachmentCapabilitySigningKey derives the capability key from the
+// deployment's JWT secret via SHA-256, mirroring composioStateSecret in
+// server/cmd/server/router.go. Deriving rather than reusing means a
+// capability signature can never collide with a JWT signature; rotating
+// JWT_SECRET additionally invalidates outstanding capabilities, which is the
+// behaviour an operator would expect from a rotation.
+func attachmentCapabilitySigningKey() []byte {
+ attachmentCapabilityKeyOnce.Do(func() {
+ sum := sha256.Sum256(append([]byte(attachmentCapabilityKeyDomain), auth.JWTSecret()...))
+ attachmentCapabilityKey = sum[:]
+ })
+ return attachmentCapabilityKey
+}
+
+// signAttachmentCapability returns the hex HMAC over the capability's fields.
+//
+// The fields are joined with a separator that cannot occur inside a UUID or a
+// decimal timestamp, so no pair of (id, exp) values can be re-split into a
+// different pair that produces the same signed message.
+func signAttachmentCapability(attachmentID string, exp int64) string {
+ mac := hmac.New(sha256.New, attachmentCapabilitySigningKey())
+ mac.Write([]byte(attachmentCapabilityVersion))
+ mac.Write([]byte("|"))
+ mac.Write([]byte(attachmentID))
+ mac.Write([]byte("|"))
+ mac.Write([]byte(strconv.FormatInt(exp, 10)))
+ return hex.EncodeToString(mac.Sum(nil))
+}
+
+// attachmentCapabilityPath builds the site-relative capability URL handed back
+// as `download_url`.
+//
+// Site-relative on purpose. Clients already resolve `download_url` against the
+// configured API base, and keeping the shape relative leaves the inline-media
+// re-sign path in packages/views/editor/attachment.tsx untouched: that hook
+// only upgrades to ABSOLUTE URLs, so it keeps ignoring proxy-mode responses
+// exactly as it does today instead of pinning a 60-second URL into an <img>
+// it caches for 20 minutes.
+func attachmentCapabilityPath(attachmentID string, now time.Time) string {
+ exp := now.Add(attachmentCapabilityTTL).Unix()
+ return "/api/attachments/" + attachmentID + "/signed-download" +
+ "?exp=" + strconv.FormatInt(exp, 10) +
+ "&sig=" + signAttachmentCapability(attachmentID, exp)
+}
+
+// verifyAttachmentCapability fails closed on every path: a missing field, an
+// unparseable expiry, an elapsed expiry, a malformed signature, and a
+// signature minted for a different attachment all return false.
+//
+// The signature covers the claimed expiry, so extending `exp` invalidates the
+// signature rather than extending the capability.
+func verifyAttachmentCapability(attachmentID, rawExp, rawSig string, now time.Time) bool {
+ if attachmentID == "" || rawExp == "" || rawSig == "" {
+ return false
+ }
+ exp, err := strconv.ParseInt(rawExp, 10, 64)
+ if err != nil {
+ return false
+ }
+ if now.Unix() > exp {
+ return false
+ }
+ got, err := hex.DecodeString(rawSig)
+ if err != nil {
+ return false
+ }
+ want, err := hex.DecodeString(signAttachmentCapability(attachmentID, exp))
+ if err != nil {
+ return false
+ }
+ return hmac.Equal(got, want)
+}
+
+// ---------------------------------------------------------------------------
+// DownloadAttachmentWithCapability — GET /api/attachments/{id}/signed-download
+// ---------------------------------------------------------------------------
+//
+// Registered as a PUBLIC route. The capability in the query IS the credential,
+// and a native download request has nothing for middleware.Auth to read, so
+// putting this behind Auth would defeat its only purpose. The authenticated
+// /api/attachments/{id}/download endpoint is left exactly as it was — this
+// route is additive, so clients that predate it keep working unchanged and
+// there is no second copy of the header/cookie/PAT/task-token resolution that
+// middleware.Auth owns.
+//
+// Always proxy-streams. Capabilities are only minted in proxy mode, and
+// streaming means this route never emits a cross-origin redirect, so the
+// signed query cannot leak to a CDN in a Referer.
+func (h *Handler) DownloadAttachmentWithCapability(w http.ResponseWriter, r *http.Request) {
+ attachmentID := chi.URLParam(r, "id")
+ query := r.URL.Query()
+ if !verifyAttachmentCapability(attachmentID, query.Get("exp"), query.Get("sig"), time.Now()) {
+ // One generic rejection for every reason, so a caller cannot
+ // distinguish "expired" from "forged" from "wrong attachment"
+ // and use the difference to probe the signer.
+ writeError(w, http.StatusForbidden, "invalid or expired download link")
+ return
+ }
+
+ attUUID, ok := parseUUIDOrBadRequest(w, attachmentID, "attachment id")
+ if !ok {
+ return
+ }
+ att, err := h.Queries.GetAttachmentByIDOnly(r.Context(), attUUID)
+ if err != nil {
+ writeError(w, http.StatusNotFound, "attachment not found")
+ return
+ }
+ if h.Storage == nil {
+ writeError(w, http.StatusServiceUnavailable, "storage not configured")
+ return
+ }
+
+ h.setAttachmentPreviewSecurityHeaders(w)
+ // The signature travels in the query string. If the streamed body is
+ // itself a document that loads subresources, no-referrer keeps that
+ // query out of the outbound Referer.
+ w.Header().Set("Referrer-Policy", "no-referrer")
+
+ h.proxyAttachmentDownload(w, r, att, h.Storage.KeyFromURL(att.Url))
+}
diff --git a/server/internal/handler/attachment_capability_test.go b/server/internal/handler/attachment_capability_test.go
new file mode 100644
index 0000000000..6201f67787
--- /dev/null
+++ b/server/internal/handler/attachment_capability_test.go
@@ -0,0 +1,327 @@
+package handler
+
+import (
+ "bytes"
+ "context"
+ "crypto/sha256"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "strconv"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/go-chi/chi/v5"
+ "github.com/multica-ai/multica/server/internal/auth"
+)
+
+const capabilityTestAttachmentID = "11111111-2222-3333-4444-555555555555"
+
+// capabilityQuery returns just the query string of a freshly minted
+// capability, so tests can vary one field at a time.
+func capabilityQuery(t *testing.T, attachmentID string, now time.Time) url.Values {
+ t.Helper()
+ path := attachmentCapabilityPath(attachmentID, now)
+ idx := strings.Index(path, "?")
+ if idx < 0 {
+ t.Fatalf("capability path has no query: %q", path)
+ }
+ values, err := url.ParseQuery(path[idx+1:])
+ if err != nil {
+ t.Fatalf("parse capability query: %v", err)
+ }
+ return values
+}
+
+// newCapabilityRequest deliberately sets NO authentication headers. The whole
+// point of the capability route is that it works for a native download that
+// carries neither a Bearer token nor a session cookie.
+func newCapabilityRequest(attachmentID string, query url.Values) (*http.Request, *httptest.ResponseRecorder) {
+ req := httptest.NewRequest("GET", "/api/attachments/"+attachmentID+"/signed-download?"+query.Encode(), nil)
+ rctx := chi.NewRouteContext()
+ rctx.URLParams.Add("id", attachmentID)
+ req = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))
+ return req, httptest.NewRecorder()
+}
+
+// ---------------------------------------------------------------------------
+// Signature unit tests (no DB)
+// ---------------------------------------------------------------------------
+
+func TestAttachmentCapability_RoundTrips(t *testing.T) {
+ now := time.Unix(1_800_000_000, 0)
+ query := capabilityQuery(t, capabilityTestAttachmentID, now)
+
+ if !verifyAttachmentCapability(capabilityTestAttachmentID, query.Get("exp"), query.Get("sig"), now) {
+ t.Fatal("freshly minted capability did not verify")
+ }
+ // Still valid one second before the TTL elapses.
+ if !verifyAttachmentCapability(
+ capabilityTestAttachmentID, query.Get("exp"), query.Get("sig"),
+ now.Add(attachmentCapabilityTTL-time.Second),
+ ) {
+ t.Fatal("capability expired before its TTL elapsed")
+ }
+}
+
+func TestAttachmentCapability_FailsClosed(t *testing.T) {
+ now := time.Unix(1_800_000_000, 0)
+ valid := capabilityQuery(t, capabilityTestAttachmentID, now)
+
+ // A capability minted for a DIFFERENT attachment must not verify against
+ // this one — the id is inside the signed message, not just the URL.
+ other := capabilityQuery(t, "99999999-8888-7777-6666-555555555555", now)
+
+ tampered := []byte(valid.Get("sig"))
+ if tampered[0] == 'a' {
+ tampered[0] = 'b'
+ } else {
+ tampered[0] = 'a'
+ }
+
+ cases := []struct {
+ name string
+ id string
+ exp string
+ sig string
+ now time.Time
+ expected bool
+ }{
+ {"valid", capabilityTestAttachmentID, valid.Get("exp"), valid.Get("sig"), now, true},
+ {"expired", capabilityTestAttachmentID, valid.Get("exp"), valid.Get("sig"), now.Add(attachmentCapabilityTTL + time.Second), false},
+ {"tampered signature", capabilityTestAttachmentID, valid.Get("exp"), string(tampered), now, false},
+ {"extended expiry", capabilityTestAttachmentID, strconv.FormatInt(now.Add(24*time.Hour).Unix(), 10), valid.Get("sig"), now, false},
+ {"signature for another attachment", capabilityTestAttachmentID, other.Get("exp"), other.Get("sig"), now, false},
+ {"missing signature", capabilityTestAttachmentID, valid.Get("exp"), "", now, false},
+ {"missing expiry", capabilityTestAttachmentID, "", valid.Get("sig"), now, false},
+ {"missing id", "", valid.Get("exp"), valid.Get("sig"), now, false},
+ {"non-numeric expiry", capabilityTestAttachmentID, "not-a-number", valid.Get("sig"), now, false},
+ {"non-hex signature", capabilityTestAttachmentID, valid.Get("exp"), "zzzz", now, false},
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := verifyAttachmentCapability(tc.id, tc.exp, tc.sig, tc.now); got != tc.expected {
+ t.Fatalf("verify = %v, want %v", got, tc.expected)
+ }
+ })
+ }
+}
+
+// The capability key must not be the JWT secret, nor a bare hash of it. If the
+// two signing domains ever shared a key, a capability signature and a session
+// signature would be interchangeable.
+func TestAttachmentCapability_KeyIsDomainSeparatedFromJWTSecret(t *testing.T) {
+ key := attachmentCapabilitySigningKey()
+ if bytes.Equal(key, auth.JWTSecret()) {
+ t.Fatal("capability key equals the raw JWT secret")
+ }
+ bare := sha256.Sum256(auth.JWTSecret())
+ if bytes.Equal(key, bare[:]) {
+ t.Fatal("capability key is an undomained hash of the JWT secret")
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Route tests
+// ---------------------------------------------------------------------------
+
+// installProxyModeStorage puts the handler into proxy mode with an in-memory
+// backend, which is the deployment shape (local disk / private object host)
+// where capabilities are minted.
+func installProxyModeStorage(t *testing.T) *mockStorage {
+ t.Helper()
+ store := &mockStorage{}
+ origStorage := testHandler.Storage
+ origCfg := testHandler.cfg
+ origSigner := testHandler.CFSigner
+ testHandler.Storage = store
+ testHandler.cfg.AttachmentDownloadMode = "proxy"
+ testHandler.CFSigner = nil
+ t.Cleanup(func() {
+ testHandler.Storage = origStorage
+ testHandler.cfg = origCfg
+ testHandler.CFSigner = origSigner
+ })
+ return store
+}
+
+func TestDownloadAttachmentWithCapability_ServesWithoutAuthentication(t *testing.T) {
+ store := installProxyModeStorage(t)
+ body := []byte("quarterly numbers, do not leak")
+ id := seedPreviewAttachment(t, store, "downloads/report.pdf", "Q3 report.pdf", "application/pdf", body)
+
+ req, w := newCapabilityRequest(id, capabilityQuery(t, id, time.Now()))
+ testHandler.DownloadAttachmentWithCapability(w, req)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200; body=%s", w.Code, w.Body.String())
+ }
+ if !bytes.Equal(w.Body.Bytes(), body) {
+ t.Fatalf("body = %q, want %q", w.Body.String(), body)
+ }
+ // The original filename must survive to the save dialog — that is half
+ // of what the bug report asked for.
+ if disposition := w.Header().Get("Content-Disposition"); !strings.Contains(disposition, "Q3 report.pdf") {
+ t.Fatalf("Content-Disposition = %q, want the original filename", disposition)
+ }
+ if got := w.Header().Get("Referrer-Policy"); got != "no-referrer" {
+ t.Fatalf("Referrer-Policy = %q, want no-referrer", got)
+ }
+ if got := w.Header().Get("Cache-Control"); got != "no-store" {
+ t.Fatalf("Cache-Control = %q, want no-store", got)
+ }
+}
+
+func TestDownloadAttachmentWithCapability_RejectsInvalidCapabilities(t *testing.T) {
+ store := installProxyModeStorage(t)
+ body := []byte("secret bytes")
+ id := seedPreviewAttachment(t, store, "downloads/secret.txt", "secret.txt", "text/plain", body)
+
+ expired := capabilityQuery(t, id, time.Now().Add(-2*attachmentCapabilityTTL))
+
+ forged := capabilityQuery(t, id, time.Now())
+ forged.Set("sig", strings.Repeat("0", len(forged.Get("sig"))))
+
+ // A capability legitimately minted for a different attachment must not
+ // unlock this one.
+ otherID := seedPreviewAttachment(t, store, "downloads/other.txt", "other.txt", "text/plain", []byte("other"))
+ crossed := capabilityQuery(t, otherID, time.Now())
+
+ cases := []struct {
+ name string
+ query url.Values
+ }{
+ {"expired", expired},
+ {"forged signature", forged},
+ {"capability for another attachment", crossed},
+ {"no capability at all", url.Values{}},
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ req, w := newCapabilityRequest(id, tc.query)
+ testHandler.DownloadAttachmentWithCapability(w, req)
+
+ if w.Code != http.StatusForbidden {
+ t.Fatalf("status = %d, want 403; body=%s", w.Code, w.Body.String())
+ }
+ if bytes.Contains(w.Body.Bytes(), body) {
+ t.Fatal("rejected response leaked the attachment body")
+ }
+ })
+ }
+}
+
+// Range support is what makes an interrupted download resumable (RAS-29). The
+// capability route reuses proxyAttachmentDownload, so it must not regress.
+func TestDownloadAttachmentWithCapability_PreservesRangeAndHeaders(t *testing.T) {
+ store := installProxyModeStorage(t)
+ body := bytes.Repeat([]byte("abcdefgh"), 512) // 4 KiB
+ id := seedPreviewAttachment(t, store, "downloads/big.bin", "big.bin", "application/octet-stream", body)
+
+ req, w := newCapabilityRequest(id, capabilityQuery(t, id, time.Now()))
+ req.Header.Set("Range", "bytes=100-199")
+ testHandler.DownloadAttachmentWithCapability(w, req)
+
+ if w.Code != http.StatusPartialContent {
+ t.Fatalf("status = %d, want 206; body len=%d", w.Code, w.Body.Len())
+ }
+ if got := w.Header().Get("Content-Range"); got != "bytes 100-199/4096" {
+ t.Fatalf("Content-Range = %q", got)
+ }
+ if !bytes.Equal(w.Body.Bytes(), body[100:200]) {
+ t.Fatalf("partial body mismatch: len=%d", w.Body.Len())
+ }
+ if disposition := w.Header().Get("Content-Disposition"); !strings.Contains(disposition, "big.bin") {
+ t.Fatalf("Content-Disposition = %q, want the original filename", disposition)
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Minting
+// ---------------------------------------------------------------------------
+
+func TestGetAttachmentByID_ProxyModeReturnsRedeemableCapability(t *testing.T) {
+ store := installProxyModeStorage(t)
+ id := seedPreviewAttachment(t, store, "downloads/inline.png", "inline.png", "image/png", []byte("png-bytes"))
+
+ req := httptest.NewRequest("GET", "/api/attachments/"+id, nil)
+ req.Header.Set("X-User-ID", testUserID)
+ req.Header.Set("X-Workspace-ID", testWorkspaceID)
+ rctx := chi.NewRouteContext()
+ rctx.URLParams.Add("id", id)
+ req = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))
+ w := httptest.NewRecorder()
+
+ testHandler.GetAttachmentByID(w, req)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200; body=%s", w.Code, w.Body.String())
+ }
+ var resp AttachmentResponse
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode response: %v; body=%s", err, w.Body.String())
+ }
+
+ // Site-relative on purpose: an absolute URL here would be picked up by
+ // the inline-media re-sign path in packages/views/editor/attachment.tsx
+ // and pinned into an <img> for far longer than the 60s TTL.
+ if !strings.HasPrefix(resp.DownloadURL, "/api/attachments/"+id+"/signed-download?") {
+ t.Fatalf("download_url = %q, want a site-relative capability path", resp.DownloadURL)
+ }
+
+ parsed, err := url.Parse(resp.DownloadURL)
+ if err != nil {
+ t.Fatalf("parse download_url: %v", err)
+ }
+ if !verifyAttachmentCapability(id, parsed.Query().Get("exp"), parsed.Query().Get("sig"), time.Now()) {
+ t.Fatalf("minted capability does not verify: %q", resp.DownloadURL)
+ }
+
+ // markdown_url is persisted into comment bodies and must outlive the
+ // session, so a 60-second capability must never reach it — that is the
+ // exact class of bug MUL-3130 fixed.
+ if strings.Contains(resp.MarkdownURL, "signed-download") {
+ t.Fatalf("markdown_url = %q, must not embed a short-lived capability", resp.MarkdownURL)
+ }
+}
+
+// List-shaped responses are held far longer than the capability TTL, so
+// attachmentToResponse must keep emitting the stable endpoint.
+func TestAttachmentToResponse_ProxyModeDoesNotMintCapability(t *testing.T) {
+ store := installProxyModeStorage(t)
+ id := seedPreviewAttachment(t, store, "downloads/listed.txt", "listed.txt", "text/plain", []byte("listed"))
+
+ att, err := testHandler.Queries.GetAttachmentByIDOnly(context.Background(), parseUUID(id))
+ if err != nil {
+ t.Fatalf("GetAttachmentByIDOnly: %v", err)
+ }
+
+ resp := testHandler.attachmentToResponse(att)
+ if want := "/api/attachments/" + id + "/download"; resp.DownloadURL != want {
+ t.Fatalf("download_url = %q, want stable %q (no capability in list responses)", resp.DownloadURL, want)
+ }
+}
+
+// The pre-existing authenticated route must stay authenticated. Adding a
+// public capability entry point must not turn the original path into an open
+// one for clients that predate this change.
+func TestDownloadAttachment_StillRequiresAuthentication(t *testing.T) {
+ store := installProxyModeStorage(t)
+ id := seedPreviewAttachment(t, store, "downloads/guarded.txt", "guarded.txt", "text/plain", []byte("guarded"))
+
+ req := httptest.NewRequest("GET", "/api/attachments/"+id+"/download", nil)
+ rctx := chi.NewRouteContext()
+ rctx.URLParams.Add("id", id)
+ req = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))
+ w := httptest.NewRecorder()
+
+ testHandler.DownloadAttachment(w, req)
+
+ if w.Code == http.StatusOK {
+ t.Fatalf("unauthenticated request to the legacy download path succeeded: %s", w.Body.String())
+ }
+}
diff --git a/server/internal/handler/file.go b/server/internal/handler/file.go
index 932192cda1..a83d4b53e8 100644
--- a/server/internal/handler/file.go
+++ b/server/internal/handler/file.go
@@ -580,7 +580,8 @@ func (h *Handler) GetAttachmentByID(w http.ResponseWriter, r *http.Request) {
// stored Content-Disposition (inline for media, attachment otherwise), which
// keeps images renderable inline while preserving the original download
// filename.
- if h.CFSigner == nil && h.resolveAttachmentDownloadMode(att.Url) == attachmentDownloadModePresign {
+ switch mode := h.resolveAttachmentDownloadMode(att.Url); {
+ case h.CFSigner == nil && mode == attachmentDownloadModePresign:
if presigner, ok := h.Storage.(storage.DownloadPresigner); ok {
key := h.Storage.KeyFromURL(att.Url)
signedURL, err := presigner.PresignGetWithContentDisposition(r.Context(), key, h.attachmentDownloadURLTTL(), "")
@@ -590,6 +591,24 @@ func (h *Handler) GetAttachmentByID(w http.ResponseWriter, r *http.Request) {
resp.DownloadURL = signedURL
}
}
+ case h.CFSigner == nil && mode == attachmentDownloadModeProxy:
+ // Proxy mode has no signed storage URL to offer, so this response
+ // would otherwise hand back the auth-gated API path — which a
+ // native download on a token-mode client cannot authenticate,
+ // leaving the user with no file (MUL-5292). Mint a
+ // single-attachment, 60-second capability instead, so the same
+ // "replace the auth-gated path with something a native loader can
+ // fetch" contract holds in all three modes.
+ //
+ // Only here, never in attachmentToResponse: list responses are held
+ // far longer than the TTL, so a capability embedded in one would be
+ // expired by the time anything used it.
+ //
+ // Gated on CFSigner being nil for the same reason as the presign
+ // branch above: when a signer is configured attachmentToResponse has
+ // already produced a credential-free signed URL, which solves the
+ // native-download problem without a capability.
+ resp.DownloadURL = attachmentCapabilityPath(resp.ID, time.Now())
}
writeJSON(w, http.StatusOK, resp)