Skip to content

The agent that grows with you

fix(webapp): a running gateway's Webapp signs in with Web Access's own Portal client

emozilla53e551c58f9c
diff --git a/gateway/webapp_listener.py b/gateway/webapp_listener.py
index c064038a0f6..fb53a45c0cf 100644
--- a/gateway/webapp_listener.py
+++ b/gateway/webapp_listener.py
@@ -215,11 +215,11 @@ def use_own_sign_in(webapp: WebappMount):
``HERMES_DASHBOARD_OAUTH_CLIENT_ID``, until the returned undo runs. None, changing nothing, when
Web Access registered no client of its own (Nous sign-in set up by hand keeps the configured
client) or the Nous sign-in plugin is not enabled."""
+ from hermes_cli.dashboard_auth import listener_client
from hermes_cli.webapp_access import sign_in_client
- from plugins.dashboard_auth import nous
client = sign_in_client(webapp.home)
- return None if client is None else nous.use_listener_client(*client)
+ return None if client is None else listener_client.use(*client)
def browser_session_token(home, *, rotate: bool = False) -> str:
diff --git a/hermes_cli/dashboard_auth/listener_client.py b/hermes_cli/dashboard_auth/listener_client.py
new file mode 100644
index 00000000000..5c7136fc4ba
--- /dev/null
+++ b/hermes_cli/dashboard_auth/listener_client.py
@@ -0,0 +1,49 @@
+"""The Nous Portal client the listener this process serves signs in with instead of the configured one.
+
+The gateway's Webapp listener signs browsers in with the client Web Access registered for it
+(``hermes_cli.webapp_access.sign_in_client``), so the dashboard's ``HERMES_DASHBOARD_OAUTH_CLIENT_ID``
+keeps the redirect URI its own sign-in needs. Plugin discovery imports the bundled Nous sign-in
+plugin under a module name of its own, so the plugin and the gateway meet here: the plugin offers
+its provider swap when discovery loads it (:func:`offer`), and reads :func:`current` whenever it
+builds its provider, a plugin reload included.
+"""
+from __future__ import annotations
+
+from typing import Callable, Optional
+
+_current: Optional[tuple[str, str]] = None
+_swap: Optional[Callable[[], Callable[[], None]]] = None
+
+
+def current() -> Optional[tuple[str, str]]:
+ """``(client_id, portal_url)`` while a listener signs in with its own client, else None."""
+ return _current
+
+
+def offer(swap: Callable[[], Callable[[], None]]) -> None:
+ """Called by the Nous sign-in plugin as discovery loads it: ``swap()`` puts its provider on the
+ :func:`current` client in place of the registered one and returns the undo."""
+ global _swap
+ _swap = swap
+
+
+def use(client_id: str, portal_url: str) -> Optional[Callable[[], None]]:
+ """Sign in with *client_id* on *portal_url* until the returned undo runs, which puts the
+ configured provider (or none) back. None, changing nothing, where the Nous sign-in plugin is
+ not loaded (``plugins.disabled``)."""
+ global _current
+ if _swap is None:
+ return None
+ _current = (client_id, portal_url)
+ try:
+ restore = _swap()
+ except BaseException:
+ _current = None
+ raise
+
+ def undo() -> None:
+ global _current
+ _current = None
+ restore()
+
+ return undo
diff --git a/plugins/dashboard_auth/nous/__init__.py b/plugins/dashboard_auth/nous/__init__.py
index 9881a541b2f..10a02c0cf3c 100644
--- a/plugins/dashboard_auth/nous/__init__.py
+++ b/plugins/dashboard_auth/nous/__init__.py
@@ -8,7 +8,7 @@ reuse detection: the middleware MUST persist ``Session.refresh_token`` back to t
every refresh or the next refresh replays a rotated token and revokes the whole session.
While the gateway serves the Webapp, its sign-in uses the client Web Access registered for the
-Webapp instead of the configured one (:func:`use_listener_client`).
+Webapp instead of the configured one (``hermes_cli.dashboard_auth.listener_client``).
"""
from __future__ import annotations
@@ -16,7 +16,7 @@ from __future__ import annotations
import logging
from typing import Any, Callable, Optional
-from hermes_cli.dashboard_auth import LoginStart, ProviderError, Session
+from hermes_cli.dashboard_auth import LoginStart, ProviderError, Session, listener_client
from plugins.dashboard_auth._shared import (
DEFAULT_TOKEN_LEEWAY_SECONDS,
JwtOAuthProvider,
@@ -40,11 +40,6 @@ _SCOPE = "agent_dashboard:access" # contract C3
_EXPECTED_CONTRACT_VERSION = 1 # contract C11
LAST_SKIP_REASON: str = "" # cleared on every register() so restarts don't leak stale reasons
-# Whether plugin discovery has run register() in this process, i.e. the plugin is enabled here.
-_DISCOVERED = False
-# (client_id, portal_url) the listener this process serves signs in with instead of the configured
-# client, or None: see use_listener_client.
-_LISTENER_CLIENT: Optional[tuple[str, str]] = None
class NousDashboardAuthProvider(JwtOAuthProvider):
@@ -139,9 +134,9 @@ def _load_config_oauth_section() -> dict:
def _settings() -> dict:
"""Resolve NousDashboardAuthProvider kwargs; the skip reason names BOTH configuration surfaces."""
section = _load_config_oauth_section()
- if _LISTENER_CLIENT is not None: # a plugin reload while the listener uses its own client keeps it
- client_id, portal_url = _LISTENER_CLIENT
- return {"client_id": client_id, "portal_url": portal_url,
+ own = listener_client.current() # a plugin reload while the listener uses its own client keeps it
+ if own is not None:
+ return {"client_id": own[0], "portal_url": own[1],
"token_leeway": parse_leeway(section.get("token_leeway"))}
client_id = resolve_env_or_cfg("HERMES_DASHBOARD_OAUTH_CLIENT_ID", section.get("client_id", ""))
portal_url = resolve_env_or_cfg("HERMES_DASHBOARD_PORTAL_URL", section.get("portal_url", "")) or _DEFAULT_PORTAL_URL
@@ -166,8 +161,8 @@ def _settings() -> dict:
def register(ctx) -> None:
"""Register ``NousDashboardAuthProvider`` when a client_id is configured."""
- global LAST_SKIP_REASON, _DISCOVERED
- _DISCOVERED = True
+ global LAST_SKIP_REASON
+ listener_client.offer(_swap_provider)
LAST_SKIP_REASON = ""
kwargs, LAST_SKIP_REASON = register_provider(ctx, logger, _TAG, NousDashboardAuthProvider, _settings)
if kwargs is not None:
@@ -176,27 +171,13 @@ def register(ctx) -> None:
kwargs["client_id"], kwargs["portal_url"], kwargs["token_leeway"])
-def use_listener_client(client_id: str, portal_url: str) -> Optional[Callable[[], None]]:
- """Sign in with the Portal client *client_id* on *portal_url* instead of the configured one until
- the returned undo runs, which puts the configured provider (or none) back. The gateway does this
- while it serves the Webapp with the client Web Access registered for it, so the dashboard's
- ``HERMES_DASHBOARD_OAUTH_CLIENT_ID`` keeps the redirect URI its own sign-in needs. None, changing
- nothing, where the plugin is not enabled (discovery never ran :func:`register`)."""
+def _swap_provider() -> Callable[[], None]:
+ """Put a provider on the listener's own client (``listener_client.use`` has made it current) in
+ place of the registered one; the returned undo puts that one, or none, back."""
from hermes_cli.dashboard_auth.registry import (
register_global_provider, restore_registration, snapshot_registration)
- global _LISTENER_CLIENT
- if not _DISCOVERED:
- return None
previous = snapshot_registration(NousDashboardAuthProvider.name)
- leeway = parse_leeway(_load_config_oauth_section().get("token_leeway"))
- provider = NousDashboardAuthProvider(client_id=client_id, portal_url=portal_url, token_leeway=leeway)
- _LISTENER_CLIENT = (client_id, portal_url)
+ provider = NousDashboardAuthProvider(**_settings())
register_global_provider(provider)
-
- def undo() -> None:
- global _LISTENER_CLIENT
- _LISTENER_CLIENT = None
- restore_registration(NousDashboardAuthProvider.name, provider, previous)
-
- return undo
+ return lambda: restore_registration(NousDashboardAuthProvider.name, provider, previous)
diff --git a/tests/hermes_cli/test_webapp_access.py b/tests/hermes_cli/test_webapp_access.py
index fe862482514..f9d75168b35 100644
--- a/tests/hermes_cli/test_webapp_access.py
+++ b/tests/hermes_cli/test_webapp_access.py
@@ -535,28 +535,48 @@ async def _login_client_id(mount, origin: str) -> str:
return parse_qs(location.query)["client_id"][0]
+def _load_nous_plugin_as_discovery_does():
+ """The bundled Nous sign-in plugin imported as plugin discovery imports it: from its folder under
+ a module name of the loader's own (``hermes_plugins.<key>``), not as ``plugins.dashboard_auth.nous``,
+ so its module-level state is not that of any other import of it."""
+ import importlib.util
+ from pathlib import Path
+
+ import plugins.dashboard_auth.nous as source
+
+ folder = Path(source.__file__).parent
+ spec = importlib.util.spec_from_file_location(
+ "hermes_plugins_test_f5.dashboard_auth__nous", folder / "__init__.py", submodule_search_locations=[str(folder)])
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
@pytest.fixture()
def gateway_listeners(tmp_path, monkeypatch):
"""The gateway's dashboard mount over the process's dashboard app, as the gateway builds it at
start: ``listener(webapp=True)`` is the Webapp's listener (every interface, behind sign-in), else
the private one. ``discover()`` runs the Nous plugin's registration as plugin discovery does at
- gateway start (and on a plugin reload). The auth registry is emptied before and after."""
+ gateway start (and on a plugin reload), on the plugin imported the way discovery imports it. The
+ auth registry and the listener's sign-in client are reset before and after."""
import types
- import plugins.dashboard_auth.nous as nous_plugin
from gateway.run_api import GatewayDashboardMount
from gateway.webapp_listener import WebappMount
from hermes_cli import web_server
- from hermes_cli.dashboard_auth import clear_providers
+ from hermes_cli.dashboard_auth import clear_providers, listener_client
from hermes_cli.dashboard_auth.registry import register_global_provider
from hermes_constants import get_hermes_home
for key in ("bound_host", "bound_port", "auth_required", "trusted_public_hosts"):
monkeypatch.setattr(web_server.app.state, key, getattr(web_server.app.state, key, None), raising=False)
+ for name in ("_current", "_swap"):
+ monkeypatch.setattr(listener_client, name, None)
dist = tmp_path / "dist-webapp"
dist.mkdir()
(dist / "index.html").write_text("<!doctype html><html><body>WEBAPP</body></html>", encoding="utf-8")
discovery = types.SimpleNamespace(register_dashboard_auth_provider=register_global_provider)
+ nous_plugin = _load_nous_plugin_as_discovery_does()
def listener(*, webapp: bool):
state = types.SimpleNamespace(bound_host="0.0.0.0", bound_port=9120,
@@ -628,19 +648,16 @@ def test_a_plugin_reload_while_the_webapp_serves_keeps_its_own_client(portal, ga
asyncio.run(scenario())
-def test_a_disabled_nous_plugin_keeps_nous_sign_in_off_the_webapp(portal, monkeypatch, tmp_path):
+def test_a_disabled_nous_plugin_keeps_nous_sign_in_off_the_webapp(portal, gateway_listeners, tmp_path):
"""Web Access's client signs the Webapp in only through the Nous sign-in plugin: where
``plugins.disabled`` keeps that plugin from loading (discovery never registered it), the Webapp
gets no Nous sign-in from Web Access either."""
- import plugins.dashboard_auth.nous as nous_plugin
from gateway.webapp_listener import WebappMount, use_own_sign_in
from hermes_cli import webapp_access
- from hermes_cli.dashboard_auth import clear_providers, get_provider
+ from hermes_cli.dashboard_auth import get_provider
from hermes_constants import get_hermes_home
webapp_access.register(LAN_CALLBACK)
- monkeypatch.setattr(nous_plugin, "_DISCOVERED", False)
- clear_providers()
assert use_own_sign_in(WebappMount(tmp_path, get_hermes_home())) is None
assert get_provider("nous") is None