Skip to content

Commit

Permalink
fix: ProxyAgent causes request.headers.host to be forcibly reset (#3026)
Browse files Browse the repository at this point in the history
* fix: ProxyAgent causes request.headers.host to be forcibly reset

* test: add proxy-agent test

* fix: passing correct host headers to proxy

* fix: Inconsistent initialization of host for different spellings
  • Loading branch information
1zilc committed Apr 4, 2024
1 parent 5f3ec97 commit 744c9b7
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 9 deletions.
20 changes: 11 additions & 9 deletions lib/dispatcher/proxy-agent.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,19 +64,19 @@ class ProxyAgent extends DispatcherBase {
this[kAgent] = new Agent({
...opts,
connect: async (opts, callback) => {
let requestedHost = opts.host
let requestedPath = opts.host
if (!opts.port) {
requestedHost += `:${defaultProtocolPort(opts.protocol)}`
requestedPath += `:${defaultProtocolPort(opts.protocol)}`
}
try {
const { socket, statusCode } = await this[kClient].connect({
origin,
port,
path: requestedHost,
path: requestedPath,
signal: opts.signal,
headers: {
...this[kProxyHeaders],
host: requestedHost
host: opts.host
},
servername: this[kProxyTls]?.servername || proxyHostname
})
Expand Down Expand Up @@ -108,16 +108,18 @@ class ProxyAgent extends DispatcherBase {
}

dispatch (opts, handler) {
const { host } = new URL(opts.origin)
const headers = buildHeaders(opts.headers)
throwIfProxyAuthIsSent(headers)

if (headers && !('host' in headers) && !('Host' in headers)) {
const { host } = new URL(opts.origin)
headers.host = host
}

return this[kAgent].dispatch(
{
...opts,
headers: {
...headers,
host
}
headers
},
handler
)
Expand Down
29 changes: 29 additions & 0 deletions test/proxy-agent.js
Original file line number Diff line number Diff line change
Expand Up @@ -842,6 +842,35 @@ test('Proxy via HTTPS to HTTP fails on wrong SNI', async (t) => {
proxyAgent.close()
})

test('ProxyAgent keeps customized host in request headers - #3019', async (t) => {
t = tspl(t, { plan: 2 })
const server = await buildServer()
const proxy = await buildProxy()

const serverUrl = `http://localhost:${server.address().port}`
const proxyUrl = `http://localhost:${proxy.address().port}`
const proxyAgent = new ProxyAgent(proxyUrl)
const customHost = 'example.com'

proxy.on('connect', (req) => {
t.strictEqual(req.headers.host, `localhost:${server.address().port}`)
})

server.on('request', (req, res) => {
t.strictEqual(req.headers.host, customHost)
res.end()
})

await request(serverUrl, {
headers: { Host: customHost },
dispatcher: proxyAgent
})

server.close()
proxy.close()
proxyAgent.close()
})

function buildServer () {
return new Promise((resolve) => {
const server = createServer()
Expand Down

0 comments on commit 744c9b7

Please sign in to comment.