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)