Debian Codegraph @

test/contrib/test_pyopenssl.py

raw
1 from __future__ import annotations
2
3 import os
4 from unittest import mock
5
6 import pytest
7
8 try:
9 from cryptography import x509
10 from OpenSSL.crypto import ( # type: ignore[import-not-found]
11 FILETYPE_PEM,
12 load_certificate,
13 )
14
15 from urllib3.contrib.pyopenssl import _dnsname_to_stdlib, get_subj_alt_name
16 except ImportError:
17 pass
18
19
20 def setup_module() -> None:
21 try:
22 from urllib3.contrib.pyopenssl import inject_into_urllib3
23
24 inject_into_urllib3()
25 except ImportError as e:
26 pytest.skip(f"Could not import PyOpenSSL: {e!r}")
27
28
29 def teardown_module() -> None:
30 try:
31 from urllib3.contrib.pyopenssl import extract_from_urllib3
32
33 extract_from_urllib3()
34 except ImportError:
35 pass
36
37
38 from ..test_ssl import TestSSL # noqa: E402, F401
39 from ..test_util import TestUtilSSL # noqa: E402, F401
40 from ..with_dummyserver.test_https import ( # noqa: E402, F401
41 TestHTTPS_IPV4SAN,
42 TestHTTPS_IPV6SAN,
43 TestHTTPS_TLSv1,
44 TestHTTPS_TLSv1_1,
45 TestHTTPS_TLSv1_2,
46 TestHTTPS_TLSv1_3,
47 )
48 from ..with_dummyserver.test_socketlevel import ( # noqa: E402, F401
49 TestClientCerts,
50 TestSNI,
51 TestSocketClosing,
52 )
53 from ..with_dummyserver.test_socketlevel import ( # noqa: E402, F401
54 TestSSL as TestSocketSSL,
55 )
56
57
58 class TestPyOpenSSLHelpers:
59 """
60 Tests for PyOpenSSL helper functions.
61 """
62
63 def test_dnsname_to_stdlib_simple(self) -> None:
64 """
65 We can convert a dnsname to a native string when the domain is simple.
66 """
67 name = "उदाहरण.परीक"
68 expected_result = "xn--p1b6ci4b4b3a.xn--11b5bs8d"
69
70 assert _dnsname_to_stdlib(name) == expected_result
71
72 def test_dnsname_to_stdlib_leading_period(self) -> None:
73 """
74 If there is a . in front of the domain name we correctly encode it.
75 """
76 name = ".उदाहरण.परीक"
77 expected_result = ".xn--p1b6ci4b4b3a.xn--11b5bs8d"
78
79 assert _dnsname_to_stdlib(name) == expected_result
80
81 def test_dnsname_to_stdlib_leading_splat(self) -> None:
82 """
83 If there's a wildcard character in the front of the string we handle it
84 appropriately.
85 """
86 name = "*.उदाहरण.परीक"
87 expected_result = "*.xn--p1b6ci4b4b3a.xn--11b5bs8d"
88
89 assert _dnsname_to_stdlib(name) == expected_result
90
91 @mock.patch("urllib3.contrib.pyopenssl.log.warning")
92 def test_get_subj_alt_name(self, mock_warning: mock.MagicMock) -> None:
93 """
94 If a certificate has two subject alternative names, cryptography raises
95 an x509.DuplicateExtension exception.
96 """
97 path = os.path.join(os.path.dirname(__file__), "duplicate_san.pem")
98 with open(path) as fp:
99 cert = load_certificate(FILETYPE_PEM, fp.read())
100
101 assert get_subj_alt_name(cert) == []
102
103 assert mock_warning.call_count == 1
104 assert isinstance(mock_warning.call_args[0][1], x509.DuplicateExtension)