The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(dashboard): reject malformed URL authorities
itsflownium8a0dfcf29fda
diff --git a/hermes_cli/web_routers/config_env.py b/hermes_cli/web_routers/config_env.pyindex a706952b110..09f5946854e 100644--- a/hermes_cli/web_routers/config_env.py+++ b/hermes_cli/web_routers/config_env.py@@ -579,7 +579,10 @@ def _write_custom_endpoint(cfg: Dict[str, Any], body: CustomEndpointUpdate) -> Traise HTTPException(status_code=400, detail="name required")if not base_url:raise HTTPException(status_code=400, detail="base_url required")- parsed = urllib.parse.urlparse(base_url)+ try:+ parsed = urllib.parse.urlparse(base_url)+ except ValueError as exc:+ raise HTTPException(status_code=400, detail="base_url must include scheme and host") from excif not parsed.scheme or not parsed.netloc:raise HTTPException(status_code=400, detail="base_url must include scheme and host")if not model:diff --git a/hermes_cli/web_routers/files.py b/hermes_cli/web_routers/files.pyindex 4dce3878ca4..09373e4c8b6 100644--- a/hermes_cli/web_routers/files.py+++ b/hermes_cli/web_routers/files.py@@ -376,7 +376,10 @@ async def proxy_remote_media(url: str, request: Request):(#74564), returning the same ``data_url`` shape as ``/api/media``. Onlyallowlisted image CDNs; the bytes stay behind the size cap."""_require_token(request)- parsed = urllib.parse.urlparse((url or "").strip())+ try:+ parsed = urllib.parse.urlparse((url or "").strip())+ except ValueError as exc:+ raise HTTPException(status_code=400, detail="A remote image URL is required") from excif parsed.scheme not in ("http", "https") or not parsed.hostname:raise HTTPException(status_code=400, detail="A remote image URL is required")if not _media_proxy_host_allowed(parsed.hostname):diff --git a/hermes_cli/web_server_chat.py b/hermes_cli/web_server_chat.pyindex 0ced511bca4..fba2869b750 100644--- a/hermes_cli/web_server_chat.py+++ b/hermes_cli/web_server_chat.py@@ -183,7 +183,10 @@ def _ws_host_origin_reason(ws: "WebSocket") -> Optional[str]:origin = ws.headers.get("origin", "")if not origin:return None- parsed = urllib.parse.urlparse(origin)+ try:+ parsed = urllib.parse.urlparse(origin)+ except ValueError:+ return f"origin_mismatch origin={origin} bound={bound_host}"if parsed.scheme not in {"http", "https"}:return Noneif not parsed.netloc or not _is_accepted_host(parsed.netloc, bound_host, trusted_public_hosts):diff --git a/tests/hermes_cli/test_web_server.py b/tests/hermes_cli/test_web_server.pyindex c568fa8f3b9..c89327df6fd 100644--- a/tests/hermes_cli/test_web_server.py+++ b/tests/hermes_cli/test_web_server.py@@ -1194,15 +1194,18 @@ CONFIG_SCHEMA = ProviderConfigSchema(assert resp.status_code == 401def test_media_proxy_rejects_disallowed_hosts_and_schemes(self):- for bad in (- "https://evil.example.com/img.png",- "https://sub.fal.media.evil.com/img.png",- "file:///etc/passwd",- "not a url",- "",+ for bad, expected_status in (+ ("https://evil.example.com/img.png", 403),+ ("https://sub.fal.media.evil.com/img.png", 403),+ ("file:///etc/passwd", 400),+ ("not a url", 400),+ ("", 400),+ ("https://[::1/img.png", 400),+ ("https://[::1].evil.test:80/img.png", 400),+ ("https://[not-an-ip]:80/img.png", 400),):resp = self.client.get("/api/media/proxy", params={"url": bad})- assert resp.status_code in (400, 403), (bad, resp.status_code)+ assert resp.status_code == expected_status, (bad, resp.status_code)def test_media_proxy_fetches_allowlisted_image_and_returns_data_url(self, monkeypatch):png_bytes = b"\x89PNG\r\n\x1a\n" + b"0" * 8@@ -2056,6 +2059,28 @@ CONFIG_SCHEMA = ProviderConfigSchema(assert not any(e["id"] == "worker-proxy" for e in default_list["endpoints"])+ def test_custom_endpoint_rejects_malformed_url_without_changing_saved_state(self):+ from hermes_cli.config import get_config_path, get_env_path++ assert self.client.post("/api/providers/custom-endpoints", json={+ "id": "proxy", "name": "Proxy", "base_url": "https://llm.example.com/v1",+ "model": "m", "api_key": "sk-original-fixture", "make_default": True,+ }).status_code == 200+ saved = {path: path.read_bytes() for path in (get_config_path(), get_env_path())}++ for base_url in (+ "https://[::1/v1",+ "https://[::1].evil.test:80/v1",+ "https://[not-an-ip]:80/v1",+ ):+ response = self.client.post("/api/providers/custom-endpoints", json={+ "id": "proxy", "name": "Changed Proxy", "base_url": base_url,+ "model": "replacement", "api_key": "sk-replacement-fixture", "make_default": True,+ })+ assert response.status_code == 400, (base_url, response.text)+ for path, data in saved.items():+ assert path.read_bytes() == data+def test_custom_endpoint_save_keeps_the_api_key_out_of_config(self):"""The key belongs in .env behind key_env, never in config.yaml (#69449)."""from hermes_cli.config import custom_endpoint_key_env, get_env_value, load_configdiff --git a/tests/hermes_cli/test_web_server_ws_origin.py b/tests/hermes_cli/test_web_server_ws_origin.pynew file mode 100644index 00000000000..52db8d45fb4--- /dev/null+++ b/tests/hermes_cli/test_web_server_ws_origin.py@@ -0,0 +1,111 @@+"""Authenticated gateway upgrades reject malformed and cross-site web origins."""++from urllib.parse import parse_qs, urlparse++import pytest+from fastapi.testclient import TestClient+from starlette.websockets import WebSocketDisconnect++from hermes_cli import web_server+from hermes_cli.dashboard_auth import clear_providers, register_provider+from hermes_cli.dashboard_auth.ws_tickets import _reset_for_tests+from tests.hermes_cli.conftest_dashboard_auth import StubAuthProvider+++def remote_dashboard(monkeypatch):+ monkeypatch.setattr(web_server.app.state, "bound_host", "100.64.0.10", raising=False)+ monkeypatch.setattr(web_server.app.state, "bound_port", 9119, raising=False)+ monkeypatch.setattr(web_server.app.state, "auth_required", True, raising=False)+ monkeypatch.setattr(web_server.app.state, "trusted_public_hosts", frozenset(), raising=False)+ monkeypatch.setattr(web_server, "_DASHBOARD_EMBEDDED_CHAT_ENABLED", True)+ clear_providers()+ _reset_for_tests()+ register_provider(StubAuthProvider())+ client = TestClient(web_server.app, base_url="http://100.64.0.10:9119")+ # TestClient's relative WS URLs use testserver rather than its HTTP base_url.+ client.headers["Host"] = "100.64.0.10:9119"+ try:+ login = client.get("/auth/login?provider=stub", follow_redirects=False)+ assert login.status_code == 302+ state = parse_qs(urlparse(login.headers["location"]).query)["state"][0]+ callback = client.get(+ "/auth/callback", params={"code": "stub_code", "state": state}, follow_redirects=False+ )+ assert callback.status_code == 302+ yield client+ finally:+ client.close()+ clear_providers()+ _reset_for_tests()+++def _ticket(client):+ response = client.post("/api/auth/ws-ticket")+ assert response.status_code == 200+ return response.json()["ticket"]+++def test_authenticated_allowed_origin_completes_gateway_handshake(remote_dashboard):+ assert remote_dashboard.get("/api/status").status_code == 200+ for origin in (+ "http://100.64.0.10:9119",+ "file://",+ "null",+ "app://hermes",+ ):+ ticket = _ticket(remote_dashboard)+ with remote_dashboard.websocket_connect(+ f"/api/ws?ticket={ticket}", headers={"Origin": origin}+ ) as connection:+ assert connection.receive_json()["params"]["type"] == "gateway.ready"+ connection.send_json({"jsonrpc": "2.0", "id": "origin-ping", "method": "gateway.ping"})+ assert connection.receive_json() == {+ "jsonrpc": "2.0", "id": "origin-ping", "result": {"ok": True}+ }+ # Reconnects must mint a fresh ticket, never reuse an accepted one.+ with pytest.raises(WebSocketDisconnect) as rejected:+ with remote_dashboard.websocket_connect(+ f"/api/ws?ticket={ticket}", headers={"Origin": origin}+ ):+ pass+ assert rejected.value.code == 4401+++def test_gateway_upgrade_preserves_auth_host_and_origin_boundaries(remote_dashboard, monkeypatch):+ for headers in (+ {"Origin": "https://evil.test"},+ {"Origin": "http://127.0.0.1:52133"},+ {"Origin": "http://localhost:61307"},+ {"Origin": "http://[::1]:52133"},+ {"Origin": "http://localhost.evil.test:52133"},+ {"Origin": "http://evil.test@localhost:52133"},+ {"Origin": "http://localhost:notaport"},+ {"Origin": "http://[::1].evil.test:52133"},+ {"Origin": "http://[::1"},+ {"Origin": "https://[not-an-ip]:52133"},+ {"Origin": "http://testclient:52133"},+ {"Host": "evil.test:9119", "Origin": "http://127.0.0.1:52133"},+ ):+ with pytest.raises(WebSocketDisconnect) as rejected:+ with remote_dashboard.websocket_connect(f"/api/ws?ticket={_ticket(remote_dashboard)}", headers=headers):+ pass+ assert rejected.value.code == 4403++ # Even an authenticated HTTP cookie session is not a WS-upgrade credential.+ for query in ("", "?ticket=invalid", f"?token={web_server._SESSION_TOKEN}"):+ with pytest.raises(WebSocketDisconnect) as rejected:+ with remote_dashboard.websocket_connect(+ f"/api/ws{query}", headers={"Origin": "null"}+ ):+ pass+ assert rejected.value.code == 4401++ # Public --insecure binds keep their existing cross-origin policy.+ monkeypatch.setattr(web_server.app.state, "auth_required", False)+ with pytest.raises(WebSocketDisconnect) as rejected:+ with remote_dashboard.websocket_connect(+ f"/api/ws?token={web_server._SESSION_TOKEN}", headers={"Origin": "http://127.0.0.1:52133"}+ ):+ pass+ assert rejected.value.code == 4403