| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import contextlib |
| 4 |
import socket |
| 5 |
import ssl |
| 6 |
import typing |
| 7 |
from pathlib import Path |
| 8 |
|
| 9 |
import pytest |
| 10 |
import trustme |
| 11 |
|
| 12 |
import urllib3.http2 |
| 13 |
import urllib3.http2.probe as http2_probe |
| 14 |
from dummyserver.app import hypercorn_app |
| 15 |
from dummyserver.asgi_proxy import ProxyApp |
| 16 |
from dummyserver.hypercornserver import run_hypercorn_in_thread |
| 17 |
from dummyserver.socketserver import HAS_IPV6 |
| 18 |
from dummyserver.testcase import HTTPSHypercornDummyServerTestCase |
| 19 |
from urllib3.util import ssl_ |
| 20 |
|
| 21 |
from .tz_stub import stub_timezone_ctx |
| 22 |
|
| 23 |
|
| 24 |
def pytest_addoption(parser: pytest.Parser) -> None: |
| 25 |
parser.addoption( |
| 26 |
"--integration", |
| 27 |
action="store_true", |
| 28 |
default=False, |
| 29 |
help="run integration tests only", |
| 30 |
) |
| 31 |
|
| 32 |
|
| 33 |
def pytest_collection_modifyitems( |
| 34 |
config: pytest.Config, items: list[pytest.Item] |
| 35 |
) -> None: |
| 36 |
integration_mode = bool(config.getoption("--integration")) |
| 37 |
skip_integration = pytest.mark.skip( |
| 38 |
reason="skipping, need --integration option to run" |
| 39 |
) |
| 40 |
skip_normal = pytest.mark.skip( |
| 41 |
reason="skipping non integration tests in --integration mode" |
| 42 |
) |
| 43 |
for item in items: |
| 44 |
if "integration" in item.keywords and not integration_mode: |
| 45 |
item.add_marker(skip_integration) |
| 46 |
elif integration_mode and "integration" not in item.keywords: |
| 47 |
item.add_marker(skip_normal) |
| 48 |
|
| 49 |
|
| 50 |
class ServerConfig(typing.NamedTuple): |
| 51 |
scheme: str |
| 52 |
host: str |
| 53 |
port: int |
| 54 |
ca_certs: str |
| 55 |
|
| 56 |
@property |
| 57 |
def base_url(self) -> str: |
| 58 |
host = self.host |
| 59 |
if ":" in host: |
| 60 |
host = f"[{host}]" |
| 61 |
return f"{self.scheme}://{host}:{self.port}" |
| 62 |
|
| 63 |
|
| 64 |
def _write_cert_to_dir( |
| 65 |
cert: trustme.LeafCert, tmpdir: Path, file_prefix: str = "server" |
| 66 |
) -> dict[str, str]: |
| 67 |
cert_path = str(tmpdir / ("%s.pem" % file_prefix)) |
| 68 |
key_path = str(tmpdir / ("%s.key" % file_prefix)) |
| 69 |
cert.private_key_pem.write_to_path(key_path) |
| 70 |
cert.cert_chain_pems[0].write_to_path(cert_path) |
| 71 |
certs = {"keyfile": key_path, "certfile": cert_path} |
| 72 |
return certs |
| 73 |
|
| 74 |
|
| 75 |
@contextlib.contextmanager |
| 76 |
def run_server_in_thread( |
| 77 |
scheme: str, host: str, tmpdir: Path, ca: trustme.CA, server_cert: trustme.LeafCert |
| 78 |
) -> typing.Generator[ServerConfig]: |
| 79 |
ca_cert_path = str(tmpdir / "ca.pem") |
| 80 |
ca.cert_pem.write_to_path(ca_cert_path) |
| 81 |
server_certs = _write_cert_to_dir(server_cert, tmpdir) |
| 82 |
|
| 83 |
with run_hypercorn_in_thread(host, server_certs, hypercorn_app) as port: |
| 84 |
yield ServerConfig(scheme, host, port, ca_cert_path) |
| 85 |
|
| 86 |
|
| 87 |
@contextlib.contextmanager |
| 88 |
def run_server_and_proxy_in_thread( |
| 89 |
proxy_scheme: str, |
| 90 |
proxy_host: str, |
| 91 |
tmpdir: Path, |
| 92 |
ca: trustme.CA, |
| 93 |
proxy_cert: trustme.LeafCert, |
| 94 |
server_cert: trustme.LeafCert, |
| 95 |
) -> typing.Generator[tuple[ServerConfig, ServerConfig]]: |
| 96 |
ca_cert_path = str(tmpdir / "ca.pem") |
| 97 |
ca.cert_pem.write_to_path(ca_cert_path) |
| 98 |
|
| 99 |
server_certs = _write_cert_to_dir(server_cert, tmpdir) |
| 100 |
proxy_certs = _write_cert_to_dir(proxy_cert, tmpdir, "proxy") |
| 101 |
|
| 102 |
with contextlib.ExitStack() as stack: |
| 103 |
port = stack.enter_context( |
| 104 |
run_hypercorn_in_thread("localhost", server_certs, hypercorn_app) |
| 105 |
) |
| 106 |
proxy_port = stack.enter_context( |
| 107 |
run_hypercorn_in_thread(proxy_host, proxy_certs, ProxyApp()) |
| 108 |
) |
| 109 |
|
| 110 |
yield ( |
| 111 |
ServerConfig(proxy_scheme, proxy_host, proxy_port, ca_cert_path), |
| 112 |
ServerConfig("https", "localhost", port, ca_cert_path), |
| 113 |
) |
| 114 |
|
| 115 |
|
| 116 |
@pytest.fixture(params=["localhost", "127.0.0.1", "::1"]) |
| 117 |
def loopback_host(request: typing.Any) -> typing.Generator[str]: |
| 118 |
host = request.param |
| 119 |
if host == "::1" and not HAS_IPV6: |
| 120 |
pytest.skip("Test requires IPv6 on loopback") |
| 121 |
yield host |
| 122 |
|
| 123 |
|
| 124 |
@pytest.fixture() |
| 125 |
def san_server( |
| 126 |
loopback_host: str, tmp_path_factory: pytest.TempPathFactory |
| 127 |
) -> typing.Generator[ServerConfig]: |
| 128 |
tmpdir = tmp_path_factory.mktemp("certs") |
| 129 |
ca = trustme.CA() |
| 130 |
|
| 131 |
server_cert = ca.issue_cert(loopback_host) |
| 132 |
|
| 133 |
with run_server_in_thread("https", loopback_host, tmpdir, ca, server_cert) as cfg: |
| 134 |
yield cfg |
| 135 |
|
| 136 |
|
| 137 |
@pytest.fixture() |
| 138 |
def no_san_server( |
| 139 |
loopback_host: str, tmp_path_factory: pytest.TempPathFactory |
| 140 |
) -> typing.Generator[ServerConfig]: |
| 141 |
tmpdir = tmp_path_factory.mktemp("certs") |
| 142 |
ca = trustme.CA() |
| 143 |
server_cert = ca.issue_cert(common_name=loopback_host) |
| 144 |
|
| 145 |
with run_server_in_thread("https", loopback_host, tmpdir, ca, server_cert) as cfg: |
| 146 |
yield cfg |
| 147 |
|
| 148 |
|
| 149 |
@pytest.fixture() |
| 150 |
def no_san_server_with_different_commmon_name( |
| 151 |
tmp_path_factory: pytest.TempPathFactory, |
| 152 |
) -> typing.Generator[ServerConfig]: |
| 153 |
tmpdir = tmp_path_factory.mktemp("certs") |
| 154 |
ca = trustme.CA() |
| 155 |
server_cert = ca.issue_cert(common_name="example.com") |
| 156 |
|
| 157 |
with run_server_in_thread("https", "localhost", tmpdir, ca, server_cert) as cfg: |
| 158 |
yield cfg |
| 159 |
|
| 160 |
|
| 161 |
@pytest.fixture |
| 162 |
def san_proxy_with_server( |
| 163 |
loopback_host: str, tmp_path_factory: pytest.TempPathFactory |
| 164 |
) -> typing.Generator[tuple[ServerConfig, ServerConfig]]: |
| 165 |
tmpdir = tmp_path_factory.mktemp("certs") |
| 166 |
ca = trustme.CA() |
| 167 |
proxy_cert = ca.issue_cert(loopback_host) |
| 168 |
server_cert = ca.issue_cert("localhost") |
| 169 |
|
| 170 |
with run_server_and_proxy_in_thread( |
| 171 |
"https", loopback_host, tmpdir, ca, proxy_cert, server_cert |
| 172 |
) as cfg: |
| 173 |
yield cfg |
| 174 |
|
| 175 |
|
| 176 |
@pytest.fixture |
| 177 |
def no_san_proxy_with_server( |
| 178 |
tmp_path_factory: pytest.TempPathFactory, |
| 179 |
) -> typing.Generator[tuple[ServerConfig, ServerConfig]]: |
| 180 |
tmpdir = tmp_path_factory.mktemp("certs") |
| 181 |
ca = trustme.CA() |
| 182 |
# only common name, no subject alternative names |
| 183 |
proxy_cert = ca.issue_cert(common_name="localhost") |
| 184 |
server_cert = ca.issue_cert("localhost") |
| 185 |
|
| 186 |
with run_server_and_proxy_in_thread( |
| 187 |
"https", "localhost", tmpdir, ca, proxy_cert, server_cert |
| 188 |
) as cfg: |
| 189 |
yield cfg |
| 190 |
|
| 191 |
|
| 192 |
@pytest.fixture |
| 193 |
def no_localhost_san_server( |
| 194 |
tmp_path_factory: pytest.TempPathFactory, |
| 195 |
) -> typing.Generator[ServerConfig]: |
| 196 |
tmpdir = tmp_path_factory.mktemp("certs") |
| 197 |
ca = trustme.CA() |
| 198 |
# non localhost common name |
| 199 |
server_cert = ca.issue_cert("example.com") |
| 200 |
|
| 201 |
with run_server_in_thread("https", "localhost", tmpdir, ca, server_cert) as cfg: |
| 202 |
yield cfg |
| 203 |
|
| 204 |
|
| 205 |
@pytest.fixture |
| 206 |
def ipv4_san_proxy_with_server( |
| 207 |
tmp_path_factory: pytest.TempPathFactory, |
| 208 |
) -> typing.Generator[tuple[ServerConfig, ServerConfig]]: |
| 209 |
tmpdir = tmp_path_factory.mktemp("certs") |
| 210 |
ca = trustme.CA() |
| 211 |
# IP address in Subject Alternative Name |
| 212 |
proxy_cert = ca.issue_cert("127.0.0.1") |
| 213 |
|
| 214 |
server_cert = ca.issue_cert("localhost") |
| 215 |
|
| 216 |
with run_server_and_proxy_in_thread( |
| 217 |
"https", "127.0.0.1", tmpdir, ca, proxy_cert, server_cert |
| 218 |
) as cfg: |
| 219 |
yield cfg |
| 220 |
|
| 221 |
|
| 222 |
@pytest.fixture |
| 223 |
def ipv6_san_proxy_with_server( |
| 224 |
tmp_path_factory: pytest.TempPathFactory, |
| 225 |
) -> typing.Generator[tuple[ServerConfig, ServerConfig]]: |
| 226 |
tmpdir = tmp_path_factory.mktemp("certs") |
| 227 |
ca = trustme.CA() |
| 228 |
# IP addresses in Subject Alternative Name |
| 229 |
proxy_cert = ca.issue_cert("::1") |
| 230 |
|
| 231 |
server_cert = ca.issue_cert("localhost") |
| 232 |
|
| 233 |
with run_server_and_proxy_in_thread( |
| 234 |
"https", "::1", tmpdir, ca, proxy_cert, server_cert |
| 235 |
) as cfg: |
| 236 |
yield cfg |
| 237 |
|
| 238 |
|
| 239 |
@pytest.fixture |
| 240 |
def ipv4_san_server( |
| 241 |
tmp_path_factory: pytest.TempPathFactory, |
| 242 |
) -> typing.Generator[ServerConfig]: |
| 243 |
tmpdir = tmp_path_factory.mktemp("certs") |
| 244 |
ca = trustme.CA() |
| 245 |
# IP address in Subject Alternative Name |
| 246 |
server_cert = ca.issue_cert("127.0.0.1") |
| 247 |
|
| 248 |
with run_server_in_thread("https", "127.0.0.1", tmpdir, ca, server_cert) as cfg: |
| 249 |
yield cfg |
| 250 |
|
| 251 |
|
| 252 |
@pytest.fixture |
| 253 |
def ipv6_san_server( |
| 254 |
tmp_path_factory: pytest.TempPathFactory, |
| 255 |
) -> typing.Generator[ServerConfig]: |
| 256 |
if not HAS_IPV6: |
| 257 |
pytest.skip("Only runs on IPv6 systems") |
| 258 |
|
| 259 |
tmpdir = tmp_path_factory.mktemp("certs") |
| 260 |
ca = trustme.CA() |
| 261 |
# IP address in Subject Alternative Name |
| 262 |
server_cert = ca.issue_cert("::1") |
| 263 |
|
| 264 |
with run_server_in_thread("https", "::1", tmpdir, ca, server_cert) as cfg: |
| 265 |
yield cfg |
| 266 |
|
| 267 |
|
| 268 |
@pytest.fixture |
| 269 |
def ipv6_no_san_server( |
| 270 |
tmp_path_factory: pytest.TempPathFactory, |
| 271 |
) -> typing.Generator[ServerConfig]: |
| 272 |
if not HAS_IPV6: |
| 273 |
pytest.skip("Only runs on IPv6 systems") |
| 274 |
|
| 275 |
tmpdir = tmp_path_factory.mktemp("certs") |
| 276 |
ca = trustme.CA() |
| 277 |
# IP address in Common Name |
| 278 |
server_cert = ca.issue_cert(common_name="::1") |
| 279 |
|
| 280 |
with run_server_in_thread("https", "::1", tmpdir, ca, server_cert) as cfg: |
| 281 |
yield cfg |
| 282 |
|
| 283 |
|
| 284 |
@pytest.fixture |
| 285 |
def stub_timezone(request: pytest.FixtureRequest) -> typing.Generator[None]: |
| 286 |
""" |
| 287 |
A pytest fixture that runs the test with a stub timezone. |
| 288 |
""" |
| 289 |
with stub_timezone_ctx(request.param): |
| 290 |
yield |
| 291 |
|
| 292 |
|
| 293 |
@pytest.fixture(scope="session") |
| 294 |
def supported_tls_versions() -> typing.AbstractSet[str | None]: |
| 295 |
# We have to create an actual TLS connection |
| 296 |
# to test if the TLS version is not disabled by |
| 297 |
# OpenSSL config. Ubuntu 20.04 specifically |
| 298 |
# disables TLSv1 and TLSv1.1. |
| 299 |
tls_versions = set() |
| 300 |
|
| 301 |
_server = HTTPSHypercornDummyServerTestCase |
| 302 |
_server.setup_class() |
| 303 |
for _ssl_version_name, min_max_version in ( |
| 304 |
("PROTOCOL_TLSv1", ssl.TLSVersion.TLSv1), |
| 305 |
("PROTOCOL_TLSv1_1", ssl.TLSVersion.TLSv1_1), |
| 306 |
("PROTOCOL_TLSv1_2", ssl.TLSVersion.TLSv1_2), |
| 307 |
("PROTOCOL_TLS", None), |
| 308 |
): |
| 309 |
_ssl_version = getattr(ssl, _ssl_version_name, 0) |
| 310 |
if _ssl_version == 0: |
| 311 |
continue |
| 312 |
_sock = socket.create_connection((_server.host, _server.port)) |
| 313 |
try: |
| 314 |
_sock = ssl_.ssl_wrap_socket( |
| 315 |
_sock, |
| 316 |
ssl_context=ssl_.create_urllib3_context( |
| 317 |
cert_reqs=ssl.CERT_NONE, |
| 318 |
ssl_minimum_version=min_max_version, |
| 319 |
ssl_maximum_version=min_max_version, |
| 320 |
), |
| 321 |
) |
| 322 |
except ssl.SSLError: |
| 323 |
pass |
| 324 |
else: |
| 325 |
tls_versions.add(_sock.version()) |
| 326 |
_sock.close() |
| 327 |
_server.teardown_class() |
| 328 |
return tls_versions |
| 329 |
|
| 330 |
|
| 331 |
@pytest.fixture(scope="function") |
| 332 |
def requires_tlsv1(supported_tls_versions: typing.AbstractSet[str]) -> None: |
| 333 |
"""Test requires TLSv1 available""" |
| 334 |
if not hasattr(ssl, "PROTOCOL_TLSv1") or "TLSv1" not in supported_tls_versions: |
| 335 |
pytest.skip("Test requires TLSv1") |
| 336 |
|
| 337 |
|
| 338 |
@pytest.fixture(scope="function") |
| 339 |
def requires_tlsv1_1(supported_tls_versions: typing.AbstractSet[str]) -> None: |
| 340 |
"""Test requires TLSv1.1 available""" |
| 341 |
if not hasattr(ssl, "PROTOCOL_TLSv1_1") or "TLSv1.1" not in supported_tls_versions: |
| 342 |
pytest.skip("Test requires TLSv1.1") |
| 343 |
|
| 344 |
|
| 345 |
@pytest.fixture(scope="function") |
| 346 |
def requires_tlsv1_2(supported_tls_versions: typing.AbstractSet[str]) -> None: |
| 347 |
"""Test requires TLSv1.2 available""" |
| 348 |
if not hasattr(ssl, "PROTOCOL_TLSv1_2") or "TLSv1.2" not in supported_tls_versions: |
| 349 |
pytest.skip("Test requires TLSv1.2") |
| 350 |
|
| 351 |
|
| 352 |
@pytest.fixture(scope="function") |
| 353 |
def requires_tlsv1_3(supported_tls_versions: typing.AbstractSet[str]) -> None: |
| 354 |
"""Test requires TLSv1.3 available""" |
| 355 |
if ( |
| 356 |
not getattr(ssl, "HAS_TLSv1_3", False) |
| 357 |
or "TLSv1.3" not in supported_tls_versions |
| 358 |
): |
| 359 |
pytest.skip("Test requires TLSv1.3") |
| 360 |
|
| 361 |
|
| 362 |
class ErroringHTTPConnection: |
| 363 |
def __init__(self, *args: typing.Any, **kwargs: typing.Any): |
| 364 |
raise ValueError( |
| 365 |
"HTTP/2 support currently only applies to HTTPS, don't use http_version for HTTP tests" |
| 366 |
) |
| 367 |
|
| 368 |
|
| 369 |
@pytest.fixture(params=["h11", "h2"]) |
| 370 |
def http_version(request: pytest.FixtureRequest) -> typing.Generator[str]: |
| 371 |
orig_HTTPConnection: typing.Any = None |
| 372 |
|
| 373 |
if request.param == "h2": |
| 374 |
urllib3.http2.inject_into_urllib3() |
| 375 |
|
| 376 |
from urllib3 import connection as urllib3_connection |
| 377 |
from urllib3.connectionpool import HTTPConnectionPool |
| 378 |
|
| 379 |
orig_HTTPConnection = urllib3_connection.HTTPConnection |
| 380 |
urllib3_connection.HTTPConnection = ErroringHTTPConnection # type: ignore[misc,assignment] |
| 381 |
HTTPConnectionPool.ConnectionCls = ErroringHTTPConnection # type: ignore[assignment] |
| 382 |
try: |
| 383 |
yield request.param |
| 384 |
finally: |
| 385 |
if request.param == "h2": |
| 386 |
urllib3_connection.HTTPConnection = orig_HTTPConnection # type: ignore[misc] |
| 387 |
HTTPConnectionPool.ConnectionCls = orig_HTTPConnection |
| 388 |
|
| 389 |
urllib3.http2.extract_from_urllib3() |
| 390 |
|
| 391 |
|
| 392 |
@pytest.fixture(autouse=True, scope="function") |
| 393 |
def reset_http2_probe_cache() -> typing.Generator[None]: |
| 394 |
# Always reset the HTTP/2 probe cache per test case. |
| 395 |
try: |
| 396 |
yield |
| 397 |
finally: |
| 398 |
http2_probe._reset() |