Class: Datadog::AppSec::Contrib::Rack::RequestMiddleware

Inherits:
Object
  • Object
show all
Defined in:
lib/datadog/appsec/contrib/rack/request_middleware.rb

Overview

Topmost Rack middleware for AppSec This should be inserted just below Datadog::Tracing::Contrib::Rack::TraceMiddleware

Instance Method Summary collapse

Constructor Details

#initialize(app, opt = {}) ⇒ RequestMiddleware

Returns a new instance of RequestMiddleware.



20
21
22
23
24
# File 'lib/datadog/appsec/contrib/rack/request_middleware.rb', line 20

def initialize(app, opt = {})
  @app = app

  @oneshot_tags_sent = false
end

Instance Method Details

#call(env) ⇒ Object

rubocop:disable Metrics/AbcSize,Metrics/PerceivedComplexity,Metrics/CyclomaticComplexity,Metrics/MethodLength



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
# File 'lib/datadog/appsec/contrib/rack/request_middleware.rb', line 27

def call(env)
  return @app.call(env) unless Datadog::AppSec.enabled?

  Datadog::Core::Remote.active_remote.barrier(:once) unless Datadog::Core::Remote.active_remote.nil?
  processor = Datadog::AppSec.processor

  processor = nil
  ready = false
  context = nil

  Datadog::AppSec.reconfigure_lock do
    processor = Datadog::AppSec.processor

    if !processor.nil? && processor.ready?
      context = processor.activate_context
      env['datadog.waf.context'] = context
      ready = true
    end
  end

  # TODO: handle exceptions, except for @app.call

  return @app.call(env) unless ready

  gateway_request = Gateway::Request.new(env)

  add_appsec_tags(processor, active_trace, active_span, env)

  request_return, request_response = catch(::Datadog::AppSec::Ext::INTERRUPT) do
    Instrumentation.gateway.push('rack.request', gateway_request) do
      @app.call(env)
    end
  end

  if request_response && request_response.any? { |action, _event| action == :block }
    request_return = AppSec::Response.negotiate(env).to_rack
  end

  gateway_response = Gateway::Response.new(
    request_return[2],
    request_return[0],
    request_return[1],
    active_context: context
  )

  _response_return, response_response = Instrumentation.gateway.push('rack.response', gateway_response)

  context.events.each do |e|
    e[:response] ||= gateway_response
    e[:request]  ||= gateway_request
  end

  AppSec::Event.record(*context.events)

  if response_response && response_response.any? { |action, _event| action == :block }
    request_return = AppSec::Response.negotiate(env).to_rack
  end

  request_return
ensure
  if context
    add_waf_runtime_tags(active_trace, context)
    processor.deactivate_context
  end
end