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