Skip to content
Myr

Cleaner no proxy support (#1103)

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

* Add internal URLMatcher class * Use URLMatcher for proxy lookups in transport_for_url * Docstring * Pin pytest * Add support for no-proxies configurations * Don't call should_not_proxy on each request * Drop print statements * Tweak comment * Tweak comment on domain wildcards * Update httpx/_utils.py Co-authored-by: Florimond Manca <florimond.manca@gmail.com> * Pull test_should_not_be_proxied cases into test_proxies_environ

authored by Tom Christie · committed by GitHub · parent f67e925 · Browse files · 4 files+152 added−120 removed
This commit

State

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

Trailers

  • Co-authored-by: Florimond Manca <florimond.manca@gmail.com>

Diff stats

4 files+152 added−120 removed

  • tests:+93 added−77 removed
  • other:+59 added−43 removed

4 files+152 added−120 removed

modified:httpx/_client.py+7 added-10 removed
47 unmodified lines
48 enforce_http_url,49 get_environment_proxies,50 get_logger,51 same_origin,52 should_not_be_proxied,52 warn_deprecated,53)5455logger = get_logger(__name__)
37 unmodified lines
93 ) -> typing.Dict[str, typing.Optional[Proxy]]:94 if proxies is None:95 if trust_env:96 return {98 key: Proxy(url=url)97 key: None if url is None else Proxy(url=url)98 for key, url in get_environment_proxies().items()99 }100 return {}101 if isinstance(proxies, dict):
454 unmodified lines
556 """557 url = request.url558 enforce_http_url(request)559561 if self._proxies and not should_not_be_proxied(url):562 for pattern, transport in self._proxies.items():563 if pattern.matches(url):564 return self._transport if transport is None else transport560 for pattern, transport in self._proxies.items():561 if pattern.matches(url):562 return self._transport if transport is None else transport563564 return self._transport565566 def request(
519 unmodified lines
1086 """1087 url = request.url1088 enforce_http_url(request)10891092 if self._proxies and not should_not_be_proxied(url):1093 for pattern, transport in self._proxies.items():1094 if pattern.matches(url):1095 return self._transport if transport is None else transport1090 for pattern, transport in self._proxies.items():1091 if pattern.matches(url):1092 return self._transport if transport is None else transport10931094 return self._transport10951096 async def request(
411 unmodified lines
modified:httpx/_utils.py+52 added-33 removed
297 unmodified lines
298 and port_or_default(url) == port_or_default(other)299 )300301302def should_not_be_proxied(url: "URL") -> bool:303 """304 Return True if url should not be proxied,305 return False otherwise.306 """307 no_proxy = getproxies().get("no")308 if not no_proxy:309 return False310 no_proxy_list = [host.strip() for host in no_proxy.split(",")]311 for name in no_proxy_list:312 if name == "*":313 return True314 if name:315 name = name.lstrip(".") # ignore leading dots316 name = re.escape(name)317 pattern = r"(.+\.)?%s$" % name318 if re.match(pattern, url.host, re.I) or re.match(319 pattern, url.authority, re.I320 ):321 return True322 return False323324325def get_environment_proxies() -> typing.Dict[str, str]:302def get_environment_proxies() -> typing.Dict[str, typing.Optional[str]]:303 """Gets proxy information from the environment"""304305 # urllib.request.getproxies() falls back on System306 # Registry and Config for proxies on Windows and macOS.307 # We don't want to propagate non-HTTP proxies into308 # our configuration such as 'TRAVIS_APT_PROXY'.332 supported_proxy_schemes = ("http", "https", "all")333 return {334 key: val335 for key, val in getproxies().items()336 if ("://" in key or key in supported_proxy_schemes)337 }309 proxy_info = getproxies()310 mounts: typing.Dict[str, typing.Optional[str]] = {}311312 for scheme in ("http", "https", "all"):313 if proxy_info.get(scheme):314 mounts[scheme] = proxy_info[scheme]315316 no_proxy_hosts = [host.strip() for host in proxy_info.get("no", "").split(",")]317 for hostname in no_proxy_hosts:318 # See https://curl.haxx.se/libcurl/c/CURLOPT_NOPROXY.html for details319 # on how names in `NO_PROXY` are handled.320 if hostname == "*":321 # If NO_PROXY=* is used or if "*" occurs as any one of the comma322 # seperated hostnames, then we should just bypass any information323 # from HTTP_PROXY, HTTPS_PROXY, ALL_PROXY, and always ignore324 # proxies.325 return {}326 elif hostname:327 # NO_PROXY=.google.com is marked as "all://*.google.com,328 # which disables "www.google.com" but not "google.com"329 # NO_PROXY=google.com is marked as "all://*google.com,330 # which disables "www.google.com" and "google.com".331 # (But not "wwwgoogle.com")332 mounts[f"all://*{hostname}"] = None333334 return mounts335336337def to_bytes(value: typing.Union[str, bytes], encoding: str = "utf-8") -> bytes:338 return value.encode(encoding) if isinstance(value, str) else value339340
140 unmodified lines
481482 url = URL(pattern)483 self.pattern = pattern484 self.scheme = "" if url.scheme == "all" else url.scheme488 self.host = url.host485 self.host = "" if url.host == "*" else url.host486 self.port = url.port487 if not url.host or url.host == "*":488 self.host_regex: typing.Optional[typing.Pattern[str]] = None489 else:490 if url.host.startswith("*."):491 # *.example.com should match "www.example.com", but not "example.com"492 domain = re.escape(url.host[2:])493 self.host_regex = re.compile(f"^.+\\.{domain}$")494 elif url.host.startswith("*"):495 # *example.com should match "www.example.com" and "example.com"496 domain = re.escape(url.host[1:])497 self.host_regex = re.compile(f"^(.+\\.)?{domain}$")498 else:499 # example.com should match "example.com" but not "www.example.com"500 domain = re.escape(url.host)501 self.host_regex = re.compile(f"^{domain}$")502503 def matches(self, other: "URL") -> bool:504 if self.scheme and self.scheme != other.scheme:505 return False494 if self.host and self.host != other.host:506 if (507 self.host508 and self.host_regex is not None509 and not self.host_regex.match(other.host)510 ):511 return False512 if self.port is not None and self.port != other.port:513 return False514 return True
3 unmodified lines
518 """519 The priority allows URLPattern instances to be sortable, so that520 we can match from most specific to least specific.521 """506 port_priority = -1 if self.port is not None else 0522 # URLs with a port should take priority over URLs without a port.523 port_priority = 0 if self.port is not None else 1524 # Longer hostnames should match first.525 host_priority = -len(self.host)526 # Longer schemes should match first.527 scheme_priority = -len(self.scheme)528 return (port_priority, host_priority, scheme_priority)529530 def __hash__(self) -> int:
11 unmodified lines
modified:tests/client/test_proxies.py+93 added
54 unmodified lines
55 ("http://example.com", None, None),56 ("http://example.com", {}, None),57 ("http://example.com", {"https": PROXY_URL}, None),58 ("http://example.com", {"http://example.net": PROXY_URL}, None),59 # Using "*" should match any domain name.60 ("http://example.com", {"http://*": PROXY_URL}, PROXY_URL),61 ("https://example.com", {"http://*": PROXY_URL}, None),62 # Using "example.com" should match example.com, but not www.example.com63 ("http://example.com", {"http://example.com": PROXY_URL}, PROXY_URL),64 ("http://www.example.com", {"http://example.com": PROXY_URL}, None),65 # Using "*.example.com" should match www.example.com, but not example.com66 ("http://example.com", {"http://*.example.com": PROXY_URL}, None),67 ("http://www.example.com", {"http://*.example.com": PROXY_URL}, PROXY_URL),68 # Using "*example.com" should match example.com and www.example.com69 ("http://example.com", {"http://*example.com": PROXY_URL}, PROXY_URL),70 ("http://www.example.com", {"http://*example.com": PROXY_URL}, PROXY_URL),71 ("http://wwwexample.com", {"http://*example.com": PROXY_URL}, None),72 # ...73 ("http://example.com:443", {"http://example.com": PROXY_URL}, PROXY_URL),74 ("http://example.com", {"all": PROXY_URL}, PROXY_URL),75 ("http://example.com", {"all": PROXY_URL, "http://example.com": None}, None),76 ("http://example.com", {"http": PROXY_URL}, PROXY_URL),
70 unmodified lines
147 "http://google.com",148 {"HTTP_PROXY": "http://example.com", "NO_PROXY": "google.com"},149 None,150 ),151 # Everything proxied when NO_PROXY is empty/unset152 (153 "http://127.0.0.1",154 {"ALL_PROXY": "http://localhost:123", "NO_PROXY": ""},155 "http://localhost:123",156 ),157 # Not proxied if NO_PROXY matches URL.158 (159 "http://127.0.0.1",160 {"ALL_PROXY": "http://localhost:123", "NO_PROXY": "127.0.0.1"},161 None,162 ),163 # Proxied if NO_PROXY scheme does not match URL.164 (165 "http://127.0.0.1",166 {"ALL_PROXY": "http://localhost:123", "NO_PROXY": "https://127.0.0.1"},167 "http://localhost:123",168 ),169 # Proxied if NO_PROXY scheme does not match host.170 (171 "http://127.0.0.1",172 {"ALL_PROXY": "http://localhost:123", "NO_PROXY": "1.1.1.1"},173 "http://localhost:123",174 ),175 # Not proxied if NO_PROXY matches host domain suffix.176 (177 "http://courses.mit.edu",178 {"ALL_PROXY": "http://localhost:123", "NO_PROXY": "mit.edu"},179 None,180 ),181 # Proxied even though NO_PROXY matches host domain *prefix*.182 (183 "https://mit.edu.info",184 {"ALL_PROXY": "http://localhost:123", "NO_PROXY": "mit.edu"},185 "http://localhost:123",186 ),187 # Not proxied if one item in NO_PROXY case matches host domain suffix.188 (189 "https://mit.edu.info",190 {"ALL_PROXY": "http://localhost:123", "NO_PROXY": "mit.edu,edu.info"},191 None,192 ),193 # Not proxied if one item in NO_PROXY case matches host domain suffix.194 # May include whitespace.195 (196 "https://mit.edu.info",197 {"ALL_PROXY": "http://localhost:123", "NO_PROXY": "mit.edu, edu.info"},198 None,199 ),200 # Proxied if no items in NO_PROXY match.201 (202 "https://mit.edu.info",203 {"ALL_PROXY": "http://localhost:123", "NO_PROXY": "mit.edu,mit.info"},204 "http://localhost:123",205 ),206 # Proxied if NO_PROXY domain doesn't match.207 (208 "https://foo.example.com",209 {"ALL_PROXY": "http://localhost:123", "NO_PROXY": "www.example.com"},210 "http://localhost:123",211 ),212 # Not proxied for subdomains matching NO_PROXY, with a leading ".".213 (214 "https://www.example1.com",215 {"ALL_PROXY": "http://localhost:123", "NO_PROXY": ".example1.com"},216 None,217 ),218 # Proxied, because NO_PROXY subdomains only match if "." seperated.219 (220 "https://www.example2.com",221 {"ALL_PROXY": "http://localhost:123", "NO_PROXY": "ample2.com"},222 "http://localhost:123",223 ),224 # No requests are proxied if NO_PROXY="*" is set.225 (226 "https://www.example3.com",227 {"ALL_PROXY": "http://localhost:123", "NO_PROXY": "*"},228 None,229 ),230 ],231)232@pytest.mark.parametrize("client_class", [httpx.Client, httpx.AsyncClient])233def test_proxies_environ(monkeypatch, client_class, url, env, expected):
11 unmodified lines
modified:tests/test_utils.py-77 removed
13 unmodified lines
14 guess_json_utf,15 obfuscate_sensitive_headers,16 parse_header_links,17 same_origin,18 should_not_be_proxied,18)19from tests.utils import override_log_level2021from .common import FIXTURES_DIR, TESTS_DIR
199 unmodified lines
221 assert list(obfuscate_sensitive_headers(headers)) == output222 assert list(obfuscate_sensitive_headers(bytes_headers)) == bytes_output223224226@pytest.mark.parametrize(227 ["url", "no_proxy", "expected"],228 [229 (230 "http://127.0.0.1",231 {"NO_PROXY": ""},232 False,233 ), # everything proxied when no_proxy is empty/unset234 (235 "http://127.0.0.1",236 {"NO_PROXY": "127.0.0.1"},237 True,238 ), # no_proxy as ip case is matched239 (240 "http://127.0.0.1",241 {"NO_PROXY": "https://127.0.0.1"},242 False,243 ), # no_proxy with scheme is ignored244 (245 "http://127.0.0.1",246 {"NO_PROXY": "1.1.1.1"},247 False,248 ), # different no_proxy means its proxied249 (250 "http://courses.mit.edu",251 {"NO_PROXY": "mit.edu"},252 True,253 ), # no_proxy for sub-domain matches254 (255 "https://mit.edu.info",256 {"NO_PROXY": "mit.edu"},257 False,258 ), # domain is actually edu.info, so should be proxied259 (260 "https://mit.edu.info",261 {"NO_PROXY": "mit.edu,edu.info"},262 True,263 ), # list in no_proxy, matches second domain264 (265 "https://mit.edu.info",266 {"NO_PROXY": "mit.edu, edu.info"},267 True,268 ), # list with spaces in no_proxy269 (270 "https://mit.edu.info",271 {"NO_PROXY": "mit.edu,mit.info"},272 False,273 ), # list in no_proxy, without any domain matching274 (275 "https://foo.example.com",276 {"NO_PROXY": "www.example.com"},277 False,278 ), # different subdomains foo vs www means we still proxy279 (280 "https://www.example1.com",281 {"NO_PROXY": ".example1.com"},282 True,283 ), # no_proxy starting with dot284 (285 "https://www.example2.com",286 {"NO_PROXY": "ample2.com"},287 False,288 ), # whole-domain matching289 (290 "https://www.example3.com",291 {"NO_PROXY": "*"},292 True,293 ), # wildcard * means nothing proxied294 ],295)296def test_should_not_be_proxied(url, no_proxy, expected):297 os.environ.update(no_proxy)298 parsed_url = httpx.URL(url)299 assert should_not_be_proxied(parsed_url) == expected300301225def test_same_origin():226 origin1 = httpx.URL("https://example.com")227 origin2 = httpx.URL("HTTPS://EXAMPLE.COM:443")228 assert same_origin(origin1, origin2)
46 unmodified lines