-
Notifications
You must be signed in to change notification settings - Fork 4k
/
bucket.ts
3127 lines (2808 loc) · 109 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 { Construct } from 'constructs';
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';
import * as events from '../../aws-events';
import * as iam from '../../aws-iam';
import * as kms from '../../aws-kms';
import {
CustomResource,
Duration,
FeatureFlags,
Fn,
IResource,
Lazy,
RemovalPolicy,
Resource,
ResourceProps,
Stack,
Tags,
Token,
Tokenization,
Annotations,
} from '../../core';
import { CfnReference } from '../../core/lib/private/cfn-reference';
import { AutoDeleteObjectsProvider } from '../../custom-resource-handlers/dist/aws-s3/auto-delete-objects-provider.generated';
import * as cxapi from '../../cx-api';
import * as regionInformation from '../../region-info';
const AUTO_DELETE_OBJECTS_RESOURCE_TYPE = 'Custom::S3AutoDeleteObjects';
const AUTO_DELETE_OBJECTS_TAG = 'aws-cdk:auto-delete-objects';
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 its
* contents. Use `bucketArn` and `arnForObjects(keys)` to obtain ARNs for
* this bucket or objects.
*
* Note that the policy statement may or may not be added to the policy.
* For example, when an `IBucket` is created from an existing bucket,
* it's not possible to tell whether the bucket already has a policy
* attached, let alone to re-use that policy to add more statements to it.
* So it's safest to do nothing in these cases.
*
* @param permission the policy statement to be added to the bucket's
* policy.
* @returns metadata about the execution of this method. If the policy
* was not added, the value of `statementAdded` will be `false`. You
* should always check this value to make sure that the operation was
* actually carried out. Otherwise, synthesis and deploy will terminate
* silently, which may be confusing.
*/
addToResourcePolicy(permission: iam.PolicyStatement): iam.AddToResourcePolicyResult;
/**
* The https URL of an S3 object. For example:
*
* - `https://s3.us-west-1.amazonaws.com/onlybucket`
* - `https://s3.us-west-1.amazonaws.com/bucket/key`
* - `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 https Transfer Acceleration URL of an S3 object. Specify `dualStack: true` at the options
* for dual-stack endpoint (connect to the bucket over IPv6). For example:
*
* - `https://bucket.s3-accelerate.amazonaws.com`
* - `https://bucket.s3-accelerate.amazonaws.com/key`
*
* @param key The S3 key of the object. If not specified, the URL of the
* bucket is returned.
* @param options Options for generating URL.
* @returns an TransferAccelerationUrl token
*/
transferAccelerationUrlForObject(key?: string, options?: TransferAccelerationUrlOptions): string;
/**
* The virtual hosted-style URL of an S3 object. Specify `regional: false` at
* the options for non-regional URL. For example:
*
* - `https://only-bucket.s3.us-west-1.amazonaws.com`
* - `https://bucket.s3.us-west-1.amazonaws.com/key`
* - `https://bucket.s3.amazonaws.com/key`
* - `https://china-bucket.s3.cn-north-1.amazonaws.com.cn/mykey`
* @param key The S3 key of the object. If not specified, the URL of the
* bucket is returned.
* @param options Options for generating URL.
* @returns an ObjectS3Url token
*/
virtualHostedUrlForObject(key?: string, options?: VirtualHostedStyleUrlOptions): string;
/**
* The S3 URL of an S3 object. For example:
* - `s3://onlybucket`
* - `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 '*'). Parameter type is `any` but `string` should be passed in.
*/
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.
*
* Before CDK version 1.85.0, this method granted the `s3:PutObject*` permission that included `s3:PutObjectAcl`,
* which could be used to grant read/write object access to IAM principals in other accounts.
* If you want to get rid of that behavior, update your CDK version to 1.85.0 or later,
* and make sure the `@aws-cdk/aws-s3:grantWriteWithoutAcl` feature flag is set to `true`
* in the `context` key of your cdk.json file.
* If you've already updated, but still need the principal to have permissions to modify the ACLs,
* use the `grantPutAcl` method.
*
* @param identity The principal
* @param objectsKeyPattern Restrict the permission to a certain key pattern (default '*'). Parameter type is `any` but `string` should be passed in.
* @param allowedActionPatterns Restrict the permissions to certain list of action patterns
*/
grantWrite(identity: iam.IGrantable, objectsKeyPattern?: any, allowedActionPatterns?: string[]): 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 '*'). Parameter type is `any` but `string` should be passed in.
*/
grantPut(identity: iam.IGrantable, objectsKeyPattern?: any): iam.Grant;
/**
* Grant the given IAM identity permissions to modify the ACLs of objects in the given Bucket.
*
* If your application has the '@aws-cdk/aws-s3:grantWriteWithoutAcl' feature flag set,
* calling `grantWrite` or `grantReadWrite` no longer grants permissions to modify the ACLs of the objects;
* in this case, if you need to modify object ACLs, call this method explicitly.
*
* @param identity The principal
* @param objectsKeyPattern Restrict the permission to a certain key pattern (default '*')
*/
grantPutAcl(identity: iam.IGrantable, objectsKeyPattern?: string): iam.Grant;
/**
* Grants s3:DeleteObject* permission to an IAM principal for objects
* in this bucket.
*
* @param identity The principal
* @param objectsKeyPattern Restrict the permission to a certain key pattern (default '*'). Parameter type is `any` but `string` should be passed in.
*/
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.
*
* Before CDK version 1.85.0, this method granted the `s3:PutObject*` permission that included `s3:PutObjectAcl`,
* which could be used to grant read/write object access to IAM principals in other accounts.
* If you want to get rid of that behavior, update your CDK version to 1.85.0 or later,
* and make sure the `@aws-cdk/aws-s3:grantWriteWithoutAcl` feature flag is set to `true`
* in the `context` key of your cdk.json file.
* If you've already updated, but still need the principal to have permissions to modify the ACLs,
* use the `grantPutAcl` method.
*
* @param identity The principal
* @param objectsKeyPattern Restrict the permission to a certain key pattern (default '*'). Parameter type is `any` but `string` should be passed in.
*/
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;
/**
* Adds a bucket notification event destination.
* @param event The event to trigger the notification
* @param dest The notification destination (Lambda, SNS Topic or SQS Queue)
*
* @param filters S3 object key filter rules to determine which objects
* trigger this event. Each filter must include a `prefix` and/or `suffix`
* that will be matched against the s3 object key. Refer to the S3 Developer Guide
* for details about allowed filter rules.
*
* @see https://docs.aws.amazon.com/AmazonS3/latest/dev/NotificationHowTo.html#notification-how-to-filtering
*
* @example
*
* declare const myLambda: lambda.Function;
* const bucket = new s3.Bucket(this, 'MyBucket');
* bucket.addEventNotification(s3.EventType.OBJECT_CREATED, new s3n.LambdaDestination(myLambda), {prefix: 'home/myusername/*'})
*
* @see
* https://docs.aws.amazon.com/AmazonS3/latest/dev/NotificationHowTo.html
*/
addEventNotification(event: EventType, dest: IBucketNotificationDestination, ...filters: NotificationKeyFilter[]): void;
/**
* Subscribes a destination to receive notifications when an object is
* created in the bucket. This is identical to calling
* `onEvent(s3.EventType.OBJECT_CREATED)`.
*
* @param dest The notification destination (see onEvent)
* @param filters Filters (see onEvent)
*/
addObjectCreatedNotification(dest: IBucketNotificationDestination, ...filters: NotificationKeyFilter[]): void;
/**
* Subscribes a destination to receive notifications when an object is
* removed from the bucket. This is identical to calling
* `onEvent(EventType.OBJECT_REMOVED)`.
*
* @param dest The notification destination (see onEvent)
* @param filters Filters (see onEvent)
*/
addObjectRemovedNotification(dest: IBucketNotificationDestination, ...filters: NotificationKeyFilter[]): void;
/**
* Enables event bridge notification, causing all events below to be sent to EventBridge:
*
* - Object Deleted (DeleteObject)
* - Object Deleted (Lifecycle expiration)
* - Object Restore Initiated
* - Object Restore Completed
* - Object Restore Expired
* - Object Storage Class Changed
* - Object Access Tier Changed
* - Object ACL Updated
* - Object Tags Added
* - Object Tags Deleted
*/
enableEventBridgeNotification(): void;
}
/**
* A reference to a bucket outside this stack
*/
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 and region
*/
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;
/**
* Force the format of the website URL of the bucket. This should be true for
* regions launched since 2014.
*
* @default - inferred from available region information, `false` otherwise
*
* @deprecated The correct website url format can be inferred automatically from the bucket `region`.
* Always provide the bucket region if the `bucketWebsiteUrl` will be used.
* Alternatively provide the full `bucketWebsiteUrl` manually.
*/
readonly bucketWebsiteNewUrlFormat?: boolean;
/**
* KMS encryption key associated with this bucket.
*
* @default - no encryption key
*/
readonly encryptionKey?: kms.IKey;
/**
* If this bucket has been configured for static website hosting.
*
* @default false
*/
readonly isWebsite?: boolean;
/**
* The account this existing bucket belongs to.
*
* @default - it's assumed the bucket belongs to the same account as the scope it's being imported into
*/
readonly account?: string;
/**
* The region this existing bucket is in.
* Features that require the region (e.g. `bucketWebsiteUrl`) won't fully work
* if the region cannot be correctly inferred.
*
* @default - it's assumed the bucket is in the same region as the scope it's being imported into
*/
readonly region?: string;
/**
* The role to be used by the notifications handler
*
* @default - a new role will be created.
*/
readonly notificationsHandlerRole?: iam.IRole;
}
/**
* 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);
*
*/
export 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: boolean;
/**
* Whether to disallow public access
*/
protected abstract disallowPublicAccess?: boolean;
private notifications?: BucketNotifications;
protected notificationsHandlerRole?: iam.IRole;
protected objectOwnership?: ObjectOwnership;
constructor(scope: Construct, id: string, props: ResourceProps = {}) {
super(scope, id, props);
this.node.addValidation({ validate: () => this.policy?.document.validateForResourcePolicy() ?? [] });
}
/**
* 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?.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 its
* contents. Use `bucketArn` and `arnForObjects(keys)` to obtain ARNs for
* this bucket or objects.
*
* Note that the policy statement may or may not be added to the policy.
* For example, when an `IBucket` is created from an existing bucket,
* it's not possible to tell whether the bucket already has a policy
* attached, let alone to re-use that policy to add more statements to it.
* So it's safest to do nothing in these cases.
*
* @param permission the policy statement to be added to the bucket's
* policy.
* @returns metadata about the execution of this method. If the policy
* was not added, the value of `statementAdded` will be `false`. You
* should always check this value to make sure that the operation was
* actually carried out. Otherwise, synthesis and deploy will terminate
* silently, which may be confusing.
*/
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 };
}
/**
* The https URL of an S3 object. Specify `regional: false` at the options
* for non-regional URLs. For example:
*
* - `https://s3.us-west-1.amazonaws.com/onlybucket`
* - `https://s3.us-west-1.amazonaws.com/bucket/key`
* - `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.${this.env.region}.${stack.urlSuffix}/`;
if (typeof key !== 'string') {
return this.urlJoin(prefix, this.bucketName);
}
return this.urlJoin(prefix, this.bucketName, key);
}
/**
* The https Transfer Acceleration URL of an S3 object. Specify `dualStack: true` at the options
* for dual-stack endpoint (connect to the bucket over IPv6). For example:
*
* - `https://bucket.s3-accelerate.amazonaws.com`
* - `https://bucket.s3-accelerate.amazonaws.com/key`
*
* @param key The S3 key of the object. If not specified, the URL of the
* bucket is returned.
* @param options Options for generating URL.
* @returns an TransferAccelerationUrl token
*/
public transferAccelerationUrlForObject(key?: string, options?: TransferAccelerationUrlOptions): string {
const dualStack = options?.dualStack ? '.dualstack' : '';
const prefix = `https://${this.bucketName}.s3-accelerate${dualStack}.amazonaws.com/`;
if (typeof key !== 'string') {
return this.urlJoin(prefix);
}
return this.urlJoin(prefix, key);
}
/**
* The virtual hosted-style URL of an S3 object. Specify `regional: false` at
* the options for non-regional URL. For example:
*
* - `https://only-bucket.s3.us-west-1.amazonaws.com`
* - `https://bucket.s3.us-west-1.amazonaws.com/key`
* - `https://bucket.s3.amazonaws.com/key`
* - `https://china-bucket.s3.cn-north-1.amazonaws.com.cn/mykey`
*
* @param key The S3 key of the object. If not specified, the URL of the
* bucket is returned.
* @param options Options for generating URL.
* @returns an ObjectS3Url token
*/
public virtualHostedUrlForObject(key?: string, options?: VirtualHostedStyleUrlOptions): string {
const domainName = options?.regional ?? true ? this.bucketRegionalDomainName : this.bucketDomainName;
const prefix = `https://${domainName}`;
if (typeof key !== 'string') {
return prefix;
}
return this.urlJoin(prefix, key);
}
/**
* The S3 URL of an S3 object. For example:
*
* - `s3://onlybucket`
* - `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 {
const prefix = 's3://';
if (typeof key !== 'string') {
return this.urlJoin(prefix, this.bucketName);
}
return this.urlJoin(prefix, this.bucketName, key);
}
/**
* Returns an ARN that represents all objects within the bucket that match
* the key pattern specified. To represent all keys, specify ``"*"``.
*
* If you need to specify a keyPattern with multiple components, concatenate them into a single string, e.g.:
*
* 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 '*'). Parameter type is `any` but `string` should be passed in.
*/
public grantRead(identity: iam.IGrantable, objectsKeyPattern: any = '*') {
return this.grant(identity, perms.BUCKET_READ_ACTIONS, perms.KEY_READ_ACTIONS,
this.bucketArn,
this.arnForObjects(objectsKeyPattern));
}
public grantWrite(identity: iam.IGrantable, objectsKeyPattern: any = '*', allowedActionPatterns: string[] = []) {
const grantedWriteActions = allowedActionPatterns.length > 0 ? allowedActionPatterns : this.writeActions;
return this.grant(identity, grantedWriteActions, 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 '*'). Parameter type is `any` but `string` should be passed in.
*/
public grantPut(identity: iam.IGrantable, objectsKeyPattern: any = '*') {
return this.grant(identity, this.putActions, perms.KEY_WRITE_ACTIONS,
this.arnForObjects(objectsKeyPattern));
}
public grantPutAcl(identity: iam.IGrantable, objectsKeyPattern: string = '*') {
return this.grant(identity, perms.BUCKET_PUT_ACL_ACTIONS, [],
this.arnForObjects(objectsKeyPattern));
}
/**
* Grants s3:DeleteObject* permission to an IAM principal for objects
* in this bucket.
*
* @param identity The principal
* @param objectsKeyPattern Restrict the permission to a certain key pattern (default '*'). Parameter type is `any` but `string` should be passed in.
*/
public grantDelete(identity: iam.IGrantable, objectsKeyPattern: any = '*') {
return this.grant(identity, perms.BUCKET_DELETE_ACTIONS, [],
this.arnForObjects(objectsKeyPattern));
}
public grantReadWrite(identity: iam.IGrantable, objectsKeyPattern: any = '*') {
const bucketActions = perms.BUCKET_READ_ACTIONS.concat(this.writeActions);
// we need unique permissions because some permissions are common between read and write key actions
const keyActions = [...new Set([...perms.KEY_READ_ACTIONS, ...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” });
*
* Note that if this `IBucket` refers to an existing bucket, possibly not
* managed by CloudFormation, this method will have no effect, since it's
* impossible to modify the policy of an existing bucket.
*
* @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.AnyPrincipal(),
resource: this,
});
}
/**
* Adds a bucket notification event destination.
* @param event The event to trigger the notification
* @param dest The notification destination (Lambda, SNS Topic or SQS Queue)
*
* @param filters S3 object key filter rules to determine which objects
* trigger this event. Each filter must include a `prefix` and/or `suffix`
* that will be matched against the s3 object key. Refer to the S3 Developer Guide
* for details about allowed filter rules.
*
* @see https://docs.aws.amazon.com/AmazonS3/latest/dev/NotificationHowTo.html#notification-how-to-filtering
*
* @example
*
* declare const myLambda: lambda.Function;
* const bucket = new s3.Bucket(this, 'MyBucket');
* bucket.addEventNotification(s3.EventType.OBJECT_CREATED, new s3n.LambdaDestination(myLambda), {prefix: 'home/myusername/*'});
*
* @see
* https://docs.aws.amazon.com/AmazonS3/latest/dev/NotificationHowTo.html
*/
public addEventNotification(event: EventType, dest: IBucketNotificationDestination, ...filters: NotificationKeyFilter[]) {
this.withNotifications(notifications => notifications.addNotification(event, dest, ...filters));
}
private withNotifications(cb: (notifications: BucketNotifications) => void) {
if (!this.notifications) {
this.notifications = new BucketNotifications(this, 'Notifications', {
bucket: this,
handlerRole: this.notificationsHandlerRole,
});
}
cb(this.notifications);
}
/**
* Subscribes a destination to receive notifications when an object is
* created in the bucket. This is identical to calling
* `onEvent(EventType.OBJECT_CREATED)`.
*
* @param dest The notification destination (see onEvent)
* @param filters Filters (see onEvent)
*/
public addObjectCreatedNotification(dest: IBucketNotificationDestination, ...filters: NotificationKeyFilter[]) {
return this.addEventNotification(EventType.OBJECT_CREATED, dest, ...filters);
}
/**
* Subscribes a destination to receive notifications when an object is
* removed from the bucket. This is identical to calling
* `onEvent(EventType.OBJECT_REMOVED)`.
*
* @param dest The notification destination (see onEvent)
* @param filters Filters (see onEvent)
*/
public addObjectRemovedNotification(dest: IBucketNotificationDestination, ...filters: NotificationKeyFilter[]) {
return this.addEventNotification(EventType.OBJECT_REMOVED, dest, ...filters);
}
/**
* Enables event bridge notification, causing all events below to be sent to EventBridge:
*
* - Object Deleted (DeleteObject)
* - Object Deleted (Lifecycle expiration)
* - Object Restore Initiated
* - Object Restore Completed
* - Object Restore Expired
* - Object Storage Class Changed
* - Object Access Tier Changed
* - Object ACL Updated
* - Object Tags Added
* - Object Tags Deleted
*/
public enableEventBridgeNotification() {
this.withNotifications(notifications => notifications.enableEventBridgeNotification());
}
private get writeActions(): string[] {
return [
...perms.BUCKET_DELETE_ACTIONS,
...this.putActions,
];
}
private get putActions(): string[] {
return FeatureFlags.of(this).isEnabled(cxapi.S3_GRANT_WRITE_WITHOUT_ACL)
? perms.BUCKET_PUT_ACTIONS
: perms.LEGACY_BUCKET_PUT_ACTIONS;
}
private urlJoin(...components: string[]): string {
return components.reduce((result, component) => {
if (result.endsWith('/')) {
result = result.slice(0, -1);
}
if (component.startsWith('/')) {
component = component.slice(1);
}
return `${result}/${component}`;
});
}
private grant(
grantee: iam.IGrantable,
bucketActions: string[],
keyActions: string[],
resourceArn: string, ...otherResourceArns: string[]) {
const resources = [resourceArn, ...otherResourceArns];
const 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;
}
}
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;