Reputation: 1781
I've been having a go at using Cloudformation/SAM to put a stack together. The lambda function below is a handler for contact creation in DynamoDB so I thought that it would be prudent to give it the least amount of privilege necessary.
I noticed that the DynamoDBWritePolicy permits more than just PutItem so I was wondering what the best way to go about locking things down even further. I appreciate that this might be overkill but it's for learning purposes.
Here's my Lambda definition:
CreateContact:
Type: AWS::Serverless::Function
Properties:
Handler: index.handler
Runtime: nodejs12.x
Policies:
- AWSLambdaBasicExecutionRole
- DynamoDBWritePolicy:
TableName: contacts
CodeUri: ./src/handlers/create-contact
Events:
ApiEvent:
Type: Api
Properties:
Path: /
Method: post
RestApiId:
Ref: APIGateway
So my question is: Should I create a new policy for PutItem only or rely on something like a permission boundary or am I overlooking any other options?
Upvotes: 0
Views: 854
Reputation: 2365
Yes, predefined policy templates provided by SAM might include permissions more than you required for your lambda function. If you need more granular level permissions (which is the best practice), you can always set them in the SAM template in lambda function's Policies object as follows:
CreateContact:
Type: AWS::Serverless::Function
Properties:
Handler: index.handler
Runtime: nodejs12.x
Policies:
- Version: 2012-10-17
Statement:
- Effect: Allow
Action: dynamodb:PutItem
Resource: !Sub "arn:aws:dynamodb:${AWS::Region}:${AWS::AccountId}:table/contacts"
CodeUri: ./src/handlers/create-contact
Events:
ApiEvent:
Type: Api
Properties:
Path: /
Method: post
RestApiId:
Ref: APIGateway
Upvotes: 3
Reputation: 2658
There is nothing wrong with your approach. You can create a new policy to 'Allow' some specific actions on specific resources.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "SpecificTable",
"Effect": "Allow",
"Action": [
"dynamodb:PutItem"
],
"Resource": "arn:aws:dynamodb:*:*:table/MyTable"
}
]
}
Upvotes: 3