keycardai-oauth 0.16.1 → 0.17.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: b094722fda3937a5c428749976362c4b6b6fe64675d7cc28fd2a4855111816d9
4
- data.tar.gz: eb6d7d3536c0cc71287e843ad0e1f135d797deb0345f6e0d21613a0709f9cb92
3
+ metadata.gz: f8ea26ce58ef5fe06ab2c0a381bd0612e14426594904e00cfd0a2611c1c0d468
4
+ data.tar.gz: aef6b5afdaabcd72cedb139080ff153a1327adc9ff7cfa51f9ab73eaa1f795e3
5
5
  SHA512:
6
- metadata.gz: 8aff3ed02700382c383616189b2427ff9862d7b1dd9d4ba3be06e0424aaf67ad260d58c57a100e52c51ac02d8bbedefdc8aa25b92980f083f6298ba0807faa17
7
- data.tar.gz: be238c65b54d8d7592a1727340272aeb075385b007bc904f03d4b59a6949215e93e1452a0a499c7ba097d3a7e2f41b233cb3948a7056d3ffb57d591e5401d0b0
6
+ metadata.gz: 12949b72e931ff0eaea9b1d9ee920dc7b582b84164e4350a45797c3639e8a00f6efe285f4dbd7fd3d4d317e6de2bf797bd33549f7e4ff492f190605f1aea98bf
7
+ data.tar.gz: 2e516f15ee72120de6fcfc00b9ddc825f8bfb6d27ea2b0d1694828d09accd8493d4b11e9c1afe017ba087c23a50978b80ceaa24510f1767c8b796c997046921c
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.17.1-keycardai-oauth (2026-11-26)
19
+
20
+
21
+ - fix(keycardai-oauth): the request timeout bounds the credential call and the whole request (SDK-121) (#120)
22
+ - * fix(keycardai-oauth): the request timeout bounds the credential call and the whole request (SDK-121)
23
+ - * fix(keycardai-oauth): account for proxy lookup before connecting (SDK-121)
24
+ - * fix(keycardai-oauth): return complete responses after the deadline (SDK-121)
25
+ - * fix(keycardai-oauth): require explicit credential timeout keywords (SDK-121)
26
+ - * fix(keycardai-oauth): scope the request deadline to the device grant (SDK-121)
27
+ - * test(keycardai-oauth): leave the forwarding example unnumbered (SDK-121)
28
+ - * fix(keycardai-oauth): reflect on credential methods without dispatch (SDK-121)
29
+ - ---------
30
+ - Co-authored-by: devin-ai-keycard <devin-ai@keycard.ai>
31
+
32
+ ## 0.17.0-keycardai-oauth (2026-11-26)
33
+
34
+
35
+ - feat(keycardai-oauth): bind metadata, challenges and audience to one resource identifier (#110)
36
+ - Implements keycard-sdk-spec#151 for keycardai-oauth and keycardai-mcp. Refs SDK-14.
37
+
18
38
  ## 0.16.1-keycardai-oauth (2026-11-26)
19
39
 
20
40
 
@@ -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
@@ -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,355 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "uri"
4
+
5
+ module Keycardai
6
+ module OAuth
7
+ # A validated resource identifier: either an absolute HTTP(S) URL (with host,
8
+ # no userinfo, no fragment) or an RFC 8141 URN. Preserves the raw string
9
+ # verbatim for audience matching and RFC 9728 metadata documents.
10
+ class ResourceIdentifier
11
+ PROTECTED_RESOURCE_PREFIX = "/.well-known/oauth-protected-resource"
12
+ URN_PATTERN = /\Aurn:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,30}[a-zA-Z0-9])?:\S+\z/i
13
+ USERINFO_PATTERN = %r{\Ahttps?://[^/?#]*@}i
14
+
15
+ attr_reader :raw, :origin, :metadata_path, :metadata_url, :query, :target
16
+
17
+ def self.parse(value)
18
+ unless value.is_a?(String) && !value.empty?
19
+ raise ConfigurationError, "resource_identifier must be a non-empty HTTP(S) URL or URN"
20
+ end
21
+ return new(raw: value, kind: :urn) if value.match?(URN_PATTERN)
22
+
23
+ parse_http(value)
24
+ end
25
+
26
+ def self.parse_http(value)
27
+ uri = URI.parse(value)
28
+ validate_http_uri!(uri, value)
29
+ origin = format_origin(uri)
30
+ path_suffix = empty_or_root_path?(uri.path) ? "" : uri.path
31
+ metadata_path = "#{PROTECTED_RESOURCE_PREFIX}#{path_suffix}"
32
+ query_suffix = uri.query ? "?#{uri.query}" : ""
33
+ target_path = uri.path.nil? || uri.path.empty? ? "/" : uri.path
34
+ new(raw: value, kind: :http, origin: origin, metadata_path: metadata_path,
35
+ metadata_url: "#{origin}#{metadata_path}#{query_suffix}",
36
+ query: uri.query, target: "#{target_path}#{query_suffix}")
37
+ rescue URI::InvalidURIError => e
38
+ raise ConfigurationError, "invalid resource_identifier #{value.inspect}: #{e.message}"
39
+ end
40
+
41
+ def self.validate_http_uri!(uri, value)
42
+ raise ConfigurationError, "resource_identifier must be an absolute HTTP(S) URL with a host or a URN" unless
43
+ http_with_host?(uri)
44
+ if uri.userinfo || value.match?(USERINFO_PATTERN)
45
+ raise ConfigurationError, "resource_identifier must not contain userinfo"
46
+ end
47
+ return unless uri.fragment || value.include?("#")
48
+
49
+ raise ConfigurationError, "resource_identifier must not contain a fragment"
50
+ end
51
+
52
+ def self.http_with_host?(uri)
53
+ uri.is_a?(URI::HTTP) && !uri.host.to_s.empty?
54
+ end
55
+ private_class_method :parse_http, :validate_http_uri!, :http_with_host?
56
+
57
+ def self.format_origin(uri)
58
+ port = uri.port && uri.port != uri.default_port ? ":#{uri.port}" : ""
59
+ "#{uri.scheme}://#{uri.host}#{port}"
60
+ end
61
+ private_class_method :format_origin
62
+
63
+ def self.empty_or_root_path?(path)
64
+ path.nil? || path.empty? || path == "/"
65
+ end
66
+ private_class_method :empty_or_root_path?
67
+
68
+ def initialize(raw:, kind:, origin: nil, metadata_path: nil, metadata_url: nil, query: nil, target: nil)
69
+ @raw = raw
70
+ @kind = kind
71
+ @origin = origin
72
+ @metadata_path = metadata_path
73
+ @metadata_url = metadata_url
74
+ @query = query
75
+ @target = target
76
+ freeze
77
+ end
78
+
79
+ def http?
80
+ @kind == :http
81
+ end
82
+
83
+ def urn?
84
+ @kind == :urn
85
+ end
86
+
87
+ def matches_request?(path:, query: "")
88
+ return false unless http?
89
+
90
+ request_target = query.empty? ? path : "#{path}?#{query}"
91
+ @target == request_target
92
+ end
93
+
94
+ def matches_metadata_request?(path:, query: "")
95
+ http? && @metadata_path == path && @query.to_s == query
96
+ end
97
+
98
+ def ==(other)
99
+ other.is_a?(self.class) && @raw == other.raw
100
+ end
101
+ alias eql? ==
102
+
103
+ def hash
104
+ @raw.hash
105
+ end
106
+ end
107
+
108
+ # Internal option validation and mode resolution for ResourceBinding.
109
+ module ResourceBindingResolver
110
+ ZONE_ID_PATTERN = /\A[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\z/
111
+
112
+ module_function
113
+
114
+ def derive_zone_issuer(base_issuer, zone_id)
115
+ validate_zone_id!(zone_id)
116
+ uri = parse_base_issuer(base_issuer)
117
+ port = uri.port && uri.port != uri.default_port ? ":#{uri.port}" : ""
118
+ "#{uri.scheme}://#{zone_id}.#{uri.host}#{port}"
119
+ end
120
+
121
+ def validate_zone_id!(zone_id)
122
+ return if zone_id.is_a?(String) && zone_id.match?(ZONE_ID_PATTERN)
123
+
124
+ raise ConfigurationError, "invalid zone ID #{zone_id.inspect}"
125
+ end
126
+
127
+ def parse_base_issuer(base_issuer)
128
+ if base_issuer.nil? || base_issuer.empty?
129
+ raise ConfigurationError, "base issuer is required for zone issuer derivation"
130
+ end
131
+
132
+ uri = URI.parse(base_issuer)
133
+ unless uri.is_a?(URI::HTTP) && uri.host && !uri.host.empty?
134
+ raise ConfigurationError, "issuer must be an absolute HTTP(S) URL with a host"
135
+ end
136
+
137
+ uri
138
+ rescue URI::InvalidURIError => e
139
+ raise ConfigurationError, "invalid issuer #{base_issuer.inspect}: #{e.message}"
140
+ end
141
+
142
+ def check_conflicts!(resource_id, zone_map, multi_resource, allow_any, audiences)
143
+ check_flag_conflicts!(resource_id, zone_map, multi_resource, allow_any)
144
+ check_audience_conflicts!(resource_id, zone_map, multi_resource, allow_any, audiences)
145
+ end
146
+
147
+ def check_flag_conflicts!(resource_id, zone_map, multi_resource, allow_any)
148
+ if multi_resource && allow_any
149
+ raise ConfigurationError, "multi_resource and allow_any_audience cannot both be true"
150
+ end
151
+
152
+ check_identifier_conflicts!(resource_id, zone_map, multi_resource, allow_any)
153
+ end
154
+
155
+ def check_identifier_conflicts!(resource_id, zone_map, multi_resource, allow_any)
156
+ unless resource_id.nil?
157
+ unless zone_map.nil?
158
+ raise ConfigurationError,
159
+ "resource_identifier and resource_identifiers_by_zone cannot both be set"
160
+ end
161
+ if multi_resource || allow_any
162
+ raise ConfigurationError, "resource_identifier cannot be combined with multi_resource or allow_any_audience"
163
+ end
164
+ end
165
+ return unless !zone_map.nil? && allow_any
166
+
167
+ raise ConfigurationError, "resource_identifiers_by_zone cannot be combined with allow_any_audience"
168
+ end
169
+
170
+ def check_audience_conflicts!(resource_id, zone_map, multi_resource, allow_any, audiences)
171
+ return if audiences.nil?
172
+ raise ConfigurationError, "audiences cannot be combined with resource_identifier" unless resource_id.nil?
173
+ raise ConfigurationError, "audiences cannot be combined with allow_any_audience" if allow_any
174
+ return unless !zone_map.nil? && !multi_resource
175
+
176
+ raise ConfigurationError,
177
+ "audiences cannot be combined with resource_identifiers_by_zone without multi_resource"
178
+ end
179
+
180
+ def parse_zone_map(zone_map)
181
+ unless zone_map.is_a?(Hash) && !zone_map.empty?
182
+ raise ConfigurationError, "resource_identifiers_by_zone must be a non-empty Hash"
183
+ end
184
+
185
+ zone_map.each_with_object({}) do |(zone_id, identifier), parsed|
186
+ validate_zone_id!(zone_id)
187
+ parsed[zone_id] = ResourceIdentifier.parse(identifier)
188
+ end.freeze
189
+ end
190
+
191
+ def valid_audience_list?(audiences)
192
+ audiences.is_a?(Array) && !audiences.empty? &&
193
+ audiences.all? { |item| item.is_a?(String) && !item.empty? }
194
+ end
195
+
196
+ def emit_legacy_warning(component, audiences)
197
+ if audiences.is_a?(Hash)
198
+ warn "#{component} is using a deprecated legacy audience map; pass resource_identifiers_by_zone: " \
199
+ "(or resource_identifier: for single-resource mode) instead.", uplevel: 2
200
+ else
201
+ warn "#{component} is using deprecated legacy resource configuration; pass resource_identifier:, " \
202
+ "resource_identifiers_by_zone:, multi_resource: true, or allow_any_audience: true.", uplevel: 2
203
+ end
204
+ end
205
+ end
206
+
207
+ # Validated resource-binding mode shared by TokenVerifier, AuthProvider,
208
+ # RequireBearerAuth, and MetadataApp. Selects exactly one of:
209
+ # :single_resource, :per_zone, :multi_resource, :shared_discovery,
210
+ # :allow_any_audience, or :legacy (with a one-time deprecation warning).
211
+ class ResourceBinding
212
+ attr_reader :mode, :identifier, :zone_identifiers, :audiences
213
+
214
+ def self.derive_zone_issuer(base_issuer, zone_id)
215
+ ResourceBindingResolver.derive_zone_issuer(base_issuer, zone_id)
216
+ end
217
+
218
+ def self.resolve(resource_identifier: nil, resource_identifiers_by_zone: nil,
219
+ multi_resource: false, allow_any_audience: false, audiences: nil,
220
+ accept_audiences: true, require_issuer_for_zones: false, base_issuer: nil,
221
+ warn_legacy: true, component: "Keycardai")
222
+ ResourceBindingResolver.check_conflicts!(
223
+ resource_identifier, resource_identifiers_by_zone, multi_resource, allow_any_audience, audiences
224
+ )
225
+ return build_single(resource_identifier) unless resource_identifier.nil?
226
+ unless resource_identifiers_by_zone.nil?
227
+ return build_zone_binding(resource_identifiers_by_zone, multi_resource: multi_resource,
228
+ audiences: audiences,
229
+ accept_audiences: accept_audiences,
230
+ require_issuer: require_issuer_for_zones,
231
+ base_issuer: base_issuer)
232
+ end
233
+ return build_multi_resource(audiences, accept_audiences: accept_audiences) if multi_resource
234
+ return new(mode: :allow_any_audience) if allow_any_audience
235
+
236
+ build_legacy(audiences, accept_audiences: accept_audiences, warn_legacy: warn_legacy, component: component)
237
+ end
238
+
239
+ def self.build_single(resource_id)
240
+ parsed = ResourceIdentifier.parse(resource_id)
241
+ new(mode: :single_resource, identifier: parsed, audiences: [parsed.raw].freeze)
242
+ end
243
+
244
+ def self.build_zone_binding(zone_map, multi_resource:, audiences:, accept_audiences:,
245
+ require_issuer:, base_issuer:)
246
+ parsed_map = ResourceBindingResolver.parse_zone_map(zone_map)
247
+ if require_issuer && parsed_map.values.any?(&:http?) && (base_issuer.nil? || base_issuer.empty?)
248
+ raise ConfigurationError, "issuer is required when resource_identifiers_by_zone contains HTTP(S) identifiers"
249
+ end
250
+ if multi_resource
251
+ return build_shared_discovery(parsed_map, audiences: audiences, accept_audiences: accept_audiences)
252
+ end
253
+
254
+ new(mode: :per_zone, zone_identifiers: parsed_map)
255
+ end
256
+
257
+ def self.build_shared_discovery(parsed_map, audiences:, accept_audiences:)
258
+ values = parsed_map.values.uniq
259
+ unless values.length == 1 && values.first.http?
260
+ raise ConfigurationError,
261
+ "shared discovery requires every zone in resource_identifiers_by_zone to share one HTTP(S) URL"
262
+ end
263
+ shared = values.first
264
+ if accept_audiences && !(audiences.is_a?(Array) && audiences == [shared.raw])
265
+ raise ConfigurationError,
266
+ "shared discovery requires audiences to be a singleton list containing the shared identifier"
267
+ end
268
+ new(mode: :shared_discovery, identifier: shared, zone_identifiers: parsed_map, audiences: [shared.raw].freeze)
269
+ end
270
+
271
+ def self.build_multi_resource(audiences, accept_audiences:)
272
+ if accept_audiences && !ResourceBindingResolver.valid_audience_list?(audiences)
273
+ raise ConfigurationError, "multi_resource requires a non-empty audiences array"
274
+ end
275
+
276
+ new(mode: :multi_resource, audiences: accept_audiences ? audiences.dup.freeze : nil)
277
+ end
278
+
279
+ def self.build_legacy(audiences, accept_audiences:, warn_legacy:, component:)
280
+ if accept_audiences && audiences.is_a?(Array) && audiences.empty?
281
+ raise ConfigurationError, "audiences must not be empty"
282
+ end
283
+
284
+ ResourceBindingResolver.emit_legacy_warning(component, audiences) if warn_legacy
285
+ new(mode: :legacy, audiences: audiences)
286
+ end
287
+ private_class_method :build_single, :build_zone_binding, :build_shared_discovery,
288
+ :build_multi_resource, :build_legacy
289
+
290
+ def initialize(mode:, identifier: nil, zone_identifiers: nil, audiences: nil)
291
+ @mode = mode
292
+ @identifier = identifier
293
+ @zone_identifiers = zone_identifiers
294
+ @audiences = audiences
295
+ freeze
296
+ end
297
+
298
+ def explicit?
299
+ @mode != :legacy
300
+ end
301
+
302
+ def legacy?
303
+ @mode == :legacy
304
+ end
305
+
306
+ def single_resource?
307
+ @mode == :single_resource
308
+ end
309
+
310
+ def per_zone?
311
+ @mode == :per_zone
312
+ end
313
+
314
+ def multi_resource?
315
+ @mode == :multi_resource
316
+ end
317
+
318
+ def shared_discovery?
319
+ @mode == :shared_discovery
320
+ end
321
+
322
+ def allow_any_audience?
323
+ @mode == :allow_any_audience
324
+ end
325
+
326
+ def zone_mode?
327
+ per_zone? || shared_discovery?
328
+ end
329
+
330
+ def publishes_metadata?
331
+ case @mode
332
+ when :single_resource then @identifier.http?
333
+ when :shared_discovery, :legacy then true
334
+ when :per_zone then @zone_identifiers.values.any?(&:http?)
335
+ else false
336
+ end
337
+ end
338
+
339
+ def zone_issuers(base_issuer)
340
+ return {} unless @zone_identifiers
341
+
342
+ @zone_identifiers.keys.to_h { |zone_id| [zone_id, self.class.derive_zone_issuer(base_issuer, zone_id)] }
343
+ end
344
+
345
+ def compatible_with?(other)
346
+ return false unless other.is_a?(self.class)
347
+
348
+ @mode == other.mode &&
349
+ @identifier == other.identifier &&
350
+ @zone_identifiers == other.zone_identifiers &&
351
+ @audiences == other.audiences
352
+ end
353
+ end
354
+ end
355
+ end
@@ -84,30 +84,43 @@ module Keycardai
84
84
  # zone issuer(s); JWKS and discovery caches are keyed by issuer so no
85
85
  # zone's keys are ever served for another.
86
86
  class TokenVerifier
87
- # @param issuers [String, Array<String>] trusted zone issuer URL(s)
88
- # @param audiences [String, Array<String>, nil] when set, tokens must
89
- # carry an intersecting aud; when nil, the verifier accepts a token
90
- # minted for any resource in the zone and warns once at construction
87
+ # @return [ResourceBinding] the validated resource-binding mode
88
+ attr_reader :resource_binding
89
+ # @return [Array<String>] trusted zone issuer URLs
90
+ attr_reader :issuers
91
+ # @return [Hash{String => String}] zone ID to issuer URL map in zone modes
92
+ attr_reader :zone_issuers
93
+
94
+ # @param issuers [String, Array<String>, Hash{String => String}, nil] trusted zone issuer URL(s)
95
+ # @param issuer [String, nil] single issuer URL, or base issuer URL for zone-scoped modes
96
+ # @param audiences [String, Array<String>, nil] accepted audiences in multi_resource or legacy mode
97
+ # @param resource_identifier [String, nil] exact HTTP(S) URL or URN in single-resource mode
98
+ # @param resource_identifiers_by_zone [Hash{String => String}, nil] zone ID to identifier map
99
+ # @param multi_resource [Boolean] explicit multi-resource or shared-discovery opt-in
100
+ # @param allow_any_audience [Boolean] explicit opt-out from audience validation
101
+ # @param resource_binding [ResourceBinding, nil] pre-validated binding (internal composition)
91
102
  # @param http_client [#get] pluggable transport
92
103
  # @param key_ttl [Numeric] JWKS key cache lifetime in seconds
93
104
  # @param discovery_ttl [Numeric] jwks_uri cache lifetime in seconds
94
105
  # @param fetch_timeout [Numeric] discovery and JWKS fetch timeout
95
106
  # @param clock [#call] returns the current Time; override in tests
96
- # @raise [ConfigurationError] no trusted issuer or explicitly empty audiences
97
- def initialize(issuers:, audiences: nil, http_client: HTTP::NetHTTPClient.new,
107
+ # @raise [ConfigurationError] invalid or conflicting mode options or no trusted issuer
108
+ def initialize(issuers: nil, issuer: nil, audiences: nil,
109
+ resource_identifier: nil, resource_identifiers_by_zone: nil,
110
+ multi_resource: false, allow_any_audience: false,
111
+ resource_binding: nil,
112
+ http_client: HTTP::NetHTTPClient.new,
98
113
  key_ttl: JWKSKeyring::DEFAULT_KEY_TTL, discovery_ttl: JWKSKeyring::DEFAULT_DISCOVERY_TTL,
99
114
  fetch_timeout: JWKSKeyring::DEFAULT_FETCH_TIMEOUT, clock: MetadataRetry::WALL_CLOCK)
100
- @issuers = Array(issuers).reject { |issuer| issuer.nil? || issuer.empty? }
101
- raise ConfigurationError, "TokenVerifier requires at least one trusted issuer" if @issuers.empty?
102
- raise ConfigurationError, "audiences must not be empty" if audiences.is_a?(Array) && audiences.empty?
103
-
104
- if audiences.nil?
105
- warn "Keycardai::OAuth::TokenVerifier has no audiences configured, so it accepts a token minted " \
106
- "for any resource in the zone; pass audiences: with this server's registered resource identifier.",
107
- uplevel: 1
108
- end
109
-
110
- @audiences = audiences
115
+ @resource_binding = resource_binding || ResourceBinding.resolve(
116
+ resource_identifier: resource_identifier,
117
+ resource_identifiers_by_zone: resource_identifiers_by_zone,
118
+ multi_resource: multi_resource,
119
+ allow_any_audience: allow_any_audience,
120
+ audiences: audiences,
121
+ component: "Keycardai::OAuth::TokenVerifier"
122
+ )
123
+ @issuers, @zone_issuers = resolve_issuers(issuers, issuer)
111
124
  @clock = clock
112
125
  @keyring = JWKSKeyring.new(http_client: http_client, key_ttl: key_ttl,
113
126
  discovery_ttl: discovery_ttl, fetch_timeout: fetch_timeout, clock: clock)
@@ -119,21 +132,27 @@ module Keycardai
119
132
  # @return [AccessToken]
120
133
  # @raise [InvalidTokenError, JWKSError]
121
134
  def verify_token(token)
122
- verify_against(@issuers, token)
135
+ raise InvalidTokenError, "per-zone verifier requires verify_token_for_zone" if @resource_binding.per_zone?
136
+
137
+ verify_against(@issuers, token, @resource_binding.audiences)
123
138
  end
124
139
 
125
- # Verify a bearer token pinned to one zone's issuer. A token minted by
126
- # any other zone is rejected before key resolution, and an issuer
127
- # outside the configured allowlist fails closed.
140
+ # Verify a bearer token pinned to one zone's issuer or zone ID. A token
141
+ # minted by any other zone is rejected before key resolution, and an
142
+ # unconfigured zone fails closed.
128
143
  #
129
144
  # @param token [String]
130
- # @param issuer [String] the zone's issuer URL
145
+ # @param zone_or_issuer [String] zone ID (in zone modes) or zone issuer URL
131
146
  # @return [AccessToken]
132
147
  # @raise [InvalidTokenError, JWKSError]
133
- def verify_token_for_zone(token, issuer)
134
- raise InvalidTokenError, "zone issuer is not configured on this verifier" unless @issuers.include?(issuer)
148
+ def verify_token_for_zone(token, zone_or_issuer)
149
+ return verify_per_zone(token, zone_or_issuer) if @resource_binding.per_zone?
150
+ return verify_shared_zone(token, zone_or_issuer) if @resource_binding.shared_discovery?
151
+ unless @issuers.include?(zone_or_issuer)
152
+ raise InvalidTokenError, "zone issuer is not configured on this verifier"
153
+ end
135
154
 
136
- verify_against([issuer], token)
155
+ verify_against([zone_or_issuer], token, @resource_binding.audiences)
137
156
  end
138
157
 
139
158
  # Drop all cached keys and discovery results.
@@ -145,8 +164,84 @@ module Keycardai
145
164
 
146
165
  private
147
166
 
148
- def verify_against(issuers, token)
149
- claims = JWTVerifier.new(issuers: issuers, keyring: @keyring, audiences: @audiences,
167
+ def verify_per_zone(token, zone_or_issuer)
168
+ zone_id = @zone_issuers.key?(zone_or_issuer) ? zone_or_issuer : @zone_issuers.key(zone_or_issuer)
169
+ raise InvalidTokenError, "zone is not configured on this verifier" unless zone_id
170
+
171
+ verify_against([@zone_issuers[zone_id]], token, [@resource_binding.zone_identifiers[zone_id].raw])
172
+ end
173
+
174
+ def verify_shared_zone(token, zone_or_issuer)
175
+ zone_issuer = @zone_issuers[zone_or_issuer] || (@issuers.include?(zone_or_issuer) ? zone_or_issuer : nil)
176
+ raise InvalidTokenError, "zone issuer is not configured on this verifier" unless zone_issuer
177
+
178
+ verify_against([zone_issuer], token, @resource_binding.audiences)
179
+ end
180
+
181
+ def resolve_issuers(issuers, issuer)
182
+ return resolve_zone_issuers(issuers, issuer) if @resource_binding.zone_mode?
183
+
184
+ raw = issuers.nil? ? issuer : issuers
185
+ list = Array(raw).reject { |item| item.nil? || item.empty? }.freeze
186
+ raise ConfigurationError, "TokenVerifier requires at least one trusted issuer" if list.empty?
187
+
188
+ [list, {}.freeze]
189
+ end
190
+
191
+ def resolve_zone_issuers(issuers, issuer)
192
+ return resolve_zone_issuer_hash(issuers) if issuers.is_a?(Hash)
193
+
194
+ base = issuer || (issuers if issuers.is_a?(String))
195
+ return resolve_derived_zone_issuers(base, issuers) unless base.to_s.empty?
196
+ return match_zone_issuer_array(issuers) if issuers.is_a?(Array) && !issuers.empty?
197
+
198
+ raise ConfigurationError, "TokenVerifier requires at least one trusted issuer"
199
+ end
200
+
201
+ def resolve_zone_issuer_hash(issuers)
202
+ expected = @resource_binding.zone_identifiers.keys.sort
203
+ unless issuers.keys.sort == expected
204
+ raise ConfigurationError, "issuers keys must match resource_identifiers_by_zone keys"
205
+ end
206
+
207
+ zone_map = issuers.transform_values(&:to_s).freeze
208
+ [zone_map.values.freeze, zone_map]
209
+ end
210
+
211
+ def resolve_derived_zone_issuers(base, issuers)
212
+ zone_map = @resource_binding.zone_issuers(base).freeze
213
+ if issuers.is_a?(Array) && issuers.map { |i| i.to_s.chomp("/") }.sort != zone_map.values.sort
214
+ raise ConfigurationError, "trusted issuers must match the zones in resource_identifiers_by_zone"
215
+ end
216
+
217
+ [zone_map.values.freeze, zone_map]
218
+ end
219
+
220
+ # Trusted issuers keep their configured spelling, so a token whose iss
221
+ # carries a trailing slash still matches it exactly.
222
+ def match_zone_issuer_array(issuers)
223
+ configured = issuers.map(&:to_s)
224
+ zone_map = @resource_binding.zone_identifiers.keys.to_h do |zone_id|
225
+ [zone_id, find_unique_zone_issuer!(configured, zone_id)]
226
+ end.freeze
227
+ unless zone_map.values.sort == configured.sort
228
+ raise ConfigurationError, "trusted issuers must match the zones in resource_identifiers_by_zone"
229
+ end
230
+
231
+ [zone_map.values.freeze, zone_map]
232
+ end
233
+
234
+ def find_unique_zone_issuer!(normalized, zone_id)
235
+ matched = normalized.select { |url| URI.parse(url).host&.start_with?("#{zone_id}.") }
236
+ raise ConfigurationError, "cannot uniquely match issuer for zone #{zone_id}" unless matched.length == 1
237
+
238
+ matched.first
239
+ rescue URI::InvalidURIError => e
240
+ raise ConfigurationError, "invalid issuer URL: #{e.message}"
241
+ end
242
+
243
+ def verify_against(issuers, token, audiences)
244
+ claims = JWTVerifier.new(issuers: issuers, keyring: @keyring, audiences: audiences,
150
245
  clock: @clock).verify(token)
151
246
  audience = claims["aud"]
152
247
  claims = claims.merge("aud" => [audience]) if audience.is_a?(String)
@@ -2,6 +2,6 @@
2
2
 
3
3
  module Keycardai
4
4
  module OAuth
5
- VERSION = "0.16.1"
5
+ VERSION = "0.17.1"
6
6
  end
7
7
  end
@@ -25,6 +25,7 @@ require_relative "oauth/token_sources"
25
25
  require_relative "oauth/credential_discovery"
26
26
  require_relative "oauth/access_context"
27
27
  require_relative "oauth/exchange_tokens"
28
+ require_relative "oauth/resource_binding"
28
29
  require_relative "oauth/token_verifier"
29
30
  require_relative "oauth/token_exchange_client"
30
31
  require_relative "oauth/client_credentials_client"
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.16.1
4
+ version: 0.17.1
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,6 +58,8 @@ 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
62
+ - lib/keycardai/oauth/resource_binding.rb
60
63
  - lib/keycardai/oauth/substitute_user.rb
61
64
  - lib/keycardai/oauth/token_exchange_client.rb
62
65
  - lib/keycardai/oauth/token_exchange_form.rb