aws-sigv4 1.0.3 → 1.5.2

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
- SHA1:
3
- metadata.gz: 230c5aa7c49bded384ea0cc96ecbc3cdc6d3bec7
4
- data.tar.gz: b1b194fa0740e2588a94dd9a0c66f7c5f4198f70
2
+ SHA256:
3
+ metadata.gz: 33cb09610570a5aefa4e83ab34277756201d8f1e50197bfe343fc49cce668672
4
+ data.tar.gz: 4d070f7cf41c0a77b69e7ca6cc80c2fb7a8111eb3640819fb01ee6602027b5d9
5
5
  SHA512:
6
- metadata.gz: 53016c5f240e3154815b4f172158a5a29c84ef7e912e756f8f5b53e619854bbc30a041358b5be4a8fc82708cbbb12c549f31c843421cbf5a0e6c3f2e0537ab23
7
- data.tar.gz: 4ff775b31b1603a3eaf5206cb0c59bdac3599a95973626d746d81ec21b8e51db46cdc9fd8cb6a7008afaeaec5bb6ac6af6a12b5317ba60e2c64303424235a63d
6
+ metadata.gz: ddb8c5fc04288a396501afb0cd74907232ac78a2ca5e3bbb4c0879c27c15d72c19e30b9ddcaf5b8fe536e8b04d4ccc3c98eee74f27f92b594058a54b29edf704
7
+ data.tar.gz: 283afcb61ae4b06a68b5a644a529b560864b82f0e69c107a8c059c04b9b6448421ac93015c483aae1bdf77bed41cb3088942c1e18dc26fc4b569aa7fde65f563
data/CHANGELOG.md ADDED
@@ -0,0 +1,103 @@
1
+ Unreleased Changes
2
+ ------------------
3
+
4
+ 1.5.2 (2022-09-30)
5
+ ------------------
6
+
7
+ * Issue - Fix an issue where quoted strings with multiple spaces are not trimmed. (#2758)
8
+
9
+ 1.5.1 (2022-07-19)
10
+ ------------------
11
+
12
+ * Issue - Fix performance regression when checking if `aws-crt` is available. (#2729)
13
+
14
+ 1.5.0 (2022-04-20)
15
+ ------------------
16
+
17
+ * Feature - Use CRT based signers if `aws-crt` is available - provides support for `sigv4a`.
18
+
19
+ 1.4.0 (2021-09-02)
20
+ ------------------
21
+
22
+ * Feature - add `signing_algorithm` option with `sigv4` default.
23
+
24
+ 1.3.0 (2021-09-01)
25
+ ------------------
26
+
27
+ * Feature - AWS SDK for Ruby no longer supports Ruby runtime versions 1.9, 2.0, 2.1, and 2.2.
28
+
29
+ 1.2.4 (2021-07-08)
30
+ ------------------
31
+
32
+ * Issue - Fix usage of `:uri_escape_path` and `:apply_checksum_header` in `Signer`.
33
+
34
+ 1.2.3 (2021-03-04)
35
+ ------------------
36
+
37
+ * Issue - Include LICENSE, CHANGELOG, and VERSION files with this gem.
38
+
39
+ 1.2.2 (2020-08-13)
40
+ ------------------
41
+
42
+ * Issue - Sort query params with same names by value when signing. (#2376)
43
+
44
+ 1.2.1 (2020-06-24)
45
+ ------------------
46
+
47
+ * Issue - Don't overwrite `host` header in sigv4 signer if given.
48
+
49
+ 1.2.0 (2020-06-17)
50
+ ------------------
51
+
52
+ * Feature - Bump `aws-eventstream` dependency to `~> 1`.
53
+
54
+ 1.1.4 (2020-05-28)
55
+ ------------------
56
+
57
+ * Issue - Don't use `expect` header to compute Signature.
58
+
59
+ 1.1.3 (2020-04-27)
60
+ ------------------
61
+
62
+ * Issue - Don't rely on the set? method of credentials.
63
+
64
+ 1.1.2 (2020-04-17)
65
+ ------------------
66
+
67
+ * Issue - Raise errors when credentials are not set (nil or empty)
68
+
69
+ 1.1.1 (2020-02-26)
70
+ ------------------
71
+
72
+ * Issue - Handle signing for unknown protocols and default ports.
73
+
74
+ 1.1.0 (2019-03-13)
75
+ ------------------
76
+
77
+ * Feature - Support signature V4 signing per event.
78
+
79
+ 1.0.3 (2018-06-28)
80
+ ------------------
81
+
82
+ * Issue - Reduce memory allocation when generating signatures.
83
+
84
+ 1.0.2 (2018-02-21)
85
+ ------------------
86
+
87
+ * Issue - Fix Ruby warning: shadowed local variable "headers".
88
+
89
+ 1.0.2 (2017-08-31)
90
+ ------------------
91
+
92
+ * Issue - Update `aws-sigv4` gemspec metadata.
93
+
94
+ 1.0.1 (2017-07-12)
95
+ ------------------
96
+
97
+ * Issue - Make UTF-8 encoding explicit in spec test.
98
+
99
+
100
+ 1.0.0 (2016-11-08)
101
+ ------------------
102
+
103
+ * Feature - Initial release of the `aws-sigv4` gem.
data/LICENSE.txt ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
data/VERSION ADDED
@@ -0,0 +1 @@
1
+ 1.5.2
@@ -1,3 +1,5 @@
1
+ # frozen_string_literal: true
2
+
1
3
  module Aws
2
4
  module Sigv4
3
5
  # Users that wish to configure static credentials can use the
@@ -28,11 +30,14 @@ module Aws
28
30
  # @return [String, nil]
29
31
  attr_reader :session_token
30
32
 
31
- # @return [Boolean]
33
+ # @return [Boolean] Returns `true` if the access key id and secret
34
+ # access key are both set.
32
35
  def set?
33
- !!(access_key_id && secret_access_key)
36
+ !access_key_id.nil? &&
37
+ !access_key_id.empty? &&
38
+ !secret_access_key.nil? &&
39
+ !secret_access_key.empty?
34
40
  end
35
-
36
41
  end
37
42
 
38
43
  # Users that wish to configure static credentials can use the
@@ -53,6 +58,10 @@ module Aws
53
58
  # @return [Credentials]
54
59
  attr_reader :credentials
55
60
 
61
+ # @return [Boolean]
62
+ def set?
63
+ !!credentials && credentials.set?
64
+ end
56
65
  end
57
66
 
58
67
  end
@@ -1,3 +1,5 @@
1
+ # frozen_string_literal: true
2
+
1
3
  module Aws
2
4
  module Sigv4
3
5
  module Errors
@@ -1,3 +1,5 @@
1
+ # frozen_string_literal: true
2
+
1
3
  require 'uri'
2
4
 
3
5
  module Aws
@@ -1,3 +1,5 @@
1
+ # frozen_string_literal: true
2
+
1
3
  module Aws
2
4
  module Sigv4
3
5
  class Signature
@@ -30,6 +32,8 @@ module Aws
30
32
  # @return [String] For debugging purposes.
31
33
  attr_accessor :content_sha256
32
34
 
35
+ # @return [Hash] Internal data for debugging purposes.
36
+ attr_accessor :extra
33
37
  end
34
38
  end
35
39
  end
@@ -1,9 +1,12 @@
1
+ # frozen_string_literal: true
2
+
1
3
  require 'openssl'
2
4
  require 'tempfile'
3
5
  require 'time'
4
6
  require 'uri'
5
7
  require 'set'
6
8
  require 'cgi'
9
+ require 'aws-eventstream'
7
10
 
8
11
  module Aws
9
12
  module Sigv4
@@ -71,6 +74,14 @@ module Aws
71
74
  #
72
75
  class Signer
73
76
 
77
+ @@use_crt =
78
+ begin
79
+ require 'aws-crt'
80
+ true
81
+ rescue LoadError
82
+ false
83
+ end
84
+
74
85
  # @overload initialize(service:, region:, access_key_id:, secret_access_key:, session_token:nil, **options)
75
86
  # @param [String] :service The service signing name, e.g. 's3'.
76
87
  # @param [String] :region The region name, e.g. 'us-east-1'.
@@ -115,6 +126,18 @@ module Aws
115
126
  # headers. This is required for AWS Glacier, and optional for
116
127
  # every other AWS service as of late 2016.
117
128
  #
129
+ # @option options [Symbol] :signing_algorithm (:sigv4) The
130
+ # algorithm to use for signing. :sigv4a is only supported when
131
+ # `aws-crt` is available.
132
+ #
133
+ # @option options [Boolean] :omit_session_token (false)
134
+ # (Supported only when `aws-crt` is available) If `true`,
135
+ # then security token is added to the final signing result,
136
+ # but is treated as "unsigned" and does not contribute
137
+ # to the authorization signature.
138
+ #
139
+ # @option options [Boolean] :normalize_path (true) (Supported only when `aws-crt` is available)
140
+ # When `true`, the uri paths will be normalized when building the canonical request
118
141
  def initialize(options = {})
119
142
  @service = extract_service(options)
120
143
  @region = extract_region(options)
@@ -122,8 +145,17 @@ module Aws
122
145
  @unsigned_headers = Set.new((options.fetch(:unsigned_headers, [])).map(&:downcase))
123
146
  @unsigned_headers << 'authorization'
124
147
  @unsigned_headers << 'x-amzn-trace-id'
125
- [:uri_escape_path, :apply_checksum_header].each do |opt|
126
- instance_variable_set("@#{opt}", options.key?(opt) ? !!options[:opt] : true)
148
+ @unsigned_headers << 'expect'
149
+ @uri_escape_path = options.fetch(:uri_escape_path, true)
150
+ @apply_checksum_header = options.fetch(:apply_checksum_header, true)
151
+ @signing_algorithm = options.fetch(:signing_algorithm, :sigv4)
152
+ @normalize_path = options.fetch(:normalize_path, true)
153
+ @omit_session_token = options.fetch(:omit_session_token, false)
154
+
155
+ if @signing_algorithm == :sigv4a && !Signer.use_crt?
156
+ raise ArgumentError, 'You are attempting to sign a' \
157
+ ' request with sigv4a which requires the `aws-crt` gem.'\
158
+ ' Please install the gem or add it to your gemfile.'
127
159
  end
128
160
  end
129
161
 
@@ -201,7 +233,9 @@ module Aws
201
233
  #
202
234
  def sign_request(request)
203
235
 
204
- creds = get_credentials
236
+ return crt_sign_request(request) if Signer.use_crt?
237
+
238
+ creds = fetch_credentials
205
239
 
206
240
  http_method = extract_http_method(request)
207
241
  url = extract_url(request)
@@ -215,7 +249,7 @@ module Aws
215
249
  content_sha256 ||= sha256_hexdigest(request[:body] || '')
216
250
 
217
251
  sigv4_headers = {}
218
- sigv4_headers['host'] = host(url)
252
+ sigv4_headers['host'] = headers['host'] || host(url)
219
253
  sigv4_headers['x-amz-date'] = datetime
220
254
  sigv4_headers['x-amz-security-token'] = creds.session_token if creds.session_token
221
255
  sigv4_headers['x-amz-content-sha256'] ||= content_sha256 if @apply_checksum_header
@@ -243,6 +277,60 @@ module Aws
243
277
  )
244
278
  end
245
279
 
280
+ # Signs a event and returns signature headers and prior signature
281
+ # used for next event signing.
282
+ #
283
+ # Headers of a sigv4 signed event message only contains 2 headers
284
+ # * ':chunk-signature'
285
+ # * computed signature of the event, binary string, 'bytes' type
286
+ # * ':date'
287
+ # * millisecond since epoch, 'timestamp' type
288
+ #
289
+ # Payload of the sigv4 signed event message contains eventstream encoded message
290
+ # which is serialized based on input and protocol
291
+ #
292
+ # To sign events
293
+ #
294
+ # headers_0, signature_0 = signer.sign_event(
295
+ # prior_signature, # hex-encoded string
296
+ # payload_0, # binary string (eventstream encoded event 0)
297
+ # encoder, # Aws::EventStreamEncoder
298
+ # )
299
+ #
300
+ # headers_1, signature_1 = signer.sign_event(
301
+ # signature_0,
302
+ # payload_1, # binary string (eventstream encoded event 1)
303
+ # encoder
304
+ # )
305
+ #
306
+ # The initial prior_signature should be using the signature computed at initial request
307
+ #
308
+ # Note:
309
+ #
310
+ # Since ':chunk-signature' header value has bytes type, the signature value provided
311
+ # needs to be a binary string instead of a hex-encoded string (like original signature
312
+ # V4 algorithm). Thus, when returning signature value used for next event siging, the
313
+ # signature value (a binary string) used at ':chunk-signature' needs to converted to
314
+ # hex-encoded string using #unpack
315
+ def sign_event(prior_signature, payload, encoder)
316
+ # Note: CRT does not currently provide event stream signing, so we always use the ruby implementation.
317
+ creds = fetch_credentials
318
+ time = Time.now
319
+ headers = {}
320
+
321
+ datetime = time.utc.strftime("%Y%m%dT%H%M%SZ")
322
+ date = datetime[0,8]
323
+ headers[':date'] = Aws::EventStream::HeaderValue.new(value: time.to_i * 1000, type: 'timestamp')
324
+
325
+ sts = event_string_to_sign(datetime, headers, payload, prior_signature, encoder)
326
+ sig = event_signature(creds.secret_access_key, date, sts)
327
+
328
+ headers[':chunk-signature'] = Aws::EventStream::HeaderValue.new(value: sig, type: 'bytes')
329
+
330
+ # Returning signed headers and signature value in hex-encoded string
331
+ [headers, sig.unpack('H*').first]
332
+ end
333
+
246
334
  # Signs a URL with query authentication. Using query parameters
247
335
  # to authenticate requests is useful when you want to express a
248
336
  # request entirely in a URL. This method is also referred as
@@ -313,13 +401,15 @@ module Aws
313
401
  #
314
402
  def presign_url(options)
315
403
 
316
- creds = get_credentials
404
+ return crt_presign_url(options) if Signer.use_crt?
405
+
406
+ creds = fetch_credentials
317
407
 
318
408
  http_method = extract_http_method(options)
319
409
  url = extract_url(options)
320
410
 
321
411
  headers = downcase_headers(options[:headers])
322
- headers['host'] = host(url)
412
+ headers['host'] ||= host(url)
323
413
 
324
414
  datetime = headers['x-amz-date']
325
415
  datetime ||= (options[:time] || Time.now).utc.strftime("%Y%m%dT%H%M%SZ")
@@ -334,8 +424,8 @@ module Aws
334
424
  params['X-Amz-Credential'] = credential(creds, date)
335
425
  params['X-Amz-Date'] = datetime
336
426
  params['X-Amz-Expires'] = extract_expires_in(options)
337
- params['X-Amz-SignedHeaders'] = signed_headers(headers)
338
427
  params['X-Amz-Security-Token'] = creds.session_token if creds.session_token
428
+ params['X-Amz-SignedHeaders'] = signed_headers(headers)
339
429
 
340
430
  params = params.map do |key, value|
341
431
  "#{uri_escape(key)}=#{uri_escape(value)}"
@@ -375,6 +465,29 @@ module Aws
375
465
  ].join("\n")
376
466
  end
377
467
 
468
+ # Compared to original #string_to_sign at signature v4 algorithm
469
+ # there is no canonical_request concept for an eventstream event,
470
+ # instead, an event contains headers and payload two parts, and
471
+ # they will be used for computing digest in #event_string_to_sign
472
+ #
473
+ # Note:
474
+ # While headers need to be encoded under eventstream format,
475
+ # payload used is already eventstream encoded (event without signature),
476
+ # thus no extra encoding is needed.
477
+ def event_string_to_sign(datetime, headers, payload, prior_signature, encoder)
478
+ encoded_headers = encoder.encode_headers(
479
+ Aws::EventStream::Message.new(headers: headers, payload: payload)
480
+ )
481
+ [
482
+ "AWS4-HMAC-SHA256-PAYLOAD",
483
+ datetime,
484
+ credential_scope(datetime[0,8]),
485
+ prior_signature,
486
+ sha256_hexdigest(encoded_headers),
487
+ sha256_hexdigest(payload)
488
+ ].join("\n")
489
+ end
490
+
378
491
  def credential_scope(date)
379
492
  [
380
493
  date,
@@ -396,6 +509,24 @@ module Aws
396
509
  hexhmac(k_credentials, string_to_sign)
397
510
  end
398
511
 
512
+ # Comparing to original signature v4 algorithm,
513
+ # returned signature is a binary string instread of
514
+ # hex-encoded string. (Since ':chunk-signature' requires
515
+ # 'bytes' type)
516
+ #
517
+ # Note:
518
+ # converting signature from binary string to hex-encoded
519
+ # string is handled at #sign_event instead. (Will be used
520
+ # as next prior signature for event signing)
521
+ def event_signature(secret_access_key, date, string_to_sign)
522
+ k_date = hmac("AWS4" + secret_access_key, date)
523
+ k_region = hmac(k_date, @region)
524
+ k_service = hmac(k_region, @service)
525
+ k_credentials = hmac(k_service, 'aws4_request')
526
+ hmac(k_credentials, string_to_sign)
527
+ end
528
+
529
+
399
530
  def path(url)
400
531
  path = url.path
401
532
  path = '/' if path == ''
@@ -409,18 +540,26 @@ module Aws
409
540
  def normalized_querystring(querystring)
410
541
  params = querystring.split('&')
411
542
  params = params.map { |p| p.match(/=/) ? p : p + '=' }
412
- # We have to sort by param name and preserve order of params that
413
- # have the same name. Default sort <=> in JRuby will swap members
543
+ # From: https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html
544
+ # Sort the parameter names by character code point in ascending order.
545
+ # Parameters with duplicate names should be sorted by value.
546
+ #
547
+ # Default sort <=> in JRuby will swap members
414
548
  # occasionally when <=> is 0 (considered still sorted), but this
415
549
  # causes our normalized query string to not match the sent querystring.
416
- # When names match, we then sort by their original order
417
- params = params.each.with_index.sort do |a, b|
550
+ # When names match, we then sort by their values. When values also
551
+ # match then we sort by their original order
552
+ params.each.with_index.sort do |a, b|
418
553
  a, a_offset = a
419
- a_name = a.split('=')[0]
420
554
  b, b_offset = b
421
- b_name = b.split('=')[0]
555
+ a_name, a_value = a.split('=')
556
+ b_name, b_value = b.split('=')
422
557
  if a_name == b_name
423
- a_offset <=> b_offset
558
+ if a_value == b_value
559
+ a_offset <=> b_offset
560
+ else
561
+ a_value <=> b_value
562
+ end
424
563
  else
425
564
  a_name <=> b_name
426
565
  end
@@ -450,22 +589,18 @@ module Aws
450
589
  end
451
590
 
452
591
  def canonical_header_value(value)
453
- value.match(/^".*"$/) ? value : value.gsub(/\s+/, ' ').strip
592
+ value.gsub(/\s+/, ' ').strip
454
593
  end
455
594
 
456
595
  def host(uri)
457
- if standard_port?(uri)
596
+ # Handles known and unknown URI schemes; default_port nil when unknown.
597
+ if uri.default_port == uri.port
458
598
  uri.host
459
599
  else
460
600
  "#{uri.host}:#{uri.port}"
461
601
  end
462
602
  end
463
603
 
464
- def standard_port?(uri)
465
- (uri.scheme == 'http' && uri.port == 80) ||
466
- (uri.scheme == 'https' && uri.port == 443)
467
- end
468
-
469
604
  # @param [File, Tempfile, IO#read, String] value
470
605
  # @return [String<SHA256 Hexdigest>]
471
606
  def sha256_hexdigest(value)
@@ -473,7 +608,9 @@ module Aws
473
608
  OpenSSL::Digest::SHA256.file(value).hexdigest
474
609
  elsif value.respond_to?(:read)
475
610
  sha256 = OpenSSL::Digest::SHA256.new
476
- while chunk = value.read(1024 * 1024, buffer ||= "") # 1MB
611
+ loop do
612
+ chunk = value.read(1024 * 1024) # 1MB
613
+ break unless chunk
477
614
  sha256.update(chunk)
478
615
  end
479
616
  value.rewind
@@ -561,22 +698,152 @@ module Aws
561
698
  self.class.uri_escape_path(string)
562
699
  end
563
700
 
564
- def get_credentials
701
+
702
+ def fetch_credentials
565
703
  credentials = @credentials_provider.credentials
566
704
  if credentials_set?(credentials)
567
705
  credentials
568
706
  else
569
- msg = 'unable to sign request without credentials set'
570
- raise Errors::MissingCredentialsError.new(msg)
707
+ raise Errors::MissingCredentialsError,
708
+ 'unable to sign request without credentials set'
571
709
  end
572
710
  end
573
711
 
712
+ # Returns true if credentials are set (not nil or empty)
713
+ # Credentials may not implement the Credentials interface
714
+ # and may just be credential like Client response objects
715
+ # (eg those returned by sts#assume_role)
574
716
  def credentials_set?(credentials)
575
- credentials.access_key_id && credentials.secret_access_key
717
+ !credentials.access_key_id.nil? &&
718
+ !credentials.access_key_id.empty? &&
719
+ !credentials.secret_access_key.nil? &&
720
+ !credentials.secret_access_key.empty?
721
+ end
722
+
723
+ ### CRT Code
724
+
725
+ # the credentials used by CRT must be a
726
+ # CRT StaticCredentialsProvider object
727
+ def crt_fetch_credentials
728
+ creds = fetch_credentials
729
+ Aws::Crt::Auth::StaticCredentialsProvider.new(
730
+ creds.access_key_id,
731
+ creds.secret_access_key,
732
+ creds.session_token
733
+ )
734
+ end
735
+
736
+ def crt_sign_request(request)
737
+ creds = crt_fetch_credentials
738
+ http_method = extract_http_method(request)
739
+ url = extract_url(request)
740
+ headers = downcase_headers(request[:headers])
741
+
742
+ datetime =
743
+ if headers.include? 'x-amz-date'
744
+ Time.parse(headers.delete('x-amz-date'))
745
+ end
746
+
747
+ content_sha256 = headers.delete('x-amz-content-sha256')
748
+ content_sha256 ||= sha256_hexdigest(request[:body] || '')
749
+
750
+ sigv4_headers = {}
751
+ sigv4_headers['host'] = headers['host'] || host(url)
752
+
753
+ # Modify the user-agent to add usage of crt-signer
754
+ # This should be temporary during developer preview only
755
+ if headers.include? 'user-agent'
756
+ headers['user-agent'] = "#{headers['user-agent']} crt-signer/#{@signing_algorithm}/#{Aws::Sigv4::VERSION}"
757
+ sigv4_headers['user-agent'] = headers['user-agent']
758
+ end
759
+
760
+ headers = headers.merge(sigv4_headers) # merge so we do not modify given headers hash
761
+
762
+ config = Aws::Crt::Auth::SigningConfig.new(
763
+ algorithm: @signing_algorithm,
764
+ signature_type: :http_request_headers,
765
+ region: @region,
766
+ service: @service,
767
+ date: datetime,
768
+ signed_body_value: content_sha256,
769
+ signed_body_header_type: @apply_checksum_header ?
770
+ :sbht_content_sha256 : :sbht_none,
771
+ credentials: creds,
772
+ unsigned_headers: @unsigned_headers,
773
+ use_double_uri_encode: @uri_escape_path,
774
+ should_normalize_uri_path: @normalize_path,
775
+ omit_session_token: @omit_session_token
776
+ )
777
+ http_request = Aws::Crt::Http::Message.new(
778
+ http_method, url.to_s, headers
779
+ )
780
+ signable = Aws::Crt::Auth::Signable.new(http_request)
781
+
782
+ signing_result = Aws::Crt::Auth::Signer.sign_request(config, signable)
783
+
784
+ Signature.new(
785
+ headers: sigv4_headers.merge(
786
+ downcase_headers(signing_result[:headers])
787
+ ),
788
+ string_to_sign: 'CRT_INTERNAL',
789
+ canonical_request: 'CRT_INTERNAL',
790
+ content_sha256: content_sha256,
791
+ extra: {config: config, signable: signable}
792
+ )
793
+ end
794
+
795
+ def crt_presign_url(options)
796
+ creds = crt_fetch_credentials
797
+
798
+ http_method = extract_http_method(options)
799
+ url = extract_url(options)
800
+ headers = downcase_headers(options[:headers])
801
+ headers['host'] ||= host(url)
802
+
803
+ datetime = headers.delete('x-amz-date')
804
+ datetime ||= (options[:time] || Time.now)
805
+
806
+ content_sha256 = headers.delete('x-amz-content-sha256')
807
+ content_sha256 ||= options[:body_digest]
808
+ content_sha256 ||= sha256_hexdigest(options[:body] || '')
809
+
810
+ config = Aws::Crt::Auth::SigningConfig.new(
811
+ algorithm: @signing_algorithm,
812
+ signature_type: :http_request_query_params,
813
+ region: @region,
814
+ service: @service,
815
+ date: datetime,
816
+ signed_body_value: content_sha256,
817
+ signed_body_header_type: @apply_checksum_header ?
818
+ :sbht_content_sha256 : :sbht_none,
819
+ credentials: creds,
820
+ unsigned_headers: @unsigned_headers,
821
+ use_double_uri_encode: @uri_escape_path,
822
+ should_normalize_uri_path: @normalize_path,
823
+ omit_session_token: @omit_session_token,
824
+ expiration_in_seconds: options.fetch(:expires_in, 900)
825
+ )
826
+ http_request = Aws::Crt::Http::Message.new(
827
+ http_method, url.to_s, headers
828
+ )
829
+ signable = Aws::Crt::Auth::Signable.new(http_request)
830
+
831
+ signing_result = Aws::Crt::Auth::Signer.sign_request(config, signable, http_method, url.to_s)
832
+ url = URI.parse(signing_result[:path])
833
+
834
+ if options[:extra] && options[:extra].is_a?(Hash)
835
+ options[:extra][:config] = config
836
+ options[:extra][:signable] = signable
837
+ end
838
+ url
576
839
  end
577
840
 
578
841
  class << self
579
842
 
843
+ def use_crt?
844
+ @@use_crt
845
+ end
846
+
580
847
  # @api private
581
848
  def uri_escape_path(path)
582
849
  path.gsub(/[^\/]+/) { |part| uri_escape(part) }
data/lib/aws-sigv4.rb CHANGED
@@ -1,4 +1,12 @@
1
+ # frozen_string_literal: true
2
+
1
3
  require_relative 'aws-sigv4/credentials'
2
4
  require_relative 'aws-sigv4/errors'
3
5
  require_relative 'aws-sigv4/signature'
4
6
  require_relative 'aws-sigv4/signer'
7
+
8
+ module Aws
9
+ module Sigv4
10
+ VERSION = File.read(File.expand_path('../VERSION', __dir__)).strip
11
+ end
12
+ end
metadata CHANGED
@@ -1,34 +1,57 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: aws-sigv4
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.0.3
4
+ version: 1.5.2
5
5
  platform: ruby
6
6
  authors:
7
7
  - Amazon Web Services
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2018-06-28 00:00:00.000000000 Z
12
- dependencies: []
13
- description: Amazon Web Services Signature Version 4 signing ligrary. Generates sigv4
11
+ date: 2022-09-30 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: aws-eventstream
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1'
20
+ - - ">="
21
+ - !ruby/object:Gem::Version
22
+ version: 1.0.2
23
+ type: :runtime
24
+ prerelease: false
25
+ version_requirements: !ruby/object:Gem::Requirement
26
+ requirements:
27
+ - - "~>"
28
+ - !ruby/object:Gem::Version
29
+ version: '1'
30
+ - - ">="
31
+ - !ruby/object:Gem::Version
32
+ version: 1.0.2
33
+ description: Amazon Web Services Signature Version 4 signing library. Generates sigv4
14
34
  signature for HTTP requests.
15
35
  email:
16
36
  executables: []
17
37
  extensions: []
18
38
  extra_rdoc_files: []
19
39
  files:
40
+ - CHANGELOG.md
41
+ - LICENSE.txt
42
+ - VERSION
20
43
  - lib/aws-sigv4.rb
21
44
  - lib/aws-sigv4/credentials.rb
22
45
  - lib/aws-sigv4/errors.rb
23
46
  - lib/aws-sigv4/request.rb
24
47
  - lib/aws-sigv4/signature.rb
25
48
  - lib/aws-sigv4/signer.rb
26
- homepage: http://github.com/aws/aws-sdk-ruby
49
+ homepage: https://github.com/aws/aws-sdk-ruby
27
50
  licenses:
28
51
  - Apache-2.0
29
52
  metadata:
30
- source_code_uri: https://github.com/aws/aws-sdk-ruby/tree/master/gems/aws-sigv4
31
- changelog_uri: https://github.com/aws/aws-sdk-ruby/tree/master/gems/aws-sigv4/CHANGELOG.md
53
+ source_code_uri: https://github.com/aws/aws-sdk-ruby/tree/version-3/gems/aws-sigv4
54
+ changelog_uri: https://github.com/aws/aws-sdk-ruby/tree/version-3/gems/aws-sigv4/CHANGELOG.md
32
55
  post_install_message:
33
56
  rdoc_options: []
34
57
  require_paths:
@@ -37,15 +60,14 @@ required_ruby_version: !ruby/object:Gem::Requirement
37
60
  requirements:
38
61
  - - ">="
39
62
  - !ruby/object:Gem::Version
40
- version: '0'
63
+ version: '2.3'
41
64
  required_rubygems_version: !ruby/object:Gem::Requirement
42
65
  requirements:
43
66
  - - ">="
44
67
  - !ruby/object:Gem::Version
45
68
  version: '0'
46
69
  requirements: []
47
- rubyforge_project:
48
- rubygems_version: 2.5.2.3
70
+ rubygems_version: 3.1.6
49
71
  signing_key:
50
72
  specification_version: 4
51
73
  summary: AWS Signature Version 4 library.