-
Notifications
You must be signed in to change notification settings - Fork 4k
/
policy-document.ts
563 lines (469 loc) · 14.2 KB
/
policy-document.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
import cdk = require('@aws-cdk/cdk');
import { Default, RegionInfo } from '@aws-cdk/region-info';
import { IPrincipal } from './principals';
import { mergePrincipal } from './util';
export class PolicyDocument extends cdk.Token {
private statements = new Array<PolicyStatement>();
/**
* Creates a new IAM policy document.
* @param defaultDocument An IAM policy document to use as an initial
* policy. All statements of this document will be copied in.
*/
constructor(private readonly baseDocument?: any) {
super();
}
public resolve(_context: cdk.ResolveContext): any {
if (this.isEmpty) {
return undefined;
}
const doc = this.baseDocument || { };
doc.Statement = doc.Statement || [ ];
doc.Version = doc.Version || '2012-10-17';
doc.Statement = doc.Statement.concat(this.statements);
return doc;
}
get isEmpty(): boolean {
return this.statements.length === 0;
}
/**
* The number of statements already added to this policy.
* Can be used, for example, to generate uniuqe "sid"s within the policy.
*/
get statementCount(): number {
return this.statements.length;
}
public addStatement(statement: PolicyStatement): PolicyDocument {
this.statements.push(statement);
return this;
}
}
/**
* Base class for policy principals
*/
export abstract class PrincipalBase implements IPrincipal {
public readonly grantPrincipal: IPrincipal = this;
/**
* Return the policy fragment that identifies this principal in a Policy.
*/
public abstract readonly policyFragment: PrincipalPolicyFragment;
/**
* When this Principal is used in an AssumeRole policy, the action to use.
*/
public readonly assumeRoleAction: string = 'sts:AssumeRole';
public addToPolicy(_statement: PolicyStatement): boolean {
// This base class is used for non-identity principals. None of them
// have a PolicyDocument to add to.
return false;
}
public toString() {
// This is a first pass to make the object readable. Descendant principals
// should return something nicer.
return JSON.stringify(this.policyFragment.principalJson);
}
public toJSON() {
// Have to implement toJSON() because the default will lead to infinite recursion.
return this.policyFragment.principalJson;
}
}
/**
* A collection of the fields in a PolicyStatement that can be used to identify a principal.
*
* This consists of the JSON used in the "Principal" field, and optionally a
* set of "Condition"s that need to be applied to the policy.
*/
export class PrincipalPolicyFragment {
constructor(
public readonly principalJson: { [key: string]: string[] },
public readonly conditions: { [key: string]: any } = { }) {
}
}
export class ArnPrincipal extends PrincipalBase {
constructor(public readonly arn: string) {
super();
}
public get policyFragment(): PrincipalPolicyFragment {
return new PrincipalPolicyFragment({ AWS: [ this.arn ] });
}
public toString() {
return `ArnPrincipal(${this.arn})`;
}
}
export class AccountPrincipal extends ArnPrincipal {
constructor(public readonly accountId: any) {
super(new StackDependentToken(stack => `arn:${stack.partition}:iam::${accountId}:root`).toString());
}
public toString() {
return `AccountPrincipal(${this.accountId})`;
}
}
/**
* An IAM principal that represents an AWS service (i.e. sqs.amazonaws.com).
*/
export class ServicePrincipal extends PrincipalBase {
constructor(public readonly service: string, private readonly opts: ServicePrincipalOpts = {}) {
super();
}
public get policyFragment(): PrincipalPolicyFragment {
return new PrincipalPolicyFragment({
Service: [
new ServicePrincipalToken(this.service, this.opts).toString()
]
});
}
public toString() {
return `ServicePrincipal(${this.service})`;
}
}
/**
* A principal that represents an AWS Organization
*/
export class OrganizationPrincipal extends PrincipalBase {
constructor(public readonly organizationId: string) {
super();
}
public get policyFragment(): PrincipalPolicyFragment {
return new PrincipalPolicyFragment(
{ AWS: ['*'] },
{ StringEquals: { 'aws:PrincipalOrgID': this.organizationId } }
);
}
public toString() {
return `OrganizationPrincipal(${this.organizationId})`;
}
}
/**
* A policy prinicipal for canonicalUserIds - useful for S3 bucket policies that use
* Origin Access identities.
*
* See https://docs.aws.amazon.com/general/latest/gr/acct-identifiers.html
*
* and
*
* https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-restricting-access-to-s3.html
*
* for more details.
*
*/
export class CanonicalUserPrincipal extends PrincipalBase {
constructor(public readonly canonicalUserId: string) {
super();
}
public get policyFragment(): PrincipalPolicyFragment {
return new PrincipalPolicyFragment({ CanonicalUser: [ this.canonicalUserId ] });
}
public toString() {
return `CanonicalUserPrincipal(${this.canonicalUserId})`;
}
}
export class FederatedPrincipal extends PrincipalBase {
public readonly assumeRoleAction: string;
constructor(
public readonly federated: string,
public readonly conditions: {[key: string]: any},
assumeRoleAction: string = 'sts:AssumeRole') {
super();
this.assumeRoleAction = assumeRoleAction;
}
public get policyFragment(): PrincipalPolicyFragment {
return new PrincipalPolicyFragment({ Federated: [ this.federated ] }, this.conditions);
}
public toString() {
return `FederatedPrincipal(${this.federated})`;
}
}
export class AccountRootPrincipal extends AccountPrincipal {
constructor() {
super(new StackDependentToken(stack => stack.accountId).toString());
}
public toString() {
return `AccountRootPrincipal()`;
}
}
/**
* A principal representing all identities in all accounts
*/
export class AnyPrincipal extends ArnPrincipal {
constructor() {
super('*');
}
public toString() {
return `AnyPrincipal()`;
}
}
/**
* A principal representing all identities in all accounts
* @deprecated use `AnyPrincipal`
*/
export class Anyone extends AnyPrincipal { }
export class CompositePrincipal extends PrincipalBase {
public readonly assumeRoleAction: string;
private readonly principals = new Array<PrincipalBase>();
constructor(principal: PrincipalBase, ...additionalPrincipals: PrincipalBase[]) {
super();
this.assumeRoleAction = principal.assumeRoleAction;
this.addPrincipals(principal);
this.addPrincipals(...additionalPrincipals);
}
public addPrincipals(...principals: PrincipalBase[]): this {
for (const p of principals) {
if (p.assumeRoleAction !== this.assumeRoleAction) {
throw new Error(
`Cannot add multiple principals with different "assumeRoleAction". ` +
`Expecting "${this.assumeRoleAction}", got "${p.assumeRoleAction}"`);
}
const fragment = p.policyFragment;
if (fragment.conditions && Object.keys(fragment.conditions).length > 0) {
throw new Error(
`Components of a CompositePrincipal must not have conditions. ` +
`Tried to add the following fragment: ${JSON.stringify(fragment)}`);
}
this.principals.push(p);
}
return this;
}
public get policyFragment(): PrincipalPolicyFragment {
const principalJson: { [key: string]: string[] } = { };
for (const p of this.principals) {
mergePrincipal(principalJson, p.policyFragment.principalJson);
}
return new PrincipalPolicyFragment(principalJson);
}
public toString() {
return `CompositePrincipal(${this.principals})`;
}
}
/**
* Represents a statement in an IAM policy document.
*/
export class PolicyStatement extends cdk.Token {
private action = new Array<any>();
private principal: { [key: string]: any[] } = {};
private resource = new Array<any>();
private condition: { [key: string]: any } = { };
private effect?: PolicyStatementEffect;
private sid?: any;
constructor(effect: PolicyStatementEffect = PolicyStatementEffect.Allow) {
super();
this.effect = effect;
}
//
// Actions
//
public addAction(action: string): PolicyStatement {
this.action.push(action);
return this;
}
public addActions(...actions: string[]): PolicyStatement {
actions.forEach(action => this.addAction(action));
return this;
}
//
// Principal
//
/**
* Indicates if this permission has a "Principal" section.
*/
public get hasPrincipal() {
return Object.keys(this.principal).length > 0;
}
public addPrincipal(principal: IPrincipal): this {
const fragment = principal.policyFragment;
mergePrincipal(this.principal, fragment.principalJson);
this.addConditions(fragment.conditions);
return this;
}
public addAwsPrincipal(arn: string): this {
return this.addPrincipal(new ArnPrincipal(arn));
}
public addAwsAccountPrincipal(accountId: string): this {
return this.addPrincipal(new AccountPrincipal(accountId));
}
public addArnPrincipal(arn: string): this {
return this.addAwsPrincipal(arn);
}
/**
* Adds a service principal to this policy statement.
*
* @param service the service name for which a service principal is requested (e.g: `s3.amazonaws.com`).
* @param opts options for adding the service principal (such as specifying a principal in a different region)
*/
public addServicePrincipal(service: string, opts?: ServicePrincipalOpts): this {
return this.addPrincipal(new ServicePrincipal(service, opts));
}
public addFederatedPrincipal(federated: any, conditions: {[key: string]: any}): this {
return this.addPrincipal(new FederatedPrincipal(federated, conditions));
}
public addAccountRootPrincipal(): this {
return this.addPrincipal(new AccountRootPrincipal());
}
public addCanonicalUserPrincipal(canonicalUserId: string): this {
return this.addPrincipal(new CanonicalUserPrincipal(canonicalUserId));
}
public addAnyPrincipal(): this {
return this.addPrincipal(new Anyone());
}
//
// Resources
//
public addResource(arn: string): PolicyStatement {
this.resource.push(arn);
return this;
}
/**
* Adds a ``"*"`` resource to this statement.
*/
public addAllResources(): PolicyStatement {
return this.addResource('*');
}
public addResources(...arns: string[]): PolicyStatement {
arns.forEach(r => this.addResource(r));
return this;
}
/**
* Indicates if this permission as at least one resource associated with it.
*/
public get hasResource() {
return this.resource && this.resource.length > 0;
}
public describe(sid: string): PolicyStatement {
this.sid = sid;
return this;
}
//
// Effect
//
/**
* Sets the permission effect to allow access to resources.
*/
public allow(): PolicyStatement {
this.effect = PolicyStatementEffect.Allow;
return this;
}
/**
* Sets the permission effect to deny access to resources.
*/
public deny(): PolicyStatement {
this.effect = PolicyStatementEffect.Deny;
return this;
}
//
// Condition
//
/**
* Add a condition to the Policy
*/
public addCondition(key: string, value: any): PolicyStatement {
this.condition[key] = value;
return this;
}
/**
* Add multiple conditions to the Policy
*/
public addConditions(conditions: {[key: string]: any}): PolicyStatement {
Object.keys(conditions).map(key => {
this.addCondition(key, conditions[key]);
});
return this;
}
/**
* Add a condition to the Policy.
*
* @deprecated For backwards compatibility. Use addCondition() instead.
*/
public setCondition(key: string, value: any): PolicyStatement {
return this.addCondition(key, value);
}
public limitToAccount(accountId: string): PolicyStatement {
return this.addCondition('StringEquals', new cdk.Token(() => {
return { 'sts:ExternalId': accountId };
}));
}
//
// Serialization
//
public resolve(_context: cdk.ResolveContext): any {
return this.toJson();
}
public toJson(): any {
return {
Action: _norm(this.action),
Condition: _norm(this.condition),
Effect: _norm(this.effect),
Principal: _normPrincipal(this.principal),
Resource: _norm(this.resource),
Sid: _norm(this.sid),
};
function _norm(values: any) {
if (typeof(values) === 'undefined') {
return undefined;
}
if (Array.isArray(values)) {
if (!values || values.length === 0) {
return undefined;
}
if (values.length === 1) {
return values[0];
}
return values;
}
if (typeof(values) === 'object') {
if (Object.keys(values).length === 0) {
return undefined;
}
}
return values;
}
function _normPrincipal(principal: { [key: string]: any[] }) {
const keys = Object.keys(principal);
if (keys.length === 0) { return undefined; }
const result: any = {};
for (const key of keys) {
const normVal = _norm(principal[key]);
if (normVal) {
result[key] = normVal;
}
}
if (Object.keys(result).length === 1 && result.AWS === '*') {
return '*';
}
return result;
}
}
}
export enum PolicyStatementEffect {
Allow = 'Allow',
Deny = 'Deny',
}
/**
* A lazy token that requires an instance of Stack to evaluate
*/
class StackDependentToken extends cdk.Token {
constructor(private readonly fn: (stack: cdk.Stack) => any) {
super();
}
public resolve(context: cdk.ResolveContext) {
return this.fn(context.scope.node.stack);
}
}
class ServicePrincipalToken extends cdk.Token {
constructor(private readonly service: string,
private readonly opts: ServicePrincipalOpts) {
super();
}
public resolve(ctx: cdk.ResolveContext) {
const region = this.opts.region || ctx.scope.node.stack.region;
const fact = RegionInfo.get(region).servicePrincipal(this.service);
return fact || Default.servicePrincipal(this.service, region, ctx.scope.node.stack.urlSuffix);
}
}
/**
* Options for a service principal.
*/
export interface ServicePrincipalOpts {
/**
* The region in which the service is operating.
*
* @default the current Stack's region.
*/
readonly region?: string;
}