Debian Codegraph @

tests/trio/test_client.py

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