Repository navigation
fix(security): first-message WebSocket auth to prevent token leakage - #2790
Conversation
Clients can now send {"type": "auth", "session_api_key": "..."} as the
first WebSocket frame instead of passing the token as a query parameter.
This keeps sk-oh-* tokens out of reverse-proxy / load-balancer access
logs (Traefik, Datadog, etc.).
Query param and header auth are preserved as deprecated fallbacks for
backwards compatibility.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Python API breakage checks — ✅ PASSEDResult: ✅ PASSED |
REST API breakage checks (OpenAPI) — ✅ PASSEDResult: ✅ PASSED |
all-hands-bot
left a comment
There was a problem hiding this comment.
🟡 Acceptable - Solves a real security problem (tokens in URLs leak to logs) with proper backward compatibility. The three-path auth flow is complex but necessary given WebSocket protocol constraints. A few improvements would help with operational visibility and clarity.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
all-hands-bot
left a comment
There was a problem hiding this comment.
QA Report: WebSocket First-Message Authentication
Verdict: ⚠️ PASS WITH ISSUES
The WebSocket first-message authentication feature works correctly and provides the intended security improvement. However, there is one minor formatting issue that needs to be fixed before merge.
Environment Setup
✅ Dependencies installed: uv sync --frozen completed successfully
✅ Python environment: Ready (Python 3.13.13)
CI & Test Status
CI Checks
- ✅ Run tests/agent-server-tests: Passed (48s)
- ✅ Run tests/sdk-tests: Passed (9s)
- ✅ Run tests/tools-tests: Passed (9s)
- ✅ Python API breakage checks: Passed
- ✅ REST API breakage checks: Passed
- ❌ Pre-commit checks: Failed due to formatting issues (see Issues Found below)
Local Test Results
$ uv run pytest tests/agent_server/test_websocket_first_message_auth.py -v
========== 14 passed in 0.27s ==========
$ uv run pytest tests/agent_server/ -k "websocket" -v
========== 33 passed, 679 deselected in 8.49s ==========Test Coverage Analysis:
- ✅ All 14 new first-message auth tests pass
- ✅ All 19 existing WebSocket tests pass (no regressions)
- ✅ Comprehensive edge case coverage:
- No auth configured
- Legacy query param auth (valid/invalid)
- Legacy header auth (valid/invalid)
- First-message auth (valid/invalid/malformed/timeout/disconnect)
- End-to-end integration tests
Functional Verification
Code Review
I performed a thorough code review of the implementation:
Security Analysis:
- ✅ No authentication bypass vulnerabilities
- ✅ Proper timeout handling (10 seconds) prevents DoS
- ✅ Generic error messages ("Authentication failed") prevent information leakage
- ✅ Race conditions prevented by synchronous auth before event processing
- ✅ First-message frame properly consumed by auth flow
Logic Verification:
# Auth flow order (as implemented):
1. If no session_api_keys configured → accept unconditionally ✓
2. If legacy key provided (query/header):
- Valid → log deprecation warning, accept ✓
- Invalid → close with 4001 (before accept) ✓
3. If no legacy key → first-message auth:
- Accept connection first (required by WebSocket protocol) ✓
- Read first frame with 10s timeout ✓
- Validate: must be dict with type="auth" and valid key ✓
- Invalid → close with 4001 ✓Backward Compatibility:
- ✅ Legacy query param auth still works (with deprecation warning logged)
- ✅ Legacy header auth still works (with deprecation warning logged)
- ✅ Existing WebSocket tests all pass (no breaking changes)
Test Coverage Completeness:
Test scenarios covered (14 tests):
1. ✓ No auth configured - immediate acceptance
2. ✓ Legacy query param - valid key
3. ✓ Legacy query param - invalid key
4. ✓ Legacy header - valid key
5. ✓ Legacy header - invalid key
6. ✓ First-message auth - valid key
7. ✓ First-message auth - invalid key
8. ✓ First-message auth - wrong type field
9. ✓ First-message auth - missing key field
10. ✓ First-message auth - malformed JSON
11. ✓ First-message auth - client disconnect
12. ✓ First-message auth - timeout (10s)
13. ✓ End-to-end events_socket - valid auth
14. ✓ End-to-end events_socket - rejected auth
Issues Found
🟡 Minor: Line Length Violation
File: tests/agent_server/test_websocket_first_message_auth.py:205
Issue: Comment line exceeds 88 character limit (89 characters)
Impact: Causes pre-commit check to fail; does not affect functionality
Current line (89 chars):
# First call: auth message (read by _accept_authenticated_websocket via receive_text)Suggested fix:
# First call: auth message (read by _accept_authenticated_websocket)
# via receive_text, then receive_json calls disconnectOr simply shorten to:
# First call: auth message read by _accept_authenticated_websocket(The inline comment on the next line already explains "Then receive_json calls: disconnect")
Summary
✅ Security Enhancement: Successfully prevents API keys from appearing in URLs/logs
✅ Backward Compatible: Legacy auth methods work with deprecation warnings
✅ Well Tested: 14 new tests + 19 existing tests all pass
✅ Clean Implementation: Proper error handling, timeouts, and validation
🟡 Minor Fix Needed: One line length violation in test file
Recommendation: Fix the line length issue and merge. The feature is functionally complete and ready for production use.
- Add comment explaining 10-second timeout rationale - Add comment explaining why accept() must precede first-message read - Log specific failure reasons (timeout, malformed JSON, disconnect, wrong type, invalid key) instead of a single generic message - Log info on successful first-message auth for adoption tracking - Add test for query-param-takes-precedence-over-first-message case Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
|
[Automatic Post]: This PR seems to be currently waiting for review. @tofarr, could you please take a look when you have a chance? |
|
[Automatic Post]: This PR seems to be currently waiting for review. @tofarr, could you please take a look when you have a chance? |
|
@OpenHands /codereview /codereview-roasted |
|
I'm on it! enyst can track my progress at all-hands.dev |
enyst
left a comment
There was a problem hiding this comment.
🟡 Acceptable
[TESTING GAPS]
- [tests/agent_server/test_websocket_first_message_auth.py, Line 222] The new coverage is mostly mock-driven around
receive_text()/close(), but the risky part of this change is the actual protocol transition: accept the socket, consume the first frame as auth, then continue normal message flow (or close with the expected code). We already have a real-client websocket test harness intests/agent_server/test_agent_server_wsproto.py, andopenhands-agent-server/AGENTS.mdexplicitly asks for live-server coverage for localized WebSocket behavior changes. I'd add one wsproto/live-server test that connects without query/header auth, sends{"type":"auth", ...}as the first frame, and proves the connection stays usable afterwards; ideally also one rejection case. That's the regression mocks won't catch.
[RISK ASSESSMENT]
- [Overall PR]
⚠️ Risk Assessment: 🟡 MEDIUM
This is a security improvement and the core logic looks reasonable, but it changes the websocket handshake/auth lifecycle in a protocol-sensitive area. The remaining risk is mostly verification risk: without one real client/server test for the new first-message path, we are trusting mocks for the most timing- and transport-dependent part of the change.
VERDICT:
❌ Needs rework: add at least one real websocket client/server test for first-message auth before merging.
KEY INSIGHT:
The security fix itself is sound; the weak spot is that the new behavior depends on real websocket handshake/frame semantics, and that is exactly where mock-only tests are least trustworthy.
This comment was marked as duplicate.
This comment was marked as duplicate.
Address enyst's review on PR #2790: the existing first-message auth tests are mock-driven, but the risky part of the change is the actual protocol transition (accept the socket, consume the first frame as auth, continue normal message flow). Add three live-server tests using the real wsproto/websockets harness: - accepted: connect with no query/header key, send auth frame first, verify connection stays usable for subsequent messages - rejected: invalid key triggers close with code 4001 - malformed: non-JSON first frame triggers close with code 4001 These exercise the real WebSocket handshake and frame semantics that mock-only tests can't validate. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
|
@enyst @all-hands-bot — addressed all review feedback: enyst's review (latest): Added three live-server tests in
All 6 tests in the wsproto file pass locally ( all-hands-bot earlier suggestions were already addressed in commit 2ef0c74 (timeout-rationale comment, accept-vs-close asymmetry comment, success log on first-message auth, per-failure-reason logging, and the legacy-precedence test). The line-length issue at line 205 was also resolved via ruff-format. |
all-hands-bot
left a comment
There was a problem hiding this comment.
🟢 Good taste - Elegant security fix with proper backward compatibility.
[RISK ASSESSMENT]
- [Overall PR]
⚠️ Risk Assessment: 🟢 LOW
This PR addresses a real security issue (token leakage in proxy logs) with a well-designed solution. The three-path auth flow (first-message → query param → header) maintains full backward compatibility while encouraging the secure approach via deprecation warnings. Complexity is justified and well-tested with both unit tests (mocks) and integration tests (real WebSocket client). Previous review concerns have all been addressed.
Key strengths:
- Solves real security problem without breaking changes
- Comprehensive test coverage (14 unit + 3 integration tests)
- Clear error handling with specific log messages
- Well-documented timeout and protocol rationale
- Shallow nesting despite multiple code paths
VERDICT: ✅ Worth merging
KEY INSIGHT: The protocol asymmetry (legacy path rejects before accept, first-message path accepts then reads then closes) is correct and necessary - WebSocket protocol requires handshake completion before frame reads.
all-hands-bot
left a comment
There was a problem hiding this comment.
✅ QA Report: PASS
First-message WebSocket authentication is correctly implemented and prevents token leakage while maintaining backward compatibility.
Does this PR achieve its stated goal?
Yes. The PR successfully implements first-message WebSocket authentication to prevent session API keys from appearing in query parameters or headers. This security improvement keeps tokens out of reverse-proxy and load-balancer access logs. Legacy authentication methods (query params, headers) remain functional with deprecation warnings, ensuring zero breaking changes for existing clients.
| Phase | Result |
|---|---|
| Environment Setup | ✅ make build successful, all dependencies installed |
| CI & Tests | ✅ All checks pass: 15/15 WebSocket auth tests pass (14 new), agent-server-tests ✓, integration tests ✓, pre-commit ✓ |
| Functional Verification | ✅ Code review confirms correct implementation of auth flow |
Functional Verification
Test 1: Verify first-message auth implementation
Step 1 — Baseline (before this PR):
Prior to this PR, WebSocket authentication only supported:
- Query parameter:
ws://host/path?session_api_key=sk-oh-xxx(appears in logs) - Header:
X-Session-API-Key: sk-oh-xxx(requires non-browser client)
No first-message auth was available, forcing tokens into URLs.
Step 2 — Examine the implementation:
Reviewed openhands-agent-server/openhands/agent_server/sockets.py lines 94-184:
async def _accept_authenticated_websocket(
websocket: WebSocket,
session_api_key: str | None,
) -> bool:
# Three-tier auth strategy:
# 1. No auth configured → accept
# 2. Legacy query/header auth → accept with deprecation warning
# 3. First-message auth → read first frame, validate JSON auth payloadImplementation correctly:
- ✅ Accepts WebSocket before reading first frame (WebSocket protocol requirement)
- ✅ Validates JSON structure:
{"type": "auth", "session_api_key": "..."} - ✅ Enforces 10-second timeout for auth frame
- ✅ Rejects with code 4001 on invalid auth
- ✅ Logs deprecation warning for legacy auth methods
- ✅ Prioritizes legacy auth over first-message (backward compat)
Step 3 — Verify test coverage:
Ran unit tests locally:
uv run pytest tests/agent_server/test_websocket_first_message_auth.py -vResult: 15/15 tests PASSED in 0.54s
Test coverage includes:
- ✅ No auth configured
- ✅ Legacy query param (valid/invalid)
- ✅ Legacy header auth (valid/invalid)
- ✅ First-message auth (valid/invalid key)
- ✅ Malformed JSON handling
- ✅ Timeout enforcement
- ✅ Client disconnect during auth
- ✅ Wrong message type
- ✅ Missing session_api_key field
- ✅ Precedence (legacy over first-message)
- ✅ End-to-end through
events_socketendpoint (2 tests)
Step 4 — Verify integration tests:
Checked tests/agent_server/test_agent_server_wsproto.py for 3 new integration tests:
test_agent_server_websocket_first_message_auth_accepted- full WebSocket handshake → auth → message flowtest_agent_server_websocket_first_message_auth_rejected- invalid key triggers code 4001test_agent_server_websocket_first_message_auth_malformed- malformed JSON triggers code 4001
These tests use real WebSocket protocol (via websockets library), not mocks.
Step 5 — CI verification:
Checked GitHub Actions:
agent-server-tests: PASS (36s)
build-binary-and-test (ubuntu): PASS (2m51s)
build-binary-and-test (macos): PASS (2m43s)
cross-tests: PASS (1m20s)
pre-commit: PASS (57s)
All WebSocket tests run in CI and pass.
Test 2: Verify security improvement
Security benefit confirmed:
-
Before this PR: Tokens required in query params (
?session_api_key=sk-oh-xxx), which appear in:- Web server access logs
- Reverse proxy logs
- Load balancer logs
- Browser history
- Referrer headers
-
After this PR: Tokens can be sent in the first WebSocket frame (after handshake), which:
- ✅ Never appears in HTTP logs
- ✅ Only visible in WebSocket frame inspection tools
- ✅ Not stored in browser history
- ✅ Not leaked via referrer headers
Module docstring (lines 7-10) explicitly states the security motivation:
"This keeps tokens out of URLs and therefore out of reverse-proxy / load-balancer access logs."
Test 3: Verify backward compatibility
Examined deprecation path:
Lines 117-128 in sockets.py:
if resolved_key is not None:
if resolved_key in config.session_api_keys:
logger.warning(
"session_api_key passed via query param or header is deprecated. "
"Use first-message auth instead."
)
await websocket.accept()
return TrueBackward compatibility verified:
- ✅ Query param auth still works (with warning)
- ✅ Header auth still works (with warning)
- ✅ Legacy methods have higher precedence than first-message auth
- ✅ Test
test_legacy_query_param_takes_precedence_over_first_messageensures no breaking changes
No existing clients will break when this SDK is released.
Issues Found
None.
Summary: This PR delivers exactly what it promises — a secure, backward-compatible first-message WebSocket authentication mechanism that prevents session API keys from leaking into logs. The implementation is well-tested (15 tests, all passing), properly documented, and maintains full compatibility with existing clients. Ready for merge.
|
[Automatic Post]: This PR seems to be currently waiting for review. @tofarr, could you please take a look when you have a chance? |
…penHands#2790) Co-authored-by: Debug Agent <debug@example.com> Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
…penHands#2790) Co-authored-by: Debug Agent <debug@example.com> Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Summary
_accept_authenticated_websocketnow supports first-message auth: when no key is found in query params or headers, the server accepts the WebSocket, reads the first frame, and validates{"type": "auth", "session_api_key": "..."}before processing any other messages. 10-second timeout for the auth frame (rationale documented inline)._safe_close_websocketnow accepts optionalcode/reasonparameters.logger.infoon successful first-message auth (parity with the legacy deprecation log) and per-reasonlogger.warningon failures (timeout, malformed JSON, client disconnect, non-object payload, wrong type, invalid key) — client-facing close reason stays generic ("Authentication failed") so we don't leak diagnostics over the wire.test_websocket_first_message_auth.py(covers no-auth, legacy query/header valid+invalid, legacy-precedence-over-first-message, first-message valid/invalid/wrong-type/missing-key/malformed-JSON/disconnect/timeout, plus end-to-end throughevents_socket) and 3 live-server tests intest_agent_server_wsproto.pyusing a real wsproto/websockets client to exercise the actual handshake → first-frame-as-auth → normal message flow transition (accepted, rejected with close 4001, malformed-JSON close 4001).Addresses the server-side component of OpenHands/OpenHands#13777 — moves the first-message auth from the V0
listen_socket.pyto the SDK as requested in tofarr's review.Test plan
{"type": "auth", ...}as first frame — will work once this SDK is released and the submodule is bumped🤖 Generated with Claude Code
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:3e70c7f-pythonRun
All tags pushed for this build
About Multi-Architecture Support
3e70c7f-python) is a multi-arch manifest supporting both amd64 and arm643e70c7f-python-amd64) are also available if needed