Skip to content

Commit

Permalink
P4ADEV-320-refactoring-accordingly-handbook
Browse files Browse the repository at this point in the history
  • Loading branch information
LarissaASLeite committed May 22, 2024
1 parent 3d10ce2 commit 0d8a60e
Show file tree
Hide file tree
Showing 10 changed files with 63 additions and 93 deletions.
9 changes: 0 additions & 9 deletions openapi/p4pa-auth.openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -59,15 +59,6 @@ components:
message:
type: string
description: "ENG: Error message - IT: Messaggio di errore"
securitySchemes:
apiKeyHeader:
type: apiKey
name: Ocp-Apim-Subscription-Key
in: header
apiKeyQuery:
type: apiKey
name: subscription-key
in: query
security:
- apiKeyHeader: []
- apiKeyQuery: []
Original file line number Diff line number Diff line change
Expand Up @@ -17,28 +17,25 @@
@Order(Ordered.HIGHEST_PRECEDENCE)
public class AuthExceptionHandler {

@ExceptionHandler(InvalidTokenException.class)
@ExceptionHandler({InvalidTokenException.class, TokenExpiredException.class})
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public AuthErrorDTO handleInvalidTokenException(InvalidTokenException ex, HttpServletRequest request){
String message = getMessage(ex, request);

return new AuthErrorDTO(AuthErrorDTO.CodeEnum.fromValue(ex.getCode()), message);
}

@ExceptionHandler(TokenExpiredException.class)
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public AuthErrorDTO handleTokenExpiredException(TokenExpiredException ex, HttpServletRequest request){
String message = getMessage(ex, request);
return new AuthErrorDTO(AuthErrorDTO.CodeEnum.fromValue(ex.getCode()), message);
}

private static String getMessage(Throwable ex, HttpServletRequest request) {
public AuthErrorDTO handleInvalidTokenException(ServiceException ex, HttpServletRequest request){
logStackTrace(ex, request);
String message = ex.getMessage();

log.info("A {} occurred handling request {}: HttpStatus 401 - {}",
ex.getClass(),
getRequestDetails(request), message);
return message;
return new AuthErrorDTO(ex.getCode(), message);
}

public static void logStackTrace(ServiceException error, HttpServletRequest request) {
if(error.isPrintStackTrace()){
log.info("A {} occurred handling request {} at {}",
error.getClass().getSimpleName() ,
getRequestDetails(request),
error.getStackTrace().length > 0 ? error.getStackTrace()[0] : "UNKNOWN");
}
}

public static String getRequestDetails(HttpServletRequest request) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package it.gov.pagopa.payhub.auth.exception;

import lombok.Getter;
import openapi.pagopa.payhub.model.AuthErrorDTO;

@Getter
public class ServiceException extends RuntimeException {
private final AuthErrorDTO.CodeEnum code;
private final boolean printStackTrace;

public ServiceException(AuthErrorDTO.CodeEnum code, String message) {
this(code, message, false, null);
}

public ServiceException(AuthErrorDTO.CodeEnum code, String message, boolean printStackTrace, Throwable ex) {
super(message, ex);
this.code = code;
this.printStackTrace = printStackTrace;
}
}
Original file line number Diff line number Diff line change
@@ -1,23 +1,20 @@
package it.gov.pagopa.payhub.auth.exception.custom;

import it.gov.pagopa.payhub.auth.exception.ServiceException;
import lombok.Getter;
import openapi.pagopa.payhub.model.AuthErrorDTO;

@Getter
public class InvalidTokenException extends RuntimeException {
private final String code;
private final boolean printStackTrace;
public class InvalidTokenException extends ServiceException {
public InvalidTokenException(String message) {
this(AuthErrorDTO.CodeEnum.INVALID_TOKEN.getValue(), message);
this(AuthErrorDTO.CodeEnum.INVALID_TOKEN, message);
}

public InvalidTokenException(String code, String message) {
public InvalidTokenException(AuthErrorDTO.CodeEnum code, String message) {
this(code, message, false, null);
}

public InvalidTokenException(String code, String message, boolean printStackTrace, Throwable ex) {
super(message, ex);
this.code = code;
this.printStackTrace = printStackTrace;
public InvalidTokenException(AuthErrorDTO.CodeEnum code, String message, boolean printStackTrace, Throwable ex) {
super(code, message, printStackTrace, ex);
}
}
Original file line number Diff line number Diff line change
@@ -1,23 +1,20 @@
package it.gov.pagopa.payhub.auth.exception.custom;

import it.gov.pagopa.payhub.auth.exception.ServiceException;
import lombok.Getter;
import openapi.pagopa.payhub.model.AuthErrorDTO;

@Getter
public class TokenExpiredException extends RuntimeException {
private final String code;
private final boolean printStackTrace;
public class TokenExpiredException extends ServiceException {
public TokenExpiredException(String message) {
this(AuthErrorDTO.CodeEnum.TOKEN_EXPIRED_DATE.getValue(), message);
this(AuthErrorDTO.CodeEnum.TOKEN_EXPIRED_DATE, message);
}

public TokenExpiredException(String code, String message) {
public TokenExpiredException(AuthErrorDTO.CodeEnum code, String message) {
this(code, message, false, null);
}

public TokenExpiredException(String code, String message, boolean printStackTrace, Throwable ex) {
super(message, ex);
this.code = code;
this.printStackTrace = printStackTrace;
public TokenExpiredException(AuthErrorDTO.CodeEnum code, String message, boolean printStackTrace, Throwable ex) {
super(code, message, printStackTrace, ex);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public Map<String, String> validate(String token, String urlJwkProvider) {
} catch (com.auth0.jwt.exceptions.TokenExpiredException e){
throw new TokenExpiredException(e.getMessage());
} catch (JwkException | JWTVerificationException ex) {
throw new InvalidTokenException(AuthErrorDTO.CodeEnum.INVALID_TOKEN.getValue(), "The token is not valid", true, ex);
throw new InvalidTokenException(AuthErrorDTO.CodeEnum.INVALID_TOKEN, "The token is not valid", true, ex);
}
}
}
20 changes: 0 additions & 20 deletions src/main/resources/logback-spring.xml
Original file line number Diff line number Diff line change
Expand Up @@ -44,26 +44,6 @@
<appender-ref ref="STDOUT"/>
</appender>

<if condition='"TRUE".equalsIgnoreCase("${ENABLE_FILE_APPENDER}")'>
<then>
<property name="LOG_FILE"
value="${LOG_FILE:-${LOG_PATH:-${LOG_TEMP:-${java.io.tmpdir:-/tmp}}}/spring.log}"/>
<include resource="org/springframework/boot/logging/logback/file-appender.xml"/>

<appender name="ASYNC_FILE"
class="ch.qos.logback.classic.AsyncAppender">
<neverBlock>true</neverBlock>
<queueSize>20000</queueSize>
<discardingThreshold>0</discardingThreshold>
<appender-ref ref="FILE"/>
</appender>

<root level="INFO">
<appender-ref ref="ASYNC_FILE"/>
</root>
</then>
</if>

<logger name="AUDIT" additivity="false">
<appender-ref ref="AUDIT"/>
</logger>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import it.gov.pagopa.payhub.auth.exception.custom.InvalidTokenException;
import it.gov.pagopa.payhub.auth.exception.custom.TokenExpiredException;
import lombok.extern.slf4j.Slf4j;
import openapi.pagopa.payhub.model.AuthErrorDTO;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
Expand Down Expand Up @@ -61,6 +62,20 @@ void handleInvalidTokenException() throws Exception {

}

@Test
void handleInvalidTokenExceptionWithStackTrace() throws Exception {
doThrow(new InvalidTokenException(AuthErrorDTO.CodeEnum.INVALID_TOKEN, "Error", true, new Throwable()))
.when(testControllerSpy).testEndpoint();

mockMvc.perform(MockMvcRequestBuilders.get("/test")
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isUnauthorized())
.andExpect(MockMvcResultMatchers.jsonPath("$.code").value("AUTH_INVALID_TOKEN"))
.andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Error"));

}

@Test
void handleTokenExpiredException() throws Exception {
doThrow(new TokenExpiredException("Error")).when(testControllerSpy).testEndpoint();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ void authTokenWrongIss() throws Exception {
assertThrows(InvalidTokenException.class, () ->
authService.authToken(token));

assertEquals(AuthErrorDTO.CodeEnum.INVALID_TOKEN.getValue(), result.getCode());
assertEquals(AuthErrorDTO.CodeEnum.INVALID_TOKEN, result.getCode());
}

@Test
Expand All @@ -88,7 +88,7 @@ void authTokenWrongAud() throws Exception {
assertThrows(InvalidTokenException.class, () ->
authService.authToken(token));

assertEquals(AuthErrorDTO.CodeEnum.INVALID_TOKEN.getValue(), result.getCode());
assertEquals(AuthErrorDTO.CodeEnum.INVALID_TOKEN, result.getCode());
}

private Map<String, String> createJWKClaims (String iss, String aud){
Expand Down
27 changes: 0 additions & 27 deletions src/test/java/it/gov/pagopa/payhub/auth/utils/MemoryAppender.java

This file was deleted.

0 comments on commit 0d8a60e

Please sign in to comment.