DomainValidateFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException { final HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest; final HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse; if(startOrStopValidateDomain(httpServletRequest, httpServletResponse)) { return; } if(!shouldCheck()) { chain.doFilter(httpServletRequest, httpServletResponse); return; } String host = cleanUrl(httpServletRequest.getHeader(HTTP_REQUEST_HEADER_HOST)).trim(); if(IpUtils.isValidIpFormat(host) || isLocal(host)) { chain.doFilter(httpServletRequest, httpServletResponse); return; } if(validateDomain(httpServletResponse, host)) { chain.doFilter(httpServletRequest, httpServletResponse); } else { logger.debug("[domain validate fail]"); } } DomainValidateFilter(BooleanSupplier shouldCheckConfig, Supplier<String> expectedDomainName); @Override void init(FilterConfig filterConfig); @Override void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain); @Override void destroy(); static final String STOP_CHECK_URI; static final String START_CHECK_URI; static final String HTTP_REQUEST_HEADER_HOST; static final int BAD_REQUEST_CODE; static final String BAD_REQUEST_MESSAGE_TEMPLATE; }
@Test public void preHandleIp() throws Exception { domain = "localhost"; String ip = "10.0.0.1:8080"; MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); request.addHeader(HTTP_REQUEST_HEADER_HOST, ip); filter.doFilter(request, response, filterChain); Assert.assertEquals(200, response.getStatus()); }
@Test public void preHandleDomain() throws Exception { domain = "localhost"; MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); request.addHeader(HTTP_REQUEST_HEADER_HOST, domain); filter.doFilter(request, response, filterChain); Assert.assertEquals(200, response.getStatus()); }
@Test public void preHandleDomainPort() throws Exception { domain = "localhost"; MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); request.addHeader(HTTP_REQUEST_HEADER_HOST, domain + ":8080"); filter.doFilter(request, response, filterChain); Assert.assertEquals(200, response.getStatus()); }
@Test public void testLocalHostCall() throws Exception { domain = "xpipe.meta.ctripcorp.com"; MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); request.addHeader(HTTP_REQUEST_HEADER_HOST, "localhost:8080"); filter.doFilter(request, response, filterChain); Assert.assertEquals(200, response.getStatus()); }