Skip to content

Commit

Permalink
refresh bearer token from file to avoid stale tokens when using mount…
Browse files Browse the repository at this point in the history
…ed service account token
  • Loading branch information
grosser committed Jan 21, 2022
1 parent e0aac1e commit 276b11b
Showing 1 changed file with 17 additions and 9 deletions.
26 changes: 17 additions & 9 deletions lib/kubeclient.rb
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,6 @@ def initialize_client(
bearer_token(@auth_options[:bearer_token])
elsif auth_options[:bearer_token_file]
validate_bearer_token_file
bearer_token(File.read(@auth_options[:bearer_token_file]))
end
end

Expand Down Expand Up @@ -358,6 +357,12 @@ def create_faraday_client(url = nil)
if @auth_options[:username] && @auth_options[:password]
connection.basic_auth(@auth_options[:username], @auth_options[:password])
end

refresh_bearer_token_from_file
if (auth = @headers[:Authorization])
connection.headers['Authorization'] = auth
end

# hook for adding custom faraday configuration
yield(connection) if block_given?
connection.use(FaradayMiddleware::FollowRedirects, limit: @http_max_redirects)
Expand All @@ -366,9 +371,7 @@ def create_faraday_client(url = nil)
end

def faraday_client
@faraday_client ||= begin
create_faraday_client
end
@faraday_client ||= create_faraday_client
end

# Accepts the following options:
Expand Down Expand Up @@ -695,11 +698,9 @@ def validate_auth_options(opts)
end

def validate_bearer_token_file
msg = "Token file #{@auth_options[:bearer_token_file]} does not exist"
raise ArgumentError, msg unless File.file?(@auth_options[:bearer_token_file])

msg = "Cannot read token file #{@auth_options[:bearer_token_file]}"
raise ArgumentError, msg unless File.readable?(@auth_options[:bearer_token_file])
file = @auth_options[:bearer_token_file]
raise ArgumentError, "Token file #{file} does not exist" unless File.file?(file)
raise ArgumentError, "Token file #{file} cannot be read" unless File.readable?(file)
end

def return_or_yield_to_watcher(watcher, &block)
Expand All @@ -713,6 +714,8 @@ def return_or_yield_to_watcher(watcher, &block)
end

def http_options(uri)
refresh_bearer_token_from_file

options = {
basic_auth_user: @auth_options[:username],
basic_auth_password: @auth_options[:password],
Expand All @@ -736,6 +739,11 @@ def http_options(uri)
options.merge(@socket_options)
end

def refresh_bearer_token_from_file
return unless (file = @auth_options[:bearer_token_file])
bearer_token(File.read(file))
end

def json_headers
{ 'Content-Type' => 'application/json' }.merge(@headers)
end
Expand Down

0 comments on commit 276b11b

Please sign in to comment.