The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): resolve slash gating from the bot-owning profile in slash_access (#121705, salvage #121722)
teknium19462098499ca
diff --git a/gateway/run_busy.py b/gateway/run_busy.pyindex ae2dc63a46e..36d84874159 100644--- a/gateway/run_busy.py+++ b/gateway/run_busy.py@@ -1097,9 +1097,10 @@ 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_runner_sourceif not canonical_cmd:return None- policy = self._slash_access_policy_for_source(source)+ policy = policy_for_runner_source(self, source)if not policy.enabled or policy.can_run(source.user_id, canonical_cmd):return Nonelogger.info(diff --git a/gateway/slash_access.py b/gateway/slash_access.pyindex 7e8b57f13c2..0d69748e217 100644--- a/gateway/slash_access.py+++ b/gateway/slash_access.py@@ -52,6 +52,10 @@ class SlashAccessPolicy:_DISABLED_POLICY = SlashAccessPolicy(enabled=False, admin_user_ids=frozenset(), user_allowed_commands=frozenset())+# Gated with nobody on the admin list: only the ``_ALWAYS_ALLOWED_FOR_USERS`` floor runs.+_FAIL_CLOSED_POLICY = SlashAccessPolicy(+ enabled=True, admin_user_ids=frozenset(), user_allowed_commands=frozenset()+)def _coerce_list(raw: Any, normalize: Callable[[str], str] = str) -> FrozenSet[str]:@@ -127,3 +131,28 @@ def policy_for_source(gateway_config: Any, source: Any) -> SlashAccessPolicy:__all__ = ["SlashAccessPolicy", "policy_from_extra", "policy_for_source"]++++def policy_for_runner_source(runner: Any, source: Any) -> SlashAccessPolicy:+ """Slash-gating policy from the profile whose bot received ``source``.++ Under ``multiplex_profiles`` the runner's ``config`` is the launch profile's alone, so a platform+ configured only in a secondary profile had no PlatformConfig there and every caller came back+ unrestricted (#121705). Authorization follows the transport (bot-owning) profile, the owner+ ``RoutingIdentity.authorization_home`` already names; a served profile whose config is not cached+ fails closed instead of inheriting the launch profile's open policy.+ """+ config = getattr(runner, "config", None)+ if not getattr(config, "multiplex_profiles", False) or source is None:+ return policy_for_source(config, source)+ from gateway.session_identity import identity_of++ identity = identity_of(source)+ owner = identity.transport_profile if identity is not None else getattr(source, "profile", None)+ primary = getattr(runner, "_primary_profile_name", None) or "default"+ if owner and owner != primary:+ config = (getattr(runner, "_profile_configs", None) or {}).get(owner)+ if config is None:+ return _FAIL_CLOSED_POLICY+ return policy_for_source(config, source)diff --git a/gateway/slash_commands.py b/gateway/slash_commands.pyindex 505c5fb3f37..0dcca288888 100644--- a/gateway/slash_commands.py+++ b/gateway/slash_commands.py@@ -182,48 +182,6 @@ 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@@ -368,8 +326,9 @@ 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_runner_sourcesource = event.source- policy = self._slash_access_policy_for_source(source)+ policy = policy_for_runner_source(self, 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"@@ -640,10 +599,11 @@ 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_runner_sourcesource = event.source- # ``getattr``: partially-constructed runners (``GatewayRunner.__new__`` in tests) have- # no ``config``; the resolver preserves the legacy ungated behavior outside multiplexing.- policy = self._slash_access_policy_for_source(source)+ # Partially-constructed runners (``GatewayRunner.__new__`` in tests) have no ``config``;+ # policy_for_source treats None as ungated.+ policy = policy_for_runner_source(self, 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 {}@@ -975,12 +935,13 @@ 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_runner_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 = self._slash_access_policy_for_source(event.source)+ policy = policy_for_runner_source(self, 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 ac00dfe23ec..e1d1be700c6 100644--- a/gateway/slash_commands_login.py+++ b/gateway/slash_commands_login.py@@ -13,6 +13,7 @@ from typing import Anyfrom uuid import uuid4from gateway.run_agent_cache import _first_agent+from gateway.slash_access import policy_for_runner_sourcefrom hermes_cli import anon_authlogger = logging.getLogger("gateway.run")@@ -70,7 +71,7 @@ class GatewayLoginCommandsMixin:if not paired_dm:return anon_auth.LOGIN_DM_ONLY- policy = self._slash_access_policy_for_source(src)+ policy = policy_for_runner_source(self, 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 f6b61cc3127..efa2d42f1f7 100644--- a/gateway/slash_commands_session.py+++ b/gateway/slash_commands_session.py@@ -305,7 +305,8 @@ 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:- policy = self._slash_access_policy_for_source(source)+ from gateway.slash_access import policy_for_runner_source+ policy = policy_for_runner_source(self, 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 934c2e5ad9f..2b8688097be 100644--- a/tests/gateway/test_slash_access_dispatch.py+++ b/tests/gateway/test_slash_access_dispatch.py@@ -143,7 +143,8 @@ async def test_whoami_non_admin_lists_runnable_commands():@pytest.mark.asyncioasync def test_secondary_profile_slash_policy_uses_its_own_config():- """the launch profile's empty policy must not bypass a routed profile's gate."""+ """#121705: a bot configured only in a secondary profile is gated by THAT profile's+ ``allow_admin_from``; the launch profile's empty policy must not make it unrestricted."""runner = _make_runner(multiplex_profiles=True)runner._profile_configs["beta"] = GatewayConfig(platforms={@@ -163,33 +164,24 @@ async def test_secondary_profile_slash_policy_uses_its_own_config():assert runner._check_slash_access(admin, "restart") is Noneassert 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"),+ # The launch profile's own (ungated) bot stays ungated ...+ assert runner._check_slash_access(_make_source(user_id="user"), "restart") is None+ # ... including a turn ROUTED to beta: ``allow_admin_from`` is per bot, so the bot-owning+ # (transport) profile's config decides, the owner ``authorization_home`` already names.+ routed = _make_source(user_id="user", profile="beta")+ routed._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+ assert runner._check_slash_access(routed, "restart") is None-async def test_missing_secondary_profile_config_fails_closed():- """a missing routed-profile config must not inherit the launch profile's open policy."""+def test_missing_secondary_profile_config_fails_closed():+ """A served profile whose config is not cached 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")+ assert runner._check_slash_access(_make_source(user_id="user", profile="beta"), "help") is None@pytest.mark.asyncio