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.
@@ -3,16 +3,16 @@
3
3
  require "erb"
4
4
 
5
5
  module KeycloakSdk
6
- # Keycloak realm의 OIDC 엔드포인트를 규약대로 조립한다(네트워크 없음).
6
+ # Assembles a Keycloak realm's OIDC endpoints by convention (no network).
7
7
  class OidcEndpoints
8
8
  attr_reader :issuer, :authorization, :token, :introspection, :end_session, :jwks
9
9
 
10
10
  def initialize(server_url, realm)
11
- # issuer는 토큰 iss 클레임과 그대로 비교하므로 realm을 인코딩하지 않는다.
11
+ # The issuer is compared as is with the token's iss claim, so the realm is not encoded.
12
12
  @issuer = "#{server_url}/realms/#{realm}"
13
- # 엔드포인트의 realm은 경로 세그먼트 하나다. "my realm"을 그대로 두면
14
- # client_credentials_token / create_authorization_request가 URI::InvalidURIError를
15
- # SDK 밖으로 흘린다(자매 SDK는 이 세그먼트를 퍼센트 인코딩한다).
13
+ # In the endpoints the realm is a single path segment. Left as is, "my realm" makes
14
+ # client_credentials_token / create_authorization_request leak a URI::InvalidURIError
15
+ # out of the SDK (the sibling SDKs percent-encode this segment).
16
16
  oidc = "#{server_url}/realms/#{escape_realm_segment(realm)}/protocol/openid-connect"
17
17
  @authorization = "#{oidc}/auth"
18
18
  @token = "#{oidc}/token"
@@ -1,13 +1,33 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module KeycloakSdk
4
- # 덕 인터페이스: 구현체는 #access_token → String 을 응답한다.
5
- # admin은 이 인터페이스로만 토큰을 받는다(auth 비의존, §4 결합 규칙).
4
+ # Duck interface: an implementation responds to #access_token → String.
5
+ # admin receives tokens only through this interface (no dependency on auth, §4 coupling rule).
6
+ # admin strips leading and trailing SP · HTAB · CR · LF from that value before sending it, and if what is left is not
7
+ # an RFC 6750 bearer token it rejects it before the request (`BearerGrammar`).
6
8
  module TokenProvider
7
9
  end
8
10
 
9
- # client-credentials 그랜트로 토큰을 발급하고 만료 전까지 캐시한다(Mutex single-flight).
10
- # admin 파사드가 소비하는 캐싱 provider(무캐시 AuthClient 직접 주입 금지 — §4 캐시 불변식).
11
+ # bearer 토큰 문법 — 아홉 SDK 가 같다(등록부 bearer-token-grammar-divergent). 앞뒤의 SP·HTAB·CR·LF 만 다듬고(NBSP·U+3000·
12
+ # VT·FF 는 다듬지 않는다 — 그래서 NUL·VT·FF 까지 지우는 `strip` 이 아니다) 남은 것이 비지 않은 RFC 6750 b64token 이면 그 값,
13
+ # 아니면 nil 이다. 보내는 자리(`Admin::BearerAuth`)와 캐시하는 자리(`ClientCredentialsTokenProvider`)가 이것 하나를 쓴다.
14
+ # 다듬기와 판정을 `\A`…`\z` 매치 하나로 한다 — b64token 안에는 다듬을 글자가 없으니 「다듬고 나서 맞춘다」와 같은 뜻이다.
15
+ # ⚠️ `\z` 다(`$` 는 줄 끝이라 "abc\nX" 를 받는다). `ascii_only?` 가 ASCII 밖·잘못된 UTF-8·ASCII 와 호환되지 않는
16
+ # 인코딩(UTF-16 등)을 매치 전에 거른다 — 거르지 않으면 매치가 ArgumentError·Encoding::CompatibilityError 를 낸다(실측).
17
+ module BearerGrammar
18
+ TOKEN = %r{\A[ \t\r\n]*([A-Za-z0-9\-._~+/]+=*)[ \t\r\n]*\z}
19
+
20
+ module_function
21
+
22
+ def sendable(text)
23
+ TOKEN.match(text)&.[](1) if text.ascii_only?
24
+ end
25
+ end
26
+ private_constant :BearerGrammar
27
+
28
+ # Issues a token with the client-credentials grant and caches it until it expires (Mutex single-flight).
29
+ # The caching provider the admin facade consumes (never inject the uncached AuthClient directly — §4 cache
30
+ # invariant).
11
31
  class ClientCredentialsTokenProvider
12
32
  include TokenProvider
13
33
 
@@ -20,11 +40,12 @@ module KeycloakSdk
20
40
  @expires_at = 0.0
21
41
  end
22
42
 
23
- # ⚠️ 기본 `inspect` 는 인스턴스 변수를 전부 찍는데, 이 클래스는 **원시 액세스 토큰 문자열**을
24
- # `@cached` 에 들고 있다(`ts.access_token` — TokenSet 이 아니라서 `TokenSet#inspect` 가 안 탄다).
25
- # 실측(2026-09-12): 재정의 전 `p provider` 가 `@cached="AT-CENSUS-TOKEN-…"` 를 원문으로 찍었다.
26
- # `Config`·`TokenSet` 은 재정의가 있는데 이 타입만 없어 생긴 **형제 간 불일치**였다.
27
- # ⚠️ 캐시 유무는 남긴다 — 빈 캐시에 `***` 를 찍으면 「토큰이 있다」는 거짓 신호가 된다.
43
+ # ⚠️ The default `inspect` prints every instance variable, and this class holds the **raw access token string**
44
+ # in `@cached` (`ts.access_token` — not a TokenSet, so `TokenSet#inspect` does not kick in).
45
+ # Measured (2026-09-12): before the override, `p provider` printed `@cached="AT-CENSUS-TOKEN-…"` verbatim.
46
+ # It was a **mismatch between siblings**: `Config` · `TokenSet` have an override and only this type lacked one.
47
+ # ⚠️ Whether a token is cached stays visible — printing `***` for an empty cache would be a false signal that
48
+ # "there is a token".
28
49
  def inspect
29
50
  "#<KeycloakSdk::ClientCredentialsTokenProvider config=#{@config.inspect} " \
30
51
  "cached=#{@cached ? '"***"' : 'nil'} expires_at=#{@expires_at.inspect}>"
@@ -37,7 +58,14 @@ module KeycloakSdk
37
58
  return @cached if @cached && now < @expires_at
38
59
 
39
60
  ts = request_token
40
- @cached = ts.access_token
61
+ # Checked before caching — a token that every admin request would reject is not held until it expires (the
62
+ # next call asks the IdP again).
63
+ token = BearerGrammar.sendable(ts.access_token)
64
+ unless token
65
+ raise AuthError, "token response has no usable access_token: it is not an RFC 6750 bearer token (b64token)"
66
+ end
67
+
68
+ @cached = token
41
69
  @expires_at = ts.expires_at ? (ts.expires_at - @config.clock_skew) : (now + 60)
42
70
  @cached
43
71
  end
@@ -1,13 +1,13 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module KeycloakSdk
4
- # OAuth 토큰 응답의 불변 값타입. access/refresh/id 토큰은 inspect에서 마스킹.
4
+ # Immutable value type of an OAuth token response. The access/refresh/id tokens are masked in inspect.
5
5
  TokenSet = Data.define(:access_token, :token_type, :expires_in, :refresh_token,
6
6
  :id_token, :scope, :expires_at) do
7
- # ⚠️ **검증은 팩토리가 아니라 생성자에 있다.** `from_response` 에만 두면 `AuthClient`
8
- # 가 `TokenSet.new` 을 직접 부르는 경로(`auth_client.rb` 의 `to_token_set`)가 그것을
9
- # 통째로 우회한다 — 독립 레그가 그 구멍을 지목했다. 생성자는 어떤 경로도 지나므로
10
- # 여기 두면 우회가 불가능하다.
7
+ # ⚠️ **The validation lives in the constructor, not the factory.** Put only in `from_response`, it would be
8
+ # bypassed entirely by the path where `AuthClient` calls `TokenSet.new` directly (`to_token_set` in
9
+ # `auth_client.rb`) — an independent leg pointed out that hole. Every path goes through the constructor, so
10
+ # placing it here makes a bypass impossible.
11
11
  def initialize(access_token:, **rest)
12
12
  unless access_token.is_a?(String) && !access_token.empty?
13
13
  raise AuthError, "token response has no usable access_token"
@@ -17,12 +17,13 @@ module KeycloakSdk
17
17
  end
18
18
 
19
19
  def self.from_response(body, received_at: Time.now.to_f)
20
- # 배열 본문은 `Array#[]` 의 TypeError 로 경계를 뚫었다 — 객체가 아니면 SDK 오류다.
20
+ # An array body broke through the boundary as a TypeError from `Array#[]` — a body that is not an object is
21
+ # an SDK error.
21
22
  raise AuthError, "token response is not a JSON object" unless body.is_a?(Hash)
22
23
 
23
- # ⚠️ **존재 검사는 타입 검사가 아니다.** 예전에는 값을 그대로 담아 숫자·해시·nil 이
24
- # `access_token` 이 됐고, 소비자는 그것을 Bearer 로 실어 보내 매번 401 을 받았다
25
- # (조용한 반복 실패). `expires_in` 의 문자열 허용은 **의도된 것**이라 건드리지 않는다.
24
+ # ⚠️ **A presence check is not a type check.** The value used to be stored as is, so a number, a hash or nil
25
+ # became the `access_token`, and the consumer sent it as the Bearer and got a 401 every time
26
+ # (a silent, repeated failure). Accepting a string `expires_in` is **intended**, so it is left alone.
26
27
  access_token = body["access_token"]
27
28
  unless access_token.is_a?(String) && !access_token.empty?
28
29
  raise AuthError, "token response has no usable access_token"
@@ -31,7 +32,7 @@ module KeycloakSdk
31
32
  expires_in = begin
32
33
  body["expires_in"] && Integer(body["expires_in"])
33
34
  rescue ArgumentError, TypeError, RangeError # RangeError: JSON 1e400 = Infinity → FloatDomainError
34
- # `cause: nil` — ArgumentError 는 그 값을 인용한다(`invalid value for Integer(): "…"`).
35
+ # `cause: nil` — ArgumentError quotes the value (`invalid value for Integer(): "…"`).
35
36
  raise AuthError, "token response has an unusable expires_in", cause: nil
36
37
  end
37
38
  new(
@@ -45,10 +46,10 @@ module KeycloakSdk
45
46
  )
46
47
  end
47
48
 
48
- # ⚠️ **만료 시각을 모르면 "만료됨"이다**(fail-safe — 자매 여덟과 동형, Java 의 M.6).
49
- # `false`(=아직 살아있다)를 돌려주면 만료 시각 미상인 토큰이 **영원히 유효**해진다.
50
- # `expires_at` 이 nil 인 경우는 서버가 `expires_in` 을 안 보냈을 때뿐이라 정상 경로가
51
- # 아니고, 그때 취할 안전한 쪽은 "재발급"이다.
49
+ # ⚠️ **An unknown expiry time means "expired"** (fail-safe — isomorphic with the eight siblings, Java's M.6).
50
+ # Returning `false` (= still alive) would make a token whose expiry time is unknown **valid forever**.
51
+ # `expires_at` is nil only when the server did not send `expires_in`, so it is not the normal path, and the
52
+ # safe side to take then is "reissue".
52
53
  def expired?(skew: 0, now: Time.now.to_f)
53
54
  return true if expires_at.nil?
54
55
 
@@ -62,20 +63,21 @@ module KeycloakSdk
62
63
  end
63
64
  alias_method :to_s, :inspect
64
65
 
65
- # ⚠️ `pp`/`pretty_inspect` 는 `inspect` 와 같은 계급의 **표시 경로**인데, `Data` 타입은 PP 가
66
- # 멤버를 직접 찍어 위 `inspect` 를 **건너뛴다**(실측: access_token 원문이 나왔다). 일반
67
- # 클래스인 `Config` 는 PP 가 `inspect` 로 폴백해 안전하다 — 그래서 `Data` 만 이 훅이 필요하다.
66
+ # ⚠️ `pp`/`pretty_inspect` is a **display path** of the same rank as `inspect`, but for a `Data` type PP prints
67
+ # the members directly and **skips** the `inspect` above (measured: the raw access_token came out). For `Config`,
68
+ # an ordinary class, PP falls back to `inspect`, so it is safe — that is why only `Data` needs this hook.
68
69
  def pretty_print(pp)
69
70
  pp.text(inspect)
70
71
  end
71
72
  end
72
73
 
73
- # 검증된 access token의 관심 클레임.
74
+ # The claims of interest of a validated access token.
74
75
  ValidatedToken = Data.define(:subject, :audience, :issuer, :expires_at, :issued_at, :claims)
75
76
 
76
- # RFC 7662 introspection 결과.
77
+ # RFC 7662 introspection result.
77
78
  IntrospectionResult = Data.define(:active, :username, :client_id, :claims) do
78
- # 객체가 아닌 본문은 SDK 오류다 — 배열은 TypeError 로 경계를 뚫었고, 문자열은 `claims` 가 문자열인 결과가 됐다.
79
+ # A body that is not an object is an SDK error — an array broke through the boundary as a TypeError, and a string
80
+ # became a result whose `claims` was a string.
79
81
  def self.from_response(body)
80
82
  raise AuthError, "introspection response is not a JSON object" unless body.is_a?(Hash)
81
83
 
@@ -88,8 +90,9 @@ module KeycloakSdk
88
90
  end
89
91
  end
90
92
 
91
- # authorization-code 흐름 시작 값(PKCE code_verifier 포함·inspect 마스킹).
92
- # nonce는 인가 URL에 실리는 재생 방지 값이라 비밀이 아니다(state와 동급 — code_verifier만 마스킹).
93
+ # The values that start an authorization-code flow (PKCE code_verifier included · masked in inspect).
94
+ # The nonce is a replay-protection value carried in the authorization URL, so it is not a secret (on a par with
95
+ # state — only code_verifier is masked).
93
96
  AuthorizationRequest = Data.define(:url, :state, :code_verifier, :nonce) do
94
97
  def inspect
95
98
  "#<KeycloakSdk::AuthorizationRequest url=#{url.inspect} state=#{state.inspect} " \
@@ -97,9 +100,9 @@ module KeycloakSdk
97
100
  end
98
101
  alias_method :to_s, :inspect
99
102
 
100
- # ⚠️ `pp`/`pretty_inspect` 는 `inspect` 와 같은 계급의 **표시 경로**인데, `Data` 타입은 PP 가
101
- # 멤버를 직접 찍어 위 `inspect` 를 **건너뛴다**(실측: access_token 원문이 나왔다). 일반
102
- # 클래스인 `Config` 는 PP 가 `inspect` 로 폴백해 안전하다 — 그래서 `Data` 만 이 훅이 필요하다.
103
+ # ⚠️ `pp`/`pretty_inspect` is a **display path** of the same rank as `inspect`, but for a `Data` type PP prints
104
+ # the members directly and **skips** the `inspect` above (measured: the raw access_token came out). For `Config`,
105
+ # an ordinary class, PP falls back to `inspect`, so it is safe — that is why only `Data` needs this hook.
103
106
  def pretty_print(pp)
104
107
  pp.text(inspect)
105
108
  end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module KeycloakSdk
4
- VERSION = "1.3.2"
4
+ VERSION = "1.4.1"
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"
@@ -25,11 +26,9 @@ require_relative "keycloak_sdk/client"
25
26
  module KeycloakSdk
26
27
  end
27
28
 
28
- # ⚠️ rack-oauth2 HTTP 타임아웃은 프로세스 전역(Rack::OAuth2.http_config)이라 per-client 미세제어가
29
- # 불가하다. 과거엔 require 시점에 하드코딩 10초로 박아 (a) 단순 require만으로 전역 상태를 변조하고
30
- # (b) Config 타임아웃을 무시했다. 이제는 AuthClient#initialize에서 Config의 connect/read 타임아웃으로
31
- # 설정한다(auth_client.rb) — require 부작용 제거 + config 반영. 전역이라는 근본 한계는 남지만
32
- # "SDK auth를 실제로 쓸 때"로 스코프가 좁혀진다(require 시점 아님).
33
- # ⚠️ SDK 자신의 토큰 요청은 이 전역 연결을 타지 않는다 — 그랜트는 SDK 커넥션(`Http.build`, 클라이언트마다 Config
34
- # 타임아웃)으로 직접 보낸다(응답 상한 때문). rack-oauth2 의 HTTP 연결을 쓰는 SDK 경로는 이제 없다(인가 URL 조립은 네트워크가 없다).
29
+ # ⚠️ rack-oauth2 의 HTTP 설정(`Rack::OAuth2.http_config`)은 프로세스 전역이고 먼저 건 쪽이 이긴다 — SDK 는 그것을
30
+ # 걸지 않는다. require 때도(과거엔 하드코딩 10초로 전역을 변조했다), AuthClient 생성 때도(걸면 호스트 앱이 나중에 건
31
+ # 블록이 조용히 버려진다). SDK 의 요청은 그 연결을 타지 않는다 — 그랜트·introspection·logout·JWKS·admin 은 전부 SDK
32
+ # 커넥션(`Http.build`, 클라이언트마다 Config 타임아웃)으로 나가고 인가 URL 조립은 네트워크가 없다
33
+ # (`spec/unit/host_http_config_spec.rb`).
35
34
  require "rack/oauth2"
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: keycloak-sdk
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.3.2
4
+ version: 1.4.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - xzawed
@@ -84,6 +84,7 @@ files:
84
84
  - lib/keycloak_sdk/admin/groups.rb
85
85
  - lib/keycloak_sdk/admin/realms.rb
86
86
  - lib/keycloak_sdk/admin/roles.rb
87
+ - lib/keycloak_sdk/admin/settle_body.rb
87
88
  - lib/keycloak_sdk/admin/users.rb
88
89
  - lib/keycloak_sdk/auth_client.rb
89
90
  - lib/keycloak_sdk/client.rb