/
policy-document.ts
226 lines (198 loc) · 6.42 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
import * as cdk from '@aws-cdk/core';
import * as cxapi from '@aws-cdk/cx-api';
import { PolicyStatement } from './policy-statement';
import { mergeStatements } from './private/merge-statements';
/**
* Properties for a new PolicyDocument
*/
export interface PolicyDocumentProps {
/**
* Automatically assign Statement Ids to all statements
*
* @default false
*/
readonly assignSids?: boolean;
/**
* Initial statements to add to the policy document
*
* @default - No statements
*/
readonly statements?: PolicyStatement[];
/**
* Try to minimize the policy by merging statements
*
* To avoid overrunning the maximum policy size, combine statements if they produce
* the same result. Merging happens according to the following rules:
*
* - The Effect of both statements is the same
* - Neither of the statements have a 'Sid'
* - Combine Principals if the rest of the statement is exactly the same.
* - Combine Resources if the rest of the statement is exactly the same.
* - Combine Actions if the rest of the statement is exactly the same.
* - We will never combine NotPrincipals, NotResources or NotActions.
*
* @default false, unless the feature flag `@aws-cdk/aws-iam:minimizePolicies` is set
*/
readonly minimize?: boolean;
}
/**
* A PolicyDocument is a collection of statements
*/
export class PolicyDocument implements cdk.IResolvable {
/**
* Creates a new PolicyDocument based on the object provided.
* This will accept an object created from the `.toJSON()` call
* @param obj the PolicyDocument in object form.
*/
public static fromJson(obj: any): PolicyDocument {
const newPolicyDocument = new PolicyDocument();
const statement = obj.Statement ?? [];
if (statement && !Array.isArray(statement)) {
throw new Error('Statement must be an array');
}
newPolicyDocument.addStatements(...obj.Statement.map((s: any) => PolicyStatement.fromJson(s)));
return newPolicyDocument;
}
public readonly creationStack: string[];
private readonly statements = new Array<PolicyStatement>();
private readonly autoAssignSids: boolean;
private readonly minimize?: boolean;
constructor(props: PolicyDocumentProps = {}) {
this.creationStack = cdk.captureStackTrace();
this.autoAssignSids = !!props.assignSids;
this.minimize = props.minimize;
this.addStatements(...props.statements || []);
}
public resolve(context: cdk.IResolveContext): any {
context.registerPostProcessor(new ReducePolicyDocument(
this.autoAssignSids,
this.minimize ?? cdk.FeatureFlags.of(context.scope).isEnabled(cxapi.IAM_MINIMIZE_POLICIES) ?? false,
));
return this.render();
}
/**
* Whether the policy document contains any statements.
*/
public get isEmpty(): boolean {
return this.statements.length === 0;
}
/**
* The number of statements already added to this policy.
* Can be used, for example, to generate unique "sid"s within the policy.
*/
public get statementCount(): number {
return this.statements.length;
}
/**
* Adds a statement to the policy document.
*
* @param statement the statement to add.
*/
public addStatements(...statement: PolicyStatement[]) {
this.statements.push(...statement);
}
/**
* Encode the policy document as a string
*/
public toString() {
return cdk.Token.asString(this, {
displayHint: 'PolicyDocument',
});
}
/**
* JSON-ify the document
*
* Used when JSON.stringify() is called
*/
public toJSON() {
return this.render();
}
/**
* Validate that all policy statements in the policy document satisfies the
* requirements for any policy.
*
* @see https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#access_policies-json
*/
public validateForAnyPolicy(): string[] {
const errors = new Array<string>();
for (const statement of this.statements) {
errors.push(...statement.validateForAnyPolicy());
}
return errors;
}
/**
* Validate that all policy statements in the policy document satisfies the
* requirements for a resource-based policy.
*
* @see https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#access_policies-json
*/
public validateForResourcePolicy(): string[] {
const errors = new Array<string>();
for (const statement of this.statements) {
errors.push(...statement.validateForResourcePolicy());
}
return errors;
}
/**
* Validate that all policy statements in the policy document satisfies the
* requirements for an identity-based policy.
*
* @see https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#access_policies-json
*/
public validateForIdentityPolicy(): string[] {
const errors = new Array<string>();
for (const statement of this.statements) {
errors.push(...statement.validateForIdentityPolicy());
}
return errors;
}
private render(): any {
if (this.isEmpty) {
return undefined;
}
const doc = {
Statement: this.statements.map(s => s.toStatementJson()),
Version: '2012-10-17',
};
return doc;
}
}
/**
* Removes duplicate statements and assign Sids if necessary
*/
class ReducePolicyDocument implements cdk.IPostProcessor {
constructor(private readonly autoAssignSids: boolean, private readonly minimize: boolean) {
}
public postProcess(input: any, _context: cdk.IResolveContext): any {
if (!input || !input.Statement) {
return input;
}
if (this.minimize) {
input.Statement = mergeStatements(input.Statement);
}
// Also remove full-on duplicates (this will not be necessary if
// we minimized, but it might still dedupe statements we didn't
// minimize like 'Deny' statements, and definitely is still necessary
// if we didn't minimize)
const jsonStatements = new Set<string>();
const uniqueStatements: any[] = [];
for (const statement of input.Statement) {
const jsonStatement = JSON.stringify(statement);
if (!jsonStatements.has(jsonStatement)) {
uniqueStatements.push(statement);
jsonStatements.add(jsonStatement);
}
}
// assign unique SIDs (the statement index) if `autoAssignSids` is enabled
const statements = uniqueStatements.map((s, i) => {
if (this.autoAssignSids && !s.Sid) {
s.Sid = i.toString();
}
return s;
});
return {
...input,
Statement: statements,
};
}
}