The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(discord): buttons stop accepting a user revoked after connect
pierrenode502df01d547f
diff --git a/plugins/platforms/discord/adapter.py b/plugins/platforms/discord/adapter.pyindex cff1603fa22..77d195ab1f3 100644--- a/plugins/platforms/discord/adapter.py+++ b/plugins/platforms/discord/adapter.py@@ -5099,6 +5099,20 @@ class DiscordAdapter(DiscordMediaMixin, DiscordThreadTitlesMixin, DiscordVoiceInif str(entry).strip().isdigit()}+ def _component_live_auth(self, interaction) -> Optional[bool]:+ """The gateway's live allowlist verdict for a component click, or None when no check is wired.+ Views hold the connect-time ``_allowed_user_ids``; a revoke run in another process+ (``hermes pairing revoke`` from the CLI or dashboard, a hand edit of .env) never reaches it,+ while the gateway check re-reads the allowlist on every call (Matrix approval reactions use+ the same check, #130920)."""+ if getattr(self, "_authorization_check", None) is None:+ return None+ user_id = str(getattr(getattr(interaction, "user", None), "id", "") or "")+ channel_id = getattr(interaction, "channel_id", None)+ chat_type = "dm" if getattr(interaction, "guild", None) is None else "group"+ return self._is_sender_authorized(+ user_id, chat_type, str(channel_id) if channel_id is not None else None)+def resolved_allowlist_user_ids(self) -> set:"""Numeric IDs from connect-time username resolution.The env mirror of ``_allowed_user_ids`` doesn't survive the per-turn .env hot-reload, so the@@ -5698,6 +5712,8 @@ class DiscordAdapter(DiscordMediaMixin, DiscordThreadTitlesMixin, DiscordVoiceIntry:channel = await self._resolve_channel(_prompt_target_id(chat_id, metadata))send_kwargs, view = build(channel)+ if view is not None:+ view.live_auth = self._component_live_authmsg = await channel.send(**send_kwargs)if view is not None:view._message = msg@@ -6373,10 +6389,14 @@ class DiscordAdapter(DiscordMediaMixin, DiscordThreadTitlesMixin, DiscordVoiceIndef _component_check_auth(interaction, allowed_user_ids: Optional[set], allowed_role_ids: Optional[set],+ live_auth: Optional[Callable[[Any], Optional[bool]]] = None,) -> bool:"""Shared user-or-role OR authorization for component button clicks.Allow on: DISCORD/GATEWAY_ALLOW_ALL_USERS, user in DISCORD/GATEWAY_ALLOWED_USERS, a role in therole allowlist, or pairing-store approval. Role allowlist with no ``roles`` (DM) rejects (fail closed).+ ``allowed_user_ids`` is the adapter's connect-time snapshot: a user found only there is confirmed+ with ``live_auth`` (the gateway's per-call check), and an explicit False falls through to the role+ and pairing grants."""user = getattr(interaction, "user", None)if user is None or getattr(user, "id", None) is None:@@ -6405,7 +6425,9 @@ def _component_check_auth(except AttributeError:uid = ""if has_users:- if "*" in user_set or (uid and uid in user_set):+ if "*" in user_set:+ return True+ if uid and uid in user_set and (live_auth is None or live_auth(interaction) is not False):return Trueif has_roles:roles_attr = getattr(user, "roles", None)@@ -6461,11 +6483,14 @@ def _define_discord_view_classes() -> None:super().__init__(timeout=timeout)self.allowed_user_ids = allowed_user_idsself.allowed_role_ids = allowed_role_ids or set()+ # The adapter's live allowlist check, bound in ``_send_prompt``.+ self.live_auth = Noneself.resolved = Falseself._message = Nonedef _check_auth(self, interaction: discord.Interaction) -> bool:- return _component_check_auth(interaction, self.allowed_user_ids, self.allowed_role_ids)+ return _component_check_auth(+ interaction, self.allowed_user_ids, self.allowed_role_ids, live_auth=self.live_auth)async def _gate(self, interaction: discord.Interaction, *, resolved_msg: Optional[str], unauth_msg: str) -> bool:"""Reject (ephemerally) an already-resolved or unauthorized click; True when it may proceed."""diff --git a/tests/gateway/test_discord_component_auth.py b/tests/gateway/test_discord_component_auth.pyindex f5a9051c4f0..28680cbf29f 100644--- a/tests/gateway/test_discord_component_auth.py+++ b/tests/gateway/test_discord_component_auth.py@@ -13,13 +13,17 @@ handling, and fail-closed behavior so the parity cannot regress."""from types import SimpleNamespace+from unittest.mock import AsyncMockimport pytest+from gateway.config import PlatformConfig+# Trigger the shared discord mock from tests/gateway/conftest.py before# importing the production module.from plugins.platforms.discord.adapter import ( # noqa: E402ClarifyChoiceView,+ DiscordAdapter,ExecApprovalView,ModelPickerView,SlashConfirmView,@@ -89,6 +93,43 @@ def test_component_check_explicit_allow_all_passes(monkeypatch, env_name, env_va# ── user allowlist ─────────────────────────────────────────────────────────[email protected](("verdict", "expected"), [(None, True), (True, True), (False, False)])+def test_snapshot_user_is_confirmed_with_the_live_check(verdict, expected):+ # The user set is the adapter's connect-time snapshot; None means no live check is wired.+ seen = []++ def live_auth(interaction):+ seen.append(interaction.user.id)+ return verdict++ assert _component_check_auth(_interaction(11111), {"11111"}, set(), live_auth=live_auth) is expected+ assert seen == [11111]+++def test_live_revoke_keeps_the_role_grant():+ interaction = _interaction(11111, role_ids=[42])+ assert _component_check_auth(interaction, {"11111"}, {42}, live_auth=lambda _i: False) is True+++async def test_approval_buttons_follow_a_revoke_made_after_connect():+ # `hermes pairing revoke` in another process rewrites .env and the pairing store, never the+ # adapter's snapshot; the card's buttons must follow the gateway's per-call check instead.+ adapter = DiscordAdapter(PlatformConfig(enabled=True, token="***"))+ adapter._allowed_user_ids = {"11111"}+ live = {"11111": True}+ adapter.set_authorization_check(lambda user_id, chat_type=None, chat_id=None, **_: live.get(user_id, False))+ channel = SimpleNamespace(send=AsyncMock(return_value=SimpleNamespace(id=1)))+ adapter._client = SimpleNamespace(get_channel=lambda _chat_id: channel, fetch_channel=AsyncMock())++ result = await adapter.send_exec_approval(chat_id="555", command="make deploy", session_key="discord:555")+ assert result.success is True+ view = channel.send.call_args.kwargs["view"]+ assert view._check_auth(_interaction(11111)) is True+ live["11111"] = False+ assert view._check_auth(_interaction(11111)) is False++# ── role allowlist OR semantics ────────────────────────────────────────────