diff --git a/packages/@aws-cdk/aws-iam/lib/policy-statement.ts b/packages/@aws-cdk/aws-iam/lib/policy-statement.ts index fd89301cb766c..ce817a58e508e 100644 --- a/packages/@aws-cdk/aws-iam/lib/policy-statement.ts +++ b/packages/@aws-cdk/aws-iam/lib/policy-statement.ts @@ -1,4 +1,5 @@ import * as cdk from '@aws-cdk/core'; +import { Group } from './group'; import { AccountPrincipal, AccountRootPrincipal, Anyone, ArnPrincipal, CanonicalUserPrincipal, FederatedPrincipal, IPrincipal, PrincipalBase, PrincipalPolicyFragment, ServicePrincipal, ServicePrincipalOpts, @@ -138,6 +139,7 @@ export class PolicyStatement { throw new Error('Cannot add \'Principals\' to policy statement if \'NotPrincipals\' have been added'); } for (const principal of principals) { + this.validatePolicyPrincipal(principal); const fragment = principal.policyFragment; mergePrincipal(this.principal, fragment.principalJson); this.addPrincipalConditions(fragment.conditions); @@ -157,12 +159,19 @@ export class PolicyStatement { throw new Error('Cannot add \'NotPrincipals\' to policy statement if \'Principals\' have been added'); } for (const notPrincipal of notPrincipals) { + this.validatePolicyPrincipal(notPrincipal); const fragment = notPrincipal.policyFragment; mergePrincipal(this.notPrincipal, fragment.principalJson); this.addPrincipalConditions(fragment.conditions); } } + 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'); + } + } + /** * Specify AWS account ID as the principal entity to the "Principal" section of a policy statement. */ diff --git a/packages/@aws-cdk/aws-iam/test/policy-statement.test.ts b/packages/@aws-cdk/aws-iam/test/policy-statement.test.ts index 5f08f45e814a1..089fa34dba74e 100644 --- a/packages/@aws-cdk/aws-iam/test/policy-statement.test.ts +++ b/packages/@aws-cdk/aws-iam/test/policy-statement.test.ts @@ -1,6 +1,6 @@ import '@aws-cdk/assert/jest'; import { Stack } from '@aws-cdk/core'; -import { AnyPrincipal, PolicyDocument, PolicyStatement } from '../lib'; +import { AnyPrincipal, Group, PolicyDocument, PolicyStatement } from '../lib'; describe('IAM policy statement', () => { @@ -180,4 +180,14 @@ describe('IAM policy statement', () => { }); }); + test('throws error when group is specified for \'Principal\' or \'NotPrincipal\'', () => { + const stack = new Stack(); + const group = new Group(stack, 'groupId'); + const policyStatement = new PolicyStatement(); + + expect(() => policyStatement.addPrincipals(group)) + .toThrow(/Cannot use an IAM Group as the 'Principal' or 'NotPrincipal' in an IAM Policy/); + expect(() => policyStatement.addNotPrincipals(group)) + .toThrow(/Cannot use an IAM Group as the 'Principal' or 'NotPrincipal' in an IAM Policy/); + }); });