Add Observability Sample

Closes gh-313
This commit is contained in:
Josh Cummings
2024-08-23 17:58:33 -06:00
parent dc116452b0
commit 3489338049
22 changed files with 970 additions and 0 deletions

View File

@@ -0,0 +1,129 @@
/*
* Copyright 2020 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
*
* https://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 example;
import java.util.List;
import io.micrometer.observation.Observation.Context;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.observation.ClientRequestObservationContext;
import org.springframework.http.server.observation.ServerRequestObservationContext;
import org.springframework.security.authentication.AuthenticationObservationContext;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Integration tests.
*
* @author Rob Winch
* @since 5.0
*/
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class HelloMethodApplicationITests {
@Autowired
TestRestTemplate rest;
@Autowired
ObservationCollector collector;
// --- /message ---
@Test
void messageWhenNotAuthenticated() {
// @formatter:off
assertThat(this.rest.getForEntity("/message", String.class).getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
List<Context> starts = this.collector.getStarts();
assertThat(starts).extracting((context) -> context.getClass())
.contains((Class) AuthenticationObservationContext.class)
.contains((Class) AuthenticationObservationContext.class)
.contains((Class) ClientRequestObservationContext.class)
.contains((Class) ServerRequestObservationContext.class);
}
@Test
void messageWhenUserThenOk() {
ResponseEntity<?> response = this.rest.exchange("/message", HttpMethod.GET, userCredentials(), String.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(response.getBody().toString()).isEqualTo("Hello User!");
List<Context> starts = this.collector.getStarts();
assertThat(starts).extracting((context) -> context.getClass())
.contains((Class) AuthenticationObservationContext.class)
.contains((Class) AuthenticationObservationContext.class)
.contains((Class) ClientRequestObservationContext.class)
.contains((Class) ServerRequestObservationContext.class);
}
// --- /secret ---
@Test
void secretWhenNotAuthenticated() {
assertThat(this.rest.getForEntity("/secret", String.class).getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
List<Context> starts = this.collector.getStarts();
assertThat(starts).extracting((context) -> context.getClass())
.contains((Class) AuthenticationObservationContext.class)
.contains((Class) AuthenticationObservationContext.class)
.contains((Class) ClientRequestObservationContext.class)
.contains((Class) ServerRequestObservationContext.class);
}
@Test
void secretWhenUserThenForbidden() {
assertThat(this.rest.exchange("/secret", HttpMethod.GET, userCredentials(), String.class).getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
List<Context> starts = this.collector.getStarts();
assertThat(starts).extracting((context) -> context.getClass())
.contains((Class) AuthenticationObservationContext.class)
.contains((Class) AuthenticationObservationContext.class)
.contains((Class) ClientRequestObservationContext.class)
.contains((Class) ServerRequestObservationContext.class);
}
@Test
void secretWhenAdminThenOk() {
ResponseEntity<?> response = this.rest.exchange("/secret", HttpMethod.GET, adminCredentials(), String.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
assertThat(response.getBody().toString()).isEqualTo("Hello Admin!");
List<Context> starts = this.collector.getStarts();
assertThat(starts).extracting((context) -> context.getClass())
.contains((Class) AuthenticationObservationContext.class)
.contains((Class) AuthenticationObservationContext.class)
.contains((Class) ClientRequestObservationContext.class)
.contains((Class) ServerRequestObservationContext.class);
}
private HttpEntity<?> userCredentials() {
HttpHeaders headers = new HttpHeaders();
headers.setBasicAuth("user", "password");
return new HttpEntity<>(headers);
}
private HttpEntity<?> adminCredentials() {
HttpHeaders headers = new HttpHeaders();
headers.setBasicAuth("admin", "password");
return new HttpEntity<>(headers);
}
}

View File

@@ -0,0 +1 @@
management.tracing.sampling.probability=1.0

View File

@@ -0,0 +1,35 @@
/*
* Copyright 2020 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
*
* https://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 example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Simple application that uses method security.
*
* @author Rob Winch
* @since 5.0
*/
@SpringBootApplication
public class HelloMethodApplication {
public static void main(String[] args) {
SpringApplication.run(HelloMethodApplication.class, args);
}
}

View File

@@ -0,0 +1,47 @@
/*
* Copyright 2020 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
*
* https://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 example;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Controller for the messages.
*
* @author Rob Winch
* @since 5.0
*/
@RestController
public class MessageController {
private final MessageService messages;
public MessageController(MessageService messages) {
this.messages = messages;
}
@GetMapping("/message")
public String message() {
return this.messages.findMessage();
}
@GetMapping("/secret")
public String secretMessage() {
return this.messages.findSecretMessage();
}
}

View File

@@ -0,0 +1,49 @@
/*
* Copyright 2020 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
*
* https://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 example;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Component;
/**
* Message service that has method security on it.
*
* @author Rob Winch
* @since 5.0
*/
@Component
public class MessageService {
/**
* Gets a message if authenticated.
* @return the message
*/
@PreAuthorize("isAuthenticated()")
public String findMessage() {
return "Hello User!";
}
/**
* Gets a message if admin.
* @return the message
*/
@PreAuthorize("hasRole('ADMIN')")
public String findSecretMessage() {
return "Hello Admin!";
}
}

View File

@@ -0,0 +1,46 @@
/*
* Copyright 2020 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
*
* https://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 example;
import java.util.ArrayList;
import java.util.List;
import io.micrometer.observation.Observation.Context;
import io.micrometer.observation.ObservationHandler;
import org.springframework.stereotype.Component;
@Component
public class ObservationCollector implements ObservationHandler {
private List<Context> starts = new ArrayList<>();
@Override
public boolean supportsContext(Context context) {
return true;
}
@Override
public void onStart(Context context) {
this.starts.add(context);
}
public List<Context> getStarts() {
return this.starts;
}
}

View File

@@ -0,0 +1,72 @@
/*
* Copyright 2020 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
*
* https://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 example;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import static org.springframework.security.config.Customizer.withDefaults;
/**
* Minimal method security configuration.
*
* @author Rob Winch
* @since 5.0
*/
@Configuration
@EnableMethodSecurity
public class SecurityConfiguration {
@Bean
SecurityFilterChain springFilterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
// Demonstrate that method security works
// Best practice to use both for defense in depth
.authorizeHttpRequests((authorize) -> authorize
.anyRequest().permitAll()
)
.httpBasic(withDefaults());
// @formatter:on
return http.build();
}
@Bean
UserDetailsService userDetailsService() {
// @formatter:off
UserDetails user = User.withDefaultPasswordEncoder()
.username("user")
.password("password")
.roles("USER")
.build();
UserDetails admin = User.withDefaultPasswordEncoder()
.username("admin")
.password("password")
.roles("ADMIN", "USER")
.build();
// @formatter:on
return new InMemoryUserDetailsManager(user, admin);
}
}

View File

@@ -0,0 +1,74 @@
/*
* Copyright 2020 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
*
* https://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 example;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.test.context.support.WithAnonymousUser;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* @author Josh Cummings
*/
@SpringBootTest
@AutoConfigureMockMvc
public class HelloMethodApplicationTests {
@Autowired
MockMvc mvc;
// --- /message ---
@Test
@WithAnonymousUser
void messageWhenNotAuthenticatedThenUnAuthorized() throws Exception {
this.mvc.perform(get("/message")).andExpect(status().isUnauthorized());
}
@Test
@WithMockUser
void messageWhenAuthenticatedThenOk() throws Exception {
this.mvc.perform(get("/message")).andExpect(status().isOk());
}
// --- /secret ---
@Test
void secretWhenNotAuthenticatedThenUnAuthorized() throws Exception {
this.mvc.perform(get("/secret")).andExpect(status().isUnauthorized());
}
@Test
@WithMockUser
void secretWhenNotAuthorizedThenForbidden() throws Exception {
this.mvc.perform(get("/secret")).andExpect(status().isForbidden());
}
@Test
@WithMockUser(roles = "ADMIN")
void secretWhenAuthorizedThenOk() throws Exception {
this.mvc.perform(get("/secret")).andExpect(status().isOk());
}
}

View File

@@ -0,0 +1,101 @@
/*
* Copyright 2020 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
*
* https://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 example;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.security.test.context.support.WithSecurityContext;
import org.springframework.security.test.context.support.WithSecurityContextFactory;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* @author Josh Cummings
*/
@SpringBootTest
public class MessageServiceTests {
@Autowired
MessageService messages;
// -- findMessage ---
@Test
@WithUnauthenticatedUser
void findMessageWhenNotAuthenticatedThenDenied() {
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.messages::findMessage);
}
@Test
@WithMockUser
void findMessageWhenUserThenSuccess() {
assertThat(this.messages.findMessage()).isEqualTo("Hello User!");
}
// -- findSecretMessage ---
@Test
@WithUnauthenticatedUser
void findSecretMessageWhenNotAuthenticatedThenDenied() {
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.messages::findSecretMessage);
}
@Test
@WithMockUser
void findSecretMessageWhenNotAuthorizedThenDenied() {
assertThatExceptionOfType(AccessDeniedException.class).isThrownBy(this.messages::findSecretMessage);
}
@Test
@WithMockUser(roles = "ADMIN")
void findSecretMessageWhenAuthorizedThenSuccess() {
assertThat(this.messages.findSecretMessage()).isEqualTo("Hello Admin!");
}
@Target({ ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@WithSecurityContext(factory = WithUnauthenticatedUserSecurityContextFactory.class)
private @interface WithUnauthenticatedUser {
}
private static final class WithUnauthenticatedUserSecurityContextFactory
implements WithSecurityContextFactory<WithUnauthenticatedUser> {
@Override
public SecurityContext createSecurityContext(WithUnauthenticatedUser annotation) {
TestingAuthenticationToken token = new TestingAuthenticationToken("user", "password");
token.setAuthenticated(false);
return new SecurityContextImpl(token);
}
}
}