Repository navigation
feat(agent-server): register refresh-on-401 hook on managed-proxy LLMs - #5222
Conversation
9e8dd79 to
cbacef2
Compare
REST API breakage checks (OpenAPI) — ✅ PASSEDResult: ✅ PASSED |
Coverage Report •
|
||||||||||||||||||||
71717ae to
0cf4e2e
Compare
Mutation review of the new testsI hand-wrote 9 mutants against Controls — all caught ✅
The suite works because it doesn't stop at the return count: Survivors — gaps 🔎
1. Trailing-slash normalization on
|
… headers Address mutation review on #5222: add tests that kill the surviving mutants around base_url allow-list normalization and the _load_headers non-object guard. - test_base_url_match_ignores_trailing_slash / test_allowlist_entry_trailing_slash_ignored assert the .rstrip("/") on both the LLM base_url and the allow-list entries. - test_non_object_headers_env_is_ignored asserts valid-but-non-object JSON in OH_LLM_API_KEY_REFRESH_HEADERS is ignored instead of crashing registration. Co-authored-by: openhands <openhands@all-hands.dev>
|
Thanks for the thorough mutation review — pushed in 10eda0b. Added all three suggested tests to
On #3 ( Full suite now 11 passed. This comment was created by an AI agent (OpenHands) on behalf of the user. |
There was a problem hiding this comment.
Code Review — register refresh-on-401 hook on managed-proxy LLMs
Taste rating: good.
Small, well-scoped, opt-in wiring change. It adds openhands/agent_server/managed_llm_key.py (register_managed_llm_key_refresh), calls it once in event_service.py right after the LocalConversation is built, and ships a focused test suite. I traced the full data/control flow — the SDK primitive from the base PR, the LLM iteration, secret resolution, and the retry path — and could not prove any material finding.
What I verified
- Scope target: PR head
10eda0b, basefix/llm-refresh-on-401-5189(stacked on #5218). The base primitive commits (df54473,7e66677,915fc3d) are present in the head, so this review reflects the merged behavior. - Mechanism correctness: The hook is registered only when
OH_LLM_API_KEY_REFRESH_URLis set, and_llm_is_in_scopegates onauth_type == "api_key"plus an optionalbase_urlallow-list. The SDK's_resolve_refreshed_api_keyindependently re-checksauth_type == "api_key",looks_like_auth_error, empty-key, and same-key — so a failed or no-op refresh provably cannot mask the original 401._refreshalso swallows all exceptions and returnsNone. Defense is layered on both sides. - Placement: Registration is correctly done in the process that runs the LLM (the hook is a non-serializable
PrivateAttr) and re-runs on resume since the private attr never travels in state.agent.get_all_llms()is defined for bothAgentandACPAgent. - Tests reach real code: The suite drives the SDK's own
_resolve_refreshed_api_keywith a real litellmAuthenticationErrorand asserts observable outcomes (fresh key returned / no retry), not mock wiring.register_local_secret_resolverserves theLookupSecretURL in-process without real HTTP. Ran locally: 11 passed in 0.21s. - CI: All checks green on the current head (
sdk-tests,agent-server-tests,pre-commit,integration-test, coverage 98% on the new module). - Prior discussion: Only AI/author mutation-testing comments, all addressed by added trailing-slash and non-object-headers tests. No unresolved human review threads.
Non-blocking consideration (not a blocking finding)
- No-allow-list default and BYOK key leakage (
managed_llm_key.py,_llm_is_in_scope): WhenOH_LLM_API_KEY_REFRESH_BASE_URLSis unset, the hook attaches to everyapi_keyLLM, including a user's BYOK LLM. The SDK retry (_auth_refreshed_llm) reuses the LLM's ownbase_url, so a BYOK LLM's 401 would retry with the managed proxy key against the user-controlled endpoint (e.g.api.openai.com) — i.e. the managed secret could reach a non-managed host. This is explicitly documented as "strongly recommended" to avoid, is fully operator-controlled (requires opting in and omitting the recommended allow-list), and the PR states the control plane sets all three env vars per conversation. It is therefore a documented design boundary rather than a proven defect. Worth considering whether the allow-list should be required (fail-closed) when the feature is enabled, as defense-in-depth — but I would not block on it.
Acceptance-criteria check
The PR intentionally delivers only the agent-server registration half; persistence, end-to-end managed-key rotation, and recovery UX from #5189 live in the enterprise repo and are out of scope here. That boundary matches #5218 and is clearly stated.
[RISK ASSESSMENT]
[Overall PR]
The change is inert unless a deployment opts in, is narrowly scoped, and is well-tested with green current-head CI. The one factor lifting it above 🟢 LOW is security sensitivity: it wires a security-sensitive credential path (the managed proxy key), which is guarded on both the agent-server and SDK sides and further protectable via the allow-list. Blast radius is limited (opt-in, single new module), and there are no system-level or untrusted-code operations. Reviewer focus area: the no-allow-list default called out above.
Verdict: Approve (no material findings; the fail-closed allow-list suggestion above is a non-blocking consideration). Note this is a draft PR stacked on #5218 — #5218 must merge first and the base will retarget to main, after which a rebase is expected.
Key architectural insight: The correctness of this feature rests entirely on scoping (which LLMs receive the hook) rather than on the refresh mechanism itself — the SDK already fails safe on empty/same/subscription keys. So the allow-list is the real security boundary, which is exactly why making it fail-closed rather than "strongly recommended" is the one design lever worth a second look.
Improve this review? If feedback seems incorrect or irrelevant, update the repository's
.agents/skills/custom-codereview-guide.md(with the/codereviewtrigger), then re-request review. The reviewer reads the guide from the PR head.Resolve with AI? Install the iterate skill and run
/iterate.Was this review helpful? React with 👍 or 👎.
This review was generated by an AI agent (OpenHands) on behalf of the user.
… headers Address mutation review on #5222: add tests that kill the surviving mutants around base_url allow-list normalization and the _load_headers non-object guard. - test_base_url_match_ignores_trailing_slash / test_allowlist_entry_trailing_slash_ignored assert the .rstrip("/") on both the LLM base_url and the allow-list entries. - test_non_object_headers_env_is_ignored asserts valid-but-non-object JSON in OH_LLM_API_KEY_REFRESH_HEADERS is ignored instead of crashing registration. Co-authored-by: openhands <openhands@all-hands.dev>
29504e7 to
338474c
Compare
juanmichelini
left a comment
There was a problem hiding this comment.
Could we treat a missing allow-list as "feature off." If OH_LLM_API_KEY_REFRESH_BASE_URLS is unset, log and return 0 instead of matching all LLMs. The operator must explicitly enumerate the managed proxy base_urls to turn the feature on.
… headers Address mutation review on #5222: add tests that kill the surviving mutants around base_url allow-list normalization and the _load_headers non-object guard. - test_base_url_match_ignores_trailing_slash / test_allowlist_entry_trailing_slash_ignored assert the .rstrip("/") on both the LLM base_url and the allow-list entries. - test_non_object_headers_env_is_ignored asserts valid-but-non-object JSON in OH_LLM_API_KEY_REFRESH_HEADERS is ignored instead of crashing registration. Co-authored-by: openhands <openhands@all-hands.dev>
338474c to
c365d53
Compare
|
Good call — done in cc19e12, the feature now fails closed.
Tests: This comment was created by an AI agent (OpenHands) on behalf of the PR author. |
… headers Address mutation review on #5222: add tests that kill the surviving mutants around base_url allow-list normalization and the _load_headers non-object guard. - test_base_url_match_ignores_trailing_slash / test_allowlist_entry_trailing_slash_ignored assert the .rstrip("/") on both the LLM base_url and the allow-list entries. - test_non_object_headers_env_is_ignored asserts valid-but-non-object JSON in OH_LLM_API_KEY_REFRESH_HEADERS is ignored instead of crashing registration. Co-authored-by: openhands <openhands@all-hands.dev>
cc19e12 to
ec95651
Compare
|
@OpenHands investigate failing PR description check |
|
I'm on it! aivong-openhands can track my progress at all-hands.dev |
|
The failing PR Description Check on PR #5222 is fixed. Root cause: the check's Fix applied: rewrote that sentence to Result: GitHub auto-triggered a re-run of |
all-hands-bot
left a comment
There was a problem hiding this comment.
This review was posted by an AI agent (OpenHands).
Review: feat(agent-server): register refresh-on-401 hook on managed-proxy LLMs
Scope
The change belongs in this repository: it adds an agent-server module (openhands-agent-server/openhands/agent_server/managed_llm_key.py) that registers the SDK hook in the process that actually runs the LLM, and the SDK primitive it depends on (set_api_key_refresh_hook) already exists on the base branch. Ownership, packaging, and layering are correct, so I continued the technical review.
Material finding: the allow-list can never match the canonical managed-proxy LLM, so the feature is inert for the case it exists to fix
_llm_is_in_scope compares the LLM's raw llm.base_url against the allow-list. For the hosted managed configuration in issue #5189 (model: openhands/deepseek-v4.1-flash, base_url: null), llm.base_url is None; the proxy URL is only materialized later at the LiteLLM boundary by litellm_call_kwargs() (openhands-sdk/openhands/sdk/llm/utils/openhands_provider.py), which falls back to OPENHANDS_LLM_PROXY_BASE_URL (https://llm-proxy.app.all-hands.dev). I reproduced this on the head:
base_url = None
effective api_base = https://llm-proxy.app.all-hands.dev
hooks registered = 0 # even with OH_LLM_API_KEY_REFRESH_BASE_URLS set to that URL
This is not a test-only artifact: the SDK canonicalization actively removes base_url when it equals the OpenHands proxy URL (canonicalize_openhands_llm_payload -> is_openhands_proxy_base_url), and issue #5189's own settings dump shows agent_settings.llm.base_url: null. So both a fresh openhands/<model> LLM and a persisted-then-reloaded one converge on base_url is None, the allow-list never matches, register_managed_llm_key_refresh returns 0, and no hook is attached - exactly the 401 token_not_found_in_db path this PR is meant to recover in place.
The fix is to match against the effective API base the call actually uses (llm._litellm_call_kwargs()["api_base"]), or otherwise resolve the openhands/ provider default, rather than the raw base_url field. The new tests set base_url explicitly on every managed LLM, so they do not exercise this configuration and pass while the production shape does not.
Other checks (no findings)
- Fail-closed gating on both required env vars, the
api_key-only and BYOK exclusion, the per-callLookupSecret(no cached rotation), whitespace stripping, and swallowing refresh errors so the original 401 surfaces are all correct and covered. - Header
$VAR/${VAR}expansion is sound and needed for the remoteOH_SESSION_API_KEYS_0case. - All check runs on head
ec95651eare green (test (24.x),pre-commit,coverage-report,agent-server-stress-tests,cross-tests, binaries, images).
Because the primary managed-proxy scenario from #5189 is not reached by the current matching logic, this needs a code change before merge.
🔄 CHANGES REQUESTED
… headers Address mutation review on #5222: add tests that kill the surviving mutants around base_url allow-list normalization and the _load_headers non-object guard. - test_base_url_match_ignores_trailing_slash / test_allowlist_entry_trailing_slash_ignored assert the .rstrip("/") on both the LLM base_url and the allow-list entries. - test_non_object_headers_env_is_ignored asserts valid-but-non-object JSON in OH_LLM_API_KEY_REFRESH_HEADERS is ignored instead of crashing registration. Co-authored-by: openhands <openhands@all-hands.dev>
7215137 to
f8c128d
Compare
all-hands-bot
left a comment
There was a problem hiding this comment.
This review was posted by an AI agent (OpenHands).
Review: feat(agent-server): register refresh-on-401 hook on managed-proxy LLMs
Scope
Belongs in this repository. The change adds an agent-server module (openhands-agent-server/openhands/agent_server/managed_llm_key.py) that registers the SDK hook in the process that actually runs the LLM, and the SDK primitive it depends on (set_api_key_refresh_hook) is already present on main now that this PR is retargeted. Ownership, layering, and packaging are correct (pure-Python module, no new data files or optional deps).
Previous finding: resolved
The earlier review flagged that scope matching used the raw llm.base_url, which is None for the canonical hosted managed configuration (openhands/<model>), so the allow-list could never match. Commit a09dff1 switches _llm_is_in_scope to litellm_call_kwargs(llm.model, llm.base_url)["api_base"], i.e. the effective provider URL. I re-verified on the current head with OH_LLM_API_KEY_REFRESH_BASE_URLS=https://llm-proxy.app.all-hands.dev and an LLM(model="openhands/deepseek-v4.1-flash", base_url=None): register_managed_llm_key_refresh now returns 1 (previously 0). The new test_canonical_managed_provider_refreshes[False|True] covers both the fresh and the serialized/reloaded LLM and drives a real completion() through stale-key 401 → refreshed-key success, which is the production failure mode from #5189.
Verification on this head
- Focused suite:
tests/agent_server/test_managed_llm_key.py+tests/agent_server/test_managed_llm_key_http.py→ 28 passed;tests/sdk/llm/test_auth_refresh_retry.py→ 17 passed. - All check runs on head
4140a134are green (test (24.x),test (22.12),agent-server-tests,sdk-tests,tools-tests,workspace-tests,coverage-report,agent-server-stress-tests,cross-tests,acp-live-tests, binaries and images). - Fail-closed gating on both required env vars, the
api_key-only and BYOK exclusions, per-callLookupSecret(no cached rotation), whitespace stripping, swallowing refresh errors so the original 401 surfaces, and header$VAR/${VAR}expansion are all correct. - The no-hook-registered case for a genuinely mismatched provider is safe:
(?litellm?...)returnsapi_base=Nonefor e.g. a BYOK endpoint, which normalizes to""and cannot accidentally match an allow-list entry (empty entries are filtered).
The one operational note is that the operator must enumerate the effective proxy URL exactly (for the openhands/ provider that is https://llm-proxy.app.all-hands.dev, without /v1), since trailing-slash normalization only — not path-suffix equivalence — is applied. That is configuration guidance for the Enterprise wiring, not a defect in this diff.
No material correctness, security, or compatibility findings on the current head.
✅ APPROVED
Wire the SDK's opt-in API-key refresh hook (set_api_key_refresh_hook, added in #5218) at LocalConversation build time so a managed proxy key rotated/healed after the conversation snapshot recovers in place instead of failing the first call with 401 token_not_found_in_db (#5189). The hook is a non-serializable Python callable, so it must be registered in the process where the LLM runs (the sandbox agent-server), not where the app-server builds and serializes the LLM. - managed_llm_key.register_managed_llm_key_refresh(agent): iterates agent.get_all_llms() and registers a hook on in-scope managed LLMs. - Re-resolves the current key via LookupSecret (fresh per call, strips whitespace, never raises -> returns None so the original 401 surfaces). - Opt-in and inert by default: no-op unless the control plane sets OH_LLM_API_KEY_REFRESH_URL. Optional OH_LLM_API_KEY_REFRESH_HEADERS and OH_LLM_API_KEY_REFRESH_BASE_URLS (scope to the managed proxy; keep BYOK LLMs untouched). Subscription auth is skipped. - event_service wires one register call after LocalConversation build. - Tests cover: off=no-op, feeds SDK resolution, base-url scoping, skips subscription, empty/failed refresh -> no retry, bad headers ignored. Co-authored-by: openhands <openhands@all-hands.dev>
… headers Address mutation review on #5222: add tests that kill the surviving mutants around base_url allow-list normalization and the _load_headers non-object guard. - test_base_url_match_ignores_trailing_slash / test_allowlist_entry_trailing_slash_ignored assert the .rstrip("/") on both the LLM base_url and the allow-list entries. - test_non_object_headers_env_is_ignored asserts valid-but-non-object JSON in OH_LLM_API_KEY_REFRESH_HEADERS is ignored instead of crashing registration. Co-authored-by: openhands <openhands@all-hands.dev>
Header values in OH_LLM_API_KEY_REFRESH_HEADERS may now reference environment
variables with $VAR / ${VAR} syntax, expanded from the sandbox environment.
This lets the control plane point an auth header at a per-sandbox credential it
cannot know when it builds the environment. In particular, remote runtimes
assign the sandbox session key (OH_SESSION_API_KEYS_0) inside the sandbox and
only return it after start, so the app server cannot embed a literal value; a
${OH_SESSION_API_KEYS_0} reference resolves at hook-build time instead.
Co-authored-by: openhands <openhands@all-hands.dev>
Co-authored-by: openhands <openhands@all-hands.dev>
Co-authored-by: openhands <openhands@all-hands.dev>
Co-authored-by: openhands <openhands@all-hands.dev>
4140a13 to
120d5fc
Compare
|
@juanmichelini can you assist with the merge? |
HUMAN:
opt into refresh on 401 hook
AGENT:
Why
#5218 adds the SDK primitive
LLM.set_api_key_refresh_hook()— re-resolve the API key and retry once on a 401 — but by design registers it nowhere, so on its own the mechanism never fires. This PR is the agent-server half: when a managed LiteLLM proxy key is rotated or healed after a conversation's LLM snapshot was taken, the sandbox keeps sending the stale key and its first call fails with401 token_not_found_in_db; only the next conversation picks up the fresh key (#5189). Registering the hook lets that first conversation re-resolve the key and recover in place.The hook has to be registered here rather than where the app-server builds the LLM: it is a Python callable held as a non-serializable private attribute, so it cannot travel with the serialized LLM into the sandbox — it must be attached in the process that actually runs the LLM and sees the 401.
The change is safe because it fails closed: registration is skipped entirely unless the deployment sets both
OH_LLM_API_KEY_REFRESH_URLandOH_LLM_API_KEY_REFRESH_BASE_URLS, the explicit allow-list of managed-proxybase_urls. Even then it attaches only toapi_keyLLMs whose effective provider URL is on that list, never to subscription auth or a user's BYOK key. A failed refresh returns nothing so the original 401 still surfaces.Summary
openhands/agent_server/managed_llm_key.pywithregister_managed_llm_key_refresh(agent), which walksagent.get_all_llms()and attaches a refresh hook to each in-scope managed LLM. The hook re-resolves the current key through a freshly builtLookupSecreteach call, strips whitespace, and swallows errors (returning nothing) so a failed refresh cannot mask the original auth error.event_service.pyright after theLocalConversationis built.OH_LLM_API_KEY_REFRESH_URL(required),OH_LLM_API_KEY_REFRESH_HEADERS(optional JSON auth headers; values may reference env vars via$VAR/${OH_SESSION_API_KEYS_0}syntax, expanded from the sandbox environment, so the control plane can point a header at a per-sandbox credential it cannot know up front),OH_LLM_API_KEY_REFRESH_BASE_URLS(required allow-list of managed-proxybase_urls; unset or empty logs a warning and leaves the feature off).tests/agent_server/test_managed_llm_key.py(16 tests, including canonical managed-provider recovery, persisted LLM reload, header env-var expansion, and fail-closed allow-list cases).Issue Number
Part of #5189. Stacked on PR 5218 — the base branch of this PR is
fix/llm-refresh-on-401-5189, notmain; it depends on theset_api_key_refresh_hookmethod that PR adds.How to Test
33 tests and pre-commit pass after merging current main. Two regression cases fail before the effective-URL fix: a fresh and a serialized/reloaded
openhands/LLM withbase_url=Nonemust register the hook and complete a call using the refreshed key after a 401. Scope matching reuses the SDK's provider URL resolver; explicit BYOK URLs and subscription auth retain their existing exclusions.Combined with SDK PR 5309, 76 targeted tests pass. A local HTTP fixture exercises the real SDK and registered agent-server hook in sync and async modes: stale key → 401 → authenticated key refresh → budget 429 stops immediately; lifting the fixture limit lets the same LLM resume. This is component integration evidence, not deployed Enterprise/Replicated acceptance. Enterprise PR 468 and released SDK/image pins remain necessary for that acceptance.
Type
Notes
main; I will then rebase so the diff stays limited to the registration changes.OpenHands/enterprise#468): exposesGET /api/keys/llm/managed/current(current/rotated managed key on demand) and injects the three sandbox env vars per sandbox with matchingOH_-prefixed names. Its refresh header references${OH_SESSION_API_KEYS_0}, which relies on the header env-var expansion added in this PR so the remote sandbox path works (the runtime assigns that key inside the sandbox and only returns it after start, so the app server cannot embed a literal value). Still pending there: bumping the pinnedopenhands-agent-server/openhands-sdk(which also advances the sandbox imageghcr.io/openhands/agent-server:<version>-python). Persistence, BYOK safety, and recovery UX from [Bug] Hosted OpenHands Cloud returns 401 token_not_found_in_db after restoring default managed LLM profile #5189's acceptance criteria live there.This PR was drafted by an AI agent on behalf of the user.
🐳 Agent Server images for this PR — GHCR package, pull/run commands, and all pushed tags (click to expand)
• GHCR package: https://github.com/OpenHands/agent-sdk/pkgs/container/agent-server
Variants & Base Images
eclipse-temurin:17-jdkpython-node-runtimepython-node-runtimepython-node-runtimegolang: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:120d5fc-pythonRun
All tags pushed for this build
About Multi-Architecture Support
120d5fc-python) is a multi-arch manifest supporting both amd64 and arm64120d5fc-python-amd64) are also available if needed