keycloak-sdk 1.3.1 → 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: 561abaa5612faf7d8d0b60dda6e925f2db242ae134e0fe68f97469ce3456ab26
4
- data.tar.gz: 1b2ff3c20ae257420c10a0d87cca3298059aa1f4c716c0c2179874eb0550f1ab
3
+ metadata.gz: 52cd15ebf26da1523bdb1d8fd7a686c67204fac085a5031f2754ecade75db80f
4
+ data.tar.gz: 1ca086fe490283624960266fa63fa88b4213d54de13a359f6cab10361aeea520
5
5
  SHA512:
6
- metadata.gz: 2ec9e56d3bcc400a6ac1cd541e2e85e3ac31de448ec5ebec1a6f033c5e814ed145d9ab2d27543c0a68a74ce521d95e3227a1290d3d0c47933e53274b07f2b28c
7
- data.tar.gz: cf086c552fa47a7c5783850e0766a7590c47788d94b50ee27ebaaf913216490f4c8b1237fab715ac578b3160ad70f82d293b226a3301460d14fff6af0e077e0e
6
+ metadata.gz: 2c4b2142282d0ca792dee70d3e5cda365813d0ecd3baa56a212dc88eed68a4c3a6d73649e93d20e5ca8e748cdae5ea19e6ea5542547d72d7879bc8f6765c6fea
7
+ data.tar.gz: a302586a9f15242ca397db66b80f19f27898564b2d266edd3674a6a6e8b5e2e78587480dd6be474213472ec543df2a4415b436bfb8ff8c962d980346f5b6c033
data/README.md CHANGED
@@ -4,7 +4,11 @@ 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.1` is on RubyGems** — a patch release on top of `1.3.0`; `1.0.0` was the first release carrying the stability guarantee. A bare `gem install keycloak-sdk` resolves it. **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.
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.
10
+ >
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.
8
12
 
9
13
  ## Requirements
10
14
 
@@ -66,6 +70,7 @@ The SDK replaces the unsafe library defaults rather than inheriting them:
66
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.
67
71
  - **Strict claim checks** — exact `iss` match, `aud` containment, mandatory `exp`, `nbf` enforced when present, and a bounded clock skew.
68
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.
69
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).
70
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).
71
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
@@ -36,9 +36,26 @@ module KeycloakSdk
36
36
  rescue StandardError => e
37
37
  # 원본을 달면 `Faraday::ParsingError#inspect` 가 요청의 베어러 토큰을, 메시지가 응답 앞부분을 찍는다(실측).
38
38
  # Faraday 밖 예외도 감싼다 — net-http 0.10 의 응답 헤더 검증 ArgumentError 는 헤더 이름을 인용한다.
39
+ status = unparsable_error_status(e)
40
+ if status
41
+ raise AdminError.from_status(status, "admin request failed: HTTP #{status}"), cause: RedactedCause.new(e)
42
+ end
43
+
39
44
  raise TransportError, "admin transport error: #{RedactedCause.describe(e)}", cause: RedactedCause.new(e)
40
45
  end
41
46
 
47
+ # 커넥션의 json 미들웨어는 상태 검사보다 먼저 해석한다 — JSON 이라면서 JSON 이 아닌 **오류** 본문(404·409·403 …)이어도
48
+ # 상태가 클래스를 정한다(.NET 과 같다). 2xx 의 해석 실패는 전송 오류 그대로다(nil).
49
+ # ⚠️ `Faraday::Error#response_status` 를 쓰지 않는다 — faraday 2.0.0 은 응답 객체에 `[:status]` 를 묻고, 그것은
50
+ # `headers[:status]` 로 위임돼 nil 이다. 응답 객체면 `status`, 해시면 `[:status]` 를 읽는다.
51
+ def unparsable_error_status(err)
52
+ return unless err.is_a?(Faraday::ParsingError)
53
+
54
+ resp = err.response
55
+ status = resp.respond_to?(:status) ? resp.status : (resp[:status] if resp.is_a?(Hash))
56
+ status if status.is_a?(Integer) && !(200..299).cover?(status)
57
+ end
58
+
42
59
  def id_from_location(resp)
43
60
  loc = resp.headers["location"]
44
61
  loc&.split("/")&.last
@@ -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 는 건드리지 않는다.
@@ -146,6 +152,73 @@ module KeycloakSdk
146
152
  end
147
153
  end
148
154
 
155
+ # ⚠️ **프록시 CONNECT 응답의 틀 상한** — HTTPS 대상을 프록시로 부르면 net-http `connect` 는 프록시 소켓 위에 **지역**
156
+ # `BufferedIO` 를 따로 만들어 CONNECT 응답(`HTTPResponse.read_new`)을 읽는다. `on_connect` 보다 앞이라 `BoundedReads` 가
157
+ # 그 읽기를 못 봤다(ruby-framing-proxy-connect-unbounded — net-http 0.9.1 은 996,039 B 머리 블록도 받고 TLS 로
158
+ # 넘어갔고, 0.10.0 은 상태 줄·블록을 1 MiB 까지 받았다 · 65,536 B 넘는 헤더 값만 다 읽은 뒤 raw ArgumentError).
159
+ # 그 `BufferedIO` 는 잡을 자리가 없으니(전역 패치 금지) 그것이 읽는 **소켓 하나**에 건다 — `rbuf_fill` 이 부르는
160
+ # `read_nonblock` 이 돌려준 바이트를 세어 `BoundedReads` 와 같은 두 상한(줄은 종단 문자까지 8,192 · 블록은 빈 줄까지
161
+ # 65,536)을 넘으면 같은 상수 메시지의 `TransportError` 다(`connect` 의 rescue 가 그 소켓을 닫는다). 빈 줄(첫 줄 뒤의
162
+ # "\r\n"·"\n" — 두 읽기에 갈려도)에서 꺼진다: 그 뒤 바이트는 손대지 않고 돌려주고(net-http 가 버린다) 그 소켓의 뒤
163
+ # 읽기는 세지 않는다.
164
+ # ⚠️ 빈 줄은 "\r\n"·"\n" 둘뿐이다(0.10 의 `chomp` 와 같다) — 0.9.1 처럼 공백만 있는 줄까지 끝으로 보면 그 줄 하나로
165
+ # 상한을 끌 수 있다.
166
+ module ConnectFraming
167
+ # 시그니처는 상류(`IO`·`OpenSSL::Buffering`)와 같다 — `BufferedIO#rbuf_fill` 은 `read_nonblock(BUFSIZE, tmp,
168
+ # exception: false)` 로 부르고(`http_framing_pins_spec`), 받은 버퍼를 같은 객체로 돌려받기를 기대한다.
169
+ def read_nonblock(len, buf = nil, exception: true)
170
+ chunk = super
171
+ kcsdk_connect_scan(chunk) if @kcsdk_connect_armed && chunk.is_a?(String)
172
+ chunk
173
+ end
174
+
175
+ def kcsdk_arm_connect_framing!
176
+ @kcsdk_connect_armed = true
177
+ @kcsdk_connect_total = 0 # 끝난 줄들의 바이트(종단 문자 포함)
178
+ @kcsdk_connect_line = 0 # 지금 줄에 쌓인 바이트 — 아직 "\n" 전
179
+ @kcsdk_connect_last = nil # 그 쌓인 바이트의 마지막 — "\r" 하나로 읽기가 끝났으면 다음 읽기의 "\n" 과 빈 줄이다
180
+ end
181
+
182
+ def kcsdk_connect_framing_armed?
183
+ @kcsdk_connect_armed == true
184
+ end
185
+
186
+ private
187
+
188
+ # ⚠️ 바이트 위치로 읽는다(`byteindex`·`getbyte`) — 소켓이 돌려주는 BINARY 문자열에서 위치는 늘 바이트다.
189
+ def kcsdk_connect_scan(chunk)
190
+ from = 0
191
+ while @kcsdk_connect_armed && (eol = chunk.byteindex("\n", from))
192
+ kcsdk_connect_line_end(chunk, from, eol)
193
+ from = eol + 1
194
+ end
195
+ kcsdk_connect_partial(chunk, from) if @kcsdk_connect_armed && from < chunk.bytesize
196
+ end
197
+
198
+ # 빈 줄 = 첫 줄이 아닌 "\n"(1 바이트) 또는 "\r\n"(2 바이트) — 2 바이트 줄의 "\r" 은 "\n" 바로 앞 바이트다.
199
+ def kcsdk_connect_line_end(chunk, from, eol)
200
+ before = eol > from ? chunk.getbyte(eol - 1) : @kcsdk_connect_last
201
+ len = @kcsdk_connect_line + eol + 1 - from
202
+ kcsdk_connect_bound(len)
203
+ blank = @kcsdk_connect_total.positive? && (len == 1 || (len == 2 && before == 13))
204
+ @kcsdk_connect_total += len
205
+ @kcsdk_connect_line = 0
206
+ @kcsdk_connect_armed = false if blank
207
+ end
208
+
209
+ def kcsdk_connect_partial(chunk, from)
210
+ @kcsdk_connect_line += chunk.bytesize - from
211
+ @kcsdk_connect_last = chunk.getbyte(-1)
212
+ kcsdk_connect_bound(@kcsdk_connect_line)
213
+ end
214
+
215
+ # `BoundedReads#kcsdk_bound_line` 와 같은 경계다 — 줄이든 블록이든 상한과 **같으면** 받고 넘으면 거부한다.
216
+ def kcsdk_connect_bound(len)
217
+ raise KeycloakSdk::TransportError, FRAMING_LINE_MSG if len > MAX_FRAMING_LINE_BYTES
218
+ raise KeycloakSdk::TransportError, FRAMING_TOTAL_MSG if @kcsdk_connect_total + len > MAX_FRAMING_BYTES
219
+ end
220
+ end
221
+
149
222
  # `Net::HTTP` 인스턴스의 싱글턴에 **prepend** 해 소켓이 만들어지는 자리(`on_connect`, `connect` 끝)에서 그 소켓에만
150
223
  # `BoundedReads` 를 건다. `begin_transport` 는 요청마다 틀 예산을 0 으로 되돌린다 — keep-alive 로 연결을 재사용해도
151
224
  # 다음 응답은 새 예산을 받는다(한 요청의 1xx 중간 응답들은 같은 예산을 나눠 쓴다 — 그래야 1xx 홍수도 묶인다).
@@ -167,6 +240,70 @@ module KeycloakSdk
167
240
  super
168
241
  @socket.kcsdk_reset_framing! if @socket.respond_to?(:kcsdk_reset_framing!)
169
242
  end
243
+
244
+ # ── 프록시 CONNECT(`ConnectFraming`) — `connect` 가 소켓을 여는 두 자리. 상한은 CONNECT 응답을 나르는 소켓에만 걸고
245
+ # 대상과의 TLS 소켓은 건드리지 않는다. ⚠️ `timeouted_connect` 는 net-http 0.9.0 에 생겼다 — gemspec 하한이다.
246
+
247
+ # 연결마다 「이 `connect` 의 첫 `ssl_socket_connect`」를 되돌린다(keep-alive 가 끊긴 뒤 다시 열 때도 같다).
248
+ def connect
249
+ @kcsdk_connect_tls_pending = true
250
+ super
251
+ end
252
+
253
+ # 평문 프록시 + HTTPS 대상 — net-http 는 이 TCP 소켓을 그대로 BufferedIO 로 감싸 CONNECT 응답을 읽는다.
254
+ def timeouted_connect(conn_addr, conn_port)
255
+ sock = super
256
+ kcsdk_bound_connect(sock) if proxy? && use_ssl? && !@proxy_use_ssl
257
+ sock
258
+ end
259
+
260
+ # TLS 프록시 + HTTPS 대상 — 이 `connect` 의 **첫** 호출이 프록시와의 TLS 소켓(CONNECT 응답을 나른다)이고, 둘째는
261
+ # 대상과의 TLS 다. `@proxy_use_ssl` 은 `connect` 가 가르는 그 ivar 다(공개 읽기가 없다 — 모양은 핀으로 고정).
262
+ def ssl_socket_connect(sock, timeout)
263
+ first = @kcsdk_connect_tls_pending
264
+ @kcsdk_connect_tls_pending = false
265
+ result = super
266
+ kcsdk_bound_connect(sock) if first && proxy? && use_ssl? && @proxy_use_ssl
267
+ result
268
+ end
269
+
270
+ def kcsdk_bound_connect(sock)
271
+ sock.extend(ConnectFraming)
272
+ sock.kcsdk_arm_connect_framing!
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
170
307
  end
171
308
 
172
309
  # 표준 `:net_http` 어댑터의 설정 블록 — 커넥션을 짓기 직전 그 `Net::HTTP` 인스턴스의 싱글턴에 `BoundedTransport` 를
@@ -175,7 +312,7 @@ module KeycloakSdk
175
312
  BOUND_CONNECTION = lambda do |http|
176
313
  http.singleton_class.prepend(BoundedTransport)
177
314
  end
178
- private_constant :BoundedReads, :BoundedTransport, :BOUND_CONNECTION
315
+ private_constant :BoundedReads, :ConnectFraming, :BoundedTransport, :BOUND_CONNECTION
179
316
 
180
317
  module_function
181
318
 
@@ -210,6 +347,40 @@ module KeycloakSdk
210
347
  resp
211
348
  end
212
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
+
213
384
  # `read_capped` 의 본문을 커넥션의 json 미들웨어가 하던 그대로 해석한다(응답을 돌려준다).
214
385
  # ⚠️ 해석한 값의 문자열이 잘못된 UTF-8 이면 해석 실패다(Faraday::ParsingError ← JSON::ParserError — 짝 없는
215
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.1"
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.1
4
+ version: 1.4.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - xzawed
@@ -37,6 +37,20 @@ dependencies:
37
37
  - - "~>"
38
38
  - !ruby/object:Gem::Version
39
39
  version: '3.2'
40
+ - !ruby/object:Gem::Dependency
41
+ name: net-http
42
+ requirement: !ruby/object:Gem::Requirement
43
+ requirements:
44
+ - - ">="
45
+ - !ruby/object:Gem::Version
46
+ version: '0.9'
47
+ type: :runtime
48
+ prerelease: false
49
+ version_requirements: !ruby/object:Gem::Requirement
50
+ requirements:
51
+ - - ">="
52
+ - !ruby/object:Gem::Version
53
+ version: '0.9'
40
54
  - !ruby/object:Gem::Dependency
41
55
  name: rack-oauth2
42
56
  requirement: !ruby/object:Gem::Requirement
@@ -70,6 +84,7 @@ files:
70
84
  - lib/keycloak_sdk/admin/groups.rb
71
85
  - lib/keycloak_sdk/admin/realms.rb
72
86
  - lib/keycloak_sdk/admin/roles.rb
87
+ - lib/keycloak_sdk/admin/settle_body.rb
73
88
  - lib/keycloak_sdk/admin/users.rb
74
89
  - lib/keycloak_sdk/auth_client.rb
75
90
  - lib/keycloak_sdk/client.rb