Skip to content

iam: cannot pass iam.ManagedPolicy or iam.Policy to lambda.Function.grantInvoke #32980

Open
@Tietew

Description

Describe the bug

Following code fails:

const func = new lambda.Function(this, 'Function', { /* ... */ });
const managedPolicy = new iam.ManagedPolicy(this, 'ManagedPolicy');
func.grantInvoke(managedPolicy);

The error message is:

Cannot use a ManagedPolicy 'MyStack/Function' as the 'Principal' or 'NotPrincipal' in an IAM Policy

Regression Issue

  • Select this option if this issue appears to be a regression.

Last Known Working CDK Version

No response

Expected Behavior

Grant lambda:InvokeFunction to ManagedPolicy or Policy.

Current Behavior

grantInvoke() throws an error described above.

Reproduction Steps

See the description above.

Possible Solution

grantInvoke() calls grantee.grantPrincipal.policyFragment.conditions to create a dedupe hash.

public grantInvoke(grantee: iam.IGrantable): iam.Grant {
const hash = createHash('sha256')
.update(JSON.stringify({
principal: grantee.grantPrincipal.toString(),
conditions: grantee.grantPrincipal.policyFragment.conditions,
}), 'utf8')
.digest('base64');
const identifier = `Invoke${hash}`;

But policyFragment getter of ManagedPolicy and Policy throws an error. (see #22712)
It should return a dummy policy fragment like Group.

public get policyFragment(): PrincipalPolicyFragment {
return new ArnPrincipal(this.groupArn).policyFragment;
}

Group is blocked in PolicyStatement

private validatePolicyPrincipal(principal: IPrincipal) {
if (principal instanceof Group) {
throw new Error('Cannot use an IAM Group as the \'Principal\' or \'NotPrincipal\' in an IAM Policy');
}
}

Additional Information/Context

No response

CDK CLI Version

2.176.0

Framework Version

2.176.0

Node.js Version

22.13.0

OS

Ubuntu

Language

TypeScript

Language Version

No response

Other information

Related to #32795

Metadata

Labels

@aws-cdk/aws-iamRelated to AWS Identity and Access ManagementbugThis issue is a bug.effort/mediumMedium work item – several days of effortp3

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions