Debian Codegraph @

dummyserver/socketserver.py

raw
1 #!/usr/bin/env python
2
3 """
4 Dummy server used for unit testing.
5 """
6
7 from __future__ import annotations
8
9 import logging
10 import os
11 import socket
12 import ssl
13 import sys
14 import threading
15 import typing
16 import warnings
17
18 import trustme
19 from cryptography.hazmat.backends import default_backend
20 from cryptography.hazmat.primitives import serialization
21
22 from urllib3.exceptions import HTTPWarning
23 from urllib3.util import resolve_cert_reqs, resolve_ssl_version
24
25 if typing.TYPE_CHECKING:
26 from typing_extensions import ParamSpec
27
28 P = ParamSpec("P")
29
30 log = logging.getLogger(__name__)
31
32 CERTS_PATH = os.path.join(os.path.dirname(__file__), "certs")
33 DEFAULT_CERTS: dict[str, typing.Any] = {
34 "certfile": os.path.join(CERTS_PATH, "server.crt"),
35 "keyfile": os.path.join(CERTS_PATH, "server.key"),
36 "cert_reqs": ssl.CERT_OPTIONAL,
37 "ca_certs": os.path.join(CERTS_PATH, "cacert.pem"),
38 "alpn_protocols": ["h2", "http/1.1"],
39 }
40 DEFAULT_CA = os.path.join(CERTS_PATH, "cacert.pem")
41 DEFAULT_CA_KEY = os.path.join(CERTS_PATH, "cacert.key")
42
43
44 def _resolves_to_ipv6(host: str) -> bool:
45 """Returns True if the system resolves host to an IPv6 address by default."""
46 resolves_to_ipv6 = False
47 try:
48 for res in socket.getaddrinfo(host, None, socket.AF_UNSPEC):
49 af, _, _, _, _ = res
50 if af == socket.AF_INET6:
51 resolves_to_ipv6 = True
52 except socket.gaierror:
53 pass
54
55 return resolves_to_ipv6
56
57
58 def _has_ipv6(host: str) -> bool:
59 """Returns True if the system can bind an IPv6 address."""
60 sock = None
61 has_ipv6 = False
62
63 if socket.has_ipv6:
64 # has_ipv6 returns true if cPython was compiled with IPv6 support.
65 # It does not tell us if the system has IPv6 support enabled. To
66 # determine that we must bind to an IPv6 address.
67 # https://github.com/urllib3/urllib3/pull/611
68 # https://bugs.python.org/issue658327
69 try:
70 sock = socket.socket(socket.AF_INET6)
71 sock.bind((host, 0))
72 has_ipv6 = _resolves_to_ipv6("localhost")
73 except Exception:
74 pass
75
76 if sock:
77 sock.close()
78 return has_ipv6
79
80
81 # Some systems may have IPv6 support but DNS may not be configured
82 # properly. We can not count that localhost will resolve to ::1 on all
83 # systems. See https://github.com/urllib3/urllib3/pull/611 and
84 # https://bugs.python.org/issue18792
85 HAS_IPV6_AND_DNS = _has_ipv6("localhost")
86 HAS_IPV6 = _has_ipv6("::1")
87
88
89 # Different types of servers we have:
90
91
92 class NoIPv6Warning(HTTPWarning):
93 "IPv6 is not available"
94
95
96 class SocketServerThread(threading.Thread):
97 """
98 :param socket_handler: Callable which receives a socket argument for one
99 request.
100 :param ready_event: Event which gets set when the socket handler is
101 ready to receive requests.
102 """
103
104 USE_IPV6 = HAS_IPV6_AND_DNS
105
106 def __init__(
107 self,
108 socket_handler: typing.Callable[[socket.socket], None],
109 host: str = "localhost",
110 ready_event: threading.Event | None = None,
111 quit_event: threading.Event | None = None,
112 ) -> None:
113 super().__init__()
114 self.daemon = True
115
116 self.socket_handler = socket_handler
117 self.host = host
118 self.ready_event = ready_event
119 self.quit_event = quit_event
120
121 def _start_server(self) -> None:
122 if self.USE_IPV6:
123 sock = socket.socket(socket.AF_INET6)
124 else:
125 warnings.warn("No IPv6 support. Falling back to IPv4.", NoIPv6Warning)
126 sock = socket.socket(socket.AF_INET)
127 if sys.platform != "win32":
128 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
129
130 with sock:
131 sock.bind((self.host, 0))
132 self.port = sock.getsockname()[1]
133
134 # Once listen() returns, the server socket is ready
135 sock.listen(1)
136
137 if self.ready_event:
138 self.ready_event.set()
139
140 self.socket_handler(sock)
141
142 def run(self) -> None:
143 self._start_server()
144
145
146 def ssl_options_to_context( # type: ignore[no-untyped-def]
147 keyfile=None,
148 certfile=None,
149 server_side=None,
150 cert_reqs=None,
151 ssl_version: str | int | None = None,
152 ca_certs=None,
153 do_handshake_on_connect=None,
154 suppress_ragged_eofs=None,
155 ciphers=None,
156 alpn_protocols=None,
157 ) -> ssl.SSLContext:
158 """Return an equivalent SSLContext based on ssl.wrap_socket args."""
159 ssl_version = resolve_ssl_version(ssl_version)
160 cert_none = resolve_cert_reqs("CERT_NONE")
161 if cert_reqs is None:
162 cert_reqs = cert_none
163 else:
164 cert_reqs = resolve_cert_reqs(cert_reqs)
165
166 ctx = ssl.SSLContext(ssl_version)
167 ctx.load_cert_chain(certfile, keyfile)
168 ctx.verify_mode = cert_reqs
169 if ctx.verify_mode != cert_none:
170 ctx.load_verify_locations(cafile=ca_certs)
171 if alpn_protocols:
172 ctx.set_alpn_protocols(alpn_protocols)
173 return ctx
174
175
176 def get_unreachable_address() -> tuple[str, int]:
177 # reserved as per rfc2606
178 return ("something.invalid", 54321)
179
180
181 def encrypt_key_pem(private_key_pem: trustme.Blob, password: bytes) -> trustme.Blob:
182 private_key = serialization.load_pem_private_key(
183 private_key_pem.bytes(), password=None, backend=default_backend()
184 )
185 encrypted_key = private_key.private_bytes(
186 serialization.Encoding.PEM,
187 serialization.PrivateFormat.TraditionalOpenSSL,
188 serialization.BestAvailableEncryption(password),
189 )
190 return trustme.Blob(encrypted_key)