Skip to content

The agent that grows with you

fix(plugins): preserve route authorization across hosted HTTP requests

funky-xamarin588f83a27345
diff --git a/hermes_cli/plugin_host.py b/hermes_cli/plugin_host.py
index e36c22ef59d..70167192f30 100644
--- a/hermes_cli/plugin_host.py
+++ b/hermes_cli/plugin_host.py
@@ -291,12 +291,14 @@ class PluginHost:
"attr": attr, "args": encode(list(args)), "kwargs": encode(kwargs)})
def asgi_request(self, plugin_name: str, dashboard_dir: str, api_file: str, method: str, path: str,
- query: str, headers: list, body: bytes, *, timeout: Optional[float] = None) -> dict[str, Any]:
+ query: str, headers: list, body: bytes, *, timeout: Optional[float] = None,
+ authenticated: bool = False) -> dict[str, Any]:
"""One dashboard ``/api/plugins/<name>/`` request, served by the plugin's router in the host;
``TimeoutError`` when no answer comes within ``timeout`` seconds (the host is left running)."""
self.ensure_started()
return self._call("asgi", {"plugin": plugin_name, "dashboard_dir": dashboard_dir, "api_file": api_file,
"method": method, "path": path, "query": query,
+ "authenticated": authenticated is True,
"headers": [list(h) for h in headers], "body": encode(body)},
timeout=timeout)
diff --git a/hermes_cli/plugin_host_child.py b/hermes_cli/plugin_host_child.py
index c9aee6a290a..6426fdbcc07 100644
--- a/hermes_cli/plugin_host_child.py
+++ b/hermes_cli/plugin_host_child.py
@@ -319,7 +319,8 @@ class HostRuntime:
async def request() -> dict[str, Any]:
import httpx
- transport = httpx.ASGITransport(app=app)
+ from hermes_cli.plugin_host_http_auth import with_hosted_admission
+ transport = httpx.ASGITransport(app=with_hosted_admission(app, params.get("authenticated")))
async with httpx.AsyncClient(transport=transport, base_url="http://plugin-host") as client:
response = await client.request(
str(params["method"]), str(params["path"]), params=str(params.get("query") or ""),
diff --git a/hermes_cli/plugin_host_http_auth.py b/hermes_cli/plugin_host_http_auth.py
new file mode 100644
index 00000000000..4831bcfe386
--- /dev/null
+++ b/hermes_cli/plugin_host_http_auth.py
@@ -0,0 +1,23 @@
+"""Carry route-local admission over the private plugin-host channel, without credentials."""
+from fastapi import HTTPException
+
+
+def admitted_for_sensitive_route(request) -> bool:
+ """Preserve the normal guard's decision without changing unguarded plugin routes."""
+ from hermes_cli.web_server import _require_token
+ try:
+ _require_token(request)
+ except HTTPException as exc:
+ if exc.status_code != 401:
+ raise
+ return False
+ return True
+
+
+def with_hosted_admission(app, authenticated):
+ """Admission belongs to this IPC request, never to the cached plugin app."""
+ async def scoped(scope, receive, send):
+ state = dict(scope.get("state") or {})
+ state["hosted_http_authenticated"] = authenticated is True
+ await app({**scope, "state": state}, receive, send)
+ return scoped
diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.py
index b4607df0c71..708a9472070 100644
--- a/hermes_cli/web_server.py
+++ b/hermes_cli/web_server.py
@@ -338,8 +338,11 @@ def _require_token(request: Request) -> None:
A verified native owner (``authenticate_native_http``) is the same-user
principal the outer seams already accepted; local Desktop runs with no
static token, so that principal must satisfy route-local policy too.
+ Hosted plugins receive this guard's decision via private IPC and request-local
+ state, not via a forwarded gateway credential or a process-wide bypass.
"""
- if getattr(request.state, "native_http_principal", None):
+ if (getattr(request.state, "native_http_principal", None)
+ or getattr(request.state, "hosted_http_authenticated", None) is True):
return
if getattr(request.app.state, "auth_required", False):
ok = getattr(request.state, "session", None) is not None
diff --git a/hermes_cli/web_server_dashboard.py b/hermes_cli/web_server_dashboard.py
index 354d7662c3a..450198c27f9 100644
--- a/hermes_cli/web_server_dashboard.py
+++ b/hermes_cli/web_server_dashboard.py
@@ -973,8 +973,11 @@ def _mount_hosted_plugin_api(app, plugin: dict, api_file_name: str) -> None:
from hermes_cli.web_server_plugin_profiles import run_hosted_request
query, headers = request.url.query, [(k, v) for k, v in request.headers.items() if k.lower() != "host"]
body = await request.body()
+ from hermes_cli.plugin_host_http_auth import admitted_for_sensitive_route
+ authenticated = admitted_for_sensitive_route(request)
return await run_hosted_request(host.home, name, lambda timeout: host.asgi_request(
- name, dashboard_dir, api_file, request.method, "/" + path, query, headers, body, timeout=timeout))
+ name, dashboard_dir, api_file, request.method, "/" + path, query, headers, body,
+ timeout=timeout, authenticated=authenticated))
app.add_api_route(f"/api/plugins/{name}/{{path:path}}", forward, include_in_schema=False,
methods=["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"],
diff --git a/hermes_cli/web_server_plugin_profiles.py b/hermes_cli/web_server_plugin_profiles.py
index cc1ccc63a3d..d999abe8297 100644
--- a/hermes_cli/web_server_plugin_profiles.py
+++ b/hermes_cli/web_server_plugin_profiles.py
@@ -246,12 +246,14 @@ async def forward_secondary_plugin_request(request, name: str) -> Optional[Respo
if k not in _GATEWAY_QUERY_KEYS])
headers = [(k, v) for k, v in request.headers.items() if k.lower() not in _GATEWAY_CREDENTIAL_HEADERS]
body = await request.body()
+ from hermes_cli.plugin_host_http_auth import admitted_for_sensitive_route
+ authenticated = admitted_for_sensitive_route(request)
def call(timeout: float) -> dict[str, Any]:
from hermes_cli.plugins import get_plugin_manager
host = get_plugin_manager()._plugin_host() # the active (secondary) profile's own host
return host.asgi_request(name, str(plugin["_dir"]), str(plugin["_api_file"]), request.method, path,
- query, headers, body, timeout=timeout)
+ query, headers, body, timeout=timeout, authenticated=authenticated)
try:
return await run_hosted_request(home, name, call)
diff --git a/tests/hermes_cli/test_plugin_host_route_auth.py b/tests/hermes_cli/test_plugin_host_route_auth.py
new file mode 100644
index 00000000000..780ad7e9c47
--- /dev/null
+++ b/tests/hermes_cli/test_plugin_host_route_auth.py
@@ -0,0 +1,99 @@
+"""Regression for #140499: upstream admission survives credential-free hosting."""
+import os
+from types import SimpleNamespace
+
+import pytest
+
+from hermes_cli.plugin_host import PluginHost
+from tests.hermes_cli import test_plugin_secondary_profile_host as secondary
+
+daemon = secondary.daemon
+
+_API = '''
+import os
+from fastapi import APIRouter, Request
+from hermes_cli.web_deps import late
+
+router = APIRouter()
+
+async def config(request: Request):
+ late("_require_token")(request)
+ return {"pid": os.getpid(), "saved": True,
+ "credentials": [k for k in request.headers if k in
+ {"authorization", "cookie", "x-hermes-session-token", "x-hermes-gateway-ticket"}]}
+'''
+
+
+def test_secondary_guarded_mutation_uses_upstream_admission(daemon, monkeypatch):
+ monkeypatch.setattr(PluginHost, "asgi_request", secondary._REAL_ASGI_REQUEST)
+ secondary._beta_plugin(daemon)
+ api = daemon.beta / "plugins" / secondary.NAME / "dashboard" / "plugin_api.py"
+ api.write_text(_API, encoding="utf-8")
+ url = f"/api/plugins/{secondary.NAME}/config"
+ try:
+ response = daemon.client.put(url, headers=daemon.beta_ticket())
+ assert response.status_code == 200, response.text
+ assert response.json()["saved"] is True
+ assert response.json()["pid"] != os.getpid()
+ assert response.json()["credentials"] == []
+ assert daemon.client.put(url, params={"profile": "beta"}).status_code == 401
+ finally:
+ secondary._shutdown_hosts()
+
+
+def test_host_admission_does_not_leak_or_come_from_http_input(tmp_path):
+ api = tmp_path / "api"
+ api.mkdir()
+ (api / "plugin_api.py").write_text(_API, encoding="utf-8")
+ home = tmp_path / "home"
+ home.mkdir()
+ host = PluginHost(SimpleNamespace(home_path=home, _plugins={}))
+ args = ("guard-probe", str(api), "plugin_api.py", "PUT", "/config", "authenticated=true",
+ [("X-Hosted-Http-Authenticated", "true")], b'{"authenticated":true}')
+ try:
+ assert host.asgi_request(*args, authenticated=True)["status"] == 200
+ for marker in (False, None, "true", 1):
+ assert host.asgi_request(*args, authenticated=marker)["status"] == 401
+ assert host.asgi_request(*args)["status"] == 401
+ assert host.asgi_request(*args, authenticated=True)["status"] == 200
+ finally:
+ host.shutdown()
+
+
+def test_launch_host_preserves_native_admission(daemon, monkeypatch):
+ monkeypatch.setattr(PluginHost, "asgi_request", secondary._REAL_ASGI_REQUEST)
+ secondary._install(daemon.launch, "launch-guard")
+ secondary._plugins(daemon.launch, enabled=["launch-guard"], isolation="host")
+ api = daemon.launch / "plugins" / "launch-guard" / "dashboard" / "plugin_api.py"
+ api.write_text(_API, encoding="utf-8")
+ try:
+ response = daemon.client.put("/api/plugins/launch-guard/config", headers=daemon.owner)
+ assert response.status_code == 200, response.text
+ assert response.json()["pid"] != os.getpid()
+ finally:
+ secondary._shutdown_hosts()
+
+
+def test_admission_matches_normal_guard_and_preserves_unguarded_routes():
+ from fastapi import FastAPI, HTTPException
+ from starlette.requests import Request
+ from hermes_cli.plugin_host_http_auth import admitted_for_sensitive_route
+ from hermes_cli import web_server
+
+ app = FastAPI()
+ scope = {"type": "http", "method": "PUT", "path": "/config", "headers": [], "app": app}
+ assert not admitted_for_sensitive_route(Request(scope))
+ assert admitted_for_sensitive_route(Request({**scope, "headers": [
+ (web_server._SESSION_HEADER_NAME.lower().encode(), web_server._SESSION_TOKEN.encode())]}))
+ app.state.auth_required = True
+ assert not admitted_for_sensitive_route(Request(scope))
+ assert admitted_for_sensitive_route(Request({**scope, "state": {"session": object()}}))
+ assert admitted_for_sensitive_route(Request({**scope, "state": {"native_http_principal": object()}}))
+ for marker in (None, False, "true", 1):
+ with pytest.raises(HTTPException) as error:
+ web_server._require_token(Request({**scope, "state": {"hosted_http_authenticated": marker}}))
+ assert error.value.status_code == 401