The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(dashboard): a gated dashboard behind a proxy takes its own page's cookie writes as on main
emozilla22103f58a86b
diff --git a/hermes_cli/dashboard_auth/middleware.py b/hermes_cli/dashboard_auth/middleware.pyindex e45c9865f4a..de66b031cc5 100644--- a/hermes_cli/dashboard_auth/middleware.py+++ b/hermes_cli/dashboard_auth/middleware.py@@ -6,7 +6,8 @@ the auth-bootstrap routes and static assets through unauthenticated; foreverything else demands a bearer token or a valid session cookie and attachesthe verified :class:`Session` to ``request.state.session``. On the gateway'sWebapp a cookie session also needs its sign-in binding to the browser credential-(``hermes_cli.webapp_sign_in``). HTML routes are+(``hermes_cli.webapp_sign_in``), and its cookie writes, sign-out included, must come+from the Webapp's own origin. HTML routes areredirected to ``/login``; ``/api/*`` routes get a 401 JSON envelope."""from __future__ import annotations@@ -72,14 +73,16 @@ def _safe_next_target(request: Request) -> str:return quote(f"{path}?{query}" if query else path, safe="")-def _cross_origin_write_detail(state: object) -> str:- """The 403 detail for a cookie write from another origin, naming the public URL setting the- listener reads: ``webapp.public_url`` on the gateway's Webapp, ``dashboard.public_url`` elsewhere."""- if getattr(state, "ui_surface", None) == "webapp":- return ("Cookie-authenticated writes must come from the Webapp's own origin. "- "Behind a reverse proxy, set webapp.public_url to the URL the browser uses.")- return ("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.")+#: The 403 detail for a cookie write from another origin; only the gateway's Webapp checks+#: (``SurfacePolicy.own_origin_cookie_writes``), so it names the public URL that listener reads.+_CROSS_ORIGIN_WRITE_DETAIL = ("Cookie-authenticated writes must come from the Webapp's own origin. "+ "Behind a reverse proxy, set webapp.public_url to the URL the browser uses.")+_SAFE_METHODS = frozenset({"GET", "HEAD", "OPTIONS", "TRACE"})+++def _own_origin_writes(request: Request) -> bool:+ from hermes_cli.web_server_surface import policy+ return policy(request.app.state).own_origin_cookie_writesdef _unauth_response(request: Request, *, reason: str) -> Response:@@ -184,9 +187,11 @@ async def gated_auth_middleware(if (getattr(request.state, "token_authenticated", False)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"+ # Login/callback routes have their own credentials/state checks. Logout is public so an+ # expired session can leave; where cookie writes must come from the listener's own origin it+ # still consumes cookies, so it goes through that check.+ own_origin = _own_origin_writes(request)+ cookie_logout = own_origin and 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@@ -212,8 +217,9 @@ async def gated_auth_middleware(gateway = webapp_sign_in.cookie_gateway(request)at, _rt = read_session_cookies(request, gateway)provider_hint = read_session_provider(request, gateway)- 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": _cross_origin_write_detail(request.app.state)})+ if (own_origin and (at or _rt) and request.method not in _SAFE_METHODS+ and not cookie_origin_is_allowed(request)):+ return JSONResponse(status_code=403, content={"detail": _CROSS_ORIGIN_WRITE_DETAIL})if cookie_logout:return await call_next(request)if not at and not _rt:diff --git a/hermes_cli/dashboard_auth/request_utils.py b/hermes_cli/dashboard_auth/request_utils.pyindex df21f01784b..69d4bf6c5e2 100644--- a/hermes_cli/dashboard_auth/request_utils.py+++ b/hermes_cli/dashboard_auth/request_utils.py@@ -53,7 +53,9 @@ def _http_origin(value: str) -> tuple[str, str, int] | None:def cookie_origin_is_allowed(request: Request) -> bool:- """Cookie writes must come from the dashboard's own origin, not just its site.+ """Cookie writes must come from the listener's own origin, not just its site. The gate asks+ only where the surface policy says so (``SurfacePolicy.own_origin_cookie_writes``: the+ gateway's Webapp); the standalone dashboard keeps main's rule.``SameSite=Lax`` keeps cross-site pages from sending the session cookies butstill admits same-site siblings (another port or subdomain). A write withoutdiff --git a/hermes_cli/web_server_surface.py b/hermes_cli/web_server_surface.pyindex 740d4bd29fd..688a69e37dc 100644--- a/hermes_cli/web_server_surface.py+++ b/hermes_cli/web_server_surface.py@@ -26,15 +26,21 @@ class SurfacePolicy:#: ``/api/webapp/socket-ticket`` mints the browser's one-use tickets for ``/api/ws`` and the voice#: streams on this same origin (accepted by the loopback and gated upgrade gates alike).gateway_ticket: bool+ #: Behind the sign-in gate, a write that carries the session cookie (``/auth/logout`` included)+ #: must come from this listener's own origin. Elsewhere the gate keeps main's rule.+ own_origin_cookie_writes: boolPOLICIES: dict[str, SurfacePolicy] = {"serve": SurfacePolicy(- serves_spa=False, html_token=True, host_terminal=False, launch_link=False, gateway_ticket=False),+ serves_spa=False, html_token=True, host_terminal=False, launch_link=False, gateway_ticket=False,+ own_origin_cookie_writes=False),"dashboard": SurfacePolicy(- serves_spa=True, html_token=True, host_terminal=False, launch_link=False, gateway_ticket=False),+ serves_spa=True, html_token=True, host_terminal=False, launch_link=False, gateway_ticket=False,+ own_origin_cookie_writes=False),"webapp": SurfacePolicy(- serves_spa=True, html_token=False, host_terminal=True, launch_link=True, gateway_ticket=True),+ serves_spa=True, html_token=False, host_terminal=True, launch_link=True, gateway_ticket=True,+ own_origin_cookie_writes=True),}diff --git a/tests/gateway/test_webapp_public_url.py b/tests/gateway/test_webapp_public_url.pyindex d942f0905dc..a13323a0437 100644--- a/tests/gateway/test_webapp_public_url.py+++ b/tests/gateway/test_webapp_public_url.py@@ -158,13 +158,3 @@ def test_a_webapp_public_url_without_sign_in_leaves_native_clients_a_listener(tmassert "webapp.public_url" in report["status"]["reason"]assert "dashboard.public_url" not in report["status"]["reason"]--def test_a_refused_cookie_write_names_the_setting_its_surface_reads():- # Behind a reverse proxy the fix is the public URL that listener reads: webapp.public_url on the- # gateway's Webapp, dashboard.public_url on the standalone dashboard.- from hermes_cli.dashboard_auth.middleware import _cross_origin_write_detail-- webapp = _cross_origin_write_detail(SimpleNamespace(ui_surface="webapp"))- dashboard = _cross_origin_write_detail(SimpleNamespace())- assert "webapp.public_url" in webapp and "dashboard.public_url" not in webapp- assert "dashboard.public_url" in dashboarddiff --git a/tests/hermes_cli/test_dashboard_auth_middleware.py b/tests/hermes_cli/test_dashboard_auth_middleware.pyindex 036f740ec43..5ee3bf50748 100644--- a/tests/hermes_cli/test_dashboard_auth_middleware.py+++ b/tests/hermes_cli/test_dashboard_auth_middleware.py@@ -221,36 +221,84 @@ 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``."""+def _proxied_gate(monkeypatch, surface: str | None) -> TestClient:+ """Gated all-interfaces bind reached through a proxy that is not in ``trusted_proxies``, with+ no ``public_url``: the server sees ``http://127.0.0.1:9119`` whatever URL the browser addressed.+ *surface* is the app's ``ui_surface`` (``None``: the standalone dashboard, as on main)."""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")+ for key in ("ui_surface", "listener_public_url", "webapp_home"):+ if hasattr(web_server.app.state, key):+ monkeypatch.delattr(web_server.app.state, key)+ if surface is not None:+ monkeypatch.setattr(web_server.app.state, "ui_surface", surface, raising=False)+ monkeypatch.setattr(web_server.app.state, "listener_public_url", "", raising=False)+ return TestClient(web_server.app, base_url="http://127.0.0.1:9119")+++def proxied_gated_webapp(monkeypatch):+ """The gateway's Webapp behind the sign-in gate, reached through such a proxy."""+ yield _proxied_gate(monkeypatch, "webapp")+ clear_providers()+++def proxied_gated_dashboard(monkeypatch):+ """The standalone ``hermes dashboard`` behind the sign-in gate, reached through such a proxy."""+ yield _proxied_gate(monkeypatch, None)clear_providers()-def test_cookie_write_trusts_the_browsers_same_origin_verdict_behind_a_proxy(proxied_gated_app):+def test_webapp_cookie_write_trusts_the_browsers_same_origin_verdict_behind_a_proxy(+ proxied_gated_webapp):"""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+ the browser's unforgeable ``Sec-Fetch-Site`` decides: the Webapp's own page may writewith its cookie session, a sibling or foreign page may not."""- _complete_stub_login(proxied_gated_app)+ _complete_stub_login(proxied_gated_webapp)- own_page = proxied_gated_app.post("/api/auth/ws-ticket", headers={+ own_page = proxied_gated_webapp.post("/api/auth/ws-ticket", headers={"Origin": "https://dash.example.com", "Sec-Fetch-Site": "same-origin"})assert own_page.status_code == 200, own_page.textfor 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={+ forged = proxied_gated_webapp.post("/api/auth/ws-ticket", headers={"Origin": origin, "Sec-Fetch-Site": fetch_site})assert forged.status_code == 403, (fetch_site, forged.text)+ # Behind a reverse proxy the fix is the public URL the Webapp's listener reads.+ assert "webapp.public_url" in forged.text and "dashboard.public_url" not in forged.text+++def test_webapp_sign_out_from_another_origin_is_refused(proxied_gated_webapp):+ """On the Webapp a cookie sign-out is a cookie write like any other: a sibling page cannot+ sign the browser out."""+ _complete_stub_login(proxied_gated_webapp)++ out = proxied_gated_webapp.post("/auth/logout", headers={+ "Origin": "https://blog.example.com", "Sec-Fetch-Site": "same-site"}, follow_redirects=False)++ assert out.status_code == 403, out.text+++def test_dashboard_page_writes_behind_a_host_rewriting_http_proxy_are_admitted_as_on_main(+ proxied_gated_dashboard):+ """With the Webapp off, the gated ``hermes dashboard`` keeps main's rule for cookie writes: the+ origin check belongs to the Webapp's listener. Behind a plain-HTTP proxy that forwards with the+ upstream's Host and no ``dashboard.public_url``, the browser sends no Fetch Metadata and only+ ``Origin: http://dash.lan``; the dashboard's own page still writes and signs out."""+ _complete_stub_login(proxied_gated_dashboard)++ write = proxied_gated_dashboard.post("/api/auth/ws-ticket", headers={"Origin": "http://dash.lan"})+ assert write.status_code == 200, write.text++ out = proxied_gated_dashboard.post("/auth/logout", headers={"Origin": "http://dash.lan"},+ follow_redirects=False)+ assert out.status_code == 302, out.text# A representative spread of the OTHER ``_require_token`` endpoints (there arediff --git a/tests/hermes_cli/test_dashboard_auth_native_cookie_writes.py b/tests/hermes_cli/test_dashboard_auth_native_cookie_writes.pyindex ffc10b72dc6..631c620b340 100644--- a/tests/hermes_cli/test_dashboard_auth_native_cookie_writes.py+++ b/tests/hermes_cli/test_dashboard_auth_native_cookie_writes.py@@ -2,10 +2,11 @@Installed Desktop builds reach password-gated gateways (and Cloud agents signed inthrough 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.+cookie but never an Origin. Those writes, ws-ticket mints included, are admitted on every+surface; a 403 would read to Desktop as an expired session. The header shapes below are what+Electron 40.10.2 sends on the wire. On the gateway's Webapp a browser page's write always+carries Origin, so page-shaped requests from another origin stay refused there (the standalone+dashboard keeps main's rule, pinned in ``test_dashboard_auth_middleware``)."""from __future__ import annotations@@ -35,13 +36,20 @@ 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."""[email protected](params=["dashboard", "webapp"])+def password_gate(request, password_hash, monkeypatch):+ """An all-interfaces listener gated by the bundled username/password provider: the standalone+ dashboard, or the gateway's Webapp (``ui_surface``), as the test's parameter says."""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)+ for key in ("ui_surface", "listener_public_url", "webapp_home"):+ if hasattr(web_server.app.state, key):+ monkeypatch.delattr(web_server.app.state, key)+ if request.param == "webapp":+ monkeypatch.setattr(web_server.app.state, "ui_surface", "webapp", raising=False)+ monkeypatch.setattr(web_server.app.state, "listener_public_url", "", raising=False)clear_providers()register_provider(basic_plugin.BasicAuthProvider(username="admin", password_hash=password_hash, secret=b"s" * 32))@@ -95,7 +103,8 @@ def test_native_cookie_session_mints_tickets_writes_config_and_refreshes(passworpytest.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):[email protected]("password_gate", ["webapp"], indirect=True)+def test_page_shaped_cookie_writes_stay_refused_on_the_webapp(password_gate, base_url, headers):client = _signed_in(base_url)ticket = client.post("/api/auth/ws-ticket", headers=headers)diff --git a/tests/hermes_cli/test_webapp_upload_security.py b/tests/hermes_cli/test_webapp_upload_security.pyindex 0d29030bc79..583afed4fd9 100644--- a/tests/hermes_cli/test_webapp_upload_security.py+++ b/tests/hermes_cli/test_webapp_upload_security.py@@ -1,6 +1,9 @@-"""Real ASGI checks of the dashboard's same-origin gate for cookie-authenticated writes.+"""Real ASGI checks of the Webapp'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``.+Behind the sign-in gate, the gateway's Webapp (``ui_surface == "webapp"``) refuses a write that+carries the session cookie unless it comes from the Webapp's own origin; the standalone dashboard+keeps main's rule (``test_dashboard_auth_middleware``). The pre-parser upload limit on the same+routes is covered in ``test_webapp_upload_limit.py``."""from __future__ import annotations@@ -27,6 +30,10 @@ def upload_app(tmp_path, monkeypatch):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)+ monkeypatch.setattr(web_server.app.state, "ui_surface", "webapp", raising=False)+ monkeypatch.setattr(web_server.app.state, "listener_public_url", "", raising=False)+ if hasattr(web_server.app.state, "webapp_home"):+ monkeypatch.delattr(web_server.app.state, "webapp_home")clear_providers()register_provider(StubAuthProvider())# Observe the actual parser's open files, retaining references so GC cannot@@ -93,18 +100,20 @@ def test_cookie_upload_requires_exact_http_origin(upload_app, headers):asyncio.run(run())-def test_cookie_same_origin_refresh_and_bearer_uploads_work(upload_app):+def test_cookie_same_origin_and_refresh_uploads_work(upload_app):+ """The Webapp's own page uploads with its cookie session, before and after a refresh. (A bearer+ token skips the origin check; on the Webapp only a native app's own sign-in has one that works,+ covered in ``tests/gateway/test_webapp_cookie_writes.py``.)"""home, spools = upload_appasync 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)+ await _login(client)for headers in ({"Origin": "https://dashboard.example.com:443"},- {"Authorization": f"Bearer {token}"},- {"Authorization": f"Bearer {token}", "Origin": "null"},+ {"Origin": "https://dashboard.example.com", "Sec-Fetch-Site": "same-origin"},):response = await client.post("/api/chat/file-upload", files={"file": ("ok.txt", b"allowed")}, headers=headers@@ -128,7 +137,7 @@ def test_cookie_same_origin_refresh_and_bearer_uploads_work(upload_app):headers={"Origin": "https://dashboard.example.com"},)assert response.status_code == 200, response.text- assert len(list((home / "uploads").iterdir())) == 4+ assert len(list((home / "uploads").iterdir())) == 3assert all(s.closed for s in spools)asyncio.run(run())@@ -177,7 +186,6 @@ def test_cookie_unsafe_methods_and_logout_but_not_auth_bootstrap(upload_app):def test_cookie_upload_accepts_trusted_proxy_origin_only(upload_app, monkeypatch, public_url):from uvicorn.middleware.proxy_headers import ProxyHeadersMiddleware- home, _ = upload_appmonkeypatch.setattr(web_server.app.state, "bound_host", "127.0.0.1")monkeypatch.setattr(web_server.app.state, "trusted_public_hosts", frozenset({"dashboard.example.com"}))@@ -188,9 +196,8 @@ def test_cookie_upload_accepts_trusted_proxy_origin_only(upload_app, monkeypatch) as client:await _login(client)if public_url:- (home / "config.yaml").write_text(- "dashboard:\n public_url: https://dashboard.example.com:8443/hermes\n"- )+ monkeypatch.setattr(web_server.app.state, "listener_public_url",+ "https://dashboard.example.com:8443/hermes")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 (