/
rule.test.ts
1048 lines (917 loc) · 30.4 KB
/
rule.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
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
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-disable object-curly-newline */
import { Annotations, Match, Template } from '@aws-cdk/assertions';
import * as iam from '@aws-cdk/aws-iam';
import * as cdk from '@aws-cdk/core';
import { EventBus, EventField, IRule, IRuleTarget, RuleTargetConfig, RuleTargetInput, Schedule } from '../lib';
import { Rule } from '../lib/rule';
/* eslint-disable quote-props */
describe('rule', () => {
test('default rule', () => {
const stack = new cdk.Stack();
new Rule(stack, 'MyRule', {
schedule: Schedule.rate(cdk.Duration.minutes(10)),
});
Template.fromStack(stack).templateMatches({
'Resources': {
'MyRuleA44AB831': {
'Type': 'AWS::Events::Rule',
'Properties': {
'ScheduleExpression': 'rate(10 minutes)',
'State': 'ENABLED',
},
},
},
});
});
test('rule displays warning when minutes are not included in cron', () => {
const stack = new cdk.Stack();
const rule = new Rule(stack, 'MyRule', {
schedule: Schedule.cron({
hour: '8',
day: '1',
}),
});
expect(rule.node.metadataEntry).toEqual([{
type: 'aws:cdk:warning',
data: 'cron: If you don\'t pass \'minute\', by default the event runs every minute. Pass \'minute: \'*\'\' if that\'s what you intend, or \'minute: 0\' to run once per hour instead.',
trace: undefined,
}]);
Annotations.fromStack(stack).hasWarning('/Default/MyRule', "cron: If you don't pass 'minute', by default the event runs every minute. Pass 'minute: '*'' if that's what you intend, or 'minute: 0' to run once per hour instead.");
});
test('rule does not display warning when minute is set to * in cron', () => {
const stack = new cdk.Stack();
const rule = new Rule(stack, 'MyRule', {
schedule: Schedule.cron({
minute: '*',
hour: '8',
day: '1',
}),
});
expect(rule.node.metadataEntry).toEqual([]);
const annotations = Annotations.fromStack(stack).findWarning('*', Match.anyValue());
expect(annotations.length).toBe(0);
});
test('can get rule name', () => {
const stack = new cdk.Stack();
const rule = new Rule(stack, 'MyRule', {
schedule: Schedule.rate(cdk.Duration.minutes(10)),
});
new cdk.CfnResource(stack, 'Res', {
type: 'Test::Resource',
properties: {
RuleName: rule.ruleName,
},
});
Template.fromStack(stack).hasResourceProperties('Test::Resource', {
RuleName: { Ref: 'MyRuleA44AB831' },
});
});
test('get rate as token', () => {
const app = new cdk.App();
const stack = new cdk.Stack(app, 'MyScheduledStack');
const lazyDuration = cdk.Duration.minutes(cdk.Lazy.number({ produce: () => 5 }));
new Rule(stack, 'MyScheduledRule', {
ruleName: 'rateInMinutes',
schedule: Schedule.rate(lazyDuration),
});
// THEN
Template.fromStack(stack).hasResourceProperties('AWS::Events::Rule', {
'Name': 'rateInMinutes',
'ScheduleExpression': 'rate(5 minutes)',
});
});
test('Seconds is not an allowed value for Schedule rate', () => {
const lazyDuration = cdk.Duration.seconds(cdk.Lazy.number({ produce: () => 5 }));
expect(() => Schedule.rate(lazyDuration)).toThrow(/Allowed units for scheduling/i);
});
test('Millis is not an allowed value for Schedule rate', () => {
const lazyDuration = cdk.Duration.millis(cdk.Lazy.number({ produce: () => 5 }));
// THEN
expect(() => Schedule.rate(lazyDuration)).toThrow(/Allowed units for scheduling/i);
});
test('rule with physical name', () => {
// GIVEN
const stack = new cdk.Stack();
// WHEN
new Rule(stack, 'MyRule', {
ruleName: 'PhysicalName',
schedule: Schedule.rate(cdk.Duration.minutes(10)),
});
// THEN
Template.fromStack(stack).hasResourceProperties('AWS::Events::Rule', {
Name: 'PhysicalName',
});
});
test('eventPattern is rendered properly', () => {
const stack = new cdk.Stack();
new Rule(stack, 'MyRule', {
eventPattern: {
account: ['account1', 'account2'],
detail: {
foo: [1, 2],
},
detailType: ['detailType1'],
id: ['id1', 'id2'],
region: ['region1', 'region2', 'region3'],
resources: ['r1'],
source: ['src1', 'src2'],
time: ['t1'],
version: ['0'],
},
});
Template.fromStack(stack).templateMatches({
'Resources': {
'MyRuleA44AB831': {
'Type': 'AWS::Events::Rule',
'Properties': {
'EventPattern': {
account: ['account1', 'account2'],
detail: { foo: [1, 2] },
'detail-type': ['detailType1'],
id: ['id1', 'id2'],
region: ['region1', 'region2', 'region3'],
resources: ['r1'],
source: ['src1', 'src2'],
time: ['t1'],
version: ['0'],
},
'State': 'ENABLED',
},
},
},
});
});
test('fails synthesis if neither eventPattern nor scheduleExpression are specified', () => {
const app = new cdk.App();
const stack = new cdk.Stack(app, 'MyStack');
new Rule(stack, 'Rule');
expect(() => app.synth()).toThrow(/Either 'eventPattern' or 'schedule' must be defined/);
});
test('addEventPattern can be used to add filters', () => {
const stack = new cdk.Stack();
const rule = new Rule(stack, 'MyRule');
rule.addEventPattern({
account: ['12345'],
detail: {
foo: ['hello', 'bar', 'hello'],
},
});
rule.addEventPattern({
source: ['aws.source'],
detail: {
foo: ['bar', 'hello'],
goo: {
hello: ['world'],
},
},
});
Template.fromStack(stack).templateMatches({
'Resources': {
'MyRuleA44AB831': {
'Type': 'AWS::Events::Rule',
'Properties': {
'EventPattern': {
'account': [
'12345',
],
'detail': {
'foo': [
'hello',
'bar',
],
'goo': {
'hello': [
'world',
],
},
},
'source': [
'aws.source',
],
},
'State': 'ENABLED',
},
},
},
});
});
test('addEventPattern can de-duplicate filters and keep the order', () => {
const stack = new cdk.Stack();
const rule = new Rule(stack, 'MyRule');
rule.addEventPattern({
detailType: ['AWS API Call via CloudTrail', 'AWS API Call via CloudTrail'],
});
rule.addEventPattern({
detailType: ['EC2 Instance State-change Notification', 'AWS API Call via CloudTrail'],
});
Template.fromStack(stack).templateMatches({
'Resources': {
'MyRuleA44AB831': {
'Type': 'AWS::Events::Rule',
'Properties': {
'EventPattern': {
'detail-type': [
'AWS API Call via CloudTrail',
'EC2 Instance State-change Notification',
],
},
'State': 'ENABLED',
},
},
},
});
});
test('targets can be added via props or addTarget with input transformer', () => {
const stack = new cdk.Stack();
const t1: IRuleTarget = {
bind: () => ({
id: '',
arn: 'ARN1',
kinesisParameters: { partitionKeyPath: 'partitionKeyPath' },
}),
};
const t2: IRuleTarget = {
bind: () => ({
id: '',
arn: 'ARN2',
input: RuleTargetInput.fromText(`This is ${EventField.fromPath('$.detail.bla')}`),
}),
};
const rule = new Rule(stack, 'EventRule', {
targets: [t1],
schedule: Schedule.rate(cdk.Duration.minutes(5)),
});
rule.addTarget(t2);
Template.fromStack(stack).templateMatches({
'Resources': {
'EventRule5A491D2C': {
'Type': 'AWS::Events::Rule',
'Properties': {
'ScheduleExpression': 'rate(5 minutes)',
'State': 'ENABLED',
'Targets': [
{
'Arn': 'ARN1',
'Id': 'Target0',
'KinesisParameters': {
'PartitionKeyPath': 'partitionKeyPath',
},
},
{
'Arn': 'ARN2',
'Id': 'Target1',
'InputTransformer': {
'InputPathsMap': {
'detail-bla': '$.detail.bla',
},
'InputTemplate': '"This is <detail-bla>"',
},
},
],
},
},
},
});
});
test('input template can contain tokens', () => {
const stack = new cdk.Stack();
const rule = new Rule(stack, 'EventRule', {
schedule: Schedule.rate(cdk.Duration.minutes(1)),
});
// a plain string should just be stringified (i.e. double quotes added and escaped)
rule.addTarget({
bind: () => ({
id: '', arn: 'ARN2', input: RuleTargetInput.fromText('Hello, "world"'),
}),
});
// tokens are used here (FnConcat), but this is a text template so we
// expect it to be wrapped in double quotes automatically for us.
rule.addTarget({
bind: () => ({
id: '',
arn: 'ARN1',
kinesisParameters: { partitionKeyPath: 'partitionKeyPath' },
input: RuleTargetInput.fromText(cdk.Fn.join('', ['a', 'b']).toString()),
}),
});
// jsonTemplate can be used to format JSON documents with replacements
rule.addTarget({
bind: () => ({
id: '',
arn: 'ARN3',
input: RuleTargetInput.fromObject({ foo: EventField.fromPath('$.detail.bar') }),
}),
});
// tokens can also used for JSON templates.
rule.addTarget({
bind: () => ({
id: '',
arn: 'ARN4',
input: RuleTargetInput.fromText(cdk.Fn.join(' ', ['hello', '"world"']).toString()),
}),
});
Template.fromStack(stack).templateMatches({
'Resources': {
'EventRule5A491D2C': {
'Type': 'AWS::Events::Rule',
'Properties': {
'State': 'ENABLED',
'ScheduleExpression': 'rate(1 minute)',
'Targets': [
{
'Arn': 'ARN2',
'Id': 'Target0',
'Input': '"Hello, \\"world\\""',
},
{
'Arn': 'ARN1',
'Id': 'Target1',
'Input': '"ab"',
'KinesisParameters': {
'PartitionKeyPath': 'partitionKeyPath',
},
},
{
'Arn': 'ARN3',
'Id': 'Target2',
'InputTransformer': {
'InputPathsMap': {
'detail-bar': '$.detail.bar',
},
'InputTemplate': '{"foo":<detail-bar>}',
},
},
{
'Arn': 'ARN4',
'Id': 'Target3',
'Input': '"hello \\"world\\""',
},
],
},
},
},
});
});
test('target can declare role which will be used', () => {
// GIVEN
const stack = new cdk.Stack();
const rule = new Rule(stack, 'EventRule', {
schedule: Schedule.rate(cdk.Duration.minutes(1)),
});
const role = new iam.Role(stack, 'SomeRole', {
assumedBy: new iam.ServicePrincipal('nobody'),
});
// a plain string should just be stringified (i.e. double quotes added and escaped)
rule.addTarget({
bind: () => ({
id: '',
arn: 'ARN2',
role,
}),
});
// THEN
Template.fromStack(stack).hasResourceProperties('AWS::Events::Rule', {
'Targets': [
{
'Arn': 'ARN2',
'Id': 'Target0',
'RoleArn': { 'Fn::GetAtt': ['SomeRole6DDC54DD', 'Arn'] },
},
],
});
});
test('in cross-account scenario, target role is only used in target account', () => {
// GIVEN
const app = new cdk.App();
const ruleStack = new cdk.Stack(app, 'RuleStack', { env: { account: '1234', region: 'us-east-1' } });
const targetStack = new cdk.Stack(app, 'TargeTStack', { env: { account: '5678', region: 'us-east-1' } });
const rule = new Rule(ruleStack, 'EventRule', {
schedule: Schedule.rate(cdk.Duration.minutes(1)),
});
const role = new iam.Role(targetStack, 'SomeRole', {
assumedBy: new iam.ServicePrincipal('nobody'),
});
// a plain string should just be stringified (i.e. double quotes added and escaped)
rule.addTarget({
bind: () => ({
id: '',
arn: 'ARN2',
role,
targetResource: role, // Not really but good enough
}),
});
// THEN
Template.fromStack(ruleStack).hasResourceProperties('AWS::Events::Rule', {
Targets: [
{
Arn: { 'Fn::Join': ['', [
'arn:',
{ 'Ref': 'AWS::Partition' },
':events:us-east-1:5678:event-bus/default',
]] },
},
],
});
Template.fromStack(targetStack).hasResourceProperties('AWS::Events::Rule', {
'Targets': [
{
'Arn': 'ARN2',
'Id': 'Target0',
'RoleArn': { 'Fn::GetAtt': ['SomeRole6DDC54DD', 'Arn'] },
},
],
});
});
test('asEventRuleTarget can use the ruleArn and a uniqueId of the rule', () => {
const stack = new cdk.Stack();
let receivedRuleArn = 'FAIL';
let receivedRuleId = 'FAIL';
const t1: IRuleTarget = {
bind: (eventRule: IRule) => {
receivedRuleArn = eventRule.ruleArn;
receivedRuleId = cdk.Names.nodeUniqueId(eventRule.node);
return {
id: '',
arn: 'ARN1',
kinesisParameters: { partitionKeyPath: 'partitionKeyPath' },
};
},
};
const rule = new Rule(stack, 'EventRule');
rule.addTarget(t1);
expect(stack.resolve(receivedRuleArn)).toEqual(stack.resolve(rule.ruleArn));
expect(receivedRuleId).toEqual(cdk.Names.uniqueId(rule));
});
test('fromEventRuleArn', () => {
// GIVEN
const stack = new cdk.Stack();
// WHEN
const importedRule = Rule.fromEventRuleArn(stack, 'ImportedRule', 'arn:aws:events:us-east-2:123456789012:rule/example');
// THEN
expect(importedRule.ruleArn).toEqual('arn:aws:events:us-east-2:123456789012:rule/example');
expect(importedRule.ruleName).toEqual('example');
});
test('rule can be disabled', () => {
// GIVEN
const stack = new cdk.Stack();
// WHEN
new Rule(stack, 'Rule', {
schedule: Schedule.expression('foom'),
enabled: false,
});
// THEN
Template.fromStack(stack).hasResourceProperties('AWS::Events::Rule', {
'State': 'DISABLED',
});
});
test('can add multiple targets with the same id', () => {
// GIVEN
const stack = new cdk.Stack();
const rule = new Rule(stack, 'Rule', {
schedule: Schedule.expression('foom'),
enabled: false,
});
rule.addTarget(new SomeTarget());
rule.addTarget(new SomeTarget());
// THEN
Template.fromStack(stack).hasResourceProperties('AWS::Events::Rule', {
Targets: [
{
'Arn': 'ARN1',
'Id': 'Target0',
'KinesisParameters': {
'PartitionKeyPath': 'partitionKeyPath',
},
},
{
'Arn': 'ARN1',
'Id': 'Target1',
'KinesisParameters': {
'PartitionKeyPath': 'partitionKeyPath',
},
},
],
});
});
test('sqsParameters are generated when they are specified in target props', () => {
const stack = new cdk.Stack();
const t1: IRuleTarget = {
bind: () => ({
id: '',
arn: 'ARN1',
sqsParameters: { messageGroupId: 'messageGroupId' },
}),
};
new Rule(stack, 'EventRule', {
schedule: Schedule.rate(cdk.Duration.minutes(5)),
targets: [t1],
});
Template.fromStack(stack).hasResourceProperties('AWS::Events::Rule', {
Targets: [
{
'Arn': 'ARN1',
'Id': 'Target0',
'SqsParameters': {
'MessageGroupId': 'messageGroupId',
},
},
],
});
});
test('associate rule with event bus', () => {
// GIVEN
const stack = new cdk.Stack();
const eventBus = new EventBus(stack, 'EventBus');
// WHEN
new Rule(stack, 'MyRule', {
eventPattern: {
detail: ['detail'],
},
eventBus,
});
// THEN
Template.fromStack(stack).hasResourceProperties('AWS::Events::Rule', {
EventBusName: {
Ref: 'EventBus7B8748AA',
},
});
});
test('throws with eventBus and schedule', () => {
// GIVEN
const app = new cdk.App();
const stack = new cdk.Stack(app, 'MyStack');
const eventBus = new EventBus(stack, 'EventBus');
// THEN
expect(() => new Rule(stack, 'MyRule', {
schedule: Schedule.rate(cdk.Duration.minutes(10)),
eventBus,
})).toThrow(/Cannot associate rule with 'eventBus' when using 'schedule'/);
});
test('allow an imported target if is in the same account and region', () => {
const app = new cdk.App();
const sourceAccount = '123456789012';
const sourceRegion = 'us-west-2';
const sourceStack = new cdk.Stack(app, 'SourceStack', { env: { account: sourceAccount, region: sourceRegion } });
const rule = new Rule(sourceStack, 'Rule', {
eventPattern: {
source: ['some-event'],
},
});
const resource = EventBus.fromEventBusArn(sourceStack, 'TargetEventBus', `arn:aws:events:${sourceRegion}:${sourceAccount}:event-bus/default`);
rule.addTarget(new SomeTarget('T', resource));
Template.fromStack(sourceStack).hasResourceProperties('AWS::Events::Rule', {
Targets: [
{
'Arn': 'ARN1',
'Id': 'T',
'KinesisParameters': {
'PartitionKeyPath': 'partitionKeyPath',
},
},
],
});
});
describe('for cross-account and/or cross-region targets', () => {
test('requires that the source stack specify a concrete account', () => {
const app = new cdk.App();
const sourceStack = new cdk.Stack(app, 'SourceStack');
const rule = new Rule(sourceStack, 'Rule');
const targetAccount = '234567890123';
const targetStack = new cdk.Stack(app, 'TargetStack', { env: { account: targetAccount } });
const resource = new cdk.Construct(targetStack, 'Resource');
expect(() => {
rule.addTarget(new SomeTarget('T', resource));
}).toThrow(/You need to provide a concrete region/);
});
test('requires that the target stack specify a concrete account', () => {
const app = new cdk.App();
const sourceAccount = '123456789012';
const sourceStack = new cdk.Stack(app, 'SourceStack', { env: { account: sourceAccount } });
const rule = new Rule(sourceStack, 'Rule');
const targetStack = new cdk.Stack(app, 'TargetStack');
const resource = new cdk.Construct(targetStack, 'Resource');
expect(() => {
rule.addTarget(new SomeTarget('T', resource));
}).toThrow(/You need to provide a concrete account for the target stack when using cross-account or cross-region events/);
});
test('requires that the target stack specify a concrete region', () => {
const app = new cdk.App();
const sourceAccount = '123456789012';
const sourceStack = new cdk.Stack(app, 'SourceStack', { env: { account: sourceAccount } });
const rule = new Rule(sourceStack, 'Rule');
const targetAccount = '234567890123';
const targetStack = new cdk.Stack(app, 'TargetStack', { env: { account: targetAccount } });
const resource = new cdk.Construct(targetStack, 'Resource');
expect(() => {
rule.addTarget(new SomeTarget('T', resource));
}).toThrow(/You need to provide a concrete region for the target stack when using cross-account or cross-region events/);
});
test('creates cross-account targets if in the same region', () => {
const app = new cdk.App();
const sourceAccount = '123456789012';
const sourceRegion = 'eu-west-2';
const sourceStack = new cdk.Stack(app, 'SourceStack', { env: { account: sourceAccount, region: sourceRegion } });
const rule = new Rule(sourceStack, 'Rule', {
eventPattern: {
source: ['some-event'],
},
});
const targetAccount = '234567890123';
const targetRegion = sourceRegion;
const targetStack = new cdk.Stack(app, 'TargetStack', { env: { account: targetAccount, region: targetRegion } });
const resource = new cdk.Construct(targetStack, 'Resource');
rule.addTarget(new SomeTarget('T', resource));
Template.fromStack(sourceStack).hasResourceProperties('AWS::Events::Rule', {
'State': 'ENABLED',
'Targets': [
{
'Id': 'T',
'Arn': {
'Fn::Join': [
'',
[
'arn:',
{ 'Ref': 'AWS::Partition' },
`:events:${targetRegion}:${targetAccount}:event-bus/default`,
],
],
},
},
],
});
Template.fromStack(targetStack).hasResourceProperties('AWS::Events::Rule', {
Targets: [
{
'Arn': 'ARN1',
'Id': 'T',
'KinesisParameters': {
'PartitionKeyPath': 'partitionKeyPath',
},
},
],
});
});
test('creates cross-region targets', () => {
const app = new cdk.App();
const sourceAccount = '123456789012';
const sourceRegion = 'us-west-2';
const sourceStack = new cdk.Stack(app, 'SourceStack', { env: { account: sourceAccount, region: sourceRegion } });
const rule = new Rule(sourceStack, 'Rule', {
eventPattern: {
source: ['some-event'],
},
});
const targetAccount = '234567890123';
const targetRegion = 'us-east-1';
const targetStack = new cdk.Stack(app, 'TargetStack', { env: { account: targetAccount, region: targetRegion } });
const resource = new cdk.Construct(targetStack, 'Resource');
rule.addTarget(new SomeTarget('T', resource));
Template.fromStack(sourceStack).hasResourceProperties('AWS::Events::Rule', {
'State': 'ENABLED',
'Targets': [
{
'Id': 'T',
'Arn': {
'Fn::Join': [
'',
[
'arn:',
{ 'Ref': 'AWS::Partition' },
`:events:${targetRegion}:${targetAccount}:event-bus/default`,
],
],
},
},
],
});
Template.fromStack(targetStack).hasResourceProperties('AWS::Events::Rule', {
Targets: [
{
'Arn': 'ARN1',
'Id': 'T',
'KinesisParameters': {
'PartitionKeyPath': 'partitionKeyPath',
},
},
],
});
});
test('do not create duplicated targets', () => {
const app = new cdk.App();
const sourceAccount = '123456789012';
const sourceRegion = 'us-west-2';
const sourceStack = new cdk.Stack(app, 'SourceStack', { env: { account: sourceAccount, region: sourceRegion } });
const rule = new Rule(sourceStack, 'Rule', {
eventPattern: {
source: ['some-event'],
},
});
const targetAccount = '234567890123';
const targetRegion = 'us-east-1';
const targetStack = new cdk.Stack(app, 'TargetStack', { env: { account: targetAccount, region: targetRegion } });
const resource = new cdk.Construct(targetStack, 'Resource');
rule.addTarget(new SomeTarget('T', resource));
// same target should be skipped
rule.addTarget(new SomeTarget('T1', resource));
Template.fromStack(sourceStack).hasResourceProperties('AWS::Events::Rule', {
'State': 'ENABLED',
'Targets': [
{
'Id': 'T',
'Arn': {
'Fn::Join': [
'',
[
'arn:',
{ 'Ref': 'AWS::Partition' },
`:events:${targetRegion}:${targetAccount}:event-bus/default`,
],
],
},
},
],
});
Template.fromStack(sourceStack).hasResourceProperties('AWS::Events::Rule', Match.not({
'State': 'ENABLED',
'Targets': [
{
'Id': 'T1',
'Arn': {
'Fn::Join': [
'',
[
'arn:',
{ 'Ref': 'AWS::Partition' },
`:events:${targetRegion}:${targetAccount}:event-bus/default`,
],
],
},
},
],
}));
});
test('requires that the target is not imported', () => {
const app = new cdk.App();
const sourceAccount = '123456789012';
const sourceRegion = 'us-west-2';
const sourceStack = new cdk.Stack(app, 'SourceStack', { env: { account: sourceAccount, region: sourceRegion } });
const rule = new Rule(sourceStack, 'Rule', {
eventPattern: {
source: ['some-event'],
},
});
const targetAccount = '123456789012';
const targetRegion = 'us-west-1';
const resource = EventBus.fromEventBusArn(sourceStack, 'TargetEventBus', `arn:aws:events:${targetRegion}:${targetAccount}:event-bus/default`);
expect(() => {
rule.addTarget(new SomeTarget('T', resource));
}).toThrow(/Cannot create a cross-account or cross-region rule for an imported resource/);
});
test('requires that the source and target stacks be part of the same App', () => {
const sourceApp = new cdk.App();
const sourceAccount = '123456789012';
const sourceStack = new cdk.Stack(sourceApp, 'SourceStack', { env: { account: sourceAccount, region: 'us-west-2' } });
const rule = new Rule(sourceStack, 'Rule');
const targetApp = new cdk.App();
const targetAccount = '234567890123';
const targetStack = new cdk.Stack(targetApp, 'TargetStack', { env: { account: targetAccount, region: 'us-west-2' } });
const resource = new cdk.Construct(targetStack, 'Resource');
expect(() => {
rule.addTarget(new SomeTarget('T', resource));
}).toThrow(/Event stack and target stack must belong to the same CDK app/);
});
test('generates the correct rules in the source and target stacks when eventPattern is passed in the constructor', () => {
const app = new cdk.App();
const sourceAccount = '123456789012';
const sourceStack = new cdk.Stack(app, 'SourceStack', {
env: {
account: sourceAccount,
region: 'us-west-2',
},
});
const rule = new Rule(sourceStack, 'Rule', {
eventPattern: {
source: ['some-event'],
},
});
const targetAccount = '234567890123';
const targetStack = new cdk.Stack(app, 'TargetStack', {
env: {
account: targetAccount,
region: 'us-west-2',
},
});
const resource1 = new cdk.Construct(targetStack, 'Resource1');
const resource2 = new cdk.Construct(targetStack, 'Resource2');
rule.addTarget(new SomeTarget('T1', resource1));
rule.addTarget(new SomeTarget('T2', resource2));
Template.fromStack(sourceStack).hasResourceProperties('AWS::Events::Rule', {
'EventPattern': {
'source': [
'some-event',
],
},
'State': 'ENABLED',
'Targets': [
{
'Id': 'T1',
'Arn': {
'Fn::Join': [
'',
[
'arn:',
{ 'Ref': 'AWS::Partition' },
`:events:us-west-2:${targetAccount}:event-bus/default`,
],
],
},
},
],
});
Template.fromStack(targetStack).hasResourceProperties('AWS::Events::Rule', {
'EventPattern': {
'source': [
'some-event',
],
},
'State': 'ENABLED',
'Targets': [
{
'Id': 'T1',
'Arn': 'ARN1',
},
],
});
Template.fromStack(targetStack).hasResourceProperties('AWS::Events::Rule', {
'EventPattern': {
'source': [
'some-event',
],
},
'State': 'ENABLED',
'Targets': [
{
'Id': 'T2',
'Arn': 'ARN1',
},
],
});
const eventBusPolicyStack = app.node.findChild(`EventBusPolicy-${sourceAccount}-us-west-2-${targetAccount}`) as cdk.Stack;
Template.fromStack(eventBusPolicyStack).hasResourceProperties('AWS::Events::EventBusPolicy', {
'Action': 'events:PutEvents',
'StatementId': `Allow-account-${sourceAccount}-${this.node.addr}`,
'Principal': sourceAccount,
});
});
test('generates the correct rule in the target stack when addEventPattern in the source rule is used', () => {
const app = new cdk.App();
const sourceAccount = '123456789012';
const sourceStack = new cdk.Stack(app, 'SourceStack', {
env: {
account: sourceAccount,
region: 'us-west-2',
},
});
const rule = new Rule(sourceStack, 'Rule');