From 7f19e158e0d0b3cf28411e9172f125288b9011d1 Mon Sep 17 00:00:00 2001 From: openhands Date: Tue, 8 Sep 2026 03:08:07 +0000 Subject: [PATCH 1/2] fix(agent-server): restore subscription credentials in pre-flight validation The validate_profile endpoint deserialized the LLM via plain Pydantic but never called create_subscription_llm_from_config(), unlike LLM.from_persisted(). When saving a new ChatGPT subscription profile, the frontend sends auth_type=subscription without the OAuth access token (it lives in the credential store). Without create_subscription_llm_from_config, the LLM's is_subscription flag stayed False and _subscription_credentials stayed None, so litellm sent api_key=None to OpenAI, failing with: "Incorrect API key provided: None" Fix: call create_subscription_llm_from_config(llm) when auth_type == subscription, mirroring the from_persisted path. Closes #4896 --- .../openhands/agent_server/profiles_router.py | 10 +++ tests/agent_server/test_profiles_router.py | 65 +++++++++++++++++++ 2 files changed, 75 insertions(+) diff --git a/openhands-agent-server/openhands/agent_server/profiles_router.py b/openhands-agent-server/openhands/agent_server/profiles_router.py index eb08fa7c3ae..fb838209578 100644 --- a/openhands-agent-server/openhands/agent_server/profiles_router.py +++ b/openhands-agent-server/openhands/agent_server/profiles_router.py @@ -297,6 +297,16 @@ async def validate_profile( cipher = get_cipher(request) llm = decrypt_incoming_llm_secrets(body.llm, cipher) if cipher else body.llm + # Restore runtime subscription credentials, mirroring ``from_persisted``. + # The frontend sends auth_type="subscription" but the OAuth access token + # lives in the credential store, not in the serialized LLM config. Without + # this, the pre-flight sends api_key=None and fails with + # "Incorrect API key provided: None". + if getattr(llm, "auth_type", None) == "subscription": + from openhands.sdk.llm.auth.openai import create_subscription_llm_from_config + + llm = create_subscription_llm_from_config(llm) + messages = [ Message( role="user", diff --git a/tests/agent_server/test_profiles_router.py b/tests/agent_server/test_profiles_router.py index 64a89480542..39b010463f4 100644 --- a/tests/agent_server/test_profiles_router.py +++ b/tests/agent_server/test_profiles_router.py @@ -1,6 +1,7 @@ """Tests for profiles_router endpoints.""" import tempfile +import time from pathlib import Path from unittest.mock import patch @@ -13,6 +14,7 @@ from openhands.agent_server.config import Config from openhands.agent_server.persistence import reset_stores from openhands.sdk.llm import LLM +from openhands.sdk.llm.auth.credentials import OAuthCredentials from openhands.sdk.llm.llm_profile_store import LLMProfileStore from openhands.sdk.llm.provider_connection_store import ProviderConnectionStore from openhands.sdk.profiles import AgentProfileStore, OpenHandsAgentProfile @@ -1984,3 +1986,66 @@ def test_validate_profile_redacts_api_key_in_unknown_error(client): assert leaked_key not in body["error"]["message"], ( "API key must not appear in the validate error response" ) + + +def test_validate_profile_subscription_restores_credentials(client): + """Pre-flight resolves OAuth credentials for subscription profiles. + + Regression: ``validate_profile`` deserialized the LLM via plain Pydantic + but never called ``create_subscription_llm_from_config``. The frontend + sends ``auth_type=subscription`` without the OAuth access token (it lives + in the credential store, not the serialized config), so the pre-flight sent + ``api_key=None`` and failed with "Incorrect API key provided: None". + + The fix mirrors ``LLM.from_persisted`` by calling + ``create_subscription_llm_from_config`` when ``auth_type == subscription``. + """ + from unittest.mock import MagicMock + + # Patch the credential store so OpenAISubscriptionAuth finds fake (valid) + # credentials without hitting the filesystem or OpenAI. The rest of + # ``create_subscription_llm_from_config`` runs with real code, producing + # a real LLM whose ``is_subscription`` flag and credentials are set. + fake_creds = OAuthCredentials( + vendor="openai", + access_token="fake-access-token", + refresh_token="fake-refresh-token", + expires_at=int(time.time() * 1000) + 3_600_000, # not expired + ) + + captured: dict = {} + + async def fake_acompletion(self, messages, **kwargs): + # The API key must be resolved from the credential store, not None. + api_key = self._get_litellm_api_key_value() + captured["api_key"] = api_key + captured["is_subscription"] = self.is_subscription + return MagicMock() + + with ( + patch( + "openhands.sdk.llm.auth.credentials.CredentialStore.get", + return_value=fake_creds, + ), + patch("openhands.sdk.llm.llm.LLM.uses_responses_api", return_value=False), + patch("openhands.sdk.llm.llm.LLM.acompletion", fake_acompletion), + ): + response = client.post( + "/api/profiles/sub-profile/validate", + json={ + "llm": { + "model": "openai/gpt-6-astra", + "auth_type": "subscription", + "subscription_vendor": "openai", + "stream": True, + "native_tool_calling": True, + } + }, + ) + + assert response.status_code == 200 + body = response.json() + assert body["valid"] is True + assert body["error"] is None + assert captured["is_subscription"] is True + assert captured["api_key"] == "fake-access-token" From ea3861d5d143e8b617ecf61c26ea576c21980a8d Mon Sep 17 00:00:00 2001 From: openhands Date: Tue, 8 Sep 2026 04:13:03 +0000 Subject: [PATCH 2/2] fix(agent-server): move subscription credential restoration inside try block Address review feedback from all-hands-bot: - Move create_subscription_llm_from_config call inside the try/except so credential errors (missing/expired) return ValidateProfileResponse(valid=False) instead of a 500 - Wrap the synchronous factory with asyncio.to_thread to avoid blocking the FastAPI event loop during token refresh - Add test for the missing-credentials failure path Co-authored-by: openhands --- .../openhands/agent_server/profiles_router.py | 27 ++++++++------ tests/agent_server/test_profiles_router.py | 35 +++++++++++++++++++ 2 files changed, 52 insertions(+), 10 deletions(-) diff --git a/openhands-agent-server/openhands/agent_server/profiles_router.py b/openhands-agent-server/openhands/agent_server/profiles_router.py index fb838209578..578fe0a0447 100644 --- a/openhands-agent-server/openhands/agent_server/profiles_router.py +++ b/openhands-agent-server/openhands/agent_server/profiles_router.py @@ -1,5 +1,6 @@ """HTTP endpoints for managing named LLM configurations (profiles).""" +import asyncio from typing import Annotated, Any from fastapi import APIRouter, HTTPException, Path, Request, status @@ -297,16 +298,6 @@ async def validate_profile( cipher = get_cipher(request) llm = decrypt_incoming_llm_secrets(body.llm, cipher) if cipher else body.llm - # Restore runtime subscription credentials, mirroring ``from_persisted``. - # The frontend sends auth_type="subscription" but the OAuth access token - # lives in the credential store, not in the serialized LLM config. Without - # this, the pre-flight sends api_key=None and fails with - # "Incorrect API key provided: None". - if getattr(llm, "auth_type", None) == "subscription": - from openhands.sdk.llm.auth.openai import create_subscription_llm_from_config - - llm = create_subscription_llm_from_config(llm) - messages = [ Message( role="user", @@ -315,6 +306,22 @@ async def validate_profile( ] try: + # Restore runtime subscription credentials, mirroring ``from_persisted``. + # The frontend sends auth_type="subscription" but the OAuth access token + # lives in the credential store, not in the serialized LLM config. Without + # this, the pre-flight sends api_key=None and fails with + # "Incorrect API key provided: None". + # + # Run the synchronous factory (which may do a network token refresh) + # off the event loop and inside the handled path so credential errors + # surface as ``valid=False`` instead of a 500. + if getattr(llm, "auth_type", None) == "subscription": + from openhands.sdk.llm.auth.openai import ( + create_subscription_llm_from_config, + ) + + llm = await asyncio.to_thread(create_subscription_llm_from_config, llm) + # Mirror the runtime dispatch (see ``amake_llm_completion``) and stay # async so provider I/O doesn't pin the FastAPI event loop. if llm.uses_responses_api(): diff --git a/tests/agent_server/test_profiles_router.py b/tests/agent_server/test_profiles_router.py index 39b010463f4..29ae961a890 100644 --- a/tests/agent_server/test_profiles_router.py +++ b/tests/agent_server/test_profiles_router.py @@ -2049,3 +2049,38 @@ async def fake_acompletion(self, messages, **kwargs): assert body["error"] is None assert captured["is_subscription"] is True assert captured["api_key"] == "fake-access-token" + + +def test_validate_profile_subscription_missing_credentials(client): + """Pre-flight returns ``valid=False`` when subscription credentials are absent. + + ``create_subscription_llm_from_config`` raises ``ValueError`` when no stored + OAuth credentials exist. The endpoint must catch this and return a + structured error instead of a 500. + """ + # CredentialStore.get returns None → refresh_if_needed_sync returns None + # → create_subscription_llm_from_config raises ValueError. + with ( + patch( + "openhands.sdk.llm.auth.credentials.CredentialStore.get", + return_value=None, + ), + patch("openhands.sdk.llm.llm.LLM.uses_responses_api", return_value=False), + ): + response = client.post( + "/api/profiles/sub-profile/validate", + json={ + "llm": { + "model": "openai/gpt-6-astra", + "auth_type": "subscription", + "subscription_vendor": "openai", + "stream": True, + "native_tool_calling": True, + } + }, + ) + + assert response.status_code == 200 + body = response.json() + assert body["valid"] is False + assert "subscription login" in body["error"]["message"].lower()