keycardai-oauth 0.11.1 → 0.11.3

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: 8f71b7db8a5101db4ad089c6ad6ccedd6b0b90ce5a90af607f560e9f764ed6ec
4
- data.tar.gz: 7d9c1390b89a0d2ad6e154c08c741bfdcda9ec13d1e9b70367e95e89c2f47866
3
+ metadata.gz: 81bfa9654a536c4ddd37bc5f700bd302fb945941c1a3418b159cad4be4e7eae2
4
+ data.tar.gz: b52960595e0380ca8ecb50731867a7c4a424b9c5aac477fde1ed289549ae8bce
5
5
  SHA512:
6
- metadata.gz: e1d432957aad1da9aaa5722ab3066e4f77a3715f6e733bfd27cb38d45112e4f5f9fc4be0831fd82efb763fb70ec691c94be5fb73ec01a7e2a8e3b5a2761dc369
7
- data.tar.gz: cce1ced53cbce8b27c09c13b0466417786fbed4cbfd37314fa0b4f84d78181cf48842d7ddf85e8b04f80d1030997483c179cd651d7991c98a2fb7907c0c90624
6
+ metadata.gz: 0503f5c96c73daa6a99cce659e5d89a4ce7044b8ca2795dad4b9e2d4a91e652170866124bd509deeff1974824bdba7f21a2e3a17e89b9cd617d8bc3d981d45f9
7
+ data.tar.gz: cd2973cb995b3f4acf071cf035a4ee8c34a9a632aefab5f598b19e0a0480c69aea51872b618bb4491150f08321e5f568a0ee73dd93b7a6f1a8fc8253b3f865b4
data/CHANGELOG.md CHANGED
@@ -15,6 +15,40 @@ 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.11.3-keycardai-oauth (2026-11-25)
19
+
20
+
21
+ - fix(keycardai-oauth): pace retries for cached metadata fetches (#82)
22
+ - * fix(keycardai-oauth): pace retries for cached metadata fetches
23
+ - Co-Authored-By: Larry Osakwe <larry@keycard.ai>
24
+ - * test(keycardai-oauth): match base conformance spec slug
25
+ - Co-Authored-By: Larry Osakwe <larry@keycard.ai>
26
+ - * fix(keycardai-oauth): synchronize and bound metadata retry pacing
27
+ - Co-Authored-By: Larry Osakwe <larry@keycard.ai>
28
+ - * fix(keycardai-oauth): use monotonic retry deadlines in default clients
29
+ - Co-Authored-By: Larry Osakwe <larry@keycard.ai>
30
+ - * test(keycardai-oauth): an oversized 429 without Retry-After starts no retry delay
31
+ - ---------
32
+ - Co-authored-by: devin-ai-keycard <devin-ai@keycard.ai>
33
+ Co-authored-by: Larry Osakwe <larry@keycard.ai>
34
+ Co-authored-by: Larry Osakwe <23560354+Larry-Osakwe@users.noreply.github.com>
35
+
36
+ ## 0.11.2-keycardai-oauth (2026-11-25)
37
+
38
+
39
+ - fix(keycardai-oauth): cap decoded authorization-server responses at 1 MiB (#81)
40
+ - * fix(keycardai-oauth): cap decoded authorization-server responses at 1 MiB
41
+ - Co-Authored-By: Larry Osakwe <larry@keycard.ai>
42
+ - * fix(keycardai-oauth): fix chunked overflow cleanup and multi-member gzip inflation
43
+ - Co-Authored-By: Larry Osakwe <larry@keycard.ai>
44
+ - * fix(keycardai-oauth): capture non-BufError Zlib errors inside BoundedBodyReader
45
+ - Co-Authored-By: Larry Osakwe <larry@keycard.ai>
46
+ - * fix(keycardai-oauth): map oversized metadata server replies and cover device polling overflows
47
+ - ---------
48
+ - Co-authored-by: devin-ai-keycard <devin-ai@keycard.ai>
49
+ Co-authored-by: Larry Osakwe <larry@keycard.ai>
50
+ Co-authored-by: Larry Osakwe <23560354+Larry-Osakwe@users.noreply.github.com>
51
+
18
52
  ## 0.11.1-keycardai-oauth (2026-11-25)
19
53
 
20
54
 
@@ -28,7 +28,7 @@ module Keycardai
28
28
  # given, or a credential is combined with a raw pair
29
29
  def initialize(issuer:, credential: nil, client_id: nil, client_secret: nil,
30
30
  http_client: HTTP::NetHTTPClient.new, timeout: nil,
31
- discovery_ttl: TokenRequests::DEFAULT_DISCOVERY_TTL, clock: -> { Time.now })
31
+ discovery_ttl: TokenRequests::DEFAULT_DISCOVERY_TTL, clock: MetadataRetry::WALL_CLOCK)
32
32
  initialize_token_client(issuer: issuer, credential: credential, client_id: client_id,
33
33
  client_secret: client_secret, http_client: http_client, timeout: timeout,
34
34
  discovery_ttl: discovery_ttl, clock: clock)
@@ -152,7 +152,7 @@ module Keycardai
152
152
  # sleep that does not respond to call, a timeout that is not
153
153
  # positive, or a negative discovery_ttl
154
154
  def initialize(issuer: nil, metadata: nil, credential: nil, client_id: nil,
155
- http_client: HTTP::NetHTTPClient.new, timeout: nil, clock: -> { Time.now },
155
+ http_client: HTTP::NetHTTPClient.new, timeout: nil, clock: MetadataRetry::WALL_CLOCK,
156
156
  sleep: ->(seconds) { Kernel.sleep(seconds) },
157
157
  discovery_ttl: TokenRequests::DEFAULT_DISCOVERY_TTL)
158
158
  ClientAuth.validate(credential: credential, client_id: client_id)
@@ -382,6 +382,10 @@ module Keycardai
382
382
  rescue NetworkError => e
383
383
  # RFC 8628 §3.5: wait longer after a connection timeout.
384
384
  raise DevicePollError.new("device token poll failed: #{e.message}", interval: interval * 2)
385
+ rescue ResponseBodyTooLargeError => e
386
+ raise unless e.status == 429 || e.status.to_i >= 500
387
+
388
+ raise DevicePollError.new("device token poll failed: #{e.message}", interval: interval)
385
389
  end
386
390
 
387
391
  # The next step after a poll that raised +error+: poll again, or stop.
@@ -415,6 +419,7 @@ module Keycardai
415
419
  @ttl = ttl
416
420
  @discovered = nil
417
421
  @discovered_at = nil
422
+ @retry = MetadataRetry.new(@clock)
418
423
  @mutex = Mutex.new
419
424
  end
420
425
 
@@ -447,7 +452,9 @@ module Keycardai
447
452
  @mutex.synchronize do
448
453
  return @discovered if @discovered && @clock.call - @discovered_at <= @ttl
449
454
 
450
- fetched = OAuth.fetch_authorization_server_metadata(@issuer, http_client: @http_client, timeout: @timeout)
455
+ fetched = @retry.fetch(@issuer) do
456
+ OAuth.fetch_authorization_server_metadata(@issuer, http_client: @http_client, timeout: @timeout)
457
+ end
451
458
  if ENDPOINTS.all? { |name| http_url?(fetched.public_send(name)) }
452
459
  @discovered = fetched
453
460
  @discovered_at = @clock.call
@@ -53,7 +53,7 @@ module Keycardai
53
53
  response = http_client.get(url, headers: { "Accept" => "application/json" }, timeout: timeout)
54
54
  unless response.success?
55
55
  raise HTTPError.new("discovery for #{issuer} returned HTTP #{response.status}",
56
- status: response.status, body: response.body)
56
+ status: response.status, body: response.body, retry_after: response.retry_after)
57
57
  end
58
58
 
59
59
  Discovery.parse_metadata(issuer, response.body)
@@ -20,11 +20,13 @@ module Keycardai
20
20
  attr_reader :status
21
21
  # @return [String]
22
22
  attr_reader :body
23
+ attr_reader :retry_after
23
24
 
24
- def initialize(message, status:, body: "")
25
+ def initialize(message, status:, body: "", retry_after: nil)
25
26
  super(message)
26
27
  @status = status
27
28
  @body = body
29
+ @retry_after = retry_after
28
30
  end
29
31
  end
30
32
 
@@ -82,6 +84,10 @@ module Keycardai
82
84
  # request after this.
83
85
  class CancelledError < Keycardai::Error; end
84
86
 
87
+ # Maximum decoded byte length read from any authorization-server HTTP
88
+ # response (1 MiB).
89
+ MAX_RESPONSE_BODY_BYTES = 1_048_576
90
+
85
91
  # The server's response violates the protocol contract: metadata with a
86
92
  # mismatched or missing issuer, a token response with no access token.
87
93
  # The +code+ discriminates the case (issuer_mismatch, invalid_metadata,
@@ -89,10 +95,33 @@ module Keycardai
89
95
  class ProtocolError < Keycardai::Error
90
96
  # @return [String]
91
97
  attr_reader :code
98
+ # @return [Integer, nil]
99
+ attr_reader :status
92
100
 
93
- def initialize(message, code:)
101
+ def initialize(message, code:, status: nil)
94
102
  super(message)
95
103
  @code = code
104
+ @status = status
105
+ end
106
+
107
+ # @return [Boolean] whether the failure is transient based on HTTP status
108
+ def retryable?
109
+ return false unless status
110
+
111
+ (200..299).cover?(status) || status == 429 || status >= 500
112
+ end
113
+ end
114
+
115
+ # Raised when a decoded authorization-server HTTP response body exceeds
116
+ # MAX_RESPONSE_BODY_BYTES while streaming.
117
+ class ResponseBodyTooLargeError < ProtocolError
118
+ # @return [Integer]
119
+ attr_reader :limit
120
+
121
+ def initialize(status:, limit: MAX_RESPONSE_BODY_BYTES)
122
+ @limit = limit
123
+ super("response body exceeded the #{limit}-byte decoded size limit (HTTP #{status})",
124
+ code: "invalid_response", status: status)
96
125
  end
97
126
  end
98
127
 
@@ -33,6 +33,13 @@ module Keycardai
33
33
  def success?
34
34
  (200..299).cover?(status)
35
35
  end
36
+
37
+ def retry_after
38
+ return unless headers.respond_to?(:find)
39
+
40
+ entry = headers.find { |name, _| name.to_s.casecmp?("Retry-After") }
41
+ Array(entry&.last).first
42
+ end
36
43
  end
37
44
 
38
45
  # Build an HTTP Basic Authorization header value (RFC 7617) for client
@@ -61,6 +68,122 @@ module Keycardai
61
68
  end
62
69
  private_class_method :percent_encode
63
70
 
71
+ # Streams a Net::HTTP response body up to MAX_RESPONSE_BODY_BYTES
72
+ # decoded bytes, inflating gzip/deflate incrementally so an oversized
73
+ # response stops before buffering or parsing.
74
+ module BoundedBodyReader
75
+ DECOMPRESSED = %w[gzip x-gzip deflate].freeze
76
+
77
+ module_function
78
+
79
+ def read(response, limit: MAX_RESPONSE_BODY_BYTES)
80
+ if DECOMPRESSED.include?(response["content-encoding"]&.downcase)
81
+ read_compressed(response, limit: limit)
82
+ else
83
+ read_plain(response, limit: limit)
84
+ end
85
+ end
86
+
87
+ def read_plain(response, limit:)
88
+ decoded = String.new(encoding: Encoding::BINARY)
89
+ each_chunk(response) { |chunk| append(decoded, chunk, response, limit) }
90
+ [decoded, nil]
91
+ end
92
+
93
+ def read_compressed(response, limit:)
94
+ decoded = String.new(encoding: Encoding::BINARY)
95
+ state = {
96
+ saw_bytes: false, raw_bytes: 0, body_error: nil,
97
+ response: response, limit: limit, inflate: Zlib::Inflate.new(32 + Zlib::MAX_WBITS),
98
+ gzip: %w[gzip x-gzip].include?(response["content-encoding"]&.downcase)
99
+ }
100
+ begin
101
+ each_chunk(response) { |chunk| consume_compressed(chunk, decoded, state) }
102
+ finish_compressed(decoded, state)
103
+ ensure
104
+ state[:inflate].close
105
+ end
106
+ return ["", state[:body_error]] if state[:body_error]
107
+
108
+ strip_encoding_headers(response, decoded)
109
+ [decoded, nil]
110
+ end
111
+
112
+ def consume_compressed(chunk, decoded, state)
113
+ return if chunk.empty?
114
+
115
+ state[:saw_bytes] = true
116
+ state[:raw_bytes] += chunk.bytesize
117
+ if state[:body_error]
118
+ check_limit(state[:raw_bytes], state[:response], state[:limit])
119
+ return
120
+ end
121
+ inflate_loop(chunk, decoded, state)
122
+ rescue Zlib::BufError
123
+ raise
124
+ rescue Zlib::Error => e
125
+ state[:body_error] = e
126
+ end
127
+
128
+ def inflate_loop(data, decoded, state)
129
+ pending = data
130
+ until pending.empty?
131
+ state[:inflate].inflate(pending) { |out| append(decoded, out, state[:response], state[:limit]) }
132
+ break unless state[:inflate].finished?
133
+
134
+ pending = next_gzip_member(state[:inflate].finish, decoded, state)
135
+ end
136
+ end
137
+
138
+ def next_gzip_member(leftover, decoded, state)
139
+ return "" if leftover.empty?
140
+
141
+ stripped = state[:gzip] ? leftover.sub(/\A\x00+/, "") : ""
142
+ unless stripped.start_with?("\x1f\x8b".b)
143
+ check_limit(decoded.bytesize + leftover.bytesize, state[:response], state[:limit])
144
+ return ""
145
+ end
146
+ state[:inflate].close
147
+ state[:inflate] = Zlib::Inflate.new(32 + Zlib::MAX_WBITS)
148
+ stripped
149
+ end
150
+
151
+ def finish_compressed(decoded, state)
152
+ return unless state[:saw_bytes] && state[:body_error].nil? && !state[:inflate].finished?
153
+
154
+ state[:inflate].finish { |out| append(decoded, out, state[:response], state[:limit]) }
155
+ rescue Zlib::BufError
156
+ raise
157
+ rescue Zlib::Error => e
158
+ state[:body_error] = e
159
+ end
160
+
161
+ def each_chunk(response, &)
162
+ if response.respond_to?(:read_body)
163
+ response.read_body(&)
164
+ else
165
+ yield response.body.to_s
166
+ end
167
+ end
168
+
169
+ def strip_encoding_headers(response, decoded)
170
+ response.delete("content-encoding")
171
+ response["content-length"] = decoded.bytesize.to_s if response["content-length"]
172
+ end
173
+
174
+ def append(decoded, chunk, response, limit)
175
+ check_limit(decoded.bytesize + chunk.bytesize, response, limit)
176
+ decoded << chunk
177
+ end
178
+
179
+ def check_limit(size, response, limit)
180
+ return if limit.nil? || size <= limit
181
+
182
+ raise ResponseBodyTooLargeError.new(status: response.code.to_i, limit: limit)
183
+ end
184
+ end
185
+ private_constant :BoundedBodyReader
186
+
64
187
  # Default transport backed by Net::HTTP. TLS is used for https URLs.
65
188
  #
66
189
  # Sessions are kept open and reused per instance, per thread, per
@@ -99,7 +222,8 @@ module Keycardai
99
222
  # or a zlib header for each.
100
223
  DECOMPRESSED = %w[gzip x-gzip deflate].freeze
101
224
 
102
- def initialize
225
+ def initialize(max_response_bytes: MAX_RESPONSE_BODY_BYTES)
226
+ @max_response_bytes = max_response_bytes
103
227
  @registry = {}
104
228
  @registry_mutex = Mutex.new
105
229
  end
@@ -161,8 +285,31 @@ module Keycardai
161
285
 
162
286
  def perform(uri, request, timeout)
163
287
  http = session_for(uri)
164
- # Timeouts are per request; a request without one gets the default
165
- # back rather than the previous request's values.
288
+ configure_http(http, timeout, request)
289
+ response, body, body_error = execute_request(http, request)
290
+ build_response(response, body, body_error)
291
+ rescue *TRANSPORT_ERRORS => e
292
+ raise NetworkError, "request to #{uri.host} failed: #{e.class}"
293
+ end
294
+
295
+ def execute_request(http, request)
296
+ yielded = nil
297
+ body = nil
298
+ body_error = nil
299
+ returned = http.request(request) do |res|
300
+ yielded = res
301
+ body, body_error = BoundedBodyReader.read(res, limit: @max_response_bytes)
302
+ end
303
+ return [yielded, body, body_error] if yielded
304
+
305
+ body, body_error = BoundedBodyReader.read(returned, limit: @max_response_bytes)
306
+ [returned, body, body_error]
307
+ rescue ResponseBodyTooLargeError
308
+ finish(http)
309
+ raise
310
+ end
311
+
312
+ def configure_http(http, timeout, request)
166
313
  http.open_timeout = timeout || DEFAULT_TIMEOUT
167
314
  http.read_timeout = timeout || DEFAULT_TIMEOUT
168
315
  http.write_timeout = timeout || DEFAULT_TIMEOUT
@@ -171,31 +318,6 @@ module Keycardai
171
318
  # client decompresses the body itself. Assigning Accept-Encoding
172
319
  # turns off Net::HTTP's decompression.
173
320
  request["Accept-Encoding"] = ACCEPT_ENCODING if request.decode_content
174
- response = http.request(request)
175
- build_response(response, decompress(response))
176
- rescue *TRANSPORT_ERRORS => e
177
- raise NetworkError, "request to #{uri.host} failed: #{e.class}"
178
- rescue Zlib::Error => e
179
- build_response(response, "", e)
180
- end
181
-
182
- # Returns the body, decompressed when its Content-Encoding is gzip or
183
- # deflate. Raises Zlib::BufError when the compressed stream ends
184
- # early, and Zlib::DataError when the body is not compressed data.
185
- def decompress(response)
186
- body = response.body.to_s
187
- return body if body.empty? || !DECOMPRESSED.include?(response["content-encoding"]&.downcase)
188
-
189
- inflate = Zlib::Inflate.new(32 + Zlib::MAX_WBITS)
190
- begin
191
- decoded = inflate.inflate(body)
192
- raise Zlib::BufError, "the compressed stream ends early" unless inflate.finished?
193
- ensure
194
- inflate.close
195
- end
196
- response.delete("content-encoding")
197
- response["content-length"] = decoded.bytesize.to_s if response["content-length"]
198
- decoded
199
321
  end
200
322
 
201
323
  def build_response(response, body, body_error = nil)
@@ -36,7 +36,7 @@ module Keycardai
36
36
  # @param clock [#call] returns the current Time; override in tests
37
37
  def initialize(http_client: HTTP::NetHTTPClient.new, key_ttl: DEFAULT_KEY_TTL,
38
38
  discovery_ttl: DEFAULT_DISCOVERY_TTL, fetch_timeout: DEFAULT_FETCH_TIMEOUT,
39
- refetch_cooldown: DEFAULT_REFETCH_COOLDOWN, clock: -> { Time.now })
39
+ refetch_cooldown: DEFAULT_REFETCH_COOLDOWN, clock: MetadataRetry::WALL_CLOCK)
40
40
  @http_client = http_client
41
41
  @key_ttl = key_ttl
42
42
  @discovery_ttl = discovery_ttl
@@ -46,6 +46,9 @@ module Keycardai
46
46
  @keys = {}
47
47
  @discovery = {}
48
48
  @key_sets = {} # jwks_uri => { keys:, fetched_at: }
49
+ @discovery_retry = MetadataRetry.new(@clock)
50
+ @jwks_retry = MetadataRetry.new(@clock)
51
+ @jwks_locks = {}
49
52
  @issuer_locks = {}
50
53
  @mutex = Mutex.new
51
54
  end
@@ -79,10 +82,14 @@ module Keycardai
79
82
  @keys.delete_if { |(cached_issuer, _), _| cached_issuer == issuer }
80
83
  entry = @discovery.delete(issuer)
81
84
  @key_sets.delete(entry[:jwks_uri]) if entry
85
+ @discovery_retry.delete(issuer)
86
+ @jwks_retry.delete(entry[:jwks_uri]) if entry
82
87
  else
83
88
  @keys.clear
84
89
  @discovery.clear
85
90
  @key_sets.clear
91
+ @discovery_retry.clear
92
+ @jwks_retry.clear
86
93
  end
87
94
  end
88
95
  end
@@ -122,11 +129,19 @@ module Keycardai
122
129
  raise_not_found(issuer, kid) if now - cached[:fetched_at] < @refetch_cooldown
123
130
  end
124
131
 
125
- keys = fetch_jwks(jwks_uri)
126
- @mutex.synchronize { @key_sets[jwks_uri] = { keys: keys, fetched_at: now } }
132
+ keys = refresh_jwks(jwks_uri)
127
133
  keys.find { |candidate| candidate["kid"] == kid } || raise_not_found(issuer, kid)
128
134
  end
129
135
 
136
+ def refresh_jwks(jwks_uri)
137
+ lock = @mutex.synchronize { @jwks_locks[jwks_uri] ||= Mutex.new }
138
+ lock.synchronize do
139
+ @jwks_retry.fetch(jwks_uri) { fetch_jwks(jwks_uri) }.tap do |fetched|
140
+ @mutex.synchronize { @key_sets[jwks_uri] = { keys: fetched, fetched_at: now } }
141
+ end
142
+ end
143
+ end
144
+
130
145
  def fresh_key_set(jwks_uri)
131
146
  @mutex.synchronize do
132
147
  entry = @key_sets[jwks_uri]
@@ -145,8 +160,9 @@ module Keycardai
145
160
  end
146
161
  return cached if cached
147
162
 
148
- jwks_uri = discover_jwks_uri(issuer)
149
- assert_same_origin(issuer, jwks_uri)
163
+ jwks_uri = @discovery_retry.fetch(issuer) do
164
+ discover_jwks_uri(issuer).tap { |uri| assert_same_origin(issuer, uri) }
165
+ end
150
166
  @mutex.synchronize { @discovery[issuer] = { jwks_uri: jwks_uri, fetched_at: now } }
151
167
  jwks_uri
152
168
  end
@@ -170,12 +186,8 @@ module Keycardai
170
186
  end
171
187
 
172
188
  def fetch_jwks(jwks_uri)
173
- response = begin
174
- @http_client.get(jwks_uri, headers: { "Accept" => "application/json" }, timeout: @fetch_timeout)
175
- rescue NetworkError => e
176
- raise JWKSFetchError, "JWKS fetch from #{jwks_uri} failed: #{e.message}"
177
- end
178
- raise JWKSFetchError, "JWKS fetch from #{jwks_uri} returned HTTP #{response.status}" unless response.success?
189
+ response = @http_client.get(jwks_uri, headers: { "Accept" => "application/json" }, timeout: @fetch_timeout)
190
+ raise_jwks_http_error(jwks_uri, response) unless response.success?
179
191
 
180
192
  document = begin
181
193
  JSON.parse(response.body)
@@ -183,6 +195,14 @@ module Keycardai
183
195
  raise JWKSFetchError, "JWKS from #{jwks_uri} is invalid JSON"
184
196
  end
185
197
  document["keys"] || raise(JWKSFetchError, "JWKS from #{jwks_uri} has no keys field")
198
+ rescue NetworkError, ResponseBodyTooLargeError => e
199
+ raise JWKSFetchError, "JWKS fetch from #{jwks_uri} failed: #{e.message}"
200
+ end
201
+
202
+ def raise_jwks_http_error(jwks_uri, response)
203
+ error = HTTPError.new("JWKS endpoint returned HTTP #{response.status}",
204
+ status: response.status, retry_after: response.retry_after)
205
+ raise JWKSFetchError, "JWKS fetch from #{jwks_uri} returned HTTP #{response.status}", cause: error
186
206
  end
187
207
 
188
208
  def import_key(jwk)
@@ -0,0 +1,123 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "time"
4
+
5
+ module Keycardai
6
+ module OAuth
7
+ # Gates caller-initiated metadata fetches by cache key.
8
+ class MetadataRetry
9
+ WALL_CLOCK = -> { Time.now }
10
+ MONOTONIC_CLOCK = -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) }
11
+ MAX_ENTRIES = 128
12
+
13
+ def self.failure_cause(error)
14
+ error.is_a?(JWKSError) ? error.cause : error
15
+ end
16
+
17
+ def self.retryable?(error)
18
+ if error.is_a?(NetworkError)
19
+ cause = error.cause
20
+ return !(cause.is_a?(OpenSSL::SSL::SSLError) && cause.message.include?("certificate verify failed"))
21
+ end
22
+
23
+ error.is_a?(HTTPError) && (error.status == 429 || (500..599).cover?(error.status))
24
+ end
25
+
26
+ def initialize(clock, monotonic_clock: clock.equal?(WALL_CLOCK) ? MONOTONIC_CLOCK : clock)
27
+ @wall_clock = clock
28
+ @monotonic_clock = monotonic_clock
29
+ @states = {}
30
+ @mutex = Mutex.new
31
+ @generation = 0
32
+ end
33
+
34
+ def fetch(key)
35
+ started = @mutex.synchronize do
36
+ state = @states[key]
37
+ raise state[:error] if state && @monotonic_clock.call < state[:until]
38
+
39
+ @generation
40
+ end
41
+
42
+ begin
43
+ value = yield
44
+ rescue Keycardai::Error => e
45
+ @mutex.synchronize { record(key, e) if @generation == started }
46
+ raise
47
+ end
48
+ @mutex.synchronize { @states.delete(key) if @generation == started }
49
+ value
50
+ end
51
+
52
+ def delete(key)
53
+ @mutex.synchronize do
54
+ @generation += 1
55
+ @states.delete(key)
56
+ end
57
+ end
58
+
59
+ def clear
60
+ @mutex.synchronize do
61
+ @generation += 1
62
+ @states.clear
63
+ end
64
+ end
65
+
66
+ private
67
+
68
+ def record(key, error)
69
+ cause = self.class.failure_cause(error)
70
+ return unless self.class.retryable?(cause)
71
+
72
+ now = @monotonic_clock.call
73
+ next_step = @states.dig(key, :next_step) || 1
74
+ delay = retry_after(cause)
75
+ return if delay.nil? && throttled?(cause)
76
+
77
+ if delay.nil?
78
+ delay = [30, next_step * rand(0.8...1.2)].min
79
+ next_step = [64, next_step * 2].min
80
+ end
81
+ remember(key, error: error, until: now + delay, next_step: next_step)
82
+ end
83
+
84
+ def remember(key, state)
85
+ @states.delete(key)
86
+ @states[key] = state
87
+ @states.shift if @states.size > MAX_ENTRIES
88
+ end
89
+
90
+ def throttled?(error)
91
+ error.is_a?(HTTPError) && error.status == 429
92
+ end
93
+
94
+ def retry_after(error)
95
+ return unless error.is_a?(HTTPError) && [429, 503].include?(error.status)
96
+
97
+ header = error.retry_after.to_s.strip
98
+ return [60, header.to_i].min if /\A[0-9]+\z/.match?(header)
99
+
100
+ wall_now = @wall_clock.call
101
+ date = http_date(header, wall_now)
102
+ (date - wall_now).clamp(0, 60) if date
103
+ rescue ArgumentError
104
+ nil
105
+ end
106
+
107
+ def http_date(header, now)
108
+ date = Time.httpdate(header)
109
+ return date if header == date.httpdate || header == date.asctime || header == date.strftime("%a %b %d %T %Y")
110
+
111
+ date = adjust_obsolete_year(date, now.getutc)
112
+ date if header == date.strftime("%A, %d-%b-%y %T GMT")
113
+ end
114
+
115
+ def adjust_obsolete_year(date, now)
116
+ year = date.year + ((now.year + 50 - date.year).div(100) * 100)
117
+ year -= 100 if year == now.year + 50 && date.strftime("%m%d%T") > now.strftime("%m%d%T")
118
+ Time.utc(year, date.month, date.day, date.hour, date.min, date.sec)
119
+ end
120
+ end
121
+ private_constant :MetadataRetry
122
+ end
123
+ end
@@ -28,7 +28,7 @@ module Keycardai
28
28
  # given, or a credential is combined with a raw pair
29
29
  def initialize(issuer:, credential: nil, client_id: nil, client_secret: nil,
30
30
  http_client: HTTP::NetHTTPClient.new, timeout: nil,
31
- discovery_ttl: TokenRequests::DEFAULT_DISCOVERY_TTL, clock: -> { Time.now })
31
+ discovery_ttl: TokenRequests::DEFAULT_DISCOVERY_TTL, clock: MetadataRetry::WALL_CLOCK)
32
32
  initialize_token_client(issuer: issuer, credential: credential, client_id: client_id,
33
33
  client_secret: client_secret, http_client: http_client, timeout: timeout,
34
34
  discovery_ttl: discovery_ttl, clock: clock)
@@ -64,7 +64,7 @@ module Keycardai
64
64
  private
65
65
 
66
66
  def initialize_token_client(issuer:, credential:, client_id:, client_secret:, http_client:, timeout:,
67
- discovery_ttl: DEFAULT_DISCOVERY_TTL, clock: -> { Time.now })
67
+ discovery_ttl: DEFAULT_DISCOVERY_TTL, clock: MetadataRetry::WALL_CLOCK)
68
68
  validate_client_auth(credential, client_id, client_secret)
69
69
 
70
70
  @issuer = issuer
@@ -74,6 +74,7 @@ module Keycardai
74
74
  @discovery_ttl = discovery_ttl
75
75
  @clock = clock
76
76
  @token_endpoints = {}
77
+ @token_endpoint_retry = MetadataRetry.new(@clock)
77
78
  @token_endpoint_mutex = Mutex.new
78
79
  end
79
80
 
@@ -88,13 +89,11 @@ module Keycardai
88
89
 
89
90
  # Discover a zone's token endpoint and cache it for discovery_ttl, keyed
90
91
  # by issuer so multi-zone clients never reuse another zone's endpoint.
91
- # Only a success is recorded: a failed discovery raises to its caller and
92
- # the next call discovers again. The mutex serializes cold-cache callers
93
- # so concurrent first calls perform a single fetch; an interrupted caller
94
- # releases it and leaves nothing behind for the others.
92
+ # Transient failures pace subsequent fetches. The mutex serializes
93
+ # cold-cache callers.
95
94
  def token_endpoint(issuer = @issuer)
96
95
  @token_endpoint_mutex.synchronize do
97
- fresh_token_endpoint(issuer) || discover_token_endpoint(issuer)
96
+ fresh_token_endpoint(issuer) || @token_endpoint_retry.fetch(issuer) { discover_token_endpoint(issuer) }
98
97
  end
99
98
  end
100
99
 
@@ -98,7 +98,7 @@ module Keycardai
98
98
  url = "#{@metadata_url}#{IDENTITY_PATH}?#{URI.encode_www_form("audience" => @audience, "format" => "full")}"
99
99
  response = begin
100
100
  @http_client.get(url, headers: { "Metadata-Flavor" => "Google" }, timeout: @timeout)
101
- rescue NetworkError => e
101
+ rescue NetworkError, ResponseBodyTooLargeError => e
102
102
  raise WorkloadIdentityRuntimeError.new("metadata server unreachable: #{e.message}", source: "gcp-metadata")
103
103
  end
104
104
  unless response.success?
@@ -87,7 +87,7 @@ module Keycardai
87
87
  # @raise [ConfigurationError] no trusted issuer or explicitly empty audiences
88
88
  def initialize(issuers:, audiences: nil, http_client: HTTP::NetHTTPClient.new,
89
89
  key_ttl: JWKSKeyring::DEFAULT_KEY_TTL, discovery_ttl: JWKSKeyring::DEFAULT_DISCOVERY_TTL,
90
- fetch_timeout: JWKSKeyring::DEFAULT_FETCH_TIMEOUT, clock: -> { Time.now })
90
+ fetch_timeout: JWKSKeyring::DEFAULT_FETCH_TIMEOUT, clock: MetadataRetry::WALL_CLOCK)
91
91
  @issuers = Array(issuers).reject { |issuer| issuer.nil? || issuer.empty? }
92
92
  raise ConfigurationError, "TokenVerifier requires at least one trusted issuer" if @issuers.empty?
93
93
  raise ConfigurationError, "audiences must not be empty" if audiences.is_a?(Array) && audiences.empty?
@@ -2,6 +2,6 @@
2
2
 
3
3
  module Keycardai
4
4
  module OAuth
5
- VERSION = "0.11.1"
5
+ VERSION = "0.11.3"
6
6
  end
7
7
  end
@@ -3,6 +3,7 @@
3
3
  require_relative "oauth/version"
4
4
  require_relative "oauth/errors"
5
5
  require_relative "oauth/http"
6
+ require_relative "oauth/metadata_retry"
6
7
  require_relative "oauth/discovery"
7
8
  require_relative "oauth/userinfo"
8
9
  require_relative "oauth/token_types"
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.11.1
4
+ version: 0.11.3
5
5
  platform: ruby
6
6
  authors:
7
7
  - Keycard
@@ -51,6 +51,7 @@ files:
51
51
  - lib/keycardai/oauth/jwks_keyring.rb
52
52
  - lib/keycardai/oauth/jwt_signer.rb
53
53
  - lib/keycardai/oauth/jwt_verifier.rb
54
+ - lib/keycardai/oauth/metadata_retry.rb
54
55
  - lib/keycardai/oauth/pkce.rb
55
56
  - lib/keycardai/oauth/private_key.rb
56
57
  - lib/keycardai/oauth/registration.rb