diff --git a/pyrit/prompt_target/websocket_target.py b/pyrit/prompt_target/websocket_target.py index 715711a84a..5fb69cf97c 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. @@ -354,17 +355,14 @@ 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( + 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: 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 2dd3a23438..c56a4c9084 100644 --- a/tests/unit/prompt_target/target/test_websocket_target.py +++ b/tests/unit/prompt_target/target/test_websocket_target.py @@ -738,6 +738,83 @@ 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) + loop = asyncio.get_running_loop() + current_time = loop.time() + + 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(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) + + 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() + return "unreachable" + + 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