Class: Honeybadger::Util::Sanitizer

Inherits:
Object
  • Object
show all
Defined in:
lib/honeybadger/util/sanitizer.rb

Constant Summary collapse

OBJECT_WHITELIST =
[Hash, Array, String, Integer, Float, TrueClass, FalseClass, NilClass]
FILTERED_REPLACEMENT =
'[FILTERED]'.freeze
TRUNCATION_REPLACEMENT =
'[TRUNCATED]'.freeze
MAX_STRING_SIZE =
2048

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ Sanitizer

Returns a new instance of Sanitizer.



12
13
14
15
16
17
18
19
20
# File 'lib/honeybadger/util/sanitizer.rb', line 12

def initialize(opts = {})
  @max_depth = opts.fetch(:max_depth, 20)

  if filters = opts.fetch(:filters, nil)
    @filters = Array(filters).collect do |f|
      f.kind_of?(Regexp) ? f : f.to_s
    end
  end
end

Instance Method Details

#filter_url(url) ⇒ Object



56
57
58
59
60
61
62
63
64
65
66
# File 'lib/honeybadger/util/sanitizer.rb', line 56

def filter_url(url)
  return url unless filters

  filtered_url = url.to_s.dup
  filtered_url.scan(/(?:^|&|\?)([^=?&]+)=([^&]+)/).each do |m|
    next unless filter_key?(m[0])
    filtered_url.gsub!(/#{m[1]}/, '[FILTERED]')
  end

  filtered_url
end

#sanitize(data, depth = 0, stack = nil) ⇒ Object



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
# File 'lib/honeybadger/util/sanitizer.rb', line 22

def sanitize(data, depth = 0, stack = nil)
  if recursive?(data)
    return '[possible infinite recursion halted]' if stack && stack.include?(data.object_id)
    stack = stack ? stack.dup : Set.new
    stack << data.object_id
  end

  if data.kind_of?(String)
    sanitize_string(data)
  elsif data.respond_to?(:to_hash)
    return '[max depth reached]' if depth >= max_depth
    hash = data.to_hash
    new_hash = {}
    hash.each_pair do |key, value|
      k = key.kind_of?(Symbol) ? key : sanitize(key, depth+1, stack)
      if filter_key?(k)
        new_hash[k] = FILTERED_REPLACEMENT
      else
        new_hash[k] = sanitize(value, depth+1, stack)
      end
    end
    new_hash
  elsif data.respond_to?(:to_ary)
    return '[max depth reached]' if depth >= max_depth
    data.to_ary.map do |value|
      sanitize(value, depth+1, stack)
    end.compact
  elsif OBJECT_WHITELIST.any? {|c| data.kind_of?(c) }
    data
  else
    sanitize_string(data.to_s)
  end
end