Search in sources :

Example 6 with JsonException

use of uk.gov.di.authentication.shared.serialization.Json.JsonException in project di-authentication-api by alphagov.

the class MfaHandler method handleRequestWithUserContext.

@Override
public APIGatewayProxyResponseEvent handleRequestWithUserContext(APIGatewayProxyRequestEvent input, Context context, MfaRequest request, UserContext userContext) {
    try {
        String persistentSessionId = PersistentIdHelper.extractPersistentIdFromHeaders(input.getHeaders());
        attachSessionIdToLogs(userContext.getSession().getSessionId());
        attachLogFieldToLogs(PERSISTENT_SESSION_ID, persistentSessionId);
        attachLogFieldToLogs(CLIENT_ID, userContext.getClient().map(ClientRegistry::getClientID).orElse("unknown"));
        LOG.info("MfaHandler received request");
        String email = request.getEmail().toLowerCase(Locale.ROOT);
        Optional<ErrorResponse> codeRequestValid = validateCodeRequestAttempts(email, userContext);
        if (codeRequestValid.isPresent()) {
            auditService.submitAuditEvent(FrontendAuditableEvent.MFA_INVALID_CODE_REQUEST, context.getAwsRequestId(), userContext.getSession().getSessionId(), userContext.getClient().map(ClientRegistry::getClientID).orElse(AuditService.UNKNOWN), AuditService.UNKNOWN, email, IpAddressHelper.extractIpAddress(input), AuditService.UNKNOWN, persistentSessionId);
            return generateApiGatewayProxyErrorResponse(400, codeRequestValid.get());
        }
        if (!userContext.getSession().validateSession(email)) {
            LOG.warn("Email does not match Email in Request");
            auditService.submitAuditEvent(FrontendAuditableEvent.MFA_MISMATCHED_EMAIL, context.getAwsRequestId(), userContext.getSession().getSessionId(), userContext.getClient().map(ClientRegistry::getClientID).orElse(AuditService.UNKNOWN), AuditService.UNKNOWN, email, IpAddressHelper.extractIpAddress(input), AuditService.UNKNOWN, persistentSessionId);
            return generateApiGatewayProxyErrorResponse(400, ERROR_1000);
        }
        String phoneNumber = authenticationService.getPhoneNumber(email).orElse(null);
        if (phoneNumber == null) {
            auditService.submitAuditEvent(FrontendAuditableEvent.MFA_MISSING_PHONE_NUMBER, context.getAwsRequestId(), userContext.getSession().getSessionId(), userContext.getClient().map(ClientRegistry::getClientID).orElse(AuditService.UNKNOWN), AuditService.UNKNOWN, email, IpAddressHelper.extractIpAddress(input), AuditService.UNKNOWN, persistentSessionId);
            return generateApiGatewayProxyErrorResponse(400, ERROR_1014);
        }
        String code = codeGeneratorService.sixDigitCode();
        codeStorageService.saveOtpCode(email, code, configurationService.getCodeExpiry(), MFA_SMS);
        sessionService.save(userContext.getSession().incrementCodeRequestCount());
        NotifyRequest notifyRequest = new NotifyRequest(phoneNumber, MFA_SMS, code);
        AuditableEvent auditableEvent;
        if (!isTestClientAndAllowedEmail(userContext, MFA_SMS)) {
            sqsClient.send(objectMapper.writeValueAsString(notifyRequest));
            auditableEvent = FrontendAuditableEvent.MFA_CODE_SENT;
        } else {
            auditableEvent = FrontendAuditableEvent.MFA_CODE_SENT_FOR_TEST_CLIENT;
        }
        auditService.submitAuditEvent(auditableEvent, context.getAwsRequestId(), userContext.getSession().getSessionId(), userContext.getClient().map(ClientRegistry::getClientID).orElse(AuditService.UNKNOWN), AuditService.UNKNOWN, email, IpAddressHelper.extractIpAddress(input), phoneNumber, persistentSessionId);
        LOG.info("Successfully processed request");
        return generateEmptySuccessApiGatewayResponse();
    } catch (JsonException e) {
        return generateApiGatewayProxyErrorResponse(400, ERROR_1001);
    } catch (ClientNotFoundException e) {
        LOG.warn("Client not found");
        return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1015);
    }
}
Also used : JsonException(uk.gov.di.authentication.shared.serialization.Json.JsonException) ClientNotFoundException(uk.gov.di.authentication.shared.exceptions.ClientNotFoundException) ClientRegistry(uk.gov.di.authentication.shared.entity.ClientRegistry) NotifyRequest(uk.gov.di.authentication.shared.entity.NotifyRequest) ErrorResponse(uk.gov.di.authentication.shared.entity.ErrorResponse) ApiGatewayResponseHelper.generateApiGatewayProxyErrorResponse(uk.gov.di.authentication.shared.helpers.ApiGatewayResponseHelper.generateApiGatewayProxyErrorResponse) FrontendAuditableEvent(uk.gov.di.authentication.frontendapi.domain.FrontendAuditableEvent) AuditableEvent(uk.gov.di.authentication.shared.domain.AuditableEvent)

Example 7 with JsonException

use of uk.gov.di.authentication.shared.serialization.Json.JsonException in project di-authentication-api by alphagov.

the class NotificationHandler method notifcationRequestHandler.

public Void notifcationRequestHandler(SQSEvent event, Context context) {
    Map<String, Object> notifyPersonalisation = new HashMap<>();
    for (SQSMessage msg : event.getRecords()) {
        try {
            NotifyRequest notifyRequest = objectMapper.readValue(msg.getBody(), NotifyRequest.class);
            try {
                switch(notifyRequest.getNotificationType()) {
                    case ACCOUNT_CREATED_CONFIRMATION:
                        notifyPersonalisation.put("contact-us-link", buildContactUsUrl("accountCreatedEmail"));
                        notificationService.sendEmail(notifyRequest.getDestination(), notifyPersonalisation, ACCOUNT_CREATED_CONFIRMATION);
                        break;
                    case VERIFY_EMAIL:
                        notifyPersonalisation.put("validation-code", notifyRequest.getCode());
                        notifyPersonalisation.put("email-address", notifyRequest.getDestination());
                        notifyPersonalisation.put("contact-us-link", buildContactUsUrl("confirmEmailAddressEmail"));
                        notificationService.sendEmail(notifyRequest.getDestination(), notifyPersonalisation, VERIFY_EMAIL);
                        break;
                    case VERIFY_PHONE_NUMBER:
                        notifyPersonalisation.put("validation-code", notifyRequest.getCode());
                        notificationService.sendText(notifyRequest.getDestination(), notifyPersonalisation, VERIFY_PHONE_NUMBER);
                        break;
                    case MFA_SMS:
                        notifyPersonalisation.put("validation-code", notifyRequest.getCode());
                        notificationService.sendText(notifyRequest.getDestination(), notifyPersonalisation, MFA_SMS);
                        break;
                    case RESET_PASSWORD:
                        notifyPersonalisation.put("reset-password-link", notifyRequest.getCode());
                        notifyPersonalisation.put("contact-us-link", buildContactUsUrl("passwordResetRequestEmail"));
                        notificationService.sendEmail(notifyRequest.getDestination(), notifyPersonalisation, RESET_PASSWORD);
                        break;
                    case PASSWORD_RESET_CONFIRMATION:
                        Map<String, Object> passwordResetConfirmationPersonalisation = new HashMap<>();
                        passwordResetConfirmationPersonalisation.put("contact-us-link", buildContactUsUrl("passwordResetConfirmationEmail"));
                        notificationService.sendEmail(notifyRequest.getDestination(), passwordResetConfirmationPersonalisation, PASSWORD_RESET_CONFIRMATION);
                        break;
                    case RESET_PASSWORD_WITH_CODE:
                        notifyPersonalisation.put("validation-code", notifyRequest.getCode());
                        notifyPersonalisation.put("email-address", notifyRequest.getDestination());
                        notifyPersonalisation.put("contact-us-link", buildContactUsUrl("passwordResetRequestEmail"));
                        notificationService.sendEmail(notifyRequest.getDestination(), notifyPersonalisation, RESET_PASSWORD_WITH_CODE);
                        break;
                }
                writeTestClientOtpToS3(notifyRequest.getCode(), notifyRequest.getDestination());
            } catch (NotificationClientException e) {
                LOG.error("Error sending with Notify using NotificationType: {}", notifyRequest.getNotificationType());
                throw new RuntimeException(String.format("Error sending with Notify using NotificationType: %s", notifyRequest.getNotificationType()), e);
            }
        } catch (JsonException e) {
            LOG.error("Error when mapping message from queue to a NotifyRequest");
            throw new RuntimeException("Error when mapping message from queue to a NotifyRequest");
        }
    }
    return null;
}
Also used : JsonException(uk.gov.di.authentication.shared.serialization.Json.JsonException) NotificationClientException(uk.gov.service.notify.NotificationClientException) HashMap(java.util.HashMap) SQSMessage(com.amazonaws.services.lambda.runtime.events.SQSEvent.SQSMessage) NotifyRequest(uk.gov.di.authentication.shared.entity.NotifyRequest)

Example 8 with JsonException

use of uk.gov.di.authentication.shared.serialization.Json.JsonException in project di-authentication-api by alphagov.

the class AuthenticateHandler method authenticateRequestHandler.

public APIGatewayProxyResponseEvent authenticateRequestHandler(APIGatewayProxyRequestEvent input, Context context) {
    return isWarming(input).orElseGet(() -> {
        String sessionId = RequestHeaderHelper.getHeaderValueOrElse(input.getHeaders(), SESSION_ID_HEADER, "");
        attachSessionIdToLogs(sessionId);
        LOG.info("Request received to the AuthenticateHandler");
        try {
            AuthenticateRequest loginRequest = objectMapper.readValue(input.getBody(), AuthenticateRequest.class);
            boolean userHasAccount = authenticationService.userExists(loginRequest.getEmail());
            if (!userHasAccount) {
                return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1010);
            }
            boolean hasValidCredentials = authenticationService.login(loginRequest.getEmail(), loginRequest.getPassword());
            if (!hasValidCredentials) {
                return generateApiGatewayProxyErrorResponse(401, ErrorResponse.ERROR_1008);
            }
            LOG.info("User has successfully Logged in. Generating successful AuthenticateResponse");
            auditService.submitAuditEvent(AccountManagementAuditableEvent.ACCOUNT_MANAGEMENT_AUTHENTICATE, context.getAwsRequestId(), sessionId, AuditService.UNKNOWN, AuditService.UNKNOWN, loginRequest.getEmail(), IpAddressHelper.extractIpAddress(input), AuditService.UNKNOWN, PersistentIdHelper.extractPersistentIdFromHeaders(input.getHeaders()));
            return generateEmptySuccessApiGatewayResponse();
        } catch (JsonException e) {
            return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1001);
        }
    });
}
Also used : JsonException(uk.gov.di.authentication.shared.serialization.Json.JsonException) AuthenticateRequest(uk.gov.di.accountmanagement.entity.AuthenticateRequest)

Example 9 with JsonException

use of uk.gov.di.authentication.shared.serialization.Json.JsonException in project di-authentication-api by alphagov.

the class NotificationHandler method notificationRequestHandler.

public Void notificationRequestHandler(SQSEvent event, Context context) {
    for (SQSMessage msg : event.getRecords()) {
        try {
            LOG.info("Message received from SQS queue");
            NotifyRequest notifyRequest = objectMapper.readValue(msg.getBody(), NotifyRequest.class);
            try {
                switch(notifyRequest.getNotificationType()) {
                    case VERIFY_EMAIL:
                        Map<String, Object> emailPersonalisation = new HashMap<>();
                        emailPersonalisation.put("validation-code", notifyRequest.getCode());
                        emailPersonalisation.put("email-address", notifyRequest.getDestination());
                        emailPersonalisation.put("contact-us-link", buildContactUsUrl("confirmEmailAddressEmail"));
                        LOG.info("Sending VERIFY_EMAIL email using Notify");
                        notificationService.sendEmail(notifyRequest.getDestination(), emailPersonalisation, notificationService.getNotificationTemplateId(NotificationType.VERIFY_EMAIL));
                        LOG.info("VERIFY_EMAIL email has been sent using Notify");
                        break;
                    case VERIFY_PHONE_NUMBER:
                        Map<String, Object> phonePersonalisation = new HashMap<>();
                        phonePersonalisation.put("validation-code", notifyRequest.getCode());
                        LOG.info("Sending VERIFY_PHONE_NUMBER email using Notify");
                        notificationService.sendText(notifyRequest.getDestination(), phonePersonalisation, notificationService.getNotificationTemplateId(NotificationType.VERIFY_PHONE_NUMBER));
                        LOG.info("VERIFY_PHONE_NUMBER text has been sent using Notify");
                        break;
                    case EMAIL_UPDATED:
                        Map<String, Object> emailUpdatePersonalisation = new HashMap<>();
                        emailUpdatePersonalisation.put("email-address", notifyRequest.getDestination());
                        emailUpdatePersonalisation.put("contact-us-link", buildContactUsUrl("emailAddressUpdatedEmail"));
                        LOG.info("Sending EMAIL_UPDATED email using Notify");
                        notificationService.sendEmail(notifyRequest.getDestination(), emailUpdatePersonalisation, notificationService.getNotificationTemplateId(NotificationType.EMAIL_UPDATED));
                        LOG.info("EMAIL_UPDATED email has been sent using Notify");
                        break;
                    case DELETE_ACCOUNT:
                        LOG.info("Sending DELETE_ACCOUNT email using Notify");
                        Map<String, Object> accountDeletedPersonalisation = new HashMap<>();
                        accountDeletedPersonalisation.put("contact-us-link", buildContactUsUrl("accountDeletedEmail"));
                        notificationService.sendEmail(notifyRequest.getDestination(), accountDeletedPersonalisation, notificationService.getNotificationTemplateId(NotificationType.DELETE_ACCOUNT));
                        LOG.info("DELETE_ACCOUNT email has been sent using Notify");
                        break;
                    case PHONE_NUMBER_UPDATED:
                        LOG.info("Sending PHONE_NUMBER_UPDATED email using Notify");
                        Map<String, Object> phoneNumberUpdatedPersonalisation = new HashMap<>();
                        phoneNumberUpdatedPersonalisation.put("contact-us-link", buildContactUsUrl("phoneNumberUpdatedEmail"));
                        notificationService.sendEmail(notifyRequest.getDestination(), phoneNumberUpdatedPersonalisation, notificationService.getNotificationTemplateId(NotificationType.PHONE_NUMBER_UPDATED));
                        LOG.info("PHONE_NUMBER_UPDATED email has been sent using Notify");
                        break;
                    case PASSWORD_UPDATED:
                        LOG.info("Sending PASSWORD_UPDATED email using Notify");
                        Map<String, Object> passwordUpdatedPersonalisation = new HashMap<>();
                        passwordUpdatedPersonalisation.put("contact-us-link", buildContactUsUrl("passwordUpdatedEmail"));
                        notificationService.sendEmail(notifyRequest.getDestination(), passwordUpdatedPersonalisation, notificationService.getNotificationTemplateId(NotificationType.PASSWORD_UPDATED));
                        LOG.info("PASSWORD_UPDATED email has been sent using Notify");
                        break;
                }
            } catch (NotificationClientException e) {
                LOG.error("Error sending with Notify", e);
                throw new RuntimeException(String.format("Error sending with Notify using NotificationType: %s", notifyRequest.getNotificationType()), e);
            }
        } catch (JsonException e) {
            LOG.error("Error when mapping message from queue to a NotifyRequest");
            throw new RuntimeException("Error when mapping message from queue to a NotifyRequest");
        }
    }
    return null;
}
Also used : JsonException(uk.gov.di.authentication.shared.serialization.Json.JsonException) NotificationClientException(uk.gov.service.notify.NotificationClientException) HashMap(java.util.HashMap) SQSMessage(com.amazonaws.services.lambda.runtime.events.SQSEvent.SQSMessage) NotifyRequest(uk.gov.di.accountmanagement.entity.NotifyRequest)

Example 10 with JsonException

use of uk.gov.di.authentication.shared.serialization.Json.JsonException in project di-authentication-api by alphagov.

the class RemoveAccountHandler method removeAccountRequestHandler.

public APIGatewayProxyResponseEvent removeAccountRequestHandler(APIGatewayProxyRequestEvent input, Context context) {
    return isWarming(input).orElseGet(() -> {
        try {
            String sessionId = RequestHeaderHelper.getHeaderValueOrElse(input.getHeaders(), SESSION_ID_HEADER, "");
            attachSessionIdToLogs(sessionId);
            LOG.info("RemoveAccountHandler received request");
            RemoveAccountRequest removeAccountRequest = objectMapper.readValue(input.getBody(), RemoveAccountRequest.class);
            String email = removeAccountRequest.getEmail();
            UserProfile userProfile = authenticationService.getUserProfileByEmailMaybe(email).orElseThrow(() -> new RuntimeException("User not found"));
            Map<String, Object> authorizerParams = input.getRequestContext().getAuthorizer();
            RequestBodyHelper.validatePrincipal(new Subject(userProfile.getPublicSubjectID()), authorizerParams);
            authenticationService.removeAccount(email);
            LOG.info("User account removed. Adding message to SQS queue");
            NotifyRequest notifyRequest = new NotifyRequest(email, NotificationType.DELETE_ACCOUNT);
            sqsClient.send(objectMapper.writeValueAsString((notifyRequest)));
            LOG.info("Remove account message successfully added to queue. Generating successful gateway response");
            auditService.submitAuditEvent(AccountManagementAuditableEvent.DELETE_ACCOUNT, context.getAwsRequestId(), sessionId, AuditService.UNKNOWN, userProfile.getSubjectID(), userProfile.getEmail(), IpAddressHelper.extractIpAddress(input), userProfile.getPhoneNumber(), PersistentIdHelper.extractPersistentIdFromHeaders(input.getHeaders()));
            return generateEmptySuccessApiGatewayResponse();
        } catch (JsonException e) {
            return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1001);
        }
    });
}
Also used : JsonException(uk.gov.di.authentication.shared.serialization.Json.JsonException) UserProfile(uk.gov.di.authentication.shared.entity.UserProfile) RemoveAccountRequest(uk.gov.di.accountmanagement.entity.RemoveAccountRequest) NotifyRequest(uk.gov.di.accountmanagement.entity.NotifyRequest) Subject(com.nimbusds.oauth2.sdk.id.Subject)

Aggregations

JsonException (uk.gov.di.authentication.shared.serialization.Json.JsonException)25 ClientRegistry (uk.gov.di.authentication.shared.entity.ClientRegistry)7 ErrorResponse (uk.gov.di.authentication.shared.entity.ErrorResponse)7 ApiGatewayResponseHelper.generateApiGatewayProxyErrorResponse (uk.gov.di.authentication.shared.helpers.ApiGatewayResponseHelper.generateApiGatewayProxyErrorResponse)7 Subject (com.nimbusds.oauth2.sdk.id.Subject)6 NotifyRequest (uk.gov.di.accountmanagement.entity.NotifyRequest)5 UserProfile (uk.gov.di.authentication.shared.entity.UserProfile)5 State (com.nimbusds.oauth2.sdk.id.State)4 NotifyRequest (uk.gov.di.authentication.shared.entity.NotifyRequest)4 SQSMessage (com.amazonaws.services.lambda.runtime.events.SQSEvent.SQSMessage)3 SignedJWT (com.nimbusds.jwt.SignedJWT)3 ErrorObject (com.nimbusds.oauth2.sdk.ErrorObject)3 NoSuchElementException (java.util.NoSuchElementException)3 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)2 ParseException (com.nimbusds.oauth2.sdk.ParseException)2 ResponseType (com.nimbusds.oauth2.sdk.ResponseType)2 ClientID (com.nimbusds.oauth2.sdk.id.ClientID)2 Date (java.util.Date)2 HashMap (java.util.HashMap)2 SdkClientException (software.amazon.awssdk.core.exception.SdkClientException)2