test_ssl_edge_cases.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638
  1. # -*- coding: utf-8 -*-
  2. import unittest
  3. import socket
  4. import ssl
  5. from unittest.mock import Mock, patch, MagicMock
  6. from websocket._ssl_compat import (
  7. SSLError,
  8. SSLEOFError,
  9. SSLWantReadError,
  10. SSLWantWriteError,
  11. HAVE_SSL,
  12. )
  13. from websocket._http import _ssl_socket, _wrap_sni_socket
  14. from websocket._exceptions import WebSocketException
  15. from websocket._socket import recv, send
  16. """
  17. test_ssl_edge_cases.py
  18. websocket - WebSocket client library for Python
  19. Copyright 2025 engn33r
  20. Licensed under the Apache License, Version 2.0 (the "License");
  21. you may not use this file except in compliance with the License.
  22. You may obtain a copy of the License at
  23. http://www.apache.org/licenses/LICENSE-2.0
  24. Unless required by applicable law or agreed to in writing, software
  25. distributed under the License is distributed on an "AS IS" BASIS,
  26. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  27. See the License for the specific language governing permissions and
  28. limitations under the License.
  29. """
  30. class SSLEdgeCasesTest(unittest.TestCase):
  31. def setUp(self):
  32. if not HAVE_SSL:
  33. self.skipTest("SSL not available")
  34. def test_ssl_handshake_failure(self):
  35. """Test SSL handshake failure scenarios"""
  36. mock_sock = Mock()
  37. # Test SSL handshake timeout
  38. with patch("ssl.SSLContext") as mock_ssl_context:
  39. mock_context = Mock()
  40. mock_ssl_context.return_value = mock_context
  41. mock_context.wrap_socket.side_effect = socket.timeout(
  42. "SSL handshake timeout"
  43. )
  44. sslopt = {"cert_reqs": ssl.CERT_REQUIRED}
  45. with self.assertRaises(socket.timeout):
  46. _ssl_socket(mock_sock, sslopt, "example.com")
  47. def test_ssl_certificate_verification_failures(self):
  48. """Test various SSL certificate verification failure scenarios"""
  49. mock_sock = Mock()
  50. # Test certificate verification failure
  51. with patch("ssl.SSLContext") as mock_ssl_context:
  52. mock_context = Mock()
  53. mock_ssl_context.return_value = mock_context
  54. mock_context.wrap_socket.side_effect = ssl.SSLCertVerificationError(
  55. "Certificate verification failed"
  56. )
  57. sslopt = {"cert_reqs": ssl.CERT_REQUIRED, "check_hostname": True}
  58. with self.assertRaises(ssl.SSLCertVerificationError):
  59. _ssl_socket(mock_sock, sslopt, "badssl.example")
  60. def test_ssl_context_configuration_edge_cases(self):
  61. """Test SSL context configuration with various edge cases"""
  62. mock_sock = Mock()
  63. # Test with pre-created SSL context
  64. with patch("ssl.SSLContext") as mock_ssl_context:
  65. existing_context = Mock()
  66. existing_context.wrap_socket.return_value = Mock()
  67. mock_ssl_context.return_value = existing_context
  68. sslopt = {"context": existing_context}
  69. # Call _ssl_socket which should use the existing context
  70. _ssl_socket(mock_sock, sslopt, "example.com")
  71. # Should use the provided context, not create a new one
  72. existing_context.wrap_socket.assert_called_once()
  73. def test_ssl_ca_bundle_environment_edge_cases(self):
  74. """Test CA bundle environment variable edge cases"""
  75. mock_sock = Mock()
  76. # Test with non-existent CA bundle file
  77. with patch.dict(
  78. "os.environ", {"WEBSOCKET_CLIENT_CA_BUNDLE": "/nonexistent/ca-bundle.crt"}
  79. ):
  80. with patch("os.path.isfile", return_value=False):
  81. with patch("os.path.isdir", return_value=False):
  82. with patch("ssl.SSLContext") as mock_ssl_context:
  83. mock_context = Mock()
  84. mock_ssl_context.return_value = mock_context
  85. mock_context.wrap_socket.return_value = Mock()
  86. sslopt = {}
  87. _ssl_socket(mock_sock, sslopt, "example.com")
  88. # Should not try to load non-existent CA bundle
  89. mock_context.load_verify_locations.assert_not_called()
  90. # Test with CA bundle directory
  91. with patch.dict("os.environ", {"WEBSOCKET_CLIENT_CA_BUNDLE": "/etc/ssl/certs"}):
  92. with patch("os.path.isfile", return_value=False):
  93. with patch("os.path.isdir", return_value=True):
  94. with patch("ssl.SSLContext") as mock_ssl_context:
  95. mock_context = Mock()
  96. mock_ssl_context.return_value = mock_context
  97. mock_context.wrap_socket.return_value = Mock()
  98. sslopt = {}
  99. _ssl_socket(mock_sock, sslopt, "example.com")
  100. # Should load CA directory
  101. mock_context.load_verify_locations.assert_called_with(
  102. cafile=None, capath="/etc/ssl/certs"
  103. )
  104. def test_ssl_cipher_configuration_edge_cases(self):
  105. """Test SSL cipher configuration edge cases"""
  106. mock_sock = Mock()
  107. # Test with invalid cipher suite
  108. with patch("ssl.SSLContext") as mock_ssl_context:
  109. mock_context = Mock()
  110. mock_ssl_context.return_value = mock_context
  111. mock_context.set_ciphers.side_effect = ssl.SSLError(
  112. "No cipher can be selected"
  113. )
  114. mock_context.wrap_socket.return_value = Mock()
  115. sslopt = {"ciphers": "INVALID_CIPHER"}
  116. with self.assertRaises(WebSocketException):
  117. _ssl_socket(mock_sock, sslopt, "example.com")
  118. def test_ssl_ecdh_curve_edge_cases(self):
  119. """Test ECDH curve configuration edge cases"""
  120. mock_sock = Mock()
  121. # Test with invalid ECDH curve
  122. with patch("ssl.SSLContext") as mock_ssl_context:
  123. mock_context = Mock()
  124. mock_ssl_context.return_value = mock_context
  125. mock_context.set_ecdh_curve.side_effect = ValueError("unknown curve name")
  126. mock_context.wrap_socket.return_value = Mock()
  127. sslopt = {"ecdh_curve": "invalid_curve"}
  128. with self.assertRaises(WebSocketException):
  129. _ssl_socket(mock_sock, sslopt, "example.com")
  130. def test_ssl_client_certificate_edge_cases(self):
  131. """Test client certificate configuration edge cases"""
  132. mock_sock = Mock()
  133. # Test with non-existent client certificate
  134. with patch("ssl.SSLContext") as mock_ssl_context:
  135. mock_context = Mock()
  136. mock_ssl_context.return_value = mock_context
  137. mock_context.load_cert_chain.side_effect = FileNotFoundError("No such file")
  138. mock_context.wrap_socket.return_value = Mock()
  139. sslopt = {"certfile": "/nonexistent/client.crt"}
  140. with self.assertRaises(WebSocketException):
  141. _ssl_socket(mock_sock, sslopt, "example.com")
  142. def test_ssl_want_read_write_retry_edge_cases(self):
  143. """Test SSL want read/write retry edge cases"""
  144. mock_sock = Mock()
  145. # Test SSLWantReadError with multiple retries before success
  146. read_attempts = [0] # Use list for mutable reference
  147. def mock_recv(bufsize):
  148. read_attempts[0] += 1
  149. if read_attempts[0] == 1:
  150. raise SSLWantReadError("The operation did not complete")
  151. elif read_attempts[0] == 2:
  152. return b"data after retries"
  153. else:
  154. return b""
  155. mock_sock.recv.side_effect = mock_recv
  156. mock_sock.gettimeout.return_value = 30.0
  157. with patch("selectors.DefaultSelector") as mock_selector_class:
  158. mock_selector = Mock()
  159. mock_selector_class.return_value = mock_selector
  160. mock_selector.select.return_value = [True] # Always ready
  161. result = recv(mock_sock, 100)
  162. self.assertEqual(result, b"data after retries")
  163. self.assertEqual(read_attempts[0], 2)
  164. # Should have used selector for retry
  165. mock_selector.register.assert_called()
  166. mock_selector.select.assert_called()
  167. def test_ssl_want_write_retry_edge_cases(self):
  168. """Test SSL want write retry edge cases"""
  169. mock_sock = Mock()
  170. # Test SSLWantWriteError with multiple retries before success
  171. write_attempts = [0] # Use list for mutable reference
  172. def mock_send(data):
  173. write_attempts[0] += 1
  174. if write_attempts[0] == 1:
  175. raise SSLWantWriteError("The operation did not complete")
  176. elif write_attempts[0] == 2:
  177. return len(data)
  178. else:
  179. return 0
  180. mock_sock.send.side_effect = mock_send
  181. mock_sock.gettimeout.return_value = 30.0
  182. with patch("selectors.DefaultSelector") as mock_selector_class:
  183. mock_selector = Mock()
  184. mock_selector_class.return_value = mock_selector
  185. mock_selector.select.return_value = [True] # Always ready
  186. result = send(mock_sock, b"test data")
  187. self.assertEqual(result, 9) # len("test data")
  188. self.assertEqual(write_attempts[0], 2)
  189. def test_ssl_eof_error_edge_cases(self):
  190. """Test SSL EOF error edge cases"""
  191. mock_sock = Mock()
  192. # Test SSLEOFError during send
  193. mock_sock.send.side_effect = SSLEOFError("SSL connection has been closed")
  194. mock_sock.gettimeout.return_value = 30.0
  195. from websocket._exceptions import WebSocketConnectionClosedException
  196. with self.assertRaises(WebSocketConnectionClosedException):
  197. send(mock_sock, b"test data")
  198. def test_ssl_pending_data_edge_cases(self):
  199. """Test SSL pending data scenarios"""
  200. from websocket._dispatcher import SSLDispatcher
  201. from websocket._app import WebSocketApp
  202. # Mock SSL socket with pending data
  203. mock_ssl_sock = Mock()
  204. mock_ssl_sock.pending.return_value = 1024 # Simulates pending SSL data
  205. # Mock WebSocketApp
  206. mock_app = Mock(spec=WebSocketApp)
  207. mock_app.sock = Mock()
  208. mock_app.sock.sock = mock_ssl_sock
  209. dispatcher = SSLDispatcher(mock_app, 5.0)
  210. # When there's pending data, should return immediately without selector
  211. result = dispatcher.select(mock_ssl_sock, Mock())
  212. # Should return the socket list when there's pending data
  213. self.assertEqual(result, [mock_ssl_sock])
  214. mock_ssl_sock.pending.assert_called_once()
  215. def test_ssl_renegotiation_edge_cases(self):
  216. """Test SSL renegotiation scenarios"""
  217. mock_sock = Mock()
  218. # Simulate SSL renegotiation during read
  219. call_count = 0
  220. def mock_recv(bufsize):
  221. nonlocal call_count
  222. call_count += 1
  223. if call_count == 1:
  224. raise SSLWantReadError("SSL renegotiation required")
  225. return b"data after renegotiation"
  226. mock_sock.recv.side_effect = mock_recv
  227. mock_sock.gettimeout.return_value = 30.0
  228. with patch("selectors.DefaultSelector") as mock_selector_class:
  229. mock_selector = Mock()
  230. mock_selector_class.return_value = mock_selector
  231. mock_selector.select.return_value = [True]
  232. result = recv(mock_sock, 100)
  233. self.assertEqual(result, b"data after renegotiation")
  234. self.assertEqual(call_count, 2)
  235. def test_ssl_server_hostname_override(self):
  236. """Test SSL server hostname override scenarios"""
  237. mock_sock = Mock()
  238. with patch("ssl.SSLContext") as mock_ssl_context:
  239. mock_context = Mock()
  240. mock_ssl_context.return_value = mock_context
  241. mock_context.wrap_socket.return_value = Mock()
  242. # Test server_hostname override
  243. sslopt = {"server_hostname": "override.example.com"}
  244. _ssl_socket(mock_sock, sslopt, "original.example.com")
  245. # Should use override hostname in wrap_socket call
  246. mock_context.wrap_socket.assert_called_with(
  247. mock_sock,
  248. do_handshake_on_connect=True,
  249. suppress_ragged_eofs=True,
  250. server_hostname="override.example.com",
  251. )
  252. def test_ssl_protocol_version_edge_cases(self):
  253. """Test SSL protocol version edge cases"""
  254. mock_sock = Mock()
  255. # Test with deprecated SSL version
  256. with patch("ssl.SSLContext") as mock_ssl_context:
  257. mock_context = Mock()
  258. mock_ssl_context.return_value = mock_context
  259. mock_context.wrap_socket.return_value = Mock()
  260. # Test that deprecated ssl_version is still handled
  261. if hasattr(ssl, "PROTOCOL_TLS"):
  262. sslopt = {"ssl_version": ssl.PROTOCOL_TLS}
  263. _ssl_socket(mock_sock, sslopt, "example.com")
  264. mock_ssl_context.assert_called_with(ssl.PROTOCOL_TLS)
  265. def test_ssl_keylog_file_edge_cases(self):
  266. """Test SSL keylog file configuration edge cases"""
  267. mock_sock = Mock()
  268. # Test with SSLKEYLOGFILE environment variable
  269. with patch.dict("os.environ", {"SSLKEYLOGFILE": "/tmp/ssl_keys.log"}):
  270. with patch("ssl.SSLContext") as mock_ssl_context:
  271. mock_context = Mock()
  272. mock_ssl_context.return_value = mock_context
  273. mock_context.wrap_socket.return_value = Mock()
  274. sslopt = {}
  275. _ssl_socket(mock_sock, sslopt, "example.com")
  276. # Should set keylog_filename
  277. self.assertEqual(mock_context.keylog_filename, "/tmp/ssl_keys.log")
  278. def test_ssl_context_verification_modes(self):
  279. """Test different SSL verification mode combinations"""
  280. mock_sock = Mock()
  281. test_cases = [
  282. # (cert_reqs, check_hostname, expected_verify_mode, expected_check_hostname)
  283. (ssl.CERT_NONE, False, ssl.CERT_NONE, False),
  284. (ssl.CERT_REQUIRED, False, ssl.CERT_REQUIRED, False),
  285. (ssl.CERT_REQUIRED, True, ssl.CERT_REQUIRED, True),
  286. ]
  287. for cert_reqs, check_hostname, expected_verify, expected_check in test_cases:
  288. with self.subTest(cert_reqs=cert_reqs, check_hostname=check_hostname):
  289. with patch("ssl.SSLContext") as mock_ssl_context:
  290. mock_context = Mock()
  291. mock_ssl_context.return_value = mock_context
  292. mock_context.wrap_socket.return_value = Mock()
  293. sslopt = {"cert_reqs": cert_reqs, "check_hostname": check_hostname}
  294. _ssl_socket(mock_sock, sslopt, "example.com")
  295. self.assertEqual(mock_context.verify_mode, expected_verify)
  296. self.assertEqual(mock_context.check_hostname, expected_check)
  297. def test_ssl_socket_shutdown_edge_cases(self):
  298. """Test SSL socket shutdown edge cases"""
  299. from websocket._core import WebSocket
  300. mock_ssl_sock = Mock()
  301. mock_ssl_sock.shutdown.side_effect = SSLError("SSL shutdown failed")
  302. ws = WebSocket()
  303. ws.sock = mock_ssl_sock
  304. ws.connected = True
  305. # Should handle SSL shutdown errors gracefully
  306. try:
  307. ws.close()
  308. except SSLError:
  309. self.fail("SSL shutdown error should be handled gracefully")
  310. def test_ssl_socket_close_during_operation(self):
  311. """Test SSL socket being closed during ongoing operations"""
  312. mock_sock = Mock()
  313. # Simulate SSL socket being closed during recv
  314. mock_sock.recv.side_effect = SSLError(
  315. "SSL connection has been closed unexpectedly"
  316. )
  317. mock_sock.gettimeout.return_value = 30.0
  318. from websocket._exceptions import WebSocketConnectionClosedException
  319. # Should handle unexpected SSL closure
  320. with self.assertRaises((SSLError, WebSocketConnectionClosedException)):
  321. recv(mock_sock, 100)
  322. def test_ssl_compression_edge_cases(self):
  323. """Test SSL compression configuration edge cases"""
  324. mock_sock = Mock()
  325. with patch("ssl.SSLContext") as mock_ssl_context:
  326. mock_context = Mock()
  327. mock_ssl_context.return_value = mock_context
  328. mock_context.wrap_socket.return_value = Mock()
  329. # Test SSL compression options (if available)
  330. sslopt = {"compression": False} # Some SSL contexts support this
  331. try:
  332. _ssl_socket(mock_sock, sslopt, "example.com")
  333. # Should not fail even if compression option is not supported
  334. except AttributeError:
  335. # Expected if SSL context doesn't support compression option
  336. pass
  337. def test_ssl_session_reuse_edge_cases(self):
  338. """Test SSL session reuse scenarios"""
  339. mock_sock = Mock()
  340. with patch("ssl.SSLContext") as mock_ssl_context:
  341. mock_context = Mock()
  342. mock_ssl_context.return_value = mock_context
  343. mock_ssl_sock = Mock()
  344. mock_context.wrap_socket.return_value = mock_ssl_sock
  345. # Test session reuse
  346. mock_ssl_sock.session = "mock_session"
  347. mock_ssl_sock.session_reused = True
  348. result = _ssl_socket(mock_sock, {}, "example.com")
  349. # Should handle session reuse without issues
  350. self.assertIsNotNone(result)
  351. def test_ssl_alpn_protocol_edge_cases(self):
  352. """Test SSL ALPN (Application Layer Protocol Negotiation) edge cases"""
  353. mock_sock = Mock()
  354. with patch("ssl.SSLContext") as mock_ssl_context:
  355. mock_context = Mock()
  356. mock_ssl_context.return_value = mock_context
  357. mock_context.wrap_socket.return_value = Mock()
  358. # Test ALPN configuration
  359. sslopt = {"alpn_protocols": ["http/1.1", "h2"]}
  360. # ALPN protocols are not currently supported in the SSL wrapper
  361. # but the test should not fail
  362. result = _ssl_socket(mock_sock, sslopt, "example.com")
  363. self.assertIsNotNone(result)
  364. # ALPN would need to be implemented in _wrap_sni_socket function
  365. def test_ssl_sni_edge_cases(self):
  366. """Test SSL SNI (Server Name Indication) edge cases"""
  367. mock_sock = Mock()
  368. # Test with IPv6 address (should not use SNI)
  369. with patch("ssl.SSLContext") as mock_ssl_context:
  370. mock_context = Mock()
  371. mock_ssl_context.return_value = mock_context
  372. mock_context.wrap_socket.return_value = Mock()
  373. # IPv6 addresses should not be used for SNI
  374. ipv6_hostname = "2001:db8::1"
  375. _ssl_socket(mock_sock, {}, ipv6_hostname)
  376. # Should use IPv6 address as server_hostname
  377. mock_context.wrap_socket.assert_called_with(
  378. mock_sock,
  379. do_handshake_on_connect=True,
  380. suppress_ragged_eofs=True,
  381. server_hostname=ipv6_hostname,
  382. )
  383. def test_ssl_buffer_size_edge_cases(self):
  384. """Test SSL buffer size related edge cases"""
  385. mock_sock = Mock()
  386. def mock_recv(bufsize):
  387. # SSL should never try to read more than 16KB at once
  388. if bufsize > 16384:
  389. raise SSLError("[SSL: BAD_LENGTH] buffer too large")
  390. return b"A" * min(bufsize, 1024) # Return smaller chunks
  391. mock_sock.recv.side_effect = mock_recv
  392. mock_sock.gettimeout.return_value = 30.0
  393. from websocket._abnf import frame_buffer
  394. # Frame buffer should handle large requests by chunking
  395. fb = frame_buffer(lambda size: recv(mock_sock, size), skip_utf8_validation=True)
  396. # This should work even with large size due to chunking
  397. result = fb.recv_strict(16384) # Exactly 16KB
  398. self.assertGreater(len(result), 0)
  399. def test_ssl_protocol_downgrade_protection(self):
  400. """Test SSL protocol downgrade protection"""
  401. mock_sock = Mock()
  402. with patch("ssl.SSLContext") as mock_ssl_context:
  403. mock_context = Mock()
  404. mock_ssl_context.return_value = mock_context
  405. mock_context.wrap_socket.side_effect = ssl.SSLError(
  406. "SSLV3_ALERT_HANDSHAKE_FAILURE"
  407. )
  408. sslopt = {"ssl_version": ssl.PROTOCOL_TLS_CLIENT}
  409. # Should propagate SSL protocol errors
  410. with self.assertRaises(ssl.SSLError):
  411. _ssl_socket(mock_sock, sslopt, "example.com")
  412. def test_ssl_certificate_chain_validation(self):
  413. """Test SSL certificate chain validation edge cases"""
  414. mock_sock = Mock()
  415. with patch("ssl.SSLContext") as mock_ssl_context:
  416. mock_context = Mock()
  417. mock_ssl_context.return_value = mock_context
  418. # Test certificate chain validation failure
  419. mock_context.wrap_socket.side_effect = ssl.SSLCertVerificationError(
  420. "certificate verify failed: certificate has expired"
  421. )
  422. sslopt = {"cert_reqs": ssl.CERT_REQUIRED, "check_hostname": True}
  423. with self.assertRaises(ssl.SSLCertVerificationError):
  424. _ssl_socket(mock_sock, sslopt, "expired.badssl.com")
  425. def test_ssl_weak_cipher_rejection(self):
  426. """Test SSL weak cipher rejection scenarios"""
  427. mock_sock = Mock()
  428. with patch("ssl.SSLContext") as mock_ssl_context:
  429. mock_context = Mock()
  430. mock_ssl_context.return_value = mock_context
  431. mock_context.wrap_socket.side_effect = ssl.SSLError("no shared cipher")
  432. sslopt = {"ciphers": "RC4-MD5"} # Intentionally weak cipher
  433. # Should fail with weak ciphers (SSL error is not wrapped by our code)
  434. with self.assertRaises(ssl.SSLError):
  435. _ssl_socket(mock_sock, sslopt, "example.com")
  436. def test_ssl_hostname_verification_edge_cases(self):
  437. """Test SSL hostname verification edge cases"""
  438. mock_sock = Mock()
  439. # Test with wildcard certificate scenarios
  440. test_cases = [
  441. ("*.example.com", "subdomain.example.com"), # Valid wildcard
  442. ("*.example.com", "sub.subdomain.example.com"), # Invalid wildcard depth
  443. ("example.com", "www.example.com"), # Hostname mismatch
  444. ]
  445. for cert_hostname, connect_hostname in test_cases:
  446. with self.subTest(cert=cert_hostname, hostname=connect_hostname):
  447. with patch("ssl.SSLContext") as mock_ssl_context:
  448. mock_context = Mock()
  449. mock_ssl_context.return_value = mock_context
  450. if (
  451. cert_hostname != connect_hostname
  452. and "sub.subdomain" in connect_hostname
  453. ):
  454. # Simulate hostname verification failure for invalid wildcard
  455. mock_context.wrap_socket.side_effect = ssl.SSLCertVerificationError(
  456. f"hostname '{connect_hostname}' doesn't match '{cert_hostname}'"
  457. )
  458. sslopt = {
  459. "cert_reqs": ssl.CERT_REQUIRED,
  460. "check_hostname": True,
  461. }
  462. with self.assertRaises(ssl.SSLCertVerificationError):
  463. _ssl_socket(mock_sock, sslopt, connect_hostname)
  464. else:
  465. mock_context.wrap_socket.return_value = Mock()
  466. sslopt = {
  467. "cert_reqs": ssl.CERT_REQUIRED,
  468. "check_hostname": True,
  469. }
  470. # Should succeed for valid cases
  471. result = _ssl_socket(mock_sock, sslopt, connect_hostname)
  472. self.assertIsNotNone(result)
  473. def test_ssl_memory_bio_edge_cases(self):
  474. """Test SSL memory BIO edge cases"""
  475. mock_sock = Mock()
  476. # Test SSL memory BIO scenarios (if available)
  477. try:
  478. import ssl
  479. if hasattr(ssl, "MemoryBIO"):
  480. with patch("ssl.SSLContext") as mock_ssl_context:
  481. mock_context = Mock()
  482. mock_ssl_context.return_value = mock_context
  483. mock_context.wrap_socket.return_value = Mock()
  484. # Memory BIO should work if available
  485. _ssl_socket(mock_sock, {}, "example.com")
  486. # Standard socket wrapping should still work
  487. mock_context.wrap_socket.assert_called_once()
  488. except (ImportError, AttributeError):
  489. self.skipTest("SSL MemoryBIO not available")
  490. if __name__ == "__main__":
  491. unittest.main()