Skip to content

Commit

Permalink
fix(iam): PrincipalWithConditions.addCondition does not work (#15414)
Browse files Browse the repository at this point in the history
In `PrincipalWithConditions` the `conditions` parameter uses the getter syntax to return a new conditions object each time, which means the `addCondition` call will effectively throw away any conditions being added.

This PR ensures the conditions added with `addCondition` show up in the resulting principal.

----

*By submitting this pull request, I confirm that my contribution is made under the terms of the Apache-2.0 license*
  • Loading branch information
TikiTDO authored Jul 19, 2021
1 parent 8668e15 commit fdce08c
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 2 deletions.
4 changes: 2 additions & 2 deletions packages/@aws-cdk/aws-iam/lib/principals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,8 +165,8 @@ export class PrincipalWithConditions implements IPrincipal {
* Add a condition to the principal
*/
public addCondition(key: string, value: Condition) {
const existingValue = this.conditions[key];
this.conditions[key] = existingValue ? { ...existingValue, ...value } : value;
const existingValue = this.additionalConditions[key];
this.additionalConditions[key] = existingValue ? { ...existingValue, ...value } : value;
}

/**
Expand Down
39 changes: 39 additions & 0 deletions packages/@aws-cdk/aws-iam/test/principals.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,45 @@ test('SAML principal', () => {
});
});

test('PrincipalWithConditions.addCondition should work', () => {
// GIVEN
const stack = new Stack();
const basePrincipal = new iam.ServicePrincipal('service.amazonaws.com');
const principalWithConditions = new iam.PrincipalWithConditions(basePrincipal, {
StringEquals: {
'aws:PrincipalOrgID': ['o-xxxxxxxxxxx'],
},
});

// WHEN
principalWithConditions.addCondition('StringEquals', { 'aws:PrincipalTag/critical': 'true' });
new iam.Role(stack, 'Role', {
assumedBy: principalWithConditions,
});

// THEN
expect(stack).toHaveResource('AWS::IAM::Role', {
AssumeRolePolicyDocument: {
Statement: [
{
Action: 'sts:AssumeRole',
Condition: {
StringEquals: {
'aws:PrincipalOrgID': ['o-xxxxxxxxxxx'],
'aws:PrincipalTag/critical': 'true',
},
},
Effect: 'Allow',
Principal: {
Service: 'service.amazonaws.com',
},
},
],
Version: '2012-10-17',
},
});
});

test('PrincipalWithConditions inherits principalAccount from AccountPrincipal ', () => {
// GIVEN
const accountPrincipal = new iam.AccountPrincipal('123456789012');
Expand Down

0 comments on commit fdce08c

Please sign in to comment.