summaryrefslogtreecommitdiff
path: root/lib/gitlab/background_migration/create_gpg_key_subkeys_from_gpg_keys.rb
blob: da8265a3a5f619bd3f4f309c8f6ccbffc08635b9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# frozen_string_literal: true
# rubocop:disable Style/Documentation

class Gitlab::BackgroundMigration::CreateGpgKeySubkeysFromGpgKeys
  class GpgKey < ActiveRecord::Base
    self.table_name = 'gpg_keys'

    include EachBatch
    include ShaAttribute

    sha_attribute :primary_keyid
    sha_attribute :fingerprint

    has_many :subkeys, class_name: 'GpgKeySubkey'
  end

  class GpgKeySubkey < ActiveRecord::Base
    self.table_name = 'gpg_key_subkeys'

    include ShaAttribute

    sha_attribute :keyid
    sha_attribute :fingerprint
  end

  def perform(gpg_key_id)
    gpg_key = GpgKey.find_by(id: gpg_key_id)

    return if gpg_key.nil?
    return if gpg_key.subkeys.any?

    create_subkeys(gpg_key)
    update_signatures(gpg_key)
  end

  private

  def create_subkeys(gpg_key)
    gpg_subkeys = Gitlab::Gpg.subkeys_from_key(gpg_key.key)

    gpg_subkeys[gpg_key.primary_keyid.upcase]&.each do |subkey_data|
      gpg_key.subkeys.build(keyid: subkey_data[:keyid], fingerprint: subkey_data[:fingerprint])
    end

    # Improve latency by doing all INSERTs in a single call
    GpgKey.transaction do
      gpg_key.save!
    end
  end

  def update_signatures(gpg_key)
    return unless gpg_key.subkeys.exists?

    InvalidGpgSignatureUpdateWorker.perform_async(gpg_key.id)
  end
end