/
immutable-role.ts
74 lines (64 loc) · 2.65 KB
/
immutable-role.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import { ConcreteDependable, DependableTrait, Resource } from '@aws-cdk/core';
import { Construct } from 'constructs';
import { Grant } from '../grant';
import { IManagedPolicy } from '../managed-policy';
import { Policy } from '../policy';
import { PolicyStatement } from '../policy-statement';
import { AddToPrincipalPolicyResult, IPrincipal } from '../principals';
import { IRole } from '../role';
/**
* An immutable wrapper around an IRole
*
* This wrapper ignores all mutating operations, like attaching policies or
* adding policy statements.
*
* Useful in cases where you want to turn off CDK's automatic permissions
* management, and instead have full control over all permissions.
*
* Note: if you want to ignore all mutations for an externally defined role
* which was imported into the CDK with {@link Role.fromRoleArn}, you don't have to use this class -
* simply pass the property mutable = false when calling {@link Role.fromRoleArn}.
*/
export class ImmutableRole extends Resource implements IRole {
public readonly assumeRoleAction = this.role.assumeRoleAction;
public readonly policyFragment = this.role.policyFragment;
public readonly grantPrincipal = this;
public readonly principalAccount = this.role.principalAccount;
public readonly roleArn = this.role.roleArn;
public readonly roleName = this.role.roleName;
public readonly stack = this.role.stack;
constructor(scope: Construct, id: string, private readonly role: IRole, private readonly addGrantsToResources: boolean) {
super(scope, id, {
account: role.env.account,
region: role.env.region,
});
// implement IDependable privately
DependableTrait.implement(this, {
dependencyRoots: [role],
});
}
public attachInlinePolicy(_policy: Policy): void {
// do nothing
}
public addManagedPolicy(_policy: IManagedPolicy): void {
// do nothing
}
public addToPolicy(statement: PolicyStatement): boolean {
return this.addToPrincipalPolicy(statement).statementAdded;
}
public addToPrincipalPolicy(_statement: PolicyStatement): AddToPrincipalPolicyResult {
// If we return `false`, the grants will try to add the statement to the resource
// (if possible).
const pretendSuccess = !this.addGrantsToResources;
return { statementAdded: pretendSuccess, policyDependable: new ConcreteDependable() };
}
public grant(grantee: IPrincipal, ...actions: string[]): Grant {
return this.role.grant(grantee, ...actions);
}
public grantPassRole(grantee: IPrincipal): Grant {
return this.role.grantPassRole(grantee);
}
public grantAssumeRole(identity: IPrincipal): Grant {
return this.role.grantAssumeRole(identity);
}
}