Debian Codegraph @

test/test_connection.py

raw
1 from __future__ import annotations
2
3 import datetime
4 import socket
5 import typing
6 from http.client import ResponseNotReady
7 from unittest import mock
8
9 import pytest
10
11 from urllib3.connection import ( # type: ignore[attr-defined]
12 RECENT_DATE,
13 CertificateError,
14 HTTPConnection,
15 HTTPSConnection,
16 _match_hostname,
17 _url_from_connection,
18 _wrap_proxy_error,
19 )
20 from urllib3.exceptions import HTTPError, ProxyError, SSLError
21 from urllib3.util import ssl_
22 from urllib3.util.request import SKIP_HEADER
23 from urllib3.util.ssl_match_hostname import (
24 CertificateError as ImplementationCertificateError,
25 )
26 from urllib3.util.ssl_match_hostname import (
27 _dnsname_match,
28 match_hostname,
29 )
30
31 if typing.TYPE_CHECKING:
32 from urllib3.util.ssl_ import _TYPE_PEER_CERT_RET_DICT
33
34
35 class TestConnection:
36 """
37 Tests in this suite should not make any network requests or connections.
38 """
39
40 def test_match_hostname_no_cert(self) -> None:
41 cert = None
42 asserted_hostname = "foo"
43 with pytest.raises(ValueError):
44 _match_hostname(cert, asserted_hostname)
45
46 def test_match_hostname_empty_cert(self) -> None:
47 cert: _TYPE_PEER_CERT_RET_DICT = {}
48 asserted_hostname = "foo"
49 with pytest.raises(ValueError):
50 _match_hostname(cert, asserted_hostname)
51
52 def test_match_hostname_match(self) -> None:
53 cert: _TYPE_PEER_CERT_RET_DICT = {"subjectAltName": (("DNS", "foo"),)}
54 asserted_hostname = "foo"
55 _match_hostname(cert, asserted_hostname)
56
57 def test_match_hostname_mismatch(self) -> None:
58 cert: _TYPE_PEER_CERT_RET_DICT = {"subjectAltName": (("DNS", "foo"),)}
59 asserted_hostname = "bar"
60 try:
61 with mock.patch("urllib3.connection.log.warning") as mock_log:
62 _match_hostname(cert, asserted_hostname)
63 except CertificateError as e:
64 assert "hostname 'bar' doesn't match 'foo'" in str(e)
65 mock_log.assert_called_once_with(
66 "Certificate did not match expected hostname: %s. Certificate: %s",
67 "bar",
68 {"subjectAltName": (("DNS", "foo"),)},
69 )
70 assert e._peer_cert == cert # type: ignore[attr-defined]
71
72 def test_match_hostname_no_dns(self) -> None:
73 cert: _TYPE_PEER_CERT_RET_DICT = {"subjectAltName": (("DNS", ""),)}
74 asserted_hostname = "bar"
75 try:
76 with mock.patch("urllib3.connection.log.warning") as mock_log:
77 _match_hostname(cert, asserted_hostname)
78 except CertificateError as e:
79 assert "hostname 'bar' doesn't match ''" in str(e)
80 mock_log.assert_called_once_with(
81 "Certificate did not match expected hostname: %s. Certificate: %s",
82 "bar",
83 {"subjectAltName": (("DNS", ""),)},
84 )
85 assert e._peer_cert == cert # type: ignore[attr-defined]
86
87 def test_match_hostname_startwith_wildcard(self) -> None:
88 cert: _TYPE_PEER_CERT_RET_DICT = {"subjectAltName": (("DNS", "*"),)}
89 asserted_hostname = "foo"
90 _match_hostname(cert, asserted_hostname)
91
92 def test_match_hostname_dnsname(self) -> None:
93 cert: _TYPE_PEER_CERT_RET_DICT = {
94 "subjectAltName": (("DNS", "xn--p1b6ci4b4b3a*.xn--11b5bs8d"),)
95 }
96 asserted_hostname = "xn--p1b6ci4b4b3a*.xn--11b5bs8d"
97 _match_hostname(cert, asserted_hostname)
98
99 def test_match_hostname_include_wildcard(self) -> None:
100 cert: _TYPE_PEER_CERT_RET_DICT = {"subjectAltName": (("DNS", "foo*"),)}
101 asserted_hostname = "foobar"
102 _match_hostname(cert, asserted_hostname)
103
104 def test_match_hostname_more_than_one_dnsname_error(self) -> None:
105 cert: _TYPE_PEER_CERT_RET_DICT = {
106 "subjectAltName": (("DNS", "foo*"), ("DNS", "fo*"))
107 }
108 asserted_hostname = "bar"
109 with pytest.raises(CertificateError, match="doesn't match either of"):
110 _match_hostname(cert, asserted_hostname)
111
112 def test_dnsname_match_include_more_than_one_wildcard_error(self) -> None:
113 with pytest.raises(CertificateError, match="too many wildcards in certificate"):
114 _dnsname_match("foo**", "foobar")
115
116 def test_match_hostname_ignore_common_name(self) -> None:
117 cert: _TYPE_PEER_CERT_RET_DICT = {"subject": ((("commonName", "foo"),),)}
118 asserted_hostname = "foo"
119 with pytest.raises(
120 ImplementationCertificateError,
121 match="no appropriate subjectAltName fields were found",
122 ):
123 match_hostname(cert, asserted_hostname)
124
125 def test_match_hostname_check_common_name(self) -> None:
126 cert: _TYPE_PEER_CERT_RET_DICT = {"subject": ((("commonName", "foo"),),)}
127 asserted_hostname = "foo"
128 match_hostname(cert, asserted_hostname, True)
129
130 def test_match_hostname_ip_address(self) -> None:
131 cert: _TYPE_PEER_CERT_RET_DICT = {
132 "subjectAltName": (("IP Address", "1.1.1.1"),)
133 }
134 asserted_hostname = "1.1.1.2"
135 try:
136 with mock.patch("urllib3.connection.log.warning") as mock_log:
137 _match_hostname(cert, asserted_hostname)
138 except CertificateError as e:
139 assert "hostname '1.1.1.2' doesn't match '1.1.1.1'" in str(e)
140 mock_log.assert_called_once_with(
141 "Certificate did not match expected hostname: %s. Certificate: %s",
142 "1.1.1.2",
143 {"subjectAltName": (("IP Address", "1.1.1.1"),)},
144 )
145 assert e._peer_cert == cert # type: ignore[attr-defined]
146
147 @pytest.mark.parametrize(
148 ["asserted_hostname", "san_ip"],
149 [
150 ("1:2::3:4", "1:2:0:0:0:0:3:4"),
151 ("1:2:0:0::3:4", "1:2:0:0:0:0:3:4"),
152 ("::0.1.0.2", "0:0:0:0:0:0:1:2"),
153 ("::1%42", "0:0:0:0:0:0:0:1"),
154 ("::2%iface", "0:0:0:0:0:0:0:2"),
155 ],
156 )
157 def test_match_hostname_ip_address_ipv6(
158 self, asserted_hostname: str, san_ip: str
159 ) -> None:
160 """Check that hostname matches follow RFC 9110 rules for IPv6."""
161 cert: _TYPE_PEER_CERT_RET_DICT = {"subjectAltName": (("IP Address", san_ip),)}
162 match_hostname(cert, asserted_hostname)
163
164 def test_match_hostname_ip_address_ipv6_doesnt_match(self) -> None:
165 cert: _TYPE_PEER_CERT_RET_DICT = {
166 "subjectAltName": (("IP Address", "1:2::2:1"),)
167 }
168 asserted_hostname = "1:2::2:2"
169 try:
170 with mock.patch("urllib3.connection.log.warning") as mock_log:
171 _match_hostname(cert, asserted_hostname)
172 except CertificateError as e:
173 assert "hostname '1:2::2:2' doesn't match '1:2::2:1'" in str(e)
174 mock_log.assert_called_once_with(
175 "Certificate did not match expected hostname: %s. Certificate: %s",
176 "1:2::2:2",
177 {"subjectAltName": (("IP Address", "1:2::2:1"),)},
178 )
179 assert e._peer_cert == cert # type: ignore[attr-defined]
180
181 def test_match_hostname_dns_with_brackets_doesnt_match(self) -> None:
182 cert: _TYPE_PEER_CERT_RET_DICT = {
183 "subjectAltName": (
184 ("DNS", "localhost"),
185 ("IP Address", "localhost"),
186 )
187 }
188 asserted_hostname = "[localhost]"
189 with pytest.raises(CertificateError) as e:
190 _match_hostname(cert, asserted_hostname)
191 assert (
192 "hostname '[localhost]' doesn't match either of 'localhost', 'localhost'"
193 in str(e.value)
194 )
195
196 def test_match_hostname_ip_address_ipv6_brackets(self) -> None:
197 cert: _TYPE_PEER_CERT_RET_DICT = {
198 "subjectAltName": (("IP Address", "1:2::2:1"),)
199 }
200 asserted_hostname = "[1:2::2:1]"
201 # Assert no error is raised
202 _match_hostname(cert, asserted_hostname)
203
204 def test_recent_date(self) -> None:
205 # This test is to make sure that the RECENT_DATE value
206 # doesn't get too far behind what the current date is.
207 # When this test fails update urllib3.connection.RECENT_DATE
208 # according to the rules defined in that file.
209 two_years = datetime.timedelta(days=365 * 2)
210 assert RECENT_DATE > (datetime.datetime.today() - two_years).date()
211
212 def test_HTTPSConnection_default_socket_options(self) -> None:
213 conn = HTTPSConnection("not.a.real.host", port=443)
214 assert conn.socket_options == [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)]
215
216 @pytest.mark.parametrize(
217 "proxy_scheme, err_part",
218 [
219 ("http", "Unable to connect to proxy"),
220 (
221 "https",
222 "Unable to connect to proxy. Your proxy appears to only use HTTP and not HTTPS",
223 ),
224 ],
225 )
226 def test_wrap_proxy_error(self, proxy_scheme: str, err_part: str) -> None:
227 new_err = _wrap_proxy_error(HTTPError("unknown protocol"), proxy_scheme)
228 assert isinstance(new_err, ProxyError) is True
229 assert err_part in new_err.args[0]
230
231 def test_url_from_pool(self) -> None:
232 conn = HTTPConnection("google.com", port=80)
233
234 path = "path?query=foo"
235 assert f"http://google.com:80/{path}" == _url_from_connection(conn, path)
236
237 def test_getresponse_requires_reponseoptions(self) -> None:
238 conn = HTTPConnection("google.com", port=80)
239
240 # Should error if a request has not been sent
241 with pytest.raises(ResponseNotReady):
242 conn.getresponse()
243
244 def test_assert_fingerprint_closes_socket(self) -> None:
245 context = mock.create_autospec(ssl_.SSLContext)
246 context.wrap_socket.return_value.getpeercert.return_value = b"fake cert"
247 conn = HTTPSConnection(
248 "google.com",
249 port=443,
250 assert_fingerprint="AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA",
251 ssl_context=context,
252 )
253 with mock.patch.object(conn, "_new_conn"):
254 with pytest.raises(SSLError):
255 conn.connect()
256
257 context.wrap_socket.return_value.close.assert_called_once_with()
258
259 def test_assert_hostname_closes_socket(self) -> None:
260 context = mock.create_autospec(ssl_.SSLContext)
261 context.wrap_socket.return_value.getpeercert.return_value = {
262 "subjectAltName": (("DNS", "google.com"),)
263 }
264 conn = HTTPSConnection(
265 "google.com", port=443, assert_hostname="example.com", ssl_context=context
266 )
267 with mock.patch.object(conn, "_new_conn"):
268 with pytest.raises(ImplementationCertificateError):
269 conn.connect()
270
271 context.wrap_socket.return_value.close.assert_called_once_with()
272
273 @pytest.mark.parametrize(
274 "accept_encoding",
275 [
276 "Accept-Encoding",
277 "accept-encoding",
278 b"Accept-Encoding",
279 b"accept-encoding",
280 None,
281 ],
282 )
283 @pytest.mark.parametrize("host", ["Host", "host", b"Host", b"host", None])
284 @pytest.mark.parametrize(
285 "user_agent", ["User-Agent", "user-agent", b"User-Agent", b"user-agent", None]
286 )
287 @pytest.mark.parametrize("chunked", [True, False])
288 def test_skip_header(
289 self,
290 accept_encoding: str | None,
291 host: str | None,
292 user_agent: str | None,
293 chunked: bool,
294 ) -> None:
295 headers = {}
296 if accept_encoding is not None:
297 headers[accept_encoding] = SKIP_HEADER
298 if host is not None:
299 headers[host] = SKIP_HEADER
300 if user_agent is not None:
301 headers[user_agent] = SKIP_HEADER
302
303 with (
304 mock.patch("urllib3.util.connection.create_connection"),
305 mock.patch(
306 "urllib3.connection._HTTPConnection.putheader"
307 ) as http_client_putheader,
308 ):
309 conn = HTTPConnection("")
310 conn.request("GET", "/headers", headers=headers, chunked=chunked)
311
312 request_headers = {}
313 for call in http_client_putheader.call_args_list:
314 header, value = call.args
315 request_headers[header] = value
316
317 if accept_encoding is None:
318 assert "Accept-Encoding" in request_headers
319 else:
320 assert accept_encoding not in request_headers
321 if host is None:
322 assert "Host" in request_headers
323 else:
324 assert host not in request_headers
325 if user_agent is None:
326 assert "User-Agent" in request_headers
327 else:
328 assert user_agent not in request_headers