Search in sources :

Example 21 with JsonException

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

the class LoginHandler method handleRequestWithUserContext.

@Override
public APIGatewayProxyResponseEvent handleRequestWithUserContext(APIGatewayProxyRequestEvent input, Context context, LoginRequest request, UserContext userContext) {
    attachSessionIdToLogs(userContext.getSession().getSessionId());
    LOG.info("Request received");
    try {
        var persistentSessionId = PersistentIdHelper.extractPersistentIdFromHeaders(input.getHeaders());
        Optional<UserProfile> userProfileMaybe = authenticationService.getUserProfileByEmailMaybe(request.getEmail());
        if (userProfileMaybe.isEmpty()) {
            auditService.submitAuditEvent(FrontendAuditableEvent.NO_ACCOUNT_WITH_EMAIL, context.getAwsRequestId(), userContext.getSession().getSessionId(), AuditService.UNKNOWN, AuditService.UNKNOWN, AuditService.UNKNOWN, IpAddressHelper.extractIpAddress(input), AuditService.UNKNOWN, persistentSessionId);
            return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1010);
        }
        UserProfile userProfile = userProfileMaybe.get();
        int incorrectPasswordCount = codeStorageService.getIncorrectPasswordCount(request.getEmail());
        if (incorrectPasswordCount >= configurationService.getMaxPasswordRetries()) {
            LOG.info("User has exceeded max password retries");
            auditService.submitAuditEvent(FrontendAuditableEvent.ACCOUNT_TEMPORARILY_LOCKED, context.getAwsRequestId(), userContext.getSession().getSessionId(), AuditService.UNKNOWN, userProfile.getSubjectID(), userProfile.getEmail(), IpAddressHelper.extractIpAddress(input), userProfile.getPhoneNumber(), persistentSessionId);
            return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1028);
        }
        if (!credentialsAreValid(request, userProfile)) {
            codeStorageService.increaseIncorrectPasswordCount(request.getEmail());
            auditService.submitAuditEvent(FrontendAuditableEvent.INVALID_CREDENTIALS, context.getAwsRequestId(), userContext.getSession().getSessionId(), AuditService.UNKNOWN, AuditService.UNKNOWN, request.getEmail(), IpAddressHelper.extractIpAddress(input), AuditService.UNKNOWN, persistentSessionId);
            return generateApiGatewayProxyErrorResponse(401, ErrorResponse.ERROR_1008);
        }
        if (incorrectPasswordCount != 0) {
            codeStorageService.deleteIncorrectPasswordCount(request.getEmail());
        }
        var isPhoneNumberVerified = userProfile.isPhoneNumberVerified();
        String redactedPhoneNumber = null;
        if (isPhoneNumberVerified) {
            redactedPhoneNumber = RedactPhoneNumberHelper.redactPhoneNumber(userProfile.getPhoneNumber());
        }
        boolean termsAndConditionsAccepted = false;
        if (Objects.nonNull(userProfile.getTermsAndConditions())) {
            termsAndConditionsAccepted = TermsAndConditionsHelper.hasTermsAndConditionsBeenAccepted(userProfile.getTermsAndConditions(), configurationService.getTermsAndConditionsVersion());
        }
        sessionService.save(userContext.getSession().setNewAccount(EXISTING));
        var isMfaRequired = MfaHelper.mfaRequired(userContext.getClientSession().getAuthRequestParams());
        var consentRequired = ConsentHelper.userHasNotGivenConsent(userContext);
        LOG.info("User has successfully logged in");
        auditService.submitAuditEvent(LOG_IN_SUCCESS, context.getAwsRequestId(), userContext.getSession().getSessionId(), AuditService.UNKNOWN, userProfile.getSubjectID(), userProfile.getEmail(), IpAddressHelper.extractIpAddress(input), userProfile.getPhoneNumber(), persistentSessionId);
        return generateApiGatewayProxyResponse(200, new LoginResponse(redactedPhoneNumber, isMfaRequired, isPhoneNumberVerified, termsAndConditionsAccepted, consentRequired));
    } catch (JsonException e) {
        return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1001);
    }
}
Also used : JsonException(uk.gov.di.authentication.shared.serialization.Json.JsonException) LoginResponse(uk.gov.di.authentication.frontendapi.entity.LoginResponse) UserProfile(uk.gov.di.authentication.shared.entity.UserProfile)

Example 22 with JsonException

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

the class NotifyCallbackHandler method notifyCallbackRequestHandler.

public APIGatewayProxyResponseEvent notifyCallbackRequestHandler(APIGatewayProxyRequestEvent input, Context context) {
    LOG.info("Received request");
    validateBearerToken(input.getHeaders());
    NotifyDeliveryReceipt deliveryReceipt;
    try {
        deliveryReceipt = objectMapper.readValue(input.getBody(), NotifyDeliveryReceipt.class);
        if (deliveryReceipt.getNotificationType().equals("sms")) {
            var countryCode = getCountryCodeFromNumber(deliveryReceipt.getTo());
            var deliveryStatus = getDeliveryStatus(deliveryReceipt.getStatus());
            LOG.info("SmsDeliveryStatus: {}, NotifyStatus: {}, CountryCode: {}", deliveryStatus, deliveryReceipt.getStatus(), countryCode);
            cloudwatchMetricsService.incrementCounter(deliveryStatus, Map.of("CountryCode", String.valueOf(countryCode), "Environment", configurationService.getEnvironment(), "NotifyStatus", deliveryReceipt.getStatus()));
            LOG.info("SMS callback request processed");
        }
    } catch (JsonException e) {
        LOG.error("Unable to parse Notify Delivery Receipt");
        throw new RuntimeException("Unable to parse Notify Delivery Receipt");
    }
    return generateEmptySuccessApiGatewayResponse();
}
Also used : JsonException(uk.gov.di.authentication.shared.serialization.Json.JsonException) NotifyDeliveryReceipt(uk.gov.di.authentication.deliveryreceiptsapi.entity.NotifyDeliveryReceipt)

Example 23 with JsonException

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

the class UpdateEmailHandler method updateEmailRequestHandler.

public APIGatewayProxyResponseEvent updateEmailRequestHandler(APIGatewayProxyRequestEvent input, Context context) {
    return isWarming(input).orElseGet(() -> {
        String sessionId = RequestHeaderHelper.getHeaderValueOrElse(input.getHeaders(), SESSION_ID_HEADER, "");
        attachSessionIdToLogs(sessionId);
        LOG.info("UpdateEmailHandler received request");
        try {
            UpdateEmailRequest updateInfoRequest = objectMapper.readValue(input.getBody(), UpdateEmailRequest.class);
            boolean isValidOtpCode = codeStorageService.isValidOtpCode(updateInfoRequest.getReplacementEmailAddress(), updateInfoRequest.getOtp(), NotificationType.VERIFY_EMAIL);
            if (!isValidOtpCode) {
                return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1020);
            }
            Optional<ErrorResponse> emailValidationErrors = ValidationHelper.validateEmailAddressUpdate(updateInfoRequest.getExistingEmailAddress(), updateInfoRequest.getReplacementEmailAddress());
            if (emailValidationErrors.isPresent()) {
                return generateApiGatewayProxyErrorResponse(400, emailValidationErrors.get());
            }
            if (dynamoService.userExists(updateInfoRequest.getReplacementEmailAddress())) {
                return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1009);
            }
            UserProfile userProfile = dynamoService.getUserProfileByEmail(updateInfoRequest.getExistingEmailAddress());
            Map<String, Object> authorizerParams = input.getRequestContext().getAuthorizer();
            RequestBodyHelper.validatePrincipal(new Subject(userProfile.getPublicSubjectID()), authorizerParams);
            dynamoService.updateEmail(updateInfoRequest.getExistingEmailAddress(), updateInfoRequest.getReplacementEmailAddress());
            LOG.info("Email has successfully been updated. Adding message to SQS queue");
            NotifyRequest notifyRequest = new NotifyRequest(updateInfoRequest.getReplacementEmailAddress(), NotificationType.EMAIL_UPDATED);
            sqsClient.send(objectMapper.writeValueAsString((notifyRequest)));
            auditService.submitAuditEvent(AccountManagementAuditableEvent.UPDATE_EMAIL, context.getAwsRequestId(), sessionId, AuditService.UNKNOWN, userProfile.getSubjectID(), updateInfoRequest.getReplacementEmailAddress(), IpAddressHelper.extractIpAddress(input), userProfile.getPhoneNumber(), PersistentIdHelper.extractPersistentIdFromHeaders(input.getHeaders()));
            LOG.info("Message successfully added to queue. Generating successful gateway response");
            return generateEmptySuccessApiGatewayResponse();
        } catch (JsonException | IllegalArgumentException e) {
            return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1001);
        }
    });
}
Also used : JsonException(uk.gov.di.authentication.shared.serialization.Json.JsonException) UpdateEmailRequest(uk.gov.di.accountmanagement.entity.UpdateEmailRequest) UserProfile(uk.gov.di.authentication.shared.entity.UserProfile) NotifyRequest(uk.gov.di.accountmanagement.entity.NotifyRequest) Subject(com.nimbusds.oauth2.sdk.id.Subject) ErrorResponse(uk.gov.di.authentication.shared.entity.ErrorResponse) ApiGatewayResponseHelper.generateApiGatewayProxyErrorResponse(uk.gov.di.authentication.shared.helpers.ApiGatewayResponseHelper.generateApiGatewayProxyErrorResponse)

Example 24 with JsonException

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

the class UpdatePasswordHandler method updatePasswordRequestHandler.

public APIGatewayProxyResponseEvent updatePasswordRequestHandler(APIGatewayProxyRequestEvent input, Context context) {
    return isWarming(input).orElseGet(() -> {
        String sessionId = RequestHeaderHelper.getHeaderValueOrElse(input.getHeaders(), SESSION_ID_HEADER, "");
        attachSessionIdToLogs(sessionId);
        LOG.info("UpdatePasswordHandler received request");
        context.getClientContext();
        try {
            UpdatePasswordRequest updatePasswordRequest = objectMapper.readValue(input.getBody(), UpdatePasswordRequest.class);
            UserProfile userProfile = dynamoService.getUserProfileByEmail(updatePasswordRequest.getEmail());
            Map<String, Object> authorizerParams = input.getRequestContext().getAuthorizer();
            RequestBodyHelper.validatePrincipal(new Subject(userProfile.getPublicSubjectID()), authorizerParams);
            String currentPassword = dynamoService.getUserCredentialsFromEmail(updatePasswordRequest.getEmail()).getPassword();
            if (verifyPassword(currentPassword, updatePasswordRequest.getNewPassword())) {
                return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1024);
            }
            dynamoService.updatePassword(updatePasswordRequest.getEmail(), updatePasswordRequest.getNewPassword());
            LOG.info("User Password has successfully been updated.  Adding confirmation message to SQS queue");
            NotifyRequest notifyRequest = new NotifyRequest(updatePasswordRequest.getEmail(), NotificationType.PASSWORD_UPDATED);
            sqsClient.send(objectMapper.writeValueAsString((notifyRequest)));
            LOG.info("Message successfully added to queue. Generating successful gateway response");
            auditService.submitAuditEvent(AccountManagementAuditableEvent.UPDATE_PASSWORD, context.getAwsRequestId(), sessionId, AuditService.UNKNOWN, userProfile.getSubjectID(), userProfile.getEmail(), IpAddressHelper.extractIpAddress(input), userProfile.getPhoneNumber(), PersistentIdHelper.extractPersistentIdFromHeaders(input.getHeaders()));
            return generateEmptySuccessApiGatewayResponse();
        } catch (JsonException | IllegalArgumentException 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) UpdatePasswordRequest(uk.gov.di.accountmanagement.entity.UpdatePasswordRequest) NotifyRequest(uk.gov.di.accountmanagement.entity.NotifyRequest) Subject(com.nimbusds.oauth2.sdk.id.Subject)

Example 25 with JsonException

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

the class IPVAuthorisationHandler method handleRequestWithUserContext.

@Override
public APIGatewayProxyResponseEvent handleRequestWithUserContext(APIGatewayProxyRequestEvent input, Context context, IPVAuthorisationRequest request, UserContext userContext) {
    try {
        if (!configurationService.isIdentityEnabled()) {
            LOG.error("Identity is not enabled");
            throw new RuntimeException("Identity is not enabled");
        }
        var persistentId = PersistentIdHelper.extractPersistentIdFromHeaders(input.getHeaders());
        attachLogFieldToLogs(PERSISTENT_SESSION_ID, persistentId);
        var clientId = userContext.getClient().map(ClientRegistry::getClientID);
        attachLogFieldToLogs(CLIENT_ID, clientId.orElse(UNKNOWN));
        LOG.info("IPVAuthorisationHandler received request");
        var authRequest = AuthenticationRequest.parse(userContext.getClientSession().getAuthRequestParams());
        var pairwiseSubject = ClientSubjectHelper.getSubjectWithSectorIdentifier(userContext.getUserProfile().orElseThrow(), configurationService.getIPVSector(), authenticationService);
        var clientID = new ClientID(configurationService.getIPVAuthorisationClientId());
        var state = new State();
        var claimsSetRequest = buildIpvClaimsRequest(authRequest).map(ClaimsSetRequest::toJSONString).orElse(null);
        var nonce = new Nonce(IdGenerator.generate());
        var encryptedJWT = authorisationService.constructRequestJWT(state, nonce, authRequest.getScope(), pairwiseSubject, claimsSetRequest);
        var authRequestBuilder = new AuthorizationRequest.Builder(new ResponseType(ResponseType.Value.CODE), clientID).endpointURI(configurationService.getIPVAuthorisationURI()).requestObject(encryptedJWT);
        var ipvAuthorisationRequest = authRequestBuilder.build();
        authorisationService.storeState(userContext.getSession().getSessionId(), state);
        auditService.submitAuditEvent(IPVAuditableEvent.IPV_AUTHORISATION_REQUESTED, context.getAwsRequestId(), userContext.getSession().getSessionId(), clientId.orElse(AuditService.UNKNOWN), AuditService.UNKNOWN, request.getEmail(), IpAddressHelper.extractIpAddress(input), AuditService.UNKNOWN, persistentId);
        LOG.info("IPVAuthorisationHandler successfully processed request, redirect URI {}", ipvAuthorisationRequest.toURI().toString());
        return generateApiGatewayProxyResponse(200, new IPVAuthorisationResponse(ipvAuthorisationRequest.toURI().toString()));
    } catch (ParseException | JsonException e) {
        return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1001);
    }
}
Also used : Nonce(com.nimbusds.openid.connect.sdk.Nonce) IPVAuthorisationResponse(uk.gov.di.authentication.ipv.entity.IPVAuthorisationResponse) JsonException(uk.gov.di.authentication.shared.serialization.Json.JsonException) State(com.nimbusds.oauth2.sdk.id.State) ClientRegistry(uk.gov.di.authentication.shared.entity.ClientRegistry) ClientID(com.nimbusds.oauth2.sdk.id.ClientID) ParseException(com.nimbusds.oauth2.sdk.ParseException) ResponseType(com.nimbusds.oauth2.sdk.ResponseType)

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