The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(dashboard): repair loopback auth identity frontend integration (#66295)
Tranquil-Flow0f56e56a2440
diff --git a/hermes_cli/dashboard_auth/routes.py b/hermes_cli/dashboard_auth/routes.pyindex d1bd6313eb4..ecffab88e21 100644--- a/hermes_cli/dashboard_auth/routes.py+++ b/hermes_cli/dashboard_auth/routes.py@@ -12,7 +12,8 @@ allowlists the public ones.POST /auth/native/token loopback code -> bearer tokensPOST /auth/native/refresh desktop-held refresh token rotationGET /api/auth/providers list registered providers (login bootstrap)- GET /api/auth/me current Session as JSON (auth-required)+ GET /api/auth/me Session as JSON (gated: verified session; loopback:+ token-validated synthetic loopback identity)POST /api/auth/ws-ticket single-use WS upgrade ticket (auth-required)"""from __future__ import annotations@@ -522,8 +523,31 @@ def _require_session(request: Request):@router.get("/api/auth/me", name="auth_me")async def api_auth_me(request: Request):- """Return the verified session as JSON. Auth-required (gate enforces)."""- sess = _require_session(request)+ """Return the verified session as JSON.++ Gated mode: the auth middleware attached a verified Session — return it.+ Loopback mode (``auth_required`` False): there is no OAuth Session, but the+ legacy ``_SESSION_TOKEN`` middleware has already validated the bearer+ token for non-public ``/api/`` routes. Report the loopback identity+ honestly instead of 401-ing (GH #66223). Belt-and-braces: re-verify the+ token so the handler stays safe even if this route were ever allowlisted.+ """+ sess = getattr(request.state, "session", None)+ if sess is None:+ if getattr(request.app.state, "auth_required", False):+ raise _http(401, "Unauthorized")+ from hermes_cli.web_server import _has_valid_session_token++ if not _has_valid_session_token(request):+ raise _http(401, "Unauthorized")+ return {+ "user_id": "local",+ "email": "",+ "display_name": "Local",+ "org_id": "",+ "provider": "loopback",+ "expires_at": 0,+ }return {"user_id": sess.user_id, "email": sess.email, "display_name": sess.display_name,"org_id": sess.org_id, "provider": sess.provider, "expires_at": sess.expires_at}diff --git a/tests/hermes_cli/test_dashboard_auth_middleware.py b/tests/hermes_cli/test_dashboard_auth_middleware.pyindex 8a5c28fc223..37e06470e10 100644--- a/tests/hermes_cli/test_dashboard_auth_middleware.py+++ b/tests/hermes_cli/test_dashboard_auth_middleware.py@@ -347,6 +347,63 @@ def test_api_auth_me_requires_auth(gated_app):assert r.status_code == 401+# ---------------------------------------------------------------------------+# Loopback-mode identity probe (GH #66223)+# ---------------------------------------------------------------------------+++def loopback_app():+ """Configure web_server.app for loopback mode (auth_required=False).++ Mirrors ``gated_app`` but flips the gate off and clears ``bound_host``+ so the host-header check doesn't reject the TestClient's requests.+ """+ clear_providers()+ prev_host = getattr(web_server.app.state, "bound_host", None)+ prev_required = getattr(web_server.app.state, "auth_required", None)+ web_server.app.state.bound_host = None+ web_server.app.state.auth_required = False+ client = TestClient(web_server.app, base_url="http://127.0.0.1")+ yield client+ clear_providers()+ web_server.app.state.bound_host = prev_host+ web_server.app.state.auth_required = prev_required+++def test_api_auth_me_returns_loopback_identity_with_valid_token(loopback_app):+ """Regression for GH #66223.++ In loopback mode there is no OAuth ``Session``, but the legacy+ ``auth_middleware`` has already validated the ephemeral+ ``_SESSION_TOKEN``. The handler must return a minimal identity so+ the SPA can resolve its boot state instead of spinning on a 401.+ """+ token = web_server._SESSION_TOKEN+ r = loopback_app.get(+ "/api/auth/me",+ headers={"Authorization": f"Bearer {token}"},+ )+ assert r.status_code == 200, (+ f"Expected 200 with a valid token in loopback mode, "+ f"got {r.status_code}: {r.text}"+ )+ body = r.json()+ assert body["provider"] == "loopback"+ assert body["user_id"] == "local"+ assert "display_name" in body+ assert "email" in body+ assert "org_id" in body+ assert "expires_at" in body+++def test_api_auth_me_still_rejects_missing_token_in_loopback(loopback_app):+ """Security boundary (GH #66223): without a valid token the endpoint+ must still 401 even in loopback mode."""+ r = loopback_app.get("/api/auth/me")+ assert r.status_code == 401++# ---------------------------------------------------------------------------# Zero-providers fail-closed# ---------------------------------------------------------------------------diff --git a/web/src/components/AuthWidget.test.tsx b/web/src/components/AuthWidget.test.tsxnew file mode 100644index 00000000000..df210584488--- /dev/null+++ b/web/src/components/AuthWidget.test.tsx@@ -0,0 +1,161 @@+// @vitest-environment jsdom+import { act } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, describe, expect, it, vi } from "vitest";++import { AuthWidget } from "./AuthWidget";+import { shouldHideAuthWidget } from "./auth-widget-visibility";++// --- Unit tests for the visibility helper ---++describe("AuthWidget loopback identity", () => {+ it("hides the auth and logout affordance for loopback identity", () => {+ expect(+ shouldHideAuthWidget({+ display_name: "Local",+ email: "",+ expires_at: 0,+ org_id: "",+ provider: "loopback",+ user_id: "local",+ }),+ ).toBe(true);+ });++ it("keeps the widget visible for gated identities", () => {+ expect(+ shouldHideAuthWidget({+ display_name: "",+ email: "",+ expires_at: 123,+ org_id: "org",+ provider: "portal",+ user_id: "user-1",+ }),+ ).toBe(false);+ });+});++// --- Integration tests: AuthWidget + real api.getAuthMe ---++/** Return a fetch mock that resolves with a JSON Response. */+function jsonFetchMock(body: unknown, status = 200) {+ return vi.fn<typeof fetch>(+ async () =>+ new Response(JSON.stringify(body), {+ headers: { "Content-Type": "application/json" },+ status,+ }),+ );+}++/** Wait one microtick for React to flush state updates. */+function flush() {+ return act(() => Promise.resolve());+}++describe("AuthWidget integration (real getAuthMe)", () => {+ let root: Root;+ let container: HTMLDivElement;++ afterEach(() => {+ if (root) {+ root.unmount();+ }+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+ });++ function setupWindow(overrides: Partial<Window> = {}) {+ vi.stubGlobal("window", {+ __HERMES_SESSION_TOKEN__: undefined,+ __HERMES_BASE_PATH__: "",+ location: { assign: vi.fn(), pathname: "/", search: "" },+ ...overrides,+ });+ }++ function render() {+ container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);+ act(() => {+ root.render(<AuthWidget />);+ });+ }++ it("hides itself when /api/auth/me returns a loopback identity", async () => {+ setupWindow({ __HERMES_SESSION_TOKEN__: "loopback-token" });+ const identity = {+ display_name: "Local",+ email: "",+ expires_at: 0,+ org_id: "",+ provider: "loopback",+ user_id: "local",+ };+ const fetchMock = jsonFetchMock(identity);+ vi.stubGlobal("fetch", fetchMock);++ render();++ // Wait for the async getAuthMe request to resolve and state to flush.+ await flush();++ // The widget should be hidden: no DOM, no logout button.+ expect(container.innerHTML).toBe("");+ expect(container.querySelector('[aria-label="Log out"]')).toBeNull();+ expect(container.textContent).not.toContain("via");++ // Prove the request went through the real getAuthMe → fetchJSON path.+ expect(fetchMock).toHaveBeenCalledTimes(1);+ const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit];+ expect(url).toBe("/api/auth/me");+ expect((init!.headers as Headers).get("X-Hermes-Session-Token")).toBe(+ "loopback-token",+ );+ });++ it("renders user info when /api/auth/me returns a non-loopback identity", async () => {+ setupWindow({ __HERMES_SESSION_TOKEN__: "portal-token" });+ const identity = {+ display_name: "Ada",+ email: "[email protected]",+ expires_at: 9999999999,+ org_id: "org-1",+ provider: "portal",+ user_id: "user-ada-123",+ };+ const fetchMock = jsonFetchMock(identity);+ vi.stubGlobal("fetch", fetchMock);++ render();+ await flush();++ // The widget should be visible with the provider and logout button.+ expect(container.innerHTML).not.toBe("");+ expect(container.textContent).toContain("Ada");+ expect(container.textContent).toContain("via portal");+ expect(container.querySelector('[aria-label="Log out"]')).not.toBeNull();+ });++ it("hides on 401 (missing/invalid token in loopback mode)", async () => {+ setupWindow({ __HERMES_SESSION_TOKEN__: "bad-token" });+ // fetchJSON throws "401: Unauthorized" for non-OK without envelope.+ const fetchMock = vi.fn<typeof fetch>(+ async () =>+ new Response("Unauthorized", {+ status: 401,+ statusText: "Unauthorized",+ }),+ );+ vi.stubGlobal("fetch", fetchMock);++ render();+ await flush();++ // Widget should hide on 401.+ expect(container.innerHTML).toBe("");+ expect(container.querySelector('[aria-label="Log out"]')).toBeNull();+ });+});diff --git a/web/src/components/AuthWidget.tsx b/web/src/components/AuthWidget.tsxindex 3a26d23b654..2799bd7ee8b 100644--- a/web/src/components/AuthWidget.tsx+++ b/web/src/components/AuthWidget.tsx@@ -25,14 +25,10 @@import { useEffect, useState } from "react";import { api, type AuthMeResponse } from "@/lib/api";-import { ApiError } from "@/lib/api-error";+import { shouldHideAuthWidget } from "./auth-widget-visibility";import { cn } from "@/lib/utils";import { LogOut } from "lucide-react";-/** Shown when /api/auth/me fails for a reason other than "not gated". */-export const AUTH_STATUS_UNAVAILABLE_MESSAGE =- "Could not check who is signed in. Reload the page; if it persists, sign in again.";-interface AuthWidgetProps {className?: string;}@@ -50,40 +46,36 @@ export function AuthWidget({ className }: AuthWidgetProps) {const [hidden, setHidden] = useState(false);const [error, setError] = useState<string | null>(null);- // Loopback / --insecure mode: the auth gate is off, so /api/auth/me is a- // guaranteed 401. Don't fire the request at all — it only produces console- // noise ("Failed to load resource: 401") on every dashboard load.- const gated =- typeof window !== "undefined" && !!window.__HERMES_AUTH_REQUIRED__;-useEffect(() => {- if (!gated) return;let cancelled = false;api.getAuthMe().then((data) => {if (cancelled) return;+ if (shouldHideAuthWidget(data)) {+ setHidden(true);+ return;+ }setMe(data);}).catch((err: unknown) => {if (cancelled) return;- // 401/403 from /api/auth/me means the gate isn't engaged in this- // process (loopback mode) — render nothing. The global 401 handler- // only redirects on the structured envelope, so a plain 401 from- // /api/auth/me with no envelope bubbles up here as an ApiError.- if (err instanceof ApiError && (err.status === 401 || err.status === 403)) {+ // 401 from /api/auth/me means the gate isn't engaged in this+ // process (loopback mode) — render nothing. fetchJSON throws an+ // Error with the status code as a prefix; the global 401+ // handler only redirects on the structured envelope, so a plain+ // 401 from /api/auth/me with no envelope bubbles up here.+ const msg = err instanceof Error ? err.message : String(err);+ if (msg.startsWith("401:") || msg.startsWith("403:")) {setHidden(true);return;}- setError(AUTH_STATUS_UNAVAILABLE_MESSAGE);+ setError("auth status unavailable");});return () => {cancelled = true;};- }, [gated]);-- // Nothing to show in ungated mode — there is no logged-in identity.- if (!gated) return null;+ }, []);if (hidden) return null;@@ -91,19 +83,11 @@ export function AuthWidget({ className }: AuthWidgetProps) {return (<divclassName={cn(- "flex flex-col gap-1 px-5 py-2 text-[0.65rem] tracking-[0.05em] text-muted-foreground/70",+ "px-5 py-2 text-[0.65rem] tracking-[0.05em] text-muted-foreground/70",className,)}- role="status">- <span>{error}</span>- <button- type="button"- onClick={() => window.location.reload()}- className="self-start underline underline-offset-2 hover:text-foreground"- >- Reload page- </button>+ {error}</div>);}diff --git a/web/src/components/auth-widget-visibility.ts b/web/src/components/auth-widget-visibility.tsnew file mode 100644index 00000000000..8cb2153ef2c--- /dev/null+++ b/web/src/components/auth-widget-visibility.ts@@ -0,0 +1,5 @@+import type { AuthMeResponse } from '@/lib/api'++export function shouldHideAuthWidget(identity: AuthMeResponse): boolean {+ return identity.provider === 'loopback'+}diff --git a/web/src/lib/api.test.ts b/web/src/lib/api.test.tsindex 7ff1ef335dc..abc5efad0d5 100644--- a/web/src/lib/api.test.ts+++ b/web/src/lib/api.test.ts@@ -287,3 +287,24 @@ describe("api OAuth helpers", () => {]);});});++describe("api.getAuthMe loopback contract", () => {+ it("accepts a token-authenticated synthetic loopback identity", async () => {+ vi.stubGlobal("window", { __HERMES_SESSION_TOKEN__: "loopback-token" });+ const identity = {+ display_name: "Local",+ email: "",+ expires_at: 0,+ org_id: "",+ provider: "loopback",+ user_id: "local",+ };+ const fetchMock = jsonFetchMock(identity);+ vi.stubGlobal("fetch", fetchMock);++ await expect(api.getAuthMe()).resolves.toEqual(identity);++ const init = fetchMock.mock.calls[0][1] as RequestInit;+ expect((init.headers as Headers).get(SESSION_HEADER)).toBe("loopback-token");+ });+});diff --git a/web/src/lib/api.ts b/web/src/lib/api.tsindex e8dfe43ced9..1197d315e32 100644--- a/web/src/lib/api.ts+++ b/web/src/lib/api.ts@@ -417,19 +417,14 @@ export const api = {/*** Identity probe for the dashboard auth gate (Phase 7).*- * Returns the verified Session as JSON when gated mode is active and a- * valid cookie is attached. Loopback mode is unaffected — the endpoint- * still exists but is never useful there (no Session, no cookie). The- * AuthWidget component swallows 401s from this call: if the gate isn't- * engaged, /api/auth/me returns 401 and the widget renders nothing.+ * Returns the verified Session when gated mode is active. In loopback mode,+ * a valid injected session token returns a synthetic ``provider=loopback``+ * identity; AuthWidget recognizes that provider and renders nothing, so it+ * never exposes a logout action that would redirect to an unavailable login.*- * ``allowUnauthorized`` is load-bearing: in loopback mode this endpoint- * 401s by design, and fetchJSON's default loopback behaviour treats a- * 401 as a rotated session token and full-page-reloads to pick up a- * fresh one. Because every *other* dashboard request succeeds (and so- * clears the one-shot reload guard), that turns this expected 401 into- * an infinite reload loop. Opting out keeps the 401 a plain throw the- * widget can catch.+ * ``allowUnauthorized`` remains load-bearing for a missing or stale loopback+ * token: keep that 401 local to the widget instead of triggering the global+ * rotated-token reload path.*/getAuthMe: () =>fetchJSON<AuthMeResponse>("/api/auth/me", undefined, {@@ -1458,7 +1453,8 @@ export const api = {/** Identity payload returned by ``GET /api/auth/me`` (Phase 7).** Returned by the dashboard's gated middleware when a valid session cookie- * is attached. ``email`` and ``display_name`` are empty strings under the+ * is attached, or as a synthetic ``provider=loopback`` identity after token+ * validation in local mode. ``email`` and ``display_name`` are empty strings under the* Nous Portal contract V1 (the access token has no email/name claims —* see Contract Anchor C4 in the plan). The AuthWidget surfaces a* truncated ``user_id`` instead.