keycloak-sdk 1.3.2 → 1.4.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 +4 -4
- data/README.md +7 -2
- data/lib/keycloak_sdk/admin/admin_client.rb +10 -4
- data/lib/keycloak_sdk/admin/bearer_auth.rb +25 -25
- data/lib/keycloak_sdk/admin/call.rb +2 -1
- data/lib/keycloak_sdk/admin/clients.rb +5 -4
- data/lib/keycloak_sdk/admin/groups.rb +4 -3
- data/lib/keycloak_sdk/admin/realms.rb +5 -5
- data/lib/keycloak_sdk/admin/roles.rb +3 -3
- data/lib/keycloak_sdk/admin/settle_body.rb +29 -0
- data/lib/keycloak_sdk/admin/users.rb +3 -3
- data/lib/keycloak_sdk/auth_client.rb +24 -29
- data/lib/keycloak_sdk/client.rb +2 -2
- data/lib/keycloak_sdk/config.rb +23 -21
- data/lib/keycloak_sdk/errors.rb +25 -19
- data/lib/keycloak_sdk/http.rb +147 -28
- data/lib/keycloak_sdk/jwks_store.rb +57 -32
- data/lib/keycloak_sdk/jwt_validator.rb +32 -15
- data/lib/keycloak_sdk/masking.rb +1 -1
- data/lib/keycloak_sdk/oidc_endpoints.rb +5 -5
- data/lib/keycloak_sdk/token_provider.rb +38 -10
- data/lib/keycloak_sdk/tokens.rb +28 -25
- data/lib/keycloak_sdk/version.rb +1 -1
- data/lib/keycloak_sdk.rb +6 -7
- metadata +2 -1
data/lib/keycloak_sdk/errors.rb
CHANGED
|
@@ -5,13 +5,13 @@ require "socket"
|
|
|
5
5
|
require "timeout"
|
|
6
6
|
|
|
7
7
|
module KeycloakSdk
|
|
8
|
-
#
|
|
8
|
+
# The root of all SDK errors.
|
|
9
9
|
class Error < StandardError; end
|
|
10
10
|
|
|
11
|
-
#
|
|
11
|
+
# Configuration validation failure.
|
|
12
12
|
class ConfigError < Error; end
|
|
13
13
|
|
|
14
|
-
#
|
|
14
|
+
# Authentication/token issuance failure (keeps the OAuth error code).
|
|
15
15
|
class AuthError < Error
|
|
16
16
|
attr_reader :oauth_error
|
|
17
17
|
|
|
@@ -21,13 +21,13 @@ module KeycloakSdk
|
|
|
21
21
|
end
|
|
22
22
|
end
|
|
23
23
|
|
|
24
|
-
#
|
|
24
|
+
# Network transport failure (timeout/connection refused/DNS).
|
|
25
25
|
class TransportError < Error; end
|
|
26
26
|
|
|
27
|
-
# JWT
|
|
27
|
+
# JWT validation failure.
|
|
28
28
|
class TokenValidationError < Error; end
|
|
29
29
|
|
|
30
|
-
# Admin REST
|
|
30
|
+
# Admin REST error (keeps the HTTP status).
|
|
31
31
|
class AdminError < Error
|
|
32
32
|
attr_reader :status
|
|
33
33
|
|
|
@@ -36,7 +36,7 @@ module KeycloakSdk
|
|
|
36
36
|
@status = status
|
|
37
37
|
end
|
|
38
38
|
|
|
39
|
-
# status →
|
|
39
|
+
# status → an instance of the matching subclass exception.
|
|
40
40
|
def self.from_status(status, message)
|
|
41
41
|
case status
|
|
42
42
|
when 404 then NotFoundError.new(message, status: status)
|
|
@@ -51,21 +51,26 @@ module KeycloakSdk
|
|
|
51
51
|
class ConflictError < AdminError; end
|
|
52
52
|
class ForbiddenError < AdminError; end
|
|
53
53
|
|
|
54
|
-
# SDK
|
|
55
|
-
#
|
|
54
|
+
# The copy attached as an SDK error's `cause` in place of the original underlying exception — it carries over **only
|
|
55
|
+
# the class-name chain and the backtrace**. The boundary attaches it with `raise …, cause: RedactedCause.new(e)`
|
|
56
|
+
# (it is not a `KeycloakSdk::Error` — it sits only in the cause slot).
|
|
56
57
|
#
|
|
57
|
-
# ⚠️ Ruby
|
|
58
|
-
#
|
|
59
|
-
#
|
|
60
|
-
# `
|
|
61
|
-
# `
|
|
62
|
-
#
|
|
58
|
+
# ⚠️ In Ruby, a `raise` inside `rescue` attaches the exception being handled as `cause` **automatically**, and
|
|
59
|
+
# `full_message` (uncaught exceptions · loggers) prints the messages of that chain. Underlying exceptions carry the
|
|
60
|
+
# response — the JSON parser puts the first 32 bytes of the body in its message, rack-oauth2 the
|
|
61
|
+
# `error_description` (the whole body for a non-JSON error), Net::HTTP the broken status line, and
|
|
62
|
+
# `Faraday::ParsingError#inspect` printed even the **request** body and headers (client secret · refresh token ·
|
|
63
|
+
# bearer). Ruby 3.2's `NoMethodError` quoted the receiver (the response body) (measured 2026-09-26 ·
|
|
64
|
+
# `spec/unit/hostile_token_response_spec.rb`). §4 also requires that the original objects are not exposed through
|
|
65
|
+
# the public API.
|
|
63
66
|
class RedactedCause < StandardError
|
|
64
|
-
#
|
|
65
|
-
#
|
|
67
|
+
# The underlying causes whose message may be carried into the SDK message — only socket · timeout · TLS
|
|
68
|
+
# failures, which cannot quote the response.
|
|
69
|
+
# ⚠️ `Faraday::ConnectionFailed` is not added wholesale — `Net::HTTPBadResponse` (a dump of the broken status
|
|
70
|
+
# line) also arrives as one.
|
|
66
71
|
QUOTE_FREE = [SystemCallError, SocketError, IOError, Timeout::Error, OpenSSL::SSL::SSLError].freeze
|
|
67
72
|
|
|
68
|
-
#
|
|
73
|
+
# The class names of the original and its `cause`s (outermost first).
|
|
69
74
|
attr_reader :lower_classes
|
|
70
75
|
|
|
71
76
|
def initialize(error)
|
|
@@ -79,7 +84,8 @@ module KeycloakSdk
|
|
|
79
84
|
set_backtrace(error.backtrace) if error.backtrace
|
|
80
85
|
end
|
|
81
86
|
|
|
82
|
-
#
|
|
87
|
+
# The description of an underlying error to carry in an SDK message — the message itself for a connection
|
|
88
|
+
# failure that cannot quote the response, otherwise only the class name.
|
|
83
89
|
def self.describe(error)
|
|
84
90
|
origin = error.respond_to?(:wrapped_exception) && error.wrapped_exception ? error.wrapped_exception : error
|
|
85
91
|
QUOTE_FREE.any? { |k| origin.is_a?(k) } ? error.message : error.class.name
|
data/lib/keycloak_sdk/http.rb
CHANGED
|
@@ -5,9 +5,10 @@ require "faraday/net_http"
|
|
|
5
5
|
require "json"
|
|
6
6
|
|
|
7
7
|
module KeycloakSdk
|
|
8
|
-
#
|
|
9
|
-
#
|
|
10
|
-
#
|
|
8
|
+
# Shared Faraday connection factory. It injects the timeouts from config and
|
|
9
|
+
# never installs the follow_redirects middleware (SSRF hardening — Faraday does not follow by default).
|
|
10
|
+
# The capped body read (`read_capped`) lives here too — the token · introspection · logout · JWKS lanes use the same
|
|
11
|
+
# mechanism.
|
|
11
12
|
module Http
|
|
12
13
|
# ⚠️ **응답 **틀**(상태 줄·헤더 줄·청크 크기/확장 줄·트레일러)의 상한.** `read_capped` 의 1 MiB 는 `on_data` 로 오는
|
|
13
14
|
# **본문 바이트**만 본다 — net-http(net-protocol 의 `BufferedIO`)는 그 앞뒤로 틀을 한도 없이 읽는다(헤더·트레일러는
|
|
@@ -32,11 +33,13 @@ module KeycloakSdk
|
|
|
32
33
|
FRAMING_TOTAL_MSG = "HTTP response framing exceeds #{MAX_FRAMING_BYTES} bytes".freeze
|
|
33
34
|
# ⚠️ 공개 API 가 아니다 — 교차언어 내부 값이다(Go 의 responseHeaderMaxBytes 도 비노출). 시험은 const_get 으로 본다.
|
|
34
35
|
private_constant :MAX_FRAMING_LINE_BYTES, :MAX_FRAMING_BYTES, :FRAMING_LINE_MSG, :FRAMING_TOTAL_MSG
|
|
35
|
-
#
|
|
36
|
-
# 1 MiB
|
|
37
|
-
#
|
|
38
|
-
#
|
|
39
|
-
# ⚠️
|
|
36
|
+
# Byte cap on the response bodies of the token endpoint (three grants · the admin lane's own token), introspection
|
|
37
|
+
# and logout. 1 MiB is 16 times the longest Bearer that Keycloak 26.6 accepts with its default settings
|
|
38
|
+
# (65,459 bytes — one more and it is HTTP 431), so no token the server accepts is refused, and an endless body
|
|
39
|
+
# stops here.
|
|
40
|
+
# ⚠️ Do not borrow the JWKS's 51,200 — a service-account token grows with the number of realms it manages.
|
|
41
|
+
# ⚠️ It must be a bare decimal literal — the nine SDKs use the same value and a cross-language guard reads this
|
|
42
|
+
# line.
|
|
40
43
|
TOKEN_RESPONSE_MAX_BYTES = 1_048_576
|
|
41
44
|
|
|
42
45
|
# ⚠️ **SDK 가 직접 읽는 요청은 인코딩 없는 본문을 청한다.** Accept-Encoding 이 없으면 net-http 가 gzip 을 청하고
|
|
@@ -46,11 +49,17 @@ module KeycloakSdk
|
|
|
46
49
|
# 압축된 바이트가 그대로 와 JSON 으로 읽히지 않으므로 SDK 오류로 닫힌다.
|
|
47
50
|
IDENTITY = { "Accept-Encoding" => "identity" }.freeze
|
|
48
51
|
|
|
52
|
+
# admin 응답의 본문을 얼마나 읽는가(admin-response-body-unbounded) — admin 커넥션의 `Admin::SettleBody` 가 요청 하나의
|
|
53
|
+
# 전송 동안만 거는 파이버 지역 값이다. 300 이상의 본문은 `TOKEN_RESPONSE_MAX_BYTES` 에서 자르고, 파사드
|
|
54
|
+
# 쓰기(요청 옵션의 표시)의 2xx 본문은 읽지 않는다 — 둘 다 net-http 가 머리를 읽은 뒤·본문을 읽기 전에 정한다
|
|
55
|
+
# (`BoundedTransport#request`). 그 밖의 성공 본문은 지금처럼 끝까지 읽는다.
|
|
56
|
+
SETTLE = :kcsdk_admin_settle
|
|
57
|
+
|
|
49
58
|
# Faraday 의 JSON 응답 규칙 그대로(JSON 콘텐츠 타입만 · 빈 본문은 nil · 해석 실패는 Faraday::ParsingError).
|
|
50
59
|
# 스트리밍으로 읽은 본문은 커넥션의 json 미들웨어가 보지 못하므로(그때 본문은 비어 있다) 여기서 같은 규칙을 건다.
|
|
51
60
|
JSON_RESPONSE = Faraday::Response::Json.new(nil, content_type: /\bjson$/)
|
|
52
61
|
UNDECODABLE = "JSON text decodes to invalid UTF-8"
|
|
53
|
-
private_constant :IDENTITY, :JSON_RESPONSE, :UNDECODABLE
|
|
62
|
+
private_constant :IDENTITY, :SETTLE, :JSON_RESPONSE, :UNDECODABLE
|
|
54
63
|
|
|
55
64
|
# 소켓 하나에 거는 **싱글턴 확장** — 전역 몽키패치가 아니라 이 SDK 가 연 `BufferedIO` 인스턴스 하나에만 붙는다
|
|
56
65
|
# (`BoundedHttp#on_connect`). 호스트 애플리케이션의 net-http 는 건드리지 않는다.
|
|
@@ -213,9 +222,39 @@ module KeycloakSdk
|
|
|
213
222
|
end
|
|
214
223
|
end
|
|
215
224
|
|
|
225
|
+
# ⚠️ **응답은 요청을 보낸 때부터 읽기 타임아웃 안에 다 읽는다**(response-read-deadline-divergent). net-protocol 의 읽기
|
|
226
|
+
# 타임아웃은 기다림 **하나**를 묶을 뿐이라, 바이트를 그보다 조금 짧은 간격으로 흘리는 서버 앞에서 응답 하나가 흘린 바이트
|
|
227
|
+
# 마다 간격 하나씩 걸렸다(수정 전 실측 2026-10-29 · 읽기 타임아웃 1 초 · 마지막 10 바이트를 0.7 초마다: 토큰·JWKS·admin 이 7,069–7,128 ms
|
|
228
|
+
# 뒤 성공 · TLS 본문 레코드의 바이트를 흘리면 22,929 ms 뒤 성공 — `response_read_deadline_spec`). `begin_transport` 가
|
|
229
|
+
# 요청마다 마감을 걸고(`kcsdk_arm_deadline!`) 이 소켓의 읽기 시도마다 본다 — 넘었으면 net-protocol 이 읽기 타임아웃에 내는
|
|
230
|
+
# 것과 같은 `Net::ReadTimeout` 이다(Faraday 의 TimeoutError → 경계의 TransportError · 메시지는 소켓뿐). 상태 줄·헤더·틀·
|
|
231
|
+
# 본문이 다 이 읽기로 오고, 최악은 마감 + 읽기 타임아웃 하나다. 스레드·타이머를 두지 않는다.
|
|
232
|
+
# ⚠️ **`rbuf_fill` 입구가 아니라 `read_nonblock` 이다** — `rbuf_fill` 은 `:wait_readable` 마다 기다렸다 다시 읽고, TLS 는
|
|
233
|
+
# 레코드가 다 올 때까지 읽을 것이 없어 채우기 하나 안에서 기다림이 이어진다(입구에서만 보면 위 TLS 가 그대로다).
|
|
234
|
+
# 닫힌 소켓은 보지 않는다 — 끊은 뒤의 읽기는 원판대로 IOError 다(`read_error_body` 가 그것만 삼킨다).
|
|
235
|
+
module ReadDeadline
|
|
236
|
+
def kcsdk_arm_deadline!(seconds)
|
|
237
|
+
@kcsdk_deadline = seconds && (Process.clock_gettime(Process::CLOCK_MONOTONIC) + seconds)
|
|
238
|
+
end
|
|
239
|
+
|
|
240
|
+
# 시그니처는 상류(`IO`·`OpenSSL::Buffering`)와 같다 — `ConnectFraming` 과 같은 까닭.
|
|
241
|
+
def read_nonblock(len, buf = nil, exception: true)
|
|
242
|
+
raise Net::ReadTimeout, to_io if kcsdk_past_deadline?
|
|
243
|
+
|
|
244
|
+
super
|
|
245
|
+
end
|
|
246
|
+
|
|
247
|
+
private
|
|
248
|
+
|
|
249
|
+
def kcsdk_past_deadline?
|
|
250
|
+
!@kcsdk_deadline.nil? && !closed? && Process.clock_gettime(Process::CLOCK_MONOTONIC) >= @kcsdk_deadline
|
|
251
|
+
end
|
|
252
|
+
end
|
|
253
|
+
|
|
216
254
|
# `Net::HTTP` 인스턴스의 싱글턴에 **prepend** 해 소켓이 만들어지는 자리(`on_connect`, `connect` 끝)에서 그 소켓에만
|
|
217
|
-
# `BoundedReads` 를 건다. `begin_transport` 는 요청마다 틀 예산을 0 으로
|
|
218
|
-
# 다음 응답은 새
|
|
255
|
+
# `BoundedReads`(와 그 IO 에 `ReadDeadline`)를 건다. `begin_transport` 는 요청마다 틀 예산을 0 으로 되돌리고 읽기 마감을
|
|
256
|
+
# 건다 — keep-alive 로 연결을 재사용해도 다음 응답은 새 예산·새 마감을 받는다(한 요청의 1xx 중간 응답들은 같은 예산을
|
|
257
|
+
# 나눠 쓴다 — 그래야 1xx 홍수도 묶인다).
|
|
219
258
|
# ⚠️ **`Net::HTTP` 를 하위 클래스로 두지 않는다.** 그 하위 클래스 인스턴스가 Faraday 스택에 남으면 공개 표면 가드의
|
|
220
259
|
# 객체 걷기(`facade_dump_spec`·`hostile_path_matrix_spec`)가 그 세 시험을 끝내지 못했다(실측: 90–150 초 timeout 에
|
|
221
260
|
# 죽었다 — 이 설계로 바꾼 뒤 같은 셋은 14 초). 원인은 가드 코드를 읽은 추정이다 — SDK 네임스페이스로 보고 그 상속 공개
|
|
@@ -228,11 +267,13 @@ module KeycloakSdk
|
|
|
228
267
|
super
|
|
229
268
|
@socket.extend(BoundedReads)
|
|
230
269
|
@socket.kcsdk_reset_framing!
|
|
270
|
+
@socket.io.extend(ReadDeadline)
|
|
231
271
|
end
|
|
232
272
|
|
|
233
273
|
def begin_transport(req)
|
|
234
274
|
super
|
|
235
275
|
@socket.kcsdk_reset_framing! if @socket.respond_to?(:kcsdk_reset_framing!)
|
|
276
|
+
@socket.io.kcsdk_arm_deadline!(read_timeout) if @socket.io.respond_to?(:kcsdk_arm_deadline!)
|
|
236
277
|
end
|
|
237
278
|
|
|
238
279
|
# ── 프록시 CONNECT(`ConnectFraming`) — `connect` 가 소켓을 여는 두 자리. 상한은 CONNECT 응답을 나르는 소켓에만 걸고
|
|
@@ -265,6 +306,39 @@ module KeycloakSdk
|
|
|
265
306
|
sock.extend(ConnectFraming)
|
|
266
307
|
sock.kcsdk_arm_connect_framing!
|
|
267
308
|
end
|
|
309
|
+
|
|
310
|
+
# ── admin 응답 본문(`SETTLE`). faraday-net_http 는 `start` 블록 안에서 `request` 에 블록을 넘기고, 그 블록이 머리를
|
|
311
|
+
# 저장한 뒤 net-http 의 `reading_body` 가 본문을 끝까지 읽는다 — 그 블록 앞에서 본문을 정하면 net-http 는 읽은
|
|
312
|
+
# 응답(`@read`)의 소켓을 더 읽지 않는다. 정한 응답의 소켓은 닫는다(남은 바이트를 다음 요청이 읽지 않게).
|
|
313
|
+
public
|
|
314
|
+
|
|
315
|
+
def request(req, body = nil, &block)
|
|
316
|
+
settle = Thread.current[SETTLE]
|
|
317
|
+
return super unless settle && started?
|
|
318
|
+
|
|
319
|
+
super do |res|
|
|
320
|
+
kcsdk_settle(res, settle[:unread])
|
|
321
|
+
block&.call(res)
|
|
322
|
+
end
|
|
323
|
+
end
|
|
324
|
+
|
|
325
|
+
private
|
|
326
|
+
|
|
327
|
+
def kcsdk_settle(res, unread)
|
|
328
|
+
if res.code.to_i >= 300
|
|
329
|
+
kcsdk_keep(res, Http.read_error_body(res) { @socket.close })
|
|
330
|
+
elsif unread
|
|
331
|
+
kcsdk_keep(res, String.new(encoding: Encoding::BINARY))
|
|
332
|
+
end
|
|
333
|
+
end
|
|
334
|
+
|
|
335
|
+
# ⚠️ **net-http `HTTPResponse` 내부(`@body`·`@read`)에 기댄다** — 읽은 응답의 `body` 는 소켓을 다시 읽지 않고 `@body`
|
|
336
|
+
# 를 돌려준다. 모양은 `admin_response_body_spec` 의 핀이 고정한다.
|
|
337
|
+
def kcsdk_keep(res, body)
|
|
338
|
+
res.instance_variable_set(:@body, body)
|
|
339
|
+
res.instance_variable_set(:@read, true)
|
|
340
|
+
@socket.close
|
|
341
|
+
end
|
|
268
342
|
end
|
|
269
343
|
|
|
270
344
|
# 표준 `:net_http` 어댑터의 설정 블록 — 커넥션을 짓기 직전 그 `Net::HTTP` 인스턴스의 싱글턴에 `BoundedTransport` 를
|
|
@@ -273,7 +347,7 @@ module KeycloakSdk
|
|
|
273
347
|
BOUND_CONNECTION = lambda do |http|
|
|
274
348
|
http.singleton_class.prepend(BoundedTransport)
|
|
275
349
|
end
|
|
276
|
-
private_constant :BoundedReads, :ConnectFraming, :BoundedTransport, :BOUND_CONNECTION
|
|
350
|
+
private_constant :BoundedReads, :ConnectFraming, :ReadDeadline, :BoundedTransport, :BOUND_CONNECTION
|
|
277
351
|
|
|
278
352
|
module_function
|
|
279
353
|
|
|
@@ -287,13 +361,17 @@ module KeycloakSdk
|
|
|
287
361
|
end
|
|
288
362
|
end
|
|
289
363
|
|
|
290
|
-
#
|
|
291
|
-
#
|
|
364
|
+
# Sends one request and reads the body only up to `max_bytes` — **regardless of status** (the same goes for a
|
|
365
|
+
# huge body on an error response). The `body` of the returned response is the bytes read (a BINARY string). Past
|
|
366
|
+
# the cap it is a `TransportError` at once, and the connection is closed.
|
|
292
367
|
#
|
|
293
|
-
# ⚠️
|
|
294
|
-
# SDK
|
|
295
|
-
#
|
|
296
|
-
#
|
|
368
|
+
# ⚠️ The check is made **before appending** a chunk — the buffer never exceeds the cap, and a chunk that would
|
|
369
|
+
# cross it is not copied. The read size is not the SDK's to choose: net-http reads 16 KiB
|
|
370
|
+
# (`Net::BufferedIO::BUFSIZE`) at a time from the socket and hands it over, so at the moment of the check what is
|
|
371
|
+
# in hand is at most the cap + one chunk (16,384 bytes). The buffer grows only as much as is read (it is not
|
|
372
|
+
# allocated to the cap up front).
|
|
373
|
+
# ⚠️ Looking only at `Content-Length` misses a response whose header is absent or false — the check uses the
|
|
374
|
+
# running total.
|
|
297
375
|
def read_capped(conn, method, url, max_bytes:, what:, body: nil, headers: {})
|
|
298
376
|
buf = String.new(encoding: Encoding::BINARY)
|
|
299
377
|
resp = conn.run_request(method, url, body, IDENTITY.merge(headers)) do |req|
|
|
@@ -308,10 +386,49 @@ module KeycloakSdk
|
|
|
308
386
|
resp
|
|
309
387
|
end
|
|
310
388
|
|
|
311
|
-
#
|
|
312
|
-
#
|
|
313
|
-
|
|
314
|
-
|
|
389
|
+
# During the transport of one admin request, lets that response's body be settled (`SETTLE`) — with `unread`
|
|
390
|
+
# it is a facade write, so a 2xx body is not read.
|
|
391
|
+
def settling(unread)
|
|
392
|
+
previous = Thread.current[SETTLE]
|
|
393
|
+
Thread.current[SETTLE] = { unread: unread }
|
|
394
|
+
yield
|
|
395
|
+
ensure
|
|
396
|
+
Thread.current[SETTLE] = previous
|
|
397
|
+
end
|
|
398
|
+
|
|
399
|
+
# Holds a body of status 300 or above only up to `TOKEN_RESPONSE_MAX_BYTES` — when a piece that crosses the cap
|
|
400
|
+
# arrives, it stops reading and truncates at the cap (it does not reject: the status has already decided the
|
|
401
|
+
# error). net-http hands over 16 KiB at a time, so what is in hand is at most the cap + one chunk.
|
|
402
|
+
# ⚠️ It calls the block (closing the socket) before cutting off — net-http's chunked read tries to read that
|
|
403
|
+
# chunk's CRLF in `ensure`, so against a server that stalled mid-chunk it waited until the read timeout even after
|
|
404
|
+
# the cut (losing the status, as a TransportError). Of the IOErrors that read raises on the closed socket, only
|
|
405
|
+
# the ones after the cut are swallowed.
|
|
406
|
+
def read_error_body(res)
|
|
407
|
+
buf = String.new(encoding: Encoding::BINARY)
|
|
408
|
+
cut = false
|
|
409
|
+
begin
|
|
410
|
+
catch(:kcsdk_cut) do
|
|
411
|
+
res.read_body do |chunk|
|
|
412
|
+
buf << chunk
|
|
413
|
+
next if buf.bytesize <= TOKEN_RESPONSE_MAX_BYTES
|
|
414
|
+
|
|
415
|
+
cut = true
|
|
416
|
+
yield
|
|
417
|
+
throw :kcsdk_cut
|
|
418
|
+
end
|
|
419
|
+
end
|
|
420
|
+
rescue IOError, SystemCallError
|
|
421
|
+
raise unless cut
|
|
422
|
+
end
|
|
423
|
+
cut ? buf.byteslice(0, TOKEN_RESPONSE_MAX_BYTES) : buf
|
|
424
|
+
end
|
|
425
|
+
|
|
426
|
+
# Parses a `read_capped` body exactly as the connection's json middleware did (returns the response).
|
|
427
|
+
# ⚠️ A string in the parsed value that is invalid UTF-8 is a parse failure (Faraday::ParsingError ←
|
|
428
|
+
# JSON::ParserError — the same shape json 3 raises for an unpaired surrogate escape). It is not rewritten — such
|
|
429
|
+
# a value turns into a raw exception as it passes through the SDK.
|
|
430
|
+
# `check_utf8: false` is for the call that uses none of the parsed value (logout) — only the middleware's verdict
|
|
431
|
+
# remains.
|
|
315
432
|
def decode_json(resp, check_utf8: true)
|
|
316
433
|
JSON_RESPONSE.on_complete(resp.env)
|
|
317
434
|
return resp if !check_utf8 || utf8?(resp.body)
|
|
@@ -319,15 +436,17 @@ module KeycloakSdk
|
|
|
319
436
|
begin
|
|
320
437
|
raise JSON::ParserError, UNDECODABLE
|
|
321
438
|
rescue JSON::ParserError => e
|
|
322
|
-
raise Faraday::ParsingError.new(e, resp) #
|
|
439
|
+
raise Faraday::ParsingError.new(e, resp) # cause chain also like json 3's failure (ParsingError <- ParserError)
|
|
323
440
|
end
|
|
324
441
|
end
|
|
325
442
|
|
|
326
|
-
#
|
|
327
|
-
#
|
|
328
|
-
#
|
|
329
|
-
#
|
|
330
|
-
#
|
|
443
|
+
# Whether every string in a parsed JSON value (keys included) is validly encoded. An unparsed body (BINARY) is
|
|
444
|
+
# always true.
|
|
445
|
+
# ⚠️ **The json version cannot prevent it** — even the locked json 3.0.2 takes raw invalid UTF-8 bytes (0xFF) as
|
|
446
|
+
# is and yields an invalid string, and json 2.9–2.21 decodes even an unpaired **low** surrogate escape (\udc00)
|
|
447
|
+
# that way (both measured). Every place such a string passes is a raw exception — the ArgumentError of the OAuth
|
|
448
|
+
# code match (`match?`), the Encoding::CompatibilityError of the admin header (net-http `strip`), the
|
|
449
|
+
# ArgumentError of ruby-jwt's base64.
|
|
331
450
|
def utf8?(value)
|
|
332
451
|
case value
|
|
333
452
|
when String then value.valid_encoding?
|
|
@@ -4,35 +4,46 @@ require "faraday"
|
|
|
4
4
|
require "json" # ⚠️ `on_data` 를 쓰면 json 미들웨어가 돌지 않아 여기서 직접 파싱한다
|
|
5
5
|
|
|
6
6
|
module KeycloakSdk
|
|
7
|
-
# DoS-safe JWKS
|
|
8
|
-
#
|
|
9
|
-
#
|
|
10
|
-
#
|
|
7
|
+
# DoS-safe JWKS store. Mutex cache + rate-limit + single-flight.
|
|
8
|
+
# A forged signature (known kid) only gets the cache back and triggers no refetch.
|
|
9
|
+
# Within the lifetime (`JWKS_MAX_AGE_SECONDS`) only an unresolved kid (force:true) triggers a refetch, and the
|
|
10
|
+
# rate-limit gate stamps at the moment the refetch is decided
|
|
11
|
+
# (not on success — this caps refetches even under a flood of forged kids in an IdP outage window).
|
|
12
|
+
# Isomorphic with Go/Rust/Python.
|
|
11
13
|
class JwksStore
|
|
12
|
-
#
|
|
13
|
-
#
|
|
14
|
-
#
|
|
15
|
-
#
|
|
14
|
+
# Lifetime (seconds) of a key set obtained by a successful load — measured on the monotonic clock from when that
|
|
15
|
+
# load **finished**. Once it has fully elapsed the cache is the same as cold: the next lookup fetches again with
|
|
16
|
+
# the same single flight · the same failure backoff, and if that fails it ends with that error. ⚠️ It does not
|
|
17
|
+
# fall back to the stale set — not even during an IdP outage (the SDK cannot tell an unreachable JWKS from
|
|
18
|
+
# withdrawn keys). A successful forced refetch also restarts the lifetime. Common to the nine languages.
|
|
19
|
+
JWKS_MAX_AGE_SECONDS = 300
|
|
20
|
+
private_constant :JWKS_MAX_AGE_SECONDS
|
|
21
|
+
|
|
22
|
+
# ⚠️ **Backoff for a failed fetch — a different axis from `min_refetch`.**
|
|
23
|
+
# `min_refetch` (30 seconds) holds back a flood of unresolved kids *once the cache is filled*. The two below
|
|
24
|
+
# hold back **the case where the cache is empty and the fetch keeps failing**. There was no gate there, so
|
|
25
|
+
# as measured, 20 validations sent 20 IdP requests straight through (2026-09-04 · the same in 7 languages).
|
|
16
26
|
#
|
|
17
|
-
# ⚠️
|
|
18
|
-
#
|
|
27
|
+
# ⚠️ **Do not reuse `min_refetch` (30 seconds) here** — a single transient 503 would become "no token can be
|
|
28
|
+
# validated for 30 seconds". So it starts short, grows exponentially and has a cap.
|
|
19
29
|
#
|
|
20
|
-
# ⚠️ **sleep
|
|
21
|
-
#
|
|
22
|
-
FAILURE_BACKOFF_BASE = 0.2 #
|
|
30
|
+
# ⚠️ **No sleep.** A library must not hold on to the caller's thread, so inside the backoff window it **fails
|
|
31
|
+
# immediately without hitting the IdP** (negative cache). The retry policy is up to the consumer.
|
|
32
|
+
FAILURE_BACKOFF_BASE = 0.2 # seconds — wait after the first failure
|
|
23
33
|
FAILURE_BACKOFF_CAP = 5.0 # 초 — 지수 증가의 상한
|
|
24
34
|
|
|
25
|
-
# ⚠️
|
|
26
|
-
#
|
|
27
|
-
#
|
|
28
|
-
# go(`jwksMaxBytes`)·rust(`JWKS_MAX_BYTES`)·java·kotlin
|
|
29
|
-
# ⚠️ `Content-Length`
|
|
30
|
-
#
|
|
35
|
+
# ⚠️ **The cap applies before the body is read whole.** It used to take `resp.body` (the value the json
|
|
36
|
+
# middleware had already parsed) as is and received as much as the server sent — a single compromised IdP could
|
|
37
|
+
# have killed the validation path through memory. 51200 is Nimbus's `RemoteJWKSet.DEFAULT_HTTP_SIZE_LIMIT`, and
|
|
38
|
+
# go (`jwksMaxBytes`) · rust (`JWKS_MAX_BYTES`) · java · kotlin use the same number.
|
|
39
|
+
# ⚠️ Judging by `Content-Length` alone misses a response whose header is absent or false — the read is cut off
|
|
40
|
+
# the moment the running total passes the cap while chunks arrive (raising inside `on_data` makes the adapter
|
|
41
|
+
# abort).
|
|
31
42
|
JWKS_MAX_BYTES = 51_200
|
|
32
43
|
|
|
33
|
-
# ⚠️
|
|
34
|
-
# public
|
|
35
|
-
#
|
|
44
|
+
# ⚠️ Do not write the default here as a number — `Config` is its single definition site. This class is an
|
|
45
|
+
# ordinary public class, so a consumer can construct it directly without going through the facade, and that path
|
|
46
|
+
# used to get 10 seconds instead of the documented 30 and hit the IdP 3 times as often (2026-08-13 Task D1).
|
|
36
47
|
def initialize(jwks_url:, http:, min_refetch: Config::DEFAULT_JWKS_MIN_REFETCH)
|
|
37
48
|
@jwks_url = jwks_url
|
|
38
49
|
@http = http
|
|
@@ -40,31 +51,42 @@ module KeycloakSdk
|
|
|
40
51
|
@mutex = Mutex.new
|
|
41
52
|
@cache = nil # {"keys" => [...]}
|
|
42
53
|
@last_refetch = nil # monotonic seconds
|
|
43
|
-
@
|
|
44
|
-
@
|
|
54
|
+
@fetched_at = nil # monotonic seconds — when the load that brought in @cache finished (the lifetime's origin)
|
|
55
|
+
@last_failure = nil # monotonic seconds — time of the last fetch failure
|
|
56
|
+
@failures = 0 # consecutive failure count (reset to 0 on success)
|
|
57
|
+
# Length (seconds) of the window the last failure opened. jitter is drawn once, when that failure is recorded,
|
|
58
|
+
# and fixed here.
|
|
59
|
+
@backoff_window = 0.0
|
|
45
60
|
end
|
|
46
61
|
|
|
47
|
-
# ruby-jwt jwks:
|
|
62
|
+
# Called by the ruby-jwt jwks: loader. force=true requests a refetch for an unresolved kid.
|
|
48
63
|
def key_set(force: false)
|
|
49
64
|
@mutex.synchronize do
|
|
50
|
-
|
|
51
|
-
return
|
|
65
|
+
cache = live_cache # nil for a set past its lifetime — everything below flows exactly as with a cold cache
|
|
66
|
+
return cache if cache && !force
|
|
67
|
+
return cache if force && !refetch_allowed?
|
|
52
68
|
|
|
53
|
-
# ⚠️
|
|
54
|
-
#
|
|
69
|
+
# ⚠️ The backoff check comes **right before** the fetch and **after** the 30-second gate. On a cold cache both
|
|
70
|
+
# returns above fall through, so without this line every validation goes out to the IdP (that was the
|
|
71
|
+
# original defect).
|
|
55
72
|
if backing_off?
|
|
56
73
|
raise TransportError,
|
|
57
74
|
"JWKS fetch backing off after #{@failures} consecutive failures " \
|
|
58
75
|
"(retry in #{backoff_remaining.round(2)}s)"
|
|
59
76
|
end
|
|
60
77
|
|
|
61
|
-
@last_refetch = monotonic if force #
|
|
78
|
+
@last_refetch = monotonic if force # stamp at decision time (a cold load spends no budget)
|
|
62
79
|
@cache = fetch_recording_failure
|
|
63
80
|
end
|
|
64
81
|
end
|
|
65
82
|
|
|
66
83
|
private
|
|
67
84
|
|
|
85
|
+
# 수명 안의 집합, 아니면 nil. 수명 판정은 이 한 자리다.
|
|
86
|
+
def live_cache
|
|
87
|
+
@cache if @cache && (monotonic - @fetched_at) < JWKS_MAX_AGE_SECONDS
|
|
88
|
+
end
|
|
89
|
+
|
|
68
90
|
def refetch_allowed?
|
|
69
91
|
@last_refetch.nil? || (monotonic - @last_refetch) >= @min_refetch
|
|
70
92
|
end
|
|
@@ -76,11 +98,12 @@ module KeycloakSdk
|
|
|
76
98
|
def backoff_remaining
|
|
77
99
|
return 0.0 if @last_failure.nil?
|
|
78
100
|
|
|
79
|
-
|
|
101
|
+
@backoff_window - (monotonic - @last_failure)
|
|
80
102
|
end
|
|
81
103
|
|
|
82
104
|
# 지수 백오프 + jitter. jitter 는 [0.5, 1.0) 배수 — 여러 인스턴스가 같은 순간에 복구를
|
|
83
|
-
# 시도해 IdP 를 다시 무너뜨리는 것(thundering herd)을 흩는다.
|
|
105
|
+
# 시도해 IdP 를 다시 무너뜨리는 것(thundering herd)을 흩는다. ⚠️ 실패를 기록할 때 한 번만 부른다 — 검사마다 부르면
|
|
106
|
+
# 같은 실패가 같은 순간에 한 번은 거부하고 한 번은 IdP 로 내보낸다(창이 0.5× 쪽으로 줄어 장애 중 요청이 최대 두 배).
|
|
84
107
|
#
|
|
85
108
|
# ⚠️ **PRNG API 를 쓰지 않고 나노초 시계에서 뽑는다.** 이 값은 비밀이 아니지만, 보안 민감
|
|
86
109
|
# 코드에서 약한 PRNG 를 호출하면 정적분석이 정당하게 막는다(실측: sonar S2245 · gosec G404).
|
|
@@ -96,12 +119,14 @@ module KeycloakSdk
|
|
|
96
119
|
|
|
97
120
|
def fetch_recording_failure
|
|
98
121
|
body = fetch
|
|
122
|
+
@fetched_at = monotonic # 수명은 적재가 끝난 이 시각부터다
|
|
99
123
|
@failures = 0
|
|
100
124
|
@last_failure = nil
|
|
101
125
|
body
|
|
102
126
|
rescue StandardError
|
|
103
127
|
@failures += 1
|
|
104
128
|
@last_failure = monotonic
|
|
129
|
+
@backoff_window = backoff_delay
|
|
105
130
|
raise
|
|
106
131
|
end
|
|
107
132
|
|
|
@@ -3,16 +3,22 @@
|
|
|
3
3
|
require "jwt"
|
|
4
4
|
|
|
5
5
|
module KeycloakSdk
|
|
6
|
-
#
|
|
7
|
-
# RS256
|
|
8
|
-
#
|
|
6
|
+
# Self-hardened JWT validator. It overrides every unsafe ruby-jwt default:
|
|
7
|
+
# RS256 pin (none/confusion rejected structurally) · exact iss · aud membership · exp required · nbf · clock skew.
|
|
8
|
+
# Keys are looked up through the DoS-safe JwksStore (a forged signature triggers no refetch). The header alg is
|
|
9
|
+
# not used to choose the verification algorithm.
|
|
9
10
|
class JwtValidator
|
|
10
|
-
#
|
|
11
|
-
#
|
|
12
|
-
|
|
11
|
+
# 받는 토큰의 길이 상한(아홉 언어 공통). Microsoft.IdentityModel 의 `DefaultMaximumTokenSizeInBytes` 와 같은 수이고,
|
|
12
|
+
# Keycloak 26.6 기본값이 받는 가장 긴 Bearer(65,459 B)의 약 3.9 배라 서버가 낸 토큰은 거부하지 않는다.
|
|
13
|
+
JWT_MAX_BYTES = 256_000
|
|
14
|
+
private_constant :JWT_MAX_BYTES
|
|
15
|
+
|
|
16
|
+
# ⚠️ Do not write the `clock_skew` default here as a number — `Config` is its single definition site (the same
|
|
17
|
+
# class of issue as Task D1). This class is public too, so a consumer can construct it directly, and if the two
|
|
18
|
+
# sites diverge, expired tokens pass for longer on that path only.
|
|
13
19
|
def initialize(issuer:, audience:, jwks_store:, algorithms: ["RS256"], clock_skew: Config::DEFAULT_CLOCK_SKEW)
|
|
14
|
-
# ruby-jwt
|
|
15
|
-
# verify_iss:true/verify_aud:true
|
|
20
|
+
# ruby-jwt's verify_iss/verify_aud builders silently become no-ops when the value is nil, so the checks are
|
|
21
|
+
# skipped even with verify_iss:true/verify_aud:true turned on — guarded fail-closed.
|
|
16
22
|
raise ConfigError, "issuer is required" if issuer.nil? || issuer.to_s.strip.empty?
|
|
17
23
|
raise ConfigError, "audience is required" if audience.nil? || audience.to_s.strip.empty?
|
|
18
24
|
|
|
@@ -23,19 +29,21 @@ module KeycloakSdk
|
|
|
23
29
|
@clock_skew = clock_skew
|
|
24
30
|
end
|
|
25
31
|
|
|
26
|
-
#
|
|
32
|
+
# The expected aud is config.expected_audience (when set) — when unset, client_id as before.
|
|
27
33
|
def self.from_config(config:, jwks_store:)
|
|
28
34
|
new(issuer: OidcEndpoints.from_config(config).issuer,
|
|
29
35
|
audience: config.expected_audience || config.client_id, jwks_store: jwks_store,
|
|
30
36
|
algorithms: config.signature_algorithms, clock_skew: config.clock_skew)
|
|
31
37
|
end
|
|
32
38
|
|
|
33
|
-
# `audience:`
|
|
34
|
-
#
|
|
35
|
-
#
|
|
39
|
+
# `audience:` is the expected aud for this call only (default = the value given at construction). The code
|
|
40
|
+
# exchange uses it to check the id_token against client_id — the key store (cache · refetch limit · backoff)
|
|
41
|
+
# stays this instance's single one.
|
|
42
|
+
# ⚠️ nil or blank is a ConfigError, as in the constructor — with `aud: nil`, ruby-jwt skips the aud check.
|
|
36
43
|
def validate(token, audience: @audience)
|
|
44
|
+
reject_oversized!(token) # ⚠️ it comes first — before splitting · decoding · the JWKS load (method below)
|
|
37
45
|
raise ConfigError, "audience is required" if audience.nil? || audience.to_s.strip.empty?
|
|
38
|
-
# ⚠️ ruby-jwt
|
|
46
|
+
# ⚠️ ruby-jwt `split`s the token first of all, and with invalid UTF-8 that is a raw ArgumentError (measured).
|
|
39
47
|
if token.is_a?(String) && !token.valid_encoding?
|
|
40
48
|
raise TokenValidationError, "JWT validation failed: token is not valid UTF-8"
|
|
41
49
|
end
|
|
@@ -43,13 +51,22 @@ module KeycloakSdk
|
|
|
43
51
|
payload, = JWT.decode(token, nil, true, decode_options(audience))
|
|
44
52
|
to_validated(payload)
|
|
45
53
|
rescue JWT::DecodeError => e
|
|
46
|
-
# ruby-jwt
|
|
47
|
-
#
|
|
54
|
+
# ruby-jwt's messages do not quote the input. Their **cause** does — when a segment is not JSON, the
|
|
55
|
+
# JSON::ParserError carries the decoded token segment (measured) — so the chain is cut with `RedactedCause`.
|
|
48
56
|
raise TokenValidationError, "JWT validation failed: #{e.message}", cause: RedactedCause.new(e)
|
|
49
57
|
end
|
|
50
58
|
|
|
51
59
|
private
|
|
52
60
|
|
|
61
|
+
# 길이 상한 — ruby-jwt 는 서명을 보기 전에 토큰을 나누고 base64·JSON 디코드하며(할당이 길이에 비례한다), 키는
|
|
62
|
+
# 그 뒤에 JWKS 에서 찾는다. 단위는 `bytesize`(진짜 JWT 는 ASCII 라 문자 수와 같다)이고, 잘못된 UTF-8 이어도 잴 수
|
|
63
|
+
# 있어 `validate` 의 인코딩 검사보다 앞이다. String 이 아닌 값은 지금처럼 ruby-jwt 가 거부한다.
|
|
64
|
+
def reject_oversized!(token)
|
|
65
|
+
return unless token.is_a?(String) && token.bytesize > JWT_MAX_BYTES
|
|
66
|
+
|
|
67
|
+
raise TokenValidationError, "JWT validation failed: token exceeds #{JWT_MAX_BYTES} bytes"
|
|
68
|
+
end
|
|
69
|
+
|
|
53
70
|
def decode_options(audience)
|
|
54
71
|
{
|
|
55
72
|
algorithms: @algorithms,
|