Skip to content

The agent that grows with you

fix(webapp): refuse an unbound profile ticket and bind explicit profiles on launch sockets

Teknium50f259a83f37
diff --git a/hermes_cli/web_routers/chat_ws.py b/hermes_cli/web_routers/chat_ws.py
index 1fc81200d23..fc1bf403f7f 100644
--- a/hermes_cli/web_routers/chat_ws.py
+++ b/hermes_cli/web_routers/chat_ws.py
@@ -676,7 +676,12 @@ async def gateway_ws(ws: WebSocket) -> None:
identity = {**identity, 'profile_scope': 'host'}
ticket_home = getattr(ws, "_hermes_ticket_profile_home", None)
served = authority
- if ticket_home and authority is not None and identity is not None:
+ if ticket_home and authority is None:
+ # Only the gateway mints a profile-bound ticket, and it unbinds its authority while the
+ # listener stops: serving the launch profile now would answer the tab for the wrong one.
+ await ws.close(code=1013)
+ return
+ if ticket_home and identity is not None:
# A Webapp tab's ticket names its profile (``webapp.issue_gateway_ticket``): bind the socket
# to that home's authority, as a native ticket does (``gateway/run_api.py``), so a request
# that names no profile is answered for the tab's profile, not the launch profile.
diff --git a/tests/hermes_cli/test_webapp_socket_profile_scope.py b/tests/hermes_cli/test_webapp_socket_profile_scope.py
index 07c5c58047a..daafa503f26 100644
--- a/tests/hermes_cli/test_webapp_socket_profile_scope.py
+++ b/tests/hermes_cli/test_webapp_socket_profile_scope.py
@@ -1,94 +1,183 @@
-"""The Webapp's gateway socket runs in the served profile's scope on a multiplexed gateway.
+"""The Webapp's gateway socket answers for the profile its ticket names, on a multiplexed gateway.
A browser tab's ``/api/ws`` reaches the gateway through the dashboard mount (``chat_ws.gateway_ws``),
-not the native ticket path (``gateway/run_api.py``) that wraps the socket in ``owner_scope``. Legacy
-handlers it falls back to (``billing.state``, ``subscription.state``, ``usage.bars``) bind no scope of
-their own, so every Webapp billing/usage read on a multiplexed gateway resolved the Nous Portal
-override with no profile secret scope: ``UnscopedSecretError`` -> "no profile secret scope on a
-multiplexed call" -> the override was dropped and the token went to the default Portal.
+not the native ticket path (``gateway/run_api.py``) that wraps the socket in ``owner_scope``. The
+authority answers ``-32601`` for ``billing.state``, so the frame falls back to the legacy handler,
+which reads the Nous Portal override through the socket's scope: unbound, a multiplexed gateway
+refused the read (``UnscopedSecretError`` -> "no profile secret scope on a multiplexed call") and the
+token went to the default Portal. ``dispatch_legacy`` binds a non-launch ticket's profile; a
+launch-profile socket relies on ``gateway_ws``'s own scope.
+
+Real ``gateway_ws``, ``handle_ws``, session authorities, legacy fallback and billing handler; only
+the upgrade gate (which stamps the ticket's identity and home on the socket) and HTTP are substituted.
"""
import asyncio
+import base64
+import io
+import json
+import logging
+import time
from pathlib import Path
from types import SimpleNamespace
+import httpx
import pytest
+from starlette.websockets import WebSocketDisconnect
-LAUNCH_PORTAL = "https://launch-portal.example.invalid"
-B_PORTAL = "https://b-portal.example.invalid"
+def _jwt(label):
+ def part(value):
+ return base64.urlsafe_b64encode(json.dumps(value).encode()).decode().rstrip("=")
+ return ".".join((part({"alg": "none"}), part({
+ "sub": label, "scope": "inference:invoke", "exp": int(time.time()) + 3600,
+ }), "fixture"))
-def two_homes(tmp_path, monkeypatch):
- launch = tmp_path / "hermes"
- b = launch / "profiles" / "b"
- b.mkdir(parents=True)
- (launch / ".env").write_text(f"HERMES_PORTAL_BASE_URL={LAUNCH_PORTAL}\n", encoding="utf-8")
- (b / ".env").write_text(f"HERMES_PORTAL_BASE_URL={B_PORTAL}\n", encoding="utf-8")
- for home in (launch, b):
- (home / "config.yaml").write_text("{}\n", encoding="utf-8")
- monkeypatch.setenv("HERMES_HOME", str(launch))
- monkeypatch.setenv("HERMES_PORTAL_BASE_URL", LAUNCH_PORTAL) # the launch process loaded its own .env
- from agent import secret_scope
- monkeypatch.setattr(secret_scope, "_MULTIPLEX_ACTIVE", True)
- return launch, b
+def _home(home, label):
+ home.mkdir(parents=True, exist_ok=True)
+ (home / "config.yaml").write_text("model:\n provider: nous\n default: fixture-model\n")
+ (home / ".env").write_text(f"HERMES_PORTAL_BASE_URL=https://{label}-portal.invalid\n")
+ (home / "auth.json").write_text(json.dumps({"version": 1, "providers": {"nous": {
+ "access_token": _jwt(label), "refresh_token": f"{label}-refresh",
+ "expires_at": "2999-01-01T00:00:00+00:00", "scope": "inference:invoke", "client_id": "fixture-client",
+ "portal_base_url": "https://portal.nousresearch.com",
+ "inference_base_url": "https://inference-api.nousresearch.com/v1",
+ }}}))
-def _gateway(launch: Path, b: Path):
- """A multiplexed runner serving both homes, and its launch authority."""
- by_home = {}
- runner = SimpleNamespace(config=SimpleNamespace(multiplex_profiles=True))
+
+def gateway(tmp_path, monkeypatch):
+ """A multiplexed runner serving the launch home and profile ``b``, each with its own authority."""
+ from agent import secret_scope
+ from gateway.config import GatewayConfig
+ from gateway.session import SessionStore
+ from gateway.session_authority import SessionAuthority
+ from hermes_cli import auth, nous_account, nous_billing
+ from hermes_state import SessionDB
+ from hermes_state_runtime import begin_runtime_epoch
+ from tui_gateway import launch_profile_policy, server
+
+ launch, b = tmp_path / "launch", tmp_path / "launch" / "profiles" / "b"
+ _home(launch, "launch")
+ _home(b, "b")
+ monkeypatch.setenv("HERMES_HOME", str(launch))
+ monkeypatch.setenv("HERMES_SHARED_AUTH_DIR", str(tmp_path / "shared-auth"))
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ for key in ("HERMES_PORTAL_BASE_URL", "NOUS_PORTAL_BASE_URL", "NOUS_INFERENCE_BASE_URL",
+ "HERMES_DEV_BILLING_FIXTURE", "HERMES_DEV_SUBSCRIPTION_FIXTURE", "HERMES_DEV_CREDITS_FIXTURE"):
+ monkeypatch.delenv(key, raising=False)
+ monkeypatch.setattr(launch_profile_policy, "_snapshot", None)
+ monkeypatch.setattr(server, "_hermes_home", str(launch))
+ monkeypatch.setattr(server, "_served_profile_homes", set())
+ monkeypatch.setattr(auth, "_RESOLVE_TOKEN_CACHE", {})
+ monkeypatch.setattr(nous_billing, "_token_cache", {})
+ nous_account.reset_nous_portal_account_info_cache()
+ previous = secret_scope.is_multiplex_active()
+ launch_profile_policy.activate_multi_profile_hosting()
+
+ by_home, dbs = {}, []
+ runner = SimpleNamespace(_draining=False, config=SimpleNamespace(multiplex_profiles=True))
runner.session_authorities = SimpleNamespace(for_home=lambda home: by_home.get(Path(home).resolve()))
for home in (launch, b):
- by_home[home.resolve()] = SimpleNamespace(profile_id=str(home), instance_id=f"i-{home.name}", runner=runner)
- return by_home[launch.resolve()]
-
-
-def _socket(authority, ticket_home=None):
- async def close(code=None):
- raise AssertionError(f"socket closed with {code}")
- return SimpleNamespace(
- app=SimpleNamespace(state=SimpleNamespace(session_authority=authority)), scope={},
- _hermes_auth_identity={"user_id": "u", "provider": "session-token"},
- _hermes_ticket_profile_home=None if ticket_home is None else str(ticket_home), close=close)
+ db = SessionDB(home / "state.db")
+ dbs.append(db)
+ store = SessionStore(config=GatewayConfig(), sessions_dir=home / "sessions")
+ store._db = db
+ runner.session_store = store
+ by_home[home.resolve()] = SessionAuthority(runner, profile_id=str(home), instance_id="first", db=db,
+ epoch=begin_runtime_epoch(db, instance_id="first"))
+ runner.session_authority = by_home[launch.resolve()]
+
+ portal_hits = []
+
+ def http_edge(request):
+ portal_hits.append(request.url.host)
+ return httpx.Response(200, json={"paid_service_access": True})
+
+ real_client = httpx.Client
+ monkeypatch.setattr(httpx, "Client", lambda *a, **k: real_client(*a, **{**k, "transport": httpx.MockTransport(http_edge)}))
+
+ def urlopen(request, *args, **kwargs):
+ portal_hits.append(httpx.URL(request.full_url).host)
+ response = io.BytesIO(json.dumps({"ok": True, "balanceUsd": "0", "role": "MEMBER"}).encode())
+ response.status = 200
+ return response
+ monkeypatch.setattr("urllib.request.urlopen", urlopen)
-
-def _portal_seen_by_socket(monkeypatch, ws) -> list:
- """Run ``gateway_ws`` with a handler that resolves the Portal override the way a legacy billing
- handler does: on a worker thread copied from the socket's context."""
from hermes_cli import mcp_startup
- from tui_gateway import ws as tui_ws
from hermes_cli.web_routers import chat_ws
async def allowed(*_a, **_k):
return True
+ monkeypatch.setattr(chat_ws, "_close_unless_sidecar_allowed", allowed)
+ monkeypatch.setattr(mcp_startup, "start_deferred_mcp_discovery_now", lambda: None)
+ try:
+ yield SimpleNamespace(launch=launch, b=b, authority=runner.session_authority, portal_hits=portal_hits)
+ finally:
+ secret_scope.set_multiplex_active(previous)
+ for db in dbs:
+ db.close()
- seen = []
- async def handler(*_a, **_k):
- from hermes_cli.auth_nous import _nous_portal_env_override
- seen.append(await asyncio.to_thread(_nous_portal_env_override))
+class _Socket:
+ """An accepted ``/api/ws`` connection carrying what the upgrade gate stamps on a Webapp ticket."""
- monkeypatch.setattr(chat_ws, "_close_unless_sidecar_allowed", allowed)
- monkeypatch.setattr(mcp_startup, "start_deferred_mcp_discovery_now", lambda: None)
- monkeypatch.setattr(tui_ws, "handle_ws", handler)
+ def __init__(self, authority, frames, ticket_home=None):
+ self.app = SimpleNamespace(state=SimpleNamespace(session_authority=authority))
+ self.scope, self.client, self.closed, self.sent = {}, None, None, []
+ self._hermes_auth_identity = {"user_id": "owner", "provider": "session-token"}
+ self._hermes_ticket_profile_home = None if ticket_home is None else str(ticket_home)
+ self._frames = [json.dumps(frame) for frame in frames]
+ self._answered = asyncio.Event()
+
+ async def accept(self, subprotocol=None):
+ pass
+
+ async def close(self, code=None):
+ self.closed = code
+
+ async def send_text(self, text):
+ frame = json.loads(text)
+ self.sent.append(frame)
+ if frame.get("id") is not None:
+ self._answered.set()
+
+ async def receive_text(self):
+ if self._frames:
+ return self._frames.pop(0)
+ await asyncio.wait_for(self._answered.wait(), 20)
+ raise WebSocketDisconnect(1000)
+
+ def reply(self, req_id):
+ return next(frame for frame in self.sent if frame.get("id") == req_id)
+
+
+def _billing_state_over_socket(gateway, ticket_home):
+ from hermes_cli.web_routers import chat_ws
+ ws = _Socket(gateway.authority, [{"jsonrpc": "2.0", "id": "bill", "method": "billing.state", "params": {}}],
+ ticket_home)
+ gateway.portal_hits.clear()
asyncio.run(chat_ws.gateway_ws(ws))
- return seen
+ assert ws.closed is None, ws.closed
+ return ws.reply("bill"), list(gateway.portal_hits)
-def test_webapp_socket_reads_the_launch_profiles_portal_override_in_its_scope(two_homes, monkeypatch, caplog):
- launch, b = two_homes
- authority = _gateway(launch, b)
+def test_billing_state_on_a_webapp_socket_reaches_its_tickets_profile_portal(gateway, caplog):
+ with caplog.at_level(logging.WARNING):
+ seen = [_billing_state_over_socket(gateway, home) for home in (gateway.b, gateway.launch, gateway.b)]
- assert _portal_seen_by_socket(monkeypatch, _socket(authority)) == [LAUNCH_PORTAL]
+ for (reply, hits), label in zip(seen, ("b", "launch", "b")):
+ assert reply["result"]["logged_in"] is True, reply
+ assert hits and set(hits) == {f"{label}-portal.invalid"}, (label, hits)
assert "no profile secret scope" not in caplog.text
-def test_webapp_socket_for_a_served_profile_reads_that_profiles_override(two_homes, monkeypatch, caplog):
- launch, b = two_homes
- authority = _gateway(launch, b)
+def test_a_profile_ticket_with_no_authority_bound_is_refused_not_served_as_the_launch_profile(gateway):
+ from hermes_cli.web_routers import chat_ws
+ ws = _Socket(None, [{"jsonrpc": "2.0", "id": "bill", "method": "billing.state", "params": {}}], gateway.b)
- seen = [_portal_seen_by_socket(monkeypatch, _socket(authority, home)) for home in (launch, b, launch)]
+ asyncio.run(chat_ws.gateway_ws(ws))
- assert seen == [[LAUNCH_PORTAL], [B_PORTAL], [LAUNCH_PORTAL]]
- assert "no profile secret scope" not in caplog.text
+ assert ws.closed == 1013
+ assert ws.sent == [] and gateway.portal_hits == []
diff --git a/tests/tui_gateway/test_legacy_fallback_launch_explicit_profile.py b/tests/tui_gateway/test_legacy_fallback_launch_explicit_profile.py
new file mode 100644
index 00000000000..a9c0c705f6c
--- /dev/null
+++ b/tests/tui_gateway/test_legacy_fallback_launch_explicit_profile.py
@@ -0,0 +1,78 @@
+"""A launch-profile socket that names another profile runs that verb in the named profile.
+
+``chat_ws.gateway_ws`` runs a launch-profile Webapp socket in the launch profile's scope, so a legacy
+verb sent with an explicit ``profile`` was answered in that scope unless its handler binds
+``profile`` itself (``_profile_scoped``): one that ignores it read the launch profile's secrets
+instead of refusing the unscoped read. ``dispatch_legacy`` binds the named profile, as it already
+did for a socket whose ticket names a non-launch profile.
+"""
+import threading
+import types
+
+import pytest
+
+LAUNCH_PORTAL = "https://launch-portal.invalid"
+BEE_PORTAL = "https://bee-portal.invalid"
+
+
+def homes(tmp_path, monkeypatch):
+ from agent import secret_scope
+ from tui_gateway import launch_profile_policy, server
+ launch = tmp_path / "root"
+ bee = launch / "profiles" / "bee"
+ bee.mkdir(parents=True)
+ (launch / ".env").write_text(f"HERMES_PORTAL_BASE_URL={LAUNCH_PORTAL}\n")
+ (bee / ".env").write_text(f"HERMES_PORTAL_BASE_URL={BEE_PORTAL}\n")
+ for home in (launch, bee):
+ (home / "config.yaml").write_text("{}\n")
+ monkeypatch.setenv("HERMES_HOME", str(launch))
+ monkeypatch.setenv("HERMES_PORTAL_BASE_URL", LAUNCH_PORTAL) # the launch process loaded its own .env
+ monkeypatch.setattr(server, "_hermes_home", launch)
+ monkeypatch.setattr(server, "_served_profile_homes", set())
+ monkeypatch.setattr(launch_profile_policy, "_snapshot", None)
+ previous = secret_scope.is_multiplex_active()
+ launch_profile_policy.activate_multi_profile_hosting()
+ seen = []
+
+ def unwrapped_secret_read(rid, params):
+ from agent.secret_scope import get_secret
+ from hermes_constants import get_hermes_home
+ seen.append((get_hermes_home().resolve(), get_secret("HERMES_PORTAL_BASE_URL")))
+ return server._ok(rid, {})
+ monkeypatch.setitem(server._methods, "probe.portal", unwrapped_secret_read)
+ yield server, launch, bee, seen
+ secret_scope.set_multiplex_active(previous)
+
+
+def _call_on_launch_socket(server, launch, params):
+ """One legacy fallback request on a socket whose ticket is the launch profile's, in the scope
+ ``gateway_ws`` binds for it."""
+ from gateway.runtime_bootstrap import _PURPOSE_CAPABILITIES
+ from tui_gateway.launch_profile_policy import launch_profile_scope_if_multiplexed
+ from tui_gateway.ws_legacy_fallback import dispatch_legacy
+ actor = types.SimpleNamespace(profile_id=str(launch), capabilities=frozenset(_PURPOSE_CAPABILITIES["interactive"]))
+ written, done = [], threading.Event()
+ transport = types.SimpleNamespace(write=lambda frame: written.append(frame) or done.set() or True)
+ with launch_profile_scope_if_multiplexed():
+ reply = dispatch_legacy(server, {"jsonrpc": "2.0", "id": 1, "method": "probe.portal", "params": params},
+ transport, actor)
+ return reply if reply is not None else (done.wait(10) and written[0])
+
+
+def test_explicit_profile_on_a_launch_socket_reads_that_profiles_secrets(homes):
+ server, launch, bee, seen = homes
+
+ for params in ({"profile": "bee"}, {}, {"profile": "bee"}):
+ assert "result" in _call_on_launch_socket(server, launch, params)
+
+ assert seen == [(bee.resolve(), BEE_PORTAL), (launch.resolve(), LAUNCH_PORTAL), (bee.resolve(), BEE_PORTAL)]
+
+
+def test_explicit_profile_that_does_not_resolve_is_refused_before_the_handler(homes):
+ server, launch, _bee, seen = homes
+
+ reply = _call_on_launch_socket(server, launch, {"profile": "missing"})
+
+ assert reply["error"]["code"] == 4064, reply
+ assert seen == []
diff --git a/tui_gateway/ws_legacy_fallback.py b/tui_gateway/ws_legacy_fallback.py
index 7f1baed3f74..5e0e53c9cf7 100644
--- a/tui_gateway/ws_legacy_fallback.py
+++ b/tui_gateway/ws_legacy_fallback.py
@@ -80,6 +80,24 @@ def _foreign_profile_home(server: Any, profile_id: Any) -> str | None:
return str(home)
+def _unavailable(req: dict) -> dict:
+ return {"jsonrpc": "2.0", "id": req.get("id"), "error": {"code": 4064, "message": "profile unavailable"}}
+
+
+def _explicit_profile_request(server: Any, req: dict) -> tuple[dict, str | None] | None:
+ """The home an explicit ``profile`` param names (Desktop's host-scoped routing): the request
+ plus that home ("" = launch), an error frame and None when the name does not resolve here, or
+ None when the request names no profile."""
+ params = req.get("params")
+ if not isinstance(params, dict) or not (explicit := str(params.get("profile") or "").strip()):
+ return None
+ try:
+ named = server._profile_home(explicit)
+ except (OSError, ValueError): # ProfileUnavailableError is a ValueError
+ return _unavailable(req), None
+ return req, str(named) if named else ""
+
+
def _ticket_profile_request(server: Any, req: dict, home: str) -> tuple[dict, str | None]:
"""Bind a non-launch ticket's profile into a legacy verb (N86). The verb runs in the ticket's
home, or in the one an explicit ``profile`` names (Desktop's host-scoped routing), so handlers
@@ -90,13 +108,9 @@ def _ticket_profile_request(server: Any, req: dict, home: str) -> tuple[dict, st
from hermes_constants import profile_name_for_home
from tui_gateway.contracts.registry import METHODS
params = req.get("params") if isinstance(req.get("params"), dict) else {}
- refused = {"jsonrpc": "2.0", "id": req.get("id"), "error": {"code": 4064, "message": "profile unavailable"}}
- if explicit := str(params.get("profile") or "").strip():
- try:
- named = server._profile_home(explicit)
- except (OSError, ValueError): # ProfileUnavailableError is a ValueError
- return refused, None
- return req, str(named) if named else ""
+ refused = _unavailable(req)
+ if (explicit := _explicit_profile_request(server, req)) is not None:
+ return explicit
contract = METHODS.get(req.get("method"))
if contract is None or "profile" not in contract.params.model_fields:
return req, home
@@ -153,6 +167,16 @@ def dispatch_legacy(server: Any, req: dict, transport: Any, actor: Any) -> dict
return req
if target:
scope = server._session_profile_runtime_scope({"profile_home": target})
+ elif (req.get("method") not in _SESSION_FALLBACK_ALLOWED
+ and (explicit := _explicit_profile_request(server, req)) is not None):
+ # A launch-profile socket runs in the launch scope (``chat_ws.gateway_ws``), so a verb that
+ # names another profile is bound to it here: a handler that ignores ``profile`` would
+ # otherwise read the launch profile's secrets instead of refusing an unscoped read.
+ req, target = explicit
+ if target is None:
+ return req
+ if target:
+ scope = server._session_profile_runtime_scope({"profile_home": target})
token = _connection_profile_home.set(home)
try:
with scope: