The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(dashboard): refuse cookie-authenticated writes from another origin
Bear Huddlestond9f1a3f6df5b
diff --git a/hermes_cli/dashboard_auth/middleware.py b/hermes_cli/dashboard_auth/middleware.pyindex 2f360140b2e..662fc017126 100644--- a/hermes_cli/dashboard_auth/middleware.py+++ b/hermes_cli/dashboard_auth/middleware.py@@ -29,8 +29,8 @@ from hermes_cli.dashboard_auth.public_paths import PUBLIC_API_PATHSfrom hermes_cli.dashboard_auth.refresh_singleflight import refresh_session_coalescedfrom hermes_cli.dashboard_auth.request_utils import (access_token_max_age as _expires_in_seconds, client_ip as _client_ip,- extract_bearer as _extract_bearer, is_safe_next_path, scan_session_providers,- unreachable_response)+ cookie_origin_is_allowed, extract_bearer as _extract_bearer, is_safe_next_path,+ scan_session_providers, unreachable_response)_log = logging.getLogger(__name__)@@ -165,8 +165,12 @@ async def gated_auth_middleware(# Already authenticated by the token-auth seam (service caller on a registered token# route): not a cookie session, must not bounce to /login.if (getattr(request.state, "token_authenticated", False)- or getattr(request.state, "native_http_principal", None)- or _path_is_public(request.url.path)):+ or getattr(request.state, "native_http_principal", None)):+ return await call_next(request)+ # Login/callback routes have their own credentials/state checks. Logout+ # is public so an expired session can leave, but still consumes cookies.+ cookie_logout = request.url.path == "/auth/logout"+ if _path_is_public(request.url.path) and not cookie_logout:return await call_next(request)# RFC 8252 native-app bearer path: the same provider-minted access token the cookie flow# stores, verified with the same provider stack, no cookie read or set. A presented-but-@@ -174,6 +178,8 @@ async def gated_auth_middleware(# following a cookie redirect.bearer = _extract_bearer(request)if bearer:+ if cookie_logout:+ return await call_next(request)try:bearer_session = _verify_access_token(request, access_token=bearer, audit=False)except ProviderError as e:@@ -185,6 +191,12 @@ async def gated_auth_middleware(at, _rt = read_session_cookies(request)provider_hint = read_session_provider(request)+ if (at or _rt) and request.method not in {"GET", "HEAD", "OPTIONS", "TRACE"} and not cookie_origin_is_allowed(request):+ return JSONResponse(status_code=403, content={+ "detail": "Cookie-authenticated writes must come from the dashboard's own origin. "+ "Behind a reverse proxy, set dashboard.public_url to the URL the browser uses."})+ if cookie_logout:+ return await call_next(request)if not at and not _rt:# No session at all: try the silent portal bounce before /login.auto = _auto_sso_response(request)diff --git a/hermes_cli/dashboard_auth/request_utils.py b/hermes_cli/dashboard_auth/request_utils.pyindex 102615c6235..353e3e84318 100644--- a/hermes_cli/dashboard_auth/request_utils.py+++ b/hermes_cli/dashboard_auth/request_utils.py@@ -52,6 +52,45 @@ def _http_origin(value: str) -> tuple[str, str, int] | None:return None+def cookie_origin_is_allowed(request: Request) -> bool:+ """Cookie writes must come from the dashboard's own origin, not just its site.++ ``SameSite=Lax`` keeps cross-site pages from sending the session cookies but+ still admits same-site siblings (another port or subdomain). A write without+ Origin passes only in a shape no page can produce (native Desktop's own+ requests), and only after the Host guard. With an Origin, the browser's+ ``Sec-Fetch-Site`` verdict decides when present: pages cannot set it, and the+ browser computes it against the URL it actually addressed, so it stays right+ behind a TLS-terminating or Host-rewriting proxy where this server's view of+ its own URL differs. Only a browser without Fetch Metadata falls back to+ comparing Origin with the OAuth public-URL authority, otherwise the request's+ Host and ASGI scheme (uvicorn applies *trusted* proxy headers). Never trust+ raw forwarded headers here or reuse WS's opaque/non-HTTP Origin exemption.+ """+ from hermes_cli.dashboard_auth.prefix import resolve_public_url+ from hermes_cli.web_server import _is_accepted_host++ bound_host = getattr(request.app.state, "bound_host", None)+ if bound_host and not _is_accepted_host(+ request.headers.get("host", ""), bound_host,+ getattr(request.app.state, "trusted_public_hosts", frozenset()),+ ):+ return False+ origins = request.headers.getlist("origin")+ fetch_sites = request.headers.getlist("sec-fetch-site")+ if not origins:+ # Electron's net.request sends Sec-Fetch-Site: none to https and loopback, and no Fetch+ # Metadata to plain http. Pages attach Origin to every non-GET and keep none for typed GETs.+ return fetch_sites in ([], ["none"])+ origin = _http_origin(origins[0]) if len(origins) == 1 else None+ if origin is None:+ return False+ if fetch_sites:+ return fetch_sites == ["same-origin"]+ target = urlsplit(resolve_public_url() or str(request.url))+ return origin == _http_origin(f"{target.scheme}://{target.netloc}")++def is_safe_next_path(path: str) -> bool:"""Same-origin post-login target: rejects non-relative and protocol-relative (``//evil``)values, the auth routes themselves, and every ``/api`` path."""diff --git a/tests/hermes_cli/test_dashboard_auth_middleware.py b/tests/hermes_cli/test_dashboard_auth_middleware.pyindex 37e06470e10..036f740ec43 100644--- a/tests/hermes_cli/test_dashboard_auth_middleware.py+++ b/tests/hermes_cli/test_dashboard_auth_middleware.py@@ -206,6 +206,7 @@ def test_gated_require_token_endpoint_accepts_cookie_session(gated_app):_complete_stub_login(gated_app)r = gated_app.post("/api/dashboard/agent-plugins/install",+ headers={"Origin": "https://fly-app.fly.dev"},json={"identifier": "definitely not a valid identifier","force": False, "enable": False},)@@ -220,6 +221,38 @@ def test_gated_require_token_endpoint_accepts_cookie_session(gated_app):)+def proxied_gated_app(monkeypatch):+ """Gated all-interfaces bind reached through a TLS-terminating proxy that is not in+ ``trusted_proxies`` and no ``public_url``: the server sees ``http://127.0.0.1:9119`` while+ the browser addresses ``https://dash.example.com``."""+ monkeypatch.delenv("HERMES_DASHBOARD_PUBLIC_URL", raising=False)+ clear_providers()+ register_provider(StubAuthProvider())+ for key, value in (("bound_host", "0.0.0.0"), ("bound_port", 9119), ("auth_required", True),+ ("trusted_public_hosts", frozenset())):+ monkeypatch.setattr(web_server.app.state, key, value, raising=False)+ yield TestClient(web_server.app, base_url="http://127.0.0.1:9119")+ clear_providers()+++def test_cookie_write_trusts_the_browsers_same_origin_verdict_behind_a_proxy(proxied_gated_app):+ """The server's own URL cannot name the browser-facing origin behind such a proxy, so+ the browser's unforgeable ``Sec-Fetch-Site`` decides: the dashboard's own page may write+ with its cookie session, a sibling or foreign page may not."""+ _complete_stub_login(proxied_gated_app)++ own_page = proxied_gated_app.post("/api/auth/ws-ticket", headers={+ "Origin": "https://dash.example.com", "Sec-Fetch-Site": "same-origin"})+ assert own_page.status_code == 200, own_page.text++ for origin, fetch_site in (("https://evil.example", "cross-site"),+ ("https://blog.example.com", "same-site")):+ forged = proxied_gated_app.post("/api/auth/ws-ticket", headers={+ "Origin": origin, "Sec-Fetch-Site": fetch_site})+ assert forged.status_code == 403, (fetch_site, forged.text)++# A representative spread of the OTHER ``_require_token`` endpoints (there are# 14 in total). The install popup was just the reported symptom; the same bug# made API-key reveal, provider validation, the OAuth-provider connect flow,diff --git a/tests/hermes_cli/test_dashboard_auth_native_cookie_writes.py b/tests/hermes_cli/test_dashboard_auth_native_cookie_writes.pynew file mode 100644index 00000000000..ffc10b72dc6--- /dev/null+++ b/tests/hermes_cli/test_dashboard_auth_native_cookie_writes.py@@ -0,0 +1,106 @@+"""Native Desktop's cookie-session writes through the real dashboard auth gate.++Installed Desktop builds reach password-gated gateways (and Cloud agents signed in+through the silent cookie flow) with Electron ``net.request``, which sends the session+cookie but never an Origin. Those writes, ws-ticket mints included, are admitted; a 403+would read to Desktop as an expired session. The header shapes below are what Electron+40.10.2 sends on the wire. A browser page's write always carries Origin, so page-shaped+requests stay refused.+"""+from __future__ import annotations++import pytest+from fastapi.testclient import TestClient++import plugins.dashboard_auth.basic as basic_plugin+from hermes_cli import web_server+from hermes_cli.config import read_raw_config+from hermes_cli.dashboard_auth import clear_providers, register_provider+from hermes_cli.dashboard_auth.cookies import SESSION_AT_COOKIE+from hermes_cli.dashboard_auth.routes import _reset_password_rate_limit++HTTPS_REMOTE = "https://agent.example.com"+PLAIN_HTTP_REMOTE = "http://192.168.50.220:9119"+# Electron net.request with useSessionCookies: Chromium marks secure targets with+# Sec-Fetch-Site none and sends no Fetch Metadata at all to a plain-http remote.+NATIVE_HEADERS = {+ HTTPS_REMOTE: {"Sec-Fetch-Site": "none", "Sec-Fetch-Mode": "no-cors", "Sec-Fetch-Dest": "empty"},+ PLAIN_HTTP_REMOTE: {},+}+CONFIG_WRITE = {"config": {"display": {"skin": "mono"}}}++[email protected](scope="module")+def password_hash():+ return basic_plugin.hash_password("hunter2")+++def password_gate(password_hash, monkeypatch):+ """An all-interfaces gateway gated by the bundled username/password provider."""+ monkeypatch.delenv("HERMES_DASHBOARD_PUBLIC_URL", raising=False)+ for key, value in (("bound_host", "0.0.0.0"), ("bound_port", 9119), ("auth_required", True),+ ("trusted_public_hosts", frozenset())):+ monkeypatch.setattr(web_server.app.state, key, value, raising=False)+ clear_providers()+ register_provider(basic_plugin.BasicAuthProvider(+ username="admin", password_hash=password_hash, secret=b"s" * 32))+ # The login limiter counts successful sign-ins too, and every test signs in once.+ _reset_password_rate_limit()+ yield+ clear_providers()+++def _signed_in(base_url: str) -> TestClient:+ client = TestClient(web_server.app, base_url=base_url)+ login = client.post("/auth/password-login",+ json={"provider": "basic", "username": "admin", "password": "hunter2"})+ assert login.status_code == 200, login.text+ return client++[email protected]("base_url", [HTTPS_REMOTE, PLAIN_HTTP_REMOTE])+def test_native_cookie_session_mints_tickets_writes_config_and_refreshes(password_gate, base_url):+ client = _signed_in(base_url)+ native = NATIVE_HEADERS[base_url]++ ticket = client.post("/api/auth/ws-ticket", headers=native)+ assert ticket.status_code == 200, ticket.text+ assert ticket.json()["ticket"]++ saved = client.put("/api/config", headers=native, json=CONFIG_WRITE)+ assert saved.status_code == 200, saved.text+ assert read_raw_config()["display"]["skin"] == "mono"++ # The access cookie lapses first; the next write must rotate the session, not 403.+ for cookie in list(client.cookies.jar):+ if cookie.name.endswith(SESSION_AT_COOKIE):+ client.cookies.delete(cookie.name, domain=cookie.domain, path=cookie.path)+ refreshed = client.post("/api/auth/ws-ticket", headers=native)+ assert refreshed.status_code == 200, refreshed.text+ assert any(name.endswith(SESSION_AT_COOKIE) for name in client.cookies)++[email protected]("base_url,headers", [+ pytest.param(HTTPS_REMOTE, {"Origin": "https://evil.example", "Sec-Fetch-Site": "none"},+ id="none-with-foreign-origin"),+ pytest.param(HTTPS_REMOTE, {"Origin": "https://blog.example.com", "Sec-Fetch-Site": "same-site"},+ id="same-site-sibling"),+ pytest.param(HTTPS_REMOTE, {"Origin": "https://evil.example", "Sec-Fetch-Site": "cross-site"},+ id="cross-site"),+ pytest.param(HTTPS_REMOTE, {"Origin": "null", "Sec-Fetch-Site": "same-site"},+ id="no-referrer-sibling-form"),+ pytest.param(HTTPS_REMOTE, {"Sec-Fetch-Site": "same-site"}, id="same-site-without-origin"),+ pytest.param(HTTPS_REMOTE, {"Sec-Fetch-Site": "cross-site"}, id="cross-site-without-origin"),+ pytest.param(PLAIN_HTTP_REMOTE, {"Origin": "http://192.168.50.220:8080"}, id="http-sibling-port"),+ pytest.param(PLAIN_HTTP_REMOTE, {"Origin": "null"}, id="http-no-referrer-form"),+])+def test_page_shaped_cookie_writes_stay_refused(password_gate, base_url, headers):+ client = _signed_in(base_url)++ ticket = client.post("/api/auth/ws-ticket", headers=headers)+ assert ticket.status_code == 403, ticket.text++ saved = client.put("/api/config", headers=headers, json=CONFIG_WRITE)+ assert saved.status_code == 403, saved.text+ assert read_raw_config().get("display", {}).get("skin") != "mono"diff --git a/tests/hermes_cli/test_dashboard_auth_ws_auth.py b/tests/hermes_cli/test_dashboard_auth_ws_auth.pyindex 0bd599eebe9..b0577d7baed 100644--- a/tests/hermes_cli/test_dashboard_auth_ws_auth.py+++ b/tests/hermes_cli/test_dashboard_auth_ws_auth.py@@ -115,7 +115,7 @@ def _logged_in(client: TestClient) -> None:class TestWsTicketEndpoint:def test_authenticated_session_can_mint(self, gated_app):_logged_in(gated_app)- r = gated_app.post("/api/auth/ws-ticket")+ r = gated_app.post("/api/auth/ws-ticket", headers={"Origin": "https://fly-app.fly.dev"})assert r.status_code == 200body = r.json()assert "ticket" in bodydiff --git a/tests/hermes_cli/test_webapp_upload_limit.py b/tests/hermes_cli/test_webapp_upload_limit.pyindex bc5ce126906..999b3ab63e3 100644--- a/tests/hermes_cli/test_webapp_upload_limit.py+++ b/tests/hermes_cli/test_webapp_upload_limit.py@@ -1,7 +1,6 @@"""Real ASGI regressions for the Webapp's pre-parser upload limit (``hermes_cli/web_upload_limit.py``).-The upload-limit half of #93508's ``test_webapp_upload_security.py``; its cookie Origin gate cases stay-with that separate change.+The cookie Origin gate on the same uploads is covered in ``test_webapp_upload_security.py``."""from __future__ import annotationsdiff --git a/tests/hermes_cli/test_webapp_upload_security.py b/tests/hermes_cli/test_webapp_upload_security.pynew file mode 100644index 00000000000..0d29030bc79--- /dev/null+++ b/tests/hermes_cli/test_webapp_upload_security.py@@ -0,0 +1,230 @@+"""Real ASGI checks of the dashboard's same-origin gate for cookie-authenticated writes.++The pre-parser upload limit on the same routes is covered in ``test_webapp_upload_limit.py``.+"""++from __future__ import annotations++import asyncio+from pathlib import Path++import httpx+import pytest+from starlette import formparsers++from hermes_cli import web_server+from hermes_cli.dashboard_auth import clear_providers, register_provider+from hermes_cli.dashboard_auth.cookies import SESSION_AT_COOKIE, SESSION_RT_COOKIE+from tests.hermes_cli.conftest_dashboard_auth import StubAuthProvider+++def upload_app(tmp_path, monkeypatch):+ home = tmp_path / "hermes-home"+ home.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(home))+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ monkeypatch.setattr(web_server.app.state, "auth_required", True, raising=False)+ monkeypatch.setattr(web_server.app.state, "bound_host", "0.0.0.0", raising=False)+ monkeypatch.setattr(web_server.app.state, "trusted_public_hosts", frozenset(), raising=False)+ clear_providers()+ register_provider(StubAuthProvider())+ # Observe the actual parser's open files, retaining references so GC cannot+ # disguise a missing close. No parser or upload implementation is mocked.+ spools = []+ real_spool = formparsers.SpooledTemporaryFile++ def track_spool(*args, **kwargs):+ spool = real_spool(*args, dir=tmp_path, **kwargs)+ spools.append(spool)+ return spool++ monkeypatch.setattr(formparsers, "SpooledTemporaryFile", track_spool)+ yield home, spools+ for spool in spools:+ spool.close()+ clear_providers()+++async def _login(client):+ response = await client.get("/auth/login?provider=stub", follow_redirects=True)+ assert response.status_code != 401+ return next(v for k, v in client.cookies.items() if k.endswith(SESSION_AT_COOKIE))+++ "headers",+ [+ # No Origin, but Fetch Metadata names an initiating page: not a native client.+ {"Sec-Fetch-Site": "same-site"},+ {"Sec-Fetch-Site": "cross-site"},+ *(+ {"Origin": origin}+ for origin in (+ "null",+ "https://evil.example.com",+ "http://dashboard.example.com",+ "https://dashboard.example.com:8443",+ "file://",+ "https://dashboard.example.com/path",+ "https://dashboard.example.com:bad",+ "https://dashboard.example.com, https://evil.example.com",+ )+ ),+ ],+)+def test_cookie_upload_requires_exact_http_origin(upload_app, headers):+ home, spools = upload_app++ async def run():+ async with httpx.AsyncClient(+ transport=httpx.ASGITransport(app=web_server.app), base_url="https://dashboard.example.com"+ ) as client:+ await _login(client)+ response = await client.post(+ "/api/chat/file-upload",+ files={"file": ("csrf.txt", b"unwanted")},+ headers=headers,+ )+ assert response.status_code == 403, response.text+ assert not (home / "uploads").exists()+ assert not spools # Refused before FastAPI opens a spool.++ asyncio.run(run())+++def test_cookie_same_origin_refresh_and_bearer_uploads_work(upload_app):+ home, spools = upload_app++ async def run():+ async with httpx.AsyncClient(+ transport=httpx.ASGITransport(app=web_server.app), base_url="https://dashboard.example.com"+ ) as client:+ token = await _login(client)+ for headers in (+ {"Origin": "https://dashboard.example.com:443"},+ {"Authorization": f"Bearer {token}"},+ {"Authorization": f"Bearer {token}", "Origin": "null"},+ ):+ response = await client.post(+ "/api/chat/file-upload", files={"file": ("ok.txt", b"allowed")}, headers=headers+ )+ assert response.status_code == 200, response.text+ assert Path(response.json()["path"]).read_bytes() == b"allowed"+ # Refresh-only cookies must face the same Origin check before rotating.+ for cookie in list(client.cookies.jar):+ if cookie.name.endswith(SESSION_AT_COOKIE):+ client.cookies.delete(cookie.name, domain=cookie.domain, path=cookie.path)+ assert any(k.endswith(SESSION_RT_COOKIE) for k in client.cookies)+ response = await client.post(+ "/api/chat/file-upload",+ files={"file": ("bad.txt", b"bad")},+ headers={"Origin": "https://dashboard.example.com:8443", "Sec-Fetch-Site": "same-site"},+ )+ assert response.status_code == 403+ response = await client.post(+ "/api/chat/file-upload",+ files={"file": ("refresh.txt", b"allowed")},+ headers={"Origin": "https://dashboard.example.com"},+ )+ assert response.status_code == 200, response.text+ assert len(list((home / "uploads").iterdir())) == 4+ assert all(s.closed for s in spools)++ asyncio.run(run())+++def test_cookie_unsafe_methods_and_logout_but_not_auth_bootstrap(upload_app):+ async def run():+ async with httpx.AsyncClient(+ transport=httpx.ASGITransport(app=web_server.app), base_url="https://dashboard.example.com"+ ) as client:+ await _login(client)+ for method in ("POST", "PUT", "PATCH", "DELETE"):+ response = await client.request(+ method, "/api/auth/me", headers={"Origin": "https://evil.example.com"}+ )+ assert response.status_code == 403+ response = await client.request(+ method, "/api/auth/me", headers={"Origin": "https://dashboard.example.com"}+ )+ assert response.status_code == 405 # Authorized; method isn't routed.+ response = await client.get("/api/auth/me")+ assert response.status_code == 200+ for path, expected in (("/auth/callback", 405), ("/auth/password-login", 422)):+ response = await client.post(path, headers={"Origin": "null"})+ assert response.status_code == expected # Bootstrap, not CSRF.+ response = await client.post(+ "/api/auth/ws-ticket",+ headers=[("Origin", "https://dashboard.example.com"), ("Origin", "https://evil.example.com")],+ )+ assert response.status_code == 403+ response = await client.post(+ "/auth/logout", headers={"Origin": "null", "Sec-Fetch-Site": "same-site"}+ )+ assert response.status_code == 403+ response = await client.post("/auth/logout", headers={"Origin": "https://dashboard.example.com"})+ assert response.status_code == 302+ assert (await client.get("/api/auth/me")).status_code == 401+ # Logout stays public, including for a stale native bearer.+ response = await client.post("/auth/logout", headers={"Authorization": "Bearer expired"})+ assert response.status_code == 302++ asyncio.run(run())++[email protected]("public_url", [False, True])+def test_cookie_upload_accepts_trusted_proxy_origin_only(upload_app, monkeypatch, public_url):+ from uvicorn.middleware.proxy_headers import ProxyHeadersMiddleware++ home, _ = upload_app+ monkeypatch.setattr(web_server.app.state, "bound_host", "127.0.0.1")+ monkeypatch.setattr(web_server.app.state, "trusted_public_hosts", frozenset({"dashboard.example.com"}))++ async def run():+ app = ProxyHeadersMiddleware(web_server.app, trusted_hosts=["127.0.0.1"])+ async with httpx.AsyncClient(+ transport=httpx.ASGITransport(app=app), base_url="https://dashboard.example.com:8443"+ ) as client:+ await _login(client)+ if public_url:+ (home / "config.yaml").write_text(+ "dashboard:\n public_url: https://dashboard.example.com:8443/hermes\n"+ )+ host = "127.0.0.1:9119" if public_url else "dashboard.example.com:8443"+ headers = {"X-Forwarded-Prefix": "/hermes", "Host": host, "X-Forwarded-Proto": "https"}+ for origin, expected in (+ ("https://dashboard.example.com:8443", 200),+ ("https://dashboard.example.com", 403),+ ("http://dashboard.example.com:8443", 403),+ ("https://evil.example.com:8443", 403),+ ):+ response = await client.post(+ "http://dashboard.example.com:8443/api/chat/file-upload",+ files={"file": ("proxy.txt", b"proxy")},+ headers={+ **headers,+ "Origin": origin,+ "Cookie": "; ".join(f"{k}={v}" for k, v in client.cookies.items()),+ },+ )+ assert response.status_code == expected, response.text+ # Raw forwarded headers are not an authority declaration. Untrusted+ # peers cannot upgrade the ASGI scheme or invent an accepted host.+ if not public_url:+ async with httpx.AsyncClient(+ transport=httpx.ASGITransport(app=app, client=("192.0.2.10", 1234)),+ base_url="http://dashboard.example.com:8443",+ ) as untrusted:+ response = await untrusted.post(+ "/api/chat/file-upload",+ files={"file": ("bad.txt", b"bad")},+ headers={+ **headers,+ "Origin": "https://dashboard.example.com:8443",+ "Cookie": "; ".join(f"{k}={v}" for k, v in client.cookies.items()),+ },+ )+ assert response.status_code == 403++ asyncio.run(run())