Skip to content

Commit

Permalink
Fix req.protocol for proxy-direct connections
Browse files Browse the repository at this point in the history
fixes #2252
  • Loading branch information
roark31337 authored and dougwilson committed Jul 23, 2014
1 parent 3fc8dc5 commit a28b7a8
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 5 deletions.
1 change: 1 addition & 0 deletions History.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down
13 changes: 8 additions & 5 deletions lib/request.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand All @@ -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];
});

Expand Down
15 changes: 15 additions & 0 deletions test/req.protocol.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand Down

0 comments on commit a28b7a8

Please sign in to comment.