Skip to content

Commit d7ff379

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-35559
1 parent e1663e2 commit d7ff379

File tree

8 files changed

+347
-46
lines changed

8 files changed

+347
-46
lines changed

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

+40-13
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.
@@ -110,6 +110,7 @@
110110
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
111111
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
112112
import org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver;
113+
import org.springframework.web.servlet.handler.AbstractUrlHandlerMapping;
113114
import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver;
114115
import org.springframework.web.servlet.i18n.FixedLocaleResolver;
115116
import org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver;
@@ -453,12 +454,29 @@ public RequestMappingHandlerMapping requestMappingHandlerMapping(
453454
@Bean
454455
public WelcomePageHandlerMapping welcomePageHandlerMapping(ApplicationContext applicationContext,
455456
FormattingConversionService mvcConversionService, ResourceUrlProvider mvcResourceUrlProvider) {
456-
WelcomePageHandlerMapping welcomePageHandlerMapping = new WelcomePageHandlerMapping(
457-
new TemplateAvailabilityProviders(applicationContext), applicationContext, getWelcomePage(),
458-
this.mvcProperties.getStaticPathPattern());
459-
welcomePageHandlerMapping.setInterceptors(getInterceptors(mvcConversionService, mvcResourceUrlProvider));
460-
welcomePageHandlerMapping.setCorsConfigurations(getCorsConfigurations());
461-
return welcomePageHandlerMapping;
457+
return createWelcomePageHandlerMapping(applicationContext, mvcConversionService, mvcResourceUrlProvider,
458+
WelcomePageHandlerMapping::new);
459+
}
460+
461+
@Bean
462+
public WelcomePageNotAcceptableHandlerMapping welcomePageNotAcceptableHandlerMapping(
463+
ApplicationContext applicationContext, FormattingConversionService mvcConversionService,
464+
ResourceUrlProvider mvcResourceUrlProvider) {
465+
return createWelcomePageHandlerMapping(applicationContext, mvcConversionService, mvcResourceUrlProvider,
466+
WelcomePageNotAcceptableHandlerMapping::new);
467+
}
468+
469+
private <T extends AbstractUrlHandlerMapping> T createWelcomePageHandlerMapping(
470+
ApplicationContext applicationContext, FormattingConversionService mvcConversionService,
471+
ResourceUrlProvider mvcResourceUrlProvider, WelcomePageHandlerMappingFactory<T> factory) {
472+
TemplateAvailabilityProviders templateAvailabilityProviders = new TemplateAvailabilityProviders(
473+
applicationContext);
474+
String staticPathPattern = this.mvcProperties.getStaticPathPattern();
475+
T handlerMapping = factory.create(templateAvailabilityProviders, applicationContext, getIndexHtmlResource(),
476+
staticPathPattern);
477+
handlerMapping.setInterceptors(getInterceptors(mvcConversionService, mvcResourceUrlProvider));
478+
handlerMapping.setCorsConfigurations(getCorsConfigurations());
479+
return handlerMapping;
462480
}
463481

464482
@Override
@@ -493,25 +511,25 @@ public FlashMapManager flashMapManager() {
493511
return super.flashMapManager();
494512
}
495513

496-
private Resource getWelcomePage() {
514+
private Resource getIndexHtmlResource() {
497515
for (String location : this.resourceProperties.getStaticLocations()) {
498-
Resource indexHtml = getIndexHtml(location);
516+
Resource indexHtml = getIndexHtmlResource(location);
499517
if (indexHtml != null) {
500518
return indexHtml;
501519
}
502520
}
503521
ServletContext servletContext = getServletContext();
504522
if (servletContext != null) {
505-
return getIndexHtml(new ServletContextResource(servletContext, SERVLET_LOCATION));
523+
return getIndexHtmlResource(new ServletContextResource(servletContext, SERVLET_LOCATION));
506524
}
507525
return null;
508526
}
509527

510-
private Resource getIndexHtml(String location) {
511-
return getIndexHtml(this.resourceLoader.getResource(location));
528+
private Resource getIndexHtmlResource(String location) {
529+
return getIndexHtmlResource(this.resourceLoader.getResource(location));
512530
}
513531

514-
private Resource getIndexHtml(Resource location) {
532+
private Resource getIndexHtmlResource(Resource location) {
515533
try {
516534
Resource resource = location.createRelative("index.html");
517535
if (resource.exists() && (resource.getURL() != null)) {
@@ -626,6 +644,15 @@ ResourceChainResourceHandlerRegistrationCustomizer resourceHandlerRegistrationCu
626644

627645
}
628646

647+
@FunctionalInterface
648+
interface WelcomePageHandlerMappingFactory<T extends AbstractUrlHandlerMapping> {
649+
650+
T create(TemplateAvailabilityProviders templateAvailabilityProviders, ApplicationContext applicationContext,
651+
Resource indexHtmlResource, String staticPathPattern);
652+
653+
}
654+
655+
@FunctionalInterface
629656
interface ResourceHandlerRegistrationCustomizer {
630657

631658
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

+4-4
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.
@@ -171,7 +171,7 @@ void handlerAdaptersCreated() {
171171

172172
@Test
173173
void handlerMappingsCreated() {
174-
this.contextRunner.run((context) -> assertThat(context).getBeans(HandlerMapping.class).hasSize(5));
174+
this.contextRunner.run((context) -> assertThat(context).getBeans(HandlerMapping.class).hasSize(6));
175175
}
176176

177177
@Test
@@ -685,8 +685,8 @@ private ContextConsumer<AssertableWebApplicationContext> assertExceptionResolver
685685
void welcomePageHandlerMappingIsAutoConfigured(String prefix) {
686686
this.contextRunner.withPropertyValues(prefix + "static-locations:classpath:/welcome-page/").run((context) -> {
687687
assertThat(context).hasSingleBean(WelcomePageHandlerMapping.class);
688-
WelcomePageHandlerMapping bean = context.getBean(WelcomePageHandlerMapping.class);
689-
assertThat(bean.getRootHandler()).isNotNull();
688+
assertThat(context.getBean(WelcomePageHandlerMapping.class).getRootHandler()).isNotNull();
689+
assertThat(context.getBean(WelcomePageNotAcceptableHandlerMapping.class).getRootHandler()).isNotNull();
690690
});
691691
}
692692

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

+1-2
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.
@@ -105,7 +105,6 @@ void handlesRequestWithEmptyAcceptHeader() {
105105
.run((context) -> MockMvcBuilders.webAppContextSetup(context).build()
106106
.perform(get("/").header(HttpHeaders.ACCEPT, "")).andExpect(status().isOk())
107107
.andExpect(forwardedUrl("index.html")));
108-
109108
}
110109

111110
@Test

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

+11-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/*
2-
* Copyright 2012-2019 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.
@@ -29,6 +29,7 @@
2929
import org.springframework.boot.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;
@@ -56,6 +57,15 @@ void contentStrategyWithWelcomePage() throws Exception {
5657
.header("Accept", MediaType.ALL.toString()).build();
5758
ResponseEntity<String> content = this.template.exchange(entity, String.class);
5859
assertThat(content.getBody()).contains("/custom-");
60+
assertThat(content.getStatusCode()).isEqualTo(HttpStatus.OK);
61+
}
62+
63+
@Test
64+
void notAcceptableWelcomePage() throws Exception {
65+
RequestEntity<?> entity = RequestEntity.get(new URI("http://localhost:" + this.port + "/"))
66+
.header("Accept", "spring/boot").build();
67+
ResponseEntity<String> content = this.template.exchange(entity, String.class);
68+
assertThat(content.getStatusCode()).isEqualTo(HttpStatus.NOT_ACCEPTABLE);
5969
}
6070

6171
@Configuration

0 commit comments

Comments
 (0)