test_federation.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  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)