Search in sources :

Example 21 with APIGatewayProxyRequestEvent

use of com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent in project aws-lambda-powertools-java by awslabs.

the class BasePersistenceStoreTest method saveInProgress_jmespath.

@Test
public void saveInProgress_jmespath() {
    APIGatewayProxyRequestEvent event = EventLoader.loadApiGatewayRestEvent("apigw_event.json");
    persistenceStore.configure(IdempotencyConfig.builder().withEventKeyJMESPath("powertools_json(body).id").build(), "myfunc");
    Instant now = Instant.now();
    persistenceStore.saveInProgress(JsonConfig.get().getObjectMapper().valueToTree(event), now);
    assertThat(dr.getStatus()).isEqualTo(DataRecord.Status.INPROGRESS);
    assertThat(dr.getExpiryTimestamp()).isEqualTo(now.plus(3600, ChronoUnit.SECONDS).getEpochSecond());
    assertThat(dr.getResponseData()).isNull();
    assertThat(dr.getIdempotencyKey()).isEqualTo("testFunction.myfunc#2fef178cc82be5ce3da6c5e0466a6182");
    assertThat(dr.getPayloadHash()).isEqualTo("");
    assertThat(status).isEqualTo(1);
}
Also used : APIGatewayProxyRequestEvent(com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent) Instant(java.time.Instant) Test(org.junit.jupiter.api.Test)

Example 22 with APIGatewayProxyRequestEvent

use of com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent in project aws-lambda-powertools-java by awslabs.

the class BasePersistenceStoreTest method saveSuccess_shouldUpdateRecord.

// </editor-fold>
// =================================================================
// =================================================================
// <editor-fold desc="saveSuccess">
@Test
public void saveSuccess_shouldUpdateRecord() throws JsonProcessingException {
    APIGatewayProxyRequestEvent event = EventLoader.loadApiGatewayRestEvent("apigw_event.json");
    LRUCache<String, DataRecord> cache = new LRUCache<>(2);
    persistenceStore.configure(IdempotencyConfig.builder().build(), null, cache);
    Product product = new Product(34543, "product", 42);
    Instant now = Instant.now();
    persistenceStore.saveSuccess(JsonConfig.get().getObjectMapper().valueToTree(event), product, now);
    assertThat(dr.getStatus()).isEqualTo(DataRecord.Status.COMPLETED);
    assertThat(dr.getExpiryTimestamp()).isEqualTo(now.plus(3600, ChronoUnit.SECONDS).getEpochSecond());
    assertThat(dr.getResponseData()).isEqualTo(JsonConfig.get().getObjectMapper().writeValueAsString(product));
    assertThat(dr.getIdempotencyKey()).isEqualTo("testFunction#47261bd5b456f400f8d191cfb3a7482f");
    assertThat(dr.getPayloadHash()).isEqualTo("");
    assertThat(status).isEqualTo(2);
    assertThat(cache).isEmpty();
}
Also used : LRUCache(software.amazon.lambda.powertools.idempotency.internal.cache.LRUCache) APIGatewayProxyRequestEvent(com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent) Instant(java.time.Instant) Product(software.amazon.lambda.powertools.idempotency.model.Product) Test(org.junit.jupiter.api.Test)

Example 23 with APIGatewayProxyRequestEvent

use of com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent in project aws-lambda-powertools-java by awslabs.

the class BasePersistenceStoreTest method saveInProgress_jmespath_NotFound_shouldNotThrowException.

@Test
public void saveInProgress_jmespath_NotFound_shouldNotThrowException() {
    APIGatewayProxyRequestEvent event = EventLoader.loadApiGatewayRestEvent("apigw_event.json");
    persistenceStore.configure(IdempotencyConfig.builder().withEventKeyJMESPath("unavailable").build(), "");
    Instant now = Instant.now();
    persistenceStore.saveInProgress(JsonConfig.get().getObjectMapper().valueToTree(event), now);
    assertThat(dr.getStatus()).isEqualTo(DataRecord.Status.INPROGRESS);
    assertThat(status).isEqualTo(1);
}
Also used : APIGatewayProxyRequestEvent(com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent) Instant(java.time.Instant) Test(org.junit.jupiter.api.Test)

Example 24 with APIGatewayProxyRequestEvent

use of com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent in project aws-lambda-powertools-java by awslabs.

the class ValidationAspectTest method validate_inputOK_schemaInClasspath_shouldValidate.

@Test
public void validate_inputOK_schemaInClasspath_shouldValidate() {
    ValidationInboundClasspathHandler handler = new ValidationInboundClasspathHandler();
    APIGatewayProxyRequestEvent event = new APIGatewayProxyRequestEvent();
    event.setBody("{" + "    \"id\": 1," + "    \"name\": \"Lampshade\"," + "    \"price\": 42" + "}");
    assertThat(handler.handleRequest(event, context)).isEqualTo("OK");
}
Also used : APIGatewayProxyRequestEvent(com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent) Test(org.junit.jupiter.api.Test)

Example 25 with APIGatewayProxyRequestEvent

use of com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent 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)

Aggregations

APIGatewayProxyRequestEvent (com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent)239 Test (org.junit.jupiter.api.Test)217 APIGatewayProxyResponseEvent (com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent)182 HashMap (java.util.HashMap)70 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)37 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)33 ErrorObject (com.nimbusds.oauth2.sdk.ErrorObject)29 NotifyRequest (uk.gov.di.authentication.shared.entity.NotifyRequest)17 URI (java.net.URI)15 Map (java.util.Map)15 UserProfile (uk.gov.di.authentication.shared.entity.UserProfile)14 Context (com.amazonaws.services.lambda.runtime.Context)13 NotifyRequest (uk.gov.di.accountmanagement.entity.NotifyRequest)13 Subject (com.nimbusds.oauth2.sdk.id.Subject)12 Instant (java.time.Instant)11 Matchers.containsString (org.hamcrest.Matchers.containsString)11 ClientID (com.nimbusds.oauth2.sdk.id.ClientID)10 AuthenticationRequest (com.nimbusds.openid.connect.sdk.AuthenticationRequest)10 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)8 JWSObject (com.nimbusds.jose.JWSObject)8