test_federation.py 13 KB

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