Resolve a host's name before matching NO_PROXY's CIDR blocks

URI::Generic.use_proxy? matches IP and CIDR entries against the
address it's given, and the resolver passed the hostname, so a DNS
name in a NO_PROXY subnet went through the proxy. The name is now
resolved, as Ruby's URI#find_proxy does, only when NO_PROXY has an IP
or CIDR entry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
josh-sanders
2026-11-09 23:27:50 +10:00
co-authored by Claude Opus 5.5
parent 6dd8328ee8
commit 5ad3004c73
2 changed files with 29 additions and 1 deletions
+14 -1
View File
@@ -26,11 +26,24 @@ module Ai::Transport::Http
return if proxy.nil?
no_proxy = env["NO_PROXY"].presence || env["no_proxy"].presence
return if no_proxy && (no_proxy.strip == "*" || !URI::Generic.use_proxy?(uri.host, uri.host, uri.port, no_proxy))
return if no_proxy && (no_proxy.strip == "*" || !URI::Generic.use_proxy?(uri.host, address(uri.host, no_proxy), uri.port, no_proxy))
proxy
end
# The host's address, for NO_PROXY's IP and CIDR entries, as Ruby's own lookup resolves it
# (URI#find_proxy). Names are resolved only when NO_PROXY has such an entry.
def address(host, no_proxy)
return host if ip?(host.delete("[]"))
return host unless no_proxy.split(",").any? { ip?(_1.strip) }
IPSocket.getaddress(host)
rescue SocketError
host
end
def ip?(value) = IPAddr.new(value).present? rescue false
# The proxy for Net::HTTP.new, which takes host, port, user and password.
def net_http_proxy(url, env: ENV)
proxy = proxy_for(url, env:)
+15
View File
@@ -28,6 +28,21 @@ class Ai::Transport::HttpTest < ActiveSupport::TestCase
assert_equal PROXY, Http.proxy_for("http://other.lan:8080", env:)
end
test "a host named by DNS goes direct when its address is in a NO_PROXY CIDR block" do
IPSocket.stubs(:getaddress).with("llm.internal").returns("10.72.200.61")
env = { "HTTPS_PROXY" => PROXY, "NO_PROXY" => "10.0.0.0/8" }
assert_nil Http.proxy_for("http://llm.internal:8180", env:)
IPSocket.stubs(:getaddress).with("api.openai.com").returns("162.159.140.245")
assert_equal PROXY, Http.proxy_for("https://api.openai.com", env:)
end
test "a name is never resolved when NO_PROXY lists only names" do
IPSocket.expects(:getaddress).never
assert_nil Http.proxy_for("http://llm.lan:8080", env: { "HTTPS_PROXY" => PROXY, "NO_PROXY" => "llm.lan" })
end
test "NO_PROXY=* sends every host direct" do
assert_nil Http.proxy_for("https://api.openai.com", env: { "HTTPS_PROXY" => PROXY, "NO_PROXY" => "*" })
assert_nil Http.proxy_for("http://llm.lan:8080", env: { "HTTP_PROXY" => PROXY, "no_proxy" => " * " })