No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 
 
 
 

275 líneas
10 KiB

  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(
  76. self.handler.on_receive_pdu(
  77. "test.serv", join_event, sent_to_us_directly=True
  78. )
  79. ),
  80. None,
  81. )
  82. # Make sure we actually joined the room
  83. self.assertEqual(
  84. self.get_success(self.store.get_latest_event_ids_in_room(self.room_id))[0],
  85. "$join:test.serv",
  86. )
  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. with LoggingContext("test-context"):
  117. failure = self.get_failure(
  118. self.handler.on_receive_pdu(
  119. "test.serv", lying_event, sent_to_us_directly=True
  120. ),
  121. FederationError,
  122. )
  123. # on_receive_pdu should throw an error
  124. self.assertEqual(
  125. failure.value.args[0],
  126. (
  127. "ERROR 403: Your server isn't divulging details about prev_events "
  128. "referenced in this event."
  129. ),
  130. )
  131. # Make sure the invalid event isn't there
  132. extrem = self.get_success(self.store.get_latest_event_ids_in_room(self.room_id))
  133. self.assertEqual(extrem[0], "$join:test.serv")
  134. def test_retry_device_list_resync(self):
  135. """Tests that device lists are marked as stale if they couldn't be synced, and
  136. that stale device lists are retried periodically.
  137. """
  138. remote_user_id = "@john:test_remote"
  139. remote_origin = "test_remote"
  140. # Track the number of attempts to resync the user's device list.
  141. self.resync_attempts = 0
  142. # When this function is called, increment the number of resync attempts (only if
  143. # we're querying devices for the right user ID), then raise a
  144. # NotRetryingDestination error to fail the resync gracefully.
  145. def query_user_devices(destination, user_id):
  146. if user_id == remote_user_id:
  147. self.resync_attempts += 1
  148. raise NotRetryingDestination(0, 0, destination)
  149. # Register the mock on the federation client.
  150. federation_client = self.homeserver.get_federation_client()
  151. federation_client.query_user_devices = Mock(side_effect=query_user_devices)
  152. # Register a mock on the store so that the incoming update doesn't fail because
  153. # we don't share a room with the user.
  154. store = self.homeserver.get_datastore()
  155. store.get_rooms_for_user = Mock(return_value=make_awaitable(["!someroom:test"]))
  156. # Manually inject a fake device list update. We need this update to include at
  157. # least one prev_id so that the user's device list will need to be retried.
  158. device_list_updater = self.homeserver.get_device_handler().device_list_updater
  159. self.get_success(
  160. device_list_updater.incoming_device_list_update(
  161. origin=remote_origin,
  162. edu_content={
  163. "deleted": False,
  164. "device_display_name": "Mobile",
  165. "device_id": "QBUAZIFURK",
  166. "prev_id": [5],
  167. "stream_id": 6,
  168. "user_id": remote_user_id,
  169. },
  170. )
  171. )
  172. # Check that there was one resync attempt.
  173. self.assertEqual(self.resync_attempts, 1)
  174. # Check that the resync attempt failed and caused the user's device list to be
  175. # marked as stale.
  176. need_resync = self.get_success(
  177. store.get_user_ids_requiring_device_list_resync()
  178. )
  179. self.assertIn(remote_user_id, need_resync)
  180. # Check that waiting for 30 seconds caused Synapse to retry resyncing the device
  181. # list.
  182. self.reactor.advance(30)
  183. self.assertEqual(self.resync_attempts, 2)
  184. def test_cross_signing_keys_retry(self):
  185. """Tests that resyncing a device list correctly processes cross-signing keys from
  186. the remote server.
  187. """
  188. remote_user_id = "@john:test_remote"
  189. remote_master_key = "85T7JXPFBAySB/jwby4S3lBPTqY3+Zg53nYuGmu1ggY"
  190. remote_self_signing_key = "QeIiFEjluPBtI7WQdG365QKZcFs9kqmHir6RBD0//nQ"
  191. # Register mock device list retrieval on the federation client.
  192. federation_client = self.homeserver.get_federation_client()
  193. federation_client.query_user_devices = Mock(
  194. return_value=succeed(
  195. {
  196. "user_id": remote_user_id,
  197. "stream_id": 1,
  198. "devices": [],
  199. "master_key": {
  200. "user_id": remote_user_id,
  201. "usage": ["master"],
  202. "keys": {"ed25519:" + remote_master_key: remote_master_key},
  203. },
  204. "self_signing_key": {
  205. "user_id": remote_user_id,
  206. "usage": ["self_signing"],
  207. "keys": {
  208. "ed25519:"
  209. + remote_self_signing_key: remote_self_signing_key
  210. },
  211. },
  212. }
  213. )
  214. )
  215. # Resync the device list.
  216. device_handler = self.homeserver.get_device_handler()
  217. self.get_success(
  218. device_handler.device_list_updater.user_device_resync(remote_user_id),
  219. )
  220. # Retrieve the cross-signing keys for this user.
  221. keys = self.get_success(
  222. self.store.get_e2e_cross_signing_keys_bulk(user_ids=[remote_user_id]),
  223. )
  224. self.assertTrue(remote_user_id in keys)
  225. # Check that the master key is the one returned by the mock.
  226. master_key = keys[remote_user_id]["master"]
  227. self.assertEqual(len(master_key["keys"]), 1)
  228. self.assertTrue("ed25519:" + remote_master_key in master_key["keys"].keys())
  229. self.assertTrue(remote_master_key in master_key["keys"].values())
  230. # Check that the self-signing key is the one returned by the mock.
  231. self_signing_key = keys[remote_user_id]["self_signing"]
  232. self.assertEqual(len(self_signing_key["keys"]), 1)
  233. self.assertTrue(
  234. "ed25519:" + remote_self_signing_key in self_signing_key["keys"].keys(),
  235. )
  236. self.assertTrue(remote_self_signing_key in self_signing_key["keys"].values())