【问题标题】:Specify resources allowed to call a function in its AWS SAM Function template指定允许在其 AWS SAM 函数模板中调用函数的资源
【发布时间】:2019-10-10 10:48:56
【问题描述】:

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"

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

政策文件不应指定主体。 (服务:AmazonIdentityManagement;状态代码:400;错误代码:MalformedPolicyDocument;请求 ID:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)

当我删除该 具有主体的策略时,通过用户池触发器访问该功能被拒绝。

【问题讨论】:

    标签: aws-lambda amazon-iam aws-sam


    【解决方案1】:

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

    因此,以下逻辑成功地创建了具有权限的函数(也称为函数策略):

    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/*"
    

    【讨论】:

      猜你喜欢
      • 2020-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-06
      • 2013-10-10
      • 1970-01-01
      • 1970-01-01
      • 2011-11-04
      相关资源
      最近更新 更多