IpsInterceptorService { public void executeBlackList(Set<String> blacklist) throws Throwable { isAuthorized = true; RequestContext ctx = RequestContext.getCurrentContext(); Set<String> requestIps = getIpFromRequest(ctx.getRequest()); Set<String> ipsWithoutMask = new HashSet<>(); Set<String> ipsWithMask = new HashSet<>(); classifyIps(blacklist, ipsWithMask, ipsWithoutMask); ipsWithMask.forEach(ipWithMask -> { requestIps.forEach(ip -> { if (isInterDomainRouting(ipWithMask, ip)) { isAuthorized = false; } }); }); if (ipsWithoutMask.stream().anyMatch(requestIps::contains)) { isAuthorized = false; } if (!isAuthorized) { ctx.getResponse().sendError(HttpStatus.UNAUTHORIZED.value(), "Unauthorized ip"); } }  void executeWhiteList(Set<String> whitelist); void executeBlackList(Set<String> blacklist);  }
@Test public void blockIpsInBlacklist() throws Throwable { RequestContext ctx = RequestContext.getCurrentContext(); MockHttpServletRequest mockHttp = new MockHttpServletRequest(); mockHttp.addHeader("X-FORWARDED-FOR", "192.168.12.128:3000"); mockHttp.setRemoteAddr("10.60.40.50"); ctx.setRequest(mockHttp); Set<String> blacklist = new HashSet<>(); blacklist.add("192.168.12.128"); ipsInterceptorService.executeBlackList(blacklist); Assert.assertEquals(HttpStatus.UNAUTHORIZED.value(), ctx.getResponse().getStatus()); }
@Test public void blockIpsWithRangeInBlacklist() throws Throwable { RequestContext ctx = RequestContext.getCurrentContext(); MockHttpServletRequest mockHttp = new MockHttpServletRequest(); mockHttp.addHeader("X-FORWARDED-FOR", "192.168.12.127:3000"); mockHttp.setRemoteAddr("10.60.40.50"); ctx.setRequest(mockHttp); Set<String> blacklist = new HashSet<>(); blacklist.add("192.168.12.0/25"); ipsInterceptorService.executeBlackList(blacklist); Assert.assertEquals(HttpStatus.UNAUTHORIZED.value(), ctx.getResponse().getStatus()); }
@Test public void allowIpsOutOfRangeInBlacklist() throws Throwable { RequestContext ctx = RequestContext.getCurrentContext(); MockHttpServletRequest mockHttp = new MockHttpServletRequest(); mockHttp.addHeader("X-FORWARDED-FOR", "192.168.12.128:3000"); mockHttp.setRemoteAddr("10.60.40.50"); ctx.setRequest(mockHttp); Set<String> blacklist = new HashSet<>(); blacklist.add("192.168.12.0/25"); ipsInterceptorService.executeBlackList(blacklist); Assert.assertEquals(HttpStatus.OK.value(), ctx.getResponse().getStatus()); }