forked from aws/aws-cdk
/
pipeline-actions.test.ts
468 lines (416 loc) · 17.6 KB
/
pipeline-actions.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
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
import '@aws-cdk/assert-internal/jest';
import * as codepipeline from '@aws-cdk/aws-codepipeline';
import * as notifications from '@aws-cdk/aws-codestarnotifications';
import * as events from '@aws-cdk/aws-events';
import * as iam from '@aws-cdk/aws-iam';
import * as s3 from '@aws-cdk/aws-s3';
import * as cdk from '@aws-cdk/core';
import * as constructs from 'constructs';
import * as _ from 'lodash';
import * as cpactions from '../../lib';
describe('Pipeline Actions', () => {
describe('CreateReplaceChangeSet', () => {
test('works', (done) => {
const app = new cdk.App();
const stack = new cdk.Stack(app, 'Stack');
const pipelineRole = new RoleDouble(stack, 'PipelineRole');
const artifact = new codepipeline.Artifact('TestArtifact');
const action = new cpactions.CloudFormationCreateReplaceChangeSetAction({
actionName: 'Action',
changeSetName: 'MyChangeSet',
stackName: 'MyStack',
templatePath: artifact.atPath('path/to/file'),
adminPermissions: false,
});
const stage = new StageDouble({
pipeline: new PipelineDouble(stack, 'Pipeline', { role: pipelineRole }),
actions: [action],
});
app.synth();
_assertPermissionGranted(done, stack, pipelineRole.statements, 'iam:PassRole', action.deploymentRole.roleArn);
const stackArn = _stackArn('MyStack', stack);
const changeSetCondition = { StringEqualsIfExists: { 'cloudformation:ChangeSetName': 'MyChangeSet' } };
_assertPermissionGranted(done, stack, pipelineRole.statements, 'cloudformation:DescribeStacks', stackArn, changeSetCondition);
_assertPermissionGranted(done, stack, pipelineRole.statements, 'cloudformation:DescribeChangeSet', stackArn, changeSetCondition);
_assertPermissionGranted(done, stack, pipelineRole.statements, 'cloudformation:CreateChangeSet', stackArn, changeSetCondition);
_assertPermissionGranted(done, stack, pipelineRole.statements, 'cloudformation:DeleteChangeSet', stackArn, changeSetCondition);
// TODO: revert "as any" once we move all actions into a single package.
expect(stage.fullActions[0].actionProperties.inputs).toEqual([artifact]);
_assertActionMatches(done, stack, stage.fullActions, 'CloudFormation', 'Deploy', {
ActionMode: 'CHANGE_SET_CREATE_REPLACE',
StackName: 'MyStack',
ChangeSetName: 'MyChangeSet',
});
done();
});
test('uses a single permission statement if the same ChangeSet name is used', () => {
const stack = new cdk.Stack();
const pipelineRole = new RoleDouble(stack, 'PipelineRole');
const artifact = new codepipeline.Artifact('TestArtifact');
new StageDouble({
pipeline: new PipelineDouble(stack, 'Pipeline', { role: pipelineRole }),
actions: [
new cpactions.CloudFormationCreateReplaceChangeSetAction({
actionName: 'ActionA',
changeSetName: 'MyChangeSet',
stackName: 'StackA',
adminPermissions: false,
templatePath: artifact.atPath('path/to/file'),
}),
new cpactions.CloudFormationCreateReplaceChangeSetAction({
actionName: 'ActionB',
changeSetName: 'MyChangeSet',
stackName: 'StackB',
adminPermissions: false,
templatePath: artifact.atPath('path/to/other/file'),
}),
],
});
expect(
stack.resolve(pipelineRole.statements.map(s => s.toStatementJson())),
).toEqual(
[
{
Action: 'iam:PassRole',
Effect: 'Allow',
Resource: [
{ 'Fn::GetAtt': ['PipelineTestStageActionARole9283FBE3', 'Arn'] },
{ 'Fn::GetAtt': ['PipelineTestStageActionBRoleCABC8FA5', 'Arn'] },
],
},
{
Action: [
'cloudformation:CreateChangeSet',
'cloudformation:DeleteChangeSet',
'cloudformation:DescribeChangeSet',
'cloudformation:DescribeStacks',
],
Condition: { StringEqualsIfExists: { 'cloudformation:ChangeSetName': 'MyChangeSet' } },
Effect: 'Allow',
Resource: [
// eslint-disable-next-line max-len
{ 'Fn::Join': ['', ['arn:', { Ref: 'AWS::Partition' }, ':cloudformation:', { Ref: 'AWS::Region' }, ':', { Ref: 'AWS::AccountId' }, ':stack/StackA/*']] },
// eslint-disable-next-line max-len
{ 'Fn::Join': ['', ['arn:', { Ref: 'AWS::Partition' }, ':cloudformation:', { Ref: 'AWS::Region' }, ':', { Ref: 'AWS::AccountId' }, ':stack/StackB/*']] },
],
},
],
);
});
});
describe('ExecuteChangeSet', () => {
test('works', (done) => {
const stack = new cdk.Stack();
const pipelineRole = new RoleDouble(stack, 'PipelineRole');
const stage = new StageDouble({
pipeline: new PipelineDouble(stack, 'Pipeline', { role: pipelineRole }),
actions: [
new cpactions.CloudFormationExecuteChangeSetAction({
actionName: 'Action',
changeSetName: 'MyChangeSet',
stackName: 'MyStack',
}),
],
});
const stackArn = _stackArn('MyStack', stack);
_assertPermissionGranted(done, stack, pipelineRole.statements, 'cloudformation:ExecuteChangeSet', stackArn,
{ StringEqualsIfExists: { 'cloudformation:ChangeSetName': 'MyChangeSet' } });
_assertActionMatches(done, stack, stage.fullActions, 'CloudFormation', 'Deploy', {
ActionMode: 'CHANGE_SET_EXECUTE',
StackName: 'MyStack',
ChangeSetName: 'MyChangeSet',
});
done();
});
test('uses a single permission statement if the same ChangeSet name is used', () => {
const stack = new cdk.Stack();
const pipelineRole = new RoleDouble(stack, 'PipelineRole');
new StageDouble({
pipeline: new PipelineDouble(stack, 'Pipeline', { role: pipelineRole }),
actions: [
new cpactions.CloudFormationExecuteChangeSetAction({
actionName: 'ActionA',
changeSetName: 'MyChangeSet',
stackName: 'StackA',
}),
new cpactions.CloudFormationExecuteChangeSetAction({
actionName: 'ActionB',
changeSetName: 'MyChangeSet',
stackName: 'StackB',
}),
],
});
expect(
stack.resolve(pipelineRole.statements.map(s => s.toStatementJson())),
).toEqual(
[
{
Action: [
'cloudformation:DescribeChangeSet',
'cloudformation:DescribeStacks',
'cloudformation:ExecuteChangeSet',
],
Condition: { StringEqualsIfExists: { 'cloudformation:ChangeSetName': 'MyChangeSet' } },
Effect: 'Allow',
Resource: [
// eslint-disable-next-line max-len
{ 'Fn::Join': ['', ['arn:', { Ref: 'AWS::Partition' }, ':cloudformation:', { Ref: 'AWS::Region' }, ':', { Ref: 'AWS::AccountId' }, ':stack/StackA/*']] },
// eslint-disable-next-line max-len
{ 'Fn::Join': ['', ['arn:', { Ref: 'AWS::Partition' }, ':cloudformation:', { Ref: 'AWS::Region' }, ':', { Ref: 'AWS::AccountId' }, ':stack/StackB/*']] },
],
},
],
);
});
});
test('the CreateUpdateStack Action sets the DescribeStack*, Create/Update/DeleteStack & PassRole permissions', (done) => {
const stack = new cdk.Stack();
const pipelineRole = new RoleDouble(stack, 'PipelineRole');
const action = new cpactions.CloudFormationCreateUpdateStackAction({
actionName: 'Action',
templatePath: new codepipeline.Artifact('TestArtifact').atPath('some/file'),
stackName: 'MyStack',
adminPermissions: false,
replaceOnFailure: true,
});
new StageDouble({
pipeline: new PipelineDouble(stack, 'Pipeline', { role: pipelineRole }),
actions: [action],
});
const stackArn = _stackArn('MyStack', stack);
_assertPermissionGranted(done, stack, pipelineRole.statements, 'cloudformation:DescribeStack*', stackArn);
_assertPermissionGranted(done, stack, pipelineRole.statements, 'cloudformation:CreateStack', stackArn);
_assertPermissionGranted(done, stack, pipelineRole.statements, 'cloudformation:UpdateStack', stackArn);
_assertPermissionGranted(done, stack, pipelineRole.statements, 'cloudformation:DeleteStack', stackArn);
_assertPermissionGranted(done, stack, pipelineRole.statements, 'iam:PassRole', action.deploymentRole.roleArn);
done();
});
test('the DeleteStack Action sets the DescribeStack*, DeleteStack & PassRole permissions', (done) => {
const stack = new cdk.Stack();
const pipelineRole = new RoleDouble(stack, 'PipelineRole');
const action = new cpactions.CloudFormationDeleteStackAction({
actionName: 'Action',
adminPermissions: false,
stackName: 'MyStack',
});
new StageDouble({
pipeline: new PipelineDouble(stack, 'Pipeline', { role: pipelineRole }),
actions: [action],
});
const stackArn = _stackArn('MyStack', stack);
_assertPermissionGranted(done, stack, pipelineRole.statements, 'cloudformation:DescribeStack*', stackArn);
_assertPermissionGranted(done, stack, pipelineRole.statements, 'cloudformation:DeleteStack', stackArn);
_assertPermissionGranted(done, stack, pipelineRole.statements, 'iam:PassRole', action.deploymentRole.roleArn);
done();
});
});
interface PolicyStatementJson {
Effect: 'Allow' | 'Deny';
Action: string | string[];
Resource: string | string[];
Condition: any;
}
function _assertActionMatches(
done: jest.DoneCallback,
stack: cdk.Stack,
actions: FullAction[],
provider: string,
category: string,
configuration?: { [key: string]: any }) {
const configurationStr = configuration
? `, configuration including ${JSON.stringify(stack.resolve(configuration), null, 2)}`
: '';
const actionsStr = JSON.stringify(actions.map(a =>
({
owner: a.actionProperties.owner,
provider: a.actionProperties.provider,
category: a.actionProperties.category,
configuration: stack.resolve(a.actionConfig.configuration),
}),
), null, 2);
if (!_hasAction(stack, actions, provider, category, configuration)) {
done.fail(`Expected to find an action with provider ${provider}, category ${category}${configurationStr}, but found ${actionsStr}`);
}
}
function _hasAction(
stack: cdk.Stack, actions: FullAction[], provider: string, category: string,
configuration?: { [key: string]: any}) {
for (const action of actions) {
if (action.actionProperties.provider !== provider) { continue; }
if (action.actionProperties.category !== category) { continue; }
if (configuration && !action.actionConfig.configuration) { continue; }
if (configuration) {
for (const key of Object.keys(configuration)) {
if (!_.isEqual(stack.resolve(action.actionConfig.configuration[key]), stack.resolve(configuration[key]))) {
continue;
}
}
}
return true;
}
return false;
}
function _assertPermissionGranted(
done: jest.DoneCallback,
stack: cdk.Stack,
statements: iam.PolicyStatement[],
action: string,
resource: string,
conditions?: any) {
const conditionStr = conditions
? ` with condition(s) ${JSON.stringify(stack.resolve(conditions))}`
: '';
const resolvedStatements = stack.resolve(statements.map(s => s.toStatementJson()));
const statementsStr = JSON.stringify(resolvedStatements, null, 2);
if (!_grantsPermission(stack, resolvedStatements, action, resource, conditions)) {
done.fail(`Expected to find a statement granting ${action} on ${JSON.stringify(stack.resolve(resource))}${conditionStr}, found:\n${statementsStr}`);
}
}
function _grantsPermission(stack: cdk.Stack, statements: PolicyStatementJson[], action: string, resource: string, conditions?: any) {
for (const statement of statements.filter(s => s.Effect === 'Allow')) {
if (!_isOrContains(stack, statement.Action, action)) { continue; }
if (!_isOrContains(stack, statement.Resource, resource)) { continue; }
if (conditions && !_isOrContains(stack, statement.Condition, conditions)) { continue; }
return true;
}
return false;
}
function _isOrContains(stack: cdk.Stack, entity: string | string[], value: string): boolean {
const resolvedValue = stack.resolve(value);
const resolvedEntity = stack.resolve(entity);
if (_.isEqual(resolvedEntity, resolvedValue)) { return true; }
if (!Array.isArray(resolvedEntity)) { return false; }
for (const tested of entity) {
if (_.isEqual(tested, resolvedValue)) { return true; }
}
return false;
}
function _stackArn(stackName: string, scope: constructs.IConstruct): string {
return cdk.Stack.of(scope).formatArn({
service: 'cloudformation',
resource: 'stack',
resourceName: `${stackName}/*`,
});
}
class PipelineDouble extends cdk.Resource implements codepipeline.IPipeline {
public readonly pipelineName: string;
public readonly pipelineArn: string;
public readonly role: iam.Role;
public readonly artifactBucket: s3.IBucket;
constructor(scope: constructs.Construct, id: string, { pipelineName, role }: { pipelineName?: string, role: iam.Role }) {
super(scope, id);
this.pipelineName = pipelineName || 'TestPipeline';
this.pipelineArn = cdk.Stack.of(this).formatArn({ service: 'codepipeline', resource: 'pipeline', resourceName: this.pipelineName });
this.role = role;
this.artifactBucket = new BucketDouble(scope, 'BucketDouble');
}
public onEvent(_id: string, _options: events.OnEventOptions): events.Rule {
throw new Error('Method not implemented.');
}
public onStateChange(_id: string, _options: events.OnEventOptions): events.Rule {
throw new Error('Method not implemented.');
}
public notifyOn(
_id: string,
_target: notifications.INotificationRuleTarget,
_options: codepipeline.PipelineNotifyOnOptions,
): notifications.NotificationRule {
throw new Error('Method not implemented.');
}
public notifyOnExecutionStateChange(
_id: string,
_target: notifications.INotificationRuleTarget,
_options?: notifications.NotificationRuleOptions,
): notifications.NotificationRule {
throw new Error('Method not implemented.');
}
public notifyOnAnyStageStateChange(
_id: string,
_target: notifications.INotificationRuleTarget,
_options?: notifications.NotificationRuleOptions,
): notifications.INotificationRule {
throw new Error('Method not implemented.');
}
public notifyOnAnyActionStateChange(
_id: string,
_target: notifications.INotificationRuleTarget,
_options?: notifications.NotificationRuleOptions,
): notifications.INotificationRule {
throw new Error('Method not implemented.');
}
public notifyOnAnyManualApprovalStateChange(
_id: string,
_target: notifications.INotificationRuleTarget,
_options?: notifications.NotificationRuleOptions,
): notifications.INotificationRule {
throw new Error('Method not implemented.');
}
public bindAsNotificationRuleSource(
_scope: constructs.Construct,
): notifications.NotificationRuleSourceConfig {
throw new Error('Method not implemented.');
}
}
class FullAction {
constructor(
readonly actionProperties: codepipeline.ActionProperties,
readonly actionConfig: codepipeline.ActionConfig) {
// empty
}
}
class StageDouble implements codepipeline.IStage {
public readonly stageName: string;
public readonly pipeline: codepipeline.IPipeline;
public readonly actions: codepipeline.IAction[] = [];
public readonly fullActions: FullAction[];
public get node(): cdk.ConstructNode {
throw new Error('StageDouble is not a real construct');
}
constructor({ name, pipeline, actions }: { name?: string, pipeline: PipelineDouble, actions: codepipeline.IAction[] }) {
this.stageName = name || 'TestStage';
this.pipeline = pipeline;
const stageParent = new cdk.Construct(pipeline, this.stageName);
const fullActions = new Array<FullAction>();
for (const action of actions) {
const actionParent = new cdk.Construct(stageParent, action.actionProperties.actionName);
fullActions.push(new FullAction(action.actionProperties, action.bind(actionParent, this, {
role: pipeline.role,
bucket: pipeline.artifactBucket,
})));
}
this.fullActions = fullActions;
}
public addAction(_action: codepipeline.IAction): void {
throw new Error('addAction() is not supported on StageDouble');
}
public onStateChange(_name: string, _target?: events.IRuleTarget, _options?: events.RuleProps):
events.Rule {
throw new Error('onStateChange() is not supported on StageDouble');
}
}
class RoleDouble extends iam.Role {
public readonly statements = new Array<iam.PolicyStatement>();
constructor(scope: constructs.Construct, id: string, props: iam.RoleProps = { assumedBy: new iam.ServicePrincipal('test') }) {
super(scope, id, props);
}
public addToPolicy(statement: iam.PolicyStatement): boolean {
this.addToPrincipalPolicy(statement);
return true;
}
public addToPrincipalPolicy(statement: iam.PolicyStatement): iam.AddToPrincipalPolicyResult {
const ret = super.addToPrincipalPolicy(statement);
this.statements.push(statement);
return ret;
}
}
class BucketDouble extends s3.Bucket {
public grantRead(identity: iam.IGrantable, _objectsKeyPattern: any = '*'): iam.Grant {
return iam.Grant.drop(identity, '');
}
public grantWrite(identity: iam.IGrantable, _objectsKeyPattern: any = '*'): iam.Grant {
return iam.Grant.drop(identity, '');
}
public grantReadWrite(identity: iam.IGrantable, _objectsKeyPattern: any = '*'): iam.Grant {
return iam.Grant.drop(identity, '');
}
}