/
repository.test.ts
703 lines (603 loc) · 20.2 KB
/
repository.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
import { EOL } from 'os';
import { Template } from '@aws-cdk/assertions';
import * as iam from '@aws-cdk/aws-iam';
import * as kms from '@aws-cdk/aws-kms';
import * as cdk from '@aws-cdk/core';
import * as ecr from '../lib';
/* eslint-disable quote-props */
describe('repository', () => {
test('construct repository', () => {
// GIVEN
const stack = new cdk.Stack();
// WHEN
new ecr.Repository(stack, 'Repo');
// THEN
Template.fromStack(stack).templateMatches({
Resources: {
Repo02AC86CF: {
Type: 'AWS::ECR::Repository',
Properties: {
ImageScanningConfiguration: {
ScanOnPush: false,
},
},
DeletionPolicy: 'Retain',
UpdateReplacePolicy: 'Retain',
},
},
});
});
test('repository creation with imageScanOnPush', () => {
// GIVEN
const stack = new cdk.Stack();
// WHEN
new ecr.Repository(stack, 'Repo', { imageScanOnPush: true });
// THEN
Template.fromStack(stack).hasResourceProperties('AWS::ECR::Repository', {
ImageScanningConfiguration: {
ScanOnPush: true,
},
});
});
test('tag-based lifecycle policy', () => {
// GIVEN
const stack = new cdk.Stack();
const repo = new ecr.Repository(stack, 'Repo');
// WHEN
repo.addLifecycleRule({ tagPrefixList: ['abc'], maxImageCount: 1 });
// THEN
Template.fromStack(stack).hasResourceProperties('AWS::ECR::Repository', {
LifecyclePolicy: {
// eslint-disable-next-line max-len
LifecyclePolicyText: '{"rules":[{"rulePriority":1,"selection":{"tagStatus":"tagged","tagPrefixList":["abc"],"countType":"imageCountMoreThan","countNumber":1},"action":{"type":"expire"}}]}',
},
});
});
test('image tag mutability can be set', () => {
// GIVEN
const stack = new cdk.Stack();
new ecr.Repository(stack, 'Repo', { imageTagMutability: ecr.TagMutability.IMMUTABLE });
// THEN
Template.fromStack(stack).hasResourceProperties('AWS::ECR::Repository', {
ImageTagMutability: 'IMMUTABLE',
});
});
test('add day-based lifecycle policy', () => {
// GIVEN
const stack = new cdk.Stack();
// WHEN
const repo = new ecr.Repository(stack, 'Repo');
repo.addLifecycleRule({
maxImageAge: cdk.Duration.days(5),
});
// THEN
Template.fromStack(stack).hasResourceProperties('AWS::ECR::Repository', {
LifecyclePolicy: {
// eslint-disable-next-line max-len
LifecyclePolicyText: '{"rules":[{"rulePriority":1,"selection":{"tagStatus":"any","countType":"sinceImagePushed","countNumber":5,"countUnit":"days"},"action":{"type":"expire"}}]}',
},
});
});
test('add count-based lifecycle policy', () => {
// GIVEN
const stack = new cdk.Stack();
const repo = new ecr.Repository(stack, 'Repo');
// WHEN
repo.addLifecycleRule({
maxImageCount: 5,
});
// THEN
Template.fromStack(stack).hasResourceProperties('AWS::ECR::Repository', {
LifecyclePolicy: {
// eslint-disable-next-line max-len
LifecyclePolicyText: '{"rules":[{"rulePriority":1,"selection":{"tagStatus":"any","countType":"imageCountMoreThan","countNumber":5},"action":{"type":"expire"}}]}',
},
});
});
test('mixing numbered and unnumbered rules', () => {
// GIVEN
const stack = new cdk.Stack();
const repo = new ecr.Repository(stack, 'Repo');
// WHEN
repo.addLifecycleRule({ tagStatus: ecr.TagStatus.TAGGED, tagPrefixList: ['a'], maxImageCount: 5 });
repo.addLifecycleRule({ rulePriority: 10, tagStatus: ecr.TagStatus.TAGGED, tagPrefixList: ['b'], maxImageCount: 5 });
// THEN
Template.fromStack(stack).hasResourceProperties('AWS::ECR::Repository', {
LifecyclePolicy: {
// eslint-disable-next-line max-len
LifecyclePolicyText: '{"rules":[{"rulePriority":10,"selection":{"tagStatus":"tagged","tagPrefixList":["b"],"countType":"imageCountMoreThan","countNumber":5},"action":{"type":"expire"}},{"rulePriority":11,"selection":{"tagStatus":"tagged","tagPrefixList":["a"],"countType":"imageCountMoreThan","countNumber":5},"action":{"type":"expire"}}]}',
},
});
});
test('tagstatus Any is automatically sorted to the back', () => {
// GIVEN
const stack = new cdk.Stack();
const repo = new ecr.Repository(stack, 'Repo');
// WHEN
repo.addLifecycleRule({ maxImageCount: 5 });
repo.addLifecycleRule({ tagStatus: ecr.TagStatus.TAGGED, tagPrefixList: ['important'], maxImageCount: 999 });
// THEN
Template.fromStack(stack).hasResourceProperties('AWS::ECR::Repository', {
LifecyclePolicy: {
// eslint-disable-next-line max-len
LifecyclePolicyText: '{"rules":[{"rulePriority":1,"selection":{"tagStatus":"tagged","tagPrefixList":["important"],"countType":"imageCountMoreThan","countNumber":999},"action":{"type":"expire"}},{"rulePriority":2,"selection":{"tagStatus":"any","countType":"imageCountMoreThan","countNumber":5},"action":{"type":"expire"}}]}',
},
});
});
test('lifecycle rules can be added upon initialization', () => {
// GIVEN
const stack = new cdk.Stack();
// WHEN
new ecr.Repository(stack, 'Repo', {
lifecycleRules: [
{ maxImageCount: 3 },
],
});
// THEN
Template.fromStack(stack).hasResourceProperties('AWS::ECR::Repository', {
'LifecyclePolicy': {
// eslint-disable-next-line max-len
'LifecyclePolicyText': '{"rules":[{"rulePriority":1,"selection":{"tagStatus":"any","countType":"imageCountMoreThan","countNumber":3},"action":{"type":"expire"}}]}',
},
});
});
test('calculate repository URI', () => {
// GIVEN
const stack = new cdk.Stack();
const repo = new ecr.Repository(stack, 'Repo');
new cdk.CfnOutput(stack, 'RepoUri', {
value: repo.repositoryUri,
});
// THEN
const arnSplit = { 'Fn::Split': [':', { 'Fn::GetAtt': ['Repo02AC86CF', 'Arn'] }] };
Template.fromStack(stack).hasOutput('*', {
'Value': {
'Fn::Join': ['', [
{ 'Fn::Select': [4, arnSplit] },
'.dkr.ecr.',
{ 'Fn::Select': [3, arnSplit] },
'.',
{ Ref: 'AWS::URLSuffix' },
'/',
{ Ref: 'Repo02AC86CF' },
]],
},
});
});
test('import with concrete arn', () => {
// GIVEN
const stack = new cdk.Stack();
// WHEN
const repo2 = ecr.Repository.fromRepositoryArn(stack, 'repo', 'arn:aws:ecr:us-east-1:585695036304:repository/foo/bar/foo/fooo');
// THEN
expect(stack.resolve(repo2.repositoryArn)).toBe('arn:aws:ecr:us-east-1:585695036304:repository/foo/bar/foo/fooo');
expect(stack.resolve(repo2.repositoryName)).toBe('foo/bar/foo/fooo');
});
test('fails if importing with token arn and no name', () => {
// GIVEN
const stack = new cdk.Stack();
// WHEN/THEN
expect(() => {
ecr.Repository.fromRepositoryArn(stack, 'arn', cdk.Fn.getAtt('Boom', 'Boom').toString());
}).toThrow(/\"repositoryArn\" is a late-bound value, and therefore \"repositoryName\" is required\. Use \`fromRepositoryAttributes\` instead/);
});
test('import with token arn and repository name (see awslabs/aws-cdk#1232)', () => {
// GIVEN
const stack = new cdk.Stack();
// WHEN
const repo = ecr.Repository.fromRepositoryAttributes(stack, 'Repo', {
repositoryArn: cdk.Fn.getAtt('Boom', 'Arn').toString(),
repositoryName: cdk.Fn.getAtt('Boom', 'Name').toString(),
});
new cdk.CfnOutput(stack, 'RepoArn', {
value: repo.repositoryArn,
});
new cdk.CfnOutput(stack, 'RepoName', {
value: repo.repositoryName,
});
// THEN
Template.fromStack(stack).hasOutput('*', {
Value: { 'Fn::GetAtt': ['Boom', 'Arn'] },
});
Template.fromStack(stack).hasOutput('*', {
Value: { 'Fn::GetAtt': ['Boom', 'Name'] },
});
});
test('import only with a repository name (arn is deduced)', () => {
// GIVEN
const stack = new cdk.Stack();
// WHEN
const repo = ecr.Repository.fromRepositoryName(stack, 'just-name', 'my-repo');
new cdk.CfnOutput(stack, 'RepoArn', {
value: repo.repositoryArn,
});
new cdk.CfnOutput(stack, 'RepoName', {
value: repo.repositoryName,
});
// THEN
Template.fromStack(stack).hasOutput('*', {
Value: {
'Fn::Join': ['', [
'arn:',
{ Ref: 'AWS::Partition' },
':ecr:',
{ Ref: 'AWS::Region' },
':',
{ Ref: 'AWS::AccountId' },
':repository/my-repo',
]],
},
});
Template.fromStack(stack).hasOutput('*', {
Value: 'my-repo',
});
});
test('arnForLocalRepository can be used to render an ARN for a local repository', () => {
// GIVEN
const stack = new cdk.Stack();
const repoName = cdk.Fn.getAtt('Boom', 'Name').toString();
// WHEN
const repo = ecr.Repository.fromRepositoryAttributes(stack, 'Repo', {
repositoryArn: ecr.Repository.arnForLocalRepository(repoName, stack),
repositoryName: repoName,
});
new cdk.CfnOutput(stack, 'RepoArn', {
value: repo.repositoryArn,
});
new cdk.CfnOutput(stack, 'RepoName', {
value: repo.repositoryName,
});
// THEN
Template.fromStack(stack).hasOutput('*', {
Value: { 'Fn::GetAtt': ['Boom', 'Name'] },
});
Template.fromStack(stack).hasOutput('*', {
Value: {
'Fn::Join': ['', [
'arn:',
{ Ref: 'AWS::Partition' },
':ecr:',
{ Ref: 'AWS::Region' },
':',
{ Ref: 'AWS::AccountId' },
':repository/',
{ 'Fn::GetAtt': ['Boom', 'Name'] },
]],
},
});
});
test('resource policy', () => {
// GIVEN
const stack = new cdk.Stack();
const repo = new ecr.Repository(stack, 'Repo');
// WHEN
repo.addToResourcePolicy(new iam.PolicyStatement({
actions: ['*'],
principals: [new iam.AnyPrincipal()],
}));
// THEN
Template.fromStack(stack).hasResourceProperties('AWS::ECR::Repository', {
RepositoryPolicyText: {
Statement: [
{
Action: '*',
Effect: 'Allow',
Principal: { AWS: '*' },
},
],
Version: '2012-10-17',
},
});
});
test('fails if repository policy has no actions', () => {
// GIVEN
const app = new cdk.App();
const stack = new cdk.Stack(app, 'my-stack');
const repo = new ecr.Repository(stack, 'Repo');
// WHEN
repo.addToResourcePolicy(new iam.PolicyStatement({
resources: ['*'],
principals: [new iam.ArnPrincipal('arn')],
}));
// THEN
expect(() => app.synth()).toThrow(/A PolicyStatement must specify at least one \'action\' or \'notAction\'/);
});
test('fails if repository policy has no IAM principals', () => {
// GIVEN
const app = new cdk.App();
const stack = new cdk.Stack(app, 'my-stack');
const repo = new ecr.Repository(stack, 'Repo');
// WHEN
repo.addToResourcePolicy(new iam.PolicyStatement({
resources: ['*'],
actions: ['ecr:*'],
}));
// THEN
expect(() => app.synth()).toThrow(/A PolicyStatement used in a resource-based policy must specify at least one IAM principal/);
});
test('default encryption configuration', () => {
// GIVEN
const app = new cdk.App();
const stack = new cdk.Stack(app, 'my-stack');
// WHEN
new ecr.Repository(stack, 'Repo', { encryption: ecr.RepositoryEncryption.AES_256 });
// THEN
Template.fromStack(stack).templateMatches({
Resources: {
Repo02AC86CF: {
Type: 'AWS::ECR::Repository',
DeletionPolicy: 'Retain',
UpdateReplacePolicy: 'Retain',
},
},
});
});
test('kms encryption configuration', () => {
// GIVEN
const app = new cdk.App();
const stack = new cdk.Stack(app, 'my-stack');
// WHEN
new ecr.Repository(stack, 'Repo', { encryption: ecr.RepositoryEncryption.KMS });
// THEN
Template.fromStack(stack).hasResourceProperties('AWS::ECR::Repository',
{
EncryptionConfiguration: {
EncryptionType: 'KMS',
},
});
});
test('kms encryption with custom kms configuration', () => {
// GIVEN
const app = new cdk.App();
const stack = new cdk.Stack(app, 'my-stack');
// WHEN
const custom_key = new kms.Key(stack, 'Key');
new ecr.Repository(stack, 'Repo', { encryptionKey: custom_key });
// THEN
Template.fromStack(stack).hasResourceProperties('AWS::ECR::Repository',
{
EncryptionConfiguration: {
EncryptionType: 'KMS',
KmsKey: {
'Fn::GetAtt': [
'Key961B73FD',
'Arn',
],
},
},
});
});
test('fails if with custom kms key and AES256 as encryption', () => {
// GIVEN
const app = new cdk.App();
const stack = new cdk.Stack(app, 'my-stack');
const custom_key = new kms.Key(stack, 'Key');
// THEN
expect(() => {
new ecr.Repository(stack, 'Repo', { encryption: ecr.RepositoryEncryption.AES_256, encryptionKey: custom_key });
}).toThrow('encryptionKey is specified, so \'encryption\' must be set to KMS (value: AES256)');
});
describe('events', () => {
test('onImagePushed without imageTag creates the correct event', () => {
const stack = new cdk.Stack();
const repo = new ecr.Repository(stack, 'Repo');
repo.onCloudTrailImagePushed('EventRule', {
target: {
bind: () => ({ arn: 'ARN', id: '' }),
},
});
Template.fromStack(stack).hasResourceProperties('AWS::Events::Rule', {
'EventPattern': {
'source': [
'aws.ecr',
],
'detail': {
'eventName': [
'PutImage',
],
'requestParameters': {
'repositoryName': [
{
'Ref': 'Repo02AC86CF',
},
],
},
},
},
'State': 'ENABLED',
});
});
test('onImageScanCompleted without imageTags creates the correct event', () => {
const stack = new cdk.Stack();
const repo = new ecr.Repository(stack, 'Repo');
repo.onImageScanCompleted('EventRule', {
target: {
bind: () => ({ arn: 'ARN', id: '' }),
},
});
Template.fromStack(stack).hasResourceProperties('AWS::Events::Rule', {
'EventPattern': {
'source': [
'aws.ecr',
],
'detail': {
'repository-name': [
{
'Ref': 'Repo02AC86CF',
},
],
'scan-status': [
'COMPLETE',
],
},
},
'State': 'ENABLED',
});
});
test('onImageScanCompleted with one imageTag creates the correct event', () => {
const stack = new cdk.Stack();
const repo = new ecr.Repository(stack, 'Repo');
repo.onImageScanCompleted('EventRule', {
imageTags: ['some-tag'],
target: {
bind: () => ({ arn: 'ARN', id: '' }),
},
});
Template.fromStack(stack).hasResourceProperties('AWS::Events::Rule', {
'EventPattern': {
'source': [
'aws.ecr',
],
'detail': {
'repository-name': [
{
'Ref': 'Repo02AC86CF',
},
],
'image-tags': [
'some-tag',
],
'scan-status': [
'COMPLETE',
],
},
},
'State': 'ENABLED',
});
});
test('onImageScanCompleted with multiple imageTags creates the correct event', () => {
const stack = new cdk.Stack();
const repo = new ecr.Repository(stack, 'Repo');
repo.onImageScanCompleted('EventRule', {
imageTags: ['tag1', 'tag2', 'tag3'],
target: {
bind: () => ({ arn: 'ARN', id: '' }),
},
});
Template.fromStack(stack).hasResourceProperties('AWS::Events::Rule', {
'EventPattern': {
'source': [
'aws.ecr',
],
'detail': {
'repository-name': [
{
'Ref': 'Repo02AC86CF',
},
],
'image-tags': [
'tag1',
'tag2',
'tag3',
],
'scan-status': [
'COMPLETE',
],
},
},
'State': 'ENABLED',
});
});
test('removal policy is "Retain" by default', () => {
// GIVEN
const stack = new cdk.Stack();
// WHEN
new ecr.Repository(stack, 'Repo');
// THEN
Template.fromStack(stack).hasResource('AWS::ECR::Repository', {
'Type': 'AWS::ECR::Repository',
'DeletionPolicy': 'Retain',
});
});
test('"Delete" removal policy can be set explicitly', () => {
// GIVEN
const stack = new cdk.Stack();
// WHEN
new ecr.Repository(stack, 'Repo', {
removalPolicy: cdk.RemovalPolicy.DESTROY,
});
// THEN
Template.fromStack(stack).hasResource('AWS::ECR::Repository', {
'Type': 'AWS::ECR::Repository',
'DeletionPolicy': 'Delete',
});
});
test('grant adds appropriate resource-*', () => {
// GIVEN
const stack = new cdk.Stack();
const repo = new ecr.Repository(stack, 'TestHarnessRepo');
// WHEN
repo.grantPull(new iam.AnyPrincipal());
// THEN
Template.fromStack(stack).hasResourceProperties('AWS::ECR::Repository', {
'RepositoryPolicyText': {
'Statement': [
{
'Action': [
'ecr:BatchCheckLayerAvailability',
'ecr:GetDownloadUrlForLayer',
'ecr:BatchGetImage',
],
'Effect': 'Allow',
'Principal': { 'AWS': '*' },
},
],
'Version': '2012-10-17',
},
});
});
});
describe('repository name validation', () => {
test('repository name validations', () => {
const stack = new cdk.Stack();
expect(() => new ecr.Repository(stack, 'Repo1', {
repositoryName: 'abc-xyz-34ab',
})).not.toThrow();
expect(() => new ecr.Repository(stack, 'Repo2', {
repositoryName: '124/pp-33',
})).not.toThrow();
});
test('repository name validation skips tokenized values', () => {
const stack = new cdk.Stack();
expect(() => new ecr.Repository(stack, 'Repo', {
repositoryName: cdk.Lazy.string({ produce: () => '_REPO' }),
})).not.toThrow();
});
test('fails with message on invalid repository names', () => {
const stack = new cdk.Stack();
const repositoryName = `-repositoRy.--${new Array(256).join('$')}`;
const expectedErrors = [
`Invalid ECR repository name (value: ${repositoryName})`,
'Repository name must be at least 2 and no more than 256 characters',
'Repository name must follow the specified pattern: (?:[a-z0-9]+(?:[._-][a-z0-9]+)*/)*[a-z0-9]+(?:[._-][a-z0-9]+)*',
].join(EOL);
expect(() => new ecr.Repository(stack, 'Repo', {
repositoryName,
})).toThrow(expectedErrors);
});
test('fails if repository name has less than 2 or more than 256 characters', () => {
const stack = new cdk.Stack();
expect(() => new ecr.Repository(stack, 'Repo1', {
repositoryName: 'a',
})).toThrow(/at least 2/);
expect(() => new ecr.Repository(stack, 'Repo2', {
repositoryName: new Array(258).join('x'),
})).toThrow(/no more than 256/);
});
test('fails if repository name does not follow the specified pattern', () => {
const stack = new cdk.Stack();
expect(() => new ecr.Repository(stack, 'Repo1', {
repositoryName: 'aAa',
})).toThrow(/must follow the specified pattern/);
expect(() => new ecr.Repository(stack, 'Repo2', {
repositoryName: 'a--a',
})).toThrow(/must follow the specified pattern/);
expect(() => new ecr.Repository(stack, 'Repo3', {
repositoryName: 'a./a-a',
})).toThrow(/must follow the specified pattern/);
expect(() => new ecr.Repository(stack, 'Repo4', {
repositoryName: 'a//a-a',
})).toThrow(/must follow the specified pattern/);
});
});
});