Spring Boot Actuator - env endpoint provides response with active_profiles and property_sources - spring

Once I invoke spring actuator endpoint (http://localhost:8080/actuator/env) it provides response in following format which include _ in between,
{
active_profiles: [ ],
property_sources: [
.....
This includes underscore in between, and this is different comparing to our other services. My expected response is without '_' as follows:
activeProfiles: [ ],
propertySources: [
I am not sure why it generates response with '_' can someone please help on this,
Thanks

Related

AWS API Gateway not passing Endpoint request header even after transformation

I'm trying to pass an Authorization header through API Gateway into a Lambda function. I can see the key in the gateway logs. But, even after I transform the input with the standard script (see below), the Authorization head still doesn't make it to the Lambda function.
Any suggestions on what I'm missing?
API Log excerpt
Endpoint request headers:
{
X-Amz-Date=20220419T143450Z,
x-amzn-apigateway-api-id=?????????,
Accept=application/x-www-form-urlencoded,
User-Agent=AmazonAPIGateway_hhompg4,
Host=lambda.us-east-1.amazonaws.com,
X-Amz-Content-Sha256=??????????????????????????????????????????????????,
X-Amzn-Trace-Id=Root=1-????????-???????????????????,
x-amzn-lambda-integration-tag=abcd-4e32-1234-???????????????, Authorization=*********************************************************************************************************************************************************************************************************************************************************************************************************************************************70cc,
X-Amz-Source-Arn=arn:aws:execute-api:us-east-1:-----------------:asfd/test/POST/,
X-Amz-Security-Token=---------------------------------------// [TRUNCATED]
Method Execution / - POST - Integration Request Transformation script:
{
"method": "$context.httpMethod",
"body" : $input.json('$'),
"headers": {
#foreach($param in $input.params().header.keySet())
"$param": "$util.escapeJavaScript($input.params().header.get($param))"
#if($foreach.hasNext),#end
#end
}
}
event keys arriving to lambda function:
2022-04-19T14:29:34.457Z INFO Object.keys(event) [
'resource',
'path',
'httpMethod',
'headers',
'multiValueHeaders',
'queryStringParameters',
'multiValueQueryStringParameters',
'pathParameters',
'stageVariables',
'requestContext',
'body',
'isBase64Encoded'
]
Object.keys(event.headers)
[
'accept',
'accept-encoding',
'accept-language',
'cache-control',
'content-type',
'Host',
'origin',
'referer',
'sec-ch-ua',
'sec-ch-ua-mobile',
'sec-ch-ua-platform',
'sec-fetch-dest',
'sec-fetch-mode',
'sec-fetch-site',
'sec-fetch-user',
'upgrade-insecure-requests',
'User-Agent',
'X-Amzn-Trace-Id',
'X-Forwarded-For',
'X-Forwarded-Port',
'X-Forwarded-Proto'
]
I was able to see my request header (Authorization) in request headers but the same was not visible in the endpoint request headers. Found that you have to enable the 'Use HTTP Proxy integration' option while setting up the integration point.

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

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. :)

How to set a base url in a springboot graphql app

How can we set a base url in springboot graphql-server app .
By default the graphiql api-console opens on http://localhost:8080/graphiql
Trying to access http://localhost:8080 through postman with a post -query as below :
{
bookings {
name
}
}
gives an error saying :
{
"timestamp": 1549913598497,
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/"
}
Q1 what should be the path to the server i should be using to invoke it.
Q2 is there a way to provide a custom base path something loke http://localhost:8080/service/api/query
Usually the server path for graphql endpoints is at http://localhost:8080/graphql. If not just inspect the network tab on your browser when you run a query on your GraphiQL interface, it will run the query on the api endpoint.
In order to change the base path you would need to change application.properties into something like:
graphql.servlet.mapping: /service/api/query
graphiql.mapping: /graphiql
graphiql.endpoint: /service/api/query
If you are using Spring Boot Property file you can change the base url like below:
spring.graphql.path=/service/api/query
Example:
When I changed the base url like below.:
spring.graphql.path=/api/projects/graphql
It reflected like below in console:
2022-11-05 08:58:14.964 INFO 17336 --- [ main] s.b.a.g.s.GraphQlWebMvcAutoConfiguration : GraphQL endpoint HTTP POST /api/projects/graphql
More can be found at below official document:
https://docs.spring.io/spring-boot/docs/current/reference/html/application-properties.html#appendix.application-properties.web

Grails 3 - Spring Rest Docs using Rest assured giving SnippetException when using JSON views

I am trying to integrate Spring REST docs with rest assured with Grails 3.1.4 application. I am using JSON Views.
Complete code is at https://github.com/rohitpal99/rest-docs
In NoteController when I use
List<Note> noteList = Note.findAll()
Map response = [totalCount: noteList.size(), type: "note"]
render response as grails.converters.JSON
Document generation works well.
But I want to use JSON views like
respond Note.findAll()
where I have _notes.gson and index.gson files in /views directory. I get a SnippetException. A usual /notes GET request response is correct.
rest.docs.ApiDocumentationSpec > test and document get request for /index FAILED
org.springframework.restdocs.snippet.SnippetException at ApiDocumentationSpec.groovy:54
with no message. Unable to track why it occurs.
Please suggest.
Full stacktrace
org.springframework.restdocs.snippet.SnippetException: The following parts of the payload were not documented:
{
"instanceList" : [ {
"title" : "Hello, World!",
"body" : "Integration Test from Hello"
}, {
"title" : "Hello, Grails",
"body" : "Integration Test from Grails"
} ]
}
at org.springframework.restdocs.payload.AbstractFieldsSnippet.validateFieldDocumentation(AbstractFieldsSnippet.java:134)
at org.springframework.restdocs.payload.AbstractFieldsSnippet.createModel(AbstractFieldsSnippet.java:74)
at org.springframework.restdocs.snippet.TemplatedSnippet.document(TemplatedSnippet.java:64)
at org.springframework.restdocs.generate.RestDocumentationGenerator.handle(RestDocumentationGenerator.java:192)
at org.springframework.restdocs.restassured.RestDocumentationFilter.filter(RestDocumentationFilter.java:63)
at com.jayway.restassured.internal.filter.FilterContextImpl.next(FilterContextImpl.groovy:73)
at org.springframework.restdocs.restassured.RestAssuredRestDocumentationConfigurer.filter(RestAssuredRestDocumentationConfigurer.java:65)
at com.jayway.restassured.internal.filter.FilterContextImpl.next(FilterContextImpl.groovy:73)
at com.jayway.restassured.internal.RequestSpecificationImpl.applyPathParamsAndSendRequest(RequestSpecificationImpl.groovy:1574)
at com.jayway.restassured.internal.RequestSpecificationImpl.get(RequestSpecificationImpl.groovy:159)
at rest.docs.ApiDocumentationSpec.$tt__$spock_feature_0_0(ApiDocumentationSpec.groovy:54)
at rest.docs.ApiDocumentationSpec.test and document get request for /index_closure2(ApiDocumentationSpec.groovy)
at groovy.lang.Closure.call(Closure.java:426)
at groovy.lang.Closure.call(Closure.java:442)
at grails.transaction.GrailsTransactionTemplate$1.doInTransaction(GrailsTransactionTemplate.groovy:70)
at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:133)
at grails.transaction.GrailsTransactionTemplate.executeAndRollback(GrailsTransactionTemplate.groovy:67)
at rest.docs.ApiDocumentationSpec.test and document get request for /index(ApiDocumentationSpec.groovy)
REST Docs will fail a test if you try to document something that isn't there or fail to document something that is there. You've documented two fields in your test:
responseFields(
fieldWithPath('totalCount').description('Total count'),
fieldWithPath('type').description("Type of result")
)))
REST Docs has failed the test as some parts of the response haven't been documented. Specifically an instanceList array that contains maps with two keys: title and body. You can document those and the other two fields with something like this:
responseFields(
fieldWithPath('totalCount').description('Total count'),
fieldWithPath('type').description("Type of result"),
fieldWithPath('instanceList[].title').description('Foo'),
fieldWithPath('instanceList[].body').description('Bar')
)))
If you don't care about potentially missing fields, you can use relaxedResponseFields instead of responseFields:
relaxedResponseFields(
fieldWithPath('totalCount').description('Total count'),
fieldWithPath('type').description("Type of result")
))
This won't fail the test if some fields are not mentioned.

grails spring security rest plugin how to skip url from authentication

I am using spring security rest plugin as well as core in my grails app,i want to have some calls those can be accessed without authentication and for this i am adding #Secured('permitAll') on action but it is not working,it is still asking for token.
I have also tried '/api/getdata': ['permitAll'] in config.groovy,but no result!!!
You need to add the anonymous filter to your filter chain.
If you followed the grails spring security rest configuration tutorial you probably got the following code:
grails.plugin.springsecurity.filterChain.chainMap = [
//Stateless chain
[
pattern: '/**',
filters: 'JOINED_FILTERS,-anonymousAuthenticationFilter,-exceptionTranslationFilter,-authenticationProcessingFilter,-securityContextPersistenceFilter,-rememberMeAuthenticationFilter'
]
]
Note that you have "-anonymousAuthenticationFilter" , which removes this filter from your filter chain.
By removing this part (-anonymousAuthenticationFilter) from your code, this filter will back to your filter chain,
so you can use the #Secured("permitAll") or #Secured(['IS_AUTHENTICATED_ANONYMOUSLY']) again.
My final filter chain map was the following and worked like a charm.
grails.plugin.springsecurity.filterChain.chainMap = [
//Stateless chain
[
pattern: '/**',
filters: 'JOINED_FILTERS,-exceptionTranslationFilter,-authenticationProcessingFilter,-securityContextPersistenceFilter,-rememberMeAuthenticationFilter'
]
]
Add this to you logback.groovy in the development environment when you need to see more details about the authentication process
logger("org.springframework.security", DEBUG, ['STDOUT'], false)
logger("grails.plugin.springsecurity", DEBUG, ['STDOUT'], false)
logger("org.pac4j", DEBUG, ['STDOUT'], false)
logger("StackTrace", ERROR, ['FULL_STACKTRACE'], false)
root(ERROR, ['STDOUT', 'FULL_STACKTRACE'])
The same idea applies if you do not use spring security rest.
Same answer I gave in another post, didn't knew what to do.
use static mapping..
grails.plugin.springsecurity.controllerAnnotations.staticRules = [
'/': ['permitAll'],
'/user/someaction1': ['permitAll'],
'/user/someaction1': ['permitAll'],
]

Resources