The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(auth): the deployment session token authorizes the gated dashboard
ethernet2edfd0d369d5
diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.pyindex afa15ce374a..9ff7e416f46 100644--- a/hermes_cli/config_defaults.py+++ b/hermes_cli/config_defaults.py@@ -1040,9 +1040,9 @@ DEFAULT_CONFIG = {"secret": "","session_ttl_seconds": 0, # 0 → plugin default (12h)},- # Drain-control token auth (dashboard_auth/drain plugin). The secret is NOT here: env- # HERMES_DASHBOARD_DRAIN_SECRET; no-op unless >=256-bit, weak secrets rejected- # (fail-closed). scope = capability label; min_secret_chars in url-safe-b64 chars.+ "session_token_auth": {"enabled": True}, # session_token plugin: a provisioned HERMES_DASHBOARD_SESSION_TOKEN (literal or file:<path>) authorizes the gated dashboard; enabled: false opts out+ # Drain-control token auth (dashboard_auth/drain plugin): the secret is NOT here (env+ # HERMES_DASHBOARD_DRAIN_SECRET); no-op unless >=256-bit, weak secrets rejected (fail-closed)."drain_auth": {"scope": "drain", "min_secret_chars": 43},# Public URL (env HERMES_DASHBOARD_PUBLIC_URL): full authority (scheme + host + optional# prefix, e.g. https://example.com/hermes) for the OAuth redirect_uri; its hostname isdiff --git a/hermes_cli/dashboard_auth/base.py b/hermes_cli/dashboard_auth/base.pyindex 9e8c7a6b0c9..b8e71461adf 100644--- a/hermes_cli/dashboard_auth/base.py+++ b/hermes_cli/dashboard_auth/base.py@@ -105,13 +105,18 @@ class DashboardAuthProvider(ABC):Subclasses MUST set ``name`` (stable lowercase id) and ``display_name``. Capability flags:``supports_password`` (credential form + ``complete_password_login``; OAuth methods may be``NotImplementedError`` stubs), ``supports_token`` (``verify_token`` for the token-auth seam),- ``supports_session`` (False for token-only credentials such as drain, never offered a login).+ ``supports_session`` (False for token-only credentials such as drain, never offered a login),+ ``interactive_login`` (False for a provider that verifies credentials but has no browser+ sign-in flow — kept out of the login page, ``/api/auth/providers`` and the auto-SSO redirect+ even though its ``verify_session`` is real; a session provider presenting a provisioned+ shared token is the bundled consumer)."""name: str = ""display_name: str = ""supports_password: bool = Falsesupports_token: bool = Falsesupports_session: bool = True+ interactive_login: bool = True@abstractmethoddef start_login(self, *, redirect_uri: str) -> LoginStart: ...diff --git a/hermes_cli/dashboard_auth/login_page.py b/hermes_cli/dashboard_auth/login_page.pyindex 099154764dd..d6292e7cd74 100644--- a/hermes_cli/dashboard_auth/login_page.py+++ b/hermes_cli/dashboard_auth/login_page.py@@ -388,6 +388,74 @@ an SSH tunnel or Tailscale.</p></html>"""+# Token-gated deployment (every registered provider is provisioned-credential-only):+# there is nothing to click, so the page explains the credential channel instead of+# rendering an empty options list. {provider_names} / {note} are pre-escaped HTML.+_TOKEN_MODE_HTML = """\+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1">+<title>Token-gated dashboard — Hermes Agent</title>+<style>+ :root {+ --background-base: #170d02;+ --midground: #ffac02;+ --foreground: #ffffff;+ --hairline: color-mix(in srgb, #ffac02 18%, transparent);+ }+ *, *::before, *::after { box-sizing: border-box; }+ html, body {+ margin: 0; padding: 0; min-height: 100%;+ background: var(--background-base);+ color: var(--foreground);+ font-family: 'Collapse', system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;+ font-size: 16px; line-height: 1.5;+ -webkit-font-smoothing: antialiased;+ }+ body {+ display: grid; place-items: center;+ padding: clamp(1.5rem, 6vh, 6rem) 1.25rem;+ }+ main {+ width: 100%; max-width: 32rem;+ padding: 2.25rem 2rem;+ background: color-mix(in srgb, #ffffff 2%, var(--background-base));+ border: 1px solid var(--hairline);+ box-shadow:+ inset 1px 1px 0 0 color-mix(in srgb, #ffffff 5%, transparent),+ inset -1px -1px 0 0 rgba(0, 0, 0, 0.4),+ 0 24px 60px -20px rgba(0, 0, 0, 0.6);+ }+ h1 {+ margin: 0 0 1rem;+ font-family: 'Rules Compressed', 'Collapse', sans-serif;+ font-weight: 600; font-size: 1.5rem;+ letter-spacing: 0.05em; text-transform: uppercase;+ color: var(--midground);+ }+ p { margin: 0 0 1rem; }+ code {+ background: var(--midground);+ color: var(--background-base);+ padding: 0.1em 0.35em;+ font-family: 'Courier New', monospace;+ font-size: 0.9em;+ }+</style>+</head>+<body>+<main>+<h1>Token-gated dashboard</h1>+<p>This deployment authenticates with a provisioned credential+({provider_names}), not a browser sign-in.</p>+<p>{note}</p>+</main>+</body>+</html>+"""+# Emitted ONLY when a ``supports_password`` provider is listed, so OAuth-only# login pages stay script-free. Plain string (not ``str.format``): braces are@@ -465,15 +533,30 @@ 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)]+ 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+ # rendering a page with no sign-in options.+ names = ", ".join(html.escape(p.display_name) for p in providers)+ # str.replace, not str.format: the template's CSS braces are literal.+ return (_TOKEN_MODE_HTML+ .replace("{provider_names}", names)+ .replace("{note}",+ "Clients authenticate with the deployment’s provisioned "+ "credential (<code>Authorization: Bearer</code>, or "+ "<code>?token=</code> on the /api/ws upgrade) — e.g. Hermes "+ "Desktop’s “Session token” remote-gateway field. "+ "There is no browser sign-in flow."))buttons = [_render_password_form(p, next_path, prefix=prefix)if getattr(p, "supports_password", False) elsef' <a class="provider-btn" 'f'href="{prefix}/auth/login?provider={html.escape(p.name, quote=True)}{next_qs}">'f'Sign in with {html.escape(p.display_name)}</a>'- for p in providers+ for p in interactive]- needs_password_script = any(getattr(p, "supports_password", False) for p in providers)+ needs_password_script = any(getattr(p, "supports_password", False) for p in interactive)html_out = _LOGIN_HTML_TEMPLATE.format(provider_buttons="\n".join(buttons),password_script=_PASSWORD_FORM_SCRIPT if needs_password_script else "",diff --git a/hermes_cli/dashboard_auth/middleware.py b/hermes_cli/dashboard_auth/middleware.pyindex ba3c9fab268..8834fa0dffd 100644--- a/hermes_cli/dashboard_auth/middleware.py+++ b/hermes_cli/dashboard_auth/middleware.py@@ -123,7 +123,8 @@ 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 = list_session_providers()+ providers = [+ p for p in list_session_providers() if getattr(p, "interactive_login", True)]if len(providers) != 1 or getattr(providers[0], "supports_password", False):return Noneprovider = providers[0]diff --git a/hermes_cli/dashboard_auth/routes.py b/hermes_cli/dashboard_auth/routes.pyindex dedc0b38598..963db63ba0d 100644--- a/hermes_cli/dashboard_auth/routes.py+++ b/hermes_cli/dashboard_auth/routes.py@@ -210,14 +210,18 @@ async def login_page(request: Request) -> HTMLResponse:@router.get("/api/auth/providers", name="auth_providers")async def api_auth_providers() -> Any:- # Only interactive providers are sign-in options; fail closed on zero.- providers = list_session_providers()- if not providers:+ # Only interactive providers are sign-in options; fail closed on zero+ # session providers. A deployment authenticated solely by a provisioned+ # 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: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 providers]}+ for p in session_providers if getattr(p, "interactive_login", True)]}# --- Public: OAuth round trip ----------------------------------------------@@ -229,6 +233,10 @@ async def auth_login(request: Request, provider: str, next: str = ""):raise _http(404, f"Unknown provider: {provider!r}")if not getattr(p, "supports_session", True):raise _http(404, f"Provider does not support interactive login: {provider!r}")+ if not getattr(p, "interactive_login", True):+ # Verifies credentials but has no sign-in flow (the session-token provider):+ # never 500 inside start_login — answer the same 404 an unknown provider gets.+ raise _http(404, f"Provider has no interactive login: {provider!r}")safe_next = _validate_post_login_target(next)if getattr(p, "supports_password", False):login_url = f"{_prefix(request)}/login"@@ -309,7 +317,8 @@ 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 = list_session_providers()+ candidates = [+ c for c in list_session_providers() if getattr(c, "interactive_login", True)]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.diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.pyindex 4bc90b38262..998fa932364 100644--- a/hermes_cli/web_server.py+++ b/hermes_cli/web_server.py@@ -909,6 +909,11 @@ def _no_auth_provider_message(host: str) -> str:"print(hash_password('your-password'))\")\n"" • OAuth: run `hermes dashboard register` (Nous Portal) or ""install a DashboardAuthProvider plugin.\n"+ " • Deployment token: provision HERMES_DASHBOARD_SESSION_TOKEN "+ "(a literal token, or 'file:<path>' naming a secret-manager-decrypted "+ "token file) — the bundled session-token provider then authorizes "+ "bearer REST + /api/ws ?token= for token-mode clients such as the "+ "Desktop's remote-gateway 'Session token' field.\n""There is no unauthenticated public-dashboard option. For "f"local-only use, bind 127.0.0.1 and leave {setting} ""unset; a configured external public URL requires auth even "diff --git a/plugins/dashboard_auth/session_token/__init__.py b/plugins/dashboard_auth/session_token/__init__.pynew file mode 100644index 00000000000..85275d1b3de--- /dev/null+++ b/plugins/dashboard_auth/session_token/__init__.py@@ -0,0 +1,152 @@+"""SessionTokenProvider — the deployment session token as a first-class credential.++Gated mode (non-loopback bind) demands a registered ``DashboardAuthProvider`` and verifies+every bearer / WS ``?token=`` through ``verify_session``. The nix/agenix deployment story+(``backend.sessionTokenFile`` → ``HERMES_DASHBOARD_SESSION_TOKEN=file:<path>``) provisions+exactly one shared secret — the same token the Desktop's "Session token" connection field+presents — but until now nothing vouched for it in gated mode, so a token-only deployment+was forced through the interactive provider prompt into basic-auth credentials it never+asked for. This provider closes that gap: it registers whenever the session token is+provisioned (and not explicitly disabled), and ``verify_session`` constant-time-compares+the presented credential against it. Both auth legs the Desktop uses — the REST+``Authorization: Bearer`` path and the ``/api/ws`` ``?token=`` upgrade credential — run+through that seam, so one provisioned token authorizes both.++It is deliberately NOT an interactive login: no login-page button, no cookies, no refresh.+A browser visiting a token-gated dashboard sees a note pointing at the deployment's+credential channel instead of a dead sign-in link. Disable with+``dashboard.session_token_auth.enabled: false`` in config.yaml (the env var itself is the+opt-in; it is a credential, so there is deliberately no new env var for the toggle).+"""+from __future__ import annotations++import hmac+import logging+import os+import time+from typing import Optional++from hermes_cli.dashboard_auth import (+ DashboardAuthProvider, RefreshExpiredError, Session)+from plugins.dashboard_auth._shared import (+ NonInteractiveMixin, SkipRegistration, load_config_section, register_provider)++logger = logging.getLogger(__name__)+_TAG = "dashboard-auth-session-token"++# The verifier re-derives an expiry on every verify (the credential itself never+# expires — rotation is replacing the env var / secret file), so this only bounds+# how long anything that ever minted a cookie from a verified session would keep it.+_SESSION_HORIZON_SECONDS = 24 * 60 * 60++LAST_SKIP_REASON: str = ""+++def _resolve_provisioned_token() -> str:+ """The exact token ``web_server`` serves under: env value, or the contents of a+ ``file:``-prefixed path (BOM-tolerant, same reader). Raises ``SystemExit`` for an+ unreadable/empty token file — ``register`` maps that to a skip so plugin discovery+ never dies for a sibling provider's misconfiguration."""+ from hermes_cli.web_server_session_token import resolve_session_token++ return resolve_session_token()+++def _load_session_token_auth_section() -> dict:+ return load_config_section(logger, _TAG, "dashboard", "session_token_auth")+++def _opt_out() -> bool:+ """``dashboard.session_token_auth.enabled: false`` disables the provider. There is no+ env toggle: the enabling side of this switch IS ``HERMES_DASHBOARD_SESSION_TOKEN``, a+ credential; behaviour belongs in config.yaml."""+ section = _load_session_token_auth_section()+ return str(section.get("enabled", True)).strip().lower() in ("0", "false", "no", "off")+++def _settings() -> dict:+ """Resolve SessionTokenProvider kwargs; raises ``SkipRegistration`` when the token is+ not provisioned, the provider is disabled, or the token file is unreadable (the file+ resolver's ``SystemExit`` — a deployment misconfiguration must not crash plugin+ discovery for every sibling plugin)."""+ if not os.environ.get("HERMES_DASHBOARD_SESSION_TOKEN", "").strip():+ raise SkipRegistration(+ "HERMES_DASHBOARD_SESSION_TOKEN is not set. Provision it (a literal token, or "+ "'file:<path>' pointing at a secret-manager-decrypted token file) to let the "+ "deployment session token authorize the gated dashboard.")+ if _opt_out():+ raise SkipRegistration(+ "dashboard.session_token_auth.enabled is false; the deployment session token "+ "does not authenticate the gated dashboard.")+ try:+ token = _resolve_provisioned_token()+ except SystemExit as exc:+ raise SkipRegistration(str(exc), level="error") from exc+ if len(token) < 32:+ logger.warning(+ "%s: the provisioned session token is short (%d chars); use a "+ "`secrets.token_urlsafe(32)`-shaped value for a deployment credential.",+ _TAG, len(token))+ return {"token": token}+++class SessionTokenProvider(NonInteractiveMixin, DashboardAuthProvider):+ """Vouches for the deployment session token (``HERMES_DASHBOARD_SESSION_TOKEN``).++ ``supports_session`` is True — the presented bearer/``?token=`` IS the session+ credential the middleware seam verifies — while ``interactive_login`` is False: there+ is no browser sign-in flow, so login surfaces must not offer it.+ """++ name = "session-token"+ display_name = "Deployment Session Token"+ supports_password = False+ supports_session = True+ interactive_login = False+ _NOT_INTERACTIVE = (+ "SessionTokenProvider has no login flow: clients present the provisioned session "+ "token directly (Authorization: Bearer, or ?token= on the /api/ws upgrade).")+ _NO_START_LOGIN = _NOT_INTERACTIVE++ def __init__(self, *, token: str) -> None:+ if not token:+ raise ValueError("token must be non-empty")+ self._token = token++ # ---- session verification (the one capability) --------------------------++ def verify_session(self, *, access_token: str) -> Optional[Session]:+ if not access_token or not hmac.compare_digest(+ access_token.encode("utf-8"), self._token.encode("utf-8")):+ return None+ return Session(+ user_id="deployment-token", email="", display_name="Deployment session token",+ org_id="", provider=self.name,+ expires_at=int(time.time()) + _SESSION_HORIZON_SECONDS,+ access_token=access_token, refresh_token="")++ def refresh_session(self, *, refresh_token: str) -> Session:+ # The credential never rotates server-side mid-process; there is nothing to+ # refresh into. Any refresh attempt is a foreign cookie's — rejected.+ raise RefreshExpiredError("the deployment session token has no refresh token")++ def revoke_session(self, *, refresh_token: str) -> None:+ # Stateless shared credential — revocation is rotation (redeploy the secret).+ # Must not raise.+ return None+++# ---- Plugin entry point ----++def register(ctx) -> None:+ """Register ``SessionTokenProvider`` when the deployment session token is provisioned+ and not disabled; a no-op otherwise (so the gate's fail-closed message keeps steering+ interactive deployments toward basic-auth / OAuth)."""+ global LAST_SKIP_REASON+ LAST_SKIP_REASON = ""+ kwargs, LAST_SKIP_REASON = register_provider(ctx, logger, _TAG, SessionTokenProvider, _settings)+ if kwargs is not None:+ logger.info(+ "%s: registered deployment session-token provider — the provisioned "+ "HERMES_DASHBOARD_SESSION_TOKEN authorizes the gated dashboard "+ "(bearer REST + /api/ws ?token=).", _TAG)diff --git a/plugins/dashboard_auth/session_token/plugin.yaml b/plugins/dashboard_auth/session_token/plugin.yamlnew file mode 100644index 00000000000..eec32995991--- /dev/null+++ b/plugins/dashboard_auth/session_token/plugin.yaml@@ -0,0 +1,7 @@+name: session-token+version: 1.0.0+description: "Dashboard auth provider — the deployment session token (HERMES_DASHBOARD_SESSION_TOKEN, including the file:<path> form the Nix modules render) as a first-class gated-mode credential. verify_session constant-time-compares the presented Authorization: Bearer / /api/ws ?token= credential against the provisioned token, so a token-only deployment satisfies the auth gate without basic-auth or OAuth — the shape the Desktop's 'Session token' remote-gateway field always promised. Not an interactive login: no login-page button, no cookies, no refresh (rotation is redeploying the secret). Disable with dashboard.session_token_auth.enabled: false."+author: NousResearch+kind: backend+requires_env:+ - HERMES_DASHBOARD_SESSION_TOKENdiff --git a/tests/hermes_cli/test_dashboard_auth_session_token_gate.py b/tests/hermes_cli/test_dashboard_auth_session_token_gate.pynew file mode 100644index 00000000000..f56bf36e3c7--- /dev/null+++ b/tests/hermes_cli/test_dashboard_auth_session_token_gate.py@@ -0,0 +1,129 @@+"""End-to-end gate tests for the session-token auth provider.++The bellona-shaped scenario: a non-loopback dashboard whose ONLY credential is the+provisioned ``HERMES_DASHBOARD_SESSION_TOKEN`` (the nix/agenix deployment story).+Before the session-token provider, that deployment hit the fail-closed gate, got+talked into basic auth by the interactive prompt, and its own token was rejected+on every gated leg (REST 401, ``/api/ws`` 403) — the desktop's "HTTP passes but the+WebSocket fails" incident. These tests pin the fixed behaviour:++ * the gate is satisfied with the token provider as the only registered provider,+ and still fails closed with none,+ * the REST bearer leg verifies the provisioned token,+ * the ``/api/ws`` upgrade accepts ``?token=<provisioned>`` and rejects anything else.+"""+from __future__ import annotations++import secrets+from types import SimpleNamespace++import pytest+from fastapi.testclient import TestClient++from hermes_cli import web_server+import hermes_cli.web_server_chat as _web_server_chat+from hermes_cli.dashboard_auth import clear_providers, register_provider+from hermes_cli.dashboard_auth.ws_tickets import _reset_for_tests+import plugins.dashboard_auth.session_token as session_token_plugin+++def token():+ return secrets.token_urlsafe(32)+++def gated_token_app(token):+ """web_server.app in gated mode with ONLY the session-token provider registered."""+ _reset_for_tests()+ clear_providers()+ register_provider(session_token_plugin.SessionTokenProvider(token=token))+ prev = {k: getattr(web_server.app.state, k, None)+ for k in ("bound_host", "bound_port", "auth_required")}+ web_server.app.state.bound_host = "bellona.ts.net"+ web_server.app.state.bound_port = 9119+ web_server.app.state.auth_required = True+ client = TestClient(web_server.app, base_url="https://bellona.ts.net")+ yield client+ clear_providers()+ _reset_for_tests()+ for k, v in prev.items():+ setattr(web_server.app.state, k, v)+++def _fake_ws(*, query: dict, client_host: str = "203.0.113.7", path: str = "/api/ws"):+ class _QP:+ def __init__(self, q):+ self._q = q++ def get(self, k, default=""):+ return self._q.get(k, default)++ return SimpleNamespace(+ query_params=_QP(query),+ headers={},+ client=SimpleNamespace(host=client_host),+ url=SimpleNamespace(path=path),+ )+++# ---------------------------------------------------------------------------+# The gate itself+# ---------------------------------------------------------------------------+++class TestGateEngagement:+ def test_token_provider_satisfies_the_fail_closed_gate(self, token):+ """A non-loopback bind with only the session-token provider starts."""+ clear_providers()+ register_provider(session_token_plugin.SessionTokenProvider(token=token))+ web_server._configure_auth_gate(+ "0.0.0.0", allow_public=False, ssh_session_token=None, ssh_owner_nonce=None)+ assert web_server.app.state.auth_required is True++ def test_no_providers_still_fails_closed(self, token):+ clear_providers()+ with pytest.raises(SystemExit):+ web_server._configure_auth_gate(+ "0.0.0.0", allow_public=False, ssh_session_token=None, ssh_owner_nonce=None)+++# ---------------------------------------------------------------------------+# The two legs the desktop exercises+# ---------------------------------------------------------------------------+++class TestRestBearerLeg:+ 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++ 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)}"})+ 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}"})+ assert r.status_code == 401+++class TestWsUpgradeLeg:+ def test_provisioned_token_is_accepted(self, gated_token_app, token):+ reason, credential = _web_server_chat._ws_auth_reason(+ _fake_ws(query={"token": token}))+ assert reason is None+ assert credential == "token"++ def test_foreign_token_is_rejected(self, gated_token_app, token):+ reason, _ = _web_server_chat._ws_auth_reason(+ _fake_ws(query={"token": secrets.token_urlsafe(32)}))+ assert reason == "token_invalid"++ def test_no_credential_is_rejected(self, gated_token_app):+ reason, credential = _web_server_chat._ws_auth_reason(_fake_ws(query={}))+ assert reason == "no_credential"+ assert credential == "none"diff --git a/tests/plugins/dashboard_auth/test_session_token_provider.py b/tests/plugins/dashboard_auth/test_session_token_provider.pynew file mode 100644index 00000000000..0faad25c618--- /dev/null+++ b/tests/plugins/dashboard_auth/test_session_token_provider.py@@ -0,0 +1,206 @@+"""Tests for the SessionTokenProvider plugin (the deployment session token as a+gated-mode credential).++Loads the bundled session_token plugin module directly and exercises:+ * registration — registers when HERMES_DASHBOARD_SESSION_TOKEN is provisioned+ (literal or file:<path>, BOM-tolerant), skips when it is absent, when the+ dashboard.session_token_auth.enabled knob opts out, and when the token file+ is unreadable (the file resolver's SystemExit mapped to a skip, never a+ discovery crash),+ * verify_session — constant-time accept of the provisioned token into a+ Session, None for anything else; refresh/revoke/start_login semantics,+ * interactive surfaces — interactive_login False keeps the provider off the+ login page (token-mode notice HTML instead) and out of /api/auth/providers.+"""+from __future__ import annotations++import secrets+from unittest.mock import MagicMock++import pytest++import plugins.dashboard_auth.session_token as session_token_plugin+from hermes_cli.dashboard_auth import RefreshExpiredError, assert_protocol_compliance+from hermes_cli.dashboard_auth import registry++[email protected](scope="module")+def plugin():+ return session_token_plugin++[email protected](autouse=True)+def _clean_env_and_registry(monkeypatch):+ monkeypatch.delenv("HERMES_DASHBOARD_SESSION_TOKEN", raising=False)+ registry.clear_providers()+ yield+ registry.clear_providers()+++def _token() -> str:+ return secrets.token_urlsafe(32)+++# ---------------------------------------------------------------------------+# Provider behaviour+# ---------------------------------------------------------------------------+++class TestProvider:+ def test_protocol_compliance(self, plugin):+ assert_protocol_compliance(plugin.SessionTokenProvider)++ def test_is_a_session_credential_but_not_an_interactive_login(self, plugin):+ p = plugin.SessionTokenProvider(token=_token())+ assert p.supports_session is True+ assert p.supports_password is False+ assert p.interactive_login is False++ def test_verify_session_accepts_the_provisioned_token(self, plugin):+ token = _token()+ p = plugin.SessionTokenProvider(token=token)+ session = p.verify_session(access_token=token)+ assert session is not None+ assert session.provider == "session-token"+ assert session.user_id == "deployment-token"+ assert session.access_token == token+ assert session.expires_at > 0++ def test_verify_session_rejects_foreign_and_empty(self, plugin):+ p = plugin.SessionTokenProvider(token=_token())+ assert p.verify_session(access_token=secrets.token_urlsafe(32)) is None+ assert p.verify_session(access_token="") is None++ def test_refresh_raises_expired_and_revoke_is_silent(self, plugin):+ p = plugin.SessionTokenProvider(token=_token())+ with pytest.raises(RefreshExpiredError):+ p.refresh_session(refresh_token="anything")+ assert p.revoke_session(refresh_token="anything") is None++ def test_interactive_methods_raise(self, plugin):+ p = plugin.SessionTokenProvider(token=_token())+ with pytest.raises(NotImplementedError):+ p.start_login(redirect_uri="r")+ with pytest.raises(NotImplementedError):+ p.complete_login(code="c", state="s", code_verifier="v", redirect_uri="r")++ def test_construction_rejects_empty_token(self, plugin):+ with pytest.raises(ValueError):+ plugin.SessionTokenProvider(token="")+++# ---------------------------------------------------------------------------+# register() entry point+# ---------------------------------------------------------------------------+++class TestRegister:+ def test_skips_when_no_token_provisioned(self, plugin, monkeypatch):+ monkeypatch.setattr(plugin, "_load_session_token_auth_section", dict)+ ctx = MagicMock()+ plugin.register(ctx)+ ctx.register_dashboard_auth_provider.assert_not_called()+ assert "HERMES_DASHBOARD_SESSION_TOKEN" in plugin.LAST_SKIP_REASON++ def test_registers_with_env_token(self, plugin, monkeypatch):+ token = _token()+ monkeypatch.setenv("HERMES_DASHBOARD_SESSION_TOKEN", token)+ monkeypatch.setattr(plugin, "_load_session_token_auth_section", dict)+ ctx = MagicMock()+ plugin.register(ctx)+ ctx.register_dashboard_auth_provider.assert_called_once()+ provider = ctx.register_dashboard_auth_provider.call_args.args[0]+ assert isinstance(provider, plugin.SessionTokenProvider)+ assert provider.verify_session(access_token=token) is not None+ assert plugin.LAST_SKIP_REASON == ""++ def test_resolves_file_prefix(self, plugin, monkeypatch, tmp_path):+ token = _token()+ token_file = tmp_path / "hermes-gateway-token"+ token_file.write_text(f"\ufeff{token}\n", encoding="utf-8") # BOM + newline+ monkeypatch.setenv("HERMES_DASHBOARD_SESSION_TOKEN", f"file:{token_file}")+ monkeypatch.setattr(plugin, "_load_session_token_auth_section", dict)+ ctx = MagicMock()+ plugin.register(ctx)+ ctx.register_dashboard_auth_provider.assert_called_once()+ provider = ctx.register_dashboard_auth_provider.call_args.args[0]+ assert provider.verify_session(access_token=token) is not None++ def test_skip_on_unreadable_token_file(self, plugin, monkeypatch, tmp_path):+ monkeypatch.setenv(+ "HERMES_DASHBOARD_SESSION_TOKEN", f"file:{tmp_path / 'missing'}")+ monkeypatch.setattr(plugin, "_load_session_token_auth_section", dict)+ ctx = MagicMock()+ plugin.register(ctx)+ ctx.register_dashboard_auth_provider.assert_not_called()+ assert plugin.LAST_SKIP_REASON++ def test_config_opt_out(self, plugin, monkeypatch):+ monkeypatch.setenv("HERMES_DASHBOARD_SESSION_TOKEN", _token())+ monkeypatch.setattr(+ plugin, "_load_session_token_auth_section", lambda: {"enabled": False})+ ctx = MagicMock()+ plugin.register(ctx)+ ctx.register_dashboard_auth_provider.assert_not_called()+ assert "enabled" in plugin.LAST_SKIP_REASON++ def test_short_token_still_registers_with_warning(+ self, plugin, monkeypatch, caplog):+ token = "short-but-mine"+ monkeypatch.setenv("HERMES_DASHBOARD_SESSION_TOKEN", token)+ monkeypatch.setattr(plugin, "_load_session_token_auth_section", dict)+ ctx = MagicMock()+ with caplog.at_level("WARNING"):+ plugin.register(ctx)+ ctx.register_dashboard_auth_provider.assert_called_once()+ assert any("short" in r.message for r in caplog.records)+++# ---------------------------------------------------------------------------+# Interactive surfaces honour interactive_login=False+# ---------------------------------------------------------------------------+++class TestInteractiveSurfaces:+ # A real provider subclass: registry.register_global_provider runs+ # assert_protocol_compliance(type(provider)), which needs the credential methods.+ @staticmethod+ def _stub(name: str, display_name: str, *, password: bool = False):+ cls = type("StubProvider", (session_token_plugin.SessionTokenProvider,), {+ "name": name, "display_name": display_name,+ "supports_password": password, "interactive_login": True})+ return cls(token=_token())++ def test_login_page_shows_token_mode_notice_not_a_button(self, plugin):+ from hermes_cli.dashboard_auth.login_page import render_login_html++ registry.register_global_provider(plugin.SessionTokenProvider(token=_token()))+ html = render_login_html(next_path="", prefix="")+ assert "Token-gated dashboard" in html+ assert "Deployment Session Token" in html+ assert "provider-btn" not in html+ assert "/auth/login?provider=" not in html++ def test_login_page_keeps_interactive_providers_clickable(self, plugin):+ from hermes_cli.dashboard_auth.login_page import render_login_html++ registry.register_global_provider(plugin.SessionTokenProvider(token=_token()))+ registry.register_global_provider(+ self._stub("basic", "Username & Password", password=True))+ html = render_login_html(next_path="", prefix="")+ assert "Token-gated dashboard" not in html+ # The password provider renders its form (a link is only for OAuth-style providers).+ assert 'data-provider="basic"' in html++ def test_api_auth_providers_filters_non_interactive(self, plugin):+ import asyncio++ from hermes_cli.dashboard_auth.routes import api_auth_providers++ registry.register_global_provider(plugin.SessionTokenProvider(token=_token()))+ providers = asyncio.run(api_auth_providers())+ assert providers == {"providers": []}++ registry.register_global_provider(self._stub("nous", "Nous Research"))+ providers = asyncio.run(api_auth_providers())+ assert [p["name"] for p in providers["providers"]] == ["nous"]diff --git a/website/docs/user-guide/features/web-dashboard.md b/website/docs/user-guide/features/web-dashboard.mdindex b181aee88c1..69da90a1a0a 100644--- a/website/docs/user-guide/features/web-dashboard.md+++ b/website/docs/user-guide/features/web-dashboard.md@@ -860,6 +860,36 @@ curl -s http://<host>:9119/api/status | jq '.auth_required, .auth_providers'`basic` is just one implementation of an extension point. Any plugin can register a password provider: set `supports_password = True` on your `DashboardAuthProvider` subclass and implement `complete_password_login(*, username, password) -> Session` (raise `InvalidCredentialsError` on rejection, `ProviderError` if your backing store is down). The OAuth `start_login` / `complete_login` methods can be left as `NotImplementedError` stubs for a pure-password provider. This is the path for LDAP-bind, a credentials database, or any other non-redirect auth scheme — the framework handles the form, the route, the cookies, and refresh for you.+### Deployment session-token provider (token-only deployments)++The bundled `plugins/dashboard_auth/session_token` plugin makes the **deployment session token** (`HERMES_DASHBOARD_SESSION_TOKEN`) a first-class gated-mode credential. This is the shape secret-managed deployments already provision — a single shared token (nix/agenix hands it over as a decrypted file; the Nix modules set `HERMES_DASHBOARD_SESSION_TOKEN=file:<path>` from `backend.sessionTokenFile`) that Hermes Desktop's remote-gateway **"Session token"** field presents. Without this provider, a non-loopback bind with only a provisioned token hit the fail-closed gate and pushed the operator into basic-auth or OAuth credentials the deployment never asked for.++When the env var is provisioned, the provider registers automatically and `verify_session` constant-time-compares the presented credential against it. Both legs a token-mode client uses run through that seam — the REST `Authorization: Bearer` path and the `/api/ws` `?token=` upgrade credential — so one provisioned token authorizes both. There is **no browser sign-in flow**: `/login` renders a note explaining the credential channel instead of sign-in buttons, and the provider is never offered by the auto-SSO redirect.++:::warning Treat the token like a password+The provisioned token grants full dashboard access to whoever holds it. Provision it from a secret manager (never a Nix store path), rotate by redeploying the secret — rotation invalidates every saved client copy, which surfaces as "HTTP reachable but the WebSocket fails" in Desktop until the new token is pasted in. There is no per-user identity behind it: for shared or internet-facing deployments prefer the [Nous Research](#default-provider-nous-research) or [self-hosted OIDC](#self-hosted-oidc-provider) provider.+:::++**Activation and opt-out.** Registering is driven by the credential itself: the provider is a no-op until `HERMES_DASHBOARD_SESSION_TOKEN` is set (env wins; `file:<path>` is read at startup and fails loudly when missing/empty). To keep the token internal-only (loopback SPA use, desktop-spawned backends) while authenticating the gate with basic-auth/OAuth instead, disable the provider:++```yaml+dashboard:+ session_token_auth:+ enabled: false+```++Verify a token-gated deployment from any machine:++```bash+curl -s http://<host>:9119/api/status | jq '.auth_required, .auth_providers'+# true+# ["session-token"]++curl -s -o /dev/null -w '%{http_code}\n' \+ -H "Authorization: Bearer $TOKEN" http://<host>:9119/api/me+# 200+```+### Self-hosted OIDC providerIf you run your own identity provider, the bundled `plugins/dashboard_auth/self_hosted` plugin authenticates the dashboard against it using **standard OpenID Connect** — no per-IDP code, no Nous Portal involved. It's verified against and works with any conformant OIDC server: