Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
176 changes: 113 additions & 63 deletions lib/read-body.js
Original file line number Diff line number Diff line change
@@ -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'))
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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)
Expand All @@ -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.`
Expand Down Expand Up @@ -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(() => {})

Expand Down
56 changes: 56 additions & 0 deletions test/aborted-requests.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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', () => {})
})
})
})
80 changes: 80 additions & 0 deletions test/error-handling.js
Original file line number Diff line number Diff line change
Expand Up @@ -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')

Expand Down Expand Up @@ -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 }, [
Expand Down