From 49642428342e5f291eb9d690802e83ed830623b5 Mon Sep 17 00:00:00 2001 From: fengmk2 Date: Tue, 23 Oct 2018 15:20:09 +0800 Subject: [PATCH] fix: use X-Forwarded-Host first on app.proxy present (#1263) --- lib/request.js | 6 ++++-- test/request/host.js | 27 +++++++++++++++++++++++++-- 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/lib/request.js b/lib/request.js index 7927344..0b0b262 100644 --- a/lib/request.js +++ b/lib/request.js @@ -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]; }, diff --git a/test/request/host.js b/test/request/host.js index f3934e6..0ad9486 100644 --- a/test/request/host.js +++ b/test/request/host.js @@ -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'); + }); }); }); });