serverless-application-model icon indicating copy to clipboard operation
serverless-application-model copied to clipboard

Auto-created role for Lambda could scope down logs policy

Open benkehoe opened this issue 7 years ago • 5 comments

When specifying an AWS::Serverless::Function without a role, SAM creates a role and attaches the AWSLambdaBasicExecutionRole managed policy to it. This provides write permissions for CloudWatch Logs, in particular:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "logs:CreateLogGroup",
        "logs:CreateLogStream",
        "logs:PutLogEvents"
      ],
      "Resource": "*"
    }
  ]
}

However, since this is part of a CloudFormation template, SAM could instead attach a non-managed policy that is specifically scoped to the log group for the function:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "logs:CreateLogGroup",
        "logs:CreateLogStream",
        "logs:PutLogEvents"
      ],
      "Resource": {"Fn::Join": [
        "", [
          "arn:",
          {"Ref": "AWS::Partition"},
          ":logs",
          {"Ref": "AWS::Region"},
          ":",
          {"Ref": "AWS::AccountId"},
          ":log-group:/aws/lambda/",
          {"Ref": "SAMFunctionLogicalId"},
          ":*"
        ],
      ]}
    }
  ]
}

This is a least-privilege policy, unlike the managed policy. If this is desirable, I can create a PR.

benkehoe avatar Apr 19 '18 12:04 benkehoe

Good catch. This is more desirable but would break back compat. Can you use an explicit policy template instead?

sanathkr avatar Apr 19 '18 13:04 sanathkr

So named something like LambdaLogsPolicy? Does/can the policy template code autoinject the function name as a parameter?

benkehoe avatar Apr 19 '18 14:04 benkehoe

Could it be a special policy template? So the relevant part of the function resource properties would look like

Policies:
- SAMFunctionLogsPolicy: True

benkehoe avatar Apr 26 '18 13:04 benkehoe

Unfortunately we can't change this without breaking backwards compatibility.

brettstack avatar Jun 30 '18 04:06 brettstack

There is likely something we could do here. Not sure if this is fully a breaking change or we could add some kind of Property to change behavior.

Also pinging here to clear the maintainer/need-response

jfuss avatar Mar 01 '22 21:03 jfuss