Module: Datadog::AppSec::Contrib::Rails::Gateway::Watcher

Defined in:
lib/datadog/appsec/contrib/rails/gateway/watcher.rb

Overview

Watcher for Rails gateway events

Class Method Summary collapse

Class Method Details

.watchObject



16
17
18
19
20
21
# File 'lib/datadog/appsec/contrib/rails/gateway/watcher.rb', line 16

def watch
  gateway = Instrumentation.gateway

  watch_request_action(gateway)
  watch_response_body_json(gateway)
end

.watch_request_action(gateway = Instrumentation.gateway) ⇒ Object



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
# File 'lib/datadog/appsec/contrib/rails/gateway/watcher.rb', line 23

def watch_request_action(gateway = Instrumentation.gateway)
  gateway.watch("rails.request.action") do |stack, gateway_request|
    context = gateway_request.env[AppSec::Ext::CONTEXT_KEY]
    limit = Datadog.configuration.appsec.body_parsing_size_limit

    persistent_data = {
      "server.request.path_params" => gateway_request.route_params,
    }

    unless limit.zero?
      byte_length = gateway_request.body_bytesize(limit)

      if byte_length
        # NOTE: Params may be parsed before this hook, leaving the
        #       body stream at EOF. Keep byte_length unset for that
        #       case, but still inspect cached params
        persistent_data["server.request.body.byte_length"] = byte_length if byte_length.positive?

        if byte_length <= limit
          body = gateway_request.parsed_body
          persistent_data["server.request.body"] = body unless body.nil? || body.empty?
        end
      end
    end

    result = context.run_waf(persistent_data, {}, Datadog.configuration.appsec.waf_timeout)

    if result.match?
      context.events.push(
        AppSec::SecurityEvent.new(result, trace: context.trace, span: context.span)
      )

      AppSec::Event.tag(context, result)
      TraceKeeper.keep!(context.trace) if result.keep?

      AppSec::ActionsHandler.handle(result.actions)
    end

    stack.call(gateway_request.request)
  end
end

.watch_response_body_json(gateway = Instrumentation.gateway) ⇒ Object



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/datadog/appsec/contrib/rails/gateway/watcher.rb', line 65

def watch_response_body_json(gateway = Instrumentation.gateway)
  gateway.watch("rails.response.body.json") do |stack, container|
    context = container.context

    persistent_data = {
      "server.response.body" => container.data,
    }
    result = context.run_waf(persistent_data, {}, Datadog.configuration.appsec.waf_timeout)

    if result.match?
      context.events.push(
        AppSec::SecurityEvent.new(result, trace: context.trace, span: context.span)
      )

      AppSec::Event.tag(context, result)
      TraceKeeper.keep!(context.trace) if result.keep?

      AppSec::ActionsHandler.handle(result.actions)
    end

    stack.call(container)
  end
end