The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(matrix): move _CryptoStateStore into adapter_crypto to keep adapter.py under its size cap
kshitijk4poor2efd6961f780
diff --git a/plugins/platforms/matrix/adapter.py b/plugins/platforms/matrix/adapter.pyindex 1beb1361ee0..69d1b09e186 100644--- a/plugins/platforms/matrix/adapter.py+++ b/plugins/platforms/matrix/adapter.py@@ -790,48 +790,6 @@ def ensure_matrix_deps() -> bool:return True-class _CryptoStateStore:- """StateStore shim for OlmMachine (MemoryStateStore lacks is_encrypted/get_encryption_info/- find_shared_rooms); falls back to a homeserver state query when the store has no info."""-- def __init__(self, client_state_store: Any, joined_rooms: set, client=None):- self._ss = client_state_store- self._joined_rooms = joined_rooms- self._client = client- # MemoryStateStore has no set_encryption_info, so cache homeserver answers here.- self._enc_info_cache: dict = {}-- async def is_encrypted(self, room_id: str) -> bool:- return (await self.get_encryption_info(room_id)) is not None-- async def get_encryption_info(self, room_id: str):- info = await self._ss.get_encryption_info(room_id) if hasattr(self._ss, "get_encryption_info") else None- if info is not None:- return info- if room_id in self._enc_info_cache:- return self._enc_info_cache[room_id]- if self._client is None:- return None- try:- from mautrix.types import EventType as _ET, RoomEncryptionStateEventContent as _Enc, RoomID as _RID- raw = await self._client.get_state_event(_RID(room_id), _ET.ROOM_ENCRYPTION)- except Exception as exc:- logger.debug("Matrix: homeserver encryption-info query failed for %s: %s", room_id, exc)- return None- if not raw:- return None- content = raw if isinstance(raw, _Enc) else _Enc.deserialize(- raw.serialize() if hasattr(raw, "serialize") else raw)- if hasattr(self._ss, "set_encryption_info"):- with suppress(Exception):- await self._ss.set_encryption_info(_RID(room_id), content)- self._enc_info_cache[room_id] = content- return content-- async def find_shared_rooms(self, user_id: str) -> list:- return list(self._joined_rooms) # all joined rooms: correct for a single-user bot--class MatrixAdapter(BasePlatformAdapter):"""Gateway adapter for Matrix (any homeserver)."""@@ -1257,6 +1215,7 @@ class MatrixAdapter(BasePlatformAdapter):if not _store_was_reset and not await self._migrate_legacy_crypto_pickle(crypto_store, crypto_db, _acct_id, _pickle_key):logger.warning("Matrix: crypto pickle migration failed — E2EE may not work correctly")+ from plugins.platforms.matrix.adapter_crypto import _CryptoStateStorecrypto_state = _CryptoStateStore(state_store, self._joined_rooms, client)olm = OlmMachine(client, crypto_store, crypto_state)olm.share_keys_min_trust = TrustState.UNVERIFIEDdiff --git a/plugins/platforms/matrix/adapter_crypto.py b/plugins/platforms/matrix/adapter_crypto.pynew file mode 100644index 00000000000..6510ffecb5b--- /dev/null+++ b/plugins/platforms/matrix/adapter_crypto.py@@ -0,0 +1,51 @@+"""Matrix E2EE crypto state-store shim handed to mautrix's OlmMachine."""++from __future__ import annotations++import logging+from contextlib import suppress+from typing import Any++logger = logging.getLogger(__name__)+++class _CryptoStateStore:+ """StateStore shim for OlmMachine (MemoryStateStore lacks is_encrypted/get_encryption_info/+ find_shared_rooms); falls back to a homeserver state query when the store has no info."""++ def __init__(self, client_state_store: Any, joined_rooms: set, client=None):+ self._ss = client_state_store+ self._joined_rooms = joined_rooms+ self._client = client+ # MemoryStateStore has no set_encryption_info, so cache homeserver answers here.+ self._enc_info_cache: dict = {}++ async def is_encrypted(self, room_id: str) -> bool:+ return (await self.get_encryption_info(room_id)) is not None++ async def get_encryption_info(self, room_id: str):+ info = await self._ss.get_encryption_info(room_id) if hasattr(self._ss, "get_encryption_info") else None+ if info is not None:+ return info+ if room_id in self._enc_info_cache:+ return self._enc_info_cache[room_id]+ if self._client is None:+ return None+ try:+ from mautrix.types import EventType as _ET, RoomEncryptionStateEventContent as _Enc, RoomID as _RID+ raw = await self._client.get_state_event(_RID(room_id), _ET.ROOM_ENCRYPTION)+ except Exception as exc:+ logger.debug("Matrix: homeserver encryption-info query failed for %s: %s", room_id, exc)+ return None+ if not raw:+ return None+ content = raw if isinstance(raw, _Enc) else _Enc.deserialize(+ raw.serialize() if hasattr(raw, "serialize") else raw)+ if hasattr(self._ss, "set_encryption_info"):+ with suppress(Exception):+ await self._ss.set_encryption_info(_RID(room_id), content)+ self._enc_info_cache[room_id] = content+ return content++ async def find_shared_rooms(self, user_id: str) -> list:+ return list(self._joined_rooms) # all joined rooms: correct for a single-user botdiff --git a/tests/gateway/test_matrix.py b/tests/gateway/test_matrix.pyindex 4161ae63142..06c73aa32b5 100644--- a/tests/gateway/test_matrix.py+++ b/tests/gateway/test_matrix.py@@ -1,6 +1,5 @@"""Tests for Matrix platform adapter (mautrix-python backend)."""import asyncio-import loggingimport sysimport timeimport types@@ -1170,70 +1169,6 @@ 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- @pytest.mark.parametrize("mode, hint", [- ("off", "set MATRIX_E2EE_MODE=optional"),- # Degraded optional mode: the install/enable advice is wrong; point at the setup failure.- ("optional", "E2EE mode is optional but the decryptor was not set up"),- ])- async def test_absorb_sync_warns_once_per_room_for_encrypted_events_without_crypto(- self, caplog, mode, hint- ):- """Encrypted events with no decryptor must fail loud, once per room (#131778)."""- adapter = _make_adapter()- adapter._closing = False- adapter._e2ee_mode = mode- 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"}]}},- "!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)- await adapter._absorb_sync(fake_client, sync_data) # rate-limited: one warning per room-- warnings = [r.getMessage() for r in caplog.records if "encrypted" in r.getMessage()]- assert len(warnings) == 1- assert "!enc:example.org" in warnings[0] and hint in warnings[0]- assert (mode == "off") == ("pip install" in warnings[0])-- @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.asyncioasync def test_sync_loop_dispatches_registered_room_message_handler(self):"""Inbound sync data should flow through handle_sync into message handling."""@@ -1637,7 +1572,7 @@ class TestMatrixEncryptedSendFallback:class TestJoinedRoomsReference:def test_joined_rooms_reference_preserved_after_reassignment(self):"""_CryptoStateStore must see updates after initial sync populates rooms."""- from plugins.platforms.matrix.adapter import _CryptoStateStore+ from plugins.platforms.matrix.adapter_crypto import _CryptoStateStorejoined = set()store = _CryptoStateStore(MagicMock(), joined)diff --git a/tests/gateway/test_matrix_encrypted_drop_warning.py b/tests/gateway/test_matrix_encrypted_drop_warning.pynew file mode 100644index 00000000000..4951348c3c8--- /dev/null+++ b/tests/gateway/test_matrix_encrypted_drop_warning.py@@ -0,0 +1,87 @@+"""Matrix fails loud when encrypted room events arrive with no E2EE decryptor (#131778)."""+import logging+from unittest.mock import AsyncMock, MagicMock++import pytest++from gateway.config import PlatformConfig+++def _make_adapter():+ from plugins.platforms.matrix.adapter import MatrixAdapter+ config = PlatformConfig(+ enabled=True,+ token="syt_test_token",+ extra={+ "homeserver": "https://matrix.example.org",+ "user_id": "@bot:example.org",+ },+ )+ return MatrixAdapter(config)+++class TestMatrixEncryptedDropWarning:++ @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+ @pytest.mark.parametrize("mode, hint", [+ ("off", "set MATRIX_E2EE_MODE=optional"),+ # Degraded optional mode: the install/enable advice is wrong; point at the setup failure.+ ("optional", "E2EE mode is optional but the decryptor was not set up"),+ ])+ async def test_absorb_sync_warns_once_per_room_for_encrypted_events_without_crypto(+ self, caplog, mode, hint+ ):+ """Encrypted events with no decryptor must fail loud, once per room (#131778)."""+ adapter = _make_adapter()+ adapter._closing = False+ adapter._e2ee_mode = mode+ 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"}]}},+ "!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)+ await adapter._absorb_sync(fake_client, sync_data) # rate-limited: one warning per room++ warnings = [r.getMessage() for r in caplog.records if "encrypted" in r.getMessage()]+ assert len(warnings) == 1+ assert "!enc:example.org" in warnings[0] and hint in warnings[0]+ assert (mode == "off") == ("pip install" in warnings[0])++ @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()]