keycardai-oauth 0.17.1 → 0.18.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: f8ea26ce58ef5fe06ab2c0a381bd0612e14426594904e00cfd0a2611c1c0d468
4
- data.tar.gz: aef6b5afdaabcd72cedb139080ff153a1327adc9ff7cfa51f9ab73eaa1f795e3
3
+ metadata.gz: d36a74f13e0df16a28c0a6251c8205776c0f8de329727ce18fcb2b9fdcce9dfc
4
+ data.tar.gz: a134012f91636e35412122424dfd4faf801a7dcfcbe352d40015d5eaa6c1c1c3
5
5
  SHA512:
6
- metadata.gz: 12949b72e931ff0eaea9b1d9ee920dc7b582b84164e4350a45797c3639e8a00f6efe285f4dbd7fd3d4d317e6de2bf797bd33549f7e4ff492f190605f1aea98bf
7
- data.tar.gz: 2e516f15ee72120de6fcfc00b9ddc825f8bfb6d27ea2b0d1694828d09accd8493d4b11e9c1afe017ba087c23a50978b80ceaa24510f1767c8b796c997046921c
6
+ metadata.gz: 9f39ade6e67f37d03307bc2150d8bb65e1a137b5d24abb7438528a533dd2ac243eaa9fddf96881b01aea22d82d08ee74f8f6e218a7e2fe7512caf1e27bffff0f
7
+ data.tar.gz: 627daa71857429430c8a536755c663d641fee788380f9033d438998a39afbf6d3ea9221e6315dc0c25df7e70ff735c59cd344fa05a4ac2c613e181a72a323734
data/CHANGELOG.md CHANGED
@@ -15,6 +15,15 @@ the loopback flow (RFC 8252), JWT signing and verification with a caching JWKS
15
15
  keyring, the three application credentials (ClientSecret with multi-zone,
16
16
  WebIdentity, WorkloadIdentity with pluggable token sources), and AccessContext.
17
17
 
18
+ ## 0.18.1-keycardai-oauth (2026-12-03)
19
+ - fix(keycardai-oauth): JWKS sets with entries the keyring cannot use (SDK-190) (#142)
20
+
21
+ ## 0.18.0-keycardai-oauth (2026-11-26)
22
+
23
+
24
+ - feat(keycardai-oauth): add RFC 7662 token introspection (#132)
25
+ - Adds introspect_token to keycardai-oauth per keycard-sdk-spec token-introspection v1 (spec#100), and types introspection_endpoint and introspection_endpoint_auth_methods_supported on AuthorizationServerMetadata (ID-881).
26
+
18
27
  ## 0.17.1-keycardai-oauth (2026-11-26)
19
28
 
20
29
 
data/README.md CHANGED
@@ -178,6 +178,31 @@ Pass `metadata:` to reuse discovery results. The server must advertise a
178
178
  `revocation_endpoint`. The operation returns `nil` on HTTP 200, even for
179
179
  unknown, expired, or already revoked tokens. It does not retry.
180
180
 
181
+ ### Introspect a token
182
+
183
+ Use a confidential client credential to check whether an access or refresh
184
+ token is active (RFC 7662).
185
+
186
+ ```ruby
187
+ credential = Keycardai::OAuth::ClientSecret.new(
188
+ ENV.fetch("KEYCARD_CLIENT_ID"),
189
+ ENV.fetch("KEYCARD_CLIENT_SECRET"),
190
+ )
191
+
192
+ result = Keycardai::OAuth.introspect_token(
193
+ "https://your-zone.keycard.cloud",
194
+ token: token_to_check,
195
+ credential: credential,
196
+ )
197
+ puts result.active
198
+ ```
199
+
200
+ The server must advertise an `introspection_endpoint`. Pass `metadata:` to
201
+ reuse discovery results. An inactive token returns `active: false` without
202
+ raising an error. Active results expose standard claims through readers such
203
+ as `result.scope` and preserve extra claims in `result.raw`. Results are not
204
+ cached, and requests are not retried automatically.
205
+
181
206
  ### Sign in a device with no browser
182
207
 
183
208
  The device authorization grant (RFC 8628) gets a token for a person on a
@@ -8,7 +8,7 @@ module Keycardai
8
8
  #
9
9
  # Credentials used with ClientCredentialsClient must implement this method.
10
10
  # It is also required when a credential is used for device authorization,
11
- # authorization code exchange with PKCE, token refresh, or token revocation.
11
+ # authorization code exchange with PKCE, token refresh, revocation, or introspection.
12
12
  #
13
13
  # It never includes a grant parameter such as grant_type or
14
14
  # subject_token_type. The caller merges it into its own request.
@@ -17,6 +17,7 @@ module Keycardai
17
17
  :issuer, :token_endpoint, :authorization_endpoint, :jwks_uri, :registration_endpoint,
18
18
  :userinfo_endpoint, :end_session_endpoint, :device_authorization_endpoint,
19
19
  :revocation_endpoint, :revocation_endpoint_auth_methods_supported,
20
+ :introspection_endpoint, :introspection_endpoint_auth_methods_supported,
20
21
  :grant_types_supported, :token_endpoint_auth_methods_supported, :response_types_supported, :raw
21
22
  ) do
22
23
  # Every member but +issuer+ defaults to nil, and +raw+ to an empty
@@ -25,7 +26,8 @@ module Keycardai
25
26
  def initialize(issuer:, token_endpoint: nil, authorization_endpoint: nil, jwks_uri: nil,
26
27
  registration_endpoint: nil, userinfo_endpoint: nil, end_session_endpoint: nil,
27
28
  device_authorization_endpoint: nil, revocation_endpoint: nil,
28
- revocation_endpoint_auth_methods_supported: nil, grant_types_supported: nil,
29
+ revocation_endpoint_auth_methods_supported: nil, introspection_endpoint: nil,
30
+ introspection_endpoint_auth_methods_supported: nil, grant_types_supported: nil,
29
31
  token_endpoint_auth_methods_supported: nil, response_types_supported: nil, raw: {})
30
32
  super
31
33
  end
@@ -1,7 +1,9 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "base64"
3
4
  require "json"
4
5
  require "jwt"
6
+ require "openssl"
5
7
  require "uri"
6
8
 
7
9
  module Keycardai
@@ -61,7 +63,7 @@ module Keycardai
61
63
  # @raise [JWKSDiscoveryError] discovery failed or metadata has no jwks_uri
62
64
  # @raise [JWKSUriValidationError] jwks_uri is cross-origin with the issuer
63
65
  # @raise [JWKSFetchError] the JWKS endpoint failed
64
- # @raise [JWKSKeyNotFoundError] the kid is absent from the fetched JWKS
66
+ # @raise [JWKSKeyNotFoundError] the fetched JWKS has no usable key for the kid
65
67
  def key(issuer, kid)
66
68
  cached = @mutex.synchronize { fresh_key(issuer, kid) }
67
69
  return cached if cached
@@ -109,28 +111,38 @@ module Keycardai
109
111
  end
110
112
 
111
113
  def resolve(issuer, kid)
112
- jwks_uri = resolve_jwks_uri(issuer)
113
- jwk = key_from_set(issuer, kid, jwks_uri)
114
+ key = key_from_set(kid, resolve_jwks_uri(issuer))
115
+ raise JWKSKeyNotFoundError, "kid #{kid.inspect} not found in JWKS for #{issuer}" unless key
114
116
 
115
- key = import_key(jwk)
116
- cache_key(issuer, kid, key)
117
- key
117
+ key.tap { cache_key(issuer, kid, key) }
118
118
  end
119
119
 
120
- # The cached key set first: a kid it holds imports with no fetch, and a kid
121
- # it lacks refetches at most once per cooldown, so a rotated-in key is found
122
- # once the cooldown has passed.
123
- def key_from_set(issuer, kid, jwks_uri)
124
- cached = fresh_key_set(jwks_uri)
125
- if cached
126
- jwk = cached[:keys].find { |candidate| candidate["kid"] == kid }
127
- return jwk if jwk
128
-
129
- raise_not_found(issuer, kid) if now - cached[:fetched_at] < @refetch_cooldown
120
+ # Try the cached set first. If it has no usable key for the kid, refetch
121
+ # at most once per cooldown so a rotated-in key can be found.
122
+ def key_from_set(kid, jwks_uri)
123
+ if (cached = fresh_key_set(jwks_uri))
124
+ key = find_key(cached[:keys], kid)
125
+ return key if key || now - cached[:fetched_at] < @refetch_cooldown
130
126
  end
131
127
 
132
- keys = refresh_jwks(jwks_uri)
133
- keys.find { |candidate| candidate["kid"] == kid } || raise_not_found(issuer, kid)
128
+ find_key(refresh_jwks(jwks_uri), kid)
129
+ end
130
+
131
+ def find_key(keys, kid)
132
+ keys.lazy.grep(Hash).filter_map do |jwk|
133
+ next unless [jwk["kid"], jwk["kty"], jwk.fetch("use", "sig"),
134
+ jwk.fetch("alg", "RS256")] == [kid, "RSA", "sig", "RS256"]
135
+
136
+ next unless (parameters = jwk.values_at("n", "e")).all?(/\A[A-Za-z0-9_-]+={0,2}\z/)
137
+
138
+ Base64.urlsafe_decode64(parameters.first)
139
+ Base64.urlsafe_decode64(parameters.last)
140
+
141
+ key = JWT::JWK.import(jwk.transform_keys(&:to_sym)).verify_key
142
+ key if key.is_a?(OpenSSL::PKey::RSA)
143
+ rescue JWT::DecodeError, OpenSSL::OpenSSLError, ArgumentError
144
+ nil
145
+ end.first
134
146
  end
135
147
 
136
148
  def refresh_jwks(jwks_uri)
@@ -149,10 +161,6 @@ module Keycardai
149
161
  end
150
162
  end
151
163
 
152
- def raise_not_found(issuer, kid)
153
- raise JWKSKeyNotFoundError, "kid #{kid.inspect} not found in JWKS for #{issuer}"
154
- end
155
-
156
164
  def resolve_jwks_uri(issuer)
157
165
  cached = @mutex.synchronize do
158
166
  entry = @discovery[issuer]
@@ -205,12 +213,6 @@ module Keycardai
205
213
  raise JWKSFetchError, "JWKS fetch from #{jwks_uri} returned HTTP #{response.status}", cause: error
206
214
  end
207
215
 
208
- def import_key(jwk)
209
- JWT::JWK.import(jwk.transform_keys(&:to_sym)).verify_key
210
- rescue JWT::JWKError, ArgumentError
211
- raise JWKSKeyNotFoundError, "JWK with kid #{jwk["kid"].inspect} could not be converted to a verification key"
212
- end
213
-
214
216
  def cache_key(issuer, kid, key)
215
217
  @mutex.synchronize do
216
218
  @keys.shift while @keys.size >= MAX_CACHED_KEYS
@@ -0,0 +1,115 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "uri"
5
+
6
+ module Keycardai
7
+ # Token introspection (RFC 7662).
8
+ module OAuth
9
+ # An RFC 7662 result. Optional claims are nil when absent. +scope+ is a
10
+ # list of scopes, and +iat+ and +exp+ are Unix seconds. +raw+ preserves
11
+ # the wire claims, including claims without dedicated readers.
12
+ TokenIntrospection = Data.define(:active, :token_type, :iss, :sub, :client_id, :aud,
13
+ :scope, :sid, :jti, :iat, :exp, :raw) do
14
+ def initialize(active:, token_type: nil, iss: nil, sub: nil, client_id: nil, aud: nil,
15
+ scope: nil, sid: nil, jti: nil, iat: nil, exp: nil, raw: {})
16
+ super
17
+ end
18
+
19
+ # @param claim [String] a claim name
20
+ # @return [Object, nil] the claim's wire value
21
+ def [](claim)
22
+ raw[claim]
23
+ end
24
+ end
25
+
26
+ # Check a token's current status with its authorization server (RFC 7662).
27
+ # An inactive token is a successful result. Results are not cached.
28
+ #
29
+ # @param issuer [String, nil] the HTTPS zone issuer URL
30
+ # @param token [String] an access token or refresh token
31
+ # @param credential [#client_authentication] confidential client credential
32
+ # @param metadata [AuthorizationServerMetadata, nil] pre-discovered metadata
33
+ # @param token_type_hint [String, nil] optional hint sent as provided
34
+ # @param http_client [#get, #post_form] pluggable transport
35
+ # @param timeout [Numeric, nil] request timeout in seconds
36
+ # @return [TokenIntrospection]
37
+ # @raise [ConfigurationError] invalid inputs or missing or invalid introspection endpoint
38
+ # @raise [OAuthError, HTTPError, ProtocolError, NetworkError]
39
+ def self.introspect_token(issuer = nil, token: nil, credential: nil, metadata: nil, token_type_hint: nil,
40
+ http_client: HTTP::NetHTTPClient.new, timeout: nil)
41
+ raise ConfigurationError, "token must be a non-empty string" unless token.is_a?(String) && !token.empty?
42
+ raise ConfigurationError, "token introspection requires a credential" unless credential
43
+
44
+ ClientAuth.validate(credential: credential, client_id: nil)
45
+ metadata, issuer = Introspection.resolve_metadata(issuer, metadata, http_client: http_client, timeout: timeout)
46
+ params = [["token", token]]
47
+ params << ["token_type_hint", token_type_hint] unless token_type_hint.nil?
48
+ Introspection.post(metadata, params, issuer: issuer, credential: credential, http_client: http_client,
49
+ timeout: timeout)
50
+ end
51
+
52
+ # Internal request and response handling for token introspection.
53
+ module Introspection
54
+ module_function
55
+
56
+ def resolve_metadata(issuer, metadata, http_client:, timeout:)
57
+ if metadata
58
+ zone = require_https_url(metadata.issuer, "metadata issuer")
59
+ matches = issuer.is_a?(String) && issuer.chomp("/") == zone.chomp("/")
60
+ return [metadata, issuer || zone] if issuer.nil? || matches
61
+
62
+ raise ConfigurationError, "issuer does not match the metadata issuer"
63
+ end
64
+
65
+ discovered = OAuth.fetch_authorization_server_metadata(require_https_url(issuer, "issuer"),
66
+ http_client: http_client, timeout: timeout)
67
+ [discovered, discovered.issuer]
68
+ end
69
+
70
+ def require_https_url(url, field)
71
+ uri = URI.parse(url) if url.is_a?(String)
72
+ return url if uri.is_a?(URI::HTTPS) && !uri.host.to_s.empty?
73
+
74
+ raise ConfigurationError, "#{field} must be an HTTPS URL"
75
+ rescue URI::InvalidURIError
76
+ raise ConfigurationError, "#{field} must be an HTTPS URL"
77
+ end
78
+
79
+ def post(metadata, params, issuer:, credential:, http_client:, timeout:)
80
+ endpoint = require_https_url(metadata.introspection_endpoint, "introspection_endpoint")
81
+ params, headers = ClientAuth.apply(params, { "Accept" => "application/json" },
82
+ issuer: issuer, endpoint: metadata.issuer, credential: credential)
83
+ parse_response(http_client.post_form(endpoint, params, headers: headers, timeout: timeout))
84
+ end
85
+
86
+ def parse_response(response)
87
+ raise TokenRequests.error_for(response, endpoint_name: "introspection endpoint") unless response.status == 200
88
+
89
+ document = JSON.parse(response.body)
90
+ raise invalid_response("introspection response is not a JSON object") unless document.is_a?(Hash)
91
+
92
+ case document["active"]
93
+ when true then active_result(document)
94
+ when false then TokenIntrospection.new(active: false, raw: { "active" => false })
95
+ else raise invalid_response("introspection response must contain a boolean active field")
96
+ end
97
+ rescue JSON::ParserError
98
+ raise invalid_response("introspection response is not valid JSON")
99
+ end
100
+
101
+ def active_result(document)
102
+ scope = document["scope"]
103
+ raise invalid_response("introspection response scope is not a string") unless scope.nil? || scope.is_a?(String)
104
+
105
+ fields = (TokenIntrospection.members - [:raw]).to_h { |name| [name, document[name.to_s]] }
106
+ TokenIntrospection.new(**fields, scope: scope&.split, raw: document)
107
+ end
108
+
109
+ def invalid_response(message)
110
+ ProtocolError.new(message, code: "invalid_response", status: 200)
111
+ end
112
+ end
113
+ private_constant :Introspection
114
+ end
115
+ end
@@ -2,6 +2,6 @@
2
2
 
3
3
  module Keycardai
4
4
  module OAuth
5
- VERSION = "0.17.1"
5
+ VERSION = "0.18.1"
6
6
  end
7
7
  end
@@ -15,6 +15,7 @@ require_relative "oauth/substitute_user"
15
15
  require_relative "oauth/pkce"
16
16
  require_relative "oauth/authorization_code"
17
17
  require_relative "oauth/token_revocation"
18
+ require_relative "oauth/token_introspection"
18
19
  require_relative "oauth/authenticate"
19
20
  require_relative "oauth/registration"
20
21
  require_relative "oauth/client_secret"
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: keycardai-oauth
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.17.1
4
+ version: 0.18.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Keycard
@@ -63,6 +63,7 @@ files:
63
63
  - lib/keycardai/oauth/substitute_user.rb
64
64
  - lib/keycardai/oauth/token_exchange_client.rb
65
65
  - lib/keycardai/oauth/token_exchange_form.rb
66
+ - lib/keycardai/oauth/token_introspection.rb
66
67
  - lib/keycardai/oauth/token_requests.rb
67
68
  - lib/keycardai/oauth/token_revocation.rb
68
69
  - lib/keycardai/oauth/token_sources.rb