Class: Conjur::Authenticator

Inherits:
Object
  • Object
show all
Defined in:
lib/conjur/authenticator.rb

Overview

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

Constant Summary collapse

TOKEN_LIFESPAN =
( ENV['CONJUR_TOKEN_LIFESPAN'] || 5 * 60 ).to_i.seconds
DELAY =
( ENV['CONJUR_TOKEN_REFRESH_DELAY'] || 10 ).to_i.seconds

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(authenticate, filename) ⇒ Authenticator

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



14
15
16
17
# File 'lib/conjur/authenticator.rb', line 14

def initialize authenticate, filename
  @authenticate = authenticate
  @filename = filename
end

Instance Attribute Details

#authenticateObject (readonly)

Returns the value of attribute authenticate.



10
11
12
# File 'lib/conjur/authenticator.rb', line 10

def authenticate
  @authenticate
end

#filenameObject (readonly)

Returns the value of attribute filename.



10
11
12
# File 'lib/conjur/authenticator.rb', line 10

def filename
  @filename
end

Class Method Details

.default_filenameObject



20
21
22
# File 'lib/conjur/authenticator.rb', line 20

def default_filename
  "/run/conjur-access-token"
end

.run(authenticate:, filename: default_filename) ⇒ Object

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



25
26
27
28
29
30
31
# 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

Instance Method Details

#fresh?Boolean

Returns:

  • (Boolean)


34
35
36
# File 'lib/conjur/authenticator.rb', line 34

def fresh?
  token && (token_age <= TOKEN_LIFESPAN)
end

#refreshObject

Perform atomic replacement of the token



39
40
41
42
43
44
45
46
47
48
49
50
51
52
# 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

#tokenObject



54
55
56
57
# File 'lib/conjur/authenticator.rb', line 54

def token
  return false if @token == false
  @token ||= load_token
end