From d9aabc4f099113944f990a84cdeb1e36072fd0ab Mon Sep 17 00:00:00 2001 From: Dmitry Ostrikov Date: Mon, 2 Mar 2026 18:09:03 +0400 Subject: [PATCH] feat: port upstream security fixes 739919097dde3921ec31b930e4b9025036fa74ee cccf0fe0e64150c4f42ccf6654165c0d66b9adab --- lib/read-body.js | 176 +++++++++++++++++++++++++-------------- test/aborted-requests.js | 56 +++++++++++++ test/error-handling.js | 80 ++++++++++++++++++ 3 files changed, 249 insertions(+), 63 deletions(-) diff --git a/lib/read-body.js b/lib/read-body.js index 43c2a7c1..bc29e9d1 100644 --- a/lib/read-body.js +++ b/lib/read-body.js @@ -1,8 +1,9 @@ const { extname } = require('path') +const fs = require('fs') const Busboy = require('@fastify/busboy') const FileType = require('file-type') const { MulterError, Codes } = require('./error') -const { createReadStream } = require('fs') +const { createReadStream } = fs const stream = require('stream') const { promisify } = require('util') const finished = promisify(require('on-finished')) @@ -48,82 +49,118 @@ const collectFields = (busboy, limits) => new Promise((resolve, reject) => { let createWriteStream -const collectFiles = (busboy, limits, fileFilter) => new Promise((resolve, reject) => { +const collectFiles = (busboy, limits, fileFilter) => { const fileTasks = [] + const tempFiles = new Set() + let errorOccured = false - busboy.on('file', async (fieldname, fileStream, filename, encoding, mimetype) => { - if (fieldname == null || fieldname === '') { - fileStream.resume() - return reject(new MulterError( - Codes.MISSING_FIELD_NAME, - 'Field name is required.' - )) - } + const rejectOnce = (reject, err) => { + if (errorOccured) return + errorOccured = true + reject(err) + } - if ( - typeof limits.fieldNameSize === 'number' && - fieldname.length > limits.fieldNameSize - ) { - return reject(new MulterError( - Codes.LIMIT_FIELD_KEY, - `The multipart field name exceeds the ${limits.fieldNameSize} byte size limit.` - )) - } + const promise = new Promise((resolve, reject) => { + const _reject = rejectOnce.bind(null, reject) - // Catch all errors on file stream - fileStream.once('error', reject) + busboy.on('file', async (fieldname, fileStream, filename, encoding, mimetype) => { + if (fieldname == null || fieldname === '') { + fileStream.resume() + return _reject(new MulterError( + Codes.MISSING_FIELD_NAME, + 'Field name is required.' + )) + } - // Catch limit exceeded on file stream - fileStream.once('limit', () => - reject(new MulterError( - Codes.LIMIT_FILE_SIZE, - `File truncated as it exceeds the ${limits.fileSize} byte size limit.`, - fieldname - ))) - - const file = { - fieldName: fieldname, - originalName: filename, - clientReportedMimeType: mimetype, - clientReportedFileExtension: extname(filename || ''), - toStream () { - return this.path ? createReadStream(this.path) : stream.Readable.from([]) + if ( + typeof limits.fieldNameSize === 'number' && + fieldname.length > limits.fieldNameSize + ) { + fileStream.resume() + return _reject(new MulterError( + Codes.LIMIT_FIELD_KEY, + `The multipart field name exceeds the ${limits.fieldNameSize} byte size limit.` + )) } - } - try { - fileFilter.filter(file) - } catch (err) { - return reject(err) - } + if (errorOccured) { + return fileStream.resume() + } - if (!createWriteStream) { - ({ createWriteStream } = await import('fs-temp')) - } + // Catch all errors on file stream + fileStream.once('error', _reject) - const target = createWriteStream() + // Catch limit exceeded on file stream + fileStream.once('limit', () => + _reject(new MulterError( + Codes.LIMIT_FILE_SIZE, + `File truncated as it exceeds the ${limits.fileSize} byte size limit.`, + fieldname + ))) + + const file = { + fieldName: fieldname, + originalName: filename, + clientReportedMimeType: mimetype, + clientReportedFileExtension: extname(filename || ''), + toStream () { + return this.path ? createReadStream(this.path) : stream.Readable.from([]) + } + } - const fileTask = FileType.stream(fileStream) - .then((stream) => { - file.detectedMimeType = (stream.fileType ? stream.fileType.mime : null) - file.detectedFileExtension = (stream.fileType ? `.${stream.fileType.ext}` : '') + try { + fileFilter.filter(file) + } catch (err) { + fileStream.resume() + return _reject(err) + } - return pipeline(stream, target) - }) - .then(() => { - file.path = target.path - file.size = target.bytesWritten + if (!createWriteStream) { + ({ createWriteStream } = await import('fs-temp')) + } - return file - }) - .catch(reject) - .finally(() => fileStream.resume()) + // Re-check after the async import — an error may have occurred in the meantime + if (errorOccured) { + return fileStream.resume() + } - fileTasks.push(fileTask) + const target = createWriteStream() + + // Track the temp file path so the caller can clean it up on error + tempFiles.add(target.path) + + const fileTask = FileType.stream(fileStream) + .then((stream) => { + file.detectedMimeType = (stream.fileType ? stream.fileType.mime : null) + file.detectedFileExtension = (stream.fileType ? `.${stream.fileType.ext}` : '') + + return pipeline(stream, target) + }) + .then(() => { + file.path = target.path + file.size = target.bytesWritten + + return file + }) + .catch(_reject) + .finally(() => fileStream.resume()) + + fileTasks.push(fileTask) + }) + + busboy.once('finish', () => { + resolve( + Promise.all(fileTasks).then((files) => { + // All files successfully written — caller owns them, clear tracking + tempFiles.clear() + return files + }) + ) + }) }) - busboy.once('finish', () => resolve(Promise.all(fileTasks))) -}) + return { promise, tempFiles } +} const DEFAULT_LIMITS = { fieldNameSize: 100, @@ -152,7 +189,7 @@ const readBody = async (req, limits, fileFilter) => { } const fields = collectFields(busboy, limits) - const files = collectFiles(busboy, limits, fileFilter) + const { promise: files, tempFiles } = collectFiles(busboy, limits, fileFilter) const guard = new Promise((resolve, reject) => { req.once('error', reject) busboy.once('error', reject) @@ -161,6 +198,14 @@ const readBody = async (req, limits, fileFilter) => { Codes.CLIENT_CLOSED_REQUEST, 'Request disconnected during file upload stream parsing.' ))) + + req.on('close', () => { + if (req.readableEnded) return + reject(new MulterError( + Codes.CLIENT_CLOSED_REQUEST, + 'Request disconnected during file upload stream parsing.' + )) + }) busboy.once('partsLimit', () => reject(new MulterError( Codes.LIMIT_PART_COUNT, `${limits.parts} max parts exceeded.` @@ -189,6 +234,11 @@ const readBody = async (req, limits, fileFilter) => { setImmediate(() => busboy.removeAllListeners()) setImmediate(() => req.resume()) + // Clean up any temp files that were written but will never be returned to the caller + for (const tmpPath of tempFiles) { + fs.unlink(tmpPath, () => {}) + } + // Wait for request to close, finish, or error await finished(req).catch(() => {}) diff --git a/test/aborted-requests.js b/test/aborted-requests.js index ac0e3f28..bb6a8519 100644 --- a/test/aborted-requests.js +++ b/test/aborted-requests.js @@ -4,6 +4,8 @@ const FormData = require('form-data') const PassThrough = require('stream').PassThrough const pify = require('pify') const assert = require('assert') +const http = require('http') +const net = require('net') function getLength (form) { return pify(form.getLength).call(form) @@ -51,4 +53,58 @@ describe('Aborted requests', () => { return assert.rejects(result, err => err.code === Codes.CLIENT_CLOSED_REQUEST) }) + + it('should not hang when client disconnects mid-upload (close event)', function (done) { + this.timeout(5000) + + const upload = new Multer().any() + + const server = http.createServer((req, res) => { + let hung = false + + const timer = setTimeout(() => { + hung = true + server.close() + done(new Error('Middleware hung when client disconnected')) + }, 1000) + + pify(upload)(req, res).then( + () => { + if (hung) return + clearTimeout(timer) + server.close() + done() + }, + () => { + if (hung) return + clearTimeout(timer) + server.close() + done() + } + ) + }) + + server.listen(0, () => { + const port = server.address().port + const boundary = 'PoC' + Date.now() + const sock = new net.Socket() + + sock.connect(port, '127.0.0.1', () => { + sock.write( + 'POST / HTTP/1.1\r\n' + + 'Host: localhost\r\n' + + `Content-Type: multipart/form-data; boundary=${boundary}\r\n` + + 'Content-Length: 999999\r\n\r\n' + + `--${boundary}\r\n` + + 'Content-Disposition: form-data; name="file"; filename="test.bin"\r\n' + + 'Content-Type: application/octet-stream\r\n\r\n' + + 'AAAAAAAAAAAAAAAA' + ) + + setTimeout(() => sock.destroy(), 50) + }) + + sock.on('error', () => {}) + }) + }) }) diff --git a/test/error-handling.js b/test/error-handling.js index 8b4c02c1..589a964f 100644 --- a/test/error-handling.js +++ b/test/error-handling.js @@ -2,6 +2,9 @@ const FormData = require('form-data') const pify = require('pify') const assert = require('assert') const stream = require('stream') +const fs = require('fs') +const os = require('os') +const path = require('path') const util = require('./_util') const { Multer, Codes } = require('../lib') @@ -71,6 +74,83 @@ describe('Error Handling', () => { ) }) + it('should not leave orphaned temp files when an error occurs during multi-file upload', async () => { + // Upload two files with a files:1 limit — busboy emits filesLimit after + // the first file, so the first file's temp write is in-flight or complete + // when the error is raised. The cleanup must unlink it. + const tmpDir = os.tmpdir() + const before = new Set(fs.readdirSync(tmpDir)) + + const form = new FormData() + form.append('file', util.file('large')) + form.append('file2', util.file('tiny')) + + const parser = new Multer({ limits: { files: 1 } }).any() + const length = await pify(form.getLength).call(form) + const req = new stream.PassThrough() + + req.headers = { + 'content-type': `multipart/form-data; boundary=${form.getBoundary()}`, + 'content-length': length + } + + await assert.rejects( + pify(parser)(form.pipe(req), null), + err => err.code === Codes.LIMIT_FILE_COUNT + ) + + // Wait a tick for async fs.unlink callbacks to settle + await new Promise(resolve => setImmediate(resolve)) + + const after = new Set(fs.readdirSync(tmpDir)) + const leaked = [...after].filter(f => !before.has(f)) + + assert.strictEqual( + leaked.length, + 0, + `Orphaned temp files left behind: ${leaked.map(f => path.join(tmpDir, f)).join(', ')}` + ) + }) + + it('should not leave orphaned temp files when fileFilter rejects a file', async () => { + // Trigger LIMIT_UNEXPECTED_FILE (fileFilter throws synchronously) while a + // valid file is already in flight — the valid file's temp write must be + // cleaned up because the caller never receives it. + const tmpDir = os.tmpdir() + const before = new Set(fs.readdirSync(tmpDir)) + + const form = new FormData() + form.append('allowed', util.file('large')) // valid field + form.append('blocked', util.file('tiny')) // unexpected field → throws + + // Only 'allowed' is permitted + const parser = new Multer().fields([{ name: 'allowed', maxCount: 1 }]) + + const length = await pify(form.getLength).call(form) + const req = new stream.PassThrough() + + req.headers = { + 'content-type': `multipart/form-data; boundary=${form.getBoundary()}`, + 'content-length': length + } + + await assert.rejects( + pify(parser)(form.pipe(req), null), + err => err.code === Codes.LIMIT_UNEXPECTED_FILE + ) + + await new Promise(resolve => setImmediate(resolve)) + + const after = new Set(fs.readdirSync(tmpDir)) + const leaked = [...after].filter(f => !before.has(f)) + + assert.strictEqual( + leaked.length, + 0, + `Orphaned temp files left behind: ${leaked.map(f => path.join(tmpDir, f)).join(', ')}` + ) + }) + it('should respect file key limit', async () => { const form = new FormData() const parser = withLimits({ fieldNameSize: 4 }, [