Skip to content

Commit

Permalink
fix: use X-Forwarded-Host first on app.proxy present (#1263)
Browse files Browse the repository at this point in the history
  • Loading branch information
fengmk2 authored and dead-horse committed Oct 23, 2018
1 parent e01cc5a commit 4964242
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 4 deletions.
6 changes: 4 additions & 2 deletions lib/request.js
Original file line number Diff line number Diff line change
Expand Up @@ -252,8 +252,10 @@ module.exports = {
get host() {
const proxy = this.app.proxy;
let host = proxy && this.get('X-Forwarded-Host');
if (this.req.httpVersionMajor >= 2) host = this.get(':authority');
host = host || this.get('Host');
if (!host) {
if (this.req.httpVersionMajor >= 2) host = this.get(':authority');
if (!host) host = this.get('Host');
}
if (!host) return '';
return host.split(/\s*,\s*/)[0];
},
Expand Down
27 changes: 25 additions & 2 deletions test/request/host.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,22 +53,45 @@ describe('req.host', () => {

describe('when X-Forwarded-Host is present', () => {
describe('and proxy is not trusted', () => {
it('should be ignored', () => {
it('should be ignored on HTTP/1', () => {
const req = request();
req.header['x-forwarded-host'] = 'bar.com';
req.header.host = 'foo.com';
assert.equal(req.host, 'foo.com');
});

it('should be ignored on HTTP/2', () => {
const req = request({
'httpVersionMajor': 2,
'httpVersion': '2.0'
});
req.header['x-forwarded-host'] = 'proxy.com:8080';
req.header[':authority'] = 'foo.com:3000';
req.header.host = 'bar.com:8000';
assert.equal(req.host, 'foo.com:3000');
});
});

describe('and proxy is trusted', () => {
it('should be used', () => {
it('should be used on HTTP/1', () => {
const req = request();
req.app.proxy = true;
req.header['x-forwarded-host'] = 'bar.com, baz.com';
req.header.host = 'foo.com';
assert.equal(req.host, 'bar.com');
});

it('should be used on HTTP/2', () => {
const req = request({
'httpVersionMajor': 2,
'httpVersion': '2.0'
});
req.app.proxy = true;
req.header['x-forwarded-host'] = 'proxy.com:8080';
req.header[':authority'] = 'foo.com:3000';
req.header.host = 'bar.com:8000';
assert.equal(req.host, 'proxy.com:8080');
});
});
});
});

0 comments on commit 4964242

Please sign in to comment.