Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 21 additions & 3 deletions sdk/ruby/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)) |
Expand All @@ -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.<group>.<method>(**fields)` posts `/v1/<group>.<rest>`: the group is the op name's
Expand Down Expand Up @@ -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`.
Expand Down
73 changes: 66 additions & 7 deletions sdk/ruby/lib/clickhouse/loom/client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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))
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),
"agent" => first_non_blank(agent, config.agent) }.compact.freeze
Expand Down Expand Up @@ -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?
Expand All @@ -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
Expand All @@ -202,6 +210,57 @@ 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. 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)
Comment thread
zlareb1 marked this conversation as resolved.
Resolved
Credentials.check_origin!(@token_provider, @base_url)
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)
Expand Down
4 changes: 4 additions & 0 deletions sdk/ruby/lib/clickhouse/loom/configuration.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
72 changes: 72 additions & 0 deletions sdk/ruby/lib/clickhouse/loom/credentials.rb
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading