class Conjur::Authenticator

Keeps a fresh Conjur access token in a named file by re-authenticating as needed.

Constants

DELAY
TOKEN_LIFESPAN

Attributes

authenticate[R]
filename[R]

Public Class Methods

default_filename() click to toggle source
# File lib/conjur/authenticator.rb, line 20
def default_filename
  "/run/conjur-access-token"
end
new(authenticate, filename) click to toggle source

authenticate should be a proc that authenticates with Conjur and returns an access token as a Hash.

# File lib/conjur/authenticator.rb, line 14
def initialize authenticate, filename
  @authenticate = authenticate
  @filename = filename
end
run(authenticate:, filename: default_filename) click to toggle source

Check the token every DELAY seconds and refresh it if it’s out of date.

# File lib/conjur/authenticator.rb, line 25
def run authenticate:, filename: default_filename
  while true
    authenticator = Authenticator.new(authenticate, filename)
    authenticator.refresh unless authenticator.fresh?
    sleep DELAY
  end
end

Public Instance Methods

fresh?() click to toggle source
# File lib/conjur/authenticator.rb, line 34
def fresh?
  token && (token_age <= TOKEN_LIFESPAN)
end
refresh() click to toggle source

Perform atomic replacement of the token

# File lib/conjur/authenticator.rb, line 39
def refresh
  token = authenticate.call
  file = Tempfile.new('conjur-access-token.')
  begin
    file.write JSON.pretty_generate(token)
    file.close
    FileUtils.mv file.path, filename
    Conjur.log << "Refreshed Conjur auth token to #{filename.inspect}\n" if Conjur.log
  ensure
    file.unlink
  end
rescue
  $stderr.puts $!
end
token() click to toggle source
# File lib/conjur/authenticator.rb, line 54
def token
  return false if @token == false
  @token ||= load_token
end

Protected Instance Methods

directory() click to toggle source
# File lib/conjur/authenticator.rb, line 66
def directory
  File.dirname(filename)
end
load_token() click to toggle source
# File lib/conjur/authenticator.rb, line 70
def load_token
  return false unless File.file?(filename)
  JSON.parse(File.read(filename)) rescue false
end
random(nbytes = 12) click to toggle source
# File lib/conjur/authenticator.rb, line 61
def random nbytes = 12
  @random ||= Random.new
  @random.bytes(nbytes).unpack('h*').first
end
token_age() click to toggle source
# File lib/conjur/authenticator.rb, line 79
def token_age
  Time.now - token_born
end
token_born() click to toggle source
# File lib/conjur/authenticator.rb, line 75
def token_born
  File.mtime(filename)
end