The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(matrix): apply pairing revocations live
FroRaut09c9ed2a6100
diff --git a/gateway/pairing.py b/gateway/pairing.pyindex 4ea389373c2..95d357e7438 100644--- a/gateway/pairing.py+++ b/gateway/pairing.py@@ -205,21 +205,28 @@ def _purge_allowlist_entries(entries, platform: str, user_id: str):def _sync_live_adapter_allowlist_remove(platform: str, user_id: str) -> None:- """Clear revoked principals from in-process adapter ``_allow_from`` snapshots,- so intake does not keep authorizing from a stale snapshot until restart."""+ """Clear revoked principals from in-process adapter allowlist snapshots,+ so intake and adapter-owned controls do not keep authorizing until restart."""platform_name = (platform or "").strip().lower()if not platform_name or not str(user_id or "").strip():returnfor adapter in _iter_live_gateway_adapters():if _adapter_platform_name(adapter) != platform_name:continue- if hasattr(adapter, "_allow_from"):- with contextlib.suppress(Exception):- adapter._allow_from = _purge_allowlist_entries(set(adapter._allow_from or ()), platform_name, user_id)+ for attr in ("_allow_from", "_allowed_user_ids"):+ if hasattr(adapter, attr):+ with contextlib.suppress(Exception):+ setattr(+ adapter,+ attr,+ _purge_allowlist_entries(getattr(adapter, attr), platform_name, user_id),+ )extra = getattr(getattr(adapter, "config", None), "extra", None)- if isinstance(extra, dict) and "allow_from" in extra:- with contextlib.suppress(Exception):- extra["allow_from"] = _purge_allowlist_entries(extra.get("allow_from"), platform_name, user_id)+ if isinstance(extra, dict):+ for key in ("allow_from", "allowed_users"):+ if key in extra:+ with contextlib.suppress(Exception):+ extra[key] = _purge_allowlist_entries(extra.get(key), platform_name, user_id)def _sync_allowlist_remove(platform: str, user_id: str) -> None:diff --git a/plugins/platforms/matrix/adapter.py b/plugins/platforms/matrix/adapter.pyindex 8e52567d690..8702f9e95e8 100644--- a/plugins/platforms/matrix/adapter.py+++ b/plugins/platforms/matrix/adapter.py@@ -2294,7 +2294,7 @@ class MatrixAdapter(BasePlatformAdapter):is_direct = bool(getattr(getattr(event, "content", None), "is_direct", False))inviter = str(getattr(event, "sender", ""))# Only authorized inviters — otherwise any federated user could pull the bot into rooms.- if not self._is_authorized_user(inviter):+ if not self._is_authorized_user(inviter, str(room_id)):logger.warning("Matrix: rejecting invite to %s from unauthorized user %s", room_id, inviter)returnlogger.info("Matrix: invited to %s — joining (is_direct=%s)", room_id, is_direct)@@ -2361,7 +2361,7 @@ class MatrixAdapter(BasePlatformAdapter):# auto-join any invite from an arbitrary federated user on# restart. An inviter missing from the stripped invite state# fails closed, like an empty sender in _on_invite.- if not self._is_authorized_user(inviter):+ if not self._is_authorized_user(inviter, str(room_id)):logger.warning("Matrix: rejecting invite to %s from unauthorized user %s",room_id,@@ -2577,15 +2577,17 @@ class MatrixAdapter(BasePlatformAdapter):expires_at = getattr(prompt, "expires_at", None)return expires_at is not None and time.monotonic() > float(expires_at)- def _is_authorized_user(self, user_id: str) -> bool:- """GATEWAY_ALLOW_ALL_USERS, or membership in MATRIX_ALLOWED_USERS."""+ def _is_authorized_user(self, user_id: str, room_id: str | None = None) -> bool:+ """Resolve live gateway authorization, falling back to the startup snapshot when unwired."""+ if getattr(self, "_authorization_check", None) is not None:+ return self._is_sender_authorized(user_id, "group", room_id) is True# Scoped read — the DEFAULT profile's os.environ opt-in must not authorize on a secondary bot.return _get_scoped_secret("GATEWAY_ALLOW_ALL_USERS", "").strip().lower() in ("true", "1", "yes") or bool(self._allowed_user_ids and user_id in self._allowed_user_ids)async def _validate_matrix_prompt_reactor(self, room_id: str, target_event_id: str, sender: str, prompt: Any, prompt_label: str) -> bool:- if not self._is_authorized_user(sender):+ if not self._is_authorized_user(sender, room_id):logger.info("Matrix: ignoring %s reaction from unauthorized user %s on %s", prompt_label, sender, target_event_id)await self._send_invalid_reaction_feedback(diff --git a/tests/gateway/test_pairing_allowlist_bypass.py b/tests/gateway/test_pairing_allowlist_bypass.pyindex e0ac09257d5..c30c09ed32d 100644--- a/tests/gateway/test_pairing_allowlist_bypass.py+++ b/tests/gateway/test_pairing_allowlist_bypass.py@@ -30,6 +30,8 @@ def _isolate_env(monkeypatch):"TELEGRAM_GROUP_ALLOWED_CHATS","WHATSAPP_ALLOWED_USERS","WHATSAPP_CLOUD_ALLOWED_USERS",+ "MATRIX_ALLOWED_USERS",+ "MATRIX_ALLOW_ALL_USERS","GATEWAY_ALLOW_ALL_USERS","GATEWAY_ALLOWED_USERS",):@@ -392,3 +394,124 @@ def test_whatsapp_live_allowlist_denies_when_env_key_removed(monkeypatch):assert adapter._live_dm_allow_from() == set()assert adapter._is_dm_intake_allowed("15551234567") is Falseassert adapter._is_dm_allowed("15551234567") is False+++async def test_matrix_pairing_revoke_denies_live_message_and_approval_without_restart(+ store, monkeypatch,+):+ """The runner's live pairing verdict must gate both Matrix messages and approvals."""+ from unittest.mock import AsyncMock, patch++ from gateway.config import GatewayConfig, PlatformConfig+ from gateway.run import GatewayRunner+ from plugins.platforms.matrix.adapter import MatrixAdapter, _MatrixApprovalPrompt++ user_id = "@paired:example.org"+ room_id = "!room:example.org"+ config = PlatformConfig(+ enabled=True,+ extra={"homeserver": "https://matrix.example.org", "user_id": "@bot:example.org"},+ )+ adapter = MatrixAdapter(config)+ runner = object.__new__(GatewayRunner)+ runner.config = GatewayConfig(platforms={Platform.MATRIX: config})+ runner.adapters = {Platform.MATRIX: adapter}+ runner._profile_adapters = {}+ runner.pairing_store = store+ runner.pairing_stores = {}+ adapter.set_authorization_check(runner._make_adapter_auth_check(Platform.MATRIX))++ source = SessionSource(+ platform=Platform.MATRIX,+ user_id=user_id,+ chat_id=room_id,+ user_name="Paired User",+ chat_type="dm",+ )+ assert runner._is_user_authorized(source) is False++ code = store.generate_code("matrix", user_id, "Paired User")+ assert code is not None+ assert store.approve_code("matrix", code) is not None+ assert runner._is_user_authorized(source) is True++ adapter._send_invalid_reaction_feedback = AsyncMock()++ async def react(prompt_id: str, reaction_id: str):+ prompt = _MatrixApprovalPrompt(+ session_key=f"session-{prompt_id}",+ chat_id=room_id,+ message_id=prompt_id,+ requester_user_id=user_id,+ )+ adapter._approval_prompts_by_event[prompt_id] = prompt+ event = SimpleNamespace(+ sender=user_id,+ event_id=reaction_id,+ room_id=room_id,+ content={"m.relates_to": {"event_id": prompt_id, "key": "✅"}},+ )+ with patch("tools.approval.resolve_gateway_approval", return_value=1) as resolve:+ await adapter._on_reaction(event)+ return prompt, resolve++ before_prompt, before_resolve = await react("$before", "$reaction-before")+ assert before_prompt.resolved is True+ before_resolve.assert_called_once_with("session-$before", "once")++ adapter_identity = id(adapter)+ assert store.revoke("matrix", user_id) is True+ assert id(adapter) == adapter_identity+ assert store.is_approved("matrix", user_id) is False+ assert runner._is_user_authorized(source) is False++ after_prompt, after_resolve = await react("$after", "$reaction-after")+ assert after_prompt.resolved is False+ after_resolve.assert_not_called()+++def test_matrix_pairing_revoke_purges_live_allowlist_snapshot(store, monkeypatch):+ """A live Matrix adapter must not retain an allowlist entry removed by pairing revoke."""+ from gateway.config import PlatformConfig+ import gateway.run as gateway_run+ import hermes_cli.config as cfg+ from plugins.platforms.matrix.adapter import MatrixAdapter++ owner_id = "@owner:example.org"+ paired_id = "@paired:example.org"+ monkeypatch.setenv("MATRIX_ALLOWED_USERS", owner_id)+ monkeypatch.setattr(+ cfg,+ "save_env_value",+ lambda key, value: os.environ.__setitem__(key, value),+ )+ monkeypatch.setattr(+ cfg,+ "remove_env_value",+ lambda key: (os.environ.pop(key, None), True)[1],+ )++ code = store.generate_code("matrix", paired_id, "Paired User")+ assert code is not None+ assert store.approve_code("matrix", code) is not None+ assert os.environ["MATRIX_ALLOWED_USERS"] == f"{owner_id},{paired_id}"++ adapter = MatrixAdapter(+ PlatformConfig(+ enabled=True,+ extra={"homeserver": "https://matrix.example.org", "user_id": "@bot:example.org"},+ )+ )+ assert adapter._is_authorized_user(paired_id) is True++ runner = SimpleNamespace(+ adapters={Platform.MATRIX: adapter},+ _profile_adapters={},+ )+ monkeypatch.setattr(gateway_run, "_gateway_runner_ref", lambda: runner)++ assert store.revoke("matrix", paired_id) is True+ assert os.environ["MATRIX_ALLOWED_USERS"] == owner_id+ assert paired_id not in adapter._allowed_user_ids+ assert adapter._is_authorized_user(paired_id) is False