Skip to content

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

Go

fix(views): route plain attachment download links through the re-sign path (MUL-7991) (#9211)

erlinerdc6b451c9c165
diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.ts
index 08e5864d41..eb80e8b10e 100644
--- a/packages/core/api/client.test.ts
+++ b/packages/core/api/client.test.ts
@@ -1589,6 +1589,36 @@ describe("ApiClient", () => {
});
describe("getAttachment", () => {
+ it("uses the attachment-owned workspace endpoint for Markdown downloads", async () => {
+ const fetchMock = vi.fn().mockResolvedValue(
+ new Response(
+ JSON.stringify({
+ id: "att-1",
+ workspace_id: "ws-b",
+ uploader_type: "member",
+ uploader_id: "u-1",
+ filename: "report.md",
+ url: "https://static.example.test/report.md",
+ download_url: "/api/attachments/att-1/signed-download?sig=abc",
+ attachment_download_url: "/api/attachments/att-1/signed-download?sig=def&dl=1",
+ content_type: "text/markdown",
+ size_bytes: 123,
+ created_at: "2026-05-11T00:00:00Z",
+ }),
+ { status: 200, headers: { "Content-Type": "application/json" } },
+ ),
+ );
+ vi.stubGlobal("fetch", fetchMock);
+ const client = new ApiClient("https://api.example.test");
+
+ const att = await client.getAttachmentForDownload("att-1");
+
+ expect(fetchMock.mock.calls[0]?.[0]).toBe(
+ "https://api.example.test/api/attachments/att-1/download-metadata",
+ );
+ expect(att.attachment_download_url).toContain("dl=1");
+ });
+
it("returns the parsed attachment for a well-formed response", async () => {
vi.stubGlobal(
"fetch",
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index b7bd302160..265d284571 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -3947,6 +3947,15 @@ export class ApiClient {
});
}
+ // The Markdown download path resolves the attachment's own workspace and
+ // checks membership there. Its link may be pasted into another workspace.
+ async getAttachmentForDownload(id: string): Promise<Attachment> {
+ const raw = await this.fetch<unknown>(`/api/attachments/${id}/download-metadata`);
+ return parseWithFallback(raw, AttachmentResponseSchema, EMPTY_ATTACHMENT, {
+ endpoint: "GET /api/attachments/{id}/download-metadata",
+ });
+ }
+
async deleteAttachment(id: string): Promise<void> {
await this.fetch(`/api/attachments/${id}`, { method: "DELETE" });
}
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index f21c39d81f..9e6785707f 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -740,6 +740,7 @@ export const EMPTY_ISSUE_PROPERTIES_RESPONSE: IssuePropertiesResponse = {
export interface AppConfigResponse {
cdn_domain: string;
+ attachment_public_url?: string;
// True when the CDN domain serves private content via time-bounded signed
// URLs (CloudFront signing) — raw storage URLs on that domain are NOT
// publicly fetchable and must not be used as native media sources
@@ -1022,6 +1023,7 @@ export const EMPTY_REFRESH_SESSION_RESPONSE: RefreshSessionResponse = {
export const AppConfigSchema = z.object({
cdn_domain: z.string().default(""),
+ attachment_public_url: OptionalStringSchema,
cdn_signed: BooleanWithDefaultSchema(false),
allow_signup: BooleanWithDefaultSchema(true),
google_client_id: OptionalStringSchema,
@@ -1042,6 +1044,7 @@ export const AppConfigSchema = z.object({
export const EMPTY_APP_CONFIG: AppConfigResponse = {
cdn_domain: "",
+ attachment_public_url: "",
cdn_signed: false,
allow_signup: true,
google_client_id: "",
diff --git a/packages/core/config/index.ts b/packages/core/config/index.ts
index 40d1208213..94aae1dfc9 100644
--- a/packages/core/config/index.ts
+++ b/packages/core/config/index.ts
@@ -3,6 +3,7 @@ import { useStore } from "zustand";
interface ConfigState {
cdnDomain: string;
+ attachmentPublicUrl: string;
// True when cdnDomain serves private content via time-bounded signed URLs
// (CloudFront signing enabled server-side). Renderers must not treat a raw
// storage URL on that domain as a loadable media source (MUL-3254).
@@ -44,6 +45,7 @@ interface ConfigState {
// promises nothing about replies and uses the legacy delete route.
commentDeleteKeepRepliesSupported: boolean;
setCdnConfig: (config: { cdnDomain: string; cdnSigned?: boolean }) => void;
+ setAttachmentPublicUrl: (url?: string) => void;
setAuthConfig: (config: {
allowSignup: boolean;
googleClientId?: string;
@@ -64,6 +66,7 @@ interface ConfigState {
export const configStore = createStore<ConfigState>((set) => ({
cdnDomain: "",
+ attachmentPublicUrl: "",
cdnSigned: false,
allowSignup: true,
googleClientId: "",
@@ -78,6 +81,7 @@ export const configStore = createStore<ConfigState>((set) => ({
issueCreatePropertiesSupported: false,
commentDeleteKeepRepliesSupported: false,
setCdnConfig: ({ cdnDomain, cdnSigned = false }) => set({ cdnDomain, cdnSigned }),
+ setAttachmentPublicUrl: (url = "") => set({ attachmentPublicUrl: url }),
setAuthConfig: ({
allowSignup,
googleClientId = "",
diff --git a/packages/core/platform/auth-initializer.test.tsx b/packages/core/platform/auth-initializer.test.tsx
index b63d7b020a..a3e0fb486a 100644
--- a/packages/core/platform/auth-initializer.test.tsx
+++ b/packages/core/platform/auth-initializer.test.tsx
@@ -6,6 +6,7 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { setApiInstance } from "../api";
import { ApiError, type ApiClient } from "../api/client";
+import { configStore } from "../config";
import {
createAuthStore,
registerAuthStore,
@@ -121,6 +122,19 @@ afterEach(() => {
});
describe("AuthInitializer recovery", () => {
+ it("publishes the API origin used by persisted attachment links", async () => {
+ const api = makeApi({
+ getConfig: vi.fn().mockResolvedValue({
+ attachment_public_url: "https://api.example.test",
+ }),
+ });
+ renderInitializer({ api });
+
+ await waitFor(() => {
+ expect(configStore.getState().attachmentPublicUrl).toBe("https://api.example.test");
+ });
+ });
+
it("keeps the token and recovers on the online event after a network failure", async () => {
const storage = makeStorage({ multica_token: "token-1" });
const getMe = vi
diff --git a/packages/core/platform/auth-initializer.tsx b/packages/core/platform/auth-initializer.tsx
index c768b2c8c1..6a500f19b6 100644
--- a/packages/core/platform/auth-initializer.tsx
+++ b/packages/core/platform/auth-initializer.tsx
@@ -59,6 +59,7 @@ export function AuthInitializer({
const request = getApi()
.getConfig()
.then((cfg) => {
+ configStore.getState().setAttachmentPublicUrl(cfg.attachment_public_url);
if (cfg.cdn_domain) {
configStore.getState().setCdnConfig({
cdnDomain: cfg.cdn_domain,
diff --git a/packages/views/editor/use-download-attachment.test.tsx b/packages/views/editor/use-download-attachment.test.tsx
index e1a4eb3f80..b1e34227c6 100644
--- a/packages/views/editor/use-download-attachment.test.tsx
+++ b/packages/views/editor/use-download-attachment.test.tsx
@@ -4,13 +4,18 @@ import { act, renderHook, waitFor } from "@testing-library/react";
// Hoisted mock for the API singleton: vi.mock factories cannot reference
// outside-of-scope vars, but vi.hoisted runs before the import graph.
const getAttachmentMock = vi.hoisted(() => vi.fn());
+const getAttachmentForDownloadMock = vi.hoisted(() => vi.fn());
const getBaseUrlMock = vi.hoisted(() => vi.fn(() => ""));
const useWorkspaceSlugMock = vi.hoisted(() =>
vi.fn<() => string | null>(() => "acme"),
);
vi.mock("@multica/core/api", () => ({
- api: { getAttachment: getAttachmentMock, getBaseUrl: getBaseUrlMock },
+ api: {
+ getAttachment: getAttachmentMock,
+ getAttachmentForDownload: getAttachmentForDownloadMock,
+ getBaseUrl: getBaseUrlMock,
+ },
}));
vi.mock("@multica/core/paths", () => ({
@@ -47,6 +52,24 @@ afterEach(() => {
});
describe("useDownloadAttachment (web)", () => {
+ it("resolves a Markdown link without using the current workspace metadata route", async () => {
+ getAttachmentForDownloadMock.mockResolvedValueOnce({
+ attachment_download_url: "/api/attachments/att-1/signed-download?sig=member",
+ });
+ const clickSpy = vi
+ .spyOn(HTMLAnchorElement.prototype, "click")
+ .mockImplementation(() => {});
+ const { result } = renderHook(() => useDownloadAttachment("markdown-link"));
+
+ await act(async () => {
+ await result.current("att-1");
+ });
+
+ expect(getAttachmentForDownloadMock).toHaveBeenCalledWith("att-1");
+ expect(getAttachmentMock).not.toHaveBeenCalled();
+ expect(clickSpy).toHaveBeenCalledOnce();
+ });
+
it("clicks the unified download endpoint without opening a blank tab or buffering a Blob", async () => {
getAttachmentMock.mockResolvedValueOnce({
id: "att-1",
diff --git a/packages/views/editor/use-download-attachment.ts b/packages/views/editor/use-download-attachment.ts
index 4dacab869a..f73457896b 100644
--- a/packages/views/editor/use-download-attachment.ts
+++ b/packages/views/editor/use-download-attachment.ts
@@ -111,7 +111,9 @@ function hasDesktopDownloadBridge(): boolean {
* the Linux/Ubuntu issue where HTML files are rendered inline instead
* of being downloaded.
*/
-export function useDownloadAttachment(): (attachmentId: string) => Promise<void> {
+export function useDownloadAttachment(
+ source: "workspace" | "markdown-link" = "workspace",
+): (attachmentId: string) => Promise<void> {
const { t } = useT("editor");
const workspaceSlug = useWorkspaceSlug();
return useCallback(
@@ -120,7 +122,9 @@ export function useDownloadAttachment(): (attachmentId: string) => Promise<void>
if (hasDesktopDownloadBridge()) {
try {
- const fresh = await api.getAttachment(attachmentId);
+ const fresh = await (source === "markdown-link"
+ ? api.getAttachmentForDownload(attachmentId)
+ : api.getAttachment(attachmentId));
// 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
@@ -151,7 +155,9 @@ export function useDownloadAttachment(): (attachmentId: string) => Promise<void>
// failures still produce the existing toast instead of a silent failed
// navigation) and where the server hands back the download URLs it mints
// for this response.
- const fresh = await api.getAttachment(attachmentId);
+ const fresh = await (source === "markdown-link"
+ ? api.getAttachmentForDownload(attachmentId)
+ : api.getAttachment(attachmentId));
if (typeof document === "undefined") {
failed();
return;
@@ -190,6 +196,6 @@ export function useDownloadAttachment(): (attachmentId: string) => Promise<void>
failed();
}
},
- [t, workspaceSlug],
+ [t, workspaceSlug, source],
);
}
diff --git a/packages/views/rich-content/app-url-link-routing.test.tsx b/packages/views/rich-content/app-url-link-routing.test.tsx
index 7efd902a0e..139bc35cae 100644
--- a/packages/views/rich-content/app-url-link-routing.test.tsx
+++ b/packages/views/rich-content/app-url-link-routing.test.tsx
@@ -10,8 +10,9 @@
* nothing about the routing decision.
*/
import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";
-import { render, screen } from "@testing-library/react";
+import { act, render, screen } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { configStore } from "@multica/core/config";
const APP_ORIGIN = "https://app.example";
@@ -45,6 +46,15 @@ vi.mock("../editor/link-hover-card", () => ({
LinkHoverCard: () => null,
}));
+// Intercepted-attachment-link click handler. A plain `<a>` to the API-host
+// attachment endpoint cannot authenticate a bare navigation (WK-11), so the
+// renderer must hand the click to this hook instead of `window.open`. We mock
+// the module so the test asserts the dispatch, not the download plumbing.
+const downloadAttachmentSpy = vi.fn();
+vi.mock("../editor/use-download-attachment", () => ({
+ useDownloadAttachment: () => downloadAttachmentSpy,
+}));
+
vi.mock("mermaid", () => ({
default: { initialize: vi.fn(), render: vi.fn() },
}));
@@ -56,6 +66,9 @@ let openSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
navigatedPaths = [];
+ act(() => {
+ configStore.getState().setAttachmentPublicUrl("https://multica-api.erlinerd.com");
+ });
window.addEventListener("multica:navigate", captureNavigate);
openSpy = vi.spyOn(window, "open").mockImplementation(() => null);
});
@@ -63,6 +76,10 @@ beforeEach(() => {
afterEach(() => {
window.removeEventListener("multica:navigate", captureNavigate);
vi.restoreAllMocks();
+ downloadAttachmentSpy.mockClear();
+ act(() => {
+ configStore.getState().setAttachmentPublicUrl("");
+ });
});
function captureNavigate(e: Event) {
@@ -132,4 +149,56 @@ describe("RichContent link routing", () => {
"noopener,noreferrer",
);
});
+
+ // WK-11: a plain-link attachment download URL (the shape `buildMarkdownURL`
+ // persists into bodies in private-storage deployments — absolute, API-host
+ // pinned) cannot authenticate a bare navigation, so it must be routed through
+ // the credentialed download hook rather than window.open.
+ it("routes a UUID attachment download link through the download hook (WK-11)", () => {
+ const id = "01a13179-08aa-7898-ae86-3a1994d2147e";
+ const download = `https://multica-api.erlinerd.com/api/attachments/${id}/download`;
+ renderContent(`[audit-report.md](${download})`);
+
+ screen.getByText("audit-report.md").click();
+
+ // Not opened as an unauthenticated external navigation, and not treated as
+ // an in-app path.
+ expect(openSpy).not.toHaveBeenCalled();
+ expect(navigatedPaths).toEqual([]);
+ expect(downloadAttachmentSpy).toHaveBeenCalledWith(id);
+ });
+
+ it("recognizes the API-host link when runtime config arrives after rendering", () => {
+ const id = "01a13179-08aa-7898-ae86-3a1994d2147e";
+ const download = `https://multica-api.erlinerd.com/api/attachments/${id}/download`;
+ act(() => configStore.getState().setAttachmentPublicUrl(""));
+ renderContent(`[report.pdf](${download})`);
+
+ act(() => configStore.getState().setAttachmentPublicUrl("https://multica-api.erlinerd.com"));
+ screen.getByText("report.pdf").click();
+
+ expect(downloadAttachmentSpy).toHaveBeenCalledWith(id);
+ expect(openSpy).not.toHaveBeenCalled();
+ });
+
+ it("does not intercept a non-UUID /api/attachments link", () => {
+ const download = `${APP_ORIGIN}/api/attachments/abc/download`;
+ renderContent(`[report.pdf](${download})`);
+
+ screen.getByText("report.pdf").click();
+
+ expect(downloadAttachmentSpy).not.toHaveBeenCalled();
+ expect(openSpy).toHaveBeenCalledWith(download, "_blank", "noopener,noreferrer");
+ });
+
+ it("keeps another deployment's attachment URL on the external link path", () => {
+ const id = "01a13179-08aa-7898-ae86-3a1994d2147e";
+ const external = `https://other.example/api/attachments/${id}/download`;
+ renderContent(`[report.pdf](${external})`);
+
+ screen.getByText("report.pdf").click();
+
+ expect(downloadAttachmentSpy).not.toHaveBeenCalled();
+ expect(openSpy).toHaveBeenCalledWith(external, "_blank", "noopener,noreferrer");
+ });
});
diff --git a/packages/views/rich-content/rich-content.tsx b/packages/views/rich-content/rich-content.tsx
index dff1f2748a..55e1d44745 100644
--- a/packages/views/rich-content/rich-content.tsx
+++ b/packages/views/rich-content/rich-content.tsx
@@ -42,7 +42,9 @@ import rehypeSanitize from "rehype-sanitize";
import { cn } from "@multica/ui/lib/utils";
import { useWorkspaceSlug } from "@multica/core/paths";
import { useConfigStore } from "@multica/core/config";
+import { api } from "@multica/core/api";
import type { Attachment } from "@multica/core/types";
+import { attachmentIdFromDownloadURL } from "@multica/core/types";
import {
isAllowedFileCardHref,
isIssueIdentifier,
@@ -67,6 +69,7 @@ import {
import { preprocessMarkdown } from "../editor/utils/preprocess";
import { highlightToHtml } from "../editor/utils/highlight-markdown";
import { AttachmentDownloadProvider } from "../editor/attachment-download-context";
+import { useDownloadAttachment } from "../editor/use-download-attachment";
import { Attachment as AttachmentRenderer } from "../editor/attachment";
import { computeClosedFences, type ClosedFence } from "./streaming-fence";
import { remarkRepairCjkStrongTrailingWhitespace } from "./cjk-emphasis";
@@ -206,9 +209,40 @@ function unfurlableEntityLink(
return entity;
}
+function ownAttachmentDownloadId(
+ href: string,
+ appOrigin: string | null,
+ attachmentPublicUrl: string,
+): string | undefined {
+ const id = attachmentIdFromDownloadURL(href);
+ if (!id) return undefined;
+ if (href.startsWith("/") && !href.startsWith("//")) return id;
+
+ // The path and UUID alone do not establish which deployment owns a link.
+ // PublicURL can differ from both the web app origin and the browser's
+ // same-origin API proxy, so the server supplies that origin via /api/config.
+ try {
+ const target = new URL(href);
+ if (target.username || target.password) return undefined;
+ const ownOrigins = [appOrigin, api.getBaseUrl?.(), attachmentPublicUrl];
+ return ownOrigins.some((base) => {
+ if (!base) return false;
+ try {
+ return new URL(base).origin === target.origin;
+ } catch {
+ return false;
+ }
+ }) ? id : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
function RichLink({ href, children }: { href?: string; children?: ReactNode }) {
const slug = useWorkspaceSlug();
const appOrigin = useAppOrigin();
+ const attachmentPublicUrl = useConfigStore((s) => s.attachmentPublicUrl);
+ const downloadAttachment = useDownloadAttachment("markdown-link");
// Platform probe only: `openInNewTab` present means desktop, where native
// anchor behavior is a dead end and every click must be intercepted. Absent
// (web), modified clicks are left to the browser — the only way to get a
@@ -219,6 +253,23 @@ function RichLink({ href, children }: { href?: string; children?: ReactNode }) {
return <span className="slash-command">{children}</span>;
}
+ // An attachment download URL written as a plain link — the shape the
+ // server persists into bodies via `buildMarkdownURL`, which in private-
+ // storage deployments is ABSOLUTE and pinned to the API host
+ // (`MULTICA_PUBLIC_URL`). A bare navigation there cannot authenticate:
+ // web's session cookie is host-locked to the API origin and
+ // SameSite=Strict (and Desktop/mobile carry a bearer token no <a> can
+ // send), so the browser gets `401 missing authorization`. Route through
+ // the download hook instead, which refreshes the authenticated metadata
+ // and navigates to the credential-bearing URL the server mints for this
+ // click (capability / presign / CloudFront, per deployment mode). Same
+ // click-time re-sign the file-card renderer already does (MUL-3130).
+ // Also require this deployment's origin; another Multica instance may use
+ // the same path shape with unrelated attachment IDs.
+ const attachmentId = href
+ ? ownAttachmentDownloadId(href, appOrigin, attachmentPublicUrl)
+ : undefined;
+
if (isMentionHref(href)) {
const match = href.match(/^mention:\/\/(member|agent|issue|project|all)\/(.+)$/);
if (match?.[1] === "issue" && match[2]) {
@@ -253,6 +304,20 @@ function RichLink({ href, children }: { href?: string; children?: ReactNode }) {
e.preventDefault();
return;
}
+ // An attachment link downloads through the re-sign path instead of a
+ // credential-less navigation (see attachmentId note above). This holds
+ // on every platform: web's session cookie is host-locked to the API
+ // origin and SameSite=Strict, and Desktop/mobile carry a bearer token
+ // no <a> can send, so a bare navigation 401s either way. The download
+ // hook owns the per-platform mechanism (capability anchor on web,
+ // native bridge on Desktop). Modified clicks stay native — the browser
+ // owns "open in background tab" and the raw URL remains the durable
+ // reference.
+ if (attachmentId && !e.metaKey && !e.ctrlKey && !e.shiftKey) {
+ e.preventDefault();
+ void downloadAttachment(attachmentId);
+ return;
+ }
if (!desktopTabs && (e.metaKey || e.ctrlKey || e.shiftKey)) return;
e.preventDefault();
openLink(href, slug, appOrigin, resolveClickIntent(e));
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 42b49d8b16..54485467be 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -1691,6 +1691,10 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
// because they are JSON-API consumers that always have
// workspace context.
r.Get("/api/attachments/{id}/download", h.DownloadAttachment)
+ // Markdown links may point to an attachment in a different workspace.
+ // Resolve that workspace from the row and check membership before minting
+ // a fresh URL; the workspace-scoped metadata route stays unchanged.
+ r.Get("/api/attachments/{id}/download-metadata", h.GetAttachmentForDownload)
r.Route("/api/workspaces", func(r chi.Router) {
r.Get("/", h.ListWorkspaces)
diff --git a/server/internal/handler/config.go b/server/internal/handler/config.go
index f5857c8782..5a6764e680 100644
--- a/server/internal/handler/config.go
+++ b/server/internal/handler/config.go
@@ -12,6 +12,9 @@ import (
type AppConfig struct {
CdnDomain string `json:"cdn_domain"`
+ // The origin used for durable private-attachment Markdown links. Clients
+ // use it only to recognize links belonging to this deployment.
+ AttachmentPublicURL string `json:"attachment_public_url,omitempty"`
// CdnSigned tells clients that the CDN domain above serves PRIVATE
// content through time-bounded signed URLs (CloudFront signing is
// enabled). When true, a raw storage URL on the CDN domain is NOT
@@ -121,6 +124,7 @@ func (h *Handler) GetConfig(w http.ResponseWriter, r *http.Request) {
if h.Storage != nil {
config.CdnDomain = h.Storage.CdnDomain()
}
+ config.AttachmentPublicURL = h.cfg.PublicURL
config.CdnSigned = h.CFSigner != nil
config.DaemonServerURL, config.DaemonAppURL = daemonSetupURLsFromEnv()
config.VCSIntegrationAvailable = h.cfg.VCSIntegrationEnabled
diff --git a/server/internal/handler/config_test.go b/server/internal/handler/config_test.go
index a8353ce6a0..8641b83432 100644
--- a/server/internal/handler/config_test.go
+++ b/server/internal/handler/config_test.go
@@ -53,8 +53,13 @@ func TestGetConfigReportsCdnSignedMode(t *testing.T) {
func TestGetConfigIncludesRuntimeAuthConfig(t *testing.T) {
origStorage := testHandler.Storage
+ origCfg := testHandler.cfg
testHandler.Storage = &mockStorage{}
- defer func() { testHandler.Storage = origStorage }()
+ testHandler.cfg.PublicURL = "https://api.example.com"
+ defer func() {
+ testHandler.Storage = origStorage
+ testHandler.cfg = origCfg
+ }()
t.Setenv("ALLOW_SIGNUP", "false")
t.Setenv("GOOGLE_CLIENT_ID", "google-client-id")
@@ -80,6 +85,9 @@ func TestGetConfigIncludesRuntimeAuthConfig(t *testing.T) {
if cfg.CdnDomain != "cdn.example.com" {
t.Fatalf("cdn_domain: want cdn.example.com, got %q", cfg.CdnDomain)
}
+ if cfg.AttachmentPublicURL != "https://api.example.com" {
+ t.Fatalf("attachment_public_url = %q, want API public URL", cfg.AttachmentPublicURL)
+ }
if cfg.AllowSignup {
t.Fatalf("allow_signup: want false, got true")
}
diff --git a/server/internal/handler/file.go b/server/internal/handler/file.go
index cac6a7b315..c1915c0904 100644
--- a/server/internal/handler/file.go
+++ b/server/internal/handler/file.go
@@ -673,6 +673,22 @@ func (h *Handler) GetAttachmentByID(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
+ h.writeSignedAttachmentMetadata(w, r, att)
+}
+
+// GetAttachmentForDownload resolves the workspace from the attachment, as the
+// durable Markdown download URL does. A link can be pasted into a different
+// workspace; the current workspace header must not change its target. The
+// membership check is the same one used by the protected download endpoint.
+func (h *Handler) GetAttachmentForDownload(w http.ResponseWriter, r *http.Request) {
+ att, ok := h.loadAttachmentForDownload(w, r)
+ if !ok {
+ return
+ }
+ h.writeSignedAttachmentMetadata(w, r, att)
+}
+
+func (h *Handler) writeSignedAttachmentMetadata(w http.ResponseWriter, r *http.Request, att db.Attachment) {
// Always signed, regardless of what the caller advertised: this endpoint is
// the single source of fresh, natively-loadable URLs. Stable-mode callers
diff --git a/server/internal/handler/file_test.go b/server/internal/handler/file_test.go
index 6f5a40c496..df2ee4e77d 100644
--- a/server/internal/handler/file_test.go
+++ b/server/internal/handler/file_test.go
@@ -25,6 +25,7 @@ import (
"github.com/go-chi/chi/v5"
"github.com/multica-ai/multica/server/internal/auth"
"github.com/multica-ai/multica/server/internal/storage"
+ "github.com/multica-ai/multica/server/internal/testutil"
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
@@ -758,6 +759,52 @@ func TestGetAttachmentByID_AutoPublicEndpointReturnsPresignedDownloadURL(t *test
}
}
+func TestGetAttachmentForDownload_UsesAttachmentWorkspaceMembership(t *testing.T) {
+ if testPool == nil {
+ t.Skip("test database not available")
+ }
+ store := &mockStorageNoCdn{}
+ origStorage, origCfg, origSigner := testHandler.Storage, testHandler.cfg, testHandler.CFSigner
+ testHandler.Storage = store
+ testHandler.cfg.AttachmentDownloadMode = "proxy"
+ testHandler.CFSigner = nil
+ t.Cleanup(func() {
+ testHandler.Storage, testHandler.cfg, testHandler.CFSigner = origStorage, origCfg, origSigner
+ })
+
+ slug := fmt.Sprintf("download-metadata-%d", time.Now().UnixNano())
+ otherWorkspaceID := dbfx.Insert(t, "workspace", testutil.Cols{
+ "name": "Download metadata workspace", "slug": slug,
+ "description": "", "issue_prefix": "DMW",
+ })
+ id := dbfx.Insert(t, "attachment", testutil.Cols{
+ "workspace_id": otherWorkspaceID,
+ "uploader_type": "member", "uploader_id": testUserID,
+ "filename": "report.pdf", "url": "https://s3.example.com/test-bucket/report.pdf",
+ "content_type": "application/pdf", "size_bytes": 12,
+ })
+
+ request := func() *http.Request {
+ req := httptest.NewRequest("GET", "/api/attachments/"+id+"/download-metadata", nil)
+ req.Header.Set("X-User-ID", testUserID)
+ req.Header.Set("X-Workspace-ID", testWorkspaceID) // viewing workspace A
+ rctx := chi.NewRouteContext()
+ rctx.URLParams.Add("id", id)
+ return req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))
+ }
+
+ testutil.Call(t, testHandler.GetAttachmentForDownload, request()).Want(http.StatusNotFound)
+ dbfx.Insert(t, "member", testutil.Cols{
+ "workspace_id": otherWorkspaceID, "user_id": testUserID, "role": "member",
+ })
+
+ var resp AttachmentResponse
+ testutil.Call(t, testHandler.GetAttachmentForDownload, request()).Want(http.StatusOK).JSON(&resp)
+ if resp.ID != id || !strings.Contains(resp.AttachmentDownloadURL, "/signed-download?") {
+ t.Fatalf("response missing attachment-specific signed URL: %+v", resp)
+ }
+}
+
// 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