Skip to content

Conversation

@filiphr
Copy link
Contributor

@filiphr filiphr commented Nov 1, 2025

The goal of this PR is to be able to configure the DispatcherServlet to only look for beans in the local application context, i.e. do not look in all ancestors.

The PR is currently only doing this for the HandlerMapping(s). However, if this is something that is acceptable for the Spring Team then I can adjust the rest of the beans in the dispatcher servlet:

  • handlerAdapters
  • handlerExceptionResolvers
  • viewResolvers

The reason for this is that we are using different DispatcherServlet(s) to expose different REST APIs and with Spring Boot Actuator the actuator endpoints were being exposed in our servlets as well. We have remedied that using Spring Security and the AntPathMatcher to block access to **/actuator/*. However, the AntPathMatcher will no longer be there in Spring 7 and I wanted to find a better solution.

I did manage to find WebMvcEndpointChildContextConfiguration from Spring Boot, that is achieving exactly what we are looking for. However, I wanted to see if we can avoid the need of all those CompositeHandlerMapping, CompositeHandlerAdapter, etc. and let the DispatcherServlet itself handle this.

If this gets accepted then the different composites in Spring Boot can be removed, and the Actuator management DispatcherServlet would only need to change

dispatcherServlet.setDetectAllHandlerAdapters(false);
dispatcherServlet.setDetectAllHandlerExceptionResolvers(false);
dispatcherServlet.setDetectAllHandlerMappings(false);
dispatcherServlet.setDetectAllViewResolvers(false);

to something like

dispatcherServlet.detectLocalHandlerMappingsOnly()
dispatcherServlet.detectLocalHandlerExceptionResolversOnly();
dispatcherServlet.detectLocalHandlerMappingsOnly();
dispatcherServlet.detectLocalViewResolversOnly();

I'm also open to adjusting the naming of the methods as well. It does not have to be exactly like I've done in this PR.

Thanks for taking the time and considering this PR

Signed-off-by: Filip Hrisafov <filip.hrisafov@gmail.com>
@spring-projects-issues spring-projects-issues added the status: waiting-for-triage An issue we've not yet triaged or decided on label Nov 1, 2025
@rstoyanchev rstoyanchev added the in: web Issues in web modules (web, webmvc, webflux, websocket) label Nov 4, 2025
@bclozel
Copy link
Member

bclozel commented Nov 5, 2025

Hello @filiphr - independently of this request, I'm wondering if you noticed that PathPattern has been improved recently to closed that gap in security matchers. See #35213

@filiphr
Copy link
Contributor Author

filiphr commented Nov 5, 2025

Thanks for sharing that @bclozel, yes I did notice the improvements in the PathPattern. However, that is not enough for us, since for us the pattern we need is /**/actuator/**. We use that to do a denyAll for all actuator endpoints which are not in the default dispatcher servlet.

We had something like:

public class ActuatorRequestMatcher extends ApplicationContextRequestMatcher<WebApplicationContext> {

    private static final RequestMatcher EMPTY_MATCHER = (request) -> false;

    private volatile RequestMatcher delegate;

    public ActuatorRequestMatcher() {
        super(WebApplicationContext.class);
    }

    @Override
    protected final void initialized(Supplier<WebApplicationContext> context) {
        this.delegate = createDelegate(context.get());
    }

    @Override
    protected final boolean matches(HttpServletRequest request,
        Supplier<WebApplicationContext> context) {
        return this.delegate.matches(request);
    }

    private RequestMatcher createDelegate(WebApplicationContext context) {
        try {
            String pathPrefix = getPathPrefix(context);
            RequestMatcherFactory requestMatcherFactory = new RequestMatcherFactory(pathPrefix);
            return createDelegate(context, requestMatcherFactory);
        } catch (NoSuchBeanDefinitionException ex) {
            return EMPTY_MATCHER;
        }
    }

    private String getPathPrefix(WebApplicationContext context) {
        try {
            return context.getBean(DispatcherServletPath.class).getPrefix();
        } catch (NoSuchBeanDefinitionException ex) {
            return "";
        }
    }

    protected RequestMatcher createDelegate(WebApplicationContext context, RequestMatcherFactory requestMatcherFactory) {
        WebEndpointProperties properties = context.getBean(WebEndpointProperties.class);
        if (StringUtils.isNotEmpty(properties.getBasePath())) {
            return new OrRequestMatcher(
                requestMatcherFactory.antPath(properties.getBasePath() + "/**"),
                requestMatcherFactory.antPath("/**" + properties.getBasePath() + "/**")
            );
        }
        return EMPTY_MATCHER;
    }

    private static class RequestMatcherFactory {

        private final String servletPath;

        RequestMatcherFactory(String servletPath) {
            this.servletPath = servletPath;
        }

        public RequestMatcher antPath(String part) {
            String pattern = (this.servletPath.equals("/") ? "" : this.servletPath);
            return new AntPathRequestMatcher(pattern + part);
        }

    }
}

Which was inspired by the Spring Boot EndpointRequest. And the way we would use it was:

http
        .securityMatcher(new ActuatorRequestMatcher())
        .authorizeHttpRequests(configurer -> configurer
                .requestMatchers(EndpointRequest.to(InfoEndpoint.class, HealthEndpoint.class)).permitAll()
                .requestMatchers(EndpointRequest.toAnyEndpoint()).hasAuthority(SecurityConstants.ACCESS_ACTUATORS)
                .anyRequest().denyAll()
        )
        .httpBasic(Customizer.withDefaults());

We did this long time ago, and back then I was not that well versed in the lower levels of the DispatcherServlet. For us, we don't even want to have the actuator endpoints in the child dispatcher servlets. By the way, I am also now aware that we could have use the applicationContext in the matcher to get all of our custom ServletRegistrationBean(s) that use DispatcherServlet and just use the url mappings defined from there, but that was long time ago and I was that well versed in these low level things.

@bclozel
Copy link
Member

bclozel commented Nov 5, 2025

Ah, thanks for the additional information. PathPattern does not support such patterns because they are costly and tend to cause expectation issues when it comes to sorting matching patterns. We'll consider this PR in due time.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

in: web Issues in web modules (web, webmvc, webflux, websocket) status: waiting-for-triage An issue we've not yet triaged or decided on

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants