debian-mirror-gitlab/app/services/clusters/aws/fetch_credentials_service.rb

81 lines
2.1 KiB
Ruby
Raw Normal View History

2019-12-26 22:10:19 +05:30
# frozen_string_literal: true
module Clusters
module Aws
class FetchCredentialsService
attr_reader :provision_role
MissingRoleError = Class.new(StandardError)
2020-01-01 13:55:28 +05:30
def initialize(provision_role, provider: nil)
2019-12-26 22:10:19 +05:30
@provision_role = provision_role
@provider = provider
2021-01-29 00:20:46 +05:30
@region = provider&.region || provision_role&.region || Clusters::Providers::Aws::DEFAULT_REGION
2019-12-26 22:10:19 +05:30
end
def execute
raise MissingRoleError.new('AWS provisioning role not configured') unless provision_role.present?
::Aws::AssumeRoleCredentials.new(
client: client,
role_arn: provision_role.role_arn,
role_session_name: session_name,
2020-01-01 13:55:28 +05:30
external_id: provision_role.role_external_id,
policy: session_policy
2019-12-26 22:10:19 +05:30
).credentials
end
private
2021-01-29 00:20:46 +05:30
attr_reader :provider, :region
2019-12-26 22:10:19 +05:30
def client
2021-02-22 17:27:13 +05:30
::Aws::STS::Client.new(**client_args)
end
def client_args
{ region: region, credentials: gitlab_credentials }.compact
2019-12-26 22:10:19 +05:30
end
def gitlab_credentials
2021-02-22 17:27:13 +05:30
# These are not needed for IAM instance profiles
return unless access_key_id.present? && secret_access_key.present?
2019-12-26 22:10:19 +05:30
::Aws::Credentials.new(access_key_id, secret_access_key)
end
def access_key_id
Gitlab::CurrentSettings.eks_access_key_id
end
def secret_access_key
Gitlab::CurrentSettings.eks_secret_access_key
end
2020-01-01 13:55:28 +05:30
##
# If we haven't created a provider record yet,
# we restrict ourselves to read only access so
# that we can safely expose credentials to the
# frontend (to be used when populating the
# creation form).
def session_policy
if provider.nil?
File.read(read_only_policy)
end
end
def read_only_policy
Rails.root.join('vendor', 'aws', 'iam', "eks_cluster_read_only_policy.json")
end
2019-12-26 22:10:19 +05:30
def session_name
if provider.present?
"gitlab-eks-cluster-#{provider.cluster_id}-user-#{provision_role.user_id}"
else
"gitlab-eks-autofill-user-#{provision_role.user_id}"
end
end
end
end
end