-
Notifications
You must be signed in to change notification settings - Fork 4k
/
role.ts
663 lines (579 loc) · 22.9 KB
/
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
import { ArnFormat, IConstruct, Duration, Resource, Stack, Token, TokenComparison, Aspects, ConcreteDependable, Annotations } from '@aws-cdk/core';
import { Construct, Node } from 'constructs';
import { Grant } from './grant';
import { CfnRole } from './iam.generated';
import { IIdentity } from './identity-base';
import { IManagedPolicy, ManagedPolicy } from './managed-policy';
import { Policy } from './policy';
import { PolicyDocument } from './policy-document';
import { PolicyStatement } from './policy-statement';
import { AddToPrincipalPolicyResult, ArnPrincipal, IPrincipal, PrincipalPolicyFragment, IComparablePrincipal } from './principals';
import { defaultAddPrincipalToAssumeRole } from './private/assume-role-policy';
import { ImmutableRole } from './private/immutable-role';
import { MutatingPolicyDocumentAdapter } from './private/policydoc-adapter';
import { AttachedPolicies, UniqueStringSet } from './util';
const MAX_INLINE_SIZE = 10000;
const MAX_MANAGEDPOL_SIZE = 6000;
/**
* Properties for defining an IAM Role
*/
export interface RoleProps {
/**
* The IAM principal (i.e. `new ServicePrincipal('sns.amazonaws.com')`)
* which can assume this role.
*
* You can later modify the assume role policy document by accessing it via
* the `assumeRolePolicy` property.
*/
readonly assumedBy: IPrincipal;
/**
* ID that the role assumer needs to provide when assuming this role
*
* If the configured and provided external IDs do not match, the
* AssumeRole operation will fail.
*
* @deprecated see {@link externalIds}
*
* @default No external ID required
*/
readonly externalId?: string;
/**
* List of IDs that the role assumer needs to provide one of when assuming this role
*
* If the configured and provided external IDs do not match, the
* AssumeRole operation will fail.
*
* @default No external ID required
*/
readonly externalIds?: string[];
/**
* A list of managed policies associated with this role.
*
* You can add managed policies later using
* `addManagedPolicy(ManagedPolicy.fromAwsManagedPolicyName(policyName))`.
*
* @default - No managed policies.
*/
readonly managedPolicies?: IManagedPolicy[];
/**
* A list of named policies to inline into this role. These policies will be
* created with the role, whereas those added by ``addToPolicy`` are added
* using a separate CloudFormation resource (allowing a way around circular
* dependencies that could otherwise be introduced).
*
* @default - No policy is inlined in the Role resource.
*/
readonly inlinePolicies?: { [name: string]: PolicyDocument };
/**
* The path associated with this role. For information about IAM paths, see
* Friendly Names and Paths in IAM User Guide.
*
* @default /
*/
readonly path?: string;
/**
* AWS supports permissions boundaries for IAM entities (users or roles).
* A permissions boundary is an advanced feature for using a managed policy
* to set the maximum permissions that an identity-based policy can grant to
* an IAM entity. An entity's permissions boundary allows it to perform only
* the actions that are allowed by both its identity-based policies and its
* permissions boundaries.
*
* @link https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-role.html#cfn-iam-role-permissionsboundary
* @link https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html
*
* @default - No permissions boundary.
*/
readonly permissionsBoundary?: IManagedPolicy;
/**
* A name for the IAM role. For valid values, see the RoleName parameter for
* the CreateRole action in the IAM API Reference.
*
* IMPORTANT: If you specify a name, you cannot perform updates that require
* replacement of this resource. You can perform updates that require no or
* some interruption. If you must replace the resource, specify a new name.
*
* If you specify a name, you must specify the CAPABILITY_NAMED_IAM value to
* acknowledge your template's capabilities. For more information, see
* Acknowledging IAM Resources in AWS CloudFormation Templates.
*
* @default - AWS CloudFormation generates a unique physical ID and uses that ID
* for the role name.
*/
readonly roleName?: string;
/**
* The maximum session duration that you want to set for the specified role.
* This setting can have a value from 1 hour (3600sec) to 12 (43200sec) hours.
*
* Anyone who assumes the role from the AWS CLI or API can use the
* DurationSeconds API parameter or the duration-seconds CLI parameter to
* request a longer session. The MaxSessionDuration setting determines the
* maximum duration that can be requested using the DurationSeconds
* parameter.
*
* If users don't specify a value for the DurationSeconds parameter, their
* security credentials are valid for one hour by default. This applies when
* you use the AssumeRole* API operations or the assume-role* CLI operations
* but does not apply when you use those operations to create a console URL.
*
* @link https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html
*
* @default Duration.hours(1)
*/
readonly maxSessionDuration?: Duration;
/**
* A description of the role. It can be up to 1000 characters long.
*
* @default - No description.
*/
readonly description?: string;
}
/**
* Options allowing customizing the behavior of {@link Role.fromRoleArn}.
*/
export interface FromRoleArnOptions {
/**
* Whether the imported role can be modified by attaching policy resources to it.
*
* @default true
*/
readonly mutable?: boolean;
/**
* For immutable roles: add grants to resources instead of dropping them
*
* If this is `false` or not specified, grant permissions added to this role are ignored.
* It is your own responsibility to make sure the role has the required permissions.
*
* If this is `true`, any grant permissions will be added to the resource instead.
*
* @default false
*/
readonly addGrantsToResources?: boolean;
}
/**
* IAM Role
*
* Defines an IAM role. The role is created with an assume policy document associated with
* the specified AWS service principal defined in `serviceAssumeRole`.
*/
export class Role extends Resource implements IRole {
/**
* Import an external role by ARN.
*
* If the imported Role ARN is a Token (such as a
* `CfnParameter.valueAsString` or a `Fn.importValue()`) *and* the referenced
* role has a `path` (like `arn:...:role/AdminRoles/Alice`), the
* `roleName` property will not resolve to the correct value. Instead it
* will resolve to the first path component. We unfortunately cannot express
* the correct calculation of the full path name as a CloudFormation
* expression. In this scenario the Role ARN should be supplied without the
* `path` in order to resolve the correct role resource.
*
* @param scope construct scope
* @param id construct id
* @param roleArn the ARN of the role to import
* @param options allow customizing the behavior of the returned role
*/
public static fromRoleArn(scope: Construct, id: string, roleArn: string, options: FromRoleArnOptions = {}): IRole {
const scopeStack = Stack.of(scope);
const parsedArn = scopeStack.splitArn(roleArn, ArnFormat.SLASH_RESOURCE_NAME);
const resourceName = parsedArn.resourceName!;
const roleAccount = parsedArn.account;
// service roles have an ARN like 'arn:aws:iam::<account>:role/service-role/<roleName>'
// or 'arn:aws:iam::<account>:role/service-role/servicename.amazonaws.com/service-role/<roleName>'
// we want to support these as well, so we just use the element after the last slash as role name
const roleName = resourceName.split('/').pop()!;
class Import extends Resource implements IRole, IComparablePrincipal {
public readonly grantPrincipal: IPrincipal = this;
public readonly principalAccount = roleAccount;
public readonly assumeRoleAction: string = 'sts:AssumeRole';
public readonly policyFragment = new ArnPrincipal(roleArn).policyFragment;
public readonly roleArn = roleArn;
public readonly roleName = roleName;
private readonly attachedPolicies = new AttachedPolicies();
private defaultPolicy?: Policy;
constructor(_scope: Construct, _id: string) {
super(_scope, _id, {
account: roleAccount,
});
}
public addToPolicy(statement: PolicyStatement): boolean {
return this.addToPrincipalPolicy(statement).statementAdded;
}
public addToPrincipalPolicy(statement: PolicyStatement): AddToPrincipalPolicyResult {
if (!this.defaultPolicy) {
this.defaultPolicy = new Policy(this, 'Policy');
this.attachInlinePolicy(this.defaultPolicy);
}
this.defaultPolicy.addStatements(statement);
return { statementAdded: true, policyDependable: this.defaultPolicy };
}
public attachInlinePolicy(policy: Policy): void {
const thisAndPolicyAccountComparison = Token.compareStrings(this.env.account, policy.env.account);
const equalOrAnyUnresolved = thisAndPolicyAccountComparison === TokenComparison.SAME ||
thisAndPolicyAccountComparison === TokenComparison.BOTH_UNRESOLVED ||
thisAndPolicyAccountComparison === TokenComparison.ONE_UNRESOLVED;
if (equalOrAnyUnresolved) {
this.attachedPolicies.attach(policy);
policy.attachToRole(this);
}
}
public addManagedPolicy(_policy: IManagedPolicy): void {
// FIXME: Add warning that we're ignoring this
}
/**
* Grant permissions to the given principal to pass this role.
*/
public grantPassRole(identity: IPrincipal): Grant {
return this.grant(identity, 'iam:PassRole');
}
/**
* Grant permissions to the given principal to pass this role.
*/
public grantAssumeRole(identity: IPrincipal): Grant {
return this.grant(identity, 'sts:AssumeRole');
}
/**
* Grant the actions defined in actions to the identity Principal on this resource.
*/
public grant(grantee: IPrincipal, ...actions: string[]): Grant {
return Grant.addToPrincipal({
grantee,
actions,
resourceArns: [this.roleArn],
scope: this,
});
}
public dedupeString(): string | undefined {
return `ImportedRole:${roleArn}`;
}
}
if (options.addGrantsToResources !== undefined && options.mutable !== false) {
throw new Error('\'addGrantsToResources\' can only be passed if \'mutable: false\'');
}
const roleArnAndScopeStackAccountComparison = Token.compareStrings(roleAccount ?? '', scopeStack.account);
const equalOrAnyUnresolved = roleArnAndScopeStackAccountComparison === TokenComparison.SAME ||
roleArnAndScopeStackAccountComparison === TokenComparison.BOTH_UNRESOLVED ||
roleArnAndScopeStackAccountComparison === TokenComparison.ONE_UNRESOLVED;
// if we are returning an immutable role then the 'importedRole' is just a throwaway construct
// so give it a different id
const mutableRoleId = (options.mutable !== false && equalOrAnyUnresolved) ? id : `MutableRole${id}`;
const importedRole = new Import(scope, mutableRoleId);
// we only return an immutable Role if both accounts were explicitly provided, and different
return options.mutable !== false && equalOrAnyUnresolved
? importedRole
: new ImmutableRole(scope, id, importedRole, options.addGrantsToResources ?? false);
}
/**
* Import an external role by name.
*
* The imported role is assumed to exist in the same account as the account
* the scope's containing Stack is being deployed to.
*/
public static fromRoleName(scope: Construct, id: string, roleName: string) {
return Role.fromRoleArn(scope, id, Stack.of(scope).formatArn({
region: '',
service: 'iam',
resource: 'role',
resourceName: roleName,
}));
}
public readonly grantPrincipal: IPrincipal = this;
public readonly principalAccount: string | undefined = this.env.account;
public readonly assumeRoleAction: string = 'sts:AssumeRole';
/**
* The assume role policy document associated with this role.
*/
public readonly assumeRolePolicy?: PolicyDocument;
/**
* Returns the ARN of this role.
*/
public readonly roleArn: string;
/**
* Returns the stable and unique string identifying the role. For example,
* AIDAJQABLZS4A3QDU576Q.
*
* @attribute
*/
public readonly roleId: string;
/**
* Returns the name of the role.
*/
public readonly roleName: string;
/**
* Returns the role.
*/
public readonly policyFragment: PrincipalPolicyFragment;
/**
* Returns the permissions boundary attached to this role
*/
public readonly permissionsBoundary?: IManagedPolicy;
private defaultPolicy?: Policy;
private readonly managedPolicies: IManagedPolicy[] = [];
private readonly attachedPolicies = new AttachedPolicies();
private readonly inlinePolicies: { [name: string]: PolicyDocument };
private readonly dependables = new Map<PolicyStatement, ConcreteDependable>();
private immutableRole?: IRole;
private _didSplit = false;
constructor(scope: Construct, id: string, props: RoleProps) {
super(scope, id, {
physicalName: props.roleName,
});
const externalIds = props.externalIds || [];
if (props.externalId) {
externalIds.push(props.externalId);
}
this.assumeRolePolicy = createAssumeRolePolicy(props.assumedBy, externalIds);
this.managedPolicies.push(...props.managedPolicies || []);
this.inlinePolicies = props.inlinePolicies || {};
this.permissionsBoundary = props.permissionsBoundary;
const maxSessionDuration = props.maxSessionDuration && props.maxSessionDuration.toSeconds();
validateMaxSessionDuration(maxSessionDuration);
const description = (props.description && props.description?.length > 0) ? props.description : undefined;
if (description && description.length > 1000) {
throw new Error('Role description must be no longer than 1000 characters.');
}
validateRolePath(props.path);
const role = new CfnRole(this, 'Resource', {
assumeRolePolicyDocument: this.assumeRolePolicy as any,
managedPolicyArns: UniqueStringSet.from(() => this.managedPolicies.map(p => p.managedPolicyArn)),
policies: _flatten(this.inlinePolicies),
path: props.path,
permissionsBoundary: this.permissionsBoundary ? this.permissionsBoundary.managedPolicyArn : undefined,
roleName: this.physicalName,
maxSessionDuration,
description,
});
this.roleId = role.attrRoleId;
this.roleArn = this.getResourceArnAttribute(role.attrArn, {
region: '', // IAM is global in each partition
service: 'iam',
resource: 'role',
// Removes leading slash from path
resourceName: `${props.path ? props.path.substr(props.path.charAt(0) === '/' ? 1 : 0) : ''}${this.physicalName}`,
});
this.roleName = this.getResourceNameAttribute(role.ref);
this.policyFragment = new ArnPrincipal(this.roleArn).policyFragment;
function _flatten(policies?: { [name: string]: PolicyDocument }) {
if (policies == null || Object.keys(policies).length === 0) {
return undefined;
}
const result = new Array<CfnRole.PolicyProperty>();
for (const policyName of Object.keys(policies)) {
const policyDocument = policies[policyName];
result.push({ policyName, policyDocument });
}
return result;
}
Aspects.of(this).add({
visit: (c) => {
if (c === this) {
this.splitLargePolicy();
}
},
});
}
/**
* Adds a permission to the role's default policy document.
* If there is no default policy attached to this role, it will be created.
* @param statement The permission statement to add to the policy document
*/
public addToPrincipalPolicy(statement: PolicyStatement): AddToPrincipalPolicyResult {
if (!this.defaultPolicy) {
this.defaultPolicy = new Policy(this, 'DefaultPolicy');
this.attachInlinePolicy(this.defaultPolicy);
}
this.defaultPolicy.addStatements(statement);
// We might split this statement off into a different policy, so we'll need to
// late-bind the dependable.
const policyDependable = new ConcreteDependable();
this.dependables.set(statement, policyDependable);
return { statementAdded: true, policyDependable };
}
public addToPolicy(statement: PolicyStatement): boolean {
return this.addToPrincipalPolicy(statement).statementAdded;
}
/**
* Attaches a managed policy to this role.
* @param policy The the managed policy to attach.
*/
public addManagedPolicy(policy: IManagedPolicy) {
if (this.managedPolicies.find(mp => mp === policy)) { return; }
this.managedPolicies.push(policy);
}
/**
* Attaches a policy to this role.
* @param policy The policy to attach
*/
public attachInlinePolicy(policy: Policy) {
this.attachedPolicies.attach(policy);
policy.attachToRole(this);
}
/**
* Grant the actions defined in actions to the identity Principal on this resource.
*/
public grant(grantee: IPrincipal, ...actions: string[]) {
return Grant.addToPrincipal({
grantee,
actions,
resourceArns: [this.roleArn],
scope: this,
});
}
/**
* Grant permissions to the given principal to pass this role.
*/
public grantPassRole(identity: IPrincipal) {
return this.grant(identity, 'iam:PassRole');
}
/**
* Grant permissions to the given principal to assume this role.
*/
public grantAssumeRole(identity: IPrincipal) {
return this.grant(identity, 'sts:AssumeRole');
}
/**
* Return a copy of this Role object whose Policies will not be updated
*
* Use the object returned by this method if you want this Role to be used by
* a construct without it automatically updating the Role's Policies.
*
* If you do, you are responsible for adding the correct statements to the
* Role's policies yourself.
*/
public withoutPolicyUpdates(options: WithoutPolicyUpdatesOptions = {}): IRole {
if (!this.immutableRole) {
this.immutableRole = new ImmutableRole(Node.of(this).scope as Construct, `ImmutableRole${this.node.id}`, this, options.addGrantsToResources ?? false);
}
return this.immutableRole;
}
protected validate(): string[] {
const errors = super.validate();
errors.push(...this.assumeRolePolicy?.validateForResourcePolicy() || []);
for (const policy of Object.values(this.inlinePolicies)) {
errors.push(...policy.validateForIdentityPolicy());
}
return errors;
}
/**
* Split large inline policies into managed policies
*
* This gets around the 10k bytes limit on role policies.
*/
private splitLargePolicy() {
if (!this.defaultPolicy || this._didSplit) {
return;
}
this._didSplit = true;
const self = this;
const originalDoc = this.defaultPolicy.document;
const splitOffDocs = originalDoc._splitDocument(this, MAX_INLINE_SIZE, MAX_MANAGEDPOL_SIZE);
// Includes the "current" document
const mpCount = this.managedPolicies.length + (splitOffDocs.size - 1);
if (mpCount > 20) {
Annotations.of(this).addWarning(`Policy too large: ${mpCount} exceeds the maximum of 20 managed policies attached to a Role`);
} else if (mpCount > 10) {
Annotations.of(this).addWarning(`Policy large: ${mpCount} exceeds 10 managed policies attached to a Role, this requires a quota increase`);
}
// Create the managed policies and fix up the dependencies
markDeclaringConstruct(originalDoc, this.defaultPolicy);
let i = 1;
for (const newDoc of splitOffDocs.keys()) {
if (newDoc === originalDoc) { continue; }
const mp = new ManagedPolicy(this, `OverflowPolicy${i++}`, {
description: `Part of the policies for ${this.node.path}`,
document: newDoc,
roles: [this],
});
markDeclaringConstruct(newDoc, mp);
}
/**
* Update the Dependables for the statements in the given PolicyDocument to point to the actual declaring construct
*/
function markDeclaringConstruct(doc: PolicyDocument, declaringConstruct: IConstruct) {
for (const original of splitOffDocs.get(doc) ?? []) {
self.dependables.get(original)?.add(declaringConstruct);
}
}
}
}
/**
* A Role object
*/
export interface IRole extends IIdentity {
/**
* Returns the ARN of this role.
*
* @attribute
*/
readonly roleArn: string;
/**
* Returns the name of this role.
*
* @attribute
*/
readonly roleName: string;
/**
* Grant the actions defined in actions to the identity Principal on this resource.
*/
grant(grantee: IPrincipal, ...actions: string[]): Grant;
/**
* Grant permissions to the given principal to pass this role.
*/
grantPassRole(grantee: IPrincipal): Grant;
/**
* Grant permissions to the given principal to assume this role.
*/
grantAssumeRole(grantee: IPrincipal): Grant;
}
function createAssumeRolePolicy(principal: IPrincipal, externalIds: string[]) {
const actualDoc = new PolicyDocument();
// If requested, add externalIds to every statement added to this doc
const addDoc = externalIds.length === 0
? actualDoc
: new MutatingPolicyDocumentAdapter(actualDoc, (statement) => {
statement.addCondition('StringEquals', {
'sts:ExternalId': externalIds.length === 1 ? externalIds[0] : externalIds,
});
return statement;
});
defaultAddPrincipalToAssumeRole(principal, addDoc);
return actualDoc;
}
function validateRolePath(path?: string) {
if (path === undefined || Token.isUnresolved(path)) {
return;
}
const validRolePath = /^(\/|\/[\u0021-\u007F]+\/)$/;
if (path.length == 0 || path.length > 512) {
throw new Error(`Role path must be between 1 and 512 characters. The provided role path is ${path.length} characters.`);
} else if (!validRolePath.test(path)) {
throw new Error(
'Role path must be either a slash or valid characters (alphanumerics and symbols) surrounded by slashes. '
+ `Valid characters are unicode characters in [\\u0021-\\u007F]. However, ${path} is provided.`);
}
}
function validateMaxSessionDuration(duration?: number) {
if (duration === undefined) {
return;
}
if (duration < 3600 || duration > 43200) {
throw new Error(`maxSessionDuration is set to ${duration}, but must be >= 3600sec (1hr) and <= 43200sec (12hrs)`);
}
}
/**
* Options for the `withoutPolicyUpdates()` modifier of a Role
*/
export interface WithoutPolicyUpdatesOptions {
/**
* Add grants to resources instead of dropping them
*
* If this is `false` or not specified, grant permissions added to this role are ignored.
* It is your own responsibility to make sure the role has the required permissions.
*
* If this is `true`, any grant permissions will be added to the resource instead.
*
* @default false
*/
readonly addGrantsToResources?: boolean;
}