Skip to content
代码片段 群组 项目
未验证 提交 4fe059ec 编辑于 作者: Yasha Rise's avatar Yasha Rise 提交者: GitLab
浏览文件

Populate cve column in pm_advisories using a migration

上级 4ff5988e
No related branches found
No related tags found
无相关合并请求
# frozen_string_literal: true
# See https://docs.gitlab.com/ee/development/migration_style_guide.html
# for more information on how to write migrations for GitLab.
class PopulateCveInPmAdvisories < Gitlab::Database::Migration[2.2]
milestone '17.8'
disable_ddl_transaction!
restrict_gitlab_migration gitlab_schema: :gitlab_pm
BATCH_SIZE = 1000
def up
advisory_model = define_batchable_model('pm_advisories')
advisory_model.each_batch(of: BATCH_SIZE) do |batch|
cve_updates = batch.filter_map do |advisory|
cve = extract_cve_from_identifiers(advisory.identifiers)
[advisory.id, cve] if cve
end
next if cve_updates.empty?
update_sql = <<-SQL
UPDATE pm_advisories
SET cve = CASE id
#{cve_updates.map { |id, cve| "WHEN #{id} THEN #{connection.quote(cve)}" }.join("\n")}
END
WHERE id IN (#{cve_updates.map(&:first).join(', ')})
SQL
execute(update_sql)
end
end
def down
advisory_model = define_batchable_model('pm_advisories')
advisory_model.each_batch(of: BATCH_SIZE) do |batch|
ids = batch.pluck(:id)
execute <<-SQL
UPDATE pm_advisories
SET cve = NULL
WHERE id IN (#{ids.join(', ')})
SQL
end
end
private
def extract_cve_from_identifiers(identifiers)
return unless identifiers.is_a?(Array)
cve_identifier = identifiers.find { |identifier| identifier['type']&.downcase == 'cve' }
cve_identifier['name'] if cve_identifier
end
end
18fdb6fb23add302a50b2120681e5b03d8416a3c46eff73005db5eb1d5690cbd
\ No newline at end of file
# frozen_string_literal: true
require 'spec_helper'
require_migration!
RSpec.describe PopulateCveInPmAdvisories, feature_category: :software_composition_analysis do
let(:advisories) { table(:pm_advisories) }
let(:migration) { described_class.new }
before do
advisories.create!(
advisory_xid: '1',
source_xid: 0,
published_date: Date.new(2023, 1, 1),
identifiers: [{ 'type' => 'CVE', 'name' => 'CVE-2023-1234' }]
)
advisories.create!(
advisory_xid: '2',
source_xid: 0,
published_date: Date.new(2023, 1, 2),
identifiers: [{ 'type' => 'CWE', 'name' => 'CWE-79' }]
)
advisories.create!(
advisory_xid: '3',
source_xid: 0,
published_date: Date.new(2023, 1, 3),
identifiers: [{ 'type' => 'CVE', 'name' => 'CVE-2023-5678' }, { 'type' => 'CWE', 'name' => 'CWE-89' }]
)
advisories.create!(
advisory_xid: '4',
source_xid: 0,
published_date: Date.new(2023, 1, 4),
identifiers: []
)
end
describe 'migration' do
it 'populates the cve column for advisories with CVE identifiers' do
reversible_migration do |migration|
migration.before -> {
expect(advisories.pluck(:cve)).to match_array([nil, nil, nil, nil])
}
migration.after -> {
expect(advisories.pluck(:cve)).to match_array(['CVE-2023-1234', nil, 'CVE-2023-5678', nil])
}
end
end
end
end
0% 加载中 .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册