Class: Gitrob::Observers::SensitiveFiles

Inherits:
Object
  • Object
show all
Defined in:
lib/gitrob/observers/sensitive_files.rb

Defined Under Namespace

Classes: InvalidPatternError, InvalidPatternFileError

Constant Summary collapse

VALID_KEYS =
%w(part type pattern caption description)
VALID_PARTS =
%w(path filename extension)
VALID_TYPES =
%w(match regex)

Class Method Summary collapse

Class Method Details

.check_blob(blob, pattern) ⇒ Object



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/gitrob/observers/sensitive_files.rb', line 61

def self.check_blob(blob, pattern)
  haystack = blob.send(pattern['part'].to_sym)
  if pattern['type'] == 'match'
    if haystack == pattern['pattern']
      blob.findings.new(
        :caption     => pattern['caption'],
        :description => pattern['description']
      )
    end
  else
    regex = Regexp.new(pattern['pattern'], Regexp::IGNORECASE)
    if !regex.match(haystack).nil?
      blob.findings.new(
        :caption     => pattern['caption'],
        :description => pattern['description']
      )
    end
  end
end

.load_patterns!Object



18
19
20
21
22
# File 'lib/gitrob/observers/sensitive_files.rb', line 18

def self.load_patterns!
  patterns = read_pattern_file!
  validate_patterns!(patterns)
  @patterns = patterns
end

.observe(blob) ⇒ Object



12
13
14
15
16
# File 'lib/gitrob/observers/sensitive_files.rb', line 12

def self.observe(blob)
  patterns.each do |pattern|
    check_blob(blob, pattern)
  end
end

.patternsObject



24
25
26
# File 'lib/gitrob/observers/sensitive_files.rb', line 24

def self.patterns
  @patterns
end

.read_pattern_file!Object



30
31
32
33
34
# File 'lib/gitrob/observers/sensitive_files.rb', line 30

def self.read_pattern_file!
  JSON.parse(File.read("#{File.dirname(__FILE__)}/../../../patterns.json"))
rescue JSON::ParserError => e
  raise InvalidPatternFileError.new("Cannot parse pattern file: #{e.message}")
end

.validate_pattern!(pattern) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/gitrob/observers/sensitive_files.rb', line 45

def self.validate_pattern!(pattern)
  pattern.keys.each do |key|
    if !VALID_KEYS.include?(key)
      raise InvalidPatternError.new("Pattern contains unknown key: #{key}")
    end
  end

  if !VALID_PARTS.include?(pattern['part'])
    raise InvalidPatternError.new("Pattern has unknown part: #{pattern['part']}")
  end

  if !VALID_TYPES.include?(pattern['type'])
    raise InvalidPatternError.new("Pattern has unknown type: #{pattern['type']}")
  end
end

.validate_patterns!(patterns) ⇒ Object



36
37
38
39
40
41
42
43
# File 'lib/gitrob/observers/sensitive_files.rb', line 36

def self.validate_patterns!(patterns)
  if !patterns.is_a?(Array) || patterns.empty?
    raise InvalidPatternFileError.new("Pattern file contains no patterns")
  end
  patterns.each do |pattern|
    validate_pattern!(pattern)
  end
end