Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(slack): scope dm mismatch validation

cyh7c31c2911bbf
diff --git a/modules/im/slack.py b/modules/im/slack.py
index b1571d118..ec3354ee2 100644
--- a/modules/im/slack.py
+++ b/modules/im/slack.py
@@ -135,16 +135,56 @@ class SlackBot(BaseIMClient):
return None
return record
- def _match_bound_dm_channel(self, user_id: Optional[str], channel_id: Optional[str]) -> Optional[bool]:
+ def _persist_bound_dm_channel(self, user_id: str, record: Any, dm_channel_id: str) -> None:
+ normalized_channel_id = str(dm_channel_id or "").strip()
+ if not normalized_channel_id:
+ return
+ existing_channel_id = str(getattr(record, "dm_chat_id", "") or "").strip()
+ if existing_channel_id == normalized_channel_id:
+ return
+ setattr(record, "dm_chat_id", normalized_channel_id)
+ if self.settings_manager is None:
+ return
+ store_getter = getattr(self.settings_manager, "get_store", None)
+ if not callable(store_getter):
+ return
+ try:
+ store = store_getter()
+ except Exception:
+ logger.debug("Failed to access settings store for Slack DM persistence", exc_info=True)
+ return
+ try:
+ store.update_user(user_id, record, platform="slack")
+ except TypeError:
+ store.update_user(user_id, record)
+ except Exception:
+ logger.debug("Failed to persist Slack dm_chat_id for %s", user_id, exc_info=True)
+ return
+ logger.info("Updated recorded Slack dm_chat_id for user %s to %s", user_id, normalized_channel_id)
+
+ async def _match_bound_dm_channel(self, user_id: Optional[str], channel_id: Optional[str]) -> Optional[bool]:
if not user_id or not channel_id:
return None
record = self._get_bound_user_record(user_id)
if record is None:
return None
dm_chat_id = str(getattr(record, "dm_chat_id", "") or "").strip()
- if not dm_chat_id:
- return None
- return dm_chat_id == channel_id
+ if dm_chat_id == channel_id:
+ return True
+ if dm_chat_id and dm_chat_id != channel_id:
+ logger.warning(
+ "Slack DM channel mismatch for user %s: recorded=%s incoming=%s",
+ user_id,
+ dm_chat_id,
+ channel_id,
+ )
+
+ canonical_dm_channel = await self._open_dm_channel(user_id)
+ canonical_dm_channel = str(canonical_dm_channel or "").strip()
+ if not canonical_dm_channel:
+ return None if not dm_chat_id else False
+ self._persist_bound_dm_channel(user_id, record, canonical_dm_channel)
+ return canonical_dm_channel == channel_id
def _is_duplicate_event(self, event_id: Optional[str]) -> bool:
"""Deduplicate Slack events using event_id with a short TTL."""
@@ -285,7 +325,13 @@ class SlackBot(BaseIMClient):
def _is_dm_context(self, context: MessageContext) -> bool:
if not bool((context.platform_specific or {}).get("is_dm", False)) and not self._channel_looks_like_dm(context.channel_id):
return False
- return self._match_bound_dm_channel(context.user_id, context.channel_id) is not False
+ record = self._get_bound_user_record(context.user_id)
+ if record is None:
+ return True
+ dm_chat_id = str(getattr(record, "dm_chat_id", "") or "").strip()
+ if not dm_chat_id:
+ return True
+ return dm_chat_id == context.channel_id
async def _open_dm_channel(self, user_id: str) -> Optional[str]:
self._ensure_clients()
@@ -1244,15 +1290,16 @@ class SlackBot(BaseIMClient):
channel_id = event.get("channel")
user_id = event.get("user")
- dm_match = self._match_bound_dm_channel(user_id, channel_id)
- if dm_match is False:
- logger.warning(
- "Ignoring Slack DM-like message from mismatched channel %s for user %s",
- channel_id,
- user_id,
- )
- return
is_dm = self._channel_looks_like_dm(channel_id)
+ if is_dm:
+ dm_match = await self._match_bound_dm_channel(user_id, channel_id)
+ if dm_match is False:
+ logger.warning(
+ "Ignoring Slack DM-like message from mismatched channel %s for user %s",
+ channel_id,
+ user_id,
+ )
+ return
# Check if this message contains a bot mention.
# In channels, app_mention will handle it. In DMs, Slack does not
diff --git a/tests/test_slack_dm_mentions.py b/tests/test_slack_dm_mentions.py
index 80031b0fc..1eb0f4bbc 100644
--- a/tests/test_slack_dm_mentions.py
+++ b/tests/test_slack_dm_mentions.py
@@ -348,6 +348,11 @@ class SlackDmMentionTests(unittest.IsolatedAsyncioTestCase):
return SimpleNamespace(dm_chat_id="D_REAL")
return None
+ def find_channel(self, channel_id, platform=None):
+ if channel_id == "C123":
+ return SimpleNamespace(enabled=True)
+ return None
+
def is_bound_user(self, user_id, platform=None):
return user_id == "U123"
@@ -358,9 +363,15 @@ class SlackDmMentionTests(unittest.IsolatedAsyncioTestCase):
def get_require_mention(self, _channel_id, global_default=False):
return global_default
+ class _WebClient:
+ async def conversations_open(self, users):
+ assert users == ["U123"]
+ return {"ok": True, "channel": {"id": "D_REAL"}}
+
async def _on_message(_context, _text):
received["called"] = True
+ slack.web_client = _WebClient()
slack.set_settings_manager(_SettingsManager())
slack.register_callbacks(on_message=_on_message)
@@ -381,6 +392,169 @@ class SlackDmMentionTests(unittest.IsolatedAsyncioTestCase):
self.assertFalse(received["called"])
+ async def test_bound_user_message_repairs_missing_dm_channel_binding(self):
+ slack = SlackBot(SlackConfig(bot_token="xoxb-test"))
+ received = {}
+ updates = []
+
+ class _Store:
+ def maybe_reload(self):
+ return None
+
+ def get_user(self, user_id, platform=None):
+ if user_id == "U123":
+ return SimpleNamespace(dm_chat_id="")
+ return None
+
+ def update_user(self, user_id, settings, platform=None):
+ updates.append((user_id, getattr(settings, "dm_chat_id", ""), platform))
+
+ def is_bound_user(self, user_id, platform=None):
+ return user_id == "U123"
+
+ class _SettingsManager:
+ def get_store(self):
+ return _Store()
+
+ def get_require_mention(self, _channel_id, global_default=False):
+ return global_default
+
+ class _WebClient:
+ async def conversations_open(self, users):
+ assert users == ["U123"]
+ return {"ok": True, "channel": {"id": "D_REAL"}}
+
+ async def _on_message(_context, text):
+ received["text"] = text
+
+ slack.web_client = _WebClient()
+ slack.set_settings_manager(_SettingsManager())
+ slack.register_callbacks(on_message=_on_message)
+
+ payload = {
+ "event_id": "evt-dm-repair-missing-binding",
+ "team_id": "T1",
+ "authorizations": [{"user_id": "U_BOT"}],
+ "event": {
+ "type": "message",
+ "channel": "D_REAL",
+ "user": "U123",
+ "text": "hello",
+ "ts": "1710000000.000255",
+ },
+ }
+
+ await slack._handle_event(payload)
+
+ self.assertEqual(received, {"text": "hello"})
+ self.assertEqual(updates, [("U123", "D_REAL", "slack")])
+
+ async def test_bound_user_missing_dm_channel_still_ignores_wrong_dm(self):
+ slack = SlackBot(SlackConfig(bot_token="xoxb-test"))
+ received = {"called": False}
+
+ class _Store:
+ def maybe_reload(self):
+ return None
+
+ def get_user(self, user_id, platform=None):
+ if user_id == "U123":
+ return SimpleNamespace(dm_chat_id="")
+ return None
+
+ def update_user(self, user_id, settings, platform=None):
+ return None
+
+ def is_bound_user(self, user_id, platform=None):
+ return user_id == "U123"
+
+ class _SettingsManager:
+ def get_store(self):
+ return _Store()
+
+ def get_require_mention(self, _channel_id, global_default=False):
+ return global_default
+
+ class _WebClient:
+ async def conversations_open(self, users):
+ assert users == ["U123"]
+ return {"ok": True, "channel": {"id": "D_REAL"}}
+
+ async def _on_message(_context, _text):
+ received["called"] = True
+
+ slack.web_client = _WebClient()
+ slack.set_settings_manager(_SettingsManager())
+ slack.register_callbacks(on_message=_on_message)
+
+ payload = {
+ "event_id": "evt-dm-missing-binding-wrong-channel",
+ "team_id": "T1",
+ "authorizations": [{"user_id": "U_BOT"}],
+ "event": {
+ "type": "message",
+ "channel": "D_OTHER",
+ "user": "U123",
+ "text": "hello",
+ "ts": "1710000000.000257",
+ },
+ }
+
+ await slack._handle_event(payload)
+
+ self.assertFalse(received["called"])
+
+ async def test_bound_user_channel_message_is_not_blocked_by_dm_guard(self):
+ slack = SlackBot(SlackConfig(bot_token="xoxb-test"))
+ received = {}
+
+ class _Store:
+ def maybe_reload(self):
+ return None
+
+ def get_user(self, user_id, platform=None):
+ if user_id == "U123":
+ return SimpleNamespace(dm_chat_id="D_REAL")
+ return None
+
+ def find_channel(self, channel_id, platform=None):
+ if channel_id == "C123":
+ return SimpleNamespace(enabled=True)
+ return None
+
+ def is_bound_user(self, user_id, platform=None):
+ return user_id == "U123"
+
+ class _SettingsManager:
+ def get_store(self):
+ return _Store()
+
+ def get_require_mention(self, _channel_id, global_default=False):
+ return global_default
+
+ async def _on_message(_context, text):
+ received["text"] = text
+
+ slack.set_settings_manager(_SettingsManager())
+ slack.register_callbacks(on_message=_on_message)
+
+ payload = {
+ "event_id": "evt-bound-user-channel-message",
+ "team_id": "T1",
+ "authorizations": [{"user_id": "U_BOT"}],
+ "event": {
+ "type": "message",
+ "channel": "C123",
+ "user": "U123",
+ "text": "hello from channel",
+ "ts": "1710000000.000258",
+ },
+ }
+
+ await slack._handle_event(payload)
+
+ self.assertEqual(received, {"text": "hello from channel"})
+
async def test_bound_user_message_from_recorded_dm_channel_still_processes(self):
slack = SlackBot(SlackConfig(bot_token="xoxb-test"))
received = {}