Skip to content

fix: deferred-init session API key auth uses app.state config at request time - #3844

Merged
tofarr merged 3 commits into
mainfrom
fix/deferred-init-session-key-auth
Jun 23, 2026
Merged

tofarr merged 3 commits into
mainfrom
fix/deferred-init-session-key-auth

Conversation

@tofarr

@tofarr tofarr commented Jun 23, 2026 •

Copy link
Copy Markdown
Collaborator

HUMAN:

I started testing this in runtime-api and realized that the authentication was not updating as part of the init process.


AGENT:

Why

When POST /api/init delivers new session_api_keys to a dormant server, subsequent requests with the new key were rejected with 401 while the original (bootstrap) key kept working. There were two related bugs:

  1. Stale closure: All three auth dependency factories (create_session_api_key_dependency, create_workspace_session_dependency, create_openai_api_key_dependency) closed over the Config object captured at server startup. POST /api/init correctly wrote the new config to app.state.config, but the closure still validated against the old object, so old keys passed and new keys failed.

  2. Never-registered dependency: _add_api_routes guarded each dependency with if config.session_api_keys:. In the common warm-pool setup where the dormant server starts with no keys (keys arrive at init time), this guard is False and no auth dependency is ever registered — meaning keys delivered via /api/init are stored in app.state.config but go completely unchecked.

Summary

  • Replaced the three factory functions with plain FastAPI dependency functions (check_session_api_key, check_workspace_session, check_openai_api_key) that read config from request.app.state.config on every request.
  • Removed the if config.session_api_keys: guards in _add_api_routes; the plain functions handle the empty-list case with an early return (consistent with how require_initialized is already unconditionally registered).
  • Dropped the now-unused config parameter from _add_api_routes.

Issue Number

N/A

How to Test

Unit tests cover the fix directly. The new regression test test_check_session_api_key_reflects_config_update mutates app.state.config mid-test and asserts:

  • Old key → 401 after the update
  • New key → 200 after the update

Run with:

uv run pytest tests/agent_server/test_dependencies.py tests/agent_server/test_api_authentication.py tests/agent_server/test_init_router.py tests/agent_server/test_workspace_cookie_auth.py -v

All 95 tests pass.

To test end-to-end manually against a dormant server:

  1. Start server with OH_DEFERRED_INIT=true OH_SECRET_KEY=bootstrap-key
  2. POST /api/init with X-Init-API-Key: bootstrap-key and body {"session_api_keys": ["new-key"]}
  3. GET /api/server_info with X-Session-API-Key: new-key → 200 ✓
  4. GET /api/server_info with X-Session-API-Key: bootstrap-key → 401 ✓

Video/Screenshots

In the video below, I start a server in dormant mode with the key dormantkey, and then use curl commands to initialize with the key activekey and validate that the new key works and the old one does not

Screen.Recording.2026-06-23.at.7.12.21.AM.mov

Type

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

Notes

This fix is backward-compatible: non-deferred servers (the common case) are unaffected — check_session_api_key returns immediately when config.session_api_keys is empty, same as before.

This PR was created by an AI agent (OpenHands) on behalf of the user.


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:4750fd7-python

Run

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

All tags pushed for this build

ghcr.io/openhands/agent-server:4750fd7-golang-amd64
ghcr.io/openhands/agent-server:4750fd7dec3927a7e7ac0f51b2a3a7903e6ac3c3-golang-amd64
ghcr.io/openhands/agent-server:fix-deferred-init-session-key-auth-golang-amd64
ghcr.io/openhands/agent-server:4750fd7-golang_tag_1.21-bookworm-amd64
ghcr.io/openhands/agent-server:4750fd7-golang-arm64
ghcr.io/openhands/agent-server:4750fd7dec3927a7e7ac0f51b2a3a7903e6ac3c3-golang-arm64
ghcr.io/openhands/agent-server:fix-deferred-init-session-key-auth-golang-arm64
ghcr.io/openhands/agent-server:4750fd7-golang_tag_1.21-bookworm-arm64
ghcr.io/openhands/agent-server:4750fd7-java-amd64
ghcr.io/openhands/agent-server:4750fd7dec3927a7e7ac0f51b2a3a7903e6ac3c3-java-amd64
ghcr.io/openhands/agent-server:fix-deferred-init-session-key-auth-java-amd64
ghcr.io/openhands/agent-server:4750fd7-eclipse-temurin_tag_17-jdk-amd64
ghcr.io/openhands/agent-server:4750fd7-java-arm64
ghcr.io/openhands/agent-server:4750fd7dec3927a7e7ac0f51b2a3a7903e6ac3c3-java-arm64
ghcr.io/openhands/agent-server:fix-deferred-init-session-key-auth-java-arm64
ghcr.io/openhands/agent-server:4750fd7-eclipse-temurin_tag_17-jdk-arm64
ghcr.io/openhands/agent-server:4750fd7-python-amd64
ghcr.io/openhands/agent-server:4750fd7dec3927a7e7ac0f51b2a3a7903e6ac3c3-python-amd64
ghcr.io/openhands/agent-server:fix-deferred-init-session-key-auth-python-amd64
ghcr.io/openhands/agent-server:4750fd7-nikolaik_s_python-nodejs_tag_python3.13-nodejs22-slim-amd64
ghcr.io/openhands/agent-server:4750fd7-python-arm64
ghcr.io/openhands/agent-server:4750fd7dec3927a7e7ac0f51b2a3a7903e6ac3c3-python-arm64
ghcr.io/openhands/agent-server:fix-deferred-init-session-key-auth-python-arm64
ghcr.io/openhands/agent-server:4750fd7-nikolaik_s_python-nodejs_tag_python3.13-nodejs22-slim-arm64
ghcr.io/openhands/agent-server:4750fd7-golang
ghcr.io/openhands/agent-server:4750fd7dec3927a7e7ac0f51b2a3a7903e6ac3c3-golang
ghcr.io/openhands/agent-server:fix-deferred-init-session-key-auth-golang
ghcr.io/openhands/agent-server:4750fd7-golang_tag_1.21-bookworm
ghcr.io/openhands/agent-server:4750fd7-java
ghcr.io/openhands/agent-server:4750fd7dec3927a7e7ac0f51b2a3a7903e6ac3c3-java
ghcr.io/openhands/agent-server:fix-deferred-init-session-key-auth-java
ghcr.io/openhands/agent-server:4750fd7-eclipse-temurin_tag_17-jdk
ghcr.io/openhands/agent-server:4750fd7-python
ghcr.io/openhands/agent-server:4750fd7dec3927a7e7ac0f51b2a3a7903e6ac3c3-python
ghcr.io/openhands/agent-server:fix-deferred-init-session-key-auth-python
ghcr.io/openhands/agent-server:4750fd7-nikolaik_s_python-nodejs_tag_python3.13-nodejs22-slim

About Multi-Architecture Support

  • Each variant tag (e.g., 4750fd7-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., 4750fd7-python-amd64) are also available if needed

The three session-key auth dependency factories
(create_session_api_key_dependency, create_workspace_session_dependency,
create_openai_api_key_dependency) all closed over the Config object
captured at server startup. When POST /api/init delivered new
session_api_keys, app.state.config was updated correctly but the
closure still held the old object, so the old key kept working and
the new key was rejected with 401.

A second related bug: _add_api_routes guarded each dependency with
"if config.session_api_keys:". In a dormant server that starts with
no keys (the common warm-pool case), this guard is False and no auth
dependency is ever registered, so new keys delivered via /api/init are
stored in app.state.config but go completely unchecked.

Fix both issues by:
- Replacing the three factory functions with plain FastAPI dependency
  functions that read config from request.app.state.config on every
  request.
- Removing the if-guards in _add_api_routes so the dependencies are
  always registered (the functions handle the empty-list case with an
  early return, matching how require_initialized is already wired).
- Dropping the now-unused config parameter from _add_api_routes.

The regression test test_check_session_api_key_reflects_config_update
directly verifies the dynamic behaviour: it mutates app.state.config
mid-test and asserts that the old key 401s and the new key 200s without
any route re-registration.

Co-authored-by: openhands <openhands@all-hands.dev>
@github-actions

github-actions Bot commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

Python API breakage checks — ✅ PASSED

Result: ✅ PASSED

Action log

@github-actions

github-actions Bot commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

REST API breakage checks (OpenAPI) — ✅ PASSED

Result: ✅ PASSED

Action log

@github-actions

github-actions Bot commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

Coverage

Coverage Report •
FileStmtsMissCoverMissing
openhands-agent-server/openhands/agent_server
   api.py2672690%109, 111–116, 118, 120, 122, 157, 169, 184, 190, 243, 248, 257–259, 495, 498, 502–504, 506, 513
   dependencies.py31293%55, 84
openhands-agent-server/openhands/agent_server/openai
   router.py41197%62
TOTAL328141417556% 

@tofarr
tofarr requested a review from all-hands-bot June 23, 2026 13:16

all-hands-bot commented Jun 23, 2026 •

Copy link
Copy Markdown
Collaborator

✅ Review complete.

This review was performed through OpenHands Cloud Automation. You can log in and view the conversation here.

@tofarr
tofarr marked this pull request as ready for review June 23, 2026 13:19

@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 fix that removes a structural wart and solves a real production bug.

What the change does

Replaces three closure-based auth-dependency factories (, , ) with plain FastAPI dependency functions that read at request time. This fixes two related bugs in the deferred-init flow:

  1. Stale closure: Factory functions closed over the object captured at startup. When replaced with a new object, the closures still validated against the old one — so new keys were rejected and old (bootstrap) keys kept working.
  2. Never-registered dependency: guarded each with . On a dormant server that starts with no keys (keys arrive at init time), this guard evaluates at startup — the auth dependency is never added, and keys delivered via go entirely unchecked.

Why this solution is correct

Moving the config read to request time is the idiomatic FastAPI fix for runtime-mutable server state. The dependency is always registered; the empty-list short-circuit inside each function () preserves the unauthenticated-server behaviour without any startup-time branching. Dropping the parameter from is a direct and welcome simplification.

Test quality

The refactored tests are a meaningful improvement over the old approach. The old tests called the inner closure directly (), bypassing FastAPI's DI machinery entirely. The new tests use and verify actual HTTP status codes through the full request lifecycle. The new regression test directly models the deferred-init scenario: mutate mid-test and assert that old keys are rejected and new keys are accepted — precisely what was broken before.

Evidence

The PR description includes a video demonstrating the end-to-end fix against a real dormant server, plus output showing 95 tests passing across the authentication test suite. Evidence quality is high.

[RISK ASSESSMENT]

  • [Overall PR] ⚠️ Risk Assessment: 🟡 MEDIUM
    This touches authentication middleware for all three route groups (, workspace routes, and the OpenAI-compat router). The logic is straightforward and well-tested, and the change is backward-compatible with non-deferred servers (the common case). The primary risk is an auth regression on the workspace or OpenAI routes; the existing and suites referenced in the PR mitigate that risk. Human sign-off before merging to main is appropriate given the security-adjacent nature of the change.

VERDICT:
✅ Worth merging — Two real bugs fixed with a cleaner design, solid test coverage, and a video demonstrating the end-to-end fix. Code is simpler after the change than before.

KEY INSIGHT:
Closing over config at route-registration time is fundamentally incompatible with deferred-init; reading at request time is the correct FastAPI pattern for runtime-mutable server state.

This review was generated by an AI agent (OpenHands) on behalf of the user through OpenHands Automation. View conversation

@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

Deferred-init auth now uses the post-init session keys for real agent-server HTTP requests, and the old/missing keys are rejected after initialization.

Does this PR achieve its stated goal?

Yes. The PR set out to make deferred-init session API key authentication read the current app.state.config after POST /api/init, and to ensure auth dependencies are registered even when the dormant server starts without session keys. I verified this by starting the actual agent-server, initializing it with session_api_keys: ["new-key"], and calling real /api/conversations/search and /v1/models endpoints on both the merge-base and PR commits: the base accepted stale/missing credentials or rejected the new key, while the PR accepts only the new key.

Phase Result
Environment Setup ✅ make build completed and installed the uv workspace successfully.
CI Status 🟡 Observed 35 successful, 2 skipped, 0 failing, and 1 pending (QA Changes by OpenHands/qa-changes).
Functional Verification ✅ Started real deferred-init agent-server instances and verified API/OpenAI auth before vs. after the PR.
Functional Verification

Test 1: Warm-pool start with no startup session keys

Step 1 — Reproduce baseline without the fix:
Checked out merge-base 48756c6f35b682e7a6be48a6ed7bc52d87ef3331, started the real server with:

OPENHANDS_SUPPRESS_BANNER=1 OH_DEFERRED_INIT=true OH_SECRET_KEY=bootstrap-key uv run agent-server

Then initialized and called the real API/OpenAI endpoints:

curl -H 'Content-Type: application/json' -H 'X-Init-API-Key: bootstrap-key'   --data-binary '{"session_api_keys":["new-key"]}' http://127.0.0.1:8000/api/init
curl -H 'X-Session-API-Key: new-key' http://127.0.0.1:8000/api/conversations/search
curl -H 'X-Session-API-Key: bootstrap-key' http://127.0.0.1:8000/api/conversations/search
curl http://127.0.0.1:8000/api/conversations/search
curl -H 'Authorization: Bearer new-key' http://127.0.0.1:8000/v1/models
curl -H 'Authorization: Bearer bootstrap-key' http://127.0.0.1:8000/v1/models
curl http://127.0.0.1:8000/v1/models

Observed:

base-no-key:init_http=200 body={"state":"ready","error":null}
base-no-key:api_new_http=200 body={"items":[],"next_page_id":null}
base-no-key:api_bootstrap_http=200 body={"items":[],"next_page_id":null}
base-no-key:api_missing_http=200 body={"items":[],"next_page_id":null}
base-no-key:openai_new_http=200 body={"object":"list","data":[]}
base-no-key:openai_bootstrap_http=200 body={"object":"list","data":[]}
base-no-key:openai_missing_http=200 body={"object":"list","data":[]}

This confirms the reported warm-pool bug: after init delivered new-key, the API and OpenAI-compatible route were still effectively open because the auth dependency was never registered at startup.

Step 2 — Apply the PR's changes:
Checked out PR commit 4750fd7dec3927a7e7ac0f51b2a3a7903e6ac3c3 and started the same server command.

Step 3 — Re-run with the fix in place:
Ran the same init and endpoint calls. Observed:

pr-no-key:init_http=200 body={"state":"ready","error":null}
pr-no-key:api_new_http=200 body={"items":[],"next_page_id":null}
pr-no-key:api_bootstrap_http=401 body={"detail":"Unauthorized"}
pr-no-key:api_missing_http=401 body={"detail":"Unauthorized"}
pr-no-key:openai_new_http=200 body={"object":"list","data":[]}
pr-no-key:openai_bootstrap_http=401 body={"detail":"Unauthorized"}
pr-no-key:openai_missing_http=401 body={"detail":"Unauthorized"}

This shows the fix works for the common dormant-server path: after init, only the newly delivered session key authorizes requests.

Test 2: Startup session key replaced during deferred init

Step 1 — Reproduce baseline without the fix:
Checked out merge-base 48756c6f35b682e7a6be48a6ed7bc52d87ef3331, started the real server with an initial session key:

OPENHANDS_SUPPRESS_BANNER=1 OH_DEFERRED_INIT=true OH_SECRET_KEY=bootstrap-key   OH_SESSION_API_KEYS='["old-key"]' uv run agent-server

Before init, old-key reached the dormant gate and missing auth was rejected, confirming the startup key was active:

base-startup-key:api_startup_http=503 body={"detail":"Internal Server Error","exception":"503: server is in deferred-init state 'dormant'; call POST /api/init first"}
base-startup-key:api_missing_http=401 body={"detail":"Unauthorized"}

After POST /api/init with new-key, observed:

base-startup-key:init_http=200 body={"state":"ready","error":null}
base-startup-key:api_new_http=401 body={"detail":"Unauthorized"}
base-startup-key:api_startup_http=200 body={"items":[],"next_page_id":null}
base-startup-key:api_missing_http=401 body={"detail":"Unauthorized"}
base-startup-key:openai_new_http=401 body={"detail":"Unauthorized"}
base-startup-key:openai_startup_http=200 body={"object":"list","data":[]}
base-startup-key:openai_missing_http=401 body={"detail":"Unauthorized"}

This reproduces the stale-config bug: routes continued authorizing old-key and rejected the new post-init key.

Step 2 — Apply the PR's changes:
Checked out PR commit 4750fd7dec3927a7e7ac0f51b2a3a7903e6ac3c3 and repeated the same startup-key scenario.

Step 3 — Re-run with the fix in place:
Observed:

pr-startup-key:init_http=200 body={"state":"ready","error":null}
pr-startup-key:api_new_http=200 body={"items":[],"next_page_id":null}
pr-startup-key:api_startup_http=401 body={"detail":"Unauthorized"}
pr-startup-key:api_missing_http=401 body={"detail":"Unauthorized"}
pr-startup-key:openai_new_http=200 body={"object":"list","data":[]}
pr-startup-key:openai_startup_http=401 body={"detail":"Unauthorized"}
pr-startup-key:openai_missing_http=401 body={"detail":"Unauthorized"}

This confirms request-time config lookup after init: the new key works and the old startup key no longer does.

Issues Found

None.

This QA review was created by an AI agent (OpenHands) on behalf of the user.

@tofarr
tofarr merged commit 09653fc into main Jun 23, 2026
43 of 44 checks passed
@tofarr
tofarr deleted the fix/deferred-init-session-key-auth branch June 23, 2026 13:34
@enyst

enyst commented Jun 23, 2026

Copy link
Copy Markdown
Member

@OpenHands Understand this PR. Then look at PR 400 and understand its goal. Find the PR where defered init was introduced, and understand how it was done, too.

Clone yourself enyst.github.com and see we have html docs there, studies and arch docs.

Add a new arch page where you document

  1. the current flow and its risks
  2. a flow like PR 400, and compare the two.

WDYT about less error-prone, standardized design pattern for the goals needed here?

Think deeply. Use frontend-design skill or the like to create a readable page with diagrams that work well.

Do not modify this PR, it was merged.

@openhands-ai

openhands-ai Bot commented Jun 23, 2026

Copy link
Copy Markdown

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

enyst commented Jun 23, 2026

Copy link
Copy Markdown
Member

I dug through PR #3844, PR #400, and PR #3287 (the deferred-init introduction), then added the requested architecture note in the docs site repo here:

enyst/enyst.github.io#3

My take: the less error-prone pattern is to standardize a typed request-time runtime boundary instead of letting routes/services read config through a mix of startup closures, app.state fields, singleton helpers, and module globals. The doc proposes a small AgentServerRuntime provider: routes are registered once, all HTTP/WebSocket auth and service dependencies resolve through that provider, and /api/init builds a complete ready runtime off to the side before atomically swapping it into app.state. It also calls out the static app-shape vs runtime-config split, since fields like CORS/root path behave differently from session keys or persistence paths.

This comment was created by an AI agent (OpenHands) on behalf of the user.

@openhands-ai

openhands-ai Bot commented Jun 23, 2026

Copy link
Copy Markdown

OpenHands encountered an error: **Failed to send message to agent server: HTTP 503 error: no available server
**

See the conversation for more information.

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