Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
import uuid
from collections.abc import Callable, Mapping
from queue import Empty, Queue
from typing import TYPE_CHECKING, SupportsIndex, overload
from urllib.parse import quote, urlparse
from typing import TYPE_CHECKING, Final, SupportsIndex, overload
from urllib.parse import urlparse

import httpx
import websockets
Expand Down Expand Up @@ -65,6 +65,8 @@

LEGACY_CONVERSATIONS_PATH = "/api/conversations"
FATAL_WS_CLOSE_CODES = frozenset({4001, 4004})
_WEBSOCKET_AUTH_TYPE: Final = "auth"
_WEBSOCKET_SESSION_API_KEY_FIELD: Final = "session_api_key"


def _agent_kind_mismatch_message(conversation_id: ConversationID) -> str:
Expand Down Expand Up @@ -214,15 +216,20 @@ async def _client_loop(self) -> None:
base = f"{ws_scheme}://{parsed.netloc}{parsed.path.rstrip('/')}"
ws_url = f"{base}/sockets/events/{self.conversation_id}"

# Add API key as query parameter if provided
if self.api_key:
ws_url += f"?session_api_key={quote(self.api_key, safe='')}"

delay = 1.0
has_connected = False
while not self._stop.is_set():
try:
async with websockets.connect(ws_url) as ws:
if self.api_key:
await ws.send(
json.dumps(
{
"type": _WEBSOCKET_AUTH_TYPE,
_WEBSOCKET_SESSION_API_KEY_FIELD: self.api_key,
}
)
)
delay = 1.0
connection_ready = False
async for message in ws:
Expand Down
39 changes: 38 additions & 1 deletion tests/cross/test_remote_conversation_live_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ def live_server_env(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
import_modules: str | None = None,
session_api_keys: list[str] | None = None,
) -> Generator[dict]:
"""Launch a real FastAPI server backed by temp workspace and conversations.

Expand Down Expand Up @@ -97,7 +98,7 @@ def live_server_env(
)

cfg = {
"session_api_keys": [], # disable auth for tests
"session_api_keys": session_api_keys or [],
"conversations_path": str(conversations_path),
"workspace_path": str(workspace_path),
}
Expand Down Expand Up @@ -202,6 +203,20 @@ def server_env(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Generator[dic
yield env


@pytest.fixture
def authenticated_server_env(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> Generator[dict]:
api_key = "test-websocket-auth-key"
with live_server_env(
tmp_path,
monkeypatch,
session_api_keys=[api_key],
) as env:
env["api_key"] = api_key
yield env


@pytest.fixture
def patched_llm(monkeypatch: pytest.MonkeyPatch) -> None:
"""Patch LLM.completion to a deterministic assistant message response."""
Expand Down Expand Up @@ -258,6 +273,28 @@ async def fake_acompletion(self, messages, tools=None, **kwargs): # type: ignor
monkeypatch.setattr(LLM, "acompletion", fake_acompletion, raising=True)


def test_remote_conversation_websocket_first_message_auth(
authenticated_server_env,
monkeypatch: pytest.MonkeyPatch,
):
monkeypatch.setenv("OPENHANDS_REMOTE_WS_READY_TIMEOUT", "2")
agent = Agent(
llm=LLM(model="gpt-4o-mini", api_key=SecretStr("test")),
tools=[],
)
workspace = RemoteWorkspace(
host=authenticated_server_env["host"],
working_dir="/tmp/workspace/project",
api_key=authenticated_server_env["api_key"],
)

conversation: RemoteConversation = Conversation(agent=agent, workspace=workspace)
try:
assert conversation.id
finally:
conversation.close()


def test_preloaded_custom_tool_resolves_in_live_server(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
):
Expand Down
65 changes: 55 additions & 10 deletions tests/sdk/conversation/remote/test_websocket_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,21 +131,46 @@ def test_callback(event):
assert callback_events[0].id == mock_event.id


def test_websocket_client_url_encodes_api_key():
"""Test that API key special characters are URL-encoded in the WebSocket URL."""
@pytest.mark.parametrize(
("api_key", "expected_messages"),
[
pytest.param(
"sk-oh-" + "a" * 64,
[
json.dumps(
{
"type": "auth",
"session_api_key": "sk-oh-" + "a" * 64,
}
)
],
id="with-api-key",
),
pytest.param(None, [], id="without-api-key"),
],
)
def test_websocket_client_authenticates_outside_url(api_key, expected_messages):
captured_urls = []
sent_messages = []

class _MockWebSocket:
async def send(self, message):
sent_messages.append(message)

def __aiter__(self):
return self

async def __anext__(self):
client._stop.set()
raise StopAsyncIteration

class _MockAsyncContextManager:
def __init__(self, url):
self.url = url

async def __aenter__(self):
captured_urls.append(self.url)
raise websockets.exceptions.ConnectionClosed(
rcvd=websockets.frames.Close(4001, "test"),
sent=websockets.frames.Close(4001, "test"),
rcvd_then_sent=False,
)
return _MockWebSocket()

async def __aexit__(self, exc_type, exc, tb):
return False
Expand All @@ -158,7 +183,7 @@ def __call__(self, url, *args, **kwargs):
host="http://localhost:8000",
conversation_id="test-conv-id",
callback=lambda event: None,
api_key="1+FYh/SRE=ds 8Q",
api_key=api_key,
)

with patch(
Expand All @@ -168,7 +193,8 @@ def __call__(self, url, *args, **kwargs):
asyncio.run(client._client_loop())

assert len(captured_urls) == 1
assert "session_api_key=1%2BFYh%2FSRE%3Dds%208Q" in captured_urls[0]
assert captured_urls[0] == ("ws://localhost:8000/sockets/events/test-conv-id")
assert sent_messages == expected_messages


def _state_update_payload(event_id: str) -> str:
Expand All @@ -193,9 +219,13 @@ def _connection_closed(code: int) -> websockets.exceptions.ConnectionClosed:


class _MockWebSocket:
def __init__(self, messages, close_code: int):
def __init__(self, messages, close_code: int, sent_messages=None):
self._messages = list(messages)
self._close_code = close_code
self._sent_messages = sent_messages if sent_messages is not None else []

async def send(self, message):
self._sent_messages.append(message)

def __aiter__(self):
return self
Expand All @@ -221,6 +251,8 @@ def test_websocket_client_retries_after_retryable_connection_closed():
"""Test that transient WebSocket closures reconnect instead of exiting."""
connect_calls = 0
callback_events = []
sent_per_connection = []
retry_delays = []

def callback(event):
callback_events.append(event)
Expand All @@ -231,20 +263,25 @@ class _MockConnect:
def __call__(self, url, *args, **kwargs):
nonlocal connect_calls
connect_calls += 1
sent_messages = []
sent_per_connection.append(sent_messages)
return _MockWebSocketContext(
_MockWebSocket(
[_state_update_payload(f"state-{connect_calls}")],
close_code=1000,
sent_messages=sent_messages,
)
)

client = WebSocketCallbackClient(
host="http://localhost:8000",
conversation_id="test-conv-id",
callback=callback,
api_key="sk-oh-" + "b" * 64,
)

async def no_sleep(delay):
retry_delays.append(delay)
return None

client._sleep_before_retry = no_sleep
Expand All @@ -257,6 +294,14 @@ async def no_sleep(delay):

assert connect_calls == 2
assert [event.id for event in callback_events] == ["state-1", "state-2"]
expected_auth = json.dumps(
{
"type": "auth",
"session_api_key": client.api_key,
}
)
assert sent_per_connection == [[expected_auth], [expected_auth]]
assert retry_delays == [1.0, 1.0]


@pytest.mark.parametrize("close_code", [4001, 4004])
Expand Down
Loading