def test(self):
        lbd_permission = awslambda.Permission("LbdPermission",
                                              Action="",
                                              FunctionName="",
                                              Principal="")

        lbd_func = awslambda.Function(
            "LbdFunc",
            Code=awslambda.Code(
                S3Bucket="my-bucket",
                S3Key="0.0.1.zip",
            ),
            Handler="my_func.handler",
            Role="arn:aws:iam::111122223333:role/todo",
            Runtime="python3.6")

        api_method = apigateway.Method(
            "ApiMethod",
            Metadata={
                TROPOSPHERE_METADATA_FIELD_NAME: {
                    ResourceLevelField.ApiResource.FULL_PATH: "users"
                }
            },
            AuthorizationType="none",
            HttpMethod="POST",
            ResourceId="",
            RestApiId="",
        )

        associate(lbd_permission, api_method, lbd_func)
        assert lbd_permission.Action == "lambda:InvokeFunction"
        assert isinstance(lbd_permission.FunctionName, GetAtt)
        assert lbd_permission.Principal == "apigateway.amazonaws.com"
        assert isinstance(lbd_permission.SourceArn, Sub)
        assert len(lbd_permission.DependsOn) == 2
Exemplo n.º 2
0
 def test(self):
     api_method = apigateway.Method(
         "ApiMethod",
         AuthorizationType="none",
         HttpMethod="POST",
         ResourceId="",
         RestApiId="",
         Integration=apigateway.Integration(Type=""),
     )
     api_authorizer = apigateway.Authorizer(
         "ApiAuthorizer",
         AuthorizerUri="",
         IdentitySource="",
         Name="",
         Type="",
     )
     associate(api_method, api_authorizer)
     assert isinstance(api_method.AuthorizerId, Ref)
Exemplo n.º 3
0
 def test(self):
     api_method = apigateway.Method(
         "ApiMethod",
         AuthorizationType="none",
         HttpMethod="POST",
         ResourceId="",
         RestApiId="",
         Integration=apigateway.Integration(Type=""),
     )
     lbd_func = awslambda.Function(
         "LbdFunc",
         Code=awslambda.Code(
             S3Bucket="my-bucket",
             S3Key="0.0.1.zip",
         ),
         Handler="my_func.handler",
         Role="arn:aws:iam::111122223333:role/todo",
         Runtime="python3.6")
     associate(api_method, lbd_func)
     assert api_method.Integration.Type == "AWS"
     assert api_method.Integration.IntegrationHttpMethod == "POST"
     assert isinstance(api_method.Integration.Uri, Sub)
Exemplo n.º 4
0
    def test(self):
        api_method = apigateway.Method(
            "ApiMethod",
            AuthorizationType="none",
            HttpMethod="POST",
            ResourceId="",
            RestApiId="",
        )
        api_resource = apigateway.Resource(
            "ApiResource",
            ParentId="",
            PathPart="users",
            RestApiId="",
        )
        associate(api_method, api_resource)
        assert len(
            api_method.Metadata[mtdt.TROPOSPHERE_METADATA_FIELD_NAME]) == 0

        associate(api_resource, rest_api, has_parent_resource=False)
        associate(api_method, api_resource)
        assert api_method.Metadata[mtdt.TROPOSPHERE_METADATA_FIELD_NAME][
            mtdt.ResourceLevelField.ApiResource.FULL_PATH] == "users"
    def apigw_method_options_for_cors_aws_object(self) -> apigateway.Method:
        """

        **中文文档**

        为了开启 Cors, 对于 Api Resource 是需要一个 Options Method 专门用于获取
        服务器的设置. 这事因为浏览器在检查到跨站请求时, 会使用 Options 方法获取服务器的
        跨站访问设置, 如果不满则, 浏览爱则会返回错误信息.
        """
        # For cors, options method doesn't need a lambda function
        depends_on = [
            self.apigw_resource_aws_object,
        ]

        # Integration Request
        request_template = {"application/json": "{\"statusCode\": 200}"}

        # Integration Response
        access_control_allow_headers = "Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token"

        if self.apigw_method_authorizer is not NOTHING:
            if self.apigw_authorizer_token_type_header_field is not NOTHING:
                access_control_allow_headers = access_control_allow_headers \
                                               + ",{}".format(self.apigw_authorizer_token_type_header_field)

        response_parameters = {
            "method.response.header.Access-Control-Allow-Origin":
            "'*'",
            "method.response.header.Access-Control-Allow-Methods":
            "'OPTIONS,GET,POST'",
            "method.response.header.Access-Control-Allow-Headers":
            "'{}'".format(access_control_allow_headers),
        }
        response_templates = {"application/json": ""}
        integration = apigateway.Integration(
            Type="MOCK",
            RequestTemplates=request_template,
            IntegrationResponses=[
                apigateway.IntegrationResponse(
                    StatusCode="200",
                    ContentHandling="CONVERT_TO_TEXT",
                    ResponseParameters=response_parameters,
                    ResponseTemplates=response_templates,
                )
            ],
            PassthroughBehavior="WHEN_NO_MATCH",
        )
        if self.apigw_method_int_passthrough_behavior is not NOTHING:
            integration.PassthroughBehavior = self.apigw_method_int_passthrough_behavior
        if self.apigw_method_int_timeout_in_milli is not NOTHING:
            integration.TimeoutInMillis = self.apigw_method_int_timeout_in_milli

        # Method Response
        method_responses = [
            apigateway.MethodResponse(
                StatusCode="200",
                ResponseModels={"application/json": "Empty"},
                ResponseParameters={
                    "method.response.header.Access-Control-Allow-Origin":
                    False,
                    "method.response.header.Access-Control-Allow-Methods":
                    False,
                    "method.response.header.Access-Control-Allow-Headers":
                    False,
                })
        ]

        apigw_method = apigateway.Method(
            title="ApigwMethod{}Options".format(
                camelcase(self.rel_module_name.replace(".", "-"))),
            RestApiId=Ref(self.apigw_restapi),
            ResourceId=Ref(self.apigw_resource_aws_object),
            AuthorizationType="NONE",
            HttpMethod="OPTIONS",
            MethodResponses=method_responses,
            Integration=integration,
        )

        apigw_method.DependsOn = depends_on

        return apigw_method
    def apigw_method_aws_object(self) -> apigateway.Method:
        if self._apigw_method_aws_object_cache is NOTHING:
            depends_on = [
                self.apigw_resource_aws_object,
                self.lbd_func_aws_object,
            ]

            # Integration Request
            request_template = {"application/json": "$input.json('$')"}

            # Integration Response
            if self.apigw_method_int_type == self.ApiMethodIntType.html:
                integration_response_200 = apigateway.IntegrationResponse(
                    StatusCode="200",
                    ResponseParameters={
                        "method.response.header.Access-Control-Allow-Origin":
                        "'*'",
                        "method.response.header.Content-Type": "'text/html'"
                    },
                    ResponseTemplates={"text/html": "$input.path('$')"},
                )
                method_response_200 = apigateway.MethodResponse(
                    StatusCode="200",
                    ResponseParameters={
                        "method.response.header.Access-Control-Allow-Origin":
                        False,
                        "method.response.header.Content-Type": False,
                    },
                    ResponseModels={"application/json": "Empty"},
                )
            elif self.apigw_method_int_type == self.ApiMethodIntType.rpc:
                integration_response_200 = apigateway.IntegrationResponse(
                    StatusCode="200",
                    ContentHandling="CONVERT_TO_TEXT",
                    ResponseParameters={},
                    ResponseTemplates={"application/json": ""})
                method_response_200 = apigateway.MethodResponse(
                    StatusCode="200",
                    ResponseParameters={},
                    ResponseModels={"application/json": "Empty"},
                )
            elif self.apigw_method_int_type == self.ApiMethodIntType.rest:
                integration_response_200 = apigateway.IntegrationResponse(
                    StatusCode="200",
                    ContentHandling="CONVERT_TO_TEXT",
                    ResponseParameters={},
                    ResponseTemplates={"application/json": ""})
                method_response_200 = apigateway.MethodResponse(
                    StatusCode="200",
                    ResponseParameters={},
                    ResponseModels={"application/json": "Empty"},
                )
            else:
                raise TypeError

            integration_responses = [
                integration_response_200,
            ]

            integration = apigateway.Integration(
                Type="AWS",
                IntegrationHttpMethod="POST",
                Uri=Sub(
                    "arn:aws:apigateway:${Region}:lambda:path/2015-03-31/functions/${LambdaArn}/invocations",
                    {
                        "Region": {
                            "Ref": "AWS::Region"
                        },
                        "LambdaArn": GetAtt(self.lbd_func_aws_object, "Arn"),
                    }),
                RequestTemplates=request_template,
                IntegrationResponses=integration_responses,
            )

            if self.apigw_method_int_passthrough_behavior is not NOTHING:
                integration.PassthroughBehavior = self.apigw_method_int_passthrough_behavior
            if self.apigw_method_int_timeout_in_milli is not NOTHING:
                integration.TimeoutInMillis = self.apigw_method_int_timeout_in_milli

            # Method Response
            method_responses = [
                method_response_200,
            ]

            if self.apigw_method_enable_cors_yes is True:
                for integration_response in integration.IntegrationResponses:
                    integration_response.ResponseParameters[
                        "method.response.header.Access-Control-Allow-Origin"] = "'*'"

                for method_response in method_responses:
                    method_response.ResponseParameters[
                        "method.response.header.Access-Control-Allow-Origin"] = False

            self.check_apigw_method_authorization_type()
            self.check_apigw_method_int_type()

            apigw_method = apigateway.Method(
                title=self.apigw_method_logic_id,
                RestApiId=Ref(self.apigw_restapi),
                ResourceId=Ref(self.apigw_resource_aws_object),
                AuthorizationType=self.apigw_method_authorization_type,
                HttpMethod=self.apigw_method_http_method,
                MethodResponses=method_responses,
                Integration=integration,
            )

            if self.apigw_method_use_authorizer_yes:
                apigw_method.AuthorizerId = Ref(self.apigw_method_authorizer)
                depends_on.append(self.apigw_method_authorizer)

            apigw_method.DependsOn = depends_on

            self._apigw_method_aws_object_cache = apigw_method

        return self._apigw_method_aws_object_cache