Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: ProxyAgent causes request.headers.host to be forcibly reset #3026

Merged
merged 4 commits into from
Apr 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading