Skip to content

Commit

Permalink
feat: support config.maxProxyCount to help get the real client ip (e…
Browse files Browse the repository at this point in the history
  • Loading branch information
dead-horse authored Apr 11, 2019
1 parent f0c1339 commit d56b831
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 3 deletions.
6 changes: 6 additions & 0 deletions app/extend/request.js
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,12 @@ module.exports = {

const val = getFromHeaders(this, this.app.config.ipHeaders) || '';
this[IPS] = val ? val.split(/\s*,\s*/) : [];

if (this.app.config.maxProxyCount > 0) {
// if maxProxyCount present, only keep `maxProxyCount + 1` ips
// [ illegalIp, clientRealIp, proxyIp1, proxyIp2 ...]
this[IPS] = this[IPS].slice(-(this.app.config.maxProxyCount + 1));
}
return this[IPS];
},

Expand Down
10 changes: 10 additions & 0 deletions config/config.default.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,16 @@ module.exports = appInfo => {
*/
proxy: false,

/**
* How many proxies the application deployed behind
* framework use this to get the clients' real ips
* `0` means not limited, for most common usage, it should be `1`
* @member {Integer} Config#maxProxyCount
* @default
* @since 1.19.0
*/
maxProxyCount: 0,

/**
* Detect request's protocol from specified headers, not case-sensitive.
* Only worked when config.proxy set to true.
Expand Down
20 changes: 17 additions & 3 deletions test/app/extend/request.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,12 +76,26 @@ describe('test/app/extend/request.test.js', () => {
assert(req.ip === '127.0.0.1');
assert(req.ip === '127.0.0.1');
});

it('should work with proxy', () => {
mm(req.socket, 'remoteAddress', '::ffff:127.0.0.1');
mm(req.header, 'x-forwarded-for', '127.0.0.1, 127.0.0.2, 127.0.0.3');
mm(app.config, 'proxy', true);
mm(app.config, 'maxProxyCount', 1);
assert(req.ip === '127.0.0.2');
});
});

describe('req.ips', () => {
it('should used x-forwarded-for', function* () {
mm(req.header, 'x-forwarded-for', '127.0.0.1,127.0.0.2');
assert.deepEqual(req.ips, [ '127.0.0.1', '127.0.0.2' ]);
it('should used x-forwarded-for', () => {
mm(req.header, 'x-forwarded-for', '127.0.0.1,127.0.0.2,127.0.0.3');
assert.deepEqual(req.ips, [ '127.0.0.1', '127.0.0.2', '127.0.0.3' ]);
});

it('should used work with maxProxyCount', () => {
mm(req.header, 'x-forwarded-for', '127.0.0.1,127.0.0.2,127.0.0.3');
mm(app.config, 'maxProxyCount', 1);
assert.deepEqual(req.ips, [ '127.0.0.2', '127.0.0.3' ]);
});

it('should used x-real-ip', function* () {
Expand Down

0 comments on commit d56b831

Please sign in to comment.