Files
hermes-agent/tests/hermes_cli/test_web_server_plugin_secret_scope.py
unsupportedpastels da01ee9c3c fix(plugins): run a served profile's dashboard plugins in its own plugin host
On a gateway serving several profiles, dashboard plugins were discovered
from the launch home only and mounted once in the gateway process. A plugin
installed only in a secondary profile answered 404 from that profile's
Desktop window, its plugins.isolation was ignored, and the interim rule ran
the launch profile's copy for it when both profiles enabled the name.

A request scoped to a secondary profile (its native grant or a ?profile=
selection) now gets that profile's own plugins, served through its own
plugin host (the existing per-profile host and its asgi op, bound to that
profile's home and secrets) whatever its isolation setting says. Their code
is never imported into the gateway.

- Discovery: the profile's own plugins/, then the root ~/.hermes/plugins
  (as a standalone `hermes --profile X serve` scanned before the cutover),
  then bundled; the profile's own copy wins a name clash. Root plugins also
  run in that profile's host.
- Consent: the requesting profile's plugins.enabled/disabled decide; the
  launch profile's consent no longer gates them. Disabled, not enabled and
  unknown names get identical answers (404 on HTTP, a 1008 close before
  accept on a websocket).
- Bundled plugins are Hermes code: a secondary profile uses the in-process
  router only when it is that profile's own bundled copy (the imported
  module's file, or for a cold mount the copy that would be mounted), and
  the cold mount binds the request's ?profile= before deciding. Otherwise,
  for example when a launch-profile user plugin shadows the bundled name,
  the request goes to the profile's host.
- Credentials: the session token, native grants, the Authorization and
  Cookie headers, and the gateway's query keys (token, ticket, internal,
  display_ticket, attach, profile; URL-decoded, every repeat) are removed
  before the request reaches the host. Ordinary plugin parameters pass.
- Assets: /dashboard-plugins/@<profile>/<name>/<file>, and
  /dashboard-plugins/... with ?profile=, bind that profile for the lookup
  and consent check (traversal and file-type checks unchanged; an unknown
  profile answers like an unknown plugin). The dashboard builds the path
  form, so files a stylesheet or bundle loads by relative URL come from
  the same profile. Its plugin loader binds its list request, asset URLs
  and loaded plugins to the selected profile and drops a list that lands
  after a switch; leaving a profile always removes that profile's
  stylesheets and bundles, even after its list became empty. A ?profile=
  rescan refreshes that profile's own cache.
- Plugin SDK: fetchJSON and authedFetch scope /api/plugins/ requests to
  the selected profile with ?profile=, and plugin sockets carry it too; a
  profile the plugin passes itself wins.
- The launch profile is unchanged.

The host protocol is request/response, so an authenticated websocket to a
secondary profile's hosted plugin gets a named refusal (HTTP 501 before
accept) instead of running in-process.

Tests that relied on a secondary profile reaching the launch copy now use
that profile's own copy (through a real host) or a bundled probe, and a
consent and refusal matrix covers both ways of selecting a profile.

Refs #134889 (PLG-3)
Refs #139523
2026-10-16 19:15:07 -04:00

105 lines
5.2 KiB
Python

"""A plugin API handler's ``get_secret()`` resolves the requested profile's credentials (#120310),
through the real mount path: the launch profile's copy in-process, a ``?profile=`` profile's own copy
in its plugin host (PLG-3). Moved out of ``test_web_server.py``.
"""
import shutil
import pytest
from tests.hermes_cli import test_web_server as web_server_tests
_EXAMPLE_PLUGIN_FIXTURE = web_server_tests._EXAMPLE_PLUGIN_FIXTURE
_install_example_plugin = web_server_tests._install_example_plugin # the fixture
class TestPluginAPISecretScopeProductionMount:
"""#120310: a plugin API handler's ``get_secret()`` must resolve the *requested*
profile's credentials under multi-profile hosting, verified through the REAL mount
path — discovery → import → ``_mount_plugin_api_routes()`` (which attaches
``_plugin_route_secret_scope``) → a live request against ``app`` — not a hand-built
``include_router``. The dedicated ``test_plugin_api_secret_scope.py`` suite proves the
dependency in isolation; this closes the actual reported surface end-to-end and pins
that the launch profile and a ``?profile=`` request read distinct secrets, that the
request profile does not leak back into the launch profile, and that an unknown
profile is rejected in the dependency before the handler runs.
"""
_PROBE_KEY = "EXAMPLE_PLUGIN_PROBE_KEY"
@pytest.fixture(autouse=True)
def _setup(self, monkeypatch, _isolate_hermes_home, _install_example_plugin):
try:
from starlette.testclient import TestClient
except ImportError:
pytest.skip("fastapi/starlette not installed")
import hermes_state
from hermes_constants import get_hermes_home
from hermes_cli import profiles
from hermes_cli.web_server import app, _SESSION_HEADER_NAME, _SESSION_TOKEN
default_home = get_hermes_home()
monkeypatch.setattr(hermes_state, "DEFAULT_DB_PATH", default_home / "state.db")
# Anchor the named-profiles root to the isolated home so ``?profile=workerb``
# resolves inside the test sandbox (mirrors test_web_server_skills_profiles).
profiles_root = default_home / "profiles"
monkeypatch.setattr(profiles, "_get_default_hermes_home", lambda: default_home)
monkeypatch.setattr(profiles, "_get_profiles_root", lambda: profiles_root)
# Named profile B: a live profile with its OWN probe key value in ``.env`` (also its identity
# marker); ``?profile=`` runs B's own installed copy in B's plugin host (PLG-3, #134889).
(worker_home := profiles_root / "workerb").mkdir(parents=True, exist_ok=True)
(worker_home / ".env").write_text(f"{self._PROBE_KEY}=sk-workerb\n", encoding="utf-8")
(worker_home / "config.yaml").write_text("plugins:\n enabled: [example]\n", encoding="utf-8")
shutil.copytree(_EXAMPLE_PLUGIN_FIXTURE, worker_home / "plugins" / "example-dashboard")
# Launch profile A: an env-only credential (systemd ``Environment=`` style), frozen
# into the launch scope when multi-profile hosting activates.
monkeypatch.setenv(self._PROBE_KEY, "sk-launch-a")
import tui_gateway.launch_profile_policy as lpp
from agent.secret_scope import is_multiplex_active, set_multiplex_active
monkeypatch.setattr(lpp, "_snapshot", None) # freeze the launch env fresh
self._previous_multiplex = is_multiplex_active()
lpp.activate_multi_profile_hosting() # freezes os.environ + flips multiplex on
self.client = TestClient(app)
self.client.headers[_SESSION_HEADER_NAME] = _SESSION_TOKEN
try:
yield
finally:
set_multiplex_active(self._previous_multiplex)
from hermes_cli import plugins as plugins_mod
for manager in list(plugins_mod._plugin_managers_by_home.values()):
host = getattr(manager, "_plugin_host_instance", None)
if host is not None:
host.shutdown()
def _probe(self, profile=None):
params = {"profile": profile} if profile is not None else None
return self.client.get("/api/plugins/example/whoami", params=params)
def test_launch_and_requested_profile_read_distinct_secrets(self):
# No ``?profile=`` → the launch profile's frozen env-only credential.
resp = self._probe()
assert resp.status_code == 200
assert resp.json() == {"ok": True, "key": "sk-launch-a"}
# ``?profile=workerb`` → that profile's own credential, through the real mount.
resp = self._probe("workerb")
assert resp.status_code == 200
assert resp.json() == {"ok": True, "key": "sk-workerb"}
# Back to the launch profile: the request scope reset, so B never leaks into A.
resp = self._probe()
assert resp.status_code == 200
assert resp.json() == {"ok": True, "key": "sk-launch-a"}
def test_unknown_profile_rejected_before_handler(self):
# The dependency raises HTTPException(404) before the handler runs, so this is a
# 404 — NOT the handler's folded ``{"ok": False}`` no-data contract.
resp = self._probe("ghost")
assert resp.status_code == 404