Skip to content

The agent that grows with you

fix(discord): a button click in a thread gets the thread's authorization verdict

calvinnwq2712a096db50
diff --git a/plugins/platforms/discord/adapter.py b/plugins/platforms/discord/adapter.py
index f5d39af68d2..a31f99c97d3 100644
--- a/plugins/platforms/discord/adapter.py
+++ b/plugins/platforms/discord/adapter.py
@@ -5046,11 +5046,10 @@ class DiscordAdapter(DiscordAuthorizationMixin, DiscordMediaMixin, DiscordThread
def _component_live_auth(self, interaction) -> Optional[bool]:
"""The gateway's live allowlist verdict for a component click (None when no check is wired):
an out-of-process revoke never reaches the connect-time ``_allowed_user_ids`` snapshot."""
+ from plugins.platforms.discord.adapter_component_auth import component_chat_context
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)
+ chat_type, chat_id, thread_id = component_chat_context(interaction, discord.Thread)
+ return self._is_sender_authorized(user_id, chat_type, chat_id, thread_id=thread_id)
def resolved_allowlist_user_ids(self) -> set:
"""Numeric IDs from connect-time username resolution.
diff --git a/plugins/platforms/discord/adapter_component_auth.py b/plugins/platforms/discord/adapter_component_auth.py
index 79927b446d3..18094ad5c2f 100644
--- a/plugins/platforms/discord/adapter_component_auth.py
+++ b/plugins/platforms/discord/adapter_component_auth.py
@@ -6,6 +6,18 @@ from typing import Any, Callable, Optional
from gateway.platforms._shared import platform_gate_env as _scoped_gate_env
+def component_chat_context(interaction, thread_cls) -> tuple[str, Optional[str], Optional[str]]:
+ """``(chat_type, chat_id, thread_id)`` of a click, labelled like message intake labels the
+ same channel: a click in a thread gets the thread's verdict, not a channel's."""
+ channel_id = getattr(interaction, "channel_id", None)
+ chat_id = str(channel_id) if channel_id is not None else None
+ if getattr(interaction, "guild", None) is None:
+ return "dm", chat_id, None
+ if isinstance(getattr(interaction, "channel", None), thread_cls):
+ return "thread", chat_id, chat_id
+ return "group", chat_id, None
+
+
def _component_check_auth(
interaction, allowed_user_ids: Optional[set], allowed_role_ids: Optional[set],
live_auth: Optional[Callable[[Any], Optional[bool]]] = None,
diff --git a/tests/gateway/test_discord_config_allowlist_multiplex.py b/tests/gateway/test_discord_config_allowlist_multiplex.py
new file mode 100644
index 00000000000..930c7eb319a
--- /dev/null
+++ b/tests/gateway/test_discord_config_allowlist_multiplex.py
@@ -0,0 +1,122 @@
+"""A Discord allowlist written only in config.yaml (``discord.allow_from``) under multiplex.
+
+The YAML bridge copies ``allow_from`` into ``os.environ['DISCORD_ALLOWED_USERS']``, but multiplexed
+authorization reads each profile's own secret scope and never falls back to ``os.environ``. The
+user must still be admitted wherever the adapter's own intake admits them: guild channels, threads
+and component clicks. Real config loader, real ``GatewayRunner`` auth callback, real adapter.
+"""
+
+import os
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+from gateway.config import Platform
+
+USER = "202965502740398090"
+STRANGER = "111111111111111111"
+CHANNEL = "1501061216548683885"
+THREAD = "1554296921646960760"
+
+
+def config_only_discord(monkeypatch):
+ """Multiplexed default profile; the Discord allowlist lives only in config.yaml."""
+ from agent import secret_scope
+
+ home = Path(os.environ["HERMES_HOME"])
+ (home / "config.yaml").write_text(
+ "gateway:\n multiplex_profiles: true\n"
+ f"discord:\n require_mention: true\n allow_from: {USER}\n",
+ encoding="utf-8",
+ )
+ (home / ".env").write_text("DISCORD_BOT_TOKEN=test-token\n", encoding="utf-8")
+ monkeypatch.delenv("DISCORD_ALLOWED_USERS", raising=False)
+ prev = secret_scope.is_multiplex_active()
+ secret_scope.set_multiplex_active(True)
+ yield home
+ secret_scope.set_multiplex_active(prev)
+
+
+def _wire(home):
+ from gateway.config import load_gateway_config
+ from gateway.pairing import PairingStore
+ from gateway.run import GatewayRunner
+ from plugins.platforms.discord.adapter import DiscordAdapter
+
+ runner = object.__new__(GatewayRunner)
+ runner.config = load_gateway_config()
+ runner.pairing_store = PairingStore(profile="default")
+ runner.pairing_stores = {"default": runner.pairing_store}
+ runner._primary_profile_name = "default"
+ runner._profile_adapters = {}
+ adapter = DiscordAdapter(runner.config.platforms[Platform.DISCORD])
+ runner.adapters = {Platform.DISCORD: adapter}
+ adapter.set_authorization_check(runner._make_adapter_auth_check(Platform.DISCORD))
+ return runner, adapter
+
+
+def _click(user_id, channel):
+ return SimpleNamespace(
+ user=SimpleNamespace(id=int(user_id), roles=[]),
+ channel_id=int(getattr(channel, "id", THREAD)),
+ guild=SimpleNamespace(id=1),
+ channel=channel,
+ )
+
+
+def _thread():
+ import discord
+
+ thread = object.__new__(discord.Thread)
+ return thread
+
+
+def test_button_click_in_a_thread_follows_the_thread_message_verdict(config_only_discord):
+ """Regression: #133213 checked every guild click as ``group``, so an allowlisted user who can
+ chat in a thread was told "This bot is private" when clicking Allow Once there."""
+ from plugins.platforms.discord.adapter_component_auth import _component_check_auth
+
+ _runner, adapter = _wire(config_only_discord)
+ snapshot = adapter._get_allowed_users()
+ assert USER in snapshot
+
+ click = _click(USER, _thread())
+ assert _component_check_auth(click, snapshot, set(), live_auth=adapter._component_live_auth) is True
+ stranger = _click(STRANGER, _thread())
+ assert _component_check_auth(stranger, snapshot, set(), live_auth=adapter._component_live_auth) is False
+
+
+def test_button_click_in_a_thread_resolves_a_thread_scoped_route(monkeypatch):
+ """A click carries the thread id, so a ``thread_id`` profile route matches it the same way it
+ matches the thread's messages: a user paired only in the routed profile can answer the card."""
+ from agent import secret_scope
+ from gateway.pairing import PairingStore
+
+ home = Path(os.environ["HERMES_HOME"])
+ (home / "profiles" / "kody").mkdir(parents=True)
+ (home / "profiles" / "kody" / ".env").write_text("", encoding="utf-8")
+ (home / "config.yaml").write_text(
+ "gateway:\n multiplex_profiles: true\ndiscord:\n require_mention: true\n"
+ f"profile_routes:\n - name: kody-thread\n platform: discord\n profile: kody\n"
+ f" thread_id: \"{THREAD}\"\n",
+ encoding="utf-8",
+ )
+ (home / ".env").write_text("DISCORD_BOT_TOKEN=test-token\nDISCORD_ALLOWED_USERS=999\n", encoding="utf-8")
+ prev = secret_scope.is_multiplex_active()
+ secret_scope.set_multiplex_active(True)
+ try:
+ runner, adapter = _wire(home)
+ kody = PairingStore(profile="kody")
+ kody._save_json(kody._approved_path("discord"), {USER: {}})
+ runner.pairing_stores["kody"] = kody
+
+ message = adapter.build_source(chat_id=THREAD, chat_type="thread", user_id=USER,
+ user_name="u", thread_id=THREAD, guild_id="1")
+ runner._canonicalize(message, primary_home=home)
+ assert message.profile == "kody"
+ assert runner._is_user_authorized_for_source(message) is True
+ assert adapter._component_live_auth(_click(USER, _thread())) is True
+ finally:
+ secret_scope.set_multiplex_active(prev)