From 7b2c351076d4bf717ef1873143e25c8d455198d1 Mon Sep 17 00:00:00 2001 From: rahulsjha <132360698+rahulsjha@users.noreply.github.com> Date: Sat, 28 Nov 2026 15:06:08 +0530 Subject: [PATCH 1/3] Ruby SDK: a token provider resent once on a 401, and ~/.loom/token --- sdk/ruby/README.md | 24 ++- sdk/ruby/lib/clickhouse/loom/client.rb | 68 +++++- sdk/ruby/lib/clickhouse/loom/configuration.rb | 4 + sdk/ruby/lib/clickhouse/loom/credentials.rb | 72 +++++++ sdk/ruby/test/credentials_test.rb | 201 ++++++++++++++++++ sdk/ruby/test/test_helper.rb | 101 +++++---- 6 files changed, 414 insertions(+), 56 deletions(-) create mode 100644 sdk/ruby/lib/clickhouse/loom/credentials.rb create mode 100644 sdk/ruby/test/credentials_test.rb diff --git a/sdk/ruby/README.md b/sdk/ruby/README.md index 39c4d941044..0670a06dfbe 100644 --- a/sdk/ruby/README.md +++ b/sdk/ruby/README.md @@ -51,7 +51,8 @@ client = Loom::Client.new(namespace: "user-42") # an argument wins over the conf | Setting | Default | | ------------------------------ | ---------------------------------------------------------------------------- | | `base_url` | `LOOM_BASE_URL`, else `http://localhost:7777` | -| `api_key` | `LOOM_API_KEY`; with neither, no `Authorization` header | +| `api_key` | `LOOM_API_KEY`, else `~/.loom/token`; with none, no `Authorization` header | +| `token_provider` | None; see [Tokens](#tokens) | | `org`, `namespace`, `agent` | Left out of the body when blank, so the server's defaults apply | | `open_timeout`, `read_timeout` | 10 and 60 seconds | | `retry_policy` | `{ max_attempts: 3, backoff: 0.25, ... }` (see [Retries](#retries)) | @@ -60,6 +61,24 @@ client = Loom::Client.new(namespace: "user-42") # an argument wins over the conf An argument to `Client.new` wins over `Loom.configure`, which wins over the environment. +### Tokens + +Instead of a fixed `api_key`, a `token_provider` hands over the token for each request: +any object with `token(refused)`, or a Proc. After a `401` the client asks it once more, +passing the token the server refused, and sends the call again with the new one. A +provider with nothing fresher returns the refused token, and the `401` is raised. An +empty token sends no `Authorization` header, and a provider that responds to `origin` +is only used with a client for that origin. + +```ruby +client = Loom::Client.new(token_provider: ->(refused) { MyVault.loom_token(renew: !refused.nil?) }) +``` + +The credential, first found wins: `token_provider:`, `api_key:`, the configured +`token_provider`, the configured `api_key`, `LOOM_API_KEY`, then the first line of +`~/.loom/token` (what `loom mint-token --save` writes). Passing both `api_key:` and +`token_provider:` raises `ArgumentError`. A stored `loom login` session is not read yet. + ## Calls `client..(**fields)` posts `/v1/.`: the group is the op name's @@ -144,8 +163,7 @@ The retry and idempotency rules of the TypeScript and Python SDKs: | `total_backoff_budget` | unbounded seconds of sleep per call | Not carried over yet: pacing on the `X-RateLimit-*` headers before a `429` arrives, a -per-call timeout, and resending a `401` with a fresh token (the gem takes a fixed -`api_key`). +per-call timeout, and a stored `loom login` session (`~/.loom/credentials`). The client does not follow redirects, so a memory body and token never go to another origin: a `3xx` answer raises a `Loom::Error`. diff --git a/sdk/ruby/lib/clickhouse/loom/client.rb b/sdk/ruby/lib/clickhouse/loom/client.rb index 155fcb4c908..1f1611e0130 100644 --- a/sdk/ruby/lib/clickhouse/loom/client.rb +++ b/sdk/ruby/lib/clickhouse/loom/client.rb @@ -9,6 +9,7 @@ require_relative "errors" require_relative "version" require_relative "configuration" +require_relative "credentials" require_relative "logging" require_relative "retry_policy" require_relative "operations" @@ -69,20 +70,25 @@ class Client # Each argument left nil takes ClickHouse::Loom.configure's value, then the environment # (LOOM_BASE_URL, LOOM_API_KEY), then the default: http://localhost:7777 and no - # Authorization header, which a server with auth off accepts. +retry_policy+ is a + # Authorization header, which a server with auth off accepts. + # + # The credential, first found wins: +token_provider+, +api_key+, the configured + # token_provider, the configured api_key, LOOM_API_KEY, then the first line of + # ~/.loom/token (see Credentials). Passing both +api_key+ and +token_provider+ raises + # ArgumentError. A provider is asked for a token on every request, and once more + # after a 401. +retry_policy+ is a # Hash of RetryPolicy fields set over the configured policy ({ max_attempts: 1 } # disables retries); +rate_limit_max_wait+ is the seconds one call may spend waiting # out 429 answers (default 15, 0 raises the first). +logger+ and +log_level+ turn on # logging (see Logging; off unless a logger is given). +sleeper+ is called with the # seconds to wait between attempts (a test seam; default Kernel#sleep). - def initialize(base_url: nil, api_key: nil, org: nil, namespace: nil, agent: nil, open_timeout: nil, - read_timeout: nil, retry_policy: nil, rate_limit_max_wait: nil, logger: nil, log_level: nil, - sleeper: nil) + def initialize(base_url: nil, api_key: nil, token_provider: nil, org: nil, namespace: nil, agent: nil, + open_timeout: nil, read_timeout: nil, retry_policy: nil, rate_limit_max_wait: nil, logger: nil, + log_level: nil, sleeper: nil) config = Loom.configuration @base_url = first_non_blank(base_url, config.base_url, ENV.fetch("LOOM_BASE_URL", nil), DEFAULT_BASE_URL).sub(%r{/+\z}, "") - # An exported but empty LOOM_API_KEY must not send "Bearer " and turn a clear 401 into a puzzle. - @api_key = first_non_blank(api_key, config.api_key, ENV.fetch("LOOM_API_KEY", nil)) + resolve_credential(config, api_key, token_provider) @identity = { "org" => first_non_blank(org, config.org), "namespace" => first_non_blank(namespace, config.namespace), "agent" => first_non_blank(agent, config.agent) }.compact.freeze @@ -184,6 +190,7 @@ def send_with_retries(op, spec, body, headers, policy) request_id: headers["X-Request-Id"] } loop do headers["X-Loom-Retry-Count"] = state[:sent].to_s + provider_bearer(headers, state) if @token_provider state[:sent] += 1 response = attempt(op, spec, body, headers, policy, state) next if response.nil? @@ -193,6 +200,7 @@ def send_with_retries(op, spec, body, headers, policy) request_id = response["X-Request-Id"] || headers["X-Request-Id"] error = Error.from_response(op, response.code.to_i, response.body, request_id, response["Retry-After"], idempotent: spec&.idempotent == true) + next if reauthenticate?(response, error, state) next if resend_after_answer?(response, error, spec, policy, state) raise error @@ -202,6 +210,54 @@ def send_with_retries(op, spec, body, headers, policy) raise end + # The credential, first found wins: the token_provider: argument, the api_key: + # argument, the configured token_provider, the configured api_key, LOOM_API_KEY, then + # ~/.loom/token. Blank keys count as unset. + def resolve_credential(config, api_key, token_provider) + if token_provider && !api_key.to_s.strip.empty? + raise ArgumentError, "Client: pass api_key or token_provider, not both" + end + + @token_provider = token_provider + # An exported but empty LOOM_API_KEY must not send "Bearer " and turn a clear 401 into a puzzle. + @api_key = first_non_blank(api_key) unless @token_provider + @token_provider ||= config.token_provider unless @api_key + unless @api_key || @token_provider + @api_key = first_non_blank(config.api_key, ENV.fetch("LOOM_API_KEY", nil)) || Credentials.token_from_file + end + Credentials.check_origin!(@token_provider, @base_url) if @token_provider + end + + # Sets the Authorization header from the provider before an attempt: a fresh token + # after a 401, and none when the provider has nothing to send. A provider with no + # fresh token (it returns the refused one) leaves the 401 standing. + def provider_bearer(headers, state) + refused = state.delete(:refused) + bearer = Credentials.provider_token(@token_provider, refused) + raise state[:refusal] if refused && bearer == refused + + state[:bearer] = bearer + if bearer.empty? + headers.delete("Authorization") + else + headers["Authorization"] = "Bearer #{bearer}" + end + end + + # A 401 to a provider's token is sent once more with a fresh one: the token may have + # expired, been revoked or rotated. The server refused before running the op, so this + # is no policy retry and spends no attempt. + def reauthenticate?(response, error, state) + return false unless @token_provider && response.code.to_i == 401 + return false if state[:bearer].to_s.empty? || state[:reauthed] + + state[:reauthed] = true + state[:refused] = state[:bearer] + state[:refusal] = error + @log.info("#{state[:op]} 401; retrying once with a fresh token (rid=#{state[:request_id]})") + true + end + # The decoded answer of a 2xx, and its summary line. def succeeded(op, response, state) out = decode(op, response) diff --git a/sdk/ruby/lib/clickhouse/loom/configuration.rb b/sdk/ruby/lib/clickhouse/loom/configuration.rb index 9e37245caa4..085717b8039 100644 --- a/sdk/ruby/lib/clickhouse/loom/configuration.rb +++ b/sdk/ruby/lib/clickhouse/loom/configuration.rb @@ -8,6 +8,10 @@ module Loom class Configuration # The server and the token; nil falls back to LOOM_BASE_URL / LOOM_API_KEY. attr_accessor :base_url, :api_key + # An object with token(refused), or a Proc, that hands over the token for each + # request instead of a static api_key (see Credentials). A client given an api_key + # argument does not use it. + attr_accessor :token_provider # The identity every call is sent as; a call can override each one. attr_accessor :org, :namespace, :agent # Seconds to wait for the connection and for each answer. diff --git a/sdk/ruby/lib/clickhouse/loom/credentials.rb b/sdk/ruby/lib/clickhouse/loom/credentials.rb new file mode 100644 index 00000000000..dc7f7eeaa0d --- /dev/null +++ b/sdk/ruby/lib/clickhouse/loom/credentials.rb @@ -0,0 +1,72 @@ +# frozen_string_literal: true + +require "uri" + +module ClickHouse + module Loom + # Where a Client's bearer token comes from, beyond a static API key. + # + # A +token_provider+ is any object with +token(refused)+ (or a Proc taking +refused+) + # that returns the token to send, as a String. The client asks it before every + # request. After a 401 it asks once more, passing the token the server refused in + # +refused+, and sends the call again with the answer; a provider that has no fresh + # token returns the refused one, and the 401 is raised. An empty token sends no + # Authorization header. A provider that responds to +origin+ ("https://loom.example") + # is only ever used with a client for that origin. This is the TypeScript SDK's + # TokenProvider: a bot's machine login or a stored `loom login` session plugs in here. + # + # The last credential a client looks for is the first line of ~/.loom/token, which + # `loom mint-token --save` writes, as the TypeScript and Python SDKs read it. + module Credentials + # The file `loom mint-token --save` writes, under the user's home directory. + TOKEN_FILE = File.join("~", ".loom", "token") + + module_function + + # The first line of ~/.loom/token (or +path+), stripped; nil when the file is + # missing, unreadable or blank, or no home directory is known. + def token_from_file(path = nil) + text = File.read(File.expand_path(path || TOKEN_FILE), encoding: "UTF-8") + line = text.strip.lines.first.to_s.strip + line.empty? ? nil : line + rescue SystemCallError, IOError, ArgumentError, EncodingError + nil + end + + # The provider's token, with +refused+ the token the server just answered 401 to + # (nil on a first try). + def provider_token(provider, refused) + token = + if provider.respond_to?(:token) + provider.token(refused) + elsif provider.respond_to?(:call) + provider.arity.zero? ? provider.call : provider.call(refused) + else + raise ArgumentError, "token_provider must respond to token(refused) or call(refused)" + end + token.to_s.strip + end + + # (scheme, host, port) of +url+, as a browser compares origins. + def origin_of(url) + uri = URI(url.to_s) + [uri.scheme.to_s.downcase, uri.host.to_s.downcase, uri.port] + rescue URI::InvalidURIError + nil + end + + # Raises ArgumentError when +provider+ is bound to another origin than +base_url+: + # its token is never sent to a server it was not made for. + def check_origin!(provider, base_url) + return unless provider.respond_to?(:origin) && provider.origin + + bound = origin_of(provider.origin) + return if bound && bound == origin_of(base_url) + + label = provider.respond_to?(:label) && provider.label ? provider.label : "the token provider" + raise ArgumentError, "refusing to send #{label}'s token to #{URI(base_url).host}: it is bound to " \ + "#{provider.origin}" + end + end + end +end diff --git a/sdk/ruby/test/credentials_test.rb b/sdk/ruby/test/credentials_test.rb new file mode 100644 index 00000000000..1f6987c6685 --- /dev/null +++ b/sdk/ruby/test/credentials_test.rb @@ -0,0 +1,201 @@ +# frozen_string_literal: true + +require_relative "test_helper" +require "fileutils" +require "logger" +require "stringio" + +# Where the bearer token comes from: a token provider (asked on every request, and once +# more after a 401) and ~/.loom/token, as in the TypeScript and Python SDKs. +class CredentialsTest < LoomTest + UNAUTHORIZED = { detail: { code: "AUTH_INVALID", message: "token expired" } }.freeze + + # A provider that hands out tokens in turn and records what it was asked. + class Rotating + attr_reader :asked + + def initialize(*tokens) + @tokens = tokens + @asked = [] + end + + def token(refused) + @asked << refused + @tokens.length > 1 ? @tokens.shift : @tokens.first + end + end + + def auth(request) + request.headers["authorization"] + end + + def write_token_file(text) + dir = File.join(Dir.home, ".loom") + FileUtils.mkdir_p(dir) + File.write(File.join(dir, "token"), text) + end + + def test_the_token_file_is_the_last_credential + write_token_file("file-token +second line +") + respond_json(200, { found: false }) + client.get("k") + assert_equal "Bearer file-token", auth(sent) + end + + def test_a_blank_or_missing_token_file_sends_no_authorization + respond_json(200, { found: false }) + client.get("k") + assert_nil auth(sent) + + write_token_file(" \n") + respond_json(200, { found: false }) + client.get("k") + assert_nil auth(sent) + end + + def test_loom_api_key_wins_over_the_token_file + write_token_file("file-token\n") + ENV["LOOM_API_KEY"] = "env-token" + respond_json(200, { found: false }) + client.get("k") + assert_equal "Bearer env-token", auth(sent) + end + + def test_a_provider_token_goes_on_every_request + provider = Rotating.new("t1", "t2") + respond_json(200, { found: false }) + respond_json(200, { found: false }) + c = client(token_provider: provider) + c.get("a") + assert_equal "Bearer t1", auth(sent) + c.get("b") + assert_equal "Bearer t2", auth(sent) + assert_equal [nil, nil], provider.asked + end + + def test_a_provider_wins_over_loom_api_key_and_the_token_file + write_token_file("file-token\n") + ENV["LOOM_API_KEY"] = "env-token" + respond_json(200, { found: false }) + client(token_provider: Rotating.new("provided")).get("k") + assert_equal "Bearer provided", auth(sent) + end + + def test_a_401_is_sent_once_more_with_a_fresh_token + provider = Rotating.new("stale", "fresh") + respond_json(401, UNAUTHORIZED) + respond_json(200, { found: true, value: "v" }) + out = client(token_provider: provider).get("k") + + assert_equal "v", out.value + assert_equal ["Bearer stale", "Bearer fresh"], @server.requests.map { |r| auth(r) } + assert_equal [nil, "stale"], provider.asked + # The same call: one request id, and the resend counted. + assert_equal 1, @server.requests.map { |r| r.headers["x-request-id"] }.uniq.length + assert_equal %w[0 1], @server.requests.map { |r| r.headers["x-loom-retry-count"] } + end + + def test_a_provider_with_no_fresh_token_leaves_the_401_standing + provider = Rotating.new("only") + respond_json(401, UNAUTHORIZED) + error = assert_raises(Loom::AuthInvalid) { client(token_provider: provider).get("k") } + + assert_equal 401, error.status + assert_equal 1, @server.requests.length + assert_equal [nil, "only"], provider.asked + end + + def test_a_second_401_is_raised + respond_json(401, UNAUTHORIZED) + respond_json(401, UNAUTHORIZED) + respond_json(200, { found: false }) + assert_raises(Loom::AuthInvalid) { client(token_provider: Rotating.new("a", "b", "c")).get("k") } + assert_equal 2, @server.requests.length + end + + def test_the_401_resend_spends_no_retry_attempt + respond_json(401, UNAUTHORIZED) + respond_json(503, { detail: { code: "BACKEND_UNAVAILABLE", message: "busy" } }) + respond_json(200, { found: false }) + c = client(token_provider: Rotating.new("a", "b"), retry_policy: { max_attempts: 2, backoff: 0.0, backoff_jitter: 0.0 }, + sleeper: ->(_) {}) + c.get("k") + assert_equal 3, @server.requests.length + end + + def test_a_401_with_a_static_key_is_not_resent + respond_json(401, UNAUTHORIZED) + respond_json(200, { found: false }) + assert_raises(Loom::AuthInvalid) { client(api_key: "static").get("k") } + assert_equal 1, @server.requests.length + end + + def test_an_empty_provider_token_sends_no_authorization + respond_json(200, { found: false }) + client(token_provider: ->(_refused) { "" }).get("k") + assert_nil auth(sent) + end + + def test_a_proc_provider_is_called_with_the_refused_token + asked = [] + provider = lambda do |refused| + asked << refused + refused ? "fresh" : "stale" + end + respond_json(401, UNAUTHORIZED) + respond_json(200, { found: false }) + client(token_provider: provider).get("k") + assert_equal [nil, "stale"], asked + assert_equal "Bearer fresh", auth(sent) + end + + def test_a_zero_argument_proc_works + respond_json(200, { found: false }) + client(token_provider: -> { "plain" }).get("k") + assert_equal "Bearer plain", auth(sent) + end + + def test_api_key_and_token_provider_together_are_refused + error = assert_raises(ArgumentError) { client(api_key: "k", token_provider: Rotating.new("t")) } + assert_match(/not both/, error.message) + end + + def test_a_provider_bound_to_another_origin_is_refused + provider = Struct.new(:origin, :label) { def token(_) = "t" }.new("https://loom.example", "login:default") + error = assert_raises(ArgumentError) { client(token_provider: provider) } + assert_match(/refusing to send login:default's token to 127\.0\.0\.1/, error.message) + assert_empty @server.requests + end + + def test_a_provider_bound_to_this_origin_is_used + provider = Struct.new(:origin) { def token(_) = "t" }.new(@server.base_url) + respond_json(200, { found: false }) + client(token_provider: provider).get("k") + assert_equal "Bearer t", auth(sent) + end + + def test_the_configured_provider_is_used_unless_an_api_key_is_passed + Loom.configure { |c| c.token_provider = Rotating.new("configured") } + respond_json(200, { found: false }) + respond_json(200, { found: false }) + client.get("a") + assert_equal "Bearer configured", auth(sent) + client(api_key: "argument").get("b") + assert_equal "Bearer argument", auth(sent) + end + + def test_the_token_is_not_logged_or_inspected + log = StringIO.new + respond_json(401, UNAUTHORIZED) + respond_json(200, { found: false }) + c = client(token_provider: Rotating.new("secret-stale-token", "secret-fresh-token"), + logger: Logger.new(log), log_level: :debug) + c.get("k") + refute_includes log.string, "secret-stale-token" + refute_includes log.string, "secret-fresh-token" + assert_includes log.string, "401; retrying once with a fresh token" + refute_includes c.inspect, "secret" + end +end diff --git a/sdk/ruby/test/test_helper.rb b/sdk/ruby/test/test_helper.rb index 7df066bb322..4e90a705d51 100644 --- a/sdk/ruby/test/test_helper.rb +++ b/sdk/ruby/test/test_helper.rb @@ -1,47 +1,54 @@ -# frozen_string_literal: true - -require "json" -require "minitest/autorun" - -require "clickhouse/loom" -require_relative "fake_server" - -class LoomTest < Minitest::Test - Loom = ClickHouse::Loom - - def setup - @server = FakeServer.new - @saved_env = ENV.to_h.slice("LOOM_BASE_URL", "LOOM_API_KEY") - ENV.delete("LOOM_BASE_URL") - ENV.delete("LOOM_API_KEY") - Loom.reset_configuration! - end - - def teardown - @server.close - ENV.delete("LOOM_BASE_URL") - ENV.delete("LOOM_API_KEY") - @saved_env.each { |name, value| ENV[name] = value } - Loom.reset_configuration! - end - - # One attempt and no wait on a 429, so a test reads the first answer as it came; the - # retry tests pass their own policy. - def client(**options) - defaults = { base_url: @server.base_url, org: "dev", namespace: "local", agent: "assistant", - retry_policy: { max_attempts: 1 }, rate_limit_max_wait: 0 } - Loom::Client.new(**defaults, **options) - end - - def respond_json(status, body, headers = {}) - @server.respond(status, JSON.generate(body), headers) - end - - def sent - @server.requests.last - end - - def sent_body - JSON.parse(sent.body) - end -end +# frozen_string_literal: true + +require "json" +require "minitest/autorun" +require "fileutils" +require "tmpdir" + +require "clickhouse/loom" +require_relative "fake_server" + +class LoomTest < Minitest::Test + Loom = ClickHouse::Loom + + def setup + @server = FakeServer.new + @saved_env = ENV.to_h.slice("LOOM_BASE_URL", "LOOM_API_KEY", "HOME") + # A home of its own, so a developer's ~/.loom/token never reaches a test. + @home = Dir.mktmpdir("loom-home") + ENV["HOME"] = @home + ENV.delete("LOOM_BASE_URL") + ENV.delete("LOOM_API_KEY") + Loom.reset_configuration! + end + + def teardown + @server.close + ENV.delete("LOOM_BASE_URL") + ENV.delete("LOOM_API_KEY") + ENV.delete("HOME") + @saved_env.each { |name, value| ENV[name] = value } + FileUtils.rm_rf(@home) + Loom.reset_configuration! + end + + # One attempt and no wait on a 429, so a test reads the first answer as it came; the + # retry tests pass their own policy. + def client(**options) + defaults = { base_url: @server.base_url, org: "dev", namespace: "local", agent: "assistant", + retry_policy: { max_attempts: 1 }, rate_limit_max_wait: 0 } + Loom::Client.new(**defaults, **options) + end + + def respond_json(status, body, headers = {}) + @server.respond(status, JSON.generate(body), headers) + end + + def sent + @server.requests.last + end + + def sent_body + JSON.parse(sent.body) + end +end From 9e09fa4686deb56c77de8797f50fc0cee4456605 Mon Sep 17 00:00:00 2001 From: rahulsjha <132360698+rahulsjha@users.noreply.github.com> Date: Sat, 28 Nov 2026 15:31:15 +0530 Subject: [PATCH 2/3] Ruby SDK: freeze the base URL the token provider's origin was checked against --- sdk/ruby/lib/clickhouse/loom/client.rb | 2 +- sdk/ruby/test/credentials_test.rb | 7 +++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/sdk/ruby/lib/clickhouse/loom/client.rb b/sdk/ruby/lib/clickhouse/loom/client.rb index 1f1611e0130..e5ad2bd5f97 100644 --- a/sdk/ruby/lib/clickhouse/loom/client.rb +++ b/sdk/ruby/lib/clickhouse/loom/client.rb @@ -87,7 +87,7 @@ def initialize(base_url: nil, api_key: nil, token_provider: nil, org: nil, names log_level: nil, sleeper: nil) config = Loom.configuration @base_url = first_non_blank(base_url, config.base_url, ENV.fetch("LOOM_BASE_URL", nil), - DEFAULT_BASE_URL).sub(%r{/+\z}, "") + DEFAULT_BASE_URL).sub(%r{/+\z}, "").freeze resolve_credential(config, api_key, token_provider) @identity = { "org" => first_non_blank(org, config.org), "namespace" => first_non_blank(namespace, config.namespace), diff --git a/sdk/ruby/test/credentials_test.rb b/sdk/ruby/test/credentials_test.rb index 1f6987c6685..ac7325f1777 100644 --- a/sdk/ruby/test/credentials_test.rb +++ b/sdk/ruby/test/credentials_test.rb @@ -169,6 +169,13 @@ def test_a_provider_bound_to_another_origin_is_refused assert_empty @server.requests end + def test_the_checked_base_url_cannot_be_changed_afterwards + provider = Struct.new(:origin) { def token(_) = "t" }.new(@server.base_url) + c = client(token_provider: provider) + assert_raises(FrozenError) { c.base_url.replace("https://other.example") } + assert_equal @server.base_url, c.base_url + end + def test_a_provider_bound_to_this_origin_is_used provider = Struct.new(:origin) { def token(_) = "t" }.new(@server.base_url) respond_json(200, { found: false }) From 021556d7c719c8ac1a864833c74a8455715b5dc3 Mon Sep 17 00:00:00 2001 From: rahulsjha <132360698+rahulsjha@users.noreply.github.com> Date: Sun, 29 Nov 2026 06:24:58 +0530 Subject: [PATCH 3/3] Ruby SDK: check the token provider's origin before each token is sent The origin was checked only when the client was built. A provider whose origin changes later, including while it refreshes after a 401, is now refused at dispatch before its token goes out. --- sdk/ruby/lib/clickhouse/loom/client.rb | 5 +++- sdk/ruby/test/credentials_test.rb | 36 ++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/sdk/ruby/lib/clickhouse/loom/client.rb b/sdk/ruby/lib/clickhouse/loom/client.rb index e5ad2bd5f97..cc9434be7f0 100644 --- a/sdk/ruby/lib/clickhouse/loom/client.rb +++ b/sdk/ruby/lib/clickhouse/loom/client.rb @@ -230,10 +230,13 @@ def resolve_credential(config, api_key, token_provider) # Sets the Authorization header from the provider before an attempt: a fresh token # after a 401, and none when the provider has nothing to send. A provider with no - # fresh token (it returns the refused one) leaves the 401 standing. + # fresh token (it returns the refused one) leaves the 401 standing. The provider's + # origin is checked again after each token it hands out, so a provider that moved to + # another server since construction never has its token sent here. def provider_bearer(headers, state) refused = state.delete(:refused) bearer = Credentials.provider_token(@token_provider, refused) + Credentials.check_origin!(@token_provider, @base_url) raise state[:refusal] if refused && bearer == refused state[:bearer] = bearer diff --git a/sdk/ruby/test/credentials_test.rb b/sdk/ruby/test/credentials_test.rb index ac7325f1777..47c85b7035a 100644 --- a/sdk/ruby/test/credentials_test.rb +++ b/sdk/ruby/test/credentials_test.rb @@ -176,6 +176,42 @@ def test_the_checked_base_url_cannot_be_changed_afterwards assert_equal @server.base_url, c.base_url end + # A provider whose origin can change after the client is built. + class Moving + attr_accessor :origin + + def initialize(origin, move_on_refresh_to: nil) + @origin = origin + @move_on_refresh_to = move_on_refresh_to + end + + def token(refused) + return "first" unless refused + + @origin = @move_on_refresh_to if @move_on_refresh_to + "fresh" + end + end + + def test_a_provider_that_moves_after_construction_is_refused_at_dispatch + provider = Moving.new(@server.base_url) + c = client(token_provider: provider) + provider.origin = "https://other.example" + respond_json(200, { found: false }) + error = assert_raises(ArgumentError) { c.get("k") } + assert_match(/refusing to send the token provider's token to 127\.0\.0\.1/, error.message) + assert_empty @server.requests + end + + def test_a_provider_that_moves_while_refreshing_after_a_401_is_refused + provider = Moving.new(@server.base_url, move_on_refresh_to: "https://other.example") + respond_json(401, UNAUTHORIZED) + respond_json(200, { found: false }) + assert_raises(ArgumentError) { client(token_provider: provider).get("k") } + assert_equal 1, @server.requests.length + assert_equal "Bearer first", auth(sent) + end + def test_a_provider_bound_to_this_origin_is_used provider = Struct.new(:origin) { def token(_) = "t" }.new(@server.base_url) respond_json(200, { found: false })