| 1 |
import dataclasses |
| 2 |
import hmac |
| 3 |
import http |
| 4 |
import logging |
| 5 |
import socket |
| 6 |
|
| 7 |
import trio |
| 8 |
|
| 9 |
from websockets.exceptions import ( |
| 10 |
ConnectionClosedError, |
| 11 |
ConnectionClosedOK, |
| 12 |
InvalidHandshake, |
| 13 |
InvalidStatus, |
| 14 |
NegotiationError, |
| 15 |
) |
| 16 |
from websockets.http11 import Request, Response |
| 17 |
from websockets.trio.client import connect |
| 18 |
from websockets.trio.server import * |
| 19 |
|
| 20 |
from ..utils import ( |
| 21 |
CLIENT_CONTEXT, |
| 22 |
MS, |
| 23 |
SERVER_CONTEXT, |
| 24 |
LoggingTestCase, |
| 25 |
) |
| 26 |
from .server import ( |
| 27 |
EvalShellMixin, |
| 28 |
get_host_port, |
| 29 |
get_uri, |
| 30 |
handler, |
| 31 |
run_server, |
| 32 |
) |
| 33 |
from .utils import IsolatedTrioTestCase |
| 34 |
|
| 35 |
|
| 36 |
class ServerTests(EvalShellMixin, LoggingTestCase, IsolatedTrioTestCase): |
| 37 |
async def test_connection(self): |
| 38 |
"""Server receives connection from client and the handshake succeeds.""" |
| 39 |
async with run_server() as server: |
| 40 |
async with connect(get_uri(server)) as client: |
| 41 |
await self.assertEval(client, "ws.protocol.state.name", "OPEN") |
| 42 |
|
| 43 |
async def test_connection_handler_returns(self): |
| 44 |
"""Connection handler returns.""" |
| 45 |
async with run_server() as server: |
| 46 |
async with connect(get_uri(server) + "/no-op") as client: |
| 47 |
with self.assertRaises(ConnectionClosedOK) as raised: |
| 48 |
await client.recv() |
| 49 |
self.assertEqual( |
| 50 |
str(raised.exception), |
| 51 |
"received 1000 (OK); then sent 1000 (OK)", |
| 52 |
) |
| 53 |
|
| 54 |
async def test_connection_handler_raises_exception(self): |
| 55 |
"""Connection handler raises an exception.""" |
| 56 |
async with run_server() as server: |
| 57 |
async with connect(get_uri(server) + "/crash") as client: |
| 58 |
with self.assertRaises(ConnectionClosedError) as raised: |
| 59 |
await client.recv() |
| 60 |
self.assertEqual( |
| 61 |
str(raised.exception), |
| 62 |
"received 1011 (internal error); then sent 1011 (internal error)", |
| 63 |
) |
| 64 |
|
| 65 |
async def test_existing_listeners(self): |
| 66 |
"""Server receives connection using pre-existing listeners.""" |
| 67 |
listeners = await trio.open_tcp_listeners(0, host="localhost") |
| 68 |
host, port = next( |
| 69 |
listener |
| 70 |
for listener in listeners |
| 71 |
if listener.socket.family == socket.AF_INET |
| 72 |
).socket.getsockname() |
| 73 |
# Unset the default values of port and host set by run_server. |
| 74 |
async with run_server(port=None, host=None, listeners=listeners): |
| 75 |
async with connect(f"ws://{host}:{port}/") as client: # type: ignore |
| 76 |
await self.assertEval(client, "ws.protocol.state.name", "OPEN") |
| 77 |
|
| 78 |
async def test_select_subprotocol(self): |
| 79 |
"""Server selects a subprotocol with the select_subprotocol callable.""" |
| 80 |
|
| 81 |
def select_subprotocol(ws, subprotocols): |
| 82 |
ws.select_subprotocol_ran = True |
| 83 |
assert "chat" in subprotocols |
| 84 |
return "chat" |
| 85 |
|
| 86 |
async with run_server( |
| 87 |
subprotocols=["chat"], |
| 88 |
select_subprotocol=select_subprotocol, |
| 89 |
) as server: |
| 90 |
async with connect(get_uri(server), subprotocols=["chat"]) as client: |
| 91 |
await self.assertEval(client, "ws.select_subprotocol_ran", "True") |
| 92 |
await self.assertEval(client, "ws.subprotocol", "chat") |
| 93 |
|
| 94 |
async def test_select_subprotocol_rejects_handshake(self): |
| 95 |
"""Server rejects handshake if select_subprotocol raises NegotiationError.""" |
| 96 |
|
| 97 |
def select_subprotocol(ws, subprotocols): |
| 98 |
raise NegotiationError |
| 99 |
|
| 100 |
async with run_server(select_subprotocol=select_subprotocol) as server: |
| 101 |
with self.assertRaises(InvalidStatus) as raised: |
| 102 |
async with connect(get_uri(server)): |
| 103 |
self.fail("did not raise") |
| 104 |
self.assertEqual( |
| 105 |
str(raised.exception), |
| 106 |
"server rejected WebSocket connection: HTTP 400", |
| 107 |
) |
| 108 |
|
| 109 |
async def test_select_subprotocol_raises_exception(self): |
| 110 |
"""Server returns an error if select_subprotocol raises an exception.""" |
| 111 |
|
| 112 |
def select_subprotocol(ws, subprotocols): |
| 113 |
raise RuntimeError |
| 114 |
|
| 115 |
async with run_server(select_subprotocol=select_subprotocol) as server: |
| 116 |
with self.assertRaises(InvalidStatus) as raised: |
| 117 |
async with connect(get_uri(server)): |
| 118 |
self.fail("did not raise") |
| 119 |
self.assertEqual( |
| 120 |
str(raised.exception), |
| 121 |
"server rejected WebSocket connection: HTTP 500", |
| 122 |
) |
| 123 |
|
| 124 |
async def test_compression_is_enabled(self): |
| 125 |
"""Server enables compression by default.""" |
| 126 |
async with run_server() as server: |
| 127 |
async with connect(get_uri(server)) as client: |
| 128 |
await self.assertEval( |
| 129 |
client, |
| 130 |
"[type(ext).__name__ for ext in ws.protocol.extensions]", |
| 131 |
"['PerMessageDeflate']", |
| 132 |
) |
| 133 |
|
| 134 |
async def test_disable_compression(self): |
| 135 |
"""Server disables compression.""" |
| 136 |
async with run_server(compression=None) as server: |
| 137 |
async with connect(get_uri(server)) as client: |
| 138 |
await self.assertEval(client, "ws.protocol.extensions", "[]") |
| 139 |
|
| 140 |
async def test_process_request_returns_none(self): |
| 141 |
"""Server runs process_request and continues the handshake.""" |
| 142 |
|
| 143 |
def process_request(ws, request): |
| 144 |
self.assertIsInstance(request, Request) |
| 145 |
ws.process_request_ran = True |
| 146 |
|
| 147 |
async with run_server(process_request=process_request) as server: |
| 148 |
async with connect(get_uri(server)) as client: |
| 149 |
await self.assertEval(client, "ws.process_request_ran", "True") |
| 150 |
|
| 151 |
async def test_async_process_request_returns_none(self): |
| 152 |
"""Server runs async process_request and continues the handshake.""" |
| 153 |
|
| 154 |
async def process_request(ws, request): |
| 155 |
self.assertIsInstance(request, Request) |
| 156 |
ws.process_request_ran = True |
| 157 |
|
| 158 |
async with run_server(process_request=process_request) as server: |
| 159 |
async with connect(get_uri(server)) as client: |
| 160 |
await self.assertEval(client, "ws.process_request_ran", "True") |
| 161 |
|
| 162 |
async def test_process_request_returns_response(self): |
| 163 |
"""Server aborts handshake if process_request returns a response.""" |
| 164 |
|
| 165 |
def process_request(ws, request): |
| 166 |
return ws.respond(http.HTTPStatus.FORBIDDEN, "Forbidden") |
| 167 |
|
| 168 |
async def handler(ws): |
| 169 |
self.fail("handler must not run") |
| 170 |
|
| 171 |
with self.assertNoLogs("websockets", logging.ERROR): |
| 172 |
async with run_server(handler, process_request=process_request) as server: |
| 173 |
with self.assertRaises(InvalidStatus) as raised: |
| 174 |
async with connect(get_uri(server)): |
| 175 |
self.fail("did not raise") |
| 176 |
self.assertEqual( |
| 177 |
str(raised.exception), |
| 178 |
"server rejected WebSocket connection: HTTP 403", |
| 179 |
) |
| 180 |
|
| 181 |
async def test_async_process_request_returns_response(self): |
| 182 |
"""Server aborts handshake if async process_request returns a response.""" |
| 183 |
|
| 184 |
async def process_request(ws, request): |
| 185 |
return ws.respond(http.HTTPStatus.FORBIDDEN, "Forbidden") |
| 186 |
|
| 187 |
async def handler(ws): |
| 188 |
self.fail("handler must not run") |
| 189 |
|
| 190 |
with self.assertNoLogs("websockets", logging.ERROR): |
| 191 |
async with run_server(handler, process_request=process_request) as server: |
| 192 |
with self.assertRaises(InvalidStatus) as raised: |
| 193 |
async with connect(get_uri(server)): |
| 194 |
self.fail("did not raise") |
| 195 |
self.assertEqual( |
| 196 |
str(raised.exception), |
| 197 |
"server rejected WebSocket connection: HTTP 403", |
| 198 |
) |
| 199 |
|
| 200 |
async def test_process_request_raises_exception(self): |
| 201 |
"""Server returns an error if process_request raises an exception.""" |
| 202 |
|
| 203 |
def process_request(ws, request): |
| 204 |
raise RuntimeError("BOOM") |
| 205 |
|
| 206 |
with self.assertLogs("websockets", logging.ERROR) as logs: |
| 207 |
async with run_server(process_request=process_request) as server: |
| 208 |
with self.assertRaises(InvalidStatus) as raised: |
| 209 |
async with connect(get_uri(server)): |
| 210 |
self.fail("did not raise") |
| 211 |
self.assertEqual( |
| 212 |
str(raised.exception), |
| 213 |
"server rejected WebSocket connection: HTTP 500", |
| 214 |
) |
| 215 |
self.assertExceptionLogged(logs, "process_request failed", "BOOM") |
| 216 |
|
| 217 |
async def test_async_process_request_raises_exception(self): |
| 218 |
"""Server returns an error if async process_request raises an exception.""" |
| 219 |
|
| 220 |
async def process_request(ws, request): |
| 221 |
raise RuntimeError("BOOM") |
| 222 |
|
| 223 |
with self.assertLogs("websockets", logging.ERROR) as logs: |
| 224 |
async with run_server(process_request=process_request) as server: |
| 225 |
with self.assertRaises(InvalidStatus) as raised: |
| 226 |
async with connect(get_uri(server)): |
| 227 |
self.fail("did not raise") |
| 228 |
self.assertEqual( |
| 229 |
str(raised.exception), |
| 230 |
"server rejected WebSocket connection: HTTP 500", |
| 231 |
) |
| 232 |
self.assertExceptionLogged(logs, "process_request failed", "BOOM") |
| 233 |
|
| 234 |
async def test_process_response_returns_none(self): |
| 235 |
"""Server runs process_response but keeps the handshake response.""" |
| 236 |
|
| 237 |
def process_response(ws, request, response): |
| 238 |
self.assertIsInstance(request, Request) |
| 239 |
self.assertIsInstance(response, Response) |
| 240 |
ws.process_response_ran = True |
| 241 |
|
| 242 |
async with run_server(process_response=process_response) as server: |
| 243 |
async with connect(get_uri(server)) as client: |
| 244 |
await self.assertEval(client, "ws.process_response_ran", "True") |
| 245 |
|
| 246 |
async def test_async_process_response_returns_none(self): |
| 247 |
"""Server runs async process_response but keeps the handshake response.""" |
| 248 |
|
| 249 |
async def process_response(ws, request, response): |
| 250 |
self.assertIsInstance(request, Request) |
| 251 |
self.assertIsInstance(response, Response) |
| 252 |
ws.process_response_ran = True |
| 253 |
|
| 254 |
async with run_server(process_response=process_response) as server: |
| 255 |
async with connect(get_uri(server)) as client: |
| 256 |
await self.assertEval(client, "ws.process_response_ran", "True") |
| 257 |
|
| 258 |
async def test_process_response_modifies_response(self): |
| 259 |
"""Server runs process_response and modifies the handshake response.""" |
| 260 |
|
| 261 |
def process_response(ws, request, response): |
| 262 |
response.headers["X-ProcessResponse"] = "OK" |
| 263 |
|
| 264 |
async with run_server(process_response=process_response) as server: |
| 265 |
async with connect(get_uri(server)) as client: |
| 266 |
self.assertEqual(client.response.headers["X-ProcessResponse"], "OK") |
| 267 |
|
| 268 |
async def test_async_process_response_modifies_response(self): |
| 269 |
"""Server runs async process_response and modifies the handshake response.""" |
| 270 |
|
| 271 |
async def process_response(ws, request, response): |
| 272 |
response.headers["X-ProcessResponse"] = "OK" |
| 273 |
|
| 274 |
async with run_server(process_response=process_response) as server: |
| 275 |
async with connect(get_uri(server)) as client: |
| 276 |
self.assertEqual(client.response.headers["X-ProcessResponse"], "OK") |
| 277 |
|
| 278 |
async def test_process_response_replaces_response(self): |
| 279 |
"""Server runs process_response and replaces the handshake response.""" |
| 280 |
|
| 281 |
def process_response(ws, request, response): |
| 282 |
headers = response.headers.copy() |
| 283 |
headers["X-ProcessResponse"] = "OK" |
| 284 |
return dataclasses.replace(response, headers=headers) |
| 285 |
|
| 286 |
async with run_server(process_response=process_response) as server: |
| 287 |
async with connect(get_uri(server)) as client: |
| 288 |
self.assertEqual(client.response.headers["X-ProcessResponse"], "OK") |
| 289 |
|
| 290 |
async def test_async_process_response_replaces_response(self): |
| 291 |
"""Server runs async process_response and replaces the handshake response.""" |
| 292 |
|
| 293 |
async def process_response(ws, request, response): |
| 294 |
headers = response.headers.copy() |
| 295 |
headers["X-ProcessResponse"] = "OK" |
| 296 |
return dataclasses.replace(response, headers=headers) |
| 297 |
|
| 298 |
async with run_server(process_response=process_response) as server: |
| 299 |
async with connect(get_uri(server)) as client: |
| 300 |
self.assertEqual(client.response.headers["X-ProcessResponse"], "OK") |
| 301 |
|
| 302 |
async def test_process_response_raises_exception(self): |
| 303 |
"""Server returns an error if process_response raises an exception.""" |
| 304 |
|
| 305 |
def process_response(ws, request, response): |
| 306 |
raise RuntimeError("BOOM") |
| 307 |
|
| 308 |
with self.assertLogs("websockets", logging.ERROR) as logs: |
| 309 |
async with run_server(process_response=process_response) as server: |
| 310 |
with self.assertRaises(InvalidStatus) as raised: |
| 311 |
async with connect(get_uri(server)): |
| 312 |
self.fail("did not raise") |
| 313 |
self.assertEqual( |
| 314 |
str(raised.exception), |
| 315 |
"server rejected WebSocket connection: HTTP 500", |
| 316 |
) |
| 317 |
self.assertExceptionLogged(logs, "process_response failed", "BOOM") |
| 318 |
|
| 319 |
async def test_async_process_response_raises_exception(self): |
| 320 |
"""Server returns an error if async process_response raises an exception.""" |
| 321 |
|
| 322 |
async def process_response(ws, request, response): |
| 323 |
raise RuntimeError("BOOM") |
| 324 |
|
| 325 |
with self.assertLogs("websockets", logging.ERROR) as logs: |
| 326 |
async with run_server(process_response=process_response) as server: |
| 327 |
with self.assertRaises(InvalidStatus) as raised: |
| 328 |
async with connect(get_uri(server)): |
| 329 |
self.fail("did not raise") |
| 330 |
self.assertEqual( |
| 331 |
str(raised.exception), |
| 332 |
"server rejected WebSocket connection: HTTP 500", |
| 333 |
) |
| 334 |
self.assertExceptionLogged(logs, "process_response failed", "BOOM") |
| 335 |
|
| 336 |
async def test_override_serve_header(self): |
| 337 |
"""Server can override Server header with server_header.""" |
| 338 |
async with run_server(server_header="Neo") as server: |
| 339 |
async with connect(get_uri(server)) as client: |
| 340 |
await self.assertEval(client, "ws.response.headers['Server']", "Neo") |
| 341 |
|
| 342 |
async def test_remove_server_header(self): |
| 343 |
"""Server can remove Server header with server_header.""" |
| 344 |
async with run_server(server_header=None) as server: |
| 345 |
async with connect(get_uri(server)) as client: |
| 346 |
await self.assertEval( |
| 347 |
client, "'Server' in ws.response.headers", "False" |
| 348 |
) |
| 349 |
|
| 350 |
async def test_keepalive_is_enabled(self): |
| 351 |
"""Server enables keepalive and measures latency.""" |
| 352 |
async with run_server(ping_interval=MS) as server: |
| 353 |
async with connect(get_uri(server)) as client: |
| 354 |
await client.send("ws.latency") |
| 355 |
latency = eval(await client.recv()) |
| 356 |
self.assertEqual(latency, 0) |
| 357 |
await trio.sleep(2 * MS) |
| 358 |
await client.send("ws.latency") |
| 359 |
latency = eval(await client.recv()) |
| 360 |
self.assertGreater(latency, 0) |
| 361 |
|
| 362 |
async def test_disable_keepalive(self): |
| 363 |
"""Server disables keepalive.""" |
| 364 |
async with run_server(ping_interval=None) as server: |
| 365 |
async with connect(get_uri(server)) as client: |
| 366 |
await trio.sleep(2 * MS) |
| 367 |
await client.send("ws.latency") |
| 368 |
latency = eval(await client.recv()) |
| 369 |
self.assertEqual(latency, 0) |
| 370 |
|
| 371 |
async def test_logger(self): |
| 372 |
"""Server accepts a logger argument.""" |
| 373 |
logger = logging.getLogger("test") |
| 374 |
async with run_server(logger=logger) as server: |
| 375 |
self.assertEqual(server.logger.name, logger.name) |
| 376 |
|
| 377 |
async def test_custom_connection_factory(self): |
| 378 |
"""Server runs ServerConnection factory provided in create_connection.""" |
| 379 |
|
| 380 |
def create_connection(*args, **kwargs): |
| 381 |
server = ServerConnection(*args, **kwargs) |
| 382 |
server.create_connection_ran = True |
| 383 |
return server |
| 384 |
|
| 385 |
async with run_server(create_connection=create_connection) as server: |
| 386 |
async with connect(get_uri(server)) as client: |
| 387 |
await self.assertEval(client, "ws.create_connection_ran", "True") |
| 388 |
|
| 389 |
async def test_connections(self): |
| 390 |
"""Server provides a connections property.""" |
| 391 |
async with run_server() as server: |
| 392 |
self.assertEqual(server.connections, set()) |
| 393 |
async with ( |
| 394 |
connect(get_uri(server)) as client1, |
| 395 |
connect(get_uri(server)) as client2, |
| 396 |
): |
| 397 |
await client1.send("ws.id") |
| 398 |
await client2.send("ws.id") |
| 399 |
self.assertEqual( |
| 400 |
{str(connection.id) for connection in server.connections}, |
| 401 |
{await client1.recv(), await client2.recv()}, |
| 402 |
) |
| 403 |
self.assertEqual(server.connections, set()) |
| 404 |
|
| 405 |
async def test_handshake_fails(self): |
| 406 |
"""Server receives connection from client but the handshake fails.""" |
| 407 |
|
| 408 |
def remove_key_header(self, request): |
| 409 |
del request.headers["Sec-WebSocket-Key"] |
| 410 |
|
| 411 |
async with run_server(process_request=remove_key_header) as server: |
| 412 |
with self.assertRaises(InvalidStatus) as raised: |
| 413 |
async with connect(get_uri(server)): |
| 414 |
self.fail("did not raise") |
| 415 |
self.assertEqual( |
| 416 |
str(raised.exception), |
| 417 |
"server rejected WebSocket connection: HTTP 400", |
| 418 |
) |
| 419 |
|
| 420 |
async def test_timeout_before_handshake_request(self): |
| 421 |
"""Server times out before receiving handshake request from client.""" |
| 422 |
with self.assertLogs("websockets", logging.DEBUG) as logs: |
| 423 |
async with run_server(open_timeout=MS) as server: |
| 424 |
stream = await trio.open_tcp_stream(*get_host_port(server)) |
| 425 |
try: |
| 426 |
# Wait for the server to close the connection. |
| 427 |
self.assertEqual(await stream.receive_some(4096), b"") |
| 428 |
finally: |
| 429 |
await stream.aclose() |
| 430 |
|
| 431 |
self.assertExceptionLogged( |
| 432 |
logs, |
| 433 |
"! no valid HTTP request", |
| 434 |
"connection closed while reading HTTP request line", |
| 435 |
) |
| 436 |
|
| 437 |
async def test_connection_closed_before_handshake_request(self): |
| 438 |
"""Server reads EOF before receiving handshake request from client.""" |
| 439 |
with self.assertLogs("websockets", logging.DEBUG) as logs: |
| 440 |
async with run_server() as server: |
| 441 |
stream = await trio.open_tcp_stream(*get_host_port(server)) |
| 442 |
await stream.aclose() |
| 443 |
|
| 444 |
self.assertExceptionLogged( |
| 445 |
logs, |
| 446 |
"! no valid HTTP request", |
| 447 |
"connection closed while reading HTTP request line", |
| 448 |
) |
| 449 |
|
| 450 |
async def test_connection_closed_before_handshake_response(self): |
| 451 |
"""Server reads EOF before sending handshake response to client.""" |
| 452 |
|
| 453 |
async def process_request(ws, _request): |
| 454 |
await ws.stream.aclose() |
| 455 |
await trio.testing.wait_all_tasks_blocked() |
| 456 |
|
| 457 |
with self.assertNoLogs("websockets", logging.ERROR): |
| 458 |
async with run_server(process_request=process_request) as server: |
| 459 |
with self.assertRaises(InvalidHandshake): |
| 460 |
async with connect(get_uri(server)): |
| 461 |
self.fail("did not raise") |
| 462 |
|
| 463 |
async def test_junk_handshake_request(self): |
| 464 |
"""Server closes the connection when receiving non-HTTP request from client.""" |
| 465 |
with self.assertLogs("websockets", logging.DEBUG) as logs: |
| 466 |
async with run_server() as server: |
| 467 |
stream = await trio.open_tcp_stream(*get_host_port(server)) |
| 468 |
await stream.send_all(b"HELO relay.invalid\r\n") |
| 469 |
try: |
| 470 |
# Wait for the server to close the connection. |
| 471 |
self.assertEqual(await stream.receive_some(4096), b"") |
| 472 |
finally: |
| 473 |
await stream.aclose() |
| 474 |
|
| 475 |
self.assertExceptionLogged( |
| 476 |
logs, |
| 477 |
"! no valid HTTP request", |
| 478 |
"invalid HTTP request line: HELO relay.invalid", |
| 479 |
) |
| 480 |
|
| 481 |
async def test_aclose_stops_accepting_connections(self): |
| 482 |
"""Server stops accepting connections.""" |
| 483 |
|
| 484 |
async def close_server(server): |
| 485 |
await server.aclose(close_connections=False) |
| 486 |
|
| 487 |
async with run_server() as server: |
| 488 |
# Connect a client and disable close_connections to delay closing. |
| 489 |
uri = get_uri(server) |
| 490 |
async with connect(uri): |
| 491 |
self.nursery.start_soon(close_server, server) |
| 492 |
await trio.testing.wait_all_tasks_blocked() |
| 493 |
|
| 494 |
# Server cannot receive new connections. |
| 495 |
with self.assertRaises(OSError): |
| 496 |
async with connect(uri): |
| 497 |
self.fail("did not raise") |
| 498 |
|
| 499 |
async def test_aclose_rejects_connecting_connections(self): |
| 500 |
"""Server rejects connecting connections with HTTP 503.""" |
| 501 |
|
| 502 |
async def process_request(ws, _request): |
| 503 |
while not ws.server.closing: |
| 504 |
await trio.sleep(0) # pragma: no cover |
| 505 |
|
| 506 |
async def close_server(server): |
| 507 |
await trio.sleep(2 * MS) |
| 508 |
await server.aclose() |
| 509 |
|
| 510 |
async with run_server(process_request=process_request) as server: |
| 511 |
self.nursery.start_soon(close_server, server) |
| 512 |
with self.assertRaises(InvalidStatus) as raised: |
| 513 |
async with connect(get_uri(server)): |
| 514 |
self.fail("did not raise") |
| 515 |
|
| 516 |
self.assertEqual( |
| 517 |
str(raised.exception), |
| 518 |
"server rejected WebSocket connection: HTTP 503", |
| 519 |
) |
| 520 |
|
| 521 |
async def test_aclose_closes_open_connections(self): |
| 522 |
"""Server closes open connections with close code 1001.""" |
| 523 |
async with run_server() as server: |
| 524 |
async with connect(get_uri(server)) as client: |
| 525 |
await server.aclose() |
| 526 |
with self.assertRaises(ConnectionClosedOK) as raised: |
| 527 |
await client.recv() |
| 528 |
self.assertEqual( |
| 529 |
str(raised.exception), |
| 530 |
"received 1001 (going away); then sent 1001 (going away)", |
| 531 |
) |
| 532 |
|
| 533 |
async def test_aclose_closes_open_connections_with_code_and_reason(self): |
| 534 |
"""Server closes open connections with custom code and reason.""" |
| 535 |
async with run_server() as server: |
| 536 |
async with connect(get_uri(server)) as client: |
| 537 |
await server.aclose(code=1012, reason="restarting") |
| 538 |
with self.assertRaises(ConnectionClosedError) as raised: |
| 539 |
await client.recv() |
| 540 |
self.assertEqual( |
| 541 |
str(raised.exception), |
| 542 |
"received 1012 (service restart) restarting; " |
| 543 |
"then sent 1012 (service restart) restarting", |
| 544 |
) |
| 545 |
|
| 546 |
async def test_aclose_keeps_connections_open(self): |
| 547 |
"""Server waits for client to close open connections.""" |
| 548 |
async with run_server() as server: |
| 549 |
server_closed = trio.Event() |
| 550 |
|
| 551 |
async def close_server(): |
| 552 |
await server.aclose(close_connections=False) |
| 553 |
server_closed.set() |
| 554 |
|
| 555 |
async with connect(get_uri(server)): |
| 556 |
self.nursery.start_soon(close_server) |
| 557 |
|
| 558 |
# The server waits for the client to close the connection. |
| 559 |
with self.assertRaises(trio.TooSlowError): |
| 560 |
with trio.fail_after(MS): |
| 561 |
await server_closed.wait() |
| 562 |
|
| 563 |
# Once the client closes the connection, the server terminates. |
| 564 |
with trio.fail_after(MS): |
| 565 |
await server_closed.wait() |
| 566 |
|
| 567 |
async def test_aclose_keeps_handlers_running(self): |
| 568 |
"""Server waits for connection handlers to terminate.""" |
| 569 |
async with run_server() as server: |
| 570 |
server_closed = trio.Event() |
| 571 |
|
| 572 |
async def close_server(): |
| 573 |
await server.aclose(close_connections=False) |
| 574 |
server_closed.set() |
| 575 |
|
| 576 |
async with connect(get_uri(server) + "/delay") as client: |
| 577 |
# Delay termination of connection handler. |
| 578 |
await client.send(str(3 * MS)) |
| 579 |
|
| 580 |
self.nursery.start_soon(close_server) |
| 581 |
|
| 582 |
# The server waits for the connection handler to terminate. |
| 583 |
with self.assertRaises(trio.TooSlowError): |
| 584 |
with trio.fail_after(2 * MS): |
| 585 |
await server_closed.wait() |
| 586 |
|
| 587 |
# Set a large timeout here, else the test becomes flaky. |
| 588 |
with trio.fail_after(5 * MS): |
| 589 |
await server_closed.wait() |
| 590 |
|
| 591 |
async def test_context_manager_closes_server(self): |
| 592 |
"""Server closes when exiting context manager.""" |
| 593 |
server = await self.nursery.start(serve, handler, 0) |
| 594 |
async with server: |
| 595 |
self.assertFalse(server.handlers_waiter.is_set()) |
| 596 |
|
| 597 |
self.assertTrue(server.handlers_waiter.is_set()) |
| 598 |
|
| 599 |
async def test_listeners(self): |
| 600 |
"""Server provides a listeners attribute.""" |
| 601 |
async with run_server() as server: |
| 602 |
sock = server.listeners[0].socket |
| 603 |
self.assertIsInstance(sock.fileno(), int) |
| 604 |
|
| 605 |
|
| 606 |
SSL_OBJECT = "ws.stream._ssl_object" |
| 607 |
|
| 608 |
|
| 609 |
class SecureServerTests(EvalShellMixin, IsolatedTrioTestCase): |
| 610 |
async def test_connection(self): |
| 611 |
"""Server receives secure connection from client.""" |
| 612 |
async with run_server(ssl=SERVER_CONTEXT) as server: |
| 613 |
async with connect(get_uri(server), ssl=CLIENT_CONTEXT) as client: |
| 614 |
await self.assertEval(client, "ws.protocol.state.name", "OPEN") |
| 615 |
await self.assertEval(client, f"{SSL_OBJECT}.version()[:3]", "TLS") |
| 616 |
|
| 617 |
async def test_timeout_during_tls_handshake(self): |
| 618 |
"""Server times out before receiving TLS handshake request from client.""" |
| 619 |
async with run_server(ssl=SERVER_CONTEXT, open_timeout=MS) as server: |
| 620 |
stream = await trio.open_tcp_stream(*get_host_port(server)) |
| 621 |
try: |
| 622 |
# Wait for the server to close the connection. |
| 623 |
self.assertEqual(await stream.receive_some(4096), b"") |
| 624 |
finally: |
| 625 |
await stream.aclose() |
| 626 |
|
| 627 |
async def test_connection_closed_during_tls_handshake(self): |
| 628 |
"""Server reads EOF before receiving TLS handshake request from client.""" |
| 629 |
async with run_server(ssl=SERVER_CONTEXT) as server: |
| 630 |
stream = await trio.open_tcp_stream(*get_host_port(server)) |
| 631 |
await stream.aclose() |
| 632 |
|
| 633 |
|
| 634 |
class ServerUsageErrorsTests(IsolatedTrioTestCase): |
| 635 |
async def test_missing_port(self): |
| 636 |
"""Server requires port.""" |
| 637 |
with self.assertRaises(ValueError) as raised: |
| 638 |
await serve(handler, None) |
| 639 |
self.assertEqual( |
| 640 |
str(raised.exception), |
| 641 |
"port is required when listeners is not provided", |
| 642 |
) |
| 643 |
|
| 644 |
async def test_port_and_listeners(self): |
| 645 |
"""Server rejects port when listeners is provided.""" |
| 646 |
listeners = await trio.open_tcp_listeners(0) |
| 647 |
try: |
| 648 |
with self.assertRaises(ValueError) as raised: |
| 649 |
await serve(handler, port=0, listeners=listeners) |
| 650 |
self.assertEqual( |
| 651 |
str(raised.exception), |
| 652 |
"port is incompatible with listeners", |
| 653 |
) |
| 654 |
finally: |
| 655 |
for listener in listeners: |
| 656 |
await listener.aclose() |
| 657 |
|
| 658 |
async def test_host_and_listeners(self): |
| 659 |
"""Server rejects host when listeners is provided.""" |
| 660 |
listeners = await trio.open_tcp_listeners(0) |
| 661 |
try: |
| 662 |
with self.assertRaises(ValueError) as raised: |
| 663 |
await serve(handler, host="localhost", listeners=listeners) |
| 664 |
self.assertEqual( |
| 665 |
str(raised.exception), |
| 666 |
"host is incompatible with listeners", |
| 667 |
) |
| 668 |
finally: |
| 669 |
for listener in listeners: |
| 670 |
await listener.aclose() |
| 671 |
|
| 672 |
async def test_backlog_and_listeners(self): |
| 673 |
"""Server rejects backlog when listeners is provided.""" |
| 674 |
listeners = await trio.open_tcp_listeners(0) |
| 675 |
try: |
| 676 |
with self.assertRaises(ValueError) as raised: |
| 677 |
await serve(handler, backlog=65535, listeners=listeners) |
| 678 |
self.assertEqual( |
| 679 |
str(raised.exception), |
| 680 |
"backlog is incompatible with listeners", |
| 681 |
) |
| 682 |
finally: |
| 683 |
for listener in listeners: |
| 684 |
await listener.aclose() |
| 685 |
|
| 686 |
async def test_invalid_subprotocol(self): |
| 687 |
"""Server rejects single value of subprotocols.""" |
| 688 |
with self.assertRaises(TypeError) as raised: |
| 689 |
await serve(handler, subprotocols="chat") |
| 690 |
self.assertEqual( |
| 691 |
str(raised.exception), |
| 692 |
"subprotocols must be a list, not a str", |
| 693 |
) |
| 694 |
|
| 695 |
async def test_unsupported_compression(self): |
| 696 |
"""Server rejects incorrect value of compression.""" |
| 697 |
with self.assertRaises(ValueError) as raised: |
| 698 |
await serve(handler, compression=False) |
| 699 |
self.assertEqual( |
| 700 |
str(raised.exception), |
| 701 |
"unsupported compression: False", |
| 702 |
) |
| 703 |
|
| 704 |
|
| 705 |
class BasicAuthTests(EvalShellMixin, IsolatedTrioTestCase): |
| 706 |
async def test_valid_authorization(self): |
| 707 |
"""basic_auth authenticates client with HTTP Basic Authentication.""" |
| 708 |
async with run_server( |
| 709 |
process_request=basic_auth(credentials=("hello", "iloveyou")), |
| 710 |
) as server: |
| 711 |
async with connect( |
| 712 |
get_uri(server), |
| 713 |
additional_headers={"Authorization": "Basic aGVsbG86aWxvdmV5b3U="}, |
| 714 |
) as client: |
| 715 |
await self.assertEval(client, "ws.username", "hello") |
| 716 |
|
| 717 |
async def test_missing_authorization(self): |
| 718 |
"""basic_auth rejects client without credentials.""" |
| 719 |
async with run_server( |
| 720 |
process_request=basic_auth(credentials=("hello", "iloveyou")), |
| 721 |
) as server: |
| 722 |
with self.assertRaises(InvalidStatus) as raised: |
| 723 |
async with connect(get_uri(server)): |
| 724 |
self.fail("did not raise") |
| 725 |
self.assertEqual( |
| 726 |
str(raised.exception), |
| 727 |
"server rejected WebSocket connection: HTTP 401", |
| 728 |
) |
| 729 |
|
| 730 |
async def test_unsupported_authorization(self): |
| 731 |
"""basic_auth rejects client with unsupported credentials.""" |
| 732 |
async with run_server( |
| 733 |
process_request=basic_auth(credentials=("hello", "iloveyou")), |
| 734 |
) as server: |
| 735 |
with self.assertRaises(InvalidStatus) as raised: |
| 736 |
async with connect( |
| 737 |
get_uri(server), |
| 738 |
additional_headers={"Authorization": "Negotiate ..."}, |
| 739 |
): |
| 740 |
self.fail("did not raise") |
| 741 |
self.assertEqual( |
| 742 |
str(raised.exception), |
| 743 |
"server rejected WebSocket connection: HTTP 401", |
| 744 |
) |
| 745 |
|
| 746 |
async def test_authorization_with_unknown_username(self): |
| 747 |
"""basic_auth rejects client with unknown username.""" |
| 748 |
async with run_server( |
| 749 |
process_request=basic_auth(credentials=("hello", "iloveyou")), |
| 750 |
) as server: |
| 751 |
with self.assertRaises(InvalidStatus) as raised: |
| 752 |
async with connect( |
| 753 |
get_uri(server), |
| 754 |
additional_headers={"Authorization": "Basic YnllOnlvdWxvdmVtZQ=="}, |
| 755 |
): |
| 756 |
self.fail("did not raise") |
| 757 |
self.assertEqual( |
| 758 |
str(raised.exception), |
| 759 |
"server rejected WebSocket connection: HTTP 401", |
| 760 |
) |
| 761 |
|
| 762 |
async def test_authorization_with_incorrect_password(self): |
| 763 |
"""basic_auth rejects client with incorrect password.""" |
| 764 |
async with run_server( |
| 765 |
process_request=basic_auth(credentials=("hello", "changeme")), |
| 766 |
) as server: |
| 767 |
with self.assertRaises(InvalidStatus) as raised: |
| 768 |
async with connect( |
| 769 |
get_uri(server), |
| 770 |
additional_headers={"Authorization": "Basic aGVsbG86aWxvdmV5b3U="}, |
| 771 |
): |
| 772 |
self.fail("did not raise") |
| 773 |
self.assertEqual( |
| 774 |
str(raised.exception), |
| 775 |
"server rejected WebSocket connection: HTTP 401", |
| 776 |
) |
| 777 |
|
| 778 |
async def test_list_of_credentials(self): |
| 779 |
"""basic_auth accepts a list of hard coded credentials.""" |
| 780 |
async with run_server( |
| 781 |
process_request=basic_auth( |
| 782 |
credentials=[ |
| 783 |
("hello", "iloveyou"), |
| 784 |
("bye", "youloveme"), |
| 785 |
] |
| 786 |
), |
| 787 |
) as server: |
| 788 |
async with connect( |
| 789 |
get_uri(server), |
| 790 |
additional_headers={"Authorization": "Basic YnllOnlvdWxvdmVtZQ=="}, |
| 791 |
) as client: |
| 792 |
await self.assertEval(client, "ws.username", "bye") |
| 793 |
|
| 794 |
async def test_check_credentials_function(self): |
| 795 |
"""basic_auth accepts a check_credentials function.""" |
| 796 |
|
| 797 |
def check_credentials(username, password): |
| 798 |
self.assertEqual(username, "hello") |
| 799 |
return hmac.compare_digest(password, "iloveyou") |
| 800 |
|
| 801 |
async with run_server( |
| 802 |
process_request=basic_auth(check_credentials=check_credentials), |
| 803 |
) as server: |
| 804 |
async with connect( |
| 805 |
get_uri(server), |
| 806 |
additional_headers={"Authorization": "Basic aGVsbG86aWxvdmV5b3U="}, |
| 807 |
) as client: |
| 808 |
await self.assertEval(client, "ws.username", "hello") |
| 809 |
|
| 810 |
async def test_check_credentials_coroutine(self): |
| 811 |
"""basic_auth accepts a check_credentials coroutine.""" |
| 812 |
|
| 813 |
async def check_credentials(username, password): |
| 814 |
self.assertEqual(username, "hello") |
| 815 |
return hmac.compare_digest(password, "iloveyou") |
| 816 |
|
| 817 |
async with run_server( |
| 818 |
process_request=basic_auth(check_credentials=check_credentials), |
| 819 |
) as server: |
| 820 |
async with connect( |
| 821 |
get_uri(server), |
| 822 |
additional_headers={"Authorization": "Basic aGVsbG86aWxvdmV5b3U="}, |
| 823 |
) as client: |
| 824 |
await self.assertEval(client, "ws.username", "hello") |
| 825 |
|
| 826 |
async def test_without_credentials_or_check_credentials(self): |
| 827 |
"""basic_auth requires either credentials or check_credentials.""" |
| 828 |
with self.assertRaises(ValueError) as raised: |
| 829 |
basic_auth() |
| 830 |
self.assertEqual( |
| 831 |
str(raised.exception), |
| 832 |
"provide either credentials or check_credentials", |
| 833 |
) |
| 834 |
|
| 835 |
async def test_with_credentials_and_check_credentials(self): |
| 836 |
"""basic_auth requires only one of credentials and check_credentials.""" |
| 837 |
with self.assertRaises(ValueError) as raised: |
| 838 |
basic_auth( |
| 839 |
credentials=("hello", "iloveyou"), |
| 840 |
check_credentials=lambda: False, # pragma: no cover |
| 841 |
) |
| 842 |
self.assertEqual( |
| 843 |
str(raised.exception), |
| 844 |
"provide either credentials or check_credentials", |
| 845 |
) |
| 846 |
|
| 847 |
async def test_bad_credentials(self): |
| 848 |
"""basic_auth receives an unsupported credentials argument.""" |
| 849 |
with self.assertRaises(TypeError) as raised: |
| 850 |
basic_auth(credentials=42) |
| 851 |
self.assertEqual( |
| 852 |
str(raised.exception), |
| 853 |
"invalid credentials argument: 42", |
| 854 |
) |
| 855 |
|
| 856 |
async def test_bad_list_of_credentials(self): |
| 857 |
"""basic_auth receives an unsupported credentials argument.""" |
| 858 |
with self.assertRaises(TypeError) as raised: |
| 859 |
basic_auth(credentials=[42]) |
| 860 |
self.assertEqual( |
| 861 |
str(raised.exception), |
| 862 |
"invalid credentials argument: [42]", |
| 863 |
) |