The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(security): honour allowlist removals and the plugin gate on the shared gateway
unsupportedpastelseea7c437ebd6
diff --git a/hermes_cli/web_server.py b/hermes_cli/web_server.pyindex 07900c04b25..a3103b2cc3a 100644--- a/hermes_cli/web_server.py+++ b/hermes_cli/web_server.py@@ -411,9 +411,10 @@ async def _plugin_api_runtime_gate(request: Request, call_next):plugin_name = parts[3] if path.startswith("/api/plugins/") and len(parts) >= 4 else ""# Only gate authenticated requests. Unauthenticated ones fall through so# auth_middleware / the OAuth gate return 401 first and this route can't- # be used as a plugin-name oracle.+ # be used as a plugin-name oracle. Desktop authenticates with a native ticket.if plugin_name and (getattr(request.state, "token_authenticated", False)+ or getattr(request.state, "native_http_principal", None)or getattr(request.app.state, "auth_required", False)or _has_valid_session_token(request)or _has_valid_query_token(request, path)diff --git a/tests/hermes_cli/test_plugin_runtime_disable_gate.py b/tests/hermes_cli/test_plugin_runtime_disable_gate.pyindex 6bb98b34351..42ecd7bbb0a 100644--- a/tests/hermes_cli/test_plugin_runtime_disable_gate.py+++ b/tests/hermes_cli/test_plugin_runtime_disable_gate.py@@ -14,6 +14,7 @@ Covers two residual bypasses addressed in the PR:from __future__ import annotationsimport json+from types import SimpleNamespacefrom unittest.mock import patch, AsyncMockimport pytest@@ -156,6 +157,35 @@ class TestPluginApiRuntimeGate:assert response.status_code == 404call_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.plugins_cmd._get_enabled_set", return_value={"hot"}), \+ patch("hermes_cli.plugins_cmd._get_disabled_set", return_value={"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# ---------------------------------------------------------------------------diff --git a/tests/tools/test_permanent_allowlist_live_reload.py b/tests/tools/test_permanent_allowlist_live_reload.pynew file mode 100644index 00000000000..9930424ec4f--- /dev/null+++ b/tests/tools/test_permanent_allowlist_live_reload.py@@ -0,0 +1,67 @@+"""A hand edit to ``command_allowlist`` must reach a long-lived process's approval check.++The unified gateway daemon serves every local session, so the import-time load of+``command_allowlist`` lived as long as the daemon: an entry the operator removed by hand+(the documented way to withdraw a standing approval) stayed auto-approved until restart.+"""++import pytest++from hermes_cli.config import get_config_path+from tools import approval+from tools.approval_floors import _command_matches_permanent_allowlist+++def allowlist_file():+ """Write ``command_allowlist`` into the isolated test home's config.yaml."""+ saved_approved = set(approval._permanent_approved)+ saved_baseline = dict(approval._permanent_baseline_by_home)+ path = get_config_path()+ path.parent.mkdir(parents=True, exist_ok=True)++ def _write(entries):+ lines = ["command_allowlist:"] + [f"- '{e}'" for e in entries] if entries else ["command_allowlist: []"]+ path.write_text("\n".join(lines) + "\n", encoding="utf-8")++ try:+ yield _write+ finally:+ approval._permanent_approved.clear()+ approval._permanent_approved.update(saved_approved)+ approval._permanent_baseline_by_home.clear()+ approval._permanent_baseline_by_home.update(saved_baseline)+++def test_entry_removed_by_hand_prompts_again(allowlist_file):+ allowlist_file(["rm -rf build", "ls *"])+ approval.load_permanent_allowlist()+ assert _command_matches_permanent_allowlist("rm -rf build")++ allowlist_file(["ls *"]) # operator withdraws the standing approval++ assert not _command_matches_permanent_allowlist("rm -rf build")+ assert not approval.is_approved("s1", "rm -rf build")+ assert _command_matches_permanent_allowlist("ls -la")+++def test_entry_added_by_hand_takes_effect(allowlist_file):+ allowlist_file(["ls *"])+ approval.load_permanent_allowlist()+ assert not _command_matches_permanent_allowlist("podman ps")++ allowlist_file(["ls *", "podman *"])++ assert _command_matches_permanent_allowlist("podman ps")+++def test_approval_made_in_process_survives_an_unrelated_hand_edit(allowlist_file):+ """An [a]lways whose save failed lives only in memory; a later edit must not drop it."""+ allowlist_file(["ls *", "git status"])+ approval.load_permanent_allowlist()+ approval.approve_permanent("recursive delete")++ allowlist_file(["ls *"])++ assert approval._is_permanently_approved("recursive delete")+ assert not _command_matches_permanent_allowlist("git status")diff --git a/tools/approval.py b/tools/approval.pyindex 1e3dccbbae7..d2621940e6b 100644--- a/tools/approval.py+++ b/tools/approval.py@@ -342,19 +342,32 @@ def _permanent_set() -> set:"""from hermes_constants import get_hermes_home_override, hermes_home_keyif get_hermes_home_override() is None:- return _permanent_approved- home_key = hermes_home_key()- approved = _permanent_approved_by_home.get(home_key)- if approved is None:- try:- approved = _read_permanent_allowlist()- except Exception as e:- logger.warning("Failed to load permanent allowlist: %s", e)- approved = set()- _permanent_approved_by_home[home_key] = approved+ approved, key = _permanent_approved, ""+ else:+ key = hermes_home_key()+ approved = _permanent_approved_by_home.setdefault(key, set())+ _sync_permanent_from_disk(approved, key)return approved+def _sync_permanent_from_disk(approved: set, key: str) -> None:+ """Apply hand edits to ``command_allowlist`` made since the last sync. The gateway daemon+ outlives any one session, so an entry the operator removed must stop being honoured now, not+ at restart. Only the on-disk delta is applied: approvals this process made but could not save+ survive. The config read is cached on the file signature. Callers hold ``_lock``."""+ try:+ on_disk = _read_permanent_allowlist()+ except Exception as e:+ logger.warning("Failed to load permanent allowlist: %s", e, exc_info=True)+ return+ baseline = _permanent_baseline_by_home.get(key, set())+ if on_disk == baseline:+ return+ approved.difference_update(baseline - on_disk)+ approved.update(on_disk - baseline)+ _permanent_baseline_by_home[key] = on_disk++def is_approved(session_key: str, pattern_key: str) -> bool:"""Session-scoped or permanent approval. Accepts the canonical key and the legacyregex-derived key so existing command_allowlist entries survive key migrations."""@@ -461,7 +474,7 @@ def save_permanent_allowlist(patterns: set):resurrected the ones removed. The result written is ``what is on disk now``plus ``what this process approved since its own baseline``; revoked entries arealso dropped from the governing permanent set so ``is_approved()`` stops- honouring them. Nothing re-reads the file on the approval hot path.+ honouring them (``_sync_permanent_from_disk`` does the same on every check).``patterns`` may only ADD: an entry left out of it is not removed, because theon-disk list wins for anything this process did not approve itself. Remove