How to configure "health" Actuator endpoint to work with token authentication? - spring

We are using token-based authentication (with Spring Security) in our Spring Boot 2 application. Now I'm introducing Spring Boot Actuator to it. I would like to configure the /health endpoint to be visible without any permissions but to show health checks details only when authorized.
I found the property management.endpoint.health.show-details=when_authorized which should be helpful but now I'm fighting with the Spring Security configuration to allow everybody to see:
{
"status": "UP"
}
under /actuator/health while users authorized with token should see:
{
"status": "UP",
"details": { ... }
}
Did you face a similar problem? How did you handle it?

OK, now I understand, if you turn off security in your application and keep management.endpoint.health.show-details=when_authorized you are getting just status field? If I'm right it's not an issue, take a look in spring class HealthWebEndpointResponseMapper into map method. As I found out this method overwrites (remove details field from the response) if condition in if is true:
public WebEndpointResponse<Health> map(Health health, SecurityContext securityContext,
ShowDetails showDetails) {
if (showDetails == ShowDetails.NEVER
|| (showDetails == ShowDetails.WHEN_AUTHORIZED
&& (securityContext.getPrincipal() == null
|| !isUserInRole(securityContext)))) {
health = Health.status(health.getStatus()).build();
}
Integer status = this.statusHttpMapper.mapStatus(health.getStatus());
return new WebEndpointResponse<>(health, status);
}
In your case, I guess you have set an above-mentioned property to when_authorized also you have turned off authentication, so the principal is null. Not sure if I'm right, but I hope I gave you a clue. :)

Related

Spring reactive Mono:blockOptional conflict with spring actuator

I'm mapping json array response to reactor world but have an issue like:
val responses = configurationClient.getData() // return json array object
.flatMap { it.bodyToMono(object : ParameterizedTypeReference<GeneralResponse<Array<ObjectResponse>>>() {})
}
.map { it.data }
.blockOptional() // exception this line
.orElse(emptyArray())!!
This snipcode doesn't work if I add this property of spring actuator
management.endpoints.enabled-by-default=true
Netty server cannot start without any exceptions.
But It works when I change to
management.endpoints.enabled-by-default=false
The Netty started well
Any ideas this issue please?
** Updated **
When I add some timeout value .blockOptional(Duration.ofSeconds(60)) //60 seconds
val responses = configurationClient.getData() // return json array object
.flatMap { it.bodyToMono(object : ParameterizedTypeReference<GeneralResponse<Array<ObjectResponse>>>() {})
}
.map { it.data }
.blockOptional(Duration.ofSeconds(60))
.get()
I pretty sure conflict somewhere between Mono and Spring actuator management.endpoints.enabled-by-default=true
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:886)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:790)
... 20 common frames omitted
Caused by: java.lang.IllegalStateException: Timeout on blocking read for 60000 MILLISECONDS
at reactor.core.publisher.BlockingOptionalMonoSubscriber.blockingGet(BlockingOptionalMonoSubscriber.java:162)
at reactor.core.publisher.Mono.blockOptional(Mono.java:1755)
Note
configurationClient.getData() this just a GET request return 200-[{...}]
Everything work if I use
management.endpoints.enabled-by-default=false
problem is solved.
Root cause:
It's not a bug of Mono:blockOptional or Spring actuator individually.
This configuration management.endpoints.enabled-by-default=true is conflict with existing actuator endpoint configurations
Solution:
Cleanup spring actuator configuration properties to avoid this conflict then Mono:blockOptional work well

Health Endpoint Metrics not being exported after Spring Boot 2 migration

My Team migrated our Microservices from Spring Boot 1 to Version 2 and since the Actuator changed, our Health Endpoint Metrics exported via prometheus jmx exporter do not work anymore.
The usual /actuator/health is working as expected, but the prometheus-jmx-exporter won't pick it up although several things tried:
I changed the Metainformation in the exporter-config.yaml to reflect the name change in Spring Boot 2
I added the io.micrometer:micrometer-registry-prometheus to our build.gradle to see if this is the issue
I exposed web and jmx endpoints acording to the Spring Boot 2 Documentation
So now I run out of ideas and would appreciate any hints oyu might be able to give me
old prometheus-jmx-exporter exporter-config.yaml:
---
lowercaseOutputName: true
lowercaseOutputLabelNames: true
whitelistObjectNames: ["org.springframework.boot:type=Endpoint,name=healthEndpoint"]
rules:
- pattern: 'org.springframework.boot<type=Endpoint, name=healthEndpoint><(.*, )?(.*)>(.*):'
name: health_endpoint_$1$3
attrNameSnakeCase: true
new prometheus-jmx-exporter exporter-config.yaml:
---
lowercaseOutputName: true
lowercaseOutputLabelNames: true
whitelistObjectNames: ["org.springframework.boot:type=Endpoint,name=Health"]
rules:
- pattern: 'org.springframework.boot<type=Endpoint, name=Health>'
name: health_endpoint_$1$3
attrNameSnakeCase: true
current application properties about actuator endpoints:
management.endpoints.web.exposure.include=info, health, refresh, metrics, prometheus
management.endpoints.jmx.exposure.include=health, metrics, prometheus
in Spring Boot 1 with the old exporter-config.yaml I get results like this:
# HELP health_endpoint_hystrix_status Invoke the underlying endpoint (org.springframework.boot<type=Endpoint, name=healthEndpoint><hystrix, status>status)
# TYPE health_endpoint_hystrix_status untyped
health_endpoint_hystrix_status 1.0
# HELP health_endpoint_status Invoke the underlying endpoint (org.springframework.boot<type=Endpoint, name=healthEndpoint><status>status)
# TYPE health_endpoint_status untyped
health_endpoint_status 1.0
But with all the changes and in Spring Boot 2 I get nothing out of this.
You can cofigure your own health value and add it to the Prometheus Metrics endpoint:
#Configuration
public class HealthMetricsConfiguration {
#Bean
public MeterRegistryCustomizer prometheusHealthCheck(HealthEndpoint healthEndpoint) {
return registry -> registry.gauge("health", healthEndpoint, HealthMetricsConfiguration::healthToCode);
}
public static int healthToCode(HealthEndpoint ep) {
Status status = ep.health().getStatus();
return status.equals(Status.UP) ? 1 : 0;
}
}

Hide details for health indicators in Spring Boot Actuator

I'm using Spring Boot health indicator from an actuator. So far example response looks like:
{
"status":"DOWN",
"details": {
"diskSpace": {
"status":"UP",
"details": {
"total":499963170816,
"free":250067189760,
"threshold":10485760
}
}
}
}
Because I need to make /actuator/health endpoint public, I need to hide details for health indicators, so I expect to get something like this:
{
"status":"DOWN",
"details": {
"diskSpace": {
"status":"UP"
}
}
}
For disk space it's not a big problem but e.g. for database I don't want to share exception message and details in case of it's outage. Also (as I mentioned at the beginning) it must be public so I don't want to make this endpoint 'when-authorized'. And at the end - it would be great if it's possible to do that without writing my own custom endpoint.
Is it possible at all?
This isn't possible at the time of writing (in Spring Boot 2.1 and earlier) without writing your own custom endpoint. I've opened an issue to consider it as an enhancement for a future version of Spring Boot.
There is a way to achieve this in Spring Boot 2.X
management:
health:
db:
enabled: false
diskspace:
enabled: false
mongo:
enabled: false
refresh:
enabled: false
More information can be found here https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-endpoints.html#_auto_configured_healthindicators

Spring Boot - Change the location of the /health endpoint to /ping/me

I set the endpoints.health.path property to /ping/me. But I cannot access the endpoint using http://localhost:9000/ping/me
It only works with http://localhost:9000/health. What am I missing ?
Here is the code in app properties file.
#Configuration for Health endpoint
endpoints.health.id=health
endpoints.health.path=/ping/me
endpoints.health.enabled=true
endpoints.health.sensitive=false
#Manage endpoints
management.port=9000
management.health.diskspace.enabled=false
The response I get is :
{
"timestamp" : 1455736069839,
"status" : 404,
"error" : "Not Found",
"message" : "Not Found",
"path" : "/ping/me"
}
The Actuator became technology-agnostic in Spring Boot 2.0.0, so it's not tied to MVC now. Thus if you use Spring Boot 2.0.x, you can just add the following config properties:
# custom actuator base path: use root mapping `/` instead of default `/actuator/`
management.endpoints.web.base-path=
# override endpoint name for health check: `/health` => `/ping/me`
management.endpoints.web.path-mapping.health=/ping/me
If you don't override the management.endpoints.web.base-path, your health-check will be available at /actuator/ping/me.
The properties like endpoints.* became deprecated in Spring Boot 2.0.0.
See below for Spring Boot 2.*
https://stackoverflow.com/a/50364513/2193477
MvcEndpoints is responsible for reading endpoints.{name}.path configurations and somehow in its afterPropertiesSet method:
for (Endpoint<?> endpoint : delegates) {
if (isGenericEndpoint(endpoint.getClass()) && endpoint.isEnabled()) {
EndpointMvcAdapter adapter = new EndpointMvcAdapter(endpoint);
String path = this.applicationContext.getEnvironment()
.getProperty("endpoints." + endpoint.getId() + ".path");
if (path != null) {
adapter.setPath(path);
}
this.endpoints.add(adapter);
}
}
It refusing from setting the endpoints.health.path, since isGenericEndpoint(...) is returning false for HealthEndpoint. Maybe it's a bug or something.
Update: Apparently this was a bug and got fixed in 1.3.3.RELEASE version. So, you can use the /ping/me as your health monitoring path in this version.

Grails Spring Security Rest - 403 Forbidden

So I just started learning Grails, and I am trying incorporate the Spring Security REST plugin into my app, the plugin is installed in addition to spring security core which is working. In my REST client, when I hit "api/login" I am able to get an access token and it says I have the role of "ROLE_ADMIN", but then when I try to hit something using that, I keep getting a 403 Forbidden. In Postman, the REST client I am using, I have my Authorization header with "Bearer {key}", with my url of "http://localhost:8080/test/api/secret" and it gives the 403 error. I am trying to setup the log4j logging to see any other issues, but does anyone know what I should look into, any help would be appreciated. I provided my classes below if that helps, I generally used default values for everything such as the UrlMappings.
RandomController.groovy
package test
import grails.plugin.springsecurity.annotation.Secured
#Secured(['IS_AUTHENTICATED_ANONYMOUSLY'])
class MyController {
#Secured(['ROLE_ADMIN'])
def secret() {
render "You have ACCESS!!!"
}
}
Bootstrap.groovy
class BootStrap {
def init = { servletContext ->
def adminRole = new SecRole(authority: 'ROLE_ADMIN').save(flush: true)
def testUser = new SecUser(username: 'bob', password: 'test')
testUser.save(flush: true)
SecUserSecRole.create testUser, adminRole, true
}
def destroy = {
}
}
UrlMappings.groovy
class UrlMappings {
static mappings = {
"/$controller/$action?/$id?(.$format)?"{
constraints {
// apply constraints here
}
}
"/api/$controller/$action?/$id?(.$format)?"{ constraints { // apply constraints here
} }
"/"(view:"/index")
"500"(view:'/error')
}
}
For what I can see from the code you posted, if you invoke url http://localhost:8080/test/api/secret, it should execute default action (maybe index) in SecretController but the controller you posted is called MyController.
To investigate further, you should enable more verbose logging using log4j configuration as suggested in the doc http://alvarosanchez.github.io/grails-spring-security-rest/1.5.1/docs/guide/debugging.html

Resources