diff --git a/server/src/__tests__/error-handler-client-abort.test.ts b/server/src/__tests__/error-handler-client-abort.test.ts index 075d732bd39..cc1b12606ef 100644 --- a/server/src/__tests__/error-handler-client-abort.test.ts +++ b/server/src/__tests__/error-handler-client-abort.test.ts @@ -1,5 +1,6 @@ -import { createServer } from "node:http"; +import { createServer, request as httpRequest } from "node:http"; import express from "express"; +import multer from "multer"; import request from "supertest"; import { beforeEach, describe, expect, it, vi } from "vitest"; import { errorHandler } from "../middleware/error-handler.js"; @@ -47,6 +48,59 @@ function createApp(onReadStarted: () => void, onErrorHandled: (err: unknown) => return app; } +/** An upload route whose multipart parsing failures reach the error handler. */ +function createUploadApp(onUploadStarted: () => void, onErrorHandled: (err: unknown) => void) { + const app = express(); + const upload = multer({ storage: multer.memoryStorage() }); + app.post( + "/upload", + (_req, _res, next) => { + onUploadStarted(); + next(); + }, + upload.single("file"), + (_req, res) => { + res.status(201).end(); + }, + ); + // A route that throws the same text while its client is still connected. + app.post("/upload-failure", () => { + throw new Error("Request aborted"); + }); + app.use((err: unknown, req: express.Request, res: express.Response, next: express.NextFunction) => { + try { + errorHandler(err, req, res, next); + } finally { + onErrorHandled(err); + } + }); + return app; +} + +/** Starts a multipart upload, sends part of the file, then drops the connection. */ +async function abandonUpload(baseUrl: string, uploadStarted: Promise) { + const boundary = "paperclip-client-abort"; + const head = [ + `--${boundary}`, + 'Content-Disposition: form-data; name="file"; filename="large.bin"', + "Content-Type: application/octet-stream", + "", + "", + ].join("\r\n"); + const clientRequest = httpRequest(`${baseUrl}/upload`, { + method: "POST", + headers: { + "content-type": `multipart/form-data; boundary=${boundary}`, + "content-length": String(10 * 1024 * 1024), + }, + }); + clientRequest.on("error", () => {}); + clientRequest.write(head); + clientRequest.write(Buffer.alloc(64 * 1024, 1)); + await uploadStarted; + clientRequest.destroy(); +} + async function withServer(app: express.Express, run: (baseUrl: string) => Promise) { const server = createServer(app); await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); @@ -97,4 +151,27 @@ describe("errorHandler client aborts", () => { message: "Request aborted", })); }); + + it("does not report an upload the client abandoned mid-body", async () => { + let uploadStarted!: () => void; + const started = new Promise((resolve) => { uploadStarted = resolve; }); + let errorHandled!: (err: unknown) => void; + const handled = new Promise((resolve) => { errorHandled = resolve; }); + await withServer(createUploadApp(() => uploadStarted(), (err) => errorHandled(err)), async (baseUrl) => { + await abandonUpload(baseUrl, started); + // multer rejects with a plain Error once Node reports the aborted request. + await expect(handled).resolves.toMatchObject({ message: expect.stringMatching(/^Request (aborted|closed)$/) }); + }); + + expect(captureExceptionMock).not.toHaveBeenCalled(); + }); + + it("still reports a request-aborted error while the client is connected", async () => { + await withServer(createUploadApp(() => {}, () => {}), async (baseUrl) => { + const response = await request(baseUrl).post("/upload-failure"); + expect(response.status).toBe(500); + }); + + expect(captureExceptionMock).toHaveBeenCalledWith(expect.objectContaining({ message: "Request aborted" })); + }); }); diff --git a/server/src/middleware/error-handler.ts b/server/src/middleware/error-handler.ts index 72dc2c937ad..7f88aea10a2 100644 --- a/server/src/middleware/error-handler.ts +++ b/server/src/middleware/error-handler.ts @@ -315,6 +315,16 @@ export function errorHandler( return; } + // multer (multipart uploads) rejects with a plain `Error: Request aborted` or + // `Error: Request closed` when the client drops the connection before the + // body ends. Treat it as a disconnect only when the request stream really + // stopped early, so the same text from a connected request is still reported. + if (isMultipartClientDisconnect(rootError, req)) { + if (!res.headersSent) res.status(499); + res.end(); + return; + } + // A route that cancels its work when the response closes (for example a // storage read) rejects with AbortError after the client has gone. That // rejection is the cancellation, not a server fault. An AbortError while @@ -403,6 +413,17 @@ export function errorHandler( }); } +const MULTIPART_CLIENT_DISCONNECT_MESSAGES = new Set(["Request aborted", "Request closed"]); + +function isMultipartClientDisconnect(error: Error, req: Request) { + return ( + error.name === "Error" && + MULTIPART_CLIENT_DISCONNECT_MESSAGES.has(error.message) && + (error as NodeJS.ErrnoException).code === undefined && + req.readableAborted === true + ); +} + function shouldExposeTrustedCloudTenantImportError(req: Request) { return ( req.actor?.source === "cloud_tenant" &&