/** * Process the annotations for the filters. */ protected static void loadApplicationFilterAnnotations(Context context) { Class<?> classClass = null; FilterDef[] filterDefs = context.findFilterDefs(); for (int i = 0; i < filterDefs.length; i++) { classClass = Introspection.loadClass(context, (filterDefs[i]).getFilterClass()); if (classClass == null) { continue; } loadClassAnnotation(context, classClass); loadFieldsAnnotation(context, classClass); loadMethodsAnnotation(context, classClass); } }
private MockFilterChain testRemoteIpFilter(FilterDef filterDef, Request request) throws LifecycleException, IOException, ServletException { Tomcat tomcat = getTomcatInstance(); Context root = tomcat.addContext("", TEMP_DIR); RemoteIpFilter remoteIpFilter = new RemoteIpFilter(); filterDef.setFilterClass(RemoteIpFilter.class.getName()); filterDef.setFilter(remoteIpFilter); filterDef.setFilterName(RemoteIpFilter.class.getName()); root.addFilterDef(filterDef); FilterMap filterMap = new FilterMap(); filterMap.setFilterName(RemoteIpFilter.class.getName()); filterMap.addURLPattern("*"); root.addFilterMap(filterMap); getTomcatInstance().start(); MockFilterChain filterChain = new MockFilterChain(); // TEST TesterResponse response = new TesterResponse(); response.setRequest(request); remoteIpFilter.doFilter(request, response, filterChain); return filterChain; }
@Test public void testDuplicateFilterMapping() throws Exception { WebXml webxml = new WebXml(); ContextConfig config = new ContextConfig(); File pFile = paramClassResource( "org/apache/catalina/startup/DuplicateMappingParamFilter"); assertTrue(pFile.exists()); try { config.processAnnotationsFile(pFile, webxml, false); fail(); } catch (IllegalArgumentException ex) { // ignore } FilterDef filterDef = webxml.getFilters().get("paramD"); assertNull(filterDef); }
private static void configureTest46243Context(Context context, boolean fail) { // Add a test filter that fails FilterDef filterDef = new FilterDef(); filterDef.setFilterClass(Bug46243Filter.class.getName()); filterDef.setFilterName("Bug46243"); filterDef.addInitParameter("fail", Boolean.toString(fail)); context.addFilterDef(filterDef); FilterMap filterMap = new FilterMap(); filterMap.setFilterName("Bug46243"); filterMap.addURLPattern("*"); context.addFilterMap(filterMap); // Add a test servlet so there is something to generate a response if // it works (although it shouldn't) Tomcat.addServlet(context, "Bug46243", new HelloWorldServlet()); context.addServletMapping("/", "Bug46243"); }
protected void startTomcat() throws Exception { tomcat = new Tomcat(); File base = new File(System.getProperty("java.io.tmpdir")); org.apache.catalina.Context ctx = tomcat.addContext("/foo",base.getAbsolutePath()); FilterDef fd = new FilterDef(); fd.setFilterClass(TestFilter.class.getName()); fd.setFilterName("TestFilter"); FilterMap fm = new FilterMap(); fm.setFilterName("TestFilter"); fm.addURLPattern("/*"); fm.addServletName("/bar"); ctx.addFilterDef(fd); ctx.addFilterMap(fm); tomcat.addServlet(ctx, "/bar", TestServlet.class.getName()); ctx.addServletMapping("/bar", "/bar"); host = "localhost"; port = getLocalPort(); tomcat.setHostname(host); tomcat.setPort(port); tomcat.start(); }
/** * Configure and initialize the set of filters for this Context. Return * <code>true</code> if all filter initialization completed successfully, or * <code>false</code> otherwise. */ public boolean filterStart() { if (getLogger().isDebugEnabled()) getLogger().debug("Starting filters"); // Instantiate and record a FilterConfig for each defined filter boolean ok = true; synchronized (filterConfigs) { filterConfigs.clear(); for (Entry<String, FilterDef> entry : filterDefs.entrySet()) { String name = entry.getKey(); if (getLogger().isDebugEnabled()) getLogger().debug(" Starting filter '" + name + "'"); ApplicationFilterConfig filterConfig = null; try { filterConfig = new ApplicationFilterConfig(this, entry.getValue()); filterConfigs.put(name, filterConfig); } catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); getLogger().error(sm.getString("standardContext.filterStart", name), t); ok = false; } } } return (ok); }
@Override public FilterRegistration getFilterRegistration(String filterName) { FilterDef filterDef = context.findFilterDef(filterName); if (filterDef == null) { return null; } return new ApplicationFilterRegistration(filterDef, context); }
@Override public Map<String, ? extends FilterRegistration> getFilterRegistrations() { Map<String, ApplicationFilterRegistration> result = new HashMap<String, ApplicationFilterRegistration>(); FilterDef[] filterDefs = context.findFilterDefs(); for (FilterDef filterDef : filterDefs) { result.put(filterDef.getFilterName(), new ApplicationFilterRegistration(filterDef, context)); } return result; }
/** * Add a filter definition to this Context. * * @param filterDef The filter definition to be added */ @Override public void addFilterDef(FilterDef filterDef) { synchronized (filterDefs) { filterDefs.put(filterDef.getFilterName(), filterDef); } fireContainerEvent("addFilterDef", filterDef); }
/** * Return the filter definition for the specified filter name, if any; * otherwise return <code>null</code>. * * @param filterName Filter name to look up */ @Override public FilterDef findFilterDef(String filterName) { synchronized (filterDefs) { return (filterDefs.get(filterName)); } }
/** * Return the set of defined filters for this Context. */ @Override public FilterDef[] findFilterDefs() { synchronized (filterDefs) { FilterDef results[] = new FilterDef[filterDefs.size()]; return (filterDefs.values().toArray(results)); } }
/** * Add a filter definition to this Context. * * @param filterDef * The filter definition to be added */ @Override public void addFilterDef(FilterDef filterDef) { synchronized (filterDefs) { filterDefs.put(filterDef.getFilterName(), filterDef); } fireContainerEvent("addFilterDef", filterDef); }
@Test public void testBug54170() throws Exception { Tomcat tomcat = getTomcatInstance(); // No file system docBase required Context ctx = tomcat.addContext("", null); Tomcat.addServlet(ctx, "HelloWorld", new HelloWorldServlet()); ctx.addServletMapping("/", "HelloWorld"); // Add a filter with a name that should be escaped if used in a JMX // object name FilterDef filterDef = new FilterDef(); filterDef.setFilterClass(AddDefaultCharsetFilter.class.getName()); filterDef.setFilterName("bug54170*"); ctx.addFilterDef(filterDef); tomcat.start(); final MBeanServer mbeanServer = Registry.getRegistry(null, null).getMBeanServer(); // There should be one Servlet MBean registered Set<ObjectName> servlets = mbeanServer.queryNames( new ObjectName("Tomcat:j2eeType=Servlet,*"), null); Assert.assertEquals(1, servlets.size()); // There should be one Filter MBean registered Set<ObjectName> filters = mbeanServer.queryNames( new ObjectName("Tomcat:j2eeType=Filter,*"), null); Assert.assertEquals(1, filters.size()); }
@Test public void testFilterMapping() throws Exception { WebXml webxml = new WebXml(); ContextConfig config = new ContextConfig(); File sFile = paramClassResource( "org/apache/catalina/startup/ParamServlet"); config.processAnnotationsFile(sFile, webxml, false); File fFile = paramClassResource( "org/apache/catalina/startup/ParamFilter"); config.processAnnotationsFile(fFile, webxml, false); FilterDef fdef = webxml.getFilters().get("paramFilter"); assertNotNull(fdef); assertEquals("Servlet says: ",fdef.getParameterMap().get("message")); }
private synchronized void init() throws Exception { if (init) return; Tomcat tomcat = getTomcatInstance(); // No file system docBase required Context root = tomcat.addContext("", null); Tomcat.addServlet(root, "Bug37794", new Bug37794Servlet()); root.addServletMapping("/test", "Bug37794"); if (createFilter) { FilterDef failedRequestFilter = new FilterDef(); failedRequestFilter.setFilterName("failedRequestFilter"); failedRequestFilter.setFilterClass( FailedRequestFilter.class.getName()); FilterMap failedRequestFilterMap = new FilterMap(); failedRequestFilterMap.setFilterName("failedRequestFilter"); failedRequestFilterMap.addURLPattern("/*"); root.addFilterDef(failedRequestFilter); root.addFilterMap(failedRequestFilterMap); } tomcat.start(); setPort(tomcat.getConnector().getLocalPort()); init = true; }
private void setUpApplication() throws Exception { context = tomcat.addContext(CONTEXT_PATH_LOGIN, System.getProperty("java.io.tmpdir")); context.setSessionTimeout(SHORT_SESSION_TIMEOUT_MINS); Tomcat.addServlet(context, SERVLET_NAME, new TesterServlet()); context.addServletMapping(URI_PROTECTED, SERVLET_NAME); FilterDef filterDef = new FilterDef(); filterDef.setFilterName(FILTER_NAME); filterDef.setFilterClass(RestCsrfPreventionFilter.class.getCanonicalName()); filterDef.addInitParameter(FILTER_INIT_PARAM, REMOVE_CUSTOMER + "," + ADD_CUSTOMER); context.addFilterDef(filterDef); FilterMap filterMap = new FilterMap(); filterMap.setFilterName(FILTER_NAME); filterMap.addURLPattern(URI_CSRF_PROTECTED); context.addFilterMap(filterMap); SecurityCollection collection = new SecurityCollection(); collection.addPattern(URI_PROTECTED); SecurityConstraint sc = new SecurityConstraint(); sc.addAuthRole(ROLE); sc.addCollection(collection); context.addConstraint(sc); LoginConfig lc = new LoginConfig(); lc.setAuthMethod(METHOD); context.setLoginConfig(lc); AuthenticatorBase basicAuthenticator = new BasicAuthenticator(); context.getPipeline().addValve(basicAuthenticator); }
private void doTest(String encoding, String expected, int mode) throws Exception { // Setup Tomcat instance Tomcat tomcat = getTomcatInstance(); // No file system docBase required Context ctx = tomcat.addContext("", null); // Add the Servlet CharsetServlet servlet = new CharsetServlet(mode); Tomcat.addServlet(ctx, "servlet", servlet); ctx.addServletMapping("/", "servlet"); // Add the Filter FilterDef filterDef = new FilterDef(); filterDef.setFilterClass(AddDefaultCharsetFilter.class.getName()); filterDef.setFilterName("filter"); if (encoding != null) { filterDef.addInitParameter("encoding", encoding); } ctx.addFilterDef(filterDef); FilterMap filterMap = new FilterMap(); filterMap.setFilterName("filter"); filterMap.addServletName("servlet"); ctx.addFilterMap(filterMap); tomcat.start(); Map<String, List<String>> headers = new HashMap<String, List<String>>(); getUrl("http://localhost:" + getPort() + "/", new ByteChunk(), headers); List<String> ctHeaders = headers.get("Content-Type"); assertEquals(1, ctHeaders.size()); String ct = ctHeaders.get(0); assertEquals("text/plain;charset=" + expected, ct); }
@Test public void testIncomingRequestIsSecuredButProtocolHeaderSaysItIsNotWithCustomValues() throws Exception { // PREPARE FilterDef filterDef = new FilterDef(); filterDef.addInitParameter("protocolHeader", "x-forwarded-proto"); filterDef.addInitParameter("remoteIpHeader", "x-my-forwarded-for"); filterDef.addInitParameter("httpServerPort", "8080"); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRemoteAddr("192.168.0.10"); request.setSecure(true); request.setScheme("https"); request.setHeader("x-my-forwarded-for", "140.211.11.130"); request.setHeader("x-forwarded-proto", "http"); // TEST HttpServletRequest actualRequest = testRemoteIpFilter(filterDef, request).getRequest(); // VERIFY boolean actualSecure = actualRequest.isSecure(); assertFalse("request must be unsecured as header x-forwarded-proto said it is http", actualSecure); String actualScheme = actualRequest.getScheme(); assertEquals("scheme must be http as header x-forwarded-proto said it is http", "http", actualScheme); int actualServerPort = actualRequest.getServerPort(); assertEquals("wrong http server port", 8080, actualServerPort); String actualRemoteAddr = actualRequest.getRemoteAddr(); assertEquals("remoteAddr", "140.211.11.130", actualRemoteAddr); String actualRemoteHost = actualRequest.getRemoteHost(); assertEquals("remoteHost", "140.211.11.130", actualRemoteHost); }
@Test public void testIncomingRequestIsSecuredButProtocolHeaderSaysItIsNotWithDefaultValues() throws Exception { // PREPARE FilterDef filterDef = new FilterDef(); filterDef.addInitParameter("protocolHeader", "x-forwarded-proto"); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRemoteAddr("192.168.0.10"); request.setSecure(true); request.setScheme("https"); request.setHeader("x-forwarded-for", "140.211.11.130"); request.setHeader("x-forwarded-proto", "http"); // TEST HttpServletRequest actualRequest = testRemoteIpFilter(filterDef, request).getRequest(); // VERIFY boolean actualSecure = actualRequest.isSecure(); assertFalse("request must be unsecured as header x-forwarded-proto said it is http", actualSecure); String actualScheme = actualRequest.getScheme(); assertEquals("scheme must be http as header x-forwarded-proto said it is http", "http", actualScheme); String actualRemoteAddr = actualRequest.getRemoteAddr(); assertEquals("remoteAddr", "140.211.11.130", actualRemoteAddr); String actualRemoteHost = actualRequest.getRemoteHost(); assertEquals("remoteHost", "140.211.11.130", actualRemoteHost); }
@Test public void testInvokeAllowedRemoteAddrWithNullRemoteIpHeader() throws Exception { // PREPARE FilterDef filterDef = new FilterDef(); filterDef.addInitParameter("internalProxies", "192\\.168\\.0\\.10|192\\.168\\.0\\.11"); filterDef.addInitParameter("trustedProxies", "proxy1|proxy2|proxy3"); filterDef.addInitParameter("remoteIpHeader", "x-forwarded-for"); filterDef.addInitParameter("proxiesHeader", "x-forwarded-by"); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRemoteAddr("192.168.0.10"); request.setRemoteHost("remote-host-original-value"); // TEST HttpServletRequest actualRequest = testRemoteIpFilter(filterDef, request).getRequest(); // VERIFY String actualXForwardedFor = request.getHeader("x-forwarded-for"); assertNull("x-forwarded-for must be null", actualXForwardedFor); String actualXForwardedBy = request.getHeader("x-forwarded-by"); assertNull("x-forwarded-by must be null", actualXForwardedBy); String actualRemoteAddr = actualRequest.getRemoteAddr(); assertEquals("remoteAddr", "192.168.0.10", actualRemoteAddr); String actualRemoteHost = actualRequest.getRemoteHost(); assertEquals("remoteHost", "remote-host-original-value", actualRemoteHost); }
@Test public void testInvokeAllProxiesAreInternal() throws Exception { // PREPARE FilterDef filterDef = new FilterDef(); filterDef.addInitParameter("internalProxies", "192\\.168\\.0\\.10|192\\.168\\.0\\.11"); filterDef.addInitParameter("trustedProxies", "proxy1|proxy2|proxy3"); filterDef.addInitParameter("remoteIpHeader", "x-forwarded-for"); filterDef.addInitParameter("proxiesHeader", "x-forwarded-by"); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRemoteAddr("192.168.0.10"); request.setRemoteHost("remote-host-original-value"); request.addHeader("x-forwarded-for", "140.211.11.130, 192.168.0.10, 192.168.0.11"); // TEST HttpServletRequest actualRequest = testRemoteIpFilter(filterDef, request).getRequest(); // VERIFY String actualXForwardedFor = actualRequest.getHeader("x-forwarded-for"); assertNull("all proxies are internal, x-forwarded-for must be null", actualXForwardedFor); String actualXForwardedBy = actualRequest.getHeader("x-forwarded-by"); assertNull("all proxies are internal, x-forwarded-by must be null", actualXForwardedBy); String actualRemoteAddr = actualRequest.getRemoteAddr(); assertEquals("remoteAddr", "140.211.11.130", actualRemoteAddr); String actualRemoteHost = actualRequest.getRemoteHost(); assertEquals("remoteHost", "140.211.11.130", actualRemoteHost); }
@Test public void testInvokeAllProxiesAreTrusted() throws Exception { // PREPARE RemoteIpFilter remoteIpFilter = new RemoteIpFilter(); FilterDef filterDef = new FilterDef(); filterDef.addInitParameter("internalProxies", "192\\.168\\.0\\.10|192\\.168\\.0\\.11"); filterDef.addInitParameter("trustedProxies", "proxy1|proxy2|proxy3"); filterDef.addInitParameter("remoteIpHeader", "x-forwarded-for"); filterDef.addInitParameter("proxiesHeader", "x-forwarded-by"); filterDef.setFilter(remoteIpFilter); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRemoteAddr("192.168.0.10"); request.setRemoteHost("remote-host-original-value"); request.setHeader("x-forwarded-for", "140.211.11.130, proxy1, proxy2"); // TEST HttpServletRequest actualRequest = testRemoteIpFilter(filterDef, request).getRequest(); // VERIFY String actualXForwardedFor = actualRequest.getHeader("x-forwarded-for"); assertNull("all proxies are trusted, x-forwarded-for must be null", actualXForwardedFor); String actualXForwardedBy = actualRequest.getHeader("x-forwarded-by"); assertEquals("all proxies are trusted, they must appear in x-forwarded-by", "proxy1, proxy2", actualXForwardedBy); String actualRemoteAddr = actualRequest.getRemoteAddr(); assertEquals("remoteAddr", "140.211.11.130", actualRemoteAddr); String actualRemoteHost = actualRequest.getRemoteHost(); assertEquals("remoteHost", "140.211.11.130", actualRemoteHost); }
@Test public void testInvokeAllProxiesAreTrustedOrInternal() throws Exception { // PREPARE FilterDef filterDef = new FilterDef(); filterDef.addInitParameter("internalProxies", "192\\.168\\.0\\.10|192\\.168\\.0\\.11"); filterDef.addInitParameter("trustedProxies", "proxy1|proxy2|proxy3"); filterDef.addInitParameter("remoteIpHeader", "x-forwarded-for"); filterDef.addInitParameter("proxiesHeader", "x-forwarded-by"); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRemoteAddr("192.168.0.10"); request.setRemoteHost("remote-host-original-value"); request.setHeader("x-forwarded-for", "140.211.11.130, proxy1, proxy2, 192.168.0.10, 192.168.0.11"); // TEST HttpServletRequest actualRequest = testRemoteIpFilter(filterDef, request).getRequest(); // VERIFY String actualXForwardedFor = actualRequest.getHeader("x-forwarded-for"); assertNull("all proxies are trusted, x-forwarded-for must be null", actualXForwardedFor); String actualXForwardedBy = actualRequest.getHeader("x-forwarded-by"); assertEquals("all proxies are trusted, they must appear in x-forwarded-by", "proxy1, proxy2", actualXForwardedBy); String actualRemoteAddr = actualRequest.getRemoteAddr(); assertEquals("remoteAddr", "140.211.11.130", actualRemoteAddr); String actualRemoteHost = actualRequest.getRemoteHost(); assertEquals("remoteHost", "140.211.11.130", actualRemoteHost); }
@Test public void testInvokeNotAllowedRemoteAddr() throws Exception { // PREPARE FilterDef filterDef = new FilterDef(); filterDef.addInitParameter("internalProxies", "192\\.168\\.0\\.10|192\\.168\\.0\\.11"); filterDef.addInitParameter("trustedProxies", "proxy1|proxy2|proxy3"); filterDef.addInitParameter("remoteIpHeader", "x-forwarded-for"); filterDef.addInitParameter("proxiesHeader", "x-forwarded-by"); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRemoteAddr("not-allowed-internal-proxy"); request.setRemoteHost("not-allowed-internal-proxy-host"); request.setHeader("x-forwarded-for", "140.211.11.130, proxy1, proxy2"); // TEST HttpServletRequest actualRequest = testRemoteIpFilter(filterDef, request).getRequest(); // VERIFY String actualXForwardedFor = actualRequest.getHeader("x-forwarded-for"); assertEquals("x-forwarded-for must be unchanged", "140.211.11.130, proxy1, proxy2", actualXForwardedFor); String actualXForwardedBy = actualRequest.getHeader("x-forwarded-by"); assertNull("x-forwarded-by must be null", actualXForwardedBy); String actualRemoteAddr = actualRequest.getRemoteAddr(); assertEquals("remoteAddr", "not-allowed-internal-proxy", actualRemoteAddr); String actualRemoteHost = actualRequest.getRemoteHost(); assertEquals("remoteHost", "not-allowed-internal-proxy-host", actualRemoteHost); }
@Test public void testRequestAttributesForAccessLog() throws Exception { // PREPARE FilterDef filterDef = new FilterDef(); filterDef.addInitParameter("protocolHeader", "x-forwarded-proto"); filterDef.addInitParameter("remoteIpHeader", "x-my-forwarded-for"); filterDef.addInitParameter("httpServerPort", "8080"); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRemoteAddr("192.168.0.10"); request.setHeader("x-my-forwarded-for", "140.211.11.130"); request.setHeader("x-forwarded-proto", "http"); // TEST HttpServletRequest actualRequest = testRemoteIpFilter(filterDef, request).getRequest(); // VERIFY Assert.assertEquals("org.apache.catalina.AccessLog.ServerPort", Integer.valueOf(8080), actualRequest.getAttribute(AccessLog.SERVER_PORT_ATTRIBUTE)); Assert.assertEquals("org.apache.catalina.AccessLog.RemoteAddr", "140.211.11.130", actualRequest.getAttribute(AccessLog.REMOTE_ADDR_ATTRIBUTE)); Assert.assertEquals("org.apache.catalina.AccessLog.RemoteHost", "140.211.11.130", actualRequest.getAttribute(AccessLog.REMOTE_HOST_ATTRIBUTE)); }
/** * Process the annotations for the filters. */ protected static void loadApplicationFilterAnnotations(Context context) { FilterDef[] filterDefs = context.findFilterDefs(); for (int i = 0; i < filterDefs.length; i++) { loadClassAnnotation(context, (filterDefs[i]).getFilterClass()); } }
/** * Return the filter definition for the specified filter name, if any; * otherwise return <code>null</code>. * * @param filterName Filter name to look up */ public FilterDef findFilterDef(String filterName) { synchronized (filterDefs) { return ((FilterDef) filterDefs.get(filterName)); } }
/** * Return the set of defined filters for this Context. */ public FilterDef[] findFilterDefs() { synchronized (filterDefs) { FilterDef results[] = new FilterDef[filterDefs.size()]; return ((FilterDef[]) filterDefs.values().toArray(results)); } }
/** * Remove the specified filter definition from this Context, if it exists; * otherwise, no action is taken. * * @param filterDef Filter definition to be removed */ public void removeFilterDef(FilterDef filterDef) { synchronized (filterDefs) { filterDefs.remove(filterDef.getFilterName()); } fireContainerEvent("removeFilterDef", filterDef); }
/** * Add a filter definition to this Context. * * @param filterDef The filter definition to be added */ public void addFilterDef(FilterDef filterDef) { synchronized (filterDefs) { filterDefs.put(filterDef.getFilterName(), filterDef); } fireContainerEvent("addFilterDef", filterDef); }
/** * Configure and initialize the set of filters for this Context. * Return <code>true</code> if all filter initialization completed * successfully, or <code>false</code> otherwise. */ public boolean filterStart() { if (debug >= 1) log("Starting filters"); // Instantiate and record a FilterConfig for each defined filter boolean ok = true; synchronized (filterConfigs) { filterConfigs.clear(); Iterator names = filterDefs.keySet().iterator(); while (names.hasNext()) { String name = (String) names.next(); if (debug >= 1) log(" Starting filter '" + name + "'"); ApplicationFilterConfig filterConfig = null; try { filterConfig = new ApplicationFilterConfig (this, (FilterDef) filterDefs.get(name)); filterConfigs.put(name, filterConfig); } catch (Throwable t) { log(sm.getString("standardContext.filterStart", name), t); ok = false; } } } return (ok); }