File: checksum_algorithm.rb

package info (click to toggle)
ruby-aws-sdk-core 3.168.1-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,924 kB
  • sloc: ruby: 15,292; makefile: 4
file content (340 lines) | stat: -rw-r--r-- 12,148 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
# frozen_string_literal: true

module Aws
  module Plugins
    # @api private
    class ChecksumAlgorithm < Seahorse::Client::Plugin
      CHUNK_SIZE = 1 * 1024 * 1024 # one MB

      # determine the set of supported client side checksum algorithms
      # CRC32c requires aws-crt (optional sdk dependency) for support
      CLIENT_ALGORITHMS = begin
        supported = %w[SHA256 SHA1 CRC32]
        begin
          require 'aws-crt'
          supported << 'CRC32C'
        rescue LoadError
        end
        supported
      end.freeze

      # priority order of checksum algorithms to validate responses against
      # Remove any algorithms not supported by client (ie, depending on CRT availability)
      CHECKSUM_ALGORITHM_PRIORITIES = %w[CRC32C SHA1 CRC32 SHA256] & CLIENT_ALGORITHMS

      # byte size of checksums, used in computing the trailer length
      CHECKSUM_SIZE = {
        'CRC32' => 16,
        'CRC32C' => 16,
        'SHA1' => 36,
        'SHA256' => 52
      }

      # Interface for computing digests on request/response bodies
      # which may be files, strings or IO like objects
      # Applies only to digest functions that produce 32 bit integer checksums
      # (eg CRC32)
      class Digest32

        attr_reader :value

        # @param [Object] digest_fn
        def initialize(digest_fn)
          @digest_fn = digest_fn
          @value = 0
        end

        def update(chunk)
          @value = @digest_fn.call(chunk, @value)
        end

        def base64digest
          Base64.encode64([@value].pack('N')).chomp
        end
      end

      def add_handlers(handlers, _config)
        handlers.add(OptionHandler, step: :initialize)
        # priority set low to ensure checksum is computed AFTER the request is
        # built but before it is signed
        handlers.add(ChecksumHandler, priority: 15, step: :build)
      end

      private

      def self.request_algorithm_selection(context)
        return unless context.operation.http_checksum

        input_member = context.operation.http_checksum['requestAlgorithmMember']
        context.params[input_member.to_sym]&.upcase if input_member
      end

      def self.request_validation_mode(context)
        return unless context.operation.http_checksum

        input_member = context.operation.http_checksum['requestValidationModeMember']
        context.params[input_member.to_sym] if input_member
      end

      def self.operation_response_algorithms(context)
        return unless context.operation.http_checksum

        context.operation.http_checksum['responseAlgorithms']
      end


      # @api private
      class OptionHandler < Seahorse::Client::Handler
        def call(context)
          context[:http_checksum] ||= {}

          # validate request configuration
          if (request_input = ChecksumAlgorithm.request_algorithm_selection(context))
            unless CLIENT_ALGORITHMS.include? request_input
              if (request_input == 'CRC32C')
                raise ArgumentError, "CRC32C requires crt support - install the aws-crt gem for support."
              else
                raise ArgumentError, "#{request_input} is not a supported checksum algorithm."
              end
            end
          end

        # validate response configuration
          if (ChecksumAlgorithm.request_validation_mode(context))
            # Compute an ordered list as the union between priority supported and the
            # operation's modeled response algorithms.
            validation_list = CHECKSUM_ALGORITHM_PRIORITIES &
              ChecksumAlgorithm.operation_response_algorithms(context)
            context[:http_checksum][:validation_list] = validation_list
          end

          @handler.call(context)
        end
      end

      # @api private
      class ChecksumHandler < Seahorse::Client::Handler

        def call(context)
          if should_calculate_request_checksum?(context)
            request_algorithm_input = ChecksumAlgorithm.request_algorithm_selection(context)
            context[:checksum_algorithms] = request_algorithm_input

            request_checksum_property = {
              'algorithm' => request_algorithm_input,
              'in' => checksum_request_in(context),
              'name' => "x-amz-checksum-#{request_algorithm_input.downcase}"
            }

            calculate_request_checksum(context, request_checksum_property)
          end

          if should_verify_response_checksum?(context)
            add_verify_response_checksum_handlers(context)
          end

          @handler.call(context)
        end

        private

        def should_calculate_request_checksum?(context)
          context.operation.http_checksum &&
            ChecksumAlgorithm.request_algorithm_selection(context)
        end

        def should_verify_response_checksum?(context)
          context[:http_checksum][:validation_list] && !context[:http_checksum][:validation_list].empty?
        end

        def calculate_request_checksum(context, checksum_properties)
          case checksum_properties['in']
          when 'header'
            header_name = checksum_properties['name']
            body = context.http_request.body_contents
            if body
              context.http_request.headers[header_name] ||=
                ChecksumAlgorithm.calculate_checksum(checksum_properties['algorithm'], body)
            end
          when 'trailer'
            apply_request_trailer_checksum(context, checksum_properties)
          end
        end

        def apply_request_trailer_checksum(context, checksum_properties)
          location_name = checksum_properties['name']

          # set required headers
          headers = context.http_request.headers
          headers['Content-Encoding'] = 'aws-chunked'
          headers['X-Amz-Content-Sha256'] = 'STREAMING-UNSIGNED-PAYLOAD-TRAILER'
          headers['X-Amz-Trailer'] = location_name

          # We currently always compute the size in the modified body wrapper - allowing us
          # to set the Content-Length header (set by content_length plugin).
          # This means we cannot use Transfer-Encoding=chunked

          if !context.http_request.body.respond_to?(:size)
            raise Aws::Errors::ChecksumError, 'Could not determine length of the body'
          end
          headers['X-Amz-Decoded-Content-Length'] = context.http_request.body.size

          context.http_request.body = AwsChunkedTrailerDigestIO.new(
            context.http_request.body,
            checksum_properties['algorithm'],
            location_name
          )
        end

        # Add events to the http_response to verify the checksum as its read
        # This prevents the body from being read multiple times
        # verification is done only once a successful response has completed
        def add_verify_response_checksum_handlers(context)
          http_response = context.http_response
          checksum_context = { }
          http_response.on_headers do |_status, headers|
            header_name, algorithm = response_header_to_verify(headers, context[:http_checksum][:validation_list])
            if header_name
              expected = headers[header_name]

              unless context[:http_checksum][:skip_on_suffix] && /-[\d]+$/.match(expected)
                checksum_context[:algorithm] = algorithm
                checksum_context[:header_name] = header_name
                checksum_context[:digest] = ChecksumAlgorithm.digest_for_algorithm(algorithm)
                checksum_context[:expected] = expected
              end
            end
          end

          http_response.on_data do |chunk|
            checksum_context[:digest].update(chunk) if checksum_context[:digest]
          end

          http_response.on_success do
            if checksum_context[:digest] &&
              (computed = checksum_context[:digest].base64digest)

              if computed != checksum_context[:expected]
                raise Aws::Errors::ChecksumError,
                      "Checksum validation failed on #{checksum_context[:header_name]} "\
                      "computed: #{computed}, expected: #{checksum_context[:expected]}"
              end

              context[:http_checksum][:validated] = checksum_context[:algorithm]
            end
          end
        end

        # returns nil if no headers to verify
        def response_header_to_verify(headers, validation_list)
          validation_list.each do |algorithm|
            header_name = "x-amz-checksum-#{algorithm}"
            return [header_name, algorithm] if headers[header_name]
          end
          nil
        end

        # determine where (header vs trailer) a request checksum should be added
        def checksum_request_in(context)
          if context.operation['authtype'].eql?('v4-unsigned-body')
            'trailer'
          else
            'header'
          end
        end

      end

      def self.calculate_checksum(algorithm, body)
        digest = ChecksumAlgorithm.digest_for_algorithm(algorithm)
        if body.respond_to?(:read)
          ChecksumAlgorithm.update_in_chunks(digest, body)
        else
          digest.update(body)
        end
        digest.base64digest
      end

      def self.digest_for_algorithm(algorithm)
        case algorithm
        when 'CRC32'
          Digest32.new(Zlib.method(:crc32))
        when 'CRC32C'
          # this will only be used if input algorithm is CRC32C AND client supports it (crt available)
          Digest32.new(Aws::Crt::Checksums.method(:crc32c))
        when 'SHA1'
          Digest::SHA1.new
        when 'SHA256'
          Digest::SHA256.new
        end
      end

      # The trailer size (in bytes) is the overhead + the trailer name +
      # the length of the base64 encoded checksum
      def self.trailer_length(algorithm, location_name)
        CHECKSUM_SIZE[algorithm] + location_name.size
      end

      def self.update_in_chunks(digest, io)
        loop do
          chunk = io.read(CHUNK_SIZE)
          break unless chunk
          digest.update(chunk)
        end
        io.rewind
      end

      # Wrapper for request body that implements application-layer
      # chunking with Digest computed on chunks + added as a trailer
      class AwsChunkedTrailerDigestIO
        CHUNK_SIZE = 16384

        def initialize(io, algorithm, location_name)
          @io = io
          @location_name = location_name
          @algorithm = algorithm
          @digest = ChecksumAlgorithm.digest_for_algorithm(algorithm)
          @trailer_io = nil
        end

        # the size of the application layer aws-chunked + trailer body
        def size
          # compute the number of chunks
          # a full chunk has 4 + 4 bytes overhead, a partial chunk is len.to_s(16).size + 4
          orig_body_size = @io.size
          n_full_chunks = orig_body_size / CHUNK_SIZE
          partial_bytes = orig_body_size % CHUNK_SIZE
          chunked_body_size = n_full_chunks * (CHUNK_SIZE + 8)
          chunked_body_size += partial_bytes.to_s(16).size + partial_bytes + 4 unless  partial_bytes.zero?
          trailer_size = ChecksumAlgorithm.trailer_length(@algorithm, @location_name)
          chunked_body_size + trailer_size
        end

        def rewind
          @io.rewind
        end

        def read(length, buf)
          # account for possible leftover bytes at the end, if we have trailer bytes, send them
          if @trailer_io
            return @trailer_io.read(length, buf)
          end

          chunk = @io.read(length)
          if chunk
            @digest.update(chunk)
            application_chunked = "#{chunk.bytesize.to_s(16)}\r\n#{chunk}\r\n"
            return StringIO.new(application_chunked).read(application_chunked.size, buf)
          else
            trailers = {}
            trailers[@location_name] = @digest.base64digest
            trailers = trailers.map { |k,v| "#{k}:#{v}"}.join("\r\n")
            @trailer_io = StringIO.new("0\r\n#{trailers}\r\n\r\n")
            chunk = @trailer_io.read(length, buf)
          end
          chunk
        end
      end
    end
  end
end