keycloak-sdk 1.3.0 → 1.3.2

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: 51b3c59bfdc3c281f3a6b71faaa6fba7e9561399bfa9e352cf275cbc42718617
4
+ data.tar.gz: 3260c90043c5d10f253266af8fc3786c7212906b1b460bfd05eb1e49cb0e38ed
5
5
  SHA512:
6
- metadata.gz: dcde89692c25c6ab41a45363018c7b47d8d629d45ce5660f74f80f1025394438314dee56e70b4e2e91d3fa63155589867ddbded27a91d79e744115ca0880a8de
7
- data.tar.gz: 4c37d217507bdee67f59b96b2e130cc057cab28a19c7ddf1686d517c0ea18c4dccd208bfb04cb2916673dff7216ffee9e029c49d309f20fe26a5575f5bef7114
6
+ metadata.gz: 04b4477363357a3fdfa3a2c324dfdbd8a992c28a8ce163f84ac65fa6f6a0bfbf591a9261786a7251f91de1d3398b5f8b279be7f696f56e709009e8f1e308274e
7
+ data.tar.gz: da685f6729d4aa0362a9d71397c23aab3205b63aae49da6199b64348d8764d4c6988dfe0be9095d912f0fbd1eab9ab9899bebff999327a06bf851c94de31eccf
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.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.2` is on RubyGems** — a patch release on top of `1.3.1`; `1.0.0` was the first release carrying the stability guarantee. A bare `gem install keycloak-sdk` resolves it. **Security**: an HTTPS call through a proxy (the SDK has no proxy option — Faraday reads `https_proxy`/`HTTPS_PROXY`) read the proxy's CONNECT reply outside the framing caps, because net-http reads that reply into its own buffer before the point the SDK hooks: net-http `0.9.1` read a 100,000-byte header line, 400 short header lines (82,039 bytes) or a 996,039-byte reply whole and went on to the TLS handshake with the origin, and `0.10.0` read the status line and header block up to its own 1 MiB limit. The socket that carries the CONNECT reply — the TCP socket for a plain proxy, the TLS socket with the proxy for a TLS proxy, never the TLS session with the origin — now gets the same two caps (8,192 bytes per line, 65,536 bytes per header block) and the same constant-message `KeycloakSdk::TransportError`; a well-formed reply passes as before. ⚠️ **`net-http >= 0.9` is now a runtime dependency** — the cap hooks `Net::HTTP#timeouted_connect`, which first appears in `0.9.0`. faraday-net_http already pulls net-http in, so most installs change nothing, but an application that pins net-http below `0.9` must raise it to install this release. **Fixed**: an admin error status (404, 409, 403 or any other non-2xx) whose body claims `Content-Type: application/json` but is not JSON — a proxy's HTML error page, say — raised `TransportError` (`admin transport error: Faraday::ParsingError`) instead of the status class; it now raises `NotFoundError`, `ConflictError`, `ForbiddenError` or `AdminError` with the usual `admin request failed: HTTP <status>` and quotes the body neither in the message nor in the cause chain (a 2xx that does not parse is still a `TransportError`). ⚠️ Code that rescued `KeycloakSdk::TransportError` for such responses now gets the status class. No public API change.
8
+ >
9
+ > `1.3.1` was a patch release on top of `1.3.0`. **Fixed — upgrade if you installed `1.3.0` recently**: with net-http `0.10` (what a fresh install resolves), a response header name that holds a control character or is longer than 1,024 bytes made `introspect`, `logout` and the admin client raise a raw `ArgumentError` that quoted the name; they now raise `KeycloakSdk::TransportError` (`introspection transport error: ArgumentError` and the like — the cause chain keeps only the class name), as the grants already raised `AuthError`. **Security**: the response *framing* — status line, header lines, chunk-size and extension lines, trailers — was outside the body caps, so a 16 MiB header line, chunk extension or trailer line, or 4,096 trailer lines of 4 KiB, were read whole (32–67 MB allocated per call). Every connection the SDK makes now reads at most 8,192 bytes per framing line and 65,536 bytes of framing per response, and beyond that drops the connection with a constant-message `KeycloakSdk::TransportError` that does not quote the response; default Keycloak responses are far below both. The bound works with net-http `0.9` and `0.10`, and it touches only the sockets the SDK opens. ⚠️ The framing budget also counts chunk-size lines, so a large body cut into chunks of a few dozen bytes is refused (Keycloak and mainstream reverse proxies chunk in KiB and pass). The admin client now refuses, before any request, an access token an HTTP header cannot carry — NUL, DEL and other control characters, or a leading or trailing space or tab — with `AuthError`; net-http used to strip or forward them. ⚠️ A consumer `TokenProvider` whose token ends in a space or tab now fails instead of being trimmed. No public API change.
8
10
 
9
11
  ## Requirements
10
12
 
@@ -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,11 +31,31 @@ 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 는 헤더 이름을 인용한다.
39
+ status = unparsable_error_status(e)
40
+ if status
41
+ raise AdminError.from_status(status, "admin request failed: HTTP #{status}"), cause: RedactedCause.new(e)
42
+ end
43
+
36
44
  raise TransportError, "admin transport error: #{RedactedCause.describe(e)}", cause: RedactedCause.new(e)
37
45
  end
38
46
 
47
+ # 커넥션의 json 미들웨어는 상태 검사보다 먼저 해석한다 — JSON 이라면서 JSON 이 아닌 **오류** 본문(404·409·403 …)이어도
48
+ # 상태가 클래스를 정한다(.NET 과 같다). 2xx 의 해석 실패는 전송 오류 그대로다(nil).
49
+ # ⚠️ `Faraday::Error#response_status` 를 쓰지 않는다 — faraday 2.0.0 은 응답 객체에 `[:status]` 를 묻고, 그것은
50
+ # `headers[:status]` 로 위임돼 nil 이다. 응답 객체면 `status`, 해시면 `[:status]` 를 읽는다.
51
+ def unparsable_error_status(err)
52
+ return unless err.is_a?(Faraday::ParsingError)
53
+
54
+ resp = err.response
55
+ status = resp.respond_to?(:status) ? resp.status : (resp[:status] if resp.is_a?(Hash))
56
+ status if status.is_a?(Integer) && !(200..299).cover?(status)
57
+ end
58
+
39
59
  def id_from_location(resp)
40
60
  loc = resp.headers["location"]
41
61
  loc&.split("/")&.last
@@ -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,229 @@ 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
+ # ⚠️ **프록시 CONNECT 응답의 틀 상한** — HTTPS 대상을 프록시로 부르면 net-http `connect` 는 프록시 소켓 위에 **지역**
150
+ # `BufferedIO` 를 따로 만들어 CONNECT 응답(`HTTPResponse.read_new`)을 읽는다. `on_connect` 보다 앞이라 `BoundedReads` 가
151
+ # 그 읽기를 못 봤다(ruby-framing-proxy-connect-unbounded — net-http 0.9.1 은 996,039 B 머리 블록도 받고 TLS 로
152
+ # 넘어갔고, 0.10.0 은 상태 줄·블록을 1 MiB 까지 받았다 · 65,536 B 넘는 헤더 값만 다 읽은 뒤 raw ArgumentError).
153
+ # 그 `BufferedIO` 는 잡을 자리가 없으니(전역 패치 금지) 그것이 읽는 **소켓 하나**에 건다 — `rbuf_fill` 이 부르는
154
+ # `read_nonblock` 이 돌려준 바이트를 세어 `BoundedReads` 와 같은 두 상한(줄은 종단 문자까지 8,192 · 블록은 빈 줄까지
155
+ # 65,536)을 넘으면 같은 상수 메시지의 `TransportError` 다(`connect` 의 rescue 가 그 소켓을 닫는다). 빈 줄(첫 줄 뒤의
156
+ # "\r\n"·"\n" — 두 읽기에 갈려도)에서 꺼진다: 그 뒤 바이트는 손대지 않고 돌려주고(net-http 가 버린다) 그 소켓의 뒤
157
+ # 읽기는 세지 않는다.
158
+ # ⚠️ 빈 줄은 "\r\n"·"\n" 둘뿐이다(0.10 의 `chomp` 와 같다) — 0.9.1 처럼 공백만 있는 줄까지 끝으로 보면 그 줄 하나로
159
+ # 상한을 끌 수 있다.
160
+ module ConnectFraming
161
+ # 시그니처는 상류(`IO`·`OpenSSL::Buffering`)와 같다 — `BufferedIO#rbuf_fill` 은 `read_nonblock(BUFSIZE, tmp,
162
+ # exception: false)` 로 부르고(`http_framing_pins_spec`), 받은 버퍼를 같은 객체로 돌려받기를 기대한다.
163
+ def read_nonblock(len, buf = nil, exception: true)
164
+ chunk = super
165
+ kcsdk_connect_scan(chunk) if @kcsdk_connect_armed && chunk.is_a?(String)
166
+ chunk
167
+ end
168
+
169
+ def kcsdk_arm_connect_framing!
170
+ @kcsdk_connect_armed = true
171
+ @kcsdk_connect_total = 0 # 끝난 줄들의 바이트(종단 문자 포함)
172
+ @kcsdk_connect_line = 0 # 지금 줄에 쌓인 바이트 — 아직 "\n" 전
173
+ @kcsdk_connect_last = nil # 그 쌓인 바이트의 마지막 — "\r" 하나로 읽기가 끝났으면 다음 읽기의 "\n" 과 빈 줄이다
174
+ end
175
+
176
+ def kcsdk_connect_framing_armed?
177
+ @kcsdk_connect_armed == true
178
+ end
179
+
180
+ private
181
+
182
+ # ⚠️ 바이트 위치로 읽는다(`byteindex`·`getbyte`) — 소켓이 돌려주는 BINARY 문자열에서 위치는 늘 바이트다.
183
+ def kcsdk_connect_scan(chunk)
184
+ from = 0
185
+ while @kcsdk_connect_armed && (eol = chunk.byteindex("\n", from))
186
+ kcsdk_connect_line_end(chunk, from, eol)
187
+ from = eol + 1
188
+ end
189
+ kcsdk_connect_partial(chunk, from) if @kcsdk_connect_armed && from < chunk.bytesize
190
+ end
191
+
192
+ # 빈 줄 = 첫 줄이 아닌 "\n"(1 바이트) 또는 "\r\n"(2 바이트) — 2 바이트 줄의 "\r" 은 "\n" 바로 앞 바이트다.
193
+ def kcsdk_connect_line_end(chunk, from, eol)
194
+ before = eol > from ? chunk.getbyte(eol - 1) : @kcsdk_connect_last
195
+ len = @kcsdk_connect_line + eol + 1 - from
196
+ kcsdk_connect_bound(len)
197
+ blank = @kcsdk_connect_total.positive? && (len == 1 || (len == 2 && before == 13))
198
+ @kcsdk_connect_total += len
199
+ @kcsdk_connect_line = 0
200
+ @kcsdk_connect_armed = false if blank
201
+ end
202
+
203
+ def kcsdk_connect_partial(chunk, from)
204
+ @kcsdk_connect_line += chunk.bytesize - from
205
+ @kcsdk_connect_last = chunk.getbyte(-1)
206
+ kcsdk_connect_bound(@kcsdk_connect_line)
207
+ end
208
+
209
+ # `BoundedReads#kcsdk_bound_line` 와 같은 경계다 — 줄이든 블록이든 상한과 **같으면** 받고 넘으면 거부한다.
210
+ def kcsdk_connect_bound(len)
211
+ raise KeycloakSdk::TransportError, FRAMING_LINE_MSG if len > MAX_FRAMING_LINE_BYTES
212
+ raise KeycloakSdk::TransportError, FRAMING_TOTAL_MSG if @kcsdk_connect_total + len > MAX_FRAMING_BYTES
213
+ end
214
+ end
215
+
216
+ # `Net::HTTP` 인스턴스의 싱글턴에 **prepend** 해 소켓이 만들어지는 자리(`on_connect`, `connect` 끝)에서 그 소켓에만
217
+ # `BoundedReads` 를 건다. `begin_transport` 는 요청마다 틀 예산을 0 으로 되돌린다 — keep-alive 로 연결을 재사용해도
218
+ # 다음 응답은 새 예산을 받는다(한 요청의 1xx 중간 응답들은 같은 예산을 나눠 쓴다 — 그래야 1xx 홍수도 묶인다).
219
+ # ⚠️ **`Net::HTTP` 를 하위 클래스로 두지 않는다.** 그 하위 클래스 인스턴스가 Faraday 스택에 남으면 공개 표면 가드의
220
+ # 객체 걷기(`facade_dump_spec`·`hostile_path_matrix_spec`)가 그 세 시험을 끝내지 못했다(실측: 90–150 초 timeout 에
221
+ # 죽었다 — 이 설계로 바꾼 뒤 같은 셋은 14 초). 원인은 가드 코드를 읽은 추정이다 — SDK 네임스페이스로 보고 그 상속 공개
222
+ # 메서드(Net::HTTP 수백 개)를 불러 실 네트워크에서 기다린다. 표준 어댑터 + 인스턴스 prepend 는 그래프에 SDK 이름의
223
+ # 어댑터·HTTP 타입을 남기지 않는다.
224
+ module BoundedTransport
225
+ private
226
+
227
+ def on_connect
228
+ super
229
+ @socket.extend(BoundedReads)
230
+ @socket.kcsdk_reset_framing!
231
+ end
232
+
233
+ def begin_transport(req)
234
+ super
235
+ @socket.kcsdk_reset_framing! if @socket.respond_to?(:kcsdk_reset_framing!)
236
+ end
237
+
238
+ # ── 프록시 CONNECT(`ConnectFraming`) — `connect` 가 소켓을 여는 두 자리. 상한은 CONNECT 응답을 나르는 소켓에만 걸고
239
+ # 대상과의 TLS 소켓은 건드리지 않는다. ⚠️ `timeouted_connect` 는 net-http 0.9.0 에 생겼다 — gemspec 하한이다.
240
+
241
+ # 연결마다 「이 `connect` 의 첫 `ssl_socket_connect`」를 되돌린다(keep-alive 가 끊긴 뒤 다시 열 때도 같다).
242
+ def connect
243
+ @kcsdk_connect_tls_pending = true
244
+ super
245
+ end
246
+
247
+ # 평문 프록시 + HTTPS 대상 — net-http 는 이 TCP 소켓을 그대로 BufferedIO 로 감싸 CONNECT 응답을 읽는다.
248
+ def timeouted_connect(conn_addr, conn_port)
249
+ sock = super
250
+ kcsdk_bound_connect(sock) if proxy? && use_ssl? && !@proxy_use_ssl
251
+ sock
252
+ end
253
+
254
+ # TLS 프록시 + HTTPS 대상 — 이 `connect` 의 **첫** 호출이 프록시와의 TLS 소켓(CONNECT 응답을 나른다)이고, 둘째는
255
+ # 대상과의 TLS 다. `@proxy_use_ssl` 은 `connect` 가 가르는 그 ivar 다(공개 읽기가 없다 — 모양은 핀으로 고정).
256
+ def ssl_socket_connect(sock, timeout)
257
+ first = @kcsdk_connect_tls_pending
258
+ @kcsdk_connect_tls_pending = false
259
+ result = super
260
+ kcsdk_bound_connect(sock) if first && proxy? && use_ssl? && @proxy_use_ssl
261
+ result
262
+ end
263
+
264
+ def kcsdk_bound_connect(sock)
265
+ sock.extend(ConnectFraming)
266
+ sock.kcsdk_arm_connect_framing!
267
+ end
268
+ end
269
+
270
+ # 표준 `:net_http` 어댑터의 설정 블록 — 커넥션을 짓기 직전 그 `Net::HTTP` 인스턴스의 싱글턴에 `BoundedTransport` 를
271
+ # prepend 한다. 프록시 인자·연결 조립은 어댑터가 그대로 하고(원판 `net_http_connection`), 프록시·keep-alive 경로는
272
+ # `http_framing_pins_spec` 이 고정한다.
273
+ BOUND_CONNECTION = lambda do |http|
274
+ http.singleton_class.prepend(BoundedTransport)
275
+ end
276
+ private_constant :BoundedReads, :ConnectFraming, :BoundedTransport, :BOUND_CONNECTION
277
+
31
278
  module_function
32
279
 
33
280
  def build(config, base_url: nil)
@@ -36,7 +283,7 @@ module KeycloakSdk
36
283
  request: { timeout: config.read_timeout, open_timeout: config.connect_timeout }
37
284
  ) do |f|
38
285
  yield f if block_given?
39
- f.adapter :net_http
286
+ f.adapter :net_http, &BOUND_CONNECTION
40
287
  end
41
288
  end
42
289
 
@@ -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.2"
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.2
5
5
  platform: ruby
6
6
  authors:
7
7
  - xzawed
@@ -37,6 +37,20 @@ dependencies:
37
37
  - - "~>"
38
38
  - !ruby/object:Gem::Version
39
39
  version: '3.2'
40
+ - !ruby/object:Gem::Dependency
41
+ name: net-http
42
+ requirement: !ruby/object:Gem::Requirement
43
+ requirements:
44
+ - - ">="
45
+ - !ruby/object:Gem::Version
46
+ version: '0.9'
47
+ type: :runtime
48
+ prerelease: false
49
+ version_requirements: !ruby/object:Gem::Requirement
50
+ requirements:
51
+ - - ">="
52
+ - !ruby/object:Gem::Version
53
+ version: '0.9'
40
54
  - !ruby/object:Gem::Dependency
41
55
  name: rack-oauth2
42
56
  requirement: !ruby/object:Gem::Requirement