Skip to content

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

Go

fix(attachments): unified download endpoint with mode + presign + proxy (MUL-2976) (#3747)

Multica Eveae27058b0a5f
diff --git a/.env.example b/.env.example
index bba3a558a2..c29a782c50 100644
--- a/.env.example
+++ b/.env.example
@@ -122,6 +122,13 @@ GOOGLE_CLIENT_SECRET=
# from S3_BUCKET + S3_REGION. S3_REGION must match the bucket's real region.
S3_BUCKET=
S3_REGION=us-west-2
+# AWS_ENDPOINT_URL — optional S3-compatible endpoint (MinIO, RustFS, R2, etc.).
+# For internal Docker/VPC hosts such as http://rustfs:9000, leave
+# ATTACHMENT_DOWNLOAD_MODE=auto or set proxy explicitly so browsers/CLI do
+# not need direct access to the object store.
+AWS_ENDPOINT_URL=
+ATTACHMENT_DOWNLOAD_MODE=auto
+ATTACHMENT_DOWNLOAD_URL_TTL=30m
CLOUDFRONT_KEY_PAIR_ID=
CLOUDFRONT_PRIVATE_KEY_SECRET=multica/cloudfront-signing-key
CLOUDFRONT_PRIVATE_KEY=
diff --git a/.github/workflows/mobile-verify.yml b/.github/workflows/mobile-verify.yml
index d435337df8..4734e487de 100644
--- a/.github/workflows/mobile-verify.yml
+++ b/.github/workflows/mobile-verify.yml
@@ -13,8 +13,9 @@ name: Mobile Verify
# - pnpm-workspace.yaml — catalog versions
# - turbo.json — turbo task pipeline
#
-# Mobile has no vitest suite today; if one lands, add `test` to the turbo
-# task list below.
+# Mobile's vitest suite is intentionally narrow (Node env, pure-function
+# tests under apps/mobile/lib/*.test.ts — see apps/mobile/vitest.config.ts).
+# RN component-level rendering is not exercised here.
on:
push:
@@ -61,5 +62,5 @@ jobs:
- name: Install dependencies
run: pnpm install
- - name: Type check and lint
- run: pnpm exec turbo typecheck lint --filter=@multica/mobile
+ - name: Type check, lint, and test
+ run: pnpm exec turbo typecheck lint test --filter=@multica/mobile
diff --git a/SELF_HOSTING_ADVANCED.md b/SELF_HOSTING_ADVANCED.md
index fe9112eb18..839463b1be 100644
--- a/SELF_HOSTING_ADVANCED.md
+++ b/SELF_HOSTING_ADVANCED.md
@@ -94,6 +94,8 @@ For file uploads and attachments, configure S3 and (optionally) CloudFront:
| `S3_REGION` | AWS region (default: `us-west-2`). Must match the bucket's actual region — used for both SDK signing and public URLs |
| `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY` | Static credentials. When both are unset, the AWS SDK default credential chain is used |
| `AWS_ENDPOINT_URL` | Custom S3-compatible endpoint (e.g. MinIO, R2, B2). Setting this switches to path-style URLs |
+| `ATTACHMENT_DOWNLOAD_MODE` | Attachment download behavior: `auto` (default), `cloudfront`, `presign`, or `proxy`. Use `proxy` for private buckets behind Docker/VPC-only endpoints such as `http://rustfs:9000` |
+| `ATTACHMENT_DOWNLOAD_URL_TTL` | TTL for CloudFront signed URLs and S3 presigned download URLs (default: `30m`) |
| `CLOUDFRONT_DOMAIN` | CloudFront distribution domain — when set, public URLs use this host instead of the S3 host |
| `CLOUDFRONT_KEY_PAIR_ID` | CloudFront key pair ID for signed URLs |
| `CLOUDFRONT_PRIVATE_KEY` | CloudFront private key (PEM format) |
diff --git a/apps/docs/content/docs/environment-variables.ja.mdx b/apps/docs/content/docs/environment-variables.ja.mdx
index 7f76209617..1efd12e17d 100644
--- a/apps/docs/content/docs/environment-variables.ja.mdx
+++ b/apps/docs/content/docs/environment-variables.ja.mdx
@@ -85,15 +85,19 @@ Multica はユーザーがアップロードした添付ファイル(コメン
| `S3_REGION` | `us-west-2` | AWS リージョン。バケットの実際のリージョンと一致する必要があります — SDK 署名と公開 URL の構築の両方に使われます |
| `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY` | 空 | 静的な認証情報。両方を設定しない場合は AWS SDK のデフォルト認証情報チェーン(IAM role / 環境認証情報)が使われます |
| `AWS_ENDPOINT_URL` | 空 | カスタムの S3 互換エンドポイント(例: [MinIO](https://min.io/))。これを設定すると path-style URL に切り替わります |
+| `ATTACHMENT_DOWNLOAD_MODE` | `auto` | 添付ファイルのダウンロード方式: `auto`、`cloudfront`、`presign`、`proxy`。`auto` では CloudFront が完全に設定されている場合は優先し、内部/プライベート endpoint host は server proxy、公開 S3 互換 endpoint は対応時に presigned GET を使います |
+| `ATTACHMENT_DOWNLOAD_URL_TTL` | `30m` | CloudFront signed URL と S3 presigned download URL の有効期間。Go duration 形式を受け付けます |
**`S3_BUCKET` を設定しない場合**: サーバーは起動時に `"S3_BUCKET not set, cloud upload disabled"` をログに記録し、すべてのアップロードはローカルディスクにフォールバックします。
-**公開 URL** は次の優先順位で構築されます。
+**保存されるオブジェクト URL** は次の優先順位で構築されます。
1. `CLOUDFRONT_DOMAIN` が設定されている場合は `https://<CLOUDFRONT_DOMAIN>/<key>`。
2. `AWS_ENDPOINT_URL` が設定されている場合は `<AWS_ENDPOINT_URL>/<S3_BUCKET>/<key>`(path-style)。
3. `https://<S3_BUCKET>.s3.<S3_REGION>.amazonaws.com/<key>`(virtual-hosted-style)。`S3_BUCKET` にドットが含まれる場合、AWS が発行するワイルドカード TLS 証明書がドットを含むバケットホストを検証できないため、サーバーは `https://s3.<S3_REGION>.amazonaws.com/<S3_BUCKET>/<key>`(path-style)にフォールバックします。
+API の `download_url` は、CloudFront 署名が設定されていない場合 `GET /api/attachments/{id}/download` を使います。この endpoint は安全な場合 CloudFront/S3 presigned URL にリダイレクトし、`http://rustfs:9000` のようなプライベート/内部 endpoint では server がストリーミングします。Docker/VPC 内部のオブジェクトストアでは `ATTACHMENT_DOWNLOAD_MODE=proxy` を明示できます。
+
### ローカルディスク(S3 が設定されていない場合)
| 変数 | デフォルト | 説明 |
diff --git a/apps/docs/content/docs/environment-variables.ko.mdx b/apps/docs/content/docs/environment-variables.ko.mdx
index 121691ee0b..973dab6ff3 100644
--- a/apps/docs/content/docs/environment-variables.ko.mdx
+++ b/apps/docs/content/docs/environment-variables.ko.mdx
@@ -85,15 +85,19 @@ Multica는 사용자가 업로드한 첨부 파일(댓글의 이미지와 파일
| `S3_REGION` | `us-west-2` | AWS 리전. 버킷의 실제 리전과 일치해야 합니다 — SDK 서명과 공개 URL 구성 모두에 사용됩니다 |
| `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY` | 비어 있음 | 정적 자격 증명. 둘 다 설정하지 않으면 AWS SDK 기본 자격 증명 체인(IAM role / 환경 자격 증명)이 사용됩니다 |
| `AWS_ENDPOINT_URL` | 비어 있음 | 사용자 정의 S3 호환 엔드포인트 (예: [MinIO](https://min.io/)). 이를 설정하면 path-style URL로 전환됩니다 |
+| `ATTACHMENT_DOWNLOAD_MODE` | `auto` | 첨부 파일 다운로드 방식: `auto`, `cloudfront`, `presign`, `proxy`. `auto`에서는 CloudFront가 완전히 설정되어 있으면 우선 사용하고, 내부/프라이빗 endpoint host는 server proxy를, 공개 S3 호환 endpoint는 지원되는 경우 presigned GET을 사용합니다 |
+| `ATTACHMENT_DOWNLOAD_URL_TTL` | `30m` | CloudFront signed URL 및 S3 presigned download URL의 유효 기간. Go duration 형식을 받습니다 |
**`S3_BUCKET`을 설정하지 않으면**: 서버는 시작 시 `"S3_BUCKET not set, cloud upload disabled"`를 로깅하고, 모든 업로드는 로컬 디스크로 폴백합니다.
-**공개 URL**은 다음 우선순위 순서로 구성됩니다:
+**저장된 객체 URL**은 다음 우선순위 순서로 구성됩니다:
1. `CLOUDFRONT_DOMAIN`이 설정된 경우 `https://<CLOUDFRONT_DOMAIN>/<key>`.
2. `AWS_ENDPOINT_URL`이 설정된 경우 `<AWS_ENDPOINT_URL>/<S3_BUCKET>/<key>` (path-style).
3. `https://<S3_BUCKET>.s3.<S3_REGION>.amazonaws.com/<key>` (virtual-hosted-style). `S3_BUCKET`에 점이 포함된 경우, AWS가 발급한 와일드카드 TLS 인증서가 점이 포함된 버킷 호스트를 검증하지 못하므로 서버는 `https://s3.<S3_REGION>.amazonaws.com/<S3_BUCKET>/<key>` (path-style)로 폴백합니다.
+API `download_url` 값은 CloudFront 서명이 설정되지 않은 경우 `GET /api/attachments/{id}/download`를 사용합니다. 이 endpoint는 안전한 경우 CloudFront/S3 presigned URL로 리디렉션하고, `http://rustfs:9000` 같은 프라이빗/내부 endpoint에서는 server가 스트리밍합니다. Docker/VPC 내부 객체 저장소에서는 `ATTACHMENT_DOWNLOAD_MODE=proxy`를 명시할 수 있습니다.
+
### 로컬 디스크 (S3가 설정되지 않은 경우)
| 변수 | 기본값 | 설명 |
diff --git a/apps/docs/content/docs/environment-variables.mdx b/apps/docs/content/docs/environment-variables.mdx
index 81ad98cebc..6f22985aa7 100644
--- a/apps/docs/content/docs/environment-variables.mdx
+++ b/apps/docs/content/docs/environment-variables.mdx
@@ -86,15 +86,19 @@ Multica stores user-uploaded attachments (images and files in comments). **S3 is
| `S3_REGION` | `us-west-2` | AWS region. Must match the bucket's actual region — it is used both for SDK signing and for building the public URL |
| `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY` | empty | Static credentials. When both are unset, the AWS SDK default credential chain is used (IAM role / environment credentials) |
| `AWS_ENDPOINT_URL` | empty | Custom S3-compatible endpoint (for example [MinIO](https://min.io/)). Setting this switches to path-style URLs |
+| `ATTACHMENT_DOWNLOAD_MODE` | `auto` | Attachment download path: `auto`, `cloudfront`, `presign`, or `proxy`. In `auto`, CloudFront is preferred when fully configured; internal/private endpoint hosts use the server proxy; public S3-compatible endpoints use presigned GET URLs when supported |
+| `ATTACHMENT_DOWNLOAD_URL_TTL` | `30m` | TTL for CloudFront signed URLs and S3 presigned download URLs. Accepts Go duration strings |
**When `S3_BUCKET` is unset**: the server logs `"S3_BUCKET not set, cloud upload disabled"` at startup, and all uploads fall back to local disk.
-**Public URLs** are constructed in this order of priority:
+**Stored object URLs** are constructed in this order of priority:
1. `https://<CLOUDFRONT_DOMAIN>/<key>` if `CLOUDFRONT_DOMAIN` is set.
2. `<AWS_ENDPOINT_URL>/<S3_BUCKET>/<key>` (path-style) if `AWS_ENDPOINT_URL` is set.
3. `https://<S3_BUCKET>.s3.<S3_REGION>.amazonaws.com/<key>` (virtual-hosted-style). When `S3_BUCKET` contains dots, the server falls back to `https://s3.<S3_REGION>.amazonaws.com/<S3_BUCKET>/<key>` (path-style) because the AWS-issued wildcard TLS certificate does not validate dotted bucket hosts.
+API `download_url` values use `GET /api/attachments/{id}/download` unless CloudFront signing is configured. The endpoint redirects to CloudFront/S3 presigned URLs when safe, or streams through the server for private/internal endpoints such as `http://rustfs:9000`. For Docker/VPC-only object stores, set `ATTACHMENT_DOWNLOAD_MODE=proxy` if auto detection is not conservative enough for your network.
+
### Local disk (when S3 is not configured)
| Variable | Default | Description |
diff --git a/apps/docs/content/docs/environment-variables.zh.mdx b/apps/docs/content/docs/environment-variables.zh.mdx
index 7f90c1719c..ca4bc989fa 100644
--- a/apps/docs/content/docs/environment-variables.zh.mdx
+++ b/apps/docs/content/docs/environment-variables.zh.mdx
@@ -86,15 +86,19 @@ Multica 存储用户上传的附件(评论里的图片、文件等)。**优
| `S3_REGION` | `us-west-2` | AWS 区域。必须和 bucket 所在区域一致——SDK 签名和公开 URL 都用它 |
| `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY` | 空 | 静态凭证。全未设时用 AWS SDK 默认凭证链(IAM role / 环境凭证)|
| `AWS_ENDPOINT_URL` | 空 | 自定义 S3 兼容端点(例如 [MinIO](https://min.io/))。设了会切到 path-style URL |
+| `ATTACHMENT_DOWNLOAD_MODE` | `auto` | 附件下载路径:`auto`、`cloudfront`、`presign` 或 `proxy`。`auto` 下 CloudFront 配完整时优先 CloudFront;内网/私有 endpoint host 走 server proxy;公网 S3 兼容 endpoint 在支持时走 presigned GET |
+| `ATTACHMENT_DOWNLOAD_URL_TTL` | `30m` | CloudFront signed URL 和 S3 presigned download URL 的有效期。使用 Go duration 格式 |
**`S3_BUCKET` 未设时**:server 启动时打 info 日志 `"S3_BUCKET not set, cloud upload disabled"`,所有上传回落到本地磁盘。
-**公开 URL** 按优先级拼装:
+**对象存储 URL** 按优先级拼装:
1. 设了 `CLOUDFRONT_DOMAIN` → `https://<CLOUDFRONT_DOMAIN>/<key>`
2. 设了 `AWS_ENDPOINT_URL` → `<AWS_ENDPOINT_URL>/<S3_BUCKET>/<key>`(path-style)
3. 默认走 AWS S3 → `https://<S3_BUCKET>.s3.<S3_REGION>.amazonaws.com/<key>`(virtual-hosted-style)。bucket 名含点时会回落到 `https://s3.<S3_REGION>.amazonaws.com/<S3_BUCKET>/<key>`(path-style),因为 AWS 通配证书无法覆盖含点 host。
+API 返回的 `download_url` 在未配置 CloudFront 签名时会指向 `GET /api/attachments/{id}/download`。这个端点会在安全时跳转到 CloudFront/S3 presigned URL;遇到 `http://rustfs:9000` 这类私有或内网 endpoint 时则由 server 流式转发。Docker/VPC 内部对象存储建议显式设置 `ATTACHMENT_DOWNLOAD_MODE=proxy`。
+
### 本地磁盘(S3 未配时)
| 环境变量 | 默认值 | 说明 |
diff --git a/apps/mobile/components/issue/comment-attachment-list.tsx b/apps/mobile/components/issue/comment-attachment-list.tsx
index c6348375da..f48b4b301c 100644
--- a/apps/mobile/components/issue/comment-attachment-list.tsx
+++ b/apps/mobile/components/issue/comment-attachment-list.tsx
@@ -26,6 +26,7 @@ import { Linking, Pressable, View } from "react-native";
import { Ionicons } from "@expo/vector-icons";
import type { Attachment } from "@multica/core/types";
import { MarkdownImage } from "@/lib/markdown/markdown-image";
+import { resolveAttachmentUrl } from "@/lib/attachment-url";
import { useColorScheme } from "@/lib/use-color-scheme";
import { THEME } from "@/lib/theme";
import { Text } from "@/components/ui/text";
@@ -108,12 +109,19 @@ function FileCard({
return (
<Pressable
onPress={() => {
- // download_url is the signed HTTPS link; opening it hands off to
+ // download_url is the canonical link — opening it hands off to
// Safari which handles auth-token-free download + previewing for
// common types (PDF, txt). Mirrors what the markdown link renderer
// does for `[name](url)`.
- if (attachment.download_url) {
- void Linking.openURL(attachment.download_url);
+ //
+ // The backend may return a server-relative URL like
+ // `/api/attachments/{id}/download` when no CloudFront signer is
+ // configured (MUL-2976). RN's `Linking.openURL` requires an
+ // absolute http(s) URL — it returns "Cannot open URL" otherwise —
+ // so resolve against `EXPO_PUBLIC_API_URL` first.
+ const target = resolveAttachmentUrl(attachment.download_url);
+ if (target) {
+ void Linking.openURL(target);
}
}}
accessibilityRole="button"
diff --git a/apps/mobile/components/issue/composer-attachment-row.tsx b/apps/mobile/components/issue/composer-attachment-row.tsx
index fef825546e..f7a016dba8 100644
--- a/apps/mobile/components/issue/composer-attachment-row.tsx
+++ b/apps/mobile/components/issue/composer-attachment-row.tsx
@@ -28,6 +28,7 @@
import { useMemo } from "react";
import { ActivityIndicator, Linking, Pressable, ScrollView, View } from "react-native";
import { Ionicons } from "@expo/vector-icons";
+import { resolveAttachmentUrl } from "@/lib/attachment-url";
import { useLightbox } from "@/lib/markdown/lightbox-provider";
import { useColorScheme } from "@/lib/use-color-scheme";
import { THEME } from "@/lib/theme";
@@ -193,8 +194,17 @@ function AttachmentChipView({ item, onRemove, onRetry }: AttachmentChipProps) {
// Prefer the local on-device file over the network URL — instant,
// no signed-URL round-trip, works the same pre/post upload.
open(item.localUri);
- } else if (item.downloadUrl) {
- void Linking.openURL(item.downloadUrl);
+ } else {
+ // Non-image file chip: open the canonical download URL in Safari.
+ // `downloadUrl` comes from `api.uploadFile(...).download_url`, which
+ // on non-CloudFront deployments is a server-relative path like
+ // `/api/attachments/{id}/download` (MUL-2976). RN's `Linking.openURL`
+ // requires an absolute http(s) URL — `Cannot open URL` otherwise — so
+ // resolve against `EXPO_PUBLIC_API_URL` first. Already-absolute
+ // CloudFront/presigned URLs pass through unchanged. `null` (no
+ // downloadUrl yet) falls through to a no-op.
+ const target = resolveAttachmentUrl(item.downloadUrl);
+ if (target) void Linking.openURL(target);
}
};
diff --git a/apps/mobile/lib/attachment-url.test.ts b/apps/mobile/lib/attachment-url.test.ts
new file mode 100644
index 0000000000..b8d2082c97
--- /dev/null
+++ b/apps/mobile/lib/attachment-url.test.ts
@@ -0,0 +1,125 @@
+/**
+ * Pure-function tests for the mobile attachment URL resolver. We exercise
+ * the with-base form because `resolveAttachmentUrl` itself is bound at
+ * module load to `process.env.EXPO_PUBLIC_API_URL`, which is what we
+ * intentionally don't want to mutate in tests — the with-base helper is
+ * the same code path with the API base passed in explicitly.
+ *
+ * Coverage target: every branch the call sites in the app rely on —
+ * - `comment-attachment-list.tsx` → file chip Linking.openURL
+ * - `markdown-image.tsx` → mc:// + RN image loader
+ * - `composer-attachment-row.tsx` → completed non-image chip
+ * tap → Linking.openURL
+ */
+import { describe, expect, it } from "vitest";
+import {
+ resolveAttachmentUrl,
+ resolveAttachmentUrlWithBase,
+} from "./attachment-url";
+
+describe("resolveAttachmentUrlWithBase", () => {
+ const BASE = "https://api.example.test";
+
+ it("prepends the API base for a server-relative path", () => {
+ expect(
+ resolveAttachmentUrlWithBase("/api/attachments/att-1/download", BASE),
+ ).toBe("https://api.example.test/api/attachments/att-1/download");
+ });
+
+ it("trims a trailing slash on the API base before joining", () => {
+ expect(
+ resolveAttachmentUrlWithBase(
+ "/api/attachments/att-1/download",
+ "https://api.example.test/",
+ ),
+ ).toBe("https://api.example.test/api/attachments/att-1/download");
+ });
+
+ it("passes an absolute https URL through unchanged (CloudFront / presigned)", () => {
+ const signed =
+ "https://cdn.example.test/att-1.bin?Policy=p&Signature=s&Key-Pair-Id=k";
+ expect(resolveAttachmentUrlWithBase(signed, BASE)).toBe(signed);
+ });
+
+ it("passes an absolute http URL through unchanged (self-hosted dev)", () => {
+ expect(
+ resolveAttachmentUrlWithBase("http://localhost:8080/file.bin", BASE),
+ ).toBe("http://localhost:8080/file.bin");
+ });
+
+ it("returns null for nullish or empty input", () => {
+ expect(resolveAttachmentUrlWithBase(null, BASE)).toBeNull();
+ expect(resolveAttachmentUrlWithBase(undefined, BASE)).toBeNull();
+ expect(resolveAttachmentUrlWithBase("", BASE)).toBeNull();
+ });
+
+ it("keeps a relative path unchanged when the base is empty (web same-origin convention)", () => {
+ // Mirrors `packages/core/workspace/avatar-url.ts` semantics for the
+ // empty-base case — the host platform resolves the path against its
+ // own document/page origin. RN doesn't have one, but exercising this
+ // branch keeps the contract explicit.
+ expect(
+ resolveAttachmentUrlWithBase("/api/attachments/att-1/download", ""),
+ ).toBe("/api/attachments/att-1/download");
+ });
+});
+
+describe("composer file chip — completed non-image attachment", () => {
+ // MUL-2976 (PR #3747 follow-up): when `api.uploadFile(...)` finishes on
+ // a non-CloudFront deployment the returned `attachment.download_url` is
+ // a server-relative path. `composer-attachment-row.tsx` taps that value
+ // straight into `Linking.openURL` — and iOS rejects relative URLs with
+ // "Cannot open URL". The fix wraps the value with `resolveAttachmentUrl`
+ // before handing it to Linking; this test pins the behaviour we rely on.
+ const BASE = "https://api.example.test";
+ // Mirrors `ComposerAttachmentItem` after a successful non-image upload.
+ const completedFileChip = {
+ localId: "local-1",
+ localUri: "file:///private/var/.../IMG_0001.pdf",
+ filename: "report.pdf",
+ mimeType: "application/pdf",
+ status: "completed" as const,
+ id: "att-42",
+ url: "mc://file/att-42",
+ downloadUrl: "/api/attachments/att-42/download",
+ };
+
+ it("resolves a server-relative downloadUrl against the API base", () => {
+ expect(
+ resolveAttachmentUrlWithBase(completedFileChip.downloadUrl, BASE),
+ ).toBe("https://api.example.test/api/attachments/att-42/download");
+ });
+
+ it("preserves an absolute downloadUrl returned by CloudFront / presign", () => {
+ const cloudFront = {
+ ...completedFileChip,
+ downloadUrl:
+ "https://cdn.example.test/att-42.pdf?Signature=s&Key-Pair-Id=k",
+ };
+ expect(
+ resolveAttachmentUrlWithBase(cloudFront.downloadUrl, BASE),
+ ).toBe(cloudFront.downloadUrl);
+ });
+
+ it("returns null when the upload hasn't populated downloadUrl yet (no Linking call)", () => {
+ // Mirrors a `completed` chip that arrived before the server response
+ // (defensive; in practice `completed` implies downloadUrl is set).
+ const partial = { ...completedFileChip, downloadUrl: undefined };
+ expect(resolveAttachmentUrlWithBase(partial.downloadUrl, BASE)).toBeNull();
+ });
+});
+
+describe("resolveAttachmentUrl (env-bound)", () => {
+ it("matches the with-base form for an absolute URL regardless of EXPO_PUBLIC_API_URL", () => {
+ // The bound form is module-evaluation-time, but for absolute URLs the
+ // base is irrelevant — guarantees pass-through stays stable.
+ const absolute = "https://cdn.example.test/file.pdf?Signature=s";
+ expect(resolveAttachmentUrl(absolute)).toBe(absolute);
+ });
+
+ it("returns null for empty input", () => {
+ expect(resolveAttachmentUrl(undefined)).toBeNull();
+ expect(resolveAttachmentUrl(null)).toBeNull();
+ expect(resolveAttachmentUrl("")).toBeNull();
+ });
+});
diff --git a/apps/mobile/lib/attachment-url.ts b/apps/mobile/lib/attachment-url.ts
new file mode 100644
index 0000000000..c22f33fade
--- /dev/null
+++ b/apps/mobile/lib/attachment-url.ts
@@ -0,0 +1,44 @@
+/**
+ * Resolve a server-relative attachment URL against the configured API base.
+ *
+ * Background: when the backend has no CloudFront signer configured (e.g.
+ * the self-hosted RustFS / private-S3 case in MUL-2976), `attachment.url`
+ * and `attachment.download_url` come back as server-relative paths like
+ * `/api/attachments/{id}/download`. Web is happy with that — same-origin
+ * `<img src="/api/...">` resolves against the document base — but RN
+ * needs an absolute http(s) URL for both `Linking.openURL` (`Cannot open
+ * URL` otherwise) and `<Image source={{ uri }}>` (no document origin to
+ * resolve against; the request is silently dropped).
+ *
+ * Mirrors `packages/core/workspace/avatar-url.ts:resolvePublicFileUrl`
+ * exactly. We don't import the core helper because its `getBaseUrl()`
+ * pulls from a singleton ApiClient that lives in `@multica/core/api` —
+ * not on the mobile sharing whitelist (apps/mobile/CLAUDE.md "mirror,
+ * don't import"). Mobile reads its own `EXPO_PUBLIC_API_URL` from the
+ * Expo env, the same value the rest of `data/api.ts` uses.
+ *
+ * Contract:
+ * - null / undefined / "" → null (caller should treat as "no URL").
+ * - already-absolute URL → returned unchanged.
+ * - server-relative path → API base + path, with a single boundary
+ * slash (we trim trailing slashes from the
+ * base before joining).
+ */
+
+const API_URL = process.env.EXPO_PUBLIC_API_URL ?? "";
+
+export function resolveAttachmentUrlWithBase(
+ rawUrl: string | null | undefined,
+ baseUrl: string,
+): string | null {
+ if (!rawUrl) return null;
+ if (!rawUrl.startsWith("/")) return rawUrl;
+ const trimmedBaseUrl = baseUrl.replace(/\/+$/, "");
+ return `${trimmedBaseUrl}${rawUrl}`;
+}
+
+export function resolveAttachmentUrl(
+ rawUrl: string | null | undefined,
+): string | null {
+ return resolveAttachmentUrlWithBase(rawUrl, API_URL);
+}
diff --git a/apps/mobile/lib/markdown/markdown-image.tsx b/apps/mobile/lib/markdown/markdown-image.tsx
index abdf3ab075..c13746781b 100644
--- a/apps/mobile/lib/markdown/markdown-image.tsx
+++ b/apps/mobile/lib/markdown/markdown-image.tsx
@@ -28,6 +28,7 @@ import { useEffect, useMemo, useState } from "react";
import { Image as RNImage, Pressable, View } from "react-native";
import { Image as ExpoImage } from "expo-image";
import type { Attachment } from "@multica/core/types";
+import { resolveAttachmentUrl } from "@/lib/attachment-url";
import { useLightbox } from "./lightbox-provider";
interface Props {
@@ -41,9 +42,21 @@ export function MarkdownImage({ uri, attachments }: Props) {
const [aspect, setAspect] = useState<number | null>(null);
const resolvedUri = useMemo(() => {
- if (!attachments || attachments.length === 0) return uri;
- const match = attachments.find((a) => a.url === uri);
- return match?.download_url || uri;
+ // mc://file/<id> → look up the matching attachment's download_url.
+ // No match (external link, html https URL, or unresolved mc://) falls
+ // through to the original uri.
+ let candidate: string | null | undefined = uri;
+ if (attachments && attachments.length > 0) {
+ const match = attachments.find((a) => a.url === uri);
+ if (match?.download_url) candidate = match.download_url;
+ }
+ // The backend may return a server-relative `download_url` (e.g.
+ // `/api/attachments/{id}/download`) when no CloudFront signer is
+ // configured — see MUL-2976. RN's image loader has no document
+ // origin to resolve against, so prepend `EXPO_PUBLIC_API_URL` for
+ // server-relative paths and let absolute URLs / external links pass
+ // through unchanged.
+ return resolveAttachmentUrl(candidate) ?? uri;
}, [uri, attachments]);
useEffect(() => {
diff --git a/apps/mobile/package.json b/apps/mobile/package.json
index cf55c7a55d..d016068b26 100644
--- a/apps/mobile/package.json
+++ b/apps/mobile/package.json
@@ -16,7 +16,8 @@
"ios:device:prod": "dotenv -e .env.production -- cross-env APP_ENV=production expo run:ios --device",
"ios:device:prod:release": "dotenv -e .env.production -- cross-env APP_ENV=production expo run:ios --device --configuration Release",
"lint": "expo lint",
- "typecheck": "tsc --noEmit"
+ "typecheck": "tsc --noEmit",
+ "test": "vitest run"
},
"dependencies": {
"@expo/vector-icons": "^14.1.0",
@@ -86,6 +87,7 @@
"cross-env": "^7.0.3",
"dotenv-cli": "^7.4.4",
"eslint-config-expo": "~55.0.0",
- "typescript": "~5.9.0"
+ "typescript": "~5.9.0",
+ "vitest": "catalog:"
}
}
diff --git a/apps/mobile/vitest.config.ts b/apps/mobile/vitest.config.ts
new file mode 100644
index 0000000000..72e19422fb
--- /dev/null
+++ b/apps/mobile/vitest.config.ts
@@ -0,0 +1,19 @@
+import { defineConfig } from "vitest/config";
+
+// Mobile vitest is intentionally minimal — Node environment only, scoped to
+// pure-function tests in `lib/`. We don't ship jsdom or RN test renderers
+// here because the app runs on Hermes / native shims and any DOM-shaped
+// runner would be a lie. Tests that need RN component rendering would
+// need a separate jest+react-native-testing-library track; for now we
+// keep this lane for helpers and serializers only.
+//
+// Co-located test files (foo.ts + foo.test.ts) match how the rest of the
+// monorepo organises vitest suites.
+export default defineConfig({
+ test: {
+ environment: "node",
+ globals: true,
+ include: ["lib/**/*.test.ts"],
+ passWithNoTests: true,
+ },
+});
diff --git a/docker-compose.selfhost.yml b/docker-compose.selfhost.yml
index 2177a84bef..f4567f0309 100644
--- a/docker-compose.selfhost.yml
+++ b/docker-compose.selfhost.yml
@@ -64,6 +64,9 @@ services:
GOOGLE_REDIRECT_URI: ${GOOGLE_REDIRECT_URI:-http://localhost:${FRONTEND_PORT:-3000}/auth/callback}
S3_BUCKET: ${S3_BUCKET:-}
S3_REGION: ${S3_REGION:-us-west-2}
+ AWS_ENDPOINT_URL: ${AWS_ENDPOINT_URL:-}
+ ATTACHMENT_DOWNLOAD_MODE: ${ATTACHMENT_DOWNLOAD_MODE:-auto}
+ ATTACHMENT_DOWNLOAD_URL_TTL: ${ATTACHMENT_DOWNLOAD_URL_TTL:-30m}
CLOUDFRONT_DOMAIN: ${CLOUDFRONT_DOMAIN:-}
CLOUDFRONT_KEY_PAIR_ID: ${CLOUDFRONT_KEY_PAIR_ID:-}
CLOUDFRONT_PRIVATE_KEY: ${CLOUDFRONT_PRIVATE_KEY:-}
diff --git a/packages/views/editor/attachment-preview-modal.test.tsx b/packages/views/editor/attachment-preview-modal.test.tsx
index 43ffd99177..4a87ec692e 100644
--- a/packages/views/editor/attachment-preview-modal.test.tsx
+++ b/packages/views/editor/attachment-preview-modal.test.tsx
@@ -17,6 +17,7 @@ vi.mock("../platform", () => ({
const {
getAttachmentTextContentMock,
downloadMock,
+ getBaseUrlMock,
FakePreviewTooLargeError,
FakePreviewUnsupportedError,
} = vi.hoisted(() => {
@@ -35,13 +36,19 @@ const {
return {
getAttachmentTextContentMock: vi.fn(),
downloadMock: vi.fn(),
+ // Default to the web shape (empty base, same-origin). Tests covering
+ // the desktop-renderer / standalone-shell case override per-test.
+ getBaseUrlMock: vi.fn(() => ""),
FakePreviewTooLargeError,
FakePreviewUnsupportedError,
};
});
vi.mock("@multica/core/api", () => ({
- api: { getAttachmentTextContent: getAttachmentTextContentMock },
+ api: {
+ getAttachmentTextContent: getAttachmentTextContentMock,
+ getBaseUrl: getBaseUrlMock,
+ },
PreviewTooLargeError: FakePreviewTooLargeError,
PreviewUnsupportedError: FakePreviewUnsupportedError,
}));
@@ -147,6 +154,9 @@ beforeEach(() => {
vi.clearAllMocks();
navState.hasOpenInNewTab = true;
slugState.value = "acme";
+ // Default to web's same-origin empty base so existing absolute-URL tests
+ // remain unaffected by the relative-URL resolution added in normalize().
+ getBaseUrlMock.mockReturnValue("");
});
afterEach(() => {
@@ -260,6 +270,113 @@ describe("AttachmentPreviewModal — dispatch", () => {
});
});
+describe("AttachmentPreviewModal — server-relative download_url resolution (MUL-2976)", () => {
+ // The unified `/api/attachments/{id}/download` endpoint returns a
+ // server-relative path on non-CloudFront deployments. The web app keeps
+ // working same-origin because `apiBaseUrl=""`, but the desktop renderer
+ // is loaded from `app://` / file: / dev-server origin and needs the
+ // absolute URL — otherwise `<img src>`, `<iframe src>`, `<video src>`
+ // hit the shell origin and fail.
+ it("prefixes the configured API base for image previews when download_url is server-relative", () => {
+ getBaseUrlMock.mockReturnValue("https://api.example.test");
+ const att = makeAttachment({
+ filename: "shot.png",
+ content_type: "image/png",
+ download_url: "/api/attachments/att-1/download",
+ });
+ render(
+ <AttachmentPreviewModal
+ source={{ kind: "full", attachment: att }}
+ open
+ onClose={() => {}}
+ />,
+ );
+ const img = document.querySelector("img");
+ expect(img?.getAttribute("src")).toBe(
+ "https://api.example.test/api/attachments/att-1/download",
+ );
+ });
+
+ it("prefixes the configured API base for PDF previews when download_url is server-relative", () => {
+ getBaseUrlMock.mockReturnValue("https://api.example.test");
+ const att = makeAttachment({
+ filename: "manual.pdf",
+ content_type: "application/pdf",
+ download_url: "/api/attachments/att-1/download",
+ });
+ render(
+ <AttachmentPreviewModal
+ source={{ kind: "full", attachment: att }}
+ open
+ onClose={() => {}}
+ />,
+ );
+ const iframe = document.querySelector("iframe");
+ expect(iframe?.getAttribute("src")).toBe(
+ "https://api.example.test/api/attachments/att-1/download",
+ );
+ });
+
+ it("keeps a same-origin relative URL untouched when the configured base is empty (web)", () => {
+ // Default web shape — empty base. Browser resolves the relative path
+ // against the document origin, no prefix needed.
+ const att = makeAttachment({
+ filename: "shot.png",
+ content_type: "image/png",
+ download_url: "/api/attachments/att-1/download",
+ });
+ render(
+ <AttachmentPreviewModal
+ source={{ kind: "full", attachment: att }}
+ open
+ onClose={() => {}}
+ />,
+ );
+ const img = document.querySelector("img");
+ expect(img?.getAttribute("src")).toBe("/api/attachments/att-1/download");
+ });
+
+ it("trims a trailing slash on the configured base when joining a relative URL", () => {
+ getBaseUrlMock.mockReturnValue("https://api.example.test/");
+ const att = makeAttachment({
+ filename: "shot.png",
+ content_type: "image/png",
+ download_url: "/api/attachments/att-1/download",
+ });
+ render(
+ <AttachmentPreviewModal
+ source={{ kind: "full", attachment: att }}
+ open
+ onClose={() => {}}
+ />,
+ );
+ const img = document.querySelector("img");
+ expect(img?.getAttribute("src")).toBe(
+ "https://api.example.test/api/attachments/att-1/download",
+ );
+ });
+
+ it("passes an already-absolute CloudFront/presigned download_url through unchanged", () => {
+ getBaseUrlMock.mockReturnValue("https://api.example.test");
+ const att = makeAttachment({
+ filename: "shot.png",
+ content_type: "image/png",
+ download_url: "https://cdn.example.test/att-1.png?Signature=s",
+ });
+ render(
+ <AttachmentPreviewModal
+ source={{ kind: "full", attachment: att }}
+ open
+ onClose={() => {}}
+ />,
+ );
+ const img = document.querySelector("img");
+ expect(img?.getAttribute("src")).toBe(
+ "https://cdn.example.test/att-1.png?Signature=s",
+ );
+ });
+});
+
describe("AttachmentPreviewModal — error states", () => {
it("shows the too-large fallback on PreviewTooLargeError", async () => {
getAttachmentTextContentMock.mockRejectedValueOnce(new FakePreviewTooLargeError());
diff --git a/packages/views/editor/attachment-preview-modal.tsx b/packages/views/editor/attachment-preview-modal.tsx
index f1a18e7ccf..f304e4bbf9 100644
--- a/packages/views/editor/attachment-preview-modal.tsx
+++ b/packages/views/editor/attachment-preview-modal.tsx
@@ -45,6 +45,7 @@ import {
import { Download, ExternalLink, FileText, Loader2, X } from "lucide-react";
import type { Attachment } from "@multica/core/types";
import { paths, useWorkspaceSlug } from "@multica/core/paths";
+import { resolvePublicFileUrl } from "@multica/core/workspace/avatar-url";
import { useT } from "../i18n";
import { useNavigation } from "../navigation";
import { openExternal } from "../platform";
@@ -92,18 +93,29 @@ interface PreviewState {
}
function normalize(source: PreviewSource): PreviewState {
+ // Resolve any server-relative URL (e.g. `/api/attachments/{id}/download`
+ // returned by the unified-endpoint metadata path when no CloudFront
+ // signer is configured) against the configured API base. Web with the
+ // default empty base keeps the relative path and resolves it against
+ // the page origin — same behaviour as before this PR. Desktop renderer
+ // (loaded from `app://` / file: / dev-server origin) needs the absolute
+ // form so `<img src>` / `<iframe src>` / `<video src>` actually point at
+ // the API server instead of the shell origin.
if (source.kind === "full") {
+ const mediaUrl =
+ resolvePublicFileUrl(source.attachment.download_url) ??
+ source.attachment.download_url;
return {
filename: source.attachment.filename,
contentType: source.attachment.content_type,
- mediaUrl: source.attachment.download_url,
+ mediaUrl,
attachmentId: source.attachment.id,
};
}
return {
filename: source.filename,
contentType: "",
- mediaUrl: source.url,
+ mediaUrl: resolvePublicFileUrl(source.url) ?? source.url,
attachmentId: null,
};
}
diff --git a/packages/views/editor/use-download-attachment.test.tsx b/packages/views/editor/use-download-attachment.test.tsx
index 4ac5e828f9..649ecb781c 100644
--- a/packages/views/editor/use-download-attachment.test.tsx
+++ b/packages/views/editor/use-download-attachment.test.tsx
@@ -4,9 +4,10 @@ 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 getBaseUrlMock = vi.hoisted(() => vi.fn(() => ""));
vi.mock("@multica/core/api", () => ({
- api: { getAttachment: getAttachmentMock },
+ api: { getAttachment: getAttachmentMock, getBaseUrl: getBaseUrlMock },
}));
vi.mock("sonner", () => ({
@@ -25,6 +26,10 @@ const SIGNED_URL =
beforeEach(() => {
vi.clearAllMocks();
+ // Default: web with same-origin API (empty base). Each test that needs
+ // a non-empty base (desktop standalone, server-relative download URL)
+ // overrides via getBaseUrlMock.mockReturnValue(...).
+ getBaseUrlMock.mockReturnValue("");
});
afterEach(() => {
@@ -118,4 +123,81 @@ describe("useDownloadAttachment (desktop)", () => {
expect(downloadURL).not.toHaveBeenCalled();
await waitFor(() => expect(toast.error).toHaveBeenCalled());
});
+
+ // MUL-2976: when the backend has no CloudFront signer, `getAttachment`
+ // returns a server-relative `download_url` like `/api/attachments/.../download`.
+ // The Electron main-process `downloadURLSafely` requires a parsable
+ // http(s) URL or it drops the request — so the renderer must resolve
+ // the path against the configured API base before crossing the bridge.
+ it("resolves a server-relative download_url against the API base before handing it to the desktop bridge", async () => {
+ const downloadURL = vi.fn();
+ (window as unknown as { desktopAPI: { downloadURL: typeof downloadURL } }).desktopAPI = {
+ downloadURL,
+ };
+ getBaseUrlMock.mockReturnValue("https://api.example.test");
+ getAttachmentMock.mockResolvedValueOnce({
+ id: "att-1",
+ url: "https://static.example.test/file.md",
+ download_url: "/api/attachments/att-1/download",
+ filename: "file.md",
+ });
+
+ const { result } = renderHook(() => useDownloadAttachment());
+
+ await act(async () => {
+ await result.current("att-1");
+ });
+
+ expect(downloadURL).toHaveBeenCalledWith(
+ "https://api.example.test/api/attachments/att-1/download",
+ );
+ });
+
+ it("trims a trailing slash on the API base when resolving a relative download_url", async () => {
+ const downloadURL = vi.fn();
+ (window as unknown as { desktopAPI: { downloadURL: typeof downloadURL } }).desktopAPI = {
+ downloadURL,
+ };
+ getBaseUrlMock.mockReturnValue("https://api.example.test/");
+ getAttachmentMock.mockResolvedValueOnce({
+ id: "att-1",
+ url: "/api/attachments/att-1/content",
+ download_url: "/api/attachments/att-1/download",
+ filename: "file.md",
+ });
+
+ const { result } = renderHook(() => useDownloadAttachment());
+
+ await act(async () => {
+ await result.current("att-1");
+ });
+
+ expect(downloadURL).toHaveBeenCalledWith(
+ "https://api.example.test/api/attachments/att-1/download",
+ );
+ });
+
+ it("passes an already-absolute download_url through unchanged when the bridge is present", async () => {
+ const downloadURL = vi.fn();
+ (window as unknown as { desktopAPI: { downloadURL: typeof downloadURL } }).desktopAPI = {
+ downloadURL,
+ };
+ // Even with a non-empty base configured, a CloudFront signed URL
+ // must not be re-prefixed.
+ getBaseUrlMock.mockReturnValue("https://api.example.test");
+ getAttachmentMock.mockResolvedValueOnce({
+ id: "att-1",
+ url: "https://cdn.example.test/att-1.bin",
+ download_url: SIGNED_URL,
+ filename: "file.md",
+ });
+
+ const { result } = renderHook(() => useDownloadAttachment());
+
+ await act(async () => {
+ await result.current("att-1");
+ });
+
+ expect(downloadURL).toHaveBeenCalledWith(SIGNED_URL);
+ });
});
diff --git a/packages/views/editor/use-download-attachment.ts b/packages/views/editor/use-download-attachment.ts
index c2dea633f0..b82f34877d 100644
--- a/packages/views/editor/use-download-attachment.ts
+++ b/packages/views/editor/use-download-attachment.ts
@@ -3,6 +3,7 @@
import { useCallback } from "react";
import { toast } from "sonner";
import { api } from "@multica/core/api";
+import { resolvePublicFileUrl } from "@multica/core/workspace/avatar-url";
import { useT } from "../i18n";
interface DesktopBridge {
@@ -49,14 +50,23 @@ export function useDownloadAttachment(): (attachmentId: string) => Promise<void>
if (hasDesktopDownloadBridge()) {
try {
const fresh = await api.getAttachment(attachmentId);
- if (!fresh.download_url) {
+ // 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);
+ if (!downloadUrl) {
failed();
return;
}
const bridge = (
window as unknown as { desktopAPI?: DesktopBridge }
).desktopAPI;
- await bridge!.downloadURL!(fresh.download_url);
+ await bridge!.downloadURL!(downloadUrl);
} catch {
failed();
}
@@ -72,17 +82,26 @@ export function useDownloadAttachment(): (attachmentId: string) => Promise<void>
: null;
try {
const fresh = await api.getAttachment(attachmentId);
- if (!fresh.download_url) {
+ // Same relative-URL handling as desktop above. For web the
+ // `apiBaseUrl` is typically empty (same-origin), so `resolvePublicFileUrl`
+ // returns the path unchanged and the browser resolves it against
+ // the page's origin — the existing same-origin behaviour. When a
+ // non-empty base is configured (e.g. tauri/standalone shells that
+ // bundle the SPA but talk to a remote API), the resolver yields an
+ // absolute URL, which works for both `placeholder.location.href`
+ // and the last-resort `window.location.href` redirect.
+ const downloadUrl = resolvePublicFileUrl(fresh.download_url);
+ if (!downloadUrl) {
placeholder?.close();
failed();
return;
}
if (placeholder) {
placeholder.opener = null;
- placeholder.location.href = fresh.download_url;
+ placeholder.location.href = downloadUrl;
} else if (typeof window !== "undefined") {
// Popup blocked outright — last-resort navigate the current tab.
- window.location.href = fresh.download_url;
+ window.location.href = downloadUrl;
}
} catch {
placeholder?.close();
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 1e92f7a84a..94f64fe8ac 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -514,6 +514,9 @@ importers:
typescript:
specifier: ~5.9.0
version: 5.9.3
+ vitest:
+ specifier: 'catalog:'
apps/web:
dependencies:
@@ -727,7 +730,7 @@ importers:
version: 5.9.3
vitest:
specifier: 'catalog:'
packages/core:
dependencies:
@@ -14900,6 +14903,15 @@ snapshots:
chai: 6.2.2
tinyrainbow: 3.1.0
+ dependencies:
+ '@vitest/spy': 4.1.0
+ estree-walker: 3.0.3
+ magic-string: 0.30.21
+ optionalDependencies:
+ msw: 2.12.14(@types/[email protected])([email protected])
+
dependencies:
'@vitest/spy': 4.1.0
@@ -22155,6 +22167,23 @@ snapshots:
d3-time: 3.1.0
d3-timer: 3.0.1
+ dependencies:
+ lightningcss: 1.32.0
+ picomatch: 4.0.3
+ postcss: 8.5.8
+ rolldown: 1.0.0-rc.10(@emnapi/[email protected])(@emnapi/[email protected])
+ tinyglobby: 0.2.15
+ optionalDependencies:
+ '@types/node': 25.5.0
+ fsevents: 2.3.3
+ jiti: 1.21.7
+ terser: 5.47.1
+ yaml: 2.9.0
+ transitivePeerDependencies:
+ - '@emnapi/core'
+ - '@emnapi/runtime'
+
dependencies:
lightningcss: 1.32.0
@@ -22172,6 +22201,35 @@ snapshots:
- '@emnapi/core'
- '@emnapi/runtime'
+ dependencies:
+ '@vitest/expect': 4.1.0
+ '@vitest/pretty-format': 4.1.0
+ '@vitest/runner': 4.1.0
+ '@vitest/snapshot': 4.1.0
+ '@vitest/spy': 4.1.0
+ '@vitest/utils': 4.1.0
+ es-module-lexer: 2.0.0
+ expect-type: 1.3.0
+ magic-string: 0.30.21
+ obug: 2.1.1
+ pathe: 2.0.3
+ picomatch: 4.0.3
+ std-env: 4.0.0
+ tinybench: 2.9.0
+ tinyexec: 1.0.4
+ tinyglobby: 0.2.15
+ tinyrainbow: 3.1.0
+ why-is-node-running: 2.3.0
+ optionalDependencies:
+ '@opentelemetry/api': 1.9.1
+ '@types/node': 25.5.0
+ jsdom: 29.0.1(@noble/[email protected])
+ transitivePeerDependencies:
+ - msw
+
dependencies:
'@vitest/expect': 4.1.0
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 9b755de988..2a07b552e4 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -151,6 +151,8 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
TrustedProxies: parseTrustedProxies(os.Getenv("MULTICA_TRUSTED_PROXIES")),
CloudRuntimeFleetURL: cloudRuntimeFleetURLFromEnv(),
CloudRuntimeFleetTimeout: envDuration("MULTICA_CLOUD_FLEET_TIMEOUT", 35*time.Second),
+ AttachmentDownloadMode: os.Getenv("ATTACHMENT_DOWNLOAD_MODE"),
+ AttachmentDownloadURLTTL: envDuration("ATTACHMENT_DOWNLOAD_URL_TTL", 30*time.Minute),
}
h := handler.New(queries, pool, hub, bus, emailSvc, store, cfSigner, analyticsClient, signupConfig, daemonHub)
h.Metrics = opts.BusinessMetrics
@@ -766,6 +768,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
// Attachments
r.Get("/api/attachments/{id}", h.GetAttachmentByID)
+ r.Get("/api/attachments/{id}/download", h.DownloadAttachment)
r.Get("/api/attachments/{id}/content", h.GetAttachmentContent)
r.Delete("/api/attachments/{id}", h.DeleteAttachment)
diff --git a/server/internal/cli/client.go b/server/internal/cli/client.go
index d4814eba82..0a32740754 100644
--- a/server/internal/cli/client.go
+++ b/server/internal/cli/client.go
@@ -444,7 +444,8 @@ func (c *APIClient) UploadFileWithURL(ctx context.Context, fileData []byte, file
// Downloads are limited to 100 MB to match the upload size limit.
//
// The URL may be absolute (a signed CloudFront/S3 URL) or relative
-// (a server-relative path like "/uploads/...") depending on how the
+// (a server-relative path like "/api/attachments/{id}/download" or
+// "/uploads/...") depending on how the
// server is configured. Relative URLs are resolved against the client's
// BaseURL and sent with the standard auth headers; absolute URLs are
// used as-is so that their query-string signatures are not disturbed.
diff --git a/server/internal/handler/file.go b/server/internal/handler/file.go
index 16481f2027..0bbfe88c93 100644
--- a/server/internal/handler/file.go
+++ b/server/internal/handler/file.go
@@ -6,6 +6,8 @@ import (
"io"
"log/slog"
"net/http"
+ "net/netip"
+ "net/url"
"path"
"strings"
"time"
@@ -13,6 +15,7 @@ import (
"github.com/go-chi/chi/v5"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/storage"
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
@@ -29,6 +32,17 @@ var extContentTypes = map[string]string{
const maxUploadSize = 100 << 20 // 100 MB
+const defaultAttachmentDownloadURLTTL = 30 * time.Minute
+
+type attachmentDownloadMode string
+
+const (
+ attachmentDownloadModeAuto attachmentDownloadMode = "auto"
+ attachmentDownloadModeCloudFront attachmentDownloadMode = "cloudfront"
+ attachmentDownloadModePresign attachmentDownloadMode = "presign"
+ attachmentDownloadModeProxy attachmentDownloadMode = "proxy"
+)
+
// maxPreviewTextSize caps the body the preview proxy will load into memory
// for text-based types. Anything larger returns 413 and the UI falls back
// to "please download". Sized so a typical README/source-file fits but a
@@ -57,20 +71,21 @@ type AttachmentResponse struct {
}
func (h *Handler) attachmentToResponse(a db.Attachment) AttachmentResponse {
+ id := uuidToString(a.ID)
resp := AttachmentResponse{
- ID: uuidToString(a.ID),
+ ID: id,
WorkspaceID: uuidToString(a.WorkspaceID),
UploaderType: a.UploaderType,
UploaderID: uuidToString(a.UploaderID),
Filename: a.Filename,
URL: a.Url,
- DownloadURL: a.Url,
+ DownloadURL: attachmentDownloadPath(id),
ContentType: a.ContentType,
SizeBytes: a.SizeBytes,
CreatedAt: a.CreatedAt.Time.Format("2006-01-02T15:04:05Z07:00"),
}
if h.CFSigner != nil {
- resp.DownloadURL = h.CFSigner.SignedURL(a.Url, time.Now().Add(30*time.Minute))
+ resp.DownloadURL = h.CFSigner.SignedURL(a.Url, time.Now().Add(h.attachmentDownloadURLTTL()))
}
if a.IssueID.Valid {
s := uuidToString(a.IssueID)
@@ -91,6 +106,37 @@ func (h *Handler) attachmentToResponse(a db.Attachment) AttachmentResponse {
return resp
}
+func attachmentDownloadPath(id string) string {
+ return "/api/attachments/" + id + "/download"
+}
+
+func normalizeAttachmentDownloadMode(raw string) (attachmentDownloadMode, bool) {
+ switch attachmentDownloadMode(strings.ToLower(strings.TrimSpace(raw))) {
+ case "", attachmentDownloadModeAuto:
+ return attachmentDownloadModeAuto, true
+ case attachmentDownloadModeCloudFront:
+ return attachmentDownloadModeCloudFront, true
+ case attachmentDownloadModePresign:
+ return attachmentDownloadModePresign, true
+ case attachmentDownloadModeProxy:
+ return attachmentDownloadModeProxy, true
+ default:
+ return attachmentDownloadModeAuto, false
+ }
+}
+
+func (h *Handler) attachmentDownloadMode() attachmentDownloadMode {
+ mode, _ := normalizeAttachmentDownloadMode(h.cfg.AttachmentDownloadMode)
+ return mode
+}
+
+func (h *Handler) attachmentDownloadURLTTL() time.Duration {
+ if h.cfg.AttachmentDownloadURLTTL > 0 {
+ return h.cfg.AttachmentDownloadURLTTL
+ }
+ return defaultAttachmentDownloadURLTTL
+}
+
// groupAttachments loads attachments for multiple comments and groups them by comment ID.
func (h *Handler) groupAttachments(r *http.Request, commentIDs []pgtype.UUID) map[string][]AttachmentResponse {
if len(commentIDs) == 0 {
@@ -338,20 +384,29 @@ func (h *Handler) ListAttachments(w http.ResponseWriter, r *http.Request) {
// ---------------------------------------------------------------------------
func (h *Handler) GetAttachmentByID(w http.ResponseWriter, r *http.Request) {
+ att, ok := h.loadAttachmentForRequest(w, r)
+ if !ok {
+ return
+ }
+
+ writeJSON(w, http.StatusOK, h.attachmentToResponse(att))
+}
+
+func (h *Handler) loadAttachmentForRequest(w http.ResponseWriter, r *http.Request) (db.Attachment, bool) {
attachmentID := chi.URLParam(r, "id")
workspaceID := h.resolveWorkspaceID(r)
if workspaceID == "" {
writeError(w, http.StatusBadRequest, "workspace_id is required")
- return
+ return db.Attachment{}, false
}
attUUID, ok := parseUUIDOrBadRequest(w, attachmentID, "attachment id")
if !ok {
- return
+ return db.Attachment{}, false
}
wsUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")
if !ok {
- return
+ return db.Attachment{}, false
}
att, err := h.Queries.GetAttachment(r.Context(), db.GetAttachmentParams{
@@ -360,10 +415,129 @@ func (h *Handler) GetAttachmentByID(w http.ResponseWriter, r *http.Request) {
})
if err != nil {
writeError(w, http.StatusNotFound, "attachment not found")
+ return db.Attachment{}, false
+ }
+
+ return att, true
+}
+
+// ---------------------------------------------------------------------------
+// DownloadAttachment — GET /api/attachments/{id}/download
+// ---------------------------------------------------------------------------
+
+func (h *Handler) DownloadAttachment(w http.ResponseWriter, r *http.Request) {
+ att, ok := h.loadAttachmentForRequest(w, r)
+ if !ok {
+ return
+ }
+ if h.Storage == nil {
+ writeError(w, http.StatusServiceUnavailable, "storage not configured")
return
}
- writeJSON(w, http.StatusOK, h.attachmentToResponse(att))
+ key := h.Storage.KeyFromURL(att.Url)
+ switch h.resolveAttachmentDownloadMode(att.Url) {
+ case attachmentDownloadModeCloudFront:
+ if h.CFSigner == nil {
+ writeError(w, http.StatusInternalServerError, "cloudfront attachment downloads are not configured")
+ return
+ }
+ http.Redirect(w, r, h.CFSigner.SignedURL(att.Url, time.Now().Add(h.attachmentDownloadURLTTL())), http.StatusFound)
+ case attachmentDownloadModePresign:
+ presigner, ok := h.Storage.(storage.Presigner)
+ if !ok {
+ writeError(w, http.StatusInternalServerError, "attachment storage does not support presigned downloads")
+ return
+ }
+ signedURL, err := presigner.PresignGet(r.Context(), key, h.attachmentDownloadURLTTL())
+ if err != nil {
+ slog.Error("failed to presign attachment download", "id", uuidToString(att.ID), "key", key, "error", err)
+ writeError(w, http.StatusBadGateway, "failed to create download URL")
+ return
+ }
+ http.Redirect(w, r, signedURL, http.StatusFound)
+ case attachmentDownloadModeProxy:
+ h.proxyAttachmentDownload(w, r, att, key)
+ default:
+ writeError(w, http.StatusInternalServerError, "invalid attachment download mode")
+ }
+}
+
+func (h *Handler) resolveAttachmentDownloadMode(rawURL string) attachmentDownloadMode {
+ switch h.attachmentDownloadMode() {
+ case attachmentDownloadModeCloudFront:
+ return attachmentDownloadModeCloudFront
+ case attachmentDownloadModePresign:
+ return attachmentDownloadModePresign
+ case attachmentDownloadModeProxy:
+ return attachmentDownloadModeProxy
+ }
+ if h.CFSigner != nil {
+ return attachmentDownloadModeCloudFront
+ }
+ if shouldProxyAttachmentURL(rawURL) {
+ return attachmentDownloadModeProxy
+ }
+ if _, ok := h.Storage.(storage.Presigner); ok {
+ return attachmentDownloadModePresign
+ }
+ return attachmentDownloadModeProxy
+}
+
+func shouldProxyAttachmentURL(rawURL string) bool {
+ u, err := url.Parse(rawURL)
+ if err != nil || u.Hostname() == "" {
+ return true
+ }
+ host := strings.ToLower(strings.TrimSuffix(strings.TrimSpace(u.Hostname()), "."))
+ if host == "" || host == "localhost" || strings.HasSuffix(host, ".localhost") {
+ return true
+ }
+ if !strings.Contains(host, ".") {
+ return true
+ }
+ switch {
+ case strings.HasSuffix(host, ".local"),
+ strings.HasSuffix(host, ".localdomain"),
+ strings.HasSuffix(host, ".internal"),
+ strings.HasSuffix(host, ".lan"),
+ strings.HasSuffix(host, ".home"),
+ strings.HasSuffix(host, ".docker"):
+ return true
+ }
+ if addr, err := netip.ParseAddr(host); err == nil {
+ return addr.IsLoopback() ||
+ addr.IsPrivate() ||
+ addr.IsLinkLocalUnicast() ||
+ addr.IsLinkLocalMulticast() ||
+ addr.IsUnspecified()
+ }
+ return false
+}
+
+func (h *Handler) proxyAttachmentDownload(w http.ResponseWriter, r *http.Request, att db.Attachment, key string) {
+ 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)
+ writeError(w, http.StatusNotFound, "attachment object not found")
+ return
+ }
+ defer reader.Close()
+
+ if att.ContentType != "" {
+ w.Header().Set("Content-Type", att.ContentType)
+ } else {
+ w.Header().Set("Content-Type", "application/octet-stream")
+ }
+ if att.SizeBytes >= 0 {
+ w.Header().Set("Content-Length", fmt.Sprintf("%d", att.SizeBytes))
+ }
+ w.Header().Set("Content-Disposition", storage.ContentDisposition(att.ContentType, att.Filename))
+ w.Header().Set("Cache-Control", "no-store")
+ w.Header().Set("X-Content-Type-Options", "nosniff")
+ if _, err := io.Copy(w, reader); err != nil {
+ slog.Error("failed to stream attachment download", "id", uuidToString(att.ID), "error", err)
+ }
}
// ---------------------------------------------------------------------------
@@ -372,40 +546,20 @@ func (h *Handler) GetAttachmentByID(w http.ResponseWriter, r *http.Request) {
// Streams the raw bytes of a text-previewable attachment back to the client.
// Exists to (a) bypass CloudFront CORS (not configured) and (b) bypass
// Content-Disposition: attachment which Chromium honors for iframe document
-// loads. Media types (image/video/audio/pdf) intentionally do NOT go through
-// this endpoint — clients render them directly from the CloudFront signed
-// download_url, which already serves them with Content-Disposition: inline
-// (see storage/util.go isInlineContentType).
+// loads. Media types (image/video/audio/pdf) intentionally use download_url
+// instead; /download signs or streams them with Content-Disposition: inline
+// using the same media-type policy as storage uploads.
//
// Hard cap: 2 MB. Larger files return 413. Anything outside the text
// whitelist returns 415.
// ---------------------------------------------------------------------------
func (h *Handler) GetAttachmentContent(w http.ResponseWriter, r *http.Request) {
- attachmentID := chi.URLParam(r, "id")
- workspaceID := h.resolveWorkspaceID(r)
- if workspaceID == "" {
- writeError(w, http.StatusBadRequest, "workspace_id is required")
- return
- }
-
- attUUID, ok := parseUUIDOrBadRequest(w, attachmentID, "attachment id")
+ att, ok := h.loadAttachmentForRequest(w, r)
if !ok {
return
}
- wsUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")
- if !ok {
- return
- }
-
- att, err := h.Queries.GetAttachment(r.Context(), db.GetAttachmentParams{
- ID: attUUID,
- WorkspaceID: wsUUID,
- })
- if err != nil {
- writeError(w, http.StatusNotFound, "attachment not found")
- return
- }
+ attachmentID := uuidToString(att.ID)
if !isTextPreviewable(att.ContentType, att.Filename) {
writeError(w, http.StatusUnsupportedMediaType, "preview not supported for this file type")
diff --git a/server/internal/handler/file_test.go b/server/internal/handler/file_test.go
index a2507b9cd9..b0fd238e07 100644
--- a/server/internal/handler/file_test.go
+++ b/server/internal/handler/file_test.go
@@ -12,8 +12,10 @@ import (
"strings"
"sync"
"testing"
+ "time"
"github.com/go-chi/chi/v5"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
)
// createHandlerTestChatSession seeds a chat_session row owned by testUserID
@@ -41,8 +43,9 @@ func createHandlerTestChatSession(t *testing.T, agentID string) string {
// strips the synthetic CDN host so consumers can pass either the URL or the
// raw key.
type mockStorage struct {
- mu sync.Mutex
- files map[string][]byte
+ mu sync.Mutex
+ files map[string][]byte
+ presignCalls []string
}
func (m *mockStorage) Upload(_ context.Context, key string, data []byte, _ string, _ string) (string, error) {
@@ -62,9 +65,14 @@ func (m *mockStorage) Delete(_ context.Context, key string) {
}
func (m *mockStorage) DeleteKeys(_ context.Context, _ []string) {}
func (m *mockStorage) KeyFromURL(rawURL string) string {
- const prefix = "https://cdn.example.com/"
- if strings.HasPrefix(rawURL, prefix) {
- return strings.TrimPrefix(rawURL, prefix)
+ for _, prefix := range []string{
+ "https://cdn.example.com/",
+ "http://rustfs:9000/test-bucket/",
+ "https://s3.example.com/test-bucket/",
+ } {
+ if strings.HasPrefix(rawURL, prefix) {
+ return strings.TrimPrefix(rawURL, prefix)
+ }
}
return rawURL
}
@@ -77,6 +85,20 @@ func (m *mockStorage) GetReader(_ context.Context, key string) (io.ReadCloser, e
}
return nil, fmt.Errorf("mockStorage GetReader: key not found: %q", key)
}
+func (m *mockStorage) PresignGet(_ context.Context, key string, _ time.Duration) (string, error) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ m.presignCalls = append(m.presignCalls, key)
+ return "https://signed.example.com/" + key + "?X-Amz-Signature=mock", nil
+}
+func (m *mockStorage) put(key string, data []byte) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if m.files == nil {
+ m.files = map[string][]byte{}
+ }
+ m.files[key] = append([]byte(nil), data...)
+}
func TestUploadFileForeignWorkspace(t *testing.T) {
origStorage := testHandler.Storage
@@ -347,6 +369,22 @@ func seedPreviewAttachment(t *testing.T, store *mockStorage, key, filename, cont
return id
}
+func seedAttachmentURL(t *testing.T, rawURL, filename, contentType string, sizeBytes int64) string {
+ t.Helper()
+ var id string
+ if err := testPool.QueryRow(context.Background(), `
+ INSERT INTO attachment (workspace_id, uploader_type, uploader_id, filename, url, content_type, size_bytes)
+ VALUES ($1, 'member', $2, $3, $4, $5, $6)
+ RETURNING id::text
+ `, testWorkspaceID, testUserID, filename, rawURL, contentType, sizeBytes).Scan(&id); err != nil {
+ t.Fatalf("seed attachment row: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM attachment WHERE id = $1`, id)
+ })
+ return id
+}
+
func newPreviewRequest(t *testing.T, attachmentID, workspaceID string) (*http.Request, *httptest.ResponseRecorder) {
t.Helper()
req := httptest.NewRequest("GET", "/api/attachments/"+attachmentID+"/content", nil)
@@ -358,6 +396,176 @@ func newPreviewRequest(t *testing.T, attachmentID, workspaceID string) (*http.Re
return req, httptest.NewRecorder()
}
+func newDownloadRequest(t *testing.T, attachmentID, workspaceID string) (*http.Request, *httptest.ResponseRecorder) {
+ t.Helper()
+ req := httptest.NewRequest("GET", "/api/attachments/"+attachmentID+"/download", nil)
+ req.Header.Set("X-User-ID", testUserID)
+ req.Header.Set("X-Workspace-ID", workspaceID)
+ rctx := chi.NewRouteContext()
+ rctx.URLParams.Add("id", attachmentID)
+ req = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))
+ return req, httptest.NewRecorder()
+}
+
+func TestAttachmentToResponse_NonCloudFrontUsesDownloadEndpoint(t *testing.T) {
+ origSigner := testHandler.CFSigner
+ testHandler.CFSigner = nil
+ t.Cleanup(func() { testHandler.CFSigner = origSigner })
+
+ id := seedAttachmentURL(t, "http://rustfs:9000/test-bucket/private.txt", "private.txt", "text/plain", 5)
+ att, err := testHandler.Queries.GetAttachment(context.Background(), db.GetAttachmentParams{
+ ID: parseUUID(id),
+ WorkspaceID: parseUUID(testWorkspaceID),
+ })
+ if err != nil {
+ t.Fatalf("GetAttachment: %v", err)
+ }
+
+ resp := testHandler.attachmentToResponse(att)
+ if resp.URL != "http://rustfs:9000/test-bucket/private.txt" {
+ t.Fatalf("stored url changed: %q", resp.URL)
+ }
+ if resp.DownloadURL != "/api/attachments/"+id+"/download" {
+ t.Fatalf("download_url = %q, want unified endpoint", resp.DownloadURL)
+ }
+}
+
+func TestDownloadAttachment_AutoInternalEndpointProxies(t *testing.T) {
+ store := &mockStorage{}
+ origStorage := testHandler.Storage
+ origCfg := testHandler.cfg
+ origSigner := testHandler.CFSigner
+ testHandler.Storage = store
+ testHandler.cfg.AttachmentDownloadMode = "auto"
+ testHandler.CFSigner = nil
+ t.Cleanup(func() {
+ testHandler.Storage = origStorage
+ testHandler.cfg = origCfg
+ testHandler.CFSigner = origSigner
+ })
+
+ key := "downloads/proxy-private.txt"
+ body := []byte("private object")
+ store.put(key, body)
+ id := seedAttachmentURL(t, "http://rustfs:9000/test-bucket/"+key, "report.txt", "text/plain", int64(len(body)))
+
+ req, w := newDownloadRequest(t, id, testWorkspaceID)
+ testHandler.DownloadAttachment(w, req)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200; body=%s", w.Code, w.Body.String())
+ }
+ if got := w.Body.String(); got != string(body) {
+ t.Fatalf("body = %q, want %q", got, body)
+ }
+ if got := w.Header().Get("Location"); got != "" {
+ t.Fatalf("Location should be empty for proxy download, got %q", got)
+ }
+ if got := w.Header().Get("Content-Disposition"); got != `attachment; filename="report.txt"` {
+ t.Fatalf("Content-Disposition = %q", got)
+ }
+ if got := w.Header().Get("Cache-Control"); got != "no-store" {
+ t.Fatalf("Cache-Control = %q, want no-store", got)
+ }
+ if got := w.Header().Get("X-Content-Type-Options"); got != "nosniff" {
+ t.Fatalf("X-Content-Type-Options = %q, want nosniff", got)
+ }
+ if len(store.presignCalls) != 0 {
+ t.Fatalf("internal endpoint should not presign, calls=%v", store.presignCalls)
+ }
+}
+
+func TestDownloadAttachment_AutoPublicEndpointPresigns(t *testing.T) {
+ store := &mockStorage{}
+ origStorage := testHandler.Storage
+ origCfg := testHandler.cfg
+ origSigner := testHandler.CFSigner
+ testHandler.Storage = store
+ testHandler.cfg.AttachmentDownloadMode = "auto"
+ testHandler.CFSigner = nil
+ t.Cleanup(func() {
+ testHandler.Storage = origStorage
+ testHandler.cfg = origCfg
+ testHandler.CFSigner = origSigner
+ })
+
+ key := "downloads/public-private.txt"
+ id := seedAttachmentURL(t, "https://s3.example.com/test-bucket/"+key, "public.txt", "text/plain", 10)
+
+ req, w := newDownloadRequest(t, id, testWorkspaceID)
+ testHandler.DownloadAttachment(w, req)
+
+ if w.Code != http.StatusFound {
+ t.Fatalf("status = %d, want 302; body=%s", w.Code, w.Body.String())
+ }
+ loc := w.Header().Get("Location")
+ if !strings.Contains(loc, "X-Amz-Signature=mock") {
+ t.Fatalf("Location = %q, want fake S3 signature", loc)
+ }
+ if len(store.presignCalls) != 1 || store.presignCalls[0] != key {
+ t.Fatalf("presign calls = %v, want [%s]", store.presignCalls, key)
+ }
+}
+
+func TestDownloadAttachment_ExplicitProxyStreamsPublicEndpoint(t *testing.T) {
+ store := &mockStorage{}
+ origStorage := testHandler.Storage
+ origCfg := testHandler.cfg
+ origSigner := testHandler.CFSigner
+ testHandler.Storage = store
+ testHandler.cfg.AttachmentDownloadMode = "proxy"
+ testHandler.CFSigner = nil
+ t.Cleanup(func() {
+ testHandler.Storage = origStorage
+ testHandler.cfg = origCfg
+ testHandler.CFSigner = origSigner
+ })
+
+ key := "downloads/forced-proxy.png"
+ body := []byte("\x89PNG\r\n\x1a\nimage")
+ store.put(key, body)
+ id := seedAttachmentURL(t, "https://s3.example.com/test-bucket/"+key, "image.png", "image/png", int64(len(body)))
+
+ req, w := newDownloadRequest(t, id, testWorkspaceID)
+ testHandler.DownloadAttachment(w, req)
+
+ if w.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200; body=%s", w.Code, w.Body.String())
+ }
+ if got := w.Body.Bytes(); !bytes.Equal(got, body) {
+ t.Fatalf("body mismatch: got %q want %q", got, body)
+ }
+ if got := w.Header().Get("Content-Disposition"); got != `inline; filename="image.png"` {
+ t.Fatalf("Content-Disposition = %q", got)
+ }
+ if len(store.presignCalls) != 0 {
+ t.Fatalf("forced proxy should not presign, calls=%v", store.presignCalls)
+ }
+}
+
+func TestShouldProxyAttachmentURL(t *testing.T) {
+ cases := []struct {
+ raw string
+ want bool
+ }{
+ {"http://rustfs:9000/test-bucket/file.txt", true},
+ {"http://localhost:9000/test-bucket/file.txt", true},
+ {"http://127.0.0.1:9000/test-bucket/file.txt", true},
+ {"http://10.0.2.15/test-bucket/file.txt", true},
+ {"https://minio.internal/test-bucket/file.txt", true},
+ {"/uploads/workspaces/abc/file.txt", true},
+ {"https://s3.example.com/test-bucket/file.txt", false},
+ {"https://bucket.s3.us-east-1.amazonaws.com/file.txt", false},
+ }
+ for _, tc := range cases {
+ t.Run(tc.raw, func(t *testing.T) {
+ if got := shouldProxyAttachmentURL(tc.raw); got != tc.want {
+ t.Fatalf("shouldProxyAttachmentURL(%q) = %v, want %v", tc.raw, got, tc.want)
+ }
+ })
+ }
+}
+
func TestGetAttachmentContent_HappyPath_Markdown(t *testing.T) {
store := &mockStorage{}
origStorage := testHandler.Storage
@@ -502,4 +710,3 @@ func TestIsTextPreviewable(t *testing.T) {
})
}
}
-
diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.go
index a282c079f8..df37d2df62 100644
--- a/server/internal/handler/handler.go
+++ b/server/internal/handler/handler.go
@@ -82,6 +82,8 @@ type Config struct {
// return 503 instead of attempting to dial a hard-coded private service.
CloudRuntimeFleetURL string
CloudRuntimeFleetTimeout time.Duration
+ AttachmentDownloadMode string
+ AttachmentDownloadURLTTL time.Duration
}
type cloudRuntimeProxy interface {
@@ -165,6 +167,15 @@ func New(queries *db.Queries, txStarter txStarter, hub *realtime.Hub, bus *event
if analyticsClient == nil {
analyticsClient = analytics.NoopClient{}
}
+ if mode, ok := normalizeAttachmentDownloadMode(cfg.AttachmentDownloadMode); ok {
+ cfg.AttachmentDownloadMode = string(mode)
+ } else {
+ slog.Warn("invalid ATTACHMENT_DOWNLOAD_MODE, using auto", "value", cfg.AttachmentDownloadMode)
+ cfg.AttachmentDownloadMode = string(attachmentDownloadModeAuto)
+ }
+ if cfg.AttachmentDownloadURLTTL <= 0 {
+ cfg.AttachmentDownloadURLTTL = defaultAttachmentDownloadURLTTL
+ }
var daemonHub *daemonws.Hub
if len(daemonHubs) > 0 {
diff --git a/server/internal/storage/local.go b/server/internal/storage/local.go
index 689a09b4a1..0c8bec8874 100644
--- a/server/internal/storage/local.go
+++ b/server/internal/storage/local.go
@@ -185,12 +185,7 @@ func (s *LocalStorage) ServeFile(w http.ResponseWriter, r *http.Request, filenam
// chose. Uploads from before the sidecar landed have no .meta.json on
// disk and fall through to the existing behavior.
if meta, ok := readLocalMeta(filePath); ok && meta.Filename != "" {
- safe := sanitizeFilename(meta.Filename)
- disposition := "attachment"
- if isInlineContentType(meta.ContentType) {
- disposition = "inline"
- }
- w.Header().Set("Content-Disposition", fmt.Sprintf(`%s; filename="%s"`, disposition, safe))
+ w.Header().Set("Content-Disposition", ContentDisposition(meta.ContentType, meta.Filename))
}
// Use http.ServeFile which has built-in path traversal protection
diff --git a/server/internal/storage/s3.go b/server/internal/storage/s3.go
index 266b84d35e..46b28a1a86 100644
--- a/server/internal/storage/s3.go
+++ b/server/internal/storage/s3.go
@@ -8,6 +8,7 @@ import (
"log/slog"
"os"
"strings"
+ "time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
@@ -172,6 +173,25 @@ func (s *S3Storage) GetReader(ctx context.Context, key string) (io.ReadCloser, e
return out.Body, nil
}
+func (s *S3Storage) PresignGet(ctx context.Context, key string, ttl time.Duration) (string, error) {
+ if key == "" {
+ return "", fmt.Errorf("s3 PresignGet: empty key")
+ }
+ if ttl <= 0 {
+ ttl = 30 * time.Minute
+ }
+ out, err := s3.NewPresignClient(s.client).PresignGetObject(ctx, &s3.GetObjectInput{
+ Bucket: aws.String(s.bucket),
+ Key: aws.String(key),
+ }, func(opts *s3.PresignOptions) {
+ opts.Expires = ttl
+ })
+ if err != nil {
+ return "", fmt.Errorf("s3 PresignGetObject: %w", err)
+ }
+ return out.URL, nil
+}
+
// Delete removes an object from S3. Errors are logged but not fatal.
func (s *S3Storage) Delete(ctx context.Context, key string) {
if key == "" {
@@ -194,17 +214,12 @@ func (s *S3Storage) DeleteKeys(ctx context.Context, keys []string) {
}
func (s *S3Storage) Upload(ctx context.Context, key string, data []byte, contentType string, filename string) (string, error) {
- safe := sanitizeFilename(filename)
- disposition := "attachment"
- if isInlineContentType(contentType) {
- disposition = "inline"
- }
_, err := s.client.PutObject(ctx, &s3.PutObjectInput{
Bucket: aws.String(s.bucket),
Key: aws.String(key),
Body: bytes.NewReader(data),
ContentType: aws.String(contentType),
- ContentDisposition: aws.String(fmt.Sprintf(`%s; filename="%s"`, disposition, safe)),
+ ContentDisposition: aws.String(ContentDisposition(contentType, filename)),
CacheControl: aws.String("max-age=432000,public"),
StorageClass: s.storageClass(),
})
diff --git a/server/internal/storage/s3_test.go b/server/internal/storage/s3_test.go
index a4464b0127..5b00a85bc3 100644
--- a/server/internal/storage/s3_test.go
+++ b/server/internal/storage/s3_test.go
@@ -1,6 +1,15 @@
package storage
-import "testing"
+import (
+ "context"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ "github.com/aws/aws-sdk-go-v2/credentials"
+ "github.com/aws/aws-sdk-go-v2/service/s3"
+)
func TestS3StorageKeyFromURL_CustomEndpointPreservesNestedKey(t *testing.T) {
s := &S3Storage{
@@ -15,6 +24,30 @@ func TestS3StorageKeyFromURL_CustomEndpointPreservesNestedKey(t *testing.T) {
}
}
+func TestS3StoragePresignGet(t *testing.T) {
+ store := &S3Storage{
+ client: s3.New(s3.Options{
+ Region: "us-east-1",
+ Credentials: aws.NewCredentialsCache(credentials.NewStaticCredentialsProvider("AKID", "SECRET", "")),
+ }),
+ bucket: "test-bucket",
+ }
+
+ got, err := store.PresignGet(context.Background(), "uploads/abc/file.txt", 5*time.Minute)
+ if err != nil {
+ t.Fatalf("PresignGet: %v", err)
+ }
+ for _, want := range []string{
+ "https://test-bucket.s3.us-east-1.amazonaws.com/uploads/abc/file.txt",
+ "X-Amz-Signature=",
+ "X-Amz-Expires=300",
+ } {
+ if !strings.Contains(got, want) {
+ t.Fatalf("presigned URL %q does not contain %q", got, want)
+ }
+ }
+}
+
func TestS3StorageKeyFromURL_CustomEndpointWithTrailingSlash(t *testing.T) {
s := &S3Storage{
bucket: "test-bucket",
diff --git a/server/internal/storage/storage.go b/server/internal/storage/storage.go
index a58e318650..f8cdb17bf8 100644
--- a/server/internal/storage/storage.go
+++ b/server/internal/storage/storage.go
@@ -3,6 +3,7 @@ package storage
import (
"context"
"io"
+ "time"
)
type Storage interface {
@@ -17,3 +18,7 @@ type Storage interface {
// must Close the returned reader.
GetReader(ctx context.Context, key string) (io.ReadCloser, error)
}
+
+type Presigner interface {
+ PresignGet(ctx context.Context, key string, ttl time.Duration) (string, error)
+}
diff --git a/server/internal/storage/util.go b/server/internal/storage/util.go
index 8e474ff021..a22137508c 100644
--- a/server/internal/storage/util.go
+++ b/server/internal/storage/util.go
@@ -19,6 +19,14 @@ func sanitizeFilename(name string) string {
return b.String()
}
+func ContentDisposition(contentType, filename string) string {
+ disposition := "attachment"
+ if isInlineContentType(contentType) {
+ disposition = "inline"
+ }
+ return disposition + `; filename="` + sanitizeFilename(filename) + `"`
+}
+
// isInlineContentType returns true for media types that browsers should
// display inline (images, video, audio, PDF). Everything else triggers a
// download via Content-Disposition: attachment.
diff --git a/server/internal/storage/util_test.go b/server/internal/storage/util_test.go
index 466b2299b4..c4c16f1ce2 100644
--- a/server/internal/storage/util_test.go
+++ b/server/internal/storage/util_test.go
@@ -41,3 +41,15 @@ func TestIsInlineContentType(t *testing.T) {
}
}
}
+
+func TestContentDisposition(t *testing.T) {
+ if got := ContentDisposition("image/png", `nice"file;.png`); got != `inline; filename="nice_file_.png"` {
+ t.Fatalf("ContentDisposition image = %q", got)
+ }
+ if got := ContentDisposition("text/plain", "notes.txt"); got != `attachment; filename="notes.txt"` {
+ t.Fatalf("ContentDisposition text = %q", got)
+ }
+ if got := ContentDisposition("image/svg+xml", "logo.svg"); got != `attachment; filename="logo.svg"` {
+ t.Fatalf("ContentDisposition svg = %q", got)
+ }
+}