aws-sdk-s3 1.206.0 → 1.212.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 (44) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +41 -0
  3. data/VERSION +1 -1
  4. data/lib/aws-sdk-s3/client.rb +6 -6
  5. data/lib/aws-sdk-s3/client_api.rb +2 -0
  6. data/lib/aws-sdk-s3/customizations.rb +1 -0
  7. data/lib/aws-sdk-s3/encryption/client.rb +2 -2
  8. data/lib/aws-sdk-s3/encryption/default_cipher_provider.rb +2 -0
  9. data/lib/aws-sdk-s3/encryption/encrypt_handler.rb +2 -0
  10. data/lib/aws-sdk-s3/encryption/kms_cipher_provider.rb +2 -0
  11. data/lib/aws-sdk-s3/encryptionV2/client.rb +98 -23
  12. data/lib/aws-sdk-s3/encryptionV2/decrypt_handler.rb +7 -162
  13. data/lib/aws-sdk-s3/encryptionV2/decryption.rb +205 -0
  14. data/lib/aws-sdk-s3/encryptionV2/default_cipher_provider.rb +17 -0
  15. data/lib/aws-sdk-s3/encryptionV2/encrypt_handler.rb +2 -0
  16. data/lib/aws-sdk-s3/encryptionV2/io_encrypter.rb +2 -0
  17. data/lib/aws-sdk-s3/encryptionV2/kms_cipher_provider.rb +8 -0
  18. data/lib/aws-sdk-s3/encryptionV2/utils.rb +5 -0
  19. data/lib/aws-sdk-s3/encryptionV3/client.rb +885 -0
  20. data/lib/aws-sdk-s3/encryptionV3/decrypt_handler.rb +98 -0
  21. data/lib/aws-sdk-s3/encryptionV3/decryption.rb +244 -0
  22. data/lib/aws-sdk-s3/encryptionV3/default_cipher_provider.rb +159 -0
  23. data/lib/aws-sdk-s3/encryptionV3/default_key_provider.rb +35 -0
  24. data/lib/aws-sdk-s3/encryptionV3/encrypt_handler.rb +98 -0
  25. data/lib/aws-sdk-s3/encryptionV3/errors.rb +47 -0
  26. data/lib/aws-sdk-s3/encryptionV3/io_auth_decrypter.rb +60 -0
  27. data/lib/aws-sdk-s3/encryptionV3/io_decrypter.rb +35 -0
  28. data/lib/aws-sdk-s3/encryptionV3/io_encrypter.rb +84 -0
  29. data/lib/aws-sdk-s3/encryptionV3/key_provider.rb +28 -0
  30. data/lib/aws-sdk-s3/encryptionV3/kms_cipher_provider.rb +159 -0
  31. data/lib/aws-sdk-s3/encryptionV3/materials.rb +58 -0
  32. data/lib/aws-sdk-s3/encryptionV3/utils.rb +321 -0
  33. data/lib/aws-sdk-s3/encryption_v2.rb +1 -0
  34. data/lib/aws-sdk-s3/encryption_v3.rb +24 -0
  35. data/lib/aws-sdk-s3/endpoint_provider.rb +21 -18
  36. data/lib/aws-sdk-s3/file_uploader.rb +9 -1
  37. data/lib/aws-sdk-s3/multipart_file_uploader.rb +4 -1
  38. data/lib/aws-sdk-s3/plugins/checksum_algorithm.rb +18 -5
  39. data/lib/aws-sdk-s3/plugins/http_200_errors.rb +58 -34
  40. data/lib/aws-sdk-s3/transfer_manager.rb +18 -0
  41. data/lib/aws-sdk-s3.rb +1 -1
  42. data/sig/client.rbs +1 -1
  43. data/sig/types.rbs +1 -1
  44. metadata +19 -3
@@ -0,0 +1,321 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'openssl'
4
+
5
+ module Aws
6
+ module S3
7
+ module EncryptionV3
8
+ # @api private
9
+ module Utils
10
+ class << self
11
+ ##= ../specification/s3-encryption/client.md#encryption-algorithm
12
+ ##% The S3EC MUST validate that the configured encryption algorithm is not legacy.
13
+ def validate_cek(content_encryption_schema)
14
+ ##= ../specification/s3-encryption/data-format/content-metadata.md#algorithm-suite-and-message-format-version-compatibility
15
+ ##% Objects encrypted with ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY MUST use the V3 message format version only.
16
+ return '115' if content_encryption_schema.nil?
17
+
18
+ case content_encryption_schema
19
+ when :alg_aes_256_gcm_hkdf_sha512_commit_key
20
+ '115'
21
+ else
22
+ ##= ../specification/s3-encryption/encryption.md#alg-aes-256-ctr-iv16-tag16-no-kdf
23
+ ##% Attempts to encrypt using AES-CTR MUST fail.
24
+ ##= ../specification/s3-encryption/encryption.md#alg-aes-256-ctr-hkdf-sha512-commit-key
25
+ ##% Attempts to encrypt using key committing AES-CTR MUST fail.
26
+ ##= ../specification/s3-encryption/client.md#encryption-algorithm
27
+ ##% If the configured encryption algorithm is legacy, then the S3EC MUST throw an exception.
28
+ ##= ../specification/s3-encryption/client.md#key-commitment
29
+ ##% If the configured Encryption Algorithm is incompatible with the key commitment policy, then it MUST throw an exception.
30
+ raise ArgumentError, "Unsupported content_encryption_schema: #{content_encryption_schema}"
31
+ end
32
+ end
33
+
34
+ def encrypt_aes_gcm(key, data, auth_data)
35
+ cipher = aes_encryption_cipher(:GCM, key)
36
+ cipher.iv = (iv = cipher.random_iv)
37
+ cipher.auth_data = auth_data
38
+
39
+ iv + cipher.update(data) + cipher.final + cipher.auth_tag
40
+ end
41
+
42
+ def encrypt_rsa(key, data, auth_data)
43
+ # Plaintext must be KeyLengthInBytes (1 Byte) + DataKey + AuthData
44
+ buf = [data.bytesize] + data.unpack('C*') + auth_data.unpack('C*')
45
+ key.public_encrypt(buf.pack('C*'), OpenSSL::PKey::RSA::PKCS1_OAEP_PADDING)
46
+ end
47
+
48
+ def decrypt_aes_gcm(key, data, auth_data)
49
+ # data is iv (12B) + key + tag (16B)
50
+ buf = data.unpack('C*')
51
+ iv = buf[0, 12].pack('C*') # iv will always be 12 bytes
52
+ tag = buf[-16, 16].pack('C*') # tag is 16 bytes
53
+ enc_key = buf[12, buf.size - (12 + 16)].pack('C*')
54
+ cipher = aes_cipher(:decrypt, :GCM, key, iv)
55
+ cipher.auth_tag = tag
56
+ cipher.auth_data = auth_data
57
+ cipher.update(enc_key) + cipher.final
58
+ end
59
+
60
+ # returns the decrypted data + auth_data
61
+ def decrypt_rsa(key, enc_data)
62
+ # Plaintext must be KeyLengthInBytes (1 Byte) + DataKey + AuthData
63
+ buf = key.private_decrypt(enc_data, OpenSSL::PKey::RSA::PKCS1_OAEP_PADDING).unpack('C*')
64
+ key_length = buf[0]
65
+ data = buf[1, key_length].pack('C*')
66
+ auth_data = buf[key_length + 1, buf.length - key_length].pack('C*')
67
+ [data, auth_data]
68
+ end
69
+
70
+ # @param [String] block_mode "CBC" or "ECB"
71
+ # @param [OpenSSL::PKey::RSA, String, nil] key
72
+ # @param [String, nil] iv The initialization vector
73
+ def aes_encryption_cipher(block_mode, key = nil, iv = nil)
74
+ aes_cipher(:encrypt, block_mode, key, iv)
75
+ end
76
+
77
+ # @param [String] block_mode "CBC" or "ECB"
78
+ # @param [OpenSSL::PKey::RSA, String, nil] key
79
+ # @param [String, nil] iv The initialization vector
80
+ def aes_decryption_cipher(block_mode, key = nil, iv = nil)
81
+ aes_cipher(:decrypt, block_mode, key, iv)
82
+ end
83
+
84
+ # @param [String] mode "encrypt" or "decrypt"
85
+ # @param [String] block_mode "CBC" or "ECB"
86
+ # @param [OpenSSL::PKey::RSA, String, nil] key
87
+ # @param [String, nil] iv The initialization vector
88
+ def aes_cipher(mode, block_mode, key, iv)
89
+ cipher =
90
+ if key
91
+ OpenSSL::Cipher.new("aes-#{cipher_size(key)}-#{block_mode.downcase}")
92
+ else
93
+ OpenSSL::Cipher.new("aes-256-#{block_mode.downcase}")
94
+ end
95
+ cipher.send(mode) # encrypt or decrypt
96
+ cipher.key = key if key
97
+ cipher.iv = iv if iv
98
+ cipher
99
+ end
100
+
101
+ # @param [String] key
102
+ # @return [Integer]
103
+ # @raise ArgumentError
104
+ def cipher_size(key)
105
+ key.bytesize * 8
106
+ end
107
+
108
+ # There is only 1 supported algorithm suite at this time
109
+ ENCRYPTION_KEY_INFO = ([0x00, 0x73].pack('C*') + 'DERIVEKEY'.encode('UTF-8')).freeze
110
+ COMMITMENT_KEY_INFO = ([0x00, 0x73].pack('C*') + 'COMMITKEY'.encode('UTF-8')).freeze
111
+
112
+ SHA512_DIGEST = OpenSSL::Digest::SHA512.new.freeze
113
+ V3_IV_BYTES = ("\x01" * 12).freeze
114
+ ALGO_ID = [0x00, 0x73].pack('C*').freeze
115
+
116
+ def generate_alg_aes_256_gcm_hkdf_sha512_commit_key_cipher(data_key)
117
+ ##= ../specification/s3-encryption/encryption.md#content-encryption
118
+ ##% The client MUST generate an IV or Message ID using the length of the IV or Message ID defined in the algorithm suite.
119
+ message_id = Utils.generate_message_id
120
+ ##= ../specification/s3-encryption/key-derivation.md#hkdf-operation
121
+ ##% - The salt MUST be the Message ID with the length defined in the algorithm suite.
122
+ commitment_key = Utils.derive_commitment_key(data_key, message_id)
123
+ cipher = alg_aes_256_gcm_hkdf_sha512_commit_key_cipher(:encrypt, data_key, message_id)
124
+
125
+ [
126
+ cipher,
127
+ ##= ../specification/s3-encryption/encryption.md#content-encryption
128
+ ##% The generated IV or Message ID MUST be set or returned from the encryption process such that it can be included in the content metadata.
129
+ message_id,
130
+ ##= ../specification/s3-encryption/encryption.md#alg-aes-256-gcm-hkdf-sha512-commit-key
131
+ ##% The derived key commitment value MUST be set or returned from the encryption process such that it can be included in the content metadata.
132
+ commitment_key
133
+ ]
134
+ end
135
+
136
+ def derive_alg_aes_256_gcm_hkdf_sha512_commit_key_cipher(data_key, message_id, stored_commitment_key)
137
+ raise Errors::DecryptionError, 'Data key length does not match algorithm suite' unless data_key.length == 32
138
+
139
+ raise Errors::DecryptionError, 'Message id length does not match algorithm suite' unless message_id.length == 28
140
+
141
+ unless stored_commitment_key.length == 28
142
+ raise Errors::DecryptionError, 'Commitment key length does not match algorithm suite'
143
+ end
144
+
145
+ ##= ../specification/s3-encryption/decryption.md#decrypting-with-commitment
146
+ ##= type=implication
147
+ ##% When using an algorithm suite which supports key commitment,
148
+ ##% the verification of the derived key commitment value MUST be done in constant time.
149
+ unless timing_safe_equal?(
150
+ ##= ../specification/s3-encryption/decryption.md#decrypting-with-commitment
151
+ ##% When using an algorithm suite which supports key commitment,
152
+ ##% the client MUST verify that the [derived key commitment](./key-derivation.md#hkdf-operation) contains the same bytes
153
+ ##% as the stored key commitment retrieved from the stored object's metadata.
154
+ Utils.derive_commitment_key(data_key, message_id),
155
+ stored_commitment_key
156
+ )
157
+ ##= ../specification/s3-encryption/decryption.md#decrypting-with-commitment
158
+ ##% When using an algorithm suite which supports key commitment,
159
+ ##% the client MUST throw an exception when the derived key commitment value and stored key commitment value do not match.
160
+ raise Errors::DecryptionError, 'Commitment key verification failed'
161
+ end
162
+
163
+ ##= ../specification/s3-encryption/decryption.md#decrypting-with-commitment
164
+ ##% When using an algorithm suite which supports key commitment,
165
+ ##% the client MUST verify the key commitment values match before deriving the [derived encryption key](./key-derivation.md#hkdf-operation).
166
+
167
+ alg_aes_256_gcm_hkdf_sha512_commit_key_cipher(:decrypt, data_key, message_id)
168
+ end
169
+
170
+ def alg_aes_256_gcm_hkdf_sha512_commit_key_cipher(mode, data_key, message_id)
171
+ ##= ../specification/s3-encryption/key-derivation.md#hkdf-operation
172
+ ##% The client MUST initialize the cipher, or call an AES-GCM encryption API, with the derived encryption key, an IV containing only bytes with the value 0x01,
173
+ ##% and the tag length defined in the Algorithm Suite when encrypting or decrypting with ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY.
174
+ cipher = Utils.aes_cipher(
175
+ mode,
176
+ :GCM,
177
+ ##= ../specification/s3-encryption/encryption.md#alg-aes-256-gcm-hkdf-sha512-commit-key
178
+ ##% The client MUST use HKDF to derive the key commitment value and the derived encrypting key as described in [Key Derivation](key-derivation.md).
179
+ Utils.derive_encryption_key(data_key, message_id),
180
+ ##= ../specification/s3-encryption/key-derivation.md#hkdf-operation
181
+ ##% When encrypting or decrypting with ALG_AES_256_GCM_HKDF_SHA512_COMMIT_KEY,
182
+ ##% the IV used in the AES-GCM content encryption/decryption MUST consist entirely of bytes with the value 0x01.
183
+ ##= ../specification/s3-encryption/key-derivation.md#hkdf-operation
184
+ ##% The IV's total length MUST match the IV length defined by the algorithm suite.
185
+ V3_IV_BYTES
186
+ ) #OpenSSL::Cipher.new("aes-256-gcm")
187
+ ##= ../specification/s3-encryption/key-derivation.md#hkdf-operation
188
+ ##% The client MUST set the AAD to the Algorithm Suite ID represented as bytes.
189
+ cipher.auth_data = ALGO_ID # auth_data must be set after key and iv
190
+ cipher
191
+ end
192
+
193
+ def generate_data_key
194
+ OpenSSL::Random.random_bytes(32)
195
+ end
196
+
197
+ def generate_message_id
198
+ ##= ../specification/s3-encryption/encryption.md#cipher-initialization
199
+ ##= type=exception
200
+ ##= reason=This would be a new runtime error that happens randomly.
201
+ ##% The client SHOULD validate that the generated IV or Message ID is not zeros.
202
+
203
+ ##= ../specification/s3-encryption/encryption.md#content-encryption
204
+ ##% The client MUST generate an IV or Message ID using the length of the IV or Message ID defined in the algorithm suite.
205
+ OpenSSL::Random.random_bytes(28)
206
+ end
207
+
208
+ def derive_encryption_key(data_key, message_id)
209
+ ##= ../specification/s3-encryption/key-derivation.md#hkdf-operation
210
+ ##% - The DEK input pseudorandom key MUST be the output from the extract step.
211
+ hkdf(
212
+ data_key,
213
+ ##= ../specification/s3-encryption/key-derivation.md#hkdf-operation
214
+ ##% - The salt MUST be the Message ID with the length defined in the algorithm suite.
215
+ message_id,
216
+ ##= ../specification/s3-encryption/key-derivation.md#hkdf-operation
217
+ ##% - The input info MUST be a concatenation of the algorithm suite ID as bytes followed by the string DERIVEKEY as UTF8 encoded bytes.
218
+ ENCRYPTION_KEY_INFO,
219
+ ##= ../specification/s3-encryption/key-derivation.md#hkdf-operation
220
+ ##% - The length of the output keying material MUST equal the encryption key length specified by the algorithm suite encryption settings.
221
+ 32
222
+ )
223
+ end
224
+
225
+ def derive_commitment_key(data_key, message_id)
226
+ ##= ../specification/s3-encryption/key-derivation.md#hkdf-operation
227
+ ##% - The CK input pseudorandom key MUST be the output from the extract step.
228
+ hkdf(
229
+ data_key,
230
+ message_id,
231
+ ##= ../specification/s3-encryption/key-derivation.md#hkdf-operation
232
+ ##% - The input info MUST be a concatenation of the algorithm suite ID as bytes followed by the string COMMITKEY as UTF8 encoded bytes.
233
+ COMMITMENT_KEY_INFO,
234
+ ##= ../specification/s3-encryption/key-derivation.md#hkdf-operation
235
+ ##% - The length of the output keying material MUST equal the commit key length specified by the supported algorithm suites.
236
+ 28
237
+ )
238
+ end
239
+
240
+ ONE_BYTE = [1].pack('C').freeze
241
+ # assert: the following function is equivalent to `OpenSSL::KDF.hkdf` for all desired_length <= 64
242
+ # see spec: 'produces identical output to native hkdf for random inputs (property-based test)'
243
+ def hkdf_fallback(input_key_material, salt, info, desired_length)
244
+ # Extract from RFC 5869
245
+ # PRK = HMAC-Hash(salt, IKM)
246
+ prk = OpenSSL::HMAC.digest(SHA512_DIGEST, salt, input_key_material)
247
+
248
+ # Expand from RFC 5869
249
+ # N = ceil(L/HashLen)
250
+ # T = T(1) | T(2) | T(3) | ... | T(N)
251
+ # OKM = first L octets of T
252
+ #
253
+ # where:
254
+ # T(0) = empty string (zero length)
255
+ # T(1) = HMAC-Hash(PRK, T(0) | info | 0x01)
256
+ # T(2) = HMAC-Hash(PRK, T(1) | info | 0x02)
257
+ # T(3) = HMAC-Hash(PRK, T(2) | info | 0x03)
258
+ #
259
+ # L == desired_length
260
+ # HashLen == 64 (because SHA512_DIGEST is fixed)
261
+ # N = ceil(desired_length/64)
262
+ # The only supported suites have desired_length less than 64
263
+ # This will result in a single iteration of the expand loop.
264
+ # This check verifies that it is safe to do not do a loop
265
+ raise Errors::DecryptionError, "Unsupported length: #{desired_length}" if desired_length > 64
266
+
267
+ # assert N == 1
268
+ #
269
+ # For a single iteration of the loop we then get:
270
+ # OKM = first L of T(0) | T(1)
271
+ # ==
272
+ # (T(0) + T(1))[0, desired_length]
273
+ # == {assert T(0) == ''}
274
+ # ('' + HMAC-Hash(PRK, '' + info + 0x01))[0, desired_length]
275
+ # == HMAC-Hash(PRK, info + 0x01)[0, desired_length]
276
+ # == {assert ONE_BYTE == 0x01}
277
+ # HMAC-Hash(PRK, info + ONE_BYTE)[0, desired_length]
278
+ # ==
279
+ OpenSSL::HMAC.digest(SHA512_DIGEST, prk, info + ONE_BYTE)[0, desired_length]
280
+ end
281
+
282
+ if defined?(OpenSSL::KDF) && OpenSSL::KDF.respond_to?(:hkdf)
283
+ def hkdf(input_key_material, salt, info, desired_length)
284
+ OpenSSL::KDF.hkdf(
285
+ ##= ../specification/s3-encryption/key-derivation.md#hkdf-operation
286
+ ##% - The input keying material MUST be the plaintext data key (PDK) generated by the key provider.
287
+ input_key_material,
288
+ salt: salt,
289
+ info: info,
290
+ ##= ../specification/s3-encryption/key-derivation.md#hkdf-operation
291
+ ##% - The length of the input keying material MUST equal the key derivation input length specified by the algorithm suite commit key derivation setting.
292
+ length: desired_length,
293
+ ##= ../specification/s3-encryption/key-derivation.md#hkdf-operation
294
+ ##% - The hash function MUST be specified by the algorithm suite commitment settings.
295
+ hash: SHA512_DIGEST
296
+ )
297
+ end
298
+ else
299
+ # This is done so that we can test hkdf_fallback when we have `OpenSSL::KDF.hkdf`
300
+ alias hkdf hkdf_fallback
301
+ end
302
+
303
+ if defined?(OpenSSL) && OpenSSL.respond_to?(:secure_compare)
304
+ def timing_safe_equal?(a, b)
305
+ OpenSSL.secure_compare(a, b)
306
+ end
307
+ else
308
+ def timing_safe_equal?(a, b)
309
+ return false unless a.bytesize == b.bytesize
310
+
311
+ l = a.unpack('C*')
312
+ r = 0
313
+ b.each_byte { |byte| r |= byte ^ l.shift }
314
+ r.zero?
315
+ end
316
+ end
317
+ end
318
+ end
319
+ end
320
+ end
321
+ end
@@ -1,4 +1,5 @@
1
1
  require 'aws-sdk-s3/encryptionV2/client'
2
+ require 'aws-sdk-s3/encryptionV2/decryption'
2
3
  require 'aws-sdk-s3/encryptionV2/decrypt_handler'
3
4
  require 'aws-sdk-s3/encryptionV2/default_cipher_provider'
4
5
  require 'aws-sdk-s3/encryptionV2/encrypt_handler'
@@ -0,0 +1,24 @@
1
+ require 'aws-sdk-s3/encryptionV3/client'
2
+ require 'aws-sdk-s3/encryptionV3/decryption'
3
+ require 'aws-sdk-s3/encryptionV3/decrypt_handler'
4
+ require 'aws-sdk-s3/encryptionV3/default_cipher_provider'
5
+ require 'aws-sdk-s3/encryptionV3/encrypt_handler'
6
+ require 'aws-sdk-s3/encryptionV3/errors'
7
+ require 'aws-sdk-s3/encryptionV3/io_encrypter'
8
+ require 'aws-sdk-s3/encryptionV3/io_decrypter'
9
+ require 'aws-sdk-s3/encryptionV3/io_auth_decrypter'
10
+ require 'aws-sdk-s3/encryptionV3/key_provider'
11
+ require 'aws-sdk-s3/encryptionV3/kms_cipher_provider'
12
+ require 'aws-sdk-s3/encryptionV3/materials'
13
+ require 'aws-sdk-s3/encryptionV3/utils'
14
+ require 'aws-sdk-s3/encryptionV3/default_key_provider'
15
+
16
+ module Aws
17
+ module S3
18
+ module EncryptionV3
19
+ AES_GCM_TAG_LEN_BYTES = 16
20
+ EC_USER_AGENT = 'S3CryptoV3'
21
+ end
22
+ end
23
+ end
24
+
@@ -417,29 +417,32 @@ module Aws::S3
417
417
  end
418
418
  if Aws::Endpoints::Matchers.set?(parameters.bucket) && (hardware_type = Aws::Endpoints::Matchers.substring(parameters.bucket, 49, 50, true)) && (region_prefix = Aws::Endpoints::Matchers.substring(parameters.bucket, 8, 12, true)) && (bucket_alias_suffix = Aws::Endpoints::Matchers.substring(parameters.bucket, 0, 7, true)) && (outpost_id = Aws::Endpoints::Matchers.substring(parameters.bucket, 32, 49, true)) && (region_partition = Aws::Endpoints::Matchers.aws_partition(parameters.region)) && Aws::Endpoints::Matchers.string_equals?(bucket_alias_suffix, "--op-s3")
419
419
  if Aws::Endpoints::Matchers.valid_host_label?(outpost_id, false)
420
- if Aws::Endpoints::Matchers.string_equals?(hardware_type, "e")
421
- if Aws::Endpoints::Matchers.string_equals?(region_prefix, "beta")
422
- if Aws::Endpoints::Matchers.not(Aws::Endpoints::Matchers.set?(parameters.endpoint))
423
- raise ArgumentError, "Expected a endpoint to be specified but no endpoint was found"
424
- end
425
- if Aws::Endpoints::Matchers.set?(parameters.endpoint) && (url = Aws::Endpoints::Matchers.parse_url(parameters.endpoint))
426
- return Aws::Endpoints::Endpoint.new(url: "https://#{parameters.bucket}.ec2.#{url['authority']}", headers: {}, properties: {"authSchemes" => [{"disableDoubleEncoding" => true, "name" => "sigv4a", "signingName" => "s3-outposts", "signingRegionSet" => ["*"]}, {"disableDoubleEncoding" => true, "name" => "sigv4", "signingName" => "s3-outposts", "signingRegion" => "#{parameters.region}"}]})
420
+ if Aws::Endpoints::Matchers.aws_virtual_hostable_s3_bucket?(parameters.bucket, false)
421
+ if Aws::Endpoints::Matchers.string_equals?(hardware_type, "e")
422
+ if Aws::Endpoints::Matchers.string_equals?(region_prefix, "beta")
423
+ if Aws::Endpoints::Matchers.not(Aws::Endpoints::Matchers.set?(parameters.endpoint))
424
+ raise ArgumentError, "Expected a endpoint to be specified but no endpoint was found"
425
+ end
426
+ if Aws::Endpoints::Matchers.set?(parameters.endpoint) && (url = Aws::Endpoints::Matchers.parse_url(parameters.endpoint))
427
+ return Aws::Endpoints::Endpoint.new(url: "https://#{parameters.bucket}.ec2.#{url['authority']}", headers: {}, properties: {"authSchemes" => [{"disableDoubleEncoding" => true, "name" => "sigv4a", "signingName" => "s3-outposts", "signingRegionSet" => ["*"]}, {"disableDoubleEncoding" => true, "name" => "sigv4", "signingName" => "s3-outposts", "signingRegion" => "#{parameters.region}"}]})
428
+ end
427
429
  end
430
+ return Aws::Endpoints::Endpoint.new(url: "https://#{parameters.bucket}.ec2.s3-outposts.#{parameters.region}.#{region_partition['dnsSuffix']}", headers: {}, properties: {"authSchemes" => [{"disableDoubleEncoding" => true, "name" => "sigv4a", "signingName" => "s3-outposts", "signingRegionSet" => ["*"]}, {"disableDoubleEncoding" => true, "name" => "sigv4", "signingName" => "s3-outposts", "signingRegion" => "#{parameters.region}"}]})
428
431
  end
429
- return Aws::Endpoints::Endpoint.new(url: "https://#{parameters.bucket}.ec2.s3-outposts.#{parameters.region}.#{region_partition['dnsSuffix']}", headers: {}, properties: {"authSchemes" => [{"disableDoubleEncoding" => true, "name" => "sigv4a", "signingName" => "s3-outposts", "signingRegionSet" => ["*"]}, {"disableDoubleEncoding" => true, "name" => "sigv4", "signingName" => "s3-outposts", "signingRegion" => "#{parameters.region}"}]})
430
- end
431
- if Aws::Endpoints::Matchers.string_equals?(hardware_type, "o")
432
- if Aws::Endpoints::Matchers.string_equals?(region_prefix, "beta")
433
- if Aws::Endpoints::Matchers.not(Aws::Endpoints::Matchers.set?(parameters.endpoint))
434
- raise ArgumentError, "Expected a endpoint to be specified but no endpoint was found"
435
- end
436
- if Aws::Endpoints::Matchers.set?(parameters.endpoint) && (url = Aws::Endpoints::Matchers.parse_url(parameters.endpoint))
437
- return Aws::Endpoints::Endpoint.new(url: "https://#{parameters.bucket}.op-#{outpost_id}.#{url['authority']}", headers: {}, properties: {"authSchemes" => [{"disableDoubleEncoding" => true, "name" => "sigv4a", "signingName" => "s3-outposts", "signingRegionSet" => ["*"]}, {"disableDoubleEncoding" => true, "name" => "sigv4", "signingName" => "s3-outposts", "signingRegion" => "#{parameters.region}"}]})
432
+ if Aws::Endpoints::Matchers.string_equals?(hardware_type, "o")
433
+ if Aws::Endpoints::Matchers.string_equals?(region_prefix, "beta")
434
+ if Aws::Endpoints::Matchers.not(Aws::Endpoints::Matchers.set?(parameters.endpoint))
435
+ raise ArgumentError, "Expected a endpoint to be specified but no endpoint was found"
436
+ end
437
+ if Aws::Endpoints::Matchers.set?(parameters.endpoint) && (url = Aws::Endpoints::Matchers.parse_url(parameters.endpoint))
438
+ return Aws::Endpoints::Endpoint.new(url: "https://#{parameters.bucket}.op-#{outpost_id}.#{url['authority']}", headers: {}, properties: {"authSchemes" => [{"disableDoubleEncoding" => true, "name" => "sigv4a", "signingName" => "s3-outposts", "signingRegionSet" => ["*"]}, {"disableDoubleEncoding" => true, "name" => "sigv4", "signingName" => "s3-outposts", "signingRegion" => "#{parameters.region}"}]})
439
+ end
438
440
  end
441
+ return Aws::Endpoints::Endpoint.new(url: "https://#{parameters.bucket}.op-#{outpost_id}.s3-outposts.#{parameters.region}.#{region_partition['dnsSuffix']}", headers: {}, properties: {"authSchemes" => [{"disableDoubleEncoding" => true, "name" => "sigv4a", "signingName" => "s3-outposts", "signingRegionSet" => ["*"]}, {"disableDoubleEncoding" => true, "name" => "sigv4", "signingName" => "s3-outposts", "signingRegion" => "#{parameters.region}"}]})
439
442
  end
440
- return Aws::Endpoints::Endpoint.new(url: "https://#{parameters.bucket}.op-#{outpost_id}.s3-outposts.#{parameters.region}.#{region_partition['dnsSuffix']}", headers: {}, properties: {"authSchemes" => [{"disableDoubleEncoding" => true, "name" => "sigv4a", "signingName" => "s3-outposts", "signingRegionSet" => ["*"]}, {"disableDoubleEncoding" => true, "name" => "sigv4", "signingName" => "s3-outposts", "signingRegion" => "#{parameters.region}"}]})
443
+ raise ArgumentError, "Unrecognized hardware type: \"Expected hardware type o or e but got #{hardware_type}\""
441
444
  end
442
- raise ArgumentError, "Unrecognized hardware type: \"Expected hardware type o or e but got #{hardware_type}\""
445
+ raise ArgumentError, "Invalid Outposts Bucket alias - it must be a valid bucket name."
443
446
  end
444
447
  raise ArgumentError, "Invalid ARN: The outpost Id must only contain a-z, A-Z, 0-9 and `-`."
445
448
  end
@@ -15,6 +15,7 @@ module Aws
15
15
  def initialize(options = {})
16
16
  @client = options[:client] || Client.new
17
17
  @executor = options[:executor]
18
+ @http_chunk_size = options[:http_chunk_size]
18
19
  @multipart_threshold = options[:multipart_threshold] || DEFAULT_MULTIPART_THRESHOLD
19
20
  end
20
21
 
@@ -37,7 +38,11 @@ module Aws
37
38
  def upload(source, options = {})
38
39
  Aws::Plugins::UserAgent.metric('S3_TRANSFER') do
39
40
  if File.size(source) >= @multipart_threshold
40
- MultipartFileUploader.new(client: @client, executor: @executor).upload(source, options)
41
+ MultipartFileUploader.new(
42
+ client: @client,
43
+ executor: @executor,
44
+ http_chunk_size: @http_chunk_size
45
+ ).upload(source, options)
41
46
  else
42
47
  put_object(source, options)
43
48
  end
@@ -59,7 +64,10 @@ module Aws
59
64
  options[:on_chunk_sent] = single_part_progress(callback)
60
65
  end
61
66
  open_file(source) do |file|
67
+ Thread.current[:net_http_override_body_stream_chunk] = @http_chunk_size if @http_chunk_size
62
68
  @client.put_object(options.merge(body: file))
69
+ ensure
70
+ Thread.current[:net_http_override_body_stream_chunk] = nil
63
71
  end
64
72
  end
65
73
 
@@ -22,6 +22,7 @@ module Aws
22
22
  def initialize(options = {})
23
23
  @client = options[:client] || Client.new
24
24
  @executor = options[:executor]
25
+ @http_chunk_size = options[:http_chunk_size]
25
26
  end
26
27
 
27
28
  # @return [Client]
@@ -78,7 +79,7 @@ module Aws
78
79
  rescue MultipartUploadError => e
79
80
  raise e
80
81
  rescue StandardError => e
81
- msg = "failed to abort multipart upload: #{e.message}. " \
82
+ msg = "failed to abort multipart upload: #{e&.message}. " \
82
83
  "Multipart upload failed: #{errors.map(&:message).join('; ')}"
83
84
  raise MultipartUploadError.new(msg, errors + [e])
84
85
  end
@@ -150,6 +151,7 @@ module Aws
150
151
 
151
152
  upload_attempts += 1
152
153
  @executor.post(part) do |p|
154
+ Thread.current[:net_http_override_body_stream_chunk] = @http_chunk_size if @http_chunk_size
153
155
  update_progress(progress, p)
154
156
  resp = @client.upload_part(p)
155
157
  p[:body].close
@@ -160,6 +162,7 @@ module Aws
160
162
  abort_upload = true
161
163
  errors << e
162
164
  ensure
165
+ Thread.current[:net_http_override_body_stream_chunk] = nil if @http_chunk_size
163
166
  completion_queue << :done
164
167
  end
165
168
  end
@@ -18,12 +18,25 @@ module Aws
18
18
  end
19
19
  end
20
20
 
21
+ # Handler to disable trailer checksums for S3-compatible services
22
+ # that don't support STREAMING-UNSIGNED-PAYLOAD-TRAILER
23
+ # See: https://github.com/aws/aws-sdk-ruby/issues/3338
24
+ class SkipTrailerChecksumsHandler < Seahorse::Client::Handler
25
+ def call(context)
26
+ context[:skip_trailer_checksums] = true if custom_endpoint?(context.config)
27
+ @handler.call(context)
28
+ end
29
+
30
+ private
31
+
32
+ def custom_endpoint?(config)
33
+ !config.regional_endpoint || !config.endpoint_provider.instance_of?(Aws::S3::EndpointProvider)
34
+ end
35
+ end
36
+
21
37
  def add_handlers(handlers, _config)
22
- handlers.add(
23
- SkipWholeMultipartGetChecksumsHandler,
24
- step: :initialize,
25
- operations: [:get_object]
26
- )
38
+ handlers.add(SkipWholeMultipartGetChecksumsHandler, step: :initialize, operations: [:get_object])
39
+ handlers.add(SkipTrailerChecksumsHandler, step: :build, priority: 16, operations: %i[put_object upload_part])
27
40
  end
28
41
  end
29
42
  end
@@ -3,15 +3,28 @@
3
3
  module Aws
4
4
  module S3
5
5
  module Plugins
6
-
7
6
  # A handful of Amazon S3 operations will respond with a 200 status
8
7
  # code but will send an error in the response body. This plugin
9
8
  # injects a handler that will parse 200 response bodies for potential
10
9
  # errors, allowing them to be retried.
11
10
  # @api private
12
11
  class Http200Errors < Seahorse::Client::Plugin
13
-
14
12
  class Handler < Seahorse::Client::Handler
13
+ # A regular expression to match error codes in the response body
14
+ CODE_PATTERN = %r{<Code>(.+?)</Code>}.freeze
15
+ private_constant :CODE_PATTERN
16
+
17
+ # A list of encodings we force into UTF-8
18
+ ENCODINGS_TO_FIX = [Encoding::US_ASCII, Encoding::ASCII_8BIT].freeze
19
+ private_constant :ENCODINGS_TO_FIX
20
+
21
+ # A regular expression to match detect errors in the response body
22
+ ERROR_PATTERN = /<\?xml\s[^>]*\?>\s*<Error>/.freeze
23
+ private_constant :ERROR_PATTERN
24
+
25
+ # A regular expression to match an error message in the response body
26
+ MESSAGE_PATTERN = %r{<Message>(.+?)</Message>}.freeze
27
+ private_constant :MESSAGE_PATTERN
15
28
 
16
29
  def call(context)
17
30
  @handler.call(context).on(200) do |response|
@@ -28,29 +41,37 @@ module Aws
28
41
 
29
42
  private
30
43
 
31
- # Streaming outputs are not subject to 200 errors.
32
- def streaming_output?(output)
33
- if (payload = output[:payload_member])
34
- # checking ref and shape
35
- payload['streaming'] || payload.shape['streaming'] ||
36
- payload.eventstream
37
- else
38
- false
44
+ def build_error(context, code, message)
45
+ S3::Errors.error_class(code).new(context, message)
46
+ end
47
+
48
+ def check_for_error(context)
49
+ xml = normalize_encoding(context.http_response.body_contents)
50
+
51
+ if xml.match?(ERROR_PATTERN)
52
+ error_code = xml.match(CODE_PATTERN)[1]
53
+ error_message = xml.match(MESSAGE_PATTERN)[1]
54
+ build_error(context, error_code, error_message)
55
+ elsif incomplete_xml_body?(xml, context.operation.output)
56
+ Seahorse::Client::NetworkingError.new(
57
+ build_error(context, 'InternalError', 'Empty or incomplete response body')
58
+ )
39
59
  end
40
60
  end
41
61
 
62
+ # Must have a member in the body and have the start of an XML Tag.
63
+ # Other incomplete xml bodies will result in an XML ParsingError.
64
+ def incomplete_xml_body?(xml, output)
65
+ members_in_body?(output) && !xml.match(/<\w/)
66
+ end
67
+
42
68
  # Checks if the output shape is a structure shape and has members that
43
69
  # are in the body for the case of a payload and a normal structure. A
44
70
  # non-structure shape will not have members in the body. In the case
45
71
  # of a string or blob, the body contents would have been checked first
46
72
  # before this method is called in incomplete_xml_body?.
47
73
  def members_in_body?(output)
48
- shape =
49
- if output[:payload_member]
50
- output[:payload_member].shape
51
- else
52
- output.shape
53
- end
74
+ shape = resolve_shape(output)
54
75
 
55
76
  if structure_shape?(shape)
56
77
  shape.members.any? { |_, k| k.location.nil? }
@@ -59,30 +80,33 @@ module Aws
59
80
  end
60
81
  end
61
82
 
62
- def structure_shape?(shape)
63
- shape.is_a?(Seahorse::Model::Shapes::StructureShape)
83
+ # Fixes encoding issues when S3 returns UTF-8 content with missing charset in Content-Type header or omits
84
+ # Content-Type header entirely. Net::HTTP defaults to US-ASCII or ASCII-8BIT when charset is unspecified.
85
+ def normalize_encoding(xml)
86
+ return xml unless xml.is_a?(String) && ENCODINGS_TO_FIX.include?(xml.encoding)
87
+
88
+ xml.force_encoding('UTF-8')
64
89
  end
65
90
 
66
- # Must have a member in the body and have the start of an XML Tag.
67
- # Other incomplete xml bodies will result in an XML ParsingError.
68
- def incomplete_xml_body?(xml, output)
69
- members_in_body?(output) && !xml.match(/<\w/)
91
+ def resolve_shape(output)
92
+ return output.shape unless output[:payload_member]
93
+
94
+ output[:payload_member].shape
70
95
  end
71
96
 
72
- def check_for_error(context)
73
- xml = context.http_response.body_contents
74
- if xml.match(/<\?xml\s[^>]*\?>\s*<Error>/)
75
- error_code = xml.match(%r{<Code>(.+?)</Code>})[1]
76
- error_message = xml.match(%r{<Message>(.+?)</Message>})[1]
77
- S3::Errors.error_class(error_code).new(context, error_message)
78
- elsif incomplete_xml_body?(xml, context.operation.output)
79
- Seahorse::Client::NetworkingError.new(
80
- S3::Errors
81
- .error_class('InternalError')
82
- .new(context, 'Empty or incomplete response body')
83
- )
97
+ # Streaming outputs are not subject to 200 errors.
98
+ def streaming_output?(output)
99
+ if (payload = output[:payload_member])
100
+ # checking ref and shape
101
+ payload['streaming'] || payload.shape['streaming'] || payload.eventstream
102
+ else
103
+ false
84
104
  end
85
105
  end
106
+
107
+ def structure_shape?(shape)
108
+ shape.is_a?(Seahorse::Model::Shapes::StructureShape)
109
+ end
86
110
  end
87
111
 
88
112
  handler(Handler, step: :sign)