Skip to content

The agent that grows with you

fix(feishu): authorize approval card clicks through the gateway allowlist

unsupportedpastelsde4fb05ec033
diff --git a/plugins/platforms/feishu/adapter.py b/plugins/platforms/feishu/adapter.py
index 5c2d91b1cb6..371e6fb6f94 100644
--- a/plugins/platforms/feishu/adapter.py
+++ b/plugins/platforms/feishu/adapter.py
@@ -2231,15 +2231,31 @@ class FeishuAdapter(BasePlatformAdapter):
future.add_done_callback(self._log_background_failure)
return True
- def _is_interactive_operator_authorized(self, open_id: str) -> bool:
- """Return whether this card-action operator may answer gated prompts."""
+ def _is_interactive_operator_authorized(self, open_id: str, *, user_id: str = "", chat_id: str = "") -> bool:
+ """Return whether this card-action operator may answer gated prompts.
+
+ Feishu admins / FEISHU_ALLOWED_USERS decide when set. With neither (setup's pairing-mode
+ default) the clicker must pass the gateway authorization inbound messages get (pairing
+ store, GATEWAY_ALLOWED_USERS, ...), so a chat member who may not use the bot can't answer.
+ """
normalized = str(open_id or "").strip()
if not normalized:
return False
allowed_ids = set(self._admins) | set(self._allowed_group_users)
- if not allowed_ids:
- return True
- return "*" in allowed_ids or normalized in allowed_ids
+ if allowed_ids:
+ return "*" in allowed_ids or normalized in allowed_ids
+ # SessionSource.user_id is the tenant user_id, else open_id (_resolve_sender_profile).
+ principal = str(user_id or "").strip() or normalized
+ # getattr: object.__new__ test doubles never ran BasePlatformAdapter.__init__. Feishu chat
+ # ids don't say DM vs group; "group" is the check's own default.
+ verdict = (
+ self._is_sender_authorized(principal, "group", str(chat_id or "") or None)
+ if getattr(self, "_authorization_check", None) is not None else None
+ )
+ if verdict is None:
+ logger.debug("[Feishu] No gateway authorization check for card operator %s; denying", normalized)
+ return False
+ return verdict
@staticmethod
def _card_response(card_data: Optional[dict[str, Any]] = None) -> Any:
@@ -2256,25 +2272,28 @@ class FeishuAdapter(BasePlatformAdapter):
def _validate_card_action(
self, *, event: Any, state: dict[str, str], label: str, ident: Any,
- ) -> Optional[tuple[str, str, str]]:
+ ) -> Optional[tuple[str, str, str, str]]:
"""Shared operator/chat checks for approval + update-prompt clicks.
- Returns ``(open_id, callback_chat_id, user_name)`` or None (already logged).
+ Returns ``(open_id, callback_chat_id, user_name, user_id)`` or None (already logged).
"""
operator = getattr(event, "operator", None)
open_id = str(getattr(operator, "open_id", "") or "")
- if not self._is_interactive_operator_authorized(open_id):
- logger.warning("[Feishu] Unauthorized %s click by %s", label, open_id or "<unknown>")
- return None
+ user_id = str(getattr(operator, "user_id", "") or "")
callback_chat_id = str(getattr(getattr(event, "context", None), "open_chat_id", "") or "")
expected_chat_id = str(state.get("chat_id", "") or "")
+ if not self._is_interactive_operator_authorized(
+ open_id, user_id=user_id, chat_id=expected_chat_id or callback_chat_id,
+ ):
+ logger.warning("[Feishu] Unauthorized %s click by %s", label, open_id or "<unknown>")
+ return None
if callback_chat_id and expected_chat_id and callback_chat_id != expected_chat_id:
logger.warning(
"[Feishu] %s callback chat mismatch for %s (expected=%s, got=%s)",
label.capitalize(), ident, expected_chat_id, callback_chat_id,
)
return None
- return open_id, callback_chat_id, self._get_cached_sender_name(open_id) or open_id
+ return open_id, callback_chat_id, self._get_cached_sender_name(open_id) or open_id, user_id
def _handle_approval_card_action(self, *, event: Any, action_value: dict[str, Any], loop: Any) -> Any:
"""Schedule approval resolution and build the synchronous callback response."""
@@ -2290,9 +2309,10 @@ class FeishuAdapter(BasePlatformAdapter):
checked = self._validate_card_action(event=event, state=state, label="approval", ident=approval_id)
if checked is None:
return self._card_response()
- open_id, chat_id, user_name = checked
+ open_id, chat_id, user_name, user_id = checked
coro = self._resolve_approval(
approval_id=approval_id, choice=choice, user_name=user_name, open_id=open_id, chat_id=chat_id,
+ user_id=user_id,
)
if not self._submit_on_loop(loop, coro):
return self._card_response()
@@ -2315,22 +2335,26 @@ class FeishuAdapter(BasePlatformAdapter):
checked = self._validate_card_action(event=event, state=state, label="update prompt", ident=prompt_id)
if checked is None:
return self._card_response()
- open_id, chat_id, user_name = checked
- coro = self._resolve_update_prompt(prompt_id, answer, user_name, open_id=open_id, chat_id=chat_id)
+ open_id, chat_id, user_name, user_id = checked
+ coro = self._resolve_update_prompt(
+ prompt_id, answer, user_name, open_id=open_id, chat_id=chat_id, user_id=user_id,
+ )
if not self._submit_on_loop(loop, coro):
return self._card_response()
return self._card_response(self._build_resolved_update_prompt_card(answer=answer, user_name=user_name))
def _pop_validated_prompt_state(
self, *, states: dict[int, dict[str, str]], ident: Any, label: str, open_id: str, chat_id: str,
- unauthorized_fmt: str, operator_repr: str,
+ unauthorized_fmt: str, operator_repr: str, user_id: str = "",
) -> Optional[dict[str, str]]:
"""Re-validate on the loop thread (state may have changed since the callback) and pop."""
state = states.get(ident)
if not state:
logger.debug("[Feishu] %s %s already resolved or unknown", label, ident)
return None
- if not self._is_interactive_operator_authorized(open_id):
+ if not self._is_interactive_operator_authorized(
+ open_id, user_id=user_id, chat_id=str(state.get("chat_id", "") or "") or chat_id,
+ ):
logger.warning(unauthorized_fmt, operator_repr, ident)
return None
expected_chat_id = str(state.get("chat_id", "") or "")
@@ -2344,12 +2368,13 @@ class FeishuAdapter(BasePlatformAdapter):
async def _resolve_approval(
self, approval_id: Any, choice: str, user_name: str, *, open_id: str = "", chat_id: str = "",
+ user_id: str = "",
) -> None:
"""Pop approval state and unblock the waiting agent thread."""
state = self._pop_validated_prompt_state(
states=self._approval_state, ident=approval_id, label="Approval", open_id=open_id, chat_id=chat_id,
unauthorized_fmt="[Feishu] Unauthorized approval click by %s for approval %s",
- operator_repr=open_id or "<unknown>",
+ operator_repr=open_id or "<unknown>", user_id=user_id,
)
if not state:
return
@@ -2378,12 +2403,13 @@ class FeishuAdapter(BasePlatformAdapter):
async def _resolve_update_prompt(
self, prompt_id: Any, answer: str, user_name: str, *, open_id: str = "", chat_id: str = "",
+ user_id: str = "",
) -> None:
"""Persist an update prompt answer for the detached update process."""
state = self._pop_validated_prompt_state(
states=self._update_prompt_state, ident=prompt_id, label="Update prompt", open_id=open_id,
chat_id=chat_id, unauthorized_fmt="[Feishu] Unauthorized update prompt click by %s for prompt %s",
- operator_repr=open_id,
+ operator_repr=open_id, user_id=user_id,
)
if not state:
return
diff --git a/tests/gateway/test_feishu_approval_buttons.py b/tests/gateway/test_feishu_approval_buttons.py
index 75b40f7e129..f8f99f94b62 100644
--- a/tests/gateway/test_feishu_approval_buttons.py
+++ b/tests/gateway/test_feishu_approval_buttons.py
@@ -206,6 +206,8 @@ class TestResolveApproval:
@pytest.mark.asyncio
async def test_resolves_once(self):
adapter = _make_adapter()
+ # No Feishu allowlist: the gateway authorization decides (here: this user is allowed).
+ adapter.set_authorization_check(lambda *_a, **_kw: True)
adapter._approval_state[1] = {
"session_key": "agent:main:feishu:group:oc_12345",
"message_id": "msg_001",
@@ -483,6 +485,8 @@ class TestCardActionCallbackResponse:
adapter._loop.is_closed = MagicMock(return_value=False)
adapter._admins = set()
adapter._allowed_group_users = set()
+ # The paired DM user passes the gateway authorization (pairing store).
+ adapter.set_authorization_check(lambda *_a, **_kw: True)
adapter._approval_state[15] = {
"session_key": "sess-15",
"message_id": "msg-15",
@@ -509,6 +513,8 @@ class TestCardActionCallbackResponse:
adapter._loop.is_closed = MagicMock(return_value=False)
adapter._admins = set()
adapter._allowed_group_users = set()
+ # The paired DM user passes the gateway authorization (pairing store).
+ adapter.set_authorization_check(lambda *_a, **_kw: True)
adapter._update_prompt_state[23] = {
"session_key": "sess-up-23",
"message_id": "msg_up_023",
@@ -614,6 +620,7 @@ class TestResolveUpdatePrompt:
adapter = _make_adapter()
monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
(tmp_path / ".hermes").mkdir()
+ adapter.set_authorization_check(lambda *_a, **_kw: True)
adapter._update_prompt_state[1] = {
"session_key": "sess-up-1",
"message_id": "msg_up_003",
diff --git a/tests/gateway/test_feishu_card_action_gateway_authz.py b/tests/gateway/test_feishu_card_action_gateway_authz.py
new file mode 100644
index 00000000000..c47a6f9d08c
--- /dev/null
+++ b/tests/gateway/test_feishu_card_action_gateway_authz.py
@@ -0,0 +1,218 @@
+"""Feishu approval / update-prompt card clicks with no Feishu allowlist or admins.
+
+Setup's default leaves FEISHU_ALLOWED_USERS and the admin list empty (pairing mode). A click
+must then pass the gateway authorization inbound messages get, and is refused when that check
+denies or was never registered. A configured Feishu allowlist still decides on its own.
+"""
+
+import importlib.util
+import sys
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+
+
+def _ensure_feishu_mocks():
+ if importlib.util.find_spec("lark_oapi") is None and "lark_oapi" not in sys.modules:
+ mod = MagicMock()
+ for name in ("lark_oapi", "lark_oapi.api.im.v1", "lark_oapi.event", "lark_oapi.event.callback_type"):
+ sys.modules.setdefault(name, mod)
+ if importlib.util.find_spec("aiohttp") is None and "aiohttp" not in sys.modules:
+ aio = MagicMock()
+ sys.modules.setdefault("aiohttp", aio)
+ sys.modules.setdefault("aiohttp.web", aio.web)
+
+
+_ensure_feishu_mocks()
+
+from gateway.config import PlatformConfig
+import plugins.platforms.feishu.adapter as feishu_module
+from plugins.platforms.feishu.adapter import FeishuAdapter
+
+
+class _FakeCallBackCard:
+ def __init__(self):
+ self.type = None
+ self.data = None
+
+
+class _FakeP2Response:
+ def __init__(self):
+ self.card = None
+
+
[email protected](autouse=True)
+def _patch_callback_card_types(monkeypatch):
+ monkeypatch.setattr(feishu_module, "P2CardActionTriggerResponse", _FakeP2Response)
+ monkeypatch.setattr(feishu_module, "CallBackCard", _FakeCallBackCard)
+
+
+def _close_submitted_coro(coro, _loop):
+ coro.close()
+ return SimpleNamespace(add_done_callback=lambda *_args, **_kwargs: None)
+
+
+def _make_adapter(*, allowed=(), admins=()) -> FeishuAdapter:
+ adapter = FeishuAdapter(PlatformConfig(enabled=True))
+ adapter._client = MagicMock()
+ adapter._loop = MagicMock()
+ adapter._loop.is_closed = MagicMock(return_value=False)
+ adapter._allowed_group_users = set(allowed)
+ adapter._admins = set(admins)
+ adapter._approval_state[1] = {"session_key": "sess-1", "message_id": "msg-1", "chat_id": "oc_group"}
+ adapter._update_prompt_state[2] = {"session_key": "sess-2", "message_id": "msg-2", "chat_id": "oc_group"}
+ return adapter
+
+
+class _GatewayCheck:
+ """Stand-in for the runner's ``set_authorization_check`` callback."""
+
+ def __init__(self, allowed_ids):
+ self.allowed_ids = set(allowed_ids)
+ self.seen = []
+
+ def __call__(self, user_id, chat_type=None, chat_id=None, **_kw):
+ self.seen.append((user_id, chat_type, chat_id))
+ return user_id in self.allowed_ids
+
+
+_gateway_check = _GatewayCheck
+
+
+def _approval_click(open_id, *, user_id=None, chat_id="oc_group"):
+ return SimpleNamespace(event=SimpleNamespace(
+ token="tok", context=SimpleNamespace(open_chat_id=chat_id),
+ operator=SimpleNamespace(open_id=open_id, user_id=user_id),
+ action=SimpleNamespace(tag="button", value={"hermes_action": "approve_once", "approval_id": 1}),
+ ))
+
+
+def _update_prompt_click(open_id):
+ return SimpleNamespace(event=SimpleNamespace(
+ token="tok", context=SimpleNamespace(open_chat_id="oc_group"),
+ operator=SimpleNamespace(open_id=open_id),
+ action=SimpleNamespace(tag="button", value={"hermes_update_prompt_action": "y", "update_prompt_id": 2}),
+ ))
+
+
+class TestNoFeishuAllowlist:
+ def test_click_refused_when_gateway_denies(self):
+ adapter = _make_adapter()
+ adapter.set_authorization_check(_gateway_check({"ou_requester"}))
+
+ with patch("asyncio.run_coroutine_threadsafe") as submit:
+ response = adapter._on_card_action_trigger(_approval_click("ou_bystander"))
+
+ assert response.card is None
+ submit.assert_not_called()
+ assert 1 in adapter._approval_state
+
+ def test_click_refused_without_gateway_check(self):
+ adapter = _make_adapter()
+ assert adapter._authorization_check is None
+
+ with patch("asyncio.run_coroutine_threadsafe") as submit:
+ response = adapter._on_card_action_trigger(_approval_click("ou_anyone"))
+
+ assert response.card is None
+ submit.assert_not_called()
+
+ def test_update_prompt_refused_when_gateway_denies(self):
+ adapter = _make_adapter()
+ adapter.set_authorization_check(_gateway_check(set()))
+
+ with patch("asyncio.run_coroutine_threadsafe") as submit:
+ response = adapter._on_card_action_trigger(_update_prompt_click("ou_bystander"))
+
+ assert response.card is None
+ submit.assert_not_called()
+ assert 2 in adapter._update_prompt_state
+
+ def test_gateway_authorized_user_can_approve(self):
+ adapter = _make_adapter()
+ check = _gateway_check({"ou_requester"})
+ adapter.set_authorization_check(check)
+
+ with patch("asyncio.run_coroutine_threadsafe", side_effect=_close_submitted_coro) as submit:
+ response = adapter._on_card_action_trigger(_approval_click("ou_requester"))
+
+ assert response.card is not None
+ submit.assert_called_once()
+ assert check.seen == [("ou_requester", "group", "oc_group")]
+
+ def test_gateway_check_uses_tenant_user_id_when_present(self):
+ """The principal matches SessionSource.user_id: tenant user_id, else open_id."""
+ adapter = _make_adapter()
+ check = _gateway_check({"u_tenant"})
+ adapter.set_authorization_check(check)
+
+ with patch("asyncio.run_coroutine_threadsafe", side_effect=_close_submitted_coro):
+ response = adapter._on_card_action_trigger(_approval_click("ou_x", user_id="u_tenant"))
+
+ assert response.card is not None
+ assert check.seen == [("u_tenant", "group", "oc_group")]
+
+ @pytest.mark.asyncio
+ async def test_loop_side_recheck_refuses_unauthorized(self):
+ adapter = _make_adapter()
+ adapter.set_authorization_check(_gateway_check({"ou_requester"}))
+
+ with patch("tools.approval.resolve_gateway_approval") as resolve:
+ await adapter._resolve_approval(1, "once", "Mallory", open_id="ou_bystander", chat_id="oc_group")
+
+ resolve.assert_not_called()
+ assert 1 in adapter._approval_state
+
+ @pytest.mark.asyncio
+ async def test_loop_side_recheck_resolves_authorized(self):
+ adapter = _make_adapter()
+ adapter.set_authorization_check(_gateway_check({"u_tenant"}))
+
+ with patch("tools.approval.resolve_gateway_approval", return_value=1) as resolve:
+ await adapter._resolve_approval(
+ 1, "once", "Alice", open_id="ou_x", chat_id="oc_group", user_id="u_tenant",
+ )
+
+ resolve.assert_called_once_with("sess-1", "once")
+
+ @pytest.mark.asyncio
+ async def test_non_approval_card_action_still_routes(self):
+ adapter = _make_adapter()
+ data = SimpleNamespace(event=SimpleNamespace(
+ token="tok_other", context=SimpleNamespace(open_chat_id="oc_group"),
+ operator=SimpleNamespace(open_id="ou_bystander"),
+ action=SimpleNamespace(tag="button", value={"custom_action": "x"}),
+ ))
+ with (
+ patch.object(adapter, "_resolve_sender_profile", new_callable=AsyncMock,
+ return_value={"user_id": "ou_bystander", "user_name": "B", "user_id_alt": None}),
+ patch.object(adapter, "get_chat_info", new_callable=AsyncMock, return_value={"name": "Chat"}),
+ patch.object(adapter, "_handle_message_with_guards", new_callable=AsyncMock) as handle,
+ ):
+ await adapter._handle_card_action_event(data)
+
+ handle.assert_called_once()
+
+
+class TestFeishuAllowlistUnchanged:
+ def test_allowlisted_user_approves_without_gateway_check(self):
+ adapter = _make_adapter(allowed={"ou_bob"})
+ check = _gateway_check(set())
+ adapter.set_authorization_check(check)
+
+ with patch("asyncio.run_coroutine_threadsafe", side_effect=_close_submitted_coro):
+ response = adapter._on_card_action_trigger(_approval_click("ou_bob"))
+
+ assert response.card is not None
+ assert check.seen == []
+
+ def test_non_allowlisted_user_refused_even_if_gateway_allows(self):
+ adapter = _make_adapter(admins={"ou_admin"})
+ adapter.set_authorization_check(_gateway_check({"ou_other"}))
+
+ with patch("asyncio.run_coroutine_threadsafe") as submit:
+ response = adapter._on_card_action_trigger(_approval_click("ou_other"))
+
+ assert response.card is None
+ submit.assert_not_called()