From 328f821d18ecf6cbe6a1020cfc855cd71f9f1a7e Mon Sep 17 00:00:00 2001 From: Yudeeswaran V Date: Thu, 15 Oct 2026 12:10:59 +0530 Subject: [PATCH 1/2] MAINT: Bound WebSocket initialization receive time --- pyrit/prompt_target/websocket_target.py | 23 +++---- .../target/test_websocket_target.py | 67 +++++++++++++++++++ 2 files changed, 78 insertions(+), 12 deletions(-) diff --git a/pyrit/prompt_target/websocket_target.py b/pyrit/prompt_target/websocket_target.py index 613aef456b..e81a379ebd 100644 --- a/pyrit/prompt_target/websocket_target.py +++ b/pyrit/prompt_target/websocket_target.py @@ -72,7 +72,8 @@ def __init__( reconnect without this callback because the target cannot infer the service-specific protocol. The callback must consume all frames produced by its restoration exchange. discard_initial_messages (int): Number of parsed messages to discard after initialization. - response_timeout_seconds (float): Maximum time to wait for a parsed response. + response_timeout_seconds (float): Maximum time to wait for a complete parsed response. During + initialization, one separate timeout budget is shared across all discarded initial messages. existing_convo (dict[str, ClientConnection] | None): Pre-initialized connections by PyRIT conversation ID. max_requests_per_minute (int | None): Maximum number of requests per minute. @@ -349,17 +350,15 @@ async def _initialize_connection_async(self, *, websocket: ClientConnection) -> for initialization_string in self._initialization_strings: await websocket.send(initialization_string) - for _ in range(self._discard_initial_messages): - try: - await asyncio.wait_for( - self._receive_message_async(websocket=websocket), - timeout=self._response_timeout_seconds, - ) - except TimeoutError: - raise TimeoutError( - "Timed out waiting for an initial WebSocket message after " - f"{self._response_timeout_seconds} seconds." - ) from None + try: + async with asyncio.timeout(self._response_timeout_seconds): + for _ in range(self._discard_initial_messages): + await self._receive_message_async(websocket=websocket) + except TimeoutError: + raise TimeoutError( + "Timed out waiting for an initial WebSocket message after " + f"{self._response_timeout_seconds} seconds." + ) from None async def _receive_message_async(self, *, websocket: ClientConnection) -> str: async for message in websocket: diff --git a/tests/unit/prompt_target/target/test_websocket_target.py b/tests/unit/prompt_target/target/test_websocket_target.py index 2b6358b3c0..da3d21138c 100644 --- a/tests/unit/prompt_target/target/test_websocket_target.py +++ b/tests/unit/prompt_target/target/test_websocket_target.py @@ -685,6 +685,73 @@ async def wait_forever(*, websocket: ClientConnection) -> str: await target._initialize_connection_async(websocket=connection) +async def test_initialize_connection_async_uses_one_timeout_for_discarded_messages( + response_parser: Callable[[str | bytes], str | None], + message_builder: Callable[[str], str | bytes], + sqlite_instance: SQLiteMemory, +) -> None: + target = WebsocketTarget( + endpoint="wss://example.com", + protocol_identifier="test-protocol", + initialization_strings=[], + response_parser=response_parser, + message_builder=message_builder, + discard_initial_messages=2, + response_timeout_seconds=0.5, + ) + connection = AsyncMock(spec=ClientConnection) + + async def receive_message(*, websocket: ClientConnection) -> str: + await asyncio.sleep(0.35) + return "initial message" + + with patch.object(target, "_receive_message_async", side_effect=receive_message) as receive: + with pytest.raises(TimeoutError, match="Timed out waiting for an initial WebSocket message"): + await target._initialize_connection_async(websocket=connection) + + assert receive.await_count == 2 + + +async def test_get_or_create_connection_async_cancellation_during_initialization_closes_connection( + response_parser: Callable[[str | bytes], str | None], + message_builder: Callable[[str], str | bytes], + sqlite_instance: SQLiteMemory, +) -> None: + target = WebsocketTarget( + endpoint="wss://example.com", + protocol_identifier="test-protocol", + initialization_strings=[], + response_parser=response_parser, + message_builder=message_builder, + discard_initial_messages=1, + ) + connection = AsyncMock(spec=ClientConnection) + receive_started = asyncio.Event() + + async def wait_for_message(*, websocket: ClientConnection) -> str: + receive_started.set() + await asyncio.Event().wait() + + with ( + patch.object(target, "_connect_async", new_callable=AsyncMock, return_value=connection), + patch.object(target, "_receive_message_async", side_effect=wait_for_message), + ): + task = asyncio.create_task( + target._get_or_create_connection_async( + conversation_id="conversation", + conversation_history=[], + ) + ) + await receive_started.wait() + task.cancel() + + with pytest.raises(asyncio.CancelledError): + await task + + connection.close.assert_awaited_once() + assert target._existing_conversation == {} + + async def test_reset_conversation_async_removes_connection(websocket_target: WebsocketTarget) -> None: connection = AsyncMock(spec=ClientConnection) websocket_target._existing_conversation["conversation"] = connection From ef0296f0c9baca8b36a9ba8c6534e3046cb58c09 Mon Sep 17 00:00:00 2001 From: Roman Lutz Date: Fri, 16 Oct 2026 00:11:18 -0700 Subject: [PATCH 2/2] Fix WebSocket initialization regression tests Use a controlled clock to verify the shared receive deadline without wall-clock timing flakes, and fix the cancellation helper return type. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: a425452c-c9cd-4304-ad54-a571e79a0488 --- pyrit/prompt_target/websocket_target.py | 3 +-- .../target/test_websocket_target.py | 16 +++++++++++++--- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/pyrit/prompt_target/websocket_target.py b/pyrit/prompt_target/websocket_target.py index e81a379ebd..07f2142014 100644 --- a/pyrit/prompt_target/websocket_target.py +++ b/pyrit/prompt_target/websocket_target.py @@ -356,8 +356,7 @@ async def _initialize_connection_async(self, *, websocket: ClientConnection) -> await self._receive_message_async(websocket=websocket) except TimeoutError: raise TimeoutError( - "Timed out waiting for an initial WebSocket message after " - f"{self._response_timeout_seconds} seconds." + f"Timed out waiting for an initial WebSocket message after {self._response_timeout_seconds} seconds." ) from None async def _receive_message_async(self, *, websocket: ClientConnection) -> str: diff --git a/tests/unit/prompt_target/target/test_websocket_target.py b/tests/unit/prompt_target/target/test_websocket_target.py index da3d21138c..ec268e4b31 100644 --- a/tests/unit/prompt_target/target/test_websocket_target.py +++ b/tests/unit/prompt_target/target/test_websocket_target.py @@ -700,12 +700,21 @@ async def test_initialize_connection_async_uses_one_timeout_for_discarded_messag response_timeout_seconds=0.5, ) connection = AsyncMock(spec=ClientConnection) + loop = asyncio.get_running_loop() + current_time = loop.time() - async def receive_message(*, websocket: ClientConnection) -> str: - await asyncio.sleep(0.35) + async def receive_message_async(*, websocket: ClientConnection) -> str: + nonlocal current_time + current_time += 0.35 + # Let the loop dispatch any deadline reached by the simulated receive. + await asyncio.sleep(0) + await asyncio.sleep(0) return "initial message" - with patch.object(target, "_receive_message_async", side_effect=receive_message) as receive: + with ( + patch.object(loop, "time", side_effect=lambda: current_time), + patch.object(target, "_receive_message_async", side_effect=receive_message_async) as receive, + ): with pytest.raises(TimeoutError, match="Timed out waiting for an initial WebSocket message"): await target._initialize_connection_async(websocket=connection) @@ -731,6 +740,7 @@ async def test_get_or_create_connection_async_cancellation_during_initialization async def wait_for_message(*, websocket: ClientConnection) -> str: receive_started.set() await asyncio.Event().wait() + return "unreachable" with ( patch.object(target, "_connect_async", new_callable=AsyncMock, return_value=connection),