Skip to content

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

Go

feat(attachments): let callers opt out of pre-signed URLs in bulk responses (MUL-5372) (#6119)

Bohan Jiang2187b5829210
diff --git a/server/internal/cli/client.go b/server/internal/cli/client.go
index e0f3be78ff..b896d6d531 100644
--- a/server/internal/cli/client.go
+++ b/server/internal/cli/client.go
@@ -161,7 +161,23 @@ func NewAPIClient(baseURL, workspaceID, token string) *APIClient {
}
}
+// clientCapabilities is the X-Client-Capabilities value every CLI request
+// advertises. It is a protocol detail, not a user-visible flag: the CLI always
+// knows how to handle these response shapes, so there is nothing for a caller
+// to opt into.
+//
+// stable_attachment_urls asks bulk responses to return the stable
+// /api/attachments/{id}/download path instead of a ~800-char CloudFront
+// signature that is re-minted on every request (MUL-5372 / GitHub #5999). The
+// CLI never hands an attachment URL to a native loader — `multica attachment
+// download <id>` fetches a fresh signature from the single-attachment endpoint,
+// which keeps signing regardless of this capability — so the signature in list
+// payloads was pure cost: raw bytes, a per-attachment RSA sign, and bytes that
+// differ on every read and therefore defeat agent prompt caching.
+const clientCapabilities = "stable_attachment_urls"
+
func (c *APIClient) setHeaders(req *http.Request) {
+ req.Header.Set("X-Client-Capabilities", clientCapabilities)
if c.Token != "" {
req.Header.Set("Authorization", "Bearer "+c.Token)
}
diff --git a/server/internal/cli/client_test.go b/server/internal/cli/client_test.go
index ac1aaeaced..0f6f05942a 100644
--- a/server/internal/cli/client_test.go
+++ b/server/internal/cli/client_test.go
@@ -427,3 +427,101 @@ func TestNormalizeGOOS(t *testing.T) {
}
}
}
+
+// TestSetHeaders_AdvertisesStableAttachmentURLs is the only test that proves
+// Phase 1 of MUL-5372 is actually switched on.
+//
+// The server-side tests verify that a request carrying
+// `X-Client-Capabilities: stable_attachment_urls` gets stable attachment paths,
+// but nothing there observes what the CLI sends. Without this assertion a typo
+// in the token, or dropping the header from setHeaders entirely, would leave
+// every other test green while the CLI silently went back to receiving ~800-char
+// signed URLs on every attachment of every list read.
+//
+// The exact string is load-bearing: the server matches the token literally
+// (handler.requestHasClientCapability), so it is asserted verbatim rather than
+// through the constant.
+func TestSetHeaders_AdvertisesStableAttachmentURLs(t *testing.T) {
+ const wantCapability = "stable_attachment_urls"
+
+ // Every verb goes through setHeaders, and an agent's read path is not only
+ // GET (comment add posts, attachment upload multiparts). Cover the shapes
+ // that actually carry attachment payloads back.
+ t.Run("GET", func(t *testing.T) {
+ var got string
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ got = r.Header.Get("X-Client-Capabilities")
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write([]byte(`{}`))
+ }))
+ defer srv.Close()
+
+ client := NewAPIClient(srv.URL, "ws-1", "test-token")
+ var out map[string]any
+ if err := client.GetJSON(context.Background(), "/api/issues/x/comments", &out); err != nil {
+ t.Fatalf("GetJSON: %v", err)
+ }
+ if got != wantCapability {
+ t.Errorf("X-Client-Capabilities = %q, want %q — Phase 1 is off unless the CLI advertises this", got, wantCapability)
+ }
+ })
+
+ t.Run("GET with headers", func(t *testing.T) {
+ var got string
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ got = r.Header.Get("X-Client-Capabilities")
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write([]byte(`[]`))
+ }))
+ defer srv.Close()
+
+ client := NewAPIClient(srv.URL, "ws-1", "test-token")
+ var out []map[string]any
+ if _, err := client.GetJSONWithHeaders(context.Background(), "/api/issues/x/comments", &out); err != nil {
+ t.Fatalf("GetJSONWithHeaders: %v", err)
+ }
+ if got != wantCapability {
+ t.Errorf("X-Client-Capabilities = %q, want %q", got, wantCapability)
+ }
+ })
+
+ t.Run("POST", func(t *testing.T) {
+ var got string
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ got = r.Header.Get("X-Client-Capabilities")
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write([]byte(`{}`))
+ }))
+ defer srv.Close()
+
+ client := NewAPIClient(srv.URL, "ws-1", "test-token")
+ var out map[string]any
+ if err := client.PostJSON(context.Background(), "/api/issues/x/comments", map[string]string{"content": "hi"}, &out); err != nil {
+ t.Fatalf("PostJSON: %v", err)
+ }
+ if got != wantCapability {
+ t.Errorf("X-Client-Capabilities = %q, want %q", got, wantCapability)
+ }
+ })
+
+ // An unauthenticated client (no token configured yet) must still advertise:
+ // the capability describes what the binary can parse, not who it is.
+ t.Run("without a token", func(t *testing.T) {
+ var got string
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ got = r.Header.Get("X-Client-Capabilities")
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write([]byte(`{}`))
+ }))
+ defer srv.Close()
+
+ client := NewAPIClient(srv.URL, "", "")
+ var out map[string]any
+ if err := client.GetJSON(context.Background(), "/api/health", &out); err != nil {
+ t.Fatalf("GetJSON: %v", err)
+ }
+ if got != wantCapability {
+ t.Errorf("X-Client-Capabilities = %q, want %q", got, wantCapability)
+ }
+ })
+}
diff --git a/server/internal/handler/attachment_capability_test.go b/server/internal/handler/attachment_capability_test.go
index 6201f67787..d2136c7686 100644
--- a/server/internal/handler/attachment_capability_test.go
+++ b/server/internal/handler/attachment_capability_test.go
@@ -300,7 +300,7 @@ func TestAttachmentToResponse_ProxyModeDoesNotMintCapability(t *testing.T) {
t.Fatalf("GetAttachmentByIDOnly: %v", err)
}
- resp := testHandler.attachmentToResponse(att)
+ resp := testHandler.attachmentToResponse(att, attachmentURLModeSigned)
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)
}
diff --git a/server/internal/handler/attachment_url_mode_test.go b/server/internal/handler/attachment_url_mode_test.go
new file mode 100644
index 0000000000..9ac9ccf5db
--- /dev/null
+++ b/server/internal/handler/attachment_url_mode_test.go
@@ -0,0 +1,221 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/go-chi/chi/v5"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// Phase 1 of MUL-5372 / GitHub #5999: bulk responses stop pre-signing
+// attachment download URLs for callers that advertise they can resolve the
+// stable path themselves. The whole design rests on the server default never
+// moving, so most of what these tests pin is what happens when a caller says
+// NOTHING.
+
+func loadTestAttachment(t *testing.T, id string) db.Attachment {
+ t.Helper()
+ att, err := testHandler.Queries.GetAttachment(context.Background(), db.GetAttachmentParams{
+ ID: parseUUID(id),
+ WorkspaceID: parseUUID(testWorkspaceID),
+ })
+ if err != nil {
+ t.Fatalf("GetAttachment: %v", err)
+ }
+ return att
+}
+
+// withCloudFrontSigner installs a real signer so DownloadURL takes the signed
+// branch — the only mode where the new capability changes anything.
+func withCloudFrontSigner(t *testing.T) {
+ t.Helper()
+ orig := testHandler.CFSigner
+ testHandler.CFSigner = testCloudFrontSigner(t)
+ t.Cleanup(func() { testHandler.CFSigner = orig })
+}
+
+func requestWithCapabilities(caps string) *http.Request {
+ r := httptest.NewRequest(http.MethodGet, "/api/issues/x/comments", nil)
+ if caps != "" {
+ r.Header.Set("X-Client-Capabilities", caps)
+ }
+ return r
+}
+
+// TestAttachmentURLMode_DefaultsToSignedWithoutCapability is the compatibility
+// promise itself: a caller that does not advertise the capability — every
+// installed mobile build, every third-party script — must get exactly the
+// pre-signed URL it gets today.
+func TestAttachmentURLMode_DefaultsToSignedWithoutCapability(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ caps string
+ }{
+ {"no header at all", ""},
+ {"unrelated capabilities", "chat_draft_restore,something_else"},
+ {"near-miss token", "stable_attachment_url"},
+ {"empty header", ""},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := attachmentURLModeFromRequest(requestWithCapabilities(tc.caps)); got != attachmentURLModeSigned {
+ t.Errorf("caps %q resolved to stable mode; the server default must never move", tc.caps)
+ }
+ })
+ }
+ // A nil request has no declaration to read either.
+ if got := attachmentURLModeFromRequest(nil); got != attachmentURLModeSigned {
+ t.Errorf("nil request must resolve to signed mode")
+ }
+}
+
+func TestAttachmentURLMode_HonorsAdvertisedCapability(t *testing.T) {
+ for _, caps := range []string{
+ ClientCapabilityStableAttachmentURLs,
+ "chat_draft_restore," + ClientCapabilityStableAttachmentURLs,
+ ClientCapabilityStableAttachmentURLs + ",other",
+ " " + ClientCapabilityStableAttachmentURLs + " ",
+ } {
+ if got := attachmentURLModeFromRequest(requestWithCapabilities(caps)); got != attachmentURLModeStable {
+ t.Errorf("caps %q did not resolve to stable mode", caps)
+ }
+ }
+}
+
+// TestAttachmentToResponse_StableModeDropsSignature covers the actual payload
+// win: same attachment, same signer, two modes.
+func TestAttachmentToResponse_StableModeDropsSignature(t *testing.T) {
+ withCloudFrontSigner(t)
+
+ id := seedAttachmentURL(t, "https://static.example.test/ws/a.png", "a.png", "image/png", 1234)
+ att := loadTestAttachment(t, id)
+
+ signed := testHandler.attachmentToResponse(att, attachmentURLModeSigned)
+ stable := testHandler.attachmentToResponse(att, attachmentURLModeStable)
+
+ if !strings.Contains(signed.DownloadURL, "Signature=") {
+ t.Fatalf("signed mode should carry a signature, got %q", signed.DownloadURL)
+ }
+ want := "/api/attachments/" + id + "/download"
+ if stable.DownloadURL != want {
+ t.Errorf("stable download_url = %q, want %q", stable.DownloadURL, want)
+ }
+ if len(stable.DownloadURL) >= len(signed.DownloadURL) {
+ t.Errorf("stable mode did not shrink download_url (%d vs %d bytes)", len(stable.DownloadURL), len(signed.DownloadURL))
+ }
+
+ // Only download_url may move. url and markdown_url carry different
+ // contracts (raw storage identity / persistable reference) and clients
+ // index markdown bodies on markdown_url, so drift there would corrupt
+ // already-persisted content.
+ if stable.URL != signed.URL {
+ t.Errorf("url must not change with mode: %q vs %q", stable.URL, signed.URL)
+ }
+ if stable.MarkdownURL != signed.MarkdownURL {
+ t.Errorf("markdown_url must not change with mode: %q vs %q", stable.MarkdownURL, signed.MarkdownURL)
+ }
+ if stable.ID != signed.ID || stable.Filename != signed.Filename ||
+ stable.ContentType != signed.ContentType || stable.SizeBytes != signed.SizeBytes {
+ t.Errorf("stable mode altered identity/metadata fields")
+ }
+}
+
+// TestAttachmentToResponse_SignedModeRotatesButStableDoesNot documents why this
+// change exists at all: the signed value is a function of an expiry the server
+// re-derives per request, so identical content yields different bytes on every
+// read and defeats content-keyed caching. Stable mode has no such term.
+func TestAttachmentToResponse_SignedModeRotatesButStableDoesNot(t *testing.T) {
+ withCloudFrontSigner(t)
+
+ id := seedAttachmentURL(t, "https://static.example.test/ws/b.png", "b.png", "image/png", 10)
+ att := loadTestAttachment(t, id)
+
+ stableA := testHandler.attachmentToResponse(att, attachmentURLModeStable)
+ stableB := testHandler.attachmentToResponse(att, attachmentURLModeStable)
+ if stableA.DownloadURL != stableB.DownloadURL {
+ t.Errorf("stable download_url must be deterministic: %q vs %q", stableA.DownloadURL, stableB.DownloadURL)
+ }
+ if strings.Contains(stableA.DownloadURL, "Policy=") || strings.Contains(stableA.DownloadURL, "Signature=") {
+ t.Errorf("stable download_url leaked signature params: %q", stableA.DownloadURL)
+ }
+
+ // The rotation half. attachmentToResponse mints its expiry from time.Now()
+ // at second granularity, so calling it twice in a row would usually land in
+ // the same second and produce identical bytes — asserting on that directly
+ // would be a flaky test of a real property. Drive the signer with two
+ // explicit expiries instead: it proves the URL varies with the expiry term,
+ // which is exactly what makes the response unstable as the clock advances.
+ signed := testHandler.attachmentToResponse(att, attachmentURLModeSigned)
+ if !strings.Contains(signed.DownloadURL, "Policy=") {
+ t.Fatalf("signed mode should embed a policy, got %q", signed.DownloadURL)
+ }
+ base := time.Now()
+ first := testHandler.CFSigner.SignedURL(att.Url, base.Add(30*time.Minute))
+ second := testHandler.CFSigner.SignedURL(att.Url, base.Add(30*time.Minute+time.Second))
+ if first == second {
+ t.Errorf("signed URL did not change with the expiry; rotation is the premise of this whole change")
+ }
+ if strings.Split(first, "?")[0] != strings.Split(second, "?")[0] {
+ t.Errorf("only the query should rotate, the resource path must be stable: %q vs %q", first, second)
+ }
+ // And re-signing with the SAME expiry must reproduce the same bytes —
+ // otherwise the rotation above would prove nothing about the clock.
+ if again := testHandler.CFSigner.SignedURL(att.Url, base.Add(30*time.Minute)); again != first {
+ t.Errorf("signing is not deterministic for a fixed expiry: %q vs %q", again, first)
+ }
+}
+
+// TestAttachmentToResponse_StableModeIsNoOpWithoutSigner pins the presign /
+// proxy deployments: they never took the signing branch, so the capability
+// changes nothing for them.
+func TestAttachmentToResponse_StableModeIsNoOpWithoutSigner(t *testing.T) {
+ orig := testHandler.CFSigner
+ testHandler.CFSigner = nil
+ t.Cleanup(func() { testHandler.CFSigner = orig })
+
+ id := seedAttachmentURL(t, "http://rustfs:9000/test-bucket/c.txt", "c.txt", "text/plain", 5)
+ att := loadTestAttachment(t, id)
+
+ signed := testHandler.attachmentToResponse(att, attachmentURLModeSigned)
+ stable := testHandler.attachmentToResponse(att, attachmentURLModeStable)
+ if signed.DownloadURL != stable.DownloadURL {
+ t.Errorf("without a signer both modes must agree: %q vs %q", signed.DownloadURL, stable.DownloadURL)
+ }
+}
+
+// TestGetAttachmentByID_IgnoresStableCapability is the load-bearing carve-out.
+// Stable-mode callers exchange the stable path for a loadable URL here —
+// `multica attachment download <id>` reads download_url off this endpoint — so
+// honoring the capability would break the flow that makes stable mode safe.
+func TestGetAttachmentByID_IgnoresStableCapability(t *testing.T) {
+ withCloudFrontSigner(t)
+
+ id := seedAttachmentURL(t, "https://static.example.test/ws/d.png", "d.png", "image/png", 7)
+
+ req := httptest.NewRequest(http.MethodGet, "/api/attachments/"+id, nil)
+ req.Header.Set("X-Client-Capabilities", ClientCapabilityStableAttachmentURLs)
+ 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("GET /api/attachments/{id} = %d, body %s", w.Code, w.Body.String())
+ }
+ var resp AttachmentResponse
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode: %v", err)
+ }
+ if !strings.Contains(resp.DownloadURL, "Signature=") {
+ t.Errorf("single-attachment endpoint must always sign, even for stable-mode callers; got %q", resp.DownloadURL)
+ }
+}
diff --git a/server/internal/handler/chat.go b/server/internal/handler/chat.go
index 0a5ce898df..a1e98e3fd1 100644
--- a/server/internal/handler/chat.go
+++ b/server/internal/handler/chat.go
@@ -1087,8 +1087,9 @@ func (h *Handler) ListChatDraftRestores(w http.ResponseWriter, r *http.Request)
writeError(w, http.StatusInternalServerError, "failed to load draft restore attachments")
return
}
+ attachmentMode := attachmentURLModeFromRequest(r)
for _, a := range attRows {
- attachmentsByID[uuidToString(a.ID)] = h.attachmentToResponse(a)
+ attachmentsByID[uuidToString(a.ID)] = h.attachmentToResponse(a, attachmentMode)
}
}
@@ -1446,8 +1447,9 @@ func (h *Handler) CancelTaskByUser(w http.ResponseWriter, r *http.Request) {
h.hydrateTaskAttributions(r.Context(), []*TaskAttribution{resp.AgentTaskResponse.Attribution})
if cancelled.CancelledChatMessage != nil {
attachments := make([]AttachmentResponse, 0, len(cancelled.CancelledChatMessage.Attachments))
+ attachmentMode := attachmentURLModeFromRequest(r)
for _, a := range cancelled.CancelledChatMessage.Attachments {
- attachments = append(attachments, h.attachmentToResponse(a))
+ attachments = append(attachments, h.attachmentToResponse(a, attachmentMode))
}
resp.CancelledChatMessage = &CancelledChatMessageResponse{
ChatSessionID: cancelled.CancelledChatMessage.ChatSessionID,
diff --git a/server/internal/handler/file.go b/server/internal/handler/file.go
index a83d4b53e8..d368972fdc 100644
--- a/server/internal/handler/file.go
+++ b/server/internal/handler/file.go
@@ -97,7 +97,56 @@ type AttachmentResponse struct {
CreatedAt string `json:"created_at"`
}
-func (h *Handler) attachmentToResponse(a db.Attachment) AttachmentResponse {
+// attachmentURLMode selects how DownloadURL is rendered on a response.
+//
+// MUL-5372 / GitHub #5999. A CloudFront-signed DownloadURL is ~800 chars, of
+// which ~630 are a Policy+Signature pair that is re-minted on every request
+// (the policy embeds now+TTL at second granularity). Emitting it for every
+// attachment of every list response is expensive three times over: raw payload,
+// a fresh RSA sign per attachment per request, and — because the bytes differ on
+// each read — it defeats any cache keyed on response content. Agents pay all
+// three and use none of it: they fetch files through the single-attachment
+// endpoint, which needs only the id.
+//
+// The mode is a caller capability declaration, never a server-side default
+// flip, so a client that does not know about it is served byte-identically to
+// before. See attachmentURLModeFromRequest.
+type attachmentURLMode int
+
+const (
+ // attachmentURLModeSigned pre-binds authorization into DownloadURL so the
+ // caller can hand it straight to a native resource load (browser <img>,
+ // Linking.openURL) that cannot attach an Authorization header. This is the
+ // default for every caller that does not opt out.
+ attachmentURLModeSigned attachmentURLMode = iota
+ // attachmentURLModeStable renders DownloadURL as the stable
+ // /api/attachments/{id}/download path. That endpoint re-signs and 302s on
+ // every hit, so the value stays correct forever and costs ~95 chars instead
+ // of ~800. Callers that pick this mode must be able to follow an
+ // authenticated redirect, or fetch a fresh signature from the
+ // single-attachment endpoint before handing a URL to a native loader.
+ attachmentURLModeStable
+)
+
+// ClientCapabilityStableAttachmentURLs is the X-Client-Capabilities token a
+// caller advertises to receive stable attachment paths instead of pre-signed
+// URLs in bulk responses. Reusing the existing capability header (rather than a
+// query parameter) keeps the declaration client-wide: it is a property of what
+// the caller can process, not of the resource being requested.
+const ClientCapabilityStableAttachmentURLs = "stable_attachment_urls"
+
+// attachmentURLModeFromRequest resolves the mode a request asked for. Absent or
+// unrecognized declarations resolve to attachmentURLModeSigned, which is what
+// makes this change safe to ship ahead of any client: the server default never
+// moves, callers migrate on their own release cadence.
+func attachmentURLModeFromRequest(r *http.Request) attachmentURLMode {
+ if r != nil && requestHasClientCapability(r, ClientCapabilityStableAttachmentURLs) {
+ return attachmentURLModeStable
+ }
+ return attachmentURLModeSigned
+}
+
+func (h *Handler) attachmentToResponse(a db.Attachment, mode attachmentURLMode) AttachmentResponse {
id := uuidToString(a.ID)
resp := AttachmentResponse{
ID: id,
@@ -112,7 +161,10 @@ func (h *Handler) attachmentToResponse(a db.Attachment) AttachmentResponse {
SizeBytes: a.SizeBytes,
CreatedAt: a.CreatedAt.Time.Format("2006-01-02T15:04:05Z07:00"),
}
- if h.CFSigner != nil {
+ // Only CloudFront mode overrides the stable path here; the presign and proxy
+ // modes already leave DownloadURL as the stable path and resolve it at
+ // download time, so stable mode is a no-op for them.
+ if h.CFSigner != nil && mode != attachmentURLModeStable {
resp.DownloadURL = h.CFSigner.SignedURL(a.Url, time.Now().Add(h.attachmentDownloadURLTTL()))
}
if a.IssueID.Valid {
@@ -277,10 +329,11 @@ func (h *Handler) groupAttachments(r *http.Request, commentIDs []pgtype.UUID) ma
slog.Error("failed to load attachments for comments", "error", err)
return nil
}
+ mode := attachmentURLModeFromRequest(r)
grouped := make(map[string][]AttachmentResponse, len(commentIDs))
for _, a := range attachments {
cid := uuidToString(a.CommentID)
- grouped[cid] = append(grouped[cid], h.attachmentToResponse(a))
+ grouped[cid] = append(grouped[cid], h.attachmentToResponse(a, mode))
}
return grouped
}
@@ -304,7 +357,7 @@ func (h *Handler) groupChatMessageAttachments(ctx context.Context, workspaceID s
grouped := make(map[string][]AttachmentResponse, len(messageIDs))
for _, a := range attachments {
mid := uuidToString(a.ChatMessageID)
- grouped[mid] = append(grouped[mid], h.attachmentToResponse(a))
+ grouped[mid] = append(grouped[mid], h.attachmentToResponse(a, attachmentURLModeSigned))
}
return grouped
}
@@ -507,7 +560,7 @@ func (h *Handler) UploadFile(w http.ResponseWriter, r *http.Request) {
// S3 upload succeeded but DB record failed — still return the link
// so the file is usable. Log the error for investigation.
} else {
- writeJSON(w, http.StatusOK, h.attachmentToResponse(att))
+ writeJSON(w, http.StatusOK, h.attachmentToResponse(att, attachmentURLModeFromRequest(r)))
return
}
@@ -554,9 +607,10 @@ func (h *Handler) ListAttachments(w http.ResponseWriter, r *http.Request) {
return
}
+ mode := attachmentURLModeFromRequest(r)
resp := make([]AttachmentResponse, len(attachments))
for i, a := range attachments {
- resp[i] = h.attachmentToResponse(a)
+ resp[i] = h.attachmentToResponse(a, mode)
}
writeJSON(w, http.StatusOK, resp)
}
@@ -571,7 +625,12 @@ func (h *Handler) GetAttachmentByID(w http.ResponseWriter, r *http.Request) {
return
}
- resp := h.attachmentToResponse(att)
+ // Always signed, regardless of what the caller advertised: this endpoint is
+ // the single source of fresh, natively-loadable URLs. Stable-mode callers
+ // (CLI `attachment download`, the web inline-media re-sign hook) exchange a
+ // stable path for a signature HERE, so honoring the capability would break
+ // the very flow that makes stable mode safe elsewhere.
+ resp := h.attachmentToResponse(att, attachmentURLModeSigned)
// Token-mode clients use this authenticated endpoint to replace the
// auth-gated API path with a URL that native media elements can load.
// Assert the same storage.DownloadPresigner that resolveAttachmentDownloadMode
diff --git a/server/internal/handler/file_test.go b/server/internal/handler/file_test.go
index 371e73f437..d97f4da141 100644
--- a/server/internal/handler/file_test.go
+++ b/server/internal/handler/file_test.go
@@ -640,7 +640,7 @@ func TestAttachmentToResponse_NonCloudFrontUsesDownloadEndpoint(t *testing.T) {
t.Fatalf("GetAttachment: %v", err)
}
- resp := testHandler.attachmentToResponse(att)
+ resp := testHandler.attachmentToResponse(att, attachmentURLModeSigned)
if resp.URL != "http://rustfs:9000/test-bucket/private.txt" {
t.Fatalf("stored url changed: %q", resp.URL)
}
@@ -1592,7 +1592,7 @@ func TestBuildMarkdownURL_PublicCdnAbsoluteURLReusedVerbatim(t *testing.T) {
t.Fatalf("GetAttachment: %v", err)
}
- resp := testHandler.attachmentToResponse(att)
+ resp := testHandler.attachmentToResponse(att, attachmentURLModeSigned)
if resp.MarkdownURL != "https://cdn.multica.test/uploads/abc.png" {
t.Fatalf("markdown_url = %q, want raw a.Url passthrough", resp.MarkdownURL)
}
@@ -1626,7 +1626,7 @@ func TestBuildMarkdownURL_PrivateBucketWithoutCdnDomainRoutesThroughAPIEndpoint(
t.Fatalf("GetAttachment: %v", err)
}
- resp := testHandler.attachmentToResponse(att)
+ resp := testHandler.attachmentToResponse(att, attachmentURLModeSigned)
want := "https://api.multica.test/api/attachments/" + id + "/download"
if resp.MarkdownURL != want {
t.Fatalf("markdown_url = %q, want absolute API endpoint %q (private bucket without explicit CDN must not persist raw S3 URL)", resp.MarkdownURL, want)
@@ -1653,7 +1653,7 @@ func TestBuildMarkdownURL_CloudFrontSignedModeNeverPersistsRawStorageURL(t *test
t.Fatalf("GetAttachment: %v", err)
}
- resp := testHandler.attachmentToResponse(att)
+ resp := testHandler.attachmentToResponse(att, attachmentURLModeSigned)
want := "https://api.multica.test/api/attachments/" + id + "/download"
if resp.MarkdownURL != want {
t.Fatalf("markdown_url = %q, want absolute API endpoint %q", resp.MarkdownURL, want)
@@ -1686,7 +1686,7 @@ func TestBuildMarkdownURL_RelativeStorageURLPrefixedWithPublicURL(t *testing.T)
t.Fatalf("GetAttachment: %v", err)
}
- resp := testHandler.attachmentToResponse(att)
+ resp := testHandler.attachmentToResponse(att, attachmentURLModeSigned)
want := "https://api.multica.test/api/attachments/" + id + "/download"
if resp.MarkdownURL != want {
t.Fatalf("markdown_url = %q, want absolute API endpoint %q", resp.MarkdownURL, want)
@@ -1712,7 +1712,7 @@ func TestBuildMarkdownURL_PublicURLUnsetFallsBackToSiteRelative(t *testing.T) {
t.Fatalf("GetAttachment: %v", err)
}
- resp := testHandler.attachmentToResponse(att)
+ resp := testHandler.attachmentToResponse(att, attachmentURLModeSigned)
want := "/api/attachments/" + id + "/download"
if resp.MarkdownURL != want {
t.Fatalf("markdown_url = %q, want site-relative fallback %q", resp.MarkdownURL, want)
@@ -1738,7 +1738,7 @@ func TestBuildMarkdownURL_StripsTrailingSlashOnPublicURL(t *testing.T) {
t.Fatalf("GetAttachment: %v", err)
}
- resp := testHandler.attachmentToResponse(att)
+ resp := testHandler.attachmentToResponse(att, attachmentURLModeSigned)
want := "https://api.multica.test/api/attachments/" + id + "/download"
if resp.MarkdownURL != want {
t.Fatalf("markdown_url = %q, want exactly one separator %q", resp.MarkdownURL, want)
diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.go
index 3c381366db..07c1f2a6a8 100644
--- a/server/internal/handler/issue.go
+++ b/server/internal/handler/issue.go
@@ -1890,9 +1890,10 @@ func (h *Handler) GetIssue(w http.ResponseWriter, r *http.Request) {
WorkspaceID: issue.WorkspaceID,
})
if err == nil && len(attachments) > 0 {
+ mode := attachmentURLModeFromRequest(r)
resp.Attachments = make([]AttachmentResponse, len(attachments))
for i, a := range attachments {
- resp.Attachments[i] = h.attachmentToResponse(a)
+ resp.Attachments[i] = h.attachmentToResponse(a, mode)
}
}
@@ -2582,13 +2583,14 @@ func (h *Handler) CreateIssue(w http.ResponseWriter, r *http.Request) {
analyticsAgentID = actualCreatorID
}
+ attachmentMode := attachmentURLModeFromRequest(r)
buildAttachmentResponses := func(atts []db.Attachment) []AttachmentResponse {
if len(atts) == 0 {
return nil
}
out := make([]AttachmentResponse, len(atts))
for i, a := range atts {
- out[i] = h.attachmentToResponse(a)
+ out[i] = h.attachmentToResponse(a, attachmentMode)
}
return out
}