keycloak-sdk 1.3.2 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 51b3c59bfdc3c281f3a6b71faaa6fba7e9561399bfa9e352cf275cbc42718617
4
- data.tar.gz: 3260c90043c5d10f253266af8fc3786c7212906b1b460bfd05eb1e49cb0e38ed
3
+ metadata.gz: 52cd15ebf26da1523bdb1d8fd7a686c67204fac085a5031f2754ecade75db80f
4
+ data.tar.gz: 1ca086fe490283624960266fa63fa88b4213d54de13a359f6cab10361aeea520
5
5
  SHA512:
6
- metadata.gz: 04b4477363357a3fdfa3a2c324dfdbd8a992c28a8ce163f84ac65fa6f6a0bfbf591a9261786a7251f91de1d3398b5f8b279be7f696f56e709009e8f1e308274e
7
- data.tar.gz: da685f6729d4aa0362a9d71397c23aab3205b63aae49da6199b64348d8764d4c6988dfe0be9095d912f0fbd1eab9ab9899bebff999327a06bf851c94de31eccf
6
+ metadata.gz: 2c4b2142282d0ca792dee70d3e5cda365813d0ecd3baa56a212dc88eed68a4c3a6d73649e93d20e5ca8e748cdae5ea19e6ea5542547d72d7879bc8f6765c6fea
7
+ data.tar.gz: a302586a9f15242ca397db66b80f19f27898564b2d266edd3674a6a6e8b5e2e78587480dd6be474213472ec543df2a4415b436bfb8ff8c962d980346f5b6c033
data/README.md CHANGED
@@ -4,7 +4,9 @@ Authentication (OIDC / OAuth2) and the Admin REST API for [Keycloak](https://www
4
4
 
5
5
  Part of a **nine-language polyglot SDK** (Java · Python · Node · Go · C# · PHP · Rust · Ruby · Kotlin) — one API surface, isomorphic across all of them: [github.com/xzawed/KeyCloakSDK](https://github.com/xzawed/KeyCloakSDK).
6
6
 
7
- > **`1.3.2` is on RubyGems** — a patch release on top of `1.3.1`; `1.0.0` was the first release carrying the stability guarantee. A bare `gem install keycloak-sdk` resolves it. **Security**: an HTTPS call through a proxy (the SDK has no proxy option — Faraday reads `https_proxy`/`HTTPS_PROXY`) read the proxy's CONNECT reply outside the framing caps, because net-http reads that reply into its own buffer before the point the SDK hooks: net-http `0.9.1` read a 100,000-byte header line, 400 short header lines (82,039 bytes) or a 996,039-byte reply whole and went on to the TLS handshake with the origin, and `0.10.0` read the status line and header block up to its own 1 MiB limit. The socket that carries the CONNECT reply — the TCP socket for a plain proxy, the TLS socket with the proxy for a TLS proxy, never the TLS session with the origin — now gets the same two caps (8,192 bytes per line, 65,536 bytes per header block) and the same constant-message `KeycloakSdk::TransportError`; a well-formed reply passes as before. ⚠️ **`net-http >= 0.9` is now a runtime dependency** — the cap hooks `Net::HTTP#timeouted_connect`, which first appears in `0.9.0`. faraday-net_http already pulls net-http in, so most installs change nothing, but an application that pins net-http below `0.9` must raise it to install this release. **Fixed**: an admin error status (404, 409, 403 or any other non-2xx) whose body claims `Content-Type: application/json` but is not JSON — a proxy's HTML error page, say — raised `TransportError` (`admin transport error: Faraday::ParsingError`) instead of the status class; it now raises `NotFoundError`, `ConflictError`, `ForbiddenError` or `AdminError` with the usual `admin request failed: HTTP <status>` and quotes the body neither in the message nor in the cause chain (a 2xx that does not parse is still a `TransportError`). ⚠️ Code that rescued `KeycloakSdk::TransportError` for such responses now gets the status class. No public API change.
7
+ > **`1.4.0` is on RubyGems** — a minor release on top of `1.3.2`; `1.0.0` was the first release carrying the stability guarantee. A bare `gem install keycloak-sdk` resolves it. It is a minor release because the public API grew by two module functions, `KeycloakSdk::Http.settling` and `KeycloakSdk::Http.read_error_body`, which the admin change below is built on; the admin middleware itself, `Admin::SettleBody`, is a private constant. **Security**: the admin client read a response body to its end even after it had the result. faraday-net_http returns a response only after it has read the body to its end, so a server wrote all of the 64 MiB it attached to the 201 body of a `create` or the 2xx body of an `update` or `delete` (182–522 ms), and a server that stalled after a 2xx head turned a write call — even a `create` that already had its `Location` — into a `TransportError` at the end of the read timeout (4,037–4,060 ms across the fifteen write calls with a 4-second timeout). Error bodies were read to their end too: a 404 with 64 MiB made one call allocate 203 MB, and net-http asked for gzip on its own and decompressed it above the cap (202 MB for a gzip error body that inflates to 64 MiB). The facade's fifteen write calls (`create`, `update` and `delete` on the five resources) now leave a 2xx body unread (the server wrote at most 393,218 bytes; 26–45 ms in front of a stalled server), and an error body (3xx and above) is held only up to 1,048,576 bytes, the token-response cap (4.2–4.3 MB for one call with a 64 MiB error body). The status class (`NotFoundError` and the like) and the message are unchanged — the message does not carry the body. An error body that stalls after passing the cap ends with its status without waiting out the read timeout (it used to end in `TransportError` after 4,042–4,072 ms). Admin requests now ask for `Accept-Encoding: identity`, so net-http no longer asks for gzip and decompresses it, and an error body sent gzipped anyway is capped by the bytes received (0.42 MB for that gzip error body). ⚠️ Against a server that sends gzip even when asked for identity, a success body cannot be parsed and becomes a `TransportError`, and on the `raw` connection such a JSON error body becomes a `Faraday::ParsingError` (net-http used to ask for gzip and decompress it). The `raw` connection still receives a 2xx body (its error body has the same cap), the body of a request streamed with `on_data` goes to the caller uncapped, and success bodies (`get`, `list`) are not capped. `validate` also used memory in proportion to a token's length before it checked the signature: ruby-jwt 3.3.0 decodes the header without a length limit (it has only a JSON depth limit of 100), so one forged token allocated 12.8–18.7 bytes per input byte (measured with `memsize_of_all` while GC was stopped). A token longer than 256,000 bytes (`bytesize`) is now rejected before anything else with `TokenValidationError` (`JWT validation failed: token exceeds 256000 bytes`), and the id_token of `exchange_code` goes through the same check. ⚠️ An empty `audience:` passed together with an over-cap token now raises `TokenValidationError` rather than `ConfigError`, because the cap comes first. The new length constant is a private constant.
8
+ >
9
+ > `1.3.2` was a patch release on top of `1.3.1`. **Security**: an HTTPS call through a proxy (the SDK has no proxy option — Faraday reads `https_proxy`/`HTTPS_PROXY`) read the proxy's CONNECT reply outside the framing caps, because net-http reads that reply into its own buffer before the point the SDK hooks: net-http `0.9.1` read a 100,000-byte header line, 400 short header lines (82,039 bytes) or a 996,039-byte reply whole and went on to the TLS handshake with the origin, and `0.10.0` read the status line and header block up to its own 1 MiB limit. The socket that carries the CONNECT reply — the TCP socket for a plain proxy, the TLS socket with the proxy for a TLS proxy, never the TLS session with the origin — now gets the same two caps (8,192 bytes per line, 65,536 bytes per header block) and the same constant-message `KeycloakSdk::TransportError`; a well-formed reply passes as before. ⚠️ **`net-http >= 0.9` is now a runtime dependency** — the cap hooks `Net::HTTP#timeouted_connect`, which first appears in `0.9.0`. faraday-net_http already pulls net-http in, so most installs change nothing, but an application that pins net-http below `0.9` must raise it to install this release. **Fixed**: an admin error status (404, 409, 403 or any other non-2xx) whose body claims `Content-Type: application/json` but is not JSON — a proxy's HTML error page, say — raised `TransportError` (`admin transport error: Faraday::ParsingError`) instead of the status class; it now raises `NotFoundError`, `ConflictError`, `ForbiddenError` or `AdminError` with the usual `admin request failed: HTTP <status>` and quotes the body neither in the message nor in the cause chain (a 2xx that does not parse is still a `TransportError`). ⚠️ Code that rescued `KeycloakSdk::TransportError` for such responses now gets the status class. No public API change.
8
10
  >
9
11
  > `1.3.1` was a patch release on top of `1.3.0`. **Fixed — upgrade if you installed `1.3.0` recently**: with net-http `0.10` (what a fresh install resolves), a response header name that holds a control character or is longer than 1,024 bytes made `introspect`, `logout` and the admin client raise a raw `ArgumentError` that quoted the name; they now raise `KeycloakSdk::TransportError` (`introspection transport error: ArgumentError` and the like — the cause chain keeps only the class name), as the grants already raised `AuthError`. **Security**: the response *framing* — status line, header lines, chunk-size and extension lines, trailers — was outside the body caps, so a 16 MiB header line, chunk extension or trailer line, or 4,096 trailer lines of 4 KiB, were read whole (32–67 MB allocated per call). Every connection the SDK makes now reads at most 8,192 bytes per framing line and 65,536 bytes of framing per response, and beyond that drops the connection with a constant-message `KeycloakSdk::TransportError` that does not quote the response; default Keycloak responses are far below both. The bound works with net-http `0.9` and `0.10`, and it touches only the sockets the SDK opens. ⚠️ The framing budget also counts chunk-size lines, so a large body cut into chunks of a few dozen bytes is refused (Keycloak and mainstream reverse proxies chunk in KiB and pass). The admin client now refuses, before any request, an access token an HTTP header cannot carry — NUL, DEL and other control characters, or a leading or trailing space or tab — with `AuthError`; net-http used to strip or forward them. ⚠️ A consumer `TokenProvider` whose token ends in a space or tab now fails instead of being trimmed. No public API change.
10
12
 
@@ -68,6 +70,7 @@ The SDK replaces the unsafe library defaults rather than inheriting them:
68
70
  - **Algorithm pinning** — the header-supplied `alg` is never trusted, so `alg: none` and HS/RS confusion are rejected structurally: the pin is applied before key lookup and signature verification, not after.
69
71
  - **Strict claim checks** — exact `iss` match, `aud` containment, mandatory `exp`, `nbf` enforced when present, and a bounded clock skew.
70
72
  - **DoS-safe JWKS** — a refetch is triggered only by an unresolved key ID and never by a bad signature, and is rate-limited to a minimum interval (`jwks_min_refetch`, 30s by default) — so **once the key set has been fetched**, no volume of forged tokens makes the SDK issue more than one JWKS request per interval. A *failed* fetch is bounded separately: consecutive failures back off exponentially (0.2s, doubling, capped at 5s, with jitter), and inside that window the SDK **fails fast without contacting the IdP**. So a cold cache during an IdP outage no longer turns every validation into a request (measured: 20 attempts → 1 request, down from 20). ⚠️ The SDK never sleeps — it returns the error immediately, so retry pacing stays the caller's decision.
73
+ - **Bounded token input** — a token longer than 256,000 bytes is rejected with `KeycloakSdk::TokenValidationError` before it is decoded and before any JWKS request.
71
74
  - **OIDC nonce / `id_token` replay protection** — `create_authorization_request` always issues a nonce (same default as `state:`) and puts it on the authorization URL. Pass it back as `exchange_code(expected_nonce:)` and the SDK fully validates the `id_token` before comparing the nonce claim. Omit `expected_nonce:` and id_token validation is skipped (same opt-out as the other eight languages).
72
75
  - **Secret handling** — `Config`, `TokenSet`, and `AuthorizationRequest` mask secrets and tokens in `#inspect` (`***`, no prefix leak), TLS verification is on by default, timeouts are always applied, and redirect-following middleware is never installed (SSRF hardening).
73
76
 
@@ -42,11 +42,16 @@ module KeycloakSdk
42
42
 
43
43
  private
44
44
 
45
+ # ⚠️ admin 요청은 인코딩 없는 본문을 청한다 — Accept-Encoding 이 없으면 net-http 가 gzip 을 청하고 상한 위에서 푼다
46
+ # (`SettleBody` 가 오류 본문을 끊어도 그 inflater 는 읽은 압축 조각을 끝까지 푼다 · `Http::IDENTITY` 와 같은 까닭).
47
+ # 요청에 이 머리가 있으면 net-http 는 자기 것을 붙이지 않고 풀지도 않는다.
45
48
  def build_conn(config, token_provider)
46
49
  Http.build(config, base_url: "#{config.server_url}/") do |f|
50
+ f.headers["Accept-Encoding"] = "identity"
47
51
  f.request :json
48
52
  f.response :json, content_type: /\bjson$/
49
53
  f.use BearerAuth, token_provider
54
+ f.use SettleBody
50
55
  end
51
56
  end
52
57
  end
@@ -11,7 +11,8 @@ module KeycloakSdk
11
11
  end
12
12
 
13
13
  def create(representation)
14
- id_from_location(request { @conn.post("admin/realms/#{esc(@realm)}/clients", representation) })
14
+ path = "admin/realms/#{esc(@realm)}/clients"
15
+ id_from_location(request { @conn.post(path, representation, &SettleBody::MARK) })
15
16
  end
16
17
 
17
18
  def get(id)
@@ -24,12 +25,12 @@ module KeycloakSdk
24
25
  end
25
26
 
26
27
  def update(id, representation)
27
- request { @conn.put("admin/realms/#{esc(@realm)}/clients/#{esc(id)}", representation) }
28
+ request { @conn.put("admin/realms/#{esc(@realm)}/clients/#{esc(id)}", representation, &SettleBody::MARK) }
28
29
  nil
29
30
  end
30
31
 
31
32
  def delete(id)
32
- request { @conn.delete("admin/realms/#{esc(@realm)}/clients/#{esc(id)}") }
33
+ request { @conn.delete("admin/realms/#{esc(@realm)}/clients/#{esc(id)}", &SettleBody::MARK) }
33
34
  nil
34
35
  end
35
36
  end
@@ -11,7 +11,8 @@ module KeycloakSdk
11
11
  end
12
12
 
13
13
  def create(representation)
14
- id_from_location(request { @conn.post("admin/realms/#{esc(@realm)}/groups", representation) })
14
+ path = "admin/realms/#{esc(@realm)}/groups"
15
+ id_from_location(request { @conn.post(path, representation, &SettleBody::MARK) })
15
16
  end
16
17
 
17
18
  def get(id)
@@ -23,12 +24,12 @@ module KeycloakSdk
23
24
  end
24
25
 
25
26
  def update(id, representation)
26
- request { @conn.put("admin/realms/#{esc(@realm)}/groups/#{esc(id)}", representation) }
27
+ request { @conn.put("admin/realms/#{esc(@realm)}/groups/#{esc(id)}", representation, &SettleBody::MARK) }
27
28
  nil
28
29
  end
29
30
 
30
31
  def delete(id)
31
- request { @conn.delete("admin/realms/#{esc(@realm)}/groups/#{esc(id)}") }
32
+ request { @conn.delete("admin/realms/#{esc(@realm)}/groups/#{esc(id)}", &SettleBody::MARK) }
32
33
  nil
33
34
  end
34
35
  end
@@ -12,7 +12,7 @@ module KeycloakSdk
12
12
 
13
13
  # POST /admin/realms — master realm 전용(realm SA는 403). 반환: realm 이름.
14
14
  def create(representation)
15
- request { @conn.post("admin/realms", representation) }
15
+ request { @conn.post("admin/realms", representation, &SettleBody::MARK) }
16
16
  representation[:realm] || representation["realm"]
17
17
  end
18
18
 
@@ -25,12 +25,12 @@ module KeycloakSdk
25
25
  end
26
26
 
27
27
  def update(realm, representation)
28
- request { @conn.put("admin/realms/#{esc(realm)}", representation) }
28
+ request { @conn.put("admin/realms/#{esc(realm)}", representation, &SettleBody::MARK) }
29
29
  nil
30
30
  end
31
31
 
32
32
  def delete(realm)
33
- request { @conn.delete("admin/realms/#{esc(realm)}") }
33
+ request { @conn.delete("admin/realms/#{esc(realm)}", &SettleBody::MARK) }
34
34
  nil
35
35
  end
36
36
  end
@@ -11,7 +11,7 @@ module KeycloakSdk
11
11
  end
12
12
 
13
13
  def create(representation)
14
- id_from_location(request { @conn.post("admin/realms/#{esc(@realm)}/roles", representation) })
14
+ id_from_location(request { @conn.post("admin/realms/#{esc(@realm)}/roles", representation, &SettleBody::MARK) })
15
15
  end
16
16
 
17
17
  def get(name)
@@ -23,12 +23,12 @@ module KeycloakSdk
23
23
  end
24
24
 
25
25
  def update(name, representation)
26
- request { @conn.put("admin/realms/#{esc(@realm)}/roles/#{esc(name)}", representation) }
26
+ request { @conn.put("admin/realms/#{esc(@realm)}/roles/#{esc(name)}", representation, &SettleBody::MARK) }
27
27
  nil
28
28
  end
29
29
 
30
30
  def delete(name)
31
- request { @conn.delete("admin/realms/#{esc(@realm)}/roles/#{esc(name)}") }
31
+ request { @conn.delete("admin/realms/#{esc(@realm)}/roles/#{esc(name)}", &SettleBody::MARK) }
32
32
  nil
33
33
  end
34
34
  end
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "faraday"
4
+
5
+ module KeycloakSdk
6
+ module Admin
7
+ # admin 응답의 본문을 얼마나 읽는가 — 등록부 admin-response-body-unbounded. 요청 하나의 전송 동안 `Http` 의 net-http
8
+ # 훅에 알린다: 300 이상의 본문은 상한에서 자르고(`raw` 커넥션의 요청도), 파사드 쓰기의 2xx 본문은 읽지 않는다.
9
+ #
10
+ # 쓰기는 응답 모양이 아니라 **요청에 단 표시**로 고른다 — `raw` 로 보낸 쓰기는 본문을 받아야 하고, 표시가 요청 옵션에
11
+ # 있으니 다른 요청(토큰 공급자가 보내는 것 포함)에는 닿지 않는다. `BearerAuth` 뒤·어댑터 바로 앞에 선다.
12
+ class SettleBody < Faraday::Middleware
13
+ UNREAD = :kcsdk_unread
14
+
15
+ # 파사드 쓰기가 요청에 다는 표시(`@conn.post(path, body, &MARK)`).
16
+ MARK = ->(req) { req.options.context = (req.options.context || {}).merge(UNREAD => true) }
17
+
18
+ # 흘려 받는 요청(`on_data` — `raw` 호출자만 쓴다)은 정하지 않는다: 본문은 오는 대로 호출자에게 가고 Faraday 는 쥐지
19
+ # 않는다. 정하면 어댑터가 읽은 응답을 다시 읽어 IOError(read_body called twice)였다.
20
+ def call(env)
21
+ return @app.call(env) if env.stream_response?
22
+
23
+ context = env.request.context
24
+ Http.settling(context.is_a?(Hash) && context[UNREAD] == true) { @app.call(env) }
25
+ end
26
+ end
27
+ private_constant :SettleBody
28
+ end
29
+ end
@@ -11,7 +11,7 @@ module KeycloakSdk
11
11
  end
12
12
 
13
13
  def create(representation)
14
- id_from_location(request { @conn.post("admin/realms/#{esc(@realm)}/users", representation) })
14
+ id_from_location(request { @conn.post("admin/realms/#{esc(@realm)}/users", representation, &SettleBody::MARK) })
15
15
  end
16
16
 
17
17
  def get(id)
@@ -23,12 +23,12 @@ module KeycloakSdk
23
23
  end
24
24
 
25
25
  def update(id, representation)
26
- request { @conn.put("admin/realms/#{esc(@realm)}/users/#{esc(id)}", representation) }
26
+ request { @conn.put("admin/realms/#{esc(@realm)}/users/#{esc(id)}", representation, &SettleBody::MARK) }
27
27
  nil
28
28
  end
29
29
 
30
30
  def delete(id)
31
- request { @conn.delete("admin/realms/#{esc(@realm)}/users/#{esc(id)}") }
31
+ request { @conn.delete("admin/realms/#{esc(@realm)}/users/#{esc(id)}", &SettleBody::MARK) }
32
32
  nil
33
33
  end
34
34
  end
@@ -46,11 +46,17 @@ module KeycloakSdk
46
46
  # 압축된 바이트가 그대로 와 JSON 으로 읽히지 않으므로 SDK 오류로 닫힌다.
47
47
  IDENTITY = { "Accept-Encoding" => "identity" }.freeze
48
48
 
49
+ # admin 응답의 본문을 얼마나 읽는가(admin-response-body-unbounded) — admin 커넥션의 `Admin::SettleBody` 가 요청 하나의
50
+ # 전송 동안만 거는 파이버 지역 값이다. 300 이상의 본문은 `TOKEN_RESPONSE_MAX_BYTES` 에서 자르고, 파사드
51
+ # 쓰기(요청 옵션의 표시)의 2xx 본문은 읽지 않는다 — 둘 다 net-http 가 머리를 읽은 뒤·본문을 읽기 전에 정한다
52
+ # (`BoundedTransport#request`). 그 밖의 성공 본문은 지금처럼 끝까지 읽는다.
53
+ SETTLE = :kcsdk_admin_settle
54
+
49
55
  # Faraday 의 JSON 응답 규칙 그대로(JSON 콘텐츠 타입만 · 빈 본문은 nil · 해석 실패는 Faraday::ParsingError).
50
56
  # 스트리밍으로 읽은 본문은 커넥션의 json 미들웨어가 보지 못하므로(그때 본문은 비어 있다) 여기서 같은 규칙을 건다.
51
57
  JSON_RESPONSE = Faraday::Response::Json.new(nil, content_type: /\bjson$/)
52
58
  UNDECODABLE = "JSON text decodes to invalid UTF-8"
53
- private_constant :IDENTITY, :JSON_RESPONSE, :UNDECODABLE
59
+ private_constant :IDENTITY, :SETTLE, :JSON_RESPONSE, :UNDECODABLE
54
60
 
55
61
  # 소켓 하나에 거는 **싱글턴 확장** — 전역 몽키패치가 아니라 이 SDK 가 연 `BufferedIO` 인스턴스 하나에만 붙는다
56
62
  # (`BoundedHttp#on_connect`). 호스트 애플리케이션의 net-http 는 건드리지 않는다.
@@ -265,6 +271,39 @@ module KeycloakSdk
265
271
  sock.extend(ConnectFraming)
266
272
  sock.kcsdk_arm_connect_framing!
267
273
  end
274
+
275
+ # ── admin 응답 본문(`SETTLE`). faraday-net_http 는 `start` 블록 안에서 `request` 에 블록을 넘기고, 그 블록이 머리를
276
+ # 저장한 뒤 net-http 의 `reading_body` 가 본문을 끝까지 읽는다 — 그 블록 앞에서 본문을 정하면 net-http 는 읽은
277
+ # 응답(`@read`)의 소켓을 더 읽지 않는다. 정한 응답의 소켓은 닫는다(남은 바이트를 다음 요청이 읽지 않게).
278
+ public
279
+
280
+ def request(req, body = nil, &block)
281
+ settle = Thread.current[SETTLE]
282
+ return super unless settle && started?
283
+
284
+ super do |res|
285
+ kcsdk_settle(res, settle[:unread])
286
+ block&.call(res)
287
+ end
288
+ end
289
+
290
+ private
291
+
292
+ def kcsdk_settle(res, unread)
293
+ if res.code.to_i >= 300
294
+ kcsdk_keep(res, Http.read_error_body(res) { @socket.close })
295
+ elsif unread
296
+ kcsdk_keep(res, String.new(encoding: Encoding::BINARY))
297
+ end
298
+ end
299
+
300
+ # ⚠️ **net-http `HTTPResponse` 내부(`@body`·`@read`)에 기댄다** — 읽은 응답의 `body` 는 소켓을 다시 읽지 않고 `@body`
301
+ # 를 돌려준다. 모양은 `admin_response_body_spec` 의 핀이 고정한다.
302
+ def kcsdk_keep(res, body)
303
+ res.instance_variable_set(:@body, body)
304
+ res.instance_variable_set(:@read, true)
305
+ @socket.close
306
+ end
268
307
  end
269
308
 
270
309
  # 표준 `:net_http` 어댑터의 설정 블록 — 커넥션을 짓기 직전 그 `Net::HTTP` 인스턴스의 싱글턴에 `BoundedTransport` 를
@@ -308,6 +347,40 @@ module KeycloakSdk
308
347
  resp
309
348
  end
310
349
 
350
+ # admin 요청 하나의 전송 동안 그 응답의 본문을 정하게 한다(`SETTLE`) — `unread` 면 파사드 쓰기라 2xx 본문을 읽지 않는다.
351
+ def settling(unread)
352
+ previous = Thread.current[SETTLE]
353
+ Thread.current[SETTLE] = { unread: unread }
354
+ yield
355
+ ensure
356
+ Thread.current[SETTLE] = previous
357
+ end
358
+
359
+ # 300 이상의 본문을 `TOKEN_RESPONSE_MAX_BYTES` 까지만 쥔다 — 상한을 넘기는 조각이 오면 읽기를 멈추고 상한에서 자른다
360
+ # (거부하지 않는다: 상태가 이미 오류를 정했다). net-http 가 16 KiB 씩 넘기므로 손에 드는 것은 많아야 상한 + 청크 하나다.
361
+ # ⚠️ 끊기 전에 블록(소켓 닫기)을 부른다 — net-http 의 청크 읽기는 `ensure` 에서 그 청크의 CRLF 를 읽으려 해, 청크
362
+ # 한가운데서 멈춘 서버 앞에서는 끊은 뒤에도 읽기 타임아웃까지 기다렸다(상태를 잃고 TransportError). 닫힌 소켓의 그
363
+ # 읽기가 내는 IOError 는 끊은 뒤의 것만 삼킨다.
364
+ def read_error_body(res)
365
+ buf = String.new(encoding: Encoding::BINARY)
366
+ cut = false
367
+ begin
368
+ catch(:kcsdk_cut) do
369
+ res.read_body do |chunk|
370
+ buf << chunk
371
+ next if buf.bytesize <= TOKEN_RESPONSE_MAX_BYTES
372
+
373
+ cut = true
374
+ yield
375
+ throw :kcsdk_cut
376
+ end
377
+ end
378
+ rescue IOError, SystemCallError
379
+ raise unless cut
380
+ end
381
+ cut ? buf.byteslice(0, TOKEN_RESPONSE_MAX_BYTES) : buf
382
+ end
383
+
311
384
  # `read_capped` 의 본문을 커넥션의 json 미들웨어가 하던 그대로 해석한다(응답을 돌려준다).
312
385
  # ⚠️ 해석한 값의 문자열이 잘못된 UTF-8 이면 해석 실패다(Faraday::ParsingError ← JSON::ParserError — 짝 없는
313
386
  # 서로게이트 이스케이프에서 json 3 이 내는 것과 같은 모양). 고쳐 쓰지 않는다 — 그 값은 SDK 를 지나며 raw 예외가 된다.
@@ -7,6 +7,11 @@ module KeycloakSdk
7
7
  # RS256 핀(none/confusion 구조적 거부)·iss 정확·aud 포함·exp 필수·nbf·클록스큐.
8
8
  # 키는 DoS-safe JwksStore로 조회한다(위조 서명은 재조회 미유발). 헤더 alg는 검증 알고리즘 선택에 미사용.
9
9
  class JwtValidator
10
+ # 받는 토큰의 길이 상한(아홉 언어 공통). Microsoft.IdentityModel 의 `DefaultMaximumTokenSizeInBytes` 와 같은 수이고,
11
+ # Keycloak 26.6 기본값이 받는 가장 긴 Bearer(65,459 B)의 약 3.9 배라 서버가 낸 토큰은 거부하지 않는다.
12
+ JWT_MAX_BYTES = 256_000
13
+ private_constant :JWT_MAX_BYTES
14
+
10
15
  # ⚠️ `clock_skew` 기본값을 여기 숫자로 적지 말 것 — `Config`가 유일한 정의 자리다(Task D1과
11
16
  # 같은 부류). 이 클래스도 public이라 소비자가 직접 생성할 수 있고, 두 자리가 갈리면 그
12
17
  # 경로에서만 만료된 토큰이 더 오래 통과한다.
@@ -34,6 +39,7 @@ module KeycloakSdk
34
39
  # 쓴다 — 키 저장소(캐시 · 재조회 제한 · 백오프)는 그대로 이 인스턴스의 것 하나다.
35
40
  # ⚠️ nil·공백은 생성자와 같이 ConfigError — ruby-jwt 는 `aud: nil` 이면 aud 검사를 건너뛴다.
36
41
  def validate(token, audience: @audience)
42
+ reject_oversized!(token) # ⚠️ 맨 앞이다 — 나누기·디코드·JWKS 적재보다 먼저(아래 메서드)
37
43
  raise ConfigError, "audience is required" if audience.nil? || audience.to_s.strip.empty?
38
44
  # ⚠️ ruby-jwt 는 맨 먼저 토큰을 `split` 하고, 잘못된 UTF-8 이면 그것이 raw ArgumentError 다(실측).
39
45
  if token.is_a?(String) && !token.valid_encoding?
@@ -50,6 +56,15 @@ module KeycloakSdk
50
56
 
51
57
  private
52
58
 
59
+ # 길이 상한 — ruby-jwt 는 서명을 보기 전에 토큰을 나누고 base64·JSON 디코드하며(할당이 길이에 비례한다), 키는
60
+ # 그 뒤에 JWKS 에서 찾는다. 단위는 `bytesize`(진짜 JWT 는 ASCII 라 문자 수와 같다)이고, 잘못된 UTF-8 이어도 잴 수
61
+ # 있어 `validate` 의 인코딩 검사보다 앞이다. String 이 아닌 값은 지금처럼 ruby-jwt 가 거부한다.
62
+ def reject_oversized!(token)
63
+ return unless token.is_a?(String) && token.bytesize > JWT_MAX_BYTES
64
+
65
+ raise TokenValidationError, "JWT validation failed: token exceeds #{JWT_MAX_BYTES} bytes"
66
+ end
67
+
53
68
  def decode_options(audience)
54
69
  {
55
70
  algorithms: @algorithms,
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module KeycloakSdk
4
- VERSION = "1.3.2"
4
+ VERSION = "1.4.0"
5
5
  end
data/lib/keycloak_sdk.rb CHANGED
@@ -13,6 +13,7 @@ require_relative "keycloak_sdk/jwt_validator"
13
13
  require_relative "keycloak_sdk/auth_client"
14
14
  require_relative "keycloak_sdk/admin/call"
15
15
  require_relative "keycloak_sdk/admin/bearer_auth"
16
+ require_relative "keycloak_sdk/admin/settle_body"
16
17
  require_relative "keycloak_sdk/admin/users"
17
18
  require_relative "keycloak_sdk/admin/clients"
18
19
  require_relative "keycloak_sdk/admin/realms"
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: keycloak-sdk
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.3.2
4
+ version: 1.4.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - xzawed
@@ -84,6 +84,7 @@ files:
84
84
  - lib/keycloak_sdk/admin/groups.rb
85
85
  - lib/keycloak_sdk/admin/realms.rb
86
86
  - lib/keycloak_sdk/admin/roles.rb
87
+ - lib/keycloak_sdk/admin/settle_body.rb
87
88
  - lib/keycloak_sdk/admin/users.rb
88
89
  - lib/keycloak_sdk/auth_client.rb
89
90
  - lib/keycloak_sdk/client.rb