From 0bfb77c9af9ec0ad60d66d7680c1a05239a9dd2f Mon Sep 17 00:00:00 2001 From: Balasankar 'Balu' C Date: Tue, 30 May 2023 15:45:32 +0530 Subject: [PATCH] Support using CI_JOB_TOKEN for authentication Signed-off-by: Balasankar 'Balu' C --- lib/gitlab/configuration.rb | 3 ++- lib/gitlab/request.rb | 15 ++++++++++++--- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/lib/gitlab/configuration.rb b/lib/gitlab/configuration.rb index 8c3735429..bd7d7b45d 100644 --- a/lib/gitlab/configuration.rb +++ b/lib/gitlab/configuration.rb @@ -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}" @@ -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 diff --git a/lib/gitlab/request.rb b/lib/gitlab/request.rb index 218b81ba0..f1a01a30e 100644 --- a/lib/gitlab/request.rb +++ b/lib/gitlab/request.rb @@ -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) @@ -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