From 1ee813534b430d748049af0e822cdb585d68f195 Mon Sep 17 00:00:00 2001 From: Rico Huijbers Date: Thu, 18 Oct 2018 15:52:12 +0200 Subject: [PATCH] feat(aws-lambda): add grantInvoke() method (#962) Add a method that gives invoke permissions on Lambdas. Fixes #961. --- .../@aws-cdk/aws-lambda/lib/lambda-ref.ts | 11 +++++++ .../@aws-cdk/aws-lambda/test/test.lambda.ts | 29 +++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/packages/@aws-cdk/aws-lambda/lib/lambda-ref.ts b/packages/@aws-cdk/aws-lambda/lib/lambda-ref.ts index 92869fb73aeb3..11c5b85ba525b 100644 --- a/packages/@aws-cdk/aws-lambda/lib/lambda-ref.ts +++ b/packages/@aws-cdk/aws-lambda/lib/lambda-ref.ts @@ -251,6 +251,17 @@ export abstract class FunctionRef extends cdk.Construct }; } + /** + * Grant the given identity permissions to invoke this Lambda + */ + public grantInvoke(identity?: iam.IPrincipal) { + if (identity) { + identity.addToPolicy(new iam.PolicyStatement() + .addAction('lambda:InvokeFunction') + .addResource(this.functionArn)); + } + } + /** * Return the given named metric for this Lambda */ diff --git a/packages/@aws-cdk/aws-lambda/test/test.lambda.ts b/packages/@aws-cdk/aws-lambda/test/test.lambda.ts index 4c2b2d42ee716..7ee63e038a7f0 100644 --- a/packages/@aws-cdk/aws-lambda/test/test.lambda.ts +++ b/packages/@aws-cdk/aws-lambda/test/test.lambda.ts @@ -1081,6 +1081,35 @@ export = { test.done(); }, + 'grantInvoke adds iam:InvokeFunction'(test: Test) { + // GIVEN + const stack = new cdk.Stack(); + const role = new iam.Role(stack, 'Role', { + assumedBy: new iam.AccountPrincipal('1234'), + }); + const fn = new lambda.Function(stack, 'Function', { + code: lambda.Code.inline('xxx'), + handler: 'index.handler', + runtime: lambda.Runtime.NodeJS810, + }); + + // WHEN + fn.grantInvoke(role); + + // THEN + expect(stack).to(haveResource('AWS::IAM::Policy', { + PolicyDocument: { + Statement: [ + { + Action: 'lambda:InvokeFunction', + Resource: { "Fn::GetAtt": [ "Function76856677", "Arn" ] } + } + ] + } + })); + + test.done(); + }, }; function newTestLambda(parent: cdk.Construct) {