From 32250f6f9563128408cf1f8056ab4286d1733f48 Mon Sep 17 00:00:00 2001 From: imSp4rky Date: Fri, 27 Nov 2026 18:05:34 -0700 Subject: [PATCH] feat(session): open a websocket on the rnet session --- docs/dev/creating-a-service.md | 6 +- tests/core/test_session_websocket.py | 114 +++++++++++++++++++++++++++ unshackle/core/session.py | 22 ++++++ 3 files changed, 141 insertions(+), 1 deletion(-) create mode 100644 tests/core/test_session_websocket.py diff --git a/docs/dev/creating-a-service.md b/docs/dev/creating-a-service.md index 2cafbe00..811e5247 100644 --- a/docs/dev/creating-a-service.md +++ b/docs/dev/creating-a-service.md @@ -171,7 +171,11 @@ class TrackRequest: streaming platform blocks you on TLS fingerprint alone, override it to return `session("Chrome131")` (any `rnet.Impersonate` preset). `RnetSession` is a drop-in `requests.Session` replacement (same `.get`/`.post`/cookie-jar - interface), so nothing else in the service changes. If instead you need + interface), so nothing else in the service changes. For a websocket, + `self.session.websocket(url, headers)` opens one with the same preset and + proxy, and sends only the headers you give. Its `recv()` has no read + timeout and gives each ping to you, so the thread that reads answers the + pings and closes the socket. If instead you need specific SSL *cipher* behaviour, mount `unshackle.core.utils.sslciphers.SSLCiphers` onto a plain `requests.Session`. diff --git a/tests/core/test_session_websocket.py b/tests/core/test_session_websocket.py new file mode 100644 index 00000000..87ed7acf --- /dev/null +++ b/tests/core/test_session_websocket.py @@ -0,0 +1,114 @@ +"""A websocket opened through the rnet session: its handshake, its frames and its debug entry.""" + +from __future__ import annotations + +import asyncio +from collections.abc import Callable +from pathlib import Path +from typing import Any + +import pytest +import rnet +from aiohttp import web +from aiohttp.test_utils import TestServer + +from tests.core.test_request_record import closed_port +from tests.core.test_request_record import debug_log as debug_log +from tests.core.test_request_record import records +from unshackle.core.session import RnetSession + +pytestmark = pytest.mark.unit + +DEADLINE = 10.0 +GIVEN = {"User-Agent": "music/9 app/14", "Authorization": "Bearer example"} +SESSION = {"User-Agent": "session-agent", "Connection": "Keep-Alive", "X-Session": "1"} + + +async def call(function: Callable[..., Any], *args: Any) -> Any: + """Run a blocking call off the loop, with a deadline, so a regression fails instead of hanging.""" + return await asyncio.wait_for(asyncio.to_thread(function, *args), DEADLINE) + + +class Seen: + """What the loopback server got: the raw lines of the handshake, and an event set at the first pong.""" + + def __init__(self) -> None: + self.lines: list[tuple[bytes, bytes]] = [] + self.pong = asyncio.Event() + + async def handle(self, request: web.Request) -> web.WebSocketResponse: + self.lines = list(request.raw_headers) + socket = web.WebSocketResponse(autoping=False) + await socket.prepare(request) + await socket.send_str("first") + if request.path == "/ping": + await socket.ping(b"probe") + async for message in socket: + if message.type == web.WSMsgType.PONG: + self.pong.set() + return socket + + +async def serve(seen: Seen) -> tuple[TestServer, Callable[[str], str]]: + app = web.Application() + app.router.add_get("/{tail:.*}", seen.handle) + server = TestServer(app) + await server.start_server() + return server, lambda path: str(server.make_url(path)).replace("http://", "ws://", 1) + + +async def test_the_handshake_carries_the_headers_given_and_none_of_the_session() -> None: + seen = Seen() + server, url = await serve(seen) + session = RnetSession() + session.headers.update(SESSION) + + socket = await call(session.websocket, url("/"), GIVEN) + first = await call(socket.recv) + await call(socket.close) + await server.close() + + names = [name.decode() for name, _ in seen.lines] + values = {name.decode(): value for name, value in seen.lines} + assert socket.status == 101 and first.text == "first" + assert names[:2] == ["User-Agent", "Authorization"] + assert {"upgrade", "connection", "sec-websocket-key", "sec-websocket-version", "host"} <= { + name.lower() for name in names + } + assert values["User-Agent"] == b"music/9 app/14" and "x-session" not in {name.lower() for name in names} + assert not set(SESSION.values()) & set(values.values()) + + +async def test_a_ping_comes_to_the_caller_and_a_pong_goes_back() -> None: + seen = Seen() + server, url = await serve(seen) + + socket = await call(RnetSession().websocket, url("/ping"), GIVEN) + first = await call(socket.recv) + ping = await call(socket.recv) + await call(socket.send, rnet.Message.from_pong(ping.ping or b"")) + await asyncio.wait_for(seen.pong.wait(), DEADLINE) + await call(socket.close) + await server.close() + + assert first.text == "first" + assert ping.ping == b"probe" + + +async def test_each_handshake_writes_one_debug_entry(debug_log: Path) -> None: + server, url = await serve(Seen()) + session = RnetSession() + + socket = await call(session.websocket, url("/"), GIVEN) + await call(socket.recv) + await call(socket.close) + await server.close() + with pytest.raises(rnet.ConnectionError): + await call(session.websocket, closed_port().replace("http://", "ws://", 1), GIVEN) + + assert [ + (entry["request"]["method"], entry["response"]["status"], entry["failure"]) for entry in records(debug_log) + ] == [ + ("GET", 101, None), + ("GET", None, "ConnectionError"), + ] diff --git a/unshackle/core/session.py b/unshackle/core/session.py index 197f1dc1..fc491782 100644 --- a/unshackle/core/session.py +++ b/unshackle/core/session.py @@ -1229,6 +1229,28 @@ class RnetSession: def patch(self, url: str, **kwargs: Any) -> RnetResponse: return self.request("PATCH", url, **kwargs) + def websocket(self, url: str, headers: dict[str, Any] | None = None) -> rnet.BlockingWebSocket: + """Open a websocket at a ``ws://`` or ``wss://`` URL, with the TLS profile and the proxy of this HTTP session. + + A new rnet client makes the handshake with ``headers``, so the default headers of the HTTP session stay out of it. + """ + if run_proxy.watched and not self.proxy_exempt and not self._client_kwargs.get("proxies"): + try: + run_proxy.check(urlparse(url).hostname, sys._getframe(1)) + except Exception: # nosec B110 - the proxy check only warns, it must never fail a handshake + pass + record = config.debug_requests + started = time.monotonic() + try: + socket = rnet.BlockingClient(**self._client_kwargs).websocket(url, headers=dict(headers or {})) + except Exception as error: + if record: + record_request("GET", url, 1, duration=time.monotonic() - started, error=error) + raise + if record: + record_request("GET", url, 1, duration=time.monotonic() - started, status=socket.status) + return socket + def prepare_request(self, req: Request) -> Request: """Compatibility shim for services using prepared requests.""" # Merge session headers into request headers