Search in sources :

Example 1 with ClientRegistry

use of uk.gov.di.authentication.shared.entity.ClientRegistry 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 ClientRegistry

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

the class TokenHandlerTest method shouldReturn200ForSuccessfulRefreshTokenRequest.

@Test
public void shouldReturn200ForSuccessfulRefreshTokenRequest() throws JOSEException, JsonProcessingException {
    SignedJWT signedRefreshToken = createSignedRefreshToken();
    KeyPair keyPair = generateRsaKeyPair();
    RefreshToken refreshToken = new RefreshToken(signedRefreshToken.serialize());
    OIDCTokenResponse tokenResponse = new OIDCTokenResponse(new OIDCTokens(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());
    when(tokenValidationService.validateRefreshTokenSignatureAndExpiry(refreshToken)).thenReturn(true);
    when(tokenValidationService.validateRefreshTokenScopes(SCOPES.toStringList(), SCOPES.toStringList())).thenReturn(true);
    RefreshTokenStore tokenStore = new RefreshTokenStore(singletonList(refreshToken.getValue()), INTERNAL_SUBJECT.getValue());
    String redisKey = REFRESH_TOKEN_PREFIX + CLIENT_ID + "." + PUBLIC_SUBJECT.getValue();
    String tokenStoreString = new ObjectMapper().writeValueAsString(tokenStore);
    when(redisConnectionService.getValue(redisKey)).thenReturn(tokenStoreString);
    when(tokenService.generateRefreshTokenResponse(eq(CLIENT_ID), eq(INTERNAL_SUBJECT), eq(SCOPES.toStringList()), eq(PUBLIC_SUBJECT))).thenReturn(tokenResponse);
    APIGatewayProxyResponseEvent result = generateApiGatewayRefreshRequest(privateKeyJWT, refreshToken.getValue());
    assertThat(result, hasStatus(200));
    assertTrue(result.getBody().contains(refreshToken.getValue()));
    assertTrue(result.getBody().contains(accessToken.getValue()));
    verify(redisConnectionService, times(1)).deleteValue(redisKey);
}
Also used : RefreshTokenStore(uk.gov.di.authentication.shared.entity.RefreshTokenStore) KeyPair(java.security.KeyPair) RefreshToken(com.nimbusds.oauth2.sdk.token.RefreshToken) OIDCTokenResponse(com.nimbusds.openid.connect.sdk.OIDCTokenResponse) OIDCTokens(com.nimbusds.openid.connect.sdk.token.OIDCTokens) PrivateKeyJWT(com.nimbusds.oauth2.sdk.auth.PrivateKeyJWT) ClientRegistry(uk.gov.di.authentication.shared.entity.ClientRegistry) SignedJWT(com.nimbusds.jwt.SignedJWT) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) APIGatewayProxyResponseEvent(com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 3 with ClientRegistry

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

the class TokenHandlerTest method shouldReturn200ForRefreshTokenRequestWhenMultipleRefreshTokensAreStored.

@Test
public void shouldReturn200ForRefreshTokenRequestWhenMultipleRefreshTokensAreStored() throws JOSEException, JsonProcessingException {
    SignedJWT signedRefreshToken = createSignedRefreshToken();
    KeyPair keyPair = generateRsaKeyPair();
    RefreshToken refreshToken = new RefreshToken(signedRefreshToken.serialize());
    RefreshToken refreshToken2 = new RefreshToken();
    OIDCTokenResponse tokenResponse = new OIDCTokenResponse(new OIDCTokens(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());
    when(tokenValidationService.validateRefreshTokenSignatureAndExpiry(refreshToken)).thenReturn(true);
    when(tokenValidationService.validateRefreshTokenScopes(SCOPES.toStringList(), SCOPES.toStringList())).thenReturn(true);
    RefreshTokenStore tokenStore = new RefreshTokenStore(List.of(refreshToken.getValue(), refreshToken2.getValue()), INTERNAL_SUBJECT.getValue());
    String redisKey = REFRESH_TOKEN_PREFIX + CLIENT_ID + "." + PUBLIC_SUBJECT.getValue();
    String tokenStoreString = new ObjectMapper().writeValueAsString(tokenStore);
    when(redisConnectionService.getValue(redisKey)).thenReturn(tokenStoreString);
    when(tokenService.generateRefreshTokenResponse(eq(CLIENT_ID), eq(INTERNAL_SUBJECT), eq(SCOPES.toStringList()), eq(PUBLIC_SUBJECT))).thenReturn(tokenResponse);
    APIGatewayProxyResponseEvent result = generateApiGatewayRefreshRequest(privateKeyJWT, refreshToken.getValue());
    assertThat(result, hasStatus(200));
    assertTrue(result.getBody().contains(refreshToken.getValue()));
    assertTrue(result.getBody().contains(accessToken.getValue()));
    String updatedTokenstore = new ObjectMapper().writeValueAsString(new RefreshTokenStore(List.of(refreshToken2.getValue()), INTERNAL_SUBJECT.getValue()));
    verify(redisConnectionService, times(1)).saveWithExpiry(redisKey, updatedTokenstore, 1234L);
}
Also used : RefreshTokenStore(uk.gov.di.authentication.shared.entity.RefreshTokenStore) KeyPair(java.security.KeyPair) RefreshToken(com.nimbusds.oauth2.sdk.token.RefreshToken) OIDCTokenResponse(com.nimbusds.openid.connect.sdk.OIDCTokenResponse) OIDCTokens(com.nimbusds.openid.connect.sdk.token.OIDCTokens) PrivateKeyJWT(com.nimbusds.oauth2.sdk.auth.PrivateKeyJWT) ClientRegistry(uk.gov.di.authentication.shared.entity.ClientRegistry) SignedJWT(com.nimbusds.jwt.SignedJWT) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) APIGatewayProxyResponseEvent(com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Test(org.junit.jupiter.api.Test) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest)

Example 4 with ClientRegistry

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

the class StartServiceTest method buildUserContext.

private UserContext buildUserContext(String vtrValue, boolean consentRequired, boolean cookieConsentShared) {
    var authRequest = new AuthenticationRequest.Builder(new ResponseType(ResponseType.Value.CODE), SCOPES, CLIENT_ID, REDIRECT_URI).state(new State()).nonce(new Nonce()).customParameter("vtr", vtrValue).build();
    var clientSession = new ClientSession(authRequest.toParameters(), LocalDateTime.now(), VectorOfTrust.getDefaults());
    var clientRegistry = new ClientRegistry().setClientID(CLIENT_ID.getValue()).setClientName(CLIENT_NAME).setConsentRequired(consentRequired).setCookieConsentShared(cookieConsentShared);
    return UserContext.builder(SESSION).withClientSession(clientSession).withClient(clientRegistry).build();
}
Also used : Nonce(com.nimbusds.openid.connect.sdk.Nonce) State(com.nimbusds.oauth2.sdk.id.State) ClientSession(uk.gov.di.authentication.shared.entity.ClientSession) ClientRegistry(uk.gov.di.authentication.shared.entity.ClientRegistry) ResponseType(com.nimbusds.oauth2.sdk.ResponseType)

Example 5 with ClientRegistry

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

the class ResetPasswordHandler method handleRequestWithUserContext.

@Override
public APIGatewayProxyResponseEvent handleRequestWithUserContext(APIGatewayProxyRequestEvent input, Context context, ResetPasswordWithCodeRequest request, UserContext userContext) {
    LOG.info("Request received to ResetPasswordHandler");
    try {
        Optional<ErrorResponse> errorResponse = validationService.validatePassword(request.getPassword());
        if (errorResponse.isPresent()) {
            return generateApiGatewayProxyErrorResponse(400, errorResponse.get());
        }
        Optional<String> subject = codeStorageService.getSubjectWithPasswordResetCode(request.getCode());
        if (subject.isEmpty()) {
            return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1021);
        }
        UserCredentials userCredentials = authenticationService.getUserCredentialsFromSubject(subject.get());
        if (userCredentials.getPassword() != null) {
            if (verifyPassword(userCredentials.getPassword(), request.getPassword())) {
                return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1024);
            }
        } else {
            LOG.info("Resetting password for migrated user");
        }
        codeStorageService.deleteSubjectWithPasswordResetCode(request.getCode());
        authenticationService.updatePassword(userCredentials.getEmail(), request.getPassword());
        int incorrectPasswordCount = codeStorageService.getIncorrectPasswordCount(userCredentials.getEmail());
        if (incorrectPasswordCount != 0) {
            codeStorageService.deleteIncorrectPasswordCount(userCredentials.getEmail());
        }
        NotifyRequest notifyRequest = new NotifyRequest(userCredentials.getEmail(), NotificationType.PASSWORD_RESET_CONFIRMATION);
        LOG.info("Placing message on queue");
        sqsClient.send(serialiseRequest(notifyRequest));
        auditService.submitAuditEvent(FrontendAuditableEvent.PASSWORD_RESET_SUCCESSFUL, context.getAwsRequestId(), userContext.getSession().getSessionId(), userContext.getClient().map(ClientRegistry::getClientID).orElse(AuditService.UNKNOWN), AuditService.UNKNOWN, userCredentials.getEmail(), IpAddressHelper.extractIpAddress(input), AuditService.UNKNOWN, PersistentIdHelper.extractPersistentIdFromHeaders(input.getHeaders()));
    } catch (JsonProcessingException | ConstraintViolationException e) {
        return generateApiGatewayProxyErrorResponse(400, ErrorResponse.ERROR_1001);
    }
    LOG.info("Generating successful response");
    return generateEmptySuccessApiGatewayResponse();
}
Also used : ClientRegistry(uk.gov.di.authentication.shared.entity.ClientRegistry) ConstraintViolationException(jakarta.validation.ConstraintViolationException) UserCredentials(uk.gov.di.authentication.shared.entity.UserCredentials) NotifyRequest(uk.gov.di.authentication.shared.entity.NotifyRequest) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ErrorResponse(uk.gov.di.authentication.shared.entity.ErrorResponse) ApiGatewayResponseHelper.generateApiGatewayProxyErrorResponse(uk.gov.di.authentication.shared.helpers.ApiGatewayResponseHelper.generateApiGatewayProxyErrorResponse)

Aggregations

ClientRegistry (uk.gov.di.authentication.shared.entity.ClientRegistry)49 Test (org.junit.jupiter.api.Test)21 KeyPair (java.security.KeyPair)20 UserProfile (uk.gov.di.authentication.shared.entity.UserProfile)12 APIGatewayProxyResponseEvent (com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent)11 ClientSession (uk.gov.di.authentication.shared.entity.ClientSession)10 PrivateKeyJWT (com.nimbusds.oauth2.sdk.auth.PrivateKeyJWT)9 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)9 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)8 ErrorResponse (uk.gov.di.authentication.shared.entity.ErrorResponse)8 ApiGatewayResponseHelper.generateApiGatewayProxyErrorResponse (uk.gov.di.authentication.shared.helpers.ApiGatewayResponseHelper.generateApiGatewayProxyErrorResponse)8 SignedJWT (com.nimbusds.jwt.SignedJWT)7 ErrorObject (com.nimbusds.oauth2.sdk.ErrorObject)7 OIDCTokenResponse (com.nimbusds.openid.connect.sdk.OIDCTokenResponse)7 JsonException (uk.gov.di.authentication.shared.serialization.Json.JsonException)7 AuthorizationCode (com.nimbusds.oauth2.sdk.AuthorizationCode)6 Subject (com.nimbusds.oauth2.sdk.id.Subject)6 AuthenticationRequest (com.nimbusds.openid.connect.sdk.AuthenticationRequest)6 OIDCTokens (com.nimbusds.openid.connect.sdk.token.OIDCTokens)6 AuthCodeExchangeData (uk.gov.di.authentication.shared.entity.AuthCodeExchangeData)6