| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import concurrent.futures |
| 4 |
import contextlib |
| 5 |
import datetime |
| 6 |
import os.path |
| 7 |
import shutil |
| 8 |
import ssl |
| 9 |
import sys |
| 10 |
import tempfile |
| 11 |
import time |
| 12 |
import typing |
| 13 |
import warnings |
| 14 |
from pathlib import Path |
| 15 |
from test import ( |
| 16 |
LONG_TIMEOUT, |
| 17 |
SHORT_TIMEOUT, |
| 18 |
TARPIT_HOST, |
| 19 |
requires_network, |
| 20 |
resolvesLocalhostFQDN, |
| 21 |
) |
| 22 |
from test.conftest import ServerConfig |
| 23 |
from unittest import mock |
| 24 |
|
| 25 |
import pytest |
| 26 |
import trustme |
| 27 |
|
| 28 |
import urllib3.http2 |
| 29 |
import urllib3.http2.probe as http2_probe |
| 30 |
import urllib3.util as util |
| 31 |
import urllib3.util.ssl_ |
| 32 |
from dummyserver.socketserver import ( |
| 33 |
DEFAULT_CA, |
| 34 |
DEFAULT_CA_KEY, |
| 35 |
DEFAULT_CERTS, |
| 36 |
encrypt_key_pem, |
| 37 |
) |
| 38 |
from dummyserver.testcase import HTTPSHypercornDummyServerTestCase |
| 39 |
from urllib3 import HTTPSConnectionPool |
| 40 |
from urllib3.connection import RECENT_DATE, HTTPSConnection, VerifiedHTTPSConnection |
| 41 |
from urllib3.exceptions import ( |
| 42 |
ConnectTimeoutError, |
| 43 |
InsecureRequestWarning, |
| 44 |
MaxRetryError, |
| 45 |
ProtocolError, |
| 46 |
SSLError, |
| 47 |
SystemTimeWarning, |
| 48 |
) |
| 49 |
from urllib3.util.ssl_match_hostname import CertificateError |
| 50 |
from urllib3.util.timeout import Timeout |
| 51 |
|
| 52 |
TLSv1_CERTS = DEFAULT_CERTS.copy() |
| 53 |
TLSv1_CERTS["ssl_version"] = getattr(ssl, "PROTOCOL_TLSv1", None) |
| 54 |
|
| 55 |
TLSv1_1_CERTS = DEFAULT_CERTS.copy() |
| 56 |
TLSv1_1_CERTS["ssl_version"] = getattr(ssl, "PROTOCOL_TLSv1_1", None) |
| 57 |
|
| 58 |
TLSv1_2_CERTS = DEFAULT_CERTS.copy() |
| 59 |
TLSv1_2_CERTS["ssl_version"] = getattr(ssl, "PROTOCOL_TLSv1_2", None) |
| 60 |
|
| 61 |
TLSv1_3_CERTS = DEFAULT_CERTS.copy() |
| 62 |
TLSv1_3_CERTS["ssl_version"] = getattr(ssl, "PROTOCOL_TLS", None) |
| 63 |
|
| 64 |
|
| 65 |
CLIENT_INTERMEDIATE_PEM = "client_intermediate.pem" |
| 66 |
CLIENT_NO_INTERMEDIATE_PEM = "client_no_intermediate.pem" |
| 67 |
CLIENT_INTERMEDIATE_KEY = "client_intermediate.key" |
| 68 |
PASSWORD_CLIENT_KEYFILE = "client_password.key" |
| 69 |
CLIENT_CERT = CLIENT_INTERMEDIATE_PEM |
| 70 |
|
| 71 |
|
| 72 |
class BaseTestHTTPS(HTTPSHypercornDummyServerTestCase): |
| 73 |
tls_protocol_name: str | None = None |
| 74 |
|
| 75 |
def tls_protocol_not_default(self) -> bool: |
| 76 |
return self.tls_protocol_name in {"TLSv1", "TLSv1.1"} |
| 77 |
|
| 78 |
def tls_version(self) -> ssl.TLSVersion: |
| 79 |
if self.tls_protocol_name is None: |
| 80 |
return pytest.skip("Skipping base test class") |
| 81 |
try: |
| 82 |
from ssl import TLSVersion |
| 83 |
except ImportError: |
| 84 |
return pytest.skip("ssl.TLSVersion isn't available") |
| 85 |
return TLSVersion[self.tls_protocol_name.replace(".", "_")] |
| 86 |
|
| 87 |
def ssl_version(self) -> int: |
| 88 |
if self.tls_protocol_name is None: |
| 89 |
return pytest.skip("Skipping base test class") |
| 90 |
|
| 91 |
if self.tls_protocol_name == "TLSv1.3" and ssl.HAS_TLSv1_3: |
| 92 |
return ssl.PROTOCOL_TLS_CLIENT |
| 93 |
if self.tls_protocol_name == "TLSv1.2" and ssl.HAS_TLSv1_2: |
| 94 |
return ssl.PROTOCOL_TLSv1_2 |
| 95 |
if self.tls_protocol_name == "TLSv1.1" and ssl.HAS_TLSv1_1: |
| 96 |
return ssl.PROTOCOL_TLSv1_1 |
| 97 |
if self.tls_protocol_name == "TLSv1" and ssl.HAS_TLSv1: |
| 98 |
return ssl.PROTOCOL_TLSv1 |
| 99 |
else: |
| 100 |
return pytest.skip(f"{self.tls_protocol_name} isn't available") |
| 101 |
|
| 102 |
@classmethod |
| 103 |
def setup_class(cls) -> None: |
| 104 |
super().setup_class() |
| 105 |
|
| 106 |
cls.certs_dir = tempfile.mkdtemp() |
| 107 |
# Start from existing root CA as we don't want to change the server certificate yet |
| 108 |
with open(DEFAULT_CA, "rb") as crt, open(DEFAULT_CA_KEY, "rb") as key: |
| 109 |
root_ca = trustme.CA.from_pem(crt.read(), key.read()) |
| 110 |
|
| 111 |
# Generate another CA to test verification failure |
| 112 |
bad_ca = trustme.CA() |
| 113 |
cls.bad_ca_path = os.path.join(cls.certs_dir, "ca_bad.pem") |
| 114 |
bad_ca.cert_pem.write_to_path(cls.bad_ca_path) |
| 115 |
|
| 116 |
# client cert chain |
| 117 |
intermediate_ca = root_ca.create_child_ca() |
| 118 |
cert = intermediate_ca.issue_cert("example.com") |
| 119 |
encrypted_key = encrypt_key_pem(cert.private_key_pem, b"letmein") |
| 120 |
|
| 121 |
cert.private_key_pem.write_to_path( |
| 122 |
os.path.join(cls.certs_dir, CLIENT_INTERMEDIATE_KEY) |
| 123 |
) |
| 124 |
encrypted_key.write_to_path( |
| 125 |
os.path.join(cls.certs_dir, PASSWORD_CLIENT_KEYFILE) |
| 126 |
) |
| 127 |
# Write the client cert and the intermediate CA |
| 128 |
client_cert = os.path.join(cls.certs_dir, CLIENT_INTERMEDIATE_PEM) |
| 129 |
cert.cert_chain_pems[0].write_to_path(client_cert) |
| 130 |
cert.cert_chain_pems[1].write_to_path(client_cert, append=True) |
| 131 |
# Write only the client cert |
| 132 |
cert.cert_chain_pems[0].write_to_path( |
| 133 |
os.path.join(cls.certs_dir, CLIENT_NO_INTERMEDIATE_PEM) |
| 134 |
) |
| 135 |
|
| 136 |
@classmethod |
| 137 |
def teardown_class(cls) -> None: |
| 138 |
super().teardown_class() |
| 139 |
|
| 140 |
shutil.rmtree(cls.certs_dir) |
| 141 |
|
| 142 |
def test_simple(self, http_version: str) -> None: |
| 143 |
with HTTPSConnectionPool( |
| 144 |
self.host, |
| 145 |
self.port, |
| 146 |
ca_certs=DEFAULT_CA, |
| 147 |
ssl_minimum_version=self.tls_version(), |
| 148 |
) as https_pool: |
| 149 |
r = https_pool.request("GET", "/") |
| 150 |
assert r.status == 200, r.data |
| 151 |
assert r.headers["server"] == f"hypercorn-{http_version}" |
| 152 |
assert r.data == b"Dummy server!" |
| 153 |
|
| 154 |
def test_default_port(self) -> None: |
| 155 |
conn = HTTPSConnection(self.host, port=None) |
| 156 |
assert conn.port == 443 |
| 157 |
|
| 158 |
@resolvesLocalhostFQDN() |
| 159 |
def test_dotted_fqdn(self) -> None: |
| 160 |
with HTTPSConnectionPool( |
| 161 |
self.host + ".", |
| 162 |
self.port, |
| 163 |
ca_certs=DEFAULT_CA, |
| 164 |
ssl_minimum_version=self.tls_version(), |
| 165 |
) as pool: |
| 166 |
r = pool.request("GET", "/") |
| 167 |
assert r.status == 200, r.data |
| 168 |
|
| 169 |
def test_client_intermediate(self) -> None: |
| 170 |
"""Check that certificate chains work well with client certs |
| 171 |
|
| 172 |
We generate an intermediate CA from the root CA, and issue a client certificate |
| 173 |
from that intermediate CA. Since the server only knows about the root CA, we |
| 174 |
need to send it the certificate *and* the intermediate CA, so that it can check |
| 175 |
the whole chain. |
| 176 |
""" |
| 177 |
with HTTPSConnectionPool( |
| 178 |
self.host, |
| 179 |
self.port, |
| 180 |
key_file=os.path.join(self.certs_dir, CLIENT_INTERMEDIATE_KEY), |
| 181 |
cert_file=os.path.join(self.certs_dir, CLIENT_INTERMEDIATE_PEM), |
| 182 |
ca_certs=DEFAULT_CA, |
| 183 |
ssl_minimum_version=self.tls_version(), |
| 184 |
) as https_pool: |
| 185 |
r = https_pool.request("GET", "/certificate") |
| 186 |
subject = r.json() |
| 187 |
assert subject["organizationalUnitName"].startswith("Testing cert") |
| 188 |
|
| 189 |
def test_client_no_intermediate(self) -> None: |
| 190 |
"""Check that missing links in certificate chains indeed break |
| 191 |
|
| 192 |
The only difference with test_client_intermediate is that we don't send the |
| 193 |
intermediate CA to the server, only the client cert. |
| 194 |
""" |
| 195 |
with HTTPSConnectionPool( |
| 196 |
self.host, |
| 197 |
self.port, |
| 198 |
cert_file=os.path.join(self.certs_dir, CLIENT_NO_INTERMEDIATE_PEM), |
| 199 |
key_file=os.path.join(self.certs_dir, CLIENT_INTERMEDIATE_KEY), |
| 200 |
ca_certs=DEFAULT_CA, |
| 201 |
ssl_minimum_version=self.tls_version(), |
| 202 |
) as https_pool: |
| 203 |
with pytest.raises((SSLError, ProtocolError)): |
| 204 |
https_pool.request("GET", "/certificate", retries=False) |
| 205 |
|
| 206 |
def test_client_key_password(self) -> None: |
| 207 |
with HTTPSConnectionPool( |
| 208 |
self.host, |
| 209 |
self.port, |
| 210 |
ca_certs=DEFAULT_CA, |
| 211 |
key_file=os.path.join(self.certs_dir, PASSWORD_CLIENT_KEYFILE), |
| 212 |
cert_file=os.path.join(self.certs_dir, CLIENT_CERT), |
| 213 |
key_password="letmein", |
| 214 |
ssl_minimum_version=self.tls_version(), |
| 215 |
) as https_pool: |
| 216 |
r = https_pool.request("GET", "/certificate") |
| 217 |
subject = r.json() |
| 218 |
assert subject["organizationalUnitName"].startswith("Testing cert") |
| 219 |
|
| 220 |
def test_client_encrypted_key_requires_password(self) -> None: |
| 221 |
with HTTPSConnectionPool( |
| 222 |
self.host, |
| 223 |
self.port, |
| 224 |
key_file=os.path.join(self.certs_dir, PASSWORD_CLIENT_KEYFILE), |
| 225 |
cert_file=os.path.join(self.certs_dir, CLIENT_CERT), |
| 226 |
key_password=None, |
| 227 |
ssl_minimum_version=self.tls_version(), |
| 228 |
) as https_pool: |
| 229 |
with pytest.raises(MaxRetryError, match="password is required") as e: |
| 230 |
https_pool.request("GET", "/certificate") |
| 231 |
|
| 232 |
assert type(e.value.reason) is SSLError |
| 233 |
|
| 234 |
def test_verified(self) -> None: |
| 235 |
with HTTPSConnectionPool( |
| 236 |
self.host, |
| 237 |
self.port, |
| 238 |
cert_reqs="CERT_REQUIRED", |
| 239 |
ca_certs=DEFAULT_CA, |
| 240 |
ssl_minimum_version=self.tls_version(), |
| 241 |
) as https_pool: |
| 242 |
with contextlib.closing(https_pool._new_conn()) as conn: |
| 243 |
assert conn.__class__ == VerifiedHTTPSConnection |
| 244 |
|
| 245 |
with warnings.catch_warnings(record=True) as w: |
| 246 |
r = https_pool.request("GET", "/") |
| 247 |
assert r.status == 200 |
| 248 |
|
| 249 |
assert [str(wm) for wm in w] == [] |
| 250 |
|
| 251 |
def test_verified_with_context(self) -> None: |
| 252 |
ctx = util.ssl_.create_urllib3_context( |
| 253 |
cert_reqs=ssl.CERT_REQUIRED, ssl_minimum_version=self.tls_version() |
| 254 |
) |
| 255 |
ctx.load_verify_locations(cafile=DEFAULT_CA) |
| 256 |
with HTTPSConnectionPool(self.host, self.port, ssl_context=ctx) as https_pool: |
| 257 |
with contextlib.closing(https_pool._new_conn()) as conn: |
| 258 |
assert conn.__class__ == VerifiedHTTPSConnection |
| 259 |
|
| 260 |
with mock.patch("warnings.warn") as warn: |
| 261 |
r = https_pool.request("GET", "/") |
| 262 |
assert r.status == 200 |
| 263 |
assert not warn.called, warn.call_args_list |
| 264 |
|
| 265 |
def test_context_combines_with_ca_certs(self) -> None: |
| 266 |
ctx = util.ssl_.create_urllib3_context( |
| 267 |
cert_reqs=ssl.CERT_REQUIRED, ssl_minimum_version=self.tls_version() |
| 268 |
) |
| 269 |
with HTTPSConnectionPool( |
| 270 |
self.host, self.port, ca_certs=DEFAULT_CA, ssl_context=ctx |
| 271 |
) as https_pool: |
| 272 |
with contextlib.closing(https_pool._new_conn()) as conn: |
| 273 |
assert conn.__class__ == VerifiedHTTPSConnection |
| 274 |
|
| 275 |
with mock.patch("warnings.warn") as warn: |
| 276 |
r = https_pool.request("GET", "/") |
| 277 |
assert r.status == 200 |
| 278 |
assert not warn.called, warn.call_args_list |
| 279 |
|
| 280 |
def test_ca_dir_verified(self, tmp_path: Path) -> None: |
| 281 |
# OpenSSL looks up certificates by the hash for their name, see c_rehash |
| 282 |
# TODO infer the bytes using `cryptography.x509.Name.public_bytes`. |
| 283 |
# https://github.com/pyca/cryptography/pull/3236 |
| 284 |
shutil.copyfile(DEFAULT_CA, str(tmp_path / "81deb5f7.0")) |
| 285 |
|
| 286 |
with HTTPSConnectionPool( |
| 287 |
self.host, |
| 288 |
self.port, |
| 289 |
cert_reqs="CERT_REQUIRED", |
| 290 |
ca_cert_dir=str(tmp_path), |
| 291 |
ssl_minimum_version=self.tls_version(), |
| 292 |
) as https_pool: |
| 293 |
with contextlib.closing(https_pool._new_conn()) as conn: |
| 294 |
assert conn.__class__ == VerifiedHTTPSConnection |
| 295 |
|
| 296 |
with warnings.catch_warnings(record=True) as w: |
| 297 |
r = https_pool.request("GET", "/") |
| 298 |
assert r.status == 200 |
| 299 |
|
| 300 |
assert [str(wm) for wm in w] == [] |
| 301 |
|
| 302 |
def test_invalid_common_name(self) -> None: |
| 303 |
with HTTPSConnectionPool( |
| 304 |
"127.0.0.1", |
| 305 |
self.port, |
| 306 |
cert_reqs="CERT_REQUIRED", |
| 307 |
ca_certs=DEFAULT_CA, |
| 308 |
ssl_minimum_version=self.tls_version(), |
| 309 |
) as https_pool: |
| 310 |
with pytest.raises(MaxRetryError) as e: |
| 311 |
https_pool.request("GET", "/", retries=0) |
| 312 |
assert type(e.value.reason) is SSLError |
| 313 |
assert "doesn't match" in str( |
| 314 |
e.value.reason |
| 315 |
) or "certificate verify failed" in str(e.value.reason) |
| 316 |
|
| 317 |
def test_verified_with_bad_ca_certs(self) -> None: |
| 318 |
with HTTPSConnectionPool( |
| 319 |
self.host, |
| 320 |
self.port, |
| 321 |
cert_reqs="CERT_REQUIRED", |
| 322 |
ca_certs=self.bad_ca_path, |
| 323 |
ssl_minimum_version=self.tls_version(), |
| 324 |
) as https_pool: |
| 325 |
with pytest.raises(MaxRetryError) as e: |
| 326 |
https_pool.request("GET", "/") |
| 327 |
assert type(e.value.reason) is SSLError |
| 328 |
assert ( |
| 329 |
"certificate verify failed" in str(e.value.reason) |
| 330 |
# PyPy is more specific |
| 331 |
or "self signed certificate in certificate chain" in str(e.value.reason) |
| 332 |
), f"Expected 'certificate verify failed', instead got: {e.value.reason!r}" |
| 333 |
|
| 334 |
def test_wrap_socket_failure_resource_leak(self) -> None: |
| 335 |
with HTTPSConnectionPool( |
| 336 |
self.host, |
| 337 |
self.port, |
| 338 |
cert_reqs="CERT_REQUIRED", |
| 339 |
ca_certs=self.bad_ca_path, |
| 340 |
ssl_minimum_version=self.tls_version(), |
| 341 |
) as https_pool: |
| 342 |
with contextlib.closing(https_pool._get_conn()) as conn: |
| 343 |
with pytest.raises(ssl.SSLError): |
| 344 |
conn.connect() |
| 345 |
|
| 346 |
assert conn.sock is not None # type: ignore[attr-defined] |
| 347 |
|
| 348 |
def test_verified_without_ca_certs(self) -> None: |
| 349 |
# default is cert_reqs=None which is ssl.CERT_NONE |
| 350 |
with HTTPSConnectionPool( |
| 351 |
self.host, |
| 352 |
self.port, |
| 353 |
cert_reqs="CERT_REQUIRED", |
| 354 |
ssl_minimum_version=self.tls_version(), |
| 355 |
) as https_pool: |
| 356 |
with pytest.raises(MaxRetryError) as e: |
| 357 |
https_pool.request("GET", "/") |
| 358 |
assert type(e.value.reason) is SSLError |
| 359 |
# there is a different error message depending on whether or |
| 360 |
# not pyopenssl is injected |
| 361 |
assert ( |
| 362 |
"No root certificates specified" in str(e.value.reason) |
| 363 |
# PyPy is more specific |
| 364 |
or "self signed certificate in certificate chain" in str(e.value.reason) |
| 365 |
# PyPy sometimes uses all-caps here |
| 366 |
or "certificate verify failed" in str(e.value.reason).lower() |
| 367 |
or "invalid certificate chain" in str(e.value.reason) |
| 368 |
), ( |
| 369 |
"Expected 'No root certificates specified', " |
| 370 |
"'certificate verify failed', or " |
| 371 |
"'invalid certificate chain', " |
| 372 |
"instead got: %r" % e.value.reason |
| 373 |
) |
| 374 |
|
| 375 |
def test_no_ssl(self) -> None: |
| 376 |
with HTTPSConnectionPool(self.host, self.port) as pool: |
| 377 |
pool.ConnectionCls = None # type: ignore[assignment] |
| 378 |
with pytest.raises(ImportError): |
| 379 |
pool._new_conn() |
| 380 |
with pytest.raises(ImportError): |
| 381 |
pool.request("GET", "/", retries=0) |
| 382 |
|
| 383 |
def test_unverified_ssl(self) -> None: |
| 384 |
"""Test that bare HTTPSConnection can connect, make requests""" |
| 385 |
with HTTPSConnectionPool( |
| 386 |
self.host, |
| 387 |
self.port, |
| 388 |
cert_reqs=ssl.CERT_NONE, |
| 389 |
ssl_minimum_version=self.tls_version(), |
| 390 |
) as pool: |
| 391 |
with mock.patch("warnings.warn") as warn: |
| 392 |
r = pool.request("GET", "/") |
| 393 |
assert r.status == 200 |
| 394 |
assert warn.called |
| 395 |
|
| 396 |
# Modern versions of Python, or systems using PyOpenSSL, only emit |
| 397 |
# the unverified warning. Older systems may also emit other |
| 398 |
# warnings, which we want to ignore here. |
| 399 |
calls = warn.call_args_list |
| 400 |
assert InsecureRequestWarning in [x[0][1] for x in calls] |
| 401 |
|
| 402 |
def test_ssl_unverified_with_ca_certs(self) -> None: |
| 403 |
with HTTPSConnectionPool( |
| 404 |
self.host, |
| 405 |
self.port, |
| 406 |
cert_reqs="CERT_NONE", |
| 407 |
ca_certs=self.bad_ca_path, |
| 408 |
ssl_minimum_version=self.tls_version(), |
| 409 |
) as pool: |
| 410 |
with mock.patch("warnings.warn") as warn: |
| 411 |
r = pool.request("GET", "/") |
| 412 |
assert r.status == 200 |
| 413 |
assert warn.called |
| 414 |
|
| 415 |
# Modern versions of Python, or systems using PyOpenSSL, only emit |
| 416 |
# the unverified warning. Older systems may also emit other |
| 417 |
# warnings, which we want to ignore here. |
| 418 |
calls = warn.call_args_list |
| 419 |
|
| 420 |
category = calls[0][0][1] |
| 421 |
assert category == InsecureRequestWarning |
| 422 |
|
| 423 |
def test_assert_hostname_false(self) -> None: |
| 424 |
with HTTPSConnectionPool( |
| 425 |
"localhost", |
| 426 |
self.port, |
| 427 |
cert_reqs="CERT_REQUIRED", |
| 428 |
ca_certs=DEFAULT_CA, |
| 429 |
ssl_minimum_version=self.tls_version(), |
| 430 |
) as https_pool: |
| 431 |
https_pool.assert_hostname = False |
| 432 |
https_pool.request("GET", "/") |
| 433 |
|
| 434 |
def test_assert_specific_hostname(self) -> None: |
| 435 |
with HTTPSConnectionPool( |
| 436 |
"localhost", |
| 437 |
self.port, |
| 438 |
cert_reqs="CERT_REQUIRED", |
| 439 |
ca_certs=DEFAULT_CA, |
| 440 |
ssl_minimum_version=self.tls_version(), |
| 441 |
) as https_pool: |
| 442 |
https_pool.assert_hostname = "localhost" |
| 443 |
https_pool.request("GET", "/") |
| 444 |
|
| 445 |
def test_server_hostname(self) -> None: |
| 446 |
with HTTPSConnectionPool( |
| 447 |
"127.0.0.1", |
| 448 |
self.port, |
| 449 |
cert_reqs="CERT_REQUIRED", |
| 450 |
ca_certs=DEFAULT_CA, |
| 451 |
server_hostname="localhost", |
| 452 |
ssl_minimum_version=self.tls_version(), |
| 453 |
) as https_pool: |
| 454 |
conn = https_pool._new_conn() |
| 455 |
conn.request("GET", "/") |
| 456 |
|
| 457 |
# Assert the wrapping socket is using the passed-through SNI name. |
| 458 |
# pyopenssl doesn't let you pull the server_hostname back off the |
| 459 |
# socket, so only add this assertion if the attribute is there (i.e. |
| 460 |
# the python ssl module). |
| 461 |
if hasattr(conn.sock, "server_hostname"): # type: ignore[attr-defined] |
| 462 |
assert conn.sock.server_hostname == "localhost" # type: ignore[attr-defined] |
| 463 |
conn.getresponse().close() |
| 464 |
conn.close() |
| 465 |
|
| 466 |
def test_assert_fingerprint_md5(self) -> None: |
| 467 |
with HTTPSConnectionPool( |
| 468 |
"localhost", |
| 469 |
self.port, |
| 470 |
cert_reqs="CERT_REQUIRED", |
| 471 |
ca_certs=DEFAULT_CA, |
| 472 |
assert_fingerprint=("55:39:BF:70:05:12:43:FA:1F:D1:BF:4E:E8:1B:07:1D"), |
| 473 |
ssl_minimum_version=self.tls_version(), |
| 474 |
) as https_pool: |
| 475 |
https_pool.request("GET", "/") |
| 476 |
|
| 477 |
def test_assert_fingerprint_sha1(self) -> None: |
| 478 |
with HTTPSConnectionPool( |
| 479 |
"localhost", |
| 480 |
self.port, |
| 481 |
cert_reqs="CERT_REQUIRED", |
| 482 |
ca_certs=DEFAULT_CA, |
| 483 |
assert_fingerprint=( |
| 484 |
"72:8B:55:4C:9A:FC:1E:88:A1:1C:AD:1B:B2:E7:CC:3E:DB:C8:F9:8A" |
| 485 |
), |
| 486 |
ssl_minimum_version=self.tls_version(), |
| 487 |
) as https_pool: |
| 488 |
https_pool.request("GET", "/") |
| 489 |
|
| 490 |
def test_assert_fingerprint_sha256(self) -> None: |
| 491 |
with HTTPSConnectionPool( |
| 492 |
"localhost", |
| 493 |
self.port, |
| 494 |
cert_reqs="CERT_REQUIRED", |
| 495 |
ca_certs=DEFAULT_CA, |
| 496 |
assert_fingerprint=( |
| 497 |
"E3:59:8E:69:FF:C5:9F:C7:88:87:44:58:22:7F:90:8D:D9:BC:12:C4:90:79:D5:" |
| 498 |
"DC:A8:5D:4F:60:40:1E:A6:D2" |
| 499 |
), |
| 500 |
ssl_minimum_version=self.tls_version(), |
| 501 |
) as https_pool: |
| 502 |
https_pool.request("GET", "/") |
| 503 |
|
| 504 |
def test_assert_invalid_fingerprint(self) -> None: |
| 505 |
def _test_request(pool: HTTPSConnectionPool) -> SSLError: |
| 506 |
with pytest.raises(MaxRetryError) as cm: |
| 507 |
pool.request("GET", "/", retries=0) |
| 508 |
assert type(cm.value.reason) is SSLError |
| 509 |
return cm.value.reason |
| 510 |
|
| 511 |
with HTTPSConnectionPool( |
| 512 |
self.host, |
| 513 |
self.port, |
| 514 |
cert_reqs="CERT_REQUIRED", |
| 515 |
ca_certs=DEFAULT_CA, |
| 516 |
ssl_minimum_version=self.tls_version(), |
| 517 |
) as https_pool: |
| 518 |
https_pool.assert_fingerprint = ( |
| 519 |
"AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA" |
| 520 |
) |
| 521 |
e = _test_request(https_pool) |
| 522 |
expected = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" |
| 523 |
got = "728b554c9afc1e88a11cad1bb2e7cc3edbc8f98a" |
| 524 |
assert ( |
| 525 |
str(e) |
| 526 |
== f'Fingerprints did not match. Expected "{expected}", got "{got}"' |
| 527 |
) |
| 528 |
|
| 529 |
# Uneven length |
| 530 |
https_pool.assert_fingerprint = "AA:A" |
| 531 |
e = _test_request(https_pool) |
| 532 |
assert "Fingerprint of invalid length:" in str(e) |
| 533 |
|
| 534 |
# Invalid length |
| 535 |
https_pool.assert_fingerprint = "AA" |
| 536 |
e = _test_request(https_pool) |
| 537 |
assert "Fingerprint of invalid length:" in str(e) |
| 538 |
|
| 539 |
def test_verify_none_and_bad_fingerprint(self) -> None: |
| 540 |
with HTTPSConnectionPool( |
| 541 |
"127.0.0.1", |
| 542 |
self.port, |
| 543 |
cert_reqs="CERT_NONE", |
| 544 |
assert_hostname=False, |
| 545 |
assert_fingerprint=( |
| 546 |
"AA:8B:55:4C:9A:FC:1E:88:A1:1C:AD:1B:B2:E7:CC:3E:DB:C8:F9:8A" |
| 547 |
), |
| 548 |
) as https_pool: |
| 549 |
with pytest.raises(MaxRetryError) as cm: |
| 550 |
https_pool.request("GET", "/", retries=0) |
| 551 |
assert type(cm.value.reason) is SSLError |
| 552 |
|
| 553 |
def test_verify_none_and_good_fingerprint(self) -> None: |
| 554 |
with HTTPSConnectionPool( |
| 555 |
"127.0.0.1", |
| 556 |
self.port, |
| 557 |
cert_reqs="CERT_NONE", |
| 558 |
assert_hostname=False, |
| 559 |
assert_fingerprint=( |
| 560 |
"72:8B:55:4C:9A:FC:1E:88:A1:1C:AD:1B:B2:E7:CC:3E:DB:C8:F9:8A" |
| 561 |
), |
| 562 |
) as https_pool: |
| 563 |
https_pool.request("GET", "/") |
| 564 |
|
| 565 |
def test_good_fingerprint_and_hostname_mismatch(self) -> None: |
| 566 |
with HTTPSConnectionPool( |
| 567 |
"127.0.0.1", |
| 568 |
self.port, |
| 569 |
cert_reqs="CERT_REQUIRED", |
| 570 |
ca_certs=DEFAULT_CA, |
| 571 |
assert_fingerprint=( |
| 572 |
"72:8B:55:4C:9A:FC:1E:88:A1:1C:AD:1B:B2:E7:CC:3E:DB:C8:F9:8A" |
| 573 |
), |
| 574 |
ssl_minimum_version=self.tls_version(), |
| 575 |
) as https_pool: |
| 576 |
https_pool.request("GET", "/") |
| 577 |
|
| 578 |
@requires_network() |
| 579 |
def test_https_timeout(self) -> None: |
| 580 |
timeout = Timeout(total=None, connect=SHORT_TIMEOUT) |
| 581 |
with HTTPSConnectionPool( |
| 582 |
TARPIT_HOST, |
| 583 |
self.port, |
| 584 |
timeout=timeout, |
| 585 |
retries=False, |
| 586 |
cert_reqs="CERT_REQUIRED", |
| 587 |
ssl_minimum_version=self.tls_version(), |
| 588 |
) as https_pool: |
| 589 |
with pytest.raises(ConnectTimeoutError): |
| 590 |
https_pool.request("GET", "/") |
| 591 |
|
| 592 |
timeout = Timeout(read=0.01) |
| 593 |
with HTTPSConnectionPool( |
| 594 |
self.host, |
| 595 |
self.port, |
| 596 |
timeout=timeout, |
| 597 |
retries=False, |
| 598 |
cert_reqs="CERT_REQUIRED", |
| 599 |
ca_certs=DEFAULT_CA, |
| 600 |
assert_fingerprint=( |
| 601 |
"72:8B:55:4C:9A:FC:1E:88:A1:1C:AD:1B:B2:E7:CC:3E:DB:C8:F9:8A" |
| 602 |
), |
| 603 |
ssl_minimum_version=self.tls_version(), |
| 604 |
) as https_pool: |
| 605 |
# TODO This was removed in https://github.com/urllib3/urllib3/pull/703/files |
| 606 |
# We need to put something back or remove this block. |
| 607 |
pass |
| 608 |
|
| 609 |
timeout = Timeout(total=None) |
| 610 |
with HTTPSConnectionPool( |
| 611 |
self.host, |
| 612 |
self.port, |
| 613 |
timeout=timeout, |
| 614 |
cert_reqs="CERT_NONE", |
| 615 |
ssl_minimum_version=self.tls_version(), |
| 616 |
) as https_pool: |
| 617 |
with pytest.warns(InsecureRequestWarning): |
| 618 |
https_pool.request("GET", "/") |
| 619 |
|
| 620 |
def test_tunnel(self, http_version: str) -> None: |
| 621 |
"""test the _tunnel behavior""" |
| 622 |
timeout = Timeout(total=None) |
| 623 |
with HTTPSConnectionPool( |
| 624 |
self.host, |
| 625 |
self.port, |
| 626 |
timeout=timeout, |
| 627 |
cert_reqs="CERT_NONE", |
| 628 |
ssl_minimum_version=self.tls_version(), |
| 629 |
) as https_pool: |
| 630 |
with contextlib.closing(https_pool._new_conn()) as conn: |
| 631 |
if http_version == "h2": |
| 632 |
with pytest.raises(NotImplementedError) as e: |
| 633 |
conn.set_tunnel(self.host, self.port) |
| 634 |
assert ( |
| 635 |
str(e.value) |
| 636 |
== "HTTP/2 does not support setting up a tunnel through a proxy" |
| 637 |
) |
| 638 |
else: |
| 639 |
conn.set_tunnel(self.host, self.port) |
| 640 |
with mock.patch.object( |
| 641 |
conn, "_tunnel", create=True, return_value=None |
| 642 |
) as conn_tunnel: |
| 643 |
with pytest.warns(InsecureRequestWarning): |
| 644 |
https_pool._make_request(conn, "GET", "/") |
| 645 |
conn_tunnel.assert_called_once_with() |
| 646 |
|
| 647 |
@requires_network() |
| 648 |
def test_enhanced_timeout(self) -> None: |
| 649 |
with HTTPSConnectionPool( |
| 650 |
TARPIT_HOST, |
| 651 |
self.port, |
| 652 |
timeout=Timeout(connect=SHORT_TIMEOUT), |
| 653 |
retries=False, |
| 654 |
cert_reqs="CERT_REQUIRED", |
| 655 |
) as https_pool: |
| 656 |
with contextlib.closing(https_pool._new_conn()) as conn: |
| 657 |
with pytest.raises(ConnectTimeoutError): |
| 658 |
https_pool.request("GET", "/") |
| 659 |
with pytest.raises(ConnectTimeoutError): |
| 660 |
https_pool._make_request(conn, "GET", "/") |
| 661 |
|
| 662 |
with HTTPSConnectionPool( |
| 663 |
TARPIT_HOST, |
| 664 |
self.port, |
| 665 |
timeout=Timeout(connect=LONG_TIMEOUT), |
| 666 |
retries=False, |
| 667 |
cert_reqs="CERT_REQUIRED", |
| 668 |
) as https_pool: |
| 669 |
with pytest.raises(ConnectTimeoutError): |
| 670 |
https_pool.request("GET", "/", timeout=Timeout(connect=SHORT_TIMEOUT)) |
| 671 |
|
| 672 |
with HTTPSConnectionPool( |
| 673 |
TARPIT_HOST, |
| 674 |
self.port, |
| 675 |
timeout=Timeout(total=None), |
| 676 |
retries=False, |
| 677 |
cert_reqs="CERT_REQUIRED", |
| 678 |
) as https_pool: |
| 679 |
with contextlib.closing(https_pool._new_conn()) as conn: |
| 680 |
with pytest.raises(ConnectTimeoutError): |
| 681 |
https_pool.request( |
| 682 |
"GET", "/", timeout=Timeout(total=None, connect=SHORT_TIMEOUT) |
| 683 |
) |
| 684 |
|
| 685 |
def test_enhanced_ssl_connection(self) -> None: |
| 686 |
fingerprint = "72:8B:55:4C:9A:FC:1E:88:A1:1C:AD:1B:B2:E7:CC:3E:DB:C8:F9:8A" |
| 687 |
|
| 688 |
with HTTPSConnectionPool( |
| 689 |
self.host, |
| 690 |
self.port, |
| 691 |
cert_reqs="CERT_REQUIRED", |
| 692 |
ca_certs=DEFAULT_CA, |
| 693 |
assert_fingerprint=fingerprint, |
| 694 |
ssl_minimum_version=self.tls_version(), |
| 695 |
) as https_pool: |
| 696 |
r = https_pool.request("GET", "/") |
| 697 |
assert r.status == 200 |
| 698 |
|
| 699 |
def test_ssl_correct_system_time(self) -> None: |
| 700 |
with HTTPSConnectionPool( |
| 701 |
self.host, |
| 702 |
self.port, |
| 703 |
ca_certs=DEFAULT_CA, |
| 704 |
ssl_minimum_version=self.tls_version(), |
| 705 |
) as https_pool: |
| 706 |
https_pool.cert_reqs = "CERT_REQUIRED" |
| 707 |
https_pool.ca_certs = DEFAULT_CA |
| 708 |
|
| 709 |
w = self._request_without_resource_warnings("GET", "/") |
| 710 |
assert [] == w |
| 711 |
|
| 712 |
def test_ssl_wrong_system_time(self) -> None: |
| 713 |
with HTTPSConnectionPool( |
| 714 |
self.host, |
| 715 |
self.port, |
| 716 |
ca_certs=DEFAULT_CA, |
| 717 |
ssl_minimum_version=self.tls_version(), |
| 718 |
) as https_pool: |
| 719 |
https_pool.cert_reqs = "CERT_REQUIRED" |
| 720 |
https_pool.ca_certs = DEFAULT_CA |
| 721 |
with mock.patch("urllib3.connection.datetime") as mock_date: |
| 722 |
mock_date.date.today.return_value = datetime.date(1970, 1, 1) |
| 723 |
|
| 724 |
w = self._request_without_resource_warnings("GET", "/") |
| 725 |
|
| 726 |
assert len(w) == 1 |
| 727 |
warning = w[0] |
| 728 |
|
| 729 |
assert SystemTimeWarning == warning.category |
| 730 |
assert isinstance(warning.message, Warning) |
| 731 |
assert str(RECENT_DATE) in warning.message.args[0] |
| 732 |
|
| 733 |
def _request_without_resource_warnings( |
| 734 |
self, method: str, url: str |
| 735 |
) -> list[warnings.WarningMessage]: |
| 736 |
with warnings.catch_warnings(record=True) as w: |
| 737 |
warnings.simplefilter("always") |
| 738 |
with HTTPSConnectionPool( |
| 739 |
self.host, |
| 740 |
self.port, |
| 741 |
ca_certs=DEFAULT_CA, |
| 742 |
ssl_minimum_version=self.tls_version(), |
| 743 |
) as https_pool: |
| 744 |
https_pool.request(method, url) |
| 745 |
|
| 746 |
w = [x for x in w if not isinstance(x.message, ResourceWarning)] |
| 747 |
|
| 748 |
return w |
| 749 |
|
| 750 |
def test_set_ssl_version_to_tls_version(self) -> None: |
| 751 |
if self.tls_protocol_name is None: |
| 752 |
pytest.skip("Skipping base test class") |
| 753 |
|
| 754 |
with HTTPSConnectionPool( |
| 755 |
self.host, self.port, ca_certs=DEFAULT_CA |
| 756 |
) as https_pool: |
| 757 |
https_pool.ssl_version = ssl_version = self.certs["ssl_version"] |
| 758 |
if ssl_version is getattr(ssl, "PROTOCOL_TLS", object()): |
| 759 |
cmgr: contextlib.AbstractContextManager[object] = ( |
| 760 |
contextlib.nullcontext() |
| 761 |
) |
| 762 |
else: |
| 763 |
cmgr = pytest.warns( |
| 764 |
FutureWarning, |
| 765 |
match=r"'ssl_version' option is deprecated and will be removed " |
| 766 |
r"in urllib3 v3\.0\. Instead use 'ssl_minimum_version'", |
| 767 |
) |
| 768 |
with cmgr: |
| 769 |
r = https_pool.request("GET", "/") |
| 770 |
assert r.status == 200, r.data |
| 771 |
|
| 772 |
def test_set_cert_default_cert_required(self) -> None: |
| 773 |
conn = VerifiedHTTPSConnection(self.host, self.port) |
| 774 |
with pytest.warns(FutureWarning) as w: |
| 775 |
conn.set_cert() |
| 776 |
assert conn.cert_reqs == ssl.CERT_REQUIRED |
| 777 |
assert len(w) == 1 and str(w[0].message) == ( |
| 778 |
"HTTPSConnection.set_cert() is deprecated and will be removed in urllib3 v3.0. " |
| 779 |
"Instead provide the parameters to the HTTPSConnection constructor." |
| 780 |
) |
| 781 |
|
| 782 |
@pytest.mark.parametrize("verify_mode", [ssl.CERT_NONE, ssl.CERT_REQUIRED]) |
| 783 |
def test_set_cert_inherits_cert_reqs_from_ssl_context( |
| 784 |
self, verify_mode: int |
| 785 |
) -> None: |
| 786 |
ssl_context = urllib3.util.ssl_.create_urllib3_context(cert_reqs=verify_mode) |
| 787 |
assert ssl_context.verify_mode == verify_mode |
| 788 |
|
| 789 |
conn = HTTPSConnection(self.host, self.port, ssl_context=ssl_context) |
| 790 |
with pytest.warns(FutureWarning) as w: |
| 791 |
conn.set_cert() |
| 792 |
|
| 793 |
assert conn.cert_reqs == verify_mode |
| 794 |
assert ( |
| 795 |
conn.ssl_context is not None and conn.ssl_context.verify_mode == verify_mode |
| 796 |
) |
| 797 |
assert len(w) == 1 and str(w[0].message) == ( |
| 798 |
"HTTPSConnection.set_cert() is deprecated and will be removed in urllib3 v3.0. " |
| 799 |
"Instead provide the parameters to the HTTPSConnection constructor." |
| 800 |
) |
| 801 |
|
| 802 |
def test_tls_protocol_name_of_socket(self) -> None: |
| 803 |
if self.tls_protocol_name is None: |
| 804 |
pytest.skip("Skipping base test class") |
| 805 |
|
| 806 |
with HTTPSConnectionPool( |
| 807 |
self.host, |
| 808 |
self.port, |
| 809 |
ca_certs=DEFAULT_CA, |
| 810 |
ssl_minimum_version=self.tls_version(), |
| 811 |
ssl_maximum_version=self.tls_version(), |
| 812 |
) as https_pool: |
| 813 |
with contextlib.closing(https_pool._get_conn()) as conn: |
| 814 |
conn.connect() |
| 815 |
if not hasattr(conn.sock, "version"): # type: ignore[attr-defined] |
| 816 |
pytest.skip("SSLSocket.version() not available") |
| 817 |
assert conn.sock.version() == self.tls_protocol_name # type: ignore[attr-defined] |
| 818 |
|
| 819 |
def test_ssl_version_is_deprecated(self) -> None: |
| 820 |
if self.tls_protocol_name is None: |
| 821 |
pytest.skip("Skipping base test class") |
| 822 |
if self.ssl_version() == ssl.PROTOCOL_TLS_CLIENT: |
| 823 |
pytest.skip( |
| 824 |
"Skipping because ssl_version=ssl.PROTOCOL_TLS_CLIENT is not deprecated" |
| 825 |
) |
| 826 |
|
| 827 |
with HTTPSConnectionPool( |
| 828 |
self.host, self.port, ca_certs=DEFAULT_CA, ssl_version=self.ssl_version() |
| 829 |
) as https_pool: |
| 830 |
with contextlib.closing(https_pool._get_conn()) as conn: |
| 831 |
with pytest.warns(FutureWarning) as w: |
| 832 |
conn.connect() |
| 833 |
|
| 834 |
assert len(w) >= 1 |
| 835 |
assert any(x.category == FutureWarning for x in w) |
| 836 |
assert any( |
| 837 |
str(x.message) |
| 838 |
== ( |
| 839 |
"'ssl_version' option is deprecated and will be removed in " |
| 840 |
"urllib3 v3.0. Instead use 'ssl_minimum_version'" |
| 841 |
) |
| 842 |
for x in w |
| 843 |
) |
| 844 |
|
| 845 |
@pytest.mark.parametrize( |
| 846 |
"ssl_version", [None, ssl.PROTOCOL_TLS, ssl.PROTOCOL_TLS_CLIENT] |
| 847 |
) |
| 848 |
def test_ssl_version_with_protocol_tls_or_client_not_deprecated( |
| 849 |
self, ssl_version: int | None |
| 850 |
) -> None: |
| 851 |
if self.tls_protocol_name is None: |
| 852 |
pytest.skip("Skipping base test class") |
| 853 |
if self.tls_protocol_not_default(): |
| 854 |
pytest.skip( |
| 855 |
f"Skipping because '{self.tls_protocol_name}' isn't set by default" |
| 856 |
) |
| 857 |
|
| 858 |
with HTTPSConnectionPool( |
| 859 |
self.host, self.port, ca_certs=DEFAULT_CA, ssl_version=ssl_version |
| 860 |
) as https_pool: |
| 861 |
with contextlib.closing(https_pool._get_conn()) as conn: |
| 862 |
with warnings.catch_warnings(record=True) as w: |
| 863 |
conn.connect() |
| 864 |
|
| 865 |
assert [str(wm) for wm in w if wm.category != ResourceWarning] == [] |
| 866 |
|
| 867 |
def test_no_tls_version_deprecation_with_ssl_context(self) -> None: |
| 868 |
if self.tls_protocol_name is None: |
| 869 |
pytest.skip("Skipping base test class") |
| 870 |
|
| 871 |
ctx = util.ssl_.create_urllib3_context(ssl_minimum_version=self.tls_version()) |
| 872 |
|
| 873 |
with HTTPSConnectionPool( |
| 874 |
self.host, |
| 875 |
self.port, |
| 876 |
ca_certs=DEFAULT_CA, |
| 877 |
ssl_context=ctx, |
| 878 |
) as https_pool: |
| 879 |
with contextlib.closing(https_pool._get_conn()) as conn: |
| 880 |
with warnings.catch_warnings(record=True) as w: |
| 881 |
conn.connect() |
| 882 |
|
| 883 |
assert [str(wm) for wm in w if wm.category != ResourceWarning] == [] |
| 884 |
|
| 885 |
def test_tls_version_maximum_and_minimum(self) -> None: |
| 886 |
if self.tls_protocol_name is None: |
| 887 |
pytest.skip("Skipping base test class") |
| 888 |
|
| 889 |
from ssl import TLSVersion |
| 890 |
|
| 891 |
min_max_versions = [ |
| 892 |
(self.tls_version(), self.tls_version()), |
| 893 |
(TLSVersion.MINIMUM_SUPPORTED, self.tls_version()), |
| 894 |
(TLSVersion.MINIMUM_SUPPORTED, TLSVersion.MAXIMUM_SUPPORTED), |
| 895 |
] |
| 896 |
|
| 897 |
for minimum_version, maximum_version in min_max_versions: |
| 898 |
with HTTPSConnectionPool( |
| 899 |
self.host, |
| 900 |
self.port, |
| 901 |
ca_certs=DEFAULT_CA, |
| 902 |
ssl_minimum_version=minimum_version, |
| 903 |
ssl_maximum_version=maximum_version, |
| 904 |
) as https_pool: |
| 905 |
conn = https_pool._get_conn() |
| 906 |
try: |
| 907 |
conn.connect() |
| 908 |
if maximum_version == TLSVersion.MAXIMUM_SUPPORTED: |
| 909 |
# A higher protocol than tls_protocol_name could be negotiated |
| 910 |
assert conn.sock.version() >= self.tls_protocol_name # type: ignore[attr-defined] |
| 911 |
else: |
| 912 |
assert conn.sock.version() == self.tls_protocol_name # type: ignore[attr-defined] |
| 913 |
finally: |
| 914 |
conn.close() |
| 915 |
|
| 916 |
@pytest.mark.parametrize("use_env_var_expansion", [True, False]) |
| 917 |
def test_sslkeylogfile( |
| 918 |
self, |
| 919 |
tmp_path: Path, |
| 920 |
monkeypatch: pytest.MonkeyPatch, |
| 921 |
use_env_var_expansion: bool, |
| 922 |
) -> None: |
| 923 |
if not hasattr(util.SSLContext, "keylog_filename"): |
| 924 |
pytest.skip("requires OpenSSL 1.1.1+") |
| 925 |
|
| 926 |
keylog_file = tmp_path / "keylogfile.txt" |
| 927 |
if use_env_var_expansion: |
| 928 |
monkeypatch.setenv("FILEPATH", str(keylog_file)) |
| 929 |
if sys.platform == "win32": |
| 930 |
monkeypatch.setenv("SSLKEYLOGFILE", "%FILEPATH%") |
| 931 |
else: |
| 932 |
monkeypatch.setenv("SSLKEYLOGFILE", "${FILEPATH}") |
| 933 |
else: |
| 934 |
monkeypatch.setenv("SSLKEYLOGFILE", str(keylog_file)) |
| 935 |
|
| 936 |
with HTTPSConnectionPool( |
| 937 |
self.host, |
| 938 |
self.port, |
| 939 |
ca_certs=DEFAULT_CA, |
| 940 |
ssl_minimum_version=self.tls_version(), |
| 941 |
) as https_pool: |
| 942 |
r = https_pool.request("GET", "/") |
| 943 |
assert r.status == 200, r.data |
| 944 |
assert keylog_file.is_file(), "keylogfile '%s' should exist" % str( |
| 945 |
keylog_file |
| 946 |
) |
| 947 |
assert keylog_file.read_text().startswith( |
| 948 |
"# TLS secrets log file" |
| 949 |
), "keylogfile '%s' should start with '# TLS secrets log file'" % str( |
| 950 |
keylog_file |
| 951 |
) |
| 952 |
|
| 953 |
@pytest.mark.parametrize("sslkeylogfile", [None, ""]) |
| 954 |
def test_sslkeylogfile_empty( |
| 955 |
self, monkeypatch: pytest.MonkeyPatch, sslkeylogfile: str | None |
| 956 |
) -> None: |
| 957 |
# Assert that an HTTPS connection doesn't error out when given |
| 958 |
# no SSLKEYLOGFILE or an empty value (ie 'SSLKEYLOGFILE=') |
| 959 |
if sslkeylogfile is not None: |
| 960 |
monkeypatch.setenv("SSLKEYLOGFILE", sslkeylogfile) |
| 961 |
else: |
| 962 |
monkeypatch.delenv("SSLKEYLOGFILE", raising=False) |
| 963 |
with HTTPSConnectionPool( |
| 964 |
self.host, |
| 965 |
self.port, |
| 966 |
ca_certs=DEFAULT_CA, |
| 967 |
ssl_minimum_version=self.tls_version(), |
| 968 |
) as pool: |
| 969 |
r = pool.request("GET", "/") |
| 970 |
assert r.status == 200, r.data |
| 971 |
|
| 972 |
def test_alpn_default(self, http_version: str) -> None: |
| 973 |
"""Default ALPN protocols are sent by default.""" |
| 974 |
with HTTPSConnectionPool( |
| 975 |
self.host, |
| 976 |
self.port, |
| 977 |
ca_certs=DEFAULT_CA, |
| 978 |
ssl_minimum_version=self.tls_version(), |
| 979 |
) as pool: |
| 980 |
r = pool.request("GET", "/alpn_protocol", retries=0) |
| 981 |
assert r.status == 200 |
| 982 |
assert r.data.decode("utf-8") == util.ALPN_PROTOCOLS[0] |
| 983 |
assert ( |
| 984 |
r.data.decode("utf-8") == {"h11": "http/1.1", "h2": "h2"}[http_version] |
| 985 |
) |
| 986 |
|
| 987 |
def test_http2_probe_result_is_cached(self, http_version: str) -> None: |
| 988 |
assert http2_probe._values() == {} |
| 989 |
|
| 990 |
for i in range(2): # Do this twice to exercise the cache path |
| 991 |
with HTTPSConnectionPool( |
| 992 |
self.host, |
| 993 |
self.port, |
| 994 |
ca_certs=DEFAULT_CA, |
| 995 |
) as pool: |
| 996 |
r = pool.request("GET", "/alpn_protocol", retries=0) |
| 997 |
assert r.status == 200 |
| 998 |
|
| 999 |
if http_version == "h2": |
| 1000 |
# This means the probe was successful. |
| 1001 |
assert http2_probe._values() == {(self.host, self.port): True} |
| 1002 |
else: |
| 1003 |
# This means the probe wasn't attempted, otherwise would have a value. |
| 1004 |
assert http_version == "h11" |
| 1005 |
assert http2_probe._values() == {} |
| 1006 |
|
| 1007 |
@pytest.mark.xfail(reason="Hypercorn always supports both HTTP/2 and HTTP/1.1") |
| 1008 |
def test_http2_probe_result_failed(self, http_version: str) -> None: |
| 1009 |
if http_version == "h2": |
| 1010 |
pytest.skip("Test must have server in HTTP/1.1 mode") |
| 1011 |
assert http2_probe._values() == {} |
| 1012 |
|
| 1013 |
urllib3.http2.inject_into_urllib3() |
| 1014 |
try: |
| 1015 |
with HTTPSConnectionPool( |
| 1016 |
self.host, |
| 1017 |
self.port, |
| 1018 |
ca_certs=DEFAULT_CA, |
| 1019 |
) as pool: |
| 1020 |
r = pool.request("GET", "/", retries=0) |
| 1021 |
assert r.status == 200 |
| 1022 |
|
| 1023 |
# The probe was a failure because Hypercorn didn't support HTTP/2. |
| 1024 |
assert http2_probe._values() == {(self.host, self.port): False} |
| 1025 |
finally: |
| 1026 |
urllib3.http2.extract_from_urllib3() |
| 1027 |
|
| 1028 |
def test_http2_probe_no_result_in_connect_error(self) -> None: |
| 1029 |
assert http2_probe._values() == {} |
| 1030 |
|
| 1031 |
urllib3.http2.inject_into_urllib3() |
| 1032 |
try: |
| 1033 |
with HTTPSConnectionPool( |
| 1034 |
TARPIT_HOST, |
| 1035 |
self.port, |
| 1036 |
ca_certs=DEFAULT_CA, |
| 1037 |
timeout=SHORT_TIMEOUT, |
| 1038 |
) as pool: |
| 1039 |
with pytest.raises(ConnectTimeoutError): |
| 1040 |
pool.request("GET", "/", retries=False) |
| 1041 |
|
| 1042 |
# The probe was inconclusive since an error occurred during connection. |
| 1043 |
assert http2_probe._values() == {(TARPIT_HOST, self.port): None} |
| 1044 |
finally: |
| 1045 |
urllib3.http2.extract_from_urllib3() |
| 1046 |
|
| 1047 |
def test_http2_probe_no_result_in_ssl_error(self) -> None: |
| 1048 |
urllib3.http2.inject_into_urllib3() |
| 1049 |
try: |
| 1050 |
with HTTPSConnectionPool( |
| 1051 |
self.host, |
| 1052 |
self.port, |
| 1053 |
ca_certs=None, |
| 1054 |
timeout=LONG_TIMEOUT, |
| 1055 |
) as pool: |
| 1056 |
with pytest.raises(SSLError): |
| 1057 |
pool.request("GET", "/", retries=False) |
| 1058 |
|
| 1059 |
# The probe was inconclusive since an error occurred during connection. |
| 1060 |
assert http2_probe._values() == {(self.host, self.port): None} |
| 1061 |
finally: |
| 1062 |
urllib3.http2.extract_from_urllib3() |
| 1063 |
|
| •1064 |
@requires_network() |
| 1065 |
def test_http2_probe_blocked_per_thread(self) -> None: |
| 1066 |
state, current_thread, last_action = None, None, time.perf_counter() |
| 1067 |
|
| 1068 |
def connect_callback(label: str, thread_id: int, **kwargs: typing.Any) -> None: |
| 1069 |
nonlocal state, current_thread, last_action |
| 1070 |
|
| 1071 |
if label in ("before connect", "after connect failure"): |
| 1072 |
# We don't know if the target supports HTTP/2 as connections fail |
| 1073 |
assert kwargs["target_supports_http2"] is None |
| 1074 |
|
| 1075 |
# Since we're trying to connect to TARPIT_HOST, all connections will |
| 1076 |
# fail, but they should be tried one after the other |
| 1077 |
now = time.perf_counter() |
| 1078 |
assert now >= last_action |
| 1079 |
last_action = now |
| 1080 |
|
| 1081 |
if label == "before connect": |
| 1082 |
assert state is None |
| 1083 |
state = "connect" |
| 1084 |
assert current_thread != thread_id |
| 1085 |
current_thread = thread_id |
| 1086 |
elif label == "after connect failure": |
| 1087 |
assert state == "connect" |
| 1088 |
assert current_thread == thread_id |
| 1089 |
state = None |
| 1090 |
|
| 1091 |
assert http2_probe._values() == {} |
| 1092 |
|
| 1093 |
connect_timeout = LONG_TIMEOUT |
| 1094 |
total_threads = 3 |
| 1095 |
urllib3.http2.inject_into_urllib3() |
| 1096 |
try: |
| 1097 |
|
| 1098 |
def try_connect(_: typing.Any) -> tuple[float, float]: |
| 1099 |
with HTTPSConnectionPool( |
| 1100 |
TARPIT_HOST, |
| 1101 |
self.port, |
| 1102 |
ca_certs=DEFAULT_CA, |
| 1103 |
timeout=connect_timeout, |
| 1104 |
) as pool: |
| 1105 |
start_time = time.time() |
| 1106 |
conn = pool._get_conn() |
| 1107 |
assert isinstance(conn, HTTPSConnection) |
| 1108 |
conn._connect_callback = connect_callback |
| 1109 |
with pytest.raises(ConnectTimeoutError): |
| 1110 |
conn.connect() |
| 1111 |
end_time = time.time() |
| 1112 |
return start_time, end_time |
| 1113 |
|
| 1114 |
threadpool = concurrent.futures.ThreadPoolExecutor(total_threads) |
| 1115 |
list(threadpool.map(try_connect, range(total_threads))) |
| 1116 |
|
| 1117 |
# The probe was inconclusive since an error occurred during connection. |
| 1118 |
assert http2_probe._values() == {(TARPIT_HOST, self.port): None} |
| 1119 |
finally: |
| 1120 |
urllib3.http2.extract_from_urllib3() |
| 1121 |
|
| 1122 |
def test_default_ssl_context_ssl_min_max_versions(self) -> None: |
| 1123 |
ctx = urllib3.util.ssl_.create_urllib3_context() |
| 1124 |
assert ctx.minimum_version == ssl.TLSVersion.TLSv1_2 |
| 1125 |
# urllib3 sets a default maximum version only when it is |
| 1126 |
# injected with PyOpenSSL SSL-support. |
| 1127 |
# Otherwise, the default maximum version is set by Python's |
| 1128 |
# `ssl.SSLContext`. The value respects OpenSSL configuration and |
| 1129 |
# can be different from `ssl.TLSVersion.MAXIMUM_SUPPORTED`. |
| 1130 |
# https://github.com/urllib3/urllib3/issues/2477#issuecomment-1151452150 |
| 1131 |
if util.IS_PYOPENSSL: |
| 1132 |
expected_maximum_version = ssl.TLSVersion.MAXIMUM_SUPPORTED |
| 1133 |
else: |
| 1134 |
expected_maximum_version = ssl.SSLContext( |
| 1135 |
ssl.PROTOCOL_TLS_CLIENT |
| 1136 |
).maximum_version |
| 1137 |
assert ctx.maximum_version == expected_maximum_version |
| 1138 |
|
| 1139 |
def test_ssl_context_ssl_version_uses_ssl_min_max_versions(self) -> None: |
| 1140 |
if self.ssl_version() == ssl.PROTOCOL_TLS_CLIENT: |
| 1141 |
pytest.skip( |
| 1142 |
"Skipping because ssl_version=ssl.PROTOCOL_TLS_CLIENT is not deprecated" |
| 1143 |
) |
| 1144 |
|
| 1145 |
with pytest.warns( |
| 1146 |
FutureWarning, |
| 1147 |
match=r"'ssl_version' option is deprecated and will be removed in " |
| 1148 |
r"urllib3 v3\.0\. Instead use 'ssl_minimum_version'", |
| 1149 |
): |
| 1150 |
ctx = urllib3.util.ssl_.create_urllib3_context( |
| 1151 |
ssl_version=self.ssl_version() |
| 1152 |
) |
| 1153 |
assert ctx.minimum_version == self.tls_version() |
| 1154 |
assert ctx.maximum_version == self.tls_version() |
| 1155 |
|
| 1156 |
def test_default_ssl_context_verify_flags(self) -> None: |
| 1157 |
ctx = urllib3.util.ssl_.create_urllib3_context() |
| 1158 |
ssl_ctx = ssl.create_default_context() |
| 1159 |
assert ctx.verify_flags == ssl_ctx.verify_flags |
| 1160 |
|
| 1161 |
def test_assert_missing_hashfunc(self, monkeypatch: pytest.MonkeyPatch) -> None: |
| 1162 |
fingerprint = "55:39:BF:70:05:12:43:FA:1F:D1:BF:4E:E8:1B:07:1D" |
| 1163 |
with HTTPSConnectionPool( |
| 1164 |
"localhost", |
| 1165 |
self.port, |
| 1166 |
cert_reqs="CERT_REQUIRED", |
| 1167 |
ca_certs=DEFAULT_CA, |
| 1168 |
assert_fingerprint=(fingerprint), |
| 1169 |
ssl_minimum_version=self.tls_version(), |
| 1170 |
) as https_pool: |
| 1171 |
digest_length = len(fingerprint.replace(":", "").lower()) |
| 1172 |
monkeypatch.setitem(urllib3.util.ssl_.HASHFUNC_MAP, digest_length, None) |
| 1173 |
with pytest.raises(MaxRetryError) as cm: |
| 1174 |
https_pool.request("GET", "/", retries=0) |
| 1175 |
assert type(cm.value.reason) is SSLError |
| 1176 |
assert ( |
| 1177 |
f"Hash function implementation unavailable for fingerprint length: {digest_length}" |
| 1178 |
== str(cm.value.reason) |
| 1179 |
) |
| 1180 |
|
| 1181 |
|
| 1182 |
@pytest.mark.usefixtures("requires_tlsv1") |
| 1183 |
class TestHTTPS_TLSv1(BaseTestHTTPS): |
| 1184 |
tls_protocol_name = "TLSv1" |
| 1185 |
certs = TLSv1_CERTS |
| 1186 |
|
| 1187 |
|
| 1188 |
@pytest.mark.usefixtures("requires_tlsv1_1") |
| 1189 |
class TestHTTPS_TLSv1_1(BaseTestHTTPS): |
| 1190 |
tls_protocol_name = "TLSv1.1" |
| 1191 |
certs = TLSv1_1_CERTS |
| 1192 |
|
| 1193 |
|
| 1194 |
@pytest.mark.usefixtures("requires_tlsv1_2") |
| 1195 |
class TestHTTPS_TLSv1_2(BaseTestHTTPS): |
| 1196 |
tls_protocol_name = "TLSv1.2" |
| 1197 |
certs = TLSv1_2_CERTS |
| 1198 |
|
| 1199 |
|
| 1200 |
@pytest.mark.usefixtures("requires_tlsv1_3") |
| 1201 |
class TestHTTPS_TLSv1_3(BaseTestHTTPS): |
| 1202 |
tls_protocol_name = "TLSv1.3" |
| 1203 |
certs = TLSv1_3_CERTS |
| 1204 |
|
| 1205 |
|
| 1206 |
class TestHTTPS_Hostname: |
| 1207 |
def test_can_validate_san(self, san_server: ServerConfig) -> None: |
| 1208 |
"""Ensure that urllib3 can validate SANs with IP addresses in them.""" |
| 1209 |
with HTTPSConnectionPool( |
| 1210 |
san_server.host, |
| 1211 |
san_server.port, |
| 1212 |
cert_reqs="CERT_REQUIRED", |
| 1213 |
ca_certs=san_server.ca_certs, |
| 1214 |
) as https_pool: |
| 1215 |
r = https_pool.request("GET", "/") |
| 1216 |
assert r.status == 200 |
| 1217 |
|
| 1218 |
def test_common_name_without_san_fails(self, no_san_server: ServerConfig) -> None: |
| 1219 |
with HTTPSConnectionPool( |
| 1220 |
no_san_server.host, |
| 1221 |
no_san_server.port, |
| 1222 |
cert_reqs="CERT_REQUIRED", |
| 1223 |
ca_certs=no_san_server.ca_certs, |
| 1224 |
) as https_pool: |
| 1225 |
with pytest.raises( |
| 1226 |
MaxRetryError, |
| 1227 |
) as e: |
| 1228 |
https_pool.request("GET", "/") |
| 1229 |
assert ( |
| 1230 |
"mismatch, certificate is not valid" in str(e.value) |
| 1231 |
or "no appropriate subjectAltName" in str(e.value) |
| 1232 |
or "Empty Subject Alternative Name extension" in str(e.value) |
| 1233 |
) |
| 1234 |
|
| 1235 |
def test_common_name_without_san_with_different_common_name( |
| 1236 |
self, no_san_server_with_different_commmon_name: ServerConfig |
| 1237 |
) -> None: |
| 1238 |
ctx = urllib3.util.ssl_.create_urllib3_context(verify_flags=0) |
| 1239 |
try: |
| 1240 |
ctx.hostname_checks_common_name = True |
| 1241 |
except AttributeError: |
| 1242 |
pytest.skip("Couldn't set 'SSLContext.hostname_checks_common_name'") |
| 1243 |
|
| 1244 |
with HTTPSConnectionPool( |
| 1245 |
no_san_server_with_different_commmon_name.host, |
| 1246 |
no_san_server_with_different_commmon_name.port, |
| 1247 |
cert_reqs="CERT_REQUIRED", |
| 1248 |
ca_certs=no_san_server_with_different_commmon_name.ca_certs, |
| 1249 |
ssl_context=ctx, |
| 1250 |
) as https_pool: |
| 1251 |
with pytest.raises(MaxRetryError) as e: |
| 1252 |
https_pool.request("GET", "/") |
| 1253 |
assert "mismatch, certificate is not valid for 'localhost'" in str( |
| 1254 |
e.value |
| 1255 |
) or "hostname 'localhost' doesn't match 'example.com'" in str(e.value) |
| 1256 |
|
| 1257 |
@pytest.mark.parametrize("use_assert_hostname", [True, False]) |
| 1258 |
def test_hostname_checks_common_name_respected( |
| 1259 |
self, no_san_server: ServerConfig, use_assert_hostname: bool |
| 1260 |
) -> None: |
| 1261 |
ctx = urllib3.util.ssl_.create_urllib3_context(verify_flags=0) |
| 1262 |
if not hasattr(ctx, "hostname_checks_common_name"): |
| 1263 |
pytest.skip("Test requires 'SSLContext.hostname_checks_common_name'") |
| 1264 |
ctx.load_verify_locations(no_san_server.ca_certs) |
| 1265 |
try: |
| 1266 |
ctx.hostname_checks_common_name = True |
| 1267 |
except AttributeError: |
| 1268 |
pytest.skip("Couldn't set 'SSLContext.hostname_checks_common_name'") |
| 1269 |
|
| 1270 |
err: MaxRetryError | None |
| 1271 |
try: |
| 1272 |
with HTTPSConnectionPool( |
| 1273 |
no_san_server.host, |
| 1274 |
no_san_server.port, |
| 1275 |
cert_reqs="CERT_REQUIRED", |
| 1276 |
ssl_context=ctx, |
| 1277 |
assert_hostname=no_san_server.host if use_assert_hostname else None, |
| 1278 |
) as https_pool: |
| 1279 |
https_pool.request("GET", "/") |
| 1280 |
except MaxRetryError as e: |
| 1281 |
err = e |
| 1282 |
else: |
| 1283 |
err = None |
| 1284 |
|
| 1285 |
# commonName is only valid for DNS names, not IP addresses. |
| 1286 |
if no_san_server.host == "localhost": |
| 1287 |
assert err is None |
| 1288 |
|
| 1289 |
# IP addresses should fail for commonName. |
| 1290 |
else: |
| 1291 |
assert err is not None |
| 1292 |
assert type(err.reason) is SSLError |
| 1293 |
assert isinstance( |
| 1294 |
err.reason.args[0], (ssl.SSLCertVerificationError, CertificateError) |
| 1295 |
) |
| 1296 |
|
| 1297 |
def test_assert_hostname_invalid_san( |
| 1298 |
self, no_localhost_san_server: ServerConfig |
| 1299 |
) -> None: |
| 1300 |
"""Ensure SAN errors are not raised while assert_hostname is false""" |
| 1301 |
with HTTPSConnectionPool( |
| 1302 |
no_localhost_san_server.host, |
| 1303 |
no_localhost_san_server.port, |
| 1304 |
cert_reqs="CERT_REQUIRED", |
| 1305 |
ca_certs=no_localhost_san_server.ca_certs, |
| 1306 |
assert_hostname=False, |
| 1307 |
) as https_pool: |
| 1308 |
https_pool.request("GET", "/") |
| 1309 |
|
| 1310 |
def test_assert_hostname_invalid_cn( |
| 1311 |
self, no_san_server_with_different_commmon_name: ServerConfig |
| 1312 |
) -> None: |
| 1313 |
"""Ensure CN errors are not raised while assert_hostname is false""" |
| 1314 |
ctx = urllib3.util.ssl_.create_urllib3_context(verify_flags=0) |
| 1315 |
with HTTPSConnectionPool( |
| 1316 |
no_san_server_with_different_commmon_name.host, |
| 1317 |
no_san_server_with_different_commmon_name.port, |
| 1318 |
cert_reqs="CERT_REQUIRED", |
| 1319 |
ca_certs=no_san_server_with_different_commmon_name.ca_certs, |
| 1320 |
ssl_context=ctx, |
| 1321 |
assert_hostname=False, |
| 1322 |
) as https_pool: |
| 1323 |
https_pool.request("GET", "/") |
| 1324 |
|
| 1325 |
|
| 1326 |
class TestHTTPS_IPV4SAN: |
| 1327 |
def test_can_validate_ip_san(self, ipv4_san_server: ServerConfig) -> None: |
| 1328 |
"""Ensure that urllib3 can validate SANs with IP addresses in them.""" |
| 1329 |
with HTTPSConnectionPool( |
| 1330 |
ipv4_san_server.host, |
| 1331 |
ipv4_san_server.port, |
| 1332 |
cert_reqs="CERT_REQUIRED", |
| 1333 |
ca_certs=ipv4_san_server.ca_certs, |
| 1334 |
) as https_pool: |
| 1335 |
r = https_pool.request("GET", "/") |
| 1336 |
assert r.status == 200 |
| 1337 |
|
| 1338 |
|
| 1339 |
class TestHTTPS_IPV6SAN: |
| 1340 |
@pytest.mark.parametrize("host", ["::1", "[::1]"]) |
| 1341 |
def test_can_validate_ipv6_san( |
| 1342 |
self, ipv6_san_server: ServerConfig, host: str, http_version: str |
| 1343 |
) -> None: |
| 1344 |
"""Ensure that urllib3 can validate SANs with IPv6 addresses in them.""" |
| 1345 |
with HTTPSConnectionPool( |
| 1346 |
host, |
| 1347 |
ipv6_san_server.port, |
| 1348 |
cert_reqs="CERT_REQUIRED", |
| 1349 |
ca_certs=ipv6_san_server.ca_certs, |
| 1350 |
) as https_pool: |
| 1351 |
r = https_pool.request("GET", "/") |
| 1352 |
assert r.status == 200 |
| 1353 |
assert r.headers["server"] == f"hypercorn-{http_version}" |