CorsFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { String sourceHost = ((HttpServletRequest) request).getHeader("Origin"); String origin = ""; try { if (SecurityUtils.isValidOrigin(sourceHost, ZeppelinConfiguration.create())) { origin = sourceHost; } } catch (URISyntaxException e) { LOGGER.error("Exception in WebDriverManager while getWebDriver ", e); } if (((HttpServletRequest) request).getMethod().equals("OPTIONS")) { HttpServletResponse resp = ((HttpServletResponse) response); addCorsHeaders(resp, origin); return; } if (response instanceof HttpServletResponse) { HttpServletResponse alteredResponse = ((HttpServletResponse) response); addCorsHeaders(alteredResponse, origin); } filterChain.doFilter(request, response); }  @Override void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain); @Override void destroy(); @Override void init(FilterConfig filterConfig);  }
@Test public void ValidCorsFilterTest() throws IOException, ServletException { CorsFilter filter = new CorsFilter(); HttpServletResponse mockResponse = mock(HttpServletResponse.class); FilterChain mockedFilterChain = mock(FilterChain.class); TestHttpServletRequest mockRequest = mock(TestHttpServletRequest.class); when(mockRequest.getHeader("Origin")).thenReturn("http: when(mockRequest.getMethod()).thenReturn("Empty"); when(mockRequest.getServerName()).thenReturn("localhost"); count = 0; doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocationOnMock) throws Throwable { headers[count] = invocationOnMock.getArguments()[1].toString(); count++; return null; } }).when(mockResponse).addHeader(anyString(), anyString()); filter.doFilter(mockRequest, mockResponse, mockedFilterChain); Assert.assertTrue(headers[0].equals("http: }
@Test public void InvalidCorsFilterTest() throws IOException, ServletException { CorsFilter filter = new CorsFilter(); HttpServletResponse mockResponse = mock(HttpServletResponse.class); FilterChain mockedFilterChain = mock(FilterChain.class); TestHttpServletRequest mockRequest = mock(TestHttpServletRequest.class); when(mockRequest.getHeader("Origin")).thenReturn("http: when(mockRequest.getMethod()).thenReturn("Empty"); when(mockRequest.getServerName()).thenReturn("evillocalhost"); doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocationOnMock) throws Throwable { headers[count] = invocationOnMock.getArguments()[1].toString(); count++; return null; } }).when(mockResponse).addHeader(anyString(), anyString()); filter.doFilter(mockRequest, mockResponse, mockedFilterChain); Assert.assertTrue(headers[0].equals("")); }