Skip to content
Myr

SOCKS proxy support (#2034)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Tom Christie · committed by GitHub · parent 7f0d43d · Browse files · 9 files+157 added−91 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

9 files+157 added−91 removed

  • tests:+29 added−18 removed
  • other:+128 added−73 removed

9 files+157 added−91 removed

modified:docs/advanced.md+13 added-25 removed
385 unmodified lines
386## HTTP Proxying387388HTTPX supports setting up [HTTP proxies](https://en.wikipedia.org/wiki/Proxy_server#Web_proxy_servers) via the `proxies` parameter to be passed on client initialization or top-level API functions like `httpx.get(..., proxies=...)`.389390_Note: SOCKS proxies are not supported yet._391390<div align="center">391 <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/27/Open_proxy_h2g2bob.svg/480px-Open_proxy_h2g2bob.svg.png"/>392 <figcaption><em>Diagram of how a proxy works (source: Wikipedia). The left hand side "Internet" blob may be your HTTPX client requesting <code>example.com</code> through a proxy.</em></figcaption>393</div>
168 unmodified lines
562563In general, the flow for making an HTTP request through a proxy is as follows:5645651. The client connects to the proxy (initial connection request).5681. The proxy somehow transfers data to the server on your behalf.5662. The proxy transfers data to the server on your behalf.567568How exactly step 2/ is performed depends on which of two proxying mechanisms is used:569570* **Forwarding**: the proxy makes the request for you, and sends back the response it obtained from the server.573* **Tunneling**: the proxy establishes a TCP connection to the server on your behalf, and the client reuses this connection to send the request and receive the response. This is known as an [HTTP Tunnel](https://en.wikipedia.org/wiki/HTTP_tunnel). This mechanism is how you can access websites that use HTTPS from an HTTP proxy (the client "upgrades" the connection to HTTPS by performing the TLS handshake with the server over the TCP connection provided by the proxy).571* **Tunnelling**: the proxy establishes a TCP connection to the server on your behalf, and the client reuses this connection to send the request and receive the response. This is known as an [HTTP Tunnel](https://en.wikipedia.org/wiki/HTTP_tunnel). This mechanism is how you can access websites that use HTTPS from an HTTP proxy (the client "upgrades" the connection to HTTPS by performing the TLS handshake with the server over the TCP connection provided by the proxy).572575#### Default behavior573### Troubleshooting proxies574577Given the technical definitions above, by default (and regardless of whether you're using an HTTP or HTTPS proxy), HTTPX will:575If you encounter issues when setting up proxies, please refer to our [Troubleshooting guide](troubleshooting.md#proxies).576579* Use forwarding for HTTP requests.580* Use tunneling for HTTPS requests.577## SOCKS578582This ensures that you can make HTTP and HTTPS requests in all cases (i.e. regardless of which type of proxy you're using).579In addition to HTTP proxies, `httpcore` also supports proxies using the SOCKS protocol.580This is an optional feature that requires an additional third-party library be installed before use.581584#### Forcing the proxy mechanism582You can install SOCKS support using `pip`:583586In most cases, the default behavior should work just fine as well as provide enough security.584```shell585$ pip install httpx[socks]586```587588But if you know what you're doing and you want to force which mechanism to use, you can do so by passing an `httpx.Proxy()` instance, setting the `mode` to either `FORWARD_ONLY` or `TUNNEL_ONLY`. For example...588You can now configure a client to make requests via a proxy using the SOCKS protocol:589590```python591# Route all requests through an HTTPS proxy, using tunneling only.592proxies = httpx.Proxy(593 url="https://localhost:8030",594 mode="TUNNEL_ONLY",595)596597with httpx.Client(proxies=proxies) as client:598 # This HTTP request will be tunneled instead of forwarded.599 r = client.get("http://example.com")591httpx.Client(proxies='socks5://user:pass@host:port')592```593602### Troubleshooting proxies603604If you encounter issues when setting up proxies, please refer to our [Troubleshooting guide](troubleshooting.md#proxies).605594## Timeout Configuration595596HTTPX is careful to enforce timeouts everywhere by default.597
582 unmodified lines
modified:docs/index.md+5 added-1 removed
modified:httpx/_transports/default.py+76 added-31 removed
135 unmodified lines
136 uds=uds,137 local_address=local_address,138 retries=retries,139 )140 else:140 elif proxy.url.scheme in ("http", "https"):141 self._pool = httpcore.HTTPProxy(142 proxy_url=httpcore.URL(143 scheme=proxy.url.raw_scheme,144 host=proxy.url.raw_host,145 port=proxy.url.port,146 target=proxy.url.raw_path,147 ),148 proxy_auth=proxy.raw_auth,149 proxy_headers=proxy.headers.raw,150 ssl_context=ssl_context,151 max_connections=limits.max_connections,152 max_keepalive_connections=limits.max_keepalive_connections,153 keepalive_expiry=limits.keepalive_expiry,154 http1=http1,155 http2=http2,156 )157 elif proxy.url.scheme == "socks5":158 try:142 self._pool = httpcore.HTTPProxy(143 proxy_url=httpcore.URL(144 scheme=proxy.url.raw_scheme,145 host=proxy.url.raw_host,146 port=proxy.url.port,147 target=proxy.url.raw_path,148 ),149 proxy_headers=proxy.headers.raw,150 ssl_context=ssl_context,151 max_connections=limits.max_connections,152 max_keepalive_connections=limits.max_keepalive_connections,153 keepalive_expiry=limits.keepalive_expiry,154 http1=http1,155 http2=http2,156 )157 except TypeError: # pragma: nocover158 self._pool = httpcore.HTTPProxy(159 proxy_url=httpcore.URL(160 scheme=proxy.url.raw_scheme,161 host=proxy.url.raw_host,162 port=proxy.url.port,163 target=proxy.url.raw_path,164 ),165 proxy_headers=proxy.headers.raw,166 ssl_context=ssl_context,167 max_connections=limits.max_connections,168 max_keepalive_connections=limits.max_keepalive_connections,169 keepalive_expiry=limits.keepalive_expiry,170 )159 import socksio # noqa160 except ImportError: # pragma: nocover161 raise ImportError(162 "Using SOCKS proxy, but the 'socksio' package is not installed. "163 "Make sure to install httpx using `pip install httpx[socks]`."164 ) from None165166 self._pool = httpcore.SOCKSProxy(167 proxy_url=httpcore.URL(168 scheme=proxy.url.raw_scheme,169 host=proxy.url.raw_host,170 port=proxy.url.port,171 target=proxy.url.raw_path,172 ),173 proxy_auth=proxy.raw_auth,174 ssl_context=ssl_context,175 max_connections=limits.max_connections,176 max_keepalive_connections=limits.max_keepalive_connections,177 keepalive_expiry=limits.keepalive_expiry,178 http1=http1,179 http2=http2,180 )181 else: # pragma: nocover182 raise ValueError(183 f"Proxy protocol must be either 'http', 'https', or 'socks5', but got {proxy.url.scheme!r}."184 )185186 def __enter__(self: T) -> T: # Use generics for subclass support.187 self._pool.__enter__()188 return self189
81 unmodified lines
271 uds=uds,272 local_address=local_address,273 retries=retries,274 )261 else:275 elif proxy.url.scheme in ("http", "https"):276 self._pool = httpcore.AsyncHTTPProxy(277 proxy_url=httpcore.URL(278 scheme=proxy.url.raw_scheme,279 host=proxy.url.raw_host,280 port=proxy.url.port,281 target=proxy.url.raw_path,282 ),283 proxy_auth=proxy.raw_auth,284 proxy_headers=proxy.headers.raw,285 ssl_context=ssl_context,286 max_connections=limits.max_connections,287 max_keepalive_connections=limits.max_keepalive_connections,288 keepalive_expiry=limits.keepalive_expiry,289 http1=http1,290 http2=http2,291 )292 elif proxy.url.scheme == "socks5":293 try:294 import socksio # noqa295 except ImportError: # pragma: nocover296 raise ImportError(297 "Using SOCKS proxy, but the 'socksio' package is not installed. "298 "Make sure to install httpx using `pip install httpx[socks]`."299 ) from None300301 self._pool = httpcore.AsyncSOCKSProxy(302 proxy_url=httpcore.URL(303 scheme=proxy.url.raw_scheme,304 host=proxy.url.raw_host,305 port=proxy.url.port,306 target=proxy.url.raw_path,307 ),308 proxy_auth=proxy.raw_auth,309 ssl_context=ssl_context,310 max_connections=limits.max_connections,311 max_keepalive_connections=limits.max_keepalive_connections,312 keepalive_expiry=limits.keepalive_expiry,313 http1=http1,314 http2=http2,315 )316 else: # pragma: nocover317 raise ValueError(318 f"Proxy protocol must be either 'http', 'https', or 'socks5', but got {proxy.url.scheme!r}."319 )320321 async def __aenter__(self: A) -> A: # Use generics for subclass support.322 await self._pool.__aenter__()323 return self324
41 unmodified lines
modified:httpx/_config.py+27 added-14 removed
1import os2import ssl3import typing4from base64 import b64encode4from pathlib import Path56import certifi7
306 unmodified lines
314 )315316317class Proxy:319 def __init__(self, url: URLTypes, *, headers: HeaderTypes = None):318 def __init__(319 self,320 url: URLTypes,321 *,322 auth: typing.Tuple[str, str] = None,323 headers: HeaderTypes = None,324 ):325 url = URL(url)326 headers = Headers(headers)327323 if url.scheme not in ("http", "https"):328 if url.scheme not in ("http", "https", "socks5"):329 raise ValueError(f"Unknown scheme for proxy URL {url!r}")330331 if url.username or url.password:327 headers.setdefault(328 "Proxy-Authorization",329 self._build_auth_header(url.username, url.password),330 )331 # Remove userinfo from the URL authority, e.g.:332 # 'username:password@proxy_host:proxy_port' -> 'proxy_host:proxy_port'332 # Remove any auth credentials from the URL.333 auth = (url.username, url.password)334 url = url.copy_with(username=None, password=None)335336 self.url = url337 self.auth = auth338 self.headers = headers339338 def _build_auth_header(self, username: str, password: str) -> str:339 userpass = (username.encode("utf-8"), password.encode("utf-8"))340 token = b64encode(b":".join(userpass)).decode()341 return f"Basic {token}"340 @property341 def raw_auth(self) -> typing.Optional[typing.Tuple[bytes, bytes]]:342 # The proxy authentication as raw bytes.343 return (344 None345 if self.auth is None346 else (self.auth[0].encode("utf-8"), self.auth[1].encode("utf-8"))347 )348349 def __repr__(self) -> str:344 return f"Proxy(url={str(self.url)!r}, headers={dict(self.headers)!r})"350 # The authentication is represented with the password component masked.351 auth = (self.auth[0], "********") if self.auth else None352353 # Build a nice concise representation.354 url_str = f"{str(self.url)!r}"355 auth_str = f", auth={auth!r}" if auth else ""356 headers_str = f", headers={dict(self.headers)!r}" if self.headers else ""357 return f"Proxy({url_str}{auth_str}{headers_str})"358359360DEFAULT_TIMEOUT_CONFIG = Timeout(timeout=5.0)361DEFAULT_LIMITS = Limits(max_connections=100, max_keepalive_connections=20)362DEFAULT_MAX_REDIRECTS = 20
modified:tests/client/test_proxies.py+14 added
45 unmodified lines
4647 assert len(expected_proxies) == len(client._mounts)484950def test_socks_proxy():51 url = httpx.URL("http://www.example.com")5253 client = httpx.Client(proxies="socks5://localhost/")54 transport = client._transport_for_url(url)55 assert isinstance(transport, httpx.HTTPTransport)56 assert isinstance(transport._pool, httpcore.SOCKSProxy)5758 async_client = httpx.AsyncClient(proxies="socks5://localhost/")59 async_transport = async_client._transport_for_url(url)60 assert isinstance(async_transport, httpx.AsyncHTTPTransport)61 assert isinstance(async_transport._pool, httpcore.AsyncSOCKSProxy)626364PROXY_URL = "http://[::1]"656667@pytest.mark.parametrize(
219 unmodified lines
modified:tests/test_config.py+15 added-18 removed
197 unmodified lines
198199 assert context.keylog_filename is None # type: ignore200201202@pytest.mark.parametrize(203 "url,expected_url,expected_headers",204 [205 ("https://example.com", "https://example.com", {}),206 (207 "https://user:pass@example.com",208 "https://example.com",209 {"proxy-authorization": "Basic dXNlcjpwYXNz"},210 ),211 ],212)213def test_proxy_from_url(url, expected_url, expected_headers):214 proxy = httpx.Proxy(url)202def test_proxy_from_url():203 proxy = httpx.Proxy("https://example.com")204216 assert str(proxy.url) == expected_url217 assert dict(proxy.headers) == expected_headers218 assert repr(proxy) == "Proxy(url='{}', headers={})".format(219 expected_url, str(expected_headers)220 )205 assert str(proxy.url) == "https://example.com"206 assert proxy.auth is None207 assert proxy.headers == {}208 assert repr(proxy) == "Proxy('https://example.com')"209210211def test_proxy_with_auth_from_url():212 proxy = httpx.Proxy("https://username:password@example.com")213214 assert str(proxy.url) == "https://example.com"215 assert proxy.auth == ("username", "password")216 assert proxy.headers == {}217 assert repr(proxy) == "Proxy('https://example.com', auth=('username', '********'))"218219220def test_invalid_proxy_scheme():221 with pytest.raises(ValueError):222 httpx.Proxy("invalid://example.com")
modified:README.md+5 added-1 removed
127 unmodified lines
128The HTTPX project relies on these excellent libraries:129130* `httpcore` - The underlying transport implementation for `httpx`.131 * `h11` - HTTP/1.1 support.132 * `h2` - HTTP/2 support. *(Optional, with `httpx[http2]`)*132* `certifi` - SSL certificates.133* `charset_normalizer` - Charset auto-detection.134* `rfc3986` - URL parsing & normalization.135 * `idna` - Internationalized domain name support.136* `sniffio` - Async library autodetection.137138As well as these optional installs:139140* `h2` - HTTP/2 support. *(Optional, with `httpx[http2]`)*141* `socksio` - SOCKS proxy support. *(Optional, with `httpx[socks]`)*142* `rich` - Rich terminal support. *(Optional, with `httpx[cli]`)*143* `click` - Command line client support. *(Optional, with `httpx[cli]`)*144* `brotli` or `brotlicffi` - Decoding for "brotli" compressed responses. *(Optional, with `httpx[brotli]`)*145* `async_generator` - Backport support for `contextlib.asynccontextmanager`. *(Only required for Python 3.6)*
7 unmodified lines
modified:requirements.txt+1 added-1 removed
1# We're pinning our tooling, because it's an environment we can strictly control.2# On the other hand, we're not pinning package dependencies, because our tests3# needs to pass with the latest version of the packages.4# Reference: https://github.com/encode/httpx/pull/1721#discussion_r6612415885-e .[cli,http2,brotli]5-e .[brotli,cli,http2,socks]67charset-normalizer==2.0.689# Documentation
26 unmodified lines
modified:setup.py+1 added
63 unmodified lines
64 "async_generator; python_version < '3.7'"65 ],66 extras_require={67 "http2": "h2>=3,<5",68 "socks": "socksio==1.*",69 "brotli": [70 "brotli; platform_python_implementation == 'CPython'",71 "brotlicffi; platform_python_implementation != 'CPython'"72 ],
27 unmodified lines