Skip to content

The agent that grows with you

fix(auth): login surfaces share one interactive-provider query

ethernet780d5a3313d7
diff --git a/hermes_cli/dashboard_auth/__init__.py b/hermes_cli/dashboard_auth/__init__.py
index 05941a68bdd..f52f683894b 100644
--- a/hermes_cli/dashboard_auth/__init__.py
+++ b/hermes_cli/dashboard_auth/__init__.py
@@ -11,7 +11,7 @@ from hermes_cli.dashboard_auth.base import (
# — otherwise a provider auto-registered during one test leaks into the next.
from hermes_cli.dashboard_auth.registry import (
register_provider, get_provider, list_providers, list_token_providers,
- list_session_providers, clear_providers)
+ list_session_providers, list_interactive_providers, clear_providers)
__all__ = [
"DashboardAuthProvider",
@@ -26,6 +26,7 @@ __all__ = [
"classify_jwks_lookup_error",
"clear_providers",
"get_provider",
+ "list_interactive_providers",
"list_providers",
"list_session_providers",
"list_token_providers",
diff --git a/hermes_cli/dashboard_auth/login_page.py b/hermes_cli/dashboard_auth/login_page.py
index d6292e7cd74..93742681652 100644
--- a/hermes_cli/dashboard_auth/login_page.py
+++ b/hermes_cli/dashboard_auth/login_page.py
@@ -14,7 +14,7 @@ from __future__ import annotations
import html
from urllib.parse import quote, urlencode
-from hermes_cli.dashboard_auth import list_session_providers
+from hermes_cli.dashboard_auth import list_interactive_providers, list_session_providers
# Single curly braces are ``str.format`` placeholders; CSS curlies are doubled.
_LOGIN_HTML_TEMPLATE = """\
@@ -533,7 +533,7 @@ def render_login_html(*, next_path: str = "", prefix: str = "") -> str:
# URL-encode then HTML-escape, matching the gate's ``_safe_next_target``
# shape so a round-tripped value is byte-identical.
next_qs = f"&next={html.escape(quote(next_path, safe=''), quote=True)}" if next_path else ""
- interactive = [p for p in providers if getattr(p, "interactive_login", True)]
+ interactive = list_interactive_providers()
if not interactive:
# A deployment authenticated by a provisioned credential (e.g. the
# session-token provider): there is nothing to click. Say so instead of
diff --git a/hermes_cli/dashboard_auth/middleware.py b/hermes_cli/dashboard_auth/middleware.py
index 8834fa0dffd..87487ea3477 100644
--- a/hermes_cli/dashboard_auth/middleware.py
+++ b/hermes_cli/dashboard_auth/middleware.py
@@ -21,7 +21,7 @@ from fastapi.responses import JSONResponse, RedirectResponse, Response
from starlette.concurrency import run_in_threadpool
from hermes_cli import webapp_sign_in
-from hermes_cli.dashboard_auth import list_session_providers
+from hermes_cli.dashboard_auth import list_interactive_providers, list_session_providers
from hermes_cli.dashboard_auth.audit import AuditEvent, audit_log
from hermes_cli.dashboard_auth.base import ProviderError
from hermes_cli.dashboard_auth.cookies import (
@@ -123,8 +123,7 @@ def _auto_sso_response(request: Request) -> Response | None:
resp = _unauth_response(request, reason="no_cookie")
clear_sso_attempt_cookie(resp, prefix=prefix_from_request(request), gateway=gateway)
return resp
- providers = [
- p for p in list_session_providers() if getattr(p, "interactive_login", True)]
+ providers = list_interactive_providers()
if len(providers) != 1 or getattr(providers[0], "supports_password", False):
return None
provider = providers[0]
diff --git a/hermes_cli/dashboard_auth/registry.py b/hermes_cli/dashboard_auth/registry.py
index 18687691f8b..ae0d377f8a3 100644
--- a/hermes_cli/dashboard_auth/registry.py
+++ b/hermes_cli/dashboard_auth/registry.py
@@ -96,6 +96,14 @@ def list_session_providers() -> list[DashboardAuthProvider]:
return [p for p in list_providers() if getattr(p, "supports_session", True)]
+def list_interactive_providers() -> list[DashboardAuthProvider]:
+ """Session providers that offer a sign-in flow (``interactive_login`` True). Every login
+ surface — the login page, ``/api/auth/providers``, auto-SSO, native authorize selection and
+ chooser, the ``native_pkce`` advertisement — uses this; the verify/refresh loops keep
+ :func:`list_session_providers`, so a provisioned-credential provider still authenticates."""
+ return [p for p in list_session_providers() if getattr(p, "interactive_login", True)]
+
+
def register_global_provider(provider: DashboardAuthProvider) -> None:
"""Register a host-owned provider in the process-global slot (upsert). The registry is shared
across every profile one dashboard process serves, so these outlive any per-home plugin
diff --git a/hermes_cli/dashboard_auth/routes.py b/hermes_cli/dashboard_auth/routes.py
index 963db63ba0d..97dfc55f911 100644
--- a/hermes_cli/dashboard_auth/routes.py
+++ b/hermes_cli/dashboard_auth/routes.py
@@ -32,7 +32,8 @@ from starlette.concurrency import run_in_threadpool
from hermes_cli import webapp_sign_in
from hermes_cli.dashboard_auth import (
- get_provider, list_providers, list_session_providers, native_flow)
+ get_provider, list_interactive_providers, list_providers, list_session_providers,
+ native_flow)
from hermes_cli.dashboard_auth import prefix as _prefix_mod
from hermes_cli.dashboard_auth.audit import AuditEvent, audit_log
from hermes_cli.dashboard_auth.base import (
@@ -215,13 +216,12 @@ async def api_auth_providers() -> Any:
# credential (interactive_login False — the session-token provider) answers
# an empty list: there is no browser sign-in to offer, which is correct,
# not an outage.
- session_providers = list_session_providers()
- if not session_providers:
+ if not list_session_providers():
return JSONResponse({"detail": "no auth providers registered"}, status_code=503)
return {"providers": [
{"name": p.name, "display_name": p.display_name,
"supports_password": bool(getattr(p, "supports_password", False))}
- for p in session_providers if getattr(p, "interactive_login", True)]}
+ for p in list_interactive_providers()]}
# --- Public: OAuth round trip ----------------------------------------------
@@ -298,7 +298,7 @@ def _select_native_provider(provider: str):
them via ``/login``); with several the caller renders a chooser instead of guessing."""
if provider:
return get_provider(provider)
- candidates = list_session_providers()
+ candidates = list_interactive_providers()
return candidates[0] if len(candidates) == 1 else None
@@ -317,8 +317,7 @@ async def auth_native_authorize(
redirect_uri = _validate_loopback_redirect_uri(redirect_uri)
p = _select_native_provider(provider)
if p is None and not provider:
- candidates = [
- c for c in list_session_providers() if getattr(c, "interactive_login", True)]
+ candidates = list_interactive_providers()
if len(candidates) > 1:
# Render the chooser BEFORE allocating broker state or setting a cookie: every link
# re-enters this same validated route with an explicit provider.
@@ -333,7 +332,9 @@ async def auth_native_authorize(
headers=_NO_STORE)
if p is None:
raise _http(404, f"Unknown provider: {provider!r}")
- if not getattr(p, "supports_session", True):
+ if not getattr(p, "supports_session", True) or not getattr(p, "interactive_login", True):
+ # Checked BEFORE register_pending: a provisioned-credential provider (session-token)
+ # has only a start_login stub, so it must never reach the upstream round trip.
raise _http(400, f"Provider does not support native login: {p.name!r}")
try:
broker_state = native_flow.register_pending(
diff --git a/hermes_cli/web_routers/status.py b/hermes_cli/web_routers/status.py
index bef45c8d755..9dc8542905f 100644
--- a/hermes_cli/web_routers/status.py
+++ b/hermes_cli/web_routers/status.py
@@ -385,18 +385,20 @@ def _auth_gate_status() -> dict[str, Any]:
native-app capability advertisement ``auth_flows`` the desktop reads to pick the
system-browser + loopback + PKCE flow over the embedded-webview cookie flow. "cookie" is
always available in gated mode; "native_pkce" when at least one interactive session
- provider is registered (token-only credentials such as drain don't count). Missing
+ provider is registered (token-only credentials such as drain, and provisioned-credential
+ session providers such as session-token, don't count). Missing
"native_pkce" ⇒ older gateway ⇒ desktop falls back automatically."""
auth_required = bool(getattr(app.state, "auth_required", False))
auth_providers: list[str] = []
auth_flows: list[str] = []
try:
from hermes_cli.dashboard_auth import (
- list_providers as _list_providers, list_session_providers as _list_session_providers)
+ list_interactive_providers as _list_interactive_providers,
+ list_providers as _list_providers)
auth_providers = [p.name for p in _list_providers()]
if auth_required:
auth_flows.append("cookie")
- if _list_session_providers():
+ if _list_interactive_providers():
auth_flows.append("native_pkce")
except Exception:
# Module not importable yet (early startup) — leave as [].
diff --git a/tests/hermes_cli/test_dashboard_auth_session_token_gate.py b/tests/hermes_cli/test_dashboard_auth_session_token_gate.py
index f56bf36e3c7..25d85f2758b 100644
--- a/tests/hermes_cli/test_dashboard_auth_session_token_gate.py
+++ b/tests/hermes_cli/test_dashboard_auth_session_token_gate.py
@@ -94,20 +94,23 @@ class TestGateEngagement:
class TestRestBearerLeg:
+ # /api/auth/me is the real identity route: an exact 200 + provider proves the bearer was
+ # verified BY this provider (a mere "not 401" would also pass on an unrouted 404).
def test_provisioned_token_passes_the_gate(self, gated_token_app, token):
- r = gated_token_app.get("/api/session", headers={"Authorization": f"Bearer {token}"})
- assert r.status_code not in (401, 403, 503), r.status_code
+ r = gated_token_app.get("/api/auth/me", headers={"Authorization": f"Bearer {token}"})
+ assert r.status_code == 200, (r.status_code, r.text)
+ assert r.json().get("provider") == "session-token"
def test_foreign_token_is_401(self, gated_token_app, token):
r = gated_token_app.get(
- "/api/session", headers={"Authorization": f"Bearer {secrets.token_urlsafe(32)}"})
+ "/api/auth/me", headers={"Authorization": f"Bearer {secrets.token_urlsafe(32)}"})
assert r.status_code == 401
def test_the_desktops_stale_copy_is_401(self, gated_token_app, token):
"""The incident's trap: a token from BEFORE a secret rotation must not verify."""
stale = secrets.token_urlsafe(32)
assert stale != token
- r = gated_token_app.get("/api/session", headers={"Authorization": f"Bearer {stale}"})
+ r = gated_token_app.get("/api/auth/me", headers={"Authorization": f"Bearer {stale}"})
assert r.status_code == 401
@@ -127,3 +130,75 @@ class TestWsUpgradeLeg:
reason, credential = _web_server_chat._ws_auth_reason(_fake_ws(query={}))
assert reason == "no_credential"
assert credential == "none"
+
+
+# ---------------------------------------------------------------------------
+# Login surfaces never select a provisioned-credential provider (review P1)
+# ---------------------------------------------------------------------------
+
+
+def _password_provider():
+ """A real interactive password provider (protocol-compliant subclass) to sit beside the
+ session-token provider; only its routing flags matter to these tests."""
+ cls = type("StubPasswordProvider", (session_token_plugin.SessionTokenProvider,), {
+ "name": "basic", "display_name": "Username & Password",
+ "supports_password": True, "interactive_login": True})
+ return cls(token=secrets.token_urlsafe(32))
+
+
+_NATIVE = {
+ "code_challenge": "x" * 43, "code_challenge_method": "S256",
+ "redirect_uri": "http://127.0.0.1:53682/callback", "state": "client-state",
+}
+
+
+class TestNativeAuthorize:
+ def _pending_count(self):
+ from hermes_cli.dashboard_auth import native_flow
+ return len(native_flow._pending)
+
+ def test_unnamed_request_auto_selects_the_one_interactive_provider(self, gated_token_app):
+ """session-token + one password provider: the password provider is the ONLY interactive
+ one, so an unnamed request selects it (was: 404, because both were counted)."""
+ register_provider(_password_provider())
+ r = gated_token_app.get("/auth/native/authorize", params=_NATIVE, follow_redirects=False)
+ assert r.status_code == 302, (r.status_code, r.text)
+ assert r.headers["location"].endswith("/login")
+
+ def test_token_only_deployment_never_reaches_start_login(self, gated_token_app):
+ """Only session-token registered: no interactive provider, a clean 4xx — never the
+ NotImplementedError from its start_login stub, and no pending broker state."""
+ before = self._pending_count()
+ r = gated_token_app.get("/auth/native/authorize", params=_NATIVE, follow_redirects=False)
+ assert 400 <= r.status_code < 500, (r.status_code, r.text)
+ assert self._pending_count() == before
+
+ def test_explicitly_named_token_provider_is_rejected_before_pending_state(
+ self, gated_token_app):
+ before = self._pending_count()
+ r = gated_token_app.get(
+ "/auth/native/authorize", params={**_NATIVE, "provider": "session-token"},
+ follow_redirects=False)
+ assert r.status_code == 400, (r.status_code, r.text)
+ assert self._pending_count() == before
+
+ def test_browser_login_route_rejects_the_token_provider(self, gated_token_app):
+ r = gated_token_app.get(
+ "/auth/login", params={"provider": "session-token"}, follow_redirects=False)
+ assert r.status_code == 404
+
+
+class TestStatusAdvertisement:
+ def _flows(self, client):
+ return client.get("/api/status").json()["auth_flows"]
+
+ def test_token_only_deployment_does_not_advertise_native_pkce(self, gated_token_app):
+ """Desktop picks the native browser flow off native_pkce; a token-only gate has no
+ browser sign-in, so advertising it would send the desktop down a dead end."""
+ flows = self._flows(gated_token_app)
+ assert "cookie" in flows
+ assert "native_pkce" not in flows
+
+ def test_native_pkce_returns_with_an_interactive_provider(self, gated_token_app):
+ register_provider(_password_provider())
+ assert "native_pkce" in self._flows(gated_token_app)
diff --git a/tests/plugins/dashboard_auth/test_session_token_provider.py b/tests/plugins/dashboard_auth/test_session_token_provider.py
index 0faad25c618..3c16dc44c30 100644
--- a/tests/plugins/dashboard_auth/test_session_token_provider.py
+++ b/tests/plugins/dashboard_auth/test_session_token_provider.py
@@ -156,6 +156,48 @@ class TestRegister:
assert any("short" in r.message for r in caplog.records)
+# ---------------------------------------------------------------------------
+# dashboard.session_token_auth through the REAL config loader
+# ---------------------------------------------------------------------------
+
+
+class TestRealConfigLoader:
+ """The opt-out key is read from an actual config.yaml under a temp HERMES_HOME via the same
+ ``load_config_section`` path the plugin uses — no loader patch, so a misspelled section or
+ key path fails here."""
+
+ @pytest.fixture
+ def home(self, monkeypatch, tmp_path):
+ home = tmp_path / ".hermes"
+ home.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ monkeypatch.setenv("HERMES_DASHBOARD_SESSION_TOKEN", _token())
+ return home
+
+ def _register(self, plugin):
+ ctx = MagicMock()
+ plugin.register(ctx)
+ return ctx
+
+ def test_enabled_false_in_config_yaml_skips_registration(self, plugin, home):
+ (home / "config.yaml").write_text(
+ "dashboard:\n session_token_auth:\n enabled: false\n", encoding="utf-8")
+ ctx = self._register(plugin)
+ ctx.register_dashboard_auth_provider.assert_not_called()
+ assert "enabled is false" in plugin.LAST_SKIP_REASON
+
+ def test_enabled_true_in_config_yaml_registers(self, plugin, home):
+ (home / "config.yaml").write_text(
+ "dashboard:\n session_token_auth:\n enabled: true\n", encoding="utf-8")
+ ctx = self._register(plugin)
+ ctx.register_dashboard_auth_provider.assert_called_once()
+
+ def test_absent_section_defaults_to_enabled(self, plugin, home):
+ (home / "config.yaml").write_text("dashboard:\n theme: default\n", encoding="utf-8")
+ ctx = self._register(plugin)
+ ctx.register_dashboard_auth_provider.assert_called_once()
+
+
# ---------------------------------------------------------------------------
# Interactive surfaces honour interactive_login=False
# ---------------------------------------------------------------------------
diff --git a/website/docs/user-guide/features/web-dashboard.md b/website/docs/user-guide/features/web-dashboard.md
index 69da90a1a0a..0600b755b0a 100644
--- a/website/docs/user-guide/features/web-dashboard.md
+++ b/website/docs/user-guide/features/web-dashboard.md
@@ -886,7 +886,7 @@ curl -s http://<host>:9119/api/status | jq '.auth_required, .auth_providers'
# ["session-token"]
curl -s -o /dev/null -w '%{http_code}\n' \
- -H "Authorization: Bearer $TOKEN" http://<host>:9119/api/me
+ -H "Authorization: Bearer $TOKEN" http://<host>:9119/api/auth/me
# 200
```