Skip to content
Open
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
3 changes: 2 additions & 1 deletion src/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -563,7 +563,8 @@ export class HttpRequest extends Macroable {
* exists
*/
if (trustProxy(this.request.socket.remoteAddress!, this.#config.trustProxy)) {
host = this.header('X-Forwarded-Host') || host
const forwardedHost = this.header('X-Forwarded-Host')
host = forwardedHost ? forwardedHost.split(/\s*,\s*/)[0] : host
}

if (!host) {
Expand Down
33 changes: 33 additions & 0 deletions tests/request.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -612,6 +612,39 @@ test.group('Request', () => {
assert.equal(body.ip, '10.10.10.10')
})

test('use the first forwarded host from a trusted proxy', async ({ assert }) => {
const { url } = await httpServer.create((req, res) => {
const request = new HttpRequestFactory()
.merge({
req,
res,
encryption,
config: {
trustProxy: proxyAddr.compile('loopback'),
},
})
.create()
res.writeHead(200, { 'content-type': 'application/json' })
res.end(
JSON.stringify({
host: request.host(),
hostname: request.hostname(),
url: request.completeUrl(),
})
)
})

const { body } = await supertest(url)
.get('/')
.set('x-forwarded-host', 'client.example.test, edge.example.test')

assert.deepEqual(body, {
host: 'client.example.test',
hostname: 'client.example.test',
url: 'http://client.example.test/',
})
})

test('trust all proxies when trustProxy is true', async ({ assert }) => {
const { url } = await httpServer.create((req, res) => {
req.headers['x-forwarded-for'] = '10.10.10.10'
Expand Down