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.
@@ -5,13 +5,13 @@ require "socket"
5
5
  require "timeout"
6
6
 
7
7
  module KeycloakSdk
8
- # 모든 SDK 오류의 루트.
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
- # 인증/토큰 발급 실패(OAuth 오류 코드 보존).
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
- # 네트워크 전송 실패(타임아웃/연결거부/DNS).
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 오류(HTTP status 보존).
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 오류의 `cause` 에 원본 하위 예외 대신 다는 사본 — **클래스 이름 사슬과 백트레이스만** 옮긴다.
55
- # 경계는 `raise …, cause: RedactedCause.new(e)` 로 단다(`KeycloakSdk::Error` 가 아니다 — 원인 자리에만 있다).
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 는 `rescue` 안의 `raise` 가 처리 중인 예외를 `cause` 에 **자동으로** 달고, `full_message`(잡히지 않은
58
- # 예외·로거)가 그 사슬의 메시지를 찍는다. 하위 예외는 응답을 싣는다 — JSON 파서는 본문 앞 32 바이트를,
59
- # rack-oauth2 는 `error_description`(JSON 이 아닌 오류면 본문 전체)을, Net::HTTP 는 깨진 상태 줄을 메시지에 싣고,
60
- # `Faraday::ParsingError#inspect` 는 **요청** 본문·헤더(클라이언트 시크릿·refresh 토큰·베어러)까지 찍었다. Ruby 3.2 의
61
- # `NoMethodError` 는 수신자(응답 본문)를 인용했다(실측 2026-09-26 · `spec/unit/hostile_token_response_spec.rb`).
62
- # 원본 객체를 공개 API 로 내보내지 않는 것은 §4 도 요구한다.
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
- # 메시지를 SDK 메시지로 옮겨도 되는 하위 원인 — 응답을 인용할 수 없는 소켓·타임아웃·TLS 실패뿐이다.
65
- # ⚠️ `Faraday::ConnectionFailed` 를 통째로 넣지 않는다 — `Net::HTTPBadResponse`(깨진 상태 줄 dump)도 그것으로 온다.
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
- # 원본과 그 `cause` 들의 클래스 이름(바깥부터).
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
- # SDK 메시지에 실을 하위 오류 설명 — 인용할 수 없는 연결 실패면 그 메시지, 아니면 클래스 이름뿐.
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
@@ -5,9 +5,10 @@ require "faraday/net_http"
5
5
  require "json"
6
6
 
7
7
  module KeycloakSdk
8
- # 공유 Faraday 커넥션 팩토리. 타임아웃을 config에서 주입하고,
9
- # follow_redirects 미들웨어를 절대 장착하지 않는다(SSRF 하드닝 — Faraday는 기본 미추종).
10
- # 상한을 건 본문 읽기(`read_capped`)도 여기 있다 — 토큰·introspection·logout·JWKS 레인이 같은 기제를 쓴다.
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
- # 토큰 엔드포인트(세 그랜트 · admin 레인의 자기 토큰)·introspection·logout 응답 본문의 상한(바이트).
36
- # 1 MiB 는 Keycloak 26.6 이 기본 설정으로 받는 가장 긴 Bearer(65,459 바이트 — 하나 더 길면 HTTP 431)의
37
- # 16 배라 서버가 받는 토큰은 거부하지 않고, 끝없는 본문은 여기서 멈춘다.
38
- # ⚠️ JWKS 의 51,200 을 빌려 쓰지 말 것 — 서비스 계정 토큰은 관리하는 realm 수만큼 자란다.
39
- # ⚠️ 맨 십진 리터럴이어야 한다 — 아홉 SDK 가 같은 값을 쓰고 교차언어 가드가 이 줄을 읽는다.
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 으로 되돌린다 — keep-alive 로 연결을 재사용해도
218
- # 다음 응답은 새 예산을 받는다(한 요청의 1xx 중간 응답들은 같은 예산을 나눠 쓴다 — 그래야 1xx 홍수도 묶인다).
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
- # 요청 하나를 보내고 본문을 `max_bytes` 까지만 읽는다 — **상태와 무관하게**(오류 응답의 거대 본문도 같다).
291
- # 돌려주는 응답의 `body` 는 읽은 바이트(BINARY 문자열)다. 넘으면 그 즉시 `TransportError` 이고 연결은 닫힌다.
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 가 정하지 못한다: net-http 가 소켓에서 16 KiB(`Net::BufferedIO::BUFSIZE`)씩 읽어 넘기므로 판정 순간
295
- # 손에 든 것은 많아야 상한 + 청크 하나(16,384 바이트)다. 버퍼는 읽은 만큼만 자란다(미리 상한만큼 잡지 않는다).
296
- # ⚠️ `Content-Length` 만 보면 그 헤더가 없거나 거짓인 응답을 놓친다 — 누적치로 판정한다.
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
- # `read_capped` 의 본문을 커넥션의 json 미들웨어가 하던 그대로 해석한다(응답을 돌려준다).
312
- # ⚠️ 해석한 값의 문자열이 잘못된 UTF-8 이면 해석 실패다(Faraday::ParsingError ← JSON::ParserError — 짝 없는
313
- # 서로게이트 이스케이프에서 json 3 이 내는 것과 같은 모양). 고쳐 쓰지 않는다 — 그 값은 SDK 를 지나며 raw 예외가 된다.
314
- # `check_utf8: false` 는 해석한 값을 하나도 쓰지 않는 호출(logout)의 것이다 — 미들웨어의 판정만 남는다.
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) # 원인 사슬도 json 3 의 실패와 같다(ParsingError <- ParserError)
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
- # 해석한 JSON 값(키 포함)의 문자열이 전부 올바른 인코딩인가. 해석하지 않은 본문(BINARY)은 언제나 참이다.
327
- # ⚠️ **json 버전으로 막을 수 없다** — 잠긴 json 3.0.2 도 날 잘못된 UTF-8 바이트(0xFF)는 그대로 받아 잘못된
328
- # 문자열을 내고, json 2.9–2.21 은 짝 없는 **낮은** 서로게이트 이스케이프(\udc00)까지 그렇게 푼다(둘 다 실측).
329
- # 그 문자열이 지나는 자리마다 raw 예외다 — OAuth 코드 대조(`match?`)의 ArgumentError, admin 헤더의
330
- # Encoding::CompatibilityError(net-http `strip`), ruby-jwt base64 의 ArgumentError.
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 스토어. Mutex 캐시 + rate-limit + single-flight.
8
- # 위조 서명(알려진 kid)은 캐시 반환만 하고 재조회를 유발하지 않는다.
9
- # 미해결 kid(force:true)만 재조회하며, rate-limit gate는 재조회 결정 시점에 stamp한다
10
- # (성공 아님 — IdP 장애창에서 위조 kid 폭주에도 재조회를 상한한다). Go/Rust/Python 동형.
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
- # ⚠️ **실패한 fetch 의 백오프 — `min_refetch` 와 다른 축이다.**
13
- # `min_refetch`(30초)는 *캐시가 찬 뒤* 미해결 kid 홍수를 막는다. 아래 둘은 **캐시가 비어
14
- # 있고 fetch 가 계속 실패할 때**를 막는다. 그 자리에는 게이트가 없어서, 측정상 20회 검증이
15
- # IdP 요청 20건을 그대로 냈다(2026-09-04 · 7개 언어 동일).
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
- # ⚠️ **여기에 `min_refetch`(30초)를 재사용하면 안 된다** — 일시적 503 한 번이 「30초간 어떤
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
- # 안에서는 **IdP 를 때리지 않고 즉시 실패**시킨다(negative cache). 재시도 정책은 소비자 몫이다.
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
- # ⚠️ **본문을 통째로 읽기 전에 상한을 건다.** 예전에는 `resp.body`(json 미들웨어가 이미
26
- # 파싱한 값)를 그대로 받아 서버가 보내는 만큼 다 받았다 — 손상된 IdP 하나가 검증 경로를
27
- # 메모리로 죽일 수 있었다. 51200 은 Nimbus `RemoteJWKSet.DEFAULT_HTTP_SIZE_LIMIT` 이고
28
- # go(`jwksMaxBytes`)·rust(`JWKS_MAX_BYTES`)·java·kotlin 이 같은 수를 쓴다.
29
- # ⚠️ `Content-Length` 로만 판정하면 그 헤더가 없거나 거짓인 응답을 놓친다 — 청크를 받으며
30
- # 누적치가 상한을 넘는 순간 읽기를 끊는다(`on_data` 안에서 raise 하면 어댑터가 중단한다).
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
- # ⚠️ 기본값을 여기 숫자로 적지 말 것 — `Config`가 유일한 정의 자리다. 이 클래스는 평범한
34
- # public 클래스라 소비자가 파사드를 거치지 않고 직접 생성할 수 있고, 예전에는 그 경로가
35
- # 문서의 30초가 아니라 10초를 받아 IdP를 3배 자주 때렸다(2026-08-13 Task D1).
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
- @last_failure = nil # monotonic seconds — 마지막 fetch 실패 시각
44
- @failures = 0 # 연속 실패 횟수(성공 시 0으로 되돌린다)
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: 로더가 호출. force=true는 미해결 kid 재조회 요청.
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
- return @cache if @cache && !force
51
- return @cache if force && !refetch_allowed?
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
- # ⚠️ 백오프 검사는 fetch **직전**이자 30초 게이트 **이후**다. 콜드 캐시에서는 위 두 return
54
- # 이 모두 통과하므로, 이 줄이 없으면 매 검증이 IdP 로 나간다(그게 원래 결함이다).
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 # 결정 시점 stamp(cold load는 예산 미소모)
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
- backoff_delay - (monotonic - @last_failure)
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
- # 자체강화 JWT 검증기. ruby-jwt의 안전하지 않은 기본값을 전부 오버라이드한다:
7
- # RS256 핀(none/confusion 구조적 거부)·iss 정확·aud 포함·exp 필수·nbf·클록스큐.
8
- # 키는 DoS-safe JwksStore로 조회한다(위조 서명은 재조회 미유발). 헤더 alg는 검증 알고리즘 선택에 미사용.
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
- # ⚠️ `clock_skew` 기본값을 여기 숫자로 적지 말 것 — `Config`가 유일한 정의 자리다(Task D1과
11
- # 같은 부류). 이 클래스도 public이라 소비자가 직접 생성할 수 있고, 두 자리가 갈리면 그
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의 verify_iss/verify_aud 빌더는 값이 nil이면 조용히 no-op이 되어
15
- # verify_iss:true/verify_aud:true를 켜도 검사를 건너뛴다 — fail-closed로 방어.
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
- # 기대 aud는 config.expected_audience(설정 시) — 미설정이면 종전대로 client_id.
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:` 는 이 호출만의 기대 aud 다(기본 = 생성 시 값). 코드 교환이 id_token 을 client_id 로 검사할 때
34
- # 쓴다 — 키 저장소(캐시 · 재조회 제한 · 백오프)는 그대로 이 인스턴스의 것 하나다.
35
- # ⚠️ nil·공백은 생성자와 같이 ConfigError — ruby-jwt 는 `aud: nil` 이면 aud 검사를 건너뛴다.
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 는 맨 먼저 토큰을 `split` 하고, 잘못된 UTF-8 이면 그것이 raw ArgumentError 다(실측).
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 메시지는 입력을 인용하지 않는다. 그 **원인**은 인용한다 — 조각이 JSON 이 아니면 JSON::ParserError 가
47
- # 디코드한 토큰 조각을 싣는다(실측) — 그래서 사슬은 `RedactedCause` 로 끊는다.
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,
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module KeycloakSdk
4
- # 완전 불투명 마스킹(접두 노출 없음).
4
+ # Fully opaque masking (no prefix exposed).
5
5
  module Masking
6
6
  module_function
7
7