Esempio n. 1
0
    def test_to_dict(self):
        request_context_mock = Mock()
        request_context_mock.to_dict.return_value = {"request_context": "the request context"}

        event = ApiGatewayLambdaEvent('request_method',
                                      'request_data',
                                      'resource',
                                      request_context_mock,
                                      {"query": "some query"},
                                      {"query": ["first query", "some query"]},
                                      {"header_key": "value"},
                                      {"header_key": ["value"]},
                                      {"param": "some param"},
                                      {"stagevars": "some vars"},
                                      'request_path',
                                      False
                                      )

        expected = {"httpMethod": "request_method",
                    "body": "request_data",
                    "resource": "resource",
                    "requestContext": {"request_context": "the request context"},
                    "queryStringParameters": {"query": "some query"},
                    "multiValueQueryStringParameters": {"query": ["first query", "some query"]},
                    "headers": {"header_key": "value"},
                    "multiValueHeaders": {"header_key": ["value"]},
                    "pathParameters": {"param": "some param"},
                    "stageVariables": {"stagevars": "some vars"},
                    "path": "request_path",
                    "isBase64Encoded": False
                    }

        self.assertEquals(event.to_dict(), expected)
Esempio n. 2
0
    def test_to_dict(self):
        request_context_mock = Mock()
        request_context_mock.to_dict.return_value = {"request_context": "the request context"}

        event = ApiGatewayLambdaEvent('request_method',
                                      'request_data',
                                      'resource',
                                      request_context_mock,
                                      {"query": "some query"},
                                      {"header_key": "value"},
                                      {"param": "some param"},
                                      {"stagevars": "some vars"},
                                      'request_path',
                                      False
                                      )

        expected = {"httpMethod": "request_method",
                    "body": "request_data",
                    "resource": "resource",
                    "requestContext": {"request_context": "the request context"},
                    "queryStringParameters": {"query": "some query"},
                    "headers": {"header_key": "value"},
                    "pathParameters": {"param": "some param"},
                    "stageVariables": {"stagevars": "some vars"},
                    "path": "request_path",
                    "isBase64Encoded": False
                    }

        self.assertEquals(event.to_dict(), expected)
Esempio n. 3
0
def generate_api_event(method, body, resource, path):
    """
    Generates an Api Event

    :param str method: HTTP Method of the request
    :param str body: Body of the request
    :param str resource: Api Gateway resource path
    :param str path: Request path
    :return dict: Dictionary representing the Api Event
    """
    headers = {
        "Via": "1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)",
        "Accept-Language": "en-US,en;q=0.8",
        "CloudFront-Is-Desktop-Viewer": "true",
        "CloudFront-Is-SmartTV-Viewer": "false",
        "CloudFront-Is-Mobile-Viewer": "false",
        "X-Forwarded-For": "127.0.0.1, 127.0.0.2",
        "CloudFront-Viewer-Country": "US",
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
        "Upgrade-Insecure-Requests": "1",
        "X-Forwarded-Port": "443",
        "Host": "1234567890.execute-api.us-east-1.amazonaws.com",
        "X-Forwarded-Proto": "https",
        "X-Amz-Cf-Id": "aaaaaaaaaae3VYQb9jd-nvCd-de396Uhbp027Y2JvkCPNLmGJHqlaA==",
        "CloudFront-Is-Tablet-Viewer": "false",
        "Cache-Control": "max-age=0",
        "User-Agent": "Custom User Agent String",
        "CloudFront-Forwarded-Proto": "https",
        "Accept-Encoding": "gzip, deflate, sdch"
    }

    query_params = {
        "foo": "bar"
    }

    path_params = {
        "proxy": path
    }

    identity = ContextIdentity(source_ip='127.0.0.1')

    context = RequestContext(resource_path=resource,
                             http_method=method,
                             stage="prod",
                             identity=identity,
                             path=resource)

    event = ApiGatewayLambdaEvent(http_method=method,
                                  body=body,
                                  resource=resource,
                                  request_context=context,
                                  query_string_params=query_params,
                                  headers=headers,
                                  path_parameters=path_params,
                                  path=path)

    return event.to_dict()
Esempio n. 4
0
    def _construct_event(flask_request, port, binary_types):
        """
        Helper method that constructs the Event to be passed to Lambda

        :param request flask_request: Flask Request
        :return: String representing the event
        """

        identity = ContextIdentity(source_ip=flask_request.remote_addr)

        endpoint = PathConverter.convert_path_to_api_gateway(flask_request.endpoint)
        method = flask_request.method

        request_data = flask_request.get_data()

        request_mimetype = flask_request.mimetype

        is_base_64 = LocalApigwService._should_base64_encode(binary_types, request_mimetype)

        if is_base_64:
            LOG.debug("Incoming Request seems to be binary. Base64 encoding the request data before sending to Lambda.")
            request_data = base64.b64encode(request_data)

        if request_data:
            # Flask does not parse/decode the request data. We should do it ourselves
            request_data = request_data.decode('utf-8')

        context = RequestContext(resource_path=endpoint,
                                 http_method=method,
                                 stage="prod",
                                 identity=identity,
                                 path=endpoint)

        event_headers = dict(flask_request.headers)
        event_headers["X-Forwarded-Proto"] = flask_request.scheme
        event_headers["X-Forwarded-Port"] = str(port)

        # APIGW does not support duplicate query parameters. Flask gives query params as a list so
        # we need to convert only grab the first item unless many were given, were we grab the last to be consistent
        # with APIGW
        query_string_dict = LocalApigwService._query_string_params(flask_request)

        event = ApiGatewayLambdaEvent(http_method=method,
                                      body=request_data,
                                      resource=endpoint,
                                      request_context=context,
                                      query_string_params=query_string_dict,
                                      headers=event_headers,
                                      path_parameters=flask_request.view_args,
                                      path=flask_request.path,
                                      is_base_64_encoded=is_base_64)

        event_str = json.dumps(event.to_dict())
        LOG.debug("Constructed String representation of Event to invoke Lambda. Event: %s", event_str)
        return event_str
    def _construct_event(flask_request, port, binary_types, stage_name=None, stage_variables=None):
        """
        Helper method that constructs the Event to be passed to Lambda

        :param request flask_request: Flask Request
        :return: String representing the event
        """
        # pylint: disable-msg=too-many-locals

        identity = ContextIdentity(source_ip=flask_request.remote_addr)

        endpoint = PathConverter.convert_path_to_api_gateway(flask_request.endpoint)
        method = flask_request.method

        request_data = flask_request.get_data()

        request_mimetype = flask_request.mimetype

        is_base_64 = LocalApigwService._should_base64_encode(binary_types, request_mimetype)

        if is_base_64:
            LOG.debug("Incoming Request seems to be binary. Base64 encoding the request data before sending to Lambda.")
            request_data = base64.b64encode(request_data)

        if request_data:
            # Flask does not parse/decode the request data. We should do it ourselves
            request_data = request_data.decode("utf-8")

        context = RequestContext(
            resource_path=endpoint, http_method=method, stage=stage_name, identity=identity, path=endpoint
        )

        headers_dict, multi_value_headers_dict = LocalApigwService._event_headers(flask_request, port)

        query_string_dict, multi_value_query_string_dict = LocalApigwService._query_string_params(flask_request)

        event = ApiGatewayLambdaEvent(
            http_method=method,
            body=request_data,
            resource=endpoint,
            request_context=context,
            query_string_params=query_string_dict,
            multi_value_query_string_params=multi_value_query_string_dict,
            headers=headers_dict,
            multi_value_headers=multi_value_headers_dict,
            path_parameters=flask_request.view_args,
            path=flask_request.path,
            is_base_64_encoded=is_base_64,
            stage_variables=stage_variables,
        )

        event_str = json.dumps(event.to_dict())
        LOG.debug("Constructed String representation of Event to invoke Lambda. Event: %s", event_str)
        return event_str
Esempio n. 6
0
    def test_to_dict_with_defaults(self):
        event = ApiGatewayLambdaEvent()

        expected = {"httpMethod": None,
                    "body": None,
                    "resource": None,
                    "requestContext": {},
                    "queryStringParameters": None,
                    "headers": None,
                    "pathParameters": None,
                    "stageVariables": None,
                    "path": None,
                    "isBase64Encoded": False
                    }

        self.assertEquals(event.to_dict(), expected)
Esempio n. 7
0
    def _construct_v_1_0_event(flask_request,
                               port,
                               binary_types,
                               stage_name=None,
                               stage_variables=None):
        """
        Helper method that constructs the Event to be passed to Lambda

        :param request flask_request: Flask Request
        :param port: the port number
        :param binary_types: list of binary types
        :param stage_name: Optional, the stage name string
        :param stage_variables: Optional, API Gateway Stage Variables
        :return: String representing the event
        """
        # pylint: disable-msg=too-many-locals

        identity = ContextIdentity(source_ip=flask_request.remote_addr)

        endpoint = PathConverter.convert_path_to_api_gateway(
            flask_request.endpoint)
        method = flask_request.method
        protocol = flask_request.environ.get("SERVER_PROTOCOL", "HTTP/1.1")
        host = flask_request.host

        request_data = flask_request.get_data()

        request_mimetype = flask_request.mimetype

        is_base_64 = LocalApigwService._should_base64_encode(
            binary_types, request_mimetype)

        if is_base_64:
            LOG.debug(
                "Incoming Request seems to be binary. Base64 encoding the request data before sending to Lambda."
            )
            request_data = base64.b64encode(request_data)

        if request_data:
            # Flask does not parse/decode the request data. We should do it ourselves
            # Note(xinhol): here we change request_data's type from bytes to str and confused mypy
            # We might want to consider to use a new variable here.
            request_data = request_data.decode("utf-8")

        query_string_dict, multi_value_query_string_dict = LocalApigwService._query_string_params(
            flask_request)

        context = RequestContext(
            resource_path=endpoint,
            http_method=method,
            stage=stage_name,
            identity=identity,
            path=endpoint,
            protocol=protocol,
            domain_name=host,
        )

        headers_dict, multi_value_headers_dict = LocalApigwService._event_headers(
            flask_request, port)

        event = ApiGatewayLambdaEvent(
            http_method=method,
            body=request_data,
            resource=endpoint,
            request_context=context,
            query_string_params=query_string_dict,
            multi_value_query_string_params=multi_value_query_string_dict,
            headers=headers_dict,
            multi_value_headers=multi_value_headers_dict,
            path_parameters=flask_request.view_args,
            path=flask_request.path,
            is_base_64_encoded=is_base_64,
            stage_variables=stage_variables,
        )

        event_str = json.dumps(event.to_dict(), sort_keys=True)
        LOG.debug(
            "Constructed String representation of Event to invoke Lambda. Event: %s",
            event_str)
        return event_str