Class: Immunio::Processor
- Inherits:
-
Object
- Object
- Immunio::Processor
- Defined in:
- lib/immunio/processor.rb
Instance Attribute Summary collapse
-
#environment ⇒ Object
Holds environment info for next channel transmission.
Instance Method Summary collapse
- #aggregate_timings(timings) ⇒ Object
- #finish_request ⇒ Object
-
#initialize(channel, vmfactory, options) ⇒ Processor
constructor
A new instance of Processor.
- #log_and_send_error(e, message = "Error", info = {}) ⇒ Object
- #new_request(request) ⇒ Object
-
#run_hook(plugin, hook, meta = {}) ⇒ Object
Run the ‘hook` and return a hash eg.: `{ “allow”: true }`.
-
#run_hook!(*args) ⇒ Object
Run the hook and raise a RequestBlocked error if the request should be blocked.
Constructor Details
#initialize(channel, vmfactory, options) ⇒ Processor
Returns a new instance of Processor.
8 9 10 11 12 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 |
# File 'lib/immunio/processor.rb', line 8 def initialize(channel, vmfactory, ) @channel = channel @vmfactory = vmfactory @dev_mode = .fetch(:dev_mode, false) @debug_mode = .fetch(:debug_mode, false) @log_timings = .fetch(:log_timings, false) # This hash is not in sync with the one in the VM. It is sent to the VM on initialization. @serverdata = {} # List of hook handlers. hook => Lua function. # Stored in the request on first execution. @hook_handlers = {} @timings = Hash.new do |timings, type| timings[type] = Hash.new do |type_timings, name| type_timings[name] = { "total_duration" => 0, "count" => 0 } end end @timings_mutex = Mutex.new # Package up aggregated timings to send to backend @channel.on_sending do @timings_mutex.synchronize do Immunio.logger.debug {"Aggregated timings since last agentmanager transmission: #{@timings}"} timings = @timings.clone @timings.clear { timings: timings }.tap do |info| next unless @environment Immunio.logger.debug {"Reporting environment info: #{@environment}"} info[:environment] = @environment @environment = nil end end end puts "[IMMUNIO] Dev mode activated!" if @dev_mode end |
Instance Attribute Details
#environment ⇒ Object
Holds environment info for next channel transmission
6 7 8 |
# File 'lib/immunio/processor.rb', line 6 def environment @environment end |
Instance Method Details
#aggregate_timings(timings) ⇒ Object
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 92 93 94 95 96 97 |
# File 'lib/immunio/processor.rb', line 67 def aggregate_timings(timings) log_pieces = [] log_pieces << "\nTimings for request (in ms):" if @log_timings request_total = timings["request"]["total"][:total_duration] log_pieces << "\tTotal request time: #{request_total}" if @log_timings @timings_mutex.synchronize do timings.each do |type, type_timings| log_pieces << "\tType: #{type}" if @log_timings && type != "request" type_total = 0 type_timings.each do |name, timing| if @log_timings && type != "request" log_pieces << "\t\t#{name}: #{timing[:total_duration]} (#{timing[:count]})" end @timings[type][name]["total_duration"] += timing[:total_duration] @timings[type][name]["count"] += timing[:count] type_total += timing[:total_duration] end if @log_timings && type != "request" log_pieces << "\tTotal time for type #{type}: #{type_total.round(3)}/#{request_total}" end end end Immunio.logger.info { log_pieces.join("\n") } if @log_timings end |
#finish_request ⇒ Object
99 100 101 102 103 104 105 106 107 108 109 110 111 |
# File 'lib/immunio/processor.rb', line 99 def finish_request request = Request.current if request Immunio.logger.debug "Finishing request #{request.id}" aggregate_timings(request.timings) ActiveSupport::Notifications.publish "immunio.finish_request", request @channel. request.encode if request.should_report? end rescue StandardError => e log_and_send_error e, "Error finishing request", request_id: request.try(:id) ensure Request.current = nil end |
#log_and_send_error(e, message = "Error", info = {}) ⇒ Object
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 |
# File 'lib/immunio/processor.rb', line 214 def log_and_send_error(e, ="Error", info={}) Immunio.logger.warn "#{}: #{e.}" Immunio.logger.warn "Stack: #{e.backtrace}" # Re-raise in dev mode before we send it to the backend. raise e if @dev_mode default_info = { type: "engine.exception", exception: e., traceback: e.backtrace, agent_version: Immunio::VERSION } @channel. default_info.merge(info) # Re-raise error in test mode so we know when something is broken in hook handlers. raise e if Rails.env.test? end |
#new_request(request) ⇒ Object
52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
# File 'lib/immunio/processor.rb', line 52 def new_request(request) # Start channel on first request @channel.start unless @channel.started? # Wait until we've received all the hooks before continuing (if # ready_timeout is set) @channel.wait_until_ready! ActiveSupport::Notifications.publish "immunio.new_request", request # Don't process request unless channel is ready (meaning we've loaded all # the hooks) or we're in dev_mode and hooks are loaded from files Request.current = request if (@channel.ready? || @dev_mode) end |
#run_hook(plugin, hook, meta = {}) ⇒ Object
Run the ‘hook` and return a hash eg.: `{ “allow”: true }`.
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 |
# File 'lib/immunio/processor.rb', line 114 def run_hook(plugin, hook, ={}) request = Request.current # Hooks called outside of a request are ignored since they are triggered while the framework is loaded. return {} unless request # Notify about the hook. This has no perf cost if there are no subscribers. # Used to test and debug the agent in the test Rails apps. ActiveSupport::Notifications.publish "immunio.hook", plugin, hook, = Time.now.utc.iso8601(6) # The VM & handlers are changed on code update. # So we ensure the request uses the same VM & hook handlers for all hooks. request.vm ||= @vmfactory.new_vm # If there is no registered handler, just log the hook and return. unless request.vm.has_function? hook Immunio.logger.debug "No hook code for '#{hook}' to run for request #{request.id}" return {} end # Converts the request data to a Lua table to speedup future calls. request.data = request.vm.create_object(request.data) globals = { "agent_type" => AGENT_TYPE, "agent_version" => VERSION, "timestamp" => , "plugin" => plugin, "hook" => hook, "meta" => , "request" => request.data, } begin Immunio.logger.debug "Running #{hook} hook for request #{request.id} with global values: #{globals}" rescue Encoding::CompatibilityError Immunio.logger.debug "Running #{hook} hook for request #{request.id} (can't log global values due to encoding incompatibility)" end # Run the hook code in the VM and time the execution. result = Request.time "hook", hook do request.vm.call hook, globals end # result.to_h can be expensive, so put it in a block so it only runs when needed begin Immunio.logger.debug { "Result from #{hook} hook: #{result ? result.to_h : {}}" } rescue Encoding::CompatibilityError Immunio.logger.debug { "Result from #{hook} hook: (can't log result due to encoding incompatibility)" } end result || {} # Previosuly this only caught VMErrors, however other exceptions can cause 500s # so to be on the safe side make sure we catch anything raised within the VM call --ol rescue StandardError => e # Log and discard VM errors # Some versions of rails, like 4.2.0, fail to JSONify some objects properly. = {} .each do |key, value| if value.is_a?(Numeric) || value.is_a?(String) || value.is_a?(TrueClass) || value.is_a?(FalseClass) [key] = value else [key] = value.inspect end end log_and_send_error e, "Error running hook #{hook}", request_id: request.id, timestamp: , plugin: plugin, hook: hook, meta: , vmcode_version: request.vm.code_version, vmdata_version: request.vm.data_version {} # Return empty result. end |
#run_hook!(*args) ⇒ Object
Run the hook and raise a RequestBlocked error if the request should be blocked.
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 |
# File 'lib/immunio/processor.rb', line 197 def run_hook!(*args) result = run_hook(*args) # Raise if not allowed (default to allow) if !result.fetch("allow", true) Immunio.logger.debug "Blocking request due to hook response" raise RequestBlocked, "The request was blocked by the Immunio agent" end # Check result for a response override. if result.has_key?(:override_status) raise OverrideResponse.new(result.fetch(:override_status), result.fetch(:override_headers, []), result.fetch(:override_body, "")) end result end |