Skip to content

Commit adfeaf6

Browse files
committed
🥅 improve error handling
1 parent e259a7e commit adfeaf6

File tree

2 files changed

+52
-5
lines changed

2 files changed

+52
-5
lines changed

lib/make-middleware.js

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,15 @@ function makeMiddleware (setup) {
101101

102102
// handle files
103103
busboy.on('file', function (fieldname, fileStream, { filename, encoding, mimeType }) {
104+
var pendingWritesIncremented = false
105+
106+
fileStream.on('error', function (err) {
107+
if (pendingWritesIncremented) {
108+
pendingWrites.decrement()
109+
}
110+
abortWithError(err)
111+
})
112+
104113
if (fieldname == null) return abortWithCode('MISSING_FIELD_NAME')
105114

106115
// don't attach to the files object, if there is no file
@@ -132,6 +141,7 @@ function makeMiddleware (setup) {
132141
}
133142

134143
var aborting = false
144+
pendingWritesIncremented = true
135145
pendingWrites.increment()
136146

137147
Object.defineProperty(file, 'stream', {
@@ -140,11 +150,6 @@ function makeMiddleware (setup) {
140150
value: fileStream
141151
})
142152

143-
fileStream.on('error', function (err) {
144-
pendingWrites.decrement()
145-
abortWithError(err)
146-
})
147-
148153
fileStream.on('limit', function () {
149154
aborting = true
150155
abortWithCode('LIMIT_FILE_SIZE', fieldname)

test/express-integration.js

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,4 +196,46 @@ describe('Express Integration', function () {
196196
req.write(body)
197197
req.end()
198198
})
199+
200+
it('should not crash on malformed multipart body with bad boundary', function (done) {
201+
var upload = multer()
202+
203+
app.post('/upload3', upload.single('image'), function (req, res) {
204+
res.status(500).end('Request should not be processed')
205+
})
206+
207+
app.use(function (err, req, res, next) {
208+
assert.strictEqual(err.message, 'Unexpected end of form')
209+
res.status(200).end('Correct error')
210+
})
211+
212+
var boundary = '----FormBoundary'
213+
var body = [
214+
'------FormBoundary',
215+
'Content-Disposition: form-data; name="image"; filename=""',
216+
'Content-Type: application/octet-stream',
217+
'',
218+
'', // empty content
219+
'------FormBoundar' // intentionally malformed final boundary (missing 'y')
220+
].join('\r\n')
221+
222+
var options = {
223+
hostname: 'localhost',
224+
port,
225+
path: '/upload3',
226+
method: 'POST',
227+
headers: {
228+
'Content-Type': 'multipart/form-data; boundary=' + boundary,
229+
'Content-Length': Buffer.byteLength(body)
230+
}
231+
}
232+
233+
var req = http.request(options, (res) => {
234+
assert.strictEqual(res.statusCode, 200)
235+
done()
236+
})
237+
238+
req.write(body)
239+
req.end()
240+
})
199241
})

0 commit comments

Comments
 (0)