From 5783c7c2f09e9e86b145dd9dab064b55c722809b Mon Sep 17 00:00:00 2001 From: lprimak Date: Mon, 23 Nov 2026 18:59:10 -0600 Subject: [PATCH] fix(web): filters use the path pattern matched by the chain resolver A custom PatternMatcher set on PathMatchingFilterChainResolver was not used by the filters in the chain, which matched the path again with their own AntPathMatcher. Non-Ant patterns did not work as a result. The resolver now records the matched pattern as a request attribute and PathMatchingFilter uses that pattern's config directly. Applies to the Guice SimpleFilterChainResolver as well, which now looks up the chain by its configured pattern after a trailing-slash match. --- .../guice/web/SimpleFilterChainResolver.java | 11 +++-- .../shiro/guice/web/ShiroWebModuleTest.java | 23 +++++++++++ .../web/SimpleFilterChainResolverTest.java | 4 ++ .../shiro/web/filter/PathMatchingFilter.java | 34 ++++++++------- .../mgt/PathMatchingFilterChainResolver.java | 26 ++++-------- .../PathMatchingFilterChainResolverTest.java | 41 +++++++++++++++++++ 6 files changed, 101 insertions(+), 38 deletions(-) diff --git a/support/guice/src/main/java/org/apache/shiro/guice/web/SimpleFilterChainResolver.java b/support/guice/src/main/java/org/apache/shiro/guice/web/SimpleFilterChainResolver.java index f63d0e0a0c..6b87590281 100644 --- a/support/guice/src/main/java/org/apache/shiro/guice/web/SimpleFilterChainResolver.java +++ b/support/guice/src/main/java/org/apache/shiro/guice/web/SimpleFilterChainResolver.java @@ -31,6 +31,7 @@ import com.google.inject.Key; import org.apache.shiro.util.PatternMatcher; +import org.apache.shiro.web.filter.PathMatchingFilter; import org.apache.shiro.web.filter.mgt.FilterChainResolver; import org.apache.shiro.web.util.WebUtils; import static org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver.removeTrailingSlash; @@ -48,17 +49,15 @@ class SimpleFilterChainResolver implements FilterChainResolver { @Override public FilterChain getChain(ServletRequest request, ServletResponse response, final FilterChain originalChain) { + request.removeAttribute(PathMatchingFilter.RESOLVED_CHAIN_ATTRIBUTE); String requestURI = WebUtils.getPathWithinApplication(WebUtils.toHttp(request)); final String requestURINoTrailingSlash = removeTrailingSlash(requestURI); for (String pathPattern : chains.keySet()) { - if (patternMatcher.matches(pathPattern, requestURI)) { + if (patternMatcher.matches(pathPattern, requestURI) + || patternMatcher.matches(removeTrailingSlash(pathPattern), requestURINoTrailingSlash)) { + request.setAttribute(PathMatchingFilter.RESOLVED_CHAIN_ATTRIBUTE, pathPattern); return proxy(originalChain, pathPattern); - } else { - pathPattern = removeTrailingSlash(pathPattern); - if (patternMatcher.matches(pathPattern, requestURINoTrailingSlash)) { - return proxy(originalChain, pathPattern); - } } } return null; diff --git a/support/guice/src/test/java/org/apache/shiro/guice/web/ShiroWebModuleTest.java b/support/guice/src/test/java/org/apache/shiro/guice/web/ShiroWebModuleTest.java index dca40c6bfb..bbe6f50db4 100644 --- a/support/guice/src/test/java/org/apache/shiro/guice/web/ShiroWebModuleTest.java +++ b/support/guice/src/test/java/org/apache/shiro/guice/web/ShiroWebModuleTest.java @@ -38,6 +38,7 @@ import org.apache.shiro.web.filter.authc.FormAuthenticationFilter; import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter; import org.apache.shiro.web.filter.authz.RolesAuthorizationFilter; +import org.apache.shiro.web.filter.PathMatchingFilter; import org.apache.shiro.web.filter.mgt.FilterChainResolver; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.apache.shiro.web.mgt.WebSecurityManager; @@ -66,9 +67,11 @@ import java.util.List; import static org.assertj.core.api.Assertions.assertThat; +import static org.easymock.EasyMock.anyString; import static org.easymock.EasyMock.createMock; import static org.easymock.EasyMock.eq; import static org.easymock.EasyMock.expect; +import static org.easymock.EasyMock.expectLastCall; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; @@ -198,6 +201,10 @@ void testAddFilterChainGuice3and4() { expect(request.getAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH)).andReturn("/test_authc_basic"); expect(request.getAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH)).andReturn("/test_perms"); expect(request.getAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH)).andReturn("/multiple_configs"); + request.removeAttribute(PathMatchingFilter.RESOLVED_CHAIN_ATTRIBUTE); + expectLastCall().anyTimes(); + request.setAttribute(eq(PathMatchingFilter.RESOLVED_CHAIN_ATTRIBUTE), anyString()); + expectLastCall().anyTimes(); replay(servletContext, request); Injector injector = Guice.createInjector(new ShiroWebModule(servletContext) { @@ -286,6 +293,10 @@ void testAddFilterChainGuice3Only() { expect(request.getAttribute(RequestDispatcher.INCLUDE_CONTEXT_PATH)).andReturn("/test_custom_filter"); expect(request.getAttribute(RequestDispatcher.INCLUDE_CONTEXT_PATH)).andReturn("/test_perms"); expect(request.getAttribute(RequestDispatcher.INCLUDE_CONTEXT_PATH)).andReturn("/multiple_configs"); + request.removeAttribute(PathMatchingFilter.RESOLVED_CHAIN_ATTRIBUTE); + expectLastCall().anyTimes(); + request.setAttribute(eq(PathMatchingFilter.RESOLVED_CHAIN_ATTRIBUTE), anyString()); + expectLastCall().anyTimes(); replay(servletContext, request); Injector injector = Guice.createInjector(new ShiroWebModule(servletContext) { @@ -356,6 +367,10 @@ void testDefaultPath() { expect(request.getAttribute(RequestDispatcher.INCLUDE_PATH_INFO)).andReturn(null).anyTimes(); expect(request.getPathInfo()).andReturn(null).anyTimes(); expect(request.getAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH)).andReturn("/test/foobar"); + request.removeAttribute(PathMatchingFilter.RESOLVED_CHAIN_ATTRIBUTE); + expectLastCall().anyTimes(); + request.setAttribute(eq(PathMatchingFilter.RESOLVED_CHAIN_ATTRIBUTE), anyString()); + expectLastCall().anyTimes(); replay(servletContext, request); Injector injector = Guice.createInjector(new ShiroWebModule(servletContext) { @@ -399,6 +414,10 @@ void testDisableGlobalFilters() { expect(request.getAttribute(RequestDispatcher.INCLUDE_PATH_INFO)).andReturn(null).anyTimes(); expect(request.getPathInfo()).andReturn(null).anyTimes(); expect(request.getAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH)).andReturn("/test/foobar"); + request.removeAttribute(PathMatchingFilter.RESOLVED_CHAIN_ATTRIBUTE); + expectLastCall().anyTimes(); + request.setAttribute(eq(PathMatchingFilter.RESOLVED_CHAIN_ATTRIBUTE), anyString()); + expectLastCall().anyTimes(); replay(servletContext, request); Injector injector = Guice.createInjector(new ShiroWebModule(servletContext) { @@ -447,6 +466,10 @@ void testChangeInvalidFilterConfig() { expect(request.getAttribute(RequestDispatcher.INCLUDE_PATH_INFO)).andReturn(null).anyTimes(); expect(request.getPathInfo()).andReturn(null).anyTimes(); expect(request.getAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH)).andReturn("/test/foobar"); + request.removeAttribute(PathMatchingFilter.RESOLVED_CHAIN_ATTRIBUTE); + expectLastCall().anyTimes(); + request.setAttribute(eq(PathMatchingFilter.RESOLVED_CHAIN_ATTRIBUTE), anyString()); + expectLastCall().anyTimes(); replay(servletContext, request); Injector injector = Guice.createInjector(new ShiroWebModule(servletContext) { diff --git a/support/guice/src/test/java/org/apache/shiro/guice/web/SimpleFilterChainResolverTest.java b/support/guice/src/test/java/org/apache/shiro/guice/web/SimpleFilterChainResolverTest.java index 24e6d9ee1d..013a3adc57 100644 --- a/support/guice/src/test/java/org/apache/shiro/guice/web/SimpleFilterChainResolverTest.java +++ b/support/guice/src/test/java/org/apache/shiro/guice/web/SimpleFilterChainResolverTest.java @@ -22,6 +22,7 @@ import com.google.inject.Key; import com.google.inject.name.Names; import org.apache.shiro.util.PatternMatcher; +import org.apache.shiro.web.filter.PathMatchingFilter; import org.apache.shiro.web.util.WebUtils; import org.easymock.IMocksControl; import org.junit.jupiter.api.Test; @@ -82,6 +83,7 @@ void testGetChain() throws Exception { ServletResponse response = ctrl.createMock(HttpServletResponse.class); FilterChain originalChain = ctrl.createMock(FilterChain.class); + request.removeAttribute(PathMatchingFilter.RESOLVED_CHAIN_ATTRIBUTE); expect(request.getAttribute(WebUtils.INCLUDE_SERVLET_PATH_ATTRIBUTE)).andReturn("/mychain"); expect(request.getAttribute(WebUtils.INCLUDE_PATH_INFO_ATTRIBUTE)).andReturn(""); @@ -89,6 +91,7 @@ void testGetChain() throws Exception { expect(patternMatcher.matches(chainOne, "/mychain")).andReturn(false).times(2); expect(patternMatcher.matches(chainTwo, "/mychain")).andReturn(true); + request.setAttribute(PathMatchingFilter.RESOLVED_CHAIN_ATTRIBUTE, chainTwo); Filter filter2a = ctrl.createMock(Filter.class); Filter filter2b = ctrl.createMock(Filter.class); @@ -113,6 +116,7 @@ void testGetChain() throws Exception { ctrl.reset(); + request.removeAttribute(PathMatchingFilter.RESOLVED_CHAIN_ATTRIBUTE); expect(request.getAttribute(WebUtils.INCLUDE_SERVLET_PATH_ATTRIBUTE)).andReturn("/nochain"); expect(request.getAttribute(WebUtils.INCLUDE_PATH_INFO_ATTRIBUTE)).andReturn(""); diff --git a/web/src/main/java/org/apache/shiro/web/filter/PathMatchingFilter.java b/web/src/main/java/org/apache/shiro/web/filter/PathMatchingFilter.java index 4f035df738..d248be36d7 100644 --- a/web/src/main/java/org/apache/shiro/web/filter/PathMatchingFilter.java +++ b/web/src/main/java/org/apache/shiro/web/filter/PathMatchingFilter.java @@ -20,6 +20,7 @@ import org.apache.shiro.util.AntPathMatcher; import org.apache.shiro.util.PatternMatcher; +import org.apache.shiro.web.filter.mgt.FilterChainResolver; import org.apache.shiro.web.servlet.AdviceFilter; import org.apache.shiro.web.util.WebUtils; import org.owasp.encoder.Encode; @@ -40,6 +41,13 @@ * @since 0.9 */ public abstract class PathMatchingFilter extends AdviceFilter implements PathConfigProcessor { + /** + * Request attribute set by the {@link FilterChainResolver} to the path pattern it matched. + * The filter uses that pattern's config instead of matching the path itself. + * + * @since 3.1.0 + */ + public static final String RESOLVED_CHAIN_ATTRIBUTE = PathMatchingFilter.class.getName() + ".RESOLVED_CHAIN"; /** * Log available to this class only @@ -181,15 +189,15 @@ protected boolean pathsMatch(String pattern, String path) { /** * Implementation that handles path-matching behavior before a request is evaluated. If the path matches and * the filter - * {@link #isEnabled(jakarta.servlet.ServletRequest, jakarta.servlet.ServletResponse, String, Object) isEnabled} for + * {@link #isEnabled(ServletRequest, ServletResponse, String, Object) isEnabled} for * that path/config, the request will be allowed through via the result from - * {@link #onPreHandle(jakarta.servlet.ServletRequest, jakarta.servlet.ServletResponse, Object) onPreHandle}. If the + * {@link #onPreHandle(ServletRequest, ServletResponse, Object) onPreHandle}. If the * path does not match or the filter is not enabled for that path, this filter will allow passthrough immediately * to allow the {@code FilterChain} to continue executing. *

* In order to retain path-matching functionality, subclasses should not override this method if at all * possible, and instead override - * {@link #onPreHandle(jakarta.servlet.ServletRequest, jakarta.servlet.ServletResponse, Object) onPreHandle} instead. + * {@link #onPreHandle(ServletRequest, ServletResponse, Object) onPreHandle} instead. * * @param request the incoming ServletRequest * @param response the outgoing ServletResponse @@ -199,20 +207,18 @@ protected boolean pathsMatch(String pattern, String path) { */ @Override protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception { - - if (this.appliedPaths == null || this.appliedPaths.isEmpty()) { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("appliedPaths property is null or empty. This Filter will passthrough immediately."); - } - return true; + // the resolver already matched the path, use its pattern if it is one of ours + String resolvedChain = (String) request.getAttribute(RESOLVED_CHAIN_ATTRIBUTE); + if (appliedPaths.containsKey(resolvedChain)) { + return isFilterChainContinued(request, response, resolvedChain, appliedPaths.get(resolvedChain)); } - for (String path : this.appliedPaths.keySet()) { + for (String path : appliedPaths.keySet()) { // If the path does match, then pass on to the subclass implementation for specific checks //(first match 'wins'): if (pathsMatch(path, request)) { LOGGER.trace("Current requestURI matches pattern '{}'. Determining filter chain execution...", path); - Object config = this.appliedPaths.get(path); + Object config = appliedPaths.get(path); return isFilterChainContinued(request, response, path, config); } } @@ -263,7 +269,7 @@ private boolean isFilterChainContinued(ServletRequest request, ServletResponse r * @return {@code true} if the request should be able to continue, {@code false} if the filter will * handle the response directly. * @throws Exception if an error occurs - * @see #isEnabled(jakarta.servlet.ServletRequest, jakarta.servlet.ServletResponse, String, Object) + * @see #isEnabled(ServletRequest, ServletResponse, String, Object) */ protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception { return true; @@ -272,12 +278,12 @@ protected boolean onPreHandle(ServletRequest request, ServletResponse response, @SuppressWarnings("UnusedParameters") /** * Path-matching version of the parent class's - * {@link #isEnabled(jakarta.servlet.ServletRequest, jakarta.servlet.ServletResponse)} method, but additionally allows + * {@link #isEnabled(ServletRequest, ServletResponse)} method, but additionally allows * for inspection of any path-specific configuration values corresponding to the specified request. Subclasses * may wish to inspect this additional mapped configuration to determine if the filter is enabled or not. *

* This method's default implementation ignores the {@code path} and {@code mappedValue} arguments and merely - * returns the value from a call to {@link #isEnabled(jakarta.servlet.ServletRequest, jakarta.servlet.ServletResponse)}. + * returns the value from a call to {@link #isEnabled(ServletRequest, ServletResponse)}. * It is expected that subclasses override this method if they need to perform enable/disable logic for a specific * request based on any path-specific config for the filter instance. * diff --git a/web/src/main/java/org/apache/shiro/web/filter/mgt/PathMatchingFilterChainResolver.java b/web/src/main/java/org/apache/shiro/web/filter/mgt/PathMatchingFilterChainResolver.java index 91968102d0..941f8939fa 100644 --- a/web/src/main/java/org/apache/shiro/web/filter/mgt/PathMatchingFilterChainResolver.java +++ b/web/src/main/java/org/apache/shiro/web/filter/mgt/PathMatchingFilterChainResolver.java @@ -20,6 +20,7 @@ import org.apache.shiro.util.AntPathMatcher; import org.apache.shiro.util.PatternMatcher; +import org.apache.shiro.web.filter.PathMatchingFilter; import org.apache.shiro.web.util.WebUtils; import org.owasp.encoder.Encode; import org.slf4j.Logger; @@ -114,6 +115,7 @@ public void setFilterChainManager(FilterChainManager filterChainManager) { @Override public FilterChain getChain(ServletRequest request, ServletResponse response, FilterChain originalChain) { + request.removeAttribute(PathMatchingFilter.RESOLVED_CHAIN_ATTRIBUTE); FilterChainManager filterChainManager = getFilterChainManager(); if (!filterChainManager.hasChains()) { return null; @@ -125,29 +127,17 @@ public FilterChain getChain(ServletRequest request, ServletResponse response, Fi //the 'chain names' in this implementation are actually path patterns defined by the user. We just use them //as the chain name for the FilterChainManager's requirements for (String pathPattern : filterChainManager.getChainNames()) { - // If the path does match, then pass on to the subclass implementation for specific checks: - if (pathMatches(pathPattern, requestURI)) { + // in spring web, the requestURI "/resource/menus" ---- "resource/menus/" both can access the resource + // but the pathPattern match "/resource/menus" can not match "resource/menus/" + // user can use requestURI + "/" to simply bypassed chain filter, to bypassed shiro protect + if (pathMatches(pathPattern, requestURI) + || pathMatches(removeTrailingSlash(pathPattern), requestURINoTrailingSlash)) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Matched path pattern [{}] for requestURI [{}]. " + "Utilizing corresponding filter chain...", pathPattern, Encode.forHtml(requestURI)); } + request.setAttribute(PathMatchingFilter.RESOLVED_CHAIN_ATTRIBUTE, pathPattern); return filterChainManager.proxy(originalChain, pathPattern); - } else { - - // in spring web, the requestURI "/resource/menus" ---- "resource/menus/" both can access the resource - // but the pathPattern match "/resource/menus" can not match "resource/menus/" - // user can use requestURI + "/" to simply bypassed chain filter, to bypassed shiro protect - - String pathPatternNoTrailingSlash = removeTrailingSlash(pathPattern); - - if (pathMatches(pathPatternNoTrailingSlash, requestURINoTrailingSlash)) { - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("Matched path pattern [{}] for requestURI [{}]. " - + "Utilizing corresponding filter chain...", - pathPattern, Encode.forHtml(requestURINoTrailingSlash)); - } - return filterChainManager.proxy(originalChain, pathPattern); - } } } diff --git a/web/src/test/java/org/apache/shiro/web/filter/mgt/PathMatchingFilterChainResolverTest.java b/web/src/test/java/org/apache/shiro/web/filter/mgt/PathMatchingFilterChainResolverTest.java index afee0690f3..8939017888 100644 --- a/web/src/test/java/org/apache/shiro/web/filter/mgt/PathMatchingFilterChainResolverTest.java +++ b/web/src/test/java/org/apache/shiro/web/filter/mgt/PathMatchingFilterChainResolverTest.java @@ -19,6 +19,8 @@ package org.apache.shiro.web.filter.mgt; import org.apache.shiro.util.AntPathMatcher; +import org.apache.shiro.util.RegExPatternMatcher; +import org.apache.shiro.web.filter.PathMatchingFilter; import org.apache.shiro.web.WebTest; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -29,9 +31,17 @@ import jakarta.servlet.ServletResponse; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -79,6 +89,37 @@ void testSetters() { assertThat(resolver.getFilterChainManager() instanceof DefaultFilterChainManager).isTrue(); } + @Test + void testFilterEnforcesChainSelectedByNonAntMatcher() throws Exception { + resolver.setPathMatcher(new RegExPatternMatcher()); + List appliedConfigs = new ArrayList<>(); + resolver.getFilterChainManager().addFilter("deny", new PathMatchingFilter() { + @Override + protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) { + appliedConfigs.add(mappedValue); + return false; + } + }); + // as a regex this does not match /secure/report, as an Ant pattern it does + resolver.getFilterChainManager().createChain("/secure/*", "deny[other]"); + resolver.getFilterChainManager().createChain("/secure/[^/]+", "deny[resolved]"); + + Map attributes = new HashMap<>(); + HttpServletRequest request = mock(HttpServletRequest.class); + HttpServletResponse response = mock(HttpServletResponse.class); + FilterChain originalChain = mock(FilterChain.class); + when(request.getServletPath()).thenReturn(""); + when(request.getPathInfo()).thenReturn("/secure/report"); + when(request.getAttribute(anyString())).thenAnswer(call -> attributes.get(call.getArgument(0))); + doAnswer(call -> attributes.put(call.getArgument(0), call.getArgument(1))) + .when(request).setAttribute(anyString(), any()); + + resolver.getChain(request, response, originalChain).doFilter(request, response); + + verify(originalChain, never()).doFilter(request, response); + assertThat((String[]) appliedConfigs.get(0)).containsExactly("resolved"); + } + @Test void testGetChainsWithoutChains() { ServletRequest request = mock(HttpServletRequest.class);