Skip to content

Commit dd45525

Browse files
committed
📱 Get proto from Forwarded header
1 parent a100dda commit dd45525

2 files changed

Lines changed: 51 additions & 1 deletion

File tree

middleware/https-redirect.js

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,16 @@
11
'use strict';
22

33
var endsWith = require('../lib/utils').endsWith;
4+
var getForwardedClient = require('../lib/utils').getForwardedClient;
5+
var _ = require('underscore');
46

57
module.exports = function(AV) {
68
return function() {
79
return function(req, res, next) {
8-
if ((AV.Cloud.__prod || endsWith(req.headers.host, '.leanapp.cn')) && (!req.secure)) {
10+
var forwardedClient = getForwardedClient(req)
11+
12+
if (forwardedClient && forwardedClient.proto === 'http' && !_.include(['loopback', 'private'], forwardedClient.range) ||
13+
!forwardedClient && (AV.Cloud.__prod || endsWith(req.headers.host, '.leanapp.cn')) && (!req.secure)) {
914
const url = `https://${req.headers.host}${req.originalUrl || req.url}`;
1015

1116
res.statusCode = 302;

test/express/https-redirect-test.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,13 @@ app.get('/test', function (req, res) {
1616
});
1717

1818
describe('https-redirect', function() {
19+
var prod = AV.Cloud.__prod
20+
21+
afterEach(function() {
22+
// rollback changes on AV.Cloud.__prod
23+
AV.Cloud.__prod = prod
24+
})
25+
1926
it('should redirect', function(done) {
2027
request(app)
2128
.get('/test')
@@ -43,4 +50,42 @@ describe('https-redirect', function() {
4350
.expect(200)
4451
.expect("Hello World!", done);
4552
});
53+
54+
it('should redirect (Forwarded, custom domain on staging)', function(done) {
55+
AV.Cloud.__prod = 0
56+
57+
request(app)
58+
.get('/test')
59+
.set('Host', 'stg-custom.domain.com')
60+
.set('Forwarded', 'for=1.2.3.4; proto=http, for=10.0.0.1')
61+
.expect(302)
62+
.end(function(err, res) {
63+
res.headers.location.should.equal('https://stg-custom.domain.com/test');
64+
done();
65+
})
66+
});
67+
68+
it('should not redirect (Forwarded, intranet)', function(done) {
69+
AV.Cloud.__prod = 0
70+
71+
request(app)
72+
.get('/test')
73+
.set('Host', 'stg-custom.domain.com')
74+
.set('Forwarded', 'for=10.0.0.1; proto=http')
75+
.set('X-Forwarded-Proto', 'http')
76+
.expect(200)
77+
.expect("Hello World!", done);
78+
});
79+
80+
it('should not redirect (Forwarded overwrite X-Forwarded-Proto)', function(done) {
81+
AV.Cloud.__prod = 0
82+
83+
request(app)
84+
.get('/test')
85+
.set('Host', 'stg-custom.domain.com')
86+
.set('Forwarded', 'for=1.2.3.4; proto=https, for=10.0.0.1; proto=http')
87+
.set('X-Forwarded-Proto', 'http')
88+
.expect(200)
89+
.expect("Hello World!", done);
90+
});
4691
});

0 commit comments

Comments
 (0)