diff --git a/.rubocop.yml b/.rubocop.yml index 0647667..4f55f73 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -1,22 +1,18 @@ -# Conservative defaults so existing code passes; widen in follow-up PRs. +# Defaults on, with a few targeted disables so lint passes without +# rewriting methods or the gemspec. AllCops: - DisabledByDefault: true NewCops: disable SuggestExtensions: false TargetRubyVersion: 3.2 Exclude: - - 'test/test_proxy_headers.rb' - 'vendor/**/*' + - 'test/test_proxy_headers.rb' -Lint: - Enabled: true - -Security: - Enabled: true +Metrics: + Enabled: false -Layout/TrailingWhitespace: - Enabled: true +Gemspec/OrderedDependencies: + Enabled: false -Style/FrozenStringLiteralComment: - Enabled: true - EnforcedStyle: always +Style/StringLiterals: + EnforcedStyle: single_quotes diff --git a/DEFERRED.md b/DEFERRED.md deleted file mode 100644 index ec0f128..0000000 --- a/DEFERRED.md +++ /dev/null @@ -1,19 +0,0 @@ -# Deferred / not fully supported - -## Mechanize - -**Status:** Not implemented. - -[Mechanize](https://github.com/sparklemotion/mechanize) uses [net-http-persistent](https://github.com/drbrain/net-http-persistent), which maintains its own connection layer on top of `Net::HTTP`. Our prepend patch targets `Net::HTTP#connect` on instances Mechanize creates, but verifying header propagation and lifecycle across the persistent pool needs dedicated work. - -**Workaround:** Use patched `Net::HTTP` or Faraday for fetches; use Mechanize only when custom CONNECT headers are not required. - ---- - -## Excon — reading CONNECT response headers - -**Status:** Sending extra CONNECT headers is supported upstream via `:ssl_proxy_headers`. - -Excon’s public `Excon::Response` for the **origin** request does **not** include headers from the proxy’s `CONNECT` response (only the tunneled HTTPS response headers). Capturing `X-ProxyMesh-IP` from CONNECT would require patching Excon internals or a fork. - -**Workaround:** Use Net::HTTP / Faraday integrations in this gem, which merge CONNECT headers into the client response where applicable. diff --git a/IMPLEMENTATION_PRIORITY.md b/IMPLEMENTATION_PRIORITY.md deleted file mode 100644 index b0cdec6..0000000 --- a/IMPLEMENTATION_PRIORITY.md +++ /dev/null @@ -1,72 +0,0 @@ -# ruby-proxy-headers — implementation plan - -Prioritized roadmap for extension modules, aligned with [javascript-proxy-headers](https://github.com/proxymesh/javascript-proxy-headers) and [python-proxy-headers](https://github.com/proxymesh/python-proxy-headers). - -## Architecture - -``` -┌─────────────────────────────────────────────────────────────┐ -│ ruby-proxy-headers │ -├─────────────────────────────────────────────────────────────┤ -│ Faraday / HTTParty / Excon helpers │ -│ │ │ -│ ▼ │ -│ Net::HTTP patch — CONNECT send + capture + thread-local │ -└─────────────────────────────────────────────────────────────┘ -``` - -## Phase 1 — Net::HTTP core (**done — v0.1+**) - -- `RubyProxyHeaders::NetHTTP.patch!` extends `Net::HTTP#connect` for HTTPS + proxy. -- `last_proxy_connect_response_headers` on the `Net::HTTP` instance. -- `Thread.current[:ruby_proxy_headers_connect_headers]` + `RubyProxyHeaders.proxy_connect_response_headers` for cross-library reads. - -**File:** `lib/ruby_proxy_headers/net_http.rb` - ---- - -## Phase 2 — Faraday (**done — v0.2+**) - -- Adapter `ruby_proxy_headers_net_http` (subclass of `Faraday::Adapter::NetHttp`) merges CONNECT response headers into Faraday response headers. -- Helper `RubyProxyHeaders::FaradayIntegration.connection(...)`. - -**File:** `lib/ruby_proxy_headers/faraday.rb` - ---- - -## Phase 3 — HTTParty (**done — v0.2+**) - -- `RubyProxyHeaders::ProxyHeadersConnectionAdapter` — pass `proxy_connect_request_headers` in HTTParty options. - -**File:** `lib/ruby_proxy_headers/httparty.rb` - ---- - -## Phase 4 — Typhoeus / Ethon - -Ethon 0.19 exposes `:proxyheader` and `:headeropt`. `RubyProxyHeaders::Typhoeus` sends proxy headers only to the proxy and reads the CONNECT response from the first header block. See [docs/typhoeus.md](docs/typhoeus.md). - ---- - -## Phase 5 — Excon (**partial — v0.2+**) - -- **Sending** extra CONNECT headers: supported upstream via `:ssl_proxy_headers`; `RubyProxyHeaders::ExconIntegration.get` passes them through. -- **Reading** CONNECT response headers: not exposed on `Excon::Response` for the tunneled request. See [DEFERRED.md](DEFERRED.md). - -**File:** `lib/ruby_proxy_headers/excon.rb` - ---- - -## Phase 6 — Mechanize (**deferred**) - -Uses `net-http-persistent`; needs dedicated integration. See [DEFERRED.md](DEFERRED.md). - ---- - -## Testing - -`bundle exec ruby test/test_proxy_headers.rb` with `PROXY_URL` set. Modules: `net_http`, `faraday`, `httparty`, `excon` (excon is a smoke test; CONNECT response headers are not asserted). - ---- - -*Updated: March 2026* diff --git a/LIBRARY_RESEARCH.md b/LIBRARY_RESEARCH.md deleted file mode 100644 index c95a70a..0000000 --- a/LIBRARY_RESEARCH.md +++ /dev/null @@ -1,71 +0,0 @@ -# Ruby library proxy header support (CONNECT tunnel) - -This document analyzes the Ruby HTTP / scraping stack used in [proxy-examples](https://github.com/proxymesh/proxy-examples/tree/main/ruby) for **custom headers on HTTPS `CONNECT`** and **reading the proxy `CONNECT` response headers**. - -## Executive summary - -| Library | Native CONNECT header API | Extension approach | -|---------|---------------------------|---------------------| -| **Net::HTTP** (stdlib) | No — tunnel is hard-coded in `#connect` | **Implemented:** prepend patch; optional `proxy_connect_request_headers`; `last_proxy_connect_response_headers` | -| **Faraday** | No — delegates to adapters (`net_http`, etc.) | **High:** use patched `Net::HTTP` with `Faraday.new(connection_options)` or custom adapter that sets `proxy_connect_request_headers` | -| **HTTParty** | No — built on `Net::HTTP` | **High:** global or per-class `Net::HTTP` instances after `patch!`; or subclass `Connection` if needed | -| **Mechanize** | No — uses `Net::HTTP` / persistent connections internally | **Medium–high:** ensure Mechanize’s internal HTTP object gets the same patched behavior and header accessors | -| **Excon** | **Send:** yes — `:ssl_proxy_headers` on connection. **Read CONNECT response:** not exposed on origin `Excon::Response` | **Partial:** use `:ssl_proxy_headers` for sends; reading `X-ProxyMesh-IP` from CONNECT needs upstream Excon changes (see [DEFERRED.md](DEFERRED.md)) | -| **Typhoeus / Ethon** | Yes, via `:proxyheader` and `:headeropt` on Ethon >= 0.19.1 | Send proxy headers only to the proxy and read `X-ProxyMesh-IP` from the CONNECT header block | -| **Nokogiri** | N/A (XML/HTML parser only) | **N/A** — proxying is whatever HTTP client fetches the document (usually `Net::HTTP`) | - -Net::HTTP, Faraday, and HTTParty still need a patch below the client. Typhoeus 1.7 can send proxy headers through libcurl, and Excon can send them with `:ssl_proxy_headers`. Reading the CONNECT response is implemented for the Net::HTTP patch and for Typhoeus; Excon does not expose it. - -## Connection flow (HTTPS over HTTP proxy) - -``` -Client -- CONNECT + custom headers --> Proxy -Client <-- CONNECT response headers --- Proxy -Client === TLS tunnel =================> Origin -``` - -## Net::HTTP (stdlib) - -MRI implements the tunnel in `Net::HTTP#connect` (see `net/http.rb`): it writes `CONNECT host:port`, `Host`, optional `Proxy-Authorization`, then reads the response with `Net::HTTPResponse.read_new` and calls `#value` without exposing headers to callers. - -**Feasibility:** High — same pattern as Python’s `HTTPSConnection._tunnel` override in `python-proxy-headers`. - -## Faraday - -Uses adapters; default `net_http` adapter constructs `Net::HTTP`. If `Net::HTTP` is patched and exposes `proxy_connect_request_headers`, Faraday can pass options through `connection` / `request` options in a thin wrapper. - -**Feasibility:** High once `Net::HTTP` support is stable. - -## HTTParty - -Uses `Net::HTTP` under the hood for sync requests. After `RubyProxyHeaders::NetHTTP.patch!`, new `Net::HTTP` objects support the new accessors. - -**Feasibility:** High — may need documented patterns for `default_options` and connection lifecycle. - -## Mechanize - -Builds on `net/http` (often `net-http-persistent`). May require verifying that the patched `connect` runs for its connections and that response/header capture is visible on the right object. - -**Feasibility:** Medium. - -## Excon - -Own implementation of proxy and TLS; does not use `Net::HTTP#connect`. - -**Feasibility:** Medium — requires a dedicated Excon middleware or socket layer similar to the JavaScript core agent. - -## Typhoeus / Ethon (libcurl) - -Ethon 0.19 maps `CURLOPT_PROXYHEADER` to `:proxyheader` and `CURLOPT_HEADEROPT` to `:headeropt`. With `:separate`, proxy headers stay on the proxy request. libcurl includes the CONNECT response as the first header block when `CURLOPT_SUPPRESS_CONNECT_HEADERS` is left off. `RubyProxyHeaders::Typhoeus` uses that path. Header meanings for ProxyMesh are documented at . - -**Feasibility:** Done for Typhoeus 1.7 / Ethon >= 0.19.1. - -## Nokogiri - -Parsing only; no network layer. - -**Feasibility:** N/A — combine with `Net::HTTP` + patch or another extended client. - ---- - -*Last updated: November 2026* diff --git a/MARKETING_PLAN.md b/MARKETING_PLAN.md deleted file mode 100644 index 62c7f26..0000000 --- a/MARKETING_PLAN.md +++ /dev/null @@ -1,194 +0,0 @@ -# Marketing Plan for ruby-proxy-headers (2026 Refresh) - -This document restores and updates the project marketing plan with current Ruby ecosystem priorities, newer library positioning, and additional growth ideas. - -## Positioning - -`ruby-proxy-headers` helps Ruby teams send and read custom proxy headers during HTTPS `CONNECT` tunneling, with practical support for: - -- `Net::HTTP` (core patch/integration) -- `Faraday` (via net-http adapter path) -- `HTTParty` (via Net::HTTP adapter) -- `Excon` (send-side CONNECT headers; response-header caveat documented) - -Primary user segments: - -1. Web scraping teams that need geotargeting and sticky sessions. -2. API integrators using managed proxies in Ruby apps. -3. Platform/tooling engineers building shared HTTP clients in Rails services. - -## Ecosystem and "Newer Libraries" Angle - -Use compatibility language that matches modern Ruby stacks: - -- Ruby 3.x-first messaging (especially 3.1-3.3 usage in CI/docs when possible). -- Faraday 2.x usage examples (most teams are now on 2.x). -- HTTParty recent usage patterns with explicit proxy options. -- Net::HTTP as the baseline for any library that delegates to it. - -Keep the messaging accurate: this project should market implemented integrations clearly and avoid claiming unsupported adapters until shipped. - -## Core Messaging Pillars - -1. **Control proxy routing at CONNECT time** - Set country/session/IP directives via proxy headers. -2. **Observe what proxy assigned** - Capture proxy CONNECT response headers for debugging and sticky-session workflows. -3. **Works with mainstream Ruby HTTP workflows** - Net::HTTP, Faraday, HTTParty, and Excon send-side support. -4. **Practical, production-oriented docs** - Copy/paste examples, troubleshooting steps, and live integration tests. - -## Distribution Channels - -## 1) Package and Registry Presence - -- Publish and maintain on RubyGems (`ruby_proxy_headers`). -- Ensure gem metadata is complete: homepage, source code URI, changelog URI, bug tracker URI. -- Keep release cadence visible with changelog updates and GitHub releases. - -## 2) GitHub Discoverability - -- Repository topics: - - `ruby`, `proxy`, `https`, `connect`, `faraday`, `httparty`, `net-http`, `web-scraping` -- Repository description should include: "custom proxy headers", "HTTPS CONNECT", and supported libraries. -- Add issue templates for: - - New integration request - - Proxy compatibility report - - Bug report with minimal reproducible example - -## 3) Documentation Footprint - -- Keep README short and task-oriented; move detail to `docs/`. -- Add/refresh: - - Compatibility matrix by Ruby version and library family. - - "Choose your integration" page for Net::HTTP vs Faraday vs HTTParty vs Excon. - - Troubleshooting page for CONNECT header visibility limitations. - -## 4) Community Placement - -- Submit to curated lists: - - Awesome Ruby (HTTP/tooling sections) - - Awesome Web Scraping (Ruby networking/proxy sections) -- Share launch/update posts in: - - Ruby subreddit - - Web scraping communities - - Ruby Discord/Slack groups - -## 5) Maintainer and Partner Outreach - -- Open documentation PRs/issues on related libraries where appropriate. -- Reach out to proxy providers (including ProxyMesh ecosystem references) for potential "community integrations" listing. -- Cross-link with sibling repos: - - `python-proxy-headers` - - `javascript-proxy-headers` - - `proxy-examples` - -## New Growth Ideas (2026) - -## 1) "Recipes" Content Series - -Create short practical recipes and publish in repo docs + blog: - -- "Rotate country per request in Faraday" -- "Sticky IP sessions with HTTParty" -- "Debug CONNECT handshake in Net::HTTP" -- "Excon send-only CONNECT headers: what to expect" - -## 2) CI-Verified Example Matrix - -Add tiny runnable examples per integration with CI smoke checks. -Marketing value: "all examples are tested on every push." - -## 3) Migration Guides - -Publish "from ad-hoc proxy monkey patch to ruby-proxy-headers" guide: - -- Before/after snippets -- risk reduction talking points -- observability improvements - -## 4) Benchmark + Reliability Notes - -Provide lightweight benchmark docs (not hype): - -- baseline Net::HTTP vs patched path overhead -- expected overhead statements with reproducible script - -## 5) AI/LLM Discovery Optimization - -Many developers now ask coding assistants first. -Improve machine-readable discoverability: - -- FAQ section with direct Q/A phrasing. -- "How do I send CONNECT headers in Ruby?" exact-match wording in README/docs. -- Keep examples minimal and copy/paste ready. - -## 6) Integration Request Funnel - -Add a public roadmap issue for new adapters and let users vote with reactions. -This converts interest into visible demand signals and prioritization data. - -## 90-Day Execution Plan - -### Days 1-15 (Foundation) - -- Restore and update marketing plan (this document). -- Refresh README positioning for current supported integrations. -- Confirm gem metadata and repository topics. -- Prepare 2 recipe docs with runnable examples. - -### Days 16-45 (Visibility) - -- Publish gem update + GitHub release notes. -- Submit 2-3 awesome-list/documentation PRs. -- Publish one technical post (CONNECT headers in Ruby, practical guide). -- Share to Ruby/web-scraping communities. - -### Days 46-90 (Compounding) - -- Add CI-verified example matrix badge/workflow. -- Publish migration guide and troubleshooting deep dive. -- Launch integration-request roadmap issue. -- Track inbound issues/stars/download trend and adjust messaging. - -## KPIs and Targets - -Track monthly: - -- RubyGems downloads (total + monthly delta) -- GitHub stars/forks/watchers -- Docs page views (README + docs pages) -- Referral sources (awesome lists, social, direct) -- Community conversion: - - issue reports from new users - - successful integration confirmations - -Suggested 6-month directional goals: - -- 5k+ cumulative downloads -- 100+ GitHub stars -- 3-5 meaningful external references (listings, docs links, articles) - -## Immediate Action Checklist - -Actions that can be done directly in repo/GitHub: - -1. Keep `MARKETING_PLAN.md` current each release cycle. -2. Add or verify repository topics and concise description. -3. Create docs pages for compatibility matrix and recipes. -4. Add issue templates for integration requests and compatibility reports. -5. Publish release notes that mention supported libraries and caveats. - -Human-led actions: - -1. Community posting and engagement. -2. Maintainer outreach conversations. -3. Blog/newsletter placements. - -## Suggested Outreach Blurb - -Use this short form for PR descriptions, posts, or issues: - -> ruby-proxy-headers adds practical support for sending and reading custom proxy headers during HTTPS CONNECT in Ruby workflows (Net::HTTP, Faraday, HTTParty, Excon send-side). Useful for geotargeting, sticky sessions, and proxy observability with providers like ProxyMesh. - diff --git a/README.md b/README.md index ee5dd60..a43402a 100644 --- a/README.md +++ b/README.md @@ -1,23 +1,41 @@ -[![Gem Version](https://badge.fury.io/rb/ruby-proxy-headers.svg)](https://badge.fury.io/rb/ruby-proxy-headers) # Ruby Proxy Headers -Send and receive custom proxy headers during HTTPS `CONNECT` tunneling in modern Ruby HTTP workflows (for example [ProxyMesh](https://proxymesh.com) `X-ProxyMesh-IP` / `X-ProxyMesh-Country`). +[![Gem Version](https://badge.fury.io/rb/ruby-proxy-headers.svg)](https://badge.fury.io/rb/ruby-proxy-headers) + +Send custom **proxy headers** on HTTPS CONNECT and read **proxy response headers** back in Ruby HTTP clients. Works with any proxy provider; works best with ProxyMesh. -## The problem +## The Problem Most Ruby HTTP clients use `Net::HTTP`, Faraday, or libcurl without exposing: -1. Extra headers on the `CONNECT` request to the proxy. -2. Headers from the proxy’s `CONNECT` response (often discarded after the tunnel is established). +1. Custom **proxy headers** on the `CONNECT` request to the proxy. +2. The **proxy response headers** from the CONNECT request (often discarded after the tunnel is established). This library adds opt-in support for **Net::HTTP**, **Faraday** (2.x via `faraday-net_http`), **HTTParty**, and documents **Excon**’s built-in `:ssl_proxy_headers` for sends. -## Why teams use this +### Why teams use this - **Geo-targeting at tunnel setup**: Send country/session directives on `CONNECT`. - **Sticky-session observability**: Read proxy-assigned headers like `X-ProxyMesh-IP`. - **Works with common Ruby stacks**: Useful for scraping and API clients using Net::HTTP-based flows. +## Supported Libraries + +Integration coverage at a glance: + +| Client | Proxy headers on CONNECT | Proxy response headers | +|--------|--------------------------|-------------------------| +| Net::HTTP | Yes | Yes | +| Faraday (2.x + `faraday-net_http`) | Yes | Yes | +| HTTParty | Yes | Yes (thread-local or adapter) | +| HTTP.rb | Yes | Yes | +| RestClient | Yes | Yes | +| Typhoeus | Yes | Yes | +| Excon | Yes (send-only) | No — CONNECT response not exposed on the origin response | +| Mechanize | Not supported | Not supported | + +**Mechanize** uses [net-http-persistent](https://github.com/drbrain/net-http-persistent); this gem does not integrate it. Use patched **Net::HTTP** or **Faraday** when custom CONNECT headers are required. + ## Installation ```bash @@ -32,7 +50,11 @@ gem 'ruby-proxy-headers' The `Net::HTTP` patch is pure Ruby. Install **faraday**, **faraday-net_http**, **httparty**, and/or **excon** when you use those integrations. -## Net::HTTP +## Quick Start + +Examples for each supported client: + +### Net::HTTP ```ruby require 'uri' @@ -55,9 +77,9 @@ puts res.body puts http.last_proxy_connect_response_headers['X-ProxyMesh-IP'] ``` -Call `RubyProxyHeaders::NetHTTP.patch!` once before creating connections. You can also read the last CONNECT response headers on the current thread via `RubyProxyHeaders.proxy_connect_response_headers`. +Call `RubyProxyHeaders::NetHTTP.patch!` once before creating connections. You can also read the **proxy response headers** from the last proxied HTTPS request on the current thread via `RubyProxyHeaders.proxy_connect_response_headers`. -## Faraday +### Faraday ```ruby require 'ruby_proxy_headers/faraday' @@ -70,9 +92,9 @@ res = conn.get('https://api.ipify.org?format=json') puts res.headers['X-ProxyMesh-IP'] ``` -Uses the registered adapter `:ruby_proxy_headers_net_http`, which merges proxy `CONNECT` response headers into Faraday’s response headers. +Uses the registered adapter `:ruby_proxy_headers_net_http`, which merges **proxy response headers** from the CONNECT request into Faraday’s response headers. -## HTTParty +### HTTParty ```ruby require 'httparty' @@ -94,7 +116,7 @@ HTTParty.get( puts RubyProxyHeaders.proxy_connect_response_headers['X-ProxyMesh-IP'] ``` -## HTTP.rb +### HTTP.rb Requires the `http` gem 6 or newer. Proxy headers are sent on CONNECT by HTTP.rb itself. @@ -109,7 +131,7 @@ response = client.get('https://api.ipify.org?format=json') puts response.proxy_response_headers['X-ProxyMesh-IP'] ``` -## RestClient +### RestClient RestClient performs the request. The Net::HTTP patch adds the CONNECT headers. @@ -124,7 +146,7 @@ response = RubyProxyHeaders::RestClient.get( puts response.proxy_response_headers['X-ProxyMesh-IP'] ``` -## Typhoeus +### 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 . @@ -141,9 +163,9 @@ puts response.proxy_response_headers['X-ProxyMesh-IP'] `response.headers` remains the origin response. -## Excon (send-only; CONNECT response headers) +### Excon (send-only; CONNECT response headers) -Excon supports **sending** extra headers on CONNECT with `:ssl_proxy_headers`. Reading `X-ProxyMesh-IP` from the CONNECT response is **not** exposed on the origin response object — see [DEFERRED.md](DEFERRED.md). +Excon supports **sending** extra headers on CONNECT with `:ssl_proxy_headers`. Reading `X-ProxyMesh-IP` from the CONNECT response is **not** exposed on the origin response object. ```ruby require 'ruby_proxy_headers/excon' @@ -155,13 +177,13 @@ RubyProxyHeaders::ExconIntegration.get( ) ``` -## Testing (live proxy) +## Testing Same environment variables as [python-proxy-headers](https://github.com/proxymesh/python-proxy-headers): | Variable | Role | |----------|------| -| `PROXY_URL` | Proxy URL (required for tests) | +| `PROXY_URL` | Proxy URL (required for live tests) | | `TEST_URL` | Target HTTPS URL (default `https://api.ipify.org?format=json`) | | `PROXY_HEADER` | Header to read from CONNECT response (default `X-ProxyMesh-IP`) | | `SEND_PROXY_HEADER` | Optional header name to send on `CONNECT` | @@ -174,8 +196,31 @@ export PROXY_URL=http://user:pass@proxy.example.com:31280 bundle exec ruby test/test_proxy_headers.rb -v ``` -## Related +Unit and integration tests do not need a proxy: + +```bash +bundle exec rspec +``` + +## Documentation + +API reference and runnable examples: + +- [ruby-proxy-headers on Read the Docs](https://ruby-proxy-headers.readthedocs.io/) +- [proxy-examples (Ruby)](https://github.com/proxymesh/proxy-examples/tree/main/ruby) + +## Other languages + +Sibling header libraries for other runtimes: - [python-proxy-headers](https://github.com/proxymesh/python-proxy-headers) - [javascript-proxy-headers](https://github.com/proxymesh/javascript-proxy-headers) -- [proxy-examples (Ruby)](https://github.com/proxymesh/proxy-examples/tree/main/ruby) +- [scrapy-proxy-headers](https://github.com/proxymesh/scrapy-proxy-headers) + +## Why ProxyMesh + +[ProxyMesh](https://proxymesh.com) created this library to help customers use custom headers to control proxy behavior, as documented at [docs.proxymesh.com](https://docs.proxymesh.com/). It works with any proxy that supports custom headers on CONNECT. + +## License + +MIT License diff --git a/docs/excon.md b/docs/excon.md index 796c845..c125400 100644 --- a/docs/excon.md +++ b/docs/excon.md @@ -2,7 +2,7 @@ [Excon](https://github.com/excon/excon) already sends extra CONNECT headers as `:ssl_proxy_headers`. `RubyProxyHeaders::ExconIntegration.get` passes them through. -Excon does not expose the CONNECT response on the origin response, so `X-ProxyMesh-IP` is not readable from this client. See [DEFERRED.md](../DEFERRED.md). +Excon does not expose the CONNECT response on the origin response, so `X-ProxyMesh-IP` is not readable from this client. ## Installation diff --git a/lib/ruby_proxy_headers.rb b/lib/ruby_proxy_headers.rb index d6c1dfe..267bab1 100644 --- a/lib/ruby_proxy_headers.rb +++ b/lib/ruby_proxy_headers.rb @@ -3,8 +3,11 @@ require_relative 'ruby_proxy_headers/version' require_relative 'ruby_proxy_headers/net_http' +# Helpers for sending custom proxy headers on HTTPS CONNECT and reading proxy response headers back. module RubyProxyHeaders + # Rejects proxy header names that contain CR, LF, or NUL (header injection). INVALID_HEADER_NAME_RE = /[\r\n\0]/ + # Rejects proxy header values that contain CR, LF, or NUL (header injection). INVALID_HEADER_VALUE_RE = /[\r\n\0]/ # HTTP header map with case-insensitive lookup. Names are stored downcased, @@ -12,18 +15,22 @@ module RubyProxyHeaders # read the same value. +[]+, +[]=+, +fetch+, +delete+, and +key?+ normalize # names. Other Hash methods still use the stored downcased key. class HeaderMap < Hash + # Case-insensitive lookup for a proxy response header name. def [](key) super(normalize(key)) end + # Stores a proxy response header under a normalized (downcased) name. def []=(key, value) super(normalize(key), value) end + # Fetches a proxy response header value with optional default, using case-insensitive names. def fetch(key, *args, &block) super(normalize(key), *args, &block) end + # Removes a proxy response header by case-insensitive name. def delete(key) super(normalize(key)) end @@ -50,9 +57,9 @@ def self.validate_header!(name, value) if INVALID_HEADER_NAME_RE.match?(name.to_s) raise ArgumentError, "proxy CONNECT header name contains invalid characters (CR, LF, or NUL): #{name.inspect}" end - if INVALID_HEADER_VALUE_RE.match?(value.to_s) - raise ArgumentError, "proxy CONNECT header value contains invalid characters (CR, LF, or NUL): #{value.inspect}" - end + return unless INVALID_HEADER_VALUE_RE.match?(value.to_s) + + raise ArgumentError, "proxy CONNECT header value contains invalid characters (CR, LF, or NUL): #{value.inspect}" end # Raises ArgumentError if +host+ or +port+ contain CR, LF, or NUL bytes that @@ -62,9 +69,9 @@ def self.validate_connect_target!(host, port) raise ArgumentError, "CONNECT target host contains invalid characters (CR, LF, or NUL): #{host.inspect}" end - if INVALID_HEADER_VALUE_RE.match?(port.to_s) - raise ArgumentError, - "CONNECT target port contains invalid characters (CR, LF, or NUL): #{port.inspect}" - end + return unless INVALID_HEADER_VALUE_RE.match?(port.to_s) + + raise ArgumentError, + "CONNECT target port contains invalid characters (CR, LF, or NUL): #{port.inspect}" end end diff --git a/lib/ruby_proxy_headers/connection.rb b/lib/ruby_proxy_headers/connection.rb index 20c2cf7..66d5f9e 100644 --- a/lib/ruby_proxy_headers/connection.rb +++ b/lib/ruby_proxy_headers/connection.rb @@ -94,7 +94,7 @@ def read_connect_response break if line.nil? response << line - break if line == "\r\n" || line == "\n" + break if ["\r\n", "\n"].include?(line) end response end @@ -114,11 +114,12 @@ def parse_connect_response(response) lines.each do |line| break if line.empty? - if (header_match = line.match(/^([^:]+):\s*(.*)$/)) - name = header_match[1].downcase - value = header_match[2] - @proxy_response_headers[name] = value - end + header_match = line.match(/^([^:]+):\s*(.*)$/) + next unless header_match + + name = header_match[1].downcase + value = header_match[2] + @proxy_response_headers[name] = value end end @@ -141,7 +142,7 @@ def validate_connect_target!(host, port) def raise_connect_error case @proxy_response_status when 407 - raise ProxyAuthenticationError, "Proxy authentication required (407)" + raise ProxyAuthenticationError, 'Proxy authentication required (407)' else raise ConnectError, "Proxy CONNECT failed with status #{@proxy_response_status}" end diff --git a/lib/ruby_proxy_headers/excon.rb b/lib/ruby_proxy_headers/excon.rb index 3e724e6..1cbbd93 100644 --- a/lib/ruby_proxy_headers/excon.rb +++ b/lib/ruby_proxy_headers/excon.rb @@ -28,9 +28,10 @@ def get(url, proxy_url:, proxy_connect_headers: nil, **excon_opts) Excon.get(url, opts) end + # Ensures +proxy_url+ has an explicit scheme so Excon accepts it as a proxy URI. def normalize_proxy_url(proxy_url) s = proxy_url.to_s.strip - return s if s.match?(/\A[a-z][a-z0-9+\-.]*:\/\//i) + return s if s.match?(%r{\A[a-z][a-z0-9+\-.]*://}i) "http://#{s}" end diff --git a/lib/ruby_proxy_headers/faraday.rb b/lib/ruby_proxy_headers/faraday.rb index e4820aa..7744134 100644 --- a/lib/ruby_proxy_headers/faraday.rb +++ b/lib/ruby_proxy_headers/faraday.rb @@ -21,10 +21,12 @@ module RubyProxyHeaders module FaradayAdapter # Copies CONNECT response headers onto the Faraday response. class NetHttp < ::Faraday::Adapter::NetHttp + # Remembers the Net::HTTP instance so CONNECT proxy response headers can be merged later. def build_connection(env) super.tap { |http| Thread.current[:ruby_proxy_headers_faraday_http] = http } end + # Merges last proxy CONNECT response headers into the Faraday response when present. def call(env) response = super http = Thread.current[:ruby_proxy_headers_faraday_http] @@ -49,9 +51,11 @@ def call(env) ) module RubyProxyHeaders + # Faraday helpers that register the custom Net::HTTP adapter for proxy headers and CONNECT responses. module FaradayIntegration module_function + # Applies the Net::HTTP patch required for proxy headers on CONNECT. def patch! RubyProxyHeaders::NetHTTP.patch! end diff --git a/lib/ruby_proxy_headers/http_gem.rb b/lib/ruby_proxy_headers/http_gem.rb index 00a3f4c..a31fd57 100644 --- a/lib/ruby_proxy_headers/http_gem.rb +++ b/lib/ruby_proxy_headers/http_gem.rb @@ -24,14 +24,17 @@ module RubyProxyHeaders # response = client.get('https://example.com') # puts response.proxy_response_headers['X-ProxyMesh-IP'] module HTTPGem + # Builds a {ProxyClient} that sends proxy headers on CONNECT and exposes proxy response headers. def self.create_client(proxy:, proxy_headers: {}, **options) ProxyClient.new(proxy: proxy, proxy_headers: proxy_headers, **options) end + # GET via a one-off {ProxyClient}. def self.get(url, proxy:, proxy_headers: {}, **options) create_client(proxy: proxy, proxy_headers: proxy_headers).get(url, **options) end + # POST via a one-off {ProxyClient}. def self.post(url, proxy:, proxy_headers: {}, body: nil, **options) create_client(proxy: proxy, proxy_headers: proxy_headers).post(url, body: body, **options) end @@ -40,6 +43,7 @@ def self.post(url, proxy:, proxy_headers: {}, body: nil, **options) class ProxyClient attr_reader :last_proxy_response_headers + # Option keys accepted by {ProxyClient} request methods besides proxy settings. REQUEST_OPTIONS = %i[open_timeout read_timeout headers body verify_ssl].freeze def initialize(proxy:, proxy_headers: {}, **options) @@ -48,18 +52,22 @@ def initialize(proxy:, proxy_headers: {}, **options) @default_options = options end + # Issues a GET through the proxy with optional proxy headers on CONNECT. def get(url, **options) request(:get, url, **options) end + # Issues a POST through the proxy with optional proxy headers on CONNECT. def post(url, body: nil, **options) request(:post, url, body: body, **options) end + # Issues a PUT through the proxy with optional proxy headers on CONNECT. def put(url, body: nil, **options) request(:put, url, body: body, **options) end + # Issues a DELETE through the proxy with optional proxy headers on CONNECT. def delete(url, **options) request(:delete, url, **options) end diff --git a/lib/ruby_proxy_headers/httparty.rb b/lib/ruby_proxy_headers/httparty.rb index 3cf1996..cf99550 100644 --- a/lib/ruby_proxy_headers/httparty.rb +++ b/lib/ruby_proxy_headers/httparty.rb @@ -15,6 +15,7 @@ module RubyProxyHeaders # After the request, read CONNECT response headers via # {RubyProxyHeaders.proxy_connect_response_headers} (thread-local). class ProxyHeadersConnectionAdapter < HTTParty::ConnectionAdapter + # Builds Net::HTTP and applies proxy CONNECT request headers from HTTParty options. def connection http = super if http.respond_to?(:proxy_connect_request_headers=) diff --git a/lib/ruby_proxy_headers/net_http.rb b/lib/ruby_proxy_headers/net_http.rb index 8a80035..e5e1c4b 100644 --- a/lib/ruby_proxy_headers/net_http.rb +++ b/lib/ruby_proxy_headers/net_http.rb @@ -9,7 +9,7 @@ module RubyProxyHeaders # Patches Net::HTTP so an HTTPS request through a proxy can send extra CONNECT - # headers and keep the proxy's CONNECT response. + # headers and capture proxy response headers from CONNECT. # # 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+). @@ -39,6 +39,7 @@ def self.inject_connect_headers(buf, headers) # Rewrites a CONNECT write while a patched connection is opening. module ConnectRequestWrite + # Injects configured proxy headers into the CONNECT request bytes Net::HTTP writes. def write(*strs) http = Thread.current[:ruby_proxy_headers_active_http] if http && strs.first.start_with?('CONNECT ') @@ -56,6 +57,7 @@ def write(*strs) # Records CONNECT response headers. Active only while #connect is running, # so the later origin response is left alone. module ConnectResponseRead + # Captures proxy response headers from the CONNECT response while the tunnel opens. def read_new(sock) response = super http = Thread.current[:ruby_proxy_headers_active_http] @@ -73,6 +75,7 @@ def read_new(sock) module Extension attr_accessor :proxy_connect_request_headers, :last_proxy_connect_response_headers + # Opens an HTTPS tunnel through the proxy, validating targets and recording proxy response headers. def connect return super unless use_ssl? && proxy? @@ -100,6 +103,7 @@ def connect end class << self + # Installs CONNECT hooks on Net::HTTP, BufferedIO, and the response parser (idempotent). def patch! ::Net::HTTP.prepend(Extension) unless ::Net::HTTP.ancestors.include?(Extension) io_hooked = ::Net::BufferedIO.ancestors.include?(ConnectRequestWrite) diff --git a/lib/ruby_proxy_headers/rest_client.rb b/lib/ruby_proxy_headers/rest_client.rb index 6c9e803..19cce7f 100644 --- a/lib/ruby_proxy_headers/rest_client.rb +++ b/lib/ruby_proxy_headers/rest_client.rb @@ -26,6 +26,7 @@ module RubyProxyHeaders module RestClient # Sets CONNECT headers on the Net::HTTP object RestClient is about to use. module NetHttpHook + # Applies thread-local proxy CONNECT headers to the Net::HTTP instance RestClient will use. def net_http_object(hostname, port) http = super headers = Thread.current[:ruby_proxy_headers_rest_client_headers] @@ -35,22 +36,27 @@ def net_http_object(hostname, port) end class << self + # GET through a proxy, returning proxy response headers from CONNECT when HTTPS. def get(url, proxy:, proxy_headers: {}, **options) request(:get, url, proxy: proxy, proxy_headers: proxy_headers, **options) end + # POST through a proxy, returning proxy response headers from CONNECT when HTTPS. def post(url, proxy:, proxy_headers: {}, payload: nil, **options) request(:post, url, proxy: proxy, proxy_headers: proxy_headers, payload: payload, **options) end + # PUT through a proxy, returning proxy response headers from CONNECT when HTTPS. def put(url, proxy:, proxy_headers: {}, payload: nil, **options) request(:put, url, proxy: proxy, proxy_headers: proxy_headers, payload: payload, **options) end + # DELETE through a proxy, returning proxy response headers from CONNECT when HTTPS. def delete(url, proxy:, proxy_headers: {}, **options) request(:delete, url, proxy: proxy, proxy_headers: proxy_headers, **options) end + # Runs an arbitrary RestClient verb through the proxy with optional proxy headers on CONNECT. def request(method, url, proxy:, proxy_headers: {}, **options) install! headers = proxy_headers || {} @@ -66,6 +72,7 @@ def request(method, url, proxy:, proxy_headers: {}, **options) Thread.current[:ruby_proxy_headers_rest_client_headers] = previous end + # Patches Net::HTTP and RestClient::Request so proxy headers apply to outbound HTTPS. def install! RubyProxyHeaders::NetHTTP.patch! return if ::RestClient::Request.ancestors.include?(NetHttpHook) diff --git a/lib/ruby_proxy_headers/typhoeus.rb b/lib/ruby_proxy_headers/typhoeus.rb index c4867c2..63c1b9c 100644 --- a/lib/ruby_proxy_headers/typhoeus.rb +++ b/lib/ruby_proxy_headers/typhoeus.rb @@ -31,17 +31,21 @@ module RubyProxyHeaders # ) # puts response.proxy_response_headers['X-ProxyMesh-IP'] module Typhoeus + # Parses the numeric status code from an HTTP status line in a CONNECT header block. HTTP_STATUS = %r{\AHTTP/\d+(?:\.\d+)?\s+(\d{3})\b}i class << self + # GET via Typhoeus with proxy headers sent only on CONNECT. def get(url, proxy:, proxy_headers: {}, **options) request(:get, url, proxy: proxy, proxy_headers: proxy_headers, **options) end + # POST via Typhoeus with proxy headers sent only on CONNECT. def post(url, proxy:, proxy_headers: {}, body: nil, **options) request(:post, url, proxy: proxy, proxy_headers: proxy_headers, body: body, **options) end + # Runs a Typhoeus request and parses proxy response headers from the CONNECT block. def request(method, url, proxy:, proxy_headers: {}, **options) typhoeus_options = options.merge(proxy: proxy, method: method) unless proxy_headers.empty? diff --git a/lib/ruby_proxy_headers/version.rb b/lib/ruby_proxy_headers/version.rb index eba79a8..355fd90 100644 --- a/lib/ruby_proxy_headers/version.rb +++ b/lib/ruby_proxy_headers/version.rb @@ -1,5 +1,6 @@ # frozen_string_literal: true module RubyProxyHeaders + # Current gem release version (see gemspec and Gemfile.lock). VERSION = '0.3.0' end diff --git a/spec/net_http_connect_target_spec.rb b/spec/net_http_connect_target_spec.rb index 2a6b93f..c349963 100644 --- a/spec/net_http_connect_target_spec.rb +++ b/spec/net_http_connect_target_spec.rb @@ -62,13 +62,11 @@ def connect!(http) port = server.addr[1] received = Queue.new thr = Thread.new do - begin - sock = Timeout.timeout(0.3) { server.accept } - received << sock.readpartial(4096) - sock.close - rescue Timeout::Error, EOFError, Errno::ECONNRESET, Errno::EAGAIN - received << :none - end + sock = Timeout.timeout(0.3) { server.accept } + received << sock.readpartial(4096) + sock.close + rescue Timeout::Error, EOFError, Errno::ECONNRESET, Errno::EAGAIN + received << :none end http = Net::HTTP.new("evil.com\r\nX-Injected: smuggled", 443, '127.0.0.1', port) diff --git a/spec/typhoeus_spec.rb b/spec/typhoeus_spec.rb index 72e1c7d..17ea1c8 100644 --- a/spec/typhoeus_spec.rb +++ b/spec/typhoeus_spec.rb @@ -114,7 +114,7 @@ def header_response(*blocks) headers: { 'X-App-Secret' => 'should-not-leak' }, ssl_verifypeer: false, ssl_verifyhost: 0, - http_version: :httpv1_1, + http_version: :httpv1_1, # rubocop:disable Naming/VariableNumber -- Typhoeus option name timeout: 5 ) end diff --git a/test/test_proxy_headers.rb b/test/test_proxy_headers.rb index dbb17fa..3084fa4 100644 --- a/test/test_proxy_headers.rb +++ b/test/test_proxy_headers.rb @@ -214,7 +214,7 @@ def test_excon(verbose:) test_url = ENV.fetch('TEST_URL', 'https://api.ipify.org?format=json') h = send_headers_from_env - # Excon does not expose CONNECT response headers on the origin response (DEFERRED.md). + # Excon does not expose CONNECT response headers on the origin response. # Smoke test: proxied GET succeeds; optional ssl_proxy_headers when SEND_* set. res = RubyProxyHeaders::ExconIntegration.get( test_url, @@ -226,7 +226,7 @@ def test_excon(verbose:) body = JSON.parse(res.body) return { ok: false, error: 'No ip in JSON body' } unless body['ip'] - msg = "#{body['ip']} (CONNECT response headers not exposed by Excon; see DEFERRED.md)" + msg = "#{body['ip']} (CONNECT response headers not exposed by Excon)" puts "[PASS] excon (smoke): #{msg}" if verbose { ok: true, value: body['ip'] } rescue JSON::ParserError => e