| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import binascii |
| 4 |
import contextlib |
| 5 |
import hashlib |
| 6 |
import ipaddress |
| 7 |
import os.path |
| 8 |
import pathlib |
| 9 |
import shutil |
| 10 |
import socket |
| 11 |
import ssl |
| 12 |
import tempfile |
| 13 |
import typing |
| 14 |
from test import LONG_TIMEOUT, SHORT_TIMEOUT, resolvesLocalhostFQDN, withPyOpenSSL |
| 15 |
from test.conftest import ServerConfig |
| 16 |
|
| 17 |
import pytest |
| 18 |
import trustme |
| 19 |
|
| 20 |
import urllib3.exceptions |
| 21 |
from dummyserver.socketserver import DEFAULT_CA, HAS_IPV6, get_unreachable_address |
| 22 |
from dummyserver.testcase import ( |
| 23 |
HypercornDummyProxyTestCase, |
| 24 |
IPv6HypercornDummyProxyTestCase, |
| 25 |
) |
| 26 |
from urllib3 import HTTPResponse |
| 27 |
from urllib3._collections import HTTPHeaderDict |
| 28 |
from urllib3.connection import HTTPSConnection, VerifiedHTTPSConnection |
| 29 |
from urllib3.connectionpool import connection_from_url |
| 30 |
from urllib3.exceptions import ( |
| 31 |
ConnectTimeoutError, |
| 32 |
InsecureRequestWarning, |
| 33 |
MaxRetryError, |
| 34 |
ProxyError, |
| 35 |
ProxySchemeUnknown, |
| 36 |
ProxySchemeUnsupported, |
| 37 |
ReadTimeoutError, |
| 38 |
SSLError, |
| 39 |
) |
| 40 |
from urllib3.poolmanager import ProxyManager, proxy_from_url |
| 41 |
from urllib3.util.retry import RequestHistory |
| 42 |
from urllib3.util.ssl_ import create_urllib3_context |
| 43 |
from urllib3.util.timeout import Timeout |
| 44 |
|
| 45 |
from .. import TARPIT_HOST, requires_network |
| 46 |
|
| 47 |
|
| 48 |
def assert_is_verified(pm: ProxyManager, *, proxy: bool, target: bool) -> None: |
| 49 |
pool = list(pm.pools._container.values())[-1] # retrieve last pool entry |
| 50 |
connection = ( |
| 51 |
pool.pool.queue[-1] if pool.pool is not None else None |
| 52 |
) # retrieve last connection entry |
| 53 |
|
| 54 |
assert connection is not None |
| 55 |
assert connection.proxy_is_verified is proxy |
| 56 |
assert connection.is_verified is target |
| 57 |
|
| 58 |
|
| 59 |
class TestHTTPProxyManager(HypercornDummyProxyTestCase): |
| 60 |
@classmethod |
| 61 |
def setup_class(cls) -> None: |
| 62 |
super().setup_class() |
| 63 |
cls.http_url = f"http://{cls.http_host}:{int(cls.http_port)}" |
| 64 |
cls.http_url_alt = f"http://{cls.http_host_alt}:{int(cls.http_port)}" |
| 65 |
cls.https_url = f"https://{cls.https_host}:{int(cls.https_port)}" |
| 66 |
cls.https_url_alt = f"https://{cls.https_host_alt}:{int(cls.https_port)}" |
| 67 |
cls.https_url_fqdn = f"https://{cls.https_host}.:{int(cls.https_port)}" |
| 68 |
cls.proxy_url = f"http://{cls.proxy_host}:{int(cls.proxy_port)}" |
| 69 |
cls.https_proxy_url = f"https://{cls.proxy_host}:{int(cls.https_proxy_port)}" |
| 70 |
|
| 71 |
# Generate another CA to test verification failure |
| 72 |
cls.certs_dir = tempfile.mkdtemp() |
| 73 |
bad_ca = trustme.CA() |
| 74 |
|
| 75 |
cls.bad_ca_path = os.path.join(cls.certs_dir, "ca_bad.pem") |
| 76 |
bad_ca.cert_pem.write_to_path(cls.bad_ca_path) |
| 77 |
|
| 78 |
@classmethod |
| 79 |
def teardown_class(cls) -> None: |
| 80 |
super().teardown_class() |
| 81 |
shutil.rmtree(cls.certs_dir) |
| 82 |
|
| 83 |
def test_basic_proxy(self) -> None: |
| 84 |
with proxy_from_url(self.proxy_url, ca_certs=DEFAULT_CA) as http: |
| 85 |
r = http.request("GET", f"{self.http_url}/") |
| 86 |
assert r.status == 200 |
| 87 |
|
| 88 |
r = http.request("GET", f"{self.https_url}/") |
| 89 |
assert r.status == 200 |
| 90 |
|
| 91 |
def test_https_proxy(self) -> None: |
| 92 |
with proxy_from_url(self.https_proxy_url, ca_certs=DEFAULT_CA) as https: |
| 93 |
r = https.request("GET", f"{self.https_url}/") |
| 94 |
assert r.status == 200 |
| 95 |
|
| 96 |
r = https.request("GET", f"{self.http_url}/") |
| 97 |
assert r.status == 200 |
| 98 |
|
| 99 |
def test_is_verified_http_proxy_to_http_target(self) -> None: |
| 100 |
with proxy_from_url(self.proxy_url, ca_certs=DEFAULT_CA) as http: |
| 101 |
r = http.request("GET", f"{self.http_url}/") |
| 102 |
assert r.status == 200 |
| 103 |
assert_is_verified(http, proxy=False, target=False) |
| 104 |
|
| 105 |
def test_is_verified_http_proxy_to_https_target(self) -> None: |
| 106 |
with proxy_from_url(self.proxy_url, ca_certs=DEFAULT_CA) as http: |
| 107 |
r = http.request("GET", f"{self.https_url}/") |
| 108 |
assert r.status == 200 |
| 109 |
assert_is_verified(http, proxy=False, target=True) |
| 110 |
|
| 111 |
def test_is_verified_https_proxy_to_http_target(self) -> None: |
| 112 |
with proxy_from_url(self.https_proxy_url, ca_certs=DEFAULT_CA) as https: |
| 113 |
r = https.request("GET", f"{self.http_url}/") |
| 114 |
assert r.status == 200 |
| 115 |
assert_is_verified(https, proxy=True, target=False) |
| 116 |
|
| 117 |
def test_is_verified_https_proxy_to_http_target_without_proxy_config(self) -> None: |
| 118 |
with proxy_from_url(self.https_proxy_url, ca_certs=DEFAULT_CA) as https: |
| 119 |
https.connection_pool_kw["_proxy_config"] = None |
| 120 |
r = https.request("GET", f"{self.http_url}/") |
| 121 |
assert r.status == 200 |
| 122 |
assert_is_verified(https, proxy=True, target=False) |
| 123 |
|
| 124 |
def test_is_verified_https_proxy_to_https_target(self) -> None: |
| 125 |
with proxy_from_url(self.https_proxy_url, ca_certs=DEFAULT_CA) as https: |
| 126 |
r = https.request("GET", f"{self.https_url}/") |
| 127 |
assert r.status == 200 |
| 128 |
assert_is_verified(https, proxy=True, target=True) |
| 129 |
|
| 130 |
def test_http_and_https_kwarg_ca_cert_data_proxy(self) -> None: |
| 131 |
with open(DEFAULT_CA) as pem_file: |
| 132 |
pem_file_data = pem_file.read() |
| 133 |
with proxy_from_url(self.https_proxy_url, ca_cert_data=pem_file_data) as https: |
| 134 |
r = https.request("GET", f"{self.https_url}/") |
| 135 |
assert r.status == 200 |
| 136 |
|
| 137 |
r = https.request("GET", f"{self.http_url}/") |
| 138 |
assert r.status == 200 |
| 139 |
|
| 140 |
def test_https_proxy_with_proxy_ssl_context(self) -> None: |
| 141 |
proxy_ssl_context = create_urllib3_context() |
| 142 |
proxy_ssl_context.load_verify_locations(DEFAULT_CA) |
| 143 |
with proxy_from_url( |
| 144 |
self.https_proxy_url, |
| 145 |
proxy_ssl_context=proxy_ssl_context, |
| 146 |
ca_certs=DEFAULT_CA, |
| 147 |
) as https: |
| 148 |
r = https.request("GET", f"{self.https_url}/") |
| 149 |
assert r.status == 200 |
| 150 |
|
| 151 |
r = https.request("GET", f"{self.http_url}/") |
| 152 |
assert r.status == 200 |
| 153 |
|
| 154 |
@withPyOpenSSL |
| 155 |
def test_https_proxy_with_proxy_ssl_context_pyopenssl(self) -> None: |
| 156 |
proxy_ssl_context = create_urllib3_context() |
| 157 |
proxy_ssl_context.load_verify_locations(DEFAULT_CA) |
| 158 |
|
| 159 |
with proxy_from_url( |
| 160 |
self.https_proxy_url, |
| 161 |
proxy_ssl_context=proxy_ssl_context, |
| 162 |
) as https: |
| 163 |
response = https.request("GET", f"{self.http_url}/") |
| 164 |
assert response.status == 200 |
| 165 |
|
| 166 |
@withPyOpenSSL |
| 167 |
def test_https_proxy_pyopenssl_not_supported(self) -> None: |
| 168 |
with proxy_from_url(self.https_proxy_url, ca_certs=DEFAULT_CA) as https: |
| 169 |
r = https.request("GET", f"{self.http_url}/") |
| 170 |
assert r.status == 200 |
| 171 |
|
| 172 |
with pytest.raises( |
| 173 |
ProxySchemeUnsupported, match="isn't available on non-native SSLContext" |
| 174 |
): |
| 175 |
https.request("GET", f"{self.https_url}/") |
| 176 |
|
| 177 |
def test_https_proxy_forwarding_for_https(self) -> None: |
| 178 |
with proxy_from_url( |
| 179 |
self.https_proxy_url, |
| 180 |
ca_certs=DEFAULT_CA, |
| 181 |
use_forwarding_for_https=True, |
| 182 |
) as https: |
| 183 |
r = https.request("GET", f"{self.http_url}/") |
| 184 |
assert r.status == 200 |
| 185 |
|
| 186 |
r = https.request("GET", f"{self.https_url}/") |
| 187 |
assert r.status == 200 |
| 188 |
|
| 189 |
@requires_network() |
| 190 |
@pytest.mark.parametrize( |
| 191 |
"proxy_ssl_context_kw", |
| 192 |
[ |
| 193 |
("ssl_context",), |
| 194 |
("proxy_ssl_context",), |
| 195 |
("ssl_context", "proxy_ssl_context"), |
| 196 |
], |
| 197 |
) |
| 198 |
def test_https_proxy_forwarding_for_https_with_custom_context( |
| 199 |
self, proxy_ssl_context_kw: tuple[str, ...] |
| 200 |
) -> None: |
| 201 |
""" |
| 202 |
Test that an HTTP request succeeds when using a forwarding HTTPS |
| 203 |
proxy with an SSL context provided via either |
| 204 |
``proxy_ssl_context``, ``ssl_context`` (fallback), or both. |
| 205 |
""" |
| 206 |
|
| 207 |
proxy_ctx = ssl.create_default_context() |
| 208 |
proxy_ctx.load_verify_locations(DEFAULT_CA) |
| 209 |
|
| 210 |
warning_checker: contextlib.AbstractContextManager[typing.Any] |
| 211 |
if "ssl_context" in proxy_ssl_context_kw: |
| 212 |
warning_checker = pytest.warns(FutureWarning, match="ssl_context") |
| 213 |
else: |
| 214 |
warning_checker = contextlib.nullcontext() |
| 215 |
with warning_checker: |
| 216 |
proxy = proxy_from_url( |
| 217 |
self.https_proxy_url, |
| 218 |
**{kw: proxy_ctx for kw in proxy_ssl_context_kw}, |
| 219 |
use_forwarding_for_https=True, |
| 220 |
) |
| 221 |
|
| 222 |
with proxy: |
| 223 |
resp = proxy.request("GET", self.https_url) |
| 224 |
assert resp.status == 200 |
| 225 |
|
| 226 |
def test_nagle_proxy(self) -> None: |
| 227 |
"""Test that proxy connections do not have TCP_NODELAY turned on""" |
| 228 |
with ProxyManager(self.proxy_url) as http: |
| 229 |
hc2 = http.connection_from_host(self.http_host, self.http_port) |
| 230 |
conn = hc2._get_conn() |
| 231 |
try: |
| 232 |
hc2._make_request(conn, "GET", f"{self.http_url}/") |
| 233 |
tcp_nodelay_setting = conn.sock.getsockopt( # type: ignore[attr-defined] |
| 234 |
socket.IPPROTO_TCP, socket.TCP_NODELAY |
| 235 |
) |
| 236 |
assert tcp_nodelay_setting == 0, ( |
| 237 |
"Expected TCP_NODELAY for proxies to be set " |
| 238 |
"to zero, instead was %s" % tcp_nodelay_setting |
| 239 |
) |
| 240 |
finally: |
| 241 |
conn.close() |
| 242 |
|
| 243 |
@pytest.mark.parametrize("proxy_scheme", ["http", "https"]) |
| 244 |
@pytest.mark.parametrize("target_scheme", ["http", "https"]) |
| 245 |
def test_proxy_conn_fail_from_dns( |
| 246 |
self, proxy_scheme: str, target_scheme: str |
| 247 |
) -> None: |
| 248 |
host, port = get_unreachable_address() |
| 249 |
with proxy_from_url( |
| 250 |
f"{proxy_scheme}://{host}:{port}/", retries=1, timeout=LONG_TIMEOUT |
| 251 |
) as http: |
| 252 |
if target_scheme == "https": |
| 253 |
target_url = self.https_url |
| 254 |
else: |
| 255 |
target_url = self.http_url |
| 256 |
|
| 257 |
with pytest.raises(MaxRetryError) as e: |
| 258 |
http.request("GET", f"{target_url}/") |
| 259 |
assert isinstance(e.value.reason, ProxyError) |
| 260 |
assert isinstance( |
| 261 |
e.value.reason.original_error, urllib3.exceptions.NameResolutionError |
| 262 |
) |
| 263 |
|
| 264 |
def test_oldapi(self) -> None: |
| 265 |
with ProxyManager( |
| 266 |
connection_from_url(self.proxy_url), ca_certs=DEFAULT_CA # type: ignore[arg-type] |
| 267 |
) as http: |
| 268 |
r = http.request("GET", f"{self.http_url}/") |
| 269 |
assert r.status == 200 |
| 270 |
|
| 271 |
r = http.request("GET", f"{self.https_url}/") |
| 272 |
assert r.status == 200 |
| 273 |
|
| 274 |
@resolvesLocalhostFQDN() |
| 275 |
def test_proxy_https_fqdn(self) -> None: |
| 276 |
with proxy_from_url(self.proxy_url, ca_certs=DEFAULT_CA) as http: |
| 277 |
r = http.request("GET", f"{self.https_url_fqdn}/") |
| 278 |
assert r.status == 200 |
| 279 |
|
| 280 |
def test_proxy_verified(self) -> None: |
| 281 |
with proxy_from_url( |
| 282 |
self.proxy_url, cert_reqs="REQUIRED", ca_certs=self.bad_ca_path |
| 283 |
) as http: |
| 284 |
with http._new_pool( |
| 285 |
"https", self.https_host, self.https_port |
| 286 |
) as https_pool: |
| 287 |
with pytest.raises(MaxRetryError) as e: |
| 288 |
https_pool.request("GET", "/", retries=0) |
| 289 |
assert isinstance(e.value.reason, SSLError) |
| 290 |
assert ( |
| 291 |
"certificate verify failed" in str(e.value.reason) |
| 292 |
# PyPy is more specific |
| 293 |
or "self signed certificate in certificate chain" in str(e.value.reason) |
| 294 |
), f"Expected 'certificate verify failed', instead got: {e.value.reason!r}" |
| 295 |
|
| 296 |
http = proxy_from_url( |
| 297 |
self.proxy_url, cert_reqs="REQUIRED", ca_certs=DEFAULT_CA |
| 298 |
) |
| 299 |
with http._new_pool( |
| 300 |
"https", self.https_host, self.https_port |
| 301 |
) as https_pool2: |
| 302 |
with contextlib.closing(https_pool._new_conn()) as conn: |
| 303 |
assert conn.__class__ == VerifiedHTTPSConnection |
| 304 |
https_pool2.request( |
| 305 |
"GET", "/" |
| 306 |
) # Should succeed without exceptions. |
| 307 |
|
| 308 |
http = proxy_from_url( |
| 309 |
self.proxy_url, cert_reqs="REQUIRED", ca_certs=DEFAULT_CA |
| 310 |
) |
| 311 |
with http._new_pool( |
| 312 |
"https", "127.0.0.1", self.https_port |
| 313 |
) as https_fail_pool: |
| 314 |
with pytest.raises( |
| 315 |
MaxRetryError, match="doesn't match|IP address mismatch" |
| 316 |
) as e: |
| 317 |
https_fail_pool.request("GET", "/", retries=0) |
| 318 |
assert isinstance(e.value.reason, SSLError) |
| 319 |
|
| 320 |
def test_redirect(self) -> None: |
| 321 |
with proxy_from_url(self.proxy_url) as http: |
| 322 |
r = http.request( |
| 323 |
"GET", |
| 324 |
f"{self.http_url}/redirect", |
| 325 |
fields={"target": f"{self.http_url}/"}, |
| 326 |
redirect=False, |
| 327 |
) |
| 328 |
|
| 329 |
assert r.status == 303 |
| 330 |
|
| 331 |
r = http.request( |
| 332 |
"GET", |
| 333 |
f"{self.http_url}/redirect", |
| 334 |
fields={"target": f"{self.http_url}/"}, |
| 335 |
) |
| 336 |
|
| 337 |
assert r.status == 200 |
| 338 |
assert r.data == b"Dummy server!" |
| 339 |
|
| 340 |
def test_cross_host_redirect(self) -> None: |
| 341 |
with proxy_from_url(self.proxy_url) as http: |
| 342 |
cross_host_location = f"{self.http_url_alt}/echo?a=b" |
| 343 |
with pytest.raises(MaxRetryError): |
| 344 |
http.request( |
| 345 |
"GET", |
| 346 |
f"{self.http_url}/redirect", |
| 347 |
fields={"target": cross_host_location}, |
| 348 |
retries=0, |
| 349 |
) |
| 350 |
|
| 351 |
r = http.request( |
| 352 |
"GET", |
| 353 |
f"{self.http_url}/redirect", |
| 354 |
fields={"target": f"{self.http_url_alt}/echo?a=b"}, |
| 355 |
retries=1, |
| 356 |
) |
| 357 |
assert isinstance(r, HTTPResponse) |
| 358 |
assert r._pool is not None |
| 359 |
assert r._pool.host != self.http_host_alt |
| 360 |
|
| 361 |
_sensitive_headers = { |
| 362 |
"Authorization": "foo", |
| 363 |
"Proxy-Authorization": "bar", |
| 364 |
"Cookie": "foo=bar", |
| 365 |
} |
| 366 |
|
| 367 |
@pytest.mark.parametrize( |
| 368 |
"sensitive_headers", |
| 369 |
(_sensitive_headers, {k.lower(): v for k, v in _sensitive_headers.items()}), |
| 370 |
ids=("capitalized", "lowercase"), |
| 371 |
) |
| 372 |
def test_cross_host_redirect_remove_headers_via_proxy_manager( |
| 373 |
self, sensitive_headers: dict[str, str] |
| 374 |
) -> None: |
| 375 |
headers_url = f"{self.http_url_alt}/headers" |
| 376 |
initial_url = f"{self.http_url}/redirect?target={headers_url}" |
| 377 |
with proxy_from_url(self.proxy_url) as proxy_mgr: |
| 378 |
r = proxy_mgr.request( |
| 379 |
"GET", initial_url, headers=sensitive_headers, retries=1 |
| 380 |
) |
| 381 |
assert r.status == 200 |
| 382 |
assert r.retries is not None |
| 383 |
assert r.retries.history == ( |
| 384 |
RequestHistory( |
| 385 |
method="GET", |
| 386 |
url=initial_url, |
| 387 |
error=None, |
| 388 |
status=303, |
| 389 |
redirect_location=headers_url, |
| 390 |
), |
| 391 |
) |
| 392 |
data = r.json() |
| 393 |
for header in sensitive_headers: |
| 394 |
assert header not in data |
| 395 |
|
| 396 |
@pytest.mark.parametrize( |
| 397 |
"sensitive_headers", |
| 398 |
(_sensitive_headers, {k.lower(): v for k, v in _sensitive_headers.items()}), |
| 399 |
ids=("capitalized", "lowercase"), |
| 400 |
) |
| 401 |
def test_cross_host_redirect_remove_headers_via_pool( |
| 402 |
self, sensitive_headers: dict[str, str] |
| 403 |
) -> None: |
| 404 |
headers_url = f"{self.http_url_alt}/headers" |
| 405 |
initial_url = f"{self.http_url}/redirect?target={headers_url}" |
| 406 |
with proxy_from_url(self.proxy_url) as proxy_mgr: |
| 407 |
pool = proxy_mgr.connection_from_url(self.http_url) |
| 408 |
r = pool.urlopen( |
| 409 |
"GET", |
| 410 |
initial_url, |
| 411 |
headers=sensitive_headers, |
| 412 |
retries=1, |
| 413 |
redirect=True, |
| 414 |
assert_same_host=False, |
| 415 |
preload_content=True, |
| 416 |
) |
| 417 |
assert r.status == 200 |
| 418 |
assert r.retries is not None |
| 419 |
assert r.retries.history == ( |
| 420 |
RequestHistory( |
| 421 |
method="GET", |
| 422 |
url=initial_url, |
| 423 |
error=None, |
| 424 |
status=303, |
| 425 |
redirect_location=headers_url, |
| 426 |
), |
| 427 |
) |
| 428 |
data = r.json() |
| 429 |
for header in sensitive_headers: |
| 430 |
assert header not in data |
| 431 |
|
| 432 |
def test_cross_protocol_redirect(self) -> None: |
| 433 |
with proxy_from_url(self.proxy_url, ca_certs=DEFAULT_CA) as http: |
| 434 |
cross_protocol_location = f"{self.https_url}/echo?a=b" |
| 435 |
with pytest.raises(MaxRetryError): |
| 436 |
http.request( |
| 437 |
"GET", |
| 438 |
f"{self.http_url}/redirect", |
| 439 |
fields={"target": cross_protocol_location}, |
| 440 |
retries=0, |
| 441 |
) |
| 442 |
|
| 443 |
r = http.request( |
| 444 |
"GET", |
| 445 |
f"{self.http_url}/redirect", |
| 446 |
fields={"target": f"{self.https_url}/echo?a=b"}, |
| 447 |
retries=1, |
| 448 |
) |
| 449 |
assert isinstance(r, HTTPResponse) |
| 450 |
assert r._pool is not None |
| 451 |
assert r._pool.host == self.https_host |
| 452 |
|
| 453 |
def test_headers(self) -> None: |
| 454 |
with proxy_from_url( |
| 455 |
self.proxy_url, |
| 456 |
headers={"Foo": "bar"}, |
| 457 |
proxy_headers={"Hickory": "dickory"}, |
| 458 |
ca_certs=DEFAULT_CA, |
| 459 |
) as http: |
| 460 |
r = http.request_encode_url("GET", f"{self.http_url}/headers") |
| 461 |
returned_headers = r.json() |
| 462 |
assert returned_headers.get("Foo") == "bar" |
| 463 |
assert returned_headers.get("Hickory") == "dickory" |
| 464 |
assert returned_headers.get("Host") == f"{self.http_host}:{self.http_port}" |
| 465 |
|
| 466 |
r = http.request_encode_url("GET", f"{self.http_url_alt}/headers") |
| 467 |
returned_headers = r.json() |
| 468 |
assert returned_headers.get("Foo") == "bar" |
| 469 |
assert returned_headers.get("Hickory") == "dickory" |
| 470 |
assert ( |
| 471 |
returned_headers.get("Host") == f"{self.http_host_alt}:{self.http_port}" |
| 472 |
) |
| 473 |
|
| 474 |
r = http.request_encode_url("GET", f"{self.https_url}/headers") |
| 475 |
returned_headers = r.json() |
| 476 |
assert returned_headers.get("Foo") == "bar" |
| 477 |
assert returned_headers.get("Hickory") is None |
| 478 |
assert ( |
| 479 |
returned_headers.get("Host") == f"{self.https_host}:{self.https_port}" |
| 480 |
) |
| 481 |
|
| 482 |
r = http.request_encode_body("POST", f"{self.http_url}/headers") |
| 483 |
returned_headers = r.json() |
| 484 |
assert returned_headers.get("Foo") == "bar" |
| 485 |
assert returned_headers.get("Hickory") == "dickory" |
| 486 |
assert returned_headers.get("Host") == f"{self.http_host}:{self.http_port}" |
| 487 |
|
| 488 |
r = http.request_encode_url( |
| 489 |
"GET", f"{self.http_url}/headers", headers={"Baz": "quux"} |
| 490 |
) |
| 491 |
returned_headers = r.json() |
| 492 |
assert returned_headers.get("Foo") is None |
| 493 |
assert returned_headers.get("Baz") == "quux" |
| 494 |
assert returned_headers.get("Hickory") == "dickory" |
| 495 |
assert returned_headers.get("Host") == f"{self.http_host}:{self.http_port}" |
| 496 |
|
| 497 |
r = http.request_encode_url( |
| 498 |
"GET", f"{self.https_url}/headers", headers={"Baz": "quux"} |
| 499 |
) |
| 500 |
returned_headers = r.json() |
| 501 |
assert returned_headers.get("Foo") is None |
| 502 |
assert returned_headers.get("Baz") == "quux" |
| 503 |
assert returned_headers.get("Hickory") is None |
| 504 |
assert ( |
| 505 |
returned_headers.get("Host") == f"{self.https_host}:{self.https_port}" |
| 506 |
) |
| 507 |
|
| 508 |
r = http.request_encode_body( |
| 509 |
"GET", f"{self.http_url}/headers", headers={"Baz": "quux"} |
| 510 |
) |
| 511 |
returned_headers = r.json() |
| 512 |
assert returned_headers.get("Foo") is None |
| 513 |
assert returned_headers.get("Baz") == "quux" |
| 514 |
assert returned_headers.get("Hickory") == "dickory" |
| 515 |
assert returned_headers.get("Host") == f"{self.http_host}:{self.http_port}" |
| 516 |
|
| 517 |
r = http.request_encode_body( |
| 518 |
"GET", f"{self.https_url}/headers", headers={"Baz": "quux"} |
| 519 |
) |
| 520 |
returned_headers = r.json() |
| 521 |
assert returned_headers.get("Foo") is None |
| 522 |
assert returned_headers.get("Baz") == "quux" |
| 523 |
assert returned_headers.get("Hickory") is None |
| 524 |
assert ( |
| 525 |
returned_headers.get("Host") == f"{self.https_host}:{self.https_port}" |
| 526 |
) |
| 527 |
|
| 528 |
def test_https_headers(self) -> None: |
| 529 |
with proxy_from_url( |
| 530 |
self.https_proxy_url, |
| 531 |
headers={"Foo": "bar"}, |
| 532 |
proxy_headers={"Hickory": "dickory"}, |
| 533 |
ca_certs=DEFAULT_CA, |
| 534 |
) as http: |
| 535 |
r = http.request_encode_url("GET", f"{self.http_url}/headers") |
| 536 |
returned_headers = r.json() |
| 537 |
assert returned_headers.get("Foo") == "bar" |
| 538 |
assert returned_headers.get("Hickory") == "dickory" |
| 539 |
assert returned_headers.get("Host") == f"{self.http_host}:{self.http_port}" |
| 540 |
|
| 541 |
r = http.request_encode_url("GET", f"{self.http_url_alt}/headers") |
| 542 |
returned_headers = r.json() |
| 543 |
assert returned_headers.get("Foo") == "bar" |
| 544 |
assert returned_headers.get("Hickory") == "dickory" |
| 545 |
assert ( |
| 546 |
returned_headers.get("Host") == f"{self.http_host_alt}:{self.http_port}" |
| 547 |
) |
| 548 |
|
| 549 |
r = http.request_encode_body( |
| 550 |
"GET", f"{self.https_url}/headers", headers={"Baz": "quux"} |
| 551 |
) |
| 552 |
returned_headers = r.json() |
| 553 |
assert returned_headers.get("Foo") is None |
| 554 |
assert returned_headers.get("Baz") == "quux" |
| 555 |
assert returned_headers.get("Hickory") is None |
| 556 |
assert ( |
| 557 |
returned_headers.get("Host") == f"{self.https_host}:{self.https_port}" |
| 558 |
) |
| 559 |
|
| 560 |
def test_https_headers_forwarding_for_https(self) -> None: |
| 561 |
with proxy_from_url( |
| 562 |
self.https_proxy_url, |
| 563 |
headers={"Foo": "bar"}, |
| 564 |
proxy_headers={"Hickory": "dickory"}, |
| 565 |
ca_certs=DEFAULT_CA, |
| 566 |
use_forwarding_for_https=True, |
| 567 |
) as http: |
| 568 |
r = http.request_encode_url("GET", f"{self.https_url}/headers") |
| 569 |
returned_headers = r.json() |
| 570 |
assert returned_headers.get("Foo") == "bar" |
| 571 |
assert returned_headers.get("Hickory") == "dickory" |
| 572 |
assert ( |
| 573 |
returned_headers.get("Host") == f"{self.https_host}:{self.https_port}" |
| 574 |
) |
| 575 |
|
| 576 |
def test_headerdict(self) -> None: |
| 577 |
default_headers = HTTPHeaderDict(a="b") |
| 578 |
proxy_headers = HTTPHeaderDict() |
| 579 |
proxy_headers.add("foo", "bar") |
| 580 |
|
| 581 |
with proxy_from_url( |
| 582 |
self.proxy_url, headers=default_headers, proxy_headers=proxy_headers |
| 583 |
) as http: |
| 584 |
request_headers = HTTPHeaderDict(baz="quux") |
| 585 |
r = http.request("GET", f"{self.http_url}/headers", headers=request_headers) |
| 586 |
returned_headers = r.json() |
| 587 |
assert returned_headers.get("Foo") == "bar" |
| 588 |
assert returned_headers.get("Baz") == "quux" |
| 589 |
|
| 590 |
def test_proxy_pooling(self) -> None: |
| 591 |
with proxy_from_url(self.proxy_url, cert_reqs="NONE") as http: |
| 592 |
for x in range(2): |
| 593 |
http.urlopen("GET", self.http_url) |
| 594 |
assert len(http.pools) == 1 |
| 595 |
|
| 596 |
for x in range(2): |
| 597 |
http.urlopen("GET", self.http_url_alt) |
| 598 |
assert len(http.pools) == 1 |
| 599 |
|
| 600 |
for x in range(2): |
| 601 |
with pytest.warns(InsecureRequestWarning): |
| 602 |
http.urlopen("GET", self.https_url) |
| 603 |
assert len(http.pools) == 2 |
| 604 |
|
| 605 |
for x in range(2): |
| 606 |
with pytest.warns(InsecureRequestWarning): |
| 607 |
http.urlopen("GET", self.https_url_alt) |
| 608 |
assert len(http.pools) == 3 |
| 609 |
|
| 610 |
def test_proxy_pooling_ext(self) -> None: |
| 611 |
with proxy_from_url(self.proxy_url) as http: |
| 612 |
hc1 = http.connection_from_url(self.http_url) |
| 613 |
hc2 = http.connection_from_host(self.http_host, self.http_port) |
| 614 |
hc3 = http.connection_from_url(self.http_url_alt) |
| 615 |
hc4 = http.connection_from_host(self.http_host_alt, self.http_port) |
| 616 |
assert hc1 == hc2 |
| 617 |
assert hc2 == hc3 |
| 618 |
assert hc3 == hc4 |
| 619 |
|
| 620 |
sc1 = http.connection_from_url(self.https_url) |
| 621 |
sc2 = http.connection_from_host( |
| 622 |
self.https_host, self.https_port, scheme="https" |
| 623 |
) |
| 624 |
sc3 = http.connection_from_url(self.https_url_alt) |
| 625 |
sc4 = http.connection_from_host( |
| 626 |
self.https_host_alt, self.https_port, scheme="https" |
| 627 |
) |
| 628 |
assert sc1 == sc2 |
| 629 |
assert sc2 != sc3 |
| 630 |
assert sc3 == sc4 |
| 631 |
|
| 632 |
@requires_network() |
| 633 |
@pytest.mark.parametrize( |
| 634 |
["proxy_scheme", "target_scheme", "use_forwarding_for_https"], |
| 635 |
[ |
| 636 |
("http", "http", False), |
| 637 |
("https", "http", False), |
| 638 |
# 'use_forwarding_for_https' is only valid for HTTPS+HTTPS. |
| 639 |
("https", "https", True), |
| 640 |
], |
| 641 |
) |
| 642 |
def test_forwarding_proxy_request_timeout( |
| 643 |
self, proxy_scheme: str, target_scheme: str, use_forwarding_for_https: bool |
| 644 |
) -> None: |
| 645 |
proxy_url = self.https_proxy_url if proxy_scheme == "https" else self.proxy_url |
| 646 |
target_url = f"{target_scheme}://{TARPIT_HOST}" |
| 647 |
|
| 648 |
with proxy_from_url( |
| 649 |
proxy_url, |
| 650 |
ca_certs=DEFAULT_CA, |
| 651 |
use_forwarding_for_https=use_forwarding_for_https, |
| 652 |
) as proxy: |
| 653 |
with pytest.raises(MaxRetryError) as e: |
| 654 |
timeout = Timeout(connect=LONG_TIMEOUT, read=SHORT_TIMEOUT) |
| 655 |
proxy.request("GET", target_url, timeout=timeout) |
| 656 |
|
| 657 |
# We sent the request to the proxy but didn't get any response |
| 658 |
# so we're not sure if that's being caused by the proxy or the |
| 659 |
# target so we put the blame on the target. |
| 660 |
assert isinstance(e.value.reason, ReadTimeoutError) |
| 661 |
|
| 662 |
@requires_network() |
| 663 |
@pytest.mark.parametrize( |
| 664 |
["proxy_scheme", "target_scheme"], [("http", "https"), ("https", "https")] |
| 665 |
) |
| 666 |
def test_tunneling_proxy_request_timeout( |
| 667 |
self, proxy_scheme: str, target_scheme: str |
| 668 |
) -> None: |
| 669 |
proxy_url = self.https_proxy_url if proxy_scheme == "https" else self.proxy_url |
| 670 |
target_url = f"{target_scheme}://{TARPIT_HOST}" |
| 671 |
|
| 672 |
with proxy_from_url( |
| 673 |
proxy_url, |
| 674 |
ca_certs=DEFAULT_CA, |
| 675 |
) as proxy: |
| 676 |
with pytest.raises(MaxRetryError) as e: |
| 677 |
timeout = Timeout(connect=LONG_TIMEOUT, read=SHORT_TIMEOUT) |
| 678 |
proxy.request("GET", target_url, timeout=timeout) |
| 679 |
|
| 680 |
assert isinstance(e.value.reason, ReadTimeoutError) |
| 681 |
|
| 682 |
@requires_network() |
| 683 |
@pytest.mark.parametrize( |
| 684 |
["proxy_scheme", "target_scheme", "use_forwarding_for_https"], |
| 685 |
[ |
| 686 |
("http", "http", False), |
| 687 |
("https", "http", False), |
| 688 |
# 'use_forwarding_for_https' is only valid for HTTPS+HTTPS. |
| 689 |
("https", "https", True), |
| 690 |
], |
| 691 |
) |
| 692 |
def test_forwarding_proxy_connect_timeout( |
| 693 |
self, proxy_scheme: str, target_scheme: str, use_forwarding_for_https: bool |
| 694 |
) -> None: |
| 695 |
proxy_url = f"{proxy_scheme}://{TARPIT_HOST}" |
| 696 |
target_url = self.https_url if target_scheme == "https" else self.http_url |
| 697 |
|
| 698 |
with proxy_from_url( |
| 699 |
proxy_url, |
| 700 |
ca_certs=DEFAULT_CA, |
| 701 |
timeout=SHORT_TIMEOUT, |
| 702 |
use_forwarding_for_https=use_forwarding_for_https, |
| 703 |
) as proxy: |
| 704 |
with pytest.raises(MaxRetryError) as e: |
| 705 |
proxy.request("GET", target_url) |
| 706 |
|
| 707 |
assert isinstance(e.value.reason, ProxyError) |
| 708 |
assert isinstance(e.value.reason.original_error, ConnectTimeoutError) |
| 709 |
|
| 710 |
@requires_network() |
| 711 |
@pytest.mark.parametrize( |
| 712 |
["proxy_scheme", "target_scheme"], [("http", "https"), ("https", "https")] |
| 713 |
) |
| 714 |
def test_tunneling_proxy_connect_timeout( |
| 715 |
self, proxy_scheme: str, target_scheme: str |
| 716 |
) -> None: |
| 717 |
proxy_url = f"{proxy_scheme}://{TARPIT_HOST}" |
| 718 |
target_url = self.https_url if target_scheme == "https" else self.http_url |
| 719 |
|
| 720 |
with proxy_from_url( |
| 721 |
proxy_url, ca_certs=DEFAULT_CA, timeout=SHORT_TIMEOUT |
| 722 |
) as proxy: |
| 723 |
with pytest.raises(MaxRetryError) as e: |
| 724 |
proxy.request("GET", target_url) |
| 725 |
|
| 726 |
assert isinstance(e.value.reason, ProxyError) |
| 727 |
assert isinstance(e.value.reason.original_error, ConnectTimeoutError) |
| 728 |
|
| 729 |
@requires_network() |
| 730 |
@pytest.mark.parametrize( |
| 731 |
["target_scheme", "use_forwarding_for_https"], |
| 732 |
[ |
| 733 |
("http", False), |
| 734 |
("https", False), |
| 735 |
("https", True), |
| 736 |
], |
| 737 |
) |
| 738 |
def test_https_proxy_tls_error( |
| 739 |
self, target_scheme: str, use_forwarding_for_https: str |
| 740 |
) -> None: |
| 741 |
target_url = self.https_url if target_scheme == "https" else self.http_url |
| 742 |
proxy_ctx = ssl.create_default_context() |
| 743 |
with proxy_from_url( |
| 744 |
self.https_proxy_url, |
| 745 |
proxy_ssl_context=proxy_ctx, |
| 746 |
use_forwarding_for_https=use_forwarding_for_https, |
| 747 |
) as proxy: |
| 748 |
with pytest.raises(MaxRetryError) as e: |
| 749 |
proxy.request("GET", target_url) |
| 750 |
assert isinstance(e.value.reason, ProxyError) |
| 751 |
assert isinstance(e.value.reason.original_error, SSLError) |
| 752 |
|
| 753 |
@requires_network() |
| 754 |
@pytest.mark.parametrize("proxy_scheme", ["http", "https"]) |
| 755 |
def test_proxy_https_target_tls_error(self, proxy_scheme: str) -> None: |
| 756 |
proxy_url = self.https_proxy_url if proxy_scheme == "https" else self.proxy_url |
| 757 |
proxy_ctx = ssl.create_default_context() |
| 758 |
proxy_ctx.load_verify_locations(DEFAULT_CA) |
| 759 |
ctx = ssl.create_default_context() |
| 760 |
|
| 761 |
with proxy_from_url( |
| 762 |
proxy_url, |
| 763 |
proxy_ssl_context=proxy_ctx, |
| 764 |
ssl_context=ctx, |
| 765 |
) as proxy: |
| 766 |
with pytest.raises(MaxRetryError) as e: |
| 767 |
proxy.request("GET", self.https_url) |
| 768 |
assert isinstance(e.value.reason, SSLError) |
| 769 |
|
| 770 |
@requires_network() |
| 771 |
def test_forwarding_proxy_tls_error_with_fallback(self) -> None: |
| 772 |
""" |
| 773 |
Test that when only ``ssl_context`` is passed to a forwarding |
| 774 |
HTTPS proxy, a ``FutureWarning`` is emitted and if the TLS |
| 775 |
handshake with the proxy fails using that context, the error is |
| 776 |
a ``ProxyError`` wrapping the original TLS error. |
| 777 |
""" |
| 778 |
ctx = ssl.create_default_context() |
| 779 |
|
| 780 |
with pytest.warns(FutureWarning, match="ssl_context"): |
| 781 |
proxy = proxy_from_url( |
| 782 |
self.https_proxy_url, |
| 783 |
ssl_context=ctx, |
| 784 |
use_forwarding_for_https=True, |
| 785 |
) |
| 786 |
|
| 787 |
with proxy: |
| 788 |
with pytest.raises(MaxRetryError) as e: |
| 789 |
proxy.request("GET", self.https_url) |
| 790 |
assert isinstance(e.value.reason, ProxyError) |
| 791 |
assert isinstance(e.value.reason.original_error, SSLError) |
| 792 |
|
| 793 |
@requires_network() |
| 794 |
def test_forwarding_proxy_ssl_context_precedence(self) -> None: |
| 795 |
""" |
| 796 |
Test that when both ``ssl_context`` and ``proxy_ssl_context`` |
| 797 |
are passed to a forwarding HTTPS proxy, ``proxy_ssl_context`` is |
| 798 |
used for the proxy connection and ``ssl_context`` is ignored |
| 799 |
(with a warning). |
| 800 |
""" |
| 801 |
ssl_context = create_urllib3_context(cert_reqs=ssl.CERT_REQUIRED) |
| 802 |
proxy_ssl_context = create_urllib3_context(cert_reqs=ssl.CERT_NONE) |
| 803 |
|
| 804 |
with pytest.warns(FutureWarning, match="ssl_context"): |
| 805 |
proxy = proxy_from_url( |
| 806 |
self.https_proxy_url, |
| 807 |
proxy_ssl_context=proxy_ssl_context, |
| 808 |
ssl_context=ssl_context, |
| 809 |
use_forwarding_for_https=True, |
| 810 |
) |
| 811 |
|
| 812 |
with proxy: |
| 813 |
pool = proxy.connection_from_url(self.https_url) |
| 814 |
with contextlib.closing(pool._new_conn()) as conn: |
| 815 |
conn = typing.cast(HTTPSConnection, conn) |
| 816 |
conn.connect() |
| 817 |
assert isinstance(conn.sock, ssl.SSLSocket) |
| 818 |
assert conn.sock.context is proxy_ssl_context |
| 819 |
assert proxy_ssl_context.verify_mode == ssl.CERT_NONE |
| 820 |
|
| 821 |
@requires_network() |
| 822 |
def test_forwarding_proxy_ssl_context_fallback(self) -> None: |
| 823 |
""" |
| 824 |
Test that when only ``ssl_context`` is passed to a forwarding |
| 825 |
HTTPS proxy, a ``FutureWarning`` is emitted and ``ssl_context`` |
| 826 |
is used as the proxy TLS context (fallback). |
| 827 |
""" |
| 828 |
ssl_context = create_urllib3_context(cert_reqs=ssl.CERT_NONE) |
| 829 |
|
| 830 |
with pytest.warns(FutureWarning, match="ssl_context"): |
| 831 |
proxy = proxy_from_url( |
| 832 |
self.https_proxy_url, |
| 833 |
ssl_context=ssl_context, |
| 834 |
cert_reqs=ssl.CERT_REQUIRED, |
| 835 |
ca_certs=DEFAULT_CA, |
| 836 |
use_forwarding_for_https=True, |
| 837 |
) |
| 838 |
|
| 839 |
assert proxy.proxy_ssl_context is ssl_context |
| 840 |
assert proxy.proxy_config is not None |
| 841 |
assert proxy.proxy_config.ssl_context is None |
| 842 |
|
| 843 |
with proxy: |
| 844 |
pool = proxy.connection_from_url(self.https_url) |
| 845 |
with contextlib.closing(pool._new_conn()) as conn: |
| 846 |
conn = typing.cast(HTTPSConnection, conn) |
| 847 |
conn.connect() |
| 848 |
assert isinstance(conn.sock, ssl.SSLSocket) |
| 849 |
assert conn.sock.context is ssl_context |
| 850 |
assert ssl_context.verify_mode == ssl.CERT_REQUIRED |
| 851 |
|
| 852 |
@requires_network() |
| 853 |
def test_https_proxy_to_http_target_ssl_context_fallback(self) -> None: |
| 854 |
ssl_context = create_urllib3_context() |
| 855 |
ssl_context.load_verify_locations(DEFAULT_CA) |
| 856 |
|
| 857 |
with proxy_from_url( |
| 858 |
self.https_proxy_url, |
| 859 |
ssl_context=ssl_context, |
| 860 |
) as proxy: |
| 861 |
pool = proxy.connection_from_url(self.http_url) |
| 862 |
with contextlib.closing(pool._new_conn()) as conn: |
| 863 |
conn = typing.cast(HTTPSConnection, conn) |
| 864 |
conn.connect() |
| 865 |
assert isinstance(conn.sock, ssl.SSLSocket) |
| 866 |
assert conn.sock.context is ssl_context |
| 867 |
|
| 868 |
@requires_network() |
| 869 |
def test_forwarding_non_https_proxy_ssl_context_fallback(self) -> None: |
| 870 |
""" |
| 871 |
Test that when only ``ssl_context`` is passed to a forwarding |
| 872 |
non-HTTPS proxy, no warning or error is emitted. |
| 873 |
""" |
| 874 |
ssl_context = ssl.create_default_context(cafile=DEFAULT_CA) |
| 875 |
# No warning/error should be emitted even when ``ssl_context`` |
| 876 |
# is provided to a non-HTTPS proxy for some reason. |
| 877 |
proxy = proxy_from_url( |
| 878 |
self.proxy_url, |
| 879 |
ssl_context=ssl_context, |
| 880 |
use_forwarding_for_https=True, |
| 881 |
) |
| 882 |
with proxy: |
| 883 |
resp = proxy.request("GET", self.https_url) |
| 884 |
assert resp.status == 200 |
| 885 |
|
| 886 |
def test_scheme_host_case_insensitive(self) -> None: |
| 887 |
"""Assert that upper-case schemes and hosts are normalized.""" |
| 888 |
with proxy_from_url(self.proxy_url.upper(), ca_certs=DEFAULT_CA) as http: |
| 889 |
r = http.request("GET", f"{self.http_url.upper()}/") |
| 890 |
assert r.status == 200 |
| 891 |
|
| 892 |
r = http.request("GET", f"{self.https_url.upper()}/") |
| 893 |
assert r.status == 200 |
| 894 |
|
| 895 |
@pytest.mark.parametrize( |
| 896 |
"url, error_msg", |
| 897 |
[ |
| 898 |
( |
| 899 |
"127.0.0.1", |
| 900 |
"Proxy URL had no scheme, should start with http:// or https://", |
| 901 |
), |
| 902 |
( |
| 903 |
"localhost:8080", |
| 904 |
"Proxy URL had no scheme, should start with http:// or https://", |
| 905 |
), |
| 906 |
( |
| 907 |
"ftp://google.com", |
| 908 |
"Proxy URL had unsupported scheme ftp, should use http:// or https://", |
| 909 |
), |
| 910 |
], |
| 911 |
) |
| 912 |
def test_invalid_schema(self, url: str, error_msg: str) -> None: |
| 913 |
with pytest.raises(ProxySchemeUnknown, match=error_msg): |
| 914 |
proxy_from_url(url) |
| 915 |
|
| 916 |
|
| 917 |
@pytest.mark.skipif(not HAS_IPV6, reason="Only runs on IPv6 systems") |
| 918 |
class TestIPv6HTTPProxyManager(IPv6HypercornDummyProxyTestCase): |
| 919 |
@classmethod |
| 920 |
def setup_class(cls) -> None: |
| 921 |
super().setup_class() |
| 922 |
cls.http_url = f"http://{cls.http_host}:{int(cls.http_port)}" |
| 923 |
cls.http_url_alt = f"http://{cls.http_host_alt}:{int(cls.http_port)}" |
| 924 |
cls.https_url = f"https://{cls.https_host}:{int(cls.https_port)}" |
| 925 |
cls.https_url_alt = f"https://{cls.https_host_alt}:{int(cls.https_port)}" |
| 926 |
cls.proxy_url = f"http://[{cls.proxy_host}]:{int(cls.proxy_port)}" |
| 927 |
|
| 928 |
def test_basic_ipv6_proxy(self) -> None: |
| 929 |
with proxy_from_url(self.proxy_url, ca_certs=DEFAULT_CA) as http: |
| 930 |
r = http.request("GET", f"{self.http_url}/") |
| 931 |
assert r.status == 200 |
| 932 |
|
| 933 |
r = http.request("GET", f"{self.https_url}/") |
| 934 |
assert r.status == 200 |
| 935 |
|
| 936 |
|
| 937 |
class TestHTTPSProxyVerification: |
| 938 |
@staticmethod |
| 939 |
def _get_proxy_fingerprint_md5(ca_path: str) -> str: |
| 940 |
proxy_pem_path = pathlib.Path(ca_path).parent / "proxy.pem" |
| 941 |
proxy_der = ssl.PEM_cert_to_DER_cert(proxy_pem_path.read_text()) |
| 942 |
proxy_hashed = hashlib.md5(proxy_der).digest() |
| 943 |
fingerprint = binascii.hexlify(proxy_hashed).decode("ascii") |
| 944 |
return fingerprint |
| 945 |
|
| 946 |
@staticmethod |
| 947 |
def _get_certificate_formatted_proxy_host(host: str) -> str: |
| 948 |
try: |
| 949 |
addr = ipaddress.ip_address(host) |
| 950 |
except ValueError: |
| 951 |
return host |
| 952 |
|
| 953 |
if addr.version != 6: |
| 954 |
return host |
| 955 |
|
| 956 |
# Transform ipv6 like '::1' to 0:0:0:0:0:0:0:1 via '0000:0000:0000:0000:0000:0000:0000:0001' |
| 957 |
return addr.exploded.replace("0000", "0").replace("000", "") |
| 958 |
|
| 959 |
def test_https_proxy_assert_fingerprint_md5( |
| 960 |
self, no_san_proxy_with_server: tuple[ServerConfig, ServerConfig] |
| 961 |
) -> None: |
| 962 |
proxy, server = no_san_proxy_with_server |
| 963 |
proxy_url = f"https://{proxy.host}:{proxy.port}" |
| 964 |
destination_url = f"https://{server.host}:{server.port}" |
| 965 |
|
| 966 |
proxy_ctx = urllib3.util.ssl_.create_urllib3_context(verify_flags=0) |
| 967 |
proxy_ctx.load_verify_locations(proxy.ca_certs) |
| 968 |
proxy_fingerprint = self._get_proxy_fingerprint_md5(proxy.ca_certs) |
| 969 |
with proxy_from_url( |
| 970 |
proxy_url, |
| 971 |
ca_certs=server.ca_certs, |
| 972 |
proxy_ssl_context=proxy_ctx, |
| 973 |
proxy_assert_fingerprint=proxy_fingerprint, |
| 974 |
) as https: |
| 975 |
https.request("GET", destination_url) |
| 976 |
|
| 977 |
@pytest.mark.parametrize("use_forwarding_for_https", [False, True]) |
| 978 |
def test_https_proxy_assert_fingerprint_md5_non_matching( |
| 979 |
self, |
| 980 |
no_san_proxy_with_server: tuple[ServerConfig, ServerConfig], |
| 981 |
use_forwarding_for_https: bool, |
| 982 |
) -> None: |
| 983 |
proxy, server = no_san_proxy_with_server |
| 984 |
proxy_url = f"https://{proxy.host}:{proxy.port}" |
| 985 |
destination_url = f"https://{server.host}:{server.port}" |
| 986 |
|
| 987 |
proxy_ctx = urllib3.util.ssl_.create_urllib3_context(verify_flags=0) |
| 988 |
proxy_ctx.load_verify_locations(proxy.ca_certs) |
| 989 |
proxy_fingerprint = self._get_proxy_fingerprint_md5(proxy.ca_certs) |
| 990 |
new_char = "b" if proxy_fingerprint[5] == "a" else "a" |
| 991 |
proxy_fingerprint = proxy_fingerprint[:5] + new_char + proxy_fingerprint[6:] |
| 992 |
|
| 993 |
with proxy_from_url( |
| 994 |
proxy_url, |
| 995 |
ca_certs=server.ca_certs, |
| 996 |
proxy_ssl_context=proxy_ctx, |
| 997 |
proxy_assert_fingerprint=proxy_fingerprint, |
| 998 |
use_forwarding_for_https=use_forwarding_for_https, |
| 999 |
) as https: |
| 1000 |
with pytest.raises(MaxRetryError) as e: |
| 1001 |
https.request("GET", destination_url) |
| 1002 |
|
| 1003 |
assert "Fingerprints did not match" in str(e) |
| 1004 |
|
| 1005 |
def test_https_proxy_assert_hostname( |
| 1006 |
self, san_proxy_with_server: tuple[ServerConfig, ServerConfig] |
| 1007 |
) -> None: |
| 1008 |
proxy, server = san_proxy_with_server |
| 1009 |
destination_url = f"https://{server.host}:{server.port}" |
| 1010 |
|
| 1011 |
with proxy_from_url( |
| 1012 |
proxy.base_url, ca_certs=proxy.ca_certs, proxy_assert_hostname=proxy.host |
| 1013 |
) as https: |
| 1014 |
https.request("GET", destination_url) |
| 1015 |
|
| 1016 |
@pytest.mark.parametrize("use_forwarding_for_https", [False, True]) |
| 1017 |
def test_https_proxy_assert_hostname_non_matching( |
| 1018 |
self, |
| 1019 |
san_proxy_with_server: tuple[ServerConfig, ServerConfig], |
| 1020 |
use_forwarding_for_https: bool, |
| 1021 |
) -> None: |
| 1022 |
proxy, server = san_proxy_with_server |
| 1023 |
destination_url = f"https://{server.host}:{server.port}" |
| 1024 |
|
| 1025 |
proxy_hostname = "example.com" |
| 1026 |
with proxy_from_url( |
| 1027 |
proxy.base_url, |
| 1028 |
ca_certs=proxy.ca_certs, |
| 1029 |
proxy_assert_hostname=proxy_hostname, |
| 1030 |
use_forwarding_for_https=use_forwarding_for_https, |
| 1031 |
) as https: |
| 1032 |
with pytest.raises(MaxRetryError) as e: |
| 1033 |
https.request("GET", destination_url) |
| 1034 |
|
| 1035 |
proxy_host = self._get_certificate_formatted_proxy_host(proxy.host) |
| 1036 |
msg = f"hostname \\'{proxy_hostname}\\' doesn\\'t match \\'{proxy_host}\\'" |
| 1037 |
assert msg in str(e) |
| 1038 |
|
| 1039 |
def test_https_proxy_hostname_verification( |
| 1040 |
self, no_localhost_san_server: ServerConfig |
| 1041 |
) -> None: |
| 1042 |
bad_server = no_localhost_san_server |
| 1043 |
bad_proxy_url = f"https://{bad_server.host}:{bad_server.port}" |
| 1044 |
|
| 1045 |
# An exception will be raised before we contact the destination domain. |
| 1046 |
test_url = "testing.com" |
| 1047 |
with proxy_from_url(bad_proxy_url, ca_certs=bad_server.ca_certs) as https: |
| 1048 |
with pytest.raises(MaxRetryError) as e: |
| 1049 |
https.request("GET", "http://%s/" % test_url) |
| 1050 |
assert isinstance(e.value.reason, ProxyError) |
| 1051 |
|
| 1052 |
ssl_error = e.value.reason.original_error |
| 1053 |
assert isinstance(ssl_error, SSLError) |
| 1054 |
assert "hostname 'localhost' doesn't match" in str( |
| 1055 |
ssl_error |
| 1056 |
) or "Hostname mismatch" in str(ssl_error) |
| 1057 |
|
| 1058 |
with pytest.raises(MaxRetryError) as e: |
| 1059 |
https.request("GET", "https://%s/" % test_url) |
| 1060 |
assert isinstance(e.value.reason, ProxyError) |
| 1061 |
|
| 1062 |
ssl_error = e.value.reason.original_error |
| 1063 |
assert isinstance(ssl_error, SSLError) |
| 1064 |
assert "hostname 'localhost' doesn't match" in str( |
| 1065 |
ssl_error |
| 1066 |
) or "Hostname mismatch" in str(ssl_error) |
| 1067 |
|
| 1068 |
def test_https_proxy_ipv4_san( |
| 1069 |
self, ipv4_san_proxy_with_server: tuple[ServerConfig, ServerConfig] |
| 1070 |
) -> None: |
| 1071 |
proxy, server = ipv4_san_proxy_with_server |
| 1072 |
proxy_url = f"https://{proxy.host}:{proxy.port}" |
| 1073 |
destination_url = f"https://{server.host}:{server.port}" |
| 1074 |
with proxy_from_url(proxy_url, ca_certs=proxy.ca_certs) as https: |
| 1075 |
r = https.request("GET", destination_url) |
| 1076 |
assert r.status == 200 |
| 1077 |
|
| 1078 |
def test_https_proxy_ipv6_san( |
| 1079 |
self, ipv6_san_proxy_with_server: tuple[ServerConfig, ServerConfig] |
| 1080 |
) -> None: |
| 1081 |
proxy, server = ipv6_san_proxy_with_server |
| 1082 |
proxy_url = f"https://[{proxy.host}]:{proxy.port}" |
| 1083 |
destination_url = f"https://{server.host}:{server.port}" |
| 1084 |
with proxy_from_url(proxy_url, ca_certs=proxy.ca_certs) as https: |
| 1085 |
r = https.request("GET", destination_url) |
| 1086 |
assert r.status == 200 |
| 1087 |
|
| 1088 |
@pytest.mark.parametrize("target_scheme", ["http", "https"]) |
| 1089 |
def test_https_proxy_no_san( |
| 1090 |
self, |
| 1091 |
no_san_proxy_with_server: tuple[ServerConfig, ServerConfig], |
| 1092 |
target_scheme: str, |
| 1093 |
) -> None: |
| 1094 |
proxy, server = no_san_proxy_with_server |
| 1095 |
proxy_url = f"https://{proxy.host}:{proxy.port}" |
| 1096 |
destination_url = f"{target_scheme}://{server.host}:{server.port}" |
| 1097 |
|
| 1098 |
with proxy_from_url(proxy_url, ca_certs=proxy.ca_certs) as https: |
| 1099 |
with pytest.raises(MaxRetryError) as e: |
| 1100 |
https.request("GET", destination_url) |
| 1101 |
assert isinstance(e.value.reason, ProxyError) |
| 1102 |
|
| 1103 |
ssl_error = e.value.reason.original_error |
| 1104 |
assert isinstance(ssl_error, SSLError) |
| 1105 |
assert ( |
| 1106 |
"no appropriate subjectAltName fields were found" in str(ssl_error) |
| 1107 |
or "Hostname mismatch, certificate is not valid for 'localhost'" |
| 1108 |
in str(ssl_error) |
| 1109 |
or "Empty Subject Alternative Name extension" in str(ssl_error) |
| 1110 |
) |
| 1111 |
|
| 1112 |
def test_https_proxy_no_san_hostname_checks_common_name( |
| 1113 |
self, no_san_proxy_with_server: tuple[ServerConfig, ServerConfig] |
| 1114 |
) -> None: |
| 1115 |
proxy, server = no_san_proxy_with_server |
| 1116 |
proxy_url = f"https://{proxy.host}:{proxy.port}" |
| 1117 |
destination_url = f"https://{server.host}:{server.port}" |
| 1118 |
|
| 1119 |
proxy_ctx = urllib3.util.ssl_.create_urllib3_context(verify_flags=0) |
| 1120 |
proxy_ctx.load_verify_locations(proxy.ca_certs) |
| 1121 |
try: |
| 1122 |
proxy_ctx.hostname_checks_common_name = True |
| 1123 |
# PyPy doesn't like us setting 'hostname_checks_common_name' |
| 1124 |
# but also has it enabled by default so we need to handle that. |
| 1125 |
except AttributeError: |
| 1126 |
pass |
| 1127 |
if getattr(proxy_ctx, "hostname_checks_common_name", False) is not True: |
| 1128 |
pytest.skip("Test requires 'SSLContext.hostname_checks_common_name=True'") |
| 1129 |
|
| 1130 |
with proxy_from_url( |
| 1131 |
proxy_url, ca_certs=server.ca_certs, proxy_ssl_context=proxy_ctx |
| 1132 |
) as https: |
| 1133 |
https.request("GET", destination_url) |
| 1134 |
|
| 1135 |
@pytest.mark.parametrize( |
| 1136 |
"target_tls_kwargs", |
| 1137 |
[ |
| 1138 |
pytest.param({"server_hostname": "example.com"}, id="server-hostname"), |
| 1139 |
pytest.param({"assert_hostname": "example.com"}, id="assert-hostname"), |
| 1140 |
pytest.param({"assert_fingerprint": "00" * 32}, id="assert-fingerprint"), |
| 1141 |
], |
| 1142 |
) |
| 1143 |
def test_https_proxy_forwarding_ignores_target_identity_settings( |
| 1144 |
self, |
| 1145 |
san_proxy_with_server: tuple[ServerConfig, ServerConfig], |
| 1146 |
target_tls_kwargs: dict[str, typing.Any], |
| 1147 |
) -> None: |
| 1148 |
proxy, server = san_proxy_with_server |
| 1149 |
proxy_ctx = create_urllib3_context() |
| 1150 |
proxy_ctx.load_verify_locations(proxy.ca_certs) |
| 1151 |
|
| 1152 |
with proxy_from_url( |
| 1153 |
proxy.base_url, |
| 1154 |
proxy_ssl_context=proxy_ctx, |
| 1155 |
proxy_assert_hostname=proxy.host, |
| 1156 |
use_forwarding_for_https=True, |
| 1157 |
**target_tls_kwargs, |
| 1158 |
) as https: |
| 1159 |
pool = https.connection_from_url(server.base_url) |
| 1160 |
with contextlib.closing(pool._new_conn()) as conn: |
| 1161 |
conn = typing.cast(HTTPSConnection, conn) |
| 1162 |
conn.connect() |
| 1163 |
assert isinstance(conn.sock, ssl.SSLSocket) |
| 1164 |
assert conn.sock.context is proxy_ctx |
| 1165 |
|
| 1166 |
def test_https_proxy_forwarding_ignores_target_client_certificate( |
| 1167 |
self, |
| 1168 |
san_proxy_with_server: tuple[ServerConfig, ServerConfig], |
| 1169 |
) -> None: |
| 1170 |
proxy, server = san_proxy_with_server |
| 1171 |
proxy_ctx = create_urllib3_context() |
| 1172 |
proxy_ctx.load_verify_locations(proxy.ca_certs) |
| 1173 |
missing_cert = str(pathlib.Path(proxy.ca_certs).with_name("missing-cert.pem")) |
| 1174 |
|
| 1175 |
with proxy_from_url( |
| 1176 |
proxy.base_url, |
| 1177 |
proxy_ssl_context=proxy_ctx, |
| 1178 |
cert_file=missing_cert, |
| 1179 |
use_forwarding_for_https=True, |
| 1180 |
) as https: |
| 1181 |
pool = https.connection_from_url(server.base_url) |
| 1182 |
with contextlib.closing(pool._new_conn()) as conn: |
| 1183 |
conn = typing.cast(HTTPSConnection, conn) |
| 1184 |
conn.connect() |
| 1185 |
assert isinstance(conn.sock, ssl.SSLSocket) |
| 1186 |
assert conn.sock.context is proxy_ctx |
| 1187 |
|
| 1188 |
def test_https_proxy_forwarding_ignores_target_tls_policy( |
| 1189 |
self, |
| 1190 |
san_proxy_with_server: tuple[ServerConfig, ServerConfig], |
| 1191 |
) -> None: |
| 1192 |
proxy, server = san_proxy_with_server |
| 1193 |
proxy_ctx = create_urllib3_context(cert_reqs=ssl.CERT_REQUIRED) |
| 1194 |
proxy_ctx.load_verify_locations(proxy.ca_certs) |
| 1195 |
proxy_cert_store_stats = proxy_ctx.cert_store_stats() |
| 1196 |
|
| 1197 |
with proxy_from_url( |
| 1198 |
proxy.base_url, |
| 1199 |
proxy_ssl_context=proxy_ctx, |
| 1200 |
cert_reqs=ssl.CERT_NONE, |
| 1201 |
ca_certs=DEFAULT_CA, |
| 1202 |
use_forwarding_for_https=True, |
| 1203 |
) as https: |
| 1204 |
for target_url in (server.base_url, "https://example.com/"): |
| 1205 |
pool = https.connection_from_url(target_url) |
| 1206 |
with contextlib.closing(pool._new_conn()) as conn: |
| 1207 |
conn = typing.cast(HTTPSConnection, conn) |
| 1208 |
conn.connect() |
| 1209 |
assert isinstance(conn.sock, ssl.SSLSocket) |
| 1210 |
assert conn.sock.context is proxy_ctx |
| 1211 |
|
| 1212 |
assert proxy_ctx.verify_mode == ssl.CERT_REQUIRED |
| 1213 |
assert proxy_ctx.cert_store_stats() == proxy_cert_store_stats |