Class: Aha::Auth::TokenCache

Inherits:
Object
  • Object
show all
Defined in:
lib/aha/auth/token_cache.rb

Overview

Caches JWKS public keys for JWT verification

Instance Method Summary collapse

Constructor Details

#initialize(ttl:) ⇒ TokenCache

Returns a new instance of TokenCache.



9
10
11
12
13
14
# File 'lib/aha/auth/token_cache.rb', line 9

def initialize(ttl:)
  @ttl = ttl
  @keys = {}
  @fetched_at = nil
  @mutex = Mutex.new
end

Instance Method Details

#clear!Object

Clear the cache



43
44
45
46
47
48
# File 'lib/aha/auth/token_cache.rb', line 43

def clear!
  @mutex.synchronize do
    @keys = {}
    @fetched_at = nil
  end
end

#get_key(kid, &fetcher) ⇒ OpenSSL::PKey::RSA?

Get a public key by key ID, fetching from server if not cached

Parameters:

  • kid (String)

    The key ID

  • fetcher (Proc)

    A proc that fetches the JWKS from the server

Returns:

  • (OpenSSL::PKey::RSA, nil)

    The public key or nil if not found



21
22
23
24
25
26
# File 'lib/aha/auth/token_cache.rb', line 21

def get_key(kid, &fetcher)
  @mutex.synchronize do
    refresh_if_needed(&fetcher)
    @keys[kid]
  end
end

#refresh!(&fetcher) ⇒ Object

Force a refresh of the JWKS cache

Parameters:

  • fetcher (Proc)

    A proc that fetches the JWKS from the server



31
32
33
34
35
# File 'lib/aha/auth/token_cache.rb', line 31

def refresh!(&fetcher)
  @mutex.synchronize do
    fetch_keys(&fetcher)
  end
end

#stale?Boolean

Check if the cache is stale

Returns:

  • (Boolean)


38
39
40
# File 'lib/aha/auth/token_cache.rb', line 38

def stale?
  @fetched_at.nil? || (Time.now.utc - @fetched_at) > @ttl
end