Skip to content

Commit b416dd6

Browse files
authored
Validate headers value (#73)
Validate headers value
2 parents 128ed98 + 3d7e724 commit b416dd6

File tree

2 files changed

+51
-1
lines changed

2 files changed

+51
-1
lines changed

lib/request.js

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
const { Readable } = require('readable-stream')
66
const util = require('util')
77
const cookie = require('cookie')
8+
const assert = require('assert')
89

910
const parseURL = require('./parseURL')
1011

@@ -46,7 +47,9 @@ function Request (options) {
4647
this.headers = {}
4748
const headers = options.headers || {}
4849
Object.keys(headers).forEach((field) => {
49-
this.headers[field.toLowerCase()] = headers[field]
50+
const value = headers[field]
51+
assert(value !== undefined, 'invalid value "undefined" for header ' + field)
52+
this.headers[field.toLowerCase()] = '' + value
5053
})
5154

5255
this.headers['user-agent'] = this.headers['user-agent'] || 'lightMyRequest'

test/test.js

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1430,3 +1430,50 @@ test('read cookie', (t) => {
14301430
])
14311431
})
14321432
})
1433+
1434+
test('correctly handles no string headers', (t) => {
1435+
t.plan(2)
1436+
const dispatch = function (req, res) {
1437+
res.writeHead(200, { 'Content-Type': 'application/json' })
1438+
res.end(JSON.stringify(req.headers))
1439+
}
1440+
1441+
const date = new Date(0)
1442+
const headers = {
1443+
integer: 12,
1444+
float: 3.14,
1445+
null: null,
1446+
string: 'string',
1447+
object: { foo: 'bar' },
1448+
array: [1, 'two', 3],
1449+
date,
1450+
true: true,
1451+
false: false
1452+
}
1453+
1454+
inject(dispatch, { method: 'GET', url: 'http://example.com:8080/hello', headers }, (err, res) => {
1455+
t.error(err)
1456+
t.deepEqual(JSON.parse(res.payload), {
1457+
integer: '12',
1458+
float: '3.14',
1459+
null: 'null',
1460+
string: 'string',
1461+
object: '[object Object]',
1462+
array: '1,two,3',
1463+
date: date.toString(),
1464+
true: 'true',
1465+
false: 'false',
1466+
host: 'example.com:8080',
1467+
'user-agent': 'lightMyRequest'
1468+
})
1469+
})
1470+
})
1471+
1472+
test('errors for invalid undefined header value', (t) => {
1473+
t.plan(1)
1474+
try {
1475+
inject((req, res) => {}, { url: '/', headers: { 'header-key': undefined } }, () => {})
1476+
} catch (err) {
1477+
t.ok(err)
1478+
}
1479+
})

0 commit comments

Comments
 (0)