Module: Supergood::Utils

Defined in:
lib/supergood/utils.rb

Class Method Summary collapse

Class Method Details

.expand(parts, obj, key_path) ⇒ Object



107
108
109
110
111
112
113
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
# File 'lib/supergood/utils.rb', line 107

def self.expand(parts, obj, key_path)
  path = key_path
  return [path] if parts.empty?

  part = parts.first
  is_property = !part.start_with?('[')
  separator = !path.empty? && is_property ? '.' : ''

  # Check for array notations
  if part.match?(/\[\*?\]/)
    return [] unless obj.is_a?(Array)

    # Expand for each element in the array
    obj.flat_map.with_index do |_, index|
      expand(parts[1..], obj[index], "#{path}#{separator}[#{index}]")
    end
  elsif part.start_with?('[') && part.end_with?(']')
    # Specific index in the array
    index = part[1...-1].to_i
    if index.is_a?(Numeric) && index < obj.length
      expand(parts[1..], obj[index], "#{path}#{separator}#{part}")
    else
      []
    end
  else
    if obj && obj.is_a?(Hash) && obj.key?(part)
      expand(parts[1..], obj[part], "#{path}#{separator}#{part}")
    else
      []
    end
  end
end

.expand_key(key, obj) ⇒ Object



140
141
142
143
# File 'lib/supergood/utils.rb', line 140

def self.expand_key(key, obj)
  parts = key.scan(/[^.\[\]]+|\[\d*\]|\[\*\]/) || []
  expand(parts, obj, '')
end

.expand_sensitive_key_set_for_arrays(obj, sensitive_keys) ⇒ Object



145
146
147
# File 'lib/supergood/utils.rb', line 145

def self.expand_sensitive_key_set_for_arrays(obj, sensitive_keys)
  sensitive_keys.flat_map { |key| expand_key(key, obj) }
end

.find_leaf_key_paths(structure, current_path = []) ⇒ Object



186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
# File 'lib/supergood/utils.rb', line 186

def self.find_leaf_key_paths(structure, current_path = [])
  key_paths = []

  if structure.is_a?(Hash)
    # Iterate through each key-value pair in the hash
    structure.each do |key, value|
      # Recursively find key paths in the value
      key_paths += find_leaf_key_paths(value, current_path + [key.to_s])
    end
  elsif structure.is_a?(Array)
    # Iterate through each element in the array
    structure.each_with_index do |element, index|
      # Modify how indices are appended to the path
      # Check if the last element in the current_path is a hash key or an array index
      if current_path.last && current_path.last.include?('[')
        new_path = current_path[0...-1] + ["#{current_path.last}[#{index}]"]
      else
        new_path = current_path + ["[#{index}]"]
      end

      # Recursively find key paths in the element
      key_paths += find_leaf_key_paths(element, new_path)
    end
  else
    # Leaf node: construct the key path and add it to the list
    key_path = current_path.join('.').gsub('.[', '[')
    key_paths << key_path unless key_path.empty?
  end

  key_paths
end

.get_endpoint_config(request, remote_config) ⇒ Object



91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/supergood/utils.rb', line 91

def self.get_endpoint_config(request, remote_config)
  domain = remote_config.keys.find { |d| get_host_without_www(request['url']).include?(d) }
  return nil unless domain

  endpoint_configs = remote_config[domain]
  endpoint_configs.each_value do |endpoint_config|
    regex = endpoint_config['regex']
    location = endpoint_config['location']
    regex_obj = Regexp.new(regex)
    str_representation = get_str_representation_from_path(request, location)
    next unless str_representation
    return endpoint_config if regex_obj.match?(str_representation)
  end
  nil
end

.get_header(request_or_response) ⇒ Object



26
27
28
29
30
31
32
# File 'lib/supergood/utils.rb', line 26

def self.get_header(request_or_response)
  header = {}
  request_or_response.each_header do |k,v|
    header[k] = v
  end
  header
end

.get_host_without_www(url) ⇒ Object



9
10
11
12
13
14
# File 'lib/supergood/utils.rb', line 9

def self.get_host_without_www(url)
  uri = URI.parse(url)
  uri = URI.parse("http://#{url}") if uri.scheme.nil?
  host = uri.host.downcase
  host.start_with?('www.') ? host[4..] : host
end

.get_str_representation_from_path(request, location) ⇒ Object



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/supergood/utils.rb', line 72

def self.get_str_representation_from_path(request, location)
  url = URI(request['url'])

  case location
  when 'domain'
    get_host_without_www(url)
  when 'url'
    url.to_s
  when 'path'
    url.path
  when 'requestHeaders'
    request['headers'].to_s
  when 'requestBody'
    request['body'].to_s
  else
    request[location.to_sym].to_s if request.key?(location.to_sym)
  end
end

.make_config(config) ⇒ Object



38
39
40
# File 'lib/supergood/utils.rb', line 38

def self.make_config(config)
  DEFAULT_CONFIG.merge(config)
end

.marshal_key_path(keypath) ⇒ Object



149
150
151
152
153
154
# File 'lib/supergood/utils.rb', line 149

def self.marshal_key_path(keypath)
  keypath.gsub(/^requestHeaders/, 'request.headers')
         .gsub(/^requestBody/, 'request.body')
         .gsub(/^responseHeaders/, 'response.headers')
         .gsub(/^responseBody/, 'response.body')
end

.prepare_data(events, remote_config, force_redact_all) ⇒ Object



272
273
274
275
276
277
278
279
# File 'lib/supergood/utils.rb', line 272

def self.prepare_data(events, remote_config, force_redact_all)
  events.map do |event|
     = redact_values_from_keys(event, remote_config, force_redact_all)
    ['event'].merge(
      'metadata': { 'sensitiveKeys': ['sensitive_key_metadata'] }
    )
  end
end

.process_remote_config(remote_config_payload) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/supergood/utils.rb', line 42

def self.process_remote_config(remote_config_payload)
  remote_config_payload ||= []
  remote_config_payload.reduce({}) do |remote_config, domain_config|
    domain = domain_config['domain']
    endpoints = domain_config['endpoints']
    endpoint_config = endpoints.reduce({}) do |config, endpoint|
      matching_regex = endpoint['matchingRegex']
      regex = matching_regex['regex']
      location = matching_regex['location']

      endpoint_configuration = endpoint['endpointConfiguration']
      action = endpoint_configuration['action']
      sensitive_keys = endpoint_configuration['sensitiveKeys'] || []
      sensitive_keys = sensitive_keys.map { |key| key['keyPath'] }

      config[regex] = {
        'location' => location,
        'regex' => regex,
        'ignored' => action == 'Ignore',
        'sensitive_keys' => sensitive_keys
      }

      config
    end

    remote_config[domain] = endpoint_config
    remote_config
  end
end

.redact_value(input) ⇒ Object



249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
# File 'lib/supergood/utils.rb', line 249

def self.redact_value(input)
  data_length = 0
  data_type = 'null'
  case input
  when Array
    data_length = input.size
    data_type = 'array'
  when Hash
    data_length = input.to_json.bytesize
    data_type = 'object'
  when String
    data_length = input.size
    data_type = 'string'
  when Numeric
    data_length = input.to_s.size
    data_type = input.integer? ? 'integer' : 'float'
  when TrueClass, FalseClass # This is a better way to check for booleans
    data_length = 1
    data_type = 'boolean'
  end
  { 'length' => data_length, 'type' => data_type }
end

.redact_values_from_keys(event, remote_config, force_redact_all) ⇒ Object



218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
# File 'lib/supergood/utils.rb', line 218

def self.redact_values_from_keys(event, remote_config, force_redact_all)
   = []
  endpoint_config = get_endpoint_config(event['request'], remote_config)

  unless (endpoint_config && endpoint_config['sensitive_keys'].any?) || force_redact_all
    return { 'event' => event, 'sensitive_key_metadata' =>  }
  end

  if force_redact_all
    # Need response.body in path
    sensitive_keys = find_leaf_key_paths(event['response']['body'], ['response', 'body'])
    sensitive_keys += find_leaf_key_paths(event['request']['body'], ['request', 'body'])
    sensitive_keys += find_leaf_key_paths(event['request']['headers'], ['request', 'headers'])
    sensitive_keys += find_leaf_key_paths(event['response']['headers'], ['response', 'headers'])
  else
    sensitive_keys = endpoint_config['sensitive_keys']
  end

  sensitive_keys = expand_sensitive_key_set_for_arrays(
    event, sensitive_keys.map { |key| marshal_key_path(key) }
  )
  sensitive_keys.each do |key_path|
    value = R_.get(event, key_path)
    event = set_value_to_nil(event, key_path)
    # Add sensitive key for array expansion
     << { 'keyPath' => unmarshal_key_path(key_path) }.merge(redact_value(value))
  end

  { 'event' => event, 'sensitive_key_metadata' =>  }
end

.request_url(http, request) ⇒ Object



34
35
36
# File 'lib/supergood/utils.rb', line 34

def self.request_url(http, request)
  URI::DEFAULT_PARSER.unescape("http#{'s' if http.use_ssl?}://#{http.address}#{request.path}")
end

.safe_parse_json(input) ⇒ Object



16
17
18
19
20
21
22
23
24
# File 'lib/supergood/utils.rb', line 16

def self.safe_parse_json(input)
  return '' if !input || input == ''

  begin
    JSON.parse(input)
  rescue => e
    input
  end
end

.set_value_to_nil(hash, key_path) ⇒ Object



163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
# File 'lib/supergood/utils.rb', line 163

def self.set_value_to_nil(hash, key_path)
  keys = key_path.split('.')
  current_key = keys.first
  index = current_key.match(/\[(\d+)\]/)

  index = index[1].to_i if index

  # Convert current_key to symbol if necessary
  current_key = current_key.gsub(/\[\d+\]/, '') if index

  return hash unless hash.keys.include?(current_key)

  if keys.length == 1
    index ? hash[current_key][index] = nil : hash[current_key] = nil
  elsif hash[current_key].is_a?(Hash)
    set_value_to_nil(hash[current_key], keys[1..].join('.'))
  elsif hash[current_key].is_a?(Array)
    set_value_to_nil(hash[current_key][index], keys[1..].join('.'))
  end

  hash
end

.unmarshal_key_path(keypath) ⇒ Object



156
157
158
159
160
161
# File 'lib/supergood/utils.rb', line 156

def self.unmarshal_key_path(keypath)
  keypath.gsub(/^request\.headers/, 'requestHeaders')
         .gsub(/^request\.body/, 'requestBody')
         .gsub(/^response\.headers/, 'responseHeaders')
         .gsub(/^response\.body/, 'responseBody')
end