Skip to content

fix(agent-server): treat whitespace-only session API keys as empty - #5749

Open
DevKaurav-14 wants to merge 3 commits into
OpenHands:mainfrom
DevKaurav-14:fix/blank-session-api-keys
Open

DevKaurav-14 wants to merge 3 commits into
OpenHands:mainfrom
DevKaurav-14:fix/blank-session-api-keys

Conversation

@DevKaurav-14

@DevKaurav-14 DevKaurav-14 commented Oct 13, 2026 •

Copy link
Copy Markdown

HUMAN:
This PR fixes the issue of whitespace-only keys being treated as real keys because PR #5659 only ignored empty session API keys.

AGENT:

Why

#5659 made the Agent Server ignore an empty session API key, but a whitespace-only key such as " " or "\n" (for example, from a template that rendered a stray space) was still kept as a real key. As a result it:

  • counted as "auth configured", so the server's default bind became 0.0.0.0 instead of loopback;
  • passed the not key guard on POST /api/init;
  • could become the cipher key through the _default_secret_key() fallback when OH_SECRET_KEY is unset or blank.

Summary

  • Config.session_api_keys drops keys that are empty after .strip() (env slots, JSON config, direct Config(...)), and the legacy V0 SESSION_API_KEY default factory skips them too.
  • _default_secret_key() skips blank session keys, so the cipher fallback never uses one; /api/init rejects blank keys with 422 without echoing the request.
  • .strip() is only used to test for blankness: non-blank keys keep their exact value, including surrounding whitespace (e.g. " key "), since keys are compared exactly.

Issue Number

Fixes #5731

How to Test

uv sync --dev
uv run pytest tests/agent_server/test_config.py tests/agent_server/test_init_router.py tests/agent_server/test_preload_modules.py -q

New tests cover each path in the issue: env slots, JSON config, direct construction, the V0 default, the _default_secret_key() fallback, the /api/init 422 guard, and _auth_enabled(), plus " key " / " session-key " being kept verbatim. 13 of the new cases fail on main and pass with this change.

Real-server check (python -m openhands.agent_server --port 18765, no config file, no OH_SECRET_KEY):

OH_SESSION_API_KEYS_0 main this branch
" " listens on *:18765 listens on 127.0.0.1:18765
" key " – listens on *:18765; unauthenticated GET /api/conversations/count → 401

Local results:

  • pre-commit on the changed files (ruff format, ruff lint, pycodestyle, pyright, import rules): all pass.
  • tests/agent_server: 2596 passed, 14 failed. The same 14 also fail on unmodified main on this machine (macOS): canvas_extensions/test_canvas_extension_backend.py (11), two tmux tests in test_api.py, and test_server_details_router.py::test_server_info_reports_configured_conversation_runtime.

Video/Screenshots

N/A. Not a visual change; see How to Test.

Type

  • Bug fix
  • Feature
  • Refactor
  • Breaking change
  • Docs / chore

Notes

  • Out of scope, per the issue's non-goals: exact-match key comparison, HTTP/WebSocket auth, and the blank OH_SECRET_KEY handling from fix(agent-server): treat an empty OH_SECRET_KEY as unset #5660.
  • _default_secret_key() reads only SESSION_API_KEY and OH_SESSION_API_KEYS_0. With slot 0 blank and slot 1 set, the cipher fallback is None, exactly as it already is for an empty slot 0. Scanning further slots would change empty-key behavior too, so it is left for a follow-up if wanted.
  • _build_initialized_config uses model_copy (no validators), but its only caller runs after the new 422 guard, so blank keys cannot reach it.

🤖 Generated with Claude Code

@DevKaurav-14
DevKaurav-14 marked this pull request as ready for review October 13, 2026 21:48
@neubig
neubig requested a review from all-hands-bot October 16, 2026 14:07

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

This review was posted by an AI agent (OpenHands).

Scope: this change is in-repo — it touches openhands-agent-server config resolution and the deferred-init /api/init guard, both owned by this repository. The linked issue #5731 carries bug / priority:low / ready-for-dev.

What I verified on head d195243:

  • Config._drop_empty_session_api_keys now drops keys that are blank after .strip() while keeping non-blank keys verbatim (including surrounding whitespace), applied across env slots, JSON config, and direct Config(...).
  • _default_session_api_keys and _default_secret_key skip blank SESSION_API_KEY / OH_SESSION_API_KEYS_0, so a blank key no longer becomes the cipher fallback.
  • The /api/init guard rejects blank keys with 422 without echoing the request body.
  • Exercised the real entry points directly (load_config(), _auth_enabled(), Config(...), cipher): " " / "\n" / "" yield session_api_keys == [], _auth_enabled() is False, secret_key is None, cipher is None; " key " is retained verbatim and still authenticates.
  • Focused suite passes locally: uv run pytest tests/agent_server/test_config.py tests/agent_server/test_init_router.py tests/agent_server/test_preload_modules.py -q -> 109 passed.

I traced the cross-layer consumers of session_api_keys (auth dependencies, OpenAI/WebSocket routers, VSCode service, /api/init builder). The changed message text (session_api_keys cannot contain empty or blank keys) is not depended on by any test or client in the tree. _build_initialized_config uses model_copy and bypasses validators, but its only production caller runs after the new 422 guard, so blank keys cannot reach it. The documented non-goals (slot-1 scanning in _default_secret_key, exact-match comparison) match existing empty-key behavior and are not regressions.

Note: current-head GitHub Actions for this fork PR show action_required (awaiting maintainer approval to run) rather than completed workflow results; this is an infrastructure gate, not a code defect, and the focused tests pass locally.

No material correctness, security, or compatibility findings.

✅ APPROVED

A session API key that is empty after stripping whitespace (e.g. "   " or
"\n" from a template that rendered a stray space) was still kept as a real
key. It enabled auth, so the server bound 0.0.0.0, was accepted by
/api/init, and could become the cipher key through the session-key
fallback when OH_SECRET_KEY is unset or blank.

Treat such keys like empty ones:
- drop them from Config.session_api_keys (env slots, JSON config, direct
  construction) and from the legacy SESSION_API_KEY default;
- reject them with 422 in the /api/init body;
- skip them in the _default_secret_key() cipher fallback.

Non-blank keys keep their exact value, including surrounding whitespace,
since keys are compared exactly.

Fixes OpenHands#5731

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@DevKaurav-14
DevKaurav-14 force-pushed the fix/blank-session-api-keys branch from d195243 to 3088207 Compare October 18, 2026 10:09
@DevKaurav-14

Copy link
Copy Markdown
Author

@enyst this fixes #5731 (follow-up to #5659); bot-approved and CI green. Could you take a look when you have a moment?

@neubig
neubig requested a review from all-hands-bot October 20, 2026 05:35

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

This review was posted by an AI agent (OpenHands).

Scope: in-repo. The change touches openhands-agent-server config resolution and the deferred-init /api/init guard, both owned by this repository per the root AGENTS.md and .agents/skills/custom-codereview-guide.md. The linked issue #5731 is open and currently carries bug / priority:low / ready-for-dev.

Note on state: the earlier all-hands-bot approval was recorded against d195243, which is not the current head; the branch was force-pushed and merged from main since. This review is against f852f9f only.

What I verified on f852f9f (not on the earlier head):

  • Config._drop_empty_session_api_keys now filters on key.strip() while returning non-blank keys verbatim. Direct construction, env slots, and the JSON config file all drop blank keys: Config(session_api_keys=[" "]) -> [], ["real-key", "\t"] -> ["real-key"], and [" key "] -> [" key "] unchanged.
  • The V0 SESSION_API_KEY factory and _default_secret_key() both skip blank values, so a blank key can no longer become the cipher key. With OH_SESSION_API_KEYS_0=" " and no OH_SECRET_KEY, secret_key and cipher are both None.
  • _auth_enabled() returns False for a blank key, so the default bind stays loopback.
  • The /api/init guard rejects blank entries with 422 without echoing the submitted key.

Live before/after on the real startup path (no config file, no OH_SECRET_KEY, OH_SESSION_API_KEYS_0=" "): the base revision at 33d8aa2 resolves session_api_keys == [" "] with a non-None secret_key and binds 0.0.0.0:18766; this head resolves session_api_keys == [] with secret_key is None and binds 127.0.0.1:18765. That reproduces the symptom in the issue on the base and confirms the fix on the head through the real entry point, not a constructed fixture.

I traced the session_api_keys consumers (dependencies.check_session_api_key, check_workspace_session, sockets.py first-message and legacy auth, vscode_service, conversation_service, mcp_oauth_store, export_session_api_key). All read session_api_keys[0] or membership, so dropping blank entries yields the first real key rather than a guessable one; no consumer depends on a blank key being present. _build_initialized_config uses model_copy and bypasses validators, but its only production caller is InitService.initialize, which now raises 422 before it runs. The changed 422 message text is not referenced by any test, client, or generated schema in the tree. The focused suite passes locally: uv run pytest tests/agent_server/test_config.py tests/agent_server/test_init_router.py tests/agent_server/test_preload_modules.py -q -> 120 passed, and pre-commit (ruff format/lint, pycodestyle, pyright, import rules) passes on the changed files.

One accepted consequence worth stating for the maintainer: a deployment that booted with a blank session key and no OH_SECRET_KEY previously got a cipher keyed on that blank string. After this change secret_key is None, so secrets persisted under the blank key can no longer be decrypted and are redacted. That is the intended outcome of the issue's acceptance criterion, and the old key was guessable, so the stored values were not meaningfully protected; it is not a reason to withhold approval.

Current-head GitHub Actions for this fork PR show action_required (awaiting maintainer approval to run) rather than completed workflow results. That is an infrastructure gate on a fork PR, not a code defect; the behavior is covered by the local run and the live startup check above.

No material correctness, security, or compatibility findings.

✅ APPROVED

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.

Agent Server: whitespace-only session API keys still count as real keys

2 participants