def test_api_gateway_proxy_v2_lambda_authorizer_event():
    event = APIGatewayProxyEventV2(load_event("apiGatewayProxyV2LambdaAuthorizerEvent.json"))

    request_context = event.request_context
    assert request_context is not None
    lambda_props = request_context.authorizer.get_lambda
    assert lambda_props is not None
    assert lambda_props["key"] == "value"
 def _to_proxy_event(self, event: Dict) -> BaseProxyEvent:
     """Convert the event dict to the corresponding data class"""
     if self._proxy_type == ProxyEventType.APIGatewayProxyEvent:
         logger.debug("Converting event to API Gateway REST API contract")
         return APIGatewayProxyEvent(event)
     if self._proxy_type == ProxyEventType.APIGatewayProxyEventV2:
         logger.debug("Converting event to API Gateway HTTP API contract")
         return APIGatewayProxyEventV2(event)
     logger.debug("Converting event to ALB contract")
     return ALBEvent(event)
Пример #3
0
def handler(event: Dict[str, Any],
            context: LambdaContext) -> Dict[str, Any]:  # noqa: WPS110

    event: APIGatewayProxyEventV2 = APIGatewayProxyEventV2(event)

    logger.info("Processing event: {}".format(json.dumps(event.body)))

    link = ""

    try:
        data = load_data(event)
    except ValueError as error:
        logger.error(error)

        return {
            "body": str(error),
            "isBase64Encoded": False,
            "headers": {
                "Access-Control-Allow-Origin": "*",
                "Access-Control-Allow-Credentials": True
            },
            "statusCode": 400,
        }

    # logger.info(pformat(data, indent=2))

    graph = populate_graph(data)

    config = convert_graph_to_modulestf_config(graph)

    prepare_render_dirs()

    render_from_modulestf_config(config,
                                 source=graph.source,
                                 regions=graph.regions)

    # Do not upload to S3 when working locally
    if os.environ.get("UPLOAD_TO_S3", False):
        shutil.make_archive("archive", "zip", FINAL_DIR)

        link = upload_file_to_s3(filename="archive.zip")

    metrics.add_metric(name="Request", unit=MetricUnit.Count, value=1)

    return {
        "body": "",
        "headers": {
            "Location": link,
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Credentials": True
        },
        "statusCode": 302,
    }
def test_api_gateway_proxy_v2_iam_event():
    event = APIGatewayProxyEventV2(load_event("apiGatewayProxyV2IamEvent.json"))

    iam = event.request_context.authorizer.iam
    assert iam is not None
    assert iam.access_key == "ARIA2ZJZYVUEREEIHAKY"
    assert iam.account_id == "1234567890"
    assert iam.caller_id == "AROA7ZJZYVRE7C3DUXHH6:CognitoIdentityCredentials"
    assert iam.cognito_amr == ["foo"]
    assert iam.cognito_identity_id == "us-east-1:3f291106-8703-466b-8f2b-3ecee1ca56ce"
    assert iam.cognito_identity_pool_id == "us-east-1:4f291106-8703-466b-8f2b-3ecee1ca56ce"
    assert iam.principal_org_id == "AwsOrgId"
    assert iam.user_arn == "arn:aws:iam::1234567890:user/Admin"
    assert iam.user_id == "AROA2ZJZYVRE7Y3TUXHH6"
Пример #5
0
def local_event(c, method="GET", path="/items/"):
    """
    Send an HTTP Gateway event to the lambda runtime emulator
    """
    from aws_lambda_powertools.utilities.data_classes import APIGatewayProxyEventV2

    http_event_dict = json.loads(pathlib.Path("event.json").read_text())

    http_event_dict["requestContext"]["http"]["path"] = path
    http_event_dict["requestContext"]["http"]["method"] = method

    http_event = APIGatewayProxyEventV2(http_event_dict)

    local_url = "http://localhost:9000/2015-03-31/functions/function/invocations"

    response = httpx.post(local_url, json=http_event._data)
    response.raise_for_status()

    pprint.pprint(response.json())
Пример #6
0
def test_api_gateway_proxy_v2_event():
    event = APIGatewayProxyEventV2(load_event("apiGatewayProxyV2Event.json"))

    assert event.version == event["version"]
    assert event.route_key == event["routeKey"]
    assert event.raw_path == event["rawPath"]
    assert event.raw_query_string == event["rawQueryString"]
    assert event.cookies == event["cookies"]
    assert event.cookies[0] == "cookie1"
    assert event.headers == event["headers"]
    assert event.query_string_parameters == event["queryStringParameters"]
    assert event.query_string_parameters["parameter2"] == "value"

    request_context = event.request_context
    assert request_context.account_id == event["requestContext"]["accountId"]
    assert request_context.api_id == event["requestContext"]["apiId"]
    assert request_context.authorizer.jwt_claim == event["requestContext"][
        "authorizer"]["jwt"]["claims"]
    assert request_context.authorizer.jwt_scopes == event["requestContext"][
        "authorizer"]["jwt"]["scopes"]
    assert request_context.domain_name == event["requestContext"]["domainName"]
    assert request_context.domain_prefix == event["requestContext"][
        "domainPrefix"]

    http = request_context.http
    assert http.method == "POST"
    assert http.path == "/my/path"
    assert http.protocol == "HTTP/1.1"
    assert http.source_ip == "IP"
    assert http.user_agent == "agent"

    assert request_context.request_id == event["requestContext"]["requestId"]
    assert request_context.route_key == event["requestContext"]["routeKey"]
    assert request_context.stage == event["requestContext"]["stage"]
    assert request_context.time == event["requestContext"]["time"]
    assert request_context.time_epoch == event["requestContext"]["timeEpoch"]

    assert event.body == event["body"]
    assert event.path_parameters == event["pathParameters"]
    assert event.is_base64_encoded == event["isBase64Encoded"]
    assert event.stage_variables == event["stageVariables"]