Skip to content

Commit

Permalink
fix(lambda): allow grantInvoke with principals (#2391)
Browse files Browse the repository at this point in the history
Fixes 'Cannot use tokens in construct ID' when calling grantInvoke with a service or account
principal.

Error with a service: Cannot use tokens in construct ID: Invoke{"Service":["${Token[TOKEN.139]}"]}
Error with an account: Cannot use tokens in construct ID: Invoke{"AWS":["${Token[TOKEN.813]}"]}
  • Loading branch information
jogold authored and rix0rrr committed May 6, 2019
1 parent 52af870 commit b3792aa
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 1 deletion.
2 changes: 1 addition & 1 deletion packages/@aws-cdk/aws-lambda/lib/function-base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,7 @@ export abstract class FunctionBase extends Resource implements IFunction {
resource: {
addToResourcePolicy: (_statement) => {
// Couldn't add permissions to the principal, so add them locally.
const identifier = 'Invoke' + JSON.stringify(grantee!.grantPrincipal.policyFragment.principalJson);
const identifier = `Invoke${grantee.grantPrincipal}`; // calls the .toString() of the princpal
this.addPermission(identifier, {
principal: grantee.grantPrincipal!,
action: 'lambda:InvokeFunction',
Expand Down
56 changes: 56 additions & 0 deletions packages/@aws-cdk/aws-lambda/test/test.lambda.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1020,6 +1020,62 @@ export = {
test.done();
},

'grantInvoke with a service principal'(test: Test) {
// GIVEN
const stack = new cdk.Stack();
const fn = new lambda.Function(stack, 'Function', {
code: lambda.Code.inline('xxx'),
handler: 'index.handler',
runtime: lambda.Runtime.NodeJS810,
});
const service = new iam.ServicePrincipal('apigateway.amazonaws.com');

// WHEN
fn.grantInvoke(service);

// THEN
expect(stack).to(haveResource('AWS::Lambda::Permission', {
Action: 'lambda:InvokeFunction',
FunctionName: {
'Fn::GetAtt': [
'Function76856677',
'Arn'
]
},
Principal: 'apigateway.amazonaws.com'
}));

test.done();
},

'grantInvoke with an account principal'(test: Test) {
// GIVEN
const stack = new cdk.Stack();
const fn = new lambda.Function(stack, 'Function', {
code: lambda.Code.inline('xxx'),
handler: 'index.handler',
runtime: lambda.Runtime.NodeJS810,
});
const account = new iam.AccountPrincipal('123456789012');

// WHEN
fn.grantInvoke(account);

// THEN
expect(stack).to(haveResource('AWS::Lambda::Permission', {
Action: 'lambda:InvokeFunction',
FunctionName: {
'Fn::GetAtt': [
'Function76856677',
'Arn'
]
},
Principal: '123456789012'
}));

test.done();
},

'Can use metricErrors on a lambda Function'(test: Test) {
// GIVEN
const stack = new cdk.Stack();
Expand Down

0 comments on commit b3792aa

Please sign in to comment.