keycloak-sdk 1.2.0 → 1.3.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 +1 -1
- data/lib/keycloak_sdk/admin/bearer_auth.rb +42 -1
- data/lib/keycloak_sdk/admin/call.rb +4 -1
- data/lib/keycloak_sdk/auth_client.rb +82 -23
- data/lib/keycloak_sdk/http.rb +222 -1
- data/lib/keycloak_sdk/jwks_store.rb +11 -10
- data/lib/keycloak_sdk/jwt_validator.rb +4 -0
- data/lib/keycloak_sdk/token_provider.rb +10 -7
- data/lib/keycloak_sdk/version.rb +1 -1
- data/lib/keycloak_sdk.rb +2 -0
- 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: 561abaa5612faf7d8d0b60dda6e925f2db242ae134e0fe68f97469ce3456ab26
|
|
4
|
+
data.tar.gz: 1b2ff3c20ae257420c10a0d87cca3298059aa1f4c716c0c2179874eb0550f1ab
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 2ec9e56d3bcc400a6ac1cd541e2e85e3ac31de448ec5ebec1a6f033c5e814ed145d9ab2d27543c0a68a74ce521d95e3227a1290d3d0c47933e53274b07f2b28c
|
|
7
|
+
data.tar.gz: cf086c552fa47a7c5783850e0766a7590c47788d94b50ee27ebaaf913216490f4c8b1237fab715ac578b3160ad70f82d293b226a3301460d14fff6af0e077e0e
|
data/README.md
CHANGED
|
@@ -4,7 +4,7 @@ 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.
|
|
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.
|
|
8
8
|
|
|
9
9
|
## Requirements
|
|
10
10
|
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
3
|
require "faraday"
|
|
4
|
+
require "net/http"
|
|
4
5
|
|
|
5
6
|
module KeycloakSdk
|
|
6
7
|
module Admin
|
|
@@ -12,7 +13,47 @@ module KeycloakSdk
|
|
|
12
13
|
end
|
|
13
14
|
|
|
14
15
|
def on_request(env)
|
|
15
|
-
|
|
16
|
+
token = @token_provider.access_token
|
|
17
|
+
sendable!(token) if token.is_a?(String)
|
|
18
|
+
env.request_headers["Authorization"] = "Bearer #{token}"
|
|
19
|
+
end
|
|
20
|
+
|
|
21
|
+
private
|
|
22
|
+
|
|
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"
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
limit = field_limit
|
|
48
|
+
return if limit.nil? || "Bearer ".bytesize + token.bytesize <= limit
|
|
49
|
+
|
|
50
|
+
raise AuthError, "admin request not sent: the access token (#{token.bytesize} bytes) does not fit an " \
|
|
51
|
+
"HTTP header field (#{limit} bytes with \"Bearer \")"
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
# 이 SDK 의 어댑터는 net-http 로 고정돼 있다(`Http.build`). 그 상한이 없는 net-http 판은 길이로 막지 않는다.
|
|
55
|
+
def field_limit
|
|
56
|
+
Net::HTTPHeader::MAX_FIELD_LENGTH if defined?(Net::HTTPHeader::MAX_FIELD_LENGTH)
|
|
16
57
|
end
|
|
17
58
|
end
|
|
18
59
|
end
|
|
@@ -31,8 +31,11 @@ module KeycloakSdk
|
|
|
31
31
|
return resp if resp.success?
|
|
32
32
|
|
|
33
33
|
raise AdminError.from_status(resp.status, "admin request failed: HTTP #{resp.status}")
|
|
34
|
-
rescue
|
|
34
|
+
rescue Error
|
|
35
|
+
raise
|
|
36
|
+
rescue StandardError => e
|
|
35
37
|
# 원본을 달면 `Faraday::ParsingError#inspect` 가 요청의 베어러 토큰을, 메시지가 응답 앞부분을 찍는다(실측).
|
|
38
|
+
# Faraday 밖 예외도 감싼다 — net-http 0.10 의 응답 헤더 검증 ArgumentError 는 헤더 이름을 인용한다.
|
|
36
39
|
raise TransportError, "admin transport error: #{RedactedCause.describe(e)}", cause: RedactedCause.new(e)
|
|
37
40
|
end
|
|
38
41
|
|
|
@@ -4,9 +4,11 @@ require "rack/oauth2"
|
|
|
4
4
|
require "securerandom"
|
|
5
5
|
require "digest"
|
|
6
6
|
require "base64"
|
|
7
|
+
require "uri"
|
|
7
8
|
|
|
8
9
|
module KeycloakSdk
|
|
9
|
-
# 인증 파사드. rack-oauth2
|
|
10
|
+
# 인증 파사드. 인가 URL(PKCE)은 rack-oauth2 로 만들고, 세 그랜트·introspection(RFC7662)·logout 은 SDK 의 Faraday
|
|
11
|
+
# 커넥션으로 직접 보낸다 — 토큰 응답 본문을 상한까지만 읽어야 하는데 rack-oauth2 는 자기 커넥션으로 통째로 읽는다.
|
|
10
12
|
# TokenProvider를 구현하지만(직접 사용용), admin은 캐싱 ClientCredentialsTokenProvider를 별도로 쓴다(§4).
|
|
11
13
|
class AuthClient
|
|
12
14
|
include TokenProvider
|
|
@@ -43,21 +45,19 @@ module KeycloakSdk
|
|
|
43
45
|
# 방지. 불일치·부재·검증실패는 모두 거부(fail-closed). 생략 시 id_token 검증을 건너뛴다
|
|
44
46
|
# (여덟 언어 공통 — exchange에서 nonce를 필수로 만들지 않는다).
|
|
45
47
|
def exchange_code(code:, code_verifier:, redirect_uri:, expected_nonce: nil)
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
48
|
+
token_set = token_request("authorization_code exchange",
|
|
49
|
+
{ grant_type: "authorization_code", code: code, redirect_uri: redirect_uri,
|
|
50
|
+
code_verifier: code_verifier }, required: :code)
|
|
49
51
|
verify_nonce!(token_set.id_token, expected_nonce) unless expected_nonce.nil?
|
|
50
52
|
token_set
|
|
51
53
|
end
|
|
52
54
|
|
|
53
55
|
def refresh(refresh_token:)
|
|
54
|
-
|
|
55
|
-
client.refresh_token = refresh_token
|
|
56
|
-
token_request("refresh") { client.access_token! }
|
|
56
|
+
token_request("refresh", { grant_type: "refresh_token", refresh_token: refresh_token }, required: :refresh_token)
|
|
57
57
|
end
|
|
58
58
|
|
|
59
59
|
def client_credentials_token
|
|
60
|
-
token_request("client-credentials"
|
|
60
|
+
token_request("client-credentials", { grant_type: "client_credentials", scope: @config.scopes.join(" ") })
|
|
61
61
|
end
|
|
62
62
|
|
|
63
63
|
# TokenProvider 계약(직접 사용용). admin은 캐싱 provider를 별도로 쓴다.
|
|
@@ -66,25 +66,34 @@ module KeycloakSdk
|
|
|
66
66
|
end
|
|
67
67
|
|
|
68
68
|
def introspect(token)
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
69
|
+
form = form!("introspection", token: token, client_id: @config.client_id, client_secret: @config.client_secret)
|
|
70
|
+
resp = Http.decode_json(Http.read_capped(@http, :post, @endpoints.introspection,
|
|
71
|
+
body: form, max_bytes: Http::TOKEN_RESPONSE_MAX_BYTES,
|
|
72
|
+
what: "introspection"))
|
|
72
73
|
raise AuthError, "introspection failed: HTTP #{resp.status}" unless resp.success?
|
|
73
74
|
|
|
74
75
|
IntrospectionResult.from_response(resp.body)
|
|
75
|
-
rescue
|
|
76
|
+
rescue Error
|
|
77
|
+
raise
|
|
78
|
+
rescue StandardError => e # Faraday 밖 예외도 — net-http 0.10 의 응답 헤더 검증은 ArgumentError 다(어댑터 목록 밖)
|
|
76
79
|
raise TransportError, "introspection transport error: #{RedactedCause.describe(e)}", cause: RedactedCause.new(e)
|
|
77
80
|
end
|
|
78
81
|
|
|
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). 해석은 상태 검사보다 먼저다.
|
|
79
86
|
def logout(refresh_token:)
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
raise AuthError, "logout failed: HTTP #{resp.status}" unless resp.success?
|
|
87
|
+
form = form!("logout", client_id: @config.client_id, client_secret: @config.client_secret,
|
|
88
|
+
refresh_token: refresh_token)
|
|
89
|
+
resp = Http.read_capped(@http, :post, @endpoints.end_session,
|
|
90
|
+
body: form, max_bytes: Http::TOKEN_RESPONSE_MAX_BYTES, what: "logout")
|
|
91
|
+
raise AuthError, "logout failed: HTTP #{resp.status}" unless Http.decode_json(resp, check_utf8: false).success?
|
|
85
92
|
|
|
86
93
|
nil
|
|
87
|
-
rescue
|
|
94
|
+
rescue Error
|
|
95
|
+
raise
|
|
96
|
+
rescue StandardError => e # introspect 와 같다(Faraday 밖 예외도 감싼다)
|
|
88
97
|
raise TransportError, "logout transport error: #{RedactedCause.describe(e)}", cause: RedactedCause.new(e)
|
|
89
98
|
end
|
|
90
99
|
|
|
@@ -97,6 +106,8 @@ module KeycloakSdk
|
|
|
97
106
|
# rack-oauth2의 프로세스 전역 HTTP 타임아웃을 Config로 설정한다(require 시점 하드코딩 대신).
|
|
98
107
|
# 타임아웃은 Faraday::Connection이 아니라 그 #options(Faraday::RequestOptions)에 있다
|
|
99
108
|
# (Connection에 open_timeout=/timeout= 세터가 없어 NoMethodError — 게차 참조).
|
|
109
|
+
# ⚠️ SDK 의 토큰 요청은 이제 rack-oauth2 의 연결을 타지 않는다(그랜트는 `token_request` 가 직접 보낸다) — 이 등록이
|
|
110
|
+
# 닿는 것은 같은 프로세스의 다른 rack-oauth2 사용자뿐이다. 등록은 first-wins(`@@http_config ||= block`)다.
|
|
100
111
|
def configure_rack_oauth2_timeouts(config)
|
|
101
112
|
Rack::OAuth2.http_config do |conn|
|
|
102
113
|
conn.options.open_timeout = config.connect_timeout
|
|
@@ -118,14 +129,18 @@ module KeycloakSdk
|
|
|
118
129
|
raise AuthError, "authorization_code exchange failed: invalid id_token: #{e.message}"
|
|
119
130
|
end
|
|
120
131
|
|
|
121
|
-
#
|
|
132
|
+
# 토큰 그랜트 하나와 그 오류 경계(§4). 하위 예외는 SDK 타입이 되고 `cause` 에는 원본 대신 `RedactedCause` 가 달린다.
|
|
122
133
|
# ⚠️ OAuth 오류는 **코드와 HTTP 상태만** 싣는다 — `error_description` 은 서버가 고른 자유 문장이라 토큰을
|
|
123
134
|
# 되울릴 수 있고, 오류 본문이 JSON 이 아니면 rack-oauth2 가 본문 전체를 거기 넣는다. 코드 자리도 서버 값이라
|
|
124
135
|
# **코드 모양**(`OAUTH_CODE` — 등록 코드는 전부 소문자·밑줄)일 때만 메시지에 싣는다(`oauth_error` 에는 그대로).
|
|
125
|
-
# ⚠️ 마지막 `StandardError` 는
|
|
126
|
-
#
|
|
127
|
-
|
|
128
|
-
|
|
136
|
+
# ⚠️ 마지막 `StandardError` 는 형식이 틀린 200 을 읽다 나는 것(NoMethodError·AttrMissing·'Unknown Token Type')과
|
|
137
|
+
# `to_token_set` 의 형 변환 실패다 — 원본이 새면 Ruby 3.2 의 NoMethodError 가 본문을 인용한다.
|
|
138
|
+
# ⚠️ 필수 값(`code`·`refresh_token`)이 비면 보내지 않는다 — rack-oauth2 의 그랜트가 하던 검사이고, 그때는 이 경계
|
|
139
|
+
# 밖에서 raw `AttrRequired::AttrMissing` 으로 샜다.
|
|
140
|
+
def token_request(operation, params, required: nil)
|
|
141
|
+
raise AuthError, "#{operation} failed: #{required} is required" if required && missing?(params[required])
|
|
142
|
+
|
|
143
|
+
to_token_set(oauth_token(post_grant(operation, params)))
|
|
129
144
|
rescue Error
|
|
130
145
|
raise
|
|
131
146
|
rescue Rack::OAuth2::Client::Error => e
|
|
@@ -139,6 +154,50 @@ module KeycloakSdk
|
|
|
139
154
|
raise AuthError, "#{operation} failed: unusable token response (#{e.class})", cause: RedactedCause.new(e)
|
|
140
155
|
end
|
|
141
156
|
|
|
157
|
+
# 그랜트를 SDK 커넥션으로 보낸다 — 클라이언트 인증은 rack-oauth2 의 기본(`:basic`)과 같은 모양(id·secret 을
|
|
158
|
+
# 각각 form-url-encode 한 뒤 base64)이고, 빈 값은 rack-oauth2 의 `Util.compact_hash` 처럼 보내지 않는다.
|
|
159
|
+
# 본문은 `TOKEN_RESPONSE_MAX_BYTES` 까지만 읽는다.
|
|
160
|
+
def post_grant(operation, params)
|
|
161
|
+
form = form!(operation, **params).reject { |_, v| v.nil? || v.to_s.match?(/\A[[:space:]]*\z/) }
|
|
162
|
+
pair = [@config.client_id, @config.client_secret].map { |v| URI.encode_www_form_component(v) }.join(":")
|
|
163
|
+
basic = { "Authorization" => "Basic #{Base64.strict_encode64(pair)}" }
|
|
164
|
+
Http.decode_json(Http.read_capped(@http, :post, @endpoints.token,
|
|
165
|
+
body: form, headers: basic,
|
|
166
|
+
max_bytes: Http::TOKEN_RESPONSE_MAX_BYTES, what: "token"))
|
|
167
|
+
end
|
|
168
|
+
|
|
169
|
+
# rack-oauth2 의 응답 규칙(`Client#handle_response` — 2.3.0 client.rb:205-240)을 SDK 가 읽은 본문에 그대로 건다:
|
|
170
|
+
# 200·201 은 token_type 이 bearer 인 `AccessToken::Bearer`, 그 밖은 `Client::Error`(본문이 객체가 아니면 'Unknown').
|
|
171
|
+
# 그 메서드는 private 이라 규칙만 옮겼다 — 결과·오류는 rack-oauth2 의 공개 타입이라 위 오류 대응이 그대로다.
|
|
172
|
+
# 객체가 아닌 200 본문은 rack-oauth2 처럼 NoMethodError 로 떨어져 `token_request` 가 AuthError 로 바꾼다.
|
|
173
|
+
def oauth_token(resp)
|
|
174
|
+
body = resp.body
|
|
175
|
+
unless (200..201).cover?(resp.status)
|
|
176
|
+
error = body.is_a?(Hash) ? body.transform_keys(&:to_sym) : { error: "Unknown", error_description: body }
|
|
177
|
+
raise Rack::OAuth2::Client::Error.new(resp.status, error)
|
|
178
|
+
end
|
|
179
|
+
|
|
180
|
+
token_hash = body.transform_keys(&:to_sym)
|
|
181
|
+
raise "Unknown Token Type" unless token_hash[:token_type]&.downcase == "bearer"
|
|
182
|
+
|
|
183
|
+
Rack::OAuth2::AccessToken::Bearer.new(token_hash)
|
|
184
|
+
end
|
|
185
|
+
|
|
186
|
+
# rack-oauth2 의 `attr_required` 와 같은 「비었다」 — nil 이거나 빈 값(공백뿐인 문자열은 비지 않았다).
|
|
187
|
+
def missing?(value)
|
|
188
|
+
value.respond_to?(:empty?) ? value.empty? : value.nil?
|
|
189
|
+
end
|
|
190
|
+
|
|
191
|
+
# 폼 값이 잘못된 UTF-8 이면 요청 없이 거부하고(어느 자리인지만 말한다) 아니면 폼을 돌려준다. Faraday 의 폼
|
|
192
|
+
# 인코더(`Faraday::Utils.escape` 의 `gsub`)가 그것에서 raw ArgumentError 를 냈다(실측: logout·introspect 는 요청 0 건에
|
|
193
|
+
# raw, 그랜트는 「unusable token response (ArgumentError)」라는 틀린 말). 고쳐 쓰지 않는다.
|
|
194
|
+
def form!(operation, **form)
|
|
195
|
+
bad = form.find { |_, v| v.is_a?(String) && !v.valid_encoding? }
|
|
196
|
+
raise AuthError, "#{operation} failed: #{bad.first} is not valid UTF-8" if bad
|
|
197
|
+
|
|
198
|
+
form
|
|
199
|
+
end
|
|
200
|
+
|
|
142
201
|
def oauth_client(redirect_uri: nil)
|
|
143
202
|
Rack::OAuth2::Client.new(
|
|
144
203
|
identifier: @config.client_id,
|
data/lib/keycloak_sdk/http.rb
CHANGED
|
@@ -1,11 +1,182 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
3
|
require "faraday"
|
|
4
|
+
require "faraday/net_http"
|
|
5
|
+
require "json"
|
|
4
6
|
|
|
5
7
|
module KeycloakSdk
|
|
6
8
|
# 공유 Faraday 커넥션 팩토리. 타임아웃을 config에서 주입하고,
|
|
7
9
|
# follow_redirects 미들웨어를 절대 장착하지 않는다(SSRF 하드닝 — Faraday는 기본 미추종).
|
|
10
|
+
# 상한을 건 본문 읽기(`read_capped`)도 여기 있다 — 토큰·introspection·logout·JWKS 레인이 같은 기제를 쓴다.
|
|
8
11
|
module Http
|
|
12
|
+
# ⚠️ **응답 **틀**(상태 줄·헤더 줄·청크 크기/확장 줄·트레일러)의 상한.** `read_capped` 의 1 MiB 는 `on_data` 로 오는
|
|
13
|
+
# **본문 바이트**만 본다 — net-http(net-protocol 의 `BufferedIO`)는 그 앞뒤로 틀을 한도 없이 읽는다(헤더·트레일러는
|
|
14
|
+
# `readuntil("\n")`, 청크 크기/확장 줄도 `readline`). 그래서 16 MiB 헤더 한 줄·청크 확장·트레일러가 상한 밖이었다
|
|
15
|
+
# (response-framing-unbounded · 2026-10-09 실측 · auth·admin 같다). 다른 여덟 언어는 전부 틀을 묶는다(.NET 64 KiB ·
|
|
16
|
+
# Go 64 KiB · Java 8,192/100 · undici · h11 · hyper).
|
|
17
|
+
#
|
|
18
|
+
# ⚠️ **두 상한은 함께 움직인다.** `MAX_FRAMING_LINE_BYTES` 는 한 **줄**(F1·F2·F3b — 거대한 줄 하나)을, `MAX_FRAMING_BYTES`
|
|
19
|
+
# 는 한 **응답의 틀 전체**(F3a — 작은 줄 다수)를 묶는다. 둘 중 하나만 두면 다른 공격이 지나간다(변이 증명 M1·M2).
|
|
20
|
+
# ⚠️ **틀 예산은 본문 중에 읽히는 청크 크기 줄도 센다** — 그래서 큰 본문을 수십 바이트 청크로 잘게 쪼갠 응답은
|
|
21
|
+
# 거부된다. Keycloak·주류 리버스 프록시는 KiB 단위로 청크하므로(nginx proxy_buffer 4–8 KiB) 현실 트래픽은 통과한다
|
|
22
|
+
# (control: `response_framing_cap_spec` 의 「realistically chunked multi-chunk body」). admin 레인은 본문 상한이 없어
|
|
23
|
+
# 이 예산이 **순수 안전 추가**다(잘게 쪼갠 무한 청크 틀을 여기서 끊는다).
|
|
24
|
+
# · 8,192 = Java MessageConstraints 줄 한도. Keycloak 26.6 의 가장 긴 응답 틀 줄 85 B(Go 실측)의 ×96.
|
|
25
|
+
# · 65,536 = .NET 헤더+트레일러 한도 · Go 머리 블록 한도. Keycloak 머리 블록 ≤339 B · 브라우저 로그인 최대 3,018 B
|
|
26
|
+
# (둘 다 Go 실측) — SDK 가 받는 것의 ×19 이상이라 기본 서버가 어떤 프록시를 거쳐 보내도 거부하지 않는다.
|
|
27
|
+
# ⚠️ 맨 십진 리터럴 — 교차언어 가드가 이 줄을 읽을 수 있어야 한다(`TOKEN_RESPONSE_MAX_BYTES` 와 같은 관용).
|
|
28
|
+
MAX_FRAMING_LINE_BYTES = 8_192
|
|
29
|
+
MAX_FRAMING_BYTES = 65_536
|
|
30
|
+
# ⚠️ 메시지에 바이트를 싣지 않는다(상수 문자열) — 다른 경계와 같은 규율(§4 · `RedactedCause`).
|
|
31
|
+
FRAMING_LINE_MSG = "HTTP response framing line exceeds #{MAX_FRAMING_LINE_BYTES} bytes".freeze
|
|
32
|
+
FRAMING_TOTAL_MSG = "HTTP response framing exceeds #{MAX_FRAMING_BYTES} bytes".freeze
|
|
33
|
+
# ⚠️ 공개 API 가 아니다 — 교차언어 내부 값이다(Go 의 responseHeaderMaxBytes 도 비노출). 시험은 const_get 으로 본다.
|
|
34
|
+
private_constant :MAX_FRAMING_LINE_BYTES, :MAX_FRAMING_BYTES, :FRAMING_LINE_MSG, :FRAMING_TOTAL_MSG
|
|
35
|
+
# 토큰 엔드포인트(세 그랜트 · admin 레인의 자기 토큰)·introspection·logout 응답 본문의 상한(바이트).
|
|
36
|
+
# 1 MiB 는 Keycloak 26.6 이 기본 설정으로 받는 가장 긴 Bearer(65,459 바이트 — 하나 더 길면 HTTP 431)의
|
|
37
|
+
# 16 배라 서버가 받는 토큰은 거부하지 않고, 끝없는 본문은 여기서 멈춘다.
|
|
38
|
+
# ⚠️ JWKS 의 51,200 을 빌려 쓰지 말 것 — 서비스 계정 토큰은 관리하는 realm 수만큼 자란다.
|
|
39
|
+
# ⚠️ 맨 십진 리터럴이어야 한다 — 아홉 SDK 가 같은 값을 쓰고 교차언어 가드가 이 줄을 읽는다.
|
|
40
|
+
TOKEN_RESPONSE_MAX_BYTES = 1_048_576
|
|
41
|
+
|
|
42
|
+
# ⚠️ **SDK 가 직접 읽는 요청은 인코딩 없는 본문을 청한다.** Accept-Encoding 이 없으면 net-http 가 gzip 을 청하고
|
|
43
|
+
# 스스로 푸는데, 그 inflater 는 상한에서 읽기를 끊어도 ensure 에서 `Inflater#finish` 로 **지금 읽은 압축 조각을
|
|
44
|
+
# 끝까지** 푼다 — 16 KiB 조각 하나가 공백이면 ~16 MiB 다(실측: JWKS 상한이 지켜진 채 피크 +24 MB).
|
|
45
|
+
# 요청에 이 헤더가 있으면 net-http 는 자기 것을 붙이지 않고 풀지도 않는다. 그래도 gzip 을 보내는 서버는
|
|
46
|
+
# 압축된 바이트가 그대로 와 JSON 으로 읽히지 않으므로 SDK 오류로 닫힌다.
|
|
47
|
+
IDENTITY = { "Accept-Encoding" => "identity" }.freeze
|
|
48
|
+
|
|
49
|
+
# Faraday 의 JSON 응답 규칙 그대로(JSON 콘텐츠 타입만 · 빈 본문은 nil · 해석 실패는 Faraday::ParsingError).
|
|
50
|
+
# 스트리밍으로 읽은 본문은 커넥션의 json 미들웨어가 보지 못하므로(그때 본문은 비어 있다) 여기서 같은 규칙을 건다.
|
|
51
|
+
JSON_RESPONSE = Faraday::Response::Json.new(nil, content_type: /\bjson$/)
|
|
52
|
+
UNDECODABLE = "JSON text decodes to invalid UTF-8"
|
|
53
|
+
private_constant :IDENTITY, :JSON_RESPONSE, :UNDECODABLE
|
|
54
|
+
|
|
55
|
+
# 소켓 하나에 거는 **싱글턴 확장** — 전역 몽키패치가 아니라 이 SDK 가 연 `BufferedIO` 인스턴스 하나에만 붙는다
|
|
56
|
+
# (`BoundedHttp#on_connect`). 호스트 애플리케이션의 net-http 는 건드리지 않는다.
|
|
57
|
+
#
|
|
58
|
+
# 틀 줄은 전부 `readuntil`/`readline` 로 읽힌다(상태 줄·헤더 줄·청크 크기/확장 줄·트레일러 — `readline` 은
|
|
59
|
+
# `readuntil("\n").chop`). `readuntil` 은 net-protocol 원판과 **같은 버퍼 주사**를 하되(종단 문자를 `@rbuf` 에서 찾고,
|
|
60
|
+
# 못 찾을 때만 `rbuf_fill` 로 소켓에서 16 KiB 를 더 받는다), 채우기 **전에** 두 상한을 건다: 쌓인 부분 줄이
|
|
61
|
+
# `MAX_FRAMING_LINE_BYTES` 를 넘으면(F1·F2·F3b — 거대한 줄 하나) 그 자리에서, 한 응답의 틀 누적이
|
|
62
|
+
# `MAX_FRAMING_BYTES` 를 넘으면(F3a — 작은 줄 다수) 거부한다. 원판이 종단 문자를 찾을 때까지 16 MiB 를 통째로
|
|
63
|
+
# 담은 **뒤** 돌려주던 것을, 채우기 루프 안에서 끊는다.
|
|
64
|
+
#
|
|
65
|
+
# ⚠️ **net-protocol `BufferedIO` 내부(`@rbuf`·`@rbuf_offset`·private `rbuf_fill`·`rbuf_consume`)에 기댄다.**
|
|
66
|
+
# 한 바이트씩 읽는 `read(1)` 은 F3a 의 64 KiB 를 쌓느라 할당을 10 MB 넘게 튀겼다(실측) — 버퍼 주사는 그 churn 이 없다.
|
|
67
|
+
# 이 내부가 바뀌면 조용히 깨지므로 `http_framing_pins_spec` 이 그 모양(ivar·메서드·`readuntil`/`readline` 호출 경로)을
|
|
68
|
+
# 핀으로 고정해 **시끄럽게** 실패시킨다. 그 내부는 net-protocol 0.2.1(루비 3.2 하한)·0.2.2·0.3.0·0.4.0 에서 같고,
|
|
69
|
+
# 0.3.0 이 `readuntil` 에 `limit:` 키워드를 더했다 — net-http 0.10 은 모든 틀 줄을 그것으로 읽는다(아래).
|
|
70
|
+
# ⚠️ 거부는 `TransportError`(상수 메시지) — net-http 가 인식하지 않는 타입이라 그 **바깥** rescue 가 소켓을 닫고
|
|
71
|
+
# 다시 던진다(비우지 않는다 · idempotent 재시도 목록에 없어 재시도도 안 된다). Faraday 어댑터의
|
|
72
|
+
# `NET_HTTP_EXCEPTIONS` 에도 없어 공개 경계까지 `TransportError` 로 그대로 올라간다.
|
|
73
|
+
module BoundedReads
|
|
74
|
+
def kcsdk_reset_framing!
|
|
75
|
+
@kcsdk_framing_total = 0
|
|
76
|
+
end
|
|
77
|
+
|
|
78
|
+
# ⚠️ 시그니처는 net-protocol 원판(0.3.0+)과 같아야 한다 — net-http 0.9.x 이하는 `sock.readuntil("\n", true)` 로
|
|
79
|
+
# 위치 인자로, 0.10 은 `sock.readuntil("\n", ignore_eof, limit: 1 MiB)` 로 키워드를 붙여 부른다. 키워드를 못 받으면
|
|
80
|
+
# SDK 의 HTTP 호출이 전부 ArgumentError 다(net-protocol 0.4.0 실측). 그래서 `ignore_eof` 를 키워드로 바꾸지 않는다
|
|
81
|
+
# (Style/OptionalBooleanParameter 를 그 이유로 끈다).
|
|
82
|
+
# `limit:` 은 원판의 뜻 그대로다 — 같은 검증(ArgumentError), 넘으면 `Net::ReadLimitExceeded` 이고 소비하지 않는다
|
|
83
|
+
# (net-http 0.10 이 그것을 HTTPBadResponse 로 바꾼다). SDK 의 두 상한을 먼저 본다 — 둘 다 넘으면 SDK 오류가 이긴다.
|
|
84
|
+
def readuntil(terminator, ignore_eof = false, limit: nil) # rubocop:disable Style/OptionalBooleanParameter
|
|
85
|
+
kcsdk_check_limit(limit)
|
|
86
|
+
@kcsdk_framing_total ||= 0
|
|
87
|
+
offset = @rbuf_offset
|
|
88
|
+
begin
|
|
89
|
+
until (idx = @rbuf.index(terminator, offset))
|
|
90
|
+
kcsdk_bound_line(@rbuf.bytesize - @rbuf_offset, limit) # 이 줄에 쌓인, 아직 소비되지 않은 바이트
|
|
91
|
+
# 원판(0.3.0+)과 같은 되감기 — 두 바이트 종단 문자가 읽기 경계에 걸쳐도 찾는다(0.2.x 는 놓쳤다).
|
|
92
|
+
# net-http 의 `"\n"` 에서는 `@rbuf.bytesize` 와 같다.
|
|
93
|
+
offset = [@rbuf.bytesize - terminator.bytesize + 1, @rbuf_offset].max
|
|
94
|
+
rbuf_fill
|
|
95
|
+
end
|
|
96
|
+
len = idx + terminator.bytesize - @rbuf_offset
|
|
97
|
+
kcsdk_bound_line(len, limit)
|
|
98
|
+
line = rbuf_consume(len)
|
|
99
|
+
rescue EOFError
|
|
100
|
+
raise unless ignore_eof
|
|
101
|
+
|
|
102
|
+
line = rbuf_consume
|
|
103
|
+
end
|
|
104
|
+
kcsdk_charge_framing(line.bytesize)
|
|
105
|
+
line
|
|
106
|
+
end
|
|
107
|
+
|
|
108
|
+
def readline
|
|
109
|
+
readuntil("\n").chop
|
|
110
|
+
end
|
|
111
|
+
|
|
112
|
+
private
|
|
113
|
+
|
|
114
|
+
# ⚠️ 이름은 전부 `kcsdk_` 로 시작한다 — 싱글턴 확장은 원판의 같은 이름 메서드를 **가린다**(원판 안의 호출까지).
|
|
115
|
+
# 원판이 `limit:` 검증을 들인 판이 바로 0.3.0 이라, `check_limit` 같은 맨 이름은 언젠가 원판과 겹칠 수 있다.
|
|
116
|
+
|
|
117
|
+
# 줄 하나(`len` 바이트 — 채우는 중이면 쌓인 몫)를 소비하기 **전에** 본다: SDK 의 두 상한, 그다음 호출자의 `limit:`.
|
|
118
|
+
def kcsdk_bound_line(len, limit)
|
|
119
|
+
raise KeycloakSdk::TransportError, FRAMING_LINE_MSG if len > MAX_FRAMING_LINE_BYTES
|
|
120
|
+
raise KeycloakSdk::TransportError, FRAMING_TOTAL_MSG if @kcsdk_framing_total + len > MAX_FRAMING_BYTES
|
|
121
|
+
raise kcsdk_limit_error, "exceeded the #{limit} byte read limit" if limit && len > limit
|
|
122
|
+
end
|
|
123
|
+
|
|
124
|
+
# ⚠️ `Net::ReadLimitExceeded` 는 net-protocol 0.3.0+ 에만 있다 — `limit:` 을 넘기는 net-http 0.10 은 그 판을 요구하지만,
|
|
125
|
+
# 0.2.x 에서 누가 직접 넘기면 NameError 가 났다(Grok 적대 레그). 그때는 그 부모 `Net::ProtocolError` 다 — 둘 다
|
|
126
|
+
# Faraday 어댑터가 `ConnectionFailed` 로 바꾼다. 전역 상수를 세우지 않는다(싱글턴 확장 규율).
|
|
127
|
+
def kcsdk_limit_error
|
|
128
|
+
defined?(Net::ReadLimitExceeded) ? Net::ReadLimitExceeded : Net::ProtocolError
|
|
129
|
+
end
|
|
130
|
+
|
|
131
|
+
# 원판과 같은 검증 — `Integer ===` 는 호출자의 값에 메서드를 부르지 않는다(원판 주석과 같은 이유).
|
|
132
|
+
def kcsdk_check_limit(limit)
|
|
133
|
+
return if limit.nil? || (Integer === limit && limit.positive?) # rubocop:disable Style/CaseEquality
|
|
134
|
+
|
|
135
|
+
got = Integer === limit ? limit : "a non-Integer" # rubocop:disable Style/CaseEquality
|
|
136
|
+
raise ArgumentError, "limit must be a positive Integer, got #{got}"
|
|
137
|
+
end
|
|
138
|
+
|
|
139
|
+
# 돌려줄 줄 하나를 틀 예산에 올린다 — EOF 로 끝난 부분 줄(`ignore_eof`)은 `kcsdk_bound_line` 을 지나지 않으므로 여기서
|
|
140
|
+
# 두 상한을 다시 본다(원판도 그 갈래에는 `limit:` 을 걸지 않는다).
|
|
141
|
+
def kcsdk_charge_framing(len)
|
|
142
|
+
raise KeycloakSdk::TransportError, FRAMING_LINE_MSG if len > MAX_FRAMING_LINE_BYTES
|
|
143
|
+
|
|
144
|
+
@kcsdk_framing_total += len
|
|
145
|
+
raise KeycloakSdk::TransportError, FRAMING_TOTAL_MSG if @kcsdk_framing_total > MAX_FRAMING_BYTES
|
|
146
|
+
end
|
|
147
|
+
end
|
|
148
|
+
|
|
149
|
+
# `Net::HTTP` 인스턴스의 싱글턴에 **prepend** 해 소켓이 만들어지는 자리(`on_connect`, `connect` 끝)에서 그 소켓에만
|
|
150
|
+
# `BoundedReads` 를 건다. `begin_transport` 는 요청마다 틀 예산을 0 으로 되돌린다 — keep-alive 로 연결을 재사용해도
|
|
151
|
+
# 다음 응답은 새 예산을 받는다(한 요청의 1xx 중간 응답들은 같은 예산을 나눠 쓴다 — 그래야 1xx 홍수도 묶인다).
|
|
152
|
+
# ⚠️ **`Net::HTTP` 를 하위 클래스로 두지 않는다.** 그 하위 클래스 인스턴스가 Faraday 스택에 남으면 공개 표면 가드의
|
|
153
|
+
# 객체 걷기(`facade_dump_spec`·`hostile_path_matrix_spec`)가 그 세 시험을 끝내지 못했다(실측: 90–150 초 timeout 에
|
|
154
|
+
# 죽었다 — 이 설계로 바꾼 뒤 같은 셋은 14 초). 원인은 가드 코드를 읽은 추정이다 — SDK 네임스페이스로 보고 그 상속 공개
|
|
155
|
+
# 메서드(Net::HTTP 수백 개)를 불러 실 네트워크에서 기다린다. 표준 어댑터 + 인스턴스 prepend 는 그래프에 SDK 이름의
|
|
156
|
+
# 어댑터·HTTP 타입을 남기지 않는다.
|
|
157
|
+
module BoundedTransport
|
|
158
|
+
private
|
|
159
|
+
|
|
160
|
+
def on_connect
|
|
161
|
+
super
|
|
162
|
+
@socket.extend(BoundedReads)
|
|
163
|
+
@socket.kcsdk_reset_framing!
|
|
164
|
+
end
|
|
165
|
+
|
|
166
|
+
def begin_transport(req)
|
|
167
|
+
super
|
|
168
|
+
@socket.kcsdk_reset_framing! if @socket.respond_to?(:kcsdk_reset_framing!)
|
|
169
|
+
end
|
|
170
|
+
end
|
|
171
|
+
|
|
172
|
+
# 표준 `:net_http` 어댑터의 설정 블록 — 커넥션을 짓기 직전 그 `Net::HTTP` 인스턴스의 싱글턴에 `BoundedTransport` 를
|
|
173
|
+
# prepend 한다. 프록시 인자·연결 조립은 어댑터가 그대로 하고(원판 `net_http_connection`), 프록시·keep-alive 경로는
|
|
174
|
+
# `http_framing_pins_spec` 이 고정한다.
|
|
175
|
+
BOUND_CONNECTION = lambda do |http|
|
|
176
|
+
http.singleton_class.prepend(BoundedTransport)
|
|
177
|
+
end
|
|
178
|
+
private_constant :BoundedReads, :BoundedTransport, :BOUND_CONNECTION
|
|
179
|
+
|
|
9
180
|
module_function
|
|
10
181
|
|
|
11
182
|
def build(config, base_url: nil)
|
|
@@ -14,7 +185,57 @@ module KeycloakSdk
|
|
|
14
185
|
request: { timeout: config.read_timeout, open_timeout: config.connect_timeout }
|
|
15
186
|
) do |f|
|
|
16
187
|
yield f if block_given?
|
|
17
|
-
f.adapter :net_http
|
|
188
|
+
f.adapter :net_http, &BOUND_CONNECTION
|
|
189
|
+
end
|
|
190
|
+
end
|
|
191
|
+
|
|
192
|
+
# 요청 하나를 보내고 본문을 `max_bytes` 까지만 읽는다 — **상태와 무관하게**(오류 응답의 거대 본문도 같다).
|
|
193
|
+
# 돌려주는 응답의 `body` 는 읽은 바이트(BINARY 문자열)다. 넘으면 그 즉시 `TransportError` 이고 연결은 닫힌다.
|
|
194
|
+
#
|
|
195
|
+
# ⚠️ 판정은 청크를 **붙이기 전에** 한다 — 버퍼는 상한을 넘지 않고, 넘는 청크는 복사하지 않는다. 읽는 크기는
|
|
196
|
+
# SDK 가 정하지 못한다: net-http 가 소켓에서 16 KiB(`Net::BufferedIO::BUFSIZE`)씩 읽어 넘기므로 판정 순간
|
|
197
|
+
# 손에 든 것은 많아야 상한 + 청크 하나(16,384 바이트)다. 버퍼는 읽은 만큼만 자란다(미리 상한만큼 잡지 않는다).
|
|
198
|
+
# ⚠️ `Content-Length` 만 보면 그 헤더가 없거나 거짓인 응답을 놓친다 — 누적치로 판정한다.
|
|
199
|
+
def read_capped(conn, method, url, max_bytes:, what:, body: nil, headers: {})
|
|
200
|
+
buf = String.new(encoding: Encoding::BINARY)
|
|
201
|
+
resp = conn.run_request(method, url, body, IDENTITY.merge(headers)) do |req|
|
|
202
|
+
req.options.on_data = proc do |chunk, _received|
|
|
203
|
+
over = buf.bytesize + chunk.bytesize > max_bytes
|
|
204
|
+
raise TransportError, "#{what} response exceeds #{max_bytes} bytes" if over
|
|
205
|
+
|
|
206
|
+
buf << chunk
|
|
207
|
+
end
|
|
208
|
+
end
|
|
209
|
+
resp.env.body = buf
|
|
210
|
+
resp
|
|
211
|
+
end
|
|
212
|
+
|
|
213
|
+
# `read_capped` 의 본문을 커넥션의 json 미들웨어가 하던 그대로 해석한다(응답을 돌려준다).
|
|
214
|
+
# ⚠️ 해석한 값의 문자열이 잘못된 UTF-8 이면 해석 실패다(Faraday::ParsingError ← JSON::ParserError — 짝 없는
|
|
215
|
+
# 서로게이트 이스케이프에서 json 3 이 내는 것과 같은 모양). 고쳐 쓰지 않는다 — 그 값은 SDK 를 지나며 raw 예외가 된다.
|
|
216
|
+
# `check_utf8: false` 는 해석한 값을 하나도 쓰지 않는 호출(logout)의 것이다 — 미들웨어의 판정만 남는다.
|
|
217
|
+
def decode_json(resp, check_utf8: true)
|
|
218
|
+
JSON_RESPONSE.on_complete(resp.env)
|
|
219
|
+
return resp if !check_utf8 || utf8?(resp.body)
|
|
220
|
+
|
|
221
|
+
begin
|
|
222
|
+
raise JSON::ParserError, UNDECODABLE
|
|
223
|
+
rescue JSON::ParserError => e
|
|
224
|
+
raise Faraday::ParsingError.new(e, resp) # 원인 사슬도 json 3 의 실패와 같다(ParsingError <- ParserError)
|
|
225
|
+
end
|
|
226
|
+
end
|
|
227
|
+
|
|
228
|
+
# 해석한 JSON 값(키 포함)의 문자열이 전부 올바른 인코딩인가. 해석하지 않은 본문(BINARY)은 언제나 참이다.
|
|
229
|
+
# ⚠️ **json 버전으로 막을 수 없다** — 잠긴 json 3.0.2 도 날 잘못된 UTF-8 바이트(0xFF)는 그대로 받아 잘못된
|
|
230
|
+
# 문자열을 내고, json 2.9–2.21 은 짝 없는 **낮은** 서로게이트 이스케이프(\udc00)까지 그렇게 푼다(둘 다 실측).
|
|
231
|
+
# 그 문자열이 지나는 자리마다 raw 예외다 — OAuth 코드 대조(`match?`)의 ArgumentError, admin 헤더의
|
|
232
|
+
# Encoding::CompatibilityError(net-http `strip`), ruby-jwt base64 의 ArgumentError.
|
|
233
|
+
def utf8?(value)
|
|
234
|
+
case value
|
|
235
|
+
when String then value.valid_encoding?
|
|
236
|
+
when Hash then value.all? { |k, v| utf8?(k) && utf8?(v) }
|
|
237
|
+
when Array then value.all? { |v| utf8?(v) }
|
|
238
|
+
else true
|
|
18
239
|
end
|
|
19
240
|
end
|
|
20
241
|
end
|
|
@@ -107,25 +107,26 @@ module KeycloakSdk
|
|
|
107
107
|
|
|
108
108
|
def fetch
|
|
109
109
|
# ⚠️ 상한은 **상태와 무관하게** 건다. 200 만 겨누면 오류 응답의 거대 본문이 그대로
|
|
110
|
-
# 들어온다 — php 가 정확히 그 순서였다(상태 검사 전에 `json_decode`).
|
|
111
|
-
|
|
112
|
-
resp = @http.get(@jwks_url) do |req|
|
|
113
|
-
req.options.on_data = proc do |chunk, _received|
|
|
114
|
-
buf << chunk
|
|
115
|
-
raise TransportError, "JWKS response exceeds #{JWKS_MAX_BYTES} bytes" if buf.bytesize > JWKS_MAX_BYTES
|
|
116
|
-
end
|
|
117
|
-
end
|
|
110
|
+
# 들어온다 — php 가 정확히 그 순서였다(상태 검사 전에 `json_decode`). 기제는 토큰 레인과 같은 `Http.read_capped`.
|
|
111
|
+
resp = Http.read_capped(@http, :get, @jwks_url, max_bytes: JWKS_MAX_BYTES, what: "JWKS")
|
|
118
112
|
raise TransportError, "JWKS fetch failed: HTTP #{resp.status}" unless resp.success?
|
|
119
113
|
|
|
120
114
|
# ⚠️ `on_data` 를 쓰면 Faraday 는 본문을 누적하지 않으므로 json 미들웨어가 돌지 않는다 —
|
|
121
115
|
# 파싱은 여기서 한다. 파싱 실패도 경계에서 SDK 타입이 되어야 한다(§4).
|
|
116
|
+
# ⚠️ 잘못된 UTF-8 로 풀리는 본문도 해석 실패다(`Http.utf8?`) — n·e 가 그러면 ruby-jwt 의 base64 가 검증 중에
|
|
117
|
+
# raw ArgumentError 를 냈다(실측, 잠긴 json 3.0.2 에서도).
|
|
122
118
|
body = begin
|
|
123
|
-
JSON.parse(
|
|
119
|
+
parsed = JSON.parse(resp.body)
|
|
120
|
+
raise JSON::ParserError, "JSON text decodes to invalid UTF-8" unless Http.utf8?(parsed)
|
|
121
|
+
|
|
122
|
+
parsed
|
|
124
123
|
rescue JSON::ParserError => e
|
|
125
124
|
raise TransportError, "JWKS response unparsable (JSON::ParserError)", cause: RedactedCause.new(e)
|
|
126
125
|
end
|
|
127
126
|
validate_key_set!(body)
|
|
128
|
-
rescue
|
|
127
|
+
rescue Error
|
|
128
|
+
raise
|
|
129
|
+
rescue StandardError => e # Faraday 밖 예외도 — net-http 0.10 의 응답 헤더 검증은 ArgumentError 다(어댑터 목록 밖)
|
|
129
130
|
raise TransportError, "JWKS transport error: #{RedactedCause.describe(e)}", cause: RedactedCause.new(e)
|
|
130
131
|
end
|
|
131
132
|
|
|
@@ -35,6 +35,10 @@ module KeycloakSdk
|
|
|
35
35
|
# ⚠️ nil·공백은 생성자와 같이 ConfigError — ruby-jwt 는 `aud: nil` 이면 aud 검사를 건너뛴다.
|
|
36
36
|
def validate(token, audience: @audience)
|
|
37
37
|
raise ConfigError, "audience is required" if audience.nil? || audience.to_s.strip.empty?
|
|
38
|
+
# ⚠️ ruby-jwt 는 맨 먼저 토큰을 `split` 하고, 잘못된 UTF-8 이면 그것이 raw ArgumentError 다(실측).
|
|
39
|
+
if token.is_a?(String) && !token.valid_encoding?
|
|
40
|
+
raise TokenValidationError, "JWT validation failed: token is not valid UTF-8"
|
|
41
|
+
end
|
|
38
42
|
|
|
39
43
|
payload, = JWT.decode(token, nil, true, decode_options(audience))
|
|
40
44
|
to_validated(payload)
|
|
@@ -45,20 +45,23 @@ module KeycloakSdk
|
|
|
45
45
|
|
|
46
46
|
private
|
|
47
47
|
|
|
48
|
+
# 본문은 `Http::TOKEN_RESPONSE_MAX_BYTES` 까지만 읽는다 — 넘으면 `TransportError` 이고 admin 요청은 나가지 않는다.
|
|
48
49
|
def request_token
|
|
49
|
-
resp = @http
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
50
|
+
resp = Http.decode_json(Http.read_capped(@http, :post, @token_url,
|
|
51
|
+
body: { grant_type: "client_credentials",
|
|
52
|
+
client_id: @config.client_id,
|
|
53
|
+
client_secret: @config.client_secret,
|
|
54
|
+
scope: @config.scopes.join(" ") },
|
|
55
|
+
max_bytes: Http::TOKEN_RESPONSE_MAX_BYTES, what: "token"))
|
|
55
56
|
unless resp.success?
|
|
56
57
|
oauth = resp.body.is_a?(Hash) ? resp.body["error"] : nil
|
|
57
58
|
raise AuthError.new("client-credentials token request failed: HTTP #{resp.status}", oauth_error: oauth)
|
|
58
59
|
end
|
|
59
60
|
|
|
60
61
|
TokenSet.from_response(resp.body, received_at: Time.now.to_f)
|
|
61
|
-
rescue
|
|
62
|
+
rescue Error
|
|
63
|
+
raise
|
|
64
|
+
rescue StandardError => e # Faraday 밖 예외도 — net-http 0.10 의 응답 헤더 검증은 ArgumentError 다(어댑터 목록 밖)
|
|
62
65
|
raise TransportError, "token endpoint transport error: #{RedactedCause.describe(e)}", cause: RedactedCause.new(e)
|
|
63
66
|
end
|
|
64
67
|
end
|
data/lib/keycloak_sdk/version.rb
CHANGED
data/lib/keycloak_sdk.rb
CHANGED
|
@@ -30,4 +30,6 @@ end
|
|
|
30
30
|
# (b) Config 타임아웃을 무시했다. 이제는 AuthClient#initialize에서 Config의 connect/read 타임아웃으로
|
|
31
31
|
# 설정한다(auth_client.rb) — require 부작용 제거 + config 반영. 전역이라는 근본 한계는 남지만
|
|
32
32
|
# "SDK auth를 실제로 쓸 때"로 스코프가 좁혀진다(require 시점 아님).
|
|
33
|
+
# ⚠️ SDK 자신의 토큰 요청은 이 전역 연결을 타지 않는다 — 그랜트는 SDK 커넥션(`Http.build`, 클라이언트마다 Config
|
|
34
|
+
# 타임아웃)으로 직접 보낸다(응답 상한 때문). rack-oauth2 의 HTTP 연결을 쓰는 SDK 경로는 이제 없다(인가 URL 조립은 네트워크가 없다).
|
|
33
35
|
require "rack/oauth2"
|