Skip to content

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

Go

MUL-6023 feat(attachments): forced-attachment download URL across all storage modes (#6756)

Danila Katalshov02e8e6c356b2
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index bc0cd2f0bf..bca8573c19 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -524,6 +524,11 @@ export const AttachmentResponseSchema = z.object({
id: z.string(),
url: z.string(),
download_url: z.string(),
+ // Forced-attachment ("download button") URL — credential-free and, unlike
+ // `download_url`, always Content-Disposition: attachment across every storage
+ // mode. Optional: a server older than this field omits it, and callers fall
+ // back to `download_url` / the stable endpoint. Never persisted (short-lived).
+ attachment_download_url: z.string().optional(),
markdown_url: z.string().optional().default(""),
filename: z.string(),
chat_session_id: z.string().nullable().optional(),
diff --git a/packages/core/drafts/draft-upload.ts b/packages/core/drafts/draft-upload.ts
index 1ad542c580..8cdd7d66d7 100644
--- a/packages/core/drafts/draft-upload.ts
+++ b/packages/core/drafts/draft-upload.ts
@@ -77,12 +77,13 @@ export function attachmentToDraftUpload(attachment: Attachment): UploadedDraftUp
filename: attachment.filename,
size: attachment.size_bytes,
contentType: attachment.content_type || undefined,
- // `download_url` is minted for the current API response and may be a
- // short-lived signed URL; draft uploads survive dialog closes and app
- // restarts, so it is stripped here. `url`/`markdown_url` stay as the
- // durable render/download paths, and content-editor's session merge
- // backfills an empty download_url from the live upload result.
- attachment: { ...attachment, download_url: "" },
+ // `download_url` and `attachment_download_url` are minted for the current API
+ // response and may be short-lived signed URLs; draft uploads survive dialog
+ // closes and app restarts, so both are stripped here. `url`/`markdown_url`
+ // stay as the durable render/download paths, and content-editor's session
+ // merge backfills an empty download_url from the live upload result (the
+ // download flow re-fetches attachment_download_url fresh via getAttachment).
+ attachment: { ...attachment, download_url: "", attachment_download_url: "" },
};
}
diff --git a/packages/core/types/attachment.ts b/packages/core/types/attachment.ts
index 139bf7744c..10ee54621d 100644
--- a/packages/core/types/attachment.ts
+++ b/packages/core/types/attachment.ts
@@ -10,6 +10,14 @@ export interface Attachment {
filename: string;
url: string;
download_url: string;
+ /**
+ * Forced-attachment ("download button") URL: credential-free and, unlike
+ * `download_url` (load-intent, serves media inline for preview), always
+ * Content-Disposition: attachment across every storage mode. Short-lived —
+ * never persist it. Optional: a server older than this field omits it, and
+ * download callers fall back to `download_url` / the stable endpoint.
+ */
+ attachment_download_url?: string;
/**
* Durable URL the client persists into markdown bodies.
*
diff --git a/packages/views/editor/use-download-attachment.test.tsx b/packages/views/editor/use-download-attachment.test.tsx
index 5e0db9289f..e1a4eb3f80 100644
--- a/packages/views/editor/use-download-attachment.test.tsx
+++ b/packages/views/editor/use-download-attachment.test.tsx
@@ -295,6 +295,64 @@ describe("useDownloadAttachment (web)", () => {
expect(clickSpy).not.toHaveBeenCalled();
await waitFor(() => expect(toast.error).toHaveBeenCalled());
});
+
+ it("prefers the forced-attachment URL over the capability and slug endpoint", async () => {
+ getAttachmentMock.mockResolvedValueOnce({
+ id: "att-1",
+ url: "https://static.example.test/pic.png",
+ // A proxy capability is present, but the forced-attachment URL wins.
+ download_url:
+ "/api/attachments/att-1/signed-download?exp=1800000060&sig=load",
+ attachment_download_url:
+ "/api/attachments/att-1/signed-download?exp=1800000060&sig=dl&dl=1",
+ filename: "pic.png",
+ });
+ const clickSpy = vi
+ .spyOn(HTMLAnchorElement.prototype, "click")
+ .mockImplementation(() => {});
+ const appendSpy = vi.spyOn(document.body, "appendChild");
+
+ const { result } = renderHook(() => useDownloadAttachment());
+ await act(async () => {
+ await result.current("att-1");
+ });
+
+ expect(clickSpy).toHaveBeenCalledOnce();
+ const anchor = appendSpy.mock.calls
+ .map(([node]) => node)
+ .find((node): node is HTMLAnchorElement =>
+ node instanceof HTMLAnchorElement,
+ );
+ expect(anchor).toBeDefined();
+ // The forced-attachment capability is used verbatim (same-origin base).
+ expect(anchor!.getAttribute("href")).toBe(
+ "/api/attachments/att-1/signed-download?exp=1800000060&sig=dl&dl=1",
+ );
+ });
+
+ it("uses the forced-attachment URL even when the workspace slug is missing", async () => {
+ useWorkspaceSlugMock.mockReturnValueOnce(null);
+ getAttachmentMock.mockResolvedValueOnce({
+ id: "att-1",
+ url: "https://static.example.test/pic.png",
+ attachment_download_url:
+ "/api/attachments/att-1/signed-download?exp=1800000060&sig=dl&dl=1",
+ filename: "pic.png",
+ });
+ const clickSpy = vi
+ .spyOn(HTMLAnchorElement.prototype, "click")
+ .mockImplementation(() => {});
+
+ const { result } = renderHook(() => useDownloadAttachment());
+ await act(async () => {
+ await result.current("att-1");
+ });
+
+ // The capability carries its own credential, so a missing slug — which only
+ // gates the legacy fallback — must not block it.
+ expect(clickSpy).toHaveBeenCalledOnce();
+ expect(toast.error).not.toHaveBeenCalled();
+ });
});
describe("useDownloadAttachment (desktop)", () => {
@@ -444,4 +502,28 @@ describe("useDownloadAttachment (desktop)", () => {
expect(downloadURL).toHaveBeenCalledWith(SIGNED_URL);
});
+
+ it("prefers the forced-attachment URL over download_url on desktop", async () => {
+ const downloadURL = vi.fn();
+ (window as unknown as { desktopAPI: { downloadURL: typeof downloadURL } }).desktopAPI = {
+ downloadURL,
+ };
+ const forced =
+ "https://cdn.example.test/att-1.png?response-content-disposition=attachment&Policy=p&Signature=s&Key-Pair-Id=k";
+ getAttachmentMock.mockResolvedValueOnce({
+ id: "att-1",
+ url: "https://static.example.test/pic.png",
+ download_url: SIGNED_URL,
+ attachment_download_url: forced,
+ filename: "pic.png",
+ });
+
+ const { result } = renderHook(() => useDownloadAttachment());
+ await act(async () => {
+ await result.current("att-1");
+ });
+
+ // The forced-attachment URL wins over the load-intent download_url.
+ expect(downloadURL).toHaveBeenCalledWith(forced);
+ });
});
diff --git a/packages/views/editor/use-download-attachment.ts b/packages/views/editor/use-download-attachment.ts
index a736b34411..4dacab869a 100644
--- a/packages/views/editor/use-download-attachment.ts
+++ b/packages/views/editor/use-download-attachment.ts
@@ -21,6 +21,17 @@ function attachmentDownloadEndpoint(
return resolvePublicFileUrl(endpoint) ?? endpoint;
}
+// Resolve the forced-attachment ("download button") URL the server minted, if
+// any. Unlike `download_url` (load-intent — media serves inline for preview),
+// `attachment_download_url` carries Content-Disposition: attachment in every
+// storage mode, so it downloads rather than previews. resolvePublicFileUrl keeps
+// a site-relative proxy capability same-origin and passes absolute presign /
+// CloudFront URLs through unchanged. Empty on a server that predates the field.
+function forcedAttachmentUrl(url: string | undefined): string | null {
+ if (!url) return null;
+ return resolvePublicFileUrl(url);
+}
+
// The capability download URL the server minted, if any.
//
// In proxy mode the backend puts a signed, single-attachment capability into
@@ -36,9 +47,9 @@ function attachmentDownloadEndpoint(
// `proxyAttachmentDownload` → `storage.ContentDisposition`, which returns
// `inline` for image/video/audio/PDF. What makes the browser download rather
// than preview is the request staying same-origin combined with the `download`
-// attribute. `resolvePublicFileUrl` leaves this URL same-origin whenever the app
-// reaches the API on its own origin; if it resolves cross-origin AND the file is
-// media, the capability previews in-tab instead — a row #6712 still tracks.
+// attribute. This is the #6713 fallback for a server that has the #6092
+// capability but not yet `attachment_download_url`; the forced-attachment URL
+// preferred above closes the cross-origin-media gap #6712 tracked.
//
// Absolute CloudFront / S3 `download_url`s are deliberately NOT used here: they
// are cross-origin and inline-tuned, so an `<a download>` to them previews the
@@ -84,14 +95,14 @@ function hasDesktopDownloadBridge(): boolean {
*
* Two execution shapes, picked at call time:
*
- * - **Web**: refreshes attachment metadata (for the existing error feedback
- * path and to obtain the capability `download_url`), then clicks a temporary
- * anchor. It prefers the signed capability URL the backend mints in proxy
- * mode — the one a bare `<a download>` navigation can authenticate without a
- * header or cookie — and otherwise falls back to the cookie-gated
- * `/api/attachments/{id}/download?workspace_slug=...` endpoint. Either way the
- * backend owns CloudFront / S3 presign / proxy selection and download
- * Content-Disposition, so large files stay in the browser's native download
+ * - **Web**: refreshes attachment metadata (for the existing error-feedback
+ * path and to read the download URLs), then clicks a temporary anchor. It
+ * prefers `attachment_download_url` — the credential-free URL that forces
+ * Content-Disposition: attachment in every storage mode — then the #6092
+ * proxy capability, then the cookie-gated
+ * `/api/attachments/{id}/download?workspace_slug=...` endpoint for a server
+ * that predates both. Either way the backend owns CloudFront / S3 presign /
+ * proxy selection, so large files stay in the browser's native download
* pipeline.
*
* - **Desktop**: uses `desktopAPI.downloadURL()` which invokes Electron's
@@ -110,15 +121,17 @@ export function useDownloadAttachment(): (attachmentId: string) => Promise<void>
if (hasDesktopDownloadBridge()) {
try {
const fresh = await api.getAttachment(attachmentId);
- // Server may return a server-relative `download_url`
- // (`/api/attachments/{id}/download`) when no CloudFront
- // signer is configured — the unified download endpoint chooses
- // CloudFront/presign/proxy at request time. Electron's main-side
- // `downloadURLSafely` requires `new URL()` to parse to http/https,
- // so resolve against the configured API base before we cross the
- // bridge. Absolute URLs (legacy CloudFront / S3 presigned) pass
- // through unchanged.
- const downloadUrl = resolvePublicFileUrl(fresh.download_url);
+ // Prefer the forced-attachment URL (Content-Disposition: attachment in
+ // every storage mode) so the native save writes the file rather than
+ // opening media inline; fall back to the load-intent `download_url` for
+ // a server that predates the field. Either may be server-relative (the
+ // proxy capability) or absolute (CloudFront / S3 presigned); Electron's
+ // main-side `downloadURLSafely` requires `new URL()` to parse to
+ // http/https, so resolve against the configured API base before we
+ // cross the bridge. Absolute URLs pass through unchanged.
+ const downloadUrl = resolvePublicFileUrl(
+ fresh.attachment_download_url || fresh.download_url,
+ );
if (!downloadUrl) {
failed();
return;
@@ -136,19 +149,28 @@ export function useDownloadAttachment(): (attachmentId: string) => Promise<void>
try {
// The preflight metadata request is both the permission check (so API
// failures still produce the existing toast instead of a silent failed
- // navigation) and where the server hands back the capability
- // `download_url` it mints in proxy mode.
+ // navigation) and where the server hands back the download URLs it mints
+ // for this response.
const fresh = await api.getAttachment(attachmentId);
if (typeof document === "undefined") {
failed();
return;
}
- // Prefer the capability URL when the server minted one. A top-level
- // `<a download>` navigation sends no `Authorization` header, so in
- // token-mode — where auth is a bearer token in JS rather than a cookie —
- // the cookie-gated slug endpoint 401s and the browser saves the error
- // body as `download.txt`. The capability URL carries its own credential
- // in the query string, so it authenticates that bare navigation itself.
+ // Prefer the forced-attachment URL when the server minted one: it is
+ // credential-free and carries Content-Disposition: attachment in every
+ // storage mode, so a bare `<a download>` navigation both authenticates
+ // and downloads — instead of previewing media inline or 401ing in
+ // token-mode.
+ const forced = forcedAttachmentUrl(fresh.attachment_download_url);
+ if (forced) {
+ triggerBrowserDownload(forced);
+ return;
+ }
+ // Older server without the forced-attachment field: fall back to the
+ // #6092 proxy capability (#6713). A top-level `<a download>` navigation
+ // sends no `Authorization` header, so in token-mode the cookie-gated
+ // slug endpoint 401s; the capability URL carries its own credential in
+ // the query string, so it authenticates that bare navigation itself.
const capability = capabilityDownloadUrl(fresh.download_url);
if (capability) {
triggerBrowserDownload(capability);
diff --git a/server/internal/handler/attachment_capability.go b/server/internal/handler/attachment_capability.go
index 9307e15d14..c6f86b74fb 100644
--- a/server/internal/handler/attachment_capability.go
+++ b/server/internal/handler/attachment_capability.go
@@ -56,6 +56,18 @@ const (
// attachmentCapabilityKeyDomain separates this signing domain from
// every other HMAC the deployment derives from the same root secret.
attachmentCapabilityKeyDomain = "attachment-download-capability:"
+
+ // attachmentCapabilityDownloadIntent is folded into a forced-attachment
+ // ("download button") capability's signed message. This is deliberate
+ // headroom, not a fix for a current threat: today the load-intent and
+ // download-intent links are minted in the same response, and flipping a load
+ // link into a forced download only makes it *less* dangerous (inline is the
+ // risky disposition), so binding the intent stops nothing an attacker could
+ // exploit now. It is kept so that if a later intent ever grants more than the
+ // load link, the signature is already intent-bound and a lower-privilege link
+ // cannot be replayed as it. It rides the URL as dl=1; the empty (load) intent
+ // signs the historical three-field message, byte-identical.
+ attachmentCapabilityDownloadIntent = "attachment"
)
var (
@@ -83,12 +95,29 @@ func attachmentCapabilitySigningKey() []byte {
// 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 {
+ return signAttachmentCapabilityIntent(attachmentID, exp, "")
+}
+
+// signAttachmentCapabilityIntent signs the capability over (version, id, exp)
+// and, for a non-empty intent, an extra domain-separation term. The load-intent
+// capability (intent "") signs exactly the historical three-field message, so
+// its signatures stay byte-identical to before; the download-intent capability
+// (attachmentCapabilityDownloadIntent) appends "|attachment". Binding the intent
+// is forward-looking headroom, not a current mitigation — flipping today's two
+// intents is not itself exploitable (see attachmentCapabilityDownloadIntent) —
+// but it keeps the signature honest if a future intent is ever more privileged
+// than the load link.
+func signAttachmentCapabilityIntent(attachmentID string, exp int64, intent string) 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)))
+ if intent != "" {
+ mac.Write([]byte("|"))
+ mac.Write([]byte(intent))
+ }
return hex.EncodeToString(mac.Sum(nil))
}
@@ -108,13 +137,28 @@ func attachmentCapabilityPath(attachmentID string, now time.Time) string {
"&sig=" + signAttachmentCapability(attachmentID, exp)
}
+// attachmentDownloadCapabilityPath builds the site-relative capability URL for a
+// forced-attachment ("download button") intent. Same short-lived, single-id
+// shape as attachmentCapabilityPath, plus dl=1 — which the redemption route
+// turns into a Content-Disposition: attachment. Kept separate, and separately
+// signed, so the load-intent link the preview path consumes keeps serving media
+// inline. Site-relative for the same reason: the inline-media re-sign hook only
+// upgrades absolute URLs, so it keeps ignoring this one.
+func attachmentDownloadCapabilityPath(attachmentID string, now time.Time) string {
+ exp := now.Add(attachmentCapabilityTTL).Unix()
+ return "/api/attachments/" + attachmentID + "/signed-download" +
+ "?exp=" + strconv.FormatInt(exp, 10) +
+ "&sig=" + signAttachmentCapabilityIntent(attachmentID, exp, attachmentCapabilityDownloadIntent) +
+ "&dl=1"
+}
+
// 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 {
+func verifyAttachmentCapability(attachmentID, rawExp, rawSig, intent string, now time.Time) bool {
if attachmentID == "" || rawExp == "" || rawSig == "" {
return false
}
@@ -129,7 +173,7 @@ func verifyAttachmentCapability(attachmentID, rawExp, rawSig string, now time.Ti
if err != nil {
return false
}
- want, err := hex.DecodeString(signAttachmentCapability(attachmentID, exp))
+ want, err := hex.DecodeString(signAttachmentCapabilityIntent(attachmentID, exp, intent))
if err != nil {
return false
}
@@ -154,7 +198,14 @@ func verifyAttachmentCapability(attachmentID, rawExp, rawSig string, now time.Ti
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()) {
+ // dl=1 is the forced-attachment ("download button") intent. It is covered by
+ // a distinct signature, so a load-intent link cannot flip itself to a
+ // download by appending dl=1 — the verification below would fail.
+ intent := ""
+ if query.Get("dl") == "1" {
+ intent = attachmentCapabilityDownloadIntent
+ }
+ if !verifyAttachmentCapability(attachmentID, query.Get("exp"), query.Get("sig"), intent, 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.
@@ -182,5 +233,5 @@ func (h *Handler) DownloadAttachmentWithCapability(w http.ResponseWriter, r *htt
// query out of the outbound Referer.
w.Header().Set("Referrer-Policy", "no-referrer")
- h.proxyAttachmentDownload(w, r, att, h.Storage.KeyFromURL(att.Url))
+ h.proxyAttachmentDownload(w, r, att, h.Storage.KeyFromURL(att.Url), intent == attachmentCapabilityDownloadIntent)
}
diff --git a/server/internal/handler/attachment_capability_test.go b/server/internal/handler/attachment_capability_test.go
index d2136c7686..2ce498e793 100644
--- a/server/internal/handler/attachment_capability_test.go
+++ b/server/internal/handler/attachment_capability_test.go
@@ -54,12 +54,12 @@ 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) {
+ 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"),
+ capabilityTestAttachmentID, query.Get("exp"), query.Get("sig"), "",
now.Add(attachmentCapabilityTTL-time.Second),
) {
t.Fatal("capability expired before its TTL elapsed")
@@ -103,13 +103,56 @@ func TestAttachmentCapability_FailsClosed(t *testing.T) {
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 {
+ if got := verifyAttachmentCapability(tc.id, tc.exp, tc.sig, "", tc.now); got != tc.expected {
t.Fatalf("verify = %v, want %v", got, tc.expected)
}
})
}
}
+// TestAttachmentDownloadCapability_IntentIsDomainSeparated pins the follow-up
+// download-intent split (dl=1): a forced-attachment capability verifies only
+// under the attachment intent, and a load-intent link cannot be flipped to a
+// forced download by appending dl=1 — its signature does not cover the intent.
+func TestAttachmentDownloadCapability_IntentIsDomainSeparated(t *testing.T) {
+ now := time.Unix(1_800_000_000, 0)
+ exp := now.Add(attachmentCapabilityTTL).Unix()
+ expStr := strconv.FormatInt(exp, 10)
+
+ loadSig := signAttachmentCapability(capabilityTestAttachmentID, exp)
+ dlSig := signAttachmentCapabilityIntent(capabilityTestAttachmentID, exp, attachmentCapabilityDownloadIntent)
+
+ if loadSig == dlSig {
+ t.Fatal("load-intent and download-intent signatures must differ")
+ }
+
+ // The download capability verifies only under the download intent.
+ if !verifyAttachmentCapability(capabilityTestAttachmentID, expStr, dlSig, attachmentCapabilityDownloadIntent, now) {
+ t.Fatal("download capability did not verify under its own intent")
+ }
+ if verifyAttachmentCapability(capabilityTestAttachmentID, expStr, dlSig, "", now) {
+ t.Fatal("download signature must not verify as a load-intent link")
+ }
+
+ // A load-intent link cannot be promoted to a forced-attachment download by
+ // tacking on dl=1 (which the handler maps to the attachment intent).
+ if verifyAttachmentCapability(capabilityTestAttachmentID, expStr, loadSig, attachmentCapabilityDownloadIntent, now) {
+ t.Fatal("load signature must not verify as a download (dl=1) capability")
+ }
+ if !verifyAttachmentCapability(capabilityTestAttachmentID, expStr, loadSig, "", now) {
+ t.Fatal("load capability must still verify under the empty intent")
+ }
+
+ // The minted download path carries dl=1 and a distinct signature.
+ path := attachmentDownloadCapabilityPath(capabilityTestAttachmentID, now)
+ if !strings.Contains(path, "dl=1") {
+ t.Fatalf("download capability path missing dl=1: %q", path)
+ }
+ if strings.Contains(attachmentCapabilityPath(capabilityTestAttachmentID, now), "dl=1") {
+ t.Fatal("load-intent capability path must not carry dl=1")
+ }
+}
+
// 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.
@@ -277,7 +320,7 @@ func TestGetAttachmentByID_ProxyModeReturnsRedeemableCapability(t *testing.T) {
if err != nil {
t.Fatalf("parse download_url: %v", err)
}
- if !verifyAttachmentCapability(id, parsed.Query().Get("exp"), parsed.Query().Get("sig"), time.Now()) {
+ if !verifyAttachmentCapability(id, parsed.Query().Get("exp"), parsed.Query().Get("sig"), "", time.Now()) {
t.Fatalf("minted capability does not verify: %q", resp.DownloadURL)
}
@@ -289,6 +332,72 @@ func TestGetAttachmentByID_ProxyModeReturnsRedeemableCapability(t *testing.T) {
}
}
+// TestGetAttachmentByID_ProxyModeDownloadURLForcesAttachment is the end-to-end
+// proof for the download-intent field: the minted attachment_download_url is a
+// site-relative dl=1 capability that verifies only under the attachment intent
+// and, once redeemed, forces Content-Disposition: attachment even for an image
+// — which the load-intent download_url path serves inline.
+func TestGetAttachmentByID_ProxyModeDownloadURLForcesAttachment(t *testing.T) {
+ store := installProxyModeStorage(t)
+ body := []byte("png-bytes")
+ id := seedPreviewAttachment(t, store, "downloads/pic.png", "pic.png", "image/png", body)
+
+ 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 dl=1 capability, distinct from the load-intent download_url,
+ // and verifiable only under the attachment intent.
+ if !strings.HasPrefix(resp.AttachmentDownloadURL, "/api/attachments/"+id+"/signed-download?") {
+ t.Fatalf("attachment_download_url = %q, want a site-relative capability path", resp.AttachmentDownloadURL)
+ }
+ parsed, err := url.Parse(resp.AttachmentDownloadURL)
+ if err != nil {
+ t.Fatalf("parse attachment_download_url: %v", err)
+ }
+ if parsed.Query().Get("dl") != "1" {
+ t.Fatalf("attachment_download_url missing dl=1: %q", resp.AttachmentDownloadURL)
+ }
+ if !verifyAttachmentCapability(id, parsed.Query().Get("exp"), parsed.Query().Get("sig"), attachmentCapabilityDownloadIntent, time.Now()) {
+ t.Fatalf("download capability does not verify under the attachment intent: %q", resp.AttachmentDownloadURL)
+ }
+ // A 60-second capability must never leak into the persisted markdown_url.
+ if strings.Contains(resp.MarkdownURL, "signed-download") {
+ t.Fatalf("markdown_url = %q, must not embed a short-lived capability", resp.MarkdownURL)
+ }
+
+ // Redeeming it forces an attachment disposition even for an image.
+ req2, w2 := newCapabilityRequest(id, parsed.Query())
+ testHandler.DownloadAttachmentWithCapability(w2, req2)
+ if w2.Code != http.StatusOK {
+ t.Fatalf("redeem status = %d, want 200; body=%s", w2.Code, w2.Body.String())
+ }
+ if !bytes.Equal(w2.Body.Bytes(), body) {
+ t.Fatalf("redeemed body mismatch: got %q", w2.Body.String())
+ }
+ disposition := w2.Header().Get("Content-Disposition")
+ if !strings.HasPrefix(disposition, "attachment") {
+ t.Fatalf("Content-Disposition = %q, want it to force attachment", disposition)
+ }
+ if !strings.Contains(disposition, "pic.png") {
+ t.Fatalf("Content-Disposition = %q, want the original filename", disposition)
+ }
+}
+
// 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) {
diff --git a/server/internal/handler/file.go b/server/internal/handler/file.go
index 6bf47fe012..b6e1f4d31a 100644
--- a/server/internal/handler/file.go
+++ b/server/internal/handler/file.go
@@ -66,6 +66,16 @@ type AttachmentResponse struct {
Filename string `json:"filename"`
URL string `json:"url"`
DownloadURL string `json:"download_url"`
+ // AttachmentDownloadURL is a credential-free URL that forces a
+ // Content-Disposition: attachment across every storage mode, for the
+ // download BUTTON — unlike DownloadURL, which is load-intent and keeps
+ // serving media inline so the preview path (resolvePreviewMediaUrl) can
+ // render it. Like DownloadURL it can be short-lived (a 60s proxy capability,
+ // a presigned URL) and therefore MUST NOT be persisted, and it is emitted
+ // ONLY by the single-attachment endpoint (GetAttachmentByID), never in list
+ // responses. Empty when the server cannot mint one for the object's storage
+ // mode; clients fall back to DownloadURL. (MUL follow-up to #6092 / #6713.)
+ AttachmentDownloadURL string `json:"attachment_download_url,omitempty"`
// MarkdownURL is the durable, absolute-when-possible URL the client
// SHOULD persist into markdown bodies (issue descriptions, comments,
// chat messages). It is computed per deployment policy by
@@ -639,8 +649,26 @@ 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.
- switch mode := h.resolveAttachmentDownloadMode(att.Url); {
- case h.CFSigner == nil && mode == attachmentDownloadModePresign:
+ switch mode := h.resolveAttachmentDownloadMode(att.Url); mode {
+ case attachmentDownloadModeCloudFront:
+ // CloudFront mode: attachmentToResponse already set DownloadURL to an
+ // inline-intent signed URL. The download button needs the forced-
+ // attachment sibling. response-content-disposition is folded into the
+ // signed Resource (SignedURLWithContentDisposition), so a client cannot
+ // strip or alter it without invalidating the signature. Keying on the
+ // resolved mode (not h.CFSigner != nil) lets an explicit proxy/presign
+ // override take effect even when a signer is configured; the nil guard
+ // keeps an explicit cloudfront mode without a configured signer from
+ // panicking — the field is left empty and the client falls back to
+ // download_url, the same graceful degrade attachmentToResponse uses.
+ if h.CFSigner != nil {
+ resp.AttachmentDownloadURL = h.CFSigner.SignedURLWithContentDisposition(
+ att.Url,
+ storage.AttachmentContentDisposition(att.Filename),
+ time.Now().Add(h.attachmentDownloadURLTTL()),
+ )
+ }
+ case attachmentDownloadModePresign:
if presigner, ok := h.Storage.(storage.DownloadPresigner); ok {
key := h.Storage.KeyFromURL(att.Url)
signedURL, err := presigner.PresignGetWithContentDisposition(r.Context(), key, h.attachmentDownloadURLTTL(), "")
@@ -649,8 +677,17 @@ func (h *Handler) GetAttachmentByID(w http.ResponseWriter, r *http.Request) {
} else {
resp.DownloadURL = signedURL
}
+ // Download-intent sibling: the same presigned object, but with a
+ // forced attachment disposition so the download button saves the
+ // file instead of previewing it. Independent of DownloadURL's inline
+ // signature above; either may be present without the other.
+ if dlURL, err := presigner.PresignGetWithContentDisposition(r.Context(), key, h.attachmentDownloadURLTTL(), storage.AttachmentContentDisposition(att.Filename)); err != nil {
+ slog.Warn("failed to presign attachment download URL", "id", uuidToString(att.ID), "key", key, "error", err)
+ } else {
+ resp.AttachmentDownloadURL = dlURL
+ }
}
- case h.CFSigner == nil && mode == attachmentDownloadModeProxy:
+ case 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,
@@ -662,12 +699,10 @@ func (h *Handler) GetAttachmentByID(w http.ResponseWriter, r *http.Request) {
// 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())
+ // Download-intent sibling capability (dl=1): the redemption route turns
+ // it into a Content-Disposition: attachment, for the download button.
+ resp.AttachmentDownloadURL = attachmentDownloadCapabilityPath(resp.ID, time.Now())
}
writeJSON(w, http.StatusOK, resp)
@@ -820,7 +855,7 @@ func (h *Handler) DownloadAttachment(w http.ResponseWriter, r *http.Request) {
h.setAttachmentPreviewSecurityHeaders(w)
http.Redirect(w, r, signedURL, http.StatusFound)
case attachmentDownloadModeProxy:
- h.proxyAttachmentDownload(w, r, att, key)
+ h.proxyAttachmentDownload(w, r, att, key, false)
default:
writeError(w, http.StatusInternalServerError, "invalid attachment download mode")
}
@@ -912,7 +947,7 @@ func (h *Handler) ServeLocalUpload(w http.ResponseWriter, r *http.Request) {
// (serveProxyRange). Multi-range is not implemented on this path; per
// RFC 7233 it is ignored and the full body is served (200), matching the
// seekable path's successful outcome rather than failing with 416.
-func (h *Handler) proxyAttachmentDownload(w http.ResponseWriter, r *http.Request, att db.Attachment, key string) {
+func (h *Handler) proxyAttachmentDownload(w http.ResponseWriter, r *http.Request, att db.Attachment, key string, forceAttachment bool) {
reader, err := h.Storage.GetReader(r.Context(), key)
if err != nil {
slog.Error("failed to open attachment for download", "id", uuidToString(att.ID), "key", key, "error", err)
@@ -926,7 +961,13 @@ func (h *Handler) proxyAttachmentDownload(w http.ResponseWriter, r *http.Request
} else {
w.Header().Set("Content-Type", "application/octet-stream")
}
- w.Header().Set("Content-Disposition", storage.ContentDisposition(att.ContentType, att.Filename))
+ disposition := storage.ContentDisposition(att.ContentType, att.Filename)
+ if forceAttachment {
+ // Download-intent capability (dl=1): override the media-aware inline
+ // disposition so the browser saves the file instead of previewing it.
+ disposition = storage.AttachmentContentDisposition(att.Filename)
+ }
+ w.Header().Set("Content-Disposition", disposition)
// no-store predates Range support; keep it. Range/206 semantics are
// independent of caching — clients resume via Content-Range, not the cache.
w.Header().Set("Cache-Control", "no-store")
diff --git a/server/internal/handler/file_test.go b/server/internal/handler/file_test.go
index d97f4da141..353d1dfc11 100644
--- a/server/internal/handler/file_test.go
+++ b/server/internal/handler/file_test.go
@@ -702,8 +702,99 @@ func TestGetAttachmentByID_AutoPublicEndpointReturnsPresignedDownloadURL(t *test
if want := "/api/attachments/" + id + "/download"; resp.MarkdownURL != want {
t.Fatalf("markdown_url = %q, want stable URL %q", resp.MarkdownURL, want)
}
- if len(store.presignCalls) != 1 || store.presignCalls[0] != key {
- t.Fatalf("presign calls = %v, want [%s]", store.presignCalls, key)
+ // The single-attachment endpoint presigns the object twice: once inline for
+ // download_url (asserted above) and once with a forced attachment disposition
+ // for attachment_download_url.
+ if len(store.presignCalls) != 2 || store.presignCalls[0] != key || store.presignCalls[1] != key {
+ t.Fatalf("presign calls = %v, want [%s %s]", store.presignCalls, key, key)
+ }
+ dl, err := url.Parse(resp.AttachmentDownloadURL)
+ if err != nil {
+ t.Fatalf("parse attachment_download_url: %v", err)
+ }
+ if got := dl.Query().Get("X-Amz-Signature"); got != "mock" {
+ t.Fatalf("attachment_download_url = %q, want an S3 presigned URL", resp.AttachmentDownloadURL)
+ }
+ if got := dl.Query().Get("response-content-disposition"); !strings.HasPrefix(got, "attachment") {
+ t.Fatalf("attachment_download_url response-content-disposition = %q, want a forced attachment disposition", got)
+ }
+}
+
+// TestGetAttachmentByID_CloudFrontModeSignsForcedAttachmentDownloadURL pins the
+// CloudFront arm of GetAttachmentByID's download-URL switch — the one storage
+// mode still unexercised at this layer. It asserts attachment_download_url is a
+// CloudFront-signed URL carrying response-content-disposition=attachment, which
+// SignedURLWithContentDisposition sets on the URL BEFORE signing, so the
+// disposition is folded into the signed Resource (a client cannot strip or alter
+// it without invalidating the Signature — that property is unit-tested in
+// cloudfront_test.go). It also asserts the load-intent download_url sibling does
+// NOT force an attachment, so the two intents stay distinct.
+func TestGetAttachmentByID_CloudFrontModeSignsForcedAttachmentDownloadURL(t *testing.T) {
+ origStorage := testHandler.Storage
+ origCfg := testHandler.cfg
+ origSigner := testHandler.CFSigner
+ testHandler.Storage = &mockStorage{}
+ testHandler.cfg.AttachmentDownloadMode = "cloudfront"
+ testHandler.CFSigner = testCloudFrontSigner(t)
+ t.Cleanup(func() {
+ testHandler.Storage = origStorage
+ testHandler.cfg = origCfg
+ testHandler.CFSigner = origSigner
+ })
+
+ id := seedAttachmentURL(
+ t,
+ "https://static.example.test/downloads/cf-report.md",
+ "cf report.md",
+ "text/markdown",
+ 12,
+ )
+
+ 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())
+ }
+
+ dl, err := url.Parse(resp.AttachmentDownloadURL)
+ if err != nil {
+ t.Fatalf("parse attachment_download_url: %v", err)
+ }
+ if dl.Host != "static.example.test" {
+ t.Fatalf("attachment_download_url host = %q, want the CloudFront domain", dl.Host)
+ }
+ if got := dl.Query().Get("response-content-disposition"); got != `attachment; filename="cf report.md"` {
+ t.Fatalf("attachment_download_url response-content-disposition = %q, want a forced attachment disposition", got)
+ }
+ // Signed as a whole: Key-Pair-Id + Signature present. Because the disposition
+ // was set before signing, it is inside the signed Resource, so a client cannot
+ // strip or alter it without invalidating this Signature.
+ if got := dl.Query().Get("Key-Pair-Id"); got != "KTEST" {
+ t.Fatalf("attachment_download_url Key-Pair-Id = %q, want KTEST (CloudFront-signed)", got)
+ }
+ if dl.Query().Get("Signature") == "" {
+ t.Fatalf("attachment_download_url missing CloudFront Signature: %q", resp.AttachmentDownloadURL)
+ }
+
+ // The load-intent sibling must NOT force an attachment, or inline preview breaks.
+ inline, err := url.Parse(resp.DownloadURL)
+ if err != nil {
+ t.Fatalf("parse download_url: %v", err)
+ }
+ if got := inline.Query().Get("response-content-disposition"); strings.HasPrefix(got, "attachment") {
+ t.Fatalf("download_url must stay load-intent, got forced attachment disposition %q", got)
}
}