Skip to content

Commit

Permalink
refactor(spring-security): refactor spring security from 5.x to 6.x w…
Browse files Browse the repository at this point in the history
…ith spring boot upgrade to 3.x

While upgrading the spring boot to 3.0.13 and spring cloud 2022.0.5, encountered the below errors during build process of kork-actuator module:
```
> Task :kork-actuator:compileJava FAILED
/kork/kork-actuator/src/main/java/com/netflix/spinnaker/kork/actuator/ActuatorEndpointsConfiguration.java:26: error: cannot find symbol
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
                                                                       ^
  symbol:   class WebSecurityConfigurerAdapter
  location: package org.springframework.security.config.annotation.web.configuration
/kork/kork-actuator/src/main/java/com/netflix/spinnaker/kork/actuator/ActuatorEndpointsConfiguration.java:30: error: cannot find symbol
public class ActuatorEndpointsConfiguration extends WebSecurityConfigurerAdapter {
                                                    ^
  symbol: class WebSecurityConfigurerAdapter
2 errors
```
With spring boot upgrade, spring security also upgrades from 5.x to 6.x. As per the migration [steps](https://www.baeldung.com/spring-security-migrate-5-to-6), `WebSecurityConfigurerAdapter` has been removed. So, it is not required to be extended, instead bean can be registered.

```
> Task :kork-actuator:compileJava FAILED
/kork/kork-actuator/src/main/java/com/netflix/spinnaker/kork/actuator/endpoint/ResolvedEnvironmentEndpoint.java:45: error: invalid method reference
        .ifPresent(sanitizer::setKeysToSanitize);
                   ^
  cannot find symbol
    symbol:   method setKeysToSanitize(T)
    location: class Sanitizer
  where T is a type-variable:
    T extends Object declared in class Optional
/kork/kork-actuator/src/main/java/com/netflix/spinnaker/kork/actuator/endpoint/ResolvedEnvironmentEndpoint.java:56: error: incompatible types: String cannot be converted to SanitizableData
                    return sanitizer.sanitize(property, environment.getProperty(property));
                                              ^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
2 errors
```
In spring boot 3, changes are introduced in sanitization of actuator [endpoints](https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-3.0-Migration-Guide#actuator-endpoints-sanitization).
Default `Sanitizer` implementation has been removed and replaced with `SanitizingFunction`.
spring-projects/spring-boot#33448
spring-projects/spring-boot#39243
spring-projects/spring-boot#32156
So, added the `ActuatorSanitizingFunction` class to provide the default implementation of `SanitizingFunction`.
  • Loading branch information
j-sandy committed Dec 19, 2024
1 parent 05883be commit 5d5bdc3
Show file tree
Hide file tree
Showing 8 changed files with 184 additions and 27 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,22 +19,28 @@

import org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest;
import org.springframework.boot.actuate.health.HealthEndpoint;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@Order(Ordered.HIGHEST_PRECEDENCE + 67)
public class ActuatorEndpointsConfiguration extends WebSecurityConfigurerAdapter {
@EnableWebSecurity
public class ActuatorEndpointsConfiguration {

@Override
public void configure(HttpSecurity http) throws Exception {
@Bean
public SecurityFilterChain configure(HttpSecurity http) throws Exception {
// The health endpoint should always be exposed without auth.
http.requestMatcher(EndpointRequest.to(HealthEndpoint.class))
.authorizeRequests()
http.securityMatcher(EndpointRequest.to(HealthEndpoint.class));
http.authorizeHttpRequests()
.requestMatchers(EndpointRequest.to(HealthEndpoint.class))
.permitAll()
.anyRequest()
.permitAll();
.authenticated();
return http.build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
/*
* Copyright 2024 OpsMx, Inc.
*
* 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 com.netflix.spinnaker.kork.actuator;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.springframework.boot.actuate.endpoint.SanitizableData;
import org.springframework.boot.actuate.endpoint.SanitizingFunction;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component
public class ActuatorSanitizingFunction implements SanitizingFunction {

private static final String[] REGEX_PARTS = {"*", "$", "^", "+"};
private static final Set<String> DEFAULT_KEYS_TO_SANITIZE =
Set.of(
"password",
"secret",
"key",
"token",
".*credentials.*",
"vcap_services",
"^vcap\\.services.*$",
"sun.java.command",
"^spring[._]application[._]json$");
private static final Set<String> URI_USERINFO_KEYS =
Set.of("uri", "uris", "url", "urls", "address", "addresses");
private static final Pattern URI_USERINFO_PATTERN =
Pattern.compile("^\\[?[A-Za-z][A-Za-z0-9\\+\\.\\-]+://.+:(.*)@.+$");
private List<Pattern> keysToSanitize = new ArrayList<>();

public ActuatorSanitizingFunction(List<String> additionalKeysToSanitize) {
addKeysToSanitize(DEFAULT_KEYS_TO_SANITIZE);
addKeysToSanitize(URI_USERINFO_KEYS);
addKeysToSanitize(additionalKeysToSanitize);
}

public ActuatorSanitizingFunction() {
addKeysToSanitize(DEFAULT_KEYS_TO_SANITIZE);
addKeysToSanitize(URI_USERINFO_KEYS);
}

private void addKeysToSanitize(Collection<String> keysToSanitize) {
for (String key : keysToSanitize) {
this.keysToSanitize.add(getPattern(key));
}
}

private Pattern getPattern(String value) {
if (isRegex(value)) {
return Pattern.compile(value, Pattern.CASE_INSENSITIVE);
}
return Pattern.compile(".*" + value + "$", Pattern.CASE_INSENSITIVE);
}

private boolean isRegex(String value) {
for (String part : REGEX_PARTS) {
if (value.contains(part)) {
return true;
}
}
return false;
}

public void setKeysToSanitize(String... keysToSanitize) {
if (keysToSanitize != null) {
for (String key : keysToSanitize) {
this.keysToSanitize.add(getPattern(key)); // todo: clear oll existing the make the list.
}
}
}

@Override
public SanitizableData apply(SanitizableData data) {
if (data.getValue() == null) {
return data;
}

for (Pattern pattern : keysToSanitize) {
if (pattern.matcher(data.getKey()).matches()) {
if (keyIsUriWithUserInfo(pattern)) {
return data.withValue(sanitizeUris(data.getValue().toString()));
}

return data.withValue(SanitizableData.SANITIZED_VALUE);
}
}

return data;
}

private boolean keyIsUriWithUserInfo(Pattern pattern) {
for (String uriKey : URI_USERINFO_KEYS) {
if (pattern.matcher(uriKey).matches()) {
return true;
}
}
return false;
}

private Object sanitizeUris(String value) {
return Arrays.stream(value.split(",")).map(this::sanitizeUri).collect(Collectors.joining(","));
}

private String sanitizeUri(String value) {
Matcher matcher = URI_USERINFO_PATTERN.matcher(value);
String password = matcher.matches() ? matcher.group(1) : null;
if (password != null) {
return StringUtils.replace(
value, ":" + password + "@", ":" + SanitizableData.SANITIZED_VALUE + "@");
}
return value;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,16 @@

import static java.lang.String.format;

import com.netflix.spinnaker.kork.actuator.ActuatorSanitizingFunction;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.endpoint.SanitizableData;
import org.springframework.boot.actuate.endpoint.Sanitizer;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
Expand All @@ -33,7 +36,9 @@
@Endpoint(id = "resolvedEnv")
public class ResolvedEnvironmentEndpoint {

private final Sanitizer sanitizer = new Sanitizer();
private final Sanitizer sanitizer;
private final ActuatorSanitizingFunction actuatorSanitizingFunction =
new ActuatorSanitizingFunction();
private final Environment environment;

@Autowired
Expand All @@ -42,7 +47,8 @@ public ResolvedEnvironmentEndpoint(
this.environment = environment;
Optional.ofNullable(properties.getKeysToSanitize())
.map(p -> p.toArray(new String[0]))
.ifPresent(sanitizer::setKeysToSanitize);
.ifPresent(actuatorSanitizingFunction::setKeysToSanitize);
sanitizer = new Sanitizer(List.of(actuatorSanitizingFunction));
}

@ReadOperation
Expand All @@ -53,7 +59,9 @@ public Map<String, Object> resolvedEnv() {
property -> property,
property -> {
try {
return sanitizer.sanitize(property, environment.getProperty(property));
return sanitizer.sanitize(
new SanitizableData(null, property, environment.getProperty(property)),
true);
} catch (Exception e) {
return format("Exception occurred: %s", e.getMessage());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,19 +36,20 @@
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.test.context.TestPropertySource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.util.UriComponentsBuilder;
import retrofit.RetrofitError;
import retrofit.client.Response;
Expand Down Expand Up @@ -153,10 +154,12 @@ private URI getUri(String path) {
@EnableAutoConfiguration
static class TestControllerConfiguration {
@EnableWebSecurity
class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().headers().disable().authorizeRequests().anyRequest().permitAll();
class WebSecurityConfig implements WebMvcConfigurer {
@Bean
protected SecurityFilterChain configure(HttpSecurity http) throws Exception {
http.csrf().disable().headers().disable();
http.authorizeRequests().anyRequest().permitAll();
return http.build();
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.context.annotation.Bean;
import org.springframework.test.context.TestPropertySource;
import org.springframework.web.bind.annotation.GetMapping;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,26 +17,31 @@

import com.netflix.spectator.api.Registry;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@ConditionalOnClass(Registry.class)
@ComponentScan(basePackages = "com.netflix.spectator.controllers")
@Order(Ordered.HIGHEST_PRECEDENCE + 101)
public class MetricsEndpointConfiguration extends WebSecurityConfigurerAdapter {
@EnableWebSecurity
public class MetricsEndpointConfiguration {

@Override
protected void configure(HttpSecurity http) throws Exception {
@Bean
public SecurityFilterChain configure(HttpSecurity http) throws Exception {
// Allow anyone to access the spectator metrics endpoint.
http.requestMatcher(new AntPathRequestMatcher("/spectator/metrics"))
.authorizeRequests()
http.securityMatcher("/spectator/metrics");
http.authorizeHttpRequests()
.requestMatchers("/spectator/metrics")
.permitAll()
.anyRequest()
.permitAll();
.authenticated();
return http.build();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.TestPropertySource;
Expand Down

0 comments on commit 5d5bdc3

Please sign in to comment.