Search in sources :

Example 1 with UserProfile

use of uk.gov.di.authentication.shared.entity.UserProfile in project di-authentication-api by alphagov.

the class TokenHandlerTest method shouldReturn200ForSuccessfulTokenRequest.

@ParameterizedTest
@MethodSource("validVectorValues")
public void shouldReturn200ForSuccessfulTokenRequest(String vectorValue) throws JOSEException {
    KeyPair keyPair = generateRsaKeyPair();
    UserProfile userProfile = generateUserProfile();
    SignedJWT signedJWT = generateIDToken(CLIENT_ID, PUBLIC_SUBJECT, "issuer-url", new ECKeyGenerator(Curve.P_256).algorithm(JWSAlgorithm.ES256).generate());
    OIDCTokenResponse tokenResponse = new OIDCTokenResponse(new OIDCTokens(signedJWT, accessToken, refreshToken));
    PrivateKeyJWT privateKeyJWT = generatePrivateKeyJWT(keyPair.getPrivate());
    ClientRegistry clientRegistry = generateClientRegistry(keyPair);
    when(tokenService.validateTokenRequestParams(anyString())).thenReturn(Optional.empty());
    when(clientService.getClient(eq(CLIENT_ID))).thenReturn(Optional.of(clientRegistry));
    when(tokenService.validatePrivateKeyJWT(anyString(), eq(clientRegistry.getPublicKey()), eq(BASE_URI), eq(CLIENT_ID))).thenReturn(Optional.empty());
    String authCode = new AuthorizationCode().toString();
    when(authorisationCodeService.getExchangeDataForCode(authCode)).thenReturn(Optional.of(new AuthCodeExchangeData().setEmail(TEST_EMAIL).setClientSessionId(CLIENT_SESSION_ID)));
    AuthenticationRequest authenticationRequest = generateAuthRequest(JsonArrayHelper.jsonArrayOf(vectorValue));
    VectorOfTrust vtr = VectorOfTrust.parseFromAuthRequestAttribute(authenticationRequest.getCustomParameter("vtr"));
    when(clientSessionService.getClientSession(CLIENT_SESSION_ID)).thenReturn(new ClientSession(authenticationRequest.toParameters(), LocalDateTime.now(), vtr));
    when(dynamoService.getUserProfileByEmail(eq(TEST_EMAIL))).thenReturn(userProfile);
    when(tokenService.generateTokenResponse(CLIENT_ID, INTERNAL_SUBJECT, SCOPES, Map.of("nonce", NONCE), PUBLIC_SUBJECT, vtr.retrieveVectorOfTrustForToken(), userProfile.getClientConsent(), clientRegistry.isConsentRequired(), null)).thenReturn(tokenResponse);
    APIGatewayProxyResponseEvent result = generateApiGatewayRequest(privateKeyJWT, authCode);
    assertThat(result, hasStatus(200));
    assertTrue(result.getBody().contains(refreshToken.getValue()));
    assertTrue(result.getBody().contains(accessToken.getValue()));
}
Also used : AuthorizationCode(com.nimbusds.oauth2.sdk.AuthorizationCode) KeyPair(java.security.KeyPair) UserProfile(uk.gov.di.authentication.shared.entity.UserProfile) OIDCTokenResponse(com.nimbusds.openid.connect.sdk.OIDCTokenResponse) PrivateKeyJWT(com.nimbusds.oauth2.sdk.auth.PrivateKeyJWT) ECKeyGenerator(com.nimbusds.jose.jwk.gen.ECKeyGenerator) VectorOfTrust(uk.gov.di.authentication.shared.entity.VectorOfTrust) SignedJWT(com.nimbusds.jwt.SignedJWT) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) APIGatewayProxyResponseEvent(com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent) AuthCodeExchangeData(uk.gov.di.authentication.shared.entity.AuthCodeExchangeData) OIDCTokens(com.nimbusds.openid.connect.sdk.token.OIDCTokens) ClientSession(uk.gov.di.authentication.shared.entity.ClientSession) ClientRegistry(uk.gov.di.authentication.shared.entity.ClientRegistry) AuthenticationRequest(com.nimbusds.openid.connect.sdk.AuthenticationRequest) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Example 2 with UserProfile

use of uk.gov.di.authentication.shared.entity.UserProfile in project di-authentication-api by alphagov.

the class UpdateEmailHandler method handleRequest.

@Override
public APIGatewayProxyResponseEvent handleRequest(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 = validationService.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 (JsonProcessingException | IllegalArgumentException e) {
            return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1001);
        }
    });
}
Also used : 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) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 3 with UserProfile

use of uk.gov.di.authentication.shared.entity.UserProfile in project di-authentication-api by alphagov.

the class ClientSubjectHelperTest method shouldReturnSameSubjectIDForMultipleClientsWithPublicSubjectType.

@Test
void shouldReturnSameSubjectIDForMultipleClientsWithPublicSubjectType() {
    KeyPair keyPair = generateRsaKeyPair();
    UserProfile userProfile = generateUserProfile();
    ClientRegistry clientRegistry1 = generateClientRegistryPairwise(keyPair, "test-client-id-1", "public", "https://test.com");
    ClientRegistry clientRegistry2 = generateClientRegistryPairwise(keyPair, "test-client-id-2", "public", "https://test.com");
    Subject subject1 = ClientSubjectHelper.getSubject(userProfile, clientRegistry1, authenticationService);
    Subject subject2 = ClientSubjectHelper.getSubject(userProfile, clientRegistry2, authenticationService);
    assertEquals(subject1, subject2);
}
Also used : KeyPair(java.security.KeyPair) UserProfile(uk.gov.di.authentication.shared.entity.UserProfile) ClientRegistry(uk.gov.di.authentication.shared.entity.ClientRegistry) Subject(com.nimbusds.oauth2.sdk.id.Subject) Test(org.junit.jupiter.api.Test)

Example 4 with UserProfile

use of uk.gov.di.authentication.shared.entity.UserProfile in project di-authentication-api by alphagov.

the class ClientSubjectHelperTest method shouldReturnSameSubjectIDForMultipleClientsWithSameSector.

@Test
void shouldReturnSameSubjectIDForMultipleClientsWithSameSector() {
    stubAuthenticationService();
    KeyPair keyPair = generateRsaKeyPair();
    UserProfile userProfile = generateUserProfile();
    ClientRegistry clientRegistry1 = generateClientRegistryPairwise(keyPair, "test-client-id-1", "pairwise", "https://test.com");
    ClientRegistry clientRegistry2 = generateClientRegistryPairwise(keyPair, "test-client-id-2", "pairwise", "https://test.com");
    Subject subject1 = ClientSubjectHelper.getSubject(userProfile, clientRegistry1, authenticationService);
    Subject subject2 = ClientSubjectHelper.getSubject(userProfile, clientRegistry2, authenticationService);
    assertEquals(subject1, subject2);
}
Also used : KeyPair(java.security.KeyPair) UserProfile(uk.gov.di.authentication.shared.entity.UserProfile) ClientRegistry(uk.gov.di.authentication.shared.entity.ClientRegistry) Subject(com.nimbusds.oauth2.sdk.id.Subject) Test(org.junit.jupiter.api.Test)

Example 5 with UserProfile

use of uk.gov.di.authentication.shared.entity.UserProfile in project di-authentication-api by alphagov.

the class ClientSubjectHelperTest method shouldReturnDifferentSubjectIDForMultipleClientsWithDifferentSectors.

@Test
void shouldReturnDifferentSubjectIDForMultipleClientsWithDifferentSectors() {
    stubAuthenticationService();
    KeyPair keyPair = generateRsaKeyPair();
    UserProfile userProfile = generateUserProfile();
    ClientRegistry clientRegistry1 = generateClientRegistryPairwise(keyPair, "test-client-id-1", "pairwise", "https://test.com");
    ClientRegistry clientRegistry2 = generateClientRegistryPairwise(keyPair, "test-client-id-2", "pairwise", "https://not-test.com");
    Subject subject1 = ClientSubjectHelper.getSubject(userProfile, clientRegistry1, authenticationService);
    Subject subject2 = ClientSubjectHelper.getSubject(userProfile, clientRegistry2, authenticationService);
    assertNotEquals(subject1, subject2);
}
Also used : KeyPair(java.security.KeyPair) UserProfile(uk.gov.di.authentication.shared.entity.UserProfile) ClientRegistry(uk.gov.di.authentication.shared.entity.ClientRegistry) Subject(com.nimbusds.oauth2.sdk.id.Subject) Test(org.junit.jupiter.api.Test)

Aggregations

UserProfile (uk.gov.di.authentication.shared.entity.UserProfile)47 Test (org.junit.jupiter.api.Test)25 Subject (com.nimbusds.oauth2.sdk.id.Subject)20 APIGatewayProxyResponseEvent (com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent)18 APIGatewayProxyRequestEvent (com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent)15 ClientRegistry (uk.gov.di.authentication.shared.entity.ClientRegistry)15 NotifyRequest (uk.gov.di.accountmanagement.entity.NotifyRequest)13 HashMap (java.util.HashMap)11 UserCredentials (uk.gov.di.authentication.shared.entity.UserCredentials)11 AuthenticationRequest (com.nimbusds.openid.connect.sdk.AuthenticationRequest)10 ClientSession (uk.gov.di.authentication.shared.entity.ClientSession)10 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)7 KeyPair (java.security.KeyPair)6 ErrorResponse (uk.gov.di.authentication.shared.entity.ErrorResponse)6 Scope (com.nimbusds.oauth2.sdk.Scope)5 LocalDateTime (java.time.LocalDateTime)5 Optional (java.util.Optional)5 LoginResponse (uk.gov.di.authentication.frontendapi.entity.LoginResponse)5 Context (com.amazonaws.services.lambda.runtime.Context)4 OIDCScopeValue (com.nimbusds.openid.connect.sdk.OIDCScopeValue)4