test_federation.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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.events import make_event_from_dict
  18. from synapse.logging.context import LoggingContext
  19. from synapse.types import UserID, create_requester
  20. from synapse.util import Clock
  21. from synapse.util.retryutils import NotRetryingDestination
  22. from tests import unittest
  23. from tests.server import ThreadedMemoryReactorClock, setup_test_homeserver
  24. from tests.test_utils import make_awaitable
  25. class MessageAcceptTests(unittest.HomeserverTestCase):
  26. def setUp(self):
  27. self.http_client = Mock()
  28. self.reactor = ThreadedMemoryReactorClock()
  29. self.hs_clock = Clock(self.reactor)
  30. self.homeserver = setup_test_homeserver(
  31. self.addCleanup,
  32. federation_http_client=self.http_client,
  33. clock=self.hs_clock,
  34. reactor=self.reactor,
  35. )
  36. user_id = UserID("us", "test")
  37. our_user = create_requester(user_id)
  38. room_creator = self.homeserver.get_room_creation_handler()
  39. self.room_id = self.get_success(
  40. room_creator.create_room(
  41. our_user, room_creator._presets_dict["public_chat"], ratelimit=False
  42. )
  43. )[0]["room_id"]
  44. self.store = self.homeserver.get_datastore()
  45. # Figure out what the most recent event is
  46. most_recent = self.get_success(
  47. self.homeserver.get_datastore().get_latest_event_ids_in_room(self.room_id)
  48. )[0]
  49. join_event = make_event_from_dict(
  50. {
  51. "room_id": self.room_id,
  52. "sender": "@baduser:test.serv",
  53. "state_key": "@baduser:test.serv",
  54. "event_id": "$join:test.serv",
  55. "depth": 1000,
  56. "origin_server_ts": 1,
  57. "type": "m.room.member",
  58. "origin": "test.servx",
  59. "content": {"membership": "join"},
  60. "auth_events": [],
  61. "prev_state": [(most_recent, {})],
  62. "prev_events": [(most_recent, {})],
  63. }
  64. )
  65. self.handler = self.homeserver.get_federation_handler()
  66. self.handler._check_event_auth = lambda origin, event, context, state, claimed_auth_event_map, backfilled: succeed(
  67. context
  68. )
  69. self.client = self.homeserver.get_federation_client()
  70. self.client._check_sigs_and_hash_and_fetch = lambda dest, pdus, **k: succeed(
  71. pdus
  72. )
  73. # Send the join, it should return None (which is not an error)
  74. self.assertEqual(
  75. self.get_success(self.handler.on_receive_pdu("test.serv", join_event)),
  76. None,
  77. )
  78. # Make sure we actually joined the room
  79. self.assertEqual(
  80. self.get_success(self.store.get_latest_event_ids_in_room(self.room_id))[0],
  81. "$join:test.serv",
  82. )
  83. def test_cant_hide_direct_ancestors(self):
  84. """
  85. If you send a message, you must be able to provide the direct
  86. prev_events that said event references.
  87. """
  88. async def post_json(destination, path, data, headers=None, timeout=0):
  89. # If it asks us for new missing events, give them NOTHING
  90. if path.startswith("/_matrix/federation/v1/get_missing_events/"):
  91. return {"events": []}
  92. self.http_client.post_json = post_json
  93. # Figure out what the most recent event is
  94. most_recent = self.get_success(
  95. self.store.get_latest_event_ids_in_room(self.room_id)
  96. )[0]
  97. # Now lie about an event
  98. lying_event = make_event_from_dict(
  99. {
  100. "room_id": self.room_id,
  101. "sender": "@baduser:test.serv",
  102. "event_id": "one:test.serv",
  103. "depth": 1000,
  104. "origin_server_ts": 1,
  105. "type": "m.room.message",
  106. "origin": "test.serv",
  107. "content": {"body": "hewwo?"},
  108. "auth_events": [],
  109. "prev_events": [("two:test.serv", {}), (most_recent, {})],
  110. }
  111. )
  112. with LoggingContext("test-context"):
  113. failure = self.get_failure(
  114. self.handler.on_receive_pdu("test.serv", lying_event),
  115. FederationError,
  116. )
  117. # on_receive_pdu should throw an error
  118. self.assertEqual(
  119. failure.value.args[0],
  120. (
  121. "ERROR 403: Your server isn't divulging details about prev_events "
  122. "referenced in this event."
  123. ),
  124. )
  125. # Make sure the invalid event isn't there
  126. extrem = self.get_success(self.store.get_latest_event_ids_in_room(self.room_id))
  127. self.assertEqual(extrem[0], "$join:test.serv")
  128. def test_retry_device_list_resync(self):
  129. """Tests that device lists are marked as stale if they couldn't be synced, and
  130. that stale device lists are retried periodically.
  131. """
  132. remote_user_id = "@john:test_remote"
  133. remote_origin = "test_remote"
  134. # Track the number of attempts to resync the user's device list.
  135. self.resync_attempts = 0
  136. # When this function is called, increment the number of resync attempts (only if
  137. # we're querying devices for the right user ID), then raise a
  138. # NotRetryingDestination error to fail the resync gracefully.
  139. def query_user_devices(destination, user_id):
  140. if user_id == remote_user_id:
  141. self.resync_attempts += 1
  142. raise NotRetryingDestination(0, 0, destination)
  143. # Register the mock on the federation client.
  144. federation_client = self.homeserver.get_federation_client()
  145. federation_client.query_user_devices = Mock(side_effect=query_user_devices)
  146. # Register a mock on the store so that the incoming update doesn't fail because
  147. # we don't share a room with the user.
  148. store = self.homeserver.get_datastore()
  149. store.get_rooms_for_user = Mock(return_value=make_awaitable(["!someroom:test"]))
  150. # Manually inject a fake device list update. We need this update to include at
  151. # least one prev_id so that the user's device list will need to be retried.
  152. device_list_updater = self.homeserver.get_device_handler().device_list_updater
  153. self.get_success(
  154. device_list_updater.incoming_device_list_update(
  155. origin=remote_origin,
  156. edu_content={
  157. "deleted": False,
  158. "device_display_name": "Mobile",
  159. "device_id": "QBUAZIFURK",
  160. "prev_id": [5],
  161. "stream_id": 6,
  162. "user_id": remote_user_id,
  163. },
  164. )
  165. )
  166. # Check that there was one resync attempt.
  167. self.assertEqual(self.resync_attempts, 1)
  168. # Check that the resync attempt failed and caused the user's device list to be
  169. # marked as stale.
  170. need_resync = self.get_success(
  171. store.get_user_ids_requiring_device_list_resync()
  172. )
  173. self.assertIn(remote_user_id, need_resync)
  174. # Check that waiting for 30 seconds caused Synapse to retry resyncing the device
  175. # list.
  176. self.reactor.advance(30)
  177. self.assertEqual(self.resync_attempts, 2)
  178. def test_cross_signing_keys_retry(self):
  179. """Tests that resyncing a device list correctly processes cross-signing keys from
  180. the remote server.
  181. """
  182. remote_user_id = "@john:test_remote"
  183. remote_master_key = "85T7JXPFBAySB/jwby4S3lBPTqY3+Zg53nYuGmu1ggY"
  184. remote_self_signing_key = "QeIiFEjluPBtI7WQdG365QKZcFs9kqmHir6RBD0//nQ"
  185. # Register mock device list retrieval on the federation client.
  186. federation_client = self.homeserver.get_federation_client()
  187. federation_client.query_user_devices = Mock(
  188. return_value=succeed(
  189. {
  190. "user_id": remote_user_id,
  191. "stream_id": 1,
  192. "devices": [],
  193. "master_key": {
  194. "user_id": remote_user_id,
  195. "usage": ["master"],
  196. "keys": {"ed25519:" + remote_master_key: remote_master_key},
  197. },
  198. "self_signing_key": {
  199. "user_id": remote_user_id,
  200. "usage": ["self_signing"],
  201. "keys": {
  202. "ed25519:"
  203. + remote_self_signing_key: remote_self_signing_key
  204. },
  205. },
  206. }
  207. )
  208. )
  209. # Resync the device list.
  210. device_handler = self.homeserver.get_device_handler()
  211. self.get_success(
  212. device_handler.device_list_updater.user_device_resync(remote_user_id),
  213. )
  214. # Retrieve the cross-signing keys for this user.
  215. keys = self.get_success(
  216. self.store.get_e2e_cross_signing_keys_bulk(user_ids=[remote_user_id]),
  217. )
  218. self.assertTrue(remote_user_id in keys)
  219. # Check that the master key is the one returned by the mock.
  220. master_key = keys[remote_user_id]["master"]
  221. self.assertEqual(len(master_key["keys"]), 1)
  222. self.assertTrue("ed25519:" + remote_master_key in master_key["keys"].keys())
  223. self.assertTrue(remote_master_key in master_key["keys"].values())
  224. # Check that the self-signing key is the one returned by the mock.
  225. self_signing_key = keys[remote_user_id]["self_signing"]
  226. self.assertEqual(len(self_signing_key["keys"]), 1)
  227. self.assertTrue(
  228. "ed25519:" + remote_self_signing_key in self_signing_key["keys"].keys(),
  229. )
  230. self.assertTrue(remote_self_signing_key in self_signing_key["keys"].values())