2019-12-11 13:08:10 -05:00
|
|
|
# frozen_string_literal: true
|
|
|
|
class KeysFinder
|
2020-10-15 08:09:06 -04:00
|
|
|
delegate :find, :find_by_id, to: :execute
|
|
|
|
|
2019-12-11 13:08:10 -05:00
|
|
|
InvalidFingerprint = Class.new(StandardError)
|
|
|
|
GitLabAccessDeniedError = Class.new(StandardError)
|
|
|
|
|
|
|
|
FINGERPRINT_ATTRIBUTES = {
|
|
|
|
'sha256' => 'fingerprint_sha256',
|
|
|
|
'md5' => 'fingerprint'
|
|
|
|
}.freeze
|
|
|
|
|
2020-02-10 04:08:56 -05:00
|
|
|
def initialize(params)
|
2019-12-11 13:08:10 -05:00
|
|
|
@params = params
|
|
|
|
end
|
|
|
|
|
|
|
|
def execute
|
2019-12-17 04:07:48 -05:00
|
|
|
keys = by_key_type
|
2020-02-10 04:08:56 -05:00
|
|
|
keys = by_users(keys)
|
2019-12-17 04:07:48 -05:00
|
|
|
keys = sort(keys)
|
|
|
|
|
|
|
|
by_fingerprint(keys)
|
2019-12-11 13:08:10 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
2020-02-10 04:08:56 -05:00
|
|
|
attr_reader :params
|
2019-12-11 13:08:10 -05:00
|
|
|
|
2019-12-17 04:07:48 -05:00
|
|
|
def by_key_type
|
|
|
|
if params[:key_type] == 'ssh'
|
|
|
|
Key.regular_keys
|
|
|
|
else
|
|
|
|
Key.all
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def sort(keys)
|
|
|
|
keys.order_last_used_at_desc
|
|
|
|
end
|
|
|
|
|
2020-02-10 04:08:56 -05:00
|
|
|
def by_users(keys)
|
|
|
|
return keys unless params[:users]
|
2019-12-17 04:07:48 -05:00
|
|
|
|
2020-02-10 04:08:56 -05:00
|
|
|
keys.for_user(params[:users])
|
2019-12-17 04:07:48 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
def by_fingerprint(keys)
|
|
|
|
return keys unless params[:fingerprint].present?
|
|
|
|
raise InvalidFingerprint unless valid_fingerprint_param?
|
|
|
|
|
2020-03-27 05:08:28 -04:00
|
|
|
keys.find_by(fingerprint_query) # rubocop: disable CodeReuse/ActiveRecord
|
2019-12-17 04:07:48 -05:00
|
|
|
end
|
|
|
|
|
2019-12-11 13:08:10 -05:00
|
|
|
def valid_fingerprint_param?
|
2022-04-05 11:08:37 -04:00
|
|
|
return Base64.decode64(fingerprint).length == 32 if fingerprint_type == "sha256"
|
|
|
|
|
|
|
|
return false if Gitlab::FIPS.enabled?
|
|
|
|
|
|
|
|
fingerprint =~ /^(\h{2}:){15}\h{2}/
|
2019-12-11 13:08:10 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
def fingerprint_query
|
|
|
|
fingerprint_attribute = FINGERPRINT_ATTRIBUTES[fingerprint_type]
|
|
|
|
|
|
|
|
Key.arel_table[fingerprint_attribute].eq(fingerprint)
|
|
|
|
end
|
|
|
|
|
|
|
|
def fingerprint_type
|
|
|
|
if params[:fingerprint].start_with?(/sha256:|SHA256:/)
|
|
|
|
"sha256"
|
|
|
|
else
|
|
|
|
"md5"
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def fingerprint
|
|
|
|
if fingerprint_type == "sha256"
|
|
|
|
params[:fingerprint].gsub(/sha256:|SHA256:/, "")
|
|
|
|
else
|
|
|
|
params[:fingerprint]
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|