/
Bucket.ts
717 lines (678 loc) · 18.1 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
import { Construct } from "constructs";
import { Queue } from "./Queue.js";
import { Topic } from "./Topic.js";
import { getFunctionRef, SSTConstruct, isCDKConstruct } from "./Construct.js";
import { App } from "./App.js";
import {
Function as Fn,
FunctionProps,
FunctionInlineDefinition,
FunctionDefinition,
} from "./Function.js";
import { BindingResource, BindingProps } from "./util/binding.js";
import { Permissions } from "./util/permission.js";
import { Duration, toCdkDuration } from "./util/duration.js";
import {
BucketProps as CDKBucketProps,
Bucket as CDKBucket,
BlockPublicAccess,
IBucket,
EventType,
CorsRule,
HttpMethods,
ObjectOwnership,
} from "aws-cdk-lib/aws-s3";
import {
LambdaDestination,
SnsDestination,
SqsDestination,
} from "aws-cdk-lib/aws-s3-notifications";
/////////////////////
// Interfaces
/////////////////////
export interface BucketCorsRule {
/**
* The collection of allowed HTTP methods.
*/
allowedMethods: (keyof typeof HttpMethods)[];
/**
* The collection of allowed origins.
*
* @example
* ```js
* // Allow all origins
* allowOrigins: ["*"]
*
* // Allow specific origins. Note that the url protocol, ie. "https://", is required.
* allowOrigins: ["https://domain.com"]
* ```
*/
allowedOrigins: string[];
/**
* The collection of allowed headers.
*/
allowedHeaders?: string[];
/**
* The collection of exposed headers.
*/
exposedHeaders?: string[];
/**
* A unique identifier for this rule.
*/
id?: string;
/**
* Specify how long the results of a preflight response can be cached
*/
maxAge?: Duration;
}
interface BucketBaseNotificationProps {
/**
* The S3 event types that will trigger the notification.
*/
events?: Lowercase<keyof typeof EventType>[];
/**
* S3 object key filter rules to determine which objects trigger this event.
*/
filters?: BucketFilter[];
}
export interface BucketFilter {
/**
* Filter what the key starts with
*/
prefix?: string;
/**
* Filter what the key ends with
*/
suffix?: string;
}
/**
* Used to define a function listener for the bucket
*
* @example
* ```js
* new Bucket(stack, "Bucket", {
* notifications: {
* myNotification: {
* function: "src/notification.main"
* }
* }
* }
* ```
*/
export interface BucketFunctionNotificationProps
extends BucketBaseNotificationProps {
/**
* String literal to signify that the notification is a function
*/
type?: "function";
/**
* The function to send notifications to
*/
function: FunctionDefinition;
}
/**
* Used to define a queue listener for the bucket
*
* @example
* ```js
* new Bucket(stack, "Bucket", {
* notifications: {
* myNotification: {
* type: "queue",
* queue: new Queue(stack, "Queue")
* }
* }
* }
* ```
*/
export interface BucketQueueNotificationProps
extends BucketBaseNotificationProps {
/**
* String literal to signify that the notification is a queue
*/
type: "queue";
/**
* The queue to send notifications to
*/
queue: Queue;
}
/**
* Used to define a topic listener for the bucket
*
* @example
* ```js
* new Bucket(stack, "Bucket", {
* notifications: {
* myNotification: {
* type: "topic",
* topic: new Topic(stack, "Topic")
* }
* }],
* }
* ```
*/
export interface BucketTopicNotificationProps
extends BucketBaseNotificationProps {
type: "topic";
/**
* The topic to send notifications to
*/
topic: Topic;
}
export interface BucketProps {
/**
* The name of the bucket.
*
* Note that it's not recommended to hard code a name for the bucket, because they must be globally unique.
*
* @example
* ```js
* new Bucket(stack, "Bucket", {
* name: "my-bucket",
* });
* ```
*/
name?: string;
/**
* The CORS configuration of this bucket.
* @default true
* @example
* ```js
* new Bucket(stack, "Bucket", {
* cors: true,
* });
* ```
*
* ```js
* new Bucket(stack, "Bucket", {
* cors: [
* {
* allowedMethods: ["GET"],
* allowedOrigins: ["https://www.example.com"],
* }
* ],
* });
* ```
*/
cors?: boolean | BucketCorsRule[];
/**
* Prevent any files from being uploaded with public access configured. Setting this to `true` prevents uploading objects with public ACLs.
* Note that setting to `false` does not necessarily mean that the bucket is completely accessible to the public. Rather, it enables the granting of public permissions on a per file basis.
* @default false
* @example
* ```js
* new Bucket(stack, "Bucket", {
* blockPublicACLs: true,
* });
* ```
*/
blockPublicACLs?: boolean;
/**
* The default function props to be applied to all the Lambda functions in the API. The `environment`, `permissions` and `layers` properties will be merged with per route definitions if they are defined.
*
* @example
* ```js
* new Bucket(stack, "Bucket", {
* defaults: {
* function: {
* timeout: 20,
* }
* },
* });
* ```
*/
defaults?: {
function?: FunctionProps;
};
/**
* Used to create notifications for various bucket events
*
* @example
* ```js
* new Bucket(stack, "Bucket", {
* notifications: {
* myNotification: "src/notification.main",
* }
* });
* ```
*/
notifications?: Record<
string,
| FunctionInlineDefinition
| BucketFunctionNotificationProps
| Queue
| BucketQueueNotificationProps
| Topic
| BucketTopicNotificationProps
>;
cdk?: {
/**
* Allows you to override default id for this construct.
*/
id?: string;
/**
* Allows you to override default settings this construct uses internally to create the bucket.
*
* @example
* ```js
* new Bucket(stack, "Bucket", {
* cdk: {
* bucket: {
* bucketName: "my-bucket",
* },
* }
* });
* ```
*/
bucket?: IBucket | CDKBucketProps;
};
}
/////////////////////
// Construct
/////////////////////
/**
* The `Bucket` construct is a higher level CDK construct that makes it easy to create an S3 Bucket and to define its notifications.
*
* @example
*
* ```js
* import { Bucket } from "sst/constructs";
*
* new Bucket(stack, "Bucket");
* ```
*/
export class Bucket extends Construct implements SSTConstruct {
public readonly id: string;
public readonly cdk: {
/**
* The internally created CDK `Bucket` instance.
*/
bucket: IBucket;
};
readonly notifications: Record<string, Fn | Queue | Topic> = {};
readonly bindingForAllNotifications: BindingResource[] = [];
readonly permissionsAttachedForAllNotifications: Permissions[] = [];
readonly props: BucketProps;
constructor(scope: Construct, id: string, props?: BucketProps) {
super(scope, props?.cdk?.id || id);
this.id = id;
this.props = props || {};
this.cdk = {} as any;
this.createBucket();
this.addNotifications(this, props?.notifications || {});
const app = this.node.root as App;
app.registerTypes(this);
}
/**
* The ARN of the internally created `Bucket` instance.
*/
public get bucketArn(): string {
return this.cdk.bucket.bucketArn;
}
/**
* The name of the internally created `Bucket` instance.
*/
public get bucketName(): string {
return this.cdk.bucket.bucketName;
}
/**
* A list of the internally created functions for the notifications.
*/
public get notificationFunctions(): Fn[] {
return Object.values(this.notifications).filter(
(notification) => notification instanceof Fn
) as Fn[];
}
/**
* Add notification subscriptions after the bucket has been created
*
* @example
* ```js {3}
* const bucket = new Bucket(stack, "Bucket");
* bucket.addNotifications(stack, {
* myNotification: "src/notification.main"
* });
* ```
*/
public addNotifications(
scope: Construct,
notifications: Record<
string,
| FunctionInlineDefinition
| BucketFunctionNotificationProps
| Queue
| BucketQueueNotificationProps
| Topic
| BucketTopicNotificationProps
>
): void {
Object.entries(notifications).forEach(
([notificationName, notification]) => {
this.addNotification(scope, notificationName, notification);
}
);
}
/**
* Binds the given list of resources to all bucket notifications
* @example
* ```js {20}
* const bucket = new Bucket(stack, "Bucket", {
* notifications: {
* myNotification: "src/function.handler",
* }
* });
*
* bucket.bind([STRIPE_KEY, bucket]);
* ```
*/
public bind(constructs: BindingResource[]) {
this.notificationFunctions.forEach((notification) =>
notification.bind(constructs)
);
this.bindingForAllNotifications.push(...constructs);
}
/**
* Binds the given list of resources to a specific bucket notification
*
* @example
* ```js {20}
* const bucket = new Bucket(stack, "Bucket", {
* notifications: {
* myNotification: "src/function.handler",
* }
* });
*
* bucket.bindToNotification("myNotification", ["s3"]);
* ```
*/
public bindToNotification(
notificationName: string,
constructs: BindingResource[]
): void {
const notification = this.notifications[notificationName];
if (!(notification instanceof Fn)) {
throw new Error(
`Cannot bind to the "${this.node.id}" Bucket notification because it's not a Lambda function`
);
}
notification.bind(constructs);
}
/**
* Attaches additional permissions to all bucket notifications
* @example
* ```js {20}
* const bucket = new Bucket(stack, "Bucket", {
* notifications: {
* myNotification: "src/function.handler",
* }
* });
*
* bucket.attachPermissions(["s3"]);
* ```
*/
public attachPermissions(permissions: Permissions): void {
this.notificationFunctions.forEach((notification) =>
notification.attachPermissions(permissions)
);
this.permissionsAttachedForAllNotifications.push(permissions);
}
/**
* Attaches additional permissions to a specific bucket notification
*
* @example
* ```js {20}
* const bucket = new Bucket(stack, "Bucket", {
* notifications: {
* myNotification: "src/function.handler",
* }
* });
*
* bucket.attachPermissionsToNotification("myNotification", ["s3"]);
* ```
*/
public attachPermissionsToNotification(
notificationName: string,
permissions: Permissions
): void {
const notification = this.notifications[notificationName];
if (!(notification instanceof Fn)) {
throw new Error(
`Cannot attach permissions to the "${this.node.id}" Bucket notification because it's not a Lambda function`
);
}
notification.attachPermissions(permissions);
}
public getConstructMetadata() {
return {
type: "Bucket" as const,
data: {
name: this.cdk.bucket.bucketName,
notifications: Object.values(this.notifications).map(getFunctionRef),
notificationNames: Object.keys(this.notifications),
},
};
}
/** @internal */
public getBindings(): BindingProps {
return {
clientPackage: "bucket",
variables: {
bucketName: {
type: "plain",
value: this.bucketName,
},
},
permissions: {
"s3:*": [this.bucketArn, `${this.bucketArn}/*`],
},
};
}
private createBucket() {
const { name, cors, blockPublicACLs, cdk } = this.props;
if (isCDKConstruct(cdk?.bucket)) {
if (cors !== undefined) {
throw new Error(
`Cannot configure the "cors" when "cdk.bucket" is a construct`
);
}
this.cdk.bucket = cdk?.bucket as CDKBucket;
} else {
this.cdk.bucket = new CDKBucket(this, "Bucket", {
bucketName: name,
cors: this.buildCorsConfig(cors),
blockPublicAccess: this.buildBlockPublicAccessConfig(blockPublicACLs),
objectOwnership: this.buildObjectOwnershipConfig(blockPublicACLs),
enforceSSL: true,
...cdk?.bucket,
});
}
}
private addNotification(
scope: Construct,
notificationName: string,
notification:
| FunctionInlineDefinition
| BucketFunctionNotificationProps
| Queue
| BucketQueueNotificationProps
| Topic
| BucketTopicNotificationProps
): void {
if (
notification instanceof Queue ||
(notification as BucketQueueNotificationProps).queue
) {
notification = notification as Queue | BucketQueueNotificationProps;
this.addQueueNotification(scope, notificationName, notification);
} else if (
notification instanceof Topic ||
(notification as BucketTopicNotificationProps).topic
) {
notification = notification as Topic | BucketTopicNotificationProps;
this.addTopicNotification(scope, notificationName, notification);
} else {
notification = notification as
| FunctionInlineDefinition
| BucketFunctionNotificationProps;
this.addFunctionNotification(scope, notificationName, notification);
}
}
private addQueueNotification(
_scope: Construct,
notificationName: string,
notification: Queue | BucketQueueNotificationProps
): void {
// Parse notification props
let notificationProps;
let queue: Queue;
if (notification instanceof Queue) {
notification = notification as Queue;
queue = notification;
} else {
notification = notification as BucketQueueNotificationProps;
notificationProps = {
events: notification.events,
filters: notification.filters,
};
queue = notification.queue;
}
this.notifications[notificationName] = queue;
// Create Notifications
const events = notificationProps?.events || [
"object_created",
"object_removed",
];
const filters = notificationProps?.filters || [];
events.forEach((event) =>
this.cdk.bucket.addEventNotification(
EventType[event.toUpperCase() as keyof typeof EventType],
new SqsDestination(queue.cdk.queue),
...filters
)
);
}
private addTopicNotification(
_scope: Construct,
notificationName: string,
notification: Topic | BucketTopicNotificationProps
): void {
// Parse notification props
let notificationProps;
let topic: Topic;
if (notification instanceof Topic) {
notification = notification as Topic;
topic = notification;
} else {
notification = notification as BucketTopicNotificationProps;
notificationProps = {
events: notification.events,
filters: notification.filters,
};
topic = notification.topic;
}
this.notifications[notificationName] = topic;
// Create Notifications
const events = notificationProps?.events || [
"object_created",
"object_removed",
];
const filters = notificationProps?.filters || [];
events.forEach((event) =>
this.cdk.bucket.addEventNotification(
EventType[event.toUpperCase() as keyof typeof EventType],
new SnsDestination(topic.cdk.topic),
...filters
)
);
}
private addFunctionNotification(
scope: Construct,
notificationName: string,
notification: FunctionInlineDefinition | BucketFunctionNotificationProps
): void {
// parse notification
let notificationFunction, notificationProps;
if ((notification as BucketFunctionNotificationProps).function) {
notification = notification as BucketFunctionNotificationProps;
notificationFunction = notification.function;
notificationProps = {
events: notification.events,
filters: notification.filters,
};
} else {
notificationFunction = notification as FunctionInlineDefinition;
}
// create function
const fn = Fn.fromDefinition(
scope,
`Notification_${this.node.id}_${notificationName}`,
notificationFunction,
this.props.defaults?.function,
`The "defaults.function" cannot be applied if an instance of a Function construct is passed in. Make sure to define all the consumers using FunctionProps, so the Table construct can apply the "defaults.function" to them.`
);
this.notifications[notificationName] = fn;
// create Notifications
const events = notificationProps?.events || [
"object_created",
"object_removed",
];
const filters = notificationProps?.filters || [];
events.forEach((event) =>
this.cdk.bucket.addEventNotification(
EventType[event.toUpperCase() as keyof typeof EventType],
new LambdaDestination(fn),
...filters
)
);
// attached permissions
this.permissionsAttachedForAllNotifications.forEach((permissions) =>
fn.attachPermissions(permissions)
);
fn.bind(this.bindingForAllNotifications);
}
private buildCorsConfig(
cors?: boolean | BucketCorsRule[]
): CorsRule[] | undefined {
if (cors === false) {
return;
}
if (cors === undefined || cors === true) {
return [
{
allowedHeaders: ["*"],
allowedMethods: [
HttpMethods.GET,
HttpMethods.PUT,
HttpMethods.HEAD,
HttpMethods.POST,
HttpMethods.DELETE,
],
allowedOrigins: ["*"],
},
];
}
return cors.map((e) => ({
allowedMethods: (e.allowedMethods || []).map(
(method) => HttpMethods[method as keyof typeof HttpMethods]
),
allowedOrigins: e.allowedOrigins,
allowedHeaders: e.allowedHeaders,
exposedHeaders: e.exposedHeaders,
id: e.id,
maxAge: e.maxAge && toCdkDuration(e.maxAge).toSeconds(),
}));
}
private buildBlockPublicAccessConfig(config?: boolean) {
return config === true
? BlockPublicAccess.BLOCK_ALL
: new BlockPublicAccess({
blockPublicAcls: false,
ignorePublicAcls: false,
});
}
private buildObjectOwnershipConfig(config?: boolean) {
return config === true
? ObjectOwnership.BUCKET_OWNER_ENFORCED
: ObjectOwnership.BUCKET_OWNER_PREFERRED;
}
}