Skip to content

Commit

Permalink
Merge pull request #700 from balasankarc/support-ci-job-token
Browse files Browse the repository at this point in the history
Support using CI_JOB_TOKEN for authentication
  • Loading branch information
NARKOZ authored Sep 18, 2024
2 parents 579bcda + 0bfb77c commit 26edb1b
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 4 deletions.
3 changes: 2 additions & 1 deletion lib/gitlab/configuration.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ module Gitlab
# Defines constants and methods related to configuration.
module Configuration
# An array of valid keys in the options hash when configuring a Gitlab::API.
VALID_OPTIONS_KEYS = %i[endpoint private_token user_agent sudo httparty].freeze
VALID_OPTIONS_KEYS = %i[endpoint private_token user_agent sudo httparty pat_prefix].freeze

# The user agent that will be sent to the API endpoint if none is set.
DEFAULT_USER_AGENT = "Gitlab Ruby Gem #{Gitlab::VERSION}"
Expand Down Expand Up @@ -37,6 +37,7 @@ def options
def reset
self.endpoint = ENV['GITLAB_API_ENDPOINT'] || ENV['CI_API_V4_URL']
self.private_token = ENV['GITLAB_API_PRIVATE_TOKEN'] || ENV['GITLAB_API_AUTH_TOKEN']
self.pat_prefix = nil
self.httparty = get_httparty_config(ENV['GITLAB_API_HTTPARTY_OPTIONS'])
self.sudo = nil
self.user_agent = DEFAULT_USER_AGENT
Expand Down
15 changes: 12 additions & 3 deletions lib/gitlab/request.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ class Request
headers 'Accept' => 'application/json', 'Content-Type' => 'application/x-www-form-urlencoded'
parser(proc { |body, _| parse(body) })

attr_accessor :private_token, :endpoint
attr_accessor :private_token, :endpoint, :pat_prefix

# Converts the response body to an ObjectifiedHash.
def self.parse(body)
Expand Down Expand Up @@ -93,10 +93,19 @@ def request_defaults(sudo = nil)
def authorization_header
raise Error::MissingCredentials, 'Please provide a private_token or auth_token for user' unless private_token

if private_token.size < 21
# The Personal Access Token prefix can be at most 20 characters, and the
# generated part is of length 20 characters. Personal Access Tokens, thus
# can have a maximum size of 40 characters. GitLab uses
# `Doorkeeper::OAuth::Helpers::UniqueToken.generate` for generating
# OAuth2 tokens, and specified `hex` as token generator method. Thus, the
# OAuth2 tokens are of length more than 64. If the token length is below
# that, it is probably a Personal Access Token or CI_JOB_TOKEN.
if private_token.size >= 64
{ 'Authorization' => "Bearer #{private_token}" }
elsif private_token.start_with?(pat_prefix.to_s)
{ 'PRIVATE-TOKEN' => private_token }
else
{ 'Authorization' => "Bearer #{private_token}" }
{ 'JOB-TOKEN' => private_token }
end
end

Expand Down

0 comments on commit 26edb1b

Please sign in to comment.