Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions src/requests/adapters.py
Original file line number Diff line number Diff line change
Expand Up @@ -480,7 +480,7 @@ def get_connection_with_tls_context(
"""
assert _is_prepared(request)

proxy = select_proxy(request.url, proxies)
proxy = select_proxy(request.url, proxies, trust_env=False)
try:
host_params, pool_kwargs = self.build_connection_pool_key_attributes(
request,
Expand Down Expand Up @@ -532,7 +532,7 @@ def get_connection(
),
DeprecationWarning,
)
proxy = select_proxy(url, proxies)
proxy = select_proxy(url, proxies, trust_env=False)

if proxy:
proxy = prepend_scheme_if_needed(proxy, "http")
Expand Down Expand Up @@ -580,7 +580,7 @@ def request_url(
"""
assert _is_prepared(request)

proxy = select_proxy(request.url, proxies)
proxy = select_proxy(request.url, proxies, trust_env=False)
scheme = urlparse(request.url).scheme

is_proxied_http_request = proxy and scheme != "https"
Expand Down
2 changes: 1 addition & 1 deletion src/requests/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ def request(
:type timeout: float or tuple
:param allow_redirects: (optional) Boolean. Enable/disable GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection. Defaults to ``True``.
:type allow_redirects: bool
:param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.
:param proxies: (optional) Dictionary mapping protocol to the URL of the proxy. Can also include a ``'no'`` or ``'no_proxy'`` key to specify URLs that should bypass proxy settings.
:param verify: (optional) Either a boolean, in which case it controls whether we verify
the server's TLS certificate, or a string, in which case it must be a path
to a CA bundle to use. Defaults to ``True``.
Expand Down
18 changes: 15 additions & 3 deletions src/requests/sessions.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@
from .structures import CaseInsensitiveDict
from .utils import ( # noqa: F401
DEFAULT_PORTS,
_extract_no_proxy,
_should_bypass_proxies_with_trust_env,
default_headers,
get_auth_from_url,
get_environ_proxies,
Expand Down Expand Up @@ -599,7 +601,8 @@ def request(
:param allow_redirects: (optional) Set to True by default.
:type allow_redirects: bool
:param proxies: (optional) Dictionary mapping protocol or protocol and
hostname to the URL of the proxy.
hostname to the URL of the proxy. Can also include a ``'no'`` or
``'no_proxy'`` key to specify URLs that should bypass proxy settings.
:param hooks: (optional) Dictionary mapping hook name to one event or
list of events, event must be callable.
:param stream: (optional) whether to immediately download the response
Expand Down Expand Up @@ -780,8 +783,17 @@ def send(self, request: PreparedRequest, **kwargs: Any) -> Response:
# Start time (approximately) of the request
start = preferred_clock()

# Check if the URL should bypass the proxy based on 'no_proxy' or 'no'
# in kwargs or environment settings (when trust_env is enabled).
adapter_kwargs = kwargs
if kwargs.get("proxies") and _should_bypass_proxies_with_trust_env(
request.url, kwargs["proxies"], self.trust_env
):
adapter_kwargs = kwargs.copy()
adapter_kwargs["proxies"] = {}

# Send the request
r = adapter.send(request, **kwargs)
r = adapter.send(request, **adapter_kwargs)

# Total elapsed time of the request (approximately)
elapsed = preferred_clock() - start
Expand Down Expand Up @@ -844,7 +856,7 @@ def merge_environment_settings(
# Gather clues from the surrounding environment.
if self.trust_env:
# Set environment's proxies.
no_proxy = proxies.get("no_proxy") if proxies is not None else None
no_proxy = _extract_no_proxy(proxies)
env_proxies = get_environ_proxies(url, no_proxy=no_proxy)
if proxies is not None:
for k, v in env_proxies.items():
Expand Down
40 changes: 36 additions & 4 deletions src/requests/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -870,29 +870,61 @@ def get_proxy(key: str) -> str | None:
return False


def _extract_no_proxy(proxies: Mapping[str, str | None] | None) -> str | None:
"""Extract an explicit proxy bypass rule ('no_proxy' or 'no') from proxies."""
if proxies is None:
return None
no_proxy = proxies.get("no_proxy")
if no_proxy is not None:
return no_proxy
return proxies.get("no")


def _should_bypass_proxies_with_trust_env(
url: str,
proxies: Mapping[str, str | None] | None,
trust_env: bool,
) -> bool:
"""Evaluate proxy bypass rules respecting explicit keys and trust_env."""
no_proxy = _extract_no_proxy(proxies)
if no_proxy is not None:
return bool(no_proxy) and should_bypass_proxies(url, no_proxy=no_proxy)
if trust_env:
return should_bypass_proxies(url, no_proxy=None)
return False


def get_environ_proxies(url: str, no_proxy: str | None = None) -> dict[str, str]:
"""
Return a dict of environment proxies.

:rtype: dict
"""
if should_bypass_proxies(url, no_proxy=no_proxy):
if no_proxy != "" and should_bypass_proxies(url, no_proxy=no_proxy):
return {}
else:
return getproxies()


def select_proxy(url: str, proxies: dict[str, str] | None) -> str | None:
def select_proxy(
url: str,
proxies: dict[str, str] | None,
trust_env: bool = True,
) -> str | None:
"""Select a proxy for the url, if applicable.

:param url: The url being for the request
:param proxies: A dictionary of schemes or schemes and hosts to proxy URLs
:param trust_env: Boolean declaring whether to trust environment configs
"""
proxies = proxies or {}
urlparts = urlparse(url)
if urlparts.hostname is None:
return proxies.get(urlparts.scheme, proxies.get("all"))

if _should_bypass_proxies_with_trust_env(url, proxies, trust_env):
return None

proxy_keys = [
urlparts.scheme + "://" + urlparts.hostname,
urlparts.scheme,
Expand Down Expand Up @@ -926,10 +958,10 @@ def resolve_proxies(
proxies = proxies if proxies is not None else {}
url = cast(str, request.url)
scheme = urlparse(url).scheme
no_proxy = proxies.get("no_proxy")
no_proxy = _extract_no_proxy(proxies)
new_proxies = proxies.copy()

if trust_env and not should_bypass_proxies(url, no_proxy=no_proxy):
if trust_env and not _should_bypass_proxies_with_trust_env(url, proxies, trust_env):
environ_proxies = get_environ_proxies(url, no_proxy=no_proxy)

proxy = environ_proxies.get(scheme, environ_proxies.get("all"))
Expand Down
87 changes: 87 additions & 0 deletions tests/test_requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -2056,6 +2056,93 @@ def __iter__(self):

assert "Unable to rewind request body" in str(e)

@pytest.mark.parametrize("bypass_key", ("no_proxy", "no"))
def test_no_proxy_in_proxies_dict(self, httpbin_secure, bypass_key):
url = httpbin_secure("get")
host = urlparse(url).hostname

proxies = {"https": INVALID_PROXY, bypass_key: host}
with override_environ(NO_PROXY="", no_proxy=""):
r = requests.get(url, proxies=proxies, verify=False)
assert r.status_code == 200

proxies = {"https": INVALID_PROXY}
with override_environ(NO_PROXY=host, no_proxy=""):
r = requests.get(url, proxies=proxies, verify=False)
assert r.status_code == 200

@pytest.mark.parametrize("bypass_key", ("no_proxy", "no"))
def test_no_proxy_star_in_proxies_dict(self, httpbin_secure, bypass_key):
url = httpbin_secure("get")
proxies = {"https": INVALID_PROXY, bypass_key: "*"}
with override_environ(NO_PROXY="", no_proxy=""):
r = requests.get(url, proxies=proxies, verify=False)
assert r.status_code == 200

@pytest.mark.parametrize("bypass_key", ("no_proxy", "no"))
def test_no_proxy_not_matching_in_proxies_dict(self, httpbin_secure, bypass_key):
url = httpbin_secure("get")
proxies = {"https": INVALID_PROXY, bypass_key: "example.com"}
with override_environ(NO_PROXY="", no_proxy=""):
with pytest.raises(ProxyError):
requests.get(url, proxies=proxies, verify=False)

def test_trust_env_false_ignores_no_proxy_env(self, httpbin_secure):
url = httpbin_secure("get")
host = urlparse(url).hostname
session = requests.Session()
session.trust_env = False
session.proxies = {"https": INVALID_PROXY}

with override_environ(NO_PROXY=host, no_proxy=host):
with pytest.raises(ProxyError):
session.get(url, verify=False)

@pytest.mark.parametrize("bypass_key", ("no_proxy", "no"))
def test_trust_env_false_honors_explicit_no_proxy(self, httpbin_secure, bypass_key):
url = httpbin_secure("get")
host = urlparse(url).hostname
session = requests.Session()
session.trust_env = False
session.proxies = {"https": INVALID_PROXY, bypass_key: host}

with override_environ(NO_PROXY="other.example", no_proxy="other.example"):
r = session.get(url, verify=False)
assert r.status_code == 200

session.proxies = {"https": INVALID_PROXY, bypass_key: "other.example"}
with override_environ(NO_PROXY=host, no_proxy=host):
with pytest.raises(ProxyError):
session.get(url, verify=False)

@pytest.mark.parametrize("bypass_key", ("no_proxy", "no"))
def test_empty_no_proxy_in_proxies_overrides_env(self, httpbin_secure, bypass_key):
url = httpbin_secure("get")
host = urlparse(url).hostname

with override_environ(NO_PROXY=host, no_proxy=host):
with pytest.raises(ProxyError):
requests.get(
url,
proxies={"https": INVALID_PROXY, bypass_key: ""},
verify=False,
)

def test_no_proxy_redirect_preserves_explicit_proxies(self, httpbin):
first_url = httpbin("redirect-to")
parsed = urlparse(first_url)
assert parsed.hostname == "127.0.0.1"
redirect_target = f"{parsed.scheme}://localhost:{parsed.port}/get"
proxies = {"http": INVALID_PROXY, "no_proxy": "127.0.0.1"}

with override_environ(NO_PROXY="", no_proxy=""):
with pytest.raises(ProxyError):
requests.get(
first_url,
params={"url": redirect_target},
proxies=proxies,
)

def test_rewind_body_failed_seek(self):
class BadFileObj:
def __init__(self, data):
Expand Down
84 changes: 84 additions & 0 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -1011,3 +1011,87 @@ def QueryValueEx(key, value_name):
monkeypatch.setattr(winreg, "OpenKey", OpenKey)
monkeypatch.setattr(winreg, "QueryValueEx", QueryValueEx)
assert should_bypass_proxies("http://example.com/", None) is False


@pytest.mark.parametrize(
"url, no_proxy_env, proxies, expected_proxy",
[
("http://example.com", "example.com", {"http": "http://proxy.com"}, None),
(
"http://example.com",
"other.com",
{"http": "http://proxy.com"},
"http://proxy.com",
),
("http://test.example.com", "example.com", {"http": "http://proxy.com"}, None),
("http://example.com", "*", {"http": "http://proxy.com"}, None),
(
"http://example.com",
None,
{"http": "http://proxy.com"},
"http://proxy.com",
),
("http://internal.com", "internal.com", {"all": "http://proxy.com"}, None),
("https://internal.com", "internal.com", {"all": "http://proxy.com"}, None),
],
)
def test_select_proxy_with_no_proxy(
url, no_proxy_env, proxies, expected_proxy, monkeypatch
):
"""Test that select_proxy honors NO_PROXY environment variable by default."""
monkeypatch.delenv("no_proxy", raising=False)
if no_proxy_env:
monkeypatch.setenv("NO_PROXY", no_proxy_env)
else:
monkeypatch.delenv("NO_PROXY", raising=False)

assert select_proxy(url, proxies) == expected_proxy


@pytest.mark.parametrize(
"url, no_proxy_env, proxies, trust_env, expected_proxy",
[
(
"http://example.com",
"example.com",
{"http": "http://proxy.com"},
False,
"http://proxy.com",
),
(
"http://example.com",
"other.com",
{"http": "http://proxy.com", "no_proxy": "example.com"},
False,
None,
),
(
"http://example.com",
"other.com",
{"http": "http://proxy.com", "no": "example.com"},
False,
None,
),
(
"http://example.com",
"example.com",
{"http": "http://proxy.com", "no_proxy": ""},
True,
"http://proxy.com",
),
(
"http://example.com",
"example.com",
{"http": "http://proxy.com", "no": ""},
True,
"http://proxy.com",
),
],
)
def test_select_proxy_trust_env_and_explicit_bypass(
url, no_proxy_env, proxies, trust_env, expected_proxy, monkeypatch
):
"""Test select_proxy trust_env handling and explicit no_proxy/no keys."""
monkeypatch.delenv("no_proxy", raising=False)
monkeypatch.setenv("NO_PROXY", no_proxy_env)
assert select_proxy(url, proxies, trust_env=trust_env) == expected_proxy