Skip to content

Commit

Permalink
Explicitly disable security on management endpoints if requested
Browse files Browse the repository at this point in the history
Previously the management endpoint filter was applied to all requests
if the user had disabled security.management.enabled, but since it
had no security applied it was letting all requests through.

The fix was to explicitly exclude the whole enclosing configuration
and carefully ignore the management endpoints in the normal security
chain.

Fixes gh-100.
  • Loading branch information
Dave Syer committed Oct 31, 2013
1 parent 5e9b8c3 commit 63a2d06
Show file tree
Hide file tree
Showing 3 changed files with 145 additions and 20 deletions.
Expand Up @@ -98,6 +98,8 @@
@EnableConfigurationProperties
public class SecurityAutoConfiguration {

private static final String[] NO_PATHS = new String[0];

@Bean(name = "org.springframework.actuate.properties.SecurityProperties")
@ConditionalOnMissingBean
public SecurityProperties securityProperties() {
Expand All @@ -119,6 +121,7 @@ public WebSecurityConfigurerAdapter applicationWebSecurityConfigurerAdapter() {

@Bean
@ConditionalOnMissingBean({ ManagementWebSecurityConfigurerAdapter.class })
@ConditionalOnExpression("${security.management.enabled:true}")
public WebSecurityConfigurerAdapter managementWebSecurityConfigurerAdapter() {
return new ManagementWebSecurityConfigurerAdapter();
}
Expand All @@ -140,6 +143,9 @@ private static class ApplicationWebSecurityConfigurerAdapter extends
@Autowired(required = false)
private ErrorController errorController;

@Autowired(required = false)
private EndpointHandlerMapping endpointHandlerMapping;

@Override
protected void configure(HttpSecurity http) throws Exception {

Expand Down Expand Up @@ -191,6 +197,10 @@ private AuthenticationEntryPoint entryPoint() {
public void configure(WebSecurity builder) throws Exception {
IgnoredRequestConfigurer ignoring = builder.ignoring();
List<String> ignored = new ArrayList<String>(this.security.getIgnored());
if (!this.security.getManagement().isEnabled()) {
ignored.addAll(Arrays.asList(getEndpointPaths(
this.endpointHandlerMapping, true)));
}
if (ignored.isEmpty()) {
ignored.addAll(DEFAULT_IGNORED);
}
Expand Down Expand Up @@ -220,8 +230,6 @@ protected AuthenticationManager authenticationManager() throws Exception {
private static class ManagementWebSecurityConfigurerAdapter extends
WebSecurityConfigurerAdapter {

private static final String[] NO_PATHS = new String[0];

@Autowired
private SecurityProperties security;

Expand All @@ -234,7 +242,8 @@ private static class ManagementWebSecurityConfigurerAdapter extends
@Override
protected void configure(HttpSecurity http) throws Exception {

String[] paths = getEndpointPaths(true); // secure endpoints
// secure endpoints
String[] paths = getEndpointPaths(this.endpointHandlerMapping, true);
if (paths.length > 0 && this.security.getManagement().isEnabled()) {
// Always protect them if present
if (this.security.isRequireSsl()) {
Expand Down Expand Up @@ -262,7 +271,7 @@ protected void configure(HttpSecurity http) throws Exception {
@Override
public void configure(WebSecurity builder) throws Exception {
IgnoredRequestConfigurer ignoring = builder.ignoring();
ignoring.antMatchers(getEndpointPaths(false));
ignoring.antMatchers(getEndpointPaths(this.endpointHandlerMapping, false));
}

private AuthenticationEntryPoint entryPoint() {
Expand All @@ -271,21 +280,6 @@ private AuthenticationEntryPoint entryPoint() {
return entryPoint;
}

private String[] getEndpointPaths(boolean secure) {
if (this.endpointHandlerMapping == null) {
return NO_PATHS;
}

List<Endpoint<?>> endpoints = this.endpointHandlerMapping.getEndpoints();
List<String> paths = new ArrayList<String>(endpoints.size());
for (Endpoint<?> endpoint : endpoints) {
if (endpoint.isSensitive() == secure) {
paths.add(endpoint.getPath());
}
}
return paths.toArray(new String[paths.size()]);
}

}

@ConditionalOnMissingBean(AuthenticationManager.class)
Expand All @@ -299,7 +293,8 @@ public static class AuthenticationManagerConfiguration {
private SecurityProperties security;

@Bean
public AuthenticationManager authenticationManager(ObjectPostProcessor<Object> objectPostProcessor) throws Exception {
public AuthenticationManager authenticationManager(
ObjectPostProcessor<Object> objectPostProcessor) throws Exception {

InMemoryUserDetailsManagerConfigurer<AuthenticationManagerBuilder> builder = new AuthenticationManagerBuilder(
objectPostProcessor).inMemoryAuthentication();
Expand All @@ -322,6 +317,22 @@ public AuthenticationManager authenticationManager(ObjectPostProcessor<Object> o

}

private static String[] getEndpointPaths(
EndpointHandlerMapping endpointHandlerMapping, boolean secure) {
if (endpointHandlerMapping == null) {
return NO_PATHS;
}

List<Endpoint<?>> endpoints = endpointHandlerMapping.getEndpoints();
List<String> paths = new ArrayList<String>(endpoints.size());
for (Endpoint<?> endpoint : endpoints) {
if (endpoint.isSensitive() == secure) {
paths.add(endpoint.getPath());
}
}
return paths.toArray(new String[paths.size()]);
}

private static void configureHeaders(HeadersConfigurer<?> configurer,
SecurityProperties.Headers headers) throws Exception {
if (headers.getHsts() != Headers.HSTS.none) {
Expand Down
Expand Up @@ -2,4 +2,5 @@
<configuration>
<include resource="org/springframework/boot/logging/logback/base.xml"/>
<!-- logger name="org.springframework.boot" level="DEBUG"/-->
<!-- logger name="org.springframework.security" level="DEBUG"/-->
</configuration>
@@ -0,0 +1,113 @@
/*
* Copyright 2012-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.springframework.boot.sample.ops;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

/**
* Integration tests for unsecured service endpoints (even with Spring Security on
* classpath).
*
* @author Dave Syer
*/
public class UnsecureManagementSampleActuatorApplicationTests {

private static ConfigurableApplicationContext context;

@BeforeClass
public static void start() throws Exception {
Future<ConfigurableApplicationContext> future = Executors
.newSingleThreadExecutor().submit(
new Callable<ConfigurableApplicationContext>() {
@Override
public ConfigurableApplicationContext call() throws Exception {
return (ConfigurableApplicationContext) SpringApplication
.run(SampleActuatorApplication.class,
"--security.management.enabled=false");
}
});
context = future.get(60, TimeUnit.SECONDS);
}

@AfterClass
public static void stop() {
if (context != null) {
context.close();
}
}

@Test
public void testHomeIsSecure() throws Exception {
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = getRestTemplate().getForEntity(
"http://localhost:8080", Map.class);
assertEquals(HttpStatus.UNAUTHORIZED, entity.getStatusCode());
@SuppressWarnings("unchecked")
Map<String, Object> body = entity.getBody();
assertEquals("Wrong body: " + body, "Unauthorized", body.get("error"));
assertFalse("Wrong headers: " + entity.getHeaders(), entity.getHeaders()
.containsKey("Set-Cookie"));
}

@Test
public void testMetrics() throws Exception {
try {
testHomeIsSecure(); // makes sure some requests have been made
} catch (AssertionError e) {
// ignore;
}
@SuppressWarnings("rawtypes")
ResponseEntity<Map> entity = getRestTemplate().getForEntity(
"http://localhost:8080/metrics", Map.class);
assertEquals(HttpStatus.OK, entity.getStatusCode());
@SuppressWarnings("unchecked")
Map<String, Object> body = entity.getBody();
assertTrue("Wrong body: " + body, body.containsKey("counter.status.401.root"));
}

private RestTemplate getRestTemplate() {
RestTemplate restTemplate = new RestTemplate();
restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
@Override
public void handleError(ClientHttpResponse response) throws IOException {
}
});
return restTemplate;

}

}

0 comments on commit 63a2d06

Please sign in to comment.