test_federation.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. # Copyright 2020 The Matrix.org Foundation C.I.C.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from typing import Collection, List, Optional, Union
  15. from unittest.mock import AsyncMock, Mock
  16. from twisted.test.proto_helpers import MemoryReactor
  17. from synapse.api.errors import FederationError
  18. from synapse.api.room_versions import RoomVersion, RoomVersions
  19. from synapse.events import EventBase, make_event_from_dict
  20. from synapse.events.snapshot import EventContext
  21. from synapse.federation.federation_base import event_from_pdu_json
  22. from synapse.handlers.device import DeviceListUpdater
  23. from synapse.http.types import QueryParams
  24. from synapse.logging.context import LoggingContext
  25. from synapse.server import HomeServer
  26. from synapse.types import JsonDict, UserID, create_requester
  27. from synapse.util import Clock
  28. from synapse.util.retryutils import NotRetryingDestination
  29. from tests import unittest
  30. class MessageAcceptTests(unittest.HomeserverTestCase):
  31. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  32. self.http_client = Mock()
  33. return self.setup_test_homeserver(federation_http_client=self.http_client)
  34. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  35. user_id = UserID("us", "test")
  36. our_user = create_requester(user_id)
  37. room_creator = self.hs.get_room_creation_handler()
  38. self.room_id = self.get_success(
  39. room_creator.create_room(
  40. our_user, room_creator._presets_dict["public_chat"], ratelimit=False
  41. )
  42. )[0]
  43. self.store = self.hs.get_datastores().main
  44. # Figure out what the most recent event is
  45. most_recent = self.get_success(
  46. self.hs.get_datastores().main.get_latest_event_ids_in_room(self.room_id)
  47. )[0]
  48. join_event = make_event_from_dict(
  49. {
  50. "room_id": self.room_id,
  51. "sender": "@baduser:test.serv",
  52. "state_key": "@baduser:test.serv",
  53. "event_id": "$join:test.serv",
  54. "depth": 1000,
  55. "origin_server_ts": 1,
  56. "type": "m.room.member",
  57. "origin": "test.servx",
  58. "content": {"membership": "join"},
  59. "auth_events": [],
  60. "prev_state": [(most_recent, {})],
  61. "prev_events": [(most_recent, {})],
  62. }
  63. )
  64. self.handler = self.hs.get_federation_handler()
  65. federation_event_handler = self.hs.get_federation_event_handler()
  66. async def _check_event_auth(
  67. origin: Optional[str], event: EventBase, context: EventContext
  68. ) -> None:
  69. pass
  70. federation_event_handler._check_event_auth = _check_event_auth # type: ignore[method-assign]
  71. self.client = self.hs.get_federation_client()
  72. async def _check_sigs_and_hash_for_pulled_events_and_fetch(
  73. dest: str, pdus: Collection[EventBase], room_version: RoomVersion
  74. ) -> List[EventBase]:
  75. return list(pdus)
  76. self.client._check_sigs_and_hash_for_pulled_events_and_fetch = _check_sigs_and_hash_for_pulled_events_and_fetch # type: ignore[assignment]
  77. # Send the join, it should return None (which is not an error)
  78. self.assertEqual(
  79. self.get_success(
  80. federation_event_handler.on_receive_pdu("test.serv", join_event)
  81. ),
  82. None,
  83. )
  84. # Make sure we actually joined the room
  85. self.assertEqual(
  86. self.get_success(self.store.get_latest_event_ids_in_room(self.room_id))[0],
  87. "$join:test.serv",
  88. )
  89. def test_cant_hide_direct_ancestors(self) -> None:
  90. """
  91. If you send a message, you must be able to provide the direct
  92. prev_events that said event references.
  93. """
  94. async def post_json(
  95. destination: str,
  96. path: str,
  97. data: Optional[JsonDict] = None,
  98. long_retries: bool = False,
  99. timeout: Optional[int] = None,
  100. ignore_backoff: bool = False,
  101. args: Optional[QueryParams] = None,
  102. ) -> Union[JsonDict, list]:
  103. # If it asks us for new missing events, give them NOTHING
  104. if path.startswith("/_matrix/federation/v1/get_missing_events/"):
  105. return {"events": []}
  106. return {}
  107. self.http_client.post_json = post_json
  108. # Figure out what the most recent event is
  109. most_recent = self.get_success(
  110. self.store.get_latest_event_ids_in_room(self.room_id)
  111. )[0]
  112. # Now lie about an event
  113. lying_event = make_event_from_dict(
  114. {
  115. "room_id": self.room_id,
  116. "sender": "@baduser:test.serv",
  117. "event_id": "one:test.serv",
  118. "depth": 1000,
  119. "origin_server_ts": 1,
  120. "type": "m.room.message",
  121. "origin": "test.serv",
  122. "content": {"body": "hewwo?"},
  123. "auth_events": [],
  124. "prev_events": [("two:test.serv", {}), (most_recent, {})],
  125. }
  126. )
  127. federation_event_handler = self.hs.get_federation_event_handler()
  128. with LoggingContext("test-context"):
  129. failure = self.get_failure(
  130. federation_event_handler.on_receive_pdu("test.serv", lying_event),
  131. FederationError,
  132. )
  133. # on_receive_pdu should throw an error
  134. self.assertEqual(
  135. failure.value.args[0],
  136. (
  137. "ERROR 403: Your server isn't divulging details about prev_events "
  138. "referenced in this event."
  139. ),
  140. )
  141. # Make sure the invalid event isn't there
  142. extrem = self.get_success(self.store.get_latest_event_ids_in_room(self.room_id))
  143. self.assertEqual(extrem[0], "$join:test.serv")
  144. def test_retry_device_list_resync(self) -> None:
  145. """Tests that device lists are marked as stale if they couldn't be synced, and
  146. that stale device lists are retried periodically.
  147. """
  148. remote_user_id = "@john:test_remote"
  149. remote_origin = "test_remote"
  150. # Track the number of attempts to resync the user's device list.
  151. self.resync_attempts = 0
  152. # When this function is called, increment the number of resync attempts (only if
  153. # we're querying devices for the right user ID), then raise a
  154. # NotRetryingDestination error to fail the resync gracefully.
  155. def query_user_devices(
  156. destination: str, user_id: str, timeout: int = 30000
  157. ) -> JsonDict:
  158. if user_id == remote_user_id:
  159. self.resync_attempts += 1
  160. raise NotRetryingDestination(0, 0, destination)
  161. # Register the mock on the federation client.
  162. federation_client = self.hs.get_federation_client()
  163. federation_client.query_user_devices = Mock(side_effect=query_user_devices) # type: ignore[method-assign]
  164. # Register a mock on the store so that the incoming update doesn't fail because
  165. # we don't share a room with the user.
  166. store = self.hs.get_datastores().main
  167. store.get_rooms_for_user = AsyncMock(return_value=["!someroom:test"])
  168. # Manually inject a fake device list update. We need this update to include at
  169. # least one prev_id so that the user's device list will need to be retried.
  170. device_list_updater = self.hs.get_device_handler().device_list_updater
  171. assert isinstance(device_list_updater, DeviceListUpdater)
  172. self.get_success(
  173. device_list_updater.incoming_device_list_update(
  174. origin=remote_origin,
  175. edu_content={
  176. "deleted": False,
  177. "device_display_name": "Mobile",
  178. "device_id": "QBUAZIFURK",
  179. "prev_id": [5],
  180. "stream_id": 6,
  181. "user_id": remote_user_id,
  182. },
  183. )
  184. )
  185. # Check that there was one resync attempt.
  186. self.assertEqual(self.resync_attempts, 1)
  187. # Check that the resync attempt failed and caused the user's device list to be
  188. # marked as stale.
  189. need_resync = self.get_success(
  190. store.get_user_ids_requiring_device_list_resync()
  191. )
  192. self.assertIn(remote_user_id, need_resync)
  193. # Check that waiting for 30 seconds caused Synapse to retry resyncing the device
  194. # list.
  195. self.reactor.advance(30)
  196. self.assertEqual(self.resync_attempts, 2)
  197. def test_cross_signing_keys_retry(self) -> None:
  198. """Tests that resyncing a device list correctly processes cross-signing keys from
  199. the remote server.
  200. """
  201. remote_user_id = "@john:test_remote"
  202. remote_master_key = "85T7JXPFBAySB/jwby4S3lBPTqY3+Zg53nYuGmu1ggY"
  203. remote_self_signing_key = "QeIiFEjluPBtI7WQdG365QKZcFs9kqmHir6RBD0//nQ"
  204. # Register mock device list retrieval on the federation client.
  205. federation_client = self.hs.get_federation_client()
  206. federation_client.query_user_devices = AsyncMock( # type: ignore[method-assign]
  207. return_value={
  208. "user_id": remote_user_id,
  209. "stream_id": 1,
  210. "devices": [],
  211. "master_key": {
  212. "user_id": remote_user_id,
  213. "usage": ["master"],
  214. "keys": {"ed25519:" + remote_master_key: remote_master_key},
  215. },
  216. "self_signing_key": {
  217. "user_id": remote_user_id,
  218. "usage": ["self_signing"],
  219. "keys": {
  220. "ed25519:" + remote_self_signing_key: remote_self_signing_key
  221. },
  222. },
  223. }
  224. )
  225. # Resync the device list.
  226. device_handler = self.hs.get_device_handler()
  227. self.get_success(
  228. device_handler.device_list_updater.multi_user_device_resync(
  229. [remote_user_id]
  230. ),
  231. )
  232. # Retrieve the cross-signing keys for this user.
  233. keys = self.get_success(
  234. self.store.get_e2e_cross_signing_keys_bulk(user_ids=[remote_user_id]),
  235. )
  236. self.assertIn(remote_user_id, keys)
  237. key = keys[remote_user_id]
  238. assert key is not None
  239. # Check that the master key is the one returned by the mock.
  240. master_key = key["master"]
  241. self.assertEqual(len(master_key["keys"]), 1)
  242. self.assertTrue("ed25519:" + remote_master_key in master_key["keys"].keys())
  243. self.assertTrue(remote_master_key in master_key["keys"].values())
  244. # Check that the self-signing key is the one returned by the mock.
  245. self_signing_key = key["self_signing"]
  246. self.assertEqual(len(self_signing_key["keys"]), 1)
  247. self.assertTrue(
  248. "ed25519:" + remote_self_signing_key in self_signing_key["keys"].keys(),
  249. )
  250. self.assertTrue(remote_self_signing_key in self_signing_key["keys"].values())
  251. class StripUnsignedFromEventsTestCase(unittest.TestCase):
  252. def test_strip_unauthorized_unsigned_values(self) -> None:
  253. event1 = {
  254. "sender": "@baduser:test.serv",
  255. "state_key": "@baduser:test.serv",
  256. "event_id": "$event1:test.serv",
  257. "depth": 1000,
  258. "origin_server_ts": 1,
  259. "type": "m.room.member",
  260. "origin": "test.servx",
  261. "content": {"membership": "join"},
  262. "auth_events": [],
  263. "unsigned": {"malicious garbage": "hackz", "more warez": "more hackz"},
  264. }
  265. filtered_event = event_from_pdu_json(event1, RoomVersions.V1)
  266. # Make sure unauthorized fields are stripped from unsigned
  267. self.assertNotIn("more warez", filtered_event.unsigned)
  268. def test_strip_event_maintains_allowed_fields(self) -> None:
  269. event2 = {
  270. "sender": "@baduser:test.serv",
  271. "state_key": "@baduser:test.serv",
  272. "event_id": "$event2:test.serv",
  273. "depth": 1000,
  274. "origin_server_ts": 1,
  275. "type": "m.room.member",
  276. "origin": "test.servx",
  277. "auth_events": [],
  278. "content": {"membership": "join"},
  279. "unsigned": {
  280. "malicious garbage": "hackz",
  281. "more warez": "more hackz",
  282. "age": 14,
  283. "invite_room_state": [],
  284. },
  285. }
  286. filtered_event2 = event_from_pdu_json(event2, RoomVersions.V1)
  287. self.assertIn("age", filtered_event2.unsigned)
  288. self.assertEqual(14, filtered_event2.unsigned["age"])
  289. self.assertNotIn("more warez", filtered_event2.unsigned)
  290. # Invite_room_state is allowed in events of type m.room.member
  291. self.assertIn("invite_room_state", filtered_event2.unsigned)
  292. self.assertEqual([], filtered_event2.unsigned["invite_room_state"])
  293. def test_strip_event_removes_fields_based_on_event_type(self) -> None:
  294. event3 = {
  295. "sender": "@baduser:test.serv",
  296. "state_key": "@baduser:test.serv",
  297. "event_id": "$event3:test.serv",
  298. "depth": 1000,
  299. "origin_server_ts": 1,
  300. "type": "m.room.power_levels",
  301. "origin": "test.servx",
  302. "content": {},
  303. "auth_events": [],
  304. "unsigned": {
  305. "malicious garbage": "hackz",
  306. "more warez": "more hackz",
  307. "age": 14,
  308. "invite_room_state": [],
  309. },
  310. }
  311. filtered_event3 = event_from_pdu_json(event3, RoomVersions.V1)
  312. self.assertIn("age", filtered_event3.unsigned)
  313. # Invite_room_state field is only permitted in event type m.room.member
  314. self.assertNotIn("invite_room_state", filtered_event3.unsigned)
  315. self.assertNotIn("more warez", filtered_event3.unsigned)