Module: Datadog::AppSec::Contrib::Rack::ResponseBody

Defined in:
lib/datadog/appsec/contrib/rack/response_body.rb

Class Method Summary collapse

Class Method Details

.content_length(body) ⇒ Object

NOTE: We compute content length only for fixed-size response bodies,

ignoring streaming bodies to avoid buffering.

On Rack 3.x, `body.to_ary` on a BodyProxy triggers `close` on all
nested BodyProxy layers. This is safe because web servers, like Puma
handles already-closed bodies (its own `to_ary` becomes a no-op).


17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/datadog/appsec/contrib/rack/response_body.rb', line 17

def self.content_length(body)
  return unless body.respond_to?(:to_ary)

  # NOTE: When `to_ary` exists but returns `nil`, the body will be
  #       transferred in chunks and we can't compute content length
  #       without buffering it.
  body_ary = body.to_ary
  return unless body_ary.is_a?(Array)

  body_ary.sum { |part| part.is_a?(String) ? part.bytesize : 0 }
rescue => e
  AppSec.telemetry.report(e, description: 'AppSec: Failed to compute body content length')

  nil
end