test_federation_event.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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. member_event.event_id,
  86. ]
  87. # mock up a load of state events which we are missing
  88. state_events = [
  89. make_event_from_dict(
  90. self.add_hashes_and_signatures_from_other_server(
  91. {
  92. "type": "test_state_type",
  93. "state_key": f"state_{i}",
  94. "room_id": room_id,
  95. "sender": OTHER_USER,
  96. "prev_events": [member_event.event_id],
  97. "auth_events": auth_event_ids,
  98. "origin_server_ts": 1,
  99. "depth": 10,
  100. "content": {"body": f"state_{i}"},
  101. }
  102. ),
  103. room_version,
  104. )
  105. for i in range(1, 10)
  106. ]
  107. # this is the state that we are going to claim is active at the prev_event.
  108. state_at_prev_event = state_events + self.get_success(
  109. main_store.get_events_as_list(initial_state_map.values())
  110. )
  111. # mock up a prev event.
  112. # Depending on the test, we either persist this upfront (as an outlier),
  113. # or let the server request it.
  114. prev_event = make_event_from_dict(
  115. self.add_hashes_and_signatures_from_other_server(
  116. {
  117. "type": "test_regular_type",
  118. "room_id": room_id,
  119. "sender": OTHER_USER,
  120. "prev_events": [],
  121. "auth_events": auth_event_ids,
  122. "origin_server_ts": 1,
  123. "depth": 11,
  124. "content": {"body": "missing_prev"},
  125. }
  126. ),
  127. room_version,
  128. )
  129. if prev_exists_as_outlier:
  130. prev_event.internal_metadata.outlier = True
  131. persistence = self.hs.get_storage_controllers().persistence
  132. self.get_success(
  133. persistence.persist_event(
  134. prev_event,
  135. EventContext.for_outlier(self.hs.get_storage_controllers()),
  136. )
  137. )
  138. else:
  139. async def get_event(destination: str, event_id: str, timeout=None):
  140. self.assertEqual(destination, self.OTHER_SERVER_NAME)
  141. self.assertEqual(event_id, prev_event.event_id)
  142. return {"pdus": [prev_event.get_pdu_json()]}
  143. self.mock_federation_transport_client.get_event.side_effect = get_event
  144. # mock up a regular event to pass into _process_pulled_event
  145. pulled_event = make_event_from_dict(
  146. self.add_hashes_and_signatures_from_other_server(
  147. {
  148. "type": "test_regular_type",
  149. "room_id": room_id,
  150. "sender": OTHER_USER,
  151. "prev_events": [prev_event.event_id],
  152. "auth_events": auth_event_ids,
  153. "origin_server_ts": 1,
  154. "depth": 12,
  155. "content": {"body": "pulled"},
  156. }
  157. ),
  158. room_version,
  159. )
  160. # we expect an outbound request to /state_ids, so stub that out
  161. self.mock_federation_transport_client.get_room_state_ids.return_value = (
  162. make_awaitable(
  163. {
  164. "pdu_ids": [e.event_id for e in state_at_prev_event],
  165. "auth_chain_ids": [],
  166. }
  167. )
  168. )
  169. # we also expect an outbound request to /state
  170. self.mock_federation_transport_client.get_room_state.return_value = (
  171. make_awaitable(
  172. StateRequestResponse(auth_events=[], state=state_at_prev_event)
  173. )
  174. )
  175. # we have to bump the clock a bit, to keep the retry logic in
  176. # FederationClient.get_pdu happy
  177. self.reactor.advance(60000)
  178. # Finally, the call under test: send the pulled event into _process_pulled_event
  179. with LoggingContext("test"):
  180. self.get_success(
  181. self.hs.get_federation_event_handler()._process_pulled_event(
  182. self.OTHER_SERVER_NAME, pulled_event, backfilled=False
  183. )
  184. )
  185. # check that the event is correctly persisted
  186. persisted = self.get_success(main_store.get_event(pulled_event.event_id))
  187. self.assertIsNotNone(persisted, "pulled event was not persisted at all")
  188. self.assertFalse(
  189. persisted.internal_metadata.is_outlier(), "pulled event was an outlier"
  190. )
  191. # check that the state at that event is as expected
  192. state = self.get_success(
  193. state_storage_controller.get_state_ids_for_event(pulled_event.event_id)
  194. )
  195. expected_state = {
  196. (e.type, e.state_key): e.event_id for e in state_at_prev_event
  197. }
  198. self.assertEqual(state, expected_state)
  199. if prev_exists_as_outlier:
  200. self.mock_federation_transport_client.get_event.assert_not_called()