lib/mihari/rule.rb in mihari-7.6.2 vs lib/mihari/rule.rb in mihari-7.6.3

- old
+ new

@@ -3,10 +3,13 @@ module Mihari class Rule < Service include Concerns::FalsePositiveNormalizable include Concerns::FalsePositiveValidatable + # @return [String, nil] + attr_reader :path_or_id + # @return [Hash] attr_reader :data # @return [Array, nil] attr_reader :errors @@ -17,13 +20,15 @@ # # Initialize # # @param [Hash] data # - def initialize(**data) + # @param [Object] path_or_id + def initialize(path_or_id: nil, **data) super() + @path_or_id = path_or_id @data = data.deep_symbolize_keys @errors = nil @base_time = Time.now.utc validate! @@ -171,14 +176,11 @@ # # @return [Array<Mihari::Models::Artifact>] # def enriched_artifacts @enriched_artifacts ||= Parallel.map(unique_artifacts) do |artifact| - artifact.tap do |tapped| - # NOTE: To apply changes correctly, enrichers should be applied to an artifact serially - enrichers.each { |enricher| enricher.result(tapped) } - end + artifact.enrich_by_enrichers enrichers end end # # Bulk emit @@ -250,28 +252,41 @@ model.save end class << self # + # Load rule from YAML file + # + # @param [String] path + # + # @return [Mihari::Rule] + # + def from_file(path) + yaml = File.read(path) + from_yaml(yaml, path: path) + end + + # # Load rule from YAML string # # @param [String] yaml + # @param [String, nil] path # # @return [Mihari::Rule] # - def from_yaml(yaml) + def from_yaml(yaml, path: nil) data = YAML.safe_load(ERB.new(yaml).result, permitted_classes: [Date, Symbol]) - new(**data) + new(path_or_id: path, **data) end # # @param [Mihari::Models::Rule] model # # @return [Mihari::Rule] # def from_model(model) - new(**model.data) + new(path_or_id: model.id, **model.data) end end private @@ -407,9 +422,9 @@ result = contract.call(data) @data = result.to_h @errors = result.errors - raise ValidationError.new("Validation failed", errors) if errors? + raise ValidationError.new("#{path_or_id}: validation failed", errors) if errors? end end end