Skip to content

fix(security): first-message WebSocket auth to prevent token leakage - #2790

Merged
xingyaoww merged 5 commits into
mainfrom
fix/websocket-first-message-auth
Apr 23, 2026
Merged

xingyaoww merged 5 commits into
mainfrom
fix/websocket-first-message-auth

Conversation

@simonrosenberg

@simonrosenberg simonrosenberg commented Apr 9, 2026 •

Copy link
Copy Markdown
Member

Summary

  • _accept_authenticated_websocket now 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).
  • Query parameter and header-based auth are kept as deprecated fallbacks so existing clients continue to work (with a deprecation warning logged).
  • _safe_close_websocket now accepts optional code/reason parameters.
  • Operational logging: logger.info on successful first-message auth (parity with the legacy deprecation log) and per-reason logger.warning on 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.
  • Tests: 15 mock-based unit tests in 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 through events_socket) and 3 live-server tests in test_agent_server_wsproto.py using 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.py to the SDK as requested in tofarr's review.

Test plan

  • All 19 existing WebSocket tests pass (no regressions)
  • 15 new mock-based first-message auth tests pass
  • 3 new live-server (real wsproto client) first-message auth tests pass — accepted / rejected (4001) / malformed (4001)
  • Pre-commit (ruff-format, ruff-lint, pyright) passes on changed files
  • Frontend update (fix(security): first-message WebSocket auth to prevent token leakage OpenHands#13777) sends {"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

Variant Architectures Base Image Docs / Tags
java amd64, arm64 eclipse-temurin:17-jdk Link
python amd64, arm64 nikolaik/python-nodejs:python3.13-nodejs22-slim Link
golang amd64, arm64 golang:1.21-bookworm Link

Pull (multi-arch manifest)

# Each variant is a multi-arch manifest supporting both amd64 and arm64
docker pull ghcr.io/openhands/agent-server:3e70c7f-python

Run

docker run -it --rm \
  -p 8000:8000 \
  --name agent-server-3e70c7f-python \
  ghcr.io/openhands/agent-server:3e70c7f-python

All tags pushed for this build

ghcr.io/openhands/agent-server:3e70c7f-golang-amd64
ghcr.io/openhands/agent-server:3e70c7f-golang_tag_1.21-bookworm-amd64
ghcr.io/openhands/agent-server:3e70c7f-golang-arm64
ghcr.io/openhands/agent-server:3e70c7f-golang_tag_1.21-bookworm-arm64
ghcr.io/openhands/agent-server:3e70c7f-java-amd64
ghcr.io/openhands/agent-server:3e70c7f-eclipse-temurin_tag_17-jdk-amd64
ghcr.io/openhands/agent-server:3e70c7f-java-arm64
ghcr.io/openhands/agent-server:3e70c7f-eclipse-temurin_tag_17-jdk-arm64
ghcr.io/openhands/agent-server:3e70c7f-python-amd64
ghcr.io/openhands/agent-server:3e70c7f-nikolaik_s_python-nodejs_tag_python3.13-nodejs22-slim-amd64
ghcr.io/openhands/agent-server:3e70c7f-python-arm64
ghcr.io/openhands/agent-server:3e70c7f-nikolaik_s_python-nodejs_tag_python3.13-nodejs22-slim-arm64
ghcr.io/openhands/agent-server:3e70c7f-golang
ghcr.io/openhands/agent-server:3e70c7f-java
ghcr.io/openhands/agent-server:3e70c7f-python

About Multi-Architecture Support

  • Each variant tag (e.g., 3e70c7f-python) is a multi-arch manifest supporting both amd64 and arm64
  • Docker automatically pulls the correct architecture for your platform
  • Individual architecture tags (e.g., 3e70c7f-python-amd64) are also available if needed

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>
@github-actions

github-actions Bot commented Apr 9, 2026 •

Copy link
Copy Markdown
Contributor

Python API breakage checks — ✅ PASSED

Result: ✅ PASSED

Action log

@github-actions

github-actions Bot commented Apr 9, 2026 •

Copy link
Copy Markdown
Contributor

REST API breakage checks (OpenAPI) — ✅ PASSED

Result: ✅ PASSED

Action log

@simonrosenberg
simonrosenberg requested a review from tofarr April 9, 2026 22:02
@github-actions

github-actions Bot commented Apr 9, 2026 •

Copy link
Copy Markdown
Contributor

Coverage

Coverage Report •
FileStmtsMissCoverMissing
openhands-agent-server/openhands/agent_server
   sockets.py1883382%163, 166, 169, 246–248, 369–370, 375–377, 383–385, 389, 391–392, 396–397, 400, 403, 405–406, 409–410, 430, 432, 446–450, 460
TOTAL234471060654% 

@all-hands-bot all-hands-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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 all-hands-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 disconnect

Or 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>
@all-hands-bot

Copy link
Copy Markdown
Collaborator

[Automatic Post]: This PR seems to be currently waiting for review. @tofarr, could you please take a look when you have a chance?

@simonrosenberg simonrosenberg self-assigned this Apr 13, 2026
@all-hands-bot

Copy link
Copy Markdown
Collaborator

[Automatic Post]: This PR seems to be currently waiting for review. @tofarr, could you please take a look when you have a chance?

@enyst

enyst commented Apr 18, 2026

Copy link
Copy Markdown
Member

@OpenHands /codereview /codereview-roasted

@openhands-ai

openhands-ai Bot commented Apr 18, 2026

Copy link
Copy Markdown

I'm on it! enyst can track my progress at all-hands.dev

@enyst enyst left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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 in tests/agent_server/test_agent_server_wsproto.py, and openhands-agent-server/AGENTS.md explicitly 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.

@openhands-ai

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>
@simonrosenberg

Copy link
Copy Markdown
Member Author

@enyst @all-hands-bot — addressed all review feedback:

enyst's review (latest): Added three live-server tests in tests/agent_server/test_agent_server_wsproto.py using the real wsproto/websockets harness, exercising the actual protocol transition (handshake → consume first frame as auth → normal message flow):

  • test_agent_server_websocket_first_message_auth_accepted — connect with no query/header key, send {"type":"auth", ...} as first frame, verify connection stays usable for subsequent messages (proves the auth frame was consumed by the auth handler, not the main loop).
  • test_agent_server_websocket_first_message_auth_rejected — invalid key triggers ConnectionClosed with rcvd.code == 4001.
  • test_agent_server_websocket_first_message_auth_malformed — non-JSON first frame triggers close with code 4001.

All 6 tests in the wsproto file pass locally (uv run pytest tests/agent_server/test_agent_server_wsproto.py -v → 6 passed in 8.70s). Combined with existing tests: 37 WebSocket tests pass with no regressions.

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.

@enyst
enyst requested a review from all-hands-bot April 18, 2026 18:10
@simonrosenberg
simonrosenberg requested a review from enyst April 18, 2026 18:10

@all-hands-bot all-hands-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 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 all-hands-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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 payload

Implementation 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 -v

Result: 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_socket endpoint (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 flow
  • test_agent_server_websocket_first_message_auth_rejected - invalid key triggers code 4001
  • test_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:

  1. 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
  2. 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 True

Backward 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_message ensures 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.

@enyst enyst left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good to me. I'd love it if @tofarr can take a look but it seems safe.

@all-hands-bot

Copy link
Copy Markdown
Collaborator

[Automatic Post]: This PR seems to be currently waiting for review. @tofarr, could you please take a look when you have a chance?

@xingyaoww
xingyaoww merged commit fc9afbb into main Apr 23, 2026
37 checks passed
@xingyaoww
xingyaoww deleted the fix/websocket-first-message-auth branch April 23, 2026 15:45
StressTestor pushed a commit to StressTestor/software-agent-sdk that referenced this pull request Jun 1, 2026
…penHands#2790)

Co-authored-by: Debug Agent <debug@example.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
pengzhang-create pushed a commit to Pyromind-Dynamics/software-agent-sdk that referenced this pull request Aug 13, 2026
…penHands#2790)

Co-authored-by: Debug Agent <debug@example.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants