test_federation.py 10 KB

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