summaryrefslogtreecommitdiff
path: root/app/models/concerns/mirror_authentication.rb
blob: e3e1a0441f8166672fe3cc52ad85e2cef7f4c748 (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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# frozen_string_literal: true

# Mirroring may use password or SSH public-key authentication. This concern
# implements support for persisting the necessary data in a `credentials`
# serialized attribute. It also needs an `url` method to be defined
module MirrorAuthentication
  SSH_PRIVATE_KEY_OPTS = {
    type: 'RSA',
    bits: 4096
  }.freeze

  extend ActiveSupport::Concern

  included do
    validates :auth_method, inclusion: { in: %w[password ssh_public_key] }, allow_blank: true

    # We should generate a key even if there's no SSH URL present
    before_validation :generate_ssh_private_key!, if: -> {
      regenerate_ssh_private_key || ( auth_method == 'ssh_public_key' && ssh_private_key.blank? )
    }

    credentials_field :auth_method, reader: false
    credentials_field :ssh_known_hosts
    credentials_field :ssh_known_hosts_verified_at
    credentials_field :ssh_known_hosts_verified_by_id
    credentials_field :ssh_private_key
    credentials_field :user
    credentials_field :password
  end

  class_methods do
    def credentials_field(name, reader: true)
      if reader
        define_method(name) do
          credentials[name] if credentials.present?
        end
      end

      define_method("#{name}=") do |value|
        self.credentials ||= {}

        # Removal of the password, username, etc, generally causes an update of
        # the value to the empty string. Detect and gracefully handle this case.
        if value.present?
          self.credentials[name] = value
        else
          self.credentials.delete(name)
        end
      end
    end
  end

  attr_accessor :regenerate_ssh_private_key

  def ssh_key_auth?
    ssh_mirror_url? && auth_method == 'ssh_public_key'
  end

  def password_auth?
    auth_method == 'password'
  end

  def ssh_mirror_url?
    url&.start_with?('ssh://')
  end

  def ssh_known_hosts_verified_by
    @ssh_known_hosts_verified_by ||= ::User.find_by(id: ssh_known_hosts_verified_by_id)
  end

  def ssh_known_hosts_fingerprints
    ::SshHostKey.fingerprint_host_keys(ssh_known_hosts)
  end

  def auth_method
    auth_method = credentials.fetch(:auth_method, nil) if credentials.present?

    auth_method.presence || 'password'
  end

  def ssh_public_key
    return nil if ssh_private_key.blank?

    comment = "git@#{::Gitlab.config.gitlab.host}"
    ::SSHKey.new(ssh_private_key, comment: comment).ssh_public_key
  end

  def generate_ssh_private_key!
    self.ssh_private_key = ::SSHKey.generate(SSH_PRIVATE_KEY_OPTS).private_key
  end
end