Skip to content

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

Go

fix: re-sign inline attachment media for token-mode clients (#4085)

Bohan Jiang6c17771cce33
diff --git a/packages/core/api/schemas.test.ts b/packages/core/api/schemas.test.ts
index f54420284b..e9f347ed82 100644
--- a/packages/core/api/schemas.test.ts
+++ b/packages/core/api/schemas.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it } from "vitest";
import {
+ AppConfigSchema,
DashboardAgentRunTimeListSchema,
DashboardUsageByAgentListSchema,
DashboardUsageDailyListSchema,
@@ -270,3 +271,24 @@ describe("dashboard + runtime usage schema drift", () => {
expect((parsed[0] as Record<string, unknown>).region).toBe("us-east");
});
});
+
+describe("AppConfigSchema cdn_signed drift", () => {
+ it("defaults cdn_signed to false when the server omits it (pre-MUL-3254 servers)", () => {
+ const parsed = AppConfigSchema.parse({ cdn_domain: "cdn.example.com" });
+ expect(parsed.cdn_signed).toBe(false);
+ });
+
+ it("coerces a malformed cdn_signed to false instead of failing the whole config", () => {
+ const parsed = AppConfigSchema.parse({
+ cdn_domain: "cdn.example.com",
+ cdn_signed: "yes",
+ });
+ expect(parsed.cdn_signed).toBe(false);
+ expect(parsed.cdn_domain).toBe("cdn.example.com");
+ });
+
+ it("keeps cdn_signed=true from a signing-enabled server", () => {
+ const parsed = AppConfigSchema.parse({ cdn_signed: true });
+ expect(parsed.cdn_signed).toBe(true);
+ });
+});
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index c88135d767..110b6baf62 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -26,6 +26,11 @@ import type { CloudRuntimeNode } from "../runtimes/cloud-runtime";
export interface AppConfigResponse {
cdn_domain: 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
+ // (MUL-3254). Older servers omit the field; treat that as false.
+ cdn_signed?: boolean;
allow_signup: boolean;
google_client_id?: string;
posthog_key?: string;
@@ -164,6 +169,7 @@ const BooleanWithDefaultSchema = (fallback: boolean) =>
export const AppConfigSchema = z.object({
cdn_domain: z.string().default(""),
+ cdn_signed: BooleanWithDefaultSchema(false),
allow_signup: BooleanWithDefaultSchema(true),
google_client_id: OptionalStringSchema,
posthog_key: OptionalStringSchema,
@@ -176,6 +182,7 @@ export const AppConfigSchema = z.object({
export const EMPTY_APP_CONFIG: AppConfigResponse = {
cdn_domain: "",
+ cdn_signed: false,
allow_signup: true,
google_client_id: "",
daemon_server_url: "",
diff --git a/packages/core/config/index.ts b/packages/core/config/index.ts
index f24336471a..005f3cbfa1 100644
--- a/packages/core/config/index.ts
+++ b/packages/core/config/index.ts
@@ -3,6 +3,10 @@ import { useStore } from "zustand";
interface ConfigState {
cdnDomain: 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).
+ cdnSigned: boolean;
allowSignup: boolean;
googleClientId: string;
daemonServerUrl: string;
@@ -11,7 +15,7 @@ interface ConfigState {
// must be hidden. Defaults to false so unknown / older servers behave like
// the managed-cloud case.
workspaceCreationDisabled: boolean;
- setCdnDomain: (domain: string) => void;
+ setCdnConfig: (config: { cdnDomain: string; cdnSigned?: boolean }) => void;
setAuthConfig: (config: {
allowSignup: boolean;
googleClientId?: string;
@@ -25,12 +29,13 @@ interface ConfigState {
export const configStore = createStore<ConfigState>((set) => ({
cdnDomain: "",
+ cdnSigned: false,
allowSignup: true,
googleClientId: "",
daemonServerUrl: "",
daemonAppUrl: "",
workspaceCreationDisabled: false,
- setCdnDomain: (domain) => set({ cdnDomain: domain }),
+ setCdnConfig: ({ cdnDomain, cdnSigned = false }) => set({ cdnDomain, cdnSigned }),
setAuthConfig: ({ allowSignup, googleClientId = "", workspaceCreationDisabled = false }) =>
set({ allowSignup, googleClientId, workspaceCreationDisabled }),
setDaemonConfig: ({ daemonServerUrl = "", daemonAppUrl = "" }) =>
diff --git a/packages/core/platform/auth-initializer.tsx b/packages/core/platform/auth-initializer.tsx
index 81ef875439..4269a7f673 100644
--- a/packages/core/platform/auth-initializer.tsx
+++ b/packages/core/platform/auth-initializer.tsx
@@ -49,7 +49,13 @@ export function AuthInitializer({
api
.getConfig()
.then((cfg) => {
- if (cfg.cdn_domain) configStore.getState().setCdnDomain(cfg.cdn_domain);
+ if (cfg.cdn_domain) {
+ configStore.getState().setCdnConfig({
+ cdnDomain: cfg.cdn_domain,
+ // Old servers omit this — false keeps the previous behavior.
+ cdnSigned: cfg.cdn_signed === true,
+ });
+ }
configStore.getState().setAuthConfig({
allowSignup: cfg.allow_signup,
googleClientId: cfg.google_client_id,
diff --git a/packages/views/editor/attachment.test.tsx b/packages/views/editor/attachment.test.tsx
index 7620293b78..d2037d0084 100644
--- a/packages/views/editor/attachment.test.tsx
+++ b/packages/views/editor/attachment.test.tsx
@@ -1,17 +1,19 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { render, screen, fireEvent } from "@testing-library/react";
+import { render, screen, fireEvent, waitFor } from "@testing-library/react";
import type { ReactElement, ReactNode } from "react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { Attachment as AttachmentRecord } from "@multica/core/types";
const {
getAttachmentTextContentMock,
+ getAttachmentMock,
getBaseUrlMock,
downloadMock,
openExternalMock,
openByUrlMock,
} = vi.hoisted(() => ({
getAttachmentTextContentMock: vi.fn(),
+ getAttachmentMock: vi.fn(),
// Default: empty base URL so existing tests render site-relative URLs
// through the proxy (i.e. exactly the way the web app behaves). The
// absolutize-specific suite below overrides this to simulate Desktop /
@@ -25,6 +27,7 @@ const {
vi.mock("@multica/core/api", () => ({
api: {
getAttachmentTextContent: getAttachmentTextContentMock,
+ getAttachment: getAttachmentMock,
getBaseUrl: getBaseUrlMock,
},
PreviewTooLargeError: class extends Error {},
@@ -154,7 +157,7 @@ function renderWithQuery(ui: ReactElement) {
beforeEach(() => {
vi.clearAllMocks();
resolverState.attachments = [];
- configStore.setState({ cdnDomain: "" });
+ configStore.setState({ cdnDomain: "", cdnSigned: false });
// Default to "no proxy override" — site-relative URLs stay as-is, mirroring
// the web app's same-origin proxy. Tests that simulate Desktop / mobile
// webview override per-case via getBaseUrlMock.mockReturnValue(...).
@@ -292,6 +295,110 @@ describe("Attachment — image dispatch", () => {
expect(imageSrcs).not.toContain("");
});
+ it("does not pick the raw CDN url when the server reports cdn_signed (MUL-3254)", () => {
+ // CloudFront signed-URL mode: the CDN domain serves PRIVATE content and
+ // a raw (unsigned) storage URL is a guaranteed 403. The pick must fall
+ // through to the durable markdown_url instead.
+ configStore.setState({ cdnDomain: "cdn.example.test", cdnSigned: true });
+ const id = "11111111-2222-3333-4444-555555555555";
+ const markdownUrl = `https://multica-api.copilothub.ai/api/attachments/${id}/download`;
+ const att = makeRecord({
+ id,
+ url: "https://cdn.example.test/uploads/ws/shot.png",
+ markdown_url: markdownUrl,
+ download_url: "",
+ });
+ resolverState.attachments = [att];
+
+ renderWithQuery(
+ <Attachment
+ attachment={{
+ kind: "url",
+ url: markdownUrl,
+ filename: "shot.png",
+ forceKind: "image",
+ }}
+ />,
+ );
+
+ const img = document.querySelector("img");
+ expect(img?.getAttribute("src")).toBe(markdownUrl);
+ // Web (same-origin proxy / same-site cookie): the API endpoint loads
+ // natively, so no metadata re-fetch is needed.
+ expect(getAttachmentMock).not.toHaveBeenCalled();
+ });
+
+ it("re-signs the inline media URL through getAttachment on token-mode clients (MUL-3254)", async () => {
+ // Desktop / mobile webview: file:// document origin, Bearer-token auth.
+ // The auth-gated /api/attachments/<id>/download endpoint 401s as a
+ // native <img> fetch, so the renderer must swap in a freshly signed URL
+ // from authenticated attachment metadata — the reopened-draft case where
+ // the persisted record deliberately strips the expired download_url.
+ getBaseUrlMock.mockReturnValue("https://multica-api.copilothub.ai");
+ configStore.setState({ cdnDomain: "cdn.example.test", cdnSigned: true });
+ const id = "11111111-2222-3333-4444-555555555555";
+ const markdownUrl = `https://multica-api.copilothub.ai/api/attachments/${id}/download`;
+ const signed =
+ "https://cdn.example.test/uploads/ws/shot.png?Signature=fresh&Key-Pair-Id=K";
+ const att = makeRecord({
+ id,
+ url: "https://cdn.example.test/uploads/ws/shot.png",
+ markdown_url: markdownUrl,
+ download_url: "",
+ });
+ resolverState.attachments = [att];
+ getAttachmentMock.mockResolvedValue(makeRecord({ id, download_url: signed }));
+
+ renderWithQuery(
+ <Attachment
+ attachment={{
+ kind: "url",
+ url: markdownUrl,
+ filename: "shot.png",
+ forceKind: "image",
+ }}
+ />,
+ );
+
+ await waitFor(() => {
+ expect(document.querySelector("img")?.getAttribute("src")).toBe(signed);
+ });
+ expect(getAttachmentMock).toHaveBeenCalledWith(id);
+ });
+
+ it("keeps the picked URL when fresh metadata has no signed download_url (MUL-3254)", async () => {
+ // Non-CloudFront deployments return the API path again as download_url —
+ // swapping to it gains nothing, so the original pick must stay.
+ getBaseUrlMock.mockReturnValue("https://multica-api.copilothub.ai");
+ const id = "11111111-2222-3333-4444-555555555555";
+ const markdownUrl = `https://multica-api.copilothub.ai/api/attachments/${id}/download`;
+ const att = makeRecord({
+ id,
+ url: "https://cdn.example.test/uploads/ws/shot.png",
+ markdown_url: markdownUrl,
+ download_url: "",
+ });
+ configStore.setState({ cdnDomain: "", cdnSigned: false });
+ resolverState.attachments = [att];
+ getAttachmentMock.mockResolvedValue(
+ makeRecord({ id, download_url: `/api/attachments/${id}/download` }),
+ );
+
+ renderWithQuery(
+ <Attachment
+ attachment={{
+ kind: "url",
+ url: markdownUrl,
+ filename: "shot.png",
+ forceKind: "image",
+ }}
+ />,
+ );
+
+ await waitFor(() => expect(getAttachmentMock).toHaveBeenCalledWith(id));
+ expect(document.querySelector("img")?.getAttribute("src")).toBe(markdownUrl);
+ });
+
it("forceKind=image renders as image even when filename is empty (markdown ![](url) regression)", () => {
renderWithQuery(
<Attachment
diff --git a/packages/views/editor/attachment.tsx b/packages/views/editor/attachment.tsx
index 5109ff4209..62bcf84dd1 100644
--- a/packages/views/editor/attachment.tsx
+++ b/packages/views/editor/attachment.tsx
@@ -32,9 +32,11 @@ import {
import { toast } from "sonner";
import { cn } from "@multica/ui/lib/utils";
import { copyText } from "@multica/ui/lib/clipboard";
+import { useQuery } from "@tanstack/react-query";
import { api } from "@multica/core/api";
import { useConfigStore } from "@multica/core/config";
import type { Attachment as AttachmentRecord } from "@multica/core/types";
+import { attachmentIdFromDownloadURL } from "@multica/core/types/attachment-url";
import { useT } from "../i18n";
import { useAttachmentDownloadResolver } from "./attachment-download-context";
import { useAttachmentPreview } from "./attachment-preview-modal";
@@ -108,13 +110,14 @@ function normalize(
input: AttachmentInput,
resolve: (url: string) => AttachmentRecord | undefined,
cdnDomain: string,
+ cdnSigned: boolean,
): Normalized {
if (input.kind === "record") {
return {
filename: input.attachment.filename,
contentType: input.attachment.content_type,
url: absolutizeMediaURL(
- pickInlineMediaURL(input.attachment, input.attachment.url, cdnDomain),
+ pickInlineMediaURL(input.attachment, input.attachment.url, cdnDomain, cdnSigned),
),
attachmentId: input.attachment.id,
record: input.attachment,
@@ -147,7 +150,7 @@ function normalize(
// uploaded image URL stayed site-relative and Electron's renderer
// origin (file://) couldn't load it.
url: absolutizeMediaURL(
- record ? pickInlineMediaURL(record, input.url, cdnDomain) : input.url,
+ record ? pickInlineMediaURL(record, input.url, cdnDomain, cdnSigned) : input.url,
),
attachmentId: record?.id,
record,
@@ -230,7 +233,10 @@ function absolutizeMediaURL(rawUrl: string): string {
// directly (public CDN, or CloudFront cookie mode). Prefer it over
// an API-shaped `markdown_url` so the rendered `<img src>` and Copy
// Link affordance expose the CDN URL while the persisted markdown
-// can remain the stable attachment endpoint.
+// can remain the stable attachment endpoint. Skipped when the server
+// reports `cdn_signed` — in CloudFront signed-URL mode the same
+// domain serves PRIVATE content and a raw (unsigned) storage URL is
+// a guaranteed 403 (MUL-3254).
// 3. `record.markdown_url` — the durable, server-policy-aligned URL.
// Beats raw `record.url` because it never points at a private
// bucket (must-fix 2 from MUL-3192 review).
@@ -241,6 +247,7 @@ function pickInlineMediaURL(
record: AttachmentRecord,
fallback: string,
cdnDomain: string,
+ cdnSigned: boolean,
): string {
const dl = record.download_url ?? "";
if (
@@ -249,7 +256,7 @@ function pickInlineMediaURL(
) {
return dl;
}
- if (storageURLMatchesCdnDomain(record.url, cdnDomain)) return record.url;
+ if (!cdnSigned && storageURLMatchesCdnDomain(record.url, cdnDomain)) return record.url;
if (record.markdown_url) return record.markdown_url;
if (record.url) return record.url;
return fallback;
@@ -285,6 +292,63 @@ function hasExpiringSignatureQuery(q: URLSearchParams): boolean {
return false;
}
+// ---------------------------------------------------------------------------
+// Inline media re-sign (MUL-3254)
+// ---------------------------------------------------------------------------
+
+// Keep refetches well inside the server's signed-URL TTL (30 min default,
+// server/internal/handler/file.go) so a re-render never serves an expired
+// signature from the query cache.
+const RESIGN_STALE_MS = 20 * 60 * 1000;
+
+// useResignedInlineMediaURL upgrades an auth-gated media URL to a freshly
+// signed one for clients that cannot load `/api/attachments/<id>/download`
+// natively.
+//
+// The picked inline URL can end up being the stable per-attachment API
+// endpoint (e.g. a reopened issue draft, whose persisted record deliberately
+// strips the short-lived signed `download_url`). That endpoint needs
+// credentials: web loads it because the session cookie rides on the <img>
+// request (same-site), but Desktop's file:// renderer and the mobile webview
+// are cross-site — no cookie is attached and the Bearer token cannot be put
+// on a native resource fetch, so the image 401s. Those clients are exactly
+// the ones with a non-empty `api.getBaseUrl()` (no same-origin /api proxy),
+// which is the existing platform signal `absolutizeMediaURL` keys off.
+//
+// For them, fetch fresh attachment metadata through the authenticated API —
+// the same re-sign the click-time download path already does — and swap in
+// the response's signed `download_url`. When the server has no signed URL to
+// offer (non-CloudFront deployments return the API path again), keep the
+// original URL rather than looping.
+function useResignedInlineMediaURL(
+ attachmentId: string | undefined,
+ pickedUrl: string,
+): string {
+ const needsResign =
+ !!attachmentId &&
+ !!pickedUrl &&
+ attachmentIdFromDownloadURL(pickedUrl) !== undefined &&
+ (api.getBaseUrl?.() ?? "") !== "";
+
+ const { data: fresh } = useQuery({
+ queryKey: ["attachment-inline-resign", attachmentId],
+ queryFn: () => api.getAttachment(attachmentId as string),
+ enabled: needsResign,
+ staleTime: RESIGN_STALE_MS,
+ gcTime: RESIGN_STALE_MS,
+ });
+
+ if (!needsResign) return pickedUrl;
+ const dl = fresh?.download_url ?? "";
+ // Accept the fresh URL only when it is an actual upgrade — absolute and no
+ // longer the auth-gated API shape (i.e. a signed storage URL the renderer
+ // can load natively).
+ if (/^https?:\/\//i.test(dl) && attachmentIdFromDownloadURL(dl) === undefined) {
+ return dl;
+ }
+ return pickedUrl;
+}
+
// ---------------------------------------------------------------------------
// Dispatcher
// ---------------------------------------------------------------------------
@@ -298,10 +362,15 @@ export function Attachment({
}: AttachmentProps) {
const { resolveAttachment, openByUrl } = useAttachmentDownloadResolver();
const cdnDomain = useConfigStore((s) => s.cdnDomain);
+ const cdnSigned = useConfigStore((s) => s.cdnSigned);
const download = useDownloadAttachment();
const preview = useAttachmentPreview();
- const state = normalize(attachment, resolveAttachment, cdnDomain);
+ const state = normalize(attachment, resolveAttachment, cdnDomain, cdnSigned);
+ // The picked URL may still be the auth-gated API endpoint (reopened drafts
+ // whose persisted record has no signed download_url). Upgrade it to a
+ // freshly signed URL on clients that can't load the endpoint natively.
+ const mediaUrl = useResignedInlineMediaURL(state.attachmentId, state.url);
const forceKind =
attachment.kind === "url" ? attachment.forceKind : undefined;
const kind =
@@ -316,15 +385,15 @@ export function Attachment({
kind: "full",
attachment: {
...state.record,
- download_url: state.url || state.record.download_url,
+ download_url: mediaUrl || state.record.download_url,
},
});
return;
}
- if (state.url) {
+ if (mediaUrl) {
preview.tryOpen({
kind: "url",
- url: state.url,
+ url: mediaUrl,
filename: state.filename,
});
}
@@ -335,14 +404,14 @@ export function Attachment({
download(state.attachmentId);
return;
}
- if (state.url) openByUrl(state.url);
+ if (mediaUrl) openByUrl(mediaUrl);
};
if (kind === "image") {
return (
<>
<ImageAttachmentView
- src={state.url}
+ src={mediaUrl}
alt={state.filename}
uploading={state.uploading}
width={state.width}
@@ -380,7 +449,7 @@ export function Attachment({
filename={state.filename}
contentType={state.contentType}
attachmentId={state.attachmentId}
- href={state.url || undefined}
+ href={mediaUrl || undefined}
uploading={state.uploading}
onPreview={openPreview}
onDownload={handleDownload}
diff --git a/server/internal/handler/config.go b/server/internal/handler/config.go
index cda8e911a7..3eb2d509da 100644
--- a/server/internal/handler/config.go
+++ b/server/internal/handler/config.go
@@ -11,6 +11,14 @@ import (
type AppConfig struct {
CdnDomain string `json:"cdn_domain"`
+ // 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
+ // publicly fetchable — renderers must not pick it as a native
+ // <img>/<video> source and should fall back to the per-attachment
+ // API endpoint or a freshly signed download_url instead (MUL-3254).
+ // Omitted when false so older clients see the previous shape.
+ CdnSigned bool `json:"cdn_signed,omitempty"`
// Public auth config consumed by the web app at runtime so self-hosted
// deployments do not need to rebuild the frontend image when operators
// toggle signup or wire Google OAuth.
@@ -51,6 +59,7 @@ func (h *Handler) GetConfig(w http.ResponseWriter, r *http.Request) {
if h.Storage != nil {
config.CdnDomain = h.Storage.CdnDomain()
}
+ config.CdnSigned = h.CFSigner != nil
config.DaemonServerURL, config.DaemonAppURL = daemonSetupURLsFromEnv()
// Re-read from env on every request so operators can rotate keys via
diff --git a/server/internal/handler/config_test.go b/server/internal/handler/config_test.go
index 8189661947..f49e0ef7e6 100644
--- a/server/internal/handler/config_test.go
+++ b/server/internal/handler/config_test.go
@@ -5,8 +5,51 @@ import (
"net/http"
"net/http/httptest"
"testing"
+
+ "github.com/multica-ai/multica/server/internal/auth"
)
+func TestGetConfigReportsCdnSignedMode(t *testing.T) {
+ origStorage := testHandler.Storage
+ origSigner := testHandler.CFSigner
+ testHandler.Storage = &mockStorage{}
+ defer func() {
+ testHandler.Storage = origStorage
+ testHandler.CFSigner = origSigner
+ }()
+
+ fetch := func() AppConfig {
+ t.Helper()
+ req := httptest.NewRequest(http.MethodGet, "/api/config", nil)
+ w := httptest.NewRecorder()
+ testHandler.GetConfig(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("GetConfig: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ var cfg AppConfig
+ if err := json.Unmarshal(w.Body.Bytes(), &cfg); err != nil {
+ t.Fatalf("decode config: %v", err)
+ }
+ return cfg
+ }
+
+ testHandler.CFSigner = nil
+ if cfg := fetch(); cfg.CdnSigned {
+ t.Fatalf("cdn_signed: want false without a CloudFront signer, got true")
+ }
+
+ // With signing enabled the same cdn_domain serves private content via
+ // signed URLs only — clients must be told raw storage URLs won't load.
+ testHandler.CFSigner = &auth.CloudFrontSigner{}
+ cfg := fetch()
+ if !cfg.CdnSigned {
+ t.Fatalf("cdn_signed: want true with a CloudFront signer, got false")
+ }
+ if cfg.CdnDomain != "cdn.example.com" {
+ t.Fatalf("cdn_domain: want cdn.example.com alongside cdn_signed, got %q", cfg.CdnDomain)
+ }
+}
+
func TestGetConfigIncludesRuntimeAuthConfig(t *testing.T) {
origStorage := testHandler.Storage
testHandler.Storage = &mockStorage{}