Search in sources :

Example 81 with Subject

use of com.nimbusds.oauth2.sdk.id.Subject in project di-authentication-api by alphagov.

the class UpdateEmailIntegrationTest method shouldReturn400WhenNewEmailIsAlreadyTaken.

@Test
void shouldReturn400WhenNewEmailIsAlreadyTaken() throws Exception {
    String publicSubjectID = userStore.signUp(EXISTING_EMAIL_ADDRESS, "password-1", SUBJECT);
    userStore.signUp(NEW_EMAIL_ADDRESS, "password-2", new Subject());
    String otp = redis.generateAndSaveEmailCode(NEW_EMAIL_ADDRESS, 300);
    var response = makeRequest(Optional.of(new UpdateEmailRequest(EXISTING_EMAIL_ADDRESS, NEW_EMAIL_ADDRESS, otp)), Collections.emptyMap(), Collections.emptyMap(), Collections.emptyMap(), Map.of("principalId", publicSubjectID));
    assertThat(response, hasStatus(HttpStatus.SC_BAD_REQUEST));
    assertThat(response, hasBody(objectMapper.writeValueAsString(ErrorResponse.ERROR_1009)));
    assertNoNotificationsReceived(notificationsQueue);
    assertNoAuditEventsReceived(auditTopic);
}
Also used : UpdateEmailRequest(uk.gov.di.accountmanagement.entity.UpdateEmailRequest) Subject(com.nimbusds.oauth2.sdk.id.Subject) Test(org.junit.jupiter.api.Test) ApiGatewayHandlerIntegrationTest(uk.gov.di.authentication.sharedtest.basetest.ApiGatewayHandlerIntegrationTest)

Example 82 with Subject

use of com.nimbusds.oauth2.sdk.id.Subject in project di-authentication-api by alphagov.

the class UpdatePhoneNumberIntegrationTest method shouldThrowExceptionWhenUserAttemptsToUpdateDifferentAccount.

@Test
void shouldThrowExceptionWhenUserAttemptsToUpdateDifferentAccount() {
    userStore.signUp(TEST_EMAIL, "password-1", SUBJECT);
    String otherSubjectID = userStore.signUp("other.user@digital.cabinet-office.gov.uk", "password-2", new Subject());
    String otp = redis.generateAndSavePhoneNumberCode(TEST_EMAIL, 300);
    Exception ex = assertThrows(RuntimeException.class, () -> makeRequest(Optional.of(new UpdatePhoneNumberRequest(TEST_EMAIL, NEW_PHONE_NUMBER, otp)), Collections.emptyMap(), Collections.emptyMap(), Collections.emptyMap(), Map.of("principalId", otherSubjectID)));
    assertThat(ex.getMessage(), is("Subject ID does not match principalId"));
}
Also used : Subject(com.nimbusds.oauth2.sdk.id.Subject) UpdatePhoneNumberRequest(uk.gov.di.accountmanagement.entity.UpdatePhoneNumberRequest) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) ApiGatewayHandlerIntegrationTest(uk.gov.di.authentication.sharedtest.basetest.ApiGatewayHandlerIntegrationTest)

Example 83 with Subject

use of com.nimbusds.oauth2.sdk.id.Subject 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 84 with Subject

use of com.nimbusds.oauth2.sdk.id.Subject 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 85 with Subject

use of com.nimbusds.oauth2.sdk.id.Subject in project di-authentication-api by alphagov.

the class AuthCodeHandlerTest method generateValidSession.

private void generateValidSession(Map<String, List<String>> authRequestParams, CredentialTrustLevel requestedLevel, boolean docAppJourney) {
    when(sessionService.getSessionFromRequestHeaders(anyMap())).thenReturn(Optional.of(session));
    when(clientSessionService.getClientSessionFromRequestHeaders(anyMap())).thenReturn(Optional.of(clientSession));
    when(vectorOfTrust.getCredentialTrustLevel()).thenReturn(requestedLevel);
    when(clientSession.getEffectiveVectorOfTrust()).thenReturn(vectorOfTrust);
    when(clientSession.getAuthRequestParams()).thenReturn(authRequestParams);
    if (docAppJourney) {
        when(clientSession.getDocAppSubjectId()).thenReturn(new Subject("docAppSubjectId"));
    }
}
Also used : Subject(com.nimbusds.oauth2.sdk.id.Subject)

Aggregations

Subject (com.nimbusds.oauth2.sdk.id.Subject)59 Test (org.junit.jupiter.api.Test)36 SignedJWT (com.nimbusds.jwt.SignedJWT)22 Date (java.util.Date)22 ApiGatewayHandlerIntegrationTest (uk.gov.di.authentication.sharedtest.basetest.ApiGatewayHandlerIntegrationTest)19 UserProfile (uk.gov.di.authentication.shared.entity.UserProfile)18 KeyPair (java.security.KeyPair)16 BearerAccessToken (com.nimbusds.oauth2.sdk.token.BearerAccessToken)15 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)13 ParseException (com.nimbusds.oauth2.sdk.ParseException)12 Scope (com.nimbusds.oauth2.sdk.Scope)12 APIGatewayProxyRequestEvent (com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent)11 APIGatewayProxyResponseEvent (com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent)11 AccessToken (com.nimbusds.oauth2.sdk.token.AccessToken)10 ECKeyGenerator (com.nimbusds.jose.jwk.gen.ECKeyGenerator)9 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)9 ECDSASigner (com.nimbusds.jose.crypto.ECDSASigner)8 Issuer (com.nimbusds.oauth2.sdk.id.Issuer)8 IDTokenClaimsSet (com.nimbusds.openid.connect.sdk.claims.IDTokenClaimsSet)8 LocalDateTime (java.time.LocalDateTime)8