Skip to content

Commit

Permalink
fix: [P4PU-364] added custom exception to assistance flow (#62)
Browse files Browse the repository at this point in the history
  • Loading branch information
Giuseppe-LaManna authored Aug 30, 2024
1 parent bbea802 commit 214670f
Show file tree
Hide file tree
Showing 10 changed files with 50 additions and 11 deletions.
3 changes: 3 additions & 0 deletions openapi/pagopa-arc-be.openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,8 @@ paths:
- arc zendesk assistance
summary: "Retrieve jwt token for the zendesk assistance"
operationId: getZendeskAssistanceToken
security:
- bearerAuth: [ ]
parameters:
- name: userEmail
in: query
Expand Down Expand Up @@ -711,6 +713,7 @@ components:
- receipt_not_found_error
- invalid_amount
- invalid_date
- invalid_email
- invalid_request
- auth_user_unauthorized
error_description:
Expand Down
5 changes: 3 additions & 2 deletions src/main/java/it/gov/pagopa/arc/config/OAuth2LoginConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,11 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Excepti
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
.authorizeHttpRequests(authorize -> authorize

// Auth endpoint must be protected
// endpoint must be protected
.requestMatchers(
"/auth",
"/auth/*"
"/auth/*",
"/assistance"
).authenticated()

// Should be changed
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,11 @@ public ResponseEntity<ErrorDTO> handlePullInvalidTokenException(RuntimeException
return handleArcErrorException(ex, request, HttpStatus.UNAUTHORIZED, ErrorDTO.ErrorEnum.AUTH_USER_UNAUTHORIZED);
}

@ExceptionHandler(ZendeskAssistanceInvalidUserEmailException.class)
public ResponseEntity<ErrorDTO> handleZendeskAssistanceInvalidUserEmailException(RuntimeException ex, HttpServletRequest request){
return handleArcErrorException(ex, request, HttpStatus.BAD_REQUEST, ErrorDTO.ErrorEnum.INVALID_EMAIL);
}

private static ResponseEntity<ErrorDTO> handleArcErrorException(RuntimeException ex, HttpServletRequest request, HttpStatus httpStatus, ErrorDTO.ErrorEnum errorEnum) {
String message = ex.getMessage();
log.info("A {} occurred handling request {}: HttpStatus {} - {}",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package it.gov.pagopa.arc.exception.custom;

import lombok.Getter;

@Getter
public class ZendeskAssistanceInvalidUserEmailException extends RuntimeException{

public ZendeskAssistanceInvalidUserEmailException(String message) {
super(message);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@
import it.gov.pagopa.arc.dto.mapper.zendeskassistancetoken.ZendeskAssistanceTokenResponseMapper;
import it.gov.pagopa.arc.model.generated.ZendeskAssistanceTokenResponse;
import jakarta.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ZendeskAssistanceTokenServiceImpl implements ZendeskAssistanceTokenService{
private final ZendeskAssistanceTokenBuilder zendeskAssistanceTokenBuilder;
private final ZendeskAssistanceTokenConfig zendeskAssistanceTokenConfig;
Expand All @@ -20,6 +22,7 @@ public ZendeskAssistanceTokenServiceImpl(ZendeskAssistanceTokenBuilder zendeskAs

@Override
public ZendeskAssistanceTokenResponse retrieveZendeskAssistanceTokenResponse(@NotNull String userEmail) {
log.info("[GET_ZENDESK_ASSISTANCE_TOKEN_RESPONSE] the creation of the jwt token was requested to request assistance on zendesk");
String zendeskAssistanceToken = zendeskAssistanceTokenBuilder.buildZendeskAssistanceToken(userEmail);
String returnTo = this.zendeskAssistanceTokenConfig.getReturnTo();

Expand Down
3 changes: 1 addition & 2 deletions src/main/java/it/gov/pagopa/arc/utils/SecurityUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,7 @@ public static IamUserInfoDTO getPrincipal() {
try{
return (IamUserInfoDTO) principal;
}catch (ClassCastException e){
//Replace this exception with custom exception
throw new RuntimeException("Invalid principal type: expected IamUserInfoDTO but got " + principal.getClass().getName());
throw new IllegalStateException("Invalid principal type: expected IamUserInfoDTO but got " + principal.getClass().getName());
}

}
Expand Down
4 changes: 2 additions & 2 deletions src/main/java/it/gov/pagopa/arc/utils/Utilities.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

import it.gov.pagopa.arc.exception.custom.BizEventsInvalidAmountException;
import it.gov.pagopa.arc.exception.custom.BizEventsInvalidDateException;
import it.gov.pagopa.arc.exception.custom.ZendeskAssistanceInvalidUserEmailException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

Expand Down Expand Up @@ -63,8 +64,7 @@ public static String extractNameFromEmailAssistanceToken(String userMail){
int index = userMail.indexOf("@");
nameExtracted = userMail.substring(0, index);
}else {
//Replace this exception with custom exception
throw new RuntimeException("Invalid user email");
throw new ZendeskAssistanceInvalidUserEmailException("Invalid user email [%s]".formatted(userMail));
}
return nameExtracted;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -195,4 +195,20 @@ void givenInvalidTokenThenHandleInvalidTokenException() throws Exception {
Assertions.assertTrue(memoryAppender.getLoggedEvents().get(0).getFormattedMessage().contains("A class it.gov.pagopa.arc.exception.custom.InvalidTokenException occurred handling request GET /test: HttpStatus 401 - Error"));
}

@Test
void givenInvalidEmailWhenExtractNameFromEmailAssistanceTokenThenHandleZendeskAssistanceInvalidUserEmailException() throws Exception {
doThrow(new ZendeskAssistanceInvalidUserEmailException("Error")).when(testControllerSpy).testEndpoint();

mockMvc.perform(MockMvcRequestBuilders.get("/test")
.param(DATA, DATA)
.header(HEADER,HEADER)
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isBadRequest())
.andExpect(MockMvcResultMatchers.jsonPath("$.error").value("invalid_email"))
.andExpect(MockMvcResultMatchers.jsonPath("$.error_description").value("Error"));

Assertions.assertTrue(memoryAppender.getLoggedEvents().get(0).getFormattedMessage().contains("A class it.gov.pagopa.arc.exception.custom.ZendeskAssistanceInvalidUserEmailException occurred handling request GET /test: HttpStatus 400 - Error"));
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ void givenWrongConfiguredSecurityContextThenThrowException(){
authentication.setDetails(new WebAuthenticationDetails(new MockHttpServletRequest()));
SecurityContextHolder.getContext().setAuthentication(authentication);

RuntimeException ex = Assertions.assertThrows(RuntimeException.class, SecurityUtils::getPrincipal);
IllegalStateException ex = Assertions.assertThrows(IllegalStateException.class, SecurityUtils::getPrincipal);
Assertions.assertEquals("Invalid principal type: expected IamUserInfoDTO but got java.lang.Object", ex.getMessage());
}

Expand Down
9 changes: 5 additions & 4 deletions src/test/java/it/gov/pagopa/arc/utils/UtilitiesTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import it.gov.pagopa.arc.exception.custom.BizEventsInvalidAmountException;
import it.gov.pagopa.arc.exception.custom.BizEventsInvalidDateException;
import it.gov.pagopa.arc.exception.custom.ZendeskAssistanceInvalidUserEmailException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
Expand Down Expand Up @@ -90,9 +91,9 @@ void givenEmptyEmailStringWhenExtractNameFromEmailAssistanceTokenThenReturnExcep
String wrongEmail = "";
//when
//then
RuntimeException exception = assertThrows(RuntimeException.class,
ZendeskAssistanceInvalidUserEmailException exception = assertThrows(ZendeskAssistanceInvalidUserEmailException .class,
() -> Utilities.extractNameFromEmailAssistanceToken(wrongEmail));
Assertions.assertEquals("Invalid user email",exception.getMessage());
Assertions.assertEquals("Invalid user email []",exception.getMessage());

}

Expand All @@ -102,9 +103,9 @@ void givenWrongEmailStringWhenExtractNameFromEmailAssistanceTokenThenReturnExcep
String wrongEmail = "email";
//when
//then
RuntimeException exception = assertThrows(RuntimeException.class,
ZendeskAssistanceInvalidUserEmailException exception = assertThrows(ZendeskAssistanceInvalidUserEmailException .class,
() -> Utilities.extractNameFromEmailAssistanceToken(wrongEmail));
Assertions.assertEquals("Invalid user email",exception.getMessage());
Assertions.assertEquals("Invalid user email [email]",exception.getMessage());

}

Expand Down

0 comments on commit 214670f

Please sign in to comment.