Skip to content

Commit

Permalink
Validate headers value (#73)
Browse files Browse the repository at this point in the history
Validate headers value
  • Loading branch information
delvedor authored Feb 3, 2020
2 parents 128ed98 + 3d7e724 commit b416dd6
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 1 deletion.
5 changes: 4 additions & 1 deletion lib/request.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
const { Readable } = require('readable-stream')
const util = require('util')
const cookie = require('cookie')
const assert = require('assert')

const parseURL = require('./parseURL')

Expand Down Expand Up @@ -46,7 +47,9 @@ function Request (options) {
this.headers = {}
const headers = options.headers || {}
Object.keys(headers).forEach((field) => {
this.headers[field.toLowerCase()] = headers[field]
const value = headers[field]
assert(value !== undefined, 'invalid value "undefined" for header ' + field)
this.headers[field.toLowerCase()] = '' + value
})

this.headers['user-agent'] = this.headers['user-agent'] || 'lightMyRequest'
Expand Down
47 changes: 47 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1430,3 +1430,50 @@ test('read cookie', (t) => {
])
})
})

test('correctly handles no string headers', (t) => {
t.plan(2)
const dispatch = function (req, res) {
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify(req.headers))
}

const date = new Date(0)
const headers = {
integer: 12,
float: 3.14,
null: null,
string: 'string',
object: { foo: 'bar' },
array: [1, 'two', 3],
date,
true: true,
false: false
}

inject(dispatch, { method: 'GET', url: 'http://example.com:8080/hello', headers }, (err, res) => {
t.error(err)
t.deepEqual(JSON.parse(res.payload), {
integer: '12',
float: '3.14',
null: 'null',
string: 'string',
object: '[object Object]',
array: '1,two,3',
date: date.toString(),
true: 'true',
false: 'false',
host: 'example.com:8080',
'user-agent': 'lightMyRequest'
})
})
})

test('errors for invalid undefined header value', (t) => {
t.plan(1)
try {
inject((req, res) => {}, { url: '/', headers: { 'header-key': undefined } }, () => {})
} catch (err) {
t.ok(err)
}
})

0 comments on commit b416dd6

Please sign in to comment.