-
Notifications
You must be signed in to change notification settings - Fork 4k
/
bucket.ts
1961 lines (1744 loc) · 63.4 KB
/
bucket.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
import { EOL } from 'os';
import * as events from '@aws-cdk/aws-events';
import * as iam from '@aws-cdk/aws-iam';
import * as kms from '@aws-cdk/aws-kms';
import { Construct, Fn, IResource, Lazy, RemovalPolicy, Resource, Stack, Token } from '@aws-cdk/core';
import { BucketPolicy } from './bucket-policy';
import { IBucketNotificationDestination } from './destination';
import { BucketNotifications } from './notifications-resource';
import * as perms from './perms';
import { LifecycleRule } from './rule';
import { CfnBucket } from './s3.generated';
import { parseBucketArn, parseBucketName } from './util';
export interface IBucket extends IResource {
/**
* The ARN of the bucket.
* @attribute
*/
readonly bucketArn: string;
/**
* The name of the bucket.
* @attribute
*/
readonly bucketName: string;
/**
* The URL of the static website.
* @attribute
*/
readonly bucketWebsiteUrl: string;
/**
* The Domain name of the static website.
* @attribute
*/
readonly bucketWebsiteDomainName: string;
/**
* The IPv4 DNS name of the specified bucket.
* @attribute
*/
readonly bucketDomainName: string;
/**
* The IPv6 DNS name of the specified bucket.
* @attribute
*/
readonly bucketDualStackDomainName: string;
/**
* The regional domain name of the specified bucket.
* @attribute
*/
readonly bucketRegionalDomainName: string;
/**
* If this bucket has been configured for static website hosting.
*/
readonly isWebsite?: boolean;
/**
* Optional KMS encryption key associated with this bucket.
*/
readonly encryptionKey?: kms.IKey;
/**
* The resource policy associated with this bucket.
*
* If `autoCreatePolicy` is true, a `BucketPolicy` will be created upon the
* first call to addToResourcePolicy(s).
*/
policy?: BucketPolicy;
/**
* Adds a statement to the resource policy for a principal (i.e.
* account/role/service) to perform actions on this bucket and/or it's
* contents. Use `bucketArn` and `arnForObjects(keys)` to obtain ARNs for
* this bucket or objects.
*/
addToResourcePolicy(permission: iam.PolicyStatement): iam.AddToResourcePolicyResult;
/**
* The https URL of an S3 object. For example:
* @example https://s3.us-west-1.amazonaws.com/onlybucket
* @example https://s3.us-west-1.amazonaws.com/bucket/key
* @example https://s3.cn-north-1.amazonaws.com.cn/china-bucket/mykey
* @param key The S3 key of the object. If not specified, the URL of the
* bucket is returned.
* @returns an ObjectS3Url token
*/
urlForObject(key?: string): string;
/**
* The S3 URL of an S3 object. For example:
* @example s3://onlybucket
* @example s3://bucket/key
* @param key The S3 key of the object. If not specified, the S3 URL of the
* bucket is returned.
* @returns an ObjectS3Url token
*/
s3UrlForObject(key?: string): string;
/**
* Returns an ARN that represents all objects within the bucket that match
* the key pattern specified. To represent all keys, specify ``"*"``.
*/
arnForObjects(keyPattern: string): string;
/**
* Grant read permissions for this bucket and it's contents to an IAM
* principal (Role/Group/User).
*
* If encryption is used, permission to use the key to decrypt the contents
* of the bucket will also be granted to the same principal.
*
* @param identity The principal
* @param objectsKeyPattern Restrict the permission to a certain key pattern (default '*')
*/
grantRead(identity: iam.IGrantable, objectsKeyPattern?: any): iam.Grant;
/**
* Grant write permissions to this bucket to an IAM principal.
*
* If encryption is used, permission to use the key to encrypt the contents
* of written files will also be granted to the same principal.
*
* @param identity The principal
* @param objectsKeyPattern Restrict the permission to a certain key pattern (default '*')
*/
grantWrite(identity: iam.IGrantable, objectsKeyPattern?: any): iam.Grant;
/**
* Grants s3:PutObject* and s3:Abort* permissions for this bucket to an IAM principal.
*
* If encryption is used, permission to use the key to encrypt the contents
* of written files will also be granted to the same principal.
* @param identity The principal
* @param objectsKeyPattern Restrict the permission to a certain key pattern (default '*')
*/
grantPut(identity: iam.IGrantable, objectsKeyPattern?: any): iam.Grant;
/**
* Grants s3:DeleteObject* permission to an IAM pricipal for objects
* in this bucket.
*
* @param identity The principal
* @param objectsKeyPattern Restrict the permission to a certain key pattern (default '*')
*/
grantDelete(identity: iam.IGrantable, objectsKeyPattern?: any): iam.Grant;
/**
* Grants read/write permissions for this bucket and it's contents to an IAM
* principal (Role/Group/User).
*
* If an encryption key is used, permission to use the key for
* encrypt/decrypt will also be granted.
*
* @param identity The principal
* @param objectsKeyPattern Restrict the permission to a certain key pattern (default '*')
*/
grantReadWrite(identity: iam.IGrantable, objectsKeyPattern?: any): iam.Grant;
/**
* Allows unrestricted access to objects from this bucket.
*
* IMPORTANT: This permission allows anyone to perform actions on S3 objects
* in this bucket, which is useful for when you configure your bucket as a
* website and want everyone to be able to read objects in the bucket without
* needing to authenticate.
*
* Without arguments, this method will grant read ("s3:GetObject") access to
* all objects ("*") in the bucket.
*
* The method returns the `iam.Grant` object, which can then be modified
* as needed. For example, you can add a condition that will restrict access only
* to an IPv4 range like this:
*
* const grant = bucket.grantPublicAccess();
* grant.resourceStatement!.addCondition(‘IpAddress’, { “aws:SourceIp”: “54.240.143.0/24” });
*
*
* @param keyPrefix the prefix of S3 object keys (e.g. `home/*`). Default is "*".
* @param allowedActions the set of S3 actions to allow. Default is "s3:GetObject".
* @returns The `iam.PolicyStatement` object, which can be used to apply e.g. conditions.
*/
grantPublicAccess(keyPrefix?: string, ...allowedActions: string[]): iam.Grant;
/**
* Defines a CloudWatch event that triggers when something happens to this bucket
*
* Requires that there exists at least one CloudTrail Trail in your account
* that captures the event. This method will not create the Trail.
*
* @param id The id of the rule
* @param options Options for adding the rule
*/
onCloudTrailEvent(id: string, options?: OnCloudTrailBucketEventOptions): events.Rule;
/**
* Defines an AWS CloudWatch event that triggers when an object is uploaded
* to the specified paths (keys) in this bucket using the PutObject API call.
*
* Note that some tools like `aws s3 cp` will automatically use either
* PutObject or the multipart upload API depending on the file size,
* so using `onCloudTrailWriteObject` may be preferable.
*
* Requires that there exists at least one CloudTrail Trail in your account
* that captures the event. This method will not create the Trail.
*
* @param id The id of the rule
* @param options Options for adding the rule
*/
onCloudTrailPutObject(id: string, options?: OnCloudTrailBucketEventOptions): events.Rule;
/**
* Defines an AWS CloudWatch event that triggers when an object at the
* specified paths (keys) in this bucket are written to. This includes
* the events PutObject, CopyObject, and CompleteMultipartUpload.
*
* Note that some tools like `aws s3 cp` will automatically use either
* PutObject or the multipart upload API depending on the file size,
* so using this method may be preferable to `onCloudTrailPutObject`.
*
* Requires that there exists at least one CloudTrail Trail in your account
* that captures the event. This method will not create the Trail.
*
* @param id The id of the rule
* @param options Options for adding the rule
*/
onCloudTrailWriteObject(id: string, options?: OnCloudTrailBucketEventOptions): events.Rule;
}
/**
* A reference to a bucket. The easiest way to instantiate is to call
* `bucket.export()`. Then, the consumer can use `Bucket.import(this, ref)` and
* get a `Bucket`.
*/
export interface BucketAttributes {
/**
* The ARN of the bucket. At least one of bucketArn or bucketName must be
* defined in order to initialize a bucket ref.
*/
readonly bucketArn?: string;
/**
* The name of the bucket. If the underlying value of ARN is a string, the
* name will be parsed from the ARN. Otherwise, the name is optional, but
* some features that require the bucket name such as auto-creating a bucket
* policy, won't work.
*/
readonly bucketName?: string;
/**
* The domain name of the bucket.
*
* @default Inferred from bucket name
*/
readonly bucketDomainName?: string;
/**
* The website URL of the bucket (if static web hosting is enabled).
*
* @default Inferred from bucket name
*/
readonly bucketWebsiteUrl?: string;
/**
* The regional domain name of the specified bucket.
*/
readonly bucketRegionalDomainName?: string;
/**
* The IPv6 DNS name of the specified bucket.
*/
readonly bucketDualStackDomainName?: string;
/**
* The format of the website URL of the bucket. This should be true for
* regions launched since 2014.
*
* @default false
*/
readonly bucketWebsiteNewUrlFormat?: boolean;
readonly encryptionKey?: kms.IKey;
/**
* If this bucket has been configured for static website hosting.
*
* @default false
*/
readonly isWebsite?: boolean;
}
/**
* Represents an S3 Bucket.
*
* Buckets can be either defined within this stack:
*
* new Bucket(this, 'MyBucket', { props });
*
* Or imported from an existing bucket:
*
* Bucket.import(this, 'MyImportedBucket', { bucketArn: ... });
*
* You can also export a bucket and import it into another stack:
*
* const ref = myBucket.export();
* Bucket.import(this, 'MyImportedBucket', ref);
*
*/
abstract class BucketBase extends Resource implements IBucket {
public abstract readonly bucketArn: string;
public abstract readonly bucketName: string;
public abstract readonly bucketDomainName: string;
public abstract readonly bucketWebsiteUrl: string;
public abstract readonly bucketWebsiteDomainName: string;
public abstract readonly bucketRegionalDomainName: string;
public abstract readonly bucketDualStackDomainName: string;
/**
* Optional KMS encryption key associated with this bucket.
*/
public abstract readonly encryptionKey?: kms.IKey;
/**
* If this bucket has been configured for static website hosting.
*/
public abstract readonly isWebsite?: boolean;
/**
* The resource policy associated with this bucket.
*
* If `autoCreatePolicy` is true, a `BucketPolicy` will be created upon the
* first call to addToResourcePolicy(s).
*/
public abstract policy?: BucketPolicy;
/**
* Indicates if a bucket resource policy should automatically created upon
* the first call to `addToResourcePolicy`.
*/
protected abstract autoCreatePolicy = false;
/**
* Whether to disallow public access
*/
protected abstract disallowPublicAccess?: boolean;
/**
* Define a CloudWatch event that triggers when something happens to this repository
*
* Requires that there exists at least one CloudTrail Trail in your account
* that captures the event. This method will not create the Trail.
*
* @param id The id of the rule
* @param options Options for adding the rule
*/
public onCloudTrailEvent(id: string, options: OnCloudTrailBucketEventOptions = {}): events.Rule {
const rule = new events.Rule(this, id, options);
rule.addTarget(options.target);
rule.addEventPattern({
source: ['aws.s3'],
detailType: ['AWS API Call via CloudTrail'],
detail: {
resources: {
ARN: options.paths ? options.paths.map(p => this.arnForObjects(p)) : [this.bucketArn],
},
},
});
return rule;
}
/**
* Defines an AWS CloudWatch event that triggers when an object is uploaded
* to the specified paths (keys) in this bucket using the PutObject API call.
*
* Note that some tools like `aws s3 cp` will automatically use either
* PutObject or the multipart upload API depending on the file size,
* so using `onCloudTrailWriteObject` may be preferable.
*
* Requires that there exists at least one CloudTrail Trail in your account
* that captures the event. This method will not create the Trail.
*
* @param id The id of the rule
* @param options Options for adding the rule
*/
public onCloudTrailPutObject(id: string, options: OnCloudTrailBucketEventOptions = {}): events.Rule {
const rule = this.onCloudTrailEvent(id, options);
rule.addEventPattern({
detail: {
eventName: ['PutObject'],
},
});
return rule;
}
/**
* Defines an AWS CloudWatch event that triggers when an object at the
* specified paths (keys) in this bucket are written to. This includes
* the events PutObject, CopyObject, and CompleteMultipartUpload.
*
* Note that some tools like `aws s3 cp` will automatically use either
* PutObject or the multipart upload API depending on the file size,
* so using this method may be preferable to `onCloudTrailPutObject`.
*
* Requires that there exists at least one CloudTrail Trail in your account
* that captures the event. This method will not create the Trail.
*
* @param id The id of the rule
* @param options Options for adding the rule
*/
public onCloudTrailWriteObject(id: string, options: OnCloudTrailBucketEventOptions = {}): events.Rule {
const rule = this.onCloudTrailEvent(id, options);
rule.addEventPattern({
detail: {
eventName: [
'CompleteMultipartUpload',
'CopyObject',
'PutObject',
],
requestParameters: {
bucketName: [this.bucketName],
key: options.paths,
},
},
});
return rule;
}
/**
* Adds a statement to the resource policy for a principal (i.e.
* account/role/service) to perform actions on this bucket and/or it's
* contents. Use `bucketArn` and `arnForObjects(keys)` to obtain ARNs for
* this bucket or objects.
*/
public addToResourcePolicy(permission: iam.PolicyStatement): iam.AddToResourcePolicyResult {
if (!this.policy && this.autoCreatePolicy) {
this.policy = new BucketPolicy(this, 'Policy', { bucket: this });
}
if (this.policy) {
this.policy.document.addStatements(permission);
return { statementAdded: true, policyDependable: this.policy };
}
return { statementAdded: false };
}
protected validate(): string[] {
const errors = super.validate();
errors.push(...this.policy?.document.validateForResourcePolicy() || []);
return errors;
}
/**
* The https URL of an S3 object. For example:
* @example https://s3.us-west-1.amazonaws.com/onlybucket
* @example https://s3.us-west-1.amazonaws.com/bucket/key
* @example https://s3.cn-north-1.amazonaws.com.cn/china-bucket/mykey
* @param key The S3 key of the object. If not specified, the URL of the
* bucket is returned.
* @returns an ObjectS3Url token
*/
public urlForObject(key?: string): string {
const stack = Stack.of(this);
const prefix = `https://s3.${stack.region}.${stack.urlSuffix}/`;
return this.buildUrl(prefix, key);
}
/**
* The S3 URL of an S3 object. For example:
* @example s3://onlybucket
* @example s3://bucket/key
* @param key The S3 key of the object. If not specified, the S3 URL of the
* bucket is returned.
* @returns an ObjectS3Url token
*/
public s3UrlForObject(key?: string): string {
return this.buildUrl('s3://', key);
}
/**
* Returns an ARN that represents all objects within the bucket that match
* the key pattern specified. To represent all keys, specify ``"*"``.
*
* If you specify multiple components for keyPattern, they will be concatenated::
*
* arnForObjects('home/', team, '/', user, '/*')
*
*/
public arnForObjects(keyPattern: string): string {
return `${this.bucketArn}/${keyPattern}`;
}
/**
* Grant read permissions for this bucket and it's contents to an IAM
* principal (Role/Group/User).
*
* If encryption is used, permission to use the key to decrypt the contents
* of the bucket will also be granted to the same principal.
*
* @param identity The principal
* @param objectsKeyPattern Restrict the permission to a certain key pattern (default '*')
*/
public grantRead(identity: iam.IGrantable, objectsKeyPattern: any = '*') {
return this.grant(identity, perms.BUCKET_READ_ACTIONS, perms.KEY_READ_ACTIONS,
this.bucketArn,
this.arnForObjects(objectsKeyPattern));
}
/**
* Grant write permissions to this bucket to an IAM principal.
*
* If encryption is used, permission to use the key to encrypt the contents
* of written files will also be granted to the same principal.
*
* @param identity The principal
* @param objectsKeyPattern Restrict the permission to a certain key pattern (default '*')
*/
public grantWrite(identity: iam.IGrantable, objectsKeyPattern: any = '*') {
return this.grant(identity, perms.BUCKET_WRITE_ACTIONS, perms.KEY_WRITE_ACTIONS,
this.bucketArn,
this.arnForObjects(objectsKeyPattern));
}
/**
* Grants s3:PutObject* and s3:Abort* permissions for this bucket to an IAM principal.
*
* If encryption is used, permission to use the key to encrypt the contents
* of written files will also be granted to the same principal.
* @param identity The principal
* @param objectsKeyPattern Restrict the permission to a certain key pattern (default '*')
*/
public grantPut(identity: iam.IGrantable, objectsKeyPattern: any = '*') {
return this.grant(identity, perms.BUCKET_PUT_ACTIONS, perms.KEY_WRITE_ACTIONS,
this.arnForObjects(objectsKeyPattern));
}
/**
* Grants s3:DeleteObject* permission to an IAM pricipal for objects
* in this bucket.
*
* @param identity The principal
* @param objectsKeyPattern Restrict the permission to a certain key pattern (default '*')
*/
public grantDelete(identity: iam.IGrantable, objectsKeyPattern: any = '*') {
return this.grant(identity, perms.BUCKET_DELETE_ACTIONS, [],
this.arnForObjects(objectsKeyPattern));
}
/**
* Grants read/write permissions for this bucket and it's contents to an IAM
* principal (Role/Group/User).
*
* If an encryption key is used, permission to use the key for
* encrypt/decrypt will also be granted.
*
* @param identity The principal
* @param objectsKeyPattern Restrict the permission to a certain key pattern (default '*')
*/
public grantReadWrite(identity: iam.IGrantable, objectsKeyPattern: any = '*') {
const bucketActions = perms.BUCKET_READ_ACTIONS.concat(perms.BUCKET_WRITE_ACTIONS);
const keyActions = perms.KEY_READ_ACTIONS.concat(perms.KEY_WRITE_ACTIONS);
return this.grant(identity,
bucketActions,
keyActions,
this.bucketArn,
this.arnForObjects(objectsKeyPattern));
}
/**
* Allows unrestricted access to objects from this bucket.
*
* IMPORTANT: This permission allows anyone to perform actions on S3 objects
* in this bucket, which is useful for when you configure your bucket as a
* website and want everyone to be able to read objects in the bucket without
* needing to authenticate.
*
* Without arguments, this method will grant read ("s3:GetObject") access to
* all objects ("*") in the bucket.
*
* The method returns the `iam.Grant` object, which can then be modified
* as needed. For example, you can add a condition that will restrict access only
* to an IPv4 range like this:
*
* const grant = bucket.grantPublicAccess();
* grant.resourceStatement!.addCondition(‘IpAddress’, { “aws:SourceIp”: “54.240.143.0/24” });
*
*
* @param keyPrefix the prefix of S3 object keys (e.g. `home/*`). Default is "*".
* @param allowedActions the set of S3 actions to allow. Default is "s3:GetObject".
*/
public grantPublicAccess(keyPrefix = '*', ...allowedActions: string[]) {
if (this.disallowPublicAccess) {
throw new Error("Cannot grant public access when 'blockPublicPolicy' is enabled");
}
allowedActions = allowedActions.length > 0 ? allowedActions : ['s3:GetObject'];
return iam.Grant.addToPrincipalOrResource({
actions: allowedActions,
resourceArns: [this.arnForObjects(keyPrefix)],
grantee: new iam.Anyone(),
resource: this,
});
}
private buildUrl(prefix: string, key?: string): string {
const components = [
prefix,
this.bucketName,
];
if (key) {
// trim prepending '/'
if (typeof key === 'string' && key.startsWith('/')) {
key = key.substr(1);
}
components.push('/');
components.push(key);
}
return components.join('');
}
private grant(
grantee: iam.IGrantable,
bucketActions: string[],
keyActions: string[],
resourceArn: string, ...otherResourceArns: string[]) {
const resources = [resourceArn, ...otherResourceArns];
const crossAccountAccess = this.isGranteeFromAnotherAccount(grantee);
let ret: iam.Grant;
if (crossAccountAccess) {
// if the access is cross-account, we need to trust the accessing principal in the bucket's policy
ret = iam.Grant.addToPrincipalAndResource({
grantee,
actions: bucketActions,
resourceArns: resources,
resource: this,
});
} else {
// if not, we don't need to modify the resource policy if the grantee is an identity principal
ret = iam.Grant.addToPrincipalOrResource({
grantee,
actions: bucketActions,
resourceArns: resources,
resource: this,
});
}
if (this.encryptionKey && keyActions && keyActions.length !== 0) {
this.encryptionKey.grant(grantee, ...keyActions);
}
return ret;
}
private isGranteeFromAnotherAccount(grantee: iam.IGrantable): boolean {
if (!(Construct.isConstruct(grantee))) {
return false;
}
const bucketStack = Stack.of(this);
const identityStack = Stack.of(grantee);
return bucketStack.account !== identityStack.account;
}
}
export interface BlockPublicAccessOptions {
/**
* Whether to block public ACLs
*
* @see https://docs.aws.amazon.com/AmazonS3/latest/dev/access-control-block-public-access.html#access-control-block-public-access-options
*/
readonly blockPublicAcls?: boolean;
/**
* Whether to block public policy
*
* @see https://docs.aws.amazon.com/AmazonS3/latest/dev/access-control-block-public-access.html#access-control-block-public-access-options
*/
readonly blockPublicPolicy?: boolean;
/**
* Whether to ignore public ACLs
*
* @see https://docs.aws.amazon.com/AmazonS3/latest/dev/access-control-block-public-access.html#access-control-block-public-access-options
*/
readonly ignorePublicAcls?: boolean;
/**
* Whether to restrict public access
*
* @see https://docs.aws.amazon.com/AmazonS3/latest/dev/access-control-block-public-access.html#access-control-block-public-access-options
*/
readonly restrictPublicBuckets?: boolean;
}
export class BlockPublicAccess {
public static readonly BLOCK_ALL = new BlockPublicAccess({
blockPublicAcls: true,
blockPublicPolicy: true,
ignorePublicAcls: true,
restrictPublicBuckets: true,
});
public static readonly BLOCK_ACLS = new BlockPublicAccess({
blockPublicAcls: true,
ignorePublicAcls: true,
});
public blockPublicAcls: boolean | undefined;
public blockPublicPolicy: boolean | undefined;
public ignorePublicAcls: boolean | undefined;
public restrictPublicBuckets: boolean | undefined;
constructor(options: BlockPublicAccessOptions) {
this.blockPublicAcls = options.blockPublicAcls;
this.blockPublicPolicy = options.blockPublicPolicy;
this.ignorePublicAcls = options.ignorePublicAcls;
this.restrictPublicBuckets = options.restrictPublicBuckets;
}
}
/**
* Specifies a metrics configuration for the CloudWatch request metrics from an Amazon S3 bucket.
*/
export interface BucketMetrics {
/**
* The ID used to identify the metrics configuration.
*/
readonly id: string;
/**
* The prefix that an object must have to be included in the metrics results.
*/
readonly prefix?: string;
/**
* Specifies a list of tag filters to use as a metrics configuration filter.
* The metrics configuration includes only objects that meet the filter's criteria.
*/
readonly tagFilters?: {[tag: string]: any};
}
/**
* All http request methods
*/
export enum HttpMethods {
/**
* The GET method requests a representation of the specified resource.
*/
GET = 'GET',
/**
* The PUT method replaces all current representations of the target resource with the request payload.
*/
PUT = 'PUT',
/**
* The HEAD method asks for a response identical to that of a GET request, but without the response body.
*/
HEAD = 'HEAD',
/**
* The POST method is used to submit an entity to the specified resource, often causing a change in state or side effects on the server.
*/
POST = 'POST',
/**
* The DELETE method deletes the specified resource.
*/
DELETE = 'DELETE',
}
/**
* Specifies a cross-origin access rule for an Amazon S3 bucket.
*/
export interface CorsRule {
/**
* A unique identifier for this rule.
*
* @default - No id specified.
*/
readonly id?: string;
/**
* The time in seconds that your browser is to cache the preflight response for the specified resource.
*
* @default - No caching.
*/
readonly maxAge?: number;
/**
* Headers that are specified in the Access-Control-Request-Headers header.
*
* @default - No headers allowed.
*/
readonly allowedHeaders?: string[];
/**
* An HTTP method that you allow the origin to execute.
*/
readonly allowedMethods: HttpMethods[];
/**
* One or more origins you want customers to be able to access the bucket from.
*/
readonly allowedOrigins: string[];
/**
* One or more headers in the response that you want customers to be able to access from their applications.
*
* @default - No headers exposed.
*/
readonly exposedHeaders?: string[];
}
/**
* All http request methods
*/
export enum RedirectProtocol {
HTTP = 'http',
HTTPS = 'https',
}
/**
* Specifies a redirect behavior of all requests to a website endpoint of a bucket.
*/
export interface RedirectTarget {
/**
* Name of the host where requests are redirected
*/
readonly hostName: string;
/**
* Protocol to use when redirecting requests
*
* @default - The protocol used in the original request.
*/
readonly protocol?: RedirectProtocol;
}
/**
* All supported inventory list formats.
*/
export enum InventoryFormat {
/**
* Generate the inventory list as CSV.
*/
CSV = 'CSV',
/**
* Generate the inventory list as Parquet.
*/
PARQUET = 'Parquet',
/**
* Generate the inventory list as Parquet.
*/
ORC = 'ORC',
}
/**
* All supported inventory frequencies.
*/
export enum InventoryFrequency {
/**
* A report is generated every day.
*/
DAILY = 'Daily',
/**
* A report is generated every Sunday (UTC timezone) after the initial report.
*/
WEEKLY = 'Weekly'
}
/**
* Inventory version support.
*/
export enum InventoryObjectVersion {
/**
* Includes all versions of each object in the report.
*/
ALL = 'All',
/**
* Includes only the current version of each object in the report.
*/
CURRENT = 'Current',
}
/**
* The destination of the inventory.
*/
export interface InventoryDestination {
/**
* Bucket where all inventories will be saved in.
*/
readonly bucket: IBucket;
/**
* The prefix to be used when saving the inventory.
*
* @default - No prefix.
*/
readonly prefix?: string;
/**
* The account ID that owns the destination S3 bucket.
* If no account ID is provided, the owner is not validated before exporting data.
* It's recommended to set an account ID to prevent problems if the destination bucket ownership changes.
*
* @default - No account ID.
*/
readonly bucketOwner?: string;
}
/**
* Specifies the inventory configuration of an S3 Bucket.
*
* @see https://docs.aws.amazon.com/AmazonS3/latest/dev/storage-inventory.html
*/
export interface Inventory {
/**
* The destination of the inventory.
*/
readonly destination: InventoryDestination;
/**
* The inventory will only include objects that meet the prefix filter criteria.
*
* @default - No objects prefix
*/
readonly objectsPrefix?: string;
/**
* The format of the inventory.
*
* @default InventoryFormat.CSV
*/
readonly format?: InventoryFormat;
/**
* Whether the inventory is enabled or disabled.
*
* @default true
*/
readonly enabled?: boolean;
/**
* The inventory configuration ID.
*
* @default - generated ID.
*/
readonly inventoryId?: string;
/**
* Frequency at which the inventory should be generated.
*
* @default InventoryFrequency.WEEKLY
*/
readonly frequency?: InventoryFrequency;
/**
* If the inventory should contain all the object versions or only the current one.
*
* @default InventoryObjectVersion.ALL
*/
readonly includeObjectVersions?: InventoryObjectVersion;
/**
* A list of optional fields to be included in the inventory result.
*
* @default - No optional fields.
*/
readonly optionalFields?: string[];
}
export interface BucketProps {
/**
* The kind of server-side encryption to apply to this bucket.
*
* If you choose KMS, you can specify a KMS key via `encryptionKey`. If
* encryption key is not specified, a key will automatically be created.
*
* @default - `Kms` if `encryptionKey` is specified, or `Unencrypted` otherwise.
*/
readonly encryption?: BucketEncryption;
/**
* External KMS key to use for bucket encryption.
*
* The 'encryption' property must be either not specified or set to "Kms".
* An error will be emitted if encryption is set to "Unencrypted" or
* "Managed".
*
* @default - If encryption is set to "Kms" and this property is undefined,
* a new KMS key will be created and associated with this bucket.
*/
readonly encryptionKey?: kms.IKey;
/**
* Physical name of this bucket.
*
* @default - Assigned by CloudFormation (recommended).
*/
readonly bucketName?: string;
/**
* Policy to apply when the bucket is removed from this stack.
*
* @default - The bucket will be orphaned.
*/
readonly removalPolicy?: RemovalPolicy;
/**
* Whether this bucket should have versioning turned on or not.
*