Module: Mihari::Mixins::Rule

Includes:
Database
Included in:
Analyzers::Rule, Commands::Initialization, Commands::Search, Commands::Validator, Structs::Rule::Rule
Defined in:
lib/mihari/mixins/rule.rb

Instance Method Summary collapse

Methods included from Database

#with_db_connection

Instance Method Details

#initialize_rule_yaml(filename, files = Dry::Files.new, template: rule_template) ⇒ nil

Create (blank) rule file

Parameters:

  • filename (String)
  • files (Dry::Files) (defaults to: Dry::Files.new)
  • template (String) (defaults to: rule_template)

Returns:

  • (nil)


79
80
81
# File 'lib/mihari/mixins/rule.rb', line 79

def initialize_rule_yaml(filename, files = Dry::Files.new, template: rule_template)
  files.write(filename, template)
end

#load_erb_yaml(yaml) ⇒ Object



12
13
14
# File 'lib/mihari/mixins/rule.rb', line 12

def load_erb_yaml(yaml)
  YAML.safe_load(ERB.new(yaml).result, permitted_classes: [Date], symbolize_names: true)
end

#load_rule(path_or_id) ⇒ Mihari::Structs::Rule::Rule

Load rule into hash

Parameters:

  • path_or_id (String)

    Path to YAML file or YAML string or ID of a rule in the database

Returns:



23
24
25
26
27
28
29
30
# File 'lib/mihari/mixins/rule.rb', line 23

def load_rule(path_or_id)
  yaml = nil

  yaml = load_yaml_from_file(path_or_id) if File.exist?(path_or_id)
  yaml = load_yaml_from_db(path_or_id) if yaml.nil?

  Structs::Rule::Rule.from_yaml yaml
end

#load_yaml_from_db(id) ⇒ Object



38
39
40
41
42
43
44
45
# File 'lib/mihari/mixins/rule.rb', line 38

def load_yaml_from_db(id)
  with_db_connection do
    rule = Mihari::Rule.find(id)
    rule.yaml || rule.symbolized_data.to_yaml
  rescue ActiveRecord::RecordNotFound
    raise ArgumentError, "ID:#{id} is not found in the database"
  end
end

#load_yaml_from_file(path) ⇒ Object



32
33
34
35
36
# File 'lib/mihari/mixins/rule.rb', line 32

def load_yaml_from_file(path)
  return nil unless Pathname(path).exist?

  File.read path
end

#rule_templateString

Returns a template for rule

Returns:

  • (String)

    A template for rule



64
65
66
67
68
# File 'lib/mihari/mixins/rule.rb', line 64

def rule_template
  yaml = File.read(File.expand_path("../templates/rule.yml.erb", __dir__))
  Structs::Rule::Rule.from_yaml yaml
  yaml
end

#validate_rule!(rule) ⇒ Object

Validate a rule

Parameters:



52
53
54
55
56
57
# File 'lib/mihari/mixins/rule.rb', line 52

def validate_rule!(rule)
  rule.validate!
rescue RuleValidationError => e
  Mihari.logger.error "Failed to parse the input as a rule"
  raise e
end