Skip to content

Commit 418dd1b

Browse files
philwebbwilkinsona
authored andcommitted
Return 406 status code if welcome page is not accepted
Add `WelcomePageNotAcceptableHandlerMapping` which will return an HTTP 406 status if a suitable welcome page is found but cannot be accepted for the request. An additional mapper is used so that we don't need to change the order of the `WelcomePageHandlerMapping`. It's possible that users may have additional root handler mappings registered to run after the `WelcomePageHandlerMapping` and we still need to respect those. Fixes gh-35552
1 parent cc2bb7c commit 418dd1b

File tree

8 files changed

+356
-42
lines changed

8 files changed

+356
-42
lines changed

spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration.java

+39-12
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,7 @@
108108
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
109109
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
110110
import org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver;
111+
import org.springframework.web.servlet.handler.AbstractUrlHandlerMapping;
111112
import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver;
112113
import org.springframework.web.servlet.i18n.FixedLocaleResolver;
113114
import org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver;
@@ -437,12 +438,29 @@ protected RequestMappingHandlerAdapter createRequestMappingHandlerAdapter() {
437438
@Bean
438439
public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext,
439440
FormattingConversionService mvcConversionService, ResourceUrlProvider mvcResourceUrlProvider) {
440-
WelcomePageHandlerMapping welcomePageHandlerMapping = new WelcomePageHandlerMapping(
441-
new TemplateAvailabilityProviders(applicationContext), applicationContext, getWelcomePage(),
442-
this.mvcProperties.getStaticPathPattern());
443-
welcomePageHandlerMapping.setInterceptors(getInterceptors(mvcConversionService, mvcResourceUrlProvider));
444-
welcomePageHandlerMapping.setCorsConfigurations(getCorsConfigurations());
445-
return welcomePageHandlerMapping;
441+
return createWelcomePageHandlerMapping(applicationContext, mvcConversionService, mvcResourceUrlProvider,
442+
WelcomePageHandlerMapping::new);
443+
}
444+
445+
@Bean
446+
public WelcomePageNotAcceptableHandlerMapping welcomePageNotAcceptableHandlerMapping(
447+
ApplicationContext applicationContext, FormattingConversionService mvcConversionService,
448+
ResourceUrlProvider mvcResourceUrlProvider) {
449+
return createWelcomePageHandlerMapping(applicationContext, mvcConversionService, mvcResourceUrlProvider,
450+
WelcomePageNotAcceptableHandlerMapping::new);
451+
}
452+
453+
private <T extends AbstractUrlHandlerMapping> T createWelcomePageHandlerMapping(
454+
ApplicationContext applicationContext, FormattingConversionService mvcConversionService,
455+
ResourceUrlProvider mvcResourceUrlProvider, WelcomePageHandlerMappingFactory<T> factory) {
456+
TemplateAvailabilityProviders templateAvailabilityProviders = new TemplateAvailabilityProviders(
457+
applicationContext);
458+
String staticPathPattern = this.mvcProperties.getStaticPathPattern();
459+
T handlerMapping = factory.create(templateAvailabilityProviders, applicationContext, getIndexHtmlResource(),
460+
staticPathPattern);
461+
handlerMapping.setInterceptors(getInterceptors(mvcConversionService, mvcResourceUrlProvider));
462+
handlerMapping.setCorsConfigurations(getCorsConfigurations());
463+
return handlerMapping;
446464
}
447465

448466
@Override
@@ -471,25 +489,25 @@ public FlashMapManager flashMapManager() {
471489
return super.flashMapManager();
472490
}
473491

474-
private Resource getWelcomePage() {
492+
private Resource getIndexHtmlResource() {
475493
for (String location : this.resourceProperties.getStaticLocations()) {
476-
Resource indexHtml = getIndexHtml(location);
494+
Resource indexHtml = getIndexHtmlResource(location);
477495
if (indexHtml != null) {
478496
return indexHtml;
479497
}
480498
}
481499
ServletContext servletContext = getServletContext();
482500
if (servletContext != null) {
483-
return getIndexHtml(new ServletContextResource(servletContext, SERVLET_LOCATION));
501+
return getIndexHtmlResource(new ServletContextResource(servletContext, SERVLET_LOCATION));
484502
}
485503
return null;
486504
}
487505

488-
private Resource getIndexHtml(String location) {
489-
return getIndexHtml(this.resourceLoader.getResource(location));
506+
private Resource getIndexHtmlResource(String location) {
507+
return getIndexHtmlResource(this.resourceLoader.getResource(location));
490508
}
491509

492-
private Resource getIndexHtml(Resource location) {
510+
private Resource getIndexHtmlResource(Resource location) {
493511
try {
494512
Resource resource = location.createRelative("index.html");
495513
if (resource.exists() && (resource.getURL() != null)) {
@@ -603,6 +621,15 @@ ResourceChainResourceHandlerRegistrationCustomizer resourceHandlerRegistrationCu
603621

604622
}
605623

624+
@FunctionalInterface
625+
interface WelcomePageHandlerMappingFactory<T extends AbstractUrlHandlerMapping> {
626+
627+
T create(TemplateAvailabilityProviders templateAvailabilityProviders, ApplicationContext applicationContext,
628+
Resource indexHtmlResource, String staticPathPattern);
629+
630+
}
631+
632+
@FunctionalInterface
606633
interface ResourceHandlerRegistrationCustomizer {
607634

608635
void customize(ResourceHandlerRegistration registration);
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
/*
2+
* Copyright 2012-2023 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package org.springframework.boot.autoconfigure.web.servlet;
18+
19+
import org.springframework.boot.autoconfigure.template.TemplateAvailabilityProviders;
20+
import org.springframework.context.ApplicationContext;
21+
import org.springframework.core.io.Resource;
22+
23+
/**
24+
* Details for a welcome page resolved from a resource or a template.
25+
*
26+
* @author Phillip Webb
27+
*/
28+
final class WelcomePage {
29+
30+
/**
31+
* Value used for an unresolved welcome page.
32+
*/
33+
static final WelcomePage UNRESOLVED = new WelcomePage(null, false);
34+
35+
private final String viewName;
36+
37+
private final boolean templated;
38+
39+
private WelcomePage(String viewName, boolean templated) {
40+
this.viewName = viewName;
41+
this.templated = templated;
42+
}
43+
44+
/**
45+
* Return the view name of the welcome page.
46+
* @return the view name
47+
*/
48+
String getViewName() {
49+
return this.viewName;
50+
}
51+
52+
/**
53+
* Return if the welcome page is from a template.
54+
* @return if the welcome page is templated
55+
*/
56+
boolean isTemplated() {
57+
return this.templated;
58+
}
59+
60+
/**
61+
* Resolve the {@link WelcomePage} to use.
62+
* @param templateAvailabilityProviders the template availability providers
63+
* @param applicationContext the application context
64+
* @param indexHtmlResource the index HTML resource to use or {@code null}
65+
* @param staticPathPattern the static path pattern being used
66+
* @return a resolved {@link WelcomePage} instance or {@link #UNRESOLVED}
67+
*/
68+
static WelcomePage resolve(TemplateAvailabilityProviders templateAvailabilityProviders,
69+
ApplicationContext applicationContext, Resource indexHtmlResource, String staticPathPattern) {
70+
if (indexHtmlResource != null && "/**".equals(staticPathPattern)) {
71+
return new WelcomePage("forward:index.html", false);
72+
}
73+
if (templateAvailabilityProviders.getProvider("index", applicationContext) != null) {
74+
return new WelcomePage("index", true);
75+
}
76+
return UNRESOLVED;
77+
}
78+
79+
}

spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/servlet/WelcomePageHandlerMapping.java

+22-26
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2012-2021 the original author or authors.
2+
* Copyright 2012-2023 the original author or authors.
33
*
44
* Licensed under the Apache License, Version 2.0 (the "License");
55
* you may not use this file except in compliance with the License.
@@ -27,19 +27,21 @@
2727
import org.springframework.boot.autoconfigure.template.TemplateAvailabilityProviders;
2828
import org.springframework.context.ApplicationContext;
2929
import org.springframework.core.io.Resource;
30+
import org.springframework.core.log.LogMessage;
3031
import org.springframework.http.HttpHeaders;
3132
import org.springframework.http.MediaType;
3233
import org.springframework.util.StringUtils;
3334
import org.springframework.web.servlet.handler.AbstractUrlHandlerMapping;
3435
import org.springframework.web.servlet.mvc.ParameterizableViewController;
3536

3637
/**
37-
* An {@link AbstractUrlHandlerMapping} for an application's welcome page. Supports both
38-
* static and templated files. If both a static and templated index page are available,
39-
* the static page is preferred.
38+
* An {@link AbstractUrlHandlerMapping} for an application's HTML welcome page. Supports
39+
* both static and templated files. If both a static and templated index page are
40+
* available, the static page is preferred.
4041
*
4142
* @author Andy Wilkinson
4243
* @author Bruce Brouwer
44+
* @see WelcomePageNotAcceptableHandlerMapping
4345
*/
4446
final class WelcomePageHandlerMapping extends AbstractUrlHandlerMapping {
4547

@@ -48,37 +50,31 @@ final class WelcomePageHandlerMapping extends AbstractUrlHandlerMapping {
4850
private static final List<MediaType> MEDIA_TYPES_ALL = Collections.singletonList(MediaType.ALL);
4951

5052
WelcomePageHandlerMapping(TemplateAvailabilityProviders templateAvailabilityProviders,
51-
ApplicationContext applicationContext, Resource welcomePage, String staticPathPattern) {
52-
if (welcomePage != null && "/**".equals(staticPathPattern)) {
53-
logger.info("Adding welcome page: " + welcomePage);
54-
setRootViewName("forward:index.html");
55-
}
56-
else if (welcomeTemplateExists(templateAvailabilityProviders, applicationContext)) {
57-
logger.info("Adding welcome page template: index");
58-
setRootViewName("index");
59-
}
60-
}
61-
62-
private boolean welcomeTemplateExists(TemplateAvailabilityProviders templateAvailabilityProviders,
63-
ApplicationContext applicationContext) {
64-
return templateAvailabilityProviders.getProvider("index", applicationContext) != null;
65-
}
66-
67-
private void setRootViewName(String viewName) {
68-
ParameterizableViewController controller = new ParameterizableViewController();
69-
controller.setViewName(viewName);
70-
setRootHandler(controller);
53+
ApplicationContext applicationContext, Resource indexHtmlResource, String staticPathPattern) {
7154
setOrder(2);
55+
WelcomePage welcomePage = WelcomePage.resolve(templateAvailabilityProviders, applicationContext,
56+
indexHtmlResource, staticPathPattern);
57+
if (welcomePage != WelcomePage.UNRESOLVED) {
58+
logger.info(LogMessage.of(() -> (!welcomePage.isTemplated()) ? "Adding welcome page: " + indexHtmlResource
59+
: "Adding welcome page template: index"));
60+
ParameterizableViewController controller = new ParameterizableViewController();
61+
controller.setViewName(welcomePage.getViewName());
62+
setRootHandler(controller);
63+
}
7264
}
7365

7466
@Override
7567
public Object getHandlerInternal(HttpServletRequest request) throws Exception {
68+
return (!isHtmlTextAccepted(request)) ? null : super.getHandlerInternal(request);
69+
}
70+
71+
private boolean isHtmlTextAccepted(HttpServletRequest request) {
7672
for (MediaType mediaType : getAcceptedMediaTypes(request)) {
7773
if (mediaType.includes(MediaType.TEXT_HTML)) {
78-
return super.getHandlerInternal(request);
74+
return true;
7975
}
8076
}
81-
return null;
77+
return false;
8278
}
8379

8480
private List<MediaType> getAcceptedMediaTypes(HttpServletRequest request) {
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
/*
2+
* Copyright 2012-2023 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package org.springframework.boot.autoconfigure.web.servlet;
18+
19+
import javax.servlet.http.HttpServletRequest;
20+
import javax.servlet.http.HttpServletResponse;
21+
22+
import org.springframework.boot.autoconfigure.template.TemplateAvailabilityProviders;
23+
import org.springframework.context.ApplicationContext;
24+
import org.springframework.core.io.Resource;
25+
import org.springframework.http.HttpStatus;
26+
import org.springframework.web.servlet.ModelAndView;
27+
import org.springframework.web.servlet.handler.AbstractUrlHandlerMapping;
28+
import org.springframework.web.servlet.mvc.Controller;
29+
30+
/**
31+
* An {@link AbstractUrlHandlerMapping} for an application's welcome page that was
32+
* ultimately not accepted.
33+
*
34+
* @author Phillip Webb
35+
*/
36+
class WelcomePageNotAcceptableHandlerMapping extends AbstractUrlHandlerMapping {
37+
38+
WelcomePageNotAcceptableHandlerMapping(TemplateAvailabilityProviders templateAvailabilityProviders,
39+
ApplicationContext applicationContext, Resource indexHtmlResource, String staticPathPattern) {
40+
setOrder(LOWEST_PRECEDENCE - 10); // Before ResourceHandlerRegistry
41+
WelcomePage welcomePage = WelcomePage.resolve(templateAvailabilityProviders, applicationContext,
42+
indexHtmlResource, staticPathPattern);
43+
if (welcomePage != WelcomePage.UNRESOLVED) {
44+
setRootHandler((Controller) this::handleRequest);
45+
}
46+
}
47+
48+
private ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) {
49+
response.setStatus(HttpStatus.NOT_ACCEPTABLE.value());
50+
return null;
51+
}
52+
53+
@Override
54+
protected Object getHandlerInternal(HttpServletRequest request) throws Exception {
55+
return super.getHandlerInternal(request);
56+
}
57+
58+
}

spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfigurationTests.java

+3-3
Original file line numberDiff line numberDiff line change
@@ -169,7 +169,7 @@ void handlerAdaptersCreated() {
169169

170170
@Test
171171
void handlerMappingsCreated() {
172-
this.contextRunner.run((context) -> assertThat(context).getBeans(HandlerMapping.class).hasSize(5));
172+
this.contextRunner.run((context) -> assertThat(context).getBeans(HandlerMapping.class).hasSize(6));
173173
}
174174

175175
@Test
@@ -687,8 +687,8 @@ void welcomePageHandlerMappingIsAutoConfigured() {
687687
this.contextRunner.withPropertyValues("spring.web.resources.static-locations:classpath:/welcome-page/")
688688
.run((context) -> {
689689
assertThat(context).hasSingleBean(WelcomePageHandlerMapping.class);
690-
WelcomePageHandlerMapping bean = context.getBean(WelcomePageHandlerMapping.class);
691-
assertThat(bean.getRootHandler()).isNotNull();
690+
assertThat(context.getBean(WelcomePageHandlerMapping.class).getRootHandler()).isNotNull();
691+
assertThat(context.getBean(WelcomePageNotAcceptableHandlerMapping.class).getRootHandler()).isNotNull();
692692
});
693693
}
694694

spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/WelcomePageHandlerMappingTests.java

-1
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,6 @@ void handlesRequestWithEmptyAcceptHeader() {
116116
.perform(get("/").header(HttpHeaders.ACCEPT, ""))
117117
.andExpect(status().isOk())
118118
.andExpect(forwardedUrl("index.html")));
119-
120119
}
121120

122121
@Test

spring-boot-project/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/web/servlet/WelcomePageIntegrationTests.java

+11
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
import org.springframework.boot.test.web.server.LocalServerPort;
3030
import org.springframework.context.annotation.Configuration;
3131
import org.springframework.context.annotation.Import;
32+
import org.springframework.http.HttpStatus;
3233
import org.springframework.http.MediaType;
3334
import org.springframework.http.RequestEntity;
3435
import org.springframework.http.ResponseEntity;
@@ -57,6 +58,16 @@ void contentStrategyWithWelcomePage() throws Exception {
5758
.build();
5859
ResponseEntity<String> content = this.template.exchange(entity, String.class);
5960
assertThat(content.getBody()).contains("/custom-");
61+
assertThat(content.getStatusCode()).isEqualTo(HttpStatus.OK);
62+
}
63+
64+
@Test
65+
void notAcceptableWelcomePage() throws Exception {
66+
RequestEntity<?> entity = RequestEntity.get(new URI("http://localhost:" + this.port + "/"))
67+
.header("Accept", "spring/boot")
68+
.build();
69+
ResponseEntity<String> content = this.template.exchange(entity, String.class);
70+
assertThat(content.getStatusCode()).isEqualTo(HttpStatus.NOT_ACCEPTABLE);
6071
}
6172

6273
@Configuration

0 commit comments

Comments
 (0)