-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathclient.rb
2089 lines (1817 loc) · 79.3 KB
/
client.rb
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
# -*- coding: utf-8 -*-
# Copyright 2011-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
require 'rexml/document'
require 'pathname'
require 'stringio'
require 'json'
require 'digest/md5'
require 'base64'
require 'nokogiri'
require 'set'
module AWS
class S3
# Client class for Amazon Simple Storage Service (S3).
class Client < Core::Client
include RegionDetection
def initialize(options = {})
super(options.merge(:http_continue_threshold => 0))
end
signature_version :S3
API_VERSION = '2006-03-01'
XMLNS = "http://s3.amazonaws.com/doc/#{API_VERSION}/"
HTTP_200_ERROR_OPERATIONS = Set.new([
:complete_multipart_upload,
:copy_object,
:copy_part,
])
autoload :XML, 'aws/s3/client/xml'
# @api private
EMPTY_BODY_ERRORS = {
304 => Errors::NotModified,
403 => Errors::Forbidden,
400 => Errors::BadRequest,
404 => Errors::NoSuchKey,
}
# @api private
CACHEABLE_REQUESTS = Set[]
include DataOptions
include Core::UriEscape
# @param [Core::Http::Request] request
# @api private
def sign_request request
case @config.s3_signature_version.to_sym
when :v4 then v4_signer.sign_request(request)
when :v3 then v3_signer.sign_request(request)
else
raise "invalid signature version #{@config.s3_signature_version.inspect}"
end
end
protected
# @return [Core::Signers::S3]
def v3_signer
@v3_signer ||= Core::Signers::S3.new(credential_provider)
end
# @return [Core::Signers::Version4]
def v4_signer
@v4_signer ||= begin
Core::Signers::Version4.new(credential_provider, 's3', @region)
end
end
# @param [Http::Request] req
# @return [Boolean]
def chunk_sign? req
req.http_method == 'PUT' &&
req.headers['content-length'].to_i > 2 * 1024 * 1024 # 2MB
end
def self.bucket_method(method_name, verb, *args, &block)
method_options = (args.pop if args.last.kind_of?(Hash)) || {}
xml_grammar = (args.pop if args.last.respond_to?(:rules))
verb = verb.to_s.upcase
subresource = args.first
add_client_request_method(method_name) do
configure_request do |req, options|
require_bucket_name!(options[:bucket_name])
req.http_method = verb
req.bucket = options[:bucket_name]
req.add_param(subresource) if subresource
if header_options = method_options[:header_options]
header_options.each do |(opt, header)|
if value = options[opt]
# for backwards compatability we translate canned acls
# header values from symbols to strings (e.g.
# :public_read translates to 'public-read')
value = (opt == :acl ? value.to_s.tr('_', '-') : value)
req.headers[header] = value
end
end
end
end
instance_eval(&block) if block
if xml_grammar
parser = Core::XML::Parser.new(xml_grammar.rules)
process_response do |resp|
resp.data = parser.parse(resp.http_response.body)
super(resp)
end
simulate_response do |resp|
resp.data = parser.simulate
super(resp)
end
end
end
end
protected
def set_metadata request, options
if metadata = options[:metadata]
Array(metadata).each do |name, value|
request.headers["x-amz-meta-#{name}"] = value
end
end
end
def set_storage_class request, options
storage_class = options[:storage_class]
if storage_class.kind_of?(Symbol)
request.headers["x-amz-storage-class"] = storage_class.to_s.upcase
elsif storage_class
request.headers["x-amz-storage-class"] = storage_class
end
end
def set_server_side_encryption request, options
sse = options[:server_side_encryption]
if sse.is_a?(Symbol)
request.headers['x-amz-server-side-encryption'] = sse.to_s.upcase
elsif sse
request.headers['x-amz-server-side-encryption'] = sse
end
end
def extract_error_details response
if
(
response.http_response.status >= 300 ||
HTTP_200_ERROR_OPERATIONS.include?(response.request_type)
) and
body = response.http_response.body and
error = Core::XML::Parser.parse(body) and
error[:code]
then
[error[:code], error[:message]]
end
end
def empty_response_body? response_body
response_body.nil? or response_body == ''
end
# There are a few of s3 requests that can generate empty bodies and
# yet still be errors. These return empty bodies to comply with the
# HTTP spec. We have to detect these errors specially.
def populate_error resp
code = resp.http_response.status
if EMPTY_BODY_ERRORS.include?(code) and empty_response_body?(resp.http_response.body)
error_class = EMPTY_BODY_ERRORS[code]
resp.error = error_class.new(resp.http_request, resp.http_response)
else
super
end
end
def retryable_error? response
super ||
http_200_error?(response) ||
response.error.is_a?(Errors::RequestTimeout)
end
# S3 may return with a 200 status code in the response, but still
# embed an error in the body for the following operations:
#
# * `#complete_multipart_upload`
# * `#copy_object`
# * `#copy_part`
#
# To ensure the response is not in error, we have to parse
# it before the normal parser.
def http_200_error? response
HTTP_200_ERROR_OPERATIONS.include?(response.request_type) &&
extract_error_details(response)
end
def new_request
req = S3::Request.new
req.force_path_style = config.s3_force_path_style?
req
end
# Previously the access control policy could be specified via :acl
# as a string or an object that responds to #to_xml. The prefered
# method now is to pass :access_control_policy an xml document.
def move_access_control_policy options
if acl = options[:acl]
if acl.is_a?(String) and is_xml?(acl)
options[:access_control_policy] = options.delete(:acl)
elsif acl.respond_to?(:to_xml)
options[:access_control_policy] = options.delete(:acl).to_xml
end
end
end
# @param [String] possible_xml
# @return [Boolean] Returns `true` if the given string is a valid xml
# document.
def is_xml? possible_xml
begin
REXML::Document.new(possible_xml).has_elements?
rescue
false
end
end
def md5 str
Base64.encode64(OpenSSL::Digest::MD5.digest(str)).strip
end
def parse_copy_part_response resp
doc = REXML::Document.new(resp.http_response.body)
resp[:etag] = doc.root.elements["ETag"].text
resp[:last_modified] = doc.root.elements["LastModified"].text
if header = resp.http_response.headers['x-amzn-requestid']
data[:request_id] = [header].flatten.first
end
end
def extract_object_headers resp
meta = {}
resp.http_response.headers.each_pair do |name,value|
if name =~ /^x-amz-meta-(.+)$/i
meta[$1] = [value].flatten.join
end
end
resp.data[:meta] = meta
if expiry = resp.http_response.headers['x-amz-expiration']
expiry.first =~ /^expiry-date="(.+)", rule-id="(.+)"$/
exp_date = DateTime.parse($1)
exp_rule_id = $2
else
exp_date = nil
exp_rule_id = nil
end
resp.data[:expiration_date] = exp_date if exp_date
resp.data[:expiration_rule_id] = exp_rule_id if exp_rule_id
restoring = false
restore_date = nil
if restore = resp.http_response.headers['x-amz-restore']
if restore.first =~ /ongoing-request="(.+?)", expiry-date="(.+?)"/
restoring = $1 == "true"
restore_date = $2 && DateTime.parse($2)
elsif restore.first =~ /ongoing-request="(.+?)"/
restoring = $1 == "true"
end
end
resp.data[:restore_in_progress] = restoring
resp.data[:restore_expiration_date] = restore_date if restore_date
{
'x-amz-version-id' => :version_id,
'content-type' => :content_type,
'content-encoding' => :content_encoding,
'cache-control' => :cache_control,
'expires' => :expires,
'etag' => :etag,
'x-amz-website-redirect-location' => :website_redirect_location,
'accept-ranges' => :accept_ranges,
'x-amz-server-side-encryption-customer-algorithm' => :sse_customer_algorithm,
'x-amz-server-side-encryption-customer-key-MD5' => :sse_customer_key_md5
}.each_pair do |header,method|
if value = resp.http_response.header(header)
resp.data[method] = value
end
end
if time = resp.http_response.header('Last-Modified')
resp.data[:last_modified] = Time.parse(time)
end
if length = resp.http_response.header('content-length')
resp.data[:content_length] = length.to_i
end
if sse = resp.http_response.header('x-amz-server-side-encryption')
resp.data[:server_side_encryption] = sse.downcase.to_sym
end
end
module Validators
# @return [Boolean] Returns true if the given bucket name is valid.
def valid_bucket_name?(bucket_name)
validate_bucket_name!(bucket_name) rescue false
end
# Returns true if the given `bucket_name` is DNS compatible.
#
# DNS compatible bucket names may be accessed like:
#
# http://dns.compat.bucket.name.s3.amazonaws.com/
#
# Whereas non-dns compatible bucket names must place the bucket
# name in the url path, like:
#
# http://s3.amazonaws.com/dns_incompat_bucket_name/
#
# @return [Boolean] Returns true if the given bucket name may be
# is dns compatible.
# this bucket n
#
def dns_compatible_bucket_name?(bucket_name)
return false if
!valid_bucket_name?(bucket_name) or
# Bucket names should be between 3 and 63 characters long
bucket_name.size > 63 or
# Bucket names must only contain lowercase letters, numbers, dots, and dashes
# and must start and end with a lowercase letter or a number
bucket_name !~ /^[a-z0-9][a-z0-9.-]+[a-z0-9]$/ or
# Bucket names should not be formatted like an IP address (e.g., 192.168.5.4)
bucket_name =~ /(\d+\.){3}\d+/ or
# Bucket names cannot contain two, adjacent periods
bucket_name['..'] or
# Bucket names cannot contain dashes next to periods
# (e.g., "my-.bucket.com" and "my.-bucket" are invalid)
(bucket_name['-.'] || bucket_name['.-'])
true
end
# Returns true if the bucket name must be used in the request
# path instead of as a sub-domain when making requests against
# S3.
#
# This can be an issue if the bucket name is DNS compatible but
# contains '.' (periods). These cause the SSL certificate to
# become invalid when making authenticated requets over SSL to the
# bucket name. The solution is to send this as a path argument
# instead.
#
# @return [Boolean] Returns true if the bucket name should be used
# as a path segement instead of dns prefix when making requests
# against s3.
#
def path_style_bucket_name? bucket_name
if dns_compatible_bucket_name?(bucket_name)
bucket_name =~ /\./ ? true : false
else
true
end
end
def validate! name, value, &block
if error_msg = yield
raise ArgumentError, "#{name} #{error_msg}"
end
value
end
def validate_key!(key)
validate!('key', key) do
case
when key.nil? || key == ''
'may not be blank'
end
end
end
def require_bucket_name! bucket_name
if [nil, ''].include?(bucket_name)
raise ArgumentError, "bucket_name may not be blank"
end
end
# Returns true if the given bucket name is valid. If the name
# is invalid, an ArgumentError is raised.
def validate_bucket_name!(bucket_name)
validate!('bucket_name', bucket_name) do
case
when bucket_name.nil? || bucket_name == ''
'may not be blank'
when bucket_name !~ /^[A-Za-z0-9._\-]+$/
'may only contain uppercase letters, lowercase letters, numbers, periods (.), ' +
'underscores (_), and dashes (-)'
when !(3..255).include?(bucket_name.size)
'must be between 3 and 255 characters long'
when bucket_name =~ /\n/
'must not contain a newline character'
end
end
end
def require_policy!(policy)
validate!('policy', policy) do
case
when policy.nil? || policy == ''
'may not be blank'
else
json_validation_message(policy)
end
end
end
def require_acl! options
acl_options = [
:acl,
:grant_read,
:grant_write,
:grant_read_acp,
:grant_write_acp,
:grant_full_control,
:access_control_policy,
]
unless options.keys.any?{|opt| acl_options.include?(opt) }
msg = "missing a required ACL option, must provide an ACL " +
"via :acl, :grant_* or :access_control_policy"
raise ArgumentError, msg
end
end
def set_body_stream_and_content_length request, options
unless options[:content_length]
msg = "S3 requires a content-length header, unable to determine "
msg << "the content length of the data provided, please set "
msg << ":content_length"
raise ArgumentError, msg
end
request.headers['content-length'] = options[:content_length]
request.body_stream = options[:data]
end
def require_upload_id!(upload_id)
validate!("upload_id", upload_id) do
"must not be blank" if upload_id.to_s.empty?
end
end
def require_part_number! part_number
validate!("part_number", part_number) do
"must not be blank" if part_number.to_s.empty?
end
end
def validate_parts!(parts)
validate!("parts", parts) do
if !parts.kind_of?(Array)
"must not be blank"
elsif parts.empty?
"must contain at least one entry"
elsif !parts.all? { |p| p.kind_of?(Hash) }
"must be an array of hashes"
elsif !parts.all? { |p| p[:part_number] }
"must contain part_number for each part"
elsif !parts.all? { |p| p[:etag] }
"must contain etag for each part"
elsif parts.any? { |p| p[:part_number].to_i < 1 }
"must not have part numbers less than 1"
end
end
end
def json_validation_message(obj)
if obj.respond_to?(:to_str)
obj = obj.to_str
elsif obj.respond_to?(:to_json)
obj = obj.to_json
end
error = nil
begin
JSON.parse(obj)
rescue => e
error = e
end
"contains invalid JSON: #{error}" if error
end
def require_allowed_methods!(allowed_methods)
validate!("allowed_methods", allowed_methods) do
if !allowed_methods.kind_of?(Array)
"must be an array"
elsif !allowed_methods.all? { |x| x.kind_of?(String) }
"must be an array of strings"
end
end
end
def require_allowed_origins!(allowed_origins)
validate!("allowed_origins", allowed_origins) do
if !allowed_origins.kind_of?(Array)
"must be an array"
elsif !allowed_origins.all? { |x| x.kind_of?(String) }
"must be an array of strings"
end
end
end
end
include Validators
extend Validators
end
class Client::V20060301 < Client
def self.object_method(method_name, verb, *args, &block)
bucket_method(method_name, verb, *args) do
configure_request do |req, options|
validate_key!(options[:key])
super(req, options)
req.key = options[:key]
end
instance_eval(&block) if block
end
end
public
# Creates a bucket.
# @overload create_bucket(options = {})
# @param [Hash] options
# @option options [required,String] :bucket_name
# @option options [String] :acl A canned ACL (e.g. 'private',
# 'public-read', etc). See the S3 API documentation for
# a complete list of valid values.
# @option options [String] :grant_read
# @option options [String] :grant_write
# @option options [String] :grant_read_acp
# @option options [String] :grant_write_acp
# @option options [String] :grant_full_control
# @return [Core::Response]
bucket_method(:create_bucket, :put, :header_options => {
:acl => 'x-amz-acl',
:grant_read => 'x-amz-grant-read',
:grant_write => 'x-amz-grant-write',
:grant_read_acp => 'x-amz-grant-read-acp',
:grant_write_acp => 'x-amz-grant-write-acp',
:grant_full_control => 'x-amz-grant-full-control',
}) do
configure_request do |req, options|
validate_bucket_name!(options[:bucket_name])
if location = options[:location_constraint]
xmlns = "http://s3.amazonaws.com/doc/#{API_VERSION}/"
req.body = <<-XML
<CreateBucketConfiguration xmlns="#{xmlns}">
<LocationConstraint>#{location}</LocationConstraint>
</CreateBucketConfiguration>
XML
end
super(req, options)
end
end
alias_method :put_bucket, :create_bucket
# @!method put_bucket_website(options = {})
# @param [Hash] options
# @option (see WebsiteConfiguration#initialize)
# @option options [required,String] :bucket_name
# @return [Core::Response]
bucket_method(:put_bucket_website, :put, 'website') do
configure_request do |req, options|
req.body = Nokogiri::XML::Builder.new do |xml|
xml.WebsiteConfiguration(:xmlns => XMLNS) do
if redirect = options[:redirect_all_requests_to]
xml.RedirectAllRequestsTo do
xml.HostName(redirect[:host_name])
xml.Protocol(redirect[:protocol]) if redirect[:protocol]
end
end
if indx = options[:index_document]
xml.IndexDocument do
xml.Suffix(indx[:suffix])
end
end
if err = options[:error_document]
xml.ErrorDocument do
xml.Key(err[:key])
end
end
rules = options[:routing_rules]
if rules.is_a?(Array) && !rules.empty?
xml.RoutingRules do
rules.each do |rule|
xml.RoutingRule do
redirect = rule[:redirect]
xml.Redirect do
xml.Protocol(redirect[:protocol]) if redirect[:protocol]
xml.HostName(redirect[:host_name]) if redirect[:host_name]
xml.ReplaceKeyPrefixWith(redirect[:replace_key_prefix_with]) if redirect[:replace_key_prefix_with]
xml.ReplaceKeyWith(redirect[:replace_key_with]) if redirect[:replace_key_with]
xml.HttpRedirectCode(redirect[:http_redirect_code]) if redirect[:http_redirect_code]
end
if condition = rule[:condition]
xml.Condition do
xml.KeyPrefixEquals(condition[:key_prefix_equals]) if condition[:key_prefix_equals]
xml.HttpErrorCodeReturnedEquals(condition[:http_error_code_returned_equals]) if condition[:http_error_code_returned_equals]
end
end
end
end
end
end
end
end.doc.root.to_xml
super(req, options)
end
end
# @overload get_bucket_website(options = {})
# @param [Hash] options
# @option options [required,String] :bucket_name
# @return [Core::Response]
# * `:index_document` - (Hash)
# * `:suffix` - (String)
# * `:error_document` - (Hash)
# * `:key` - (String)
bucket_method(:get_bucket_website, :get, 'website', XML::GetBucketWebsite)
# @overload delete_bucket_website(options = {})
# @param [Hash] options
# @option options [required,String] :bucket_name
# @return [Core::Response]
bucket_method(:delete_bucket_website, :delete, 'website')
# Deletes an empty bucket.
# @overload delete_bucket(options = {})
# @param [Hash] options
# @option options [required,String] :bucket_name
# @return [Core::Response]
bucket_method(:delete_bucket, :delete)
# @overload set_bucket_lifecycle_configuration(options = {})
# @param [Hash] options
# @option options [required,String] :bucket_name
# @option options [required,String] :lifecycle_configuration
# @return [Core::Response]
bucket_method(:set_bucket_lifecycle_configuration, :put) do
configure_request do |req, options|
xml = options[:lifecycle_configuration]
req.add_param('lifecycle')
req.body = xml
req.headers['content-md5'] = md5(xml)
super(req, options)
end
end
# @overload get_bucket_lifecycle_configuration(options = {})
# @param [Hash] options
# @option options [required,String] :bucket_name
# @return [Core::Response]
bucket_method(:get_bucket_lifecycle_configuration, :get) do
configure_request do |req, options|
req.add_param('lifecycle')
super(req, options)
end
process_response do |resp|
xml = resp.http_response.body
resp.data = XML::GetBucketLifecycleConfiguration.parse(xml)
end
end
# @overload delete_bucket_lifecycle_configuration(options = {})
# @param [Hash] options
# @option options [required,String] :bucket_name
# @return [Core::Response]
bucket_method(:delete_bucket_lifecycle_configuration, :delete) do
configure_request do |req, options|
req.add_param('lifecycle')
super(req, options)
end
end
# @overload put_bucket_cors(options = {})
# @param [Hash] options
# @option options [required,String] :bucket_name
# @option options [required,Array<Hash>] :rules An array of rule hashes.
# * `:id` - (String) A unique identifier for the rule. The ID
# value can be up to 255 characters long. The IDs help you find
# a rule in the configuration.
# * `:allowed_methods` - (required,Array<String>) A list of HTTP
# methods that you want to allow the origin to execute.
# Each rule must identify at least one method.
# * `:allowed_origins` - (required,Array<String>) A list of origins
# you want to allow cross-domain requests from. This can
# contain at most one * wild character.
# * `:allowed_headers` - (Array<String>) A list of headers allowed
# in a pre-flight OPTIONS request via the
# Access-Control-Request-Headers header. Each header name
# specified in the Access-Control-Request-Headers header must
# have a corresponding entry in the rule.
# Amazon S3 will send only the allowed headers in a response
# that were requested. This can contain at most one * wild
# character.
# * `:max_age_seconds` - (Integer) The time in seconds that your
# browser is to cache the preflight response for the specified
# resource.
# * `:expose_headers` - (Array<String>) One or more headers in
# the response that you want customers to be able to access
# from their applications (for example, from a JavaScript
# XMLHttpRequest object).
# @return [Core::Response]
bucket_method(:put_bucket_cors, :put) do
configure_request do |req, options|
req.add_param('cors')
options[:rules].each do |rule|
require_allowed_methods!(rule[:allowed_methods])
require_allowed_origins!(rule[:allowed_origins])
end
xml = Nokogiri::XML::Builder.new do |xml|
xml.CORSConfiguration do
options[:rules].each do |rule|
xml.CORSRule do
xml.ID(rule[:id]) if rule[:id]
(rule[:allowed_methods] || []).each do |method|
xml.AllowedMethod(method)
end
(rule[:allowed_origins] || []).each do |origin|
xml.AllowedOrigin(origin)
end
(rule[:allowed_headers] || []).each do |header|
xml.AllowedHeader(header)
end
xml.MaxAgeSeconds(rule[:max_age_seconds]) if
rule[:max_age_seconds]
(rule[:expose_headers] || []).each do |header|
xml.ExposeHeader(header)
end
end
end
end
end.doc.root.to_xml
req.body = xml
req.headers['content-md5'] = md5(xml)
super(req, options)
end
end
# @overload get_bucket_cors(options = {})
# @param [Hash] options
# @option options [required,String] :bucket_name
# @return [Core::Response]
bucket_method(:get_bucket_cors, :get) do
configure_request do |req, options|
req.add_param('cors')
super(req, options)
end
process_response do |resp|
resp.data = XML::GetBucketCors.parse(resp.http_response.body)
end
end
# @overload delete_bucket_cors(options = {})
# @param [Hash] options
# @option options [required,String] :bucket_name
# @return [Core::Response]
bucket_method(:delete_bucket_cors, :delete) do
configure_request do |req, options|
req.add_param('cors')
super(req, options)
end
end
# @overload put_bucket_tagging(options = {})
# @param [Hash] options
# @option options [required,String] :bucket_name
# @option options [Hash] :tags
# @return [Core::Response]
bucket_method(:put_bucket_tagging, :put) do
configure_request do |req, options|
req.add_param('tagging')
xml = Nokogiri::XML::Builder.new
xml.Tagging do |xml|
xml.TagSet do
options[:tags].each_pair do |key,value|
xml.Tag do
xml.Key(key)
xml.Value(value)
end
end
end
end
xml = xml.doc.root.to_xml
req.body = xml
req.headers['content-md5'] = md5(xml)
super(req, options)
end
end
# @overload get_bucket_tagging(options = {})
# @param [Hash] options
# @option options [required,String] :bucket_name
# @return [Core::Response]
bucket_method(:get_bucket_tagging, :get) do
configure_request do |req, options|
req.add_param('tagging')
super(req, options)
end
process_response do |resp|
resp.data = XML::GetBucketTagging.parse(resp.http_response.body)
end
end
# @overload delete_bucket_tagging(options = {})
# @param [Hash] options
# @option options [required,String] :bucket_name
# @return [Core::Response]
bucket_method(:delete_bucket_tagging, :delete) do
configure_request do |req, options|
req.add_param('tagging')
super(req, options)
end
end
# @overload list_buckets(options = {})
# @param [Hash] options
# @return [Core::Response]
add_client_request_method(:list_buckets) do
configure_request do |req, options|
req.http_method = "GET"
end
process_response do |resp|
resp.data = XML::ListBuckets.parse(resp.http_response.body)
end
simulate_response do |resp|
resp.data = Core::XML::Parser.new(XML::ListBuckets.rules).simulate
end
end
# Sets the access policy for a bucket.
# @overload set_bucket_policy(options = {})
# @param [Hash] options
# @option options [required,String] :bucket_name
# @option options [required,String] :policy This can be a String
# or any object that responds to `#to_json`.
# @return [Core::Response]
bucket_method(:set_bucket_policy, :put, 'policy') do
configure_request do |req, options|
require_policy!(options[:policy])
super(req, options)
policy = options[:policy]
policy = policy.to_json unless policy.respond_to?(:to_str)
req.body = policy
end
end
# Gets the access policy for a bucket.
# @overload get_bucket_policy(options = {})
# @param [Hash] options
# @option options [required,String] :bucket_name
# @return [Core::Response]
bucket_method(:get_bucket_policy, :get, 'policy') do
process_response do |resp|
resp.data[:policy] = resp.http_response.body
end
end
# Deletes the access policy for a bucket.
# @overload delete_bucket_policy(options = {})
# @param [Hash] options
# @option options [required,String] :bucket_name
# @return [Core::Response]
bucket_method(:delete_bucket_policy, :delete, 'policy')
# @overload set_bucket_versioning(options = {})
# @param [Hash] options
# @option options [required,String] :bucket_name
# @option options [required,String] :state
# @option options [String] :mfa_delete
# @option options [String] :mfa
# @return [Core::Response]
bucket_method(:set_bucket_versioning, :put, 'versioning', :header_options => { :mfa => "x-amz-mfa" }) do
configure_request do |req, options|
state = options[:state].to_s.downcase.capitalize
unless state =~ /^(Enabled|Suspended)$/
raise ArgumentError, "invalid versioning state `#{state}`"
end
# Leave validation of MFA options to S3
mfa_delete = options[:mfa_delete].to_s.downcase.capitalize if options[:mfa_delete]
# Generate XML request for versioning
req.body = Nokogiri::XML::Builder.new do |xml|
xml.VersioningConfiguration('xmlns' => XMLNS) do
xml.Status(state)
xml.MfaDelete(mfa_delete) if mfa_delete
end
end.doc.root.to_xml
super(req, options)
end
end