creativelive / hapi-ratelimit

Hapi rate limiting module
MIT License
33 stars 15 forks source link

request.remoteAddress should not be used behind proxies #24

Open bf opened 8 years ago

bf commented 8 years ago

When having a reverse proxy-based setup request.info.remoteAddress should not be used as it always holds the proxy's IP and not the real client IP. This means that the request rate limiting is actually enforced against the proxy and not the individual clients.

In order to fix this, we need to look at the x-forwarded-for HTTP header (if it exists) and take the real client's IP address from it.

There is a hapijs issue which talks about the same problem: https://github.com/hapijs/hapi/issues/1210

They actually propose a function which will extract the client IP address from the x-forwarded-for headed if it exists. We might use it:

/**
 *  extract the final client ip address.   can not use request.info.remoteAddress directly because client may be behind a proxy/loadbalancer
 * @param request
 */
export function extractClientIp(request: hapi.Request) {
    //from http://stackoverflow.com/questions/29496257/knowing-request-ip-in-hapi-js-restful-api
    var xFF = request.headers['x-forwarded-for'];
    var ip = xFF ? xFF.split(',')[0] : request.info.remoteAddress;
    return ip;
}
bf commented 8 years ago

I have created a pull request

https://github.com/creativelive/hapi-ratelimit/pull/25