Class: HasHelpers::ServiceTrust::JwksClient

Inherits:
Object
  • Object
show all
Defined in:
lib/has_helpers/service_trust/jwks_client.rb

Defined Under Namespace

Classes: CacheEntry

Constant Summary collapse

NETWORK_ERRORS =
[
  Errno::ECONNREFUSED, Errno::ECONNRESET, Errno::EHOSTUNREACH,
  Errno::ENETUNREACH, Errno::ETIMEDOUT, EOFError, IOError,
  SocketError, Timeout::Error,
  Net::OpenTimeout, Net::ReadTimeout, Net::HTTPError,
  OpenSSL::SSL::SSLError
].freeze

Class Method Summary collapse

Class Method Details

.clear_cache!Object



58
59
60
# File 'lib/has_helpers/service_trust/jwks_client.rb', line 58

def clear_cache!
  monitor.synchronize { memory_cache.clear }
end

.fetch_keys_for(issuer) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/has_helpers/service_trust/jwks_client.rb', line 34

def fetch_keys_for(issuer)
  trusted = HasHelpers::ServiceTrust.config.trusted_issuer(issuer)
  raise UntrustedIssuerError, "untrusted issuer" unless trusted

  cache_key = issuer.to_s

  fresh = monitor.synchronize { cache_hit(cache_key) }
  return fresh if fresh

  begin
    fetch_and_cache(cache_key, trusted.url)
  rescue *NETWORK_ERRORS => e
    stale = monitor.synchronize { stale_hit(cache_key) }
    return stale if stale

    raise JwksUnavailableError, "jwks fetch failed: #{e.class}: #{e.message}"
  rescue OutboundTLSError, JwksUnavailableError
    stale = monitor.synchronize { stale_hit(cache_key) }
    return stale if stale

    raise
  end
end

.public_key_for(issuer, kid) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
# File 'lib/has_helpers/service_trust/jwks_client.rb', line 22

def public_key_for(issuer, kid)
  stub = Test.public_key_for(issuer, kid) if Test.enabled?
  return stub if stub

  jwk = fetch_keys_for(issuer).find { |key| key["kid"] == kid.to_s }
  raise InvalidSignatureError, "unknown key id" unless jwk

  JWT::JWK.import(jwk).public_key
rescue JWT::JWKError => e
  raise InvalidSignatureError, e.message
end