Skip to content

Commit

Permalink
fix(iam): support adding permissions to imported roles (#2805)
Browse files Browse the repository at this point in the history
Now create a Policy and attach it to imported roles as well.

This will only work for imported roles in the same account. If you
need to reference roles in other accounts without trying to add
these policy statements, use an `AwsPrincipal`.

Relates to #2381, #2651, #2652, #2662.
  • Loading branch information
rix0rrr committed Jun 17, 2019
1 parent b8a1c8e commit 936464f
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 5 deletions.
18 changes: 13 additions & 5 deletions packages/@aws-cdk/aws-iam/lib/role.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,13 +116,21 @@ export class Role extends Resource implements IRole {
public readonly roleArn = roleArn;
public readonly roleName = Stack.of(scope).parseArn(roleArn).resourceName!;

public addToPolicy(_statement: PolicyStatement): boolean {
// Statement will be added to resource instead
return false;
private readonly attachedPolicies = new AttachedPolicies();
private defaultPolicy?: Policy;

public addToPolicy(statement: PolicyStatement): boolean {
if (!this.defaultPolicy) {
this.defaultPolicy = new Policy(this, 'Policy');
this.attachInlinePolicy(this.defaultPolicy);
}
this.defaultPolicy.addStatement(statement);
return true;
}

public attachInlinePolicy(_policy: Policy): void {
// FIXME: Add warning that we're ignoring this
public attachInlinePolicy(policy: Policy): void {
this.attachedPolicies.attach(policy);
policy.attachToRole(this);
}

public attachManagedPolicy(_arn: string): void {
Expand Down
27 changes: 27 additions & 0 deletions packages/@aws-cdk/aws-iam/test/test.role.ts
Original file line number Diff line number Diff line change
Expand Up @@ -260,5 +260,32 @@ export = {
test.deepEqual(importedRole.roleArn, 'arn:aws:iam::123456789012:role/S3Access');
test.deepEqual(importedRole.roleName, 'S3Access');
test.done();
},

'add policy to imported role'(test: Test) {
// GIVEN
const stack = new Stack();
const importedRole = Role.fromRoleArn(stack, 'ImportedRole', 'arn:aws:iam::123456789012:role/MyRole');

// WHEN
importedRole.addToPolicy(new PolicyStatement()
.addAction('s3:*')
.addResource('xyz'));

// THEN
expect(stack).to(haveResource('AWS::IAM::Policy', {
PolicyDocument: {
Statement: [
{
Action: "s3:*",
Effect: "Allow",
Resource: "xyz"
}
],
Version: "2012-10-17"
},
Roles: [ "MyRole" ]
}));
test.done();
}
};

0 comments on commit 936464f

Please sign in to comment.