1
0

test_federation.py 11 KB

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