Skip to content

Commit

Permalink
feat(ratelimit): Adding source IP address to anonymous prinicipal (#355)
Browse files Browse the repository at this point in the history
  • Loading branch information
robzienert committed Mar 28, 2017
1 parent 76d2545 commit 43e4cff
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 3 deletions.
Expand Up @@ -49,7 +49,7 @@ public RateLimitingInterceptor(RateLimiter rateLimiter, Registry registry, boole

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String principal = getPrincipal().toString();
String principal = getPrincipal(request).toString();
if (UNKNOWN_PRINCIPAL.equals(principal)) {
// Occurs when Spring decides to dispatch to /error after we send the initial 429.
// Pass through so that the JSON error body gets rendered.
Expand Down Expand Up @@ -90,7 +90,7 @@ public void postHandle(HttpServletRequest request, HttpServletResponse response,
}
}

private Object getPrincipal() {
private Object getPrincipal(HttpServletRequest request) {
SecurityContext context = SecurityContextHolder.getContext();
Authentication authentication = context.getAuthentication();

Expand All @@ -103,6 +103,14 @@ private Object getPrincipal() {
}

log.warn("Unknown principal type, assuming anonymous");
return "anonymous";
return "anonymous-" + sourceIpAddress(request);
}

private String sourceIpAddress(HttpServletRequest request) {
String ip = request.getHeader("X-FORWARDED-FOR");
if (ip == null) {
return request.getRemoteAddr();
}
return ip;
}
}
Expand Up @@ -74,6 +74,10 @@ public Rate incrementAndGetRate(String name) {
}

private int getCapacity(Jedis jedis, String name) {
if (name.startsWith("anonymous")) {
name = "anonymous";
}

String capacity = jedis.get(getRedisCapacityKey(name));
if (capacity != null) {
try {
Expand Down
Expand Up @@ -128,4 +128,21 @@ class RedisRateLimiterSpec extends Specification {
cleanup:
jedis.close()
}

def 'should use same capacity override for all anonymous principals'() {
given:
RedisRateLimiter subject = new RedisRateLimiter((JedisPool) embeddedRedis.pool, 3, 1, [
'anonymous': 5
])

Jedis jedis = embeddedRedis.pool.resource

expect:
subject.getCapacity(jedis, 'foo') == 3
subject.getCapacity(jedis, 'anonymous') == 5
subject.getCapacity(jedis, 'anonymous-10.10.10.10') == 5

cleanup:
jedis.close()
}
}

0 comments on commit 43e4cff

Please sign in to comment.