test_federation_event.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. # Copyright 2022 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 import mock
  15. from synapse.events import make_event_from_dict
  16. from synapse.events.snapshot import EventContext
  17. from synapse.federation.transport.client import StateRequestResponse
  18. from synapse.logging.context import LoggingContext
  19. from synapse.rest import admin
  20. from synapse.rest.client import login, room
  21. from tests import unittest
  22. from tests.test_utils import event_injection, make_awaitable
  23. class FederationEventHandlerTests(unittest.FederatingHomeserverTestCase):
  24. servlets = [
  25. admin.register_servlets,
  26. login.register_servlets,
  27. room.register_servlets,
  28. ]
  29. def make_homeserver(self, reactor, clock):
  30. # mock out the federation transport client
  31. self.mock_federation_transport_client = mock.Mock(
  32. spec=["get_room_state_ids", "get_room_state", "get_event"]
  33. )
  34. return super().setup_test_homeserver(
  35. federation_transport_client=self.mock_federation_transport_client
  36. )
  37. def test_process_pulled_event_with_missing_state(self) -> None:
  38. """Ensure that we correctly handle pulled events with lots of missing state
  39. In this test, we pretend we are processing a "pulled" event (eg, via backfill
  40. or get_missing_events). The pulled event has a prev_event we haven't previously
  41. seen, so the server requests the state at that prev_event. There is a lot
  42. of state we don't have, so we expect the server to make a /state request.
  43. We check that the pulled event is correctly persisted, and that the state is
  44. as we expect.
  45. """
  46. return self._test_process_pulled_event_with_missing_state(False)
  47. def test_process_pulled_event_with_missing_state_where_prev_is_outlier(
  48. self,
  49. ) -> None:
  50. """Ensure that we correctly handle pulled events with lots of missing state
  51. A slight modification to test_process_pulled_event_with_missing_state. Again
  52. we have a "pulled" event which refers to a prev_event with lots of state,
  53. but in this case we already have the prev_event (as an outlier, obviously -
  54. if it were a regular event, we wouldn't need to request the state).
  55. """
  56. return self._test_process_pulled_event_with_missing_state(True)
  57. def _test_process_pulled_event_with_missing_state(
  58. self, prev_exists_as_outlier: bool
  59. ) -> None:
  60. OTHER_USER = f"@user:{self.OTHER_SERVER_NAME}"
  61. main_store = self.hs.get_datastores().main
  62. state_storage_controller = self.hs.get_storage_controllers().state
  63. # create the room
  64. user_id = self.register_user("kermit", "test")
  65. tok = self.login("kermit", "test")
  66. room_id = self.helper.create_room_as(room_creator=user_id, tok=tok)
  67. room_version = self.get_success(main_store.get_room_version(room_id))
  68. # allow the remote user to send state events
  69. self.helper.send_state(
  70. room_id,
  71. "m.room.power_levels",
  72. {"events_default": 0, "state_default": 0},
  73. tok=tok,
  74. )
  75. # add the remote user to the room
  76. member_event = self.get_success(
  77. event_injection.inject_member_event(self.hs, room_id, OTHER_USER, "join")
  78. )
  79. initial_state_map = self.get_success(
  80. main_store.get_partial_current_state_ids(room_id)
  81. )
  82. auth_event_ids = [
  83. initial_state_map[("m.room.create", "")],
  84. initial_state_map[("m.room.power_levels", "")],
  85. initial_state_map[("m.room.join_rules", "")],
  86. member_event.event_id,
  87. ]
  88. # mock up a load of state events which we are missing
  89. state_events = [
  90. make_event_from_dict(
  91. self.add_hashes_and_signatures(
  92. {
  93. "type": "test_state_type",
  94. "state_key": f"state_{i}",
  95. "room_id": room_id,
  96. "sender": OTHER_USER,
  97. "prev_events": [member_event.event_id],
  98. "auth_events": auth_event_ids,
  99. "origin_server_ts": 1,
  100. "depth": 10,
  101. "content": {"body": f"state_{i}"},
  102. }
  103. ),
  104. room_version,
  105. )
  106. for i in range(1, 10)
  107. ]
  108. # this is the state that we are going to claim is active at the prev_event.
  109. state_at_prev_event = state_events + self.get_success(
  110. main_store.get_events_as_list(initial_state_map.values())
  111. )
  112. # mock up a prev event.
  113. # Depending on the test, we either persist this upfront (as an outlier),
  114. # or let the server request it.
  115. prev_event = make_event_from_dict(
  116. self.add_hashes_and_signatures(
  117. {
  118. "type": "test_regular_type",
  119. "room_id": room_id,
  120. "sender": OTHER_USER,
  121. "prev_events": [],
  122. "auth_events": auth_event_ids,
  123. "origin_server_ts": 1,
  124. "depth": 11,
  125. "content": {"body": "missing_prev"},
  126. }
  127. ),
  128. room_version,
  129. )
  130. if prev_exists_as_outlier:
  131. prev_event.internal_metadata.outlier = True
  132. persistence = self.hs.get_storage_controllers().persistence
  133. self.get_success(
  134. persistence.persist_event(
  135. prev_event,
  136. EventContext.for_outlier(self.hs.get_storage_controllers()),
  137. )
  138. )
  139. else:
  140. async def get_event(destination: str, event_id: str, timeout=None):
  141. self.assertEqual(destination, self.OTHER_SERVER_NAME)
  142. self.assertEqual(event_id, prev_event.event_id)
  143. return {"pdus": [prev_event.get_pdu_json()]}
  144. self.mock_federation_transport_client.get_event.side_effect = get_event
  145. # mock up a regular event to pass into _process_pulled_event
  146. pulled_event = make_event_from_dict(
  147. self.add_hashes_and_signatures(
  148. {
  149. "type": "test_regular_type",
  150. "room_id": room_id,
  151. "sender": OTHER_USER,
  152. "prev_events": [prev_event.event_id],
  153. "auth_events": auth_event_ids,
  154. "origin_server_ts": 1,
  155. "depth": 12,
  156. "content": {"body": "pulled"},
  157. }
  158. ),
  159. room_version,
  160. )
  161. # we expect an outbound request to /state_ids, so stub that out
  162. self.mock_federation_transport_client.get_room_state_ids.return_value = (
  163. make_awaitable(
  164. {
  165. "pdu_ids": [e.event_id for e in state_at_prev_event],
  166. "auth_chain_ids": [],
  167. }
  168. )
  169. )
  170. # we also expect an outbound request to /state
  171. self.mock_federation_transport_client.get_room_state.return_value = (
  172. make_awaitable(
  173. StateRequestResponse(auth_events=[], state=state_at_prev_event)
  174. )
  175. )
  176. # we have to bump the clock a bit, to keep the retry logic in
  177. # FederationClient.get_pdu happy
  178. self.reactor.advance(60000)
  179. # Finally, the call under test: send the pulled event into _process_pulled_event
  180. with LoggingContext("test"):
  181. self.get_success(
  182. self.hs.get_federation_event_handler()._process_pulled_event(
  183. self.OTHER_SERVER_NAME, pulled_event, backfilled=False
  184. )
  185. )
  186. # check that the event is correctly persisted
  187. persisted = self.get_success(main_store.get_event(pulled_event.event_id))
  188. self.assertIsNotNone(persisted, "pulled event was not persisted at all")
  189. self.assertFalse(
  190. persisted.internal_metadata.is_outlier(), "pulled event was an outlier"
  191. )
  192. # check that the state at that event is as expected
  193. state = self.get_success(
  194. state_storage_controller.get_state_ids_for_event(pulled_event.event_id)
  195. )
  196. expected_state = {
  197. (e.type, e.state_key): e.event_id for e in state_at_prev_event
  198. }
  199. self.assertEqual(state, expected_state)
  200. if prev_exists_as_outlier:
  201. self.mock_federation_transport_client.get_event.assert_not_called()