1
0

test_federation.py 11 KB

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