-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathS3Bucket.js
More file actions
2578 lines (2334 loc) · 116 KB
/
S3Bucket.js
File metadata and controls
2578 lines (2334 loc) · 116 KB
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
require('rubico/global')
const crypto = require('crypto')
const HTTP = require('./HTTP')
const Readable = require('./Readable')
const userAgent = require('./userAgent')
const AwsAuthorization = require('./internal/AwsAuthorization')
const AmzDate = require('./internal/AmzDate')
const AwsError = require('./internal/AwsError')
const parseURL = require('./internal/parseURL')
const createS3DeleteObjectError = require('./internal/createS3DeleteObjectError')
const XML = require('./XML')
const HTMLEntities = require('html-entities')
const encodeURIComponentRFC3986 = require('./internal/encodeURIComponentRFC3986')
/**
* @name S3Bucket
*
* @docs
* ```coffeescript [specscript]
* new S3Bucket(options {
* name string,
* accessKeyId: string,
* secretAccessKey: string,
* region: string,
* endpoint: string
* BlockPublicACLs: boolean,
* IgnorePublicACLs: boolean,
* BlockPublicPolicy: boolean,
* RestrictPublicBuckets: boolean,
* RequestPayer: 'Requester'|'BucketOwner',
* ObjectLockEnabled: boolean,
* ObjectLockDefaultRetentionMode: 'COMPLIANCE'|'GOVERNANCE',
* ObjectLockDefaultRetentionDays: number,
* ObjectLockDefaultRetentionYears: number,
* VersioningMfaDelete: 'Enabled'|'Disabled',
* VersioningStatus: 'Enabled'|'Suspended',
* }) -> s3bucket S3Bucket
* ```
*
* Presidium S3Bucket client for [AWS S3](https://aws.amazon.com/s3/). Creates a new S3 Bucket under `name` if a bucket does not already exist. Access to the newly creaed S3 Bucket is private.
*
* S3Bucket instances have a `ready` promise that resolves when the S3 Bucket is active.
*
* Arguments:
* * `options`
* * `name` - globally unique name of the AWS S3 Bucket.
* * `accessKeyId` - long term credential (ID) of an [IAM](https://aws.amazon.com/iam/) user.
* * `secretAccessKey` - long term credential (secret) of an [IAM](https://aws.amazon.com/iam/) user.
* * `region` - geographic location of data center cluster, e.g. `us-east-1` or `us-west-2`. [Full list of AWS regions](https://docs.aws.amazon.com/global-infrastructure/latest/regions/aws-regions.html#available-regions)
* * `BlockPublicACLs` - if `false`, AWS S3 does not block public access control lists (ACLs) for this bucket and objects in this bucket. Default `true`.
* * `IgnorePublicACLs` - if `false`, AWS S3 does not ignore public access control lists (ACLs) for this bucket and objects in this bucket. Default `true`.
* * `BlockPublicPolicy` - if `false`, AWS S3 does not block public bucket policies for this bucket. Default `true`.
* * `RestrictPublicBuckets` - if `false`, AWS S3 does not restrict public bucket policies for this bucket. Default `true`.
* * `RequestPayer` - the payer for requests to the AWS S3 Bucket. Defaults to `BucketOwner`.
* * `ObjectLockEnabled` - if `true`, AWS S3 enables Object Lock for this bucket. Defaults to `false`.
* * `ObjectLockDefaultRetentionMode` - the default Object Lock mode (`'GOVERNANCE'` or `'COMPLIANCE'`) for this bucket. Defaults to `'COMPLIANCE'`
* * `'COMPLIANCE'` - no one, including the root user, can delete a locked object.
* * `'GOVERNANCE'` - users with special permissions can delete a locked object.
* * `ObjectLockDefaultRetentionDays` - number of days that a locked object is protected by Object Lock for this bucket.
* * `ObjectLockDefaultRetentionYears` - number of years that a locked object is protected by Object Lock for this bucket.
* * `VersioningMfaDelete` - if `'Enabled'`, AWS S3 requires multifactor authentication (MFA) before permanently deleting object versions or change bucket versioning states for this bucket. Defaults to `'Disabled'`.
* * `VersioningStatus` - if `'Enabled'`, AWS S3 enables versioning for objects in this bucket, and all objects added to the bucket receive a unique Version ID. If `'Suspended'`, existing object versions remain in the bucket, new objects receive a `null` Version ID, and overwrites of objects behave as they would in an unversioned bucket. Defaults to `'Suspended'`.
*
* Return:
* * `s3Bucket` - an S3Bucket instance.
*
* ```javascript
* const S3Bucket = require('presidium/S3Bucket')
* const AwsCredentials = require('presidium/AwsCredentials')
*
* const awsCreds = await AwsCredentials('default')
* awsCreds.region = 'us-east-1'
*
* const myBucket = new S3Bucket({
* name: 'my-bucket-name',
* ...awsCreds,
* })
* ```
*
*/
class S3Bucket {
constructor(options) {
this.name = options.name
this.accessKeyId = options.accessKeyId ?? ''
this.secretAccessKey = options.secretAccessKey ?? ''
this.region = options.region ?? ''
this.apiVersion = '2012-08-10'
this.host0 = 's3.amazonaws.com'
this.host1 = `s3.${this.region}.amazonaws.com`
this.endpoint0 = `s3.amazonaws.com/${this.name}`
this.endpoint1 = `s3.${this.region}.amazonaws.com/${this.name}`
this.protocol = 'https'
this.http0 = new HTTP(`${this.protocol}://${this.endpoint0}`)
this.http1 = new HTTP(`${this.protocol}://${this.endpoint1}`)
if (options.ACL) {
this.ACL = options.ACL
}
if (options.ObjectOwnership) {
this.ObjectOwnership = options.ObjectOwnership
}
this.BlockPublicACLs = options.BlockPublicACLs ?? true
this.IgnorePublicACLs = options.IgnorePublicACLs ?? true
this.BlockPublicPolicy = options.BlockPublicPolicy ?? true
this.RestrictPublicBuckets = options.RestrictPublicBuckets ?? true
this.RequestPayer = options.RequestPayer ?? 'BucketOwner'
this.ObjectLockEnabled = options.ObjectLockEnabled ?? false
this.ObjectLockDefaultRetentionMode =
options.ObjectLockDefaultRetentionMode // 'COMPLIANCE'|'GOVERNANCE'
this.ObjectLockDefaultRetentionDays =
options.ObjectLockDefaultRetentionDays
this.ObjectLockDefaultRetentionYears =
options.ObjectLockDefaultRetentionYears
if (
this.ObjectLockDefaultRetentionMode
&& this.ObjectLockDefaultRetentionDays == null
&& this.ObjectLockDefaultRetentionYears == null
) {
throw new Error('ObjectLockDefaultRetentionDays or ObjectLockDefaultRetentionYears must be specified with ObjectLockDefaultRetentionMode')
}
this.VersioningMfaDelete = options.VersioningMfaDelete ?? 'Disabled'
this.VersioningStatus = options.VersioningStatus ?? 'Suspended'
/**
* @name ready
*
* @docs
* ```coffeescript [specscript]
* ready -> promise Promise<>
* ```
*
* The ready promise for the S3Bucket instance. Resolves when the S3 Bucket is active.
*
* ```javascript
* const awsCreds = await AwsCredentials('default')
* awsCreds.region = 'us-east-1'
*
* const myBucket = new S3Bucket({
* name: 'my-bucket-name',
* ...awsCreds,
* })
* await myBucket.ready
* ```
*/
this.autoReady = options.autoReady ?? true
if (this.autoReady) {
this.ready = this._readyPromise()
}
}
/**
* @name _readyPromise
*
* @docs
* ```coffeescript [specscript]
* bucket._readyPromise() -> ready Promise<>
* ```
*/
async _readyPromise() {
try {
await this.getLocation()
return { message: 'bucket-exists' }
} catch (error) {
if (error.name == 'NoSuchBucket') {
await this.create()
await this.putPublicAccessBlock()
await this.putRequestPayment()
if (this.VersioningStatus == 'Enabled') {
await this.putVersioning()
}
if (this.ObjectLockEnabled) {
await this.putObjectLockConfiguration()
}
return { message: 'created-bucket' }
} else {
throw error
}
}
}
/**
* @name _awsRequest0
*
* @docs
* ```coffeescript [specscript]
* module http 'https://nodejs.org/api/http.html'
*
* table._awsRequest0(
* method string,
* url string,
* headers object
* body string
* ) -> response Promise<http.ServerResponse>
* ```
*/
_awsRequest0(method, url, headers, body) {
const amzDate = AmzDate()
const payloadHash =
crypto.createHash('sha256').update(body, 'utf8').digest('hex')
const urlData = parseURL(url)
headers = {
'Host': this.host0,
'X-Amz-Content-SHA256': payloadHash,
'X-Amz-Date': amzDate,
'Date': new Date().toUTCString(),
'Content-Length': Buffer.byteLength(body, 'utf8'),
'User-Agent': userAgent,
...headers,
}
const amzHeaders = {}
for (const key in headers) {
if (key.toLowerCase().startsWith('x-amz')) {
amzHeaders[key] = headers[key]
}
}
const authorizationHeaders = {
'Host': this.host0,
...headers['Content-MD5'] ? {
'Content-MD5': headers['Content-MD5']
} : {},
...amzHeaders
}
headers['Authorization'] = AwsAuthorization({
accessKeyId: this.accessKeyId,
secretAccessKey: this.secretAccessKey,
region: this.region,
method,
endpoint: this.endpoint0,
protocol: this.protocol,
canonicalUri: `/${this.name}${urlData.pathname}`,
serviceName: 's3',
payloadHash,
expires: 300,
queryParams: urlData.searchParams,
headers: authorizationHeaders,
})
return this.http0[method](url, { headers, body })
}
/**
* @name _awsRequest1
*
* @docs
* ```coffeescript [specscript]
* module http 'https://nodejs.org/api/http.html'
*
* table._awsRequest1(
* method string,
* url string,
* headers object
* body string
* ) -> response Promise<http.ServerResponse>
* ```
*/
_awsRequest1(method, url, headers, body) {
const amzDate = AmzDate()
const payloadHash =
crypto.createHash('sha256').update(body, 'utf8').digest('hex')
const urlData = parseURL(url)
headers = {
'Host': this.host1,
'X-Amz-Content-SHA256': payloadHash,
'X-Amz-Date': amzDate,
'Date': new Date().toUTCString(),
'Content-Length': Buffer.byteLength(body, 'utf8'),
'User-Agent': userAgent,
...headers,
}
const amzHeaders = {}
for (const key in headers) {
if (key.toLowerCase().startsWith('x-amz')) {
amzHeaders[key] = headers[key]
}
}
const authorizationHeaders = {
'Host': this.host1,
...headers['Content-MD5'] ? {
'Content-MD5': headers['Content-MD5']
} : {},
...amzHeaders
}
headers['Authorization'] = AwsAuthorization({
accessKeyId: this.accessKeyId,
secretAccessKey: this.secretAccessKey,
region: this.region,
method,
endpoint: this.endpoint1,
protocol: this.protocol,
canonicalUri: `/${this.name}${urlData.pathname}`,
serviceName: 's3',
payloadHash,
expires: 300,
queryParams: urlData.searchParams,
headers: authorizationHeaders,
})
return this.http1[method](url, { headers, body })
}
/**
* @name getLocation
*
* @docs
* ```coffeescript [specscript]
* bucket.getLocation() -> data Promise<{
* LocationConstraint: string|null
* }>
* ```
*/
async getLocation() {
const response = await this._awsRequest0('GET', '/?location', {}, '')
if (response.ok) {
const text = await Readable.Text(response)
const xmlData = XML.parse(HTMLEntities.decode(text))
return {
LocationConstraint: typeof xmlData.LocationConstraint == 'string'
? xmlData.LocationConstraint
: null
}
}
throw new AwsError(await Readable.Text(response), response.status)
}
/**
* @name create
*
* @docs
* ```coffeescript [specscript]
* bucket.create() -> data Promise<{}>
* ```
*
* Create the AWS S3 Bucket.
*
* Arguments:
* * (none)
*
* Return:
* * `data` - a promise of an empty object.
*
* ```javascript
* const awsCreds = await AwsCredentials('default')
* awsCreds.region = 'us-east-1'
*
* const myBucket = new S3Bucket({
* name: 'my-bucket-name',
* ...awsCreds,
* autoReady: false,
* })
*
* await myBucket.create()
* ```
*/
async create() {
const headers = {}
/*
if (this.ACL) {
headers['X-Amz-ACL'] = this.ACL
}
*/
if (this.ObjectOwnership) {
headers['X-Amz-Object-Ownership'] = this.ObjectOwnership
}
if (this.GrantFullControl) {
headers['X-Amz-Grant-Full-Control'] = this.GrantFullControl
}
const body = this.region == 'us-east-1' ? '' : `
<CreateBucketConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<LocationConstraint>${this.region}</LocationConstraint>
</CreateBucketConfiguration >
`.trim()
const response = await this._awsRequest1('PUT', '/', headers, body)
if (response.ok) {
await Readable.Text(response)
return {}
}
throw new AwsError(await Readable.Text(response), response.status)
}
/**
* @name putPublicAccessBlock
*
* @docs
* ```coffeescript [specscript]
* putPublicAccessBlock() -> data Promise<{}>
* ```
*
* Create or replace the `PublicAccessBlock` configuration for the AWS S3 Bucket.
*
*/
async putPublicAccessBlock() {
const headers = {}
const body = `
<?xml version="1.0" encoding="UTF-8"?>
<PublicAccessBlockConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<BlockPublicAcls>${this.BlockPublicACLs}</BlockPublicAcls>
<IgnorePublicAcls>${this.IgnorePublicACLs}</IgnorePublicAcls>
<BlockPublicPolicy>${this.BlockPublicPolicy}</BlockPublicPolicy>
<RestrictPublicBuckets>${this.RestrictPublicBuckets}</RestrictPublicBuckets>
</PublicAccessBlockConfiguration>
`.trim()
headers['Content-MD5'] = crypto.createHash('md5').update(body).digest('base64')
const response = await this._awsRequest1('PUT', '/?publicAccessBlock', headers, body)
if (response.ok) {
await Readable.Text(response)
return {}
}
throw new AwsError(await Readable.Text(response), response.status)
}
/**
* @name putRequestPayment
*
* @docs
* ```coffeescript [specscript]
* putRequestPayment() -> data Promise<{}>
* ```
*
* Create or replace the `RequestPayment` configuration for the AWS S3 Bucket.
*
*/
async putRequestPayment() {
const headers = {}
const body = `
<?xml version="1.0" encoding="UTF-8"?>
<RequestPaymentConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<Payer>${this.RequestPayer}</Payer>
</RequestPaymentConfiguration>
`.trim()
headers['Content-MD5'] = crypto.createHash('md5').update(body).digest('base64')
const response = await this._awsRequest1('PUT', '/?requestPayment', headers, body)
if (response.ok) {
await Readable.Text(response)
return {}
}
throw new AwsError(await Readable.Text(response), response.status)
}
/**
* @name putObjectLockConfiguration
*
* @docs
* ```coffeescript [specscript]
* putObjectLockConfiguration() -> Promise<{}>
* ```
*
* Apply an AWS S3 Bucket policy to an AWS S3 Bucket.
*
*/
async putObjectLockConfiguration() {
const headers = {}
const body = `
<?xml version="1.0" encoding="UTF-8"?>
<ObjectLockConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<ObjectLockEnabled>Enabled</ObjectLockEnabled>
${this.ObjectLockDefaultRetentionMode ? `
<Rule>
<DefaultRetention>
<Mode>${this.ObjectLockDefaultRetentionMode}</Mode>
${
this.ObjectLockDefaultRetentionDays == null
? `<Years>${this.ObjectLockDefaultRetentionYears}</Years>`
: `<Days>${this.ObjectLockDefaultRetentionDays}</Days>`
}
</DefaultRetention>
</Rule>
` : ''}
</ObjectLockConfiguration>
`.trim()
headers['Content-MD5'] = crypto.createHash('md5').update(body).digest('base64')
const response = await this._awsRequest0('PUT', '/?object-lock', headers, body)
if (response.ok) {
await Readable.Text(response)
return {}
}
throw new AwsError(await Readable.Text(response), response.status)
}
/**
* @name putVersioning
*
* @docs
* ```coffeescript [specscript]
* putVersioning() -> Promise<{}>
* ```
*
* Apply an AWS S3 Bucket policy to an AWS S3 Bucket.
*
*/
async putVersioning() {
const headers = {}
const body = `
<?xml version="1.0" encoding="UTF-8"?>
<VersioningConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<MfaDelete>${this.VersioningMfaDelete}</MfaDelete>
<Status>${this.VersioningStatus}</Status>
</VersioningConfiguration>
`.trim()
headers['Content-MD5'] = crypto.createHash('md5').update(body).digest('base64')
const response = await this._awsRequest0('PUT', '/?versioning', headers, body)
if (response.ok) {
await Readable.Text(response)
return {}
}
throw new AwsError(await Readable.Text(response), response.status)
}
/**
* @name putPolicy
*
* @docs
* ```coffeescript [specscript]
* putPolicy(options {
* policy: object,
* }) -> data Promise<{}>
* ```
*
* Apply an [AWS Access Policy](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html) to an AWS S3 Bucket.
*
* Arguments:
* * `options`
* * `policy` - the access policy object
*
* Return:
* * `data` - a promise of an empty object.
*
* ```javascript
* const awsCreds = await AwsCredentials('default')
* awsCreds.region = 'us-east-1'
*
* const myBucket = new S3Bucket({
* name: 'my-bucket-name',
* ...awsCreds,
* })
* await myBucket.ready
*
* await myBucket.putPolicy({
* "Version": "2012-10-17",
* "Statement": [
* {
* "Effect": "Allow",
* "Principal": {
* "AWS": "arn:aws:iam::AccountA-ID:root"
* },
* "Action": "sts:AssumeRole"
* }
* ]
* })
* ```
*/
async putPolicy(options) {
const { policy } = options
const body = JSON.stringify(policy)
const response = await this._awsRequest0('PUT', '/?policy', {}, body)
if (response.ok) {
await Readable.Text(response)
return {}
}
throw new AwsError(await Readable.Text(response), response.status)
}
/**
* @name getPolicy
*
* @docs
* ```coffeescript [specscript]
* getPolicy() -> BucketPolicy Promise<{
* Version: string,
* Id: string,
* Statement: Array,
* }>
* ```
*
* Returns the [AWS Access Policy](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html) of an AWS S3 Bucket.
*
* Arguments:
* * (none)
*
* Return:
* * `BucketPolicy` - a promise of the bucket's access policy.
*
* ```javascript
* const awsCreds = await AwsCredentials('default')
* awsCreds.region = 'us-east-1'
*
* const myBucket = new S3Bucket({
* name: 'my-bucket-name',
* ...awsCreds,
* })
* await myBucket.ready
*
* const policy = await myBucket.getPolicy()
* ```
*/
async getPolicy() {
const response = await this._awsRequest0('GET', '/?policy', {}, '')
if (response.ok) {
const data = await Readable.JSON(response)
return data
}
throw new AwsError(await Readable.Text(response), response.status)
}
/**
* @name closeConnections
*
* @docs
* ```coffeescript [specscript]
* closeConnections() -> undefined
* ```
*
* Closes underlying TCP connections.
*
* Arguments:
* * (none)
*
* Return:
* * undefined
*/
closeConnections() {
this.http0.closeConnections()
this.http1.closeConnections()
}
/**
* @name delete
*
* @docs
* ```coffeescript [specscript]
* bucket.delete() -> data Promise<{}>
* ```
*
* Deletes an AWS S3 Bucket.
*
* Arguments:
* * (none)
*
* Return:
* * `data` - a promise of an empty object.
*
* ```javascript
* const awsCreds = await AwsCredentials('default')
* awsCreds.region = 'us-east-1'
*
* const myBucket = new S3Bucket({
* name: 'my-bucket-name',
* ...awsCreds,
* autoReady: false,
* })
*
* await myBucket.delete()
* ```
*
*/
async delete(options = {}) {
const response = await this._awsRequest1('DELETE', '/', {}, '')
if (response.ok) {
await Readable.Text(response)
return {}
}
throw new AwsError(await Readable.Text(response), response.status)
}
/**
* @name putObject
*
* @docs
* ```coffeescript [specscript]
* type DateString = string # Wed Dec 31 1969 16:00:00 GMT-0800 (PST)
* type TimestampSeconds = number # 1751111429
*
* bucket.putObject(
* key string,
* body Buffer|TypedArray|Blob|string|ReadableStream,
* options {
* ACL: 'private'|'public-read'|'public-read-write'|'authenticated-read'
* |'aws-exec-read'|'bucket-owner-read'|'bucket-owner-full-control',
* CacheControl: string,
* ContentDisposition: string,
* ContentEncoding: string,
* ContentLanguage: string,
* ContentLength: number,
* ContentMD5: string,
* ContentType: string,
* ChecksumAlgorithm: 'CRC32'|'CRC32C'|'SHA1'|'SHA256',
* ChecksumCRC32: string,
* ChecksumCRC32C: string,
* ChecksumCRC64NVME: string,
* ChecksumSHA1: string,
* ChecksumSHA256: string,
* Expires: Date|DateString|TimestampSeconds,
* IfNoneMatch: '*',
* GrantFullControl: string,
* GrantRead: string,
* GrantReadACP: string,
* GrantWriteACP: string,
* Metadata: Object<string>,
* ServerSideEncryption: 'AES256'|'aws:kms'|'aws:kms:dsse',
* StorageClass: 'STANDARD'|'REDUCED_REDUNDANCY'|'STANDARD_IA'|'ONEZONE_IA'
* |'INTELLIGENT_TIERING'|'GLACIER'|'DEEP_ARCHIVE'|'OUTPOSTS'
* |'GLACIER_IR'|'SNOW'|'EXPRESS_ONEZONE',
* WebsiteRedirectLocation: string,
* SSECustomerAlgorithm: string,
* SSECustomerKey: Buffer|TypedArray|Blob|string,
* SSECustomerKeyMD5: string,
* SSEKMSKeyId: string,
* SSEKMSEncryptionContext: string,
* BucketKeyEnabled: boolean,
* RequestPayer: 'Requester'|'BucketOwner'
* Tagging: string, # key1=value1&key2=value2
* ObjectLockMode: 'GOVERNANCE'|'COMPLIANCE',
* ObjectLockRetainUntilDate: Date|DateString|TimestampSeconds,
* ObjectLockLegalHoldStatus: 'ON'|'OFF',
* }
* ) -> data Promise<{
* Expiration: string,
* ETag: string,
* ChecksumCRC32: string,
* ChecksumCRC32C: string,
* ChecksumCRC64NVME: string,
* ChecksumSHA1: string,
* ChecksumSHA256: string,
* ServerSideEncryption: 'AES256'|'aws:kms'|'aws:kms:dsse',
* VersionId: string,
* SSECustomerAlgorithm: 'AES256'|'aws:kms'|'aws:kms:dsse',
* SSECustomerKeyMD5: string,
* SSEKMSKeyId: string,
* SSEKMSEncryptionContext: string,
* BucketKeyEnabled: boolean,
* }>
* ```
*
* Puts an object in the AWS S3 Bucket.
*
* Arguments:
* * `key` - the key of the object inside the bucket. An object key is essentially the path to the object inside a bucket without the leading slash.
* * `body` - the content of the object.
* * `options`
* * `ACL` - the [canned access control list (ACL)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/acl-overview.html#canned-acl) to apply to the object. For more information, see [Access control list (ACL) overview](https://docs.aws.amazon.com/AmazonS3/latest/userguide/acl-overview.html) from the _Amazon S3 User Guide_.
* * `CacheControl` - lists directives for caches along the request/response chain. For more information, see [Cache-Control](https://www.rfc-editor.org/rfc/rfc9111#section-5.2).
* * `ContentDisposition` - conveys additional information about how to process the response payload. For more information, see [Content-Disposition](https://www.rfc-editor.org/rfc/rfc6266#section-4).
* * `ContentEncoding` - indicates what content coding(s) have been applied to the object in order to obtain data in the media type referenced by the `ContentType` option. For more information, see [Content-Encoding](https://www.rfc-editor.org/rfc/rfc9110.html#section-8.4).
* * `ContentLanguage` - describes the natural language(s) of the intended audience for the object. For more information, see [Content-Language](https://www.rfc-editor.org/rfc/rfc9110.html#section-8.5)
* * `ContentLength` - indicates the object's data length as a non-negative integer number of bytes. For more information, see [Content-Length](https://www.rfc-editor.org/rfc/rfc9110.html#section-8.6).
* * `ContentMD5` - the base64-encoded 128-bit MD5 digest of the object. For more information, see [RFC 1864](https://datatracker.ietf.org/doc/html/rfc1864).
* * `ContentType` - indicates the media type of the object. For more information, see [Content-Type](https://www.rfc-editor.org/rfc/rfc9110.html#section-8.3).
* * `ChecksumAlgorithm`- indicates the algorithm used to create the [checksum](https://docs.aws.amazon.com/AmazonS3/latest/API/API_Checksum.html) of the object. For more information, see [Checking object integrity in Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/checking-object-integrity.html) from the _Amazon S3 User Guide_.
* * `ChecksumCRC32` - the base64-encoded, 32-bit CRC-32 [checksum](https://docs.aws.amazon.com/AmazonS3/latest/API/API_Checksum.html) of the object. For more information, see [Checking object integrity in Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/checking-object-integrity.html) from the _Amazon S3 User Guide_.
* * `ChecksumCRC32C` - the base64-encoded, 32-bit CRC-32C [checksum](https://docs.aws.amazon.com/AmazonS3/latest/API/API_Checksum.html) of the object. For more information, see [Checking object integrity in Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/checking-object-integrity.html) from the _Amazon S3 User Guide_.
* * `ChecksumCRC64NVME` - the base64-encoded, 64-bit CRC-64NVME [checksum](https://docs.aws.amazon.com/AmazonS3/latest/API/API_Checksum.html) of the object. For more information, see [Checking object integrity in Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/checking-object-integrity.html) from the _Amazon S3 User Guide_.
* * `ChecksumSHA1` - the base64-encoded, 160-bit SHA-1 digest of the object. For more information, see [Checking object integrity in Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/checking-object-integrity.html) from the _Amazon S3 User Guide_.
* * `ChecksumSHA256` - the base64-encoded, 256-bit SHA-256 digest of the object. For more information, see [Checking object integrity in Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/checking-object-integrity.html) from the _Amazon S3 User Guide_.
* * `Expires` - the date/time after which the object is considered stale. For more information, see [Expires](https://www.rfc-editor.org/rfc/rfc7234#section-5.3).
* * `IfNoneMatch` - uploads the object only if the object key name does not already exist in the bucket. Otherwise, Amazon S3 responds with `412 Precondition Failed`. If a conflicting operation occurs during the upload, Amazon S3 responds with `409 ConditionalRequestConflict`. For more information, see [RFC 7232](https://datatracker.ietf.org/doc/html/rfc7232) and [Add preconditions to S3 operations with conditional requests](https://docs.aws.amazon.com/AmazonS3/latest/userguide/conditional-requests.html).
* * `GrantFullControl` - gives the grantee READ, READ_ACP, and WRITE_ACP permissions on the object.
* * `GrantRead` - allows the grantee to read the object data and its metadata.
* * `GrantReadACP` - allows the grantee to read the object ACL.
* * `GrantWriteACP` - allows the grantee to write the ACL for the applicable object.
* * `Metadata` - [metadata](https://www.ibm.com/think/topics/metadata) about the object.
* * `ServerSideEncryption` - the server-side encryption algorithm used for object encryption. For more information, see [Using server-side encryption with Amazon S3 managed keys (SSE-S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingServerSideEncryption.html) from the _Amazon S3 User Guide_.
* * `StorageClass` - the [storage class](https://docs.aws.amazon.com/AmazonS3/latest/userguide/storage-class-intro.html) associated with the object. Defaults to `STANDARD`.
* * `WebsiteRedirectLocation` - if a bucket is configured as a website, redirects requests for this object to another object in the same bucket or to an external URL. Amazon S3 stores the value of this header in the object metadata. For information about object metadata, see [Working with object metadata](https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingMetadata.html) from the _Amazon S3 User Guide_.
* * `SSECustomerAlgorithm` - the server-side encryption algorithm used for object encryption. For more information, see [Using server-side encryption with Amazon S3 managed keys (SSE-S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingServerSideEncryption.html) from the _Amazon S3 User Guide_.
* * `SSECustomerKey` - the customer-provided encryption key used for object encryption. For more information, see [Using server-side encryption with Amazon S3 managed keys (SSE-S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingServerSideEncryption.html) from the _Amazon S3 User Guide_.
* * `SSECustomerKeyMD5` - the 128-bit MD5 digest of the encryption key according to [RFC 1321](https://www.ietf.org/rfc/rfc1321.txt). Amazon S3 uses this header to check for message integrity.
* * `SSEKMSKeyId` - the [AWS KMS](https://docs.aws.amazon.com/kms/latest/developerguide/overview.html) Key ID, Key ARN, or Key Alias used for object encryption. If a KMS key doesn't exist in the same account, this value must be the Key ARN.
* * `SSEKMSEncryptionContext` - additional [AWS KMS](https://docs.aws.amazon.com/kms/latest/developerguide/overview.html) contextual information used for object encryption. The value for this header is a base64-encoded string of a UTF-8 encoded JSON value containing the encryption context as key-value pairs. This value is stored as object metadata and is passed automatically to AWS KMS for future `GetObject` operations on the object. For more information, see [Encryption context](https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingKMSEncryption.html#encryption-context) from the _Amazon S3 User Guide_.
* * `BucketKeyEnabled` - if `true`, Amazon S3 uses the Amazon S3 Bucket key for object encryption with [AWS KMS](https://docs.aws.amazon.com/kms/latest/developerguide/overview.html) keys (SSE-KMS).
* * `Tagging` - the [tag-set](https://docs.aws.amazon.com/whitepapers/latest/tagging-best-practices/what-are-tags.html) for the object encoded as URL query paramters (e.g. "Key1=Value1&Key2=Value2).
* * `ObjectLockMode` - the object lock mode. For more information, see [Locking objects with Object Lock](https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-lock.html) from the _Amazon S3 User Guide_.
* * `ObjectLockRetainUntilDate` - the date/time when the object's Object Lock expires. For more information, see [Locking objects with Object Lock](https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-lock.html) from the _Amazon S3 User Guide_.
* * `ObjectLockLegalHoldStatus` - if `true`, a legal hold will be applied to the object. For more information, see [Locking objects with Object Lock](https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-lock.html) from the _Amazon S3 User Guide_.
*
* Return:
* * `data`
* * `Expiration` - if the expiration is configured for the object (see [PutBucketLifecycleConfiguration](https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutBucketLifecycleConfiguration.html) from the _Amazon S3 User Guide_), this header will be present in the response. Includes the `expiry-date` and `rule-id` key-value pairs that provide information about object expiration. The value of the `rule-id` is URL-encoded.
* * `ETag` - the entity tag or MD5 hash of the object.
* * `ChecksumCRC32` - the base64-encoded, 32-bit CRC-32 [checksum](https://docs.aws.amazon.com/AmazonS3/latest/API/API_Checksum.html) of the object. For more information, see [Checking object integrity in Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/checking-object-integrity.html) from the _Amazon S3 User Guide_.
* * `ChecksumCRC32C` - the base64-encoded, 32-bit CRC-32C [checksum](https://docs.aws.amazon.com/AmazonS3/latest/API/API_Checksum.html) of the object. For more information, see [Checking object integrity in Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/checking-object-integrity.html) from the _Amazon S3 User Guide_.
* * `ChecksumCRC64NVME` - the base64-encoded, 64-bit CRC-64NVME [checksum](https://docs.aws.amazon.com/AmazonS3/latest/API/API_Checksum.html) of the object. For more information, see [Checking object integrity in Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/checking-object-integrity.html) from the _Amazon S3 User Guide_.
* * `ChecksumSHA1` - the base64-encoded, 160-bit SHA-1 digest of the object. For more information, see [Checking object integrity in Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/checking-object-integrity.html) from the _Amazon S3 User Guide_.
* * `ChecksumSHA256` - the base64-encoded, 256-bit SHA-256 digest of the object. For more information, see [Checking object integrity in Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/checking-object-integrity.html) from the _Amazon S3 User Guide_.
* * `ChecksumType` - the checksum type of the object, which determines how part-level checksums are combined to create an object-level checksum for multipart objects. For more information, see [Checking object integrity in Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/checking-object-integrity.html) from the _Amazon S3 User Guide_.
* * `ServerSideEncryption` - the server-side encryption algorithm used for object encryption. For more information, see [Using server-side encryption with Amazon S3 managed keys (SSE-S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingServerSideEncryption.html) from the _Amazon S3 User Guide_.
* * `VersionId` - the specific version of the object. For more information, see [Retaining multiple versions of objects with S3 Versioning](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Versioning.html) from the _Amazon S3 User Guide_.
* * `SSECustomerAlgorithm` - the server-side encryption algorithm used for object encryption. For more information, see [Using server-side encryption with Amazon S3 managed keys (SSE-S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingServerSideEncryption.html) from the _Amazon S3 User Guide_.
* * `SSECustomerKeyMD5` - the 128-bit MD5 digest of the encryption key according to [RFC 1321](https://www.ietf.org/rfc/rfc1321.txt). Amazon S3 uses this header to check for message integrity.
* * `SSEKMSKeyId` - the [AWS KMS](https://docs.aws.amazon.com/kms/latest/developerguide/overview.html) Key ID, Key ARN, or Key Alias used for object encryption.
* * `SSEKMSEncryptionContext` - additional [AWS KMS](https://docs.aws.amazon.com/kms/latest/developerguide/overview.html) contextual information used for object encryption. The value for this header is a base64-encoded string of a UTF-8 encoded JSON value containing the encryption context as key-value pairs. This value is stored as object metadata and is passed automatically to AWS KMS for future `GetObject` operations on the object. For more information, see [Encryption context](https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingKMSEncryption.html#encryption-context) from the _Amazon S3 User Guide_.
* * `BucketKeyEnabled` - indicates that Amazon S3 used the Amazon S3 Bucket key for object encryption with [AWS KMS](https://docs.aws.amazon.com/kms/latest/developerguide/overview.html) keys (SSE-KMS).
*
* ```javascript
* const awsCreds = await AwsCredentials('default')
* awsCreds.region = 'us-east-1'
*
* const myBucket = new S3Bucket({
* name: 'my-bucket-name',
* ...awsCreds,
* })
* await myBucket.ready
*
* await myBucket.putObject('some-key', '{"hello":"world"}', {
* ContentType: 'application/json',
* })
* ```
*
*/
async putObject(key, body, options = {}) {
const headers = {}
if (options.ACL) {
headers['X-Amz-ACL'] = options.ACL
}
if (options.CacheControl) {
headers['Cache-Control'] = options.CacheControl
}
if (options.ContentDisposition) {
headers['Content-Disposition'] = options.ContentDisposition
}
if (options.ContentEncoding) {
headers['Content-Encoding'] = options.ContentEncoding
}
if (options.ContentLanguage) {
headers['Content-Language'] = options.ContentLanguage
}
if (options.ContentLength) {
headers['Content-Length'] = options.ContentLength
}
if (body.readable) {
body = await Readable.Buffer(body)
}
if (options.ContentMD5) {
headers['Content-MD5'] = options.ContentMD5
} else {
headers['Content-MD5'] = crypto.createHash('md5').update(body).digest('base64')
}
if (options.ContentType) {
headers['Content-Type'] = options.ContentType
} else {
headers['Content-Type'] = 'application/octet-stream'
}
if (options.ChecksumAlgorithm) {
headers['X-Amz-Checksum-Algorithm'] = options.ChecksumAlgorithm
}
if (options.ChecksumCRC32) {
headers['X-Amz-Checksum-CRC32'] = options.ChecksumCRC32
}
if (options.ChecksumCRC32C) {
headers['X-Amz-Checksum-CRC32C'] = options.ChecksumCRC32C
}
if (options.ChecksumCRC64NVME) {
headers['X-Amz-Checksum-CRC64NVME'] = options.ChecksumCRC64NVME
}
if (options.ChecksumSHA1) {
headers['X-Amz-Checksum-SHA1'] = options.ChecksumSHA1
}
if (options.ChecksumSHA256) {
headers['X-Amz-Checksum-SHA256'] = options.ChecksumSHA256
}
if (options.Expires) {
headers['Expires'] = options.Expires
}
if (options.IfNoneMatch) {
headers['If-None-Match'] = options.IfNoneMatch
}
if (options.GrantFullControl) {
headers['X-Amz-Grant-Full-Control'] = options.GrantFullControl
}
if (options.GrantRead) {
headers['X-Amz-Grant-Read'] = options.GrantRead
}
if (options.GrantReadACP) {
headers['X-Amz-Grant-Read-ACP'] = options.GrantReadACP
}
if (options.GrantWriteACP) {
headers['X-Amz-Grant-Write-ACP'] = options.GrantWriteACP
}
if (options.ServerSideEncryption) {
headers['X-Amz-Server-Side-Encryption'] = options.ServerSideEncryption
}
if (options.StorageClass) {
headers['X-Amz-Storage-Class'] = options.StorageClass
}
if (options.WebsiteRedirectLocation) {
headers['X-Amz-Website-Redirect-Location'] = options.WebsiteRedirectLocation
}
if (options.SSECustomerAlgorithm) {
headers['X-Amz-Server-Side-Encryption-Customer-Algorithm'] =
options.SSECustomerAlgorithm
}
if (options.SSECustomerKey) {
headers['X-Amz-Server-Side-Encryption-Customer-Key'] =
options.SSECustomerKey
}
if (options.SSECustomerKeyMD5) {
headers['X-Amz-Server-Side-Encryption-Customer-Key-MD5'] =
options.SSECustomerKeyMD5
}
if (options.SSEKMSKeyId) {
headers['X-Amz-Server-Side-Encryption-AWS-KMS-Key-ID'] = options.SSEKMSKeyId
}
if (options.SSEKMSEncryptionContext) {
headers['X-Amz-Server-Side-Encryption-Context'] =
options.SSEKMSEncryptionContext
}
if (options.BucketKeyEnabled) {
headers['X-Amz-Server-Side-Encryption-Bucket-Key-Enabled'] =
options.BucketKeyEnabled
}
if (options.Tagging) {
headers['X-Amz-Tagging'] = options.Tagging
}
if (options.ObjectLockMode) {
headers['X-Amz-Object-Lock-Mode'] = options.ObjectLockMode
}
if (options.ObjectLockRetainUntilDate) {
headers['X-Amz-Object-Lock-Retain-Until-Date'] =
options.ObjectLockRetainUntilDate
}
if (options.ObjectLockLegalHoldStatus) {
headers['X-Amz-Object-Lock-Legal-Hold'] =
options.ObjectLockLegalHoldStatus
}
const encodedKey = encodeURIComponentRFC3986(key).replace(/%2F/g, '/')
const response = await this._awsRequest1('PUT', `/${encodedKey}`, headers, body)
if (response.ok) {
const data = {}
if (response.headers['etag']) {
data.ETag = response.headers['etag']
}
/* TODO
// https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutObject.html;
// Sample Response for general purpose buckets: Expiration rule created using lifecycle configuration
if (response.headers['x-amz-expiration']) {
data.Expiration = response.headers['x-amz-expiration']
}
*/