The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(matrix): warn when encrypted room events arrive with no E2EE decryptor
liuhao1024846e63d9ec53
diff --git a/plugins/platforms/matrix/adapter.py b/plugins/platforms/matrix/adapter.pyindex 1a288fb0f56..239f8e0f3a6 100644--- a/plugins/platforms/matrix/adapter.py+++ b/plugins/platforms/matrix/adapter.py@@ -893,6 +893,8 @@ class MatrixAdapter(BasePlatformAdapter):from collections import dequeself._processed_events: deque = deque(maxlen=1000) # event dedup, newest keptself._processed_events_set: set = set()+ # Rooms already warned for dropping encrypted events this process lifetime (#131778).+ self._warned_encrypted_drop_rooms: Set[str] = set()self._threads = ThreadParticipationTracker("matrix") # require_mention bypassself._parked_voices = ParkedVoices() # unmentioned voice awaiting a bare @mentionself._require_mention: bool = self._parse_require_mention(config)@@ -1923,6 +1925,7 @@ class MatrixAdapter(BasePlatformAdapter):if rooms_join or initial:self._joined_rooms.update(rooms_join.keys())self._invalidate_room_identities()+ self._warn_encrypted_drops(rooms_join, client)nb = sync_data.get("next_batch") # incremental syncs resume from hereif nb:await client.sync_store.put_next_batch(nb)@@ -1936,6 +1939,28 @@ class MatrixAdapter(BasePlatformAdapter):self._schedule_pending_invite_joins(sync_data)return nb+ def _warn_encrypted_drops(self, rooms_join: Dict[str, Any], client: Any) -> None:+ """Fail loud when encrypted room events arrive but no decryptor is attached (#131778).++ With E2EE off, or after the optional mode degraded (missing deps / failed setup) and+ kept the connection, ``m.room.encrypted`` timeline events dispatch to an empty+ ROOM_ENCRYPTED handler set — mautrix drops them without a trace, so an encrypted room+ looks connected but deaf: syncs succeed, no errors, no warnings. One warning per room+ per process; with a decryptor attached, mautrix's own machinery already reports+ decryption failures."""+ if getattr(client, "crypto", None) is not None:+ return+ for room_id, room_data in rooms_join.items():+ if room_id in self._warned_encrypted_drop_rooms:+ continue+ events = ((room_data or {}).get("timeline", {}) or {}).get("events", ()) or ()+ if any(isinstance(ev, dict) and ev.get("type") == "m.room.encrypted" for ev in events):+ self._warned_encrypted_drop_rooms.add(room_id)+ logger.warning(+ "Matrix: dropping encrypted messages in %s — this process has no E2EE decryptor "+ "(E2EE off or unavailable). %s. Without it, messages in encrypted rooms never "+ "reach the agent.", room_id, _E2EE_INSTALL_HINT)+async def _dispatch_sync(self, sync_data: Dict[str, Any]) -> None:"""Dispatch a sync response through the mautrix event machinery."""client = self._clientdiff --git a/tests/gateway/test_matrix.py b/tests/gateway/test_matrix.pyindex 96a09ac0132..a0706727997 100644--- a/tests/gateway/test_matrix.py+++ b/tests/gateway/test_matrix.py@@ -1,5 +1,6 @@"""Tests for Matrix platform adapter (mautrix-python backend)."""import asyncio+import loggingimport sysimport timeimport types@@ -1169,6 +1170,79 @@ class TestMatrixSyncLoop:assert called is True+ @staticmethod+ def _cryptoless_client():+ """Client with no decryptor attached (E2EE off, or the optional mode degraded)."""+ fake_client = MagicMock()+ fake_client.crypto = None+ fake_client.sync_store = MagicMock()+ fake_client.sync_store.put_next_batch = AsyncMock()+ fake_client.handle_sync = MagicMock(return_value=[])+ return fake_client++ @pytest.mark.asyncio+ async def test_absorb_sync_warns_once_per_room_for_encrypted_events_without_crypto(+ self, caplog+ ):+ """Encrypted events with no decryptor must fail loud, once per room (#131778)."""+ adapter = _make_adapter()+ adapter._closing = False+ fake_client = self._cryptoless_client()+ adapter._client = fake_client++ sync_data = {+ "rooms": {"join": {"!enc:example.org": {+ "timeline": {"events": [{"type": "m.room.encrypted", "event_id": "$e1"}]}}}},+ "next_batch": "s1",+ }+ with caplog.at_level(logging.WARNING, logger="plugins.platforms.matrix.adapter"):+ await adapter._absorb_sync(fake_client, sync_data)+ await adapter._absorb_sync(fake_client, sync_data) # rate-limited: one warning per room++ warnings = [r for r in caplog.records+ if "!enc:example.org" in r.getMessage() and "encrypted" in r.getMessage()]+ assert len(warnings) == 1++ @pytest.mark.asyncio+ async def test_absorb_sync_no_encrypted_warning_when_crypto_attached(self, caplog):+ """With a decryptor attached, mautrix's own machinery reports failures instead."""+ adapter = _make_adapter()+ adapter._closing = False+ fake_client = self._cryptoless_client()+ # OlmMachine attached: mautrix's DecryptionDispatcher handles encrypted events.+ fake_client.crypto = MagicMock()+ adapter._client = fake_client++ sync_data = {+ "rooms": {"join": {"!enc:example.org": {+ "timeline": {"events": [{"type": "m.room.encrypted", "event_id": "$e1"}]}}}},+ "next_batch": "s1",+ }+ with caplog.at_level(logging.WARNING, logger="plugins.platforms.matrix.adapter"):+ await adapter._absorb_sync(fake_client, sync_data)++ assert not [r for r in caplog.records if "encrypted" in r.getMessage()]++ @pytest.mark.asyncio+ async def test_absorb_sync_no_warning_for_plaintext_events_without_crypto(+ self, caplog+ ):+ """Plain rooms must not trip the encrypted-drop warning."""+ adapter = _make_adapter()+ adapter._closing = False+ fake_client = self._cryptoless_client()+ adapter._client = fake_client++ sync_data = {+ "rooms": {"join": {"!plain:example.org": {+ "timeline": {"events": [{"type": "m.room.message", "event_id": "$m1"}]}}}},+ "next_batch": "s1",+ }+ with caplog.at_level(logging.WARNING, logger="plugins.platforms.matrix.adapter"):+ await adapter._absorb_sync(fake_client, sync_data)++ assert not [r for r in caplog.records if "encrypted" in r.getMessage()]+@pytest.mark.asyncioasync def test_sync_loop_dispatches_registered_room_message_handler(self):"""Inbound sync data should flow through handle_sync into message handling."""