Class: Immunio::HTTPTracker

Inherits:
Object
  • Object
show all
Defined in:
lib/immunio/plugins/http_tracker.rb

Overview

Rack middleware tracking HTTP requests and responses and triggers the proper hooks.

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ HTTPTracker

Returns a new instance of HTTPTracker.



9
10
11
# File 'lib/immunio/plugins/http_tracker.rb', line 9

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



13
14
15
16
17
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/immunio/plugins/http_tracker.rb', line 13

def call(env)
  request = Request.new(env)
  request.time "plugin", "#{Module.nesting[0]}::#{__method__}" do
    Immunio.logger.debug { "Creating new request in HTTPTracker" }
    Immunio.new_request(request)

    Immunio.run_hook! "http_tracker", "http_request_start", meta_from_env(env)

    env['rack.input'] = InputWrapper.new(env['rack.input'])

    status, headers, body = Request.pause "plugin", "#{Module.nesting[0]}::#{__method__}" do
      @app.call(env)
    end

    # Run hook for the session only if it was loaded
    session = env["rack.session"]
    if session_was_loaded?(session)
      Immunio.run_hook! "http_tracker", "framework_session",
                        session_id: extract_session_id(session)
    end

    # Immunio expects response headers as a list of tuples.
    list_headers = headers_to_list(headers)

    result = Immunio.run_hook! "http_tracker", "http_response_start",
                               status: status, headers: list_headers

    # If new headers are specified, convert them back to the Ruby hash format.
    if result["headers"] != nil
      # The new_headers completely replace the originals.
      headers = list_to_headers(result["headers"].to_a)
    end

    # Send the response
    [status, headers, body]
  end

rescue RequestBlocked
  Request.time "plugin", "#{Module.nesting[0]}::#{__method__}[RequestBlocked]" do
    status, headers, body = Immunio.blocked_app.call(env)
    # Do not allow blocking the request here
    Immunio.run_hook "http_tracker", "http_response_start",
                     status: status, headers: headers

    [status, headers, body]
  end
rescue OverrideResponse => override
  status, headers, body = Immunio.override_response.call(env, override)

  Immunio.run_hook "http_tracker", "http_response_start",
                   status: status, headers: headers
  [status, headers, body]
end