Repository navigation
fix(security): authenticate WebSockets outside URLs - #4279
Conversation
Co-authored-by: openhands <openhands@all-hands.dev>
Python API breakage checks — ✅ PASSEDResult: ✅ PASSED |
REST API breakage checks (OpenAPI) — ✅ PASSEDResult: ✅ PASSED |
Coverage Report •
|
||||||||||||||||||||
all-hands-bot
left a comment
There was a problem hiding this comment.
✅ QA Report: PASS
Verified the SDK WebSocket client behavior with a real local WebSocket server: the PR removes session API keys from event-socket URLs and sends them as the first client frame.
Does this PR achieve its stated goal?
Yes. The stated goal was to keep session API keys out of WebSocket URLs while authenticating immediately after connect. On origin/main, the captured request path contained ?session_api_key=... and no first client frame arrived within 1s; on the PR branch, the request path was /sockets/events/qa-conversation and the first frame was {"type": "auth", "session_api_key": ...}. A no-api-key probe on the PR branch also connected with a clean URL and no unsolicited auth frame.
| Phase | Result |
|---|---|
| Environment Setup | ✅ make build completed and installed the editable workspace packages. |
| CI Status | |
| Functional Verification | ✅ Before/after WebSocket probe confirmed the security fix and the no-api-key edge case. |
Functional Verification
Test 1: WebSocket auth moves from URL query to first frame
Step 1 — Reproduce / establish baseline (without the fix):
Checked out origin/main and ran a local WebSocket capture probe:
git switch --detach origin/main
OPENHANDS_SUPPRESS_BANNER=1 uv run python - <<'PY'
# Started websockets.serve on localhost, instantiated WebSocketCallbackClient
# with api_key='sk-oh-' + 'a' * 64, captured ws.request.path and first ws.recv().
PYObserved:
{"first_client_frame": "<NO_CLIENT_FRAME_WITHIN_1.0S>", "request_path": "/sockets/events/qa-conversation?session_api_key=sk-oh-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}This confirms the bug exists on the base branch because credential material appears in the WebSocket request URL, which is the path/query layer commonly copied into reverse-proxy and access logs.
Step 2 — Apply the PR's changes:
Checked out fix-websocket-auth-frame at 45ca400558905ab1cd7c2692ab3c0439ff1eb423.
Step 3 — Re-run with the fix in place:
Ran the same local-server probe, plus the no-api-key edge case:
git switch fix-websocket-auth-frame
OPENHANDS_SUPPRESS_BANNER=1 uv run python - <<'PY'
# Same local WebSocket capture script; first with api_key, then with api_key=None.
PYObserved:
[
{
"api_key_supplied": true,
"first_client_frame": "{\"type\": \"auth\", \"session_api_key\": \"sk-oh-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}",
"request_path": "/sockets/events/qa-conversation"
},
{
"api_key_supplied": false,
"first_client_frame": "<NO_CLIENT_FRAME_WITHIN_1.0S>",
"request_path": "/sockets/events/qa-conversation"
}
]This confirms the fix works: with an API key, the URL is clean and the auth payload is the first client frame; without an API key, the client still connects with a clean URL and does not send an auth frame.
Issues Found
None.
This review was created by an AI agent (OpenHands) on behalf of the user.
all-hands-bot
left a comment
There was a problem hiding this comment.
✅ QA Report: PASS
Verified the SDK WebSocket client against a real local WebSocket endpoint: base leaked session_api_key in the URL, while this PR sends a clean URL and moves auth into the first client frame.
Does this PR achieve its stated goal?
Yes. The stated goal is to remove session_api_key from Python SDK WebSocket URLs while preserving authentication via the existing first-message auth payload. In before/after execution, the base branch connected to /sockets/events/...?...session_api_key=... and sent no first frame; the PR connected to /sockets/events/... and the first client frame decoded to {"type": "auth", "session_api_key": ...}. That confirms the credential is no longer exposed in the WebSocket URL and is sent outside the URL as intended.
| Phase | Result |
|---|---|
| Environment Setup | ✅ make build completed; dependencies installed and development environment ready. |
| CI Status | 🟡 GitHub reported 35 successful, 16 skipped, 1 pending, 0 failing checks at QA time. |
| Functional Verification | ✅ Real WebSocket capture verified clean URL + first-frame auth on the PR. |
Functional Verification
Test 1: WebSocket API key moves from URL query to first frame
I used a temporary QA script that starts a real local websockets.serve(...) endpoint, then instantiates the SDK WebSocketCallbackClient with a fake API key containing URL-sensitive characters: 1+FYh/SRE=ds 8Q. The server records the request path and waits for the first client frame.
Step 1 — Reproduce / establish baseline without the fix:
Ran:
git fetch origin main --quiet
git checkout --quiet origin/main
OPENHANDS_SUPPRESS_BANNER=1 uv run python /tmp/qa_ws_capture.pyOutput:
{"decoded_first_message": null, "first_message": null, "path": "/sockets/events/qa-ws-auth-conversation?session_api_key=sk-oh-qa-token-with-specials-1%2BFYh%2FSRE%3Dds%208Q"}This confirms the baseline bug: the fake credential is URL-encoded into the WebSocket request path, which is the data reverse proxies commonly log. The server also received no first client frame within the capture window.
Step 2 — Apply the PR changes:
Checked out the PR commit:
git checkout --quiet 45ca400558905ab1cd7c2692ab3c0439ff1eb423Step 3 — Re-run with the fix in place:
Ran the same capture script:
OPENHANDS_SUPPRESS_BANNER=1 uv run python /tmp/qa_ws_capture.pyOutput:
{"decoded_first_message": {"session_api_key": "sk-oh-qa-token-with-specials-1+FYh/SRE=ds 8Q", "type": "auth"}, "first_message": "{"type": "auth", "session_api_key": "sk-oh-qa-token-with-specials-1+FYh/SRE=ds 8Q"}", "path": "/sockets/events/qa-ws-auth-conversation"}This confirms the fix works: the WebSocket URL path is clean, and the auth payload is sent as the first client frame with the original API key preserved exactly, including special characters.
Issues Found
None.
This QA review was created by an AI agent (OpenHands) on behalf of the user.
Mutation-testing the new suiteI ran mutation testing against The rewritten
Exact-equality assertions on both What survives is everything about the loop the frame now lives inside:
1. Reconnects are not covered — and that's where auth now livesThe auth frame moved inside if self.api_key and not has_connected:
await ws.send(...)leaves the suite fully green, but in production every reconnect after a network blip would hit the server's first-message-auth path with no frame and get closed at the 10s deadline in
def test_websocket_client_reauthenticates_on_reconnect():
sent_per_connection = []
class _MockWebSocket:
def __init__(self):
self.sent = []
sent_per_connection.append(self.sent)
async def send(self, message):
self.sent.append(message)
def __aiter__(self):
return self
async def __anext__(self):
if len(sent_per_connection) >= 2:
client._stop.set()
raise StopAsyncIteration
raise websockets.exceptions.ConnectionClosed(
rcvd=websockets.frames.Close(1006, "boom"),
sent=None,
rcvd_then_sent=False,
)
# ... connect() returns a fresh _MockWebSocket each call ...
assert len(sent_per_connection) == 2
expected = json.dumps({"type": "auth", "session_api_key": client.api_key})
assert sent_per_connection == [[expected], [expected]] # re-auth on every connect2. The
|
Co-authored-by: openhands <openhands@all-hands.dev>
|
Addressed in 82f6714. The unit coverage now asserts both keyed and keyless connections, verifies auth is sent on every reconnect, and pins the backoff reset to 1 second after each successful connection. The reconnect mock now accepts sends, so removing the key guard fails diagnostically instead of hanging. I also added a client-to-real-agent-server round-trip test to pin the shared first-message-auth contract. The PR Notes already call out that the server retains the deprecated query fallback for older clients. |
all-hands-bot
left a comment
There was a problem hiding this comment.
✅ QA Report: PASS
The SDK WebSocket client now keeps session_api_key out of the URL and sends it as the first client frame; I found no functional issues.
Does this PR achieve its stated goal?
Yes. I exercised the real SDK WebSocket client against a real local WebSocket server with an API key containing spaces and URL-reserved characters. On origin/main, the server observed the credential in the WebSocket request path and no first frame; on this PR commit, the request path was clean and the first client frame was the auth payload.
| Phase | Result |
|---|---|
| Environment Setup | ✅ make build completed successfully and installed the uv environment |
| CI Status | 🟡 23 passing, 7 still in progress, 13 skipped at query time; no failing checks observed |
| Functional Verification | ✅ Before/after WebSocket probe confirms the intended auth transport change |
Functional Verification
Test 1: API key moves from WebSocket URL to first client frame
Step 1 — Reproduce / establish baseline without the fix:
Ran git switch --detach origin/main && OPENHANDS_SUPPRESS_BANNER=1 uv run python /tmp/qa_ws_probe.py using a temporary script that instantiated WebSocketCallbackClient and connected it to a real local websockets server:
[{"first_message": null, "path": "/sockets/events/qa-conversation?session_api_key=qa%20key%2Fwith%2Bsymbols%3Fand%20spaces"}]This confirms the reported bug exists on base: the session API key is present in the WebSocket request URL, where reverse proxies and access logs can capture it, and the client sends no first auth frame.
Step 2 — Apply the PR changes:
Restored fix-websocket-auth-frame at commit 82f6714418c51580027228efe7d3fa82330950b2.
Step 3 — Re-run with the fix in place:
Ran git rev-parse HEAD && OPENHANDS_SUPPRESS_BANNER=1 uv run python /tmp/qa_ws_probe.py:
82f6714418c51580027228efe7d3fa82330950b2
[{"first_message": "{"type": "auth", "session_api_key": "qa key/with+symbols?and spaces"}", "path": "/sockets/events/qa-conversation"}]
This confirms the fix works: the WebSocket path no longer contains session_api_key, and the first client frame carries the existing auth payload.
Test 2: No-api-key behavior remains clean
Ran QA_API_KEY=__NONE__ OPENHANDS_SUPPRESS_BANNER=1 uv run python /tmp/qa_ws_probe.py on the PR branch:
[{"first_message": null, "path": "/sockets/events/qa-conversation"}]This confirms clients without an API key still connect without adding an auth query parameter or sending a spurious auth frame.
Issues Found
None.
This review was created by an AI agent (OpenHands) on behalf of the user.
VascoSch92
left a comment
There was a problem hiding this comment.
Just one thing to be sure it is wanted: Dropping the query param outright means the client now only works against agent-server v1.19.0 or newer. Is that correct?
Co-authored-by: openhands <openhands@all-hands.dev>
|
On the compatibility question: the exact floor is agent-server v1.18.1, not v1.19.0. First-message WebSocket auth landed in #2790 and was released in v1.18.1; v1.18.0 does not support it. This floor applies when session-key authentication is configured. No-key clients send no auth frame and remain compatible with older servers. Dropping the query parameter for authenticated connections is intentional so we do not retain the credential-leaking fallback. |
all-hands-bot
left a comment
There was a problem hiding this comment.
✅ QA Report: PASS
The PR removes the SDK WebSocket API key from the URL and still authenticates successfully against a real agent-server using the first client frame.
Does this PR achieve its stated goal?
Yes. The stated goal was to remove session_api_key from Python SDK WebSocket URLs and send the existing auth payload as the first client frame. I verified the old SDK behavior put the key in the query string, the PR SDK uses a clean WebSocket URL and sends {"type":"auth","session_api_key":...} first, and a live authenticated agent-server accepts that no-query first-frame auth while rejecting an invalid first-frame key.
| Phase | Result |
|---|---|
| Environment Setup | ✅ uv sync --dev completed; branch HEAD was 0a7e7ea0234f9fd69c28814dd363e863e63683fe |
| CI Status | 🟡 51 checks observed: 34 pass, 1 pending (qa-changes), 16 skipping |
| Functional Verification | ✅ SDK client behavior and live agent-server WebSocket auth path verified with real WebSocket traffic |
Functional Verification
Test 1: SDK WebSocket client no longer puts the API key in the URL
Step 1 — Reproduce / establish baseline without the fix:
Checked out the base commit in /tmp/qa-ws-base and ran a local WebSocket server probe that records the request path and first client frame:
OPENHANDS_SUPPRESS_BANNER=1 uv run --project /tmp/qa-ws-base python /tmp/qa_sdk_ws_client_probe.pyObserved:
{
"client_class": "WebSocketCallbackClient",
"first_client_frame": null,
"request_path": "/sockets/events/qa-conversation-id?session_api_key=1%2BFYh%2FSRE%3Dds%208Q"
}This confirms the pre-PR behavior exposed session_api_key in the WebSocket request URL and did not send a first auth frame.
Step 2 — Apply the PR's changes:
Checked out PR commit 0a7e7ea0234f9fd69c28814dd363e863e63683fe in /tmp/qa-ws-head.
Step 3 — Re-run with the fix in place:
Ran the same probe against the PR worktree:
OPENHANDS_SUPPRESS_BANNER=1 uv run --project /tmp/qa-ws-head python /tmp/qa_sdk_ws_client_probe.pyObserved:
{
"client_class": "WebSocketCallbackClient",
"first_client_frame": "{"type": "auth", "session_api_key": "1+FYh/SRE=ds 8Q"}",
"request_path": "/sockets/events/qa-conversation-id"
}This confirms the PR removes the credential from the URL and sends it as the first WebSocket client frame instead.
Test 2: A real authenticated agent-server accepts no-query first-frame auth
Step 1 — Establish live server baseline:
Started the PR branch's real agent-server with a session API key and created a real conversation through the authenticated HTTP API:
OH_SESSION_API_KEYS_0=qa-server-key OPENHANDS_SUPPRESS_BANNER=1 uv run --project /tmp/qa-ws-head agent-server --host 127.0.0.1 --port 18081
curl -H 'Content-Type: application/json' -H 'X-Session-API-Key: qa-server-key' --data @/tmp/qa_create_conversation.json http://127.0.0.1:18081/api/conversationsObserved HTTP_STATUS:201 with conversation ID d70f5fba-c67b-459d-9d34-4cf7882be457, confirming the server and authenticated API were usable.
Step 2 — Exercise WebSocket auth variants:
Connected to the real conversation WebSocket using three user-relevant variants: legacy query auth, no-query invalid first-frame auth, and no-query valid first-frame auth.
OPENHANDS_SUPPRESS_BANNER=1 uv run --project /tmp/qa-ws-head python /tmp/qa_agent_server_ws_probe.pyObserved summary:
[
{
"label": "valid-query-fallback-baseline",
"state": "received-message",
"url": "ws://127.0.0.1:18081/sockets/events/d70f5fba-c67b-459d-9d34-4cf7882be457?session_api_key=qa-server-key"
},
{
"close_code": 4001,
"close_reason": "Authentication failed",
"label": "no-query-invalid-first-frame-auth",
"state": "closed-after-connect",
"url": "ws://127.0.0.1:18081/sockets/events/d70f5fba-c67b-459d-9d34-4cf7882be457"
},
{
"label": "no-query-valid-first-frame-auth",
"state": "received-message",
"url": "ws://127.0.0.1:18081/sockets/events/d70f5fba-c67b-459d-9d34-4cf7882be457"
}
]This shows the server still accepts the legacy query fallback, rejects a bad first-frame key with 4001 Authentication failed, and accepts the PR's intended no-query valid first-frame auth by sending a conversation state event.
Issues Found
None.
This review was created by an AI agent (OpenHands) on behalf of the user.
HUMAN:
Remove session_api_key from Python SDK WebSocket URLs.
AGENT:
Why
Session API keys in WebSocket query strings are copied into reverse-proxy and access logs. Production log review confirmed credential-bearing event-socket URLs.
Summary
Issue Number
N/A
How to Test
Video/Screenshots
N/A. This is a wire-protocol security change.
Type
Notes
Agent-server first-message authentication is already available on main from #2790. The server retains its deprecated query fallback for older clients.
Agent Server images for this PR
• GHCR package: https://github.com/OpenHands/agent-sdk/pkgs/container/agent-server
Variants & Base Images
eclipse-temurin:17-jdknikolaik/python-nodejs:python3.13-nodejs22-slimgolang:1.21-bookwormPull (multi-arch manifest)
# Each variant is a multi-arch manifest supporting both amd64 and arm64 docker pull ghcr.io/openhands/agent-server:0a7e7ea-pythonRun
All tags pushed for this build
About Multi-Architecture Support
0a7e7ea-python) is a multi-arch manifest supporting both amd64 and arm640a7e7ea-python-amd64) are also available if needed