-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
grant.ts
395 lines (351 loc) · 12.1 KB
/
grant.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
import { Dependable, IConstruct, IDependable } from 'constructs';
import { PolicyStatement } from './policy-statement';
import { IGrantable, IPrincipal } from './principals';
import * as cdk from '../../core';
/**
* Basic options for a grant operation
*
*/
export interface CommonGrantOptions {
/**
* The principal to grant to
*
* @default if principal is undefined, no work is done.
*/
readonly grantee: IGrantable;
/**
* The actions to grant
*/
readonly actions: string[];
/**
* The resource ARNs to grant to
*/
readonly resourceArns: string[];
/**
* Any conditions to attach to the grant
*
* @default - No conditions
*/
readonly conditions?: Record<string, Record<string, unknown>>;
}
/**
* Options for a grant operation
*
*/
export interface GrantWithResourceOptions extends CommonGrantOptions {
/**
* The resource with a resource policy
*
* The statement will be added to the resource policy if it couldn't be
* added to the principal policy.
*/
readonly resource: IResourceWithPolicy;
/**
* When referring to the resource in a resource policy, use this as ARN.
*
* (Depending on the resource type, this needs to be '*' in a resource policy).
*
* @default Same as regular resource ARNs
*/
readonly resourceSelfArns?: string[];
}
/**
* Options for a grant operation that only applies to principals
*
*/
export interface GrantOnPrincipalOptions extends CommonGrantOptions {
/**
* Construct to report warnings on in case grant could not be registered
*
* @default - the construct in which this construct is defined
*/
readonly scope?: IConstruct;
}
/**
* Options for a grant operation to both identity and resource
*
*/
export interface GrantOnPrincipalAndResourceOptions extends CommonGrantOptions {
/**
* The resource with a resource policy
*
* The statement will always be added to the resource policy.
*/
readonly resource: IResourceWithPolicy;
/**
* When referring to the resource in a resource policy, use this as ARN.
*
* (Depending on the resource type, this needs to be '*' in a resource policy).
*
* @default Same as regular resource ARNs
*/
readonly resourceSelfArns?: string[];
/**
* The principal to use in the statement for the resource policy.
*
* @default - the principal of the grantee will be used
*/
readonly resourcePolicyPrincipal?: IPrincipal;
}
/**
* Result of a grant() operation
*
* This class is not instantiable by consumers on purpose, so that they will be
* required to call the Grant factory functions.
*/
export class Grant implements IDependable {
/**
* Grant the given permissions to the principal
*
* The permissions will be added to the principal policy primarily, falling
* back to the resource policy if necessary. The permissions must be granted
* somewhere.
*
* - Trying to grant permissions to a principal that does not admit adding to
* the principal policy while not providing a resource with a resource policy
* is an error.
* - Trying to grant permissions to an absent principal (possible in the
* case of imported resources) leads to a warning being added to the
* resource construct.
*/
public static addToPrincipalOrResource(options: GrantWithResourceOptions): Grant {
const result = Grant.addToPrincipal({
...options,
scope: options.resource,
});
const resourceAndPrincipalAccountComparison = options.grantee.grantPrincipal.principalAccount
? cdk.Token.compareStrings(options.resource.env.account, options.grantee.grantPrincipal.principalAccount)
: undefined;
// if both accounts are tokens, we assume here they are the same
const equalOrBothUnresolved = resourceAndPrincipalAccountComparison === cdk.TokenComparison.SAME
|| resourceAndPrincipalAccountComparison == cdk.TokenComparison.BOTH_UNRESOLVED;
const sameAccount: boolean = resourceAndPrincipalAccountComparison
? equalOrBothUnresolved
// if the principal doesn't have an account (for example, a service principal),
// we should modify the resource's trust policy
: false;
// If we added to the principal AND we're in the same account, then we're done.
// If not, it's a different account and we must also add a trust policy on the resource.
if (result.success && sameAccount) {
return result;
}
const statement = new PolicyStatement({
actions: options.actions,
resources: (options.resourceSelfArns || options.resourceArns),
principals: [options.grantee!.grantPrincipal],
});
const resourceResult = options.resource.addToResourcePolicy(statement);
return new Grant({
resourceStatement: statement,
options,
policyDependable: resourceResult.statementAdded ? resourceResult.policyDependable ?? options.resource : undefined,
});
}
/**
* Try to grant the given permissions to the given principal
*
* Absence of a principal leads to a warning, but failing to add
* the permissions to a present principal is not an error.
*/
public static addToPrincipal(options: GrantOnPrincipalOptions): Grant {
const statement = new PolicyStatement({
actions: options.actions,
resources: options.resourceArns,
conditions: options.conditions,
});
const addedToPrincipal = options.grantee.grantPrincipal.addToPrincipalPolicy(statement);
if (!addedToPrincipal.statementAdded) {
return new Grant({ principalStatement: undefined, options });
}
if (!addedToPrincipal.policyDependable) {
throw new Error('Contract violation: when Principal returns statementAdded=true, it should return a dependable');
}
return new Grant({ principalStatement: statement, options, policyDependable: addedToPrincipal.policyDependable });
}
/**
* Add a grant both on the principal and on the resource
*
* As long as any principal is given, granting on the principal may fail (in
* case of a non-identity principal), but granting on the resource will
* never fail.
*
* Statement will be the resource statement.
*/
public static addToPrincipalAndResource(options: GrantOnPrincipalAndResourceOptions): Grant {
const result = Grant.addToPrincipal({
...options,
scope: options.resource,
});
const statement = new PolicyStatement({
actions: options.actions,
resources: (options.resourceSelfArns || options.resourceArns),
principals: [options.resourcePolicyPrincipal || options.grantee!.grantPrincipal],
});
const resourceResult = options.resource.addToResourcePolicy(statement);
const resourceDependable = resourceResult.statementAdded ? resourceResult.policyDependable ?? options.resource : undefined;
return new Grant({
principalStatement: statement,
resourceStatement: result.resourceStatement,
options,
policyDependable: resourceDependable ? new CompositeDependable(result, resourceDependable) : result,
});
}
/**
* Returns a "no-op" `Grant` object which represents a "dropped grant".
*
* This can be used for e.g. imported resources where you may not be able to modify
* the resource's policy or some underlying policy which you don't know about.
*
* @param grantee The intended grantee
* @param _intent The user's intent (will be ignored at the moment)
*/
public static drop(grantee: IGrantable, _intent: string): Grant {
return new Grant({
options: { grantee, actions: [], resourceArns: [] },
});
}
/**
* The statement that was added to the principal's policy
*
* @deprecated Use `principalStatements` instead
*/
public readonly principalStatement?: PolicyStatement;
/**
* The statements that were added to the principal's policy
*/
public readonly principalStatements = new Array<PolicyStatement>();
/**
* The statement that was added to the resource policy
*
* @deprecated Use `resourceStatements` instead
*/
public readonly resourceStatement?: PolicyStatement;
/**
* The statements that were added to the principal's policy
*/
public readonly resourceStatements = new Array<PolicyStatement>();
/**
* The options originally used to set this result
*
* Private member doubles as a way to make it impossible for an object literal to
* be structurally the same as this class.
*/
private readonly options: CommonGrantOptions;
private readonly dependables = new Array<IDependable>();
private constructor(props: GrantProps) {
this.options = props.options;
this.principalStatement = props.principalStatement;
this.resourceStatement = props.resourceStatement;
if (this.principalStatement) {
this.principalStatements.push(this.principalStatement);
}
if (this.resourceStatement) {
this.resourceStatements.push(this.resourceStatement);
}
if (props.policyDependable) {
this.dependables.push(props.policyDependable);
}
const self = this;
Dependable.implement(this, {
get dependencyRoots() {
return Array.from(new Set(self.dependables.flatMap(d => Dependable.of(d).dependencyRoots)));
},
});
}
/**
* Whether the grant operation was successful
*/
public get success(): boolean {
return this.principalStatement !== undefined || this.resourceStatement !== undefined;
}
/**
* Throw an error if this grant wasn't successful
*/
public assertSuccess(): void {
if (!this.success) {
// eslint-disable-next-line max-len
throw new Error(`${describeGrant(this.options)} could not be added on either identity or resource policy.`);
}
}
/**
* Make sure this grant is applied before the given constructs are deployed
*
* The same as construct.node.addDependency(grant), but slightly nicer to read.
*/
public applyBefore(...constructs: IConstruct[]) {
for (const construct of constructs) {
construct.node.addDependency(this);
}
}
/**
* Combine two grants into a new one
*/
public combine(rhs: Grant) {
const combinedPrinc = [...this.principalStatements, ...rhs.principalStatements];
const combinedRes = [...this.resourceStatements, ...rhs.resourceStatements];
const ret = new Grant({
options: this.options,
principalStatement: combinedPrinc[0],
resourceStatement: combinedRes[0],
});
ret.principalStatements.splice(0, ret.principalStatements.length, ...combinedPrinc);
ret.resourceStatements.splice(0, ret.resourceStatements.length, ...combinedRes);
ret.dependables.push(...this.dependables, ...rhs.dependables);
return ret;
}
}
function describeGrant(options: CommonGrantOptions) {
return `Permissions for '${options.grantee}' to call '${options.actions}' on '${options.resourceArns}'`;
}
interface GrantProps {
readonly options: CommonGrantOptions;
readonly principalStatement?: PolicyStatement;
readonly resourceStatement?: PolicyStatement;
/**
* Constructs whose deployment applies the grant
*
* Used to add dependencies on grants
*/
readonly policyDependable?: IDependable;
}
/**
* A resource with a resource policy that can be added to
*/
export interface IResourceWithPolicy extends cdk.IResource {
/**
* Add a statement to the resource's resource policy
*/
addToResourcePolicy(statement: PolicyStatement): AddToResourcePolicyResult;
}
/**
* Result of calling addToResourcePolicy
*/
export interface AddToResourcePolicyResult {
/**
* Whether the statement was added
*/
readonly statementAdded: boolean;
/**
* Dependable which allows depending on the policy change being applied
*
* @default - If `statementAdded` is true, the resource object itself.
* Otherwise, no dependable.
*/
readonly policyDependable?: IDependable;
}
/**
* Composite dependable
*
* Not as simple as eagerly getting the dependency roots from the
* inner dependables, as they may be mutable so we need to defer
* the query.
*/
export class CompositeDependable implements IDependable {
constructor(...dependables: IDependable[]) {
Dependable.implement(this, {
get dependencyRoots(): IConstruct[] {
return Array.prototype.concat.apply([], dependables.map(d => Dependable.of(d).dependencyRoots));
},
});
}
}