1
0

test_federation.py 14 KB

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