keycloak-sdk 1.4.0 → 1.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/README.md +4 -2
- data/lib/keycloak_sdk/admin/admin_client.rb +5 -4
- data/lib/keycloak_sdk/admin/bearer_auth.rb +25 -25
- data/lib/keycloak_sdk/admin/call.rb +2 -1
- data/lib/keycloak_sdk/admin/clients.rb +1 -1
- data/lib/keycloak_sdk/admin/realms.rb +2 -2
- data/lib/keycloak_sdk/auth_client.rb +24 -29
- data/lib/keycloak_sdk/client.rb +2 -2
- data/lib/keycloak_sdk/config.rb +23 -21
- data/lib/keycloak_sdk/errors.rb +25 -19
- data/lib/keycloak_sdk/http.rb +79 -33
- data/lib/keycloak_sdk/jwks_store.rb +57 -32
- data/lib/keycloak_sdk/jwt_validator.rb +18 -16
- data/lib/keycloak_sdk/masking.rb +1 -1
- data/lib/keycloak_sdk/oidc_endpoints.rb +5 -5
- data/lib/keycloak_sdk/token_provider.rb +38 -10
- data/lib/keycloak_sdk/tokens.rb +28 -25
- data/lib/keycloak_sdk/version.rb +1 -1
- data/lib/keycloak_sdk.rb +5 -7
- metadata +1 -1
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: e3968afa42f3c2e2df3716ac09af5773c2c7f9290e7310f2f4b51b1f79e1603f
|
|
4
|
+
data.tar.gz: 06b96f67524ae3161e8be14fb09246f1faa9190e4b8df5b04bf1075408e74c7f
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: ac65a88b4593b5da59b654b4240ccd4e430164323c10dba1c11457b1b118ab92c1921b52cd76524f8be5460ff3931594db370e5b77ec681f31ce98ccc6645a78
|
|
7
|
+
data.tar.gz: 0bbb4b5036db0b34fa52ae74edb2be7bf779c0e2c386d45a2c38483000756638ce0f83cfedda951f799a0c9b28d8269ff047cf21a0a3b90f0bc794804590d6c7
|
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.4.
|
|
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.
|
|
8
10
|
>
|
|
9
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.
|
|
10
12
|
>
|
|
@@ -69,7 +71,7 @@ The SDK replaces the unsafe library defaults rather than inheriting them:
|
|
|
69
71
|
|
|
70
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.
|
|
71
73
|
- **Strict claim checks** — exact `iss` match, `aud` containment, mandatory `exp`, `nbf` enforced when present, and a bounded clock skew.
|
|
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.
|
|
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.
|
|
73
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.
|
|
74
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).
|
|
75
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).
|
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
module KeycloakSdk
|
|
4
4
|
module Admin
|
|
5
|
-
# Admin REST
|
|
6
|
-
#
|
|
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,12 +30,13 @@ module KeycloakSdk
|
|
|
30
30
|
Groups.new(@conn, @config.realm)
|
|
31
31
|
end
|
|
32
32
|
|
|
33
|
-
#
|
|
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
|
-
#
|
|
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
|
|
@@ -5,7 +5,7 @@ require "net/http"
|
|
|
5
5
|
|
|
6
6
|
module KeycloakSdk
|
|
7
7
|
module Admin
|
|
8
|
-
#
|
|
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
|
-
# ⚠️
|
|
24
|
-
# 때
|
|
25
|
-
#
|
|
26
|
-
#
|
|
27
|
-
#
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
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
|
-
#
|
|
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
|
|
|
@@ -19,7 +19,7 @@ module KeycloakSdk
|
|
|
19
19
|
request { @conn.get("admin/realms/#{esc(@realm)}/clients/#{esc(id)}") }.body
|
|
20
20
|
end
|
|
21
21
|
|
|
22
|
-
# client_id
|
|
22
|
+
# Lookup by client_id: list + filter (admin keys on the internal uuid).
|
|
23
23
|
def list(**params)
|
|
24
24
|
request { @conn.get("admin/realms/#{esc(@realm)}/clients", params) }.body
|
|
25
25
|
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,7 +10,7 @@ module KeycloakSdk
|
|
|
10
10
|
@conn = conn
|
|
11
11
|
end
|
|
12
12
|
|
|
13
|
-
# POST /admin/realms — master realm
|
|
13
|
+
# POST /admin/realms — master realm only (a realm SA gets 403). Returns: the realm name.
|
|
14
14
|
def create(representation)
|
|
15
15
|
request { @conn.post("admin/realms", representation, &SettleBody::MARK) }
|
|
16
16
|
representation[:realm] || representation["realm"]
|
|
@@ -7,14 +7,19 @@ require "base64"
|
|
|
7
7
|
require "uri"
|
|
8
8
|
|
|
9
9
|
module KeycloakSdk
|
|
10
|
-
#
|
|
11
|
-
#
|
|
12
|
-
#
|
|
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
|
-
#
|
|
17
|
-
#
|
|
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
|
|
44
|
-
# realm JWKS
|
|
45
|
-
#
|
|
46
|
-
# (
|
|
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
|
|
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
|
|
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
|
-
#
|
|
83
|
-
#
|
|
84
|
-
# UTF-8
|
|
85
|
-
#
|
|
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
|
|
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` 와 같은 하나를 쓴다.
|
data/lib/keycloak_sdk/client.rb
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
3
|
module KeycloakSdk
|
|
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 #
|
|
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
|
data/lib/keycloak_sdk/config.rb
CHANGED
|
@@ -3,22 +3,23 @@
|
|
|
3
3
|
require "uri"
|
|
4
4
|
|
|
5
5
|
module KeycloakSdk
|
|
6
|
-
#
|
|
6
|
+
# Immutable configuration. Validated and frozen at construction. client_secret is masked in inspect.
|
|
7
7
|
class Config
|
|
8
|
-
#
|
|
9
|
-
#
|
|
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
|
-
# ⚠️
|
|
13
|
-
#
|
|
14
|
-
# (
|
|
15
|
-
#
|
|
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
|
|
21
|
-
#
|
|
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
|
-
#
|
|
38
|
-
#
|
|
39
|
-
# ConfigError
|
|
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
|
-
#
|
|
47
|
-
#
|
|
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
|
-
#
|
|
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
|
-
#
|
|
55
|
-
# aud
|
|
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
|
data/lib/keycloak_sdk/errors.rb
CHANGED
|
@@ -5,13 +5,13 @@ require "socket"
|
|
|
5
5
|
require "timeout"
|
|
6
6
|
|
|
7
7
|
module KeycloakSdk
|
|
8
|
-
#
|
|
8
|
+
# The root of all SDK errors.
|
|
9
9
|
class Error < StandardError; end
|
|
10
10
|
|
|
11
|
-
#
|
|
11
|
+
# Configuration validation failure.
|
|
12
12
|
class ConfigError < Error; end
|
|
13
13
|
|
|
14
|
-
#
|
|
14
|
+
# Authentication/token issuance failure (keeps the OAuth error code).
|
|
15
15
|
class AuthError < Error
|
|
16
16
|
attr_reader :oauth_error
|
|
17
17
|
|
|
@@ -21,13 +21,13 @@ module KeycloakSdk
|
|
|
21
21
|
end
|
|
22
22
|
end
|
|
23
23
|
|
|
24
|
-
#
|
|
24
|
+
# Network transport failure (timeout/connection refused/DNS).
|
|
25
25
|
class TransportError < Error; end
|
|
26
26
|
|
|
27
|
-
# JWT
|
|
27
|
+
# JWT validation failure.
|
|
28
28
|
class TokenValidationError < Error; end
|
|
29
29
|
|
|
30
|
-
# Admin REST
|
|
30
|
+
# Admin REST error (keeps the HTTP status).
|
|
31
31
|
class AdminError < Error
|
|
32
32
|
attr_reader :status
|
|
33
33
|
|
|
@@ -36,7 +36,7 @@ module KeycloakSdk
|
|
|
36
36
|
@status = status
|
|
37
37
|
end
|
|
38
38
|
|
|
39
|
-
# status →
|
|
39
|
+
# status → an instance of the matching subclass exception.
|
|
40
40
|
def self.from_status(status, message)
|
|
41
41
|
case status
|
|
42
42
|
when 404 then NotFoundError.new(message, status: status)
|
|
@@ -51,21 +51,26 @@ module KeycloakSdk
|
|
|
51
51
|
class ConflictError < AdminError; end
|
|
52
52
|
class ForbiddenError < AdminError; end
|
|
53
53
|
|
|
54
|
-
# SDK
|
|
55
|
-
#
|
|
54
|
+
# The copy attached as an SDK error's `cause` in place of the original underlying exception — it carries over **only
|
|
55
|
+
# the class-name chain and the backtrace**. The boundary attaches it with `raise …, cause: RedactedCause.new(e)`
|
|
56
|
+
# (it is not a `KeycloakSdk::Error` — it sits only in the cause slot).
|
|
56
57
|
#
|
|
57
|
-
# ⚠️ Ruby
|
|
58
|
-
#
|
|
59
|
-
#
|
|
60
|
-
# `
|
|
61
|
-
# `
|
|
62
|
-
#
|
|
58
|
+
# ⚠️ In Ruby, a `raise` inside `rescue` attaches the exception being handled as `cause` **automatically**, and
|
|
59
|
+
# `full_message` (uncaught exceptions · loggers) prints the messages of that chain. Underlying exceptions carry the
|
|
60
|
+
# response — the JSON parser puts the first 32 bytes of the body in its message, rack-oauth2 the
|
|
61
|
+
# `error_description` (the whole body for a non-JSON error), Net::HTTP the broken status line, and
|
|
62
|
+
# `Faraday::ParsingError#inspect` printed even the **request** body and headers (client secret · refresh token ·
|
|
63
|
+
# bearer). Ruby 3.2's `NoMethodError` quoted the receiver (the response body) (measured 2026-09-26 ·
|
|
64
|
+
# `spec/unit/hostile_token_response_spec.rb`). §4 also requires that the original objects are not exposed through
|
|
65
|
+
# the public API.
|
|
63
66
|
class RedactedCause < StandardError
|
|
64
|
-
#
|
|
65
|
-
#
|
|
67
|
+
# The underlying causes whose message may be carried into the SDK message — only socket · timeout · TLS
|
|
68
|
+
# failures, which cannot quote the response.
|
|
69
|
+
# ⚠️ `Faraday::ConnectionFailed` is not added wholesale — `Net::HTTPBadResponse` (a dump of the broken status
|
|
70
|
+
# line) also arrives as one.
|
|
66
71
|
QUOTE_FREE = [SystemCallError, SocketError, IOError, Timeout::Error, OpenSSL::SSL::SSLError].freeze
|
|
67
72
|
|
|
68
|
-
#
|
|
73
|
+
# The class names of the original and its `cause`s (outermost first).
|
|
69
74
|
attr_reader :lower_classes
|
|
70
75
|
|
|
71
76
|
def initialize(error)
|
|
@@ -79,7 +84,8 @@ module KeycloakSdk
|
|
|
79
84
|
set_backtrace(error.backtrace) if error.backtrace
|
|
80
85
|
end
|
|
81
86
|
|
|
82
|
-
#
|
|
87
|
+
# The description of an underlying error to carry in an SDK message — the message itself for a connection
|
|
88
|
+
# failure that cannot quote the response, otherwise only the class name.
|
|
83
89
|
def self.describe(error)
|
|
84
90
|
origin = error.respond_to?(:wrapped_exception) && error.wrapped_exception ? error.wrapped_exception : error
|
|
85
91
|
QUOTE_FREE.any? { |k| origin.is_a?(k) } ? error.message : error.class.name
|