-
Notifications
You must be signed in to change notification settings - Fork 218
Expand file tree
/
Copy pathcompileNotifications.test.js
More file actions
701 lines (603 loc) · 24.8 KB
/
compileNotifications.test.js
File metadata and controls
701 lines (603 loc) · 24.8 KB
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
'use strict';
const _ = require('lodash');
const expect = require('chai').expect;
const sinon = require('sinon');
const createServerless = require('../../test/createServerless');
const ServerlessStepFunctions = require('../..');
describe('#compileNotifications', () => {
let consoleLogSpy;
let serverless;
let serverlessStepFunctions;
beforeEach(() => {
consoleLogSpy = sinon.spy();
serverless = createServerless();
serverless.servicePath = true;
serverless.service.service = 'step-functions';
serverless.service.provider.compiledCloudFormationTemplate = { Resources: {} };
serverless.cli = { consoleLog: consoleLogSpy };
const options = {
stage: 'dev',
region: 'ap-northeast-1',
};
serverlessStepFunctions = new ServerlessStepFunctions(serverless, options);
});
const validateCloudWatchEvent = (resources, logicalId, status, targetsCount) => {
expect(resources).to.haveOwnProperty(logicalId);
const event = resources[logicalId];
expect(event.Type).to.equal('AWS::Events::Rule');
expect(event.Properties.EventPattern.source).to.deep.equal(['aws.states']);
expect(event.Properties.EventPattern.detail.status).to.deep.equal([status]);
expect(event.Properties.Targets).to.have.lengthOf(targetsCount);
for (const target of event.Properties.Targets) {
const isStringOrFn = _.isString(target.Arn)
|| (target.Arn.Ref && _.isString(target.Arn.Ref))
|| (target.Arn['Fn::GetAtt'] && _.isArray(target.Arn['Fn::GetAtt']));
expect(isStringOrFn).to.equal(true);
}
const sqsWithParam = event.Properties.Targets.find((t) => t.SqsParameters);
expect(sqsWithParam).to.not.equal(undefined);
const kinesisWithParam = event.Properties.Targets.find((t) => t.KinesisParameters);
expect(kinesisWithParam).to.not.equal(undefined);
};
const validateHasPermission = (iamRole, action, resource) => {
const policies = iamRole.Properties.Policies;
const matchedPolicy = policies.find((policy) => {
const statement = policy.PolicyDocument.Statement[0];
return statement.Action === action && _.isEqual(statement.Resource, resource);
});
expect(matchedPolicy).to.not.equal(
undefined,
`IAM Role is expected to have policy for [${action}] on [${resource}]`,
);
};
const validateHasSnsPolicy = (resources, topicArn) => {
const snsPolicies = _.values(resources).filter((resource) => resource.Type === 'AWS::SNS::TopicPolicy');
const matchedPolicy = snsPolicies.find((policy) => _.isEqual(
policy.Properties.Topics[0],
topicArn,
));
expect(matchedPolicy).to.not.equal(
undefined,
`SNS topic policy is missing for [${topicArn}]`,
);
};
const validateHasSqsPolicy = (resources, queueUrl) => {
const sqsPolicies = _.values(resources).filter((resource) => resource.Type === 'AWS::SQS::QueuePolicy');
const matchedPolicy = sqsPolicies.find((policy) => _.isEqual(
policy.Properties.Queues[0],
queueUrl,
));
expect(matchedPolicy).to.not.equal(
undefined,
`SQS queue policy is missing for [${queueUrl}]`,
);
};
const validateHasLambdaPermission = (resources, lambdaArn) => {
const lambdaPolicies = _.values(resources).filter((resource) => resource.Type === 'AWS::Lambda::Permission');
const matchedPolicy = lambdaPolicies.find((policy) => _.isEqual(
policy.Properties.FunctionName,
lambdaArn,
));
expect(matchedPolicy).to.not.equal(
undefined,
`Lambda permission is missing for [${lambdaArn}]`,
);
};
const genStateMachineWithTargets = (name, targets) => ({
id: name,
name,
definition: {
StartAt: 'A',
States: {
A: {
Type: 'Pass',
End: true,
},
},
},
notifications: {
ABORTED: targets,
FAILED: targets,
RUNNING: targets,
SUCCEEDED: targets,
TIMED_OUT: targets,
},
});
it('should generate CloudWatch Event Rules with string ARNs', () => {
const targets = [
{ sns: 'SNS_TOPIC_ARN' },
{ sqs: 'SQS_QUEUE_ARN' },
{ sqs: 'arn:aws:sqs:#{AWS::Region}:#{AWS::AccountId}:MyQueue' },
{ sqs: { arn: 'SQS_QUEUE_NESTED_ARN', messageGroupId: '12345' } },
{ lambda: 'LAMBDA_FUNCTION_ARN' },
{ kinesis: 'KINESIS_STREAM_ARN' },
{ kinesis: { arn: 'KINESIS_STREAM_NESTED_ARN', partitionKeyPath: '$.id' } },
{ firehose: 'FIREHOSE_STREAM_ARN' },
{ stepFunctions: 'STATE_MACHINE_ARN' },
];
serverless.service.stepFunctions = {
stateMachines: {
beta1: genStateMachineWithTargets('Beta1', targets),
beta2: genStateMachineWithTargets('Beta2', targets),
},
};
serverlessStepFunctions.compileNotifications();
const resources = serverlessStepFunctions.serverless.service
.provider.compiledCloudFormationTemplate.Resources;
const count = targets.length;
const validateCloudWatchEvents = (prefix) => {
validateCloudWatchEvent(resources, `${prefix}NotificationsABORTEDEventRule`, 'ABORTED', count);
validateCloudWatchEvent(resources, `${prefix}NotificationsFAILEDEventRule`, 'FAILED', count);
validateCloudWatchEvent(resources, `${prefix}NotificationsRUNNINGEventRule`, 'RUNNING', count);
validateCloudWatchEvent(resources, `${prefix}NotificationsSUCCEEDEDEventRule`, 'SUCCEEDED', count);
validateCloudWatchEvent(resources, `${prefix}NotificationsTIMEDOUTEventRule`, 'TIMED_OUT', count);
};
validateCloudWatchEvents('Beta1');
validateCloudWatchEvents('Beta2');
const validateIamRole = (iamRole) => {
// 4 targets (excluding sns, sqs, lambda), 5 event rules = 5 * 4 = 20 policies
expect(iamRole.Properties.Policies).to.have.lengthOf(20);
validateHasPermission(iamRole, 'kinesis:PutRecord', 'KINESIS_STREAM_ARN');
validateHasPermission(iamRole, 'kinesis:PutRecord', 'KINESIS_STREAM_NESTED_ARN');
validateHasPermission(iamRole, 'firehose:PutRecord', 'FIREHOSE_STREAM_ARN');
validateHasPermission(iamRole, 'states:StartExecution', 'STATE_MACHINE_ARN');
};
validateIamRole(resources.Beta1NotificationsIamRole);
validateIamRole(resources.Beta2NotificationsIamRole);
const toQueueUrl = (queueName) => ({
'Fn::Sub': [
'https://sqs.${AWS::Region}.amazonaws.com/${AWS::AccountId}/${QueueName}',
{ QueueName: queueName },
],
});
validateHasSnsPolicy(resources, 'SNS_TOPIC_ARN');
validateHasSqsPolicy(resources, toQueueUrl('SQS_QUEUE_ARN'));
validateHasSqsPolicy(resources, toQueueUrl('MyQueue'));
validateHasSqsPolicy(resources, toQueueUrl('SQS_QUEUE_NESTED_ARN'));
validateHasLambdaPermission(resources, 'LAMBDA_FUNCTION_ARN');
expect(consoleLogSpy.callCount).equal(0);
});
it('should generate CloudWatch Event Rules with Ref ang Fn::GetAtt', () => {
const snsArn = { Ref: 'MyTopic' };
const sqsArn = { 'Fn::GetAtt': ['MyQueue', 'Arn'] };
const sqsNestedArn = { 'Fn::GetAtt': ['MyNestedQueue', 'Arn'] };
const lambdaArn = { 'Fn::GetAtt': ['MyFunction', 'Arn'] };
const kinesisArn = { 'Fn::GetAtt': ['MyStream', 'Arn'] };
const kinesisNestedArn = { 'Fn::GetAtt': ['MyNestedStream', 'Arn'] };
const firehoseArn = { 'Fn::GetAtt': ['MyDeliveryStream', 'Arn'] };
const stepFunctionsArn = { Ref: 'MyStateMachine' };
const targets = [
{ sns: snsArn },
{ sqs: sqsArn },
{ sqs: { arn: sqsNestedArn, messageGroupId: '12345' } },
{ lambda: lambdaArn },
{ kinesis: kinesisArn },
{ kinesis: { arn: kinesisNestedArn, partitionKeyPath: '$.id' } },
{ firehose: firehoseArn },
{ stepFunctions: stepFunctionsArn },
];
serverless.service.stepFunctions = {
stateMachines: {
beta1: genStateMachineWithTargets('Beta1', targets),
beta2: genStateMachineWithTargets('Beta2', targets),
},
};
serverlessStepFunctions.compileNotifications();
const resources = serverlessStepFunctions.serverless.service
.provider.compiledCloudFormationTemplate.Resources;
const count = targets.length;
const validateCloudWatchEvents = (prefix) => {
validateCloudWatchEvent(resources, `${prefix}NotificationsABORTEDEventRule`, 'ABORTED', count);
validateCloudWatchEvent(resources, `${prefix}NotificationsFAILEDEventRule`, 'FAILED', count);
validateCloudWatchEvent(resources, `${prefix}NotificationsRUNNINGEventRule`, 'RUNNING', count);
validateCloudWatchEvent(resources, `${prefix}NotificationsSUCCEEDEDEventRule`, 'SUCCEEDED', count);
validateCloudWatchEvent(resources, `${prefix}NotificationsTIMEDOUTEventRule`, 'TIMED_OUT', count);
};
validateCloudWatchEvents('Beta1');
validateCloudWatchEvents('Beta2');
const validateIamRole = (iamRole) => {
// 4 targets (excluding sns, sqs, lambda), 5 event rules = 5 * 4 = 20 policies
expect(iamRole.Properties.Policies).to.have.lengthOf(20);
validateHasPermission(iamRole, 'kinesis:PutRecord', kinesisArn);
validateHasPermission(iamRole, 'kinesis:PutRecord', kinesisNestedArn);
validateHasPermission(iamRole, 'firehose:PutRecord', firehoseArn);
validateHasPermission(iamRole, 'states:StartExecution', stepFunctionsArn);
};
validateIamRole(resources.Beta1NotificationsIamRole);
validateIamRole(resources.Beta2NotificationsIamRole);
validateHasSnsPolicy(resources, snsArn);
validateHasSqsPolicy(resources, { Ref: 'MyQueue' });
validateHasSqsPolicy(resources, { Ref: 'MyNestedQueue' });
validateHasLambdaPermission(resources, lambdaArn);
expect(consoleLogSpy.callCount).equal(0);
});
it('should do deterministic compilation of CloudWatch Event Rules', () => {
const snsArn = { Ref: 'MyTopic' };
const sqsArn = { 'Fn::GetAtt': ['MyQueue', 'Arn'] };
const sqsNestedArn = { 'Fn::GetAtt': ['MyNestedQueue', 'Arn'] };
const lambdaArn = { 'Fn::GetAtt': ['MyFunction', 'Arn'] };
const kinesisArn = { 'Fn::GetAtt': ['MyStream', 'Arn'] };
const kinesisNestedArn = { 'Fn::GetAtt': ['MyNestedStream', 'Arn'] };
const firehoseArn = { 'Fn::GetAtt': ['MyDeliveryStream', 'Arn'] };
const stepFunctionsArn = { Ref: 'MyStateMachine' };
const targets = [
{ sns: snsArn },
{ sqs: sqsArn },
{ sqs: { arn: sqsNestedArn, messageGroupId: '12345' } },
{ lambda: lambdaArn },
{ kinesis: kinesisArn },
{ kinesis: { arn: kinesisNestedArn, partitionKeyPath: '$.id' } },
{ firehose: firehoseArn },
{ stepFunctions: stepFunctionsArn },
{ sns: 'SNS_TOPIC_ARN' },
{ sqs: 'SQS_QUEUE_ARN' },
{ sqs: 'arn:aws:sqs:#{AWS::Region}:#{AWS::AccountId}:MyQueue' },
{ sqs: { arn: 'SQS_QUEUE_NESTED_ARN', messageGroupId: '12345' } },
{ lambda: 'LAMBDA_FUNCTION_ARN' },
{ kinesis: 'KINESIS_STREAM_ARN' },
{ kinesis: { arn: 'KINESIS_STREAM_NESTED_ARN', partitionKeyPath: '$.id' } },
{ firehose: 'FIREHOSE_STREAM_ARN' },
{ stepFunctions: 'STATE_MACHINE_ARN' },
];
const definition = {
stateMachines: {
beta1: genStateMachineWithTargets('Beta1', targets),
beta2: genStateMachineWithTargets('Beta2', targets),
},
};
serverless.service.stepFunctions = _.cloneDeep(definition);
serverlessStepFunctions.compileNotifications();
const resources1 = _.cloneDeep(serverlessStepFunctions.serverless.service
.provider.compiledCloudFormationTemplate.Resources);
serverless.service.stepFunctions = _.cloneDeep(definition);
serverlessStepFunctions.compileNotifications();
const resources2 = _.cloneDeep(serverlessStepFunctions.serverless.service
.provider.compiledCloudFormationTemplate.Resources);
expect(resources1).to.deep.equal(resources2);
});
it('should not generate resources when no notifications are defined', () => {
const genStateMachine = (name) => ({
name,
definition: {
StartAt: 'A',
States: {
A: {
Type: 'Pass',
End: true,
},
},
},
});
serverless.service.stepFunctions = {
stateMachines: {
beta1: genStateMachine('Beta1'),
beta2: genStateMachine('Beta2'),
},
};
serverlessStepFunctions.compileNotifications();
const resources = serverlessStepFunctions.serverless.service
.provider.compiledCloudFormationTemplate.Resources;
expect(_.keys(resources)).to.have.lengthOf(0);
expect(consoleLogSpy.callCount).equal(0);
});
it('should not generate resources when notifications is empty', () => {
const genStateMachine = (name) => ({
name,
definition: {
StartAt: 'A',
States: {
A: {
Type: 'Pass',
End: true,
},
},
},
notifications: {},
});
serverless.service.stepFunctions = {
stateMachines: {
beta1: genStateMachine('Beta1'),
beta2: genStateMachine('Beta2'),
},
};
serverlessStepFunctions.compileNotifications();
const resources = serverlessStepFunctions.serverless.service
.provider.compiledCloudFormationTemplate.Resources;
expect(_.keys(resources)).to.have.lengthOf(0);
expect(consoleLogSpy.callCount).equal(0);
});
it('should not generate resources when targets are empty', () => {
const genStateMachine = (name) => ({
name,
definition: {
StartAt: 'A',
States: {
A: {
Type: 'Pass',
End: true,
},
},
},
notifications: {
ABORTED: [],
FAILED: [],
RUNNING: [],
SUCCEEDED: [],
TIMED_OUT: [],
},
});
serverless.service.stepFunctions = {
stateMachines: {
beta1: genStateMachine('Beta1'),
beta2: genStateMachine('Beta2'),
},
};
serverlessStepFunctions.compileNotifications();
const resources = serverlessStepFunctions.serverless.service
.provider.compiledCloudFormationTemplate.Resources;
expect(_.keys(resources)).to.have.lengthOf(0);
expect(consoleLogSpy.callCount).equal(0);
});
it('should log the validation errors if notifications contains non-existent status', () => {
const targets = [
{ sns: 'SNS_TOPIC_ARN' },
];
const genStateMachine = (name) => ({
id: name,
name,
definition: {
StartAt: 'A',
States: {
A: {
Type: 'Pass',
End: true,
},
},
},
notifications: {
ABORTED: targets,
FAILURE: targets, // wrong name
},
});
serverless.service.stepFunctions = {
stateMachines: {
beta1: genStateMachine('Beta1'),
},
};
serverlessStepFunctions.compileNotifications();
const resources = serverlessStepFunctions.serverless.service
.provider.compiledCloudFormationTemplate.Resources;
expect(_.keys(resources)).to.have.lengthOf(0);
expect(consoleLogSpy.callCount).equal(1);
const { args } = consoleLogSpy.lastCall;
const [logMessage] = args;
expect(logMessage.startsWith('State machine [Beta1] : notifications config is malformed.'))
.to.equal(true);
});
it('should log the validation errors if notifications contains non-existent target type', () => {
const wrongTargets = [
{ sns: 'SNS_TOPIC_ARN' },
{ sqqs: 'SQS_QUEUE_ARN' },
];
const genStateMachine = (name) => ({
id: name,
name,
definition: {
StartAt: 'A',
States: {
A: {
Type: 'Pass',
End: true,
},
},
},
notifications: {
ABORTED: wrongTargets,
},
});
serverless.service.stepFunctions = {
stateMachines: {
beta1: genStateMachine('Beta1'),
},
};
serverlessStepFunctions.compileNotifications();
const resources = serverlessStepFunctions.serverless.service
.provider.compiledCloudFormationTemplate.Resources;
expect(_.keys(resources)).to.have.lengthOf(0);
expect(consoleLogSpy.callCount).equal(1);
const { args } = consoleLogSpy.lastCall;
const [logMessage] = args;
expect(logMessage.startsWith('State machine [Beta1] : notifications config is malformed.'))
.to.equal(true);
});
it('should log the validation errors if state machine is an Express Workflow', () => {
const genStateMachine = (name) => ({
name,
type: 'EXPRESS',
definition: {
StartAt: 'A',
States: {
A: {
Type: 'Pass',
End: true,
},
},
},
notifications: {
ABORTED: [{ sns: 'SNS_TOPIC_ARN' }],
},
});
serverless.service.stepFunctions = {
stateMachines: {
beta1: genStateMachine('Beta1'),
},
};
serverlessStepFunctions.compileNotifications();
const resources = serverlessStepFunctions.serverless.service
.provider.compiledCloudFormationTemplate.Resources;
expect(_.keys(resources)).to.have.lengthOf(0);
expect(consoleLogSpy.callCount).equal(1);
const { args } = consoleLogSpy.lastCall;
const [logMessage] = args;
expect(logMessage.startsWith('State machine [Beta1] : notifications are not supported on Express Workflows.'))
.to.equal(true);
});
it('should resolve local function names via Fn::GetAtt in notifications to CloudFormation logical IDs', () => {
serverless.service.functions = {
'send-email-on-failure': { handler: 'path/to/file.handler' },
};
const lambdaArn = { 'Fn::GetAtt': ['send-email-on-failure', 'Arn'] };
const targets = [{ lambda: lambdaArn }];
serverless.service.stepFunctions = {
stateMachines: {
myWorkflow: genStateMachineWithTargets('MyWorkflow', targets),
},
};
serverlessStepFunctions.compileNotifications();
const resources = serverlessStepFunctions.serverless.service
.provider.compiledCloudFormationTemplate.Resources;
const expectedLogicalId = 'SendDashemailDashonDashfailureLambdaFunction';
const expectedArn = { 'Fn::GetAtt': [expectedLogicalId, 'Arn'] };
// The EventRule target Arn should use the normalized logical ID
const eventRule = resources.MyWorkflowNotificationsFAILEDEventRule;
expect(eventRule.Properties.Targets[0].Arn).to.deep.equal(expectedArn);
// The Lambda permission should also use the normalized logical ID
validateHasLambdaPermission(resources, expectedArn);
});
it('should resolve local function names via Ref in notifications to CloudFormation logical IDs', () => {
serverless.service.functions = {
'send-email-on-failure': { handler: 'path/to/file.handler' },
};
const lambdaRef = { Ref: 'send-email-on-failure' };
const targets = [{ lambda: lambdaRef }];
serverless.service.stepFunctions = {
stateMachines: {
myWorkflow: genStateMachineWithTargets('MyWorkflow', targets),
},
};
serverlessStepFunctions.compileNotifications();
const resources = serverlessStepFunctions.serverless.service
.provider.compiledCloudFormationTemplate.Resources;
const expectedLogicalId = 'SendDashemailDashonDashfailureLambdaFunction';
const expectedRef = { Ref: expectedLogicalId };
const eventRule = resources.MyWorkflowNotificationsFAILEDEventRule;
expect(eventRule.Properties.Targets[0].Arn).to.deep.equal(expectedRef);
validateHasLambdaPermission(resources, expectedRef);
});
it('should support inputPath on notification targets', () => {
const targets = [
{ sns: 'SNS_TOPIC_ARN', inputPath: '$.detail' },
{ sqs: 'SQS_QUEUE_ARN', inputPath: '$.detail' },
];
serverless.service.stepFunctions = {
stateMachines: {
myWorkflow: genStateMachineWithTargets('MyWorkflow', targets),
},
};
serverlessStepFunctions.compileNotifications();
const resources = serverlessStepFunctions.serverless.service
.provider.compiledCloudFormationTemplate.Resources;
const eventRule = resources.MyWorkflowNotificationsABORTEDEventRule;
expect(eventRule.Properties.Targets[0].InputPath).to.equal('$.detail');
expect(eventRule.Properties.Targets[1].InputPath).to.equal('$.detail');
});
it('should support inputTransformer on notification targets', () => {
const targets = [
{
sns: 'SNS_TOPIC_ARN',
inputTransformer: {
inputPathsMap: { status: '$.detail.status', name: '$.detail.name' },
inputTemplate: '"State machine <name> finished with status <status>"',
},
},
];
serverless.service.stepFunctions = {
stateMachines: {
myWorkflow: genStateMachineWithTargets('MyWorkflow', targets),
},
};
serverlessStepFunctions.compileNotifications();
const resources = serverlessStepFunctions.serverless.service
.provider.compiledCloudFormationTemplate.Resources;
const eventRule = resources.MyWorkflowNotificationsABORTEDEventRule;
const cfnTarget = eventRule.Properties.Targets[0];
expect(cfnTarget.InputTransformer).to.deep.equal({
InputPathsMap: { status: '$.detail.status', name: '$.detail.name' },
InputTemplate: '"State machine <name> finished with status <status>"',
});
});
it('should apply provider.iam.role.path to notifications IAM role', () => {
serverless.service.stepFunctions = {
stateMachines: {
beta1: genStateMachineWithTargets('Beta1', [{ stepFunctions: 'STATE_MACHINE_ARN' }]),
},
};
serverless.service.provider.iam = { role: { path: '/teamA/' } };
serverlessStepFunctions.compileNotifications();
const resources = serverlessStepFunctions.serverless.service
.provider.compiledCloudFormationTemplate.Resources;
expect(resources.Beta1NotificationsIamRole.Properties.Path).to.equal('/teamA/');
});
it('should produce a single SNS topic policy when multiple state machines share the same topic', () => {
// Reproduces issue #275: each state machine generates its own AWS::SNS::TopicPolicy
// for the shared topic. CloudFormation applies them sequentially — the second
// overwrites the first, leaving the first machine's notifications unauthorised.
// The fix merges policies for the same topic into a single resource with combined
// statements so CloudFormation only sets the policy once, correctly.
serverless.service.stepFunctions = {
stateMachines: {
machine1: genStateMachineWithTargets('Machine1', [{ sns: 'arn:aws:sns:us-east-1:123:shared-topic' }]),
machine2: genStateMachineWithTargets('Machine2', [{ sns: 'arn:aws:sns:us-east-1:123:shared-topic' }]),
},
};
serverlessStepFunctions.compileNotifications();
const resources = serverlessStepFunctions.serverless.service
.provider.compiledCloudFormationTemplate.Resources;
const snsPolicies = _.values(resources).filter((r) => r.Type === 'AWS::SNS::TopicPolicy');
const policiesForSharedTopic = snsPolicies.filter((p) => _.isEqual(
p.Properties.Topics[0],
'arn:aws:sns:us-east-1:123:shared-topic',
));
expect(policiesForSharedTopic).to.have.lengthOf(1);
// Both machines × 5 statuses = 10 statements in the merged policy
const statements = [].concat(policiesForSharedTopic[0].Properties.PolicyDocument.Statement);
expect(statements.length).to.equal(10);
});
it('should produce a single SQS queue policy when multiple state machines share the same queue', () => {
serverless.service.stepFunctions = {
stateMachines: {
machine1: genStateMachineWithTargets('Machine1', [{ sqs: 'arn:aws:sqs:us-east-1:123:shared-queue' }]),
machine2: genStateMachineWithTargets('Machine2', [{ sqs: 'arn:aws:sqs:us-east-1:123:shared-queue' }]),
},
};
serverlessStepFunctions.compileNotifications();
const resources = serverlessStepFunctions.serverless.service
.provider.compiledCloudFormationTemplate.Resources;
const sqsPolicies = _.values(resources).filter((r) => r.Type === 'AWS::SQS::QueuePolicy');
expect(sqsPolicies).to.have.lengthOf(1);
const statements = [].concat(sqsPolicies[0].Properties.PolicyDocument.Statement);
expect(statements.length).to.equal(10);
});
it('should merge SNS policies when same topic is used for multiple statuses in one state machine', () => {
serverless.service.stepFunctions = {
stateMachines: {
machine1: {
id: 'Machine1',
name: 'Machine1',
definition: { StartAt: 'A', States: { A: { Type: 'Pass', End: true } } },
notifications: {
SUCCEEDED: [{ sns: 'arn:aws:sns:us-east-1:123:shared-topic' }],
FAILED: [{ sns: 'arn:aws:sns:us-east-1:123:shared-topic' }],
},
},
},
};
serverlessStepFunctions.compileNotifications();
const resources = serverlessStepFunctions.serverless.service
.provider.compiledCloudFormationTemplate.Resources;
const snsPolicies = _.values(resources).filter((r) => r.Type === 'AWS::SNS::TopicPolicy');
expect(snsPolicies).to.have.lengthOf(1);
const statements = [].concat(snsPolicies[0].Properties.PolicyDocument.Statement);
expect(statements.length).to.equal(2);
});
});