Fix req.protocol for proxy-direct connections

fixes #2252
This commit is contained in:
Ashley Streb
2014-07-18 11:33:16 -04:00
committed by Douglas Christopher Wilson
parent 3fc8dc54ee
commit a28b7a85cf
3 changed files with 24 additions and 5 deletions

View File

@@ -1,6 +1,7 @@
3.x
===
* Fix `req.protocol` for proxy-direct connections
* Pass options from `res.sendfile` to `send`
* deps: connect@2.24.0
- deps: body-parser@~1.5.0

View File

@@ -341,7 +341,9 @@ req.is = function(type){
* Return the protocol string "http" or "https"
* when requested with TLS. When the "trust proxy"
* setting trusts the socket address, the
* "X-Forwarded-Proto" header field will be trusted.
* "X-Forwarded-Proto" header field will be trusted
* and used if present.
*
* If you're running behind a reverse proxy that
* supplies https for you this may be enabled.
*
@@ -350,17 +352,18 @@ req.is = function(type){
*/
req.__defineGetter__('protocol', function(){
var proto = this.connection.encrypted
? 'https'
: 'http';
var trust = this.app.get('trust proxy fn');
if (!trust(this.connection.remoteAddress)) {
return this.connection.encrypted
? 'https'
: 'http';
return proto;
}
// Note: X-Forwarded-Proto is normally only ever a
// single value, but this is to be safe.
var proto = this.get('X-Forwarded-Proto') || 'http';
proto = this.get('X-Forwarded-Proto') || proto;
return proto.split(/\s*,\s*/)[0];
});

View File

@@ -32,6 +32,21 @@ describe('req', function(){
.expect('https', done);
})
it('should default to the socket addr if X-Forwarded-Proto not present', function(done){
var app = express();
app.enable('trust proxy');
app.use(function(req, res){
req.connection.encrypted = true;
res.end(req.protocol);
});
request(app)
.get('/')
.expect('https', done);
})
it('should ignore X-Forwarded-Proto if socket addr not trusted', function(done){
var app = express();