Module: Datadog::AppSec::Utils::HTTP::BodyReader

Defined in:
lib/datadog/appsec/utils/http/body_reader.rb

Class Method Summary collapse

Class Method Details

.read(body, limit:, rewind_before_read: false) ⇒ Object



10
11
12
13
14
15
16
# File 'lib/datadog/appsec/utils/http/body_reader.rb', line 10

def read(body, limit:, rewind_before_read: false)
  return body.byteslice(0, limit + 1) if body.is_a?(String)
  return if body.nil? || !body.respond_to?(:read)
  return if rewind_before_read && !body.respond_to?(:rewind)

  read_stream(body, limit: limit, rewind_before_read: rewind_before_read)
end

.read_stream(body, limit:, rewind_before_read: false) ⇒ Object



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
# File 'lib/datadog/appsec/utils/http/body_reader.rb', line 18

def read_stream(body, limit:, rewind_before_read: false)
  # @type var rewound: bool
  rewound = false

  if rewind_before_read
    return unless rewind(body)

    rewound = true
  end

  buffer = +"".b
  max = limit + 1

  while buffer.bytesize <= limit
    chunk = body.read(max - buffer.bytesize)
    break if chunk.nil? || chunk.empty?

    buffer << chunk
  end

  buffer
rescue => e
  Datadog.logger.debug { "AppSec: Failed to read body: #{e.class}: #{e.message}" }

  raise
ensure
  rewind(body) if rewound
end