keycloak-sdk 1.3.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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: b1a2f1983231445d40411139a273115f4680aced0fe873b06a26bf0965e050cb
4
- data.tar.gz: 5c5b50cdfca4f6839d2bcb94a9a107f0772bc3a4dad386a43b77ccc8b44a37b7
3
+ metadata.gz: 561abaa5612faf7d8d0b60dda6e925f2db242ae134e0fe68f97469ce3456ab26
4
+ data.tar.gz: 1b2ff3c20ae257420c10a0d87cca3298059aa1f4c716c0c2179874eb0550f1ab
5
5
  SHA512:
6
- metadata.gz: dcde89692c25c6ab41a45363018c7b47d8d629d45ce5660f74f80f1025394438314dee56e70b4e2e91d3fa63155589867ddbded27a91d79e744115ca0880a8de
7
- data.tar.gz: 4c37d217507bdee67f59b96b2e130cc057cab28a19c7ddf1686d517c0ea18c4dccd208bfb04cb2916673dff7216ffee9e029c49d309f20fe26a5575f5bef7114
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.3.0` is on RubyGems** — a minor release on top of `1.2.0`; `1.0.0` was the first release carrying the stability guarantee. A bare `gem install keycloak-sdk` resolves it. **Security**: token, introspection and logout responses — on the grants, `introspect`, `logout` and the admin client's `ClientCredentialsTokenProvider` — are now read only up to 1,048,576 bytes; a usable token padded with 32 MiB of JSON whitespace used to be read whole, and `logout` read any body to the end. The cap is 16 times the longest bearer a default Keycloak 26.6 accepts, so no token a server accepts is refused; a larger response raises `KeycloakSdk::TransportError` (`token response exceeds 1048576 bytes` and the like) whatever its status, and the admin client sends no admin request. A response that decodes to invalid UTF-8 and an access token that a header cannot carry now raise SDK errors instead of a raw `ArgumentError` or `Encoding::CompatibilityError` — the admin client's quoted the whole bearer token. An invalid-UTF-8 input to `validate`, `introspect`, `logout` or a grant now raises an SDK error too (`TokenValidationError`, or `AuthError` without a request). ⚠️ **Token, introspection, logout and JWKS requests now send `Accept-Encoding: identity`**, so a server that answers them with gzip anyway fails. ⚠️ **The grants now go out on the SDK's own connection** rather than rack-oauth2's process-wide one: `Config` timeouts apply per client and the `User-Agent` becomes Faraday's default, while client authentication, parameters and error handling are unchanged; an empty `code` or `refresh_token` raises `AuthError` without a request. **Added**: `KeycloakSdk::Http::TOKEN_RESPONSE_MAX_BYTES` and the helpers `Http.read_capped`, `Http.decode_json` and `Http.utf8?`.
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
 
@@ -24,14 +24,25 @@ module KeycloakSdk
24
24
  # 때(`initialize_http_header`) CR·LF 면 헤더 값을 **통째로 인용한** raw ArgumentError(= Bearer 누출)를,
25
25
  # `MAX_FIELD_LENGTH`(65,536)를 넘으면 raw ArgumentError 를, 잘못된 UTF-8 이면 `strip` 의 raw
26
26
  # Encoding::CompatibilityError 를 낸다 — 셋 다 admin 경계(`rescue Faraday::Error`)를 지나 샜다(실측).
27
- # ⚠️ 고쳐 쓰지 않는다(잘라내거나 바꿔 보내면 다른 토큰이다). NUL·U+00FF 위 문자는 net-http 가 막지 않으므로
28
- # 그대로 보내고 판정은 서버에 맡긴다. 메시지에는 토큰을 싣지 않는다(길이만).
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
+ # 위 문자)은 그대로 보내고 판정은 서버에 맡긴다. 메시지에는 토큰을 싣지 않는다(길이만).
29
32
  def sendable!(token)
30
33
  raise AuthError, "admin request not sent: the access token is not valid UTF-8" unless token.valid_encoding?
31
34
 
32
35
  if token.match?(/[\r\n]/)
33
36
  raise AuthError, "admin request not sent: the access token holds CR or LF, which an HTTP header cannot carry"
34
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
35
46
 
36
47
  limit = field_limit
37
48
  return if limit.nil? || "Bearer ".bytesize + token.bytesize <= limit
@@ -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 Faraday::Error => e
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
 
@@ -73,7 +73,9 @@ module KeycloakSdk
73
73
  raise AuthError, "introspection failed: HTTP #{resp.status}" unless resp.success?
74
74
 
75
75
  IntrospectionResult.from_response(resp.body)
76
- rescue Faraday::Error => e
76
+ rescue Error
77
+ raise
78
+ rescue StandardError => e # Faraday 밖 예외도 — net-http 0.10 의 응답 헤더 검증은 ArgumentError 다(어댑터 목록 밖)
77
79
  raise TransportError, "introspection transport error: #{RedactedCause.describe(e)}", cause: RedactedCause.new(e)
78
80
  end
79
81
 
@@ -89,7 +91,9 @@ module KeycloakSdk
89
91
  raise AuthError, "logout failed: HTTP #{resp.status}" unless Http.decode_json(resp, check_utf8: false).success?
90
92
 
91
93
  nil
92
- rescue Faraday::Error => e
94
+ rescue Error
95
+ raise
96
+ rescue StandardError => e # introspect 와 같다(Faraday 밖 예외도 감싼다)
93
97
  raise TransportError, "logout transport error: #{RedactedCause.describe(e)}", cause: RedactedCause.new(e)
94
98
  end
95
99
 
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "faraday"
4
+ require "faraday/net_http"
4
5
  require "json"
5
6
 
6
7
  module KeycloakSdk
@@ -8,6 +9,29 @@ module KeycloakSdk
8
9
  # follow_redirects 미들웨어를 절대 장착하지 않는다(SSRF 하드닝 — Faraday는 기본 미추종).
9
10
  # 상한을 건 본문 읽기(`read_capped`)도 여기 있다 — 토큰·introspection·logout·JWKS 레인이 같은 기제를 쓴다.
10
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
11
35
  # 토큰 엔드포인트(세 그랜트 · admin 레인의 자기 토큰)·introspection·logout 응답 본문의 상한(바이트).
12
36
  # 1 MiB 는 Keycloak 26.6 이 기본 설정으로 받는 가장 긴 Bearer(65,459 바이트 — 하나 더 길면 HTTP 431)의
13
37
  # 16 배라 서버가 받는 토큰은 거부하지 않고, 끝없는 본문은 여기서 멈춘다.
@@ -28,6 +52,131 @@ module KeycloakSdk
28
52
  UNDECODABLE = "JSON text decodes to invalid UTF-8"
29
53
  private_constant :IDENTITY, :JSON_RESPONSE, :UNDECODABLE
30
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
+
31
180
  module_function
32
181
 
33
182
  def build(config, base_url: nil)
@@ -36,7 +185,7 @@ module KeycloakSdk
36
185
  request: { timeout: config.read_timeout, open_timeout: config.connect_timeout }
37
186
  ) do |f|
38
187
  yield f if block_given?
39
- f.adapter :net_http
188
+ f.adapter :net_http, &BOUND_CONNECTION
40
189
  end
41
190
  end
42
191
 
@@ -124,7 +124,9 @@ module KeycloakSdk
124
124
  raise TransportError, "JWKS response unparsable (JSON::ParserError)", cause: RedactedCause.new(e)
125
125
  end
126
126
  validate_key_set!(body)
127
- rescue Faraday::Error => e
127
+ rescue Error
128
+ raise
129
+ rescue StandardError => e # Faraday 밖 예외도 — net-http 0.10 의 응답 헤더 검증은 ArgumentError 다(어댑터 목록 밖)
128
130
  raise TransportError, "JWKS transport error: #{RedactedCause.describe(e)}", cause: RedactedCause.new(e)
129
131
  end
130
132
 
@@ -59,7 +59,9 @@ module KeycloakSdk
59
59
  end
60
60
 
61
61
  TokenSet.from_response(resp.body, received_at: Time.now.to_f)
62
- rescue Faraday::Error => e
62
+ rescue Error
63
+ raise
64
+ rescue StandardError => e # Faraday 밖 예외도 — net-http 0.10 의 응답 헤더 검증은 ArgumentError 다(어댑터 목록 밖)
63
65
  raise TransportError, "token endpoint transport error: #{RedactedCause.describe(e)}", cause: RedactedCause.new(e)
64
66
  end
65
67
  end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module KeycloakSdk
4
- VERSION = "1.3.0"
4
+ VERSION = "1.3.1"
5
5
  end
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.0
4
+ version: 1.3.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - xzawed