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 (CorsUtils.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 @SuppressWarnings("rawtypes") public void validCorsFilterTest() throws IOException, ServletException { CorsFilter filter = new CorsFilter(); HttpServletResponse mockResponse = mock(HttpServletResponse.class); FilterChain mockedFilterChain = mock(FilterChain.class); HttpServletRequest mockRequest = mock(HttpServletRequest.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).setHeader(anyString(), anyString()); filter.doFilter(mockRequest, mockResponse, mockedFilterChain); Assert.assertTrue(headers[0].equals("http: }
@Test @SuppressWarnings("rawtypes") public void invalidCorsFilterTest() throws IOException, ServletException { CorsFilter filter = new CorsFilter(); HttpServletResponse mockResponse = mock(HttpServletResponse.class); FilterChain mockedFilterChain = mock(FilterChain.class); HttpServletRequest mockRequest = mock(HttpServletRequest.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).setHeader(anyString(), anyString()); filter.doFilter(mockRequest, mockResponse, mockedFilterChain); Assert.assertTrue(headers[0].equals("")); }