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