diff --git a/lib/interceptor/dns.js b/lib/interceptor/dns.js index c4fb7da19b5..fc5dc1a4366 100644 --- a/lib/interceptor/dns.js +++ b/lib/interceptor/dns.js @@ -358,7 +358,7 @@ module.exports = interceptorOpts => { servername: origin.hostname, // For SNI on TLS origin: newOrigin, headers: { - host: origin.hostname, + host: origin.host, ...origDispatchOpts.headers } } diff --git a/test/interceptors/dns.js b/test/interceptors/dns.js index a70c67972ad..944c190492e 100644 --- a/test/interceptors/dns.js +++ b/test/interceptors/dns.js @@ -124,7 +124,7 @@ test('Should respect DNS origin hostname for SNI on TLS', async t => { } server.on('request', (req, res) => { - t.equal(req.headers.host, 'localhost') + t.equal(req.headers.host, `localhost:${server.address().port}`) res.writeHead(200, { 'content-type': 'text/plain' }) res.end('hello world!') }) @@ -1731,3 +1731,86 @@ test('Should handle max cached items', async t => { t.equal(response3.statusCode, 200) t.equal(await response3.body.text(), 'hello world! (x2)') }) + +test('#3937 - Handle host correctly', async t => { + t = tspl(t, { plan: 10 }) + + const hostsnames = [] + const server = createServer() + const requestOptions = { + method: 'GET', + path: '/', + headers: { + 'content-type': 'application/json' + } + } + + server.on('request', (req, res) => { + t.equal(req.headers.host, `localhost:${server.address().port}`) + + res.writeHead(200, { 'content-type': 'text/plain' }) + res.end('hello world!') + }) + + server.listen(0) + + await once(server, 'listening') + + const client = new Agent().compose([ + dispatch => { + return (opts, handler) => { + const url = new URL(opts.origin) + + t.equal(hostsnames.includes(url.hostname), false) + + if (url.hostname[0] === '[') { + // [::1] -> ::1 + t.equal(isIP(url.hostname.slice(1, 4)), 6) + } else { + t.equal(isIP(url.hostname), 4) + } + + hostsnames.push(url.hostname) + + return dispatch(opts, handler) + } + }, + dns({ + lookup: (_origin, _opts, cb) => { + cb(null, [ + { + address: '::1', + family: 6 + }, + { + address: '127.0.0.1', + family: 4 + } + ]) + } + }) + ]) + + after(async () => { + await client.close() + server.close() + + await once(server, 'close') + }) + + const response = await client.request({ + ...requestOptions, + origin: `http://localhost:${server.address().port}` + }) + + t.equal(response.statusCode, 200) + t.equal(await response.body.text(), 'hello world!') + + const response2 = await client.request({ + ...requestOptions, + origin: `http://localhost:${server.address().port}` + }) + + t.equal(response2.statusCode, 200) + t.equal(await response2.body.text(), 'hello world!') +})