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.
- checksums.yaml +4 -4
- data/README.md +4 -2
- data/lib/keycloak_sdk/admin/admin_client.rb +5 -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 +1 -1
- data/lib/keycloak_sdk/admin/realms.rb +2 -2
- 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 +79 -33
- data/lib/keycloak_sdk/jwks_store.rb +57 -32
- data/lib/keycloak_sdk/jwt_validator.rb +18 -16
- 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 +5 -7
- metadata +1 -1
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 을 청하고
|
|
@@ -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 으로
|
|
224
|
-
# 다음 응답은 새
|
|
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
|
-
#
|
|
330
|
-
#
|
|
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
|
|
334
|
-
#
|
|
335
|
-
#
|
|
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
|
|
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
|
|
360
|
-
#
|
|
361
|
-
#
|
|
362
|
-
#
|
|
363
|
-
#
|
|
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`
|
|
385
|
-
# ⚠️
|
|
386
|
-
#
|
|
387
|
-
#
|
|
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) #
|
|
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
|
-
#
|
|
400
|
-
#
|
|
401
|
-
#
|
|
402
|
-
#
|
|
403
|
-
#
|
|
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
|
|
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,21 +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
|
# 받는 토큰의 길이 상한(아홉 언어 공통). 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`
|
|
16
|
-
#
|
|
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
|
|
20
|
-
# 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.
|
|
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
|
-
#
|
|
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:`
|
|
39
|
-
#
|
|
40
|
-
#
|
|
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) # ⚠️
|
|
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
|
|
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
|
|
53
|
-
#
|
|
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
|
|
data/lib/keycloak_sdk/masking.rb
CHANGED
|
@@ -3,16 +3,16 @@
|
|
|
3
3
|
require "erb"
|
|
4
4
|
|
|
5
5
|
module KeycloakSdk
|
|
6
|
-
# Keycloak realm
|
|
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
|
|
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
|
-
#
|
|
14
|
-
# client_credentials_token / create_authorization_request
|
|
15
|
-
#
|
|
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
|
-
#
|
|
5
|
-
# admin
|
|
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
|
-
#
|
|
10
|
-
#
|
|
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
|
-
# ⚠️
|
|
24
|
-
# `@cached`
|
|
25
|
-
#
|
|
26
|
-
# `Config
|
|
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
|
-
|
|
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
|