| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import contextlib |
| 4 |
import socket |
| 5 |
import ssl |
| 6 |
import threading |
| 7 |
import typing |
| 8 |
from test import LONG_TIMEOUT |
| 9 |
|
| 10 |
import pytest |
| 11 |
|
| 12 |
from dummyserver.app import hypercorn_app |
| 13 |
from dummyserver.asgi_proxy import ProxyApp |
| 14 |
from dummyserver.hypercornserver import run_hypercorn_in_thread |
| 15 |
from dummyserver.socketserver import DEFAULT_CERTS, HAS_IPV6, SocketServerThread |
| 16 |
from urllib3.connection import HTTPConnection |
| 17 |
from urllib3.util.ssltransport import SSLTransport |
| 18 |
|
| 19 |
|
| 20 |
def consume_socket( |
| 21 |
sock: SSLTransport | socket.socket, |
| 22 |
chunks: int = 65536, |
| 23 |
quit_event: threading.Event | None = None, |
| 24 |
) -> bytearray: |
| 25 |
consumed = bytearray() |
| 26 |
sock.settimeout(LONG_TIMEOUT) |
| 27 |
while True: |
| 28 |
if quit_event and quit_event.is_set(): |
| 29 |
break |
| 30 |
try: |
| 31 |
b = sock.recv(chunks) |
| 32 |
except TimeoutError: |
| 33 |
continue |
| 34 |
assert isinstance(b, bytes) |
| 35 |
consumed += b |
| 36 |
if b.endswith(b"\r\n\r\n"): |
| 37 |
break |
| 38 |
return consumed |
| 39 |
|
| 40 |
|
| 41 |
class SocketDummyServerTestCase: |
| 42 |
""" |
| 43 |
A simple socket-based server is created for this class that is good for |
| 44 |
exactly one request. |
| 45 |
""" |
| 46 |
|
| 47 |
scheme = "http" |
| 48 |
host = "localhost" |
| 49 |
|
| 50 |
server_thread: typing.ClassVar[SocketServerThread] |
| 51 |
port: typing.ClassVar[int] |
| 52 |
|
| 53 |
tmpdir: typing.ClassVar[str] |
| 54 |
ca_path: typing.ClassVar[str] |
| 55 |
cert_combined_path: typing.ClassVar[str] |
| 56 |
cert_path: typing.ClassVar[str] |
| 57 |
key_path: typing.ClassVar[str] |
| 58 |
password_key_path: typing.ClassVar[str] |
| 59 |
|
| 60 |
server_context: typing.ClassVar[ssl.SSLContext] |
| 61 |
client_context: typing.ClassVar[ssl.SSLContext] |
| 62 |
|
| 63 |
proxy_server: typing.ClassVar[SocketDummyServerTestCase] |
| 64 |
|
| 65 |
@classmethod |
| 66 |
def _start_server( |
| 67 |
cls, |
| 68 |
socket_handler: typing.Callable[[socket.socket], None], |
| 69 |
quit_event: threading.Event | None = None, |
| 70 |
) -> None: |
| 71 |
ready_event = threading.Event() |
| 72 |
cls.server_thread = SocketServerThread( |
| 73 |
socket_handler=socket_handler, |
| 74 |
ready_event=ready_event, |
| 75 |
host=cls.host, |
| 76 |
quit_event=quit_event, |
| 77 |
) |
| 78 |
cls.server_thread.start() |
| 79 |
ready_event.wait(5) |
| 80 |
if not ready_event.is_set(): |
| 81 |
raise Exception("most likely failed to start server") |
| 82 |
cls.port = cls.server_thread.port |
| 83 |
|
| 84 |
@classmethod |
| 85 |
def start_response_handler( |
| 86 |
cls, |
| 87 |
response: bytes, |
| 88 |
num: int = 1, |
| 89 |
block_send: threading.Event | None = None, |
| 90 |
) -> threading.Event: |
| 91 |
ready_event = threading.Event() |
| 92 |
quit_event = threading.Event() |
| 93 |
|
| 94 |
def socket_handler(listener: socket.socket) -> None: |
| 95 |
for _ in range(num): |
| 96 |
ready_event.set() |
| 97 |
|
| 98 |
listener.settimeout(LONG_TIMEOUT) |
| 99 |
while True: |
| 100 |
if quit_event.is_set(): |
| 101 |
return |
| 102 |
try: |
| 103 |
sock = listener.accept()[0] |
| 104 |
break |
| 105 |
except TimeoutError: |
| 106 |
continue |
| 107 |
consume_socket(sock, quit_event=quit_event) |
| 108 |
if quit_event.is_set(): |
| 109 |
sock.close() |
| 110 |
return |
| 111 |
if block_send: |
| 112 |
while not block_send.wait(LONG_TIMEOUT): |
| 113 |
if quit_event.is_set(): |
| 114 |
sock.close() |
| 115 |
return |
| 116 |
block_send.clear() |
| 117 |
sock.send(response) |
| 118 |
sock.close() |
| 119 |
|
| 120 |
cls._start_server(socket_handler, quit_event=quit_event) |
| 121 |
return ready_event |
| 122 |
|
| 123 |
@classmethod |
| 124 |
def start_basic_handler( |
| 125 |
cls, num: int = 1, block_send: threading.Event | None = None |
| 126 |
) -> threading.Event: |
| 127 |
return cls.start_response_handler( |
| 128 |
b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n", |
| 129 |
num, |
| 130 |
block_send, |
| 131 |
) |
| 132 |
|
| 133 |
@staticmethod |
| 134 |
def quit_server_thread(server_thread: SocketServerThread) -> None: |
| 135 |
if server_thread.quit_event: |
| 136 |
server_thread.quit_event.set() |
| 137 |
# in principle the maximum time that the thread can take to notice |
| 138 |
# the quit_event is LONG_TIMEOUT and the thread should terminate |
| 139 |
# shortly after that, we give 5 seconds leeway just in case |
| 140 |
server_thread.join(LONG_TIMEOUT * 2 + 5.0) |
| 141 |
if server_thread.is_alive(): |
| 142 |
raise Exception("server_thread did not exit") |
| 143 |
|
| 144 |
@classmethod |
| 145 |
def teardown_class(cls) -> None: |
| 146 |
if hasattr(cls, "server_thread"): |
| 147 |
cls.quit_server_thread(cls.server_thread) |
| 148 |
|
| 149 |
def teardown_method(self) -> None: |
| 150 |
if hasattr(self, "server_thread"): |
| 151 |
self.quit_server_thread(self.server_thread) |
| 152 |
|
| 153 |
def assert_header_received( |
| 154 |
self, |
| 155 |
received_headers: typing.Iterable[bytes], |
| 156 |
header_name: str, |
| 157 |
expected_value: str | None = None, |
| 158 |
) -> None: |
| 159 |
header_name_bytes = header_name.encode("ascii") |
| 160 |
if expected_value is None: |
| 161 |
expected_value_bytes = None |
| 162 |
else: |
| 163 |
expected_value_bytes = expected_value.encode("ascii") |
| 164 |
header_titles = [] |
| 165 |
for header in received_headers: |
| 166 |
key, value = header.split(b": ") |
| 167 |
header_titles.append(key) |
| 168 |
if key == header_name_bytes and expected_value_bytes is not None: |
| 169 |
assert value == expected_value_bytes |
| 170 |
assert header_name_bytes in header_titles |
| 171 |
|
| 172 |
|
| 173 |
class IPV4SocketDummyServerTestCase(SocketDummyServerTestCase): |
| 174 |
@classmethod |
| 175 |
def _start_server( |
| 176 |
cls, |
| 177 |
socket_handler: typing.Callable[[socket.socket], None], |
| 178 |
quit_event: threading.Event | None = None, |
| 179 |
) -> None: |
| 180 |
ready_event = threading.Event() |
| 181 |
cls.server_thread = SocketServerThread( |
| 182 |
socket_handler=socket_handler, |
| 183 |
ready_event=ready_event, |
| 184 |
host=cls.host, |
| 185 |
quit_event=quit_event, |
| 186 |
) |
| 187 |
cls.server_thread.USE_IPV6 = False |
| 188 |
cls.server_thread.start() |
| 189 |
ready_event.wait(5) |
| 190 |
if not ready_event.is_set(): |
| 191 |
raise Exception("most likely failed to start server") |
| 192 |
cls.port = cls.server_thread.port |
| 193 |
|
| 194 |
|
| 195 |
class HypercornDummyServerTestCase: |
| 196 |
host = "localhost" |
| 197 |
host_alt = "127.0.0.1" |
| 198 |
port: typing.ClassVar[int] |
| 199 |
base_url: typing.ClassVar[str] |
| 200 |
base_url_alt: typing.ClassVar[str] |
| 201 |
certs: typing.ClassVar[dict[str, typing.Any]] = {} |
| 202 |
|
| 203 |
_stack: typing.ClassVar[contextlib.ExitStack] |
| 204 |
|
| 205 |
@classmethod |
| 206 |
def setup_class(cls) -> None: |
| 207 |
with contextlib.ExitStack() as stack: |
| 208 |
cls.port = stack.enter_context( |
| 209 |
run_hypercorn_in_thread(cls.host, cls.certs, hypercorn_app) |
| 210 |
) |
| 211 |
cls._stack = stack.pop_all() |
| 212 |
|
| 213 |
@classmethod |
| 214 |
def teardown_class(cls) -> None: |
| 215 |
cls._stack.close() |
| 216 |
|
| 217 |
|
| 218 |
class HTTPSHypercornDummyServerTestCase(HypercornDummyServerTestCase): |
| 219 |
scheme = "https" |
| 220 |
host = "localhost" |
| 221 |
certs = DEFAULT_CERTS |
| 222 |
certs_dir = "" |
| 223 |
bad_ca_path = "" |
| 224 |
|
| 225 |
|
| 226 |
class HypercornDummyProxyTestCase: |
| 227 |
http_host: typing.ClassVar[str] = "localhost" |
| 228 |
http_host_alt: typing.ClassVar[str] = "127.0.0.1" |
| 229 |
http_port: typing.ClassVar[int] |
| 230 |
http_url: typing.ClassVar[str] |
| 231 |
http_url_alt: typing.ClassVar[str] |
| 232 |
|
| 233 |
https_host: typing.ClassVar[str] = "localhost" |
| 234 |
https_host_alt: typing.ClassVar[str] = "127.0.0.1" |
| 235 |
https_certs: typing.ClassVar[dict[str, typing.Any]] = DEFAULT_CERTS |
| 236 |
https_port: typing.ClassVar[int] |
| 237 |
https_url: typing.ClassVar[str] |
| 238 |
https_url_alt: typing.ClassVar[str] |
| 239 |
https_url_fqdn: typing.ClassVar[str] |
| 240 |
|
| 241 |
proxy_host: typing.ClassVar[str] = "localhost" |
| 242 |
proxy_host_alt: typing.ClassVar[str] = "127.0.0.1" |
| 243 |
proxy_port: typing.ClassVar[int] |
| 244 |
proxy_url: typing.ClassVar[str] |
| 245 |
https_proxy_port: typing.ClassVar[int] |
| 246 |
https_proxy_url: typing.ClassVar[str] |
| 247 |
|
| 248 |
certs_dir: typing.ClassVar[str] = "" |
| 249 |
bad_ca_path: typing.ClassVar[str] = "" |
| 250 |
|
| 251 |
server_thread: typing.ClassVar[threading.Thread] |
| 252 |
_stack: typing.ClassVar[contextlib.ExitStack] |
| 253 |
|
| 254 |
@classmethod |
| 255 |
def setup_class(cls) -> None: |
| 256 |
with contextlib.ExitStack() as stack: |
| 257 |
cls.http_port = stack.enter_context( |
| 258 |
run_hypercorn_in_thread(cls.http_host, None, hypercorn_app) |
| 259 |
) |
| 260 |
cls.https_port = stack.enter_context( |
| 261 |
run_hypercorn_in_thread(cls.https_host, cls.https_certs, hypercorn_app) |
| 262 |
) |
| 263 |
cls.proxy_port = stack.enter_context( |
| 264 |
run_hypercorn_in_thread(cls.proxy_host, None, ProxyApp()) |
| 265 |
) |
| 266 |
upstream_ca_certs = cls.https_certs.get("ca_certs") |
| 267 |
cls.https_proxy_port = stack.enter_context( |
| 268 |
run_hypercorn_in_thread( |
| 269 |
cls.proxy_host, cls.https_certs, ProxyApp(upstream_ca_certs) |
| 270 |
) |
| 271 |
) |
| 272 |
cls._stack = stack.pop_all() |
| 273 |
|
| 274 |
@classmethod |
| 275 |
def teardown_class(cls) -> None: |
| 276 |
cls._stack.close() |
| 277 |
|
| 278 |
|
| 279 |
@pytest.mark.skipif(not HAS_IPV6, reason="IPv6 not available") |
| 280 |
class IPv6HypercornDummyServerTestCase(HypercornDummyServerTestCase): |
| 281 |
host = "::1" |
| 282 |
|
| 283 |
|
| 284 |
@pytest.mark.skipif(not HAS_IPV6, reason="IPv6 not available") |
| 285 |
class IPv6HypercornDummyProxyTestCase(HypercornDummyProxyTestCase): |
| 286 |
http_host = "localhost" |
| 287 |
http_host_alt = "127.0.0.1" |
| 288 |
|
| 289 |
https_host = "localhost" |
| 290 |
https_host_alt = "127.0.0.1" |
| 291 |
https_certs = DEFAULT_CERTS |
| 292 |
|
| 293 |
proxy_host = "::1" |
| 294 |
proxy_host_alt = "127.0.0.1" |
| 295 |
|
| 296 |
|
| 297 |
class ConnectionMarker: |
| 298 |
""" |
| 299 |
Marks an HTTP(S)Connection's socket after a request was made. |
| 300 |
|
| 301 |
Helps a test server understand when a client finished a request, |
| 302 |
without implementing a complete HTTP server. |
| 303 |
""" |
| 304 |
|
| 305 |
MARK_FORMAT = b"$#MARK%04x*!" |
| 306 |
|
| 307 |
@classmethod |
| 308 |
@contextlib.contextmanager |
| 309 |
def mark(cls, monkeypatch: pytest.MonkeyPatch) -> typing.Generator[None]: |
| 310 |
""" |
| 311 |
Mark connections under in that context. |
| 312 |
""" |
| 313 |
|
| 314 |
orig_request = HTTPConnection.request |
| 315 |
|
| 316 |
def call_and_mark( |
| 317 |
target: typing.Callable[..., None], |
| 318 |
) -> typing.Callable[..., None]: |
| 319 |
def part( |
| 320 |
self: HTTPConnection, *args: typing.Any, **kwargs: typing.Any |
| 321 |
) -> None: |
| 322 |
target(self, *args, **kwargs) |
| 323 |
self.sock.sendall(cls._get_socket_mark(self.sock, False)) |
| 324 |
|
| 325 |
return part |
| 326 |
|
| 327 |
with monkeypatch.context() as m: |
| 328 |
m.setattr(HTTPConnection, "request", call_and_mark(orig_request)) |
| 329 |
yield |
| 330 |
|
| 331 |
@classmethod |
| 332 |
def consume_request(cls, sock: socket.socket, chunks: int = 65536) -> bytearray: |
| 333 |
""" |
| 334 |
Consume a socket until after the HTTP request is sent. |
| 335 |
""" |
| 336 |
consumed = bytearray() |
| 337 |
mark = cls._get_socket_mark(sock, True) |
| 338 |
while True: |
| 339 |
b = sock.recv(chunks) |
| 340 |
if not b: |
| 341 |
break |
| 342 |
consumed += b |
| 343 |
if consumed.endswith(mark): |
| 344 |
break |
| 345 |
return consumed |
| 346 |
|
| 347 |
@classmethod |
| 348 |
def _get_socket_mark(cls, sock: socket.socket, server: bool) -> bytes: |
| 349 |
if server: |
| 350 |
port = sock.getpeername()[1] |
| 351 |
else: |
| 352 |
port = sock.getsockname()[1] |
| 353 |
return cls.MARK_FORMAT % (port,) |