SAM give access to Cognito - aws-lambda

I want to be able to call cognito functions through boto3 from my Lambda function in Python environment. What's the best way to give this type of access? I've done the following yaml but not sure if that's the best practice or I'm making the template longer.
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
sam-app
Sample SAM Template for sam-app
Resources:
HelloWorldFunction:
Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
Properties:
CodeUri: hello_world/
Handler: app.lambda_handler
Runtime: python3.7
Policies:
- AWSLambdaExecute # Managed Policy
- Version: '2012-10-17' # Policy Document
Statement:
- Effect: Allow
Action:
- cognito-idp:ListUsers
Resource: 'arn:aws:cognito-idp:us-east-2:****:*****'
Events:
HelloWorld:
Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
Properties:
Path: /hello
Method: get
Outputs:
# ServerlessRestApi is an implicit API created out of Events key under Serverless::Function
# Find out more about other implicit resources you can reference within SAM
# https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api
HelloWorldApi:
Description: "API Gateway endpoint URL for Prod stage for Hello World function"
Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/"
HelloWorldFunction:
Description: "Hello World Lambda Function ARN"
Value: !GetAtt HelloWorldFunction.Arn
HelloWorldFunctionIamRole:
Description: "Implicit IAM Role created for Hello World function"
Value: !GetAtt HelloWorldFunctionRole.Arn
I'm talking about the "Policies", is my template up to the standards? or is there a shortcut I can take?

Related

Invalid template resource property 'Policies'

Can you please help with what is wrong here?
when I am trying to run this following cloud formation stack getting error. I am trying to create the lambda function with the sns role using cloud formation Invalid template resource property 'Policies'
AWSTemplateFormatVersion: '2010-09-09'
Description: VPC function.
Resources:
Function:
Type: AWS::Lambda::Function
Properties:
Handler: index.handler
Code:
S3Bucket: teste-artifact-bucket
S3Key: function.zip
Runtime: python3.6
Timeout: 5
TracingConfig:
Mode: Active
LambdaExecutionRole:
Description: Creating service role in IAM for AWS Lambda
Type: AWS::IAM::Role
Properties:
RoleName:
Fn::Sub: ${ProjectId}-execution
AssumeRolePolicyDocument:
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action: sts:AssumeRole
Path: /
Policies:
PolicyName: Lamda addtional access
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- sns:Subscribe
- sns:Publish
- sns:CreateTopic
- logs:PutLogEvents
- logs:CreateLogStream
- logs:CreateLogGroup
Resource: '*'
ManagedPolicyArns:
- !Sub 'arn:${AWS::Partition}:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole'
LambdaFunctionLogGroup:
Type: AWS::Logs::LogGroup
Properties:
LogGroupName: !Sub '/aws/lambda/${ProjectId}'
RetentionInDays: 60
Policies code block isn't indented far enough

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

TL; DR: How should I edit the template below so that it can be triggered by a user pool trigger?
I try to crate a CloudFormation template for a Lambda function defining both the services the function can call and be called from. It should be run with a Cognito User Pool trigger.
To do that, I've defined a resource in template of type AWS::Serverless::Function briefly as follows. Watch out the Policies section:
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"
The second policy I have inserted for restricting the resources can call my function fails during the stack creation:
Policy document should not specify a principal. (Service: AmazonIdentityManagement; Status Code: 400; Error Code: MalformedPolicyDocument; Request ID: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)
When I remove that policy with principal, the access to the function through the user pool trigger is denied.
I figured out that the permissions should be created as a separate resource with type AWS::Lambda::Permission which can take the function name or arn it will be attached to.
Thus, the following logic creates the function with permissions (a.k.a. Function Policy) successfully:
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/*"

Can i add a codecommit trigger to my lambda function via CloudFormation

Im writing a lambda function that i want to be triggered by somebody updating the master branch of a repo. The repo already exists on the account.
Is there a way in cloudformation that i can add the trigger to the lambda function? I guess at a snip i could cretae some cloudwatch rule to trigger the lambda, but would rather keep it all inside the lambda.
Thanks
R
If you are using AWS serverless transform then you can self contain it within the lambda. Although the transform generates the cloudwatch rule and the lambda permission, so it's basically the same you mentioned.
nevertheless here's an example to do what you want
AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31
Description: Pipeline which triggers lambda for codecommit changes
Parameters:
BranchName:
Default: master
Description: The GIT branch
Type: String
RepositoryName:
Description: The GIT repository
Type: String
StackOwner:
Description: The stack owner
Type: String
Resources:
BasicLambdaRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
Path: "/"
Policies:
- PolicyName: root
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action: logs:*
Resource: arn:aws:logs:*:*:*
- Effect: Allow
Action: '*'
Resource: '*'
PipelineTriggerFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: src/trigger
Handler: codetrigger.handler
MemorySize: 256
Role: !GetAtt BasicLambdaRole.Arn
Runtime: python3.6
Timeout: 900
Environment:
Variables:
TestVariable: "TestValue"
Events:
CodeCommitPushEvent:
Type: CloudWatchEvent
Properties:
Pattern:
source:
- aws.codecommit
resources:
- !Sub 'arn:aws:codecommit:${AWS::Region}:${AWS::AccountId}:${RepositoryName}'
detail:
event:
- referenceCreated
- referenceUpdated
repositoryName:
- !Ref RepositoryName
referenceName:
- !Ref BranchName
Tags:
'owner': !Ref StackOwner
'task': !Ref RepositoryName
Obviously, specify the lambda role better and not give all permissions as provided in the example.

AWS SAM cloudformation: API Gateway can't invoke lambda (AWS::Serverless::Function )

I created a template.yaml file to declare a simple lambda function that is invoked by api gateway. When I try to invoke the function from the api gateway url the request fails with {"message": "Internal server error"} and in cloudwatch api gateway logs I see the error message Invalid permissions on Lambda function.
This is my template.yaml:
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Parameters:
AliasName:
Type: String
Default: dev
Resources:
DynamoDBTenantTable:
Type: AWS::DynamoDB::Table
Properties:
AttributeDefinitions:
- AttributeName: clientApiKey
AttributeType: S
KeySchema:
- AttributeName: clientApiKey
KeyType: HASH
ProvisionedThroughput:
ReadCapacityUnits: 5
WriteCapacityUnits: 5
TableName: !Sub "authtable-${AliasName}"
AmeAuthenticatorLambda:
Type: AWS::Serverless::Function
Properties:
Handler: authenticator.handler
Policies: AmazonDynamoDBFullAccess
Runtime: nodejs8.10
CodeUri: src/
Environment:
Variables:
TABLE_NAME: !Sub "authtable-${AliasName}"
Events:
AuthenticatorEvent:
Type: Api
Properties:
Path: /authentication/
Method: POST
The SAM Documentation says that the syntax above is able to create the necessary permissions and API declaration implicitly.
I also followed an example from AWS website.
If I add to the template.yaml file a lambda:InvokeFunction permission then the invocation works, but by reading the documentation doing that should not be necessary.
What can be going wrong?

AWS Lambda scheduled with CodeStar: SyncResources com.amazon.coral.service.InternalFailure

I'm trying to deploy scheduled AWS Lambda function using CodeStar.
I have started from the webserver template of CodeStart and I have modified the template.yml in order to use the scheduled events.
AWSTemplateFormatVersion: 2010-09-09
Transform:
- AWS::Serverless-2016-10-31
- AWS::CodeStar
Parameters:
ProjectId:
Type: String
Description: AWS CodeStar projectID used to associate new resources to team members
Resources:
HelloWorld:
Type: AWS::Serverless::Function
Properties:
Handler: app.handler
Runtime: nodejs6.10
Role:
Fn::ImportValue:
!Join ['-', [!Ref 'ProjectId', !Ref 'AWS::Region','LambdaTrustRole']]
Events:
MyEvent:
Type: Schedule
Properties:
Schedule: rate(5 minutes)
I had attached the Policie CloudWatchEventsFullAccess to the Role CodeStarWorker-xxxxx-CloudFormation in order to allow the events:PutRule.
When I launch the CodePipeline I end getting an error in the deploy stage (CloudFormation) saying:
CREATE_FAILED AWS::CodeStar::SyncResources SyncResources1493352569577 com.amazon.coral.service.InternalFailure
No resources in your CloudFormation template are related to CodeStar so I think removing the 'AWS::CodeStar' line one the top should fix it.

Resources