From 74c7a6781b05854e70ce06f2c9fda35599122eb0 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 12 Nov 2026 21:58:07 +0000 Subject: [PATCH 1/3] Fix CONNECT headers for Net::HTTP, HTTP.rb, RestClient, and Faraday. Stop copying Net::HTTP#connect. HTTP.rb uses its own proxy headers, RestClient keeps using Net::HTTP, and Faraday reads the CONNECT response through public adapter methods. Co-authored-by: ProxyMesh AI --- .agents/skills/ruby-proxy-headers/SKILL.md | 2 + CHANGELOG.md | 4 + Gemfile.lock | 25 ++- README.md | 30 +++ lib/ruby_proxy_headers/faraday.rb | 35 ++-- lib/ruby_proxy_headers/http_gem.rb | 96 +++++---- lib/ruby_proxy_headers/net_http.rb | 228 ++++++++------------- lib/ruby_proxy_headers/rest_client.rb | 136 ++++++------ ruby-proxy-headers.gemspec | 2 + spec/client_proxy_spec.rb | 127 ++++++++++++ spec/net_http_compat_spec.rb | 123 +++++++++++ spec/support/mock_connect_proxy.rb | 90 ++++++++ test/test_proxy_headers.rb | 50 ++++- 13 files changed, 682 insertions(+), 266 deletions(-) create mode 100644 spec/client_proxy_spec.rb create mode 100644 spec/net_http_compat_spec.rb diff --git a/.agents/skills/ruby-proxy-headers/SKILL.md b/.agents/skills/ruby-proxy-headers/SKILL.md index 63f0c86..8088310 100644 --- a/.agents/skills/ruby-proxy-headers/SKILL.md +++ b/.agents/skills/ruby-proxy-headers/SKILL.md @@ -32,6 +32,8 @@ Install faraday, httparty, excon, or typhoeus (~> 1.7) as needed. | HTTParty | `ruby_proxy_headers/httparty` | `ProxyHeadersConnectionAdapter` | | Excon | `ruby_proxy_headers/excon` | `ExconIntegration.get` (send-only) | | Typhoeus | `ruby_proxy_headers/typhoeus` | `Typhoeus.get` (`proxy_response_headers`) | +| HTTP.rb | `ruby_proxy_headers/http_gem` | `HTTPGem.create_client` (http gem >= 6) | +| RestClient | `ruby_proxy_headers/rest_client` | `RestClient.get` | ## Usage Patterns diff --git a/CHANGELOG.md b/CHANGELOG.md index 29fd464..4bd405f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed - HTTPS requests through `RubyProxyHeaders::Typhoeus` no longer call `RubyProxyHeaders::NetHTTP.request`, which is not defined. +- HTTP.rb and RestClient no longer call that missing method. HTTP.rb uses its own `proxy_headers` on CONNECT. RestClient keeps using Net::HTTP, with CONNECT headers attached by the Net::HTTP patch. +- The Net::HTTP patch no longer replaces `Net::HTTP#connect` with a copy of the Ruby 3.2 method. Socket setup, `timeouted_connect`, and HTTPS proxies stay in the installed net-http. +- The Faraday adapter no longer overrides faraday-net_http's private `request_with_wrapped_block`. CONNECT response headers are merged from `build_connection` and `call`. +- `NetHTTP.patch!` still applies after WebMock swaps `Net::HTTP` out and restores it. ## [0.1.0] - 2024-02-28 diff --git a/Gemfile.lock b/Gemfile.lock index ad13db9..d307ded 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -39,6 +39,10 @@ GEM ffi (1.17.4-x86_64-linux-gnu) ffi (1.17.4-x86_64-linux-musl) hashdiff (1.2.1) + http (6.0.4) + http-cookie (~> 1.0) + llhttp (~> 0.6.1) + http-accept (1.7.0) http-cookie (1.1.6) domain_name (~> 0.5) httparty (0.24.3) @@ -48,6 +52,7 @@ GEM json (3.1.0) language_server-protocol (3.17.0.6) lint_roller (1.1.0) + llhttp (0.6.2) logger (1.7.0) mechanize (2.14.2) addressable (~> 2.8) @@ -67,7 +72,6 @@ GEM mime-types-data (~> 3.2025, >= 3.2025.0507) mime-types-data (3.2026.1027) mini_mime (1.1.5) - mini_portile2 (2.8.9) multi_xml (0.6.0) net-http (0.10.0) net-protocol (>= 0.3.0) @@ -77,10 +81,8 @@ GEM connection_pool (>= 2.2.4, < 4) net-protocol (0.4.0) timeout + netrc (0.11.0) nkf (0.3.0) - nokogiri (1.19.6) - mini_portile2 (~> 2.8.2) - racc (~> 1.4) nokogiri (1.19.6-aarch64-linux-gnu) racc (~> 1.4) nokogiri (1.19.6-aarch64-linux-musl) @@ -107,6 +109,11 @@ GEM rainbow (3.1.1) rake (13.4.2) regexp_parser (2.13.1) + rest-client (2.1.0) + http-accept (>= 1.7.0, < 2.0) + http-cookie (>= 1.0.2, < 2.0) + mime-types (>= 1.16, < 4.0) + netrc (~> 0.8) rexml (3.4.4) rspec (3.13.2) rspec-core (~> 3.13.0) @@ -159,7 +166,6 @@ PLATFORMS arm-linux-gnu arm-linux-musl arm64-darwin - ruby x86_64-darwin x86_64-linux-gnu x86_64-linux-musl @@ -170,9 +176,11 @@ DEPENDENCIES excon (~> 1.4) faraday (~> 2.14) faraday-net_http (~> 3.4) + http (~> 6.0) httparty (~> 0.24) mechanize (~> 2.14) rake (~> 13.0) + rest-client (~> 2.1) rspec (~> 3.12) rubocop (~> 1.50) ruby-proxy-headers! @@ -204,24 +212,26 @@ CHECKSUMS ffi (1.17.4-x86_64-linux-gnu) sha256=9d3db14c2eae074b382fa9c083fe95aec6e0a1451da249eab096c34002bc752d ffi (1.17.4-x86_64-linux-musl) sha256=3fdf9888483de005f8ef8d1cf2d3b20d86626af206cbf780f6a6a12439a9c49e hashdiff (1.2.1) sha256=9c079dbc513dfc8833ab59c0c2d8f230fa28499cc5efb4b8dd276cf931457cd1 + http (6.0.4) sha256=3768f902489ea8309424f1881c668af8d3ca73675648a755dfe2cb0030d42d26 + http-accept (1.7.0) sha256=c626860682bfbb3b46462f8c39cd470fd7b0584f61b3cc9df5b2e9eb9972a126 http-cookie (1.1.6) sha256=ba4b82be64de61dc281243dac70e3c382c45142f20268ed9276a3670c93feaa9 httparty (0.24.3) sha256=5c95cf29ca70d5bfd834e56140ddfca6e94166c3b870cde9c25d157cdb5a00d2 json (3.1.0) sha256=3ce7ccf8fde58960177a3a756c31f292a4c1e1dedee884547096a5b0604e3bd8 language_server-protocol (3.17.0.6) sha256=5ef2c0c138f8267e1bc631d3328347d354f96724b0af22f2c79516120443b7f0 lint_roller (1.1.0) sha256=2c0c845b632a7d172cb849cc90c1bce937a28c5c8ccccb50dfd46a485003cc87 + llhttp (0.6.2) sha256=3c3c59aafb1e1594ab2f45293478f697458f5a91eb0f0db4b27f61a064024982 logger (1.7.0) sha256=196edec7cc44b66cfb40f9755ce11b392f21f7967696af15d274dde7edff0203 mechanize (2.14.2) sha256=aaf0a91dad80a2a72f51054780731d42ffed564fc530d6cffa8022717508e23e mime-types (3.7.0) sha256=dcebf61c246f08e15a4de34e386ebe8233791e868564a470c3fe77c00eed5e56 mime-types-data (3.2026.1027) sha256=4568729e44974c1c8a8ceb76f7a5fc164e8c9553335455688bb3c00020f5d83f mini_mime (1.1.5) sha256=8681b7e2e4215f2a159f9400b5816d85e9d8c6c6b491e96a12797e798f8bccef - mini_portile2 (2.8.9) sha256=0cd7c7f824e010c072e33f68bc02d85a00aeb6fce05bb4819c03dfd3c140c289 multi_xml (0.6.0) sha256=d24393cf958adb226db884b976b007914a89c53ad88718e25679d7008823ad52 net-http (0.10.0) sha256=1a2ff6e37a05724973c43f2bf7bf105f59c36a4cd0a7e9b1c021a0a566987c27 net-http-digest_auth (1.4.1) sha256=4b8ad50ed8d180a58db5d6c49449b987dd0466fe01e24037945bc007562a08db net-http-persistent (4.0.8) sha256=ef3de8319d691537b329053fae3a33195f8b070bbbfae8bf1a58c796081960e6 net-protocol (0.4.0) sha256=f9f90c8c6f64794a45160bf422177a336db12809de3beeeaa26b88fcd2e8c853 + netrc (0.11.0) sha256=de1ce33da8c99ab1d97871726cba75151113f117146becbe45aa85cb3dabee3f nkf (0.3.0) sha256=357a8dbeba38b727b75930f665146546076a394a1c243faf634ff176e3588895 - nokogiri (1.19.6) sha256=a61e7192fc2691c23bc0241907c4dbcb70ada6ab904796ce2426a57171022c8f nokogiri (1.19.6-aarch64-linux-gnu) sha256=746fca23be3cd3f121cabab65cb44c52049e4cf9f0d36e7e8c3c0eb6cc298c57 nokogiri (1.19.6-aarch64-linux-musl) sha256=4a5620da1c52150e0343bd2bba7dbd9b3899b5eb41687dc1942c9092d81e52a3 nokogiri (1.19.6-arm-linux-gnu) sha256=574e50ddd99ed71aaa868027d84eb3b9f051e55fe07ddc844e4fdd654be953fc @@ -238,6 +248,7 @@ CHECKSUMS rainbow (3.1.1) sha256=039491aa3a89f42efa1d6dec2fc4e62ede96eb6acd95e52f1ad581182b79bc6a rake (13.4.2) sha256=cb825b2bd5f1f8e91ca37bddb4b9aaf345551b4731da62949be002fa89283701 regexp_parser (2.13.1) sha256=5aedb6b7c35688f51e86eef17a15374dfd287c83f4ca644b2c5f3ec50a33b44b + rest-client (2.1.0) sha256=35a6400bdb14fae28596618e312776c158f7ebbb0ccad752ff4fa142bf2747e3 rexml (3.4.4) sha256=19e0a2c3425dfbf2d4fc1189747bdb2f849b6c5e74180401b15734bc97b5d142 rspec (3.13.2) sha256=206284a08ad798e61f86d7ca3e376718d52c0bc944626b2349266f239f820587 rspec-core (3.13.6) sha256=a8823c6411667b60a8bca135364351dda34cd55e44ff94c4be4633b37d828b2d diff --git a/README.md b/README.md index f8f3f98..ee5dd60 100644 --- a/README.md +++ b/README.md @@ -94,6 +94,36 @@ HTTParty.get( puts RubyProxyHeaders.proxy_connect_response_headers['X-ProxyMesh-IP'] ``` +## HTTP.rb + +Requires the `http` gem 6 or newer. Proxy headers are sent on CONNECT by HTTP.rb itself. + +```ruby +require 'ruby_proxy_headers/http_gem' + +client = RubyProxyHeaders::HTTPGem.create_client( + proxy: 'http://user:pass@proxy.example.com:31280', + proxy_headers: { 'X-ProxyMesh-Country' => 'US' } +) +response = client.get('https://api.ipify.org?format=json') +puts response.proxy_response_headers['X-ProxyMesh-IP'] +``` + +## RestClient + +RestClient performs the request. The Net::HTTP patch adds the CONNECT headers. + +```ruby +require 'ruby_proxy_headers/rest_client' + +response = RubyProxyHeaders::RestClient.get( + 'https://api.ipify.org?format=json', + proxy: 'http://user:pass@proxy.example.com:31280', + proxy_headers: { 'X-ProxyMesh-Country' => 'US' } +) +puts response.proxy_response_headers['X-ProxyMesh-IP'] +``` + ## Typhoeus Requires Typhoeus 1.7. Proxy headers go to libcurl as `CURLOPT_PROXYHEADER` and are not copied onto the origin request. Header names are documented at . diff --git a/lib/ruby_proxy_headers/faraday.rb b/lib/ruby_proxy_headers/faraday.rb index 2e089bc..e4820aa 100644 --- a/lib/ruby_proxy_headers/faraday.rb +++ b/lib/ruby_proxy_headers/faraday.rb @@ -14,28 +14,31 @@ module RubyProxyHeaders # Faraday adapter that merges proxy CONNECT response headers into Faraday response headers. # Use with {RubyProxyHeaders::NetHTTP.patch!}. + # + # faraday-net_http 3.4 and 3.5 perform the request in the private method + # +request_with_wrapped_block+. This adapter does not override that method. + # It uses the public +build_connection+ and +call+ methods. module FaradayAdapter + # Copies CONNECT response headers onto the Faraday response. class NetHttp < ::Faraday::Adapter::NetHttp - def request_with_wrapped_block(http, env, &block) - res = super - merge_proxy_headers(env, http) - res + def build_connection(env) + super.tap { |http| Thread.current[:ruby_proxy_headers_faraday_http] = http } end - private + def call(env) + response = super + http = Thread.current[:ruby_proxy_headers_faraday_http] + headers = http.last_proxy_connect_response_headers if http + if env[:response_headers] && headers + headers.each do |key, value| + next if value.nil? - def merge_proxy_headers(env, http) - return unless env[:response_headers] - return unless http.respond_to?(:last_proxy_connect_response_headers) - - ph = http.last_proxy_connect_response_headers - return unless ph.is_a?(Hash) - - ph.each do |k, v| - next if v.nil? - - env[:response_headers][k] ||= v + env[:response_headers][key] ||= value + end end + response + ensure + Thread.current[:ruby_proxy_headers_faraday_http] = nil end end end diff --git a/lib/ruby_proxy_headers/http_gem.rb b/lib/ruby_proxy_headers/http_gem.rb index 0a1eb2b..dc26881 100644 --- a/lib/ruby_proxy_headers/http_gem.rb +++ b/lib/ruby_proxy_headers/http_gem.rb @@ -1,48 +1,50 @@ # frozen_string_literal: true +require 'delegate' +require 'openssl' +require 'uri' +require_relative '../ruby_proxy_headers' + +begin + require 'http' +rescue LoadError => e + raise LoadError, "the http gem >= 6 is required for ruby_proxy_headers/http_gem (#{e.message})" +end + module RubyProxyHeaders - # HTTP.rb (http gem) integration for proxy headers support. + # HTTP.rb (the +http+ gem) sends +proxy_headers+ on CONNECT and returns them + # as +response.proxy_headers+. This wrapper adds +proxy_response_headers+, + # matching the other adapters. # # @example # client = RubyProxyHeaders::HTTPGem.create_client( - # proxy: 'http://user:pass@proxy:8080', + # proxy: 'http://user:pass@proxy.example.com:31280', # proxy_headers: { 'X-ProxyMesh-Country' => 'US' } # ) - # # response = client.get('https://example.com') - # puts response.proxy_response_headers - # + # puts response.proxy_response_headers['X-ProxyMesh-IP'] module HTTPGem - # Create an HTTP client with proxy header support. - # @param proxy [String] Proxy URL - # @param proxy_headers [Hash] Custom headers to send to proxy - # @param options [Hash] Additional HTTP.rb options - # @return [ProxyClient] - def self.create_client(proxy:, proxy_headers: {}, **options) - ProxyClient.new(proxy: proxy, proxy_headers: proxy_headers, **options) + def self.create_client(proxy:, proxy_headers: {}, **) + ProxyClient.new(proxy: proxy, proxy_headers: proxy_headers) end - # Make a GET request with proxy headers. def self.get(url, proxy:, proxy_headers: {}, **options) create_client(proxy: proxy, proxy_headers: proxy_headers).get(url, **options) end - # Make a POST request with proxy headers. def self.post(url, proxy:, proxy_headers: {}, body: nil, **options) create_client(proxy: proxy, proxy_headers: proxy_headers).post(url, body: body, **options) end - # Proxy client wrapper for HTTP.rb + # HTTP.rb client that sends proxy_headers on CONNECT. class ProxyClient - def initialize(proxy:, proxy_headers: {}, **options) + attr_reader :last_proxy_response_headers + + def initialize(proxy:, proxy_headers: {}) @proxy = proxy - @proxy_headers = proxy_headers - @options = options - @last_proxy_response_headers = nil + @proxy_headers = proxy_headers || {} end - attr_reader :last_proxy_response_headers - def get(url, **options) request(:get, url, **options) end @@ -62,32 +64,38 @@ def delete(url, **options) private def request(method, url, **options) - uri = URI.parse(url) - - # Use our core connection for HTTPS - if uri.scheme == 'https' - response = RubyProxyHeaders::NetHTTP.request( - method, - url, - proxy: @proxy, - proxy_headers: @proxy_headers, - headers: options[:headers], - body: options[:body] - ) - @last_proxy_response_headers = response.proxy_response_headers - return response + @proxy_headers.each { |key, value| RubyProxyHeaders.validate_header!(key, value) } + proxy_uri = URI.parse(@proxy) + user = proxy_uri.user && URI.decode_www_form_component(proxy_uri.user) + password = proxy_uri.password && URI.decode_www_form_component(proxy_uri.password) + client = ::HTTP.via(proxy_uri.host, proxy_uri.port, user, password, @proxy_headers) + timeouts = {} + timeouts[:connect] = options[:open_timeout] if options[:open_timeout] + timeouts[:read] = options[:read_timeout] if options[:read_timeout] + client = client.timeout(timeouts) unless timeouts.empty? + + request_options = {} + request_options[:headers] = options[:headers] if options[:headers] + request_options[:body] = options[:body] unless options[:body].nil? + if options[:verify_ssl] == false + context = OpenSSL::SSL::SSLContext.new + context.verify_mode = OpenSSL::SSL::VERIFY_NONE + request_options[:ssl_context] = context end - # For HTTP, use standard http gem - require 'http' + response = client.request(method, url, **request_options) + @last_proxy_response_headers = response.proxy_headers + ProxyResponse.new(response) + end + end - proxy_uri = URI.parse(@proxy) - ::HTTP.via( - proxy_uri.host, - proxy_uri.port, - proxy_uri.user, - proxy_uri.password - ).send(method, url, **options) + # HTTP::Response plus +proxy_response_headers+. + class ProxyResponse < SimpleDelegator + attr_reader :proxy_response_headers + + def initialize(response) + super(response) + @proxy_response_headers = response.proxy_headers end end end diff --git a/lib/ruby_proxy_headers/net_http.rb b/lib/ruby_proxy_headers/net_http.rb index 23a2f27..9f76ec4 100644 --- a/lib/ruby_proxy_headers/net_http.rb +++ b/lib/ruby_proxy_headers/net_http.rb @@ -1,16 +1,20 @@ # frozen_string_literal: true require 'net/http' -require 'net/protocol' require 'openssl' -require 'resolv' -require 'timeout' + +# Loaded for header validation. Requiring this file first is safe: the parent +# requires it back and Ruby drops the cycle. +require_relative '../ruby_proxy_headers' module RubyProxyHeaders - # Patches Net::HTTP#connect for HTTPS-over-proxy so extra headers can be sent on - # the CONNECT request and response headers can be read (e.g. ProxyMesh - # X-ProxyMesh-IP). Based on the same tunnel flow as Python's http.client / urllib3 - # extensions in python-proxy-headers. + # Patches Net::HTTP so an HTTPS request through a proxy can send extra CONNECT + # headers and keep the proxy's CONNECT response. + # + # The patch does not copy +Net::HTTP#connect+. The installed net-http still + # owns the socket, +timeouted_connect+, and HTTPS-to-proxy (+proxy_use_ssl+). + # A prepend validates the target, then rewrites the CONNECT bytes that + # upstream writes and records the CONNECT response. # # @example # require 'ruby_proxy_headers/net_http' @@ -20,155 +24,105 @@ module RubyProxyHeaders # http.use_ssl = true # http.proxy_connect_request_headers = { 'X-ProxyMesh-IP' => '203.0.113.1' } # res = http.request(Net::HTTP::Get.new(uri)) - # p http.last_proxy_connect_response_headers + # p http.last_proxy_connect_response_headers['X-ProxyMesh-IP'] module NetHTTP - unless const_defined?(:ORIGINAL_CONNECT, false) - ORIGINAL_CONNECT = ::Net::HTTP.instance_method(:connect) - end + # Inserts +headers+ before the blank line that ends a CONNECT request. + def self.inject_connect_headers(buf, headers) + return buf if headers.nil? || headers.empty? - module Extension - attr_accessor :proxy_connect_request_headers - attr_reader :last_proxy_connect_response_headers + headers.each { |key, value| RubyProxyHeaders.validate_header!(key, value) } - def connect - if use_ssl? && proxy? - connect_with_proxy_tunnel - else - RubyProxyHeaders::NetHTTP::ORIGINAL_CONNECT.bind_call(self) - end + extra = String.new(encoding: buf.encoding) + headers.each do |key, value| + extra << "#{key}: #{value}\r\n".encode(buf.encoding) end + "#{buf.sub(/\r\n\r\n\z/, "\r\n")}#{extra}\r\n" + end - private - - # Duplicates Net::HTTP#connect (MRI 3.2) for the HTTPS + proxy branch, with - # optional extra CONNECT headers and capture of the CONNECT response headers. - def connect_with_proxy_tunnel - s = nil - if use_ssl? - @ssl_context = OpenSSL::SSL::SSLContext.new - end - - if use_ssl? && proxy? - # Fail before any socket I/O: CONNECT interpolates these into a raw request line. - RubyProxyHeaders.validate_connect_target!(conn_address, @port) - RubyProxyHeaders.validate_connect_target!(@address, @port) - end - - if proxy? - conn_addr = proxy_address - conn_port = proxy_port - else - conn_addr = conn_address - conn_port = port + # Rewrites a CONNECT write while a patched connection is opening. + module ConnectRequestWrite + def write(*strs) + http = Thread.current[:ruby_proxy_headers_active_http] + joined = strs.join + if http && joined.start_with?('CONNECT ') + strs = [ + RubyProxyHeaders::NetHTTP.inject_connect_headers( + joined, + http.proxy_connect_request_headers + ) + ] end + super(*strs) + end + end - debug "opening connection to #{conn_addr}:#{conn_port}..." - s = Timeout.timeout(@open_timeout, Net::OpenTimeout) do - begin - TCPSocket.open(conn_addr, conn_port, @local_host, @local_port) - rescue StandardError => e - raise e, "Failed to open TCP connection to " \ - "#{conn_addr}:#{conn_port} (#{e.message})" - end + # Records CONNECT response headers. Active only while #connect is running, + # so the later origin response is left alone. + module ConnectResponseRead + def read_new(sock) + response = super + http = Thread.current[:ruby_proxy_headers_active_http] + if http + headers = HeaderMap.new + response.each_header { |key, value| headers[key] = value } + http.instance_variable_set(:@last_proxy_connect_response_headers, headers) + Thread.current[:ruby_proxy_headers_connect_headers] = headers.dup end - s.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1) - debug 'opened' - - if use_ssl? - if proxy? - plain_sock = Net::BufferedIO.new(s, read_timeout: @read_timeout, - write_timeout: @write_timeout, - continue_timeout: @continue_timeout, - debug_output: @debug_output) - buf = +"CONNECT #{conn_address}:#{@port} HTTP/#{::Net::HTTP::HTTPVersion}\r\n" \ - "Host: #{@address}:#{@port}\r\n" - if proxy_user - credential = ["#{proxy_user}:#{proxy_pass}"].pack('m0') - buf << "Proxy-Authorization: Basic #{credential}\r\n" - end - if proxy_connect_request_headers&.any? - proxy_connect_request_headers.each do |k, v| - RubyProxyHeaders.validate_header!(k, v) - buf << "#{k}: #{v}\r\n" - end - end - buf << "\r\n" - plain_sock.write(buf) - - proxy_res = ::Net::HTTPResponse.read_new(plain_sock) - @last_proxy_connect_response_headers = {} - proxy_res.each_header do |k, v| - @last_proxy_connect_response_headers[k] = v - end - Thread.current[:ruby_proxy_headers_connect_headers] = @last_proxy_connect_response_headers.dup - proxy_res.value - end - - ssl_parameters = {} - iv_list = instance_variables - Net::HTTP::SSL_IVNAMES.each_with_index do |ivname, i| - if iv_list.include?(ivname) - value = instance_variable_get(ivname) - unless value.nil? - ssl_parameters[Net::HTTP::SSL_ATTRIBUTES[i]] = value - end - end - end - @ssl_context.set_params(ssl_parameters) - unless @ssl_context.session_cache_mode.nil? - @ssl_context.session_cache_mode = - OpenSSL::SSL::SSLContext::SESSION_CACHE_CLIENT | - OpenSSL::SSL::SSLContext::SESSION_CACHE_NO_INTERNAL_STORE - end - if @ssl_context.respond_to?(:session_new_cb) - @ssl_context.session_new_cb = proc { |sock, sess| @ssl_session = sess } - end + response + end + end - verify_hostname = @ssl_context.verify_hostname + # Instance methods prepended onto Net::HTTP. + module Extension + attr_accessor :proxy_connect_request_headers + attr_reader :last_proxy_connect_response_headers - case @address - when Resolv::IPv4::Regex, Resolv::IPv6::Regex - @ssl_context.verify_hostname = false - else - ssl_host_address = @address - end + def connect + return super unless use_ssl? && proxy? - debug "starting SSL for #{conn_addr}:#{conn_port}..." - s = OpenSSL::SSL::SSLSocket.new(s, @ssl_context) - s.sync_close = true - s.hostname = ssl_host_address if s.respond_to?(:hostname=) && ssl_host_address + # Reject smuggled targets and header values before any socket I/O. + RubyProxyHeaders.validate_connect_target!(conn_address, @port) + RubyProxyHeaders.validate_connect_target!(@address, @port) + proxy_connect_request_headers&.each do |key, value| + RubyProxyHeaders.validate_header!(key, value) + end - if @ssl_session && - Process.clock_gettime(Process::CLOCK_REALTIME) < @ssl_session.time.to_f + @ssl_session.timeout - s.session = @ssl_session + @last_proxy_connect_response_headers = nil + previous_http = Thread.current[:ruby_proxy_headers_active_http] + previous_headers = Thread.current[:ruby_proxy_headers_connect_headers] + begin + Thread.current[:ruby_proxy_headers_active_http] = self + Thread.current[:ruby_proxy_headers_connect_headers] = nil + super + ensure + Thread.current[:ruby_proxy_headers_active_http] = previous_http + if Thread.current[:ruby_proxy_headers_connect_headers].nil? + Thread.current[:ruby_proxy_headers_connect_headers] = previous_headers end - ssl_socket_connect(s, @open_timeout) - if (@ssl_context.verify_mode != OpenSSL::SSL::VERIFY_NONE) && verify_hostname - s.post_connection_check(@address) - end - debug "SSL established, protocol: #{s.ssl_version}, cipher: #{s.cipher[0]}" - end - @socket = Net::BufferedIO.new(s, read_timeout: @read_timeout, - write_timeout: @write_timeout, - continue_timeout: @continue_timeout, - debug_output: @debug_output) - @last_communicated = nil - on_connect - rescue StandardError => e - if s - debug "Conn close because of connect error #{e}" - s.close end - raise end end class << self def patch! - return if @patched - - ::Net::HTTP.prepend(Extension) - @patched = true + @patch_mutex ||= Mutex.new + @patch_mutex.synchronize do + return if @patched + + # WebMock replaces Net::HTTP with a subclass created before patch!. + # Prepend the original class so that subclass inherits it, including + # after WebMock.disable! puts the original constant back. + classes = [::Net::HTTP] + if defined?(::WebMock::HttpLibAdapters::NetHttpAdapter) + classes.unshift(::WebMock::HttpLibAdapters::NetHttpAdapter::OriginalNetHTTP) + end + classes.uniq.each do |klass| + klass.prepend(Extension) unless klass.ancestors.include?(Extension) + end + ::Net::BufferedIO.prepend(ConnectRequestWrite) + ::Net::HTTPResponse.singleton_class.prepend(ConnectResponseRead) + @patched = true + end end def patched? diff --git a/lib/ruby_proxy_headers/rest_client.rb b/lib/ruby_proxy_headers/rest_client.rb index 845f019..6c9e803 100644 --- a/lib/ruby_proxy_headers/rest_client.rb +++ b/lib/ruby_proxy_headers/rest_client.rb @@ -1,89 +1,105 @@ # frozen_string_literal: true +require 'delegate' +require 'openssl' +require 'uri' +require_relative '../ruby_proxy_headers' + +begin + require 'rest-client' +rescue LoadError => e + raise LoadError, "rest-client is required for ruby_proxy_headers/rest_client (#{e.message})" +end + module RubyProxyHeaders - # RestClient integration for proxy headers support. + # RestClient uses Net::HTTP. HTTPS requests go through that client so + # redirects and payloads stay RestClient's. The Net::HTTP patch attaches + # CONNECT headers and records +X-ProxyMesh-IP+. # # @example # response = RubyProxyHeaders::RestClient.get( # 'https://example.com', - # proxy: 'http://user:pass@proxy:8080', + # proxy: 'http://user:pass@proxy.example.com:31280', # proxy_headers: { 'X-ProxyMesh-Country' => 'US' } # ) - # puts response.proxy_response_headers - # + # puts response.proxy_response_headers['X-ProxyMesh-IP'] module RestClient - # Make a GET request with proxy headers. - def self.get(url, proxy:, proxy_headers: {}, **options) - request(:get, url, proxy: proxy, proxy_headers: proxy_headers, **options) - end - - # Make a POST request with proxy headers. - def self.post(url, proxy:, proxy_headers: {}, payload: nil, **options) - request(:post, url, proxy: proxy, proxy_headers: proxy_headers, body: payload, **options) - end - - # Make a PUT request with proxy headers. - def self.put(url, proxy:, proxy_headers: {}, payload: nil, **options) - request(:put, url, proxy: proxy, proxy_headers: proxy_headers, body: payload, **options) - end - - # Make a DELETE request with proxy headers. - def self.delete(url, proxy:, proxy_headers: {}, **options) - request(:delete, url, proxy: proxy, proxy_headers: proxy_headers, **options) + # Sets CONNECT headers on the Net::HTTP object RestClient is about to use. + module NetHttpHook + def net_http_object(hostname, port) + http = super + headers = Thread.current[:ruby_proxy_headers_rest_client_headers] + http.proxy_connect_request_headers = headers if headers&.any? + http + end end - # Make a request with proxy headers. - def self.request(method, url, proxy:, proxy_headers: {}, **options) - require 'rest-client' + class << self + def get(url, proxy:, proxy_headers: {}, **options) + request(:get, url, proxy: proxy, proxy_headers: proxy_headers, **options) + end - uri = URI.parse(url) + def post(url, proxy:, proxy_headers: {}, payload: nil, **options) + request(:post, url, proxy: proxy, proxy_headers: proxy_headers, payload: payload, **options) + end - # For HTTPS with proxy headers, use our core connection - if uri.scheme == 'https' && !proxy_headers.empty? - response = RubyProxyHeaders::NetHTTP.request( - method, - url, - proxy: proxy, - proxy_headers: proxy_headers, - headers: options[:headers], - body: options[:body] - ) - return response + def put(url, proxy:, proxy_headers: {}, payload: nil, **options) + request(:put, url, proxy: proxy, proxy_headers: proxy_headers, payload: payload, **options) end - # For HTTP or no proxy headers, use standard RestClient - ::RestClient.proxy = proxy - response = ::RestClient.send(method, url, options) - ProxyResponse.new(response, {}) - end + def delete(url, proxy:, proxy_headers: {}, **options) + request(:delete, url, proxy: proxy, proxy_headers: proxy_headers, **options) + end - # Response wrapper with proxy headers accessor - class ProxyResponse - attr_reader :proxy_response_headers + def request(method, url, proxy:, proxy_headers: {}, **options) + install! + headers = proxy_headers || {} + https = URI.parse(url).scheme == 'https' + headers.each { |key, value| RubyProxyHeaders.validate_header!(key, value) } if https - def initialize(response, proxy_headers) - @response = response - @proxy_response_headers = proxy_headers + previous = Thread.current[:ruby_proxy_headers_rest_client_headers] + Thread.current[:ruby_proxy_headers_rest_client_headers] = https ? headers : nil + response = ::RestClient::Request.execute(execute_options(method, url, proxy, options)) + captured = RubyProxyHeaders.proxy_connect_response_headers + ProxyResponse.new(response, captured ? captured.dup : HeaderMap.new) + ensure + Thread.current[:ruby_proxy_headers_rest_client_headers] = previous end - def code - @response.code - end + def install! + RubyProxyHeaders::NetHTTP.patch! + return if ::RestClient::Request.ancestors.include?(NetHttpHook) - def body - @response.body + ::RestClient::Request.prepend(NetHttpHook) end - def headers - @response.headers - end + private - def method_missing(method, *args, &block) - @response.send(method, *args, &block) + def execute_options(method, url, proxy, options) + payload = options.key?(:payload) ? options[:payload] : options[:body] + verify_ssl = options[:verify_ssl] + verify_ssl = OpenSSL::SSL::VERIFY_PEER if verify_ssl == true + verify_ssl = OpenSSL::SSL::VERIFY_NONE if verify_ssl == false + { + method: method, + url: url, + proxy: proxy, + headers: options[:headers], + payload: payload, + open_timeout: options[:open_timeout], + read_timeout: options[:read_timeout], + verify_ssl: verify_ssl + }.compact end + end - def respond_to_missing?(method, include_private = false) - @response.respond_to?(method, include_private) || super + # RestClient response plus CONNECT response headers. + class ProxyResponse < SimpleDelegator + attr_reader :proxy_response_headers + + def initialize(response, proxy_headers) + super(response) + @proxy_response_headers = proxy_headers end end end diff --git a/ruby-proxy-headers.gemspec b/ruby-proxy-headers.gemspec index a00edce..5997817 100644 --- a/ruby-proxy-headers.gemspec +++ b/ruby-proxy-headers.gemspec @@ -30,8 +30,10 @@ Gem::Specification.new do |s| s.add_development_dependency 'excon', '~> 1.4' s.add_development_dependency 'faraday', '~> 2.14' s.add_development_dependency 'faraday-net_http', '~> 3.4' + s.add_development_dependency 'http', '~> 6.0' s.add_development_dependency 'httparty', '~> 0.24' s.add_development_dependency 'mechanize', '~> 2.14' + s.add_development_dependency 'rest-client', '~> 2.1' # Optional at runtime. The Typhoeus adapter needs 1.7 so Ethon exposes # CURLOPT_PROXYHEADER. Callers install typhoeus themselves. s.add_development_dependency 'ethon', '>= 0.19.1', '< 0.20' diff --git a/spec/client_proxy_spec.rb b/spec/client_proxy_spec.rb new file mode 100644 index 0000000..e0888b3 --- /dev/null +++ b/spec/client_proxy_spec.rb @@ -0,0 +1,127 @@ +# frozen_string_literal: true + +require 'spec_helper' +require 'ruby_proxy_headers/faraday' +require 'ruby_proxy_headers/http_gem' +require 'ruby_proxy_headers/httparty' +require 'ruby_proxy_headers/rest_client' +require 'timeout' +require_relative 'support/mock_connect_proxy' + +RSpec.describe 'client CONNECT headers' do + around do |example| + WebMock.disable! + example.run + ensure + WebMock.enable! + WebMock.disable_net_connect! + end + + let(:proxy_headers) { { 'X-ProxyMesh-Country' => 'US' } } + + def open_lab + origin = MockConnect::Origin.new + proxy = MockConnect::Proxy.new + [origin, proxy, "https://127.0.0.1:#{origin.port}/resource", "http://127.0.0.1:#{proxy.port}"] + end + + def expect_separated(origin, proxy) + expect(proxy.connect_request).to include('X-ProxyMesh-Country: US') + expect(proxy.connect_request).not_to include('X-App-Secret') + expect(origin.request).to include('X-App-Secret: should-not-leak') + expect(origin.request).not_to include('X-ProxyMesh-Country') + end + + it 'uses HTTP.rb proxy_headers on CONNECT and reads X-ProxyMesh-IP' do + origin, proxy, url, proxy_url = open_lab + client = RubyProxyHeaders::HTTPGem.create_client(proxy: proxy_url, proxy_headers: proxy_headers) + response = client.get( + url, + headers: { 'X-App-Secret' => 'should-not-leak' }, + verify_ssl: false, + open_timeout: 5, + read_timeout: 5 + ) + + expect(response.code).to eq(200) + expect(response.body.to_s).to eq('origin-ok') + expect(response.proxy_response_headers['X-ProxyMesh-IP']).to eq('203.0.113.10') + expect(client.last_proxy_response_headers['X-ProxyMesh-Country-Echo']).to eq('US') + expect_separated(origin, proxy) + ensure + proxy&.stop + origin&.stop + end + + it 'uses RestClient for HTTPS and reads X-ProxyMesh-IP from CONNECT' do + origin, proxy, url, proxy_url = open_lab + response = RubyProxyHeaders::RestClient.get( + url, + proxy: proxy_url, + proxy_headers: proxy_headers, + headers: { 'X-App-Secret' => 'should-not-leak' }, + verify_ssl: false, + open_timeout: 5, + read_timeout: 5 + ) + + expect(response.code).to eq(200) + expect(response.body).to eq('origin-ok') + expect(response.proxy_response_headers['X-ProxyMesh-IP']).to eq('203.0.113.10') + expect(response.proxy_response_headers['X-ProxyMesh-Country-Echo']).to eq('US') + expect_separated(origin, proxy) + ensure + proxy&.stop + origin&.stop + end + + it 'merges CONNECT response headers through Faraday public adapter methods' do + owner = RubyProxyHeaders::FaradayAdapter::NetHttp.instance_method(:request_with_wrapped_block).owner + expect(owner).to eq(Faraday::Adapter::NetHttp) + + origin, proxy, url, proxy_url = open_lab + connection = RubyProxyHeaders::FaradayIntegration.connection( + proxy: proxy_url, + proxy_connect_headers: proxy_headers + ) do |builder| + builder.ssl.verify = false + end + response = connection.get(url) do |request| + request.headers['X-App-Secret'] = 'should-not-leak' + end + + expect(response.status).to eq(200) + expect(response.body).to eq('origin-ok') + expect(response.headers['X-ProxyMesh-IP']).to eq('203.0.113.10') + expect(response.headers['X-ProxyMesh-Country-Echo']).to eq('US') + expect_separated(origin, proxy) + ensure + proxy&.stop + origin&.stop + end + + it 'reads X-ProxyMesh-IP for HTTParty' do + origin, proxy, url, proxy_url = open_lab + RubyProxyHeaders::NetHTTP.patch! + parsed = URI(proxy_url) + response = HTTParty.get( + url, + http_proxyaddr: parsed.host, + http_proxyport: parsed.port, + verify: false, + headers: { 'X-App-Secret' => 'should-not-leak' }, + proxy_connect_request_headers: proxy_headers, + connection_adapter: RubyProxyHeaders::ProxyHeadersConnectionAdapter, + timeout: 5 + ) + + expect(response.code).to eq(200) + headers = RubyProxyHeaders.proxy_connect_response_headers + expect(headers['X-ProxyMesh-IP']).to eq('203.0.113.10') + expect(headers['X-ProxyMesh-Country-Echo']).to eq('US') + expect_separated(origin, proxy) + ensure + proxy&.stop + origin&.stop + end +end diff --git a/spec/net_http_compat_spec.rb b/spec/net_http_compat_spec.rb new file mode 100644 index 0000000..4392362 --- /dev/null +++ b/spec/net_http_compat_spec.rb @@ -0,0 +1,123 @@ +# frozen_string_literal: true + +require 'spec_helper' +require 'socket' +require 'timeout' +require_relative 'support/mock_connect_proxy' + +RSpec.describe 'net-http CONNECT compatibility' do + around do |example| + WebMock.disable! + example.run + ensure + WebMock.enable! + WebMock.disable_net_connect! + end + + before do + RubyProxyHeaders::NetHTTP.patch! + end + + it 'round-trips a custom CONNECT header on the installed net-http' do + origin = MockConnect::Origin.new + proxy = MockConnect::Proxy.new + uri = URI("https://127.0.0.1:#{origin.port}/resource") + http = Net::HTTP.new(uri.host, uri.port, '127.0.0.1', proxy.port) + http.use_ssl = true + http.verify_mode = OpenSSL::SSL::VERIFY_NONE + http.open_timeout = 5 + http.read_timeout = 5 + http.proxy_connect_request_headers = { 'X-ProxyMesh-Country' => 'US' } + request = Net::HTTP::Get.new(uri) + request['X-App-Secret'] = 'should-not-leak' + + response = http.request(request) + + expect(response.code).to eq('200') + expect(response.body).to eq('origin-ok') + expect(http.last_proxy_connect_response_headers['X-ProxyMesh-IP']).to eq('203.0.113.10') + expect(http.last_proxy_connect_response_headers['x-proxymesh-country-echo']).to eq('US') + expect(RubyProxyHeaders.proxy_connect_response_headers['X-ProxyMesh-IP']).to eq('203.0.113.10') + expect(proxy.connect_request).to include('X-ProxyMesh-Country: US') + expect(proxy.connect_request).not_to include('X-App-Secret') + expect(origin.request).to include('X-App-Secret: should-not-leak') + expect(origin.request).not_to include('X-ProxyMesh-Country') + ensure + proxy&.stop + origin&.stop + end + + it 'does not write CONNECT bytes when the target host contains CR' do + server = TCPServer.new('127.0.0.1', 0) + received = Queue.new + thread = Thread.new do + sock = Timeout.timeout(0.4) { server.accept } + received << sock.readpartial(4096) + sock.close + rescue Timeout::Error, EOFError, Errno::ECONNRESET + received << :none + end + + http = Net::HTTP.new("evil.com\r\nX-Injected: smuggled", 443, '127.0.0.1', server.addr[1]) + http.use_ssl = true + http.open_timeout = 1 + http.read_timeout = 1 + http.proxy_connect_request_headers = { 'X-ProxyMesh-Country' => 'US' } + + expect { http.send(:connect) }.to raise_error(ArgumentError, /target host/i) + expect(Timeout.timeout(0.5) { received.pop }).to eq(:none) + ensure + thread&.kill + server&.close + end + + it 'keeps the patch after WebMock restores the original Net::HTTP' do + WebMock.enable! + RubyProxyHeaders::NetHTTP.patch! + WebMock.disable! + + origin = MockConnect::Origin.new + proxy = MockConnect::Proxy.new + uri = URI("https://127.0.0.1:#{origin.port}/") + http = Net::HTTP.new(uri.host, uri.port, '127.0.0.1', proxy.port) + http.use_ssl = true + http.verify_mode = OpenSSL::SSL::VERIFY_NONE + http.open_timeout = 5 + http.read_timeout = 5 + http.proxy_connect_request_headers = { 'X-ProxyMesh-Country' => 'US' } + + response = http.request(Net::HTTP::Get.new(uri)) + + expect(response.code).to eq('200') + expect(http.last_proxy_connect_response_headers['X-ProxyMesh-IP']).to eq('203.0.113.10') + expect(proxy.connect_request).to include('X-ProxyMesh-Country: US') + ensure + proxy&.stop + origin&.stop + end + + it 'sends the custom header inside TLS when the proxy uses HTTPS' do + origin = MockConnect::Origin.new + proxy = MockConnect::TlsProxy.new + uri = URI("https://127.0.0.1:#{origin.port}/") + http = Net::HTTP.new(uri.host, uri.port, '127.0.0.1', proxy.port) + http.use_ssl = true + http.proxy_use_ssl = true + http.verify_mode = OpenSSL::SSL::VERIFY_NONE + http.open_timeout = 5 + http.read_timeout = 5 + http.proxy_connect_request_headers = { 'X-ProxyMesh-Country' => 'US' } + + response = http.request(Net::HTTP::Get.new(uri)) + + expect(response.code).to eq('200') + expect(response.body).to eq('origin-ok') + expect(http.last_proxy_connect_response_headers['X-ProxyMesh-IP']).to eq('203.0.113.9') + expect(proxy.first_byte).to eq(0x16) + expect(proxy.connect_request).to start_with('CONNECT ') + expect(proxy.connect_request).to include('X-ProxyMesh-Country: US') + ensure + proxy&.stop + origin&.stop + end +end diff --git a/spec/support/mock_connect_proxy.rb b/spec/support/mock_connect_proxy.rb index 2e28400..39bb003 100644 --- a/spec/support/mock_connect_proxy.rb +++ b/spec/support/mock_connect_proxy.rb @@ -172,4 +172,94 @@ def copy(src, dst) end end end + + # HTTPS proxy. Records the first TCP byte (a TLS handshake is 0x16) and the + # CONNECT request after the proxy TLS handshake. Bytes after the CONNECT + # response are forwarded raw because net-http continues the origin handshake + # on the underlying socket. + class TlsProxy + attr_reader :port, :connect_request, :first_byte, :error + + def initialize + @connect_request = nil + @first_byte = nil + @error = nil + @tcp = TCPServer.new('127.0.0.1', 0) + @port = @tcp.addr[1] + @context = nil + @thread = Thread.new { accept_loop } + end + + def stop + @tcp.close + rescue IOError + nil + ensure + @thread.join(1) + @thread.kill if @thread.alive? + end + + private + + def accept_loop + loop do + client = @tcp.accept + handle(client) + end + rescue IOError, Errno::EBADF + nil + rescue StandardError => e + @error = e + end + + def handle(client) + peeked = client.recv(1, Socket::MSG_PEEK) + @first_byte = peeked.bytes.first + cert, key = MockConnect.self_signed_cert + context = OpenSSL::SSL::SSLContext.new + context.cert = cert + context.key = key + ssl = OpenSSL::SSL::SSLSocket.new(client, context) + ssl.sync_close = false + ssl.accept + head = +'' + while (line = ssl.gets) + head << line + break if ["\r\n", "\n"].include?(line) + end + @connect_request = head + ssl.write( + "HTTP/1.1 200 Connection established\r\nX-ProxyMesh-IP: 203.0.113.9\r\n\r\n" + ) + target = head.lines.first.to_s.split[1].to_s + host, _, port = target.rpartition(':') + upstream = TCPSocket.new(host, Integer(port)) + splice_raw(client, upstream) + rescue StandardError => e + @error ||= e + ensure + client&.close + end + + def splice_raw(left, right) + threads = [Thread.new { copy_raw(left, right) }, Thread.new { copy_raw(right, left) }] + threads.each do |thread| + thread.join + rescue StandardError + nil + end + end + + def copy_raw(src, dst) + IO.copy_stream(src, dst) + rescue IOError, SystemCallError, OpenSSL::SSL::SSLError + nil + ensure + begin + dst.close + rescue IOError, SystemCallError + nil + end + end + end end diff --git a/test/test_proxy_headers.rb b/test/test_proxy_headers.rb index e9d5978..dbb17fa 100644 --- a/test/test_proxy_headers.rb +++ b/test/test_proxy_headers.rb @@ -8,11 +8,13 @@ # SEND_PROXY_HEADER, SEND_PROXY_VALUE — optional extra headers on CONNECT # # Usage: -# bundle exec ruby test/test_proxy_headers.rb [-v] [net_http faraday httparty excon] +# bundle exec ruby test/test_proxy_headers.rb [-v] [net_http faraday httparty excon typhoeus http_gem rest_client] require 'json' require 'uri' require 'openssl' +require 'ruby_proxy_headers/http_gem' +require 'ruby_proxy_headers/rest_client' require 'ruby_proxy_headers/typhoeus' ROOT = File.expand_path('..', __dir__) @@ -140,6 +142,48 @@ def test_httparty(verbose:) { ok: false, error: e.message } end +def test_http_gem(verbose:) + proxy_url = env_proxy_url + raise 'Set PROXY_URL' unless proxy_url + + test_url = ENV.fetch('TEST_URL', 'https://api.ipify.org?format=json') + proxy_header = ENV.fetch('PROXY_HEADER', 'X-ProxyMesh-IP') + h = send_headers_from_env + + client = RubyProxyHeaders::HTTPGem.create_client( + proxy: normalized_proxy_url(proxy_url), + proxy_headers: h + ) + res = client.get(test_url) + return { ok: false, error: "HTTP #{res.code}" } unless res.code.to_i == 200 + + val = find_header(res.proxy_response_headers, proxy_header) + assert_proxy_header(val, proxy_header, verbose: verbose, label: 'http_gem') +rescue StandardError => e + { ok: false, error: e.message } +end + +def test_rest_client(verbose:) + proxy_url = env_proxy_url + raise 'Set PROXY_URL' unless proxy_url + + test_url = ENV.fetch('TEST_URL', 'https://api.ipify.org?format=json') + proxy_header = ENV.fetch('PROXY_HEADER', 'X-ProxyMesh-IP') + h = send_headers_from_env + + res = RubyProxyHeaders::RestClient.get( + test_url, + proxy: normalized_proxy_url(proxy_url), + proxy_headers: h + ) + return { ok: false, error: "HTTP #{res.code}" } unless res.code.to_i == 200 + + val = find_header(res.proxy_response_headers, proxy_header) + assert_proxy_header(val, proxy_header, verbose: verbose, label: 'rest_client') +rescue StandardError => e + { ok: false, error: e.message } +end + def test_typhoeus(verbose:) proxy_url = env_proxy_url raise 'Set PROXY_URL' unless proxy_url @@ -196,7 +240,9 @@ def test_excon(verbose:) 'faraday' => method(:test_faraday), 'httparty' => method(:test_httparty), 'excon' => method(:test_excon), - 'typhoeus' => method(:test_typhoeus) + 'typhoeus' => method(:test_typhoeus), + 'http_gem' => method(:test_http_gem), + 'rest_client' => method(:test_rest_client) }.freeze def print_help From 8b40b83e278320a86668ac6b5b8ea53ba1e18174 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 12 Nov 2026 22:02:03 +0000 Subject: [PATCH 2/3] Return HTTP.rb CONNECT headers as a HeaderMap. The live harness only reads Hash headers, and HTTP::Headers is not a Hash, so X-ProxyMesh-IP was missing for that client. Co-authored-by: ProxyMesh AI --- lib/ruby_proxy_headers/http_gem.rb | 14 ++++++++++---- spec/client_proxy_spec.rb | 1 + 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/lib/ruby_proxy_headers/http_gem.rb b/lib/ruby_proxy_headers/http_gem.rb index dc26881..65ba805 100644 --- a/lib/ruby_proxy_headers/http_gem.rb +++ b/lib/ruby_proxy_headers/http_gem.rb @@ -84,8 +84,14 @@ def request(method, url, **options) end response = client.request(method, url, **request_options) - @last_proxy_response_headers = response.proxy_headers - ProxyResponse.new(response) + # HTTP::Headers is not a Hash. Copy into HeaderMap so callers can + # read X-ProxyMesh-IP the same way as the other adapters. + mapped = HeaderMap.new + response.proxy_headers.each do |name, value| + mapped[name] = mapped.key?(name) ? "#{mapped[name]}, #{value}" : value + end + @last_proxy_response_headers = mapped + ProxyResponse.new(response, mapped) end end @@ -93,9 +99,9 @@ def request(method, url, **options) class ProxyResponse < SimpleDelegator attr_reader :proxy_response_headers - def initialize(response) + def initialize(response, proxy_headers) super(response) - @proxy_response_headers = response.proxy_headers + @proxy_response_headers = proxy_headers end end end diff --git a/spec/client_proxy_spec.rb b/spec/client_proxy_spec.rb index e0888b3..263fca2 100644 --- a/spec/client_proxy_spec.rb +++ b/spec/client_proxy_spec.rb @@ -45,6 +45,7 @@ def expect_separated(origin, proxy) expect(response.code).to eq(200) expect(response.body.to_s).to eq('origin-ok') + expect(response.proxy_response_headers).to be_a(Hash) expect(response.proxy_response_headers['X-ProxyMesh-IP']).to eq('203.0.113.10') expect(client.last_proxy_response_headers['X-ProxyMesh-Country-Echo']).to eq('US') expect_separated(origin, proxy) From 7f0dbbec7bcea586d9c7257b1f796ea3981056cf Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 12 Nov 2026 22:19:15 +0000 Subject: [PATCH 3/3] Keep the Net::HTTP write hook off the hot path. Rewrite CONNECT bytes only while a patched connection is opening, and leave the WebMock class swap in the specs. HTTP.rb client options are passed through instead of dropped. Co-authored-by: ProxyMesh AI --- lib/ruby_proxy_headers/http_gem.rb | 15 ++++++++---- lib/ruby_proxy_headers/net_http.rb | 37 +++++++++--------------------- spec/spec_helper.rb | 1 + spec/support/net_http_webmock.rb | 18 +++++++++++++++ 4 files changed, 41 insertions(+), 30 deletions(-) create mode 100644 spec/support/net_http_webmock.rb diff --git a/lib/ruby_proxy_headers/http_gem.rb b/lib/ruby_proxy_headers/http_gem.rb index 65ba805..00a3f4c 100644 --- a/lib/ruby_proxy_headers/http_gem.rb +++ b/lib/ruby_proxy_headers/http_gem.rb @@ -24,8 +24,8 @@ module RubyProxyHeaders # response = client.get('https://example.com') # puts response.proxy_response_headers['X-ProxyMesh-IP'] module HTTPGem - def self.create_client(proxy:, proxy_headers: {}, **) - ProxyClient.new(proxy: proxy, proxy_headers: proxy_headers) + def self.create_client(proxy:, proxy_headers: {}, **options) + ProxyClient.new(proxy: proxy, proxy_headers: proxy_headers, **options) end def self.get(url, proxy:, proxy_headers: {}, **options) @@ -40,9 +40,12 @@ def self.post(url, proxy:, proxy_headers: {}, body: nil, **options) class ProxyClient attr_reader :last_proxy_response_headers - def initialize(proxy:, proxy_headers: {}) + REQUEST_OPTIONS = %i[open_timeout read_timeout headers body verify_ssl].freeze + + def initialize(proxy:, proxy_headers: {}, **options) @proxy = proxy - @proxy_headers = proxy_headers || {} + @proxy_headers = proxy_headers + @default_options = options end def get(url, **options) @@ -64,6 +67,10 @@ def delete(url, **options) private def request(method, url, **options) + options = @default_options.merge(options) + unknown = options.keys - REQUEST_OPTIONS + raise ArgumentError, "unknown option: #{unknown.first}" unless unknown.empty? + @proxy_headers.each { |key, value| RubyProxyHeaders.validate_header!(key, value) } proxy_uri = URI.parse(@proxy) user = proxy_uri.user && URI.decode_www_form_component(proxy_uri.user) diff --git a/lib/ruby_proxy_headers/net_http.rb b/lib/ruby_proxy_headers/net_http.rb index 9f76ec4..8a80035 100644 --- a/lib/ruby_proxy_headers/net_http.rb +++ b/lib/ruby_proxy_headers/net_http.rb @@ -30,8 +30,6 @@ module NetHTTP def self.inject_connect_headers(buf, headers) return buf if headers.nil? || headers.empty? - headers.each { |key, value| RubyProxyHeaders.validate_header!(key, value) } - extra = String.new(encoding: buf.encoding) headers.each do |key, value| extra << "#{key}: #{value}\r\n".encode(buf.encoding) @@ -43,11 +41,10 @@ def self.inject_connect_headers(buf, headers) module ConnectRequestWrite def write(*strs) http = Thread.current[:ruby_proxy_headers_active_http] - joined = strs.join - if http && joined.start_with?('CONNECT ') + if http && strs.first.start_with?('CONNECT ') strs = [ RubyProxyHeaders::NetHTTP.inject_connect_headers( - joined, + strs.join, http.proxy_connect_request_headers ) ] @@ -65,7 +62,7 @@ def read_new(sock) if http headers = HeaderMap.new response.each_header { |key, value| headers[key] = value } - http.instance_variable_set(:@last_proxy_connect_response_headers, headers) + http.last_proxy_connect_response_headers = headers Thread.current[:ruby_proxy_headers_connect_headers] = headers.dup end response @@ -74,8 +71,7 @@ def read_new(sock) # Instance methods prepended onto Net::HTTP. module Extension - attr_accessor :proxy_connect_request_headers - attr_reader :last_proxy_connect_response_headers + attr_accessor :proxy_connect_request_headers, :last_proxy_connect_response_headers def connect return super unless use_ssl? && proxy? @@ -105,24 +101,13 @@ def connect class << self def patch! - @patch_mutex ||= Mutex.new - @patch_mutex.synchronize do - return if @patched - - # WebMock replaces Net::HTTP with a subclass created before patch!. - # Prepend the original class so that subclass inherits it, including - # after WebMock.disable! puts the original constant back. - classes = [::Net::HTTP] - if defined?(::WebMock::HttpLibAdapters::NetHttpAdapter) - classes.unshift(::WebMock::HttpLibAdapters::NetHttpAdapter::OriginalNetHTTP) - end - classes.uniq.each do |klass| - klass.prepend(Extension) unless klass.ancestors.include?(Extension) - end - ::Net::BufferedIO.prepend(ConnectRequestWrite) - ::Net::HTTPResponse.singleton_class.prepend(ConnectResponseRead) - @patched = true - end + ::Net::HTTP.prepend(Extension) unless ::Net::HTTP.ancestors.include?(Extension) + io_hooked = ::Net::BufferedIO.ancestors.include?(ConnectRequestWrite) + ::Net::BufferedIO.prepend(ConnectRequestWrite) unless io_hooked + response_class = ::Net::HTTPResponse.singleton_class + response_hooked = response_class.ancestors.include?(ConnectResponseRead) + response_class.prepend(ConnectResponseRead) unless response_hooked + @patched = true end def patched? diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index c56313f..a5b9678 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -3,6 +3,7 @@ require 'bundler/setup' require 'ruby_proxy_headers' require 'webmock/rspec' +require_relative 'support/net_http_webmock' RSpec.configure do |config| config.expect_with :rspec do |expectations| diff --git a/spec/support/net_http_webmock.rb b/spec/support/net_http_webmock.rb new file mode 100644 index 0000000..97343b5 --- /dev/null +++ b/spec/support/net_http_webmock.rb @@ -0,0 +1,18 @@ +# frozen_string_literal: true + +# WebMock replaces Net::HTTP with a subclass created before patch!. +# Specs prepend the saved original class so WebMock.disable! still has the +# CONNECT wrapper. The library itself only patches Net::HTTP. +module RubyProxyHeaders + module NetHTTP + class << self + alias patch_net_http! patch! + + def patch! + original = ::WebMock::HttpLibAdapters::NetHttpAdapter::OriginalNetHTTP + original.prepend(Extension) unless original.ancestors.include?(Extension) + patch_net_http! + end + end + end +end