Class: Knievel::Auth::JwtFileTokenSource

Inherits:
Object
  • Object
show all
Defined in:
lib/knievel/auth/jwt_file_token_source.rb

Overview

File-backed bearer-token source for k8s ServiceAccount tokens (kubelet rewrites the file every few minutes; see “Recommended path: Kubernetes SA tokens” in ‘MIGRATION_RX.md`).

Re-reads the file at most once per ‘ttl_seconds` so we don’t hit disk on every API call. The cached value is invalidated on TTL expiry, but file rewrites in between are not picked up — ‘ttl_seconds` is the upper bound on how stale a token can be when the rotation happens. 30 s matches what the rx initializer was doing manually and is well under the typical kubelet rotation window.

Constant Summary collapse

DEFAULT_TTL_SECONDS =
30

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path, ttl_seconds: DEFAULT_TTL_SECONDS, clock: -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) }) ⇒ JwtFileTokenSource

Returns a new instance of JwtFileTokenSource.



22
23
24
25
26
27
28
29
# File 'lib/knievel/auth/jwt_file_token_source.rb', line 22

def initialize(path, ttl_seconds: DEFAULT_TTL_SECONDS, clock: -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) })
  @path = path
  @ttl_seconds = ttl_seconds
  @clock = clock
  @cached_token = nil
  @cached_at = nil
  @monitor = Monitor.new
end

Instance Attribute Details

#pathObject (readonly)

Returns the value of attribute path.



31
32
33
# File 'lib/knievel/auth/jwt_file_token_source.rb', line 31

def path
  @path
end

Instance Method Details

#to_procObject

Returns a ‘Proc` suitable for assignment to `Knievel::Configuration#access_token_getter`.



46
47
48
# File 'lib/knievel/auth/jwt_file_token_source.rb', line 46

def to_proc
  method(:token).to_proc
end

#tokenObject



33
34
35
36
37
38
39
40
41
42
# File 'lib/knievel/auth/jwt_file_token_source.rb', line 33

def token
  @monitor.synchronize do
    now = @clock.call
    if @cached_at.nil? || (now - @cached_at) >= @ttl_seconds
      @cached_token = File.read(@path).strip
      @cached_at = now
    end
    @cached_token
  end
end