fix(webui): surface OAuth model catalog authorization failures

This commit is contained in:
Xubin Ren committed 2026-09-21 00:13:46 +08:00
1 parent a478c96bde
commit 024fe8f636
26 files changed
+585 -34

No files matched your search

+123
View File
@@ -12,6 +12,7 @@ import httpx
import pytest
from nanobot.providers.oauth_model_catalog import (
OAuthCatalogAuthRequiredError,
OAuthModelCatalog,
get_oauth_model_catalog,
invalidate_oauth_model_catalog,
@@ -513,3 +514,125 @@ def test_catalog_treats_empty_remote_list_as_failure_and_can_be_invalidated() ->
assert refreshed.source == "remote"
assert refreshed.models[0].id == "provider/new"
assert calls == 2
@pytest.mark.parametrize("with_cache", [False, True])
@pytest.mark.parametrize(
("status", "body", "expected"),
[
(401, {"error": {"code": "token_revoked"}}, "auth_required"),
(401, "non-json", "auth_required"),
(400, {"error": "invalid_grant"}, "auth_required"),
(403, {"error": {"code": "token_revoked"}}, "auth_required"),
(403, {"error": "insufficient_scope"}, "unavailable"),
(429, {"error": "invalid_grant"}, "unavailable"),
(503, {}, "unavailable"),
],
)
def test_catalog_retains_safe_error_kind_until_reauthentication(
with_cache: bool, status: int, body: object, expected: str,
) -> None:
from loguru import logger
now = [0.0]
failing = [not with_cache]
calls = 0
sentinel = "private-token-and-account-fixture"
logs: list[str] = []
def fetch(_proxy):
nonlocal calls
calls += 1
if failing[0]:
request = httpx.Request("GET", f"https://example.com/{sentinel}")
response = httpx.Response(status, json=body, request=request)
raise httpx.HTTPStatusError(sentinel, request=request, response=response)
return (ProviderModelSpec(id="provider/new"),)
catalog = OAuthModelCatalog(
fallback_models=(_fallback_model(),), fetch=fetch,
fresh_ttl_s=10, stale_ttl_s=100, monotonic=lambda: now[0],
)
if with_cache:
assert catalog.get(cache_key="same-account").error_kind is None
now[0] = 11
failing[0] = True
sink = logger.add(lambda message: logs.append(str(message)))
try:
first = catalog.get(cache_key="same-account")
second = catalog.get(cache_key="same-account")
finally:
logger.remove(sink)
assert first.source == ("stale" if with_cache else "fallback")
assert first.error_kind == second.error_kind == expected
assert calls == (2 if with_cache else 1)
assert sentinel not in repr(first) + "".join(logs)
# Same account re-login must bypass both the stale list and negative cache.
failing[0] = False
catalog.invalidate()
recovered = catalog.get(cache_key="same-account")
assert recovered.source == "remote"
assert recovered.error_kind is None
assert recovered.message is None
assert recovered.models[0].id == "provider/new"
@pytest.mark.parametrize("failure", [httpx.ConnectError("offline"), httpx.ReadTimeout("slow")])
def test_catalog_network_errors_do_not_request_sign_in(failure: Exception) -> None:
def fetch(_proxy):
raise failure
catalog = OAuthModelCatalog(fallback_models=(_fallback_model(),), fetch=fetch)
assert catalog.get(cache_key="one").error_kind == "unavailable"
@pytest.mark.parametrize(
("message", "reauth"),
[
('Token refresh failed: 400 {"error":"invalid_grant","token":"private"}', True),
('Token refresh failed: 401 private', True),
('Token refresh failed: 429 {"error":"invalid_grant"}', False),
('Token refresh failed: 503 private', False),
('network error mentions invalid_grant', False),
('OAuth credentials not found. Please run the login command.', True),
],
)
def test_codex_catalog_classifies_sdk_refresh_envelope(monkeypatch, message, reauth):
from nanobot.providers.openai_codex_provider import _fetch_openai_codex_models
def fail(**_kwargs):
raise RuntimeError(message)
monkeypatch.setattr("nanobot.providers.openai_codex_provider.get_codex_token", fail)
with pytest.raises(RuntimeError) as error:
_fetch_openai_codex_models(None)
assert isinstance(error.value, OAuthCatalogAuthRequiredError) is reauth
if reauth:
assert "private" not in str(error.value)
def test_xai_catalog_classifies_expired_refresh_credentials(monkeypatch):
from nanobot.providers.xai_grok_provider import _fetch_xai_grok_models
from nanobot.providers.xai_oauth import XAIOAuthReauthRequiredError, _oauth_http_error
failure = _oauth_http_error(
httpx.Response(400, json={"error": "invalid_grant", "error_description": "private"}),
"token refresh",
)
assert isinstance(failure, XAIOAuthReauthRequiredError)
assert "private" not in str(failure)
def fail(**_kwargs):
raise failure
monkeypatch.setattr("nanobot.providers.xai_grok_provider.get_xai_oauth_token", fail)
with pytest.raises(OAuthCatalogAuthRequiredError):
_fetch_xai_grok_models(None)
@pytest.mark.parametrize("status", [403, 429, 503])
def test_xai_oauth_other_failures_are_not_reauthentication(status):
from nanobot.providers.xai_oauth import XAIOAuthReauthRequiredError, _oauth_http_error
failure = _oauth_http_error(httpx.Response(status, json={}), "token refresh")
assert not isinstance(failure, XAIOAuthReauthRequiredError)
+83
View File
@@ -2120,6 +2120,89 @@ def test_provider_models_payload_returns_online_openai_codex_models(
}
@pytest.mark.parametrize("source", ["stale", "fallback"])
@pytest.mark.parametrize("error_kind", ["auth_required", "unavailable"])
def test_provider_models_payload_exposes_catalog_failure_with_usable_models(
monkeypatch, source, error_kind,
):
monkeypatch.setattr(
"nanobot.webui.settings_models.get_oauth_model_catalog",
lambda *_args, **_kwargs: OAuthModelCatalogSnapshot(
models=(ProviderModelSpec(id="openai-codex/offline-model"),),
source=source, fetched_at=123, error_kind=error_kind,
),
)
payload = provider_models_payload({"provider": ["openai_codex"]})
assert payload["status"] == "available"
assert payload["source"] == source
assert payload["error_kind"] == error_kind
assert payload["models"][0]["id"] == "openai-codex/offline-model"
def test_copilot_explicit_login_does_not_reuse_revoked_credentials(monkeypatch, oauth_flows):
from unittest.mock import Mock
login = Mock(return_value=SimpleNamespace(access="new-token"))
invalidate = Mock()
monkeypatch.setattr(
"nanobot.providers.github_copilot_provider.get_github_copilot_login_status",
lambda: SimpleNamespace(access="revoked-token"),
)
monkeypatch.setattr("nanobot.providers.github_copilot_provider.login_github_copilot", login)
monkeypatch.setattr("nanobot.webui.settings_models.invalidate_oauth_model_catalog", invalidate)
monkeypatch.setattr("nanobot.webui.settings_api.settings_payload", lambda **_: {"ready": True})
assert login_oauth_provider({"provider": ["github-copilot"]}, oauth_flows=oauth_flows) == {"ready": True}
login.assert_called_once()
invalidate.assert_called_once_with("github_copilot")
@pytest.mark.parametrize("provider", ["openai_codex", "xai_grok"])
def test_oauth_completion_clears_same_account_catalog_failure(monkeypatch, oauth_flows, provider):
from nanobot.providers.oauth_model_catalog import OAuthModelCatalog
signed_in = [False]
def fetch(_proxy):
if not signed_in[0]:
request = httpx.Request("GET", "https://example.com/models")
raise httpx.HTTPStatusError("revoked", request=request, response=httpx.Response(401))
return (ProviderModelSpec(id="provider/new-model"),)
catalog = OAuthModelCatalog(fallback_models=(), fetch=fetch)
module = f"nanobot.providers.{provider}_provider"
monkeypatch.setattr(f"{module}._{provider.upper()}_MODEL_CATALOG", catalog)
monkeypatch.setattr(
"nanobot.webui.settings_models.get_oauth_model_catalog",
lambda *_args, **_kwargs: catalog.get(cache_key="same-account"),
)
monkeypatch.setattr("nanobot.webui.settings_api.settings_payload", lambda **_: {"ready": True})
class Flow:
expired = False
def cancel(self):
pass
def complete(*_args):
signed_in[0] = True
return SimpleNamespace(access="fixture")
owner = "openai_codex_oauth" if provider == "openai_codex" else "xai_oauth"
completion = "complete_openai_codex_oauth_login" if provider == "openai_codex" else "complete_xai_oauth_login"
monkeypatch.setattr(f"nanobot.providers.{owner}.{completion}", complete)
oauth_flows.register(provider, "flow-test", Flow())
before = provider_models_payload({"provider": [provider]})
assert before["error_kind"] == "auth_required"
assert complete_oauth_provider(
{"provider": [provider], "flow_id": ["flow-test"]},
"synthetic-callback", oauth_flows=oauth_flows,
) == {"ready": True}
after = provider_models_payload({"provider": [provider]})
assert after["source"] == "remote"
assert after["error_kind"] is None
assert after["models"][0]["id"] == "provider/new-model"
def test_provider_models_payload_returns_online_github_copilot_models(
monkeypatch: pytest.MonkeyPatch,
) -> None: