forked from aws-amplify/amplify-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
/
iam_access_drift.test.ts
398 lines (365 loc) · 12.1 KB
/
iam_access_drift.test.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
import { after, before, describe, it } from 'node:test';
import { execa } from 'execa';
import path from 'path';
import { TestBranch, amplifyAppPool } from '../amplify_app_pool.js';
import { BackendIdentifier } from '@aws-amplify/plugin-types';
import {
AccessAnalyzerClient,
AccessCheckPolicyType,
CheckNoNewAccessCommand,
CheckNoNewAccessCommandOutput,
} from '@aws-sdk/client-accessanalyzer';
import {
CloudFormationClient,
DeleteStackCommand,
} from '@aws-sdk/client-cloudformation';
import {
GetPolicyCommand,
GetPolicyCommandOutput,
GetPolicyVersionCommand,
GetPolicyVersionCommandOutput,
GetRoleCommand,
GetRoleCommandOutput,
GetRolePolicyCommand,
GetRolePolicyCommandOutput,
IAMClient,
ListRolePoliciesCommand,
ListRolePoliciesCommandOutput,
} from '@aws-sdk/client-iam';
import fsp from 'fs/promises';
import { e2eToolingClientConfig } from '../e2e_tooling_client_config.js';
import { DeployedResourcesFinder } from '../find_deployed_resource.js';
import { NpmProxyController } from '../npm_proxy_controller.js';
import assert from 'assert';
import os from 'os';
import { BackendIdentifierConversions } from '@aws-amplify/platform-core';
import { amplifyAtTag } from '../constants.js';
void describe('iam access drift', () => {
let branchBackendIdentifier: BackendIdentifier;
let testBranch: TestBranch;
let cfnClient: CloudFormationClient;
let iamClient: IAMClient;
let accessAnalyzerClient: AccessAnalyzerClient;
let tempDir: string;
let baselineDir: string;
let deployedResourcesFinder: DeployedResourcesFinder;
let baselineNpmProxyController: NpmProxyController;
let currentNpmProxyController: NpmProxyController;
before(async () => {
assert.ok(
process.env.BASELINE_DIR,
'BASELINE_DIR environment variable must be set and point to amplify-backend repo at baseline version'
);
baselineDir = process.env.BASELINE_DIR;
tempDir = await fsp.mkdtemp(
path.join(os.tmpdir(), 'test-iam-access-drift')
);
iamClient = new IAMClient(e2eToolingClientConfig);
cfnClient = new CloudFormationClient(e2eToolingClientConfig);
accessAnalyzerClient = new AccessAnalyzerClient(e2eToolingClientConfig);
deployedResourcesFinder = new DeployedResourcesFinder(cfnClient);
baselineNpmProxyController = new NpmProxyController(baselineDir);
currentNpmProxyController = new NpmProxyController();
testBranch = await amplifyAppPool.createTestBranch();
branchBackendIdentifier = {
namespace: testBranch.appId,
name: testBranch.branchName,
type: 'branch',
};
});
after(async () => {
await cfnClient.send(
new DeleteStackCommand({
StackName: BackendIdentifierConversions.toStackName(
branchBackendIdentifier
),
})
);
await fsp.rm(tempDir, { recursive: true });
await baselineNpmProxyController.tearDown();
await currentNpmProxyController.tearDown();
});
const deploy = async (): Promise<void> => {
await execa(
'npx',
[
'ampx',
'pipeline-deploy',
'--branch',
branchBackendIdentifier.name,
'--appId',
branchBackendIdentifier.namespace,
],
{
cwd: tempDir,
stdio: 'inherit',
env: {
CI: 'true',
},
}
);
};
type ManagedIamPolicy = {
policyArn: string;
policyStatement: string;
};
type RoleTrustPolicy = {
roleName: string;
policyStatement: string;
};
type RoleInlinePolicy = {
roleName: string;
policyName: string;
policyStatement: string;
};
type PolicyComparisonParams = {
baselinePolicy?: ManagedIamPolicy | RoleTrustPolicy | RoleInlinePolicy;
currentPolicy?: ManagedIamPolicy | RoleTrustPolicy | RoleInlinePolicy;
policyType: AccessCheckPolicyType;
};
type PolicyComparisonResult = {
baselinePolicy:
| ManagedIamPolicy
| RoleTrustPolicy
| RoleInlinePolicy
| undefined;
currentPolicy:
| ManagedIamPolicy
| RoleTrustPolicy
| RoleInlinePolicy
| undefined;
comparisonResult: Omit<CheckNoNewAccessCommandOutput, '$metadata'>;
};
const listManagedIamPolicies = async (): Promise<Array<ManagedIamPolicy>> => {
const policies: Array<ManagedIamPolicy> = [];
const policyArns = await deployedResourcesFinder.findByBackendIdentifier(
branchBackendIdentifier,
'AWS::IAM::ManagedPolicy'
);
for (const policyArn of policyArns) {
const getPolicyResponse: GetPolicyCommandOutput = await iamClient.send(
new GetPolicyCommand({
PolicyArn: policyArn,
})
);
const getPolicyVersionResponse: GetPolicyVersionCommandOutput =
await iamClient.send(
new GetPolicyVersionCommand({
PolicyArn: policyArn,
VersionId: getPolicyResponse.Policy?.DefaultVersionId,
})
);
if (getPolicyVersionResponse.PolicyVersion?.Document) {
policies.push({
policyArn,
policyStatement: decodeURIComponent(
getPolicyVersionResponse.PolicyVersion.Document
),
});
}
}
return policies;
};
const listRoleTrustPolicies = async (): Promise<Array<RoleTrustPolicy>> => {
const policies: Array<RoleTrustPolicy> = [];
const roleNames = await deployedResourcesFinder.findByBackendIdentifier(
branchBackendIdentifier,
'AWS::IAM::Role'
);
for (const roleName of roleNames) {
const getRoleResponse: GetRoleCommandOutput = await iamClient.send(
new GetRoleCommand({
RoleName: roleName,
})
);
if (getRoleResponse.Role?.AssumeRolePolicyDocument) {
policies.push({
roleName,
policyStatement: decodeURIComponent(
getRoleResponse.Role.AssumeRolePolicyDocument
),
});
}
}
return policies;
};
const listRoleInlinePolicies = async (): Promise<Array<RoleInlinePolicy>> => {
const policies: Array<RoleInlinePolicy> = [];
const roleNames = await deployedResourcesFinder.findByBackendIdentifier(
branchBackendIdentifier,
'AWS::IAM::Role'
);
for (const roleName of roleNames) {
let nextToken: string | undefined;
do {
const listRolePoliciesResponse: ListRolePoliciesCommandOutput =
await iamClient.send(
new ListRolePoliciesCommand({
RoleName: roleName,
Marker: nextToken,
})
);
nextToken = listRolePoliciesResponse.Marker;
if (listRolePoliciesResponse.PolicyNames) {
for (const policyName of listRolePoliciesResponse.PolicyNames) {
const getRolePolicyResponse: GetRolePolicyCommandOutput =
await iamClient.send(
new GetRolePolicyCommand({
RoleName: roleName,
PolicyName: policyName,
})
);
if (getRolePolicyResponse.PolicyDocument) {
policies.push({
roleName,
policyName,
policyStatement: decodeURIComponent(
getRolePolicyResponse.PolicyDocument
),
});
}
}
}
} while (nextToken);
}
return policies;
};
const reinstallDependencies = async (): Promise<void> => {
await fsp.rm(path.join(tempDir, 'node_modules'), {
recursive: true,
force: true,
});
await fsp.unlink(path.join(tempDir, 'package-lock.json'));
await execa('npm', ['install'], {
cwd: tempDir,
stdio: 'inherit',
});
};
const comparePolicy = async (
policyComparisonParams: PolicyComparisonParams
): Promise<Omit<CheckNoNewAccessCommandOutput, '$metadata'>> => {
if (
!policyComparisonParams.baselinePolicy &&
!policyComparisonParams.currentPolicy
) {
throw new Error('Neither baseline nor current policy has been provided');
}
if (!policyComparisonParams.baselinePolicy) {
return {
message:
'A new policy was added to sample application when using new version of packages',
result: 'FAIL',
};
}
if (!policyComparisonParams.currentPolicy) {
return {
message:
'A new policy was removed from sample application when using new version of packages',
result: 'FAIL',
};
}
return await accessAnalyzerClient.send(
new CheckNoNewAccessCommand({
existingPolicyDocument:
policyComparisonParams.baselinePolicy.policyStatement,
newPolicyDocument: policyComparisonParams.currentPolicy.policyStatement,
policyType: policyComparisonParams.policyType,
})
);
};
const matchBaselineAndCurrentPolicies = <
T extends ManagedIamPolicy | RoleTrustPolicy | RoleInlinePolicy
>(
baselinePolicies: Array<T>,
currentPolicies: Array<T>,
uniqueKeyProvider: (policy: T) => string,
policyType: AccessCheckPolicyType
): IterableIterator<PolicyComparisonParams> => {
const policyComparisonParamsMap = new Map<string, PolicyComparisonParams>();
baselinePolicies.forEach((policy) => {
const key = uniqueKeyProvider(policy);
let policyComparisonParams = policyComparisonParamsMap.get(key);
if (!policyComparisonParams) {
policyComparisonParams = {
policyType,
};
policyComparisonParamsMap.set(key, policyComparisonParams);
}
policyComparisonParams.baselinePolicy = policy;
});
currentPolicies.forEach((policy) => {
const key = uniqueKeyProvider(policy);
let policyComparisonParams = policyComparisonParamsMap.get(key);
if (!policyComparisonParams) {
policyComparisonParams = {
policyType,
};
policyComparisonParamsMap.set(key, policyComparisonParams);
}
policyComparisonParams.currentPolicy = policy;
});
return policyComparisonParamsMap.values();
};
void it('should not drift iam policies', async () => {
await baselineNpmProxyController.setUp();
await execa('npm', ['create', amplifyAtTag, '--yes'], {
cwd: tempDir,
stdio: 'inherit',
});
await deploy();
const baselineManagedIamPolicies = await listManagedIamPolicies();
const baselineRoleTrustPolicies = await listRoleTrustPolicies();
const baselineRoleInlinePolicies = await listRoleInlinePolicies();
await baselineNpmProxyController.tearDown();
await currentNpmProxyController.setUp();
await reinstallDependencies();
await deploy();
const currentManagedIamPolicies = await listManagedIamPolicies();
const currentRoleTrustPolicies = await listRoleTrustPolicies();
const currentRoleInlinePolicies = await listRoleInlinePolicies();
const allPolicyComparisonParams: Array<PolicyComparisonParams> = [];
allPolicyComparisonParams.push(
...matchBaselineAndCurrentPolicies(
baselineManagedIamPolicies,
currentManagedIamPolicies,
(policy) => policy.policyArn,
'IDENTITY_POLICY'
)
);
allPolicyComparisonParams.push(
...matchBaselineAndCurrentPolicies(
baselineRoleTrustPolicies,
currentRoleTrustPolicies,
(policy) => policy.roleName,
'RESOURCE_POLICY'
)
);
allPolicyComparisonParams.push(
...matchBaselineAndCurrentPolicies(
baselineRoleInlinePolicies,
currentRoleInlinePolicies,
(policy) => `${policy.roleName}-${policy.policyName}`,
'IDENTITY_POLICY'
)
);
const comparisonResults: Array<PolicyComparisonResult> = [];
for (const policyComparisonParams of allPolicyComparisonParams) {
comparisonResults.push({
baselinePolicy: policyComparisonParams.baselinePolicy,
currentPolicy: policyComparisonParams.currentPolicy,
comparisonResult: await comparePolicy(policyComparisonParams),
});
}
const policiesWithNewAccess = comparisonResults.filter(
(result) => result.comparisonResult.result === 'FAIL'
);
assert.strictEqual(
policiesWithNewAccess.length,
0,
`
One of policies gained new access. Review the following results:
${JSON.stringify(policiesWithNewAccess, null, 2)}
`
);
});
});