Skip to content

feat(agent-server): register refresh-on-401 hook on managed-proxy LLMs - #5222

Merged
ak684 merged 9 commits into
mainfrom
feat/agent-server-register-refresh-hook-5189
Sep 29, 2026
Merged

ak684 merged 9 commits into
mainfrom
feat/agent-server-register-refresh-hook-5189

Conversation

@aivong-openhands

@aivong-openhands aivong-openhands commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

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 with 401 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_URL and OH_LLM_API_KEY_REFRESH_BASE_URLS, the explicit allow-list of managed-proxy base_urls. Even then it attaches only to api_key LLMs 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

  • Add openhands/agent_server/managed_llm_key.py with register_managed_llm_key_refresh(agent), which walks agent.get_all_llms() and attaches a refresh hook to each in-scope managed LLM. The hook re-resolves the current key through a freshly built LookupSecret each call, strips whitespace, and swallows errors (returning nothing) so a failed refresh cannot mask the original auth error.
  • Call it once in event_service.py right after the LocalConversation is built.
  • Opt-in via env vars read from the sandbox: 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-proxy base_urls; unset or empty logs a warning and leaves the feature off).
  • Add 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, not main; it depends on the set_api_key_refresh_hook method that PR adds.

How to Test

uv run pytest tests/agent_server/test_managed_llm_key.py tests/sdk/llm/test_auth_refresh_retry.py -q
uv run pre-commit run --files openhands-agent-server/openhands/agent_server/managed_llm_key.py tests/agent_server/test_managed_llm_key.py

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 with base_url=None must 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

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

Notes

  • Merge order: feat(llm): OHE-3276 refresh API key and retry once on a 401 #5218 must merge first. When it does, GitHub retargets this PR's base to main; I will then rebase so the diff stays limited to the registration changes.
  • Enterprise side (separate repo, OpenHands/enterprise#468): exposes GET /api/keys/llm/managed/current (current/rotated managed key on demand) and injects the three sandbox env vars per sandbox with matching OH_-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 pinned openhands-agent-server/openhands-sdk (which also advances the sandbox image ghcr.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

Variant Architectures Base Image Docs / Tags
java amd64, arm64 eclipse-temurin:17-jdk Link
python-slim amd64, arm64 python-node-runtime Link
python-minimal amd64, arm64 python-node-runtime Link
python amd64, arm64 python-node-runtime 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:120d5fc-python

Run

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

All tags pushed for this build

ghcr.io/openhands/agent-server:120d5fc-golang-amd64
ghcr.io/openhands/agent-server:120d5fcc61263d51f70d25ea24a8b804fec54128-golang-amd64
ghcr.io/openhands/agent-server:feat-agent-server-register-refresh-hook-5189-golang-amd64
ghcr.io/openhands/agent-server:120d5fc-golang_tag_1.21-bookworm-amd64
ghcr.io/openhands/agent-server:120d5fc-golang-arm64
ghcr.io/openhands/agent-server:120d5fcc61263d51f70d25ea24a8b804fec54128-golang-arm64
ghcr.io/openhands/agent-server:feat-agent-server-register-refresh-hook-5189-golang-arm64
ghcr.io/openhands/agent-server:120d5fc-golang_tag_1.21-bookworm-arm64
ghcr.io/openhands/agent-server:120d5fc-java-amd64
ghcr.io/openhands/agent-server:120d5fcc61263d51f70d25ea24a8b804fec54128-java-amd64
ghcr.io/openhands/agent-server:feat-agent-server-register-refresh-hook-5189-java-amd64
ghcr.io/openhands/agent-server:120d5fc-eclipse-temurin_tag_17-jdk-amd64
ghcr.io/openhands/agent-server:120d5fc-java-arm64
ghcr.io/openhands/agent-server:120d5fcc61263d51f70d25ea24a8b804fec54128-java-arm64
ghcr.io/openhands/agent-server:feat-agent-server-register-refresh-hook-5189-java-arm64
ghcr.io/openhands/agent-server:120d5fc-eclipse-temurin_tag_17-jdk-arm64
ghcr.io/openhands/agent-server:120d5fc-python-amd64
ghcr.io/openhands/agent-server:120d5fcc61263d51f70d25ea24a8b804fec54128-python-amd64
ghcr.io/openhands/agent-server:feat-agent-server-register-refresh-hook-5189-python-amd64
ghcr.io/openhands/agent-server:120d5fc-python-node-runtime-amd64
ghcr.io/openhands/agent-server:120d5fc-python-arm64
ghcr.io/openhands/agent-server:120d5fcc61263d51f70d25ea24a8b804fec54128-python-arm64
ghcr.io/openhands/agent-server:feat-agent-server-register-refresh-hook-5189-python-arm64
ghcr.io/openhands/agent-server:120d5fc-python-node-runtime-arm64
ghcr.io/openhands/agent-server:120d5fc-python-minimal-amd64
ghcr.io/openhands/agent-server:120d5fcc61263d51f70d25ea24a8b804fec54128-python-minimal-amd64
ghcr.io/openhands/agent-server:feat-agent-server-register-refresh-hook-5189-python-minimal-amd64
ghcr.io/openhands/agent-server:120d5fc-python-node-runtime-minimal-amd64
ghcr.io/openhands/agent-server:120d5fc-python-minimal-arm64
ghcr.io/openhands/agent-server:120d5fcc61263d51f70d25ea24a8b804fec54128-python-minimal-arm64
ghcr.io/openhands/agent-server:feat-agent-server-register-refresh-hook-5189-python-minimal-arm64
ghcr.io/openhands/agent-server:120d5fc-python-node-runtime-minimal-arm64
ghcr.io/openhands/agent-server:120d5fc-python-slim-amd64
ghcr.io/openhands/agent-server:120d5fcc61263d51f70d25ea24a8b804fec54128-python-slim-amd64
ghcr.io/openhands/agent-server:feat-agent-server-register-refresh-hook-5189-python-slim-amd64
ghcr.io/openhands/agent-server:120d5fc-python-node-runtime-slim-amd64
ghcr.io/openhands/agent-server:120d5fc-python-slim-arm64
ghcr.io/openhands/agent-server:120d5fcc61263d51f70d25ea24a8b804fec54128-python-slim-arm64
ghcr.io/openhands/agent-server:feat-agent-server-register-refresh-hook-5189-python-slim-arm64
ghcr.io/openhands/agent-server:120d5fc-python-node-runtime-slim-arm64
ghcr.io/openhands/agent-server:120d5fc-golang
ghcr.io/openhands/agent-server:120d5fcc61263d51f70d25ea24a8b804fec54128-golang
ghcr.io/openhands/agent-server:feat-agent-server-register-refresh-hook-5189-golang
ghcr.io/openhands/agent-server:120d5fc-golang_tag_1.21-bookworm
ghcr.io/openhands/agent-server:120d5fc-java
ghcr.io/openhands/agent-server:120d5fcc61263d51f70d25ea24a8b804fec54128-java
ghcr.io/openhands/agent-server:feat-agent-server-register-refresh-hook-5189-java
ghcr.io/openhands/agent-server:120d5fc-eclipse-temurin_tag_17-jdk
ghcr.io/openhands/agent-server:120d5fc-python-minimal
ghcr.io/openhands/agent-server:120d5fcc61263d51f70d25ea24a8b804fec54128-python-minimal
ghcr.io/openhands/agent-server:feat-agent-server-register-refresh-hook-5189-python-minimal
ghcr.io/openhands/agent-server:120d5fc-python-node-runtime-minimal
ghcr.io/openhands/agent-server:120d5fc-python-slim
ghcr.io/openhands/agent-server:120d5fcc61263d51f70d25ea24a8b804fec54128-python-slim
ghcr.io/openhands/agent-server:feat-agent-server-register-refresh-hook-5189-python-slim
ghcr.io/openhands/agent-server:120d5fc-python-node-runtime-slim
ghcr.io/openhands/agent-server:120d5fc-python
ghcr.io/openhands/agent-server:120d5fcc61263d51f70d25ea24a8b804fec54128-python
ghcr.io/openhands/agent-server:feat-agent-server-register-refresh-hook-5189-python
ghcr.io/openhands/agent-server:120d5fc-python-node-runtime

About Multi-Architecture Support

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

@aivong-openhands
aivong-openhands marked this pull request as draft September 22, 2026 14:30
@aivong-openhands
aivong-openhands force-pushed the feat/agent-server-register-refresh-hook-5189 branch from 9e8dd79 to cbacef2 Compare September 22, 2026 14:32
@github-actions

github-actions Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

REST API breakage checks (OpenAPI) — ✅ PASSED

Result: ✅ PASSED

Action log

@github-actions

github-actions Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Coverage

Coverage Report •
FileStmtsMissCoverMissing
openhands-agent-server/openhands/agent_server
   event_service.py92212087%185–186, 308, 312, 317, 344, 351, 385, 388–389, 393–394, 405, 411, 440–442, 445–446, 535–536, 657, 677, 704, 728–729, 733, 741, 744, 760, 792, 803, 810, 816, 876, 879, 894–895, 983, 1013, 1016, 1054, 1094, 1112, 1126, 1274, 1394–1397, 1401, 1441, 1445, 1452, 1466, 1481, 1528–1530, 1610, 1635, 1641, 1643, 1653, 1655, 1662, 1672, 1674–1675, 1679, 1693–1698, 1700, 1727, 1733, 1742–1743, 1749–1752, 1760–1763, 1807–1809, 1864–1865, 1867–1874, 1876–1877, 1886–1887, 1889–1890, 1897–1898, 1900–1901, 1912, 1937, 1943, 1949, 1958–1959, 1981, 1991
TOTAL450921867059% 

@aivong-openhands
aivong-openhands force-pushed the feat/agent-server-register-refresh-hook-5189 branch from 71717ae to 0cf4e2e Compare September 22, 2026 16:42
@aivong-openhands

Copy link
Copy Markdown
Contributor Author

Mutation review of the new tests

I hand-wrote 9 mutants against tests/agent_server/test_managed_llm_key.py (baseline: 8 passed in ~0.2s) — 4 controls that revert the PR's own behaviour and must die, and 5 candidates around the machinery. Scope here is test strength only, not correctness or design.

Controls — all caught ✅

Mutant Result
Revert the opt-in gate (if not url: return 0) so registration runs with no refresh URL ❌ caught
Count an in-scope LLM but never actually attach the hook ❌ caught
Drop the subscription-auth guard (treat a subscription LLM as in-scope) ❌ caught
Ignore the allow-list (every api_key LLM, incl. BYOK, in scope) ❌ caught

The suite works because it doesn't stop at the return count: test_registers_and_feeds_sdk_resolution plants a stale key, serves a distinct fresh one, and drives the SDK's own _resolve_refreshed_api_key with a real litellm AuthenticationError — so "counted but not attached" and "same key returned" both die instead of sliding through. Good, load-bearing assertions.

Survivors — gaps 🔎

Mutant Result
Drop .rstrip("/") on the LLM base_url before the allow-list match ✅ 8 passed
Drop .rstrip("/") on the allow-list entries ✅ 8 passed
Disable the not isinstance(data, dict) guard in _load_headers ✅ 8 passed
Drop or None on the refreshed value (return "" instead of None) ✅ 8 passed (likely equivalent — see below)

1. Trailing-slash normalization on base_url is unasserted (two survivors)

_llm_is_in_scope normalizes both sides with .rstrip("/"), and _managed_base_urls does the same on each allow-list entry — but every test uses base_url and allow-list values that already agree exactly (https://llm-proxy.example/v1 on both sides). So deleting either .rstrip("/") keeps the suite green. This is the highest-consequence gap: the allow-list is the safety boundary and the on/off switch for the whole feature. If a deployment sets OH_LLM_API_KEY_REFRESH_BASE_URLS to .../v1/ while the snapshot LLM carries .../v1 (or vice versa), the hook is silently not registered, the 401-recovery this PR exists to deliver never fires, and no test would notice the normalization was lost.

Two assertions (both directions) kill both mutants:

def test_base_url_match_ignores_trailing_slash(monkeypatch):
    monkeypatch.setenv(REFRESH_URL_ENV, REFRESH_URL)
    # allow-list has no trailing slash, LLM base_url does — must still match.
    monkeypatch.setenv(REFRESH_BASE_URLS_ENV, MANAGED_BASE_URL)
    llm = _llm("m", MANAGED_BASE_URL + "/")
    assert register_managed_llm_key_refresh(_agent(llm)) == 1


def test_allowlist_entry_trailing_slash_ignored(monkeypatch):
    monkeypatch.setenv(REFRESH_URL_ENV, REFRESH_URL)
    # allow-list has a trailing slash, LLM base_url does not — must still match.
    monkeypatch.setenv(REFRESH_BASE_URLS_ENV, MANAGED_BASE_URL + "/")
    llm = _llm("m", MANAGED_BASE_URL)
    assert register_managed_llm_key_refresh(_agent(llm)) == 1

Verified: both pass on the PR branch unmodified; the first fails with the LLM-side .rstrip("/") removed, the second fails with the allow-list-side .rstrip("/") removed.

2. The _load_headers non-object guard is untested

test_bad_headers_env_is_ignored covers non-JSON ("not-json" → JSONDecodeError → {}), but nothing covers valid JSON that isn't an object. Disabling if not isinstance(data, dict): leaves the suite green because no test ever sets OH_LLM_API_KEY_REFRESH_HEADERS to something like ["a","b"]. In production that branch is the only thing standing between a mis-set env var and an AttributeError: 'list' object has no attribute 'items' raised from register_managed_llm_key_refresh — which runs right after the conversation is built in event_service.py, so the crash would surface at conversation start rather than being swallowed.

def test_non_object_headers_env_is_ignored(monkeypatch):
    monkeypatch.setenv(REFRESH_URL_ENV, REFRESH_URL)
    monkeypatch.setenv(REFRESH_HEADERS_ENV, '["a", "b"]')  # valid JSON, not an object
    monkeypatch.delenv(REFRESH_BASE_URLS_ENV, raising=False)
    llm = _llm("m", MANAGED_BASE_URL)
    # Registration must not raise, and the hook must still resolve.
    assert register_managed_llm_key_refresh(_agent(llm)) == 1
    with _served_key(REFRESH_URL, "fresh_key"):
        refreshed = llm._resolve_refreshed_api_key(_auth_error())
    assert refreshed is not None
    assert refreshed.get_secret_value() == "fresh_key"

Verified: passes on the PR branch; fails (errors) with the isinstance guard disabled.

3. return value or None — I think this is an equivalent mutant

Changing _refresh's return value or None to return value survives, but I believe it's equivalent, not a gap. When the served body is whitespace/empty, value strips to ""; the SDK's _resolve_refreshed_api_key then builds SecretStr("") and bails on if not new_secret.get_secret_value(): return None, so the retry is skipped either way. The .strip() itself is asserted — test_empty_served_key_does_not_retry kills the mutant that removes it. The or None is defensive belt-and-suspenders against a future consumer that doesn't guard empty; I'd keep it, but there's no observable behaviour to test given today's SDK. Flagging in case I'm missing a caller.

Not a test gap

  • Structural safety that beats any test: the subscription-auth and allow-list guards are enforced in _llm_is_in_scope, and reverting either kills a test (controls above) — the BYOK/subscription key genuinely can't receive the managed hook.
  • The _refresh closure swallows all exceptions and the SDK independently guards "same key" and "empty key", so a failed or no-op refresh provably cannot mask the original 401. That layering is well covered by test_hook_failure_surfaces_original_error and the controls.

This comment was generated by an AI assistant on behalf of the user.

aivong-openhands added a commit that referenced this pull request Sep 22, 2026
… 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>
@aivong-openhands

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough mutation review — pushed in 10eda0b.

Added all three suggested tests to tests/agent_server/test_managed_llm_key.py:

  • Trailing-slash normalization (both survivors): test_base_url_match_ignores_trailing_slash and test_allowlist_entry_trailing_slash_ignored assert matching succeeds in both directions. Verified: both pass unmodified; the first fails with the LLM-side .rstrip("/") removed, the second fails with the allow-list-side .rstrip("/") removed.
  • _load_headers non-object guard: test_non_object_headers_env_is_ignored sets OH_LLM_API_KEY_REFRESH_HEADERS='["a","b"]' (valid JSON, not an object) and asserts registration still succeeds and the hook resolves. Verified: passes unmodified; errors with AttributeError: 'list' object has no attribute 'items' when the isinstance guard is disabled.

On #3 (return value or None) — agreed it's an equivalent mutant given today's SDK guards empty keys, so no test added; keeping the or None as defensive belt-and-suspenders per your note.

Full suite now 11 passed.

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

@aivong-openhands aivong-openhands left a comment •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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, base fix/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_URL is set, and _llm_is_in_scope gates on auth_type == "api_key" plus an optional base_url allow-list. The SDK's _resolve_refreshed_api_key independently re-checks auth_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. _refresh also swallows all exceptions and returns None. 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 both Agent and ACPAgent.
  • Tests reach real code: The suite drives the SDK's own _resolve_refreshed_api_key with a real litellm AuthenticationError and asserts observable outcomes (fresh key returned / no retry), not mock wiring. register_local_secret_resolver serves the LookupSecret URL 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): When OH_LLM_API_KEY_REFRESH_BASE_URLS is unset, the hook attaches to every api_key LLM, including a user's BYOK LLM. The SDK retry (_auth_refreshed_llm) reuses the LLM's own base_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] ⚠️ Risk Assessment: 🟡 MEDIUM

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 /codereview trigger), 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.

@aivong-openhands
aivong-openhands marked this pull request as ready for review September 22, 2026 18:56
@juanmichelini
juanmichelini self-requested a review September 22, 2026 19:09
aivong-openhands added a commit that referenced this pull request Sep 22, 2026
… 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>
@aivong-openhands
aivong-openhands force-pushed the feat/agent-server-register-refresh-hook-5189 branch from 29504e7 to 338474c Compare September 22, 2026 22:10

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

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.

aivong-openhands added a commit that referenced this pull request Sep 24, 2026
… 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>
@aivong-openhands
aivong-openhands force-pushed the feat/agent-server-register-refresh-hook-5189 branch from 338474c to c365d53 Compare September 24, 2026 15:51
@aivong-openhands

Copy link
Copy Markdown
Contributor Author

Good call — done in cc19e12, the feature now fails closed.

OH_LLM_API_KEY_REFRESH_BASE_URLS is required: if it is unset or expands to an empty set, register_managed_llm_key_refresh logs a warning naming both env vars and returns 0 without touching any LLM, even when OH_LLM_API_KEY_REFRESH_URL is set. The "no allow-list matches everything" branch in _llm_is_in_scope is gone, so the hook can only ever attach to a base_url an operator enumerated explicitly — a BYOK LLM can no longer pick it up through a misconfiguration.

Tests: test_without_allowlist_applies_to_all_api_key_llms is replaced by test_without_allowlist_feature_stays_off (asserts 0 registrations and that a 401 resolves no key), plus a new test_blank_allowlist_feature_stays_off for a set-but-empty value like " , ". The remaining cases now set the allow-list explicitly. 14 passed. Module docstring and PR description updated to list the allow-list as required rather than recommended.

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

aivong-openhands added a commit that referenced this pull request Sep 24, 2026
… 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>
@aivong-openhands
aivong-openhands force-pushed the feat/agent-server-register-refresh-hook-5189 branch from cc19e12 to ec95651 Compare September 24, 2026 17:22
@aivong-openhands

Copy link
Copy Markdown
Contributor Author

@OpenHands investigate failing PR description check

@openhands-ai

openhands-ai Bot commented Sep 24, 2026

Copy link
Copy Markdown

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

@openhands-ai

openhands-ai Bot commented Sep 24, 2026

Copy link
Copy Markdown

The failing PR Description Check on PR #5222 is fixed.

Root cause: the check's ## Issue Number section scan treats every bare #<num> reference in that section as a linked issue. The description said Part of #5189. Stacked on #5218 …. While #5189 carries ready-for-dev, #5218 is actually this PR's stacked base PR (not an issue,) and has no ready-for-dev label, so the checker error'd: Linked issue(s) (#5218) carry neither ready-for-dev nor a pre-rollout creation date.

Fix applied: rewrote that sentence to Stacked on PR 5218 so only the real issue (#5189) is scanned as a linked issue. I verified the new body passes the exact checker logic locally (template sections, HUMAN/AGENT markers, issues readiness via the GitHub API), then PATCHed it onto the PR (HTTP 200).

Result: GitHub auto-triggered a re-run of PR Description Check on the updated description — it completed success (run 36034817159). The working tree is unchanged (description-only edit, no commit needed).

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

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-call LookupSecret (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 remote OH_SESSION_API_KEYS_0 case.
  • All check runs on head ec95651e are 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

Base automatically changed from fix/llm-refresh-on-401-5189 to main September 25, 2026 02:48
ak684 pushed a commit that referenced this pull request Sep 25, 2026
… 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>
@ak684
ak684 force-pushed the feat/agent-server-register-refresh-hook-5189 branch from 7215137 to f8c128d Compare September 25, 2026 02:48

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

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 4140a134 are 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-call LookupSecret (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?...) returns api_base=None for 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

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

LGTM

aivong-openhands and others added 9 commits September 28, 2026 10:45
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>
@aivong-openhands
aivong-openhands force-pushed the feat/agent-server-register-refresh-hook-5189 branch from 4140a13 to 120d5fc Compare September 28, 2026 15:45
@aivong-openhands

Copy link
Copy Markdown
Contributor Author

@juanmichelini can you assist with the merge?

@ak684
ak684 merged commit a72751d into main Sep 29, 2026
52 checks passed
@ak684
ak684 deleted the feat/agent-server-register-refresh-hook-5189 branch September 29, 2026 18:06
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.

6 participants