keycloak-sdk 1.4.0 → 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,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 을 청하고
@@ -219,9 +222,39 @@ module KeycloakSdk
219
222
  end
220
223
  end
221
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
+
222
254
  # `Net::HTTP` 인스턴스의 싱글턴에 **prepend** 해 소켓이 만들어지는 자리(`on_connect`, `connect` 끝)에서 그 소켓에만
223
- # `BoundedReads` 를 건다. `begin_transport` 는 요청마다 틀 예산을 0 으로 되돌린다 — keep-alive 로 연결을 재사용해도
224
- # 다음 응답은 새 예산을 받는다(한 요청의 1xx 중간 응답들은 같은 예산을 나눠 쓴다 — 그래야 1xx 홍수도 묶인다).
255
+ # `BoundedReads`(와 그 IO 에 `ReadDeadline`)를 건다. `begin_transport` 는 요청마다 틀 예산을 0 으로 되돌리고 읽기 마감을
256
+ # 건다 — keep-alive 로 연결을 재사용해도 다음 응답은 새 예산·새 마감을 받는다(한 요청의 1xx 중간 응답들은 같은 예산을
257
+ # 나눠 쓴다 — 그래야 1xx 홍수도 묶인다).
225
258
  # ⚠️ **`Net::HTTP` 를 하위 클래스로 두지 않는다.** 그 하위 클래스 인스턴스가 Faraday 스택에 남으면 공개 표면 가드의
226
259
  # 객체 걷기(`facade_dump_spec`·`hostile_path_matrix_spec`)가 그 세 시험을 끝내지 못했다(실측: 90–150 초 timeout 에
227
260
  # 죽었다 — 이 설계로 바꾼 뒤 같은 셋은 14 초). 원인은 가드 코드를 읽은 추정이다 — SDK 네임스페이스로 보고 그 상속 공개
@@ -234,11 +267,13 @@ module KeycloakSdk
234
267
  super
235
268
  @socket.extend(BoundedReads)
236
269
  @socket.kcsdk_reset_framing!
270
+ @socket.io.extend(ReadDeadline)
237
271
  end
238
272
 
239
273
  def begin_transport(req)
240
274
  super
241
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!)
242
277
  end
243
278
 
244
279
  # ── 프록시 CONNECT(`ConnectFraming`) — `connect` 가 소켓을 여는 두 자리. 상한은 CONNECT 응답을 나르는 소켓에만 걸고
@@ -312,7 +347,7 @@ module KeycloakSdk
312
347
  BOUND_CONNECTION = lambda do |http|
313
348
  http.singleton_class.prepend(BoundedTransport)
314
349
  end
315
- private_constant :BoundedReads, :ConnectFraming, :BoundedTransport, :BOUND_CONNECTION
350
+ private_constant :BoundedReads, :ConnectFraming, :ReadDeadline, :BoundedTransport, :BOUND_CONNECTION
316
351
 
317
352
  module_function
318
353
 
@@ -326,13 +361,17 @@ module KeycloakSdk
326
361
  end
327
362
  end
328
363
 
329
- # 요청 하나를 보내고 본문을 `max_bytes` 까지만 읽는다 — **상태와 무관하게**(오류 응답의 거대 본문도 같다).
330
- # 돌려주는 응답의 `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.
331
367
  #
332
- # ⚠️ 판정은 청크를 **붙이기 전에** 한다 — 버퍼는 상한을 넘지 않고, 넘는 청크는 복사하지 않는다. 읽는 크기는
333
- # SDK 가 정하지 못한다: net-http 가 소켓에서 16 KiB(`Net::BufferedIO::BUFSIZE`)씩 읽어 넘기므로 판정 순간
334
- # 손에 든 것은 많아야 상한 + 청크 하나(16,384 바이트)다. 버퍼는 읽은 만큼만 자란다(미리 상한만큼 잡지 않는다).
335
- # ⚠️ `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.
336
375
  def read_capped(conn, method, url, max_bytes:, what:, body: nil, headers: {})
337
376
  buf = String.new(encoding: Encoding::BINARY)
338
377
  resp = conn.run_request(method, url, body, IDENTITY.merge(headers)) do |req|
@@ -347,7 +386,8 @@ module KeycloakSdk
347
386
  resp
348
387
  end
349
388
 
350
- # admin 요청 하나의 전송 동안 그 응답의 본문을 정하게 한다(`SETTLE`) — `unread` 면 파사드 쓰기라 2xx 본문을 읽지 않는다.
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.
351
391
  def settling(unread)
352
392
  previous = Thread.current[SETTLE]
353
393
  Thread.current[SETTLE] = { unread: unread }
@@ -356,11 +396,13 @@ module KeycloakSdk
356
396
  Thread.current[SETTLE] = previous
357
397
  end
358
398
 
359
- # 300 이상의 본문을 `TOKEN_RESPONSE_MAX_BYTES` 까지만 쥔다 — 상한을 넘기는 조각이 오면 읽기를 멈추고 상한에서 자른다
360
- # (거부하지 않는다: 상태가 이미 오류를 정했다). net-http 가 16 KiB 씩 넘기므로 손에 드는 것은 많아야 상한 + 청크 하나다.
361
- # ⚠️ 끊기 전에 블록(소켓 닫기)을 부른다 — net-http 의 청크 읽기는 `ensure` 에서 그 청크의 CRLF 를 읽으려 해, 청크
362
- # 한가운데서 멈춘 서버 앞에서는 끊은 뒤에도 읽기 타임아웃까지 기다렸다(상태를 잃고 TransportError). 닫힌 소켓의 그
363
- # 읽기가 내는 IOError 는 끊은 뒤의 것만 삼킨다.
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.
364
406
  def read_error_body(res)
365
407
  buf = String.new(encoding: Encoding::BINARY)
366
408
  cut = false
@@ -381,10 +423,12 @@ module KeycloakSdk
381
423
  cut ? buf.byteslice(0, TOKEN_RESPONSE_MAX_BYTES) : buf
382
424
  end
383
425
 
384
- # `read_capped` 의 본문을 커넥션의 json 미들웨어가 하던 그대로 해석한다(응답을 돌려준다).
385
- # ⚠️ 해석한 값의 문자열이 잘못된 UTF-8 이면 해석 실패다(Faraday::ParsingError ← JSON::ParserError — 짝 없는
386
- # 서로게이트 이스케이프에서 json 3 이 내는 것과 같은 모양). 고쳐 쓰지 않는다 — 그 값은 SDK 를 지나며 raw 예외가 된다.
387
- # `check_utf8: false` 는 해석한 값을 하나도 쓰지 않는 호출(logout)의 것이다 — 미들웨어의 판정만 남는다.
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.
388
432
  def decode_json(resp, check_utf8: true)
389
433
  JSON_RESPONSE.on_complete(resp.env)
390
434
  return resp if !check_utf8 || utf8?(resp.body)
@@ -392,15 +436,17 @@ module KeycloakSdk
392
436
  begin
393
437
  raise JSON::ParserError, UNDECODABLE
394
438
  rescue JSON::ParserError => e
395
- 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)
396
440
  end
397
441
  end
398
442
 
399
- # 해석한 JSON 값(키 포함)의 문자열이 전부 올바른 인코딩인가. 해석하지 않은 본문(BINARY)은 언제나 참이다.
400
- # ⚠️ **json 버전으로 막을 수 없다** — 잠긴 json 3.0.2 도 날 잘못된 UTF-8 바이트(0xFF)는 그대로 받아 잘못된
401
- # 문자열을 내고, json 2.9–2.21 은 짝 없는 **낮은** 서로게이트 이스케이프(\udc00)까지 그렇게 푼다(둘 다 실측).
402
- # 그 문자열이 지나는 자리마다 raw 예외다 — OAuth 코드 대조(`match?`)의 ArgumentError, admin 헤더의
403
- # 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.
404
450
  def utf8?(value)
405
451
  case value
406
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,21 +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
11
  # 받는 토큰의 길이 상한(아홉 언어 공통). Microsoft.IdentityModel 의 `DefaultMaximumTokenSizeInBytes` 와 같은 수이고,
11
12
  # Keycloak 26.6 기본값이 받는 가장 긴 Bearer(65,459 B)의 약 3.9 배라 서버가 낸 토큰은 거부하지 않는다.
12
13
  JWT_MAX_BYTES = 256_000
13
14
  private_constant :JWT_MAX_BYTES
14
15
 
15
- # ⚠️ `clock_skew` 기본값을 여기 숫자로 적지 말 것 — `Config`가 유일한 정의 자리다(Task D1과
16
- # 같은 부류). 이 클래스도 public이라 소비자가 직접 생성할 수 있고, 두 자리가 갈리면 그
17
- # 경로에서만 만료된 토큰이 더 오래 통과한다.
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.
18
19
  def initialize(issuer:, audience:, jwks_store:, algorithms: ["RS256"], clock_skew: Config::DEFAULT_CLOCK_SKEW)
19
- # ruby-jwt의 verify_iss/verify_aud 빌더는 값이 nil이면 조용히 no-op이 되어
20
- # 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.
21
22
  raise ConfigError, "issuer is required" if issuer.nil? || issuer.to_s.strip.empty?
22
23
  raise ConfigError, "audience is required" if audience.nil? || audience.to_s.strip.empty?
23
24
 
@@ -28,20 +29,21 @@ module KeycloakSdk
28
29
  @clock_skew = clock_skew
29
30
  end
30
31
 
31
- # 기대 aud는 config.expected_audience(설정 시) — 미설정이면 종전대로 client_id.
32
+ # The expected aud is config.expected_audience (when set) — when unset, client_id as before.
32
33
  def self.from_config(config:, jwks_store:)
33
34
  new(issuer: OidcEndpoints.from_config(config).issuer,
34
35
  audience: config.expected_audience || config.client_id, jwks_store: jwks_store,
35
36
  algorithms: config.signature_algorithms, clock_skew: config.clock_skew)
36
37
  end
37
38
 
38
- # `audience:` 는 이 호출만의 기대 aud 다(기본 = 생성 시 값). 코드 교환이 id_token 을 client_id 로 검사할 때
39
- # 쓴다 — 키 저장소(캐시 · 재조회 제한 · 백오프)는 그대로 이 인스턴스의 것 하나다.
40
- # ⚠️ 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.
41
43
  def validate(token, audience: @audience)
42
- reject_oversized!(token) # ⚠️ 맨 앞이다 — 나누기·디코드·JWKS 적재보다 먼저(아래 메서드)
44
+ reject_oversized!(token) # ⚠️ it comes first — before splitting · decoding · the JWKS load (method below)
43
45
  raise ConfigError, "audience is required" if audience.nil? || audience.to_s.strip.empty?
44
- # ⚠️ 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).
45
47
  if token.is_a?(String) && !token.valid_encoding?
46
48
  raise TokenValidationError, "JWT validation failed: token is not valid UTF-8"
47
49
  end
@@ -49,8 +51,8 @@ module KeycloakSdk
49
51
  payload, = JWT.decode(token, nil, true, decode_options(audience))
50
52
  to_validated(payload)
51
53
  rescue JWT::DecodeError => e
52
- # ruby-jwt 메시지는 입력을 인용하지 않는다. 그 **원인**은 인용한다 — 조각이 JSON 이 아니면 JSON::ParserError 가
53
- # 디코드한 토큰 조각을 싣는다(실측) — 그래서 사슬은 `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`.
54
56
  raise TokenValidationError, "JWT validation failed: #{e.message}", cause: RedactedCause.new(e)
55
57
  end
56
58
 
@@ -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
 
@@ -3,16 +3,16 @@
3
3
  require "erb"
4
4
 
5
5
  module KeycloakSdk
6
- # Keycloak realm의 OIDC 엔드포인트를 규약대로 조립한다(네트워크 없음).
6
+ # Assembles a Keycloak realm's OIDC endpoints by convention (no network).
7
7
  class OidcEndpoints
8
8
  attr_reader :issuer, :authorization, :token, :introspection, :end_session, :jwks
9
9
 
10
10
  def initialize(server_url, realm)
11
- # issuer는 토큰 iss 클레임과 그대로 비교하므로 realm을 인코딩하지 않는다.
11
+ # The issuer is compared as is with the token's iss claim, so the realm is not encoded.
12
12
  @issuer = "#{server_url}/realms/#{realm}"
13
- # 엔드포인트의 realm은 경로 세그먼트 하나다. "my realm"을 그대로 두면
14
- # client_credentials_token / create_authorization_request가 URI::InvalidURIError를
15
- # SDK 밖으로 흘린다(자매 SDK는 이 세그먼트를 퍼센트 인코딩한다).
13
+ # In the endpoints the realm is a single path segment. Left as is, "my realm" makes
14
+ # client_credentials_token / create_authorization_request leak a URI::InvalidURIError
15
+ # out of the SDK (the sibling SDKs percent-encode this segment).
16
16
  oidc = "#{server_url}/realms/#{escape_realm_segment(realm)}/protocol/openid-connect"
17
17
  @authorization = "#{oidc}/auth"
18
18
  @token = "#{oidc}/token"
@@ -1,13 +1,33 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module KeycloakSdk
4
- # 덕 인터페이스: 구현체는 #access_token → String 을 응답한다.
5
- # admin은 이 인터페이스로만 토큰을 받는다(auth 비의존, §4 결합 규칙).
4
+ # Duck interface: an implementation responds to #access_token → String.
5
+ # admin receives tokens only through this interface (no dependency on auth, §4 coupling rule).
6
+ # admin strips leading and trailing SP · HTAB · CR · LF from that value before sending it, and if what is left is not
7
+ # an RFC 6750 bearer token it rejects it before the request (`BearerGrammar`).
6
8
  module TokenProvider
7
9
  end
8
10
 
9
- # client-credentials 그랜트로 토큰을 발급하고 만료 전까지 캐시한다(Mutex single-flight).
10
- # admin 파사드가 소비하는 캐싱 provider(무캐시 AuthClient 직접 주입 금지 — §4 캐시 불변식).
11
+ # bearer 토큰 문법 — 아홉 SDK 가 같다(등록부 bearer-token-grammar-divergent). 앞뒤의 SP·HTAB·CR·LF 만 다듬고(NBSP·U+3000·
12
+ # VT·FF 는 다듬지 않는다 — 그래서 NUL·VT·FF 까지 지우는 `strip` 이 아니다) 남은 것이 비지 않은 RFC 6750 b64token 이면 그 값,
13
+ # 아니면 nil 이다. 보내는 자리(`Admin::BearerAuth`)와 캐시하는 자리(`ClientCredentialsTokenProvider`)가 이것 하나를 쓴다.
14
+ # 다듬기와 판정을 `\A`…`\z` 매치 하나로 한다 — b64token 안에는 다듬을 글자가 없으니 「다듬고 나서 맞춘다」와 같은 뜻이다.
15
+ # ⚠️ `\z` 다(`$` 는 줄 끝이라 "abc\nX" 를 받는다). `ascii_only?` 가 ASCII 밖·잘못된 UTF-8·ASCII 와 호환되지 않는
16
+ # 인코딩(UTF-16 등)을 매치 전에 거른다 — 거르지 않으면 매치가 ArgumentError·Encoding::CompatibilityError 를 낸다(실측).
17
+ module BearerGrammar
18
+ TOKEN = %r{\A[ \t\r\n]*([A-Za-z0-9\-._~+/]+=*)[ \t\r\n]*\z}
19
+
20
+ module_function
21
+
22
+ def sendable(text)
23
+ TOKEN.match(text)&.[](1) if text.ascii_only?
24
+ end
25
+ end
26
+ private_constant :BearerGrammar
27
+
28
+ # Issues a token with the client-credentials grant and caches it until it expires (Mutex single-flight).
29
+ # The caching provider the admin facade consumes (never inject the uncached AuthClient directly — §4 cache
30
+ # invariant).
11
31
  class ClientCredentialsTokenProvider
12
32
  include TokenProvider
13
33
 
@@ -20,11 +40,12 @@ module KeycloakSdk
20
40
  @expires_at = 0.0
21
41
  end
22
42
 
23
- # ⚠️ 기본 `inspect` 는 인스턴스 변수를 전부 찍는데, 이 클래스는 **원시 액세스 토큰 문자열**을
24
- # `@cached` 에 들고 있다(`ts.access_token` — TokenSet 이 아니라서 `TokenSet#inspect` 가 안 탄다).
25
- # 실측(2026-09-12): 재정의 전 `p provider` 가 `@cached="AT-CENSUS-TOKEN-…"` 를 원문으로 찍었다.
26
- # `Config`·`TokenSet` 은 재정의가 있는데 이 타입만 없어 생긴 **형제 간 불일치**였다.
27
- # ⚠️ 캐시 유무는 남긴다 — 빈 캐시에 `***` 를 찍으면 「토큰이 있다」는 거짓 신호가 된다.
43
+ # ⚠️ The default `inspect` prints every instance variable, and this class holds the **raw access token string**
44
+ # in `@cached` (`ts.access_token` — not a TokenSet, so `TokenSet#inspect` does not kick in).
45
+ # Measured (2026-09-12): before the override, `p provider` printed `@cached="AT-CENSUS-TOKEN-…"` verbatim.
46
+ # It was a **mismatch between siblings**: `Config` · `TokenSet` have an override and only this type lacked one.
47
+ # ⚠️ Whether a token is cached stays visible — printing `***` for an empty cache would be a false signal that
48
+ # "there is a token".
28
49
  def inspect
29
50
  "#<KeycloakSdk::ClientCredentialsTokenProvider config=#{@config.inspect} " \
30
51
  "cached=#{@cached ? '"***"' : 'nil'} expires_at=#{@expires_at.inspect}>"
@@ -37,7 +58,14 @@ module KeycloakSdk
37
58
  return @cached if @cached && now < @expires_at
38
59
 
39
60
  ts = request_token
40
- @cached = ts.access_token
61
+ # Checked before caching — a token that every admin request would reject is not held until it expires (the
62
+ # next call asks the IdP again).
63
+ token = BearerGrammar.sendable(ts.access_token)
64
+ unless token
65
+ raise AuthError, "token response has no usable access_token: it is not an RFC 6750 bearer token (b64token)"
66
+ end
67
+
68
+ @cached = token
41
69
  @expires_at = ts.expires_at ? (ts.expires_at - @config.clock_skew) : (now + 60)
42
70
  @cached
43
71
  end