Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;

Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -82,13 +83,15 @@ 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("");

expect(request.getCharacterEncoding()).andStubReturn(null);

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);
Expand All @@ -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("");

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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
Expand Down Expand Up @@ -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.
* <p/>
* 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
Expand All @@ -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);
}
}
Expand Down Expand Up @@ -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;
Expand All @@ -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.
* <p/>
* 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.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand All @@ -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);
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -79,6 +89,37 @@ void testSetters() {
assertThat(resolver.getFilterChainManager() instanceof DefaultFilterChainManager).isTrue();
}

@Test
void testFilterEnforcesChainSelectedByNonAntMatcher() throws Exception {
resolver.setPathMatcher(new RegExPatternMatcher());
List<Object> 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<String, Object> 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.<String>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);
Expand Down
Loading