指定允许在其 AWS SAM 函数模板中调用函数的资源

Specify resources allowed to call a function in its AWS SAM Function template

TL; DR:我应该如何编辑下面的模板,以便它可以被用户池触发器触发?

我尝试为定义该函数可以调用和被调用的服务的 Lambda 函数创建一个 CloudFormation 模板。它应该是带有 Cognito 用户池触发器的 运行。

为此,我在 AWS::Serverless::Function 类型的模板中简要定义了一个资源,如下所示。注意 Policies 部分:

Resources:
  MyFunctionResource:
    Type: AWS::Serverless::Function
    Properties:
      FunctionName: MyFunctionName
      CodeUri: ./
      Handler: "lambda_function.lambda_handler"
      MemorySize: 128
      Runtime: python3.7
      Timeout: 3
      Policies:
        - Version: "2012-10-17"
          Statement:
            - Effect: Allow
              Action:
                - "cognito-idp:*"
                - "logs:*"
                ...
              Resource: "*"
        - Version: "2012-10-17"
          Statement:
            - Effect: Allow
              Action: "lambda:InvokeFunction"
              Principal:
                Service: cognito-idp.amazonaws.com
              Resource: !Sub "arn:aws:lambda:${AWS::Region}:${AWS::AccountId}:function:MyFunctionName"

我插入的第二个限制资源的策略可以在堆栈创建期间调用我的函数失败:

Policy document should not specify a principal. (Service: AmazonIdentityManagement; Status Code: 400; Error Code: MalformedPolicyDocument; Request ID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)

当我删除带有主体的策略时,通过用户池触发器访问函数被拒绝。

我发现应该将权限创建为类型为 AWS::Lambda::Permission 的单独资源,它可以采用函数名称或 arn 它将附加到。

因此,以下逻辑成功创建了具有权限(a.k.a.Function Policy)的函数:

Resources:
  MyFunctionResource:
    Type: AWS::Serverless::Function
    Properties:
      FunctionName: MyFunctionName
      CodeUri: ./
      Handler: "lambda_function.lambda_handler"
      MemorySize: 128
      Runtime: python3.7
      Timeout: 3
      Policies:
        - Version: "2012-10-17"
          Statement:
            - Effect: Allow
              Action:
                - "cognito-idp:*"
                - "logs:*"
                ...
              Resource: "*"
## Remove this section
#       - Version: "2012-10-17"
#         Statement:
#           - Effect: Allow
#             Action: "lambda:InvokeFunction"
#             Principal:
#               Service: cognito-idp.amazonaws.com
#             Resource: !Sub "arn:aws:lambda:${AWS::Region}:${AWS::AccountId}:function:MyFunctionName"

## Add this instead
  MyFunctionPermissions:
    Type: AWS::Lambda::Permission
    Properties:
      Action: "lambda:InvokeFunction"
      FunctionName: !GetAtt MyFunctionResource.Arn
      Principal: "cognito-idp.amazonaws.com"
      SourceArn: !Sub "arn:aws:cognito-idp:${AWS::Region}:${AWS::AccountId}:userpool/*"