Skip to content
Myr

Implement HTTPProxy dispatcher (#259)

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

authored by Seth Michael Larson · committed by GitHub · parent f1dde95 · Browse files · 13 files+549 added−19 removed
This commit

State

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

Diff stats

13 files+549 added−19 removed

  • tests:+257 added−6 removed
  • other:+292 added−13 removed

13 files+549 added−19 removed

modified:httpx/dispatch/connection_pool.py+13 added-8 removed
126 unmodified lines
127128 return response129130 async def acquire_connection(self, origin: Origin) -> HTTPConnection:131 logger.debug(f"acquire_connection origin={origin!r}")132 connection = self.active_connections.pop_by_origin(origin, http2_only=True)133 if connection is None:134 connection = self.keepalive_connections.pop_by_origin(origin)131 logger.debug("acquire_connection origin={origin!r}")132 connection = self.pop_connection(origin)133136 if connection is not None and connection.is_connection_dropped():137 self.max_connections.release()138 connection = None139134 if connection is None:135 await self.max_connections.acquire()136 connection = HTTPConnection(137 origin,
34 unmodified lines
172 connections = list(self.keepalive_connections)173 self.keepalive_connections.clear()174 for connection in connections:175 await connection.close()176177 def pop_connection(self, origin: Origin) -> typing.Optional[HTTPConnection]:178 connection = self.active_connections.pop_by_origin(origin, http2_only=True)179 if connection is None:180 connection = self.keepalive_connections.pop_by_origin(origin)181182 if connection is not None and connection.is_connection_dropped():183 self.max_connections.release()184 connection = None185186 return connection
modified:httpx/dispatch/http11.py+1 added-1 removed
151 unmodified lines
152 event = await self._receive_event(timeout)153 if isinstance(event, h11.Data):154 yield bytes(event.data)155 else:156 assert isinstance(event, h11.EndOfMessage)156 assert isinstance(event, h11.EndOfMessage) or event is h11.PAUSED157 break # pragma: no cover158159 async def _receive_event(self, timeout: TimeoutConfig = None) -> H11Event:160 """
48 unmodified lines
modified:httpx/dispatch/http2.py+1 added-1 removed
33 unmodified lines
34 self, request: AsyncRequest, timeout: TimeoutTypes = None35 ) -> AsyncResponse:36 timeout = None if timeout is None else TimeoutConfig(timeout)3738 #  Start sending the request.38 # Start sending the request.39 if not self.initialized:40 self.initiate_connection()4142 stream_id = await self.send_headers(request, timeout)
182 unmodified lines
added:httpx/dispatch/proxy_http.py+251 added
1import enum23import h1145from ..concurrency.base import ConcurrencyBackend6from ..config import (7 DEFAULT_POOL_LIMITS,8 DEFAULT_TIMEOUT_CONFIG,9 CertTypes,10 PoolLimits,11 SSLConfig,12 TimeoutTypes,13 VerifyTypes,14)15from ..exceptions import ProxyError16from ..middleware.basic_auth import build_basic_auth_header17from ..models import (18 URL,19 AsyncRequest,20 AsyncResponse,21 Headers,22 HeaderTypes,23 Origin,24 URLTypes,25)26from ..utils import get_logger27from .connection import HTTPConnection28from .connection_pool import ConnectionPool29from .http2 import HTTP2Connection30from .http11 import HTTP11Connection3132logger = get_logger(__name__)333435class HTTPProxyMode(enum.Enum):36 DEFAULT = "DEFAULT"37 FORWARD_ONLY = "FORWARD_ONLY"38 TUNNEL_ONLY = "TUNNEL_ONLY"394041class HTTPProxy(ConnectionPool):42 """A proxy that sends requests to the recipient server43 on behalf of the connecting client.44 """4546 def __init__(47 self,48 proxy_url: URLTypes,49 *,50 proxy_headers: HeaderTypes = None,51 proxy_mode: HTTPProxyMode = HTTPProxyMode.DEFAULT,52 verify: VerifyTypes = True,53 cert: CertTypes = None,54 timeout: TimeoutTypes = DEFAULT_TIMEOUT_CONFIG,55 pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,56 backend: ConcurrencyBackend = None,57 ):5859 super(HTTPProxy, self).__init__(60 verify=verify,61 cert=cert,62 timeout=timeout,63 pool_limits=pool_limits,64 backend=backend,65 )6667 self.proxy_url = URL(proxy_url)68 self.proxy_mode = proxy_mode69 self.proxy_headers = Headers(proxy_headers)7071 url = self.proxy_url72 if url.username or url.password:73 self.proxy_headers.setdefault(74 "Proxy-Authorization",75 build_basic_auth_header(url.username, url.password),76 )77 # Remove userinfo from the URL authority, e.g.:78 # 'username:password@proxy_host:proxy_port' -> 'proxy_host:proxy_port'79 credentials, _, authority = url.authority.rpartition("@")80 self.proxy_url = url.copy_with(authority=authority)8182 async def acquire_connection(self, origin: Origin) -> HTTPConnection:83 if self.should_forward_origin(origin):84 logger.debug(85 f"forward_connection proxy_url={self.proxy_url!r} origin={origin!r}"86 )87 return await super().acquire_connection(self.proxy_url.origin)88 else:89 logger.debug(90 f"tunnel_connection proxy_url={self.proxy_url!r} origin={origin!r}"91 )92 return await self.tunnel_connection(origin)9394 async def tunnel_connection(self, origin: Origin) -> HTTPConnection:95 """Creates a new HTTPConnection via the CONNECT method96 usually reserved for proxying HTTPS connections.97 """98 connection = self.pop_connection(origin)99100 if connection is None:101 connection = await self.request_tunnel_proxy_connection(origin)102103 # After we receive the 2XX response from the proxy that our104 # tunnel is open we switch the connection's origin105 # to the original so the tunnel can be re-used.106 self.active_connections.remove(connection)107 connection.origin = origin108 self.active_connections.add(connection)109110 await self.tunnel_start_tls(origin, connection)111 else:112 self.active_connections.add(connection)113114 return connection115116 async def request_tunnel_proxy_connection(self, origin: Origin) -> HTTPConnection:117 """Creates an HTTPConnection by setting up a TCP tunnel"""118 proxy_headers = self.proxy_headers.copy()119 proxy_headers.setdefault("Accept", "*/*")120 proxy_request = AsyncRequest(121 method="CONNECT", url=self.proxy_url.copy_with(), headers=proxy_headers122 )123 proxy_request.url.full_path = f"{origin.host}:{origin.port}"124125 await self.max_connections.acquire()126127 connection = HTTPConnection(128 self.proxy_url.origin,129 verify=self.verify,130 cert=self.cert,131 timeout=self.timeout,132 backend=self.backend,133 http_versions=["HTTP/1.1"], # Short-lived 'connection'134 trust_env=self.trust_env,135 release_func=self.release_connection,136 )137 self.active_connections.add(connection)138139 # See if our tunnel has been opened successfully140 proxy_response = await connection.send(proxy_request)141 logger.debug(142 f"tunnel_response "143 f"proxy_url={self.proxy_url!r} "144 f"origin={origin!r} "145 f"response={proxy_response!r}"146 )147 if not (200 <= proxy_response.status_code <= 299):148 await proxy_response.read()149 raise ProxyError(150 f"Non-2XX response received from HTTP proxy "151 f"({proxy_response.status_code})",152 request=proxy_request,153 response=proxy_response,154 )155 else:156 proxy_response.on_close = None157 await proxy_response.read()158159 return connection160161 async def tunnel_start_tls(162 self, origin: Origin, connection: HTTPConnection163 ) -> None:164 """Runs start_tls() on a TCP-tunneled connection"""165166 # Store this information here so that we can transfer167 # it to the new internal connection object after168 # the old one goes to 'SWITCHED_PROTOCOL'.169 http_version = "HTTP/1.1"170 http_connection = connection.h11_connection171 assert http_connection is not None172 assert http_connection.h11_state.our_state == h11.SWITCHED_PROTOCOL173 on_release = http_connection.on_release174 stream = http_connection.stream175176 # If we need to start TLS again for the target server177 # we need to pull the TCP stream off the internal178 # HTTP connection object and run start_tls()179 if origin.is_ssl:180 ssl_config = SSLConfig(cert=self.cert, verify=self.verify)181 timeout = connection.timeout182 ssl_context = await connection.get_ssl_context(ssl_config)183 assert ssl_context is not None184185 logger.debug(186 f"tunnel_start_tls "187 f"proxy_url={self.proxy_url!r} "188 f"origin={origin!r}"189 )190 stream = await self.backend.start_tls(191 stream=stream,192 hostname=origin.host,193 ssl_context=ssl_context,194 timeout=timeout,195 )196 http_version = stream.get_http_version()197 logger.debug(198 f"tunnel_tls_complete "199 f"proxy_url={self.proxy_url!r} "200 f"origin={origin!r} "201 f"http_version={http_version!r}"202 )203204 if http_version == "HTTP/2":205 connection.h2_connection = HTTP2Connection(206 stream, self.backend, on_release=on_release207 )208 else:209 assert http_version == "HTTP/1.1"210 connection.h11_connection = HTTP11Connection(211 stream, self.backend, on_release=on_release212 )213214 def should_forward_origin(self, origin: Origin) -> bool:215 """Determines if the given origin should216 be forwarded or tunneled. If 'proxy_mode' is 'DEFAULT'217 then the proxy will forward all 'HTTP' requests and218 tunnel all 'HTTPS' requests.219 """220 return (221 self.proxy_mode == HTTPProxyMode.DEFAULT and not origin.is_ssl222 ) or self.proxy_mode == HTTPProxyMode.FORWARD_ONLY223224 async def send(225 self,226 request: AsyncRequest,227 verify: VerifyTypes = None,228 cert: CertTypes = None,229 timeout: TimeoutTypes = None,230 ) -> AsyncResponse:231232 if self.should_forward_origin(request.url.origin):233 # Change the request to have the target URL234 # as its full_path and switch the proxy URL235 # for where the request will be sent.236 target_url = str(request.url)237 request.url = self.proxy_url.copy_with()238 request.url.full_path = target_url239 for name, value in self.proxy_headers.items():240 request.headers.setdefault(name, value)241242 return await super().send(243 request=request, verify=verify, cert=cert, timeout=timeout244 )245246 def __repr__(self) -> str:247 return (248 f"HTTPProxy(proxy_url={self.proxy_url!r} "249 f"proxy_headers={self.proxy_headers!r} "250 f"proxy_mode={self.proxy_mode!r})"251 )
modified:httpx/__init__.py+5 added
20 unmodified lines
21)22from .dispatch.base import AsyncDispatcher, Dispatcher23from .dispatch.connection import HTTPConnection24from .dispatch.connection_pool import ConnectionPool25from .dispatch.proxy_http import HTTPProxy, HTTPProxyMode26from .exceptions import (27 ConnectTimeout,28 CookieConflict,29 DecodingError,30 InvalidURL,31 NotRedirectResponse,32 PoolTimeout,33 ProtocolError,34 ProxyError,35 ReadTimeout,36 RedirectBodyUnavailable,37 RedirectLoop,38 ResponseClosed,
52 unmodified lines
91 "HTTPConnection",92 "BasePoolSemaphore",93 "BaseBackgroundManager",94 "ConnectionPool",95 "HTTPProxy",96 "HTTPProxyMode",97 "ConnectTimeout",98 "CookieConflict",99 "DecodingError",100 "InvalidURL",
5 unmodified lines
106 "RedirectLoop",107 "ResponseClosed",108 "ResponseNotRead",109 "StreamConsumed",110 "ProxyError",111 "Timeout",112 "TooManyRedirects",113 "WriteTimeout",114 "AsyncDispatcher",
29 unmodified lines
modified:httpx/api.py-1 removed
25 unmodified lines
26 cookies: CookieTypes = None,27 auth: AuthTypes = None,28 timeout: TimeoutTypes = None,29 allow_redirects: bool = True,30 # proxies30 cert: CertTypes = None,31 verify: VerifyTypes = True,32 stream: bool = False,33 trust_env: bool = None,
253 unmodified lines
modified:httpx/client.py+2 added-2 removed
332 unmodified lines
333 headers: HeaderTypes = None,334 cookies: CookieTypes = None,335 stream: bool = False,336 auth: AuthTypes = None,337 allow_redirects: bool = False, #  Note: Differs to usual default.337 allow_redirects: bool = False, # NOTE: Differs to usual default.338 cert: CertTypes = None,339 verify: VerifyTypes = None,340 timeout: TimeoutTypes = None,341 trust_env: bool = None,
441 unmodified lines
783 headers: HeaderTypes = None,784 cookies: CookieTypes = None,785 stream: bool = False,786 auth: AuthTypes = None,787 allow_redirects: bool = False, #  Note: Differs to usual default.787 allow_redirects: bool = False, # NOTE: Differs to usual default.788 cert: CertTypes = None,789 verify: VerifyTypes = None,790 timeout: TimeoutTypes = None,791 trust_env: bool = None,
174 unmodified lines
modified:httpx/exceptions.py+6 added
51 unmodified lines
52 Timeout while waiting to acquire a connection from the pool.53 """545556class ProxyError(HTTPError):57 """58 Error from within a proxy59 """606162# HTTP exceptions...636465class ProtocolError(HTTPError):
91 unmodified lines
modified:httpx/models.py+13 added
113 unmodified lines
114 raise InvalidURL("No scheme included in URL.")115 if not self.host:116 raise InvalidURL("No host included in URL.")117118 # Allow setting full_path to custom attributes requests119 # like OPTIONS, CONNECT, and forwarding proxy requests.120 self._full_path: typing.Optional[str] = None121122 @property123 def scheme(self) -> str:124 return self._uri_reference.scheme or ""125
31 unmodified lines
157 return self._uri_reference.query or ""158159 @property160 def full_path(self) -> str:161 if self._full_path is not None:162 return self._full_path163 path = self.path164 if self.query:165 path += "?" + self.query166 return path167168 @full_path.setter169 def full_path(self, value: typing.Optional[str]) -> None:170 self._full_path = value171172 @property173 def fragment(self) -> str:174 return self._uri_reference.fragment or ""175
259 unmodified lines
435 headers = Headers(headers)436 for header in headers:437 self[header] = headers[header]438439 def copy(self) -> "Headers":440 return Headers(self.items(), encoding=self.encoding)441442 def __getitem__(self, key: str) -> str:443 """444 Return a single header value.445
809 unmodified lines
added:tests/dispatch/test_proxy_http.py+181 added
1import pytest23import httpx45from .utils import MockRawSocketBackend678async def test_proxy_tunnel_success(backend):9 raw_io = MockRawSocketBackend(10 data_to_send=(11 [12 b"HTTP/1.1 200 OK\r\n"13 b"Date: Sun, 10 Oct 2010 23:26:07 GMT\r\n"14 b"Server: proxy-server\r\n"15 b"\r\n",16 b"HTTP/1.1 404 Not Found\r\n"17 b"Date: Sun, 10 Oct 2010 23:26:07 GMT\r\n"18 b"Server: origin-server\r\n"19 b"\r\n",20 ]21 ),22 backend=backend,23 )24 async with httpx.HTTPProxy(25 proxy_url="http://127.0.0.1:8000",26 backend=raw_io,27 proxy_mode=httpx.HTTPProxyMode.TUNNEL_ONLY,28 ) as proxy:29 response = await proxy.request("GET", f"http://example.com")3031 assert response.status_code == 40432 assert response.headers["Server"] == "origin-server"3334 assert response.request.method == "GET"35 assert response.request.url == "http://example.com"36 assert response.request.headers["Host"] == "example.com"3738 recv = raw_io.received_data39 assert len(recv) == 340 assert recv[0] == b"--- CONNECT(127.0.0.1, 8000) ---"41 assert recv[1].startswith(42 b"CONNECT example.com:80 HTTP/1.1\r\nhost: 127.0.0.1:8000\r\n"43 )44 assert recv[2].startswith(b"GET / HTTP/1.1\r\nhost: example.com\r\n")454647@pytest.mark.parametrize("status_code", [300, 304, 308, 401, 500])48async def test_proxy_tunnel_non_2xx_response(backend, status_code):49 raw_io = MockRawSocketBackend(50 data_to_send=(51 [52 b"HTTP/1.1 %d Not Good\r\n" % status_code,53 b"Date: Sun, 10 Oct 2010 23:26:07 GMT\r\n"54 b"Server: proxy-server\r\n"55 b"\r\n",56 ]57 ),58 backend=backend,59 )6061 with pytest.raises(httpx.ProxyError) as e:62 async with httpx.HTTPProxy(63 proxy_url="http://127.0.0.1:8000",64 backend=raw_io,65 proxy_mode=httpx.HTTPProxyMode.TUNNEL_ONLY,66 ) as proxy:67 await proxy.request("GET", f"http://example.com")6869 # ProxyError.request should be the CONNECT request not the original request70 assert e.value.request.method == "CONNECT"71 assert e.value.request.headers["Host"] == "127.0.0.1:8000"72 assert e.value.request.url.full_path == "example.com:80"7374 # ProxyError.response should be the CONNECT response75 assert e.value.response.status_code == status_code76 assert e.value.response.headers["Server"] == "proxy-server"7778 # Verify that the request wasn't sent after receiving an error from CONNECT79 recv = raw_io.received_data80 assert len(recv) == 281 assert recv[0] == b"--- CONNECT(127.0.0.1, 8000) ---"82 assert recv[1].startswith(83 b"CONNECT example.com:80 HTTP/1.1\r\nhost: 127.0.0.1:8000\r\n"84 )858687async def test_proxy_tunnel_start_tls(backend):88 raw_io = MockRawSocketBackend(89 data_to_send=(90 [91 b"HTTP/1.1 200 OK\r\n"92 b"Date: Sun, 10 Oct 2010 23:26:07 GMT\r\n"93 b"Server: proxy-server\r\n"94 b"\r\n",95 b"HTTP/1.1 404 Not Found\r\n"96 b"Date: Sun, 10 Oct 2010 23:26:07 GMT\r\n"97 b"Server: origin-server\r\n"98 b"\r\n",99 ]100 ),101 backend=backend,102 )103 async with httpx.HTTPProxy(104 proxy_url="http://127.0.0.1:8000",105 backend=raw_io,106 proxy_mode=httpx.HTTPProxyMode.TUNNEL_ONLY,107 ) as proxy:108 response = await proxy.request("GET", f"https://example.com")109110 assert response.status_code == 404111 assert response.headers["Server"] == "origin-server"112113 assert response.request.method == "GET"114 assert response.request.url == "https://example.com"115 assert response.request.headers["Host"] == "example.com"116117 recv = raw_io.received_data118 assert len(recv) == 4119 assert recv[0] == b"--- CONNECT(127.0.0.1, 8000) ---"120 assert recv[1].startswith(121 b"CONNECT example.com:443 HTTP/1.1\r\nhost: 127.0.0.1:8000\r\n"122 )123 assert recv[2] == b"--- START_TLS(example.com) ---"124 assert recv[3].startswith(b"GET / HTTP/1.1\r\nhost: example.com\r\n")125126127@pytest.mark.parametrize(128 "proxy_mode", [httpx.HTTPProxyMode.FORWARD_ONLY, httpx.HTTPProxyMode.DEFAULT]129)130async def test_proxy_forwarding(backend, proxy_mode):131 raw_io = MockRawSocketBackend(132 data_to_send=(133 [134 b"HTTP/1.1 200 OK\r\n"135 b"Date: Sun, 10 Oct 2010 23:26:07 GMT\r\n"136 b"Server: origin-server\r\n"137 b"\r\n"138 ]139 ),140 backend=backend,141 )142 async with httpx.HTTPProxy(143 proxy_url="http://127.0.0.1:8000", backend=raw_io, proxy_mode=proxy_mode144 ) as proxy:145 response = await proxy.request("GET", f"http://example.com")146147 assert response.status_code == 200148 assert response.headers["Server"] == "origin-server"149150 assert response.request.method == "GET"151 assert response.request.url == "http://127.0.0.1:8000"152 assert response.request.url.full_path == "http://example.com"153 assert response.request.headers["Host"] == "example.com"154155 recv = raw_io.received_data156 assert len(recv) == 2157 assert recv[0] == b"--- CONNECT(127.0.0.1, 8000) ---"158 assert recv[1].startswith(159 b"GET http://example.com HTTP/1.1\r\nhost: example.com\r\n"160 )161162163def test_proxy_url_with_username_and_password():164 proxy = httpx.HTTPProxy("http://user:password@example.com:1080")165166 assert proxy.proxy_url == "http://example.com:1080"167 assert proxy.proxy_headers["Proxy-Authorization"] == "Basic dXNlcjpwYXNzd29yZA=="168169170def test_proxy_repr():171 proxy = httpx.HTTPProxy(172 "http://127.0.0.1:1080",173 proxy_headers={"Custom": "Header"},174 proxy_mode=httpx.HTTPProxyMode.DEFAULT,175 )176177 assert repr(proxy) == (178 "HTTPProxy(proxy_url=URL('http://127.0.0.1:1080') "179 "proxy_headers=Headers({'custom': 'Header'}) "180 "proxy_mode=<HTTPProxyMode.DEFAULT: 'DEFAULT'>)"181 )
modified:tests/dispatch/utils.py+58 added
158 unmodified lines
159 self.buffer += self.conn.data_to_send()160 self.returning[stream_id] = False161 self.conn.end_stream(stream_id)162 self.buffer += self.conn.data_to_send()163164165class MockRawSocketBackend:166 def __init__(self, data_to_send=b"", backend=None):167 self.backend = AsyncioBackend() if backend is None else backend168 self.data_to_send = data_to_send169 self.received_data = []170 self.stream = MockRawSocketStream(self)171172 async def connect(173 self,174 hostname: str,175 port: int,176 ssl_context: typing.Optional[ssl.SSLContext],177 timeout: TimeoutConfig,178 ) -> BaseStream:179 self.received_data.append(180 b"--- CONNECT(%s, %d) ---" % (hostname.encode(), port)181 )182 return self.stream183184 async def start_tls(185 self,186 stream: BaseStream,187 hostname: str,188 ssl_context: ssl.SSLContext,189 timeout: TimeoutConfig,190 ) -> BaseStream:191 self.received_data.append(b"--- START_TLS(%s) ---" % hostname.encode())192 return self.stream193194 # Defer all other attributes and methods to the underlying backend.195 def __getattr__(self, name: str) -> typing.Any:196 return getattr(self.backend, name)197198199class MockRawSocketStream(BaseStream):200 def __init__(self, backend: MockRawSocketBackend):201 self.backend = backend202203 def get_http_version(self) -> str:204 return "HTTP/1.1"205206 def write_no_block(self, data: bytes) -> None:207 self.backend.received_data.append(data)208209 async def write(self, data: bytes, timeout: TimeoutConfig = None) -> None:210 if data:211 self.write_no_block(data)212213 async def read(self, n, timeout, flag=None) -> bytes:214 await sleep(self.backend.backend, 0)215 if not self.backend.data_to_send:216 return b""217 return self.backend.data_to_send.pop(0)218219 async def close(self) -> None:220 pass
modified:tests/models/test_url.py+7 added
175 unmodified lines
176177 assert all(url in urls for url in url_set)178179180def test_url_full_path_setter():181 url = URL("http://example.org")182183 url.full_path = "http://example.net"184 assert url.full_path == "http://example.net"185186187def test_origin_from_url_string():188 origin = Origin("https://example.com")189 assert origin.scheme == "https"190 assert origin.is_ssl
2 unmodified lines
modified:tests/conftest.py+11 added-6 removed
15 unmodified lines
16from uvicorn.main import Server1718from httpx import URL, AsyncioBackend1920ENVIRONMENT_VARIABLES = (20ENVIRONMENT_VARIABLES = {21 "SSL_CERT_FILE",22 "REQUESTS_CA_BUNDLE",23 "CURL_CA_BUNDLE",22 "SSL_CERT_DIR",23 "HTTP_PROXY",24 "HTTPS_PROXY",25 "ALL_PROXY",26 "NO_PROXY",27 "SSLKEYLOGFILE",29)28}293031@pytest.fixture(scope="function", autouse=True)32def clean_environ() -> typing.Dict[str, typing.Any]:33 """Keeps os.environ clean for every test without having to mock os.environ"""34 original_environ = os.environ.copy()36 for key in ENVIRONMENT_VARIABLES:37 os.environ.pop(key, None)35 os.environ.clear()36 os.environ.update(37 {38 k: v39 for k, v in original_environ.items()40 if k not in ENVIRONMENT_VARIABLES and k.lower() not in ENVIRONMENT_VARIABLES41 }42 )43 yield44 os.environ.clear()45 os.environ.update(original_environ)46
226 unmodified lines