Debian Codegraph @

tests/sync/test_client.py

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