Files
hermes-agent/tests/hermes_cli/test_plugin_runtime_disable_gate.py
David Dudok de Wit 876e37c077 fix(security): hold the plugin gate on websockets and for every served profile
The runtime gate on /api/plugins/<name>/ stopped short in several ways.

- PLG-8: _plugin_api_runtime_gate is HTTP middleware, so a plugin disabled
  while the server ran kept accepting new websocket connections until
  restart. A pure ASGI gate now applies the same rule to upgrades. It closes
  before accept, ahead of the route's own credential check (that check is
  the disabled plugin's code, and a gated-mode ticket is single-use); on the
  wire that is the same 403 handshake an unknown route or a refused
  credential gets, so it is no plugin-name oracle.
- PLG-9: under a secondary profile's native ticket the gate read only that
  profile's plugin lists. Dashboard discovery scans only the launch home and
  the root, so every copy this server imports, hands to a plugin host or
  serves files from is the launch profile's. A plugin the launch profile
  disabled stayed reachable for the secondary profile (routes and assets),
  and that profile's first request for a plugin only it enabled hot-mounted
  the launch copy in its scope: imported here, or, under its own
  plugins.isolation: host, run by its plugin host with its secrets
  (GHSA-mcfc-hp25-cjv7). The hot mount also took plugins.isolation from the
  requesting profile, so an in-process secondary imported a plugin the
  launch profile runs in a host.
- A session-token request with ?profile= ran a plugin in the selected
  profile's scope even when that profile had disabled it.

One rule now holds for HTTP, websocket upgrades, assets, the dashboard
plugin list (no tab whose script and API refuse) and the hot mount:
a plugin is served only while the launch profile, whose copy it is, has it
enabled and so does the profile the request acts for (a native ticket's
profile, a ?profile= selection once its scope is bound, else the launch
profile). Mount decisions, hot mounts included, are the launch profile's
alone, its isolation mode included. The gates read the enable lists once
per profile scope from the cached read-only config.

Refs #134889 (PLG-8, PLG-9)

(cherry picked from commit 04759b71e5f0eabac25b9cf7ba15216c405972c8)
2026-10-16 12:45:05 +00:00

220 lines
8.5 KiB
Python

"""Regression tests for runtime plugin disable gating.
Covers two residual bypasses addressed in the PR:
1. Plugin API routes mounted at startup remain callable even after the
plugin is added to ``plugins.disabled`` at runtime. The new
``_plugin_api_runtime_gate`` middleware blocks these requests.
2. Bundled plugin assets were served from the unauthenticated
``/dashboard-plugins/{name}/{path}`` route even when the bundled
plugin was in ``plugins.disabled``. The updated ``serve_plugin_asset``
now applies the disabled check to bundled plugins too.
"""
from __future__ import annotations
import json
from types import SimpleNamespace
from unittest.mock import patch, AsyncMock
import pytest
from hermes_cli import web_server
@pytest.fixture(autouse=True)
def _reset_plugin_cache():
"""Bust the plugin cache before and after each test."""
web_server._dashboard_plugins_cache = None
yield
web_server._dashboard_plugins_cache = None
@pytest.fixture
def test_client(monkeypatch, tmp_path):
"""Set up a Starlette TestClient with auth bypassed."""
try:
from starlette.testclient import TestClient
except ImportError:
pytest.skip("fastapi/starlette not installed")
from hermes_cli.web_server import app, _SESSION_HEADER_NAME, _SESSION_TOKEN
# Isolate HERMES_HOME so config reads go to our tmp.
monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))
(tmp_path / "home").mkdir(parents=True)
client = TestClient(app)
client.headers[_SESSION_HEADER_NAME] = _SESSION_TOKEN
return client
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _make_bundled_plugin(tmp_path, name="bundledx"):
"""Create a minimal bundled plugin with a JS asset."""
dashboard_dir = tmp_path / "bundled" / name / "dashboard"
dashboard_dir.mkdir(parents=True)
dist_dir = dashboard_dir / "dist"
dist_dir.mkdir()
(dist_dir / "index.js").write_text("console.log('bundled');")
(dashboard_dir / "manifest.json").write_text(json.dumps({
"name": name,
"label": name.title(),
"entry": "dist/index.js",
}))
return dashboard_dir
# ---------------------------------------------------------------------------
# Test 1: Runtime-disabled user plugin API routes return 404
# ---------------------------------------------------------------------------
class TestPluginApiRuntimeGate:
"""After a user plugin is disabled at runtime, its mounted API routes
must return 404 — not 200 — even though the router was already
included at startup. The _plugin_api_runtime_gate middleware enforces
this at request time."""
@pytest.mark.asyncio
async def test_middleware_blocks_disabled_user_plugin(self):
"""Middleware returns 404 for a user plugin added to disabled set."""
from starlette.requests import Request
from starlette.responses import JSONResponse
fake_plugin = {
"name": "hot",
"source": "user",
}
# Simulate a request to /api/plugins/hot/probe
scope = {
"type": "http",
"method": "GET",
"path": "/api/plugins/hot/probe",
"query_string": b"",
"headers": [],
"state": {"token_authenticated": True},
}
request = Request(scope)
call_next = AsyncMock(return_value=JSONResponse({"ok": True}))
with patch.object(web_server, "_get_dashboard_plugins", return_value=[fake_plugin]), \
patch("hermes_cli.web_server_dashboard._plugin_enable_sets_here", return_value=({"hot"}, {"hot"})):
response = await web_server._plugin_api_runtime_gate(request, call_next)
assert response.status_code == 404
call_next.assert_not_called()
@pytest.mark.asyncio
async def test_middleware_passes_non_plugin_api_routes(self):
"""Middleware ignores non-plugin API routes."""
from starlette.requests import Request
from starlette.responses import JSONResponse
scope = {
"type": "http",
"method": "GET",
"path": "/api/status",
"query_string": b"",
"headers": [],
"state": {"token_authenticated": True},
}
request = Request(scope)
expected_resp = JSONResponse({"ok": True})
call_next = AsyncMock(return_value=expected_resp)
response = await web_server._plugin_api_runtime_gate(request, call_next)
assert response is expected_resp
call_next.assert_called_once()
@pytest.mark.asyncio
async def test_middleware_unknown_plugin_defaults_to_user_blocks(self):
"""Unknown plugin name (not in discovery cache) is treated as user
plugin and blocked when not enabled."""
from starlette.requests import Request
from starlette.responses import JSONResponse
scope = {
"type": "http",
"method": "GET",
"path": "/api/plugins/unknown/action",
"query_string": b"",
"headers": [],
"state": {"token_authenticated": True},
}
request = Request(scope)
call_next = AsyncMock(return_value=JSONResponse({"ok": True}))
with patch.object(web_server, "_get_dashboard_plugins", return_value=[]), \
patch("hermes_cli.web_server_dashboard._plugin_enable_sets_here", return_value=(set(), set())):
response = await web_server._plugin_api_runtime_gate(request, call_next)
assert response.status_code == 404
call_next.assert_not_called()
@pytest.mark.asyncio
async def test_middleware_blocks_disabled_plugin_for_native_ticket_request(self):
"""Desktop authenticates with a native ticket (``native_http_principal``), not a
session token; a plugin disabled while the daemon runs must 404 for it too."""
from starlette.requests import Request
from starlette.responses import JSONResponse
scope = {
"type": "http",
"method": "GET",
"path": "/api/plugins/hot/probe",
"query_string": b"",
"headers": [],
"state": {"native_http_principal": {"profile_id": "default", "purpose": "native-http"}},
# Local Desktop: loopback mode, no gated auth.
"app": SimpleNamespace(state=SimpleNamespace(auth_required=False)),
}
request = Request(scope)
call_next = AsyncMock(return_value=JSONResponse({"ok": True}))
with patch.object(web_server, "_get_dashboard_plugins", return_value=[{"name": "hot", "source": "user"}]), \
patch("hermes_cli.web_server_dashboard._plugin_enable_sets_here", return_value=({"hot"}, {"hot"})):
response = await web_server._plugin_api_runtime_gate(request, call_next)
assert response.status_code == 404
call_next.assert_not_called()
# ---------------------------------------------------------------------------
# Test 2: Disabled bundled plugin assets return 404
# ---------------------------------------------------------------------------
class TestBundledPluginAssetGate:
"""Bundled plugins in ``plugins.disabled`` must have their static
assets blocked — not just hidden from the listing endpoint."""
def test_bundled_asset_returns_404_when_disabled(self, test_client, tmp_path, monkeypatch):
"""A disabled bundled plugin's JS asset must return 404."""
plugin_dir = _make_bundled_plugin(tmp_path, "bundledx")
fake_plugin = {
"name": "bundledx",
"label": "Bundledx",
"source": "bundled",
"entry": "dist/index.js",
"_dir": str(plugin_dir),
}
with patch.object(web_server, "_get_dashboard_plugins", return_value=[fake_plugin]):
# Sanity: asset is served when not disabled.
with patch("hermes_cli.web_server_dashboard._plugin_enable_sets_here", return_value=(set(), set())):
resp = test_client.get("/dashboard-plugins/bundledx/dist/index.js")
assert resp.status_code == 200, (
"Sanity: bundled plugin asset should be served when not disabled"
)
# Disable it.
with patch("hermes_cli.web_server_dashboard._plugin_enable_sets_here", return_value=(set(), {"bundledx"})):
resp = test_client.get("/dashboard-plugins/bundledx/dist/index.js")
assert resp.status_code == 404, (
"Disabled bundled plugin asset must return 404"
)