keycloak-sdk 1.3.2 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 51b3c59bfdc3c281f3a6b71faaa6fba7e9561399bfa9e352cf275cbc42718617
4
- data.tar.gz: 3260c90043c5d10f253266af8fc3786c7212906b1b460bfd05eb1e49cb0e38ed
3
+ metadata.gz: e3968afa42f3c2e2df3716ac09af5773c2c7f9290e7310f2f4b51b1f79e1603f
4
+ data.tar.gz: 06b96f67524ae3161e8be14fb09246f1faa9190e4b8df5b04bf1075408e74c7f
5
5
  SHA512:
6
- metadata.gz: 04b4477363357a3fdfa3a2c324dfdbd8a992c28a8ce163f84ac65fa6f6a0bfbf591a9261786a7251f91de1d3398b5f8b279be7f696f56e709009e8f1e308274e
7
- data.tar.gz: da685f6729d4aa0362a9d71397c23aab3205b63aae49da6199b64348d8764d4c6988dfe0be9095d912f0fbd1eab9ab9899bebff999327a06bf851c94de31eccf
6
+ metadata.gz: ac65a88b4593b5da59b654b4240ccd4e430164323c10dba1c11457b1b118ab92c1921b52cd76524f8be5460ff3931594db370e5b77ec681f31ce98ccc6645a78
7
+ data.tar.gz: 0bbb4b5036db0b34fa52ae74edb2be7bf779c0e2c386d45a2c38483000756638ce0f83cfedda951f799a0c9b28d8269ff047cf21a0a3b90f0bc794804590d6c7
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.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.1` is on RubyGems** — a patch release on top of `1.4.0`; `1.0.0` was the first release carrying the stability guarantee. A bare `gem install keycloak-sdk` resolves it. **Security**: the admin client now holds the access token it sends as a Bearer to one rule shared by all nine SDKs: leading and trailing SP, HTAB, CR and LF are stripped, and unless what remains is a non-empty RFC 6750 `b64token` (ASCII letters and digits and `-._~+/`, with `=` only at the end) the request is not sent and the call fails with `AuthError`, which does not quote the token. `BearerAuth` (the facade and `raw`) and the SDK's provider apply it, and the provider does not cache such a token. It used to reject a leading or trailing space or tab and to send an inner space or a non-ASCII character as is. ⚠️ A token that ends in a newline, or starts or ends with a space or tab, used to be rejected and is now stripped and sent. An access token that is not a String now gets the same check, on the text that goes into the header: a consumer `TokenProvider` that returned a Symbol holding CR or LF made the `raw` connection raise a raw `ArgumentError` quoting the whole Bearer and the facade raise `TransportError` (`admin transport error: ArgumentError`), a Symbol holding NUL or a trailing space went out as is or with the space removed, and `nil` or `""` went out as `Authorization: Bearer` (measured). These now raise the same `AuthError` as a String, and an empty token sends no request (`admin request not sent: the access token is empty`). A Symbol or number that passes the check still goes out as that text, and the SDK's `ClientCredentialsTokenProvider` always yields a non-empty String, so it is unaffected. The responses the SDK reads itself (token, introspection, JWKS and admin) are now read in full within the configured timeout, counted from when the request is sent. The timeout used to apply to each read only, so a server that trickled bytes, each just inside the read timeout, held one call for about the size cap times the read timeout (7 seconds with a 1-second setting); such a call now ends with the existing timeout error, within the deadline plus one read. A JWKS key set now expires 300 seconds after the load that fetched it finished, and an expired set is treated as a cold cache: the next validation fetches it again through the cold-load path (the same single flight and the same failure backoff) and rejects the token if that fetch fails, instead of validating with the stale keys. Until now the Ruby SDK gave a key set no lifetime, so it kept accepting a key the IdP had removed until a token with a new `kid` arrived. ⚠️ If the JWKS cannot be reached for more than 300 seconds, validation fails — by design, because the SDK cannot tell an unreachable JWKS from a key the IdP has removed. The failure backoff's jitter (×[0.5, 1.0)) was drawn again at every check, so the same failure could refuse a validation at 190 ms and send the next one to the IdP at 191 ms; it is now drawn once, when the failure happens. **Fixed**: building a `KeycloakClient` set the `Config` timeouts on rack-oauth2's process-wide `Rack::OAuth2.http_config`, and rack-oauth2 keeps only the first block set, so when the SDK was built first, a block the host application set later was silently dropped. The SDK's requests do not use that connection, so it no longer sets it. ⚠️ Code in the same process that uses rack-oauth2 directly no longer inherits the SDK's timeouts — set `Rack::OAuth2.http_config` yourself if it needs them. **Changed**: ⚠️ an admin response — lists and `raw` success bodies included — must now arrive in full within the configured timeout (the response deadline above). The timeout used to apply per read, so a large list over a slow link was received to its end; that is now a timeout error, so raise the timeout if you fetch large lists over a slow link. The Go, Rust, Node, PHP and .NET admin clients already behaved this way. The documentation YARD renders (the public API, including the comments shown in the source view of public methods) is now in English; the code is unchanged. No public API changed.
8
+ >
9
+ > `1.4.0` was a minor release on top of `1.3.2`. 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.
10
+ >
11
+ > `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
12
  >
9
13
  > `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
14
 
@@ -67,7 +71,8 @@ The SDK replaces the unsafe library defaults rather than inheriting them:
67
71
 
68
72
  - **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
73
  - **Strict claim checks** — exact `iss` match, `aud` containment, mandatory `exp`, `nbf` enforced when present, and a bounded clock skew.
70
- - **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.
74
+ - **DoS-safe JWKS** — a fetched key set is used for 300 seconds. The first validation after that fetches it again, and if that fetch fails the validation fails (`KeycloakSdk::TransportError`): keys older than 300 seconds are never used, even during an IdP outage. Within those 300 seconds 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 on top of that 300-second refetch. 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.
75
+ - **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
76
  - **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
77
  - **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
78
 
@@ -2,8 +2,8 @@
2
2
 
3
3
  module KeycloakSdk
4
4
  module Admin
5
- # Admin REST 파사드. gem 없이 Faraday로 직접 래핑하고, bearer는 주입된 TokenProvider에서 소싱한다.
6
- # representation은 plain hash로 통과한다(문서화된 은닉성 예외).
5
+ # Admin REST facade. It wraps the API directly with Faraday, without a gem, and sources the bearer from the
6
+ # injected TokenProvider. Representations pass through as plain hashes (a documented hiding exception).
7
7
  class AdminClient
8
8
  def initialize(config:, token_provider:)
9
9
  @config = config
@@ -30,23 +30,29 @@ module KeycloakSdk
30
30
  Groups.new(@conn, @config.realm)
31
31
  end
32
32
 
33
- # 탈출구: 내부 Faraday 커넥션(base = {server_url}/, bearer 자동).
33
+ # Escape hatch: the internal Faraday connection (base = {server_url}/, bearer attached automatically).
34
34
  def raw
35
35
  @conn
36
36
  end
37
37
 
38
- # 자원 정리: 내부 Faraday 커넥션을 닫는다(§4 close 계약 — KeycloakClient#close가 위임).
38
+ # Releases resources: closes the internal Faraday connection (§4 close contract — KeycloakClient#close
39
+ # delegates to it).
39
40
  def close
40
41
  @conn.close if @conn.respond_to?(:close)
41
42
  end
42
43
 
43
44
  private
44
45
 
46
+ # ⚠️ admin 요청은 인코딩 없는 본문을 청한다 — Accept-Encoding 이 없으면 net-http 가 gzip 을 청하고 상한 위에서 푼다
47
+ # (`SettleBody` 가 오류 본문을 끊어도 그 inflater 는 읽은 압축 조각을 끝까지 푼다 · `Http::IDENTITY` 와 같은 까닭).
48
+ # 요청에 이 머리가 있으면 net-http 는 자기 것을 붙이지 않고 풀지도 않는다.
45
49
  def build_conn(config, token_provider)
46
50
  Http.build(config, base_url: "#{config.server_url}/") do |f|
51
+ f.headers["Accept-Encoding"] = "identity"
47
52
  f.request :json
48
53
  f.response :json, content_type: /\bjson$/
49
54
  f.use BearerAuth, token_provider
55
+ f.use SettleBody
50
56
  end
51
57
  end
52
58
  end
@@ -5,7 +5,7 @@ require "net/http"
5
5
 
6
6
  module KeycloakSdk
7
7
  module Admin
8
- # 매 요청마다 TokenProvider에서 bearer 토큰을 소싱해 Authorization 헤더를 설정한다.
8
+ # Sources a bearer token from the TokenProvider on every request and sets the Authorization header.
9
9
  class BearerAuth < Faraday::Middleware
10
10
  def initialize(app, token_provider)
11
11
  super(app)
@@ -13,37 +13,37 @@ module KeycloakSdk
13
13
  end
14
14
 
15
15
  def on_request(env)
16
- token = @token_provider.access_token
17
- sendable!(token) if token.is_a?(String)
16
+ token = sendable!(bearer_text(@token_provider.access_token))
18
17
  env.request_headers["Authorization"] = "Bearer #{token}"
19
18
  end
20
19
 
21
20
  private
22
21
 
23
- # ⚠️ **net-http 가 헤더에 실을 수 없는 Bearer 는 보내기 전에 SDK 오류로 거부한다.** net-http 는 요청 헤더를 만들
24
- # 때(`initialize_http_header`) CR·LF 면 헤더 값을 **통째로 인용한** raw ArgumentError(= Bearer 누출)를,
25
- # `MAX_FIELD_LENGTH`(65,536)를 넘으면 raw ArgumentError 를, 잘못된 UTF-8 이면 `strip` 의 raw
26
- # Encoding::CompatibilityError 를 낸다 — 셋 다 admin 경계(`rescue Faraday::Error`)를 지나 샜다(실측).
27
- # ⚠️ **같은 `value.strip`(0.9.1 header.rb:195)이 끝의 NUL·공백·탭·VT·FF 를 말없이 지운다** — 다른 토큰이 나갔다.
28
- # 앞의 공백·탭은 그대로 나가지만 받는 쪽이 `Bearer` 뒤 공백으로 접고(RFC 9110 §11.4 `1*SP`), NUL·그 밖의 C0·DEL 은
29
- # 어디 있든 그대로 나가지만 헤더 값에 올 수 없다(§5.5 — field-vchar·SP·HTAB 뿐). 셋 다 같은 거부다(실측 · 시험).
30
- # ⚠️ 고쳐 쓰지 않는다(잘라내거나 바꿔 보내면 다른 토큰이다). 헤더 값에 올 수 있는 것(가운데 공백·탭 · U+00FF
31
- # 위 문자)은 그대로 보내고 판정은 서버에 맡긴다. 메시지에는 토큰을 싣지 않는다(길이만).
32
- def sendable!(token)
33
- raise AuthError, "admin request not sent: the access token is not valid UTF-8" unless token.valid_encoding?
34
-
35
- if token.match?(/[\r\n]/)
36
- raise AuthError, "admin request not sent: the access token holds CR or LF, which an HTTP header cannot carry"
37
- end
38
- if token.match?(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/)
39
- raise AuthError, "admin request not sent: the access token holds NUL, DEL or another control character, " \
40
- "which an HTTP header cannot carry"
41
- end
42
- if token.match?(/\A[ \t]|[ \t]\z/)
43
- raise AuthError, "admin request not sent: the access token starts or ends with a space or tab, which an " \
44
- "HTTP header cannot carry"
22
+ # ⚠️ **검사는 헤더에 실릴 글에 건다 — String 이 아닌 값도.** 덕 계약은 String 이지만 주입한 provider 는 무엇이든
23
+ # 돌려줄 수 있고 헤더에 실리던 것은 그 값의 글이다 — String 일 때만 검사하던 때 CR 든 Symbol 은 `raw` 에서 Bearer 를
24
+ # 통째로 인용한 raw ArgumentError 였다(실측). String 이 아니라고 거부하지 않는다(검사를 지나는 Symbol·숫자는 예전
25
+ # 글 그대로 나간다). 글로는 **한 번만** 바꿔 검사한 글을 보낸다. `to_s` 가 아니라 보간인 것은 예전 헤더와 같은
26
+ # 바이트라서다 — `to_s` 가 String 이 아닌 것을 돌려주면 보간은 그것을 `#<Class:0x…>` 로 바꾸고, 그 글은 문법이 거부한다.
27
+ def bearer_text(token)
28
+ token.is_a?(String) ? token : "#{token}" # rubocop:disable Style/RedundantInterpolation
29
+ end
30
+
31
+ # ⚠️ **보내기 전에 bearer 문법(`BearerGrammar` — token_provider.rb)으로 다듬거나 SDK 오류로 거부한다.** 다듬은 값을
32
+ # 돌려준다. 거부는 넷을 한 번에 막는다 — net-http 의 raw 예외(CR·LF 면 헤더 값을 **통째로 인용한** ArgumentError, 잘못된
33
+ # UTF-8 이면 `strip` 의 Encoding::CompatibilityError — admin 경계를 지나 샜다), 그 `strip`(0.9.1 header.rb:195)이 끝의
34
+ # NUL·VT·FF 를 말없이 지워 보낸 다른 토큰, 「Authorization: Bearer」로 나간 빈 토큰(nil 의 글도 ""), 헤더 값에는 올 수
35
+ # 있지만 bearer 가 아닌 것(가운데 공백·탭 · ASCII 밖 — 예전에는 그대로 보냈다). 메시지에는 토큰을 싣지 않는다(길이만).
36
+ def sendable!(text)
37
+ token = BearerGrammar.sendable(text)
38
+ unless token
39
+ raise AuthError, "admin request not sent: the access token is not an RFC 6750 bearer token (b64token)"
45
40
  end
46
41
 
42
+ fits_field!(token)
43
+ token
44
+ end
45
+
46
+ def fits_field!(token)
47
47
  limit = field_limit
48
48
  return if limit.nil? || "Bearer ".bytesize + token.bytesize <= limit
49
49
 
@@ -4,7 +4,8 @@ require "erb"
4
4
 
5
5
  module KeycloakSdk
6
6
  module Admin
7
- # 리소스 공용: 요청 실행 + 오류 경계 변환 + Location 헤더 id 추출 + 경로 세그먼트 이스케이프.
7
+ # Shared by the resources: request execution + error conversion at the boundary + id extraction from the
8
+ # Location header + path segment escaping.
8
9
  module Call
9
10
  private
10
11
 
@@ -11,25 +11,26 @@ 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)
18
19
  request { @conn.get("admin/realms/#{esc(@realm)}/clients/#{esc(id)}") }.body
19
20
  end
20
21
 
21
- # client_id로 조회: 목록 + 필터(admin은 내부 uuid 키).
22
+ # Lookup by client_id: list + filter (admin keys on the internal uuid).
22
23
  def list(**params)
23
24
  request { @conn.get("admin/realms/#{esc(@realm)}/clients", params) }.body
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
@@ -2,7 +2,7 @@
2
2
 
3
3
  module KeycloakSdk
4
4
  module Admin
5
- # top-level — name 키.
5
+ # top-level — keyed by name.
6
6
  class Realms
7
7
  include Call
8
8
 
@@ -10,9 +10,9 @@ module KeycloakSdk
10
10
  @conn = conn
11
11
  end
12
12
 
13
- # POST /admin/realms — master realm 전용(realm SA는 403). 반환: realm 이름.
13
+ # POST /admin/realms — master realm only (a realm SA gets 403). Returns: the realm name.
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
@@ -7,14 +7,19 @@ require "base64"
7
7
  require "uri"
8
8
 
9
9
  module KeycloakSdk
10
- # 인증 파사드. 인가 URL(PKCE)은 rack-oauth2 로 만들고, 세 그랜트·introspection(RFC7662)·logout 은 SDK 의 Faraday
11
- # 커넥션으로 직접 보낸다 — 토큰 응답 본문을 상한까지만 읽어야 하는데 rack-oauth2 는 자기 커넥션으로 통째로 읽는다.
12
- # TokenProvider를 구현하지만(직접 사용용), admin은 캐싱 ClientCredentialsTokenProvider를 별도로 쓴다(§4).
10
+ # Authentication facade. The authorization URL (PKCE) is built with rack-oauth2, while the three grants ·
11
+ # introspection (RFC7662) · logout are sent directly on the SDK's Faraday connection — the token response body has
12
+ # to be read only up to the cap, but rack-oauth2 reads it whole on its own connection.
13
+ # ⚠️ That is why `Rack::OAuth2.http_config` is not set — it is global and whoever sets it first wins
14
+ # (`@@http_config ||= block`), so for the SDK it would be useless and would only discard the block the host app
15
+ # sets later ("is left to the host" in `auth_client_spec`).
16
+ # It implements TokenProvider (for direct use), but admin uses a separate caching ClientCredentialsTokenProvider (§4).
13
17
  class AuthClient
14
18
  include TokenProvider
15
19
 
16
- # 메시지에 실어도 되는 OAuth 오류 코드 모양 — RFC 6749·OIDC 등록 코드와 Keycloak 코드는 전부 이 모양이고,
17
- # 토큰·시크릿(JWT·base64·hex·UUID)은 대문자·숫자·점·하이픈 때문에 걸러진다.
20
+ # The shape of an OAuth error code that may go into a message — RFC 6749 · OIDC registered codes and Keycloak's
21
+ # codes all have this shape, while tokens and secrets (JWT · base64 · hex · UUID) are filtered out by their
22
+ # uppercase letters, digits, dots and hyphens.
18
23
  OAUTH_CODE = /\A[a-z_]{1,64}\z/
19
24
 
20
25
  def initialize(config:, http:, jwt_validator:)
@@ -22,7 +27,6 @@ module KeycloakSdk
22
27
  @http = http
23
28
  @jwt_validator = jwt_validator
24
29
  @endpoints = OidcEndpoints.from_config(config)
25
- configure_rack_oauth2_timeouts(config)
26
30
  end
27
31
 
28
32
  def create_authorization_request(redirect_uri:, scopes: nil, state: SecureRandom.urlsafe_base64(24),
@@ -40,10 +44,11 @@ module KeycloakSdk
40
44
  AuthorizationRequest.new(url: url.to_s, state: state, code_verifier: verifier, nonce: nonce)
41
45
  end
42
46
 
43
- # `expected_nonce`가 주어지면(create_authorization_request가 항상 돌려주는 nonce) 응답 id_token을
44
- # realm JWKS로 서명·iss·aud(client_id)·exp까지 강화 검증한 뒤 nonce 클레임을 대조한다 — OIDC nonce 재생
45
- # 방지. 불일치·부재·검증실패는 모두 거부(fail-closed). 생략 시 id_token 검증을 건너뛴다
46
- # (여덟 언어 공통 — exchange에서 nonce를 필수로 만들지 않는다).
47
+ # When `expected_nonce` is given (the nonce create_authorization_request always returns), the response's id_token
48
+ # goes through hardened validation against the realm JWKS — signature · iss · aud (client_id) · exp — before its
49
+ # nonce claim is compared: OIDC nonce replay protection. Mismatch, absence and validation failure are all
50
+ # rejected (fail-closed). When omitted, id_token validation is skipped
51
+ # (common to the eight languages — exchange does not make the nonce mandatory).
47
52
  def exchange_code(code:, code_verifier:, redirect_uri:, expected_nonce: nil)
48
53
  token_set = token_request("authorization_code exchange",
49
54
  { grant_type: "authorization_code", code: code, redirect_uri: redirect_uri,
@@ -60,7 +65,7 @@ module KeycloakSdk
60
65
  token_request("client-credentials", { grant_type: "client_credentials", scope: @config.scopes.join(" ") })
61
66
  end
62
67
 
63
- # TokenProvider 계약(직접 사용용). admin은 캐싱 provider를 별도로 쓴다.
68
+ # TokenProvider contract (for direct use). admin uses a separate caching provider.
64
69
  def access_token
65
70
  client_credentials_token.access_token
66
71
  end
@@ -75,14 +80,16 @@ module KeycloakSdk
75
80
  IntrospectionResult.from_response(resp.body)
76
81
  rescue Error
77
82
  raise
78
- rescue StandardError => e # Faraday 밖 예외도 — net-http 0.10 의 응답 헤더 검증은 ArgumentError 다(어댑터 목록 밖)
83
+ rescue StandardError => e # non-Faraday exceptions too — net-http 0.10's response header validation
84
+ # raises ArgumentError (outside the adapter's list)
79
85
  raise TransportError, "introspection transport error: #{RedactedCause.describe(e)}", cause: RedactedCause.new(e)
80
86
  end
81
87
 
82
- # 본문은 쓰지 않지만 읽는다 — `TOKEN_RESPONSE_MAX_BYTES` 까지만(넘으면 상태와 무관하게 TransportError).
83
- # 해석은 커넥션의 json 미들웨어가 하던 그대로 남긴다: JSON 이라면서 JSON 이 아닌 본문은 지금처럼 TransportError 다.
84
- # UTF-8 검사는 걸지 않는다(`check_utf8: false`) — 값을 쓰지 않아 지킬 것이 없고, 걸면 400 이 오류 본문의 바이트에
85
- # 따라 AuthError 에서 TransportError 로 바뀐다(hostile_token_response_spec 의 u2). 해석은 상태 검사보다 먼저다.
88
+ # The body is not used, but it is read — only up to `TOKEN_RESPONSE_MAX_BYTES` (past that, TransportError
89
+ # regardless of status). Parsing stays exactly as the connection's json middleware did it: a body that claims to be
90
+ # JSON but is not is a TransportError, as now. No UTF-8 check is applied (`check_utf8: false`) — no value is used,
91
+ # so there is nothing to protect, and with the check a 400 would turn from AuthError into TransportError depending
92
+ # on the bytes of the error body (u2 in hostile_token_response_spec). Parsing comes before the status check.
86
93
  def logout(refresh_token:)
87
94
  form = form!("logout", client_id: @config.client_id, client_secret: @config.client_secret,
88
95
  refresh_token: refresh_token)
@@ -93,7 +100,7 @@ module KeycloakSdk
93
100
  nil
94
101
  rescue Error
95
102
  raise
96
- rescue StandardError => e # introspect 와 같다(Faraday 밖 예외도 감싼다)
103
+ rescue StandardError => e # same as introspect (wraps non-Faraday exceptions too)
97
104
  raise TransportError, "logout transport error: #{RedactedCause.describe(e)}", cause: RedactedCause.new(e)
98
105
  end
99
106
 
@@ -103,18 +110,6 @@ module KeycloakSdk
103
110
 
104
111
  private
105
112
 
106
- # rack-oauth2의 프로세스 전역 HTTP 타임아웃을 Config로 설정한다(require 시점 하드코딩 대신).
107
- # 타임아웃은 Faraday::Connection이 아니라 그 #options(Faraday::RequestOptions)에 있다
108
- # (Connection에 open_timeout=/timeout= 세터가 없어 NoMethodError — 게차 참조).
109
- # ⚠️ SDK 의 토큰 요청은 이제 rack-oauth2 의 연결을 타지 않는다(그랜트는 `token_request` 가 직접 보낸다) — 이 등록이
110
- # 닿는 것은 같은 프로세스의 다른 rack-oauth2 사용자뿐이다. 등록은 first-wins(`@@http_config ||= block`)다.
111
- def configure_rack_oauth2_timeouts(config)
112
- Rack::OAuth2.http_config do |conn|
113
- conn.options.open_timeout = config.connect_timeout
114
- conn.options.timeout = config.read_timeout
115
- end
116
- end
117
-
118
113
  # id_token의 nonce 클레임을 대조하기 전에 강화 JwtValidator로 서명·iss·aud·exp까지 검증한다.
119
114
  # aud 는 `expected_audience` 재정의가 아니라 **client_id** 다(OIDC Core §2·§3.1.3.7) — 재정의는 액세스 토큰의 것.
120
115
  # 검증기(=키 저장소)는 `validate` 와 같은 하나를 쓴다.
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module KeycloakSdk
4
- # 통합 진입점. auth는 즉시 조립, admin은 지연 조립(전용 캐싱 TokenProvider 주입 — §4).
4
+ # Unified entry point. auth is assembled eagerly, admin lazily (a dedicated caching TokenProvider is injected — §4).
5
5
  class KeycloakClient
6
6
  attr_reader :auth
7
7
 
@@ -30,7 +30,7 @@ module KeycloakSdk
30
30
  end
31
31
 
32
32
  def close
33
- @admin&.close # 지연 생성된 admin의 Faraday 커넥션도 정리(§4 close 계약 — 이전엔 누락)
33
+ @admin&.close # also closes the lazily built admin's Faraday connection (§4 close contract — previously missed)
34
34
  [@form_http, @jwks_http].each { |h| h.close if h.respond_to?(:close) }
35
35
  nil
36
36
  end
@@ -3,22 +3,23 @@
3
3
  require "uri"
4
4
 
5
5
  module KeycloakSdk
6
- # 불변 설정. 생성 시 검증하고 freeze한다. client_secret은 inspect에서 마스킹.
6
+ # Immutable configuration. Validated and frozen at construction. client_secret is masked in inspect.
7
7
  class Config
8
- # JWKS 최소 재조회 간격 기본값의 **유일한 정의 자리**(초). DoS 증폭 상한이고 아홉 언어가
9
- # 같은 값으로 정렬돼 있다 — `scripts/test/test-security-defaults.sh`가 아홉 언어 코드와
10
- # 소비자 문서를 함께 대조한다.
8
+ # The **single definition site** of the default minimum JWKS refetch interval (seconds). It is the DoS
9
+ # amplification cap, and the nine languages are aligned on the same value —
10
+ # `scripts/test/test-security-defaults.sh` checks the nine languages' code and the consumer docs together.
11
11
  #
12
- # ⚠️ 이 숫자를 다른 곳에 다시 적지 말 것. 예전에는 여기 30.0, `JwksStore#initialize`에 10.0으로
13
- # **두 번** 적혀 있었다. `JwksStore`는 평범한 public 클래스라 소비자가 직접 생성하면
14
- # (파사드를 거치지 않으면) 문서가 말하는 30초가 아니라 10초를 받아 **IdP를 3배 자주** 때렸다.
15
- # 한글 README도 그 10.0을 그대로 옮겨 적고 있었다(2026-08-12 문서 감사 → 2026-08-13 Task D1).
12
+ # ⚠️ Do not restate this number anywhere else. It used to be written **twice** — 30.0 here and 10.0 in
13
+ # `JwksStore#initialize`. `JwksStore` is an ordinary public class, so a consumer who constructed it directly
14
+ # (without going through the facade) got 10 seconds instead of the 30 seconds the docs state and hit **the IdP
15
+ # 3 times as often**. The Korean README had copied that 10.0 as is, too (2026-08-12 docs audit → 2026-08-13
16
+ # Task D1).
16
17
  DEFAULT_JWKS_MIN_REFETCH = 30.0
17
18
 
18
- # JWT `exp`/`nbf` 검증의 시계 오차 허용치 기본값(초). 이것도 아홉 언어 공동 불변식이다 —
19
- # 한 언어만 커지면 **그 언어에서만 만료된 토큰이 더 오래 통과한다**.
20
- # ⚠️ `JwtValidator#initialize`가 같은 값을 두 번째로 적고 있었다(둘 다 30이라 아직 갈리지는
21
- # 않았으나 JWKS가 10.0/30.0으로 갈린 것과 똑같은 모양이다). 그 자리는 이제 이 상수를 참조한다.
19
+ # The default clock-skew tolerance (seconds) for JWT `exp`/`nbf` validation. This too is an invariant shared by
20
+ # the nine languages — if it grows in one language only, **expired tokens pass for longer in that language only**.
21
+ # ⚠️ `JwtValidator#initialize` used to write the same value a second time (both were 30, so they had not diverged
22
+ # yet, but it had exactly the shape of the JWKS split into 10.0/30.0). That site now references this constant.
22
23
  DEFAULT_CLOCK_SKEW = 30
23
24
 
24
25
  # 깨진 server_url의 ConfigError 접두사. 뒤에 짧은 사유만 붙인다(입력·파서 메시지 금지).
@@ -34,25 +35,26 @@ module KeycloakSdk
34
35
  connect_timeout: 10, read_timeout: 10, clock_skew: DEFAULT_CLOCK_SKEW,
35
36
  jwks_min_refetch: DEFAULT_JWKS_MIN_REFETCH, expected_audience: nil)
36
37
  @server_url = strip_trailing_slashes(normalize_required("server_url", server_url))
37
- # 정규화 직후. 상대 URL("kc.example.com")은 첫 토큰 요청에서 RuntimeError "No Host Info"로,
38
- # 공백이 섞인 URL("http://kc example.com")은 URI::InvalidURIError로 나간다. 둘 다
39
- # ConfigError가 아니라 공개 API 밖으로 새는 예외라 생성 시점에 닫는다.
40
- # InvalidURIError#message는 입력을 그대로 에코하므로 사유만 남긴다.
38
+ # Right after normalization. A relative URL ("kc.example.com") goes out as RuntimeError "No Host Info" on the
39
+ # first token request, and a URL with a space in it ("http://kc example.com") as URI::InvalidURIError. Neither
40
+ # is a ConfigError — both are exceptions leaking out of the public API — so they are closed off at construction.
41
+ # InvalidURIError#message echoes the input verbatim, so only the reason is kept.
41
42
  require_absolute_http_url!(@server_url)
42
43
  @realm = normalize_required("realm", realm)
43
44
  @client_id = normalize_required("client_id", client_id)
44
45
  @client_secret = client_secret
45
46
  @scopes = Array(scopes).freeze
46
- # JWT 서명 검증 허용 알고리즘 핀(기본 RS256). ES256/PS256 realm을 위해 설정 가능하되
47
- # 빈 집합은 alg 핀을 무력화하므로 거부한다.
47
+ # Pin of the algorithms allowed for JWT signature verification (default RS256). Configurable for ES256/PS256
48
+ # realms, but an empty set would disable the alg pin, so it is rejected.
48
49
  @signature_algorithms = non_empty_array("signature_algorithms", signature_algorithms).freeze
49
50
  @connect_timeout = positive("connect_timeout", connect_timeout)
50
51
  @read_timeout = positive("read_timeout", read_timeout)
51
52
  @clock_skew = non_negative("clock_skew", clock_skew)
52
- # 미해결 kid로 인한 JWKS 재조회의 최소 간격(초) — DoS 증폭 상한. 기본값은 위 상수.
53
+ # Minimum interval (seconds) between JWKS refetches caused by an unresolved kid — the DoS amplification cap.
54
+ # The default is the constant above.
53
55
  @jwks_min_refetch = non_negative("jwks_min_refetch", jwks_min_refetch)
54
- # 토큰 aud에 들어있어야 할 값(기본 nil = client_id). 기본 realm은 client-credentials 토큰의
55
- # aud에 client_id를 넣지 않으므로, realm이 실제로 발급하는 리소스/오디언스를 지정한다.
56
+ # The value that must be in the token's aud (default nil = client_id). A stock realm does not put client_id in
57
+ # a client-credentials token's aud, so set the resource/audience the realm actually issues.
56
58
  @expected_audience = expected_audience
57
59
  freeze
58
60
  end