The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(auth): accept provider-verified session tokens in gated WS auth
Brooklyn Nicholson063de859ddeb
diff --git a/hermes_cli/web_server_chat.py b/hermes_cli/web_server_chat.pyindex a8a0dca0115..0ced511bca4 100644--- a/hermes_cli/web_server_chat.py+++ b/hermes_cli/web_server_chat.py@@ -14,9 +14,11 @@ import sysimport tempfileimport threadingimport urllib.request-from fastapi import FastAPI, WebSocket, WebSocketDisconnect-from pathlib import Pathfrom typing import Optional++from fastapi import FastAPI, Request, WebSocket, WebSocketDisconnect+from pathlib import Path+from typing import Optional # noqa: F811 — historical duplicate import keptfrom hermes_cli.pty_session import PtySessionRegistry# Same logger the code used before extraction (record parity).@@ -217,6 +219,31 @@ def _gateway_ws_ticket_from_subprotocol(ws: "WebSocket") -> tuple[str, str]:return (ticket, "ok") if ticket else ("", "invalid")+def _ws_request_view(ws: "WebSocket") -> "Request":+ """A ``Request`` facade over a ``WebSocket`` for the auth helpers.++ ``_verify_access_token`` only touches ``request.headers`` (X-Forwarded-For+ via ``client_ip``) and ``request.client`` on this path (``audit=False``,+ no cookie/redirect work), so a lightweight duck-typed stand-in avoids+ constructing a real ASGI request inside the upgrade. ``scan_session_providers``+ itself never sees the request — only the provider callbacks do.+ """+ from fastapi import Request++ return Request({+ "type": "http",+ "headers": [(k.lower().encode("latin-1"), v.encode("latin-1"))+ for k, v in getattr(ws.headers, "items", lambda: {})()],+ "client": (ws.client.host, 0) if ws.client else None,+ "server": None,+ "scheme": "ws",+ "method": "GET",+ "path": ws.url.path,+ "query_string": b"",+ "root_path": "",+ })++def _ws_auth_reason(ws: "WebSocket") -> tuple[Optional[str], str]:"""Validate WS-upgrade auth; return ``(reason, credential)``.@@ -227,8 +254,12 @@ def _ws_auth_reason(ws: "WebSocket") -> tuple[Optional[str], str]:Loopback / ``--insecure``: legacy ``?token=`` (constant-time compared).Gated: ``?ticket=`` (browser-minted, single-use, 30s TTL) or ``?internal=``(process-lifetime, multi-use, only for server-spawned WS clients so the PTY- child can reconnect; never injected into the SPA). The legacy token is- rejected in gated mode: a leaked ``_SESSION_TOKEN`` must not grant access.+ child can reconnect; never injected into the SPA), or ``?token=`` holding a+ user session access token (verified against the dashboard auth session+ providers — the same ``verify_session`` seam the native bearer REST leg+ uses — e.g. a token-mode Remote desktop connection). The legacy in-process+ ``_SESSION_TOKEN`` is rejected in gated mode: a leaked ``_SESSION_TOKEN``+ must not grant access."""from hermes_cli.web_server import _SESSION_TOKEN, appauth_required = bool(getattr(app.state, "auth_required", False))@@ -266,26 +297,71 @@ def _ws_auth_reason(ws: "WebSocket") -> tuple[Optional[str], str]:if protocol_reason == "invalid":return "ticket_invalid", "ticket-subprotocol"ticket = protocol_ticket or ws.query_params.get("ticket", "")- if not ticket:- return "no_credential", "none"+ if ticket:+ try:+ info = consume_ticket(ticket)+ if info.get("provider") == "bot-desktop":+ # A display ticket admits one RFB bridge on /api/display/ws (a watch-only+ # capability handed to a screen viewer); it must not double as a login here.+ raise TicketInvalid("display ticket presented as a gateway login")+ _stamp_identity(info)+ if protocol_ticket:+ # Select only the stable public protocol during accept. The+ # ticket-bearing protocol is a credential and must never be+ # reflected back to the browser or retained after admission.+ ws._hermes_ws_subprotocol = _GATEWAY_WS_PROTOCOL+ return None, "ticket-subprotocol"+ return None, "ticket"+ except TicketInvalid as exc:+ _reject(str(exc))+ return "ticket_invalid", "ticket"++ # A user session access token (``?token=``) is verified against the+ # dashboard auth session providers — the SAME ``verify_session`` seam+ # the native bearer REST leg uses (``_verify_access_token``). A+ # token-mode Remote desktop connection bakes its stored session token+ # into the WS URL (buildGatewayWsUrl), so before this leg existed the+ # only credentials gated mode accepted were browser-minted tickets and+ # the WS upgrade 403'd forever. The legacy in-process+ # ``_SESSION_TOKEN`` never reaches this check: gated mode falls+ # through to the explicit rejection below (leaked-constant safety),+ # and a provider-verified token is accepted on identity merit.+ token = ws.query_params.get("token", "")+ if token:+ from hermes_cli.dashboard_auth.base import ProviderError+ from hermes_cli.dashboard_auth.middleware import _verify_access_token- try:- info = consume_ticket(ticket)- if info.get("provider") == "bot-desktop":- # A display ticket admits one RFB bridge on /api/display/ws (a watch-only- # capability handed to a screen viewer); it must not double as a login here.- raise TicketInvalid("display ticket presented as a gateway login")- _stamp_identity(info)- if protocol_ticket:- # Select only the stable public protocol during accept. The- # ticket-bearing protocol is a credential and must never be- # reflected back to the browser or retained after admission.- ws._hermes_ws_subprotocol = _GATEWAY_WS_PROTOCOL- return None, "ticket-subprotocol"- return None, "ticket"- except TicketInvalid as exc:- _reject(str(exc))- return "ticket_invalid", "ticket"+ try:+ session = _verify_access_token(+ _ws_request_view(ws), access_token=token, audit=False)+ except ProviderError as exc:+ # All providers unreachable (IDP outage) — reject without+ # crashing the upgrade; the REST bearer leg answers 503, and+ # the WS accept path has no status channel, only close codes.+ _reject(f"session token verify unavailable: {exc}")+ return "token_unavailable", "token"+ if session is not None:+ _stamp_identity({+ "user_id": getattr(session, "user_id", None),+ "provider": getattr(session, "provider", None),+ })+ audit_log(+ AuditEvent.TOKEN_AUTH_SUCCESS,+ provider=getattr(session, "provider", None),+ user_id=getattr(session, "user_id", None),+ ip=(ws.client.host if ws.client else ""),+ path=ws.url.path,+ )+ return None, "token"+ audit_log(+ AuditEvent.TOKEN_AUTH_FAILURE,+ reason="session_token_invalid",+ ip=(ws.client.host if ws.client else ""),+ path=ws.url.path,+ )+ return "token_invalid", "token"++ return "no_credential", "none"token = ws.query_params.get("token", "")if not token:diff --git a/tests/hermes_cli/test_dashboard_auth_ws_auth.py b/tests/hermes_cli/test_dashboard_auth_ws_auth.pyindex e7da822a732..ef558fc9a17 100644--- a/tests/hermes_cli/test_dashboard_auth_ws_auth.py+++ b/tests/hermes_cli/test_dashboard_auth_ws_auth.py@@ -13,6 +13,7 @@ pre-existing regression unrelated to dashboard-auth.from __future__ import annotations+import timefrom types import SimpleNamespaceimport pytest@@ -28,7 +29,7 @@ from hermes_cli.dashboard_auth.ws_tickets import (internal_ws_credential,mint_ticket,)-from tests.hermes_cli.conftest_dashboard_auth import StubAuthProvider+from tests.hermes_cli.conftest_dashboard_auth import StubAuthProvider, _sign# ---------------------------------------------------------------------------@@ -268,6 +269,80 @@ class TestWsAuthOkGated:ws = _fake_ws(query={"token": web_server._SESSION_TOKEN})assert _web_server_chat._ws_auth_ok(ws) is False+ def test_session_token_accepted_in_gated_mode(self, gated_app):+ """A provider-verified session access token (?token=) is accepted in+ gated mode — the credential a token-mode Remote desktop connection+ bakes into its WS URL. Reuses the same verify_session provider seam+ as the native bearer REST leg (#106685)."""+ access_token = _sign({+ "sub": "remote-desktop-user",+ "email": "[email protected]",+ "name": "Remote User",+ "org_id": "org-1",+ "exp": int(time.time()) + 3600,+ })+ ws = _fake_ws(query={"token": access_token}, path="/api/ws")+ assert _web_server_chat._ws_auth_ok(ws) is True+ assert ws._hermes_auth_identity == {+ "user_id": "remote-desktop-user",+ "provider": "stub",+ }++ def test_invalid_session_token_rejected_in_gated_mode(self, gated_app):+ """A bogus ?token= fails with token_invalid (and audits), not a crash."""+ ws = _fake_ws(query={"token": "bogus-token"}, path="/api/ws")+ reason, cred = _web_server_chat._ws_auth_reason(ws)+ assert reason == "token_invalid"+ assert cred == "token"+ assert _web_server_chat._ws_auth_ok(ws) is False++ def test_expired_session_token_rejected_in_gated_mode(self, gated_app):+ """A well-formed but expired session token is rejected: the provider+ verify seam honours exp, so a leaked stale token grants nothing."""+ access_token = _sign({+ "sub": "remote-desktop-user",+ "email": "[email protected]",+ "name": "Remote User",+ "org_id": "org-1",+ "exp": int(time.time()) - 3600,+ })+ ws = _fake_ws(query={"token": access_token}, path="/api/ws")+ assert _web_server_chat._ws_auth_ok(ws) is False++ def test_display_ticket_still_rejected_as_gateway_login(self, gated_app):+ """The token leg must not disturb the bot-desktop display-ticket+ guard: a display ticket presented as a gateway login stays invalid."""+ ticket = mint_ticket(user_id="bot-user", provider="bot-desktop")+ ws = _fake_ws(query={"ticket": ticket}, path="/api/ws")+ assert _web_server_chat._ws_auth_ok(ws) is False++ def test_session_token_audit_logs(self, gated_app, tmp_path, monkeypatch):+ """Accept and reject of a session token both audit."""+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ from hermes_cli.dashboard_auth import audit as audit_mod++ if hasattr(audit_mod, "_LOGGER"):+ monkeypatch.setattr(audit_mod, "_LOGGER", None, raising=False)++ access_token = _sign({+ "sub": "remote-desktop-user",+ "email": "[email protected]",+ "name": "Remote User",+ "org_id": "org-1",+ "exp": int(time.time()) + 3600,+ })+ ws_ok = _fake_ws(query={"token": access_token}, path="/api/ws")+ assert _web_server_chat._ws_auth_ok(ws_ok) is True++ ws_bad = _fake_ws(query={"token": "bogus-token"}, path="/api/ws")+ assert _web_server_chat._ws_auth_ok(ws_bad) is False++ log_file = tmp_path / "logs" / "dashboard-auth.log"+ if log_file.exists():+ content = log_file.read_text()+ assert "token_auth_success" in content+ assert "token_auth_failure" in content+def test_rejection_audit_logs(self, gated_app, tmp_path, monkeypatch):# Point the audit log at a tmp dir so we can read what got written.monkeypatch.setenv("HERMES_HOME", str(tmp_path))