Repository navigation
fix: deferred-init session API key auth uses app.state config at request time - #3844
Conversation
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>
Python API breakage checks — ✅ PASSEDResult: ✅ PASSED |
REST API breakage checks (OpenAPI) — ✅ PASSEDResult: ✅ PASSED |
Coverage Report •
|
|||||||||||||||||||||||||||||||||||
|
✅ Review complete. This review was performed through OpenHands Cloud Automation. You can log in and view the conversation here. |
all-hands-bot
left a comment
There was a problem hiding this comment.
🟢 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:
- 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.
- 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
left a comment
There was a problem hiding this comment.
✅ 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-serverThen 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/modelsObserved:
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-serverBefore 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.
|
@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
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. |
|
I'm on it! enyst can track my progress at all-hands.dev |
|
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: 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 This comment was created by an AI agent (OpenHands) on behalf of the user. |
|
OpenHands encountered an error: **Failed to send message to agent server: HTTP 503 error: no available server See the conversation for more information. |
…est time (OpenHands#3844) Co-authored-by: openhands <openhands@all-hands.dev>
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/initdelivers newsession_api_keysto 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:Stale closure: All three auth dependency factories (
create_session_api_key_dependency,create_workspace_session_dependency,create_openai_api_key_dependency) closed over theConfigobject captured at server startup.POST /api/initcorrectly wrote the new config toapp.state.config, but the closure still validated against the old object, so old keys passed and new keys failed.Never-registered dependency:
_add_api_routesguarded each dependency withif 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 isFalseand no auth dependency is ever registered — meaning keys delivered via/api/initare stored inapp.state.configbut go completely unchecked.Summary
check_session_api_key,check_workspace_session,check_openai_api_key) that readconfigfromrequest.app.state.configon every request.if config.session_api_keys:guards in_add_api_routes; the plain functions handle the empty-list case with an early return (consistent with howrequire_initializedis already unconditionally registered).configparameter 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_updatemutatesapp.state.configmid-test and asserts:Run with:
All 95 tests pass.
To test end-to-end manually against a dormant server:
OH_DEFERRED_INIT=true OH_SECRET_KEY=bootstrap-keyPOST /api/initwithX-Init-API-Key: bootstrap-keyand body{"session_api_keys": ["new-key"]}GET /api/server_infowithX-Session-API-Key: new-key→ 200 ✓GET /api/server_infowithX-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 keyactivekeyand validate that the new key works and the old one does notScreen.Recording.2026-06-23.at.7.12.21.AM.mov
Type
Notes
This fix is backward-compatible: non-deferred servers (the common case) are unaffected —
check_session_api_keyreturns immediately whenconfig.session_api_keysis 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
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:4750fd7-pythonRun
All tags pushed for this build
About Multi-Architecture Support
4750fd7-python) is a multi-arch manifest supporting both amd64 and arm644750fd7-python-amd64) are also available if needed