Skip to content
Open
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
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,22 @@ end
client = WorkOS.client
```

### Proxy

By default the SDK uses the proxy from the `http_proxy` environment variable, which applies to every `Net::HTTP` client in the process. To route only WorkOS requests through a proxy, or only some clients, pass `proxy`:

```ruby
WorkOS.configure do |config|
config.api_key = ENV.fetch("WORKOS_API_KEY")
config.proxy = "http://user:pass@proxy.example.com:8080"
end

# Or per client
proxied = WorkOS::Client.new(api_key: "sk_...", proxy: "http://proxy.example.com:8080")
```

Only `http://` proxy URLs are supported; requests to the WorkOS API stay encrypted end to end through the proxy. When `proxy` is set it is always used, so `no_proxy` does not apply to it. When it is not set, the environment variables behave as before.

## Client patterns

### Singleton (recommended for most apps)
Expand Down
64 changes: 60 additions & 4 deletions lib/workos/base_client.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# frozen_string_literal: true

# @oagen-ignore-file — hand-maintained runtime
require "digest"
require "json"
require "logger"
require "net/http"
Expand All @@ -23,6 +24,12 @@ module WorkOS
# log_level: :info
# )
#
# @example Route this client's requests through an HTTP proxy
# client = WorkOS::Client.new(
# api_key: "sk_...",
# proxy: "http://user:pass@proxy.example.com:8080"
# )
#
# @example Shut down connections before forking
# client.shutdown
class BaseClient
Expand All @@ -41,14 +48,21 @@ class BaseClient
"v#{WorkOS::VERSION}"
].join("; ").freeze

attr_reader :api_key, :base_url, :client_id, :timeout, :max_retries, :logger, :log_level, :jwt_issuer
attr_reader :api_key, :base_url, :client_id, :timeout, :max_retries, :logger, :log_level, :jwt_issuer, :proxy

# @param proxy [String, URI::HTTP, nil] URL of an HTTP proxy to send this
# client's requests through, e.g. `"http://user:pass@proxy.example.com:8080"`.
# Only `http://` proxy URLs are supported; HTTPS API traffic is tunneled
# through the proxy with CONNECT. An explicit proxy is always used, so
# the `no_proxy` environment variable does not apply to it. When nil
# (the default), Net::HTTP keeps reading the proxy from the
# `http_proxy` / `no_proxy` environment variables.
# @param jwt_issuer [String, Array<String>, nil] Expected `iss` claim of
# session access tokens (one issuer or a list of accepted issuers).
# When nil, the issuer is not validated.
def initialize(api_key: nil, base_url: DEFAULT_BASE_URL, client_id: nil,
timeout: DEFAULT_TIMEOUT, max_retries: DEFAULT_MAX_RETRIES,
logger: nil, log_level: nil, jwt_issuer: nil, random: Random.new)
logger: nil, log_level: nil, jwt_issuer: nil, random: Random.new, proxy: nil)
@api_key = api_key
@base_url = base_url
@client_id = client_id
Expand All @@ -58,6 +72,9 @@ def initialize(api_key: nil, base_url: DEFAULT_BASE_URL, client_id: nil,
@log_level = log_level
@jwt_issuer = jwt_issuer
@random = random
@proxy = proxy
@proxy_uri = parse_proxy(proxy)
@proxy_cache_key = @proxy_uri && Digest::SHA256.hexdigest(@proxy_uri.to_s)
end

# -- Request builders -------------------------------------------------
Expand Down Expand Up @@ -285,7 +302,7 @@ def connection_for(base_url, timeout)
return conn
end

http = Net::HTTP.new(uri.host, uri.port)
http = build_http(uri)
http.use_ssl = (uri.scheme == "https")
http.read_timeout = timeout
http.open_timeout = timeout
Expand All @@ -297,6 +314,42 @@ def connection_for(base_url, timeout)
http
end

# Only pass proxy arguments when a proxy was configured. Passing an
# explicit nil proxy address would turn off Net::HTTP's default lookup
# of the `http_proxy` environment variable.
def build_http(uri)
return Net::HTTP.new(uri.host, uri.port) unless @proxy_uri

Net::HTTP.new(
uri.host,
uri.port,
@proxy_uri.hostname,
@proxy_uri.port,
decode_proxy_credential(@proxy_uri.user),
decode_proxy_credential(@proxy_uri.password)
)
end

# Error messages never echo the proxy URL because it can hold credentials.
def parse_proxy(proxy)
return nil if proxy.nil?

uri = begin
URI(proxy.to_s)
rescue URI::InvalidURIError
nil
end
unless uri.is_a?(URI::HTTP) && uri.scheme == "http" && uri.hostname && !uri.hostname.empty?
raise ArgumentError, "proxy must be an http:// URL such as \"http://proxy.example.com:8080\""
end

uri
end

def decode_proxy_credential(value)
value && URI.decode_uri_component(value)
end

def evict_connection(base_url)
uri = URI(base_url)
keys = thread_connections.keys.select { |key| key.start_with?("#{uri.scheme}:#{uri.host}:#{uri.port}:") }
Expand All @@ -319,7 +372,10 @@ def evict_lru_connections(cache)
end

def connection_key(uri, timeout)
"#{uri.scheme}:#{uri.host}:#{uri.port}:#{timeout}"
key = "#{uri.scheme}:#{uri.host}:#{uri.port}:#{timeout}"
# Clients with different proxies must never share a pooled connection.
# The proxy is hashed so its credentials are not stored in the key.
@proxy_cache_key ? "#{key}:proxy=#{@proxy_cache_key}" : key
end

# Per-fiber connection cache (non-inherited).
Expand Down
5 changes: 3 additions & 2 deletions lib/workos/configuration.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ module WorkOS
# config.log_level = :info
# end
class Configuration
attr_accessor :api_key, :base_url, :client_id, :timeout, :max_retries, :logger, :log_level, :jwt_issuer
attr_accessor :api_key, :base_url, :client_id, :timeout, :max_retries, :logger, :log_level, :jwt_issuer, :proxy

def initialize
@base_url = WorkOS::BaseClient::DEFAULT_BASE_URL
Expand Down Expand Up @@ -48,7 +48,8 @@ def client
max_retries: configuration.max_retries,
logger: configuration.logger,
log_level: configuration.log_level,
jwt_issuer: configuration.jwt_issuer
jwt_issuer: configuration.jwt_issuer,
proxy: configuration.proxy
)
end

Expand Down
204 changes: 204 additions & 0 deletions test/workos/test_base_client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -395,6 +395,210 @@ def test_connection_cache_is_not_shared_with_threads_spawned_after_warming
assert_same warm, parent_cache["https:api.workos.com:443:30"]
end

def test_proxy_defaults_to_nil
assert_nil @client.proxy
end

# Without an explicit proxy, Net::HTTP must keep reading http_proxy from
# the environment exactly as it did before the option existed.
def test_connection_without_proxy_still_reads_proxy_from_env
with_stubbed_start do
with_env("http_proxy" => "http://env-proxy.example.com:3128", "no_proxy" => nil) do
conn = @client.send(:connection_for, "https://api.workos.com", 30)

assert conn.proxy_from_env?
assert conn.proxy?
assert_equal "env-proxy.example.com", conn.proxy_address
assert_equal 3128, conn.proxy_port
end
end
end

def test_connection_without_proxy_or_env_is_direct
with_stubbed_start do
with_env("http_proxy" => nil, "HTTP_PROXY" => nil) do
conn = @client.send(:connection_for, "https://api.workos.com", 30)

refute conn.proxy?
end
end
end

def test_connection_without_proxy_keeps_the_existing_cache_key
uri = URI("https://api.workos.com")

assert_equal "https:api.workos.com:443:30", @client.send(:connection_key, uri, 30)
end

def test_explicit_proxy_is_used_for_connections
client = WorkOS::BaseClient.new(api_key: "sk_test_123", proxy: "http://proxy.example.com:8080")

with_stubbed_start do
conn = client.send(:connection_for, "https://api.workos.com", 30)

refute conn.proxy_from_env?
assert conn.proxy?
assert_equal "proxy.example.com", conn.proxy_address
assert_equal 8080, conn.proxy_port
assert_nil conn.proxy_user
assert_nil conn.proxy_pass
assert conn.use_ssl?
assert_equal "api.workos.com", conn.address
end
end

def test_explicit_proxy_takes_precedence_over_env
client = WorkOS::BaseClient.new(api_key: "sk_test_123", proxy: "http://proxy.example.com:8080")

with_stubbed_start do
with_env("http_proxy" => "http://env-proxy.example.com:3128", "no_proxy" => "api.workos.com") do
conn = client.send(:connection_for, "https://api.workos.com", 30)

assert conn.proxy?
assert_equal "proxy.example.com", conn.proxy_address
assert_equal 8080, conn.proxy_port
end
end
end

def test_explicit_proxy_credentials_are_percent_decoded
client = WorkOS::BaseClient.new(api_key: "sk_test_123", proxy: "http://us%40er:p%3Ass+word@proxy.example.com:8080")

with_stubbed_start do
conn = client.send(:connection_for, "https://api.workos.com", 30)

assert_equal "us@er", conn.proxy_user
assert_equal "p:ss+word", conn.proxy_pass
end
end

def test_explicit_proxy_accepts_a_uri_and_defaults_the_port
client = WorkOS::BaseClient.new(api_key: "sk_test_123", proxy: URI("http://proxy.example.com"))

with_stubbed_start do
conn = client.send(:connection_for, "https://api.workos.com", 30)

assert_equal "proxy.example.com", conn.proxy_address
assert_equal 80, conn.proxy_port
end
end

def test_proxy_reader_returns_the_configured_value
client = WorkOS::BaseClient.new(api_key: "sk_test_123", proxy: "http://proxy.example.com:8080")

assert_equal "http://proxy.example.com:8080", client.proxy
end

def test_invalid_proxy_raises_argument_error
["", "proxy.example.com:8080", "https://proxy.example.com", "socks5://proxy.example.com:1080", "http://", "http://bad host", 8080].each do |proxy|
assert_raises(ArgumentError, "expected #{proxy.inspect} to be rejected") do
WorkOS::BaseClient.new(api_key: "sk_test_123", proxy: proxy)
end
end
end

def test_invalid_proxy_error_does_not_leak_credentials
error = assert_raises(ArgumentError) do
WorkOS::BaseClient.new(api_key: "sk_test_123", proxy: "https://user:s3cret@proxy.example.com")
end

refute_includes error.message, "s3cret"
refute_includes error.message, "user"
end

# Clients that differ only by proxy must not reuse each other's pooled
# connection, otherwise traffic would silently take the wrong route.
def test_clients_with_different_proxies_do_not_share_connections
proxied = WorkOS::BaseClient.new(api_key: "sk_test_123", proxy: "http://proxy-a.example.com:8080")
other = WorkOS::BaseClient.new(api_key: "sk_test_123", proxy: "http://proxy-b.example.com:8080")
same = WorkOS::BaseClient.new(api_key: "sk_test_123", proxy: "http://proxy-a.example.com:8080")

with_stubbed_start do
with_env("http_proxy" => nil, "HTTP_PROXY" => nil) do
direct_conn = @client.send(:connection_for, "https://api.workos.com", 30)
proxied_conn = proxied.send(:connection_for, "https://api.workos.com", 30)
other_conn = other.send(:connection_for, "https://api.workos.com", 30)

refute direct_conn.proxy?
assert_equal "proxy-a.example.com", proxied_conn.proxy_address
assert_equal "proxy-b.example.com", other_conn.proxy_address
assert_equal 3, [direct_conn, proxied_conn, other_conn].map(&:object_id).uniq.length
assert_equal 3, Thread.current[:workos_connections].size

# Asking again reuses each pooled connection, and a client configured
# with the same proxy shares the entry.
assert_same proxied_conn, proxied.send(:connection_for, "https://api.workos.com", 30)
assert_same proxied_conn, same.send(:connection_for, "https://api.workos.com", 30)
assert_same other_conn, other.send(:connection_for, "https://api.workos.com", 30)
assert_same direct_conn, @client.send(:connection_for, "https://api.workos.com", 30)
assert_equal 3, Thread.current[:workos_connections].size
end
end
end

def test_proxy_credentials_are_part_of_the_cache_key_but_not_stored_in_it
uri = URI("https://api.workos.com")
first = WorkOS::BaseClient.new(proxy: "http://user:s3cret@proxy.example.com:8080")
second = WorkOS::BaseClient.new(proxy: "http://user:other@proxy.example.com:8080")

first_key = first.send(:connection_key, uri, 30)

refute_equal first_key, second.send(:connection_key, uri, 30)
refute_includes first_key, "s3cret"
assert first_key.start_with?("https:api.workos.com:443:30:")
end

def test_evict_connection_removes_proxied_connections
client = WorkOS::BaseClient.new(api_key: "sk_test_123", proxy: "http://proxy.example.com:8080")
key = client.send(:connection_key, URI("https://api.workos.com"), 30)
conn = FakeConnection.new
Thread.current[:workos_connections] = {key => conn}

client.send(:evict_connection, "https://api.workos.com")

assert_empty Thread.current[:workos_connections]
assert conn.finished
end

def test_requests_through_a_proxied_client_never_log_proxy_credentials
io = StringIO.new
client = WorkOS::BaseClient.new(
api_key: "sk_test_123",
proxy: "http://user:s3cret@proxy.example.com:8080",
logger: Logger.new(io),
log_level: :debug,
max_retries: 0
)
stub_request(:get, "https://api.workos.com/organizations").to_return(status: 500, body: "{}")

assert_raises(WorkOS::APIError) { client.request(method: :get, path: "/organizations") }

refute_empty io.string
refute_includes io.string, "s3cret"
refute_includes io.string, "proxy.example.com"
end

# Stubs Net::HTTP#start to avoid real TCP+TLS connections while still
# marking the connection as started, so pooled reuse is exercised.
def with_stubbed_start
original_start = Net::HTTP.instance_method(:start)
Net::HTTP.define_method(:start) do
@started = true
self
end
yield
ensure
Net::HTTP.define_method(:start, original_start)
end

def with_env(overrides)
saved = overrides.to_h { |name, _| [name, ENV[name]] }
overrides.each { |name, value| ENV[name] = value }
yield
ensure
saved.each { |name, value| ENV[name] = value }
end

# Exercises the connection_for path (not just the storage helper):
# each thread must open and cache its *own* Net::HTTP connection rather
# than reusing one established on another thread.
Expand Down
Loading
Loading