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
Provenance
- Commit
8dc9b6b- Tree
c10cf32- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
7f0d43d
9 files changed+157 added−91 removed
modified:docs/advanced.md+13 added-25 removed
385 unmodified lines386 ## HTTP Proxying387 388 HTTPX 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=...)`.389 390-_Note: SOCKS proxies are not supported yet._391-390 <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 lines562 563 In general, the flow for making an HTTP request through a proxy is as follows:564 565 1. The client connects to the proxy (initial connection request).568-1. The proxy somehow transfers data to the server on your behalf.566+2. The proxy transfers data to the server on your behalf.567 568 How exactly step 2/ is performed depends on which of two proxying mechanisms is used:569 570 * **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).572 575-#### Default behavior573+### Troubleshooting proxies574 577-Given the technical definitions above, by default (and regardless of whether you're using an HTTP or HTTPS proxy), HTTPX will:575+If you encounter issues when setting up proxies, please refer to our [Troubleshooting guide](troubleshooting.md#proxies).576 579-* Use forwarding for HTTP requests.580-* Use tunneling for HTTPS requests.577+## SOCKS578 582-This ensures that you can make HTTP and HTTPS requests in all cases (i.e. regardless of which type of proxy you're using).579+In addition to HTTP proxies, `httpcore` also supports proxies using the SOCKS protocol.580+This is an optional feature that requires an additional third-party library be installed before use.581 584-#### Forcing the proxy mechanism582+You can install SOCKS support using `pip`:583 586-In most cases, the default behavior should work just fine as well as provide enough security.584+```shell585+$ pip install httpx[socks]586+```587 588-But 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...588+You can now configure a client to make requests via a proxy using the SOCKS protocol:589 590 ```python591-# Route all requests through an HTTPS proxy, using tunneling only.592-proxies = httpx.Proxy(593- url="https://localhost:8030",594- mode="TUNNEL_ONLY",595-)596-597-with httpx.Client(proxies=proxies) as client:598- # This HTTP request will be tunneled instead of forwarded.599- r = client.get("http://example.com")591+httpx.Client(proxies='socks5://user:pass@host:port')592 ```593 602-### Troubleshooting proxies603-604-If you encounter issues when setting up proxies, please refer to our [Troubleshooting guide](troubleshooting.md#proxies).605-594 ## Timeout Configuration595 596 HTTPX is careful to enforce timeouts everywhere by default.597 582 unmodified linesmodified:docs/index.md+5 added-1 removed
110 unmodified linesExpand all11111211311411511511611711811912012112212312412512612712828 unmodified lines110 unmodified linesExpand allThe HTTPX project relies on these excellent libraries:
* `httpcore` - The underlying transport implementation for `httpx`. * `h11` - HTTP/1.1 support. * `h2` - HTTP/2 support. *(Optional, with `httpx[http2]`)** `certifi` - SSL certificates.* `charset_normalizer` - Charset auto-detection.* `rfc3986` - URL parsing & normalization. * `idna` - Internationalized domain name support.* `sniffio` - Async library autodetection.
As well as these optional installs:
* `h2` - HTTP/2 support. *(Optional, with `httpx[http2]`)** `socksio` - SOCKS proxy support. *(Optional, with `httpx[socks]`)** `rich` - Rich terminal support. *(Optional, with `httpx[cli]`)** `click` - Command line client support. *(Optional, with `httpx[cli]`)** `brotli` or `brotlicffi` - Decoding for "brotli" compressed responses. *(Optional, with `httpx[brotli]`)** `async_generator` - Backport support for `contextlib.asynccontextmanager`. *(Only required for Python 3.6)*28 unmodified linesmodified:httpx/_transports/default.py+76 added-31 removed
135 unmodified lines136 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 None165 166+ 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+ )185+186 def __enter__(self: T) -> T: # Use generics for subclass support.187 self._pool.__enter__()188 return self189 81 unmodified lines271 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 None300 301+ 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+ )320+321 async def __aenter__(self: A) -> A: # Use generics for subclass support.322 await self._pool.__aenter__()323 return self324 41 unmodified linesmodified:httpx/_config.py+27 added-14 removed
1 import os2 import ssl3 import typing4-from base64 import b64encode4 from pathlib import Path5 6 import certifi7 306 unmodified lines314 )315 316 317 class 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)327 323- 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}")330 331 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)335 336 self.url = url337+ self.auth = auth338 self.headers = headers339 338- 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+ )348 349 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 None352 353+ # 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})"358 359+360 DEFAULT_TIMEOUT_CONFIG = Timeout(timeout=5.0)361 DEFAULT_LIMITS = Limits(max_connections=100, max_keepalive_connections=20)362 DEFAULT_MAX_REDIRECTS = 20modified:tests/client/test_proxies.py+14 added
45 unmodified lines46 47 assert len(expected_proxies) == len(client._mounts)48 49 50+def test_socks_proxy():51+ url = httpx.URL("http://www.example.com")52+53+ 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)57+58+ 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)62+63+64 PROXY_URL = "http://[::1]"65 66 67 @pytest.mark.parametrize(219 unmodified linesmodified:tests/test_config.py+15 added-18 removed
197 unmodified lines198 199 assert context.keylog_filename is None # type: ignore200 201 202-@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-)213-def test_proxy_from_url(url, expected_url, expected_headers):214- proxy = httpx.Proxy(url)202+def test_proxy_from_url():203+ proxy = httpx.Proxy("https://example.com")204 216- 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')"209 210 211+def test_proxy_with_auth_from_url():212+ proxy = httpx.Proxy("https://username:password@example.com")213+214+ 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', '********'))"218+219+220 def test_invalid_proxy_scheme():221 with pytest.raises(ValueError):222 httpx.Proxy("invalid://example.com")modified:README.md+5 added-1 removed
127 unmodified lines128 The HTTPX project relies on these excellent libraries:129 130 * `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.137+138+As well as these optional installs:139+140+* `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 linesmodified: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]6 7 charset-normalizer==2.0.68 9 # Documentation26 unmodified linesmodified:setup.py+1 added
63 unmodified lines64 "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