The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(dashboard-auth): a non-JWT bearer is "not my token", not "provider unreachable" (#94558)
Teknium2f44998353b7
diff --git a/hermes_cli/dashboard_auth/__init__.py b/hermes_cli/dashboard_auth/__init__.pyindex c07b2ade6f3..9a997fd224c 100644--- a/hermes_cli/dashboard_auth/__init__.py+++ b/hermes_cli/dashboard_auth/__init__.py@@ -19,6 +19,7 @@ from hermes_cli.dashboard_auth.base import (ProviderError,RefreshExpiredError,assert_protocol_compliance,+ classify_jwks_lookup_error,)from hermes_cli.dashboard_auth.registry import (register_provider,@@ -39,6 +40,7 @@ __all__ = ["ProviderError","RefreshExpiredError","assert_protocol_compliance",+ "classify_jwks_lookup_error","register_provider","get_provider","list_providers",diff --git a/hermes_cli/dashboard_auth/base.py b/hermes_cli/dashboard_auth/base.pyindex 2d744c6cf3d..02db55f65e3 100644--- a/hermes_cli/dashboard_auth/base.py+++ b/hermes_cli/dashboard_auth/base.py@@ -110,6 +110,45 @@ class RefreshExpiredError(Exception):"""+def classify_jwks_lookup_error(exc: BaseException) -> Exception:+ """Map a ``PyJWKClient.get_signing_key_from_jwt`` failure to the protocol.++ Only a genuine transport failure (the IDP's JWKS endpoint could not be+ fetched) is a :class:`ProviderError` — middleware turns that into 503+ "auth provider unreachable" so a flaky IDP never forces a logout.++ Everything else means the token itself cannot be verified by this+ provider and is an :class:`InvalidCodeError` (``verify_session`` returns+ ``None``, the middleware tries the next provider / refresh / 401):++ * ``jwt.DecodeError`` — the bearer is not a JWT at all (an opaque peer+ key, a legacy session token, garbage). #94558: hosted agents answered+ every non-JWT bearer with a fast 503 ``Auth provider 'nous'+ unreachable`` even though Portal was healthy, because "cannot parse"+ and "cannot reach" were folded into one branch.+ * ``jwt.PyJWKSetError`` — the JWKS was fetched fine but holds no key for+ this token's ``kid`` (rotated/foreign key). The provider was reached;+ the token is simply not one of ours.++ ``PyJWKClientConnectionError`` is the only ``PyJWKClientError`` subclass+ that denotes unreachability; a bare ``PyJWKClientError`` (unexpected+ JWKS shape) is kept as a provider fault since the IDP misbehaved.+ """+ try:+ import jwt+ except Exception: # pragma: no cover - jwt is a hard dep of these providers+ return ProviderError(f"JWKS lookup failed: {exc!r}")+ if isinstance(exc, jwt.PyJWKClientConnectionError):+ return ProviderError(f"JWKS lookup failed: {exc}")+ if isinstance(exc, (jwt.DecodeError, jwt.PyJWKSetError)):+ return InvalidCodeError(f"token not verifiable by this provider: {exc}")+ if isinstance(exc, jwt.PyJWKClientError):+ return ProviderError(f"JWKS lookup failed: {exc}")+ if isinstance(exc, jwt.InvalidTokenError):+ return InvalidCodeError(f"token not verifiable by this provider: {exc}")+ return ProviderError(f"JWKS lookup failed: {exc!r}")++class DashboardAuthProvider(ABC):"""Protocol every dashboard-auth provider plugin implements.diff --git a/plugins/dashboard_auth/nous/__init__.py b/plugins/dashboard_auth/nous/__init__.pyindex 69acd18e36b..fdb28173eed 100644--- a/plugins/dashboard_auth/nous/__init__.py+++ b/plugins/dashboard_auth/nous/__init__.py@@ -85,6 +85,7 @@ from hermes_cli.dashboard_auth import (LoginStart,ProviderError,RefreshExpiredError,+ classify_jwks_lookup_error,Session,)@@ -436,10 +437,11 @@ class NousDashboardAuthProvider(DashboardAuthProvider):signing_key = self._get_jwks_client().get_signing_key_from_jwt(access_token)- except jwt.PyJWKClientError as exc:- raise ProviderError(f"JWKS lookup failed: {exc}") from exc- except Exception as exc: # pragma: no cover - defensive- raise ProviderError(f"JWKS lookup failed: {exc!r}") from exc+ except Exception as exc:+ # Unreachable JWKS -> ProviderError (503); a bearer that is not+ # one of our JWTs (opaque peer key, foreign kid) -> InvalidCodeError+ # (None / next provider). Folding both into 503 produced #94558.+ raise classify_jwks_lookup_error(exc) from exctry:claims = jwt.decode(diff --git a/plugins/dashboard_auth/self_hosted/__init__.py b/plugins/dashboard_auth/self_hosted/__init__.pyindex 2672006571c..7b7283b2df7 100644--- a/plugins/dashboard_auth/self_hosted/__init__.py+++ b/plugins/dashboard_auth/self_hosted/__init__.py@@ -93,6 +93,7 @@ from hermes_cli.dashboard_auth import (LoginStart,ProviderError,RefreshExpiredError,+ classify_jwks_lookup_error,Session,)@@ -617,10 +618,11 @@ class SelfHostedOIDCProvider(DashboardAuthProvider):signing_key = self._get_jwks_client().get_signing_key_from_jwt(id_token)- except jwt.PyJWKClientError as exc:- raise ProviderError(f"JWKS lookup failed: {exc}") from exc- except Exception as exc: # pragma: no cover - defensive- raise ProviderError(f"JWKS lookup failed: {exc!r}") from exc+ except Exception as exc:+ # Unreachable JWKS -> ProviderError (503); a bearer that is not+ # one of our JWTs (opaque peer key, foreign kid) -> InvalidCodeError+ # (None / next provider). Folding both into 503 produced #94558.+ raise classify_jwks_lookup_error(exc) from exctry:claims = jwt.decode(diff --git a/tests/plugins/dashboard_auth/test_opaque_bearer_not_unreachable.py b/tests/plugins/dashboard_auth/test_opaque_bearer_not_unreachable.pynew file mode 100644index 00000000000..8b624214842--- /dev/null+++ b/tests/plugins/dashboard_auth/test_opaque_bearer_not_unreachable.py@@ -0,0 +1,156 @@+"""#94558 — a non-JWT bearer must not be reported as "Auth provider unreachable".++Hosted agents answered every opaque/peer bearer on the gated API with a fast+HTTP 503 ``{"detail": "Auth provider 'nous' unreachable"}`` while Portal was+perfectly healthy: ``NousDashboardAuthProvider._verify_jwt`` folded *every*+``PyJWKClient`` failure — including ``DecodeError('Not enough segments')`` for+a token that is not a JWT at all — into ``ProviderError``. Only a transport+failure fetching the JWKS is "unreachable"; anything else means "not my+token" (``verify_session`` -> None -> 401 / next provider).++Real ``NousDashboardAuthProvider`` + real ``SelfHostedOIDCProvider`` JWKS path,+a real local HTTP JWKS server (reachable case) or a closed port (unreachable),+and the real gated web_server app for the HTTP-level assertion.+"""+from __future__ import annotations++import json+import threading+from http.server import BaseHTTPRequestHandler, HTTPServer++import jwt+import pytest+from starlette.testclient import TestClient++from hermes_cli import web_server+from hermes_cli.dashboard_auth import (+ InvalidCodeError,+ ProviderError,+ classify_jwks_lookup_error,+ clear_providers,+ register_provider,+)+from hermes_cli.dashboard_auth.cookies import SESSION_AT_COOKIE+import plugins.dashboard_auth.nous as nous_plugin++OPAQUE_PEER_KEY = "hk_live_opaque_peer_key_0123456789abcdef"+# Well-formed RS256 JWT header with an unknown kid, bogus payload/signature.+FOREIGN_KID_JWT = "eyJhbGciOiJSUzI1NiIsImtpZCI6Inp6eiJ9.e30.sig"++[email protected](scope="module")+def empty_jwks_server():+ """A reachable JWKS endpoint that knows no keys."""++ class _H(BaseHTTPRequestHandler):+ def do_GET(self): # noqa: N802+ self.send_response(200)+ self.send_header("content-type", "application/json")+ self.end_headers()+ self.wfile.write(json.dumps({"keys": []}).encode())++ def log_message(self, *a): # silence+ pass++ srv = HTTPServer(("127.0.0.1", 0), _H)+ t = threading.Thread(target=srv.serve_forever, daemon=True)+ t.start()+ yield f"http://127.0.0.1:{srv.server_address[1]}"+ srv.shutdown()+++def _nous(portal_url: str) -> nous_plugin.NousDashboardAuthProvider:+ return nous_plugin.NousDashboardAuthProvider(client_id="agent:test-instance", portal_url=portal_url)+++# ── classifier ────────────────────────────────────────────────────────────++def test_classifier_maps_transport_failure_to_provider_error():+ exc = jwt.PyJWKClientConnectionError("Fail to fetch data from the url")+ assert isinstance(classify_jwks_lookup_error(exc), ProviderError)+++ "exc",+ [+ jwt.DecodeError("Not enough segments"),+ jwt.PyJWKSetError("The JWK Set did not contain any keys"),+ jwt.InvalidTokenError("bad"),+ ],+)+def test_classifier_maps_unverifiable_token_to_invalid_code(exc):+ assert isinstance(classify_jwks_lookup_error(exc), InvalidCodeError)+++def test_classifier_keeps_bare_jwk_client_error_as_provider_fault():+ assert isinstance(classify_jwks_lookup_error(jwt.PyJWKClientError("weird JWKS shape")), ProviderError)+++# ── Nous provider ─────────────────────────────────────────────────────────++def test_opaque_bearer_with_healthy_portal_is_not_unreachable(empty_jwks_server):+ provider = _nous(empty_jwks_server)+ assert provider.verify_session(access_token=OPAQUE_PEER_KEY) is None+++def test_foreign_kid_jwt_with_healthy_portal_is_not_unreachable(empty_jwks_server):+ provider = _nous(empty_jwks_server)+ assert provider.verify_session(access_token=FOREIGN_KID_JWT) is None+++def test_real_jwt_with_unreachable_portal_still_raises_provider_error():+ provider = _nous("http://127.0.0.1:9") # discard port: connection refused+ with pytest.raises(ProviderError):+ provider.verify_session(access_token=FOREIGN_KID_JWT)+++def test_opaque_bearer_with_unreachable_portal_is_still_just_not_ours():+ """No network call is even needed to know an opaque string is not our JWT."""+ provider = _nous("http://127.0.0.1:9")+ assert provider.verify_session(access_token=OPAQUE_PEER_KEY) is None+++# ── self-hosted OIDC provider (sibling site of the same hunk) ──────────────++def test_self_hosted_provider_shares_the_classification(empty_jwks_server, monkeypatch):+ import plugins.dashboard_auth.self_hosted as sh++ provider = object.__new__(sh.SelfHostedOIDCProvider)+ provider._jwks_client = None+ provider._client_id = "hermes"+ monkeypatch.setattr(+ provider, "_get_discovery",+ lambda: {"jwks_uri": f"{empty_jwks_server}/jwks", "issuer": empty_jwks_server},+ )+ with pytest.raises(InvalidCodeError):+ provider._verify_id_token(OPAQUE_PEER_KEY)+++# ── HTTP level: the gated API answers 401, not 503 ────────────────────────++def _gated_nous(empty_jwks_server):+ clear_providers()+ prev = {k: getattr(web_server.app.state, k, None) for k in ("bound_host", "bound_port", "auth_required")}+ web_server.app.state.bound_host = "agent.example.test"+ web_server.app.state.bound_port = 443+ web_server.app.state.auth_required = True+ register_provider(_nous(empty_jwks_server))+ yield TestClient(web_server.app, base_url="https://agent.example.test")+ clear_providers()+ for k, v in prev.items():+ setattr(web_server.app.state, k, v)+++def test_gated_api_rejects_opaque_bearer_with_401_not_503(_gated_nous):+ r = _gated_nous.get("/api/auth/me", headers={"Authorization": f"Bearer {OPAQUE_PEER_KEY}"})+ assert r.status_code != 503, r.text+ assert r.status_code == 401+ assert "unreachable" not in r.text.lower()+++def test_gated_api_rejects_opaque_cookie_with_401_not_503(_gated_nous):+ _gated_nous.cookies.set(SESSION_AT_COOKIE, OPAQUE_PEER_KEY)+ r = _gated_nous.get("/api/auth/me")+ assert r.status_code != 503, r.text+ assert "unreachable" not in r.text.lower()