Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8609: fix(upload): stream 100 MiB uploads through web without truncation (#9905)
SUBARUAWA4861ca4b43be1f8
diff --git a/SELF_HOSTING_ADVANCED.md b/SELF_HOSTING_ADVANCED.mdindex 74509091df..cae1e93657 100644--- a/SELF_HOSTING_ADVANCED.md+++ b/SELF_HOSTING_ADVANCED.md@@ -123,6 +123,14 @@ use S3-compatible object storage instead.| `LOCAL_UPLOAD_DIR` | Directory attachments are written to (default: `./data/uploads`). The default is **relative to the backend's working directory** — `/app` in the bundled image, where the compose file mounts the `backend_uploads` volume. When running the binary manually it resolves against whatever directory you launched from, so set an absolute path; otherwise uploads land somewhere new each time the launch directory changes, and existing `attachment` rows point at files the server no longer looks for || `LOCAL_UPLOAD_BASE_URL` | Optional absolute base for attachment URLs (e.g. `http://localhost:8080`). Leave empty to store `/uploads/...` paths that stay relative to the API origin |+Uploads support files up to **100 MiB**. The backend allows an additional+1 MiB for multipart boundaries and metadata, and returns HTTP 413 for oversized+files or requests. The web upload route streams the body to the backend, so+Next Proxy's body-buffer limit does not truncate uploads, including requests+without `Content-Length`. If you deploy your own reverse proxy or ingress,+allow request bodies of at least **101 MiB** there too. The upload limit is fixed;+no upload-size environment variable is supported.+#### S3 / CloudFront| Variable | Description |diff --git a/apps/web/app/api/upload-file/route.ts b/apps/web/app/api/upload-file/route.tsnew file mode 100644index 0000000000..c6ccdab4ee--- /dev/null+++ b/apps/web/app/api/upload-file/route.ts@@ -0,0 +1,11 @@+import { proxyUpload } from "@/platform/upload-proxy";++export const runtime = "nodejs";++export async function POST(request: Request): Promise<Response> {+ return proxyUpload(request);+}++export async function OPTIONS(request: Request): Promise<Response> {+ return proxyUpload(request);+}diff --git a/apps/web/platform/upload-proxy.test.ts b/apps/web/platform/upload-proxy.test.tsnew file mode 100644index 0000000000..d1fe2245e7--- /dev/null+++ b/apps/web/platform/upload-proxy.test.ts@@ -0,0 +1,181 @@+// @vitest-environment node++import { createServer } from "node:http";+import { afterEach, describe, expect, it, vi } from "vitest";+import { proxyUpload } from "./upload-proxy";++const production = { NODE_ENV: "production", REMOTE_API_URL: "http://backend:8080" };++afterEach(() => vi.restoreAllMocks());++describe("proxyUpload", () => {+ it("uploads a 2 MiB multipart body with Expect: 100-continue through real fetch", async () => {+ let receivedBody: Buffer | undefined;+ let receivedExpect: string | undefined;+ const upstream = createServer((request, response) => {+ receivedExpect = request.headers.expect;+ const chunks: Buffer[] = [];+ request.on("data", (chunk: Buffer) => chunks.push(chunk));+ request.on("end", () => {+ receivedBody = Buffer.concat(chunks);+ response.end("uploaded");+ });+ });+ await new Promise<void>((resolve, reject) => {+ upstream.once("error", reject);+ upstream.listen(0, "127.0.0.1", resolve);+ });++ try {+ const address = upstream.address();+ if (!address || typeof address === "string") throw new Error("missing upstream port");+ const form = new FormData();+ form.append("file", new Blob([new Uint8Array(2 * 1024 * 1024)]), "attachment.bin");+ const request = new Request("https://app.test/api/upload-file", {+ method: "POST",+ headers: { Expect: "100-continue" },+ body: form,+ });+ const expectedBody = Buffer.from(await request.clone().arrayBuffer());+ const response = await proxyUpload(request, {+ ...production,+ REMOTE_API_URL: `http://127.0.0.1:${address.port}`,+ });++ expect(response.status).toBe(200);+ expect(await response.text()).toBe("uploaded");+ expect(receivedExpect).toBeUndefined();+ expect(receivedBody?.equals(expectedBody)).toBe(true);+ } finally {+ await new Promise<void>((resolve, reject) => {+ upstream.close((error) => error ? reject(error) : resolve());+ upstream.closeAllConnections();+ });+ }+ });++ it("forwards the untouched multipart stream, credentials, workspace, and query", async () => {+ const body = new ReadableStream<Uint8Array>();+ const request = new Request("https://app.test/api/upload-file?draft=1", {+ method: "POST",+ headers: {+ authorization: "Bearer test-token",+ cookie: "multica_session=test-session",+ "x-csrf-token": "test-csrf",+ "x-workspace-slug": "acme",+ "content-type": "multipart/form-data; boundary=test",+ "content-length": "100",+ connection: "keep-alive, x-hop-only",+ "x-hop-only": "discard",+ },+ body,+ duplex: "half",+ } as RequestInit & { duplex: "half" });+ const fetchImpl = vi.fn(async (_url: string | URL | Request, init?: RequestInit) => {+ expect(init?.method).toBe("POST");+ expect(init?.body).toBe(request.body);+ expect(init?.signal).toBe(request.signal);+ expect(init?.redirect).toBe("manual");+ const headers = new Headers(init?.headers);+ for (const name of ["authorization", "cookie", "x-csrf-token", "x-workspace-slug", "content-type"]) {+ expect(headers.get(name)).toBe(request.headers.get(name));+ }+ for (const name of ["content-length", "connection", "x-hop-only"]) {+ expect(headers.has(name)).toBe(false);+ }+ expect(headers.get("accept-encoding")).toBe("identity");+ expect(headers.get("x-forwarded-host")).toBe("app.test");+ return new Response("uploaded", { status: 201, headers: { "x-upload-id": "att-1" } });+ });+ const response = await proxyUpload(request, { ...production, REMOTE_API_URL: "http://backend:8080/base" }, fetchImpl);+ expect(String(fetchImpl.mock.calls[0]?.[0])).toBe("http://backend:8080/base/api/upload-file?draft=1");+ expect(request.bodyUsed).toBe(false);+ expect(response.status).toBe(201);+ expect(response.headers.get("x-upload-id")).toBe("att-1");+ expect(await response.text()).toBe("uploaded");+ });++ it.each([401, 403, 413, 500])("preserves the backend's %i response and structured body", async (status) => {+ const body = { error: "backend rejection", code: "test_code", max_size_bytes: 104857600 };+ const response = await proxyUpload(+ new Request("https://app.test/api/upload-file", { method: "POST" }),+ production,+ vi.fn().mockResolvedValue(Response.json(body, { status })),+ );+ expect(response.status).toBe(status);+ expect(await response.json()).toEqual(body);+ });++ it("preserves multiple cookies but removes hop headers and decoded-response framing", async () => {+ const headers = new Headers({+ connection: "x-hop-only",+ "x-hop-only": "discard",+ "content-encoding": "gzip",+ "content-length": "45",+ "content-type": "application/json",+ });+ headers.append("set-cookie", "first=1; HttpOnly");+ headers.append("set-cookie", "second=2; HttpOnly");+ // Node fetch exposes decoded body bytes while retaining the wire headers.+ const response = await proxyUpload(+ new Request("https://app.test/api/upload-file", { method: "POST" }),+ production,+ vi.fn().mockResolvedValue(new Response('{"ok":true}', { headers })),+ );+ expect(response.headers.getSetCookie()).toEqual(["first=1; HttpOnly", "second=2; HttpOnly"]);+ for (const name of ["connection", "x-hop-only", "content-encoding", "content-length"]) {+ expect(response.headers.has(name)).toBe(false);+ }+ expect(await response.json()).toEqual({ ok: true });+ });++ it("forwards CORS preflight to the existing backend", async () => {+ const request = new Request("https://app.test/api/upload-file", {+ method: "OPTIONS",+ headers: { origin: "https://client.test", "access-control-request-method": "POST" },+ });+ const fetchImpl = vi.fn(async (_url: string | URL | Request, init?: RequestInit) => {+ expect(init?.method).toBe("OPTIONS");+ expect(new Headers(init?.headers).get("origin")).toBe("https://client.test");+ return new Response(null, { status: 204, headers: { "access-control-allow-origin": "https://client.test" } });+ });+ const response = await proxyUpload(request, production, fetchImpl);+ expect(response.status).toBe(204);+ expect(response.headers.get("access-control-allow-origin")).toBe("https://client.test");+ });++ it("returns 503 without fetching if the production backend is not configured", async () => {+ const fetchImpl = vi.fn();+ const response = await proxyUpload(new Request("https://app.test/api/upload-file"), { NODE_ENV: "production" }, fetchImpl);+ expect(response.status).toBe(503);+ expect(fetchImpl).not.toHaveBeenCalled();+ });++ it("uses the existing development backend resolver", async () => {+ const fetchImpl = vi.fn().mockResolvedValue(Response.json({ ok: true }));+ await proxyUpload(new Request("https://app.test/api/upload-file"), { NODE_ENV: "development", BACKEND_PORT: "18080" }, fetchImpl);+ expect(String(fetchImpl.mock.calls[0]?.[0])).toBe("http://localhost:18080/api/upload-file");+ });++ it("returns a stable 502 for an unreachable backend", async () => {+ vi.spyOn(console, "error").mockImplementation(() => {});+ const response = await proxyUpload(+ new Request("https://app.test/api/upload-file"), production,+ vi.fn().mockRejectedValue(new Error("connection refused")),+ );+ expect(response.status).toBe(502);+ expect(await response.json()).toEqual({ error: "file upload backend unavailable" });+ });++ it("propagates request cancellation to the upstream fetch", async () => {+ const controller = new AbortController();+ const request = new Request("https://app.test/api/upload-file", { signal: controller.signal });+ const fetchImpl = vi.fn((_url: string | URL | Request, init?: RequestInit) => new Promise<Response>((_resolve, reject) => {+ init?.signal?.addEventListener("abort", () => reject(init.signal?.reason), { once: true });+ }));+ const response = proxyUpload(request, production, fetchImpl);+ controller.abort(new DOMException("user cancelled", "AbortError"));+ await expect(response).rejects.toThrow("user cancelled");+ expect(fetchImpl.mock.calls[0]?.[1]?.signal?.aborted).toBe(true);+ });+});diff --git a/apps/web/platform/upload-proxy.ts b/apps/web/platform/upload-proxy.tsnew file mode 100644index 0000000000..5140449fea--- /dev/null+++ b/apps/web/platform/upload-proxy.ts@@ -0,0 +1,84 @@+import {+ resolveDevRemoteApiUrl,+ resolveRemoteApiUrl,+} from "../config/runtime-urls";++type RuntimeEnv = Record<string, string | undefined>;+type FetchLike = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;++const HOP_BY_HOP_HEADERS = [+ "connection",+ "host",+ "keep-alive",+ "proxy-authenticate",+ "proxy-authorization",+ "proxy-connection",+ "te",+ "trailer",+ "transfer-encoding",+ "upgrade",+];++function forwardedHeaders(source: Headers): Headers {+ const headers = new Headers(source);+ for (const name of source.get("connection")?.split(",") ?? []) {+ if (name.trim()) headers.delete(name.trim());+ }+ for (const name of HOP_BY_HOP_HEADERS) headers.delete(name);+ return headers;+}++/** Forward multipart bytes without buffering or parsing them in Next.js. */+export async function proxyUpload(+ request: Request,+ env: RuntimeEnv = process.env,+ fetchImpl: FetchLike = fetch,+): Promise<Response> {+ const origin = env.NODE_ENV === "development"+ ? resolveDevRemoteApiUrl(env)+ : resolveRemoteApiUrl(env);+ if (!origin) {+ return Response.json({ error: "file upload backend is not configured" }, { status: 503 });+ }++ const incomingURL = new URL(request.url);+ const upstreamURL = new URL(origin);+ upstreamURL.pathname = `${upstreamURL.pathname.replace(/\/+$/, "")}/api/upload-file`;+ upstreamURL.search = incomingURL.search;+ const headers = forwardedHeaders(request.headers);+ // The outgoing streaming request uses its own transfer framing.+ headers.delete("content-length");+ // Next's HTTP server handles 100-continue; Node fetch rejects Expect.+ headers.delete("expect");+ headers.set("x-forwarded-host", request.headers.get("host") ?? incomingURL.host);+ headers.set("accept-encoding", "identity");++ try {+ // Node fetch requires duplex for a streaming request body.+ const init: RequestInit & { duplex: "half" } = {+ method: request.method,+ headers,+ body: request.body,+ redirect: "manual",+ signal: request.signal,+ duplex: "half",+ };+ const upstream = await fetchImpl(upstreamURL, init);+ const responseHeaders = forwardedHeaders(upstream.headers);+ // Fetch decodes compressed responses, so their wire encoding and length+ // cannot describe the response stream returned to the browser.+ responseHeaders.delete("content-encoding");+ responseHeaders.delete("content-length");+ return new Response(upstream.body, {+ status: upstream.status,+ statusText: upstream.statusText,+ headers: responseHeaders,+ });+ } catch (error) {+ if (request.signal.aborted) throw error;+ console.error("upload proxy request failed", {+ error: error instanceof Error ? error.message : String(error),+ });+ return Response.json({ error: "file upload backend unavailable" }, { status: 502 });+ }+}diff --git a/apps/web/proxy.test.ts b/apps/web/proxy.test.tsindex e66d7981dd..c79ad662f1 100644--- a/apps/web/proxy.test.ts+++ b/apps/web/proxy.test.ts@@ -1,4 +1,5 @@import { describe, expect, it } from "vitest";+import { unstable_doesMiddlewareMatch } from "next/experimental/testing/server";import { NextRequest } from "next/server";import { MULTICA_LOCALE_HEADER } from "./lib/locale-routing";import { config, proxy } from "./proxy";@@ -288,3 +289,16 @@ describe("proxy root and locale handling", () => {).toBe("zh-Hans");});});+++describe("upload route bypasses the buffering proxy", () => {+ it.each(["/api/upload-file", "/api/upload-file/"])(+ "excludes %s from Proxy matching",+ (url) => expect(unstable_doesMiddlewareMatch({ config, url })).toBe(false),+ );++ it.each(["/api", "/api/config", "/api/upload-file-extra", "/v1/issues", "/auth/token", "/docs/intro", "/login"])(+ "keeps the existing proxy behavior for %s",+ (url) => expect(unstable_doesMiddlewareMatch({ config, url })).toBe(true),+ );+});diff --git a/apps/web/proxy.ts b/apps/web/proxy.tsindex 2ebf037c3d..3097d9cf6d 100644--- a/apps/web/proxy.ts+++ b/apps/web/proxy.ts@@ -118,7 +118,9 @@ export const config = {// request time instead of being baked into next.config.js at build time.matcher: ["/v1/:path*",- "/api/:path*",+ // Uploads stream through an App Router handler instead of Proxy's body clone.+ "/api",+ "/api/((?!upload-file(?:/|$)).*)","/auth/:path*","/uploads/:path*","/docs/:path*",diff --git a/server/internal/handler/file.go b/server/internal/handler/file.goindex bf9ae17867..b9a040e984 100644--- a/server/internal/handler/file.go+++ b/server/internal/handler/file.go@@ -35,8 +35,6 @@ var extContentTypes = map[string]string{".wasm": "application/wasm",}-const maxUploadSize = 100 << 20 // 100 MB-const defaultAttachmentDownloadURLTTL = 30 * time.Minutetype attachmentDownloadMode string@@ -380,13 +378,19 @@ func (h *Handler) UploadFile(w http.ResponseWriter, r *http.Request) {workspaceID := h.resolveWorkspaceID(r)- r.Body = http.MaxBytesReader(w, r.Body, maxUploadSize)-- if err := r.ParseMultipartForm(maxUploadSize); err != nil {- writeError(w, http.StatusBadRequest, "file too large or invalid multipart form")+ err := parseUploadForm(w, r)+ if r.MultipartForm != nil {+ defer r.MultipartForm.RemoveAll()+ }+ if err != nil {+ var sizeErr *http.MaxBytesError+ if errors.As(err, &sizeErr) {+ writeError(w, http.StatusRequestEntityTooLarge, "file exceeds the 100 MiB upload limit")+ } else {+ writeError(w, http.StatusBadRequest, "invalid multipart form")+ }return}- defer r.MultipartForm.RemoveAll()file, header, err := r.FormFile("file")if err != nil {diff --git a/server/internal/handler/file_upload_limits.go b/server/internal/handler/file_upload_limits.gonew file mode 100644index 0000000000..3e4f82c26d--- /dev/null+++ b/server/internal/handler/file_upload_limits.go@@ -0,0 +1,22 @@+package handler++import "net/http"++const maxUploadSize = 100 << 20 // 100 MiB per file++// File contents have their own limit; multipart boundaries and metadata+// need extra room within the whole-request cap.+const maxUploadBodySize = maxUploadSize + (1 << 20)++func parseUploadForm(w http.ResponseWriter, r *http.Request) error {+ r.Body = http.MaxBytesReader(w, r.Body, maxUploadBodySize)+ if err := r.ParseMultipartForm(maxUploadSize); err != nil {+ return err+ }+ for _, header := range r.MultipartForm.File["file"] {+ if header.Size > maxUploadSize {+ return &http.MaxBytesError{Limit: maxUploadSize}+ }+ }+ return nil+}diff --git a/server/internal/handler/file_upload_limits_test.go b/server/internal/handler/file_upload_limits_test.gonew file mode 100644index 0000000000..18337c77c6--- /dev/null+++ b/server/internal/handler/file_upload_limits_test.go@@ -0,0 +1,87 @@+package handler++import (+ "bytes"+ "errors"+ "io"+ "mime/multipart"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+)++type uploadZeroReader struct{}++func (uploadZeroReader) Read(p []byte) (int, error) {+ clear(p)+ return len(p), nil+}++func TestParseUploadFormSizeLimits(t *testing.T) {+ for _, tc := range []struct {+ name string+ size int64+ metadataSize int+ wantLimit int64+ }{+ {name: "above Next proxy default", size: 11 << 20},+ {name: "below file limit", size: maxUploadSize - 1},+ {name: "exact file limit with metadata", size: maxUploadSize, metadataSize: 1024},+ {name: "one byte above file limit", size: maxUploadSize + 1, wantLimit: maxUploadSize},+ {name: "request body limit", size: maxUploadSize, metadataSize: 2 << 20, wantLimit: maxUploadBodySize},+ } {+ t.Run(tc.name, func(t *testing.T) {+ var envelope bytes.Buffer+ writer := multipart.NewWriter(&envelope)+ if _, err := writer.CreateFormFile("file", "attachment.bin"); err != nil {+ t.Fatal(err)+ }+ prefixLen := envelope.Len()+ if err := writer.WriteField("description", strings.Repeat("m", tc.metadataSize)); err != nil {+ t.Fatal(err)+ }+ if err := writer.Close(); err != nil {+ t.Fatal(err)+ }+ body := io.MultiReader(bytes.NewReader(envelope.Bytes()[:prefixLen]), io.LimitReader(uploadZeroReader{}, tc.size), bytes.NewReader(envelope.Bytes()[prefixLen:]))+ req := httptest.NewRequest(http.MethodPost, "/api/upload-file", body)+ req.Header.Set("Content-Type", writer.FormDataContentType())+ err := parseUploadForm(httptest.NewRecorder(), req)+ if req.MultipartForm != nil {+ defer req.MultipartForm.RemoveAll()+ }+ if tc.wantLimit != 0 {+ var limitErr *http.MaxBytesError+ if !errors.As(err, &limitErr) || limitErr.Limit != tc.wantLimit {+ t.Fatalf("error = %v, want MaxBytesError with limit %d", err, tc.wantLimit)+ }+ return+ }+ if err != nil {+ t.Fatal(err)+ }+ file, header, err := req.FormFile("file")+ if err != nil {+ t.Fatal(err)+ }+ defer file.Close()+ if header.Size != tc.size {+ t.Fatalf("received %d bytes, want %d", header.Size, tc.size)+ }+ if got := req.FormValue("description"); len(got) != tc.metadataSize {+ t.Fatalf("received %d metadata bytes, want %d", len(got), tc.metadataSize)+ }+ })+ }+}++func TestParseUploadFormMalformed(t *testing.T) {+ req := httptest.NewRequest(http.MethodPost, "/api/upload-file", strings.NewReader("broken multipart"))+ req.Header.Set("Content-Type", "multipart/form-data; boundary=test")+ err := parseUploadForm(httptest.NewRecorder(), req)+ var limitErr *http.MaxBytesError+ if err == nil || errors.As(err, &limitErr) {+ t.Fatalf("expected a malformed multipart error, got %v", err)+ }+}