occurrence.rb 8.13 KB
Newer Older
1 2 3
# frozen_string_literal: true

module Vulnerabilities
4
  class Occurrence < ApplicationRecord
5
    include ShaAttribute
6
    include ::Gitlab::Utils::StrongMemoize
7
    include Presentable
8 9 10

    self.table_name = "vulnerability_occurrences"

11 12 13
    OCCURRENCES_PER_PAGE = 20

    paginates_per OCCURRENCES_PER_PAGE
14

15 16 17 18 19
    sha_attribute :project_fingerprint
    sha_attribute :location_fingerprint

    belongs_to :project
    belongs_to :scanner, class_name: 'Vulnerabilities::Scanner'
20
    belongs_to :primary_identifier, class_name: 'Vulnerabilities::Identifier', inverse_of: :primary_occurrences
21
    belongs_to :vulnerability, inverse_of: :findings
22 23 24

    has_many :occurrence_identifiers, class_name: 'Vulnerabilities::OccurrenceIdentifier'
    has_many :identifiers, through: :occurrence_identifiers, class_name: 'Vulnerabilities::Identifier'
25 26
    has_many :occurrence_pipelines, class_name: 'Vulnerabilities::OccurrencePipeline'
    has_many :pipelines, through: :occurrence_pipelines, class_name: 'Ci::Pipeline'
27

28 29
    attr_writer :sha

30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
    CONFIDENCE_LEVELS = {
      undefined: 0,
      ignore: 1,
      unknown: 2,
      experimental: 3,
      low: 4,
      medium: 5,
      high: 6,
      confirmed: 7
    }.with_indifferent_access.freeze

    SEVERITY_LEVELS = {
      undefined: 0,
      info: 1,
      unknown: 2,
      # experimental: 3, formerly used by confidence, no longer applicable
      low: 4,
      medium: 5,
      high: 6,
      critical: 7
    }.with_indifferent_access.freeze

52
    REPORT_TYPES = {
53 54 55 56
      sast: 0,
      dependency_scanning: 1,
      container_scanning: 2,
      dast: 3
57 58
    }.with_indifferent_access.freeze

59
    enum confidence: CONFIDENCE_LEVELS, _prefix: :confidence
60
    enum report_type: REPORT_TYPES
61
    enum severity: SEVERITY_LEVELS, _prefix: :severity
62 63 64

    validates :scanner, presence: true
    validates :project, presence: true
65
    validates :uuid, presence: true
66

67
    validates :primary_identifier, presence: true
68 69 70 71
    validates :project_fingerprint, presence: true
    validates :location_fingerprint, presence: true
    # Uniqueness validation doesn't work with binary columns, so save this useless query. It is enforce by DB constraint anyway.
    # TODO: find out why it fails
72
    # validates :location_fingerprint, presence: true, uniqueness: { scope: [:primary_identifier_id, :scanner_id, :ref, :pipeline_id, :project_id] }
73 74
    validates :name, presence: true
    validates :report_type, presence: true
75 76
    validates :severity, presence: true
    validates :confidence, presence: true
77 78 79 80

    validates :metadata_version, presence: true
    validates :raw_metadata, presence: true

Heinrich Lee Yu's avatar
Heinrich Lee Yu committed
81
    scope :report_type, -> (type) { where(report_type: report_types[type]) }
82
    scope :ordered, -> { order(severity: :desc, confidence: :desc, id: :asc) }
83

84 85 86
    scope :by_report_types, -> (values) { where(report_type: values) }
    scope :by_projects, -> (values) { where(project_id: values) }
    scope :by_severities, -> (values) { where(severity: values) }
87
    scope :by_confidences, -> (values) { where(confidence: values) }
88

89
    scope :all_preloaded, -> do
90
      preload(:scanner, :identifiers, project: [:namespace, :project_feature])
91 92
    end

93 94
    scope :scoped_project, -> { where('vulnerability_occurrences.project_id = projects.id') }

95
    def self.for_pipelines_with_sha(pipelines)
96 97
      joins(:pipelines)
        .where(ci_pipelines: { id: pipelines })
98 99 100
        .select("vulnerability_occurrences.*, ci_pipelines.sha")
    end

101 102 103 104 105
    def self.for_pipelines(pipelines)
      joins(:occurrence_pipelines)
        .where(vulnerability_occurrence_pipelines: { pipeline_id: pipelines })
    end

106 107 108
    def self.count_by_day_and_severity(period)
      joins(:occurrence_pipelines)
        .select('CAST(vulnerability_occurrence_pipelines.created_at AS DATE) AS day', :severity, 'COUNT(distinct vulnerability_occurrences.id) as count')
109
        .where(['vulnerability_occurrence_pipelines.created_at >= ?', Time.zone.now.beginning_of_day - period])
110 111 112 113
        .group(:day, :severity)
        .order('day')
    end

114
    def self.counted_by_severity
115 116 117
      group(:severity).count.each_with_object({}) do |(severity, count), accum|
        accum[SEVERITY_LEVELS[severity]] = count
      end
118 119
    end

120 121 122 123 124 125 126 127 128 129 130 131
    def self.with_vulnerabilities_for_state(project:, report_type:, project_fingerprints:)
      Vulnerabilities::Occurrence
        .joins(:vulnerability)
        .where(
          project: project,
          report_type: report_type,
          project_fingerprint: project_fingerprints
        )
        .select('report_type, vulnerability_id, project_fingerprint, raw_metadata, '\
                'vulnerabilities.id, vulnerabilities.state') # fetching only required attributes
    end

132 133 134 135 136
    # sha can be sourced from a joined pipeline or set from the report
    def sha
      self[:sha] || @sha
    end

137 138 139 140 141 142 143 144 145 146 147 148
    def state
      return 'dismissed' if dismissal_feedback.present?

      if vulnerability.nil?
        'new'
      elsif vulnerability.closed?
        'resolved'
      else
        'confirmed'
      end
    end

149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
    def self.undismissed
      where(
        "NOT EXISTS (?)",
        Feedback.select(1)
        .where("ENCODE(#{table_name}.project_fingerprint, 'HEX') = vulnerability_feedback.project_fingerprint") # rubocop:disable GitlabSecurity/SqlInjection
        .for_dismissal
      )
    end

    def self.batch_count_by_project_and_severity(project_id, severity)
      BatchLoader.for(project_id: project_id, severity: severity).batch(default_value: 0) do |items, loader|
        project_ids = items.map { |i| i[:project_id] }.uniq
        severities = items.map { |i| i[:severity] }.uniq

        counts = undismissed
          .by_severities(severities)
          .by_projects(project_ids)
          .group(:project_id, :severity)
          .count

        counts.each do |(found_project_id, found_severity), count|
          loader_key = { project_id: found_project_id, severity: found_severity }
          loader.call(loader_key, count)
        end
      end
    end

176 177 178 179 180 181 182 183 184
    def feedback(feedback_type:)
      params = {
        project_id: project_id,
        category: report_type,
        project_fingerprint: project_fingerprint,
        feedback_type: feedback_type
      }

      BatchLoader.for(params).batch do |items, loader|
185 186 187
        project_ids = items.map { |i| i[:project_id] }
        categories = items.map { |i| i[:category] }
        fingerprints = items.map { |i| i[:project_fingerprint] }
188

189
        Vulnerabilities::Feedback.all_preloaded.where(
190 191 192 193
          project_id: project_ids.uniq,
          category: categories.uniq,
          project_fingerprint: fingerprints.uniq
        ).each do |feedback|
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
          loaded_params = {
            project_id: feedback.project_id,
            category: feedback.category,
            project_fingerprint: feedback.project_fingerprint,
            feedback_type: feedback.feedback_type
          }
          loader.call(loaded_params, feedback)
        end
      end
    end

    def dismissal_feedback
      feedback(feedback_type: 'dismissal')
    end

    def issue_feedback
      feedback(feedback_type: 'issue')
    end

213 214 215 216
    def merge_request_feedback
      feedback(feedback_type: 'merge_request')
    end

217 218
    def metadata
      strong_memoize(:metadata) do
Nick Thomas's avatar
Nick Thomas committed
219 220 221
        JSON.parse(raw_metadata)
      rescue JSON::ParserError
        {}
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
      end
    end

    def description
      metadata.dig('description')
    end

    def solution
      metadata.dig('solution')
    end

    def location
      metadata.fetch('location', {})
    end

    def links
      metadata.fetch('links', [])
    end
240 241 242 243

    def remediations
      metadata.dig('remediations')
    end
Can Eldem's avatar
Can Eldem committed
244 245 246 247 248 249 250 251 252 253 254 255 256 257

    alias_method :==, :eql? # eql? is necessary in some cases like array intersection

    def eql?(other)
      other.report_type == report_type &&
        other.location == location &&
        other.first_fingerprint == first_fingerprint
    end

    # Array.difference (-) method uses hash and eql? methods to do comparison
    def hash
      report_type.hash ^ location.hash ^ first_fingerprint.hash
    end

258 259 260 261 262 263 264 265
    def severity_value
      self.class.severities[self.severity]
    end

    def confidence_value
      self.class.confidences[self.confidence]
    end

Can Eldem's avatar
Can Eldem committed
266 267 268 269 270
    protected

    def first_fingerprint
      identifiers.first&.fingerprint
    end
271 272
  end
end