Skip to content

Commit b93ffd4

Browse files
iconoeugendougwilson
authored andcommitted
Support multiple hosts in X-Forwarded-Host
fixes #3494 closes #3495
1 parent 8da5110 commit b93ffd4

File tree

3 files changed

+55
-0
lines changed

3 files changed

+55
-0
lines changed

History.md

+1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ unreleased
33

44
* Improve error message for non-strings to `res.sendFile`
55
* Improve error message for `null`/`undefined` to `res.status`
6+
* Support multiple hosts in `X-Forwarded-Host`
67

78
4.16.4 / 2018-10-10
89
===================

lib/request.js

+4
Original file line numberDiff line numberDiff line change
@@ -430,6 +430,10 @@ defineGetter(req, 'hostname', function hostname(){
430430

431431
if (!host || !trust(this.connection.remoteAddress, 0)) {
432432
host = this.get('Host');
433+
} else if (host.indexOf(',') !== -1) {
434+
// Note: X-Forwarded-Host is normally only ever a
435+
// single value, but this is to be safe.
436+
host = host.substring(0, host.indexOf(',')).trimRight()
433437
}
434438

435439
if (!host) return;

test/req.hostname.js

+50
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,56 @@ describe('req', function(){
116116
.set('Host', 'example.com')
117117
.expect('example.com', done);
118118
})
119+
120+
describe('when multiple X-Forwarded-Host', function () {
121+
it('should use the first value', function (done) {
122+
var app = express()
123+
124+
app.enable('trust proxy')
125+
126+
app.use(function (req, res) {
127+
res.send(req.hostname)
128+
})
129+
130+
request(app)
131+
.get('/')
132+
.set('Host', 'localhost')
133+
.set('X-Forwarded-Host', 'example.com, foobar.com')
134+
.expect(200, 'example.com', done)
135+
})
136+
137+
it('should remove OWS around comma', function (done) {
138+
var app = express()
139+
140+
app.enable('trust proxy')
141+
142+
app.use(function (req, res) {
143+
res.send(req.hostname)
144+
})
145+
146+
request(app)
147+
.get('/')
148+
.set('Host', 'localhost')
149+
.set('X-Forwarded-Host', 'example.com , foobar.com')
150+
.expect(200, 'example.com', done)
151+
})
152+
153+
it('should strip port number', function (done) {
154+
var app = express()
155+
156+
app.enable('trust proxy')
157+
158+
app.use(function (req, res) {
159+
res.send(req.hostname)
160+
})
161+
162+
request(app)
163+
.get('/')
164+
.set('Host', 'localhost')
165+
.set('X-Forwarded-Host', 'example.com:8080 , foobar.com:8888')
166+
.expect(200, 'example.com', done)
167+
})
168+
})
119169
})
120170

121171
describe('when "trust proxy" is disabled', function(){

0 commit comments

Comments
 (0)