From d889f05ce8b12ee561b450f49738f3561bd5f36f Mon Sep 17 00:00:00 2001 From: Nate Prewitt Date: Wed, 1 Jun 2022 00:06:24 -0600 Subject: [PATCH] Tolerate bad registry entries in Windows proxy settings --- requests/utils.py | 2 +- tests/test_utils.py | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/requests/utils.py b/requests/utils.py index 3df4cd151a..1baab8ccad 100644 --- a/requests/utils.py +++ b/requests/utils.py @@ -83,7 +83,7 @@ def proxy_bypass_registry(host): proxyEnable = int(winreg.QueryValueEx(internetSettings, "ProxyEnable")[0]) # ProxyOverride is almost always a string proxyOverride = winreg.QueryValueEx(internetSettings, "ProxyOverride")[0] - except OSError: + except (OSError, ValueError): return False if not proxyEnable or not proxyOverride: return False diff --git a/tests/test_utils.py b/tests/test_utils.py index a714b4700e..112bbd1eaf 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -864,6 +864,39 @@ def QueryValueEx(key, value_name): assert should_bypass_proxies(url, None) == expected +@pytest.mark.skipif(os.name != "nt", reason="Test only on Windows") +def test_should_bypass_proxies_win_registry_bad_values(monkeypatch): + """Tests for function should_bypass_proxies to check if proxy + can be bypassed or not with Windows invalid registry settings. + """ + import winreg + + class RegHandle: + def Close(self): + pass + + ie_settings = RegHandle() + + def OpenKey(key, subkey): + return ie_settings + + def QueryValueEx(key, value_name): + if key is ie_settings: + if value_name == "ProxyEnable": + # Invalid response; Should be an int or int-y value + return [""] + elif value_name == "ProxyOverride": + return ["192.168.*;127.0.0.1;localhost.localdomain;172.16.1.1"] + + monkeypatch.setenv("http_proxy", "") + monkeypatch.setenv("https_proxy", "") + monkeypatch.setenv("no_proxy", "") + monkeypatch.setenv("NO_PROXY", "") + monkeypatch.setattr(winreg, "OpenKey", OpenKey) + monkeypatch.setattr(winreg, "QueryValueEx", QueryValueEx) + assert should_bypass_proxies("http://172.16.1.1/", None) is False + + @pytest.mark.parametrize( "env_name, value", (