Search in sources :

Example 16 with APIGatewayProxyResponseEvent

use of com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent in project di-authentication-api by alphagov.

the class AuthorisationHandler method handleRequest.

@Override
public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent input, Context context) {
    return isWarming(input).orElseGet(() -> {
        var persistentSessionId = authorizationService.getExistingOrCreateNewPersistentSessionId(input.getHeaders());
        var ipAddress = IpAddressHelper.extractIpAddress(input);
        auditService.submitAuditEvent(OidcAuditableEvent.AUTHORISATION_REQUEST_RECEIVED, context.getAwsRequestId(), AuditService.UNKNOWN, AuditService.UNKNOWN, AuditService.UNKNOWN, AuditService.UNKNOWN, ipAddress, AuditService.UNKNOWN, persistentSessionId);
        attachLogFieldToLogs(PERSISTENT_SESSION_ID, persistentSessionId);
        attachLogFieldToLogs(AWS_REQUEST_ID, context.getAwsRequestId());
        LOG.info("Received authentication request");
        Map<String, List<String>> queryStringParameters;
        AuthenticationRequest authRequest;
        try {
            queryStringParameters = input.getQueryStringParameters().entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, entry -> List.of(entry.getValue())));
            authRequest = AuthenticationRequest.parse(queryStringParameters);
        } catch (ParseException e) {
            if (e.getRedirectionURI() == null) {
                LOG.warn("Authentication request could not be parsed: redirect URI or Client ID is missing from auth request");
                throw new RuntimeException("Redirect URI or ClientID is missing from auth request", e);
            }
            LOG.warn("Authentication request could not be parsed", e);
            return generateErrorResponse(e.getRedirectionURI(), e.getState(), e.getResponseMode(), e.getErrorObject(), context, ipAddress, persistentSessionId);
        } catch (NullPointerException e) {
            LOG.warn("No query string parameters are present in the Authentication request", e);
            throw new RuntimeException("No query string parameters are present in the Authentication request", e);
        }
        var error = authorizationService.validateAuthRequest(authRequest);
        return error.map(e -> generateErrorResponse(authRequest.getRedirectionURI(), authRequest.getState(), authRequest.getResponseMode(), e, context, ipAddress, persistentSessionId)).orElseGet(() -> getOrCreateSessionAndRedirect(queryStringParameters, sessionService.getSessionFromSessionCookie(input.getHeaders()), authRequest, context, ipAddress, persistentSessionId));
    });
}
Also used : Prompt(com.nimbusds.openid.connect.sdk.Prompt) SessionService(uk.gov.di.authentication.shared.services.SessionService) URISyntaxException(java.net.URISyntaxException) LocalDateTime(java.time.LocalDateTime) Context(com.amazonaws.services.lambda.runtime.Context) ConfigurationService(uk.gov.di.authentication.shared.services.ConfigurationService) RequestHandler(com.amazonaws.services.lambda.runtime.RequestHandler) ResponseMode(com.nimbusds.oauth2.sdk.ResponseMode) ResponseHeaders(uk.gov.di.authentication.shared.entity.ResponseHeaders) APIGatewayProxyRequestEvent(com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent) Session(uk.gov.di.authentication.shared.entity.Session) CLIENT_SESSION_ID(uk.gov.di.authentication.shared.helpers.LogLineHelper.LogFieldName.CLIENT_SESSION_ID) PERSISTENT_SESSION_ID(uk.gov.di.authentication.shared.helpers.LogLineHelper.LogFieldName.PERSISTENT_SESSION_ID) Map(java.util.Map) ParseException(com.nimbusds.oauth2.sdk.ParseException) URI(java.net.URI) AWS_REQUEST_ID(uk.gov.di.authentication.shared.helpers.LogLineHelper.LogFieldName.AWS_REQUEST_ID) CLIENT_ID(uk.gov.di.authentication.shared.helpers.LogLineHelper.LogFieldName.CLIENT_ID) LogLineHelper.updateAttachedSessionIdToLogs(uk.gov.di.authentication.shared.helpers.LogLineHelper.updateAttachedSessionIdToLogs) MetadataPair.pair(uk.gov.di.authentication.shared.services.AuditService.MetadataPair.pair) WarmerHelper.isWarming(uk.gov.di.authentication.shared.helpers.WarmerHelper.isWarming) AuthenticationErrorResponse(com.nimbusds.openid.connect.sdk.AuthenticationErrorResponse) OIDCError(com.nimbusds.openid.connect.sdk.OIDCError) URIBuilder(org.apache.http.client.utils.URIBuilder) OidcAuditableEvent(uk.gov.di.authentication.oidc.domain.OidcAuditableEvent) IpAddressHelper(uk.gov.di.authentication.shared.helpers.IpAddressHelper) APIGatewayProxyResponseEvent(com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent) ClientSession(uk.gov.di.authentication.shared.entity.ClientSession) AuditService(uk.gov.di.authentication.shared.services.AuditService) LogLineHelper.attachLogFieldToLogs(uk.gov.di.authentication.shared.helpers.LogLineHelper.attachLogFieldToLogs) State(com.nimbusds.oauth2.sdk.id.State) ErrorObject(com.nimbusds.oauth2.sdk.ErrorObject) CookieHelper(uk.gov.di.authentication.shared.helpers.CookieHelper) Collectors(java.util.stream.Collectors) AuthorizationService(uk.gov.di.authentication.shared.services.AuthorizationService) ClientSessionService(uk.gov.di.authentication.shared.services.ClientSessionService) Objects(java.util.Objects) List(java.util.List) Logger(org.apache.logging.log4j.Logger) AuthenticationRequest(com.nimbusds.openid.connect.sdk.AuthenticationRequest) LogLineHelper.attachSessionIdToLogs(uk.gov.di.authentication.shared.helpers.LogLineHelper.attachSessionIdToLogs) LogLineHelper.updateAttachedLogFieldToLogs(uk.gov.di.authentication.shared.helpers.LogLineHelper.updateAttachedLogFieldToLogs) Optional(java.util.Optional) LogManager(org.apache.logging.log4j.LogManager) List(java.util.List) ParseException(com.nimbusds.oauth2.sdk.ParseException) AuthenticationRequest(com.nimbusds.openid.connect.sdk.AuthenticationRequest)

Example 17 with APIGatewayProxyResponseEvent

use of com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent 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 18 with APIGatewayProxyResponseEvent

use of com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent 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 19 with APIGatewayProxyResponseEvent

use of com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent in project di-authentication-api by alphagov.

the class AuthCodeHandlerTest method shouldGenerateSuccessfulAuthResponseAndUpliftAsNecessary.

@ParameterizedTest
@MethodSource("upliftTestParameters")
void shouldGenerateSuccessfulAuthResponseAndUpliftAsNecessary(CredentialTrustLevel initialLevel, CredentialTrustLevel requestedLevel, CredentialTrustLevel finalLevel) throws ClientNotFoundException, URISyntaxException, JsonProcessingException {
    AuthorizationCode authorizationCode = new AuthorizationCode();
    AuthenticationRequest authRequest = generateValidSessionAndAuthRequest(requestedLevel);
    session.setCurrentCredentialStrength(initialLevel).setNewAccount(NEW);
    AuthenticationSuccessResponse authSuccessResponse = new AuthenticationSuccessResponse(authRequest.getRedirectionURI(), authorizationCode, null, null, authRequest.getState(), null, authRequest.getResponseMode());
    when(authorizationService.isClientRedirectUriValid(eq(CLIENT_ID), eq(REDIRECT_URI))).thenReturn(true);
    when(authorisationCodeService.generateAuthorisationCode(eq(CLIENT_SESSION_ID), eq(EMAIL))).thenReturn(authorizationCode);
    when(authorizationService.generateSuccessfulAuthResponse(any(AuthenticationRequest.class), any(AuthorizationCode.class))).thenReturn(authSuccessResponse);
    APIGatewayProxyResponseEvent response = generateApiRequest();
    assertThat(response, hasStatus(200));
    AuthCodeResponse authCodeResponse = new ObjectMapper().readValue(response.getBody(), AuthCodeResponse.class);
    assertThat(authCodeResponse.getLocation(), equalTo(authSuccessResponse.toURI().toString()));
    assertThat(session.getCurrentCredentialStrength(), equalTo(finalLevel));
    verify(sessionService).save(session.setAuthenticated(true));
    verify(auditService).submitAuditEvent(OidcAuditableEvent.AUTH_CODE_ISSUED, "aws-session-id", SESSION_ID, CLIENT_ID.getValue(), AuditService.UNKNOWN, EMAIL, "123.123.123.123", AuditService.UNKNOWN, PERSISTENT_SESSION_ID);
    verify(cloudwatchMetricsService).incrementCounter("SignIn", Map.of("Account", "NEW", "Environment", "unit-test", "Client", CLIENT_ID.getValue()));
}
Also used : AuthorizationCode(com.nimbusds.oauth2.sdk.AuthorizationCode) AuthCodeResponse(uk.gov.di.authentication.oidc.entity.AuthCodeResponse) AuthenticationRequest(com.nimbusds.openid.connect.sdk.AuthenticationRequest) APIGatewayProxyResponseEvent(com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent) AuthenticationSuccessResponse(com.nimbusds.openid.connect.sdk.AuthenticationSuccessResponse) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Example 20 with APIGatewayProxyResponseEvent

use of com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent in project di-authentication-api by alphagov.

the class IdentityHandlerTest method shouldReturn401WhenBearerTokenIsNotParseable.

@Test
void shouldReturn401WhenBearerTokenIsNotParseable() throws AccessTokenException {
    APIGatewayProxyRequestEvent event = new APIGatewayProxyRequestEvent();
    event.setHeaders(Map.of("Authorization", "this-is-not-a-valid-token"));
    AccessTokenException accessTokenException = new AccessTokenException("Unable to parse AccessToken", INVALID_TOKEN);
    when(accessTokenService.parse("this-is-not-a-valid-token", true)).thenThrow(accessTokenException);
    APIGatewayProxyResponseEvent result = handler.handleRequest(event, context);
    assertThat(result, hasStatus(401));
    assertEquals(INVALID_TOKEN_RESPONSE, result.getMultiValueHeaders());
}
Also used : APIGatewayProxyRequestEvent(com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent) AccessTokenException(uk.gov.di.authentication.shared.exceptions.AccessTokenException) APIGatewayProxyResponseEvent(com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent) Test(org.junit.jupiter.api.Test)

Aggregations

APIGatewayProxyResponseEvent (com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent)260 Test (org.junit.jupiter.api.Test)214 APIGatewayProxyRequestEvent (com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent)182 HashMap (java.util.HashMap)56 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)43 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)30 ErrorObject (com.nimbusds.oauth2.sdk.ErrorObject)22 URI (java.net.URI)21 NotifyRequest (uk.gov.di.authentication.shared.entity.NotifyRequest)17 UserProfile (uk.gov.di.authentication.shared.entity.UserProfile)17 Map (java.util.Map)16 ClientRegistry (uk.gov.di.authentication.shared.entity.ClientRegistry)14 ClientSession (uk.gov.di.authentication.shared.entity.ClientSession)14 Context (com.amazonaws.services.lambda.runtime.Context)13 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)13 AuthenticationRequest (com.nimbusds.openid.connect.sdk.AuthenticationRequest)13 NotifyRequest (uk.gov.di.accountmanagement.entity.NotifyRequest)13 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)12 Subject (com.nimbusds.oauth2.sdk.id.Subject)12 URIBuilder (org.apache.http.client.utils.URIBuilder)11