Skip to content

Commit

Permalink
allow only one host header (#507)
Browse files Browse the repository at this point in the history
  • Loading branch information
cberescu committed Jan 8, 2024
1 parent 2fc4c8f commit 75cbb4d
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 8 deletions.
17 changes: 9 additions & 8 deletions lib/httpRequestBuilder.js
Expand Up @@ -45,14 +45,21 @@ function requestBuilder (defaults) {
const headers = reqData.headers
const body = reqData.body

let host = getPropertyCaseInsensitive(reqData.headers, 'host') || reqData.host
const headersDefinedHost = getPropertyCaseInsensitive(reqData.headers, 'host')
let host = headersDefinedHost || reqData.host

if (!host) {
const hostname = reqData.hostname
const port = reqData.port
host = hostname + ':' + port
}

const baseReq = [
`${method} ${path} HTTP/1.1`
]
if (!headersDefinedHost) {
baseReq.push(`Host: ${host}`)
}
baseReq.push('Connection: keep-alive')
if (reqData.auth) {
const encodedAuth = Buffer.from(reqData.auth).toString('base64')
headers.Authorization = `Basic ${encodedAuth}`
Expand All @@ -62,12 +69,6 @@ function requestBuilder (defaults) {
throw new Error(`${method} HTTP method is not supported`)
}

const baseReq = [
`${method} ${path} HTTP/1.1`,
`Host: ${host}`,
'Connection: keep-alive'
]

let bodyBuf

if (typeof body === 'string') {
Expand Down
17 changes: 17 additions & 0 deletions test/httpRequestBuilder.test.js
Expand Up @@ -99,6 +99,23 @@ test('request builder should add a Content-Length header when the body buffer ex
'request is okay')
})

test('request builder should add only one HOST header', (t) => {
t.plan(1)

const opts = server.address()
opts.method = 'POST'
opts.headers = {
Host: 'example.com'
}

const build = RequestBuilder(opts)

const result = build({ body: 'body' })
t.same(result,
Buffer.from('POST / HTTP/1.1\r\nConnection: keep-alive\r\nHost: example.com\r\nContent-Length: 4\r\n\r\nbody'),
'request is okay')
})

test('request builder should add a Content-Length header with correct calculated value when the body buffer exists and idReplacement is enabled as a default override', (t) => {
t.plan(1)

Expand Down

0 comments on commit 75cbb4d

Please sign in to comment.