The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): use routed profile for slash access checks
Mohamad Kansod067d2fdc39a
diff --git a/gateway/run_busy.py b/gateway/run_busy.pyindex b7d5f8b1c7c..ae2dc63a46e 100644--- a/gateway/run_busy.py+++ b/gateway/run_busy.py@@ -1097,10 +1097,9 @@ class GatewayBusySessionMixin:def _check_slash_access(self, source: SessionSource, canonical_cmd: str) -> Optional[str]:"""Denial message if ``source`` cannot run ``canonical_cmd``, else None (both dispatch pathsuse it so an in-flight agent can't bypass admin gating; no ``allow_admin_from`` → None)."""- from gateway.slash_access import policy_for_source as _policy_for_sourceif not canonical_cmd:return None- policy = _policy_for_source(self.config, source)+ policy = self._slash_access_policy_for_source(source)if not policy.enabled or policy.can_run(source.user_id, canonical_cmd):return Nonelogger.info(diff --git a/gateway/slash_commands.py b/gateway/slash_commands.pyindex 7539d7ce7d3..505c5fb3f37 100644--- a/gateway/slash_commands.py+++ b/gateway/slash_commands.py@@ -182,6 +182,48 @@ class GatewaySlashCommandsMixin(async_session_store: AsyncSessionStore# ------------------------------------------------------------------ shared helpers+ def _slash_access_policy_for_source(self, source):+ """resolve slash permissions from the profile that serves ``source``.++ a multiplexed runner's ``self.config`` belongs only to its launch profile. routed+ profiles have their own cached gateway config; if that config is missing, fail closed+ instead of treating the source as unrestricted.+ """+ from gateway.slash_access import SlashAccessPolicy, policy_for_source++ config = getattr(self, "config", None)+ if not getattr(config, "multiplex_profiles", False):+ return policy_for_source(config, source)+ fail_closed = SlashAccessPolicy(+ enabled=True,+ admin_user_ids=frozenset(),+ user_allowed_commands=frozenset(),+ )+ if source is None:+ return fail_closed++ try:+ from gateway.session_identity import identity_of+ identity = identity_of(source)+ profile_name = getattr(identity, "runtime_profile", None)+ except Exception:+ return fail_closed+ profile_name = (profile_name or getattr(source, "profile", None) or "").strip()+ if not profile_name:+ profile_name = (getattr(self, "_primary_profile_name", None) or "").strip()++ primary_profile = (getattr(self, "_primary_profile_name", None) or "").strip()+ if profile_name and profile_name == primary_profile:+ profile_config = config+ elif profile_name:+ profile_config = (getattr(self, "_profile_configs", None) or {}).get(profile_name)+ else:+ profile_config = None++ if profile_config is None:+ return fail_closed+ return policy_for_source(profile_config, source)+def _cached_agent_for(self, session_key: str, *, lockless_fallback: bool = False):"""Peek the cached AIAgent for *session_key* without evicting it, or None. Entries are``(agent, signature, ...)`` tuples (bare agents from test doubles accepted). Historical callers@@ -326,9 +368,8 @@ class GatewaySlashCommandsMixin(async def _handle_whoami_command(self, event: MessageEvent) -> str:"""Handle /whoami — platform, DM-vs-group scope, tier and runnable commands (always allowed)."""- from gateway.slash_access import policy_for_sourcesource = event.source- policy = policy_for_source(self.config, source)+ policy = self._slash_access_policy_for_source(source)platform = source.platform.value if source and source.platform else "?"chat_type = ((source.chat_type if source else "") or "dm").lower()scope = "DM" if chat_type in {"dm", "direct", "private", ""} else "group/channel"@@ -599,11 +640,10 @@ class GatewaySlashCommandsMixin("""``allowed_commands`` for /help and /commands when the caller is a gated non-admin:the slash-access floor + ``user_allowed_commands`` (mirrors /whoami), so the catalognever advertises commands ``_check_slash_access`` would refuse. Admins / ungated -> {}."""- from gateway.slash_access import policy_for_sourcesource = event.source# ``getattr``: partially-constructed runners (``GatewayRunner.__new__`` in tests) have- # no ``config``; policy_for_source treats None as ungated.- policy = policy_for_source(getattr(self, "config", None), source)+ # no ``config``; the resolver preserves the legacy ungated behavior outside multiplexing.+ policy = self._slash_access_policy_for_source(source)if policy.enabled and not policy.is_admin(source.user_id if source else None):return {"allowed_commands": {"help", "whoami", *policy.user_allowed_commands}}return {}@@ -935,13 +975,12 @@ class GatewaySlashCommandsMixin(async def _handle_approvals_command(self, event: MessageEvent) -> str:"""Show or persist the profile-wide dangerous-command approval mode."""- from gateway.slash_access import policy_for_sourcefrom hermes_cli.approval_mode import run_approval_mode_commandrequested = event.get_command_args().strip() or None# This mutates profile-wide security policy. The central slash gate can allow selected# commands to non-admin users, so enforce admin again at this side-effect boundary.# Unconfigured policies remain unrestricted.- policy = policy_for_source(self.config, event.source)+ policy = self._slash_access_policy_for_source(event.source)if requested and not policy.is_admin(event.source.user_id):return "Only gateway admins can change the persistent approval mode."# Approval checks load config dynamically; do not evict the cached agent or alter itsdiff --git a/gateway/slash_commands_login.py b/gateway/slash_commands_login.pyindex c16f7f1ba4a..ac00dfe23ec 100644--- a/gateway/slash_commands_login.py+++ b/gateway/slash_commands_login.py@@ -13,7 +13,6 @@ from typing import Anyfrom uuid import uuid4from gateway.run_agent_cache import _first_agent-from gateway.slash_access import policy_for_sourcefrom hermes_cli import anon_authlogger = logging.getLogger("gateway.run")@@ -71,7 +70,7 @@ class GatewayLoginCommandsMixin:if not paired_dm:return anon_auth.LOGIN_DM_ONLY- policy = policy_for_source(self.config, src)+ policy = self._slash_access_policy_for_source(src)if policy.enabled and not policy.is_admin(getattr(src, "user_id", None)):return anon_auth.LOGIN_NOT_ALLOWEDdiff --git a/gateway/slash_commands_session.py b/gateway/slash_commands_session.pyindex 1975312bc69..f6b61cc3127 100644--- a/gateway/slash_commands_session.py+++ b/gateway/slash_commands_session.py@@ -305,8 +305,7 @@ class GatewaySessionCommandsMixin:Stricter than ``SlashAccessPolicy.is_admin()``, which is True for every caller when slashgating is DISABLED — the default config would make everyone cross-origin-capable (IDOR)."""try:- from gateway.slash_access import policy_for_source- policy = policy_for_source(self.config, source)+ policy = self._slash_access_policy_for_source(source)uid = getattr(source, "user_id", None)return bool(policy.enabled and uid and policy.is_admin(uid))except Exception:diff --git a/tests/gateway/test_slash_access_dispatch.py b/tests/gateway/test_slash_access_dispatch.pyindex 6cafa160385..934c2e5ad9f 100644--- a/tests/gateway/test_slash_access_dispatch.py+++ b/tests/gateway/test_slash_access_dispatch.py@@ -19,6 +19,7 @@ Coverage targets:from __future__ import annotationsfrom datetime import datetime+from pathlib import Pathfrom types import SimpleNamespacefrom unittest.mock import AsyncMock, MagicMock@@ -27,6 +28,7 @@ import pytestfrom gateway.config import GatewayConfig, Platform, PlatformConfigfrom gateway.platforms.event import MessageEventfrom gateway.session import SessionEntry, SessionSource, build_session_key+from gateway.session_identity import RoutingIdentitydef _make_source(@@ -35,6 +37,7 @@ def _make_source(user_id: str = "user1",chat_type: str = "dm",chat_id: str = "c1",+ profile: str | None = None,) -> SessionSource:return SessionSource(platform=platform,@@ -42,6 +45,7 @@ def _make_source(chat_id=chat_id,user_name=f"name-{user_id}",chat_type=chat_type,+ profile=profile,)@@ -50,11 +54,13 @@ def _make_event(text: str, source: SessionSource) -> MessageEvent:def _make_runner(*, platform_extra: dict | None = None,- platform: Platform = Platform.DISCORD):+ platform: Platform = Platform.DISCORD,+ multiplex_profiles: bool = False):from gateway.run import GatewayRunnerrunner = object.__new__(GatewayRunner)runner.config = GatewayConfig(+ multiplex_profiles=multiplex_profiles,platforms={platform: PlatformConfig(enabled=True,@@ -89,6 +95,8 @@ def _make_runner(*, platform_extra: dict | None = None,runner.session_store.rewrite_transcript = MagicMock()runner.session_store.update_session = MagicMock()runner._running_agents = {}+ runner._primary_profile_name = "primary"+ runner._profile_configs = {}runner._running_agents_ts = {}runner._session_run_generation = {}runner._pending_messages = {}@@ -133,6 +141,57 @@ async def test_whoami_non_admin_lists_runnable_commands():assert "/model" in result+async def test_secondary_profile_slash_policy_uses_its_own_config():+ """the launch profile's empty policy must not bypass a routed profile's gate."""+ runner = _make_runner(multiplex_profiles=True)+ runner._profile_configs["beta"] = GatewayConfig(+ platforms={+ Platform.DISCORD: PlatformConfig(+ enabled=True,+ extra={"allow_admin_from": ["admin"], "user_allowed_commands": ["status"]},+ )+ }+ )+ user = _make_source(user_id="user", profile="beta")+ denied = runner._check_slash_access(user, "restart")+ assert denied is not None and "⛔" in denied+ assert "Tier: user" in await runner._handle_whoami_command(_make_event("/whoami", user))+ assert runner._resume_caller_is_admin(user) is False++ admin = _make_source(user_id="admin", profile="beta")+ assert runner._check_slash_access(admin, "restart") is None+ assert runner._resume_caller_is_admin(admin) is True++ primary = _make_source(user_id="user")+ assert runner._check_slash_access(primary, "restart") is None++ pinned = _make_source(user_id="user", profile="primary")+ pinned._identity = RoutingIdentity(+ transport_profile="primary",+ runtime_profile="beta",+ authorization_home=Path("/profiles/primary"),+ runtime_home=Path("/profiles/beta"),+ )+ assert runner._check_slash_access(pinned, "restart") is not None+++async def test_missing_secondary_profile_config_fails_closed():+ """a missing routed-profile config must not inherit the launch profile's open policy."""+ runner = _make_runner(multiplex_profiles=True)+ denied = runner._check_slash_access(_make_source(user_id="user", profile="beta"), "restart")+ assert denied is not None and "⛔" in denied+++def test_missing_source_fails_closed_for_multiplexed_policy():+ runner = _make_runner(multiplex_profiles=True)+ policy = runner._slash_access_policy_for_source(None)+ assert policy.enabled+ assert not policy.can_run(None, "restart")+ assert policy.can_run(None, "help")++@pytest.mark.asyncioasync def test_help_non_admin_lists_only_runnable_commands():"""/help for a gated non-admin renders the floor + user_allowed_commands, never the