Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support config.maxProxyCount to help get the real client ip #3612

Merged
merged 5 commits into from
Apr 11, 2019
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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 2.20.2
*/
maxProxyCount: 0,

/**
* Detect request's protocol from specified headers, not case-sensitive.
* Only worked when config.proxy set to true.
Expand Down
18 changes: 16 additions & 2 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', () => {
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' ]);
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', () => {
Expand Down