diff options
| -rw-r--r-- | Makefile | [diff] [file] | 4 | ||||
| -rw-r--r-- | tests/check_install.py | [diff] [file] | 2 | ||||
| -rw-r--r-- | tests/conftest.py | [diff] [file] | 5 | ||||
| -rw-r--r-- | tests/mypy.ini | [diff] [file] | 9 | ||||
| -rw-r--r-- | tests/requirements.txt | [diff] [file] | 2 | ||||
| -rw-r--r-- | tests/test_impersonate.py | [diff] [file] | 172 |
6 files changed, 134 insertions, 60 deletions
@@ -66,3 +66,7 @@ clean: distclean: rm -rf $(BUILD_DIR) .PHONY: distclean + +typecheck: + python -m mypy --config-file tests/mypy.ini tests/test_impersonate.py tests/conftest.py tests/check_install.py +.PHONY: typecheck diff --git a/tests/check_install.py b/tests/check_install.py index 1894413..3648b15 100644 --- a/tests/check_install.py +++ b/tests/check_install.py @@ -32,7 +32,7 @@ int main(void) """ -def main(): +def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--prefix", required=True, type=Path) parser.add_argument("--libdir", default="lib") diff --git a/tests/conftest.py b/tests/conftest.py index 5428fa0..b4617ab 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,4 +1,7 @@ -def pytest_addoption(parser): +import pytest + + +def pytest_addoption(parser: pytest.Parser) -> None: # Where to find curl-impersonate's binaries parser.addoption("--install-dir", action="store", default="/usr/local") parser.addoption("--capture-interface", action="store", default="eth0") diff --git a/tests/mypy.ini b/tests/mypy.ini new file mode 100644 index 0000000..3c2285d --- /dev/null +++ b/tests/mypy.ini @@ -0,0 +1,9 @@ +[mypy] +python_version = 3.10 +disallow_untyped_defs = True + +[mypy-th1.*] +ignore_missing_imports = True + +[mypy-dpkt.*] +ignore_missing_imports = True diff --git a/tests/requirements.txt b/tests/requirements.txt index 1bf0cb0..16f90ef 100644 --- a/tests/requirements.txt +++ b/tests/requirements.txt @@ -3,3 +3,5 @@ pytest pytest-asyncio websockets>=15,<16 th1 @ git+https://github.com/lexiforest/th1.git@main +mypy>=1.10,<2 +types-PyYAML diff --git a/tests/test_impersonate.py b/tests/test_impersonate.py index 217035c..171db77 100644 --- a/tests/test_impersonate.py +++ b/tests/test_impersonate.py @@ -11,6 +11,8 @@ import tempfile import itertools import asyncio import time +from collections.abc import AsyncIterator, Collection, Iterator +from typing import Any, TypedDict, cast import yaml import pytest @@ -21,8 +23,27 @@ from th1.http2.signature import HTTP2Signature import dpkt +class HTTP3Response(TypedDict): + http3: dict[str, Any] + tls: dict[str, Any] + + +class HTTP3Expected(TypedDict, total=False): + perk_text_normalized: str + settings: str + pseudo_headers_order: str + quic_transport_parameters: str + headers: dict[str, str] + ja3_text: str + signature_algorithms: list[Any] + + +TransportParameters = dict[str, str | None] +BrowserSignatures = dict[str, dict[str, Any]] + + @pytest.fixture -def browser_signatures(): +def browser_signatures() -> BrowserSignatures: docs = {} for path in pathlib.Path("signatures").glob("**/*.yaml"): with open(path, "r") as f: @@ -90,13 +111,10 @@ for path in pathlib.Path("signatures").glob("**/*.yaml"): @pytest.fixture -def socks5_udp_proxy(pytestconfig): +def socks5_udp_proxy(pytestconfig: pytest.Config) -> Iterator[str]: """Run a local SOCKS5 server with UDP ASSOCIATE support.""" - socks5 = os.path.join( - pytestconfig.getoption("install_dir"), "bin", "socks5" - ) - if not os.access(socks5, os.X_OK): - socks5 = shutil.which("socks5") + installed = os.path.join(pytestconfig.getoption("install_dir"), "bin", "socks5") + socks5 = installed if os.access(installed, os.X_OK) else shutil.which("socks5") if not socks5: pytest.skip("socks5 test server is not installed") @@ -135,13 +153,13 @@ def socks5_udp_proxy(pytestconfig): @pytest.fixture -def test_urls(): +def test_urls() -> list[str]: # Shuffle TEST_URLS randomly return random.sample(TEST_URLS, k=len(TEST_URLS)) @pytest.fixture -def tcpdump(pytestconfig): +def tcpdump(pytestconfig: pytest.Config) -> Iterator[subprocess.Popen[bytes]]: """Initialize a sniffer to capture curl's traffic.""" interface = pytestconfig.getoption("capture_interface") @@ -175,7 +193,9 @@ def tcpdump(pytestconfig): p.wait(timeout=10) -async def _read_proc_output(proc, timeout: int = 5): +async def _read_proc_output( + proc: asyncio.subprocess.Process, timeout: int = 5 +) -> bytes: """Read an async process' output until timeout is reached""" data = bytes() loop = asyncio.get_running_loop() @@ -184,7 +204,8 @@ async def _read_proc_output(proc, timeout: int = 5): while passed < timeout: try: data += await asyncio.wait_for( - proc.stdout.readline(), timeout=timeout - passed + cast(asyncio.StreamReader, proc.stdout).readline(), + timeout=timeout - passed, ) except asyncio.TimeoutError: pass @@ -192,11 +213,11 @@ async def _read_proc_output(proc, timeout: int = 5): return data -async def _wait_nghttpd(proc): +async def _wait_nghttpd(proc: asyncio.subprocess.Process) -> bool: """Wait for nghttpd to start listening on its designated port""" data = bytes() while data is not None: - data = await proc.stdout.readline() + data = await cast(asyncio.StreamReader, proc.stdout).readline() if not data: # Process terminated return False @@ -209,7 +230,7 @@ async def _wait_nghttpd(proc): @pytest.fixture -async def nghttpd(): +async def nghttpd() -> AsyncIterator[asyncio.subprocess.Process]: """Initialize an HTTP/2 server. The returned object is an asyncio.subprocess.Process object, so async methods must be used with it. @@ -243,14 +264,20 @@ async def nghttpd(): await proc.wait() -def _set_ld_preload(env_vars, lib): +def _set_ld_preload(env_vars: dict[str, str], lib: str) -> None: if sys.platform.startswith("linux"): env_vars["LD_PRELOAD"] = lib + ".so" elif sys.platform.startswith("darwin"): env_vars["DYLD_INSERT_LIBRARIES"] = lib + ".dylib" -def _run_curl(curl_binary, env_vars, extra_args, urls, output="/dev/null"): +def _run_curl( + curl_binary: str, + env_vars: dict[str, str] | None, + extra_args: list[str] | None, + urls: list[str], + output: str = "/dev/null", +) -> int: env = os.environ.copy() if env_vars: env.update(env_vars) @@ -281,7 +308,9 @@ def _run_curl(curl_binary, env_vars, extra_args, urls, output="/dev/null"): return curl.wait(timeout=60) -def _assert_partial_tls_signature(sig, expected, allow_tls_permutation): +def _assert_partial_tls_signature( + sig: TLSClientHelloSignature, expected: dict[str, Any], allow_tls_permutation: bool +) -> None: """Compare supplied th1 fields with profile GREASE/resumption rules.""" actual = sig.to_dict() ciphers = actual["ciphersuites"] @@ -316,7 +345,9 @@ def _assert_partial_tls_signature(sig, expected, allow_tls_permutation): ) -def test_tls_client_hello_smoke(pytestconfig, browser_signatures): +def test_tls_client_hello_smoke( + pytestconfig: pytest.Config, browser_signatures: BrowserSignatures +) -> None: """Check one recent profile over loopback without a packet sniffer.""" profile = "chrome152" binary = "curl-impersonate.exe" if sys.platform == "win32" else "curl-impersonate" @@ -373,15 +404,15 @@ def test_tls_client_hello_smoke(pytestconfig, browser_signatures): CURL_BINARIES_AND_SIGNATURES, ) def test_tls_client_hello( - pytestconfig, - tcpdump, - curl_binary, - env_vars, - ld_preload, - browser_signatures, - expected_signature, - test_urls, -): + pytestconfig: pytest.Config, + tcpdump: subprocess.Popen[bytes], + curl_binary: str, + env_vars: dict[str, str] | None, + ld_preload: str | None, + browser_signatures: BrowserSignatures, + expected_signature: str, + test_urls: list[str], +) -> None: """ Check that curl's TLS signature is identical to that of a real browser. @@ -401,7 +432,7 @@ def test_tls_client_hello( pytest.skip() _set_ld_preload( - env_vars, + cast(dict[str, str], env_vars), os.path.join(pytestconfig.getoption("install_dir"), "lib", ld_preload), ) @@ -415,7 +446,8 @@ def test_tls_client_hello( # If tcpdump finished running before timeout, it's likely it failed # with an error. assert tcpdump.returncode == 0, ( - f"tcpdump failed with error code {tcpdump.returncode}, " f"stderr: {stderr}" + f"tcpdump failed with error code {tcpdump.returncode}, " + f"stderr: {stderr!r}" ) except subprocess.TimeoutExpired: tcpdump.kill() @@ -463,14 +495,14 @@ def test_tls_client_hello( CURL_BINARIES_AND_SIGNATURES, ) async def test_http2_headers( - pytestconfig, - nghttpd, - curl_binary, - env_vars, - ld_preload, - browser_signatures, - expected_signature, -): + pytestconfig: pytest.Config, + nghttpd: asyncio.subprocess.Process, + curl_binary: str, + env_vars: dict[str, str] | None, + ld_preload: str | None, + browser_signatures: BrowserSignatures, + expected_signature: str, +) -> None: curl_binary = os.path.join( pytestconfig.getoption("install_dir"), "bin", curl_binary ) @@ -482,7 +514,7 @@ async def test_http2_headers( pytest.skip() _set_ld_preload( - env_vars, + cast(dict[str, str], env_vars), os.path.join(pytestconfig.getoption("install_dir"), "lib", ld_preload), ) @@ -509,9 +541,11 @@ async def test_http2_headers( assert equals, msg -def _http3_transport_parameters(text, auto_ids=()): +def _http3_transport_parameters( + text: str, auto_ids: Collection[str] = () +) -> TransportParameters: """Normalize option hex literals and explicitly variable QUIC values.""" - result = {} + result: TransportParameters = {} for item in text.split(";"): key, separator, value = item.partition(":") if value.startswith("0x"): @@ -522,7 +556,7 @@ def _http3_transport_parameters(text, auto_ids=()): return result -def _assert_http3_signature(response, expected): +def _assert_http3_signature(response: HTTP3Response, expected: HTTP3Expected) -> None: actual = response["http3"] if "perk_text_normalized" in expected: assert actual["perk_text_normalized"] == expected["perk_text_normalized"] @@ -563,8 +597,13 @@ def _assert_http3_signature(response, expected): "curl_binary, env_vars, ld_preload, profile", HTTP3_CLIENTS ) def test_http3_fingerprint( - pytestconfig, browser_signatures, curl_binary, env_vars, ld_preload, profile -): + pytestconfig: pytest.Config, + browser_signatures: BrowserSignatures, + curl_binary: str, + env_vars: dict[str, str] | None, + ld_preload: str | None, + profile: str, +) -> None: """Compare stable HTTP/3, QUIC, and QUIC TLS fingerprint fields.""" curl_binary = os.path.join( pytestconfig.getoption("install_dir"), "bin", curl_binary @@ -605,8 +644,11 @@ def test_http3_fingerprint( @pytest.mark.parametrize("proxy_scheme", ["socks5", "socks5h"]) @pytest.mark.parametrize("http3_option", ["--http3", "--http3-only"]) def test_http3_through_socks_udp_proxy( - pytestconfig, socks5_udp_proxy, proxy_scheme, http3_option -): + pytestconfig: pytest.Config, + socks5_udp_proxy: str, + proxy_scheme: str, + http3_option: str, +) -> None: """HTTP/3 must use SOCKS5 UDP ASSOCIATE for proxied QUIC traffic.""" curl_binary = os.path.join( pytestconfig.getoption("install_dir"), "bin", "curl-impersonate" @@ -655,14 +697,14 @@ def test_http3_through_socks_udp_proxy( "curl_binary, env_vars, ld_preload, profile", HTTP3_CLIENTS ) async def test_http3_fallback_to_http2( - pytestconfig, - nghttpd, - browser_signatures, - curl_binary, - env_vars, - ld_preload, - profile, -): + pytestconfig: pytest.Config, + nghttpd: asyncio.subprocess.Process, + browser_signatures: BrowserSignatures, + curl_binary: str, + env_vars: dict[str, str] | None, + ld_preload: str | None, + profile: str, +) -> None: """HTTP/3 preferred mode must retain the profile when falling back to H2.""" curl_binary = os.path.join( pytestconfig.getoption("install_dir"), "bin", curl_binary @@ -707,8 +749,12 @@ async def test_http3_fallback_to_http2( ], ) async def test_no_builtin_headers( - pytestconfig, nghttpd, curl_binary, env_vars, ld_preload -): + pytestconfig: pytest.Config, + nghttpd: asyncio.subprocess.Process, + curl_binary: str, + env_vars: dict[str, str], + ld_preload: str, +) -> None: """ Ensure the built-in headers of libcurl-impersonate are not added when the CURL_IMPERSONATE_HEADERS environment variable is set to "no". @@ -772,7 +818,13 @@ async def test_no_builtin_headers( ), ], ) -async def test_user_agent(pytestconfig, nghttpd, curl_binary, env_vars, ld_preload): +async def test_user_agent( + pytestconfig: pytest.Config, + nghttpd: asyncio.subprocess.Process, + curl_binary: str, + env_vars: dict[str, str], + ld_preload: str, +) -> None: """ Ensure that any user-agent set with CURLOPT_HTTPHEADER will override the one set by libcurl-impersonate. @@ -832,8 +884,12 @@ async def test_user_agent(pytestconfig, nghttpd, curl_binary, env_vars, ld_prelo ], ) async def test_user_agent_curlopt_useragent( - pytestconfig, nghttpd, curl_binary, env_vars, ld_preload -): + pytestconfig: pytest.Config, + nghttpd: asyncio.subprocess.Process, + curl_binary: str, + env_vars: dict[str, str], + ld_preload: str, +) -> None: """ Ensure that any user-agent set with CURLOPT_USERAGENT will override the one set by libcurl-impersonate. See: |
