mss-sdk 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. checksums.yaml +7 -0
  2. data/.yardopts +9 -0
  3. data/LICENSE.txt +0 -0
  4. data/README.md +192 -0
  5. data/bin/mss-rb +178 -0
  6. data/ca-bundle.crt +3554 -0
  7. data/lib/mss/core/async_handle.rb +89 -0
  8. data/lib/mss/core/cacheable.rb +76 -0
  9. data/lib/mss/core/client.rb +786 -0
  10. data/lib/mss/core/collection/simple.rb +81 -0
  11. data/lib/mss/core/collection/with_limit_and_next_token.rb +70 -0
  12. data/lib/mss/core/collection/with_next_token.rb +96 -0
  13. data/lib/mss/core/collection.rb +262 -0
  14. data/lib/mss/core/configuration.rb +527 -0
  15. data/lib/mss/core/credential_providers.rb +653 -0
  16. data/lib/mss/core/data.rb +251 -0
  17. data/lib/mss/core/deprecations.rb +83 -0
  18. data/lib/mss/core/endpoints.rb +36 -0
  19. data/lib/mss/core/http/connection_pool.rb +374 -0
  20. data/lib/mss/core/http/curb_handler.rb +150 -0
  21. data/lib/mss/core/http/handler.rb +88 -0
  22. data/lib/mss/core/http/net_http_handler.rb +144 -0
  23. data/lib/mss/core/http/patch.rb +98 -0
  24. data/lib/mss/core/http/request.rb +258 -0
  25. data/lib/mss/core/http/response.rb +80 -0
  26. data/lib/mss/core/indifferent_hash.rb +87 -0
  27. data/lib/mss/core/inflection.rb +55 -0
  28. data/lib/mss/core/ini_parser.rb +41 -0
  29. data/lib/mss/core/json_client.rb +46 -0
  30. data/lib/mss/core/json_parser.rb +75 -0
  31. data/lib/mss/core/json_request_builder.rb +34 -0
  32. data/lib/mss/core/json_response_parser.rb +78 -0
  33. data/lib/mss/core/lazy_error_classes.rb +107 -0
  34. data/lib/mss/core/log_formatter.rb +426 -0
  35. data/lib/mss/core/managed_file.rb +31 -0
  36. data/lib/mss/core/meta_utils.rb +44 -0
  37. data/lib/mss/core/model.rb +61 -0
  38. data/lib/mss/core/naming.rb +29 -0
  39. data/lib/mss/core/option_grammar.rb +737 -0
  40. data/lib/mss/core/options/json_serializer.rb +81 -0
  41. data/lib/mss/core/options/validator.rb +154 -0
  42. data/lib/mss/core/options/xml_serializer.rb +117 -0
  43. data/lib/mss/core/page_result.rb +74 -0
  44. data/lib/mss/core/policy.rb +938 -0
  45. data/lib/mss/core/query_client.rb +40 -0
  46. data/lib/mss/core/query_error_parser.rb +23 -0
  47. data/lib/mss/core/query_request_builder.rb +46 -0
  48. data/lib/mss/core/query_response_parser.rb +34 -0
  49. data/lib/mss/core/region.rb +84 -0
  50. data/lib/mss/core/region_collection.rb +79 -0
  51. data/lib/mss/core/resource.rb +412 -0
  52. data/lib/mss/core/resource_cache.rb +39 -0
  53. data/lib/mss/core/response.rb +214 -0
  54. data/lib/mss/core/response_cache.rb +49 -0
  55. data/lib/mss/core/rest_error_parser.rb +23 -0
  56. data/lib/mss/core/rest_json_client.rb +39 -0
  57. data/lib/mss/core/rest_request_builder.rb +153 -0
  58. data/lib/mss/core/rest_response_parser.rb +65 -0
  59. data/lib/mss/core/rest_xml_client.rb +46 -0
  60. data/lib/mss/core/service_interface.rb +82 -0
  61. data/lib/mss/core/signers/base.rb +45 -0
  62. data/lib/mss/core/signers/cloud_front.rb +55 -0
  63. data/lib/mss/core/signers/s3.rb +158 -0
  64. data/lib/mss/core/signers/version_2.rb +71 -0
  65. data/lib/mss/core/signers/version_3.rb +85 -0
  66. data/lib/mss/core/signers/version_3_https.rb +60 -0
  67. data/lib/mss/core/signers/version_4/chunk_signed_stream.rb +190 -0
  68. data/lib/mss/core/signers/version_4.rb +227 -0
  69. data/lib/mss/core/uri_escape.rb +43 -0
  70. data/lib/mss/core/xml/frame.rb +245 -0
  71. data/lib/mss/core/xml/frame_stack.rb +84 -0
  72. data/lib/mss/core/xml/grammar.rb +306 -0
  73. data/lib/mss/core/xml/parser.rb +69 -0
  74. data/lib/mss/core/xml/root_frame.rb +64 -0
  75. data/lib/mss/core/xml/sax_handlers/libxml.rb +46 -0
  76. data/lib/mss/core/xml/sax_handlers/nokogiri.rb +55 -0
  77. data/lib/mss/core/xml/sax_handlers/ox.rb +40 -0
  78. data/lib/mss/core/xml/sax_handlers/rexml.rb +46 -0
  79. data/lib/mss/core/xml/stub.rb +122 -0
  80. data/lib/mss/core.rb +602 -0
  81. data/lib/mss/errors.rb +161 -0
  82. data/lib/mss/rails.rb +194 -0
  83. data/lib/mss/s3/access_control_list.rb +262 -0
  84. data/lib/mss/s3/acl_object.rb +263 -0
  85. data/lib/mss/s3/acl_options.rb +200 -0
  86. data/lib/mss/s3/bucket.rb +757 -0
  87. data/lib/mss/s3/bucket_collection.rb +161 -0
  88. data/lib/mss/s3/bucket_lifecycle_configuration.rb +472 -0
  89. data/lib/mss/s3/bucket_region_cache.rb +51 -0
  90. data/lib/mss/s3/bucket_tag_collection.rb +110 -0
  91. data/lib/mss/s3/bucket_version_collection.rb +78 -0
  92. data/lib/mss/s3/cipher_io.rb +119 -0
  93. data/lib/mss/s3/client/xml.rb +265 -0
  94. data/lib/mss/s3/client.rb +2076 -0
  95. data/lib/mss/s3/config.rb +60 -0
  96. data/lib/mss/s3/cors_rule.rb +107 -0
  97. data/lib/mss/s3/cors_rule_collection.rb +193 -0
  98. data/lib/mss/s3/data_options.rb +190 -0
  99. data/lib/mss/s3/encryption_utils.rb +145 -0
  100. data/lib/mss/s3/errors.rb +93 -0
  101. data/lib/mss/s3/multipart_upload.rb +353 -0
  102. data/lib/mss/s3/multipart_upload_collection.rb +75 -0
  103. data/lib/mss/s3/object_collection.rb +355 -0
  104. data/lib/mss/s3/object_metadata.rb +102 -0
  105. data/lib/mss/s3/object_upload_collection.rb +76 -0
  106. data/lib/mss/s3/object_version.rb +153 -0
  107. data/lib/mss/s3/object_version_collection.rb +88 -0
  108. data/lib/mss/s3/paginated_collection.rb +74 -0
  109. data/lib/mss/s3/policy.rb +73 -0
  110. data/lib/mss/s3/prefix_and_delimiter_collection.rb +46 -0
  111. data/lib/mss/s3/prefixed_collection.rb +84 -0
  112. data/lib/mss/s3/presign_v4.rb +135 -0
  113. data/lib/mss/s3/presigned_post.rb +574 -0
  114. data/lib/mss/s3/region_detection.rb +75 -0
  115. data/lib/mss/s3/request.rb +61 -0
  116. data/lib/mss/s3/s3_object.rb +1795 -0
  117. data/lib/mss/s3/tree/branch_node.rb +67 -0
  118. data/lib/mss/s3/tree/child_collection.rb +103 -0
  119. data/lib/mss/s3/tree/leaf_node.rb +93 -0
  120. data/lib/mss/s3/tree/node.rb +21 -0
  121. data/lib/mss/s3/tree/parent.rb +86 -0
  122. data/lib/mss/s3/tree.rb +115 -0
  123. data/lib/mss/s3/uploaded_part.rb +81 -0
  124. data/lib/mss/s3/uploaded_part_collection.rb +83 -0
  125. data/lib/mss/s3/website_configuration.rb +101 -0
  126. data/lib/mss/s3.rb +161 -0
  127. data/lib/mss/version.rb +16 -0
  128. data/lib/mss-sdk.rb +2 -0
  129. data/lib/mss.rb +14 -0
  130. data/rails/init.rb +14 -0
  131. metadata +201 -0
@@ -0,0 +1,1795 @@
1
+ # Copyright 2011-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License"). You
4
+ # may not use this file except in compliance with the License. A copy of
5
+ # the License is located at
6
+ #
7
+ #
8
+ # or in the "license" file accompanying this file. This file is
9
+ # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
10
+ # ANY KIND, either express or implied. See the License for the specific
11
+ # language governing permissions and limitations under the License.
12
+
13
+ require 'uri'
14
+ require 'base64'
15
+
16
+ module MSS
17
+ class S3
18
+
19
+ # Represents an object in S3. Objects live in a bucket and have
20
+ # unique keys.
21
+ #
22
+ # # Getting Objects
23
+ #
24
+ # You can get an object by its key.
25
+ #
26
+ # s3 = MSS::S3.new
27
+ # obj = s3.buckets['my-bucket'].objects['key'] # no request made
28
+ #
29
+ # You can also get objects by enumerating a objects in a bucket.
30
+ #
31
+ # bucket.objects.each do |obj|
32
+ # puts obj.key
33
+ # end
34
+ #
35
+ # See {ObjectCollection} for more information on finding objects.
36
+ #
37
+ # # Creating Objects
38
+ #
39
+ # You create an object by writing to it. The following two
40
+ # expressions are equivalent.
41
+ #
42
+ # obj = bucket.objects.create('key', 'data')
43
+ # obj = bucket.objects['key'].write('data')
44
+ #
45
+ # # Writing Objects
46
+ #
47
+ # To upload data to S3, you simply need to call {#write} on an object.
48
+ #
49
+ # obj.write('Hello World!')
50
+ # obj.read
51
+ # #=> 'Hello World!'
52
+ #
53
+ # ## Uploading Files
54
+ #
55
+ # You can upload a file to S3 in a variety of ways. Given a path
56
+ # to a file (as a string) you can do any of the following:
57
+ #
58
+ # # specify the data as a path to a file
59
+ # obj.write(Pathname.new(path_to_file))
60
+ #
61
+ # # also works this way
62
+ # obj.write(:file => path_to_file)
63
+ #
64
+ # # Also accepts an open file object
65
+ # file = File.open(path_to_file, 'rb')
66
+ # obj.write(file)
67
+ #
68
+ # All three examples above produce the same result. The file
69
+ # will be streamed to S3 in chunks. It will not be loaded
70
+ # entirely into memory.
71
+ #
72
+ # ## Streaming Uploads
73
+ #
74
+ # When you call {#write} with an IO-like object, it will be streamed
75
+ # to S3 in chunks.
76
+ #
77
+ # While it is possible to determine the size of many IO objects, you may
78
+ # have to specify the :content_length of your IO object.
79
+ # If the exact size can not be known, you may provide an
80
+ # `:estimated_content_length`. Depending on the size (actual or
81
+ # estimated) of your data, it will be uploaded in a single request or
82
+ # in multiple requests via {#multipart_upload}.
83
+ #
84
+ # You may also stream uploads to S3 using a block:
85
+ #
86
+ # obj.write do |buffer, bytes|
87
+ # # writing fewer than the requested number of bytes to the buffer
88
+ # # will cause write to stop yielding to the block
89
+ # end
90
+ #
91
+ # # Reading Objects
92
+ #
93
+ # You can read an object directly using {#read}. Be warned, this will
94
+ # load the entire object into memory and is not recommended for large
95
+ # objects.
96
+ #
97
+ # obj.write('abc')
98
+ # puts obj.read
99
+ # #=> abc
100
+ #
101
+ # ## Streaming Downloads
102
+ #
103
+ # If you want to stream an object from S3, you can pass a block
104
+ # to {#read}.
105
+ #
106
+ # File.open('output', 'wb') do |file|
107
+ # large_object.read do |chunk|
108
+ # file.write(chunk)
109
+ # end
110
+ # end
111
+ #
112
+ # # Encryption
113
+ #
114
+ # Amazon S3 can encrypt objects for you service-side. You can also
115
+ # use client-side encryption.
116
+ #
117
+ # ## Server Side Encryption
118
+ #
119
+ # You can specify to use server side encryption when writing an object.
120
+ #
121
+ # obj.write('data', :server_side_encryption => :aes256)
122
+ #
123
+ # You can also make this the default behavior.
124
+ #
125
+ # MSS.config(:s3_server_side_encryption => :aes256)
126
+ #
127
+ # s3 = MSS::S3.new
128
+ # s3.buckets['name'].objects['key'].write('abc') # will be encrypted
129
+ #
130
+ # ## Client Side Encryption
131
+ #
132
+ # Client side encryption utilizes envelope encryption, so that your keys are
133
+ # never sent to S3. You can use a symetric key or an asymmetric
134
+ # key pair.
135
+ #
136
+ # ### Symmetric Key Encryption
137
+ #
138
+ # An AES key is used for symmetric encryption. The key can be 128, 192,
139
+ # and 256 bit sizes. Start by generating key or read a previously
140
+ # generated key.
141
+ #
142
+ # # generate a new random key
143
+ # my_key = OpenSSL::Cipher.new("AES-256-ECB").random_key
144
+ #
145
+ # # read an existing key from disk
146
+ # my_key = File.read("my_key.der")
147
+ #
148
+ # Now you can encrypt locally and upload the encrypted data to S3.
149
+ # To do this, you need to provide your key.
150
+ #
151
+ # obj = bucket.objects["my-text-object"]
152
+ #
153
+ # # encrypt then upload data
154
+ # obj.write("MY TEXT", :encryption_key => my_key)
155
+ #
156
+ # # try read the object without decrypting, oops
157
+ # obj.read
158
+ # #=> '.....'
159
+ #
160
+ # Lastly, you can download and decrypt by providing the same key.
161
+ #
162
+ # obj.read(:encryption_key => my_key)
163
+ # #=> "MY TEXT"
164
+ #
165
+ # ### Asymmetric Key Pair
166
+ #
167
+ # A RSA key pair is used for asymmetric encryption. The public key is used
168
+ # for encryption and the private key is used for decryption. Start
169
+ # by generating a key.
170
+ #
171
+ # my_key = OpenSSL::PKey::RSA.new(1024)
172
+ #
173
+ # Provide your key to #write and the data will be encrypted before it
174
+ # is uploaded. Pass the same key to #read to decrypt the data
175
+ # when you download it.
176
+ #
177
+ # obj = bucket.objects["my-text-object"]
178
+ #
179
+ # # encrypt and upload the data
180
+ # obj.write("MY TEXT", :encryption_key => my_key)
181
+ #
182
+ # # download and decrypt the data
183
+ # obj.read(:encryption_key => my_key)
184
+ # #=> "MY TEXT"
185
+ #
186
+ # ### Configuring storage locations
187
+ #
188
+ # By default, encryption materials are stored in the object metadata.
189
+ # If you prefer, you can store the encryption materials in a separate
190
+ # object in S3. This object will have the same key + '.instruction'.
191
+ #
192
+ # # new object, does not exist yet
193
+ # obj = bucket.objects["my-text-object"]
194
+ #
195
+ # # no instruction file present
196
+ # bucket.objects['my-text-object.instruction'].exists?
197
+ # #=> false
198
+ #
199
+ # # store the encryption materials in the instruction file
200
+ # # instead of obj#metadata
201
+ # obj.write("MY TEXT",
202
+ # :encryption_key => MY_KEY,
203
+ # :encryption_materials_location => :instruction_file)
204
+ #
205
+ # bucket.objects['my-text-object.instruction'].exists?
206
+ # #=> true
207
+ #
208
+ # If you store the encryption materials in an instruction file, you
209
+ # must tell #read this or it will fail to find your encryption materials.
210
+ #
211
+ # # reading an encrypted file whos materials are stored in an
212
+ # # instruction file, and not metadata
213
+ # obj.read(:encryption_key => MY_KEY,
214
+ # :encryption_materials_location => :instruction_file)
215
+ #
216
+ # ### Configuring default behaviors
217
+ #
218
+ # You can configure the default key such that it will automatically
219
+ # encrypt and decrypt for you. You can do this globally or for a
220
+ # single S3 interface
221
+ #
222
+ # # all objects uploaded/downloaded with this s3 object will be
223
+ # # encrypted/decrypted
224
+ # s3 = MSS::S3.new(:s3_encryption_key => "MY_KEY")
225
+ #
226
+ # # set the key to always encrypt/decrypt
227
+ # MSS.config(:s3_encryption_key => "MY_KEY")
228
+ #
229
+ # You can also configure the default storage location for the encryption
230
+ # materials.
231
+ #
232
+ # MSS.config(:s3_encryption_materials_location => :instruction_file)
233
+ #
234
+ class S3Object
235
+
236
+ include Core::Model
237
+ include DataOptions
238
+ include ACLOptions
239
+ include MSS::S3::EncryptionUtils
240
+
241
+ # @param [Bucket] bucket The bucket this object belongs to.
242
+ # @param [String] key The object's key.
243
+ def initialize(bucket, key, opts = {})
244
+ @content_length = opts.delete(:content_length)
245
+ @etag = opts.delete(:etag)
246
+ @last_modified = opts.delete(:last_modified)
247
+ super
248
+ @key = key
249
+ @bucket = bucket
250
+ end
251
+
252
+ # @return [String] The objects unique key
253
+ attr_reader :key
254
+
255
+ # @return [Bucket] The bucket this object is in.
256
+ attr_reader :bucket
257
+
258
+ # @api private
259
+ def inspect
260
+ "<#{self.class}:#{bucket.name}/#{key}>"
261
+ end
262
+
263
+ # @return [Boolean] Returns true if the other object belongs to the
264
+ # same bucket and has the same key.
265
+ def == other
266
+ other.kind_of?(S3Object) and other.bucket == bucket and other.key == key
267
+ end
268
+ alias_method :eql?, :==
269
+
270
+ # @return [Boolean] Returns `true` if the object exists in S3.
271
+ def exists?
272
+ head
273
+ rescue Errors::NoSuchKey => e
274
+ false
275
+ else
276
+ true
277
+ end
278
+
279
+ # Performs a HEAD request against this object and returns an object
280
+ # with useful information about the object, including:
281
+ #
282
+ # * metadata (hash of user-supplied key-value pairs)
283
+ # * content_length (integer, number of bytes)
284
+ # * content_type (as sent to S3 when uploading the object)
285
+ # * etag (typically the object's MD5)
286
+ # * server_side_encryption (the algorithm used to encrypt the
287
+ # object on the server side, e.g. `:aes256`)
288
+ #
289
+ # @param [Hash] options
290
+ # @option options [String] :version_id Which version of this object
291
+ # to make a HEAD request against.
292
+ # @return A head object response with metadata,
293
+ # content_length, content_type, etag and server_side_encryption.
294
+ def head options = {}
295
+ client.head_object(options.merge(
296
+ :bucket_name => bucket.name, :key => key))
297
+ end
298
+
299
+ # Returns the object's ETag.
300
+ #
301
+ # Generally the ETAG is the MD5 of the object. If the object was
302
+ # uploaded using multipart upload then this is the MD5 all of the
303
+ # upload-part-md5s.
304
+ #
305
+ # @return [String] Returns the object's ETag
306
+ # def etag
307
+ # @etag = config.s3_cache_object_attributes && @etag || head[:etag]
308
+ # end
309
+
310
+ # Returns the object's last modified time.
311
+ #
312
+ # @return [Time] Returns the object's last modified time.
313
+ def last_modified
314
+ @last_modified = config.s3_cache_object_attributes && @last_modified || head[:last_modified]
315
+ end
316
+
317
+ # @return [Integer] Size of the object in bytes.
318
+ def content_length
319
+ @content_length = config.s3_cache_object_attributes && @content_length || head[:content_length]
320
+ end
321
+
322
+ # @note S3 does not compute content-type. It reports the content-type
323
+ # as was reported during the file upload.
324
+ # @return [String] Returns the content type as reported by S3,
325
+ # defaults to an empty string when not provided during upload.
326
+ def content_type
327
+ head[:content_type]
328
+ end
329
+
330
+ # @return [DateTime,nil]
331
+ # def expiration_date
332
+ # head[:expiration_date]
333
+ # end
334
+
335
+ # @return [String,nil]
336
+ # def expiration_rule_id
337
+ # head[:expiration_rule_id]
338
+ # end
339
+
340
+ # @return [Symbol, nil] Returns the algorithm used to encrypt
341
+ # the object on the server side, or `nil` if SSE was not used
342
+ # when storing the object.
343
+ # def server_side_encryption
344
+ # head[:server_side_encryption]
345
+ # end
346
+
347
+ # @return [true, false] Returns true if the object was stored
348
+ # using server side encryption.
349
+ # def server_side_encryption?
350
+ # !server_side_encryption.nil?
351
+ # end
352
+
353
+ # @return [Boolean] whether a {#restore} operation on the
354
+ # object is currently being performed on the object.
355
+ # @see #restore_expiration_date
356
+ # @since 1.7.2
357
+ # def restore_in_progress?
358
+ # head[:restore_in_progress]
359
+ # end
360
+
361
+ # @return [DateTime] the time when the temporarily restored object
362
+ # will be removed from S3. Note that the original object will remain
363
+ # available in Glacier.
364
+ # @return [nil] if the object was not restored from an archived
365
+ # copy
366
+ # @since 1.7.2
367
+ # def restore_expiration_date
368
+ # head[:restore_expiration_date]
369
+ # end
370
+
371
+ # @return [Boolean] whether the object is a temporary copy of an
372
+ # archived object in the Glacier storage class.
373
+ # @since 1.7.2
374
+ # def restored_object?
375
+ # !!head[:restore_expiration_date]
376
+ # end
377
+
378
+ # Deletes the object from its S3 bucket.
379
+ #
380
+ # @param [Hash] options
381
+ #
382
+ # @option [String] :version_id (nil) If present the specified version
383
+ # of this object will be deleted. Only works for buckets that have
384
+ # had versioning enabled.
385
+ #
386
+ # @option [Boolean] :delete_instruction_file (false) Set this to `true`
387
+ # if you use client-side encryption and the encryption materials
388
+ # were stored in a separate object in S3 (key.instruction).
389
+ #
390
+ # @option [String] :mfa The serial number and current token code of
391
+ # the Multi-Factor Authentication (MFA) device for the user. Format
392
+ # is "SERIAL TOKEN" - with a space between the serial and token.
393
+ #
394
+ # @return [nil]
395
+ def delete options = {}
396
+ client.delete_object(options.merge(
397
+ :bucket_name => bucket.name,
398
+ :key => key))
399
+
400
+ if options[:delete_instruction_file]
401
+ client.delete_object(
402
+ :bucket_name => bucket.name,
403
+ :key => key + '.instruction')
404
+ end
405
+
406
+ nil
407
+
408
+ end
409
+
410
+ # Restores a temporary copy of an archived object from the
411
+ # Glacier storage tier. After the specified `days`, Amazon
412
+ # S3 deletes the temporary copy. Note that the object
413
+ # remains archived; Amazon S3 deletes only the restored copy.
414
+ #
415
+ # Restoring an object does not occur immediately. Use
416
+ # {#restore_in_progress?} to check the status of the operation.
417
+ #
418
+ # @option [Integer] :days (1) the number of days to keep the object
419
+ # @return [Boolean] `true` if a restore can be initiated.
420
+ # @since 1.7.2
421
+ # def restore options = {}
422
+ # options[:days] ||= 1
423
+ # client.restore_object(options.merge({
424
+ # :bucket_name => bucket.name,
425
+ # :key => key,
426
+ # }))
427
+ # true
428
+ # end
429
+
430
+ # @option [String] :version_id (nil) If present the metadata object
431
+ # will be for the specified version.
432
+ # @return [ObjectMetadata] Returns an instance of ObjectMetadata
433
+ # representing the metadata for this object.
434
+ def metadata options = {}
435
+ options[:config] = config
436
+ ObjectMetadata.new(self, options)
437
+ end
438
+
439
+ # Returns a collection representing all the object versions
440
+ # for this object.
441
+ #
442
+ # @example
443
+ #
444
+ # bucket.versioning_enabled? # => true
445
+ # version = bucket.objects["mykey"].versions.latest
446
+ #
447
+ # @return [ObjectVersionCollection]
448
+ # def versions
449
+ # ObjectVersionCollection.new(self)
450
+ # end
451
+
452
+ # Uploads data to the object in S3.
453
+ #
454
+ # obj = s3.buckets['bucket-name'].objects['key']
455
+ #
456
+ # # strings
457
+ # obj.write("HELLO")
458
+ #
459
+ # # files (by path)
460
+ # obj.write(Pathname.new('path/to/file.txt'))
461
+ #
462
+ # # file objects
463
+ # obj.write(File.open('path/to/file.txt', 'rb'))
464
+ #
465
+ # # IO objects (must respond to #read and #eof?)
466
+ # obj.write(io)
467
+ #
468
+ # ### Multipart Uploads vs Single Uploads
469
+ #
470
+ # This method will intelligently choose between uploading the
471
+ # file in a signal request and using {#multipart_upload}.
472
+ # You can control this behavior by configuring the thresholds
473
+ # and you can disable the multipart feature as well.
474
+ #
475
+ # # always send the file in a single request
476
+ # obj.write(file, :single_request => true)
477
+ #
478
+ # # upload the file in parts if the total file size exceeds 100MB
479
+ # obj.write(file, :multipart_threshold => 100 * 1024 * 1024)
480
+ #
481
+ # @overload write(data, options = {})
482
+ #
483
+ # @param [String,Pathname,File,IO] data The data to upload.
484
+ # This may be a:
485
+ # * String
486
+ # * Pathname
487
+ # * File
488
+ # * IO
489
+ # * Any object that responds to `#read` and `#eof?`.
490
+ #
491
+ # @param options [Hash] Additional upload options.
492
+ #
493
+ # @option options [Integer] :content_length If provided, this
494
+ # option must match the total number of bytes written to S3.
495
+ # This options is *required* when it is not possible to
496
+ # automatically determine the size of `data`.
497
+ #
498
+ # @option options [Integer] :estimated_content_length When uploading
499
+ # data of unknown content length, you may specify this option to
500
+ # hint what mode of upload should take place. When
501
+ # `:estimated_content_length` exceeds the `:multipart_threshold`,
502
+ # then the data will be uploaded in parts, otherwise it will
503
+ # be read into memory and uploaded via {Client#put_object}.
504
+ #
505
+ # @option options [Boolean] :single_request (false) When `true`,
506
+ # this method will always upload the data in a single request
507
+ # (via {Client#put_object}). When `false`, this method will
508
+ # choose between {Client#put_object} and {#multipart_upload}.
509
+ #
510
+ # @option options [Integer] :multipart_threshold (16777216) Specifies
511
+ # the maximum size (in bytes) of a single-request upload. If the
512
+ # data exceeds this threshold, it will be uploaded via
513
+ # {#multipart_upload}. The default threshold is 16MB and can
514
+ # be configured via MSS.config(:s3_multipart_threshold => ...).
515
+ #
516
+ # @option options [Integer] :multipart_min_part_size (5242880) The
517
+ # minimum size of a part to upload to S3 when using
518
+ # {#multipart_upload}. S3 will reject parts smaller than 5MB
519
+ # (except the final part). The default is 5MB and can be
520
+ # configured via MSS.config(:s3_multipart_min_part_size => ...).
521
+ #
522
+ # @option options [Hash] :metadata A hash of metadata to be
523
+ # included with the object. These will be sent to S3 as
524
+ # headers prefixed with `x-amz-meta`. Each name, value pair
525
+ # must conform to US-ASCII.
526
+ #
527
+ # @option options [Symbol,String] :acl (:private) A canned access
528
+ # control policy. Valid values are:
529
+ #
530
+ # * `:private`
531
+ # * `:public_read`
532
+ # * `:public_read_write`
533
+ # * `:authenticated_read`
534
+ # * `:bucket_owner_read`
535
+ # * `:bucket_owner_full_control`
536
+ #
537
+ # @option options [String] :grant_read
538
+ #
539
+ # @option options [String] :grant_write
540
+ #
541
+ # @option options [String] :grant_read_acp
542
+ #
543
+ # @option options [String] :grant_write_acp
544
+ #
545
+ # @option options [String] :grant_full_control
546
+ #
547
+ # @option options [Boolean] :reduced_redundancy (false) When `true`,
548
+ # this object will be stored with Reduced Redundancy Storage.
549
+ #
550
+ # @option options :cache_control [String] Can be used to specify
551
+ # caching behavior. See
552
+ # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9
553
+ #
554
+ # @option options :content_disposition [String] Specifies
555
+ # presentational information for the object. See
556
+ # http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.5.1
557
+ #
558
+ # @option options :content_encoding [String] Specifies what
559
+ # content encodings have been applied to the object and thus
560
+ # what decoding mechanisms must be applied to obtain the
561
+ # media-type referenced by the `Content-Type` header field.
562
+ # See
563
+ # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11
564
+ #
565
+ # @option options [String] :content_md5
566
+ # The base64 encoded content md5 of the data.
567
+ #
568
+ # @option options :content_type A standard MIME type
569
+ # describing the format of the object data.
570
+ #
571
+ # @option options [Symbol] :server_side_encryption (nil) If this
572
+ # option is set, the object will be stored using server side
573
+ # encryption. The only valid value is `:aes256`, which
574
+ # specifies that the object should be stored using the AES
575
+ # encryption algorithm with 256 bit keys. By default, this
576
+ # option uses the value of the `:s3_server_side_encryption`
577
+ # option in the current configuration; for more information,
578
+ # see {MSS.config}.
579
+ #
580
+ # @option options [OpenSSL::PKey::RSA, String] :encryption_key
581
+ # Set this to encrypt the data client-side using envelope
582
+ # encryption. The key must be an OpenSSL asymmetric key
583
+ # or a symmetric key string (16, 24 or 32 bytes in length).
584
+ #
585
+ # @option options [Symbol] :encryption_materials_location (:metadata)
586
+ # Set this to `:instruction_file` if you prefer to store the
587
+ # client-side encryption materials in a separate object in S3
588
+ # instead of in the object metadata.
589
+ #
590
+ # @option options [String] :expires The date and time at which the
591
+ # object is no longer cacheable.
592
+ #
593
+ # @option options [String] :website_redirect_location
594
+ #
595
+ # @return [S3Object, ObjectVersion] If the bucket has versioning
596
+ # enabled, this methods returns an {ObjectVersion}, otherwise
597
+ # this method returns `self`.
598
+ #
599
+ def write *args, &block
600
+
601
+ options = compute_write_options(*args, &block)
602
+
603
+ add_storage_class_option(options)
604
+ #add_sse_options(options)
605
+ add_cse_options(options)
606
+
607
+ if use_multipart?(options)
608
+ write_with_multipart(options)
609
+ else
610
+ write_with_put_object(options)
611
+ end
612
+
613
+ end
614
+
615
+ # Performs a multipart upload. Use this if you have specific
616
+ # needs for how the upload is split into parts, or if you want
617
+ # to have more control over how the failure of an individual
618
+ # part upload is handled. Otherwise, {#write} is much simpler
619
+ # to use.
620
+ #
621
+ # Note: After you initiate multipart upload and upload one or
622
+ # more parts, you must either complete or abort multipart
623
+ # upload in order to stop getting charged for storage of the
624
+ # uploaded parts. Only after you either complete or abort
625
+ # multipart upload, Amazon S3 frees up the parts storage and
626
+ # stops charging you for the parts storage.
627
+ #
628
+ # @example Uploading an object in two parts
629
+ #
630
+ # bucket.objects.myobject.multipart_upload do |upload|
631
+ # upload.add_part("a" * 5242880)
632
+ # upload.add_part("b" * 2097152)
633
+ # end
634
+ #
635
+ # @example Uploading parts out of order
636
+ #
637
+ # bucket.objects.myobject.multipart_upload do |upload|
638
+ # upload.add_part("b" * 2097152, :part_number => 2)
639
+ # upload.add_part("a" * 5242880, :part_number => 1)
640
+ # end
641
+ #
642
+ # @example Aborting an upload after parts have been added
643
+ #
644
+ # bucket.objects.myobject.multipart_upload do |upload|
645
+ # upload.add_part("b" * 2097152, :part_number => 2)
646
+ # upload.abort
647
+ # end
648
+ #
649
+ # @example Starting an upload and completing it later by ID
650
+ #
651
+ # upload = bucket.objects.myobject.multipart_upload
652
+ # upload.add_part("a" * 5242880)
653
+ # upload.add_part("b" * 2097152)
654
+ # id = upload.id
655
+ #
656
+ # # later or in a different process
657
+ # upload = bucket.objects.myobject.multipart_uploads[id]
658
+ # upload.complete(:remote_parts)
659
+ #
660
+ # @yieldparam [MultipartUpload] upload A handle to the upload.
661
+ # {MultipartUpload#close} is called in an `ensure` clause so
662
+ # that the upload will always be either completed or
663
+ # aborted.
664
+ #
665
+ # @param [Hash] options Options for the upload.
666
+ #
667
+ # @option options [Hash] :metadata A hash of metadata to be
668
+ # included with the object. These will be sent to S3 as
669
+ # headers prefixed with `x-amz-meta`. Each name, value pair
670
+ # must conform to US-ASCII.
671
+ #
672
+ # @option options [Symbol] :acl (private) A canned access
673
+ # control policy. Valid values are:
674
+ #
675
+ # * `:private`
676
+ # * `:public_read`
677
+ # * `:public_read_write`
678
+ # * `:authenticated_read`
679
+ # * `:bucket_owner_read`
680
+ # * `:bucket_owner_full_control`
681
+ #
682
+ # @option options [Boolean] :reduced_redundancy (false) If true,
683
+ # Reduced Redundancy Storage will be enabled for the uploaded
684
+ # object.
685
+ #
686
+ # @option options :cache_control [String] Can be used to specify
687
+ # caching behavior. See
688
+ # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9
689
+ #
690
+ # @option options :content_disposition [String] Specifies
691
+ # presentational information for the object. See
692
+ # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec19.5.1
693
+ #
694
+ # @option options :content_encoding [String] Specifies what
695
+ # content encodings have been applied to the object and thus
696
+ # what decoding mechanisms must be applied to obtain the
697
+ # media-type referenced by the `Content-Type` header field.
698
+ # See
699
+ # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11
700
+ #
701
+ # @option options :content_type A standard MIME type
702
+ # describing the format of the object data.
703
+ #
704
+ # @option options [Symbol] :server_side_encryption (nil) If this
705
+ # option is set, the object will be stored using server side
706
+ # encryption. The only valid value is `:aes256`, which
707
+ # specifies that the object should be stored using the AES
708
+ # encryption algorithm with 256 bit keys. By default, this
709
+ # option uses the value of the `:s3_server_side_encryption`
710
+ # option in the current configuration; for more information,
711
+ # see {MSS.config}.
712
+ #
713
+ # @return [S3Object, ObjectVersion] If the bucket has versioning
714
+ # enabled, returns the {ObjectVersion} representing the
715
+ # version that was uploaded. If versioning is disabled,
716
+ # returns self.
717
+ #
718
+ def multipart_upload(options = {})
719
+
720
+ options = options.dup
721
+ #add_sse_options(options)
722
+
723
+ upload = multipart_uploads.create(options)
724
+
725
+ if block_given?
726
+ begin
727
+ yield(upload)
728
+ upload.close
729
+ rescue => e
730
+ upload.abort
731
+ raise e
732
+ end
733
+ else
734
+ upload
735
+ end
736
+ end
737
+
738
+ # @example Abort any in-progress uploads for the object:
739
+ #
740
+ # object.multipart_uploads.each(&:abort)
741
+ #
742
+ # @return [ObjectUploadCollection] Returns an object representing the
743
+ # collection of uploads that are in progress for this object.
744
+ def multipart_uploads
745
+ ObjectUploadCollection.new(self)
746
+ end
747
+
748
+ # Moves an object to a new key.
749
+ #
750
+ # This works by copying the object to a new key and then
751
+ # deleting the old object. This function returns the
752
+ # new object once this is done.
753
+ #
754
+ # bucket = s3.buckets['old-bucket']
755
+ # old_obj = bucket.objects['old-key']
756
+ #
757
+ # # renaming an object returns a new object
758
+ # new_obj = old_obj.move_to('new-key')
759
+ #
760
+ # old_obj.key #=> 'old-key'
761
+ # old_obj.exists? #=> false
762
+ #
763
+ # new_obj.key #=> 'new-key'
764
+ # new_obj.exists? #=> true
765
+ #
766
+ # If you need to move an object to a different bucket, pass
767
+ # `:bucket` or `:bucket_name`.
768
+ #
769
+ # obj = s3.buckets['old-bucket'].objects['old-key']
770
+ # obj.move_to('new-key', :bucket_name => 'new_bucket')
771
+ #
772
+ # If the copy succeeds, but the then the delete fails, an error
773
+ # will be raised.
774
+ #
775
+ # @param [String] target The key to move this object to.
776
+ #
777
+ # @param [Hash] options
778
+ #
779
+ # @option (see #copy_to)
780
+ #
781
+ # @return [S3Object] Returns a new object with the new key.
782
+ #
783
+ def move_to target, options = {}
784
+ copy = copy_to(target, options)
785
+ delete
786
+ copy
787
+ end
788
+ alias_method :rename_to, :move_to
789
+
790
+ # Copies data from one S3 object to another.
791
+ #
792
+ # S3 handles the copy so the clients does not need to fetch the data
793
+ # and upload it again. You can also change the storage class and
794
+ # metadata of the object when copying.
795
+ #
796
+ # @note This operation does not copy the ACL, storage class
797
+ # (standard vs. reduced redundancy) or server side encryption
798
+ # setting from the source object. If you don't specify any of
799
+ # these options when copying, the object will have the default
800
+ # values as described below.
801
+ #
802
+ # @param [Mixed] source
803
+ #
804
+ # @param [Hash] options
805
+ #
806
+ # @option options [String] :bucket_name The slash-prefixed name of
807
+ # the bucket the source object can be found in. Defaults to the
808
+ # current object's bucket.
809
+ #
810
+ # @option options [Bucket] :bucket The bucket the source object
811
+ # can be found in. Defaults to the current object's bucket.
812
+ #
813
+ # @option options [Hash] :metadata A hash of metadata to save
814
+ # with the copied object. Each name, value pair must conform
815
+ # to US-ASCII. When blank, the sources metadata is copied.
816
+ # If you set this value, you must set ALL metadata values for
817
+ # the object as we do not preserve existing values.
818
+ #
819
+ # @option options [String] :content_type The content type of
820
+ # the copied object. Defaults to the source object's content
821
+ # type.
822
+ #
823
+ # @option options [String] :content_disposition The presentational
824
+ # information for the object. Defaults to the source object's
825
+ # content disposition.
826
+ #
827
+ # @option options [Boolean] :reduced_redundancy (false) If true the
828
+ # object is stored with reduced redundancy in S3 for a lower cost.
829
+ #
830
+ # @option options [String] :version_id (nil) Causes the copy to
831
+ # read a specific version of the source object.
832
+ #
833
+ # @option options [Symbol] :acl (private) A canned access
834
+ # control policy. Valid values are:
835
+ #
836
+ # * `:private`
837
+ # * `:public_read`
838
+ # * `:public_read_write`
839
+ # * `:authenticated_read`
840
+ # * `:bucket_owner_read`
841
+ # * `:bucket_owner_full_control`
842
+ #
843
+ # @option options [Symbol] :server_side_encryption (nil) If this
844
+ # option is set, the object will be stored using server side
845
+ # encryption. The only valid value is `:aes256`, which
846
+ # specifies that the object should be stored using the AES
847
+ # encryption algorithm with 256 bit keys. By default, this
848
+ # option uses the value of the `:s3_server_side_encryption`
849
+ # option in the current configuration; for more information,
850
+ # see {MSS.config}.
851
+ #
852
+ # @option options [Boolean] :client_side_encrypted (false) Set to true
853
+ # when the object being copied was client-side encrypted. This
854
+ # is important so the encryption metadata will be copied.
855
+ #
856
+ # @option options [Boolean] :use_multipart_copy (false) Set this to
857
+ # `true` if you need to copy an object that is larger than 5GB.
858
+ #
859
+ # @option options :cache_control [String] Can be used to specify
860
+ # caching behavior. See
861
+ # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9
862
+ #
863
+ # @option options [String] :expires The date and time at which the
864
+ # object is no longer cacheable.
865
+ #
866
+ # @return [nil]
867
+ def copy_from source, options = {}
868
+
869
+ options = options.dup
870
+
871
+ options[:copy_source] =
872
+ case source
873
+ when S3Object
874
+ "/#{source.bucket.name}/#{source.key}"
875
+ when ObjectVersion
876
+ options[:version_id] = source.version_id
877
+ "/#{source.object.bucket.name}/#{source.object.key}"
878
+ else
879
+ if options[:bucket]
880
+ "/#{options.delete(:bucket).name}/#{source}"
881
+ elsif options[:bucket_name]
882
+ # oops, this should be slash-prefixed, but unable to change
883
+ # this without breaking users that already work-around this
884
+ # bug by sending :bucket_name => "/bucket-name"
885
+ "#{options.delete(:bucket_name)}/#{source}"
886
+ else
887
+ "/#{self.bucket.name}/#{source}"
888
+ end
889
+ end
890
+
891
+ if [:metadata, :content_disposition, :content_type, :cache_control,
892
+ ].any? {|opt| options.key?(opt) }
893
+ then
894
+ options[:metadata_directive] = 'REPLACE'
895
+ else
896
+ options[:metadata_directive] ||= 'COPY'
897
+ end
898
+
899
+ # copies client-side encryption materials (from the metadata or
900
+ # instruction file)
901
+ if options.delete(:client_side_encrypted)
902
+ copy_cse_materials(source, options)
903
+ end
904
+
905
+ #add_sse_options(options)
906
+
907
+ options[:storage_class] = options.delete(:reduced_redundancy) ?
908
+ 'REDUCED_REDUNDANCY' : 'STANDARD'
909
+
910
+ options[:bucket_name] = bucket.name
911
+ options[:key] = key
912
+
913
+ if use_multipart_copy?(options)
914
+ multipart_copy(options)
915
+ else
916
+ resp = client.copy_object(options)
917
+ end
918
+
919
+ nil
920
+
921
+ end
922
+
923
+ # Copies data from the current object to another object in S3.
924
+ #
925
+ # S3 handles the copy so the client does not need to fetch the data
926
+ # and upload it again. You can also change the storage class and
927
+ # metadata of the object when copying.
928
+ #
929
+ # @note This operation does not copy the ACL, storage class
930
+ # (standard vs. reduced redundancy) or server side encryption
931
+ # setting from this object to the new object. If you don't
932
+ # specify any of these options when copying, the new object
933
+ # will have the default values as described below.
934
+ #
935
+ # @param [S3Object,String] target An S3Object, or a string key of
936
+ # and object to copy to.
937
+ #
938
+ # @param [Hash] options
939
+ #
940
+ # @option options [String] :bucket_name The slash-prefixed name of the
941
+ # bucket the object should be copied into. Defaults to the current
942
+ # object's bucket.
943
+ #
944
+ # @option options [Bucket] :bucket The bucket the target object
945
+ # should be copied into. Defaults to the current object's bucket.
946
+ #
947
+ # @option options [Hash] :metadata A hash of metadata to save
948
+ # with the copied object. Each name, value pair must conform
949
+ # to US-ASCII. When blank, the sources metadata is copied.
950
+ #
951
+ # @option options [Boolean] :reduced_redundancy (false) If true
952
+ # the object is stored with reduced redundancy in S3 for a
953
+ # lower cost.
954
+ #
955
+ # @option options [Symbol] :acl (private) A canned access
956
+ # control policy. Valid values are:
957
+ #
958
+ # * `:private`
959
+ # * `:public_read`
960
+ # * `:public_read_write`
961
+ # * `:authenticated_read`
962
+ # * `:bucket_owner_read`
963
+ # * `:bucket_owner_full_control`
964
+ #
965
+ # @option options [Symbol] :server_side_encryption (nil) If this
966
+ # option is set, the object will be stored using server side
967
+ # encryption. The only valid value is `:aes256`, which
968
+ # specifies that the object should be stored using the AES
969
+ # encryption algorithm with 256 bit keys. By default, this
970
+ # option uses the value of the `:s3_server_side_encryption`
971
+ # option in the current configuration; for more information,
972
+ # see {MSS.config}.
973
+ #
974
+ # @option options [Boolean] :client_side_encrypted (false) When `true`,
975
+ # the client-side encryption materials will be copied. Without this
976
+ # option, the key and iv are not guaranteed to be transferred to
977
+ # the new object.
978
+ #
979
+ # @option options [String] :expires The date and time at which the
980
+ # object is no longer cacheable.
981
+ #
982
+ # @return [S3Object] Returns the copy (target) object.
983
+ #
984
+ def copy_to target, options = {}
985
+
986
+ unless target.is_a?(S3Object)
987
+
988
+ bucket = case
989
+ when options[:bucket] then options[:bucket]
990
+ when options[:bucket_name]
991
+ Bucket.new(options[:bucket_name], :config => config)
992
+ else self.bucket
993
+ end
994
+
995
+ target = S3Object.new(bucket, target)
996
+ end
997
+
998
+ copy_opts = options.dup
999
+ copy_opts.delete(:bucket)
1000
+ copy_opts.delete(:bucket_name)
1001
+
1002
+ target.copy_from(self, copy_opts)
1003
+ target
1004
+
1005
+ end
1006
+
1007
+ # Fetches the object data from S3. If you pass a block to this
1008
+ # method, the data will be yielded to the block in chunks as it
1009
+ # is read off the HTTP response.
1010
+ #
1011
+ # ### Read an object from S3 in chunks
1012
+ #
1013
+ # When downloading large objects it is recommended to pass a block
1014
+ # to #read. Data will be yielded to the block as it is read off
1015
+ # the HTTP response.
1016
+ #
1017
+ # # read an object from S3 to a file
1018
+ # File.open('output.txt', 'wb') do |file|
1019
+ # bucket.objects['key'].read do |chunk|
1020
+ # file.write(chunk)
1021
+ # end
1022
+ # end
1023
+ #
1024
+ # ### Reading an object without a block
1025
+ #
1026
+ # When you omit the block argument to #read, then the entire
1027
+ # HTTP response and read and the object data is loaded into
1028
+ # memory.
1029
+ #
1030
+ # bucket.objects['key'].read
1031
+ # #=> 'object-contents-here'
1032
+ #
1033
+ # @param [Hash] options
1034
+ #
1035
+ # @option options [String] :version_id Reads data from a
1036
+ # specific version of this object.
1037
+ #
1038
+ # @option options [Time] :if_unmodified_since If specified, the
1039
+ # method will raise
1040
+ # `MSS::S3::Errors::PreconditionFailed` unless the
1041
+ # object has not been modified since the given time.
1042
+ #
1043
+ # @option options [Time] :if_modified_since If specified, the
1044
+ # method will raise `MSS::S3::Errors::NotModified` if
1045
+ # the object has not been modified since the given time.
1046
+ #
1047
+ # @option options [String] :if_match If specified, the method
1048
+ # will raise `MSS::S3::Errors::PreconditionFailed`
1049
+ # unless the object ETag matches the provided value.
1050
+ #
1051
+ # @option options [String] :if_none_match If specified, the
1052
+ # method will raise `MSS::S3::Errors::NotModified` if
1053
+ # the object ETag matches the provided value.
1054
+ #
1055
+ # @option options [Range] :range A byte range to read data from
1056
+ #
1057
+ # @option options [OpenSSL::PKey::RSA, String] :encryption_key
1058
+ # (nil) If this option is set, the object will be decrypted using
1059
+ # envelope encryption. The valid values are OpenSSL asymmetric keys
1060
+ # `OpenSSL::Pkey::RSA` or strings representing symmetric keys
1061
+ # of an AES-128/192/256-ECB cipher as a `String`.
1062
+ # This value defaults to the value in `s3_encryption_key`;
1063
+ # for more information, see {MSS.config}.
1064
+ #
1065
+ # Symmetric Keys:
1066
+ #
1067
+ # cipher = OpenSSL::Cipher.new('AES-256-ECB')
1068
+ # key = cipher.random_key
1069
+ #
1070
+ # Asymmetric keys can also be generated as so:
1071
+ # key = OpenSSL::PKey::RSA.new(KEY_SIZE)
1072
+ #
1073
+ # @option options [Symbol] :encryption_materials_location (:metadata)
1074
+ # Set this to `:instruction_file` if the encryption materials
1075
+ # are not stored in the object metadata
1076
+ #
1077
+ # @note `:range` option cannot be used with client-side encryption
1078
+ #
1079
+ # @note All decryption reads incur at least an extra HEAD operation.
1080
+ #
1081
+ def read options = {}, &read_block
1082
+
1083
+ options[:bucket_name] = bucket.name
1084
+ options[:key] = key
1085
+
1086
+ if should_decrypt?(options)
1087
+ get_encrypted_object(options, &read_block)
1088
+ else
1089
+ resp_data = get_object(options, &read_block)
1090
+ block_given? ? resp_data : resp_data[:data]
1091
+ end
1092
+
1093
+ end
1094
+
1095
+ # @api private
1096
+ module ACLProxy
1097
+
1098
+ attr_accessor :object
1099
+
1100
+ def change
1101
+ yield(self)
1102
+ object.acl = self
1103
+ end
1104
+
1105
+ end
1106
+
1107
+ # Returns the object's access control list. This will be an
1108
+ # instance of AccessControlList, plus an additional `change`
1109
+ # method:
1110
+ #
1111
+ # object.acl.change do |acl|
1112
+ # # remove any grants to someone other than the bucket owner
1113
+ # owner_id = object.bucket.owner.id
1114
+ # acl.grants.reject! do |g|
1115
+ # g.grantee.canonical_user_id != owner_id
1116
+ # end
1117
+ # end
1118
+ #
1119
+ # Note that changing the ACL is not an atomic operation; it
1120
+ # fetches the current ACL, yields it to the block, and then
1121
+ # sets it again. Therefore, it's possible that you may
1122
+ # overwrite a concurrent update to the ACL using this
1123
+ # method.
1124
+ #
1125
+ # @return [AccessControlList]
1126
+ #
1127
+ def acl
1128
+
1129
+ resp = client.get_object_acl(:bucket_name => bucket.name, :key => key)
1130
+
1131
+ acl = AccessControlList.new(resp.data)
1132
+ acl.extend ACLProxy
1133
+ acl.object = self
1134
+ acl
1135
+
1136
+ end
1137
+
1138
+ # Sets the objects's ACL (access control list). You can provide an ACL
1139
+ # in a number of different formats.
1140
+ # @param (see ACLOptions#acl_options)
1141
+ # @return [nil]
1142
+ def acl=(acl)
1143
+
1144
+ client_opts = {}
1145
+ client_opts[:bucket_name] = bucket.name
1146
+ client_opts[:key] = key
1147
+
1148
+ client.put_object_acl(acl_options(acl).merge(client_opts))
1149
+ nil
1150
+
1151
+ end
1152
+
1153
+ # @api private
1154
+ REQUEST_PARAMETERS = Core::Signers::S3::QUERY_PARAMS.map do |p|
1155
+ p.tr("-","_").to_sym
1156
+ end
1157
+
1158
+ # Generates a presigned URL for an operation on this object.
1159
+ # This URL can be used by a regular HTTP client to perform the
1160
+ # desired operation without credentials and without changing
1161
+ # the permissions of the object.
1162
+ #
1163
+ # @example Generate a url to read an object
1164
+ #
1165
+ # bucket.objects.myobject.url_for(:read)
1166
+ #
1167
+ # @example Generate a url to delete an object
1168
+ #
1169
+ # bucket.objects.myobject.url_for(:delete)
1170
+ #
1171
+ # @example Override response headers for reading an object
1172
+ #
1173
+ # object = bucket.objects.myobject
1174
+ # url = object.url_for(:read,
1175
+ # :response_content_type => "application/json")
1176
+ #
1177
+ # @example Generate a url that expires in 10 minutes
1178
+ #
1179
+ # bucket.objects.myobject.url_for(:read, :expires => 10*60)
1180
+ #
1181
+ # @param [Symbol, String] method The HTTP verb or object
1182
+ # method for which the returned URL will be valid. Valid
1183
+ # values:
1184
+ #
1185
+ # * `:get` or `:read`
1186
+ # * `:put` or `:write`
1187
+ # * `:delete`
1188
+ # * `:head`
1189
+ #
1190
+ # @param [Hash] options Additional options for generating the URL.
1191
+ #
1192
+ # @option options :expires Sets the expiration time of the
1193
+ # URL; after this time S3 will return an error if the URL is
1194
+ # used. This can be an integer (to specify the number of
1195
+ # seconds after the current time), a string (which is parsed
1196
+ # as a date using Time#parse), a Time, or a DateTime object.
1197
+ # This option defaults to one hour after the current time.
1198
+ #
1199
+ # @option options [Boolean] :secure (true) Whether to generate a
1200
+ # secure (HTTPS) URL or a plain HTTP url.
1201
+ #
1202
+ # @option options [String] :content_type Object content type for
1203
+ # HTTP PUT. When provided, has to be also added to the request
1204
+ # header as a 'content-type' field
1205
+ #
1206
+ # @option options [String] :content_md5 Object MD5 hash for HTTP PUT.
1207
+ # When provided, has to be also added to the request header as a
1208
+ # 'content-md5' field
1209
+ #
1210
+ # @option options [String] :endpoint Sets the hostname of the
1211
+ # endpoint.
1212
+ #
1213
+ # @option options [Integer] :port Sets the port of the
1214
+ # endpoint (overrides config.s3_port).
1215
+ #
1216
+ # @option options [Boolean] :force_path_style (false) Indicates
1217
+ # whether the generated URL should place the bucket name in
1218
+ # the path (true) or as a subdomain (false).
1219
+ #
1220
+ # @option options [String] :response_content_type Sets the
1221
+ # Content-Type header of the response when performing an
1222
+ # HTTP GET on the returned URL.
1223
+ #
1224
+ # @option options [String] :response_content_language Sets the
1225
+ # Content-Language header of the response when performing an
1226
+ # HTTP GET on the returned URL.
1227
+ #
1228
+ # @option options [String] :response_expires Sets the Expires
1229
+ # header of the response when performing an HTTP GET on the
1230
+ # returned URL.
1231
+ #
1232
+ # @option options [String] :response_cache_control Sets the
1233
+ # Cache-Control header of the response when performing an
1234
+ # HTTP GET on the returned URL.
1235
+ #
1236
+ # @option options [String] :response_content_disposition Sets
1237
+ # the Content-Disposition header of the response when
1238
+ # performing an HTTP GET on the returned URL.
1239
+ #
1240
+ # @option options [String] :acl The value to use for the
1241
+ # x-amz-acl.
1242
+ #
1243
+ # @option options [String] :response_content_encoding Sets the
1244
+ # Content-Encoding header of the response when performing an
1245
+ # HTTP GET on the returned URL.
1246
+ #
1247
+ # @option options [:v3, :v4] :signature_version (:v3)
1248
+ #
1249
+ # @return [URI::HTTP, URI::HTTPS]
1250
+ def url_for(method, options = {})
1251
+
1252
+ options = options.dup
1253
+ options[:expires] = expiration_timestamp(options[:expires])
1254
+ options[:secure] = config.use_ssl? unless options.key?(:secure)
1255
+ options[:signature_version] ||= config.s3_signature_version
1256
+
1257
+ case options[:signature_version]
1258
+ when :v3 then presign_v3(method, options)
1259
+ # when :v4 then presign_v4(method, options)
1260
+ else
1261
+ # msg = "invalid signature version, expected :v3 or :v4, got "
1262
+ msg = "invalid signature version, expected :v3, got "
1263
+ msg << options[:signature_version].inspect
1264
+ raise ArgumentError, msg
1265
+ end
1266
+ end
1267
+
1268
+ # Generates a public (not authenticated) URL for the object.
1269
+ #
1270
+ # @param [Hash] options Options for generating the URL.
1271
+ #
1272
+ # @option options [Boolean] :secure Whether to generate a
1273
+ # secure (HTTPS) URL or a plain HTTP url.
1274
+ #
1275
+ # @return [URI::HTTP, URI::HTTPS]
1276
+ #
1277
+ def public_url(options = {})
1278
+ options[:secure] = config.use_ssl? unless options.key?(:secure)
1279
+ build_uri(request_for_signing(options), options)
1280
+ end
1281
+
1282
+ # Generates fields for a presigned POST to this object. This
1283
+ # method adds a constraint that the key must match the key of
1284
+ # this object. All options are sent to the PresignedPost
1285
+ # constructor.
1286
+ #
1287
+ # @see PresignedPost
1288
+ # @return [PresignedPost]
1289
+ # def presigned_post(options = {})
1290
+ # PresignedPost.new(bucket, options.merge(:key => key))
1291
+ # end
1292
+
1293
+ # @note Changing the storage class of an object incurs a COPY
1294
+ # operation.
1295
+ #
1296
+ # Changes the storage class of the object to enable or disable
1297
+ # Reduced Redundancy Storage (RRS).
1298
+ #
1299
+ # @param [true,false] value If this is true, the object will be
1300
+ # copied in place and stored with reduced redundancy at a
1301
+ # lower cost. Otherwise, the object will be copied and stored
1302
+ # with the standard storage class.
1303
+ #
1304
+ # @return [true,false] The `value` parameter.
1305
+ # def reduced_redundancy= value
1306
+ # copy_from(key, :reduced_redundancy => value)
1307
+ # value
1308
+ # end
1309
+
1310
+ private
1311
+
1312
+ def presign_v4(method, options)
1313
+ PresignV4.new(self).presign(method, options)
1314
+ end
1315
+
1316
+ def presign_v3(method, options)
1317
+ options[:acl] = options[:acl].to_s.sub('_', '-') if options[:acl]
1318
+
1319
+ req = request_for_signing(options)
1320
+ req.http_method = http_method(method)
1321
+ req.add_param("AWSAccessKeyId", config.credential_provider.access_key_id)
1322
+ req.add_param("versionId", options[:version_id]) if options[:version_id]
1323
+ req.add_param("Signature", signature(req, options))
1324
+ req.add_param("Expires", options[:expires])
1325
+ req.add_param("x-amz-acl", options[:acl]) if options[:acl]
1326
+ if config.credential_provider.session_token
1327
+ req.add_param(
1328
+ "x-amz-security-token",
1329
+ config.credential_provider.session_token
1330
+ )
1331
+ end
1332
+
1333
+ build_uri(req, options)
1334
+ end
1335
+
1336
+ # Used to determine if the data needs to be copied in parts
1337
+ def use_multipart_copy? options
1338
+ options[:use_multipart_copy]
1339
+ end
1340
+
1341
+ def multipart_copy options
1342
+
1343
+ unless options[:content_length]
1344
+ msg = "unknown content length, must set :content_length " +
1345
+ "to use multi-part copy"
1346
+ raise ArgumentError, msg
1347
+ end
1348
+
1349
+ part_size = compute_part_size(options)
1350
+ clean_up_options(options)
1351
+ source_length = options.delete(:content_length)
1352
+
1353
+ multipart_upload(options) do |upload|
1354
+ pos = 0
1355
+ # We copy in part_size chunks until we read the
1356
+ until pos >= source_length
1357
+ last_byte = (pos + part_size >= source_length) ? source_length - 1 : pos + part_size - 1
1358
+ upload.copy_part(options[:copy_source], options.merge({:copy_source_range => "bytes=#{pos}-#{last_byte}"}))
1359
+ pos += part_size
1360
+ end
1361
+ end
1362
+ end
1363
+
1364
+ # @return [Boolean]
1365
+ def should_decrypt? options
1366
+ options[:encryption_key] or config.s3_encryption_key
1367
+ end
1368
+
1369
+ # A small wrapper around client#get_object
1370
+ def get_object options, &read_block
1371
+ client.get_object(options, &read_block).data
1372
+ end
1373
+
1374
+ # A wrapper around get_object that decrypts
1375
+ def get_encrypted_object options, &read_block
1376
+ decryption_cipher(options) do |cipher|
1377
+ if block_given?
1378
+ resp = get_object(options) do |chunk|
1379
+ yield(cipher.update(chunk))
1380
+ end
1381
+ yield(cipher.final)
1382
+ resp
1383
+ else
1384
+ cipher.update(get_object(options)[:data]) + cipher.final
1385
+ end
1386
+ end
1387
+ end
1388
+
1389
+ # @return [Boolean] Returns `true` if the :data option is large or
1390
+ # guessed to be larger than a configured threshold.
1391
+ def use_multipart? options
1392
+ estimated_content_length(options) > multipart_threshold(options) and
1393
+ !options[:single_request]
1394
+ end
1395
+
1396
+ # @return [Integer] Returns the number of bytes where a multipart
1397
+ # upload is used instead of #put_object.
1398
+ def multipart_threshold options
1399
+ threshold = options[:multipart_threshold] ||
1400
+ config.s3_multipart_threshold
1401
+ end
1402
+
1403
+ # @return [Integer] Returns the size of each multipart chunk.
1404
+ def compute_part_size options
1405
+
1406
+ max_parts = options[:multipart_max_parts] ||
1407
+ config.s3_multipart_max_parts
1408
+
1409
+ min_size = options[:multipart_min_part_size] ||
1410
+ config.s3_multipart_min_part_size
1411
+
1412
+ estimated_size = estimated_content_length(options)
1413
+
1414
+ part_size = [(estimated_size.to_f / max_parts).ceil, min_size].max.to_i
1415
+ part_size += 16 - (part_size % 16)
1416
+ part_size
1417
+
1418
+ end
1419
+
1420
+ # @return [Integer] Returns the size of the data or an estimated
1421
+ # size as provided by the user (useful for IO streams).
1422
+ def estimated_content_length options
1423
+ estimate = options[:content_length] ||
1424
+ options[:estimated_content_length]
1425
+ unless estimate
1426
+ msg = "unknown content length, must set :content_length or " +
1427
+ ":estimated_content_length"
1428
+ raise ArgumentError, msg
1429
+ end
1430
+ estimate
1431
+ end
1432
+
1433
+ def build_uri(request, options)
1434
+ uri_class = options[:secure] ? URI::HTTPS : URI::HTTP
1435
+ uri_class.build(:host => request.host,
1436
+ :port => request.port,
1437
+ :path => request.path,
1438
+ :query => request.querystring)
1439
+ end
1440
+
1441
+ def signature request, options
1442
+ parts = []
1443
+ parts << request.http_method
1444
+ parts << options[:content_md5].to_s
1445
+ parts << options[:content_type].to_s
1446
+ parts << options[:expires]
1447
+ parts << "x-amz-acl:#{options[:acl]}" if options[:acl]
1448
+ if token = config.credential_provider.session_token
1449
+ parts << "x-amz-security-token:#{token}"
1450
+ end
1451
+ parts << Core::Signers::S3.canonicalized_resource(request)
1452
+
1453
+ string_to_sign = parts.join("\n")
1454
+
1455
+ secret = config.credential_provider.secret_access_key
1456
+ Core::Signers::Base.sign(secret, string_to_sign, 'sha1')
1457
+ end
1458
+
1459
+ def expiration_timestamp(input)
1460
+ input = input.to_int if input.respond_to?(:to_int)
1461
+ case input
1462
+ when Time then input.to_i
1463
+ when DateTime then Time.parse(input.to_s).to_i
1464
+ when Integer then (Time.now + input).to_i
1465
+ when String then Time.parse(input).to_i
1466
+ else (Time.now + 60*60).to_i
1467
+ end
1468
+ end
1469
+
1470
+ def http_method(input)
1471
+ symbol = case input
1472
+ when :read then :get
1473
+ when :write then :put
1474
+ else
1475
+ input
1476
+ end
1477
+ symbol.to_s.upcase
1478
+ end
1479
+
1480
+ def request_for_signing(options)
1481
+
1482
+ port = [443, 80].include?(config.s3_port) ?
1483
+ (options[:secure] ? 443 : 80) :
1484
+ config.s3_port
1485
+
1486
+ req = Request.new
1487
+
1488
+ req.key = key
1489
+ req.host = options.fetch(:endpoint, config.s3_endpoint)
1490
+
1491
+ if req.host.nil? && options.include?(:endpoint) && options[:endpoint].nil?
1492
+ req.host = bucket.name
1493
+ else
1494
+ req.bucket = bucket.name
1495
+ end
1496
+
1497
+ req.port = options.fetch(:port, port)
1498
+ req.force_path_style = options.fetch(:force_path_style, config.s3_force_path_style)
1499
+
1500
+ REQUEST_PARAMETERS.each do |param|
1501
+ req.add_param(param.to_s.tr("_","-"),
1502
+ options[param]) if options.key?(param)
1503
+ end
1504
+
1505
+ req
1506
+ end
1507
+
1508
+ def add_sse_options(options)
1509
+ unless options.key?(:server_side_encryption)
1510
+ options[:server_side_encryption] = config.s3_server_side_encryption
1511
+ end
1512
+ options.delete(:server_side_encryption) if
1513
+ options[:server_side_encryption].nil?
1514
+ end
1515
+
1516
+ # Adds client-side encryption metadata headers and encrypts key
1517
+ def add_cse_options(options)
1518
+ encryption_key_for(options) do |encryption_key|
1519
+
1520
+ check_encryption_materials(:encrypt, encryption_key)
1521
+ cipher = get_aes_cipher(:encrypt, :CBC)
1522
+
1523
+ generate_aes_key(cipher) do |envelope_key, envelope_iv|
1524
+ envelope_key, envelope_iv =
1525
+ encode_envelope_key(encryption_key, envelope_key, envelope_iv)
1526
+
1527
+ build_cse_metadata(options,
1528
+ envelope_key,
1529
+ envelope_iv) do |headers, encryption_materials|
1530
+ store_encryption_materials(options, headers, encryption_materials)
1531
+ end
1532
+ end
1533
+
1534
+ # Wrap current stream in encryption
1535
+ options[:data] = CipherIO.new(cipher,
1536
+ options[:data],
1537
+ options[:content_length])
1538
+
1539
+ # Update content_length
1540
+ options[:content_length] =
1541
+ get_encrypted_size(options[:content_length]) if
1542
+ options[:content_length]
1543
+
1544
+ end
1545
+ remove_cse_options(options)
1546
+ end
1547
+
1548
+ # @yield [String, String] Yields an encrypted encoded key and iv pair
1549
+ def encode_envelope_key encryption_key, envelope_key, envelope_iv, &block
1550
+ envelope_key = encrypt(envelope_key, encryption_key)
1551
+ [encode64(envelope_key), encode64(envelope_iv)]
1552
+ end
1553
+
1554
+ # @yield [Hash, Hash] Yields headers and encryption materials that are
1555
+ # to be stored in the metadata and/or instruction file
1556
+ def build_cse_metadata options, enc_envelope_key, enc_envelope_iv, &block
1557
+ # Ensure metadata exists
1558
+ options[:metadata] = {} unless options[:metadata]
1559
+
1560
+ matdesc = options[:encryption_matdesc] || config.s3_encryption_matdesc
1561
+
1562
+ encryption_materials = {'x-amz-key' => enc_envelope_key,
1563
+ 'x-amz-iv' => enc_envelope_iv,
1564
+ 'x-amz-matdesc' => matdesc}
1565
+ orig_headers = {}
1566
+
1567
+ # Save the unencrypted content length
1568
+ if options[:content_length]
1569
+ orig_headers['x-amz-unencrypted-content-length'] =
1570
+ options[:content_length]
1571
+ end
1572
+
1573
+ # Save the unencrypted content MD5
1574
+ if options[:content_md5]
1575
+ orig_headers['x-amz-unencrypted-content-md5'] =
1576
+ options[:content_md5]
1577
+ options.delete(:content_md5)
1578
+ end
1579
+
1580
+ options[:metadata].merge!(orig_headers)
1581
+
1582
+ yield([orig_headers, encryption_materials])
1583
+ end
1584
+
1585
+ # Stores the headers and encryption materials needed to decrypt the data
1586
+ # and to know unencrypted information about the object
1587
+ def store_encryption_materials options, orig_headers, encryption_materials
1588
+ # Get the storage location
1589
+ cse_location = options[:encryption_materials_location] ||
1590
+ config.s3_encryption_materials_location
1591
+
1592
+ # Encryption type specific metadata
1593
+ case cse_location
1594
+ when :metadata
1595
+ options[:metadata].merge!(encryption_materials)
1596
+ when :instruction_file
1597
+ json_string = JSON.generate(encryption_materials)
1598
+ inst_headers = {'x-amz-crypto-instr-file' => ""}.merge(orig_headers)
1599
+ bucket.objects["#{key}.instruction"].write(json_string,
1600
+ :metadata => inst_headers)
1601
+ else
1602
+ msg = "invalid :encryption_materials_location, expected "
1603
+ msg << ":metadata or :instruction_file, got: #{cse_location.inspect}"
1604
+ raise ArgumentError, msg
1605
+ end
1606
+ nil
1607
+ end
1608
+
1609
+ # Removes any extra headers client-side encryption uses.
1610
+ def remove_cse_options options
1611
+ options.delete(:encryption_key)
1612
+ options.delete(:encryption_materials_location)
1613
+ options.delete(:encryption_matdesc)
1614
+ end
1615
+
1616
+ # Yields a decryption cipher for the given client-side encryption key
1617
+ # or raises an error.
1618
+ def decryption_cipher options, &block
1619
+ encryption_key_for(options) do |encryption_key|
1620
+
1621
+ check_encryption_materials(:decrypt, encryption_key)
1622
+
1623
+ location = options[:encryption_materials_location] ||
1624
+ config.s3_encryption_materials_location
1625
+
1626
+ cipher =
1627
+ decryption_materials(location, options) do |envelope_key, envelope_iv|
1628
+ envelope_key, envelope_iv =
1629
+ decode_envelope_key(envelope_key, envelope_iv, encryption_key)
1630
+ get_aes_cipher(:decrypt, :CBC, envelope_key, envelope_iv)
1631
+ end
1632
+
1633
+ remove_cse_options(options)
1634
+
1635
+ yield(cipher)
1636
+
1637
+ end
1638
+ end
1639
+
1640
+ # Decodes the envelope key for decryption
1641
+ def decode_envelope_key envelope_key, envelope_iv, encryption_key
1642
+ decrypted_key =
1643
+ begin
1644
+ decrypt(decode64(envelope_key), encryption_key)
1645
+ rescue RuntimeError
1646
+ msg = "Master key used to decrypt data key is not correct."
1647
+ raise MSS::S3::Errors::IncorrectClientSideEncryptionKey, msg
1648
+ end
1649
+
1650
+ [decrypted_key, decode64(envelope_iv)]
1651
+ end
1652
+
1653
+
1654
+ # @yield [String, String, String] Yields encryption materials for
1655
+ # decryption
1656
+ def decryption_materials location, options = {}, &block
1657
+
1658
+ materials = case location
1659
+ when :metadata then get_metadata_materials(options)
1660
+ when :instruction_file then get_inst_file_materials
1661
+ else
1662
+ msg = "invalid :encryption_materials_location option, expected "
1663
+ msg << ":metadata or :instruction_file, got: #{location.inspect}"
1664
+ raise ArgumentError, msg
1665
+ end
1666
+
1667
+ envelope_key, envelope_iv = materials
1668
+
1669
+ unless envelope_key and envelope_iv
1670
+ raise 'no encryption materials found, unable to decrypt'
1671
+ end
1672
+
1673
+ yield(envelope_key, envelope_iv)
1674
+
1675
+ end
1676
+
1677
+ # @return [String, String, String] Returns the data key, envelope_iv, and the
1678
+ # material description for decryption from the metadata.
1679
+ def get_metadata_materials(options)
1680
+ opts = {}
1681
+ opts[:version_id] = options[:version_id] if options[:version_id]
1682
+ metadata(opts).to_h.values_at(*%w(x-amz-key x-amz-iv))
1683
+ end
1684
+
1685
+ # @return [String, String, String] Returns the data key, envelope_iv, and the
1686
+ # material description for decryption from the instruction file.
1687
+ def get_inst_file_materials
1688
+ obj = bucket.objects["#{key}.instruction"]
1689
+ JSON.parse(obj.read).values_at(*%w(x-amz-key x-amz-iv))
1690
+ end
1691
+
1692
+ # @yield [Hash] Yields the metadata to be saved for client-side encryption
1693
+ def copy_cse_materials source, options
1694
+ cse_materials = {}
1695
+ meta = source.metadata.to_h
1696
+ cse_materials['x-amz-key'] = meta['x-amz-key'] if meta['x-amz-key']
1697
+ cse_materials['x-amz-iv'] = meta['x-amz-iv'] if meta['x-amz-iv']
1698
+ cse_materials['x-amz-matdesc'] = meta['x-amz-matdesc'] if
1699
+ meta['x-amz-matdesc']
1700
+ cse_materials['x-amz-unencrypted-content-length'] =
1701
+ meta['x-amz-unencrypted-content-length'] if
1702
+ meta['x-amz-unencrypted-content-length']
1703
+ cse_materials['x-amz-unencrypted-content-md5'] =
1704
+ meta['x-amz-unencrypted-content-md5'] if
1705
+ meta['x-amz-unencrypted-content-md5']
1706
+
1707
+ if
1708
+ cse_materials['x-amz-key'] and
1709
+ cse_materials['x-amz-iv'] and
1710
+ cse_materials['x-amz-matdesc']
1711
+ then
1712
+ options[:metadata] = (options[:metadata] || {}).merge(cse_materials)
1713
+ else
1714
+ # Handling instruction file
1715
+ source_inst = "#{source.key}.instruction"
1716
+ dest_inst = "#{key}.instruction"
1717
+ self.bucket.objects[dest_inst].copy_from(
1718
+ source.bucket.objects[source_inst])
1719
+ end
1720
+ end
1721
+
1722
+ # Removes unwanted options that should not be passed to the client.
1723
+ def clean_up_options(options)
1724
+ options.delete(:estimated_content_length)
1725
+ options.delete(:single_request)
1726
+ options.delete(:multipart_threshold)
1727
+ end
1728
+
1729
+ # Performs a write using a multipart upload
1730
+ def write_with_multipart options
1731
+ part_size = compute_part_size(options)
1732
+ clean_up_options(options)
1733
+ options.delete(:content_length)
1734
+
1735
+ multipart_upload(options) do |upload|
1736
+ upload.add_part(options[:data].read(part_size)) until
1737
+ options[:data].eof?
1738
+ end
1739
+ end
1740
+
1741
+ # Performs a write using a single request
1742
+ def write_with_put_object options
1743
+
1744
+ # its possible we don't know the content length of the data
1745
+ # option, but the :estimated_content_length was sufficiently
1746
+ # small that we will read the entire stream into memory
1747
+ # so we can tell s3 the content length (this is required).
1748
+ unless options[:content_length]
1749
+ data = StringIO.new
1750
+
1751
+ while (chunk = options[:data].read(4 * 1024))
1752
+ data << chunk
1753
+ end
1754
+
1755
+ options[:content_length] = data.size
1756
+ data.rewind
1757
+ options[:data] = data
1758
+ end
1759
+
1760
+ clean_up_options(options)
1761
+
1762
+ options[:bucket_name] = bucket.name
1763
+ options[:key] = key
1764
+
1765
+ resp = client.put_object(options)
1766
+
1767
+ resp.data[:version_id] ?
1768
+ ObjectVersion.new(self, resp.data[:version_id]) : self
1769
+ end
1770
+
1771
+ def encryption_key_for options, &block
1772
+ if key = options[:encryption_key] || config.s3_encryption_key
1773
+ yield(key)
1774
+ end
1775
+ end
1776
+
1777
+ def add_storage_class_option options
1778
+ if options[:reduced_redundancy] == true
1779
+ options[:storage_class] = 'REDUCED_REDUNDANCY'
1780
+ end
1781
+ end
1782
+
1783
+ # @return [String] Encodes a `String` in base 64 regardless of version of
1784
+ # Ruby for http headers (removes newlines).
1785
+ def encode64 input
1786
+ Base64.encode64(input).split("\n") * ""
1787
+ end
1788
+
1789
+ # @return [String] Decodes a `String` in base 64.
1790
+ def decode64 input
1791
+ Base64.decode64(input)
1792
+ end
1793
+ end
1794
+ end
1795
+ end