Skip to content

Commit 75c0d69

Browse files
mmrwoodsfilmaj
andauthored
fix: body parser behaviour when multiple Content-Type present in HTTP request (#562)
Fixes #568 * Fix body parser to handle borked content type * add extra comment, linting --------- Co-authored-by: filmaj <[email protected]>
1 parent f695ab4 commit 75c0d69

File tree

2 files changed

+17
-6
lines changed

2 files changed

+17
-6
lines changed

src/http/helpers/body-parser.js

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ module.exports = function parseBody (req) {
1414
// Paranoid deep copy
1515
let request = JSON.parse(JSON.stringify(req))
1616
let headers = request.headers
17+
// Note: content-type header may have multiple, comma-separated values. matching w/ includes may match to multiple different types
1718
let contentType = type => headers?.['content-type']?.includes(type) || headers?.['Content-Type']?.includes(type)
1819

1920
let isString = typeof request.body === 'string'
@@ -39,17 +40,14 @@ module.exports = function parseBody (req) {
3940
throw Error('Invalid request body encoding or invalid JSON')
4041
}
4142
}
42-
43-
if (isPlainText || isXml) {
43+
else if (isPlainText || isXml) {
4444
request.body = new Buffer.from(request.body, 'base64').toString()
4545
}
46-
47-
if (isFormURLEncoded) {
46+
else if (isFormURLEncoded) {
4847
let data = new Buffer.from(request.body, 'base64').toString()
4948
request.body = qs.parse(data)
5049
}
51-
52-
if (isMultiPartFormData || isOctetStream) {
50+
else if (isMultiPartFormData || isOctetStream) {
5351
request.body = request.body.base64
5452
? request.body
5553
: { base64: request.body }

test/unit/src/http/helpers/body-parser-test.js

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,19 @@ let octetStream = { 'Content-Type': 'application/octet-stream' }
2020
let text = { 'Content-Type': 'text/plain' }
2121
let xmlText = { 'Content-Type': 'text/xml' }
2222
let xmlApp = { 'Content-Type': 'application/xml' }
23+
let multipleTypes = { 'Content-Type': 'application/json, text/plain' }
24+
25+
test('Borked requests', t => {
26+
t.plan(1)
27+
28+
let req = {
29+
body: str(hi),
30+
headers: multipleTypes,
31+
isBase64Encoded: false,
32+
}
33+
t.equals(str(parseBody(req)), str(hi), `body matches ${str(req.body)}`)
34+
35+
})
2336

2437
test('Architect v10+ requests', t => {
2538
t.plan(6)

0 commit comments

Comments
 (0)