Debian Codegraph @

tests/asyncio/test_client.py

raw
1 import asyncio
2 import contextlib
3 import http
4 import logging
5 import os
6 import pathlib
7 import socket
8 import ssl
9 import sys
10 import unittest
11 from unittest.mock import patch
12
13 from websockets.asyncio.client import *
14 from websockets.asyncio.server import serve, unix_serve
15 from websockets.client import backoff
16 from websockets.exceptions import (
17 InvalidHandshake,
18 InvalidMessage,
19 InvalidProxy,
20 InvalidProxyMessage,
21 InvalidStatus,
22 InvalidURI,
23 ProxyError,
24 SecurityError,
25 )
26 from websockets.extensions.permessage_deflate import PerMessageDeflate
27
28 from ..proxy import ProxyMixin
29 from ..utils import CLIENT_CONTEXT, MS, SERVER_CONTEXT, temp_unix_socket_path
30 from .server import args, get_host_port, get_uri, handler
31
32
33 def short_backoff():
34 defaults = backoff.__defaults__
35 yield from backoff(
36 defaults[0] * MS,
37 defaults[1] * MS,
38 defaults[2] * MS,
39 defaults[3],
40 )
41
42
43 @contextlib.asynccontextmanager
44 async def few_redirects():
45 from websockets.asyncio import client
46
47 max_redirects = client.MAX_REDIRECTS
48 client.MAX_REDIRECTS = 2
49 try:
50 yield
51 finally:
52 client.MAX_REDIRECTS = max_redirects
53
54
55 class ClientTests(unittest.IsolatedAsyncioTestCase):
56 async def test_context_manager(self):
57 """Client connects to server and disconnects automatically."""
58 async with serve(*args) as server:
59 async with connect(get_uri(server)) as client:
60 self.assertEqual(client.protocol.state.name, "OPEN")
61 self.assertEqual(client.protocol.state.name, "CLOSED")
62
63 async def test_direct_connection(self):
64 """Client connects to server directly."""
65 async with serve(*args) as server:
66 client = await connect(get_uri(server))
67 self.addAsyncCleanup(client.close)
68 self.assertEqual(client.protocol.state.name, "OPEN")
69
70 async def test_explicit_host_port(self):
71 """Client connects using an explicit host / port."""
72 async with serve(*args) as server:
73 host, port = get_host_port(server)
74 async with connect("ws://overridden/", host=host, port=port) as client:
75 self.assertEqual(client.protocol.state.name, "OPEN")
76
77 async def test_existing_socket(self):
78 """Client connects using a pre-existing socket."""
79 async with serve(*args) as server:
80 with socket.create_connection(get_host_port(server)) as sock:
81 # Use a non-existing domain to ensure we connect via sock.
82 async with connect("ws://invalid/", sock=sock) as client:
83 self.assertEqual(client.protocol.state.name, "OPEN")
84
85 async def test_compression_is_enabled(self):
86 """Client enables compression by default."""
87 async with serve(*args) as server:
88 async with connect(get_uri(server)) as client:
89 self.assertEqual(
90 [type(ext) for ext in client.protocol.extensions],
91 [PerMessageDeflate],
92 )
93
94 async def test_disable_compression(self):
95 """Client disables compression."""
96 async with serve(*args) as server:
97 async with connect(get_uri(server), compression=None) as client:
98 self.assertEqual(client.protocol.extensions, [])
99
100 async def test_additional_headers(self):
101 """Client can set additional headers with additional_headers."""
102 async with serve(*args) as server:
103 async with connect(
104 get_uri(server), additional_headers={"Authorization": "Bearer ..."}
105 ) as client:
106 self.assertEqual(client.request.headers["Authorization"], "Bearer ...")
107
108 async def test_override_user_agent_header(self):
109 """Client can override User-Agent header with user_agent_header."""
110 async with serve(*args) as server:
111 async with connect(get_uri(server), user_agent_header="Smith") as client:
112 self.assertEqual(client.request.headers["User-Agent"], "Smith")
113
114 async def test_remove_user_agent_header(self):
115 """Client can remove User-Agent header with user_agent_header."""
116 async with serve(*args) as server:
117 async with connect(get_uri(server), user_agent_header=None) as client:
118 self.assertNotIn("User-Agent", client.request.headers)
119
120 async def test_legacy_user_agent_header(self):
121 """Client can override User-Agent header with additional_headers."""
122 async with serve(*args) as server:
123 async with connect(
124 get_uri(server), additional_headers={"User-Agent": "Smith"}
125 ) as client:
126 self.assertEqual(client.request.headers["User-Agent"], "Smith")
127
128 async def test_keepalive_is_enabled(self):
129 """Client enables keepalive and measures latency by default."""
130 async with serve(*args) as server:
131 async with connect(get_uri(server), ping_interval=MS) as client:
132 self.assertEqual(client.latency, 0)
133 await asyncio.sleep(2 * MS)
134 self.assertGreater(client.latency, 0)
135
136 async def test_disable_keepalive(self):
137 """Client disables keepalive."""
138 async with serve(*args) as server:
139 async with connect(get_uri(server), ping_interval=None) as client:
140 await asyncio.sleep(2 * MS)
141 self.assertEqual(client.latency, 0)
142
143 async def test_logger(self):
144 """Client accepts a logger argument."""
145 logger = logging.getLogger("test")
146 async with serve(*args) as server:
147 async with connect(get_uri(server), logger=logger) as client:
148 self.assertEqual(client.logger.name, logger.name)
149
150 async def test_custom_connection_factory(self):
151 """Client runs ClientConnection factory provided in create_connection."""
152
153 def create_connection(*args, **kwargs):
154 client = ClientConnection(*args, **kwargs)
155 client.create_connection_ran = True
156 return client
157
158 async with serve(*args) as server:
159 async with connect(
160 get_uri(server),
161 create_connection=create_connection,
162 ) as client:
163 self.assertTrue(client.create_connection_ran)
164
165 async def test_reconnect(self):
166 """Client reconnects to server."""
167 iterations = 0
168 successful = 0
169
170 async def process_request(connection, request):
171 nonlocal iterations
172 iterations += 1
173 # Retriable errors
174 if iterations == 1:
175 await asyncio.sleep(3 * MS)
176 elif iterations == 2:
177 connection.transport.close()
178 elif iterations == 3:
179 return connection.respond(http.HTTPStatus.SERVICE_UNAVAILABLE, "🚒")
180 # Fatal error
181 elif iterations == 6:
182 return connection.respond(http.HTTPStatus.PAYMENT_REQUIRED, "💸")
183
184 async with serve(*args, process_request=process_request) as server:
185 with self.assertRaises(InvalidStatus) as raised:
186 async for client in connect(
187 get_uri(server),
188 open_timeout=3 * MS,
189 reconnect_delays=short_backoff,
190 ):
191 self.assertEqual(client.protocol.state.name, "OPEN")
192 successful += 1
193
194 self.assertEqual(
195 str(raised.exception),
196 "server rejected WebSocket connection: HTTP 402",
197 )
198 self.assertEqual(iterations, 6)
199 self.assertEqual(successful, 2)
200
201 async def test_reconnect_with_custom_process_exception(self):
202 """Client runs process_exception to tell if errors are retryable or fatal."""
203 iteration = 0
204
205 def process_request(connection, request):
206 nonlocal iteration
207 iteration += 1
208 if iteration == 1:
209 return connection.respond(http.HTTPStatus.SERVICE_UNAVAILABLE, "🚒")
210 return connection.respond(http.HTTPStatus.IM_A_TEAPOT, "🫖")
211
212 def process_exception(exc):
213 if isinstance(exc, InvalidStatus):
214 if 500 <= exc.response.status_code < 600:
215 return None
216 if exc.response.status_code == 418:
217 return Exception("🫖 💔 ☕️")
218 self.fail("unexpected exception")
219
220 async with serve(*args, process_request=process_request) as server:
221 with self.assertRaises(Exception) as raised:
222 async for _ in connect(
223 get_uri(server),
224 process_exception=process_exception,
225 reconnect_delays=short_backoff,
226 ):
227 self.fail("did not raise")
228
229 self.assertEqual(iteration, 2)
230 self.assertEqual(
231 str(raised.exception),
232 "🫖 💔 ☕️",
233 )
234
235 async def test_reconnect_with_custom_process_exception_raising_exception(self):
236 """Client supports raising an exception in process_exception."""
237
238 def process_request(connection, request):
239 return connection.respond(http.HTTPStatus.IM_A_TEAPOT, "🫖")
240
241 def process_exception(exc):
242 if isinstance(exc, InvalidStatus) and exc.response.status_code == 418:
243 raise Exception("🫖 💔 ☕️")
244 self.fail("unexpected exception")
245
246 async with serve(*args, process_request=process_request) as server:
247 with self.assertRaises(Exception) as raised:
248 async for _ in connect(
249 get_uri(server),
250 process_exception=process_exception,
251 reconnect_delays=short_backoff,
252 ):
253 self.fail("did not raise")
254
255 self.assertEqual(
256 str(raised.exception),
257 "🫖 💔 ☕️",
258 )
259
260 async def test_redirect(self):
261 """Client follows redirect."""
262
263 def redirect(connection, request):
264 if request.path == "/redirect":
265 response = connection.respond(http.HTTPStatus.FOUND, "")
266 response.headers["Location"] = "/"
267 return response
268
269 async with serve(*args, process_request=redirect) as server:
270 async with connect(get_uri(server) + "/redirect") as client:
271 self.assertEqual(client.protocol.uri.path, "/")
272
273 async def test_cross_origin_redirect(self):
274 """Client follows redirect to a secure URI on a different origin."""
275
276 def redirect(connection, request):
277 response = connection.respond(http.HTTPStatus.FOUND, "")
278 response.headers["Location"] = get_uri(other_server)
279 return response
280
281 async with serve(*args, process_request=redirect) as server:
282 async with serve(*args) as other_server:
283 async with connect(get_uri(server)):
284 self.assertFalse(server.connections)
285 self.assertTrue(other_server.connections)
286
287 @few_redirects()
288 async def test_redirect_limit(self):
289 """Client stops following redirects after limit is reached."""
290
291 def redirect(connection, request):
292 response = connection.respond(http.HTTPStatus.FOUND, "")
293 response.headers["Location"] = request.path
294 return response
295
296 async with serve(*args, process_request=redirect) as server:
297 with self.assertRaises(SecurityError) as raised:
298 async with connect(get_uri(server)):
299 self.fail("did not raise")
300
301 self.assertEqual(
302 str(raised.exception),
303 "more than 2 redirects",
304 )
305
306 async def test_redirect_with_explicit_host_port(self):
307 """Client follows redirect with an explicit host / port."""
308
309 def redirect(connection, request):
310 if request.path == "/redirect":
311 response = connection.respond(http.HTTPStatus.FOUND, "")
312 response.headers["Location"] = "/"
313 return response
314
315 async with serve(*args, process_request=redirect) as server:
316 host, port = get_host_port(server)
317 async with connect(
318 "ws://overridden/redirect", host=host, port=port
319 ) as client:
320 self.assertEqual(client.protocol.uri.path, "/")
321
322 async def test_cross_origin_redirect_with_explicit_host_port(self):
323 """Client doesn't follow cross-origin redirect with an explicit host / port."""
324
325 def redirect(connection, request):
326 response = connection.respond(http.HTTPStatus.FOUND, "")
327 response.headers["Location"] = "ws://other/"
328 return response
329
330 async with serve(*args, process_request=redirect) as server:
331 host, port = get_host_port(server)
332 with self.assertRaises(ValueError) as raised:
333 async with connect("ws://overridden/", host=host, port=port):
334 self.fail("did not raise")
335
336 self.assertEqual(
337 str(raised.exception),
338 "cannot follow cross-origin redirect to ws://other/ "
339 "with an explicit host or port",
340 )
341
342 async def test_redirect_with_existing_socket(self):
343 """Client doesn't follow redirect when using a pre-existing socket."""
344
345 def redirect(connection, request):
346 response = connection.respond(http.HTTPStatus.FOUND, "")
347 response.headers["Location"] = "/"
348 return response
349
350 async with serve(*args, process_request=redirect) as server:
351 with socket.create_connection(get_host_port(server)) as sock:
352 with self.assertRaises(ValueError) as raised:
353 # Use a non-existing domain to ensure we connect via sock.
354 async with connect("ws://invalid/redirect", sock=sock):
355 self.fail("did not raise")
356
357 self.assertEqual(
358 str(raised.exception),
359 "cannot follow redirect to ws://invalid/ with a preexisting socket",
360 )
361
362 async def test_cross_origin_redirect_strips_credentials(self):
363 """Client strips credentials when following a cross-origin redirect."""
364
365 def redirect(connection, request):
366 response = connection.respond(http.HTTPStatus.FOUND, "")
367 response.headers["Location"] = get_uri(other_server)
368 return response
369
370 async with serve(*args, process_request=redirect) as server:
371 async with serve(*args) as other_server:
372 async with connect(
373 get_uri(server),
374 additional_headers={
375 "Authorization": "Bearer secret",
376 "Cookie": "session=secret",
377 "Proxy-Authorization": "Basic secret",
378 "X-Custom": "keep",
379 },
380 ) as client:
381 self.assertNotIn("Authorization", client.request.headers)
382 self.assertNotIn("Cookie", client.request.headers)
383 self.assertNotIn("Proxy-Authorization", client.request.headers)
384 self.assertIn("X-Custom", client.request.headers)
385
386 async def test_same_origin_redirect_preserves_credentials(self):
387 """Client preserves credentials when following a same-origin redirect."""
388
389 def redirect(connection, request):
390 if request.path == "/redirect":
391 response = connection.respond(http.HTTPStatus.FOUND, "")
392 response.headers["Location"] = "/"
393 return response
394
395 async with serve(*args, process_request=redirect) as server:
396 async with connect(
397 get_uri(server) + "/redirect",
398 additional_headers={
399 "Authorization": "Bearer secret",
400 "Cookie": "session=secret",
401 "Proxy-Authorization": "Basic secret",
402 "X-Custom": "keep",
403 },
404 ) as client:
405 self.assertIn("Authorization", client.request.headers)
406 self.assertIn("Cookie", client.request.headers)
407 self.assertIn("Proxy-Authorization", client.request.headers)
408
409 async def test_invalid_uri(self):
410 """Client receives an invalid URI."""
411 with self.assertRaises(InvalidURI):
412 async with connect("http://localhost"): # invalid scheme
413 self.fail("did not raise")
414
415 async def test_tcp_connection_fails(self):
416 """Client fails to connect to server."""
417 with self.assertRaises(OSError):
418 async with connect("ws://localhost:12345"): # invalid port
419 self.fail("did not raise")
420
421 async def test_handshake_fails(self):
422 """Client connects to server but the handshake fails."""
423
424 def remove_accept_header(self, request, response):
425 del response.headers["Sec-WebSocket-Accept"]
426
427 # The connection will be open for the server but failed for the client.
428 # Use a connection handler that exits immediately to avoid an exception.
429 async with serve(*args, process_response=remove_accept_header) as server:
430 with self.assertRaises(InvalidHandshake) as raised:
431 async with connect(get_uri(server) + "/no-op", close_timeout=MS):
432 self.fail("did not raise")
433 self.assertEqual(
434 str(raised.exception),
435 "missing Sec-WebSocket-Accept header",
436 )
437
438 async def test_timeout_during_handshake(self):
439 """Client times out before receiving handshake response from server."""
440 # Replace the WebSocket server with a TCP server that doesn't respond.
441 with socket.create_server(("localhost", 0)) as sock:
442 host, port = sock.getsockname()
443 with self.assertRaises(TimeoutError) as raised:
444 async with connect(f"ws://{host}:{port}", open_timeout=MS):
445 self.fail("did not raise")
446 self.assertEqual(
447 str(raised.exception),
448 "timed out during opening handshake",
449 )
450
451 async def test_connection_closed_during_handshake(self):
452 """Client reads EOF before receiving handshake response from server."""
453
454 def close_connection(self, request):
455 self.transport.close()
456
457 async with serve(*args, process_request=close_connection) as server:
458 with self.assertRaises(InvalidMessage) as raised:
459 async with connect(get_uri(server)):
460 self.fail("did not raise")
461 self.assertEqual(
462 str(raised.exception),
463 "did not receive a valid HTTP response",
464 )
465 self.assertIsInstance(raised.exception.__cause__, EOFError)
466 self.assertEqual(
467 str(raised.exception.__cause__),
468 "connection closed while reading HTTP status line",
469 )
470
471 async def test_http_response(self):
472 """Client reads HTTP response."""
473
474 def http_response(connection, request):
475 return connection.respond(http.HTTPStatus.OK, "👌")
476
477 async with serve(*args, process_request=http_response) as server:
478 with self.assertRaises(InvalidStatus) as raised:
479 async with connect(get_uri(server)):
480 self.fail("did not raise")
481
482 self.assertEqual(raised.exception.response.status_code, 200)
483 self.assertEqual(raised.exception.response.body.decode(), "👌")
484
485 async def test_http_response_without_content_length(self):
486 """Client reads HTTP response without a Content-Length header."""
487
488 def http_response(connection, request):
489 response = connection.respond(http.HTTPStatus.OK, "👌")
490 del response.headers["Content-Length"]
491 return response
492
493 async with serve(*args, process_request=http_response) as server:
494 with self.assertRaises(InvalidStatus) as raised:
495 async with connect(get_uri(server)):
496 self.fail("did not raise")
497
498 self.assertEqual(raised.exception.response.status_code, 200)
499 self.assertEqual(raised.exception.response.body.decode(), "👌")
500
501 async def test_junk_handshake_response(self):
502 """Client closes the connection when receiving non-HTTP response from server."""
503
504 async def junk(reader, writer):
505 # Wait for the client to send the handshake request.
506 await asyncio.sleep(MS)
507 writer.write(b"220 smtp.invalid ESMTP Postfix\r\n")
508 # Wait for the client to close the connection.
509 await reader.read(4096)
510 writer.close()
511
512 server = await asyncio.start_server(junk, "localhost", 0)
513 host, port = get_host_port(server)
514 async with server:
515 with self.assertRaises(InvalidMessage) as raised:
516 async with connect(f"ws://{host}:{port}"):
517 self.fail("did not raise")
518 self.assertEqual(
519 str(raised.exception),
520 "did not receive a valid HTTP response",
521 )
522 self.assertIsInstance(raised.exception.__cause__, ValueError)
523 self.assertEqual(
524 str(raised.exception.__cause__),
525 "unsupported protocol; expected HTTP/1.1: "
526 "220 smtp.invalid ESMTP Postfix",
527 )
528
529
530 class SecureClientTests(unittest.IsolatedAsyncioTestCase):
531 async def test_context_manager(self):
532 """Client connects to server securely and disconnects automatically."""
533 async with serve(*args, ssl=SERVER_CONTEXT) as server:
534 async with connect(get_uri(server), ssl=CLIENT_CONTEXT) as client:
535 self.assertEqual(client.protocol.state.name, "OPEN")
536 ssl_object = client.transport.get_extra_info("ssl_object")
537 self.assertEqual(ssl_object.version()[:3], "TLS")
538 self.assertEqual(client.protocol.state.name, "CLOSED")
539
540 async def test_direct_connection(self):
541 """Client connects to server securely and directly."""
542 async with serve(*args, ssl=SERVER_CONTEXT) as server:
543 client = await connect(get_uri(server), ssl=CLIENT_CONTEXT)
544 self.addAsyncCleanup(client.close)
545 self.assertEqual(client.protocol.state.name, "OPEN")
546 ssl_object = client.transport.get_extra_info("ssl_object")
547 self.assertEqual(ssl_object.version()[:3], "TLS")
548
549 async def test_set_server_hostname_implicitly(self):
550 """Client sets server_hostname to the host in the WebSocket URI."""
551 async with serve(*args, ssl=SERVER_CONTEXT) as server:
552 host, port = get_host_port(server)
553 async with connect(
554 "wss://overridden/", host=host, port=port, ssl=CLIENT_CONTEXT
555 ) as client:
556 ssl_object = client.transport.get_extra_info("ssl_object")
557 self.assertEqual(ssl_object.server_hostname, "overridden")
558
559 async def test_set_server_hostname_explicitly(self):
560 """Client sets server_hostname to the value provided in argument."""
561 async with serve(*args, ssl=SERVER_CONTEXT) as server:
562 async with connect(
563 get_uri(server), ssl=CLIENT_CONTEXT, server_hostname="overridden"
564 ) as client:
565 ssl_object = client.transport.get_extra_info("ssl_object")
566 self.assertEqual(ssl_object.server_hostname, "overridden")
567
568 async def test_reject_invalid_server_certificate(self):
569 """Client rejects certificate where server certificate isn't trusted."""
570 async with serve(*args, ssl=SERVER_CONTEXT) as server:
571 with self.assertRaises(ssl.SSLCertVerificationError) as raised:
572 # The test certificate is self-signed.
573 async with connect(get_uri(server)):
574 self.fail("did not raise")
575 self.assertIn(
576 "self signed certificate",
577 str(raised.exception).replace("-", " "),
578 )
579
580 async def test_reject_invalid_server_hostname(self):
581 """Client rejects certificate where server hostname doesn't match."""
582 async with serve(*args, ssl=SERVER_CONTEXT) as server:
583 with self.assertRaises(ssl.SSLCertVerificationError) as raised:
584 # This hostname isn't included in the test certificate.
585 async with connect(
586 get_uri(server), ssl=CLIENT_CONTEXT, server_hostname="invalid"
587 ):
588 self.fail("did not raise")
589 self.assertIn(
590 "Hostname mismatch",
591 str(raised.exception),
592 )
593
594 async def test_cross_origin_redirect(self):
595 """Client follows redirect to a secure URI on a different origin."""
596
597 def redirect(connection, request):
598 response = connection.respond(http.HTTPStatus.FOUND, "")
599 response.headers["Location"] = get_uri(other_server)
600 return response
601
602 async with serve(*args, ssl=SERVER_CONTEXT, process_request=redirect) as server:
603 async with serve(*args, ssl=SERVER_CONTEXT) as other_server:
604 async with connect(get_uri(server), ssl=CLIENT_CONTEXT):
605 self.assertFalse(server.connections)
606 self.assertTrue(other_server.connections)
607
608 async def test_redirect_to_insecure_uri(self):
609 """Client doesn't follow redirect from secure URI to non-secure URI."""
610
611 def redirect(connection, request):
612 response = connection.respond(http.HTTPStatus.FOUND, "")
613 response.headers["Location"] = insecure_uri
614 return response
615
616 async with serve(*args, ssl=SERVER_CONTEXT, process_request=redirect) as server:
617 with self.assertRaises(SecurityError) as raised:
618 secure_uri = get_uri(server)
619 insecure_uri = secure_uri.replace("wss://", "ws://")
620 async with connect(secure_uri, ssl=CLIENT_CONTEXT):
621 self.fail("did not raise")
622
623 self.assertEqual(
624 str(raised.exception),
625 f"cannot follow redirect to non-secure URI {insecure_uri}",
626 )
627
628
629 @unittest.skipUnless("mitmproxy" in sys.modules, "mitmproxy not installed")
630 class SocksProxyClientTests(ProxyMixin, unittest.IsolatedAsyncioTestCase):
631 proxy_mode = "socks5@51080"
632
633 @patch.dict(os.environ, {"socks_proxy": "http://localhost:51080"})
634 async def test_socks_proxy(self):
635 """Client connects to server through a SOCKS5 proxy."""
636 async with serve(*args) as server:
637 async with connect(get_uri(server)) as client:
638 self.assertEqual(client.protocol.state.name, "OPEN")
639 self.assertNumFlows(1)
640
641 @patch.dict(os.environ, {"socks_proxy": "http://localhost:51080"})
642 async def test_secure_socks_proxy(self):
643 """Client connects to server securely through a SOCKS5 proxy."""
644 async with serve(*args, ssl=SERVER_CONTEXT) as server:
645 async with connect(get_uri(server), ssl=CLIENT_CONTEXT) as client:
646 self.assertEqual(client.protocol.state.name, "OPEN")
647 self.assertNumFlows(1)
648
649 @patch.dict(os.environ, {"socks_proxy": "http://hello:iloveyou@localhost:51080"})
650 async def test_authenticated_socks_proxy(self):
651 """Client connects to server through an authenticated SOCKS5 proxy."""
652 try:
653 self.proxy_options.update(proxyauth="hello:iloveyou")
654 async with serve(*args) as server:
655 async with connect(get_uri(server)) as client:
656 self.assertEqual(client.protocol.state.name, "OPEN")
657 finally:
658 self.proxy_options.update(proxyauth=None)
659 self.assertNumFlows(1)
660
661 @patch.dict(os.environ, {"socks_proxy": "http://localhost:51080"})
662 async def test_authenticated_socks_proxy_error(self):
663 """Client fails to authenticate to the SOCKS5 proxy."""
664 from python_socks import ProxyError as SocksProxyError
665
666 try:
667 self.proxy_options.update(proxyauth="any")
668 with self.assertRaises(ProxyError) as raised:
669 async with connect("ws://example.com/"):
670 self.fail("did not raise")
671 finally:
672 self.proxy_options.update(proxyauth=None)
673 self.assertEqual(
674 str(raised.exception),
675 "failed to connect to SOCKS proxy",
676 )
677 self.assertIsInstance(raised.exception.__cause__, SocksProxyError)
678 self.assertNumFlows(0)
679
680 @patch.dict(os.environ, {"socks_proxy": "http://localhost:11080"}) # bad port
681 async def test_socks_proxy_connection_failure(self):
682 """Client fails to connect to the SOCKS5 proxy."""
683 from python_socks import ProxyConnectionError as SocksProxyConnectionError
684
685 with self.assertRaises(OSError) as raised:
686 async with connect("ws://example.com/"):
687 self.fail("did not raise")
688 # Don't test str(raised.exception) because we don't control it.
689 self.assertIsInstance(raised.exception, SocksProxyConnectionError)
690 self.assertNumFlows(0)
691
692 async def test_socks_proxy_connection_timeout(self):
693 """Client times out while connecting to the SOCKS5 proxy."""
694 # Replace the proxy with a TCP server that doesn't respond.
695 with socket.create_server(("localhost", 0)) as sock:
696 host, port = sock.getsockname()
697 with patch.dict(os.environ, {"socks_proxy": f"http://{host}:{port}"}):
698 with self.assertRaises(TimeoutError) as raised:
699 async with connect("ws://example.com/", open_timeout=MS):
700 self.fail("did not raise")
701 self.assertEqual(
702 str(raised.exception),
703 "timed out during opening handshake",
704 )
705 self.assertNumFlows(0)
706
707 async def test_explicit_socks_proxy(self):
708 """Client connects to server through a SOCKS5 proxy set explicitly."""
709 async with serve(*args) as server:
710 async with connect(
711 get_uri(server),
712 # Take this opportunity to test socks5 instead of socks5h.
713 proxy="socks5://localhost:51080",
714 ) as client:
715 self.assertEqual(client.protocol.state.name, "OPEN")
716 self.assertNumFlows(1)
717
718 @patch.dict(os.environ, {"socks_proxy": "http://localhost:51080"})
719 async def test_ignore_proxy_with_existing_socket(self):
720 """Client connects using a pre-existing socket."""
721 async with serve(*args) as server:
722 with socket.create_connection(get_host_port(server)) as sock:
723 # Use a non-existing domain to ensure we connect via sock.
724 async with connect("ws://invalid/", sock=sock) as client:
725 self.assertEqual(client.protocol.state.name, "OPEN")
726 self.assertNumFlows(0)
727
728
729 @unittest.skipUnless("mitmproxy" in sys.modules, "mitmproxy not installed")
730 class HTTPProxyClientTests(ProxyMixin, unittest.IsolatedAsyncioTestCase):
731 proxy_mode = "regular@58080"
732
733 @patch.dict(os.environ, {"https_proxy": "http://localhost:58080"})
734 async def test_http_proxy(self):
735 """Client connects to server through an HTTP proxy."""
736 async with serve(*args) as server:
737 async with connect(get_uri(server)) as client:
738 self.assertEqual(client.protocol.state.name, "OPEN")
739 self.assertNumFlows(1)
740
741 @patch.dict(os.environ, {"https_proxy": "http://localhost:58080"})
742 async def test_secure_http_proxy(self):
743 """Client connects to server securely through an HTTP proxy."""
744 async with serve(*args, ssl=SERVER_CONTEXT) as server:
745 async with connect(get_uri(server), ssl=CLIENT_CONTEXT) as client:
746 self.assertEqual(client.protocol.state.name, "OPEN")
747 ssl_object = client.transport.get_extra_info("ssl_object")
748 self.assertEqual(ssl_object.version()[:3], "TLS")
749 self.assertNumFlows(1)
750
751 @patch.dict(os.environ, {"https_proxy": "http://hello:iloveyou@localhost:58080"})
752 async def test_authenticated_http_proxy(self):
753 """Client connects to server through an authenticated HTTP proxy."""
754 try:
755 self.proxy_options.update(proxyauth="hello:iloveyou")
756 async with serve(*args) as server:
757 async with connect(get_uri(server)) as client:
758 self.assertEqual(client.protocol.state.name, "OPEN")
759 finally:
760 self.proxy_options.update(proxyauth=None)
761 self.assertNumFlows(1)
762
763 @patch.dict(os.environ, {"https_proxy": "http://localhost:58080"})
764 async def test_authenticated_http_proxy_error(self):
765 """Client fails to authenticate to the HTTP proxy."""
766 try:
767 self.proxy_options.update(proxyauth="any")
768 with self.assertRaises(ProxyError) as raised:
769 async with connect("ws://example.com/"):
770 self.fail("did not raise")
771 finally:
772 self.proxy_options.update(proxyauth=None)
773 self.assertEqual(
774 str(raised.exception),
775 "proxy rejected connection: HTTP 407",
776 )
777 self.assertNumFlows(0)
778
779 @patch.dict(os.environ, {"https_proxy": "http://localhost:58080"})
780 async def test_http_proxy_override_user_agent(self):
781 """Client can override User-Agent header with user_agent_header."""
782 async with serve(*args) as server:
783 async with connect(get_uri(server), user_agent_header="Smith") as client:
784 self.assertEqual(client.protocol.state.name, "OPEN")
785 [http_connect] = self.get_http_connects()
786 self.assertEqual(http_connect.request.headers[b"User-Agent"], "Smith")
787
788 @patch.dict(os.environ, {"https_proxy": "http://localhost:58080"})
789 async def test_http_proxy_remove_user_agent(self):
790 """Client can remove User-Agent header with user_agent_header."""
791 async with serve(*args) as server:
792 async with connect(get_uri(server), user_agent_header=None) as client:
793 self.assertEqual(client.protocol.state.name, "OPEN")
794 [http_connect] = self.get_http_connects()
795 self.assertNotIn(b"User-Agent", http_connect.request.headers)
796
797 @patch.dict(os.environ, {"https_proxy": "http://localhost:58080"})
798 async def test_http_proxy_protocol_error(self):
799 """Client receives invalid data when connecting to the HTTP proxy."""
800 try:
801 self.proxy_options.update(break_http_connect=True)
802 with self.assertRaises(InvalidProxyMessage) as raised:
803 async with connect("ws://example.com/"):
804 self.fail("did not raise")
805 finally:
806 self.proxy_options.update(break_http_connect=False)
807 self.assertEqual(
808 str(raised.exception),
809 "did not receive a valid HTTP response from proxy",
810 )
811 self.assertNumFlows(0)
812
813 @patch.dict(os.environ, {"https_proxy": "http://localhost:58080"})
814 async def test_http_proxy_connection_error(self):
815 """Client receives no response when connecting to the HTTP proxy."""
816 try:
817 self.proxy_options.update(close_http_connect=True)
818 with self.assertRaises(InvalidProxyMessage) as raised:
819 async with connect("ws://example.com/"):
820 self.fail("did not raise")
821 finally:
822 self.proxy_options.update(close_http_connect=False)
823 self.assertEqual(
824 str(raised.exception),
825 "did not receive a valid HTTP response from proxy",
826 )
827 self.assertNumFlows(0)
828
829 @patch.dict(os.environ, {"https_proxy": "http://localhost:28080"}) # bad port
830 async def test_http_proxy_connection_failure(self):
831 """Client fails to connect to the HTTP proxy."""
832 with self.assertRaises(OSError):
833 async with connect("ws://example.com/"):
834 self.fail("did not raise")
835 # Don't test str(raised.exception) because we don't control it.
836 self.assertNumFlows(0)
837
838 async def test_http_proxy_connection_timeout(self):
839 """Client times out while connecting to the HTTP proxy."""
840 # Replace the proxy with a TCP server that doesn't respond.
841 with socket.create_server(("localhost", 0)) as sock:
842 host, port = sock.getsockname()
843 with patch.dict(os.environ, {"https_proxy": f"http://{host}:{port}"}):
844 with self.assertRaises(TimeoutError) as raised:
845 async with connect("ws://example.com/", open_timeout=MS):
846 self.fail("did not raise")
847 self.assertEqual(
848 str(raised.exception),
849 "timed out during opening handshake",
850 )
851
852 @patch.dict(os.environ, {"https_proxy": "https://localhost:58080"})
853 async def test_https_proxy(self):
854 """Client connects to server through an HTTPS proxy."""
855 async with serve(*args) as server:
856 async with connect(
857 get_uri(server),
858 proxy_ssl=self.proxy_context,
859 ) as client:
860 self.assertEqual(client.protocol.state.name, "OPEN")
861 self.assertNumFlows(1)
862
863 @patch.dict(os.environ, {"https_proxy": "https://localhost:58080"})
864 async def test_secure_https_proxy(self):
865 """Client connects to server securely through an HTTPS proxy."""
866 async with serve(*args, ssl=SERVER_CONTEXT) as server:
867 async with connect(
868 get_uri(server),
869 ssl=CLIENT_CONTEXT,
870 proxy_ssl=self.proxy_context,
871 ) as client:
872 self.assertEqual(client.protocol.state.name, "OPEN")
873 ssl_object = client.transport.get_extra_info("ssl_object")
874 self.assertEqual(ssl_object.version()[:3], "TLS")
875 self.assertNumFlows(1)
876
877 @patch.dict(os.environ, {"https_proxy": "https://localhost:58080"})
878 async def test_https_proxy_server_hostname(self):
879 """Client sets server_hostname to the value of proxy_server_hostname."""
880 async with serve(*args) as server:
881 async with connect(
882 get_uri(server),
883 proxy_ssl=self.proxy_context,
884 proxy_server_hostname="overridden",
885 # Pass an argument not prefixed with proxy_ for coverage.
886 happy_eyeballs_delay=0.1,
887 ) as client:
888 ssl_object = client.transport.get_extra_info("ssl_object")
889 self.assertEqual(ssl_object.server_hostname, "overridden")
890 self.assertNumFlows(1)
891
892 @patch.dict(os.environ, {"https_proxy": "https://localhost:58080"})
893 async def test_https_proxy_invalid_proxy_certificate(self):
894 """Client rejects certificate when proxy certificate isn't trusted."""
895 with self.assertRaises(ssl.SSLCertVerificationError) as raised:
896 # The proxy certificate isn't trusted.
897 async with connect("wss://example.com/"):
898 self.fail("did not raise")
899 self.assertIn(
900 "unable to get local issuer certificate",
901 str(raised.exception),
902 )
903
904 @patch.dict(os.environ, {"https_proxy": "https://localhost:58080"})
905 async def test_https_proxy_invalid_server_certificate(self):
906 """Client rejects certificate when proxy certificate isn't trusted."""
907 async with serve(*args, ssl=SERVER_CONTEXT) as server:
908 with self.assertRaises(ssl.SSLCertVerificationError) as raised:
909 # The test certificate is self-signed.
910 async with connect(get_uri(server), proxy_ssl=self.proxy_context):
911 self.fail("did not raise")
912 self.assertIn(
913 "self signed certificate",
914 str(raised.exception).replace("-", " "),
915 )
916 self.assertNumFlows(1)
917
918
919 @unittest.skipUnless(hasattr(socket, "AF_UNIX"), "this test requires Unix sockets")
920 class UnixClientTests(unittest.IsolatedAsyncioTestCase):
921 async def test_context_manager(self):
922 """Client connects to Unix server and disconnects automatically."""
923 with temp_unix_socket_path() as path:
924 async with unix_serve(handler, path):
925 async with unix_connect(path) as client:
926 self.assertEqual(client.protocol.state.name, "OPEN")
927 self.assertEqual(client.protocol.state.name, "CLOSED")
928
929 async def test_direct_connection(self):
930 """Client connects to Unix server directly."""
931 with temp_unix_socket_path() as path:
932 async with unix_serve(handler, path):
933 client = await unix_connect(path)
934 self.addAsyncCleanup(client.close)
935 self.assertEqual(client.protocol.state.name, "OPEN")
936
937 async def test_set_host_header(self):
938 """Client sets the Host header to the host in the WebSocket URI."""
939 # This is part of the documented behavior of unix_connect().
940 with temp_unix_socket_path() as path:
941 async with unix_serve(handler, path):
942 async with unix_connect(path, uri="ws://overridden/") as client:
943 self.assertEqual(client.request.headers["Host"], "overridden")
944
945 async def test_cross_origin_redirect(self):
946 """Client doesn't follows redirect to a URI on a different origin."""
947
948 def redirect(connection, request):
949 response = connection.respond(http.HTTPStatus.FOUND, "")
950 response.headers["Location"] = "ws://other/"
951 return response
952
953 with temp_unix_socket_path() as path:
954 async with unix_serve(handler, path, process_request=redirect):
955 with self.assertRaises(ValueError) as raised:
956 async with unix_connect(path):
957 self.fail("did not raise")
958
959 self.assertEqual(
960 str(raised.exception),
961 "cannot follow cross-origin redirect to ws://other/ with a Unix socket",
962 )
963
964 async def test_secure_context_manager(self):
965 """Client connects to Unix server securely and disconnects automatically."""
966 with temp_unix_socket_path() as path:
967 async with unix_serve(handler, path, ssl=SERVER_CONTEXT):
968 async with unix_connect(path, ssl=CLIENT_CONTEXT) as client:
969 self.assertEqual(client.protocol.state.name, "OPEN")
970 ssl_object = client.transport.get_extra_info("ssl_object")
971 self.assertEqual(ssl_object.version()[:3], "TLS")
972 self.assertEqual(client.protocol.state.name, "CLOSED")
973
974 async def test_secure_direct_connection(self):
975 """Client connects to Unix server securely and directly."""
976 with temp_unix_socket_path() as path:
977 async with unix_serve(handler, path, ssl=SERVER_CONTEXT):
978 client = await unix_connect(path, ssl=CLIENT_CONTEXT)
979 self.addAsyncCleanup(client.close)
980 self.assertEqual(client.protocol.state.name, "OPEN")
981 ssl_object = client.transport.get_extra_info("ssl_object")
982 self.assertEqual(ssl_object.version()[:3], "TLS")
983
984 async def test_set_server_hostname(self):
985 """Client sets server_hostname to the host in the WebSocket URI."""
986 # This is part of the documented behavior of unix_connect().
987 with temp_unix_socket_path() as path:
988 async with unix_serve(handler, path, ssl=SERVER_CONTEXT):
989 async with unix_connect(
990 path,
991 ssl=CLIENT_CONTEXT,
992 uri="wss://overridden/",
993 ) as client:
994 ssl_object = client.transport.get_extra_info("ssl_object")
995 self.assertEqual(ssl_object.server_hostname, "overridden")
996
997 async def test_pathlib_path(self):
998 """Client accepts a pathlib.Path object as the path argument."""
999 with temp_unix_socket_path() as path:
1000 async with unix_serve(handler, path):
1001 async with unix_connect(pathlib.Path(path)) as client:
1002 self.assertEqual(client.protocol.state.name, "OPEN")
1003
1004 async def test_non_existing_path(self):
1005 """Client attempts to connect to a non-existing Unix socket path."""
1006 with temp_unix_socket_path() as path:
1007 with self.assertRaises(FileNotFoundError):
1008 async with unix_connect(path + ".doesnotexist"):
1009 self.fail("did not raise")
1010
1011
1012 class ClientUsageErrorsTests(unittest.IsolatedAsyncioTestCase):
1013 async def test_ssl_without_secure_uri(self):
1014 """Client rejects ssl when URI isn't secure."""
1015 with self.assertRaises(ValueError) as raised:
1016 await connect("ws://localhost/", ssl=CLIENT_CONTEXT)
1017 self.assertEqual(
1018 str(raised.exception),
1019 "ssl argument is incompatible with a ws:// URI",
1020 )
1021
1022 async def test_secure_uri_without_ssl(self):
1023 """Client rejects ssl=None when URI is secure."""
1024 with self.assertRaises(ValueError) as raised:
1025 await connect("wss://localhost/", ssl=None)
1026 self.assertEqual(
1027 str(raised.exception),
1028 "ssl=None is incompatible with a wss:// URI",
1029 )
1030
1031 async def test_proxy_ssl_without_https_proxy(self):
1032 """Client rejects proxy_ssl when proxy isn't HTTPS."""
1033 with self.assertRaises(ValueError) as raised:
1034 await connect(
1035 "ws://localhost/",
1036 proxy="http://localhost:8080",
1037 proxy_ssl=True,
1038 )
1039 self.assertEqual(
1040 str(raised.exception),
1041 "proxy_ssl argument is incompatible with an http:// proxy",
1042 )
1043
1044 async def test_https_proxy_without_proxy_ssl(self):
1045 """Client rejects proxy_ssl=None when proxy is HTTPS."""
1046 with self.assertRaises(ValueError) as raised:
1047 await connect(
1048 "ws://localhost/",
1049 proxy="https://localhost:8080",
1050 proxy_ssl=None,
1051 )
1052 self.assertEqual(
1053 str(raised.exception),
1054 "proxy_ssl=None is incompatible with an https:// proxy",
1055 )
1056
1057 async def test_unsupported_proxy(self):
1058 """Client rejects unsupported proxy."""
1059 with self.assertRaises(InvalidProxy) as raised:
1060 async with connect("ws://example.com/", proxy="other://localhost:51080"):
1061 self.fail("did not raise")
1062 self.assertEqual(
1063 str(raised.exception),
1064 "other://localhost:51080 isn't a valid proxy: scheme other isn't supported",
1065 )
1066
1067 async def test_unix_without_path_or_sock(self):
1068 """Unix client requires path when sock isn't provided."""
1069 with self.assertRaises(ValueError) as raised:
1070 await unix_connect()
1071 self.assertEqual(
1072 str(raised.exception),
1073 "no path and sock were specified",
1074 )
1075
1076 async def test_unix_with_path_and_sock(self):
1077 """Unix client rejects path when sock is provided."""
1078 sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
1079 self.addCleanup(sock.close)
1080 with self.assertRaises(ValueError) as raised:
1081 await unix_connect(path="/", sock=sock)
1082 self.assertEqual(
1083 str(raised.exception),
1084 "path and sock can not be specified at the same time",
1085 )
1086
1087 async def test_invalid_subprotocol(self):
1088 """Client rejects single value of subprotocols."""
1089 with self.assertRaises(TypeError) as raised:
1090 await connect("ws://localhost/", subprotocols="chat")
1091 self.assertEqual(
1092 str(raised.exception),
1093 "subprotocols must be a list, not a str",
1094 )
1095
1096 async def test_unsupported_compression(self):
1097 """Client rejects incorrect value of compression."""
1098 with self.assertRaises(ValueError) as raised:
1099 await connect("ws://localhost/", compression=False)
1100 self.assertEqual(
1101 str(raised.exception),
1102 "unsupported compression: False",
1103 )
1104
1105 async def test_reentrancy(self):
1106 """Client isn't reentrant."""
1107 async with serve(*args) as server:
1108 connecter = connect(get_uri(server))
1109 async with connecter:
1110 with self.assertRaises(RuntimeError) as raised:
1111 async with connecter:
1112 self.fail("did not raise")
1113 self.assertEqual(
1114 str(raised.exception),
1115 "connect() isn't reentrant",
1116 )