keycardai-oauth 0.17.0 → 0.18.0

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: c719d8515dd3a5993acfada29fe6dc65f2391964ea44d97a17c1a5c256622122
4
- data.tar.gz: 8b20cf6ed5f14fccd4f33249b22beaf61bf10bc29f614cdd23a31790c61de841
3
+ metadata.gz: 7323b08ecc145c0bafc58a6bd60601d1bddc03f5fd882ca601fbc2fcc28e8c60
4
+ data.tar.gz: 5f0c548850c689e7e36c2924a0af3322060043e12fbf4ef1c62eee148e8473b9
5
5
  SHA512:
6
- metadata.gz: cf9c56ee56533cbbbd0036cc0ac8c2676691beebdece8702ecb3872cb4280dec0d5ce9f5f49e3ff63ce1880322818ae3be275f529f616fb7c19212e2f976b7b5
7
- data.tar.gz: 3d4d3a8688daa918437d67d143dce221bb7d27084287201fb5e614767b1220204e021fd208feb18faac89a7495755978553fc76f1a4d729f8839cbcc4a381ddc
6
+ metadata.gz: e2a497de6c213f57b042c389b9a87c89b51706b52cb66fb0c3b27c540764dfde854c86d761abe8edb80d19082d6fab3ef55e10b61e9f73a3ffb4e286a4dfdfa2
7
+ data.tar.gz: 6a16f864d5c8c516fd46ffba05cb1a1759b0be7cb971ce2a9066f19191eebaf601605892fba2ff53885fcbf70c38571d422fcb1db7e0cd1ef07c5f35bb450661
data/CHANGELOG.md CHANGED
@@ -15,6 +15,26 @@ 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.0-keycardai-oauth (2026-11-26)
19
+
20
+
21
+ - feat(keycardai-oauth): add RFC 7662 token introspection (#132)
22
+ - 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).
23
+
24
+ ## 0.17.1-keycardai-oauth (2026-11-26)
25
+
26
+
27
+ - fix(keycardai-oauth): the request timeout bounds the credential call and the whole request (SDK-121) (#120)
28
+ - * fix(keycardai-oauth): the request timeout bounds the credential call and the whole request (SDK-121)
29
+ - * fix(keycardai-oauth): account for proxy lookup before connecting (SDK-121)
30
+ - * fix(keycardai-oauth): return complete responses after the deadline (SDK-121)
31
+ - * fix(keycardai-oauth): require explicit credential timeout keywords (SDK-121)
32
+ - * fix(keycardai-oauth): scope the request deadline to the device grant (SDK-121)
33
+ - * test(keycardai-oauth): leave the forwarding example unnumbered (SDK-121)
34
+ - * fix(keycardai-oauth): reflect on credential methods without dispatch (SDK-121)
35
+ - ---------
36
+ - Co-authored-by: devin-ai-keycard <devin-ai@keycard.ai>
37
+
18
38
  ## 0.17.0-keycardai-oauth (2026-11-26)
19
39
 
20
40
 
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.
@@ -68,9 +68,9 @@ module Keycardai
68
68
  # repeated keys such as resource survive
69
69
  # @param headers [Hash{String => String}]
70
70
  # @return [Array(Array<Array(String, String)>, Hash{String => String})]
71
- def apply(params, headers, issuer:, endpoint:, credential: nil, client_id: nil, client_secret: nil)
71
+ def apply(params, headers, issuer:, endpoint:, credential: nil, client_id: nil, client_secret: nil, options: {})
72
72
  if credential
73
- auth = credential.client_authentication(issuer: issuer, endpoint: endpoint)
73
+ auth = credential.client_authentication(issuer: issuer, endpoint: endpoint, **options)
74
74
  [params + auth.params.to_a, headers.merge(auth.headers)]
75
75
  elsif client_secret
76
76
  [params, headers.merge("Authorization" => HTTP.basic_authorization(client_id, client_secret))]
@@ -0,0 +1,87 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Keycardai
4
+ module OAuth
5
+ module HTTP
6
+ # Net::HTTP can read multiple times before yielding a body chunk, for
7
+ # example while parsing a header or the framing around a chunk.
8
+ module DeadlineSocket
9
+ attr_writer :deadline_session
10
+
11
+ def read_nonblock(...)
12
+ request_deadline&.remaining
13
+ super
14
+ end
15
+
16
+ def write_nonblock(...)
17
+ request_deadline&.remaining
18
+ super
19
+ end
20
+
21
+ def wait_readable(timeout = nil)
22
+ super(bounded_wait(timeout))
23
+ end
24
+
25
+ def wait_writable(timeout = nil)
26
+ super(bounded_wait(timeout))
27
+ end
28
+
29
+ private
30
+
31
+ def request_deadline
32
+ @deadline_session.request_deadline
33
+ end
34
+
35
+ def bounded_wait(timeout)
36
+ remaining = request_deadline&.remaining
37
+ [timeout, remaining].compact.min
38
+ end
39
+ end
40
+ private_constant :DeadlineSocket
41
+
42
+ # Applies a fresh budget to connections and sockets on a reused session.
43
+ module DeadlineSession
44
+ attr_accessor :request_deadline
45
+
46
+ def start_with_deadline(deadline)
47
+ self.request_deadline = deadline
48
+ apply_deadline
49
+ start unless started?
50
+ apply_deadline
51
+ end
52
+
53
+ private
54
+
55
+ def apply_deadline
56
+ remaining = request_deadline.remaining
57
+ self.open_timeout = self.read_timeout = self.write_timeout = remaining
58
+ end
59
+
60
+ def connect
61
+ # Proxy selection can resolve the destination before Net::HTTP opens
62
+ # a socket. Cache the selection before setting the connect budget.
63
+ proxy_uri if proxy_from_env?
64
+ apply_deadline
65
+ super
66
+ bound_socket(@socket.io)
67
+ end
68
+
69
+ def timeouted_connect(...)
70
+ super.tap { |socket| bound_socket(socket) }
71
+ end
72
+
73
+ def ssl_socket_connect(socket, _timeout)
74
+ super(socket, request_deadline.remaining)
75
+ end
76
+
77
+ def bound_socket(socket)
78
+ [socket, socket.to_io].uniq.each do |io|
79
+ io.extend(DeadlineSocket)
80
+ io.deadline_session = self
81
+ end
82
+ end
83
+ end
84
+ private_constant :DeadlineSession
85
+ end
86
+ end
87
+ end
@@ -135,8 +135,11 @@ module Keycardai
135
135
  # @param client_id [String, nil] public client; sent in every body
136
136
  # @param http_client [#get, #post_form] pluggable transport
137
137
  # @param timeout [Numeric, nil] per-request timeout in seconds, for
138
- # discovery, the device authorization request, and each poll. nil
139
- # uses the transport's default, 10 seconds for NetHTTPClient.
138
+ # discovery, the device authorization request, and each poll. The
139
+ # device requests share their budget with client authentication.
140
+ # nil uses the transport's default, 10 seconds for NetHTTPClient.
141
+ # Credentials can accept a timeout in seconds or a deadline Time
142
+ # to stop cooperatively. Otherwise the client checks when they return.
140
143
  # @param clock [#call] returns the current Time; read for expires_at,
141
144
  # the poll waits, and the discovery cache
142
145
  # @param sleep [#call] waits the given number of seconds. Inject fakes
@@ -158,8 +161,8 @@ module Keycardai
158
161
  @issuer = resolve_issuer(issuer, metadata)
159
162
  @credential = credential
160
163
  @client_id = client_id
161
- @http_client = http_client
162
- @timeout = timeout
164
+ @request = DeviceRequest.new(issuer: @issuer, credential: credential, client_id: client_id,
165
+ http_client: http_client, timeout: timeout)
163
166
  @clock = clock
164
167
  @sleep = sleep
165
168
  @endpoints = DeviceEndpoints.new(issuer: @issuer, metadata: metadata, http_client: http_client,
@@ -324,13 +327,9 @@ module Keycardai
324
327
  end
325
328
 
326
329
  def post(endpoint, params)
327
- params, headers = authenticate(endpoint, params)
328
- @http_client.post_form(endpoint, params, headers: headers, timeout: @timeout)
329
- end
330
-
331
- def authenticate(endpoint, params)
332
- ClientAuth.apply(params, { "Accept" => "application/json" }, issuer: @issuer, endpoint: endpoint,
333
- credential: @credential, client_id: @client_id)
330
+ deadline = @request.deadline
331
+ params, headers = @request.authenticate(endpoint, params, @request.credential_options(deadline))
332
+ @request.send_form(endpoint, params, headers, deadline)
334
333
  end
335
334
 
336
335
  def starting_interval(authorization, interval)
@@ -373,10 +372,12 @@ module Keycardai
373
372
  # poll. The credential is called outside every rescue, so its failure
374
373
  # is raised as is.
375
374
  def poll_step(authorization, endpoint, interval, cancellation)
376
- params, headers = authenticate(endpoint, poll_params(authorization))
375
+ deadline = @request.deadline
376
+ options = with_poll_transport_errors(interval) { @request.credential_options(deadline) }
377
+ params, headers = @request.authenticate(endpoint, poll_params(authorization), options)
377
378
  cancellation.check
378
379
  check_expired(authorization)
379
- response = send_poll(endpoint, params, headers, interval)
380
+ response = with_poll_transport_errors(interval) { @request.send_form(endpoint, params, headers, deadline) }
380
381
  begin
381
382
  [TokenRequests.parse_response(response), interval]
382
383
  rescue HTTPError => e
@@ -384,8 +385,8 @@ module Keycardai
384
385
  end
385
386
  end
386
387
 
387
- def send_poll(endpoint, params, headers, interval)
388
- @http_client.post_form(endpoint, params, headers: headers, timeout: @timeout)
388
+ def with_poll_transport_errors(interval)
389
+ yield
389
390
  rescue NetworkError => e
390
391
  # RFC 8628 §3.5: wait longer after a connection timeout.
391
392
  raise DevicePollError.new("device token poll failed: #{e.message}", interval: interval * 2)
@@ -410,6 +411,39 @@ module Keycardai
410
411
  end
411
412
  end
412
413
 
414
+ # The credential step and the HTTP step draw from the same request budget.
415
+ class DeviceRequest
416
+ def initialize(issuer:, credential:, client_id:, http_client:, timeout:)
417
+ @issuer = issuer
418
+ @credential = credential
419
+ @client_id = client_id
420
+ @http_client = http_client
421
+ @timeout = timeout || (HTTP::NetHTTPClient::DEFAULT_TIMEOUT if http_client.is_a?(HTTP::NetHTTPClient))
422
+ end
423
+
424
+ def deadline
425
+ RequestDeadline.new(@timeout) if @timeout
426
+ end
427
+
428
+ def credential_options(deadline)
429
+ deadline&.credential_options(@credential) || {}
430
+ end
431
+
432
+ def authenticate(endpoint, params, options)
433
+ ClientAuth.apply(params, { "Accept" => "application/json" },
434
+ issuer: @issuer, endpoint: endpoint, credential: @credential, client_id: @client_id,
435
+ options: options)
436
+ end
437
+
438
+ def send_form(endpoint, params, headers, deadline)
439
+ remaining = deadline&.remaining
440
+ # Injected transports keep the numeric timeout interface.
441
+ timeout = @http_client.instance_of?(HTTP::NetHTTPClient) ? deadline : remaining
442
+ @http_client.post_form(endpoint, params, headers: headers, timeout: timeout)
443
+ end
444
+ end
445
+ private_constant :DeviceRequest
446
+
413
447
  # The device grant's two endpoints, from pre-discovered metadata or from
414
448
  # discovery. Discovered metadata is cached for +ttl+ seconds when both
415
449
  # endpoints are http or https URLs. Otherwise it is not cached, and the
@@ -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
@@ -5,6 +5,9 @@ require "net/http"
5
5
  require "uri"
6
6
  require "zlib"
7
7
 
8
+ require_relative "request_deadline"
9
+ require_relative "deadline_socket"
10
+
8
11
  module Keycardai
9
12
  module OAuth
10
13
  # Pluggable HTTP transport. Every network operation in the SDK goes
@@ -188,22 +191,19 @@ module Keycardai
188
191
  # Default transport backed by Net::HTTP. TLS is used for https URLs.
189
192
  #
190
193
  # Sessions are kept open and reused per instance, per thread, per
191
- # (host, port, scheme). A thread only ever touches its own sessions, so
192
- # the request path takes no lock; a small mutex guards only the registry
193
- # of per-thread session maps, and dead threads are swept from it whenever
194
- # it is touched. There is no transparent retry: a keepalive connection
195
- # the server dropped while idle surfaces as NetworkError on the next
196
- # request, the same as any other failure.
194
+ # (host, port, scheme, timeout policy). A thread only ever touches its own
195
+ # sessions, so the request path takes no lock; a small mutex guards only
196
+ # the registry of per-thread session maps, and dead threads are swept from
197
+ # it whenever it is touched. There is no transparent retry: a keepalive
198
+ # connection the server dropped while idle surfaces as NetworkError on the
199
+ # next request, the same as any other failure.
197
200
  #
198
201
  # Call {#close} when no requests are in flight to finish every session.
199
202
  # An instance that is never closed, such as the throwaway client built by
200
203
  # module-level function defaults, keeps its sessions until it is garbage
201
204
  # collected, which closes the underlying sockets.
202
205
  class NetHTTPClient
203
- # Open, read and write timeout for a request whose caller passed no
204
- # timeout: 10 seconds, so a request to the zone cannot wait for
205
- # Net::HTTP's 60. Each one bounds a single step of the request, such as
206
- # one read from the socket, not the whole request.
206
+ # Timeout in seconds when the caller supplies none.
207
207
  DEFAULT_TIMEOUT = 10
208
208
 
209
209
  # What a request raises when the connection or the response fails:
@@ -285,12 +285,15 @@ module Keycardai
285
285
  private
286
286
 
287
287
  def perform(uri, request, timeout)
288
- http = session_for(uri)
288
+ deadline = timeout.is_a?(RequestDeadline)
289
+ http = session_for(uri, deadline: deadline)
289
290
  configure_http(http, timeout, request)
290
291
  response, body, body_error = execute_request(http, request)
291
292
  build_response(response, body, body_error)
292
293
  rescue *TRANSPORT_ERRORS => e
293
294
  raise NetworkError, "request to #{uri.host} failed: #{e.class}"
295
+ ensure
296
+ http.request_deadline = nil if deadline && http
294
297
  end
295
298
 
296
299
  def execute_request(http, request)
@@ -311,10 +314,12 @@ module Keycardai
311
314
  end
312
315
 
313
316
  def configure_http(http, timeout, request)
314
- http.open_timeout = timeout || DEFAULT_TIMEOUT
315
- http.read_timeout = timeout || DEFAULT_TIMEOUT
316
- http.write_timeout = timeout || DEFAULT_TIMEOUT
317
- http.start unless http.started?
317
+ if timeout.is_a?(RequestDeadline)
318
+ http.start_with_deadline(timeout)
319
+ else
320
+ http.open_timeout = http.read_timeout = http.write_timeout = timeout || DEFAULT_TIMEOUT
321
+ http.start unless http.started?
322
+ end
318
323
  # Net::HTTP does not report a gzip stream that ends early, so the
319
324
  # client decompresses the body itself. Assigning Accept-Encoding
320
325
  # turns off Net::HTTP's decompression.
@@ -325,13 +330,14 @@ module Keycardai
325
330
  Response.new(status: response.code.to_i, headers: response.to_hash, body: body, body_error: body_error)
326
331
  end
327
332
 
328
- def session_for(uri)
333
+ def session_for(uri, deadline:)
329
334
  sessions = sessions_for_current_thread
330
- key = [uri.host, uri.port, uri.scheme]
335
+ key = [uri.host, uri.port, uri.scheme, deadline]
331
336
  http = sessions[key]
332
337
  return http if http&.started?
333
338
 
334
339
  http = Net::HTTP.new(uri.host, uri.port)
340
+ http.extend(DeadlineSession) if deadline
335
341
  http.use_ssl = uri.scheme == "https"
336
342
  # Net::HTTP retries a failed GET once by default.
337
343
  http.max_retries = 0
@@ -0,0 +1,47 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Keycardai
4
+ module OAuth
5
+ # One monotonic budget for a request, independent of wall-clock changes.
6
+ class RequestDeadline
7
+ def initialize(timeout)
8
+ @expires_at = monotonic_time + timeout
9
+ end
10
+
11
+ def remaining
12
+ seconds = @expires_at - monotonic_time
13
+ raise NetworkError, "request deadline exceeded" unless seconds.positive?
14
+
15
+ seconds
16
+ end
17
+
18
+ def credential_options(credential)
19
+ seconds = remaining
20
+ return {} unless credential
21
+
22
+ parameters = credential_parameters(credential)
23
+ options = {}
24
+ options[:deadline] = Time.now + seconds if accepts_keyword?(parameters, :deadline)
25
+ options[:timeout] = seconds if accepts_keyword?(parameters, :timeout)
26
+ options
27
+ end
28
+
29
+ private
30
+
31
+ def credential_parameters(credential)
32
+ Kernel.instance_method(:method).bind_call(credential, :client_authentication).parameters
33
+ rescue NameError
34
+ []
35
+ end
36
+
37
+ def accepts_keyword?(parameters, keyword)
38
+ parameters.any? { |kind, name| name == keyword && %i[key keyreq].include?(kind) }
39
+ end
40
+
41
+ def monotonic_time
42
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
43
+ end
44
+ end
45
+ private_constant :RequestDeadline
46
+ end
47
+ end
@@ -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.0"
5
+ VERSION = "0.18.0"
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.0
4
+ version: 0.18.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Keycard
@@ -44,6 +44,7 @@ files:
44
44
  - lib/keycardai/oauth/client_credentials_client.rb
45
45
  - lib/keycardai/oauth/client_secret.rb
46
46
  - lib/keycardai/oauth/credential_discovery.rb
47
+ - lib/keycardai/oauth/deadline_socket.rb
47
48
  - lib/keycardai/oauth/device_authorization.rb
48
49
  - lib/keycardai/oauth/discovery.rb
49
50
  - lib/keycardai/oauth/errors.rb
@@ -57,10 +58,12 @@ files:
57
58
  - lib/keycardai/oauth/printed_form.rb
58
59
  - lib/keycardai/oauth/private_key.rb
59
60
  - lib/keycardai/oauth/registration.rb
61
+ - lib/keycardai/oauth/request_deadline.rb
60
62
  - lib/keycardai/oauth/resource_binding.rb
61
63
  - lib/keycardai/oauth/substitute_user.rb
62
64
  - lib/keycardai/oauth/token_exchange_client.rb
63
65
  - lib/keycardai/oauth/token_exchange_form.rb
66
+ - lib/keycardai/oauth/token_introspection.rb
64
67
  - lib/keycardai/oauth/token_requests.rb
65
68
  - lib/keycardai/oauth/token_revocation.rb
66
69
  - lib/keycardai/oauth/token_sources.rb