Class: Datadog::AppSec::Contrib::Devise::TrackingMiddleware

Inherits:
Object
  • Object
show all
Defined in:
lib/datadog/appsec/contrib/devise/tracking_middleware.rb

Overview

A Rack middleware capable of tracking currently signed user

Constant Summary collapse

WARDEN_KEY =
'warden'
SESSION_ID_KEY =
'session_id'

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ TrackingMiddleware

Returns a new instance of TrackingMiddleware.


15
16
17
18
# File 'lib/datadog/appsec/contrib/devise/tracking_middleware.rb', line 15

def initialize(app)
  @app = app
  @devise_session_scope_keys = {}
end

Instance Method Details

#call(env) ⇒ Object


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
# File 'lib/datadog/appsec/contrib/devise/tracking_middleware.rb', line 20

def call(env)
  return @app.call(env) unless AppSec.enabled?
  return @app.call(env) unless Configuration.auto_user_instrumentation_enabled?
  return @app.call(env) unless AppSec.active_context

  unless env.key?(WARDEN_KEY)
    Datadog.logger.debug { 'AppSec: unable to track requests, due to missing warden manager' }
    return @app.call(env)
  end

  context = AppSec.active_context
  if context.trace.nil? || context.span.nil?
    Datadog.logger.debug { 'AppSec: unable to track requests, due to missing trace or span' }
    return @app.call(env)
  end

  # NOTE: Rails session id will be set for unauthenticated users as well,
  #       so we need to make sure we are tracking only authenticated users.
  id = transform(extract_id(env[WARDEN_KEY]))
  session_id = env[WARDEN_KEY].raw_session[SESSION_ID_KEY] if id

  if id
    # NOTE: There is no option to set session id without setting user id via SDK.
    unless context.span.has_tag?(Ext::TAG_USR_ID) && context.span.has_tag?(Ext::TAG_SESSION_ID)
      user_id = context.span[Ext::TAG_USR_ID] || id
      user_session_id = context.span[Ext::TAG_SESSION_ID] || session_id

      # FIXME: The current implementation of event arguments is forsing us
      #        to bloat User class, and pass nil-value instead of skip
      #        passing them at first place.
      #        This is a temporary situation until we refactor events model.
      AppSec::Instrumentation.gateway.push(
        'identity.set_user', AppSec::Instrumentation::Gateway::User.new(user_id, nil, user_session_id)
      )
    end

    context.span[Ext::TAG_USR_ID] ||= id
    context.span[Ext::TAG_DD_USR_ID] = id
    context.span[Ext::TAG_DD_COLLECTION_MODE] ||= Configuration.auto_user_instrumentation_mode
  end

  @app.call(env)
end