-
Notifications
You must be signed in to change notification settings - Fork 4k
/
Copy pathpolicy-statement.ts
340 lines (290 loc) · 8.83 KB
/
policy-statement.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
import * as cdk from '@aws-cdk/core';
import { AccountPrincipal, AccountRootPrincipal, Anyone, ArnPrincipal, CanonicalUserPrincipal,
FederatedPrincipal, IPrincipal, ServicePrincipal, ServicePrincipalOpts } from './principals';
import { mergePrincipal } from './util';
/**
* Represents a statement in an IAM policy document.
*/
export class PolicyStatement {
/**
* Statement ID for this statement
*/
public sid?: string;
public effect: Effect;
private readonly action = new Array<any>();
private readonly notAction = new Array<any>();
private readonly principal: { [key: string]: any[] } = {};
private readonly notPrincipal: { [key: string]: any[] } = {};
private readonly resource = new Array<any>();
private readonly notResource = new Array<any>();
private readonly condition: { [key: string]: any } = { };
constructor(props: PolicyStatementProps = {}) {
// Validate actions
for (const action of [...props.actions || [], ...props.notActions || []]) {
if (!/^(\*|[a-zA-Z0-9-]+:[a-zA-Z0-9*]+)$/.test(action)) {
throw new Error(`Action '${action}' is invalid. An action string consists of a service namespace, a colon, and the name of an action. Action names can include wildcards.`);
}
}
this.effect = props.effect || Effect.ALLOW;
this.addActions(...props.actions || []);
this.addNotActions(...props.notActions || []);
this.addPrincipals(...props.principals || []);
this.addNotPrincipals(...props.notPrincipals || []);
this.addResources(...props.resources || []);
this.addNotResources(...props.notResources || []);
if (props.conditions !== undefined) {
this.addConditions(props.conditions);
}
}
//
// Actions
//
public addActions(...actions: string[]) {
if (actions.length > 0 && this.notAction.length > 0) {
throw new Error(`Cannot add 'Actions' to policy statement if 'NotActions' have been added`);
}
this.action.push(...actions);
}
public addNotActions(...notActions: string[]) {
if (notActions.length > 0 && this.action.length > 0) {
throw new Error(`Cannot add 'NotActions' to policy statement if 'Actions' have been added`);
}
this.notAction.push(...notActions);
}
//
// Principal
//
/**
* Indicates if this permission has a "Principal" section.
*/
public get hasPrincipal() {
return Object.keys(this.principal).length > 0 || Object.keys(this.notPrincipal).length > 0;
}
public addPrincipals(...principals: IPrincipal[]) {
if (Object.keys(principals).length > 0 && Object.keys(this.notPrincipal).length > 0) {
throw new Error(`Cannot add 'Principals' to policy statement if 'NotPrincipals' have been added`);
}
for (const principal of principals) {
const fragment = principal.policyFragment;
mergePrincipal(this.principal, fragment.principalJson);
this.addConditions(fragment.conditions);
}
}
public addNotPrincipals(...notPrincipals: IPrincipal[]) {
if (Object.keys(notPrincipals).length > 0 && Object.keys(this.principal).length > 0) {
throw new Error(`Cannot add 'NotPrincipals' to policy statement if 'Principals' have been added`);
}
for (const notPrincipal of notPrincipals) {
const fragment = notPrincipal.policyFragment;
mergePrincipal(this.notPrincipal, fragment.principalJson);
this.addConditions(fragment.conditions);
}
}
public addAwsAccountPrincipal(accountId: string) {
this.addPrincipals(new AccountPrincipal(accountId));
}
public addArnPrincipal(arn: string) {
this.addPrincipals(new ArnPrincipal(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.addPrincipals(new ServicePrincipal(service, opts));
}
public addFederatedPrincipal(federated: any, conditions: {[key: string]: any}) {
this.addPrincipals(new FederatedPrincipal(federated, conditions));
}
public addAccountRootPrincipal() {
this.addPrincipals(new AccountRootPrincipal());
}
public addCanonicalUserPrincipal(canonicalUserId: string) {
this.addPrincipals(new CanonicalUserPrincipal(canonicalUserId));
}
public addAnyPrincipal() {
this.addPrincipals(new Anyone());
}
//
// Resources
//
public addResources(...arns: string[]) {
if (arns.length > 0 && this.notResource.length > 0) {
throw new Error(`Cannot add 'Resources' to policy statement if 'NotResources' have been added`);
}
this.resource.push(...arns);
}
public addNotResources(...arns: string[]) {
if (arns.length > 0 && this.resource.length > 0) {
throw new Error(`Cannot add 'NotResources' to policy statement if 'Resources' have been added`);
}
this.notResource.push(...arns);
}
/**
* Adds a ``"*"`` resource to this statement.
*/
public addAllResources() {
this.addResources('*');
}
/**
* Indicates if this permission as at least one resource associated with it.
*/
public get hasResource() {
return this.resource && this.resource.length > 0;
}
//
// Condition
//
/**
* Add a condition to the Policy
*/
public addCondition(key: string, value: any) {
this.condition[key] = value;
}
/**
* Add multiple conditions to the Policy
*/
public addConditions(conditions: {[key: string]: any}) {
Object.keys(conditions).map(key => {
this.addCondition(key, conditions[key]);
});
}
/**
* Add a condition that limits to a given account
*/
public addAccountCondition(accountId: string) {
this.addCondition('StringEquals', { 'sts:ExternalId': accountId });
}
public toStatementJson(): any {
return noUndef({
Action: _norm(this.action),
NotAction: _norm(this.notAction),
Condition: _norm(this.condition),
Effect: _norm(this.effect),
Principal: _normPrincipal(this.principal),
NotPrincipal: _normPrincipal(this.notPrincipal),
Resource: _norm(this.resource),
NotResource: _norm(this.notResource),
Sid: _norm(this.sid),
});
function _norm(values: any) {
if (typeof(values) === 'undefined') {
return undefined;
}
if (cdk.Token.isUnresolved(values)) {
return values;
}
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;
}
}
public toString() {
return cdk.Token.asString(this, {
displayHint: 'PolicyStatement'
});
}
/**
* JSON-ify the statement
*
* Used when JSON.stringify() is called
*/
public toJSON() {
return this.toStatementJson();
}
}
export enum Effect {
ALLOW = 'Allow',
DENY = 'Deny',
}
/**
* Interface for creating a policy statement
*/
export interface PolicyStatementProps {
/**
* List of actions to add to the statement
*
* @default - no actions
*/
readonly actions?: string[];
/**
* List of not actions to add to the statement
*
* @default - no not-actions
*/
readonly notActions?: string[];
/**
* List of principals to add to the statement
*
* @default - no principals
*/
readonly principals?: IPrincipal[];
/**
* List of not principals to add to the statement
*
* @default - no not principals
*/
readonly notPrincipals?: IPrincipal[];
/**
* Resource ARNs to add to the statement
*
* @default - no resources
*/
readonly resources?: string[];
/**
* NotResource ARNs to add to the statement
*
* @default - no not-resources
*/
readonly notResources?: string[];
/**
* Conditions to add to the statement
*
* @default - no condition
*/
readonly conditions?: {[key: string]: any};
/**
* Whether to allow or deny the actions in this statement
*
* @default - allow
*/
readonly effect?: Effect;
}
function noUndef(x: any): any {
const ret: any = {};
for (const [key, value] of Object.entries(x)) {
if (value !== undefined) {
ret[key] = value;
}
}
return ret;
}