Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions openhands-agent-server/openhands/agent_server/profiles_router.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -305,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():
Expand Down
100 changes: 100 additions & 0 deletions tests/agent_server/test_profiles_router.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Tests for profiles_router endpoints."""

import tempfile
import time
from pathlib import Path
from unittest.mock import patch

Expand All @@ -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
Expand Down Expand Up @@ -1984,3 +1986,101 @@ 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"


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()
Loading