test_federation_event.py 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047
  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 typing import Optional
  15. from unittest import mock
  16. from synapse.api.errors import AuthError, StoreError
  17. from synapse.api.room_versions import RoomVersion
  18. from synapse.event_auth import (
  19. check_state_dependent_auth_rules,
  20. check_state_independent_auth_rules,
  21. )
  22. from synapse.events import make_event_from_dict
  23. from synapse.events.snapshot import EventContext
  24. from synapse.federation.transport.client import StateRequestResponse
  25. from synapse.logging.context import LoggingContext
  26. from synapse.rest import admin
  27. from synapse.rest.client import login, room
  28. from synapse.state.v2 import _mainline_sort, _reverse_topological_power_sort
  29. from synapse.types import JsonDict
  30. from tests import unittest
  31. from tests.test_utils import event_injection, make_awaitable
  32. class FederationEventHandlerTests(unittest.FederatingHomeserverTestCase):
  33. servlets = [
  34. admin.register_servlets,
  35. login.register_servlets,
  36. room.register_servlets,
  37. ]
  38. def make_homeserver(self, reactor, clock):
  39. # mock out the federation transport client
  40. self.mock_federation_transport_client = mock.Mock(
  41. spec=["get_room_state_ids", "get_room_state", "get_event", "backfill"]
  42. )
  43. return super().setup_test_homeserver(
  44. federation_transport_client=self.mock_federation_transport_client
  45. )
  46. def test_process_pulled_event_with_missing_state(self) -> None:
  47. """Ensure that we correctly handle pulled events with lots of missing state
  48. In this test, we pretend we are processing a "pulled" event (eg, via backfill
  49. or get_missing_events). The pulled event has a prev_event we haven't previously
  50. seen, so the server requests the state at that prev_event. There is a lot
  51. of state we don't have, so we expect the server to make a /state request.
  52. We check that the pulled event is correctly persisted, and that the state is
  53. as we expect.
  54. """
  55. return self._test_process_pulled_event_with_missing_state(False)
  56. def test_process_pulled_event_with_missing_state_where_prev_is_outlier(
  57. self,
  58. ) -> None:
  59. """Ensure that we correctly handle pulled events with lots of missing state
  60. A slight modification to test_process_pulled_event_with_missing_state. Again
  61. we have a "pulled" event which refers to a prev_event with lots of state,
  62. but in this case we already have the prev_event (as an outlier, obviously -
  63. if it were a regular event, we wouldn't need to request the state).
  64. """
  65. return self._test_process_pulled_event_with_missing_state(True)
  66. def _test_process_pulled_event_with_missing_state(
  67. self, prev_exists_as_outlier: bool
  68. ) -> None:
  69. OTHER_USER = f"@user:{self.OTHER_SERVER_NAME}"
  70. main_store = self.hs.get_datastores().main
  71. state_storage_controller = self.hs.get_storage_controllers().state
  72. # create the room
  73. user_id = self.register_user("kermit", "test")
  74. tok = self.login("kermit", "test")
  75. room_id = self.helper.create_room_as(room_creator=user_id, tok=tok)
  76. room_version = self.get_success(main_store.get_room_version(room_id))
  77. # allow the remote user to send state events
  78. self.helper.send_state(
  79. room_id,
  80. "m.room.power_levels",
  81. {"events_default": 0, "state_default": 0},
  82. tok=tok,
  83. )
  84. # add the remote user to the room
  85. member_event = self.get_success(
  86. event_injection.inject_member_event(self.hs, room_id, OTHER_USER, "join")
  87. )
  88. initial_state_map = self.get_success(
  89. main_store.get_partial_current_state_ids(room_id)
  90. )
  91. auth_event_ids = [
  92. initial_state_map[("m.room.create", "")],
  93. initial_state_map[("m.room.power_levels", "")],
  94. member_event.event_id,
  95. ]
  96. # mock up a load of state events which we are missing
  97. state_events = [
  98. make_event_from_dict(
  99. self.add_hashes_and_signatures_from_other_server(
  100. {
  101. "type": "test_state_type",
  102. "state_key": f"state_{i}",
  103. "room_id": room_id,
  104. "sender": OTHER_USER,
  105. "prev_events": [member_event.event_id],
  106. "auth_events": auth_event_ids,
  107. "origin_server_ts": 1,
  108. "depth": 10,
  109. "content": {"body": f"state_{i}"},
  110. }
  111. ),
  112. room_version,
  113. )
  114. for i in range(1, 10)
  115. ]
  116. # this is the state that we are going to claim is active at the prev_event.
  117. state_at_prev_event = state_events + self.get_success(
  118. main_store.get_events_as_list(initial_state_map.values())
  119. )
  120. # mock up a prev event.
  121. # Depending on the test, we either persist this upfront (as an outlier),
  122. # or let the server request it.
  123. prev_event = make_event_from_dict(
  124. self.add_hashes_and_signatures_from_other_server(
  125. {
  126. "type": "test_regular_type",
  127. "room_id": room_id,
  128. "sender": OTHER_USER,
  129. "prev_events": [],
  130. "auth_events": auth_event_ids,
  131. "origin_server_ts": 1,
  132. "depth": 11,
  133. "content": {"body": "missing_prev"},
  134. }
  135. ),
  136. room_version,
  137. )
  138. if prev_exists_as_outlier:
  139. prev_event.internal_metadata.outlier = True
  140. persistence = self.hs.get_storage_controllers().persistence
  141. self.get_success(
  142. persistence.persist_event(
  143. prev_event,
  144. EventContext.for_outlier(self.hs.get_storage_controllers()),
  145. )
  146. )
  147. else:
  148. async def get_event(destination: str, event_id: str, timeout=None):
  149. self.assertEqual(destination, self.OTHER_SERVER_NAME)
  150. self.assertEqual(event_id, prev_event.event_id)
  151. return {"pdus": [prev_event.get_pdu_json()]}
  152. self.mock_federation_transport_client.get_event.side_effect = get_event
  153. # mock up a regular event to pass into _process_pulled_event
  154. pulled_event = make_event_from_dict(
  155. self.add_hashes_and_signatures_from_other_server(
  156. {
  157. "type": "test_regular_type",
  158. "room_id": room_id,
  159. "sender": OTHER_USER,
  160. "prev_events": [prev_event.event_id],
  161. "auth_events": auth_event_ids,
  162. "origin_server_ts": 1,
  163. "depth": 12,
  164. "content": {"body": "pulled"},
  165. }
  166. ),
  167. room_version,
  168. )
  169. # we expect an outbound request to /state_ids, so stub that out
  170. self.mock_federation_transport_client.get_room_state_ids.return_value = (
  171. make_awaitable(
  172. {
  173. "pdu_ids": [e.event_id for e in state_at_prev_event],
  174. "auth_chain_ids": [],
  175. }
  176. )
  177. )
  178. # we also expect an outbound request to /state
  179. self.mock_federation_transport_client.get_room_state.return_value = (
  180. make_awaitable(
  181. StateRequestResponse(auth_events=[], state=state_at_prev_event)
  182. )
  183. )
  184. # we have to bump the clock a bit, to keep the retry logic in
  185. # FederationClient.get_pdu happy
  186. self.reactor.advance(60000)
  187. # Finally, the call under test: send the pulled event into _process_pulled_event
  188. with LoggingContext("test"):
  189. self.get_success(
  190. self.hs.get_federation_event_handler()._process_pulled_event(
  191. self.OTHER_SERVER_NAME, pulled_event, backfilled=False
  192. )
  193. )
  194. # check that the event is correctly persisted
  195. persisted = self.get_success(main_store.get_event(pulled_event.event_id))
  196. self.assertIsNotNone(persisted, "pulled event was not persisted at all")
  197. self.assertFalse(
  198. persisted.internal_metadata.is_outlier(), "pulled event was an outlier"
  199. )
  200. # check that the state at that event is as expected
  201. state = self.get_success(
  202. state_storage_controller.get_state_ids_for_event(pulled_event.event_id)
  203. )
  204. expected_state = {
  205. (e.type, e.state_key): e.event_id for e in state_at_prev_event
  206. }
  207. self.assertEqual(state, expected_state)
  208. if prev_exists_as_outlier:
  209. self.mock_federation_transport_client.get_event.assert_not_called()
  210. def test_process_pulled_event_records_failed_backfill_attempts(
  211. self,
  212. ) -> None:
  213. """
  214. Test to make sure that failed backfill attempts for an event are
  215. recorded in the `event_failed_pull_attempts` table.
  216. In this test, we pretend we are processing a "pulled" event via
  217. backfill. The pulled event has a fake `prev_event` which our server has
  218. obviously never seen before so it attempts to request the state at that
  219. `prev_event` which expectedly fails because it's a fake event. Because
  220. the server can't fetch the state at the missing `prev_event`, the
  221. "pulled" event fails the history check and is fails to process.
  222. We check that we correctly record the number of failed pull attempts
  223. of the pulled event and as a sanity check, that the "pulled" event isn't
  224. persisted.
  225. """
  226. OTHER_USER = f"@user:{self.OTHER_SERVER_NAME}"
  227. main_store = self.hs.get_datastores().main
  228. # Create the room
  229. user_id = self.register_user("kermit", "test")
  230. tok = self.login("kermit", "test")
  231. room_id = self.helper.create_room_as(room_creator=user_id, tok=tok)
  232. room_version = self.get_success(main_store.get_room_version(room_id))
  233. # We expect an outbound request to /state_ids, so stub that out
  234. self.mock_federation_transport_client.get_room_state_ids.return_value = make_awaitable(
  235. {
  236. # Mimic the other server not knowing about the state at all.
  237. # We want to cause Synapse to throw an error (`Unable to get
  238. # missing prev_event $fake_prev_event`) and fail to backfill
  239. # the pulled event.
  240. "pdu_ids": [],
  241. "auth_chain_ids": [],
  242. }
  243. )
  244. # We also expect an outbound request to /state
  245. self.mock_federation_transport_client.get_room_state.return_value = make_awaitable(
  246. StateRequestResponse(
  247. # Mimic the other server not knowing about the state at all.
  248. # We want to cause Synapse to throw an error (`Unable to get
  249. # missing prev_event $fake_prev_event`) and fail to backfill
  250. # the pulled event.
  251. auth_events=[],
  252. state=[],
  253. )
  254. )
  255. pulled_event = make_event_from_dict(
  256. self.add_hashes_and_signatures_from_other_server(
  257. {
  258. "type": "test_regular_type",
  259. "room_id": room_id,
  260. "sender": OTHER_USER,
  261. "prev_events": [
  262. # The fake prev event will make the pulled event fail
  263. # the history check (`Unable to get missing prev_event
  264. # $fake_prev_event`)
  265. "$fake_prev_event"
  266. ],
  267. "auth_events": [],
  268. "origin_server_ts": 1,
  269. "depth": 12,
  270. "content": {"body": "pulled"},
  271. }
  272. ),
  273. room_version,
  274. )
  275. # The function under test: try to process the pulled event
  276. with LoggingContext("test"):
  277. self.get_success(
  278. self.hs.get_federation_event_handler()._process_pulled_event(
  279. self.OTHER_SERVER_NAME, pulled_event, backfilled=True
  280. )
  281. )
  282. # Make sure our failed pull attempt was recorded
  283. backfill_num_attempts = self.get_success(
  284. main_store.db_pool.simple_select_one_onecol(
  285. table="event_failed_pull_attempts",
  286. keyvalues={"event_id": pulled_event.event_id},
  287. retcol="num_attempts",
  288. )
  289. )
  290. self.assertEqual(backfill_num_attempts, 1)
  291. # The function under test: try to process the pulled event again
  292. with LoggingContext("test"):
  293. self.get_success(
  294. self.hs.get_federation_event_handler()._process_pulled_event(
  295. self.OTHER_SERVER_NAME, pulled_event, backfilled=True
  296. )
  297. )
  298. # Make sure our second failed pull attempt was recorded (`num_attempts` was incremented)
  299. backfill_num_attempts = self.get_success(
  300. main_store.db_pool.simple_select_one_onecol(
  301. table="event_failed_pull_attempts",
  302. keyvalues={"event_id": pulled_event.event_id},
  303. retcol="num_attempts",
  304. )
  305. )
  306. self.assertEqual(backfill_num_attempts, 2)
  307. # And as a sanity check, make sure the event was not persisted through all of this.
  308. persisted = self.get_success(
  309. main_store.get_event(pulled_event.event_id, allow_none=True)
  310. )
  311. self.assertIsNone(
  312. persisted,
  313. "pulled event that fails the history check should not be persisted at all",
  314. )
  315. def test_process_pulled_event_clears_backfill_attempts_after_being_successfully_persisted(
  316. self,
  317. ) -> None:
  318. """
  319. Test to make sure that failed pull attempts
  320. (`event_failed_pull_attempts` table) for an event are cleared after the
  321. event is successfully persisted.
  322. In this test, we pretend we are processing a "pulled" event via
  323. backfill. The pulled event succesfully processes and the backward
  324. extremeties are updated along with clearing out any failed pull attempts
  325. for those old extremities.
  326. We check that we correctly cleared failed pull attempts of the
  327. pulled event.
  328. """
  329. OTHER_USER = f"@user:{self.OTHER_SERVER_NAME}"
  330. main_store = self.hs.get_datastores().main
  331. # Create the room
  332. user_id = self.register_user("kermit", "test")
  333. tok = self.login("kermit", "test")
  334. room_id = self.helper.create_room_as(room_creator=user_id, tok=tok)
  335. room_version = self.get_success(main_store.get_room_version(room_id))
  336. # allow the remote user to send state events
  337. self.helper.send_state(
  338. room_id,
  339. "m.room.power_levels",
  340. {"events_default": 0, "state_default": 0},
  341. tok=tok,
  342. )
  343. # add the remote user to the room
  344. member_event = self.get_success(
  345. event_injection.inject_member_event(self.hs, room_id, OTHER_USER, "join")
  346. )
  347. initial_state_map = self.get_success(
  348. main_store.get_partial_current_state_ids(room_id)
  349. )
  350. auth_event_ids = [
  351. initial_state_map[("m.room.create", "")],
  352. initial_state_map[("m.room.power_levels", "")],
  353. member_event.event_id,
  354. ]
  355. pulled_event = make_event_from_dict(
  356. self.add_hashes_and_signatures_from_other_server(
  357. {
  358. "type": "test_regular_type",
  359. "room_id": room_id,
  360. "sender": OTHER_USER,
  361. "prev_events": [member_event.event_id],
  362. "auth_events": auth_event_ids,
  363. "origin_server_ts": 1,
  364. "depth": 12,
  365. "content": {"body": "pulled"},
  366. }
  367. ),
  368. room_version,
  369. )
  370. # Fake the "pulled" event failing to backfill once so we can test
  371. # if it's cleared out later on.
  372. self.get_success(
  373. main_store.record_event_failed_pull_attempt(
  374. pulled_event.room_id, pulled_event.event_id, "fake cause"
  375. )
  376. )
  377. # Make sure we have a failed pull attempt recorded for the pulled event
  378. backfill_num_attempts = self.get_success(
  379. main_store.db_pool.simple_select_one_onecol(
  380. table="event_failed_pull_attempts",
  381. keyvalues={"event_id": pulled_event.event_id},
  382. retcol="num_attempts",
  383. )
  384. )
  385. self.assertEqual(backfill_num_attempts, 1)
  386. # The function under test: try to process the pulled event
  387. with LoggingContext("test"):
  388. self.get_success(
  389. self.hs.get_federation_event_handler()._process_pulled_event(
  390. self.OTHER_SERVER_NAME, pulled_event, backfilled=True
  391. )
  392. )
  393. # Make sure the failed pull attempts for the pulled event are cleared
  394. backfill_num_attempts = self.get_success(
  395. main_store.db_pool.simple_select_one_onecol(
  396. table="event_failed_pull_attempts",
  397. keyvalues={"event_id": pulled_event.event_id},
  398. retcol="num_attempts",
  399. allow_none=True,
  400. )
  401. )
  402. self.assertIsNone(backfill_num_attempts)
  403. # And as a sanity check, make sure the "pulled" event was persisted.
  404. persisted = self.get_success(
  405. main_store.get_event(pulled_event.event_id, allow_none=True)
  406. )
  407. self.assertIsNotNone(persisted, "pulled event was not persisted at all")
  408. def test_backfill_signature_failure_does_not_fetch_same_prev_event_later(
  409. self,
  410. ) -> None:
  411. """
  412. Test to make sure we backoff and don't try to fetch a missing prev_event when we
  413. already know it has a invalid signature from checking the signatures of all of
  414. the events in the backfill response.
  415. """
  416. OTHER_USER = f"@user:{self.OTHER_SERVER_NAME}"
  417. main_store = self.hs.get_datastores().main
  418. # Create the room
  419. user_id = self.register_user("kermit", "test")
  420. tok = self.login("kermit", "test")
  421. room_id = self.helper.create_room_as(room_creator=user_id, tok=tok)
  422. room_version = self.get_success(main_store.get_room_version(room_id))
  423. # Allow the remote user to send state events
  424. self.helper.send_state(
  425. room_id,
  426. "m.room.power_levels",
  427. {"events_default": 0, "state_default": 0},
  428. tok=tok,
  429. )
  430. # Add the remote user to the room
  431. member_event = self.get_success(
  432. event_injection.inject_member_event(self.hs, room_id, OTHER_USER, "join")
  433. )
  434. initial_state_map = self.get_success(
  435. main_store.get_partial_current_state_ids(room_id)
  436. )
  437. auth_event_ids = [
  438. initial_state_map[("m.room.create", "")],
  439. initial_state_map[("m.room.power_levels", "")],
  440. member_event.event_id,
  441. ]
  442. # We purposely don't run `add_hashes_and_signatures_from_other_server`
  443. # over this because we want the signature check to fail.
  444. pulled_event_without_signatures = make_event_from_dict(
  445. {
  446. "type": "test_regular_type",
  447. "room_id": room_id,
  448. "sender": OTHER_USER,
  449. "prev_events": [member_event.event_id],
  450. "auth_events": auth_event_ids,
  451. "origin_server_ts": 1,
  452. "depth": 12,
  453. "content": {"body": "pulled_event_without_signatures"},
  454. },
  455. room_version,
  456. )
  457. # Create a regular event that should pass except for the
  458. # `pulled_event_without_signatures` in the `prev_event`.
  459. pulled_event = make_event_from_dict(
  460. self.add_hashes_and_signatures_from_other_server(
  461. {
  462. "type": "test_regular_type",
  463. "room_id": room_id,
  464. "sender": OTHER_USER,
  465. "prev_events": [
  466. member_event.event_id,
  467. pulled_event_without_signatures.event_id,
  468. ],
  469. "auth_events": auth_event_ids,
  470. "origin_server_ts": 1,
  471. "depth": 12,
  472. "content": {"body": "pulled_event"},
  473. }
  474. ),
  475. room_version,
  476. )
  477. # We expect an outbound request to /backfill, so stub that out
  478. self.mock_federation_transport_client.backfill.return_value = make_awaitable(
  479. {
  480. "origin": self.OTHER_SERVER_NAME,
  481. "origin_server_ts": 123,
  482. "pdus": [
  483. # This is one of the important aspects of this test: we include
  484. # `pulled_event_without_signatures` so it fails the signature check
  485. # when we filter down the backfill response down to events which
  486. # have valid signatures in
  487. # `_check_sigs_and_hash_for_pulled_events_and_fetch`
  488. pulled_event_without_signatures.get_pdu_json(),
  489. # Then later when we process this valid signature event, when we
  490. # fetch the missing `prev_event`s, we want to make sure that we
  491. # backoff and don't try and fetch `pulled_event_without_signatures`
  492. # again since we know it just had an invalid signature.
  493. pulled_event.get_pdu_json(),
  494. ],
  495. }
  496. )
  497. # Keep track of the count and make sure we don't make any of these requests
  498. event_endpoint_requested_count = 0
  499. room_state_ids_endpoint_requested_count = 0
  500. room_state_endpoint_requested_count = 0
  501. async def get_event(
  502. destination: str, event_id: str, timeout: Optional[int] = None
  503. ) -> None:
  504. nonlocal event_endpoint_requested_count
  505. event_endpoint_requested_count += 1
  506. async def get_room_state_ids(
  507. destination: str, room_id: str, event_id: str
  508. ) -> None:
  509. nonlocal room_state_ids_endpoint_requested_count
  510. room_state_ids_endpoint_requested_count += 1
  511. async def get_room_state(
  512. room_version: RoomVersion, destination: str, room_id: str, event_id: str
  513. ) -> None:
  514. nonlocal room_state_endpoint_requested_count
  515. room_state_endpoint_requested_count += 1
  516. # We don't expect an outbound request to `/event`, `/state_ids`, or `/state` in
  517. # the happy path but if the logic is sneaking around what we expect, stub that
  518. # out so we can detect that failure
  519. self.mock_federation_transport_client.get_event.side_effect = get_event
  520. self.mock_federation_transport_client.get_room_state_ids.side_effect = (
  521. get_room_state_ids
  522. )
  523. self.mock_federation_transport_client.get_room_state.side_effect = (
  524. get_room_state
  525. )
  526. # The function under test: try to backfill and process the pulled event
  527. with LoggingContext("test"):
  528. self.get_success(
  529. self.hs.get_federation_event_handler().backfill(
  530. self.OTHER_SERVER_NAME,
  531. room_id,
  532. limit=1,
  533. extremities=["$some_extremity"],
  534. )
  535. )
  536. if event_endpoint_requested_count > 0:
  537. self.fail(
  538. "We don't expect an outbound request to /event in the happy path but if "
  539. "the logic is sneaking around what we expect, make sure to fail the test. "
  540. "We don't expect it because the signature failure should cause us to backoff "
  541. "and not asking about pulled_event_without_signatures="
  542. f"{pulled_event_without_signatures.event_id} again"
  543. )
  544. if room_state_ids_endpoint_requested_count > 0:
  545. self.fail(
  546. "We don't expect an outbound request to /state_ids in the happy path but if "
  547. "the logic is sneaking around what we expect, make sure to fail the test. "
  548. "We don't expect it because the signature failure should cause us to backoff "
  549. "and not asking about pulled_event_without_signatures="
  550. f"{pulled_event_without_signatures.event_id} again"
  551. )
  552. if room_state_endpoint_requested_count > 0:
  553. self.fail(
  554. "We don't expect an outbound request to /state in the happy path but if "
  555. "the logic is sneaking around what we expect, make sure to fail the test. "
  556. "We don't expect it because the signature failure should cause us to backoff "
  557. "and not asking about pulled_event_without_signatures="
  558. f"{pulled_event_without_signatures.event_id} again"
  559. )
  560. # Make sure we only recorded a single failure which corresponds to the signature
  561. # failure initially in `_check_sigs_and_hash_for_pulled_events_and_fetch` before
  562. # we process all of the pulled events.
  563. backfill_num_attempts_for_event_without_signatures = self.get_success(
  564. main_store.db_pool.simple_select_one_onecol(
  565. table="event_failed_pull_attempts",
  566. keyvalues={"event_id": pulled_event_without_signatures.event_id},
  567. retcol="num_attempts",
  568. )
  569. )
  570. self.assertEqual(backfill_num_attempts_for_event_without_signatures, 1)
  571. # And make sure we didn't record a failure for the event that has the missing
  572. # prev_event because we don't want to cause a cascade of failures. Not being
  573. # able to fetch the `prev_events` just means we won't be able to de-outlier the
  574. # pulled event. But we can still use an `outlier` in the state/auth chain for
  575. # another event. So we shouldn't stop a downstream event from trying to pull it.
  576. self.get_failure(
  577. main_store.db_pool.simple_select_one_onecol(
  578. table="event_failed_pull_attempts",
  579. keyvalues={"event_id": pulled_event.event_id},
  580. retcol="num_attempts",
  581. ),
  582. # StoreError: 404: No row found
  583. StoreError,
  584. )
  585. def test_process_pulled_event_with_rejected_missing_state(self) -> None:
  586. """Ensure that we correctly handle pulled events with missing state containing a
  587. rejected state event
  588. In this test, we pretend we are processing a "pulled" event (eg, via backfill
  589. or get_missing_events). The pulled event has a prev_event we haven't previously
  590. seen, so the server requests the state at that prev_event. We expect the server
  591. to make a /state request.
  592. We simulate a remote server whose /state includes a rejected kick event for a
  593. local user. Notably, the kick event is rejected only because it cites a rejected
  594. auth event and would otherwise be accepted based on the room state. During state
  595. resolution, we re-run auth and can potentially introduce such rejected events
  596. into the state if we are not careful.
  597. We check that the pulled event is correctly persisted, and that the state
  598. afterwards does not include the rejected kick.
  599. """
  600. # The DAG we are testing looks like:
  601. #
  602. # ...
  603. # |
  604. # v
  605. # remote admin user joins
  606. # | |
  607. # +-------+ +-------+
  608. # | |
  609. # | rejected power levels
  610. # | from remote server
  611. # | |
  612. # | v
  613. # | rejected kick of local user
  614. # v from remote server
  615. # new power levels |
  616. # | v
  617. # | missing event
  618. # | from remote server
  619. # | |
  620. # +-------+ +-------+
  621. # | |
  622. # v v
  623. # pulled event
  624. # from remote server
  625. #
  626. # (arrows are in the opposite direction to prev_events.)
  627. OTHER_USER = f"@user:{self.OTHER_SERVER_NAME}"
  628. main_store = self.hs.get_datastores().main
  629. # Create the room.
  630. kermit_user_id = self.register_user("kermit", "test")
  631. kermit_tok = self.login("kermit", "test")
  632. room_id = self.helper.create_room_as(
  633. room_creator=kermit_user_id, tok=kermit_tok
  634. )
  635. room_version = self.get_success(main_store.get_room_version(room_id))
  636. # Add another local user to the room. This user is going to be kicked in a
  637. # rejected event.
  638. bert_user_id = self.register_user("bert", "test")
  639. bert_tok = self.login("bert", "test")
  640. self.helper.join(room_id, user=bert_user_id, tok=bert_tok)
  641. # Allow the remote user to kick bert.
  642. # The remote user is going to send a rejected power levels event later on and we
  643. # need state resolution to order it before another power levels event kermit is
  644. # going to send later on. Hence we give both users the same power level, so that
  645. # ties are broken by `origin_server_ts`.
  646. self.helper.send_state(
  647. room_id,
  648. "m.room.power_levels",
  649. {"users": {kermit_user_id: 100, OTHER_USER: 100}},
  650. tok=kermit_tok,
  651. )
  652. # Add the remote user to the room.
  653. other_member_event = self.get_success(
  654. event_injection.inject_member_event(self.hs, room_id, OTHER_USER, "join")
  655. )
  656. initial_state_map = self.get_success(
  657. main_store.get_partial_current_state_ids(room_id)
  658. )
  659. create_event = self.get_success(
  660. main_store.get_event(initial_state_map[("m.room.create", "")])
  661. )
  662. bert_member_event = self.get_success(
  663. main_store.get_event(initial_state_map[("m.room.member", bert_user_id)])
  664. )
  665. power_levels_event = self.get_success(
  666. main_store.get_event(initial_state_map[("m.room.power_levels", "")])
  667. )
  668. # We now need a rejected state event that will fail
  669. # `check_state_independent_auth_rules` but pass
  670. # `check_state_dependent_auth_rules`.
  671. # First, we create a power levels event that we pretend the remote server has
  672. # accepted, but the local homeserver will reject.
  673. next_depth = 100
  674. next_timestamp = other_member_event.origin_server_ts + 100
  675. rejected_power_levels_event = make_event_from_dict(
  676. self.add_hashes_and_signatures_from_other_server(
  677. {
  678. "type": "m.room.power_levels",
  679. "state_key": "",
  680. "room_id": room_id,
  681. "sender": OTHER_USER,
  682. "prev_events": [other_member_event.event_id],
  683. "auth_events": [
  684. initial_state_map[("m.room.create", "")],
  685. initial_state_map[("m.room.power_levels", "")],
  686. # The event will be rejected because of the duplicated auth
  687. # event.
  688. other_member_event.event_id,
  689. other_member_event.event_id,
  690. ],
  691. "origin_server_ts": next_timestamp,
  692. "depth": next_depth,
  693. "content": power_levels_event.content,
  694. }
  695. ),
  696. room_version,
  697. )
  698. next_depth += 1
  699. next_timestamp += 100
  700. with LoggingContext("send_rejected_power_levels_event"):
  701. self.get_success(
  702. self.hs.get_federation_event_handler()._process_pulled_event(
  703. self.OTHER_SERVER_NAME,
  704. rejected_power_levels_event,
  705. backfilled=False,
  706. )
  707. )
  708. self.assertEqual(
  709. self.get_success(
  710. main_store.get_rejection_reason(
  711. rejected_power_levels_event.event_id
  712. )
  713. ),
  714. "auth_error",
  715. )
  716. # Then we create a kick event for a local user that cites the rejected power
  717. # levels event in its auth events. The kick event will be rejected solely
  718. # because of the rejected auth event and would otherwise be accepted.
  719. rejected_kick_event = make_event_from_dict(
  720. self.add_hashes_and_signatures_from_other_server(
  721. {
  722. "type": "m.room.member",
  723. "state_key": bert_user_id,
  724. "room_id": room_id,
  725. "sender": OTHER_USER,
  726. "prev_events": [rejected_power_levels_event.event_id],
  727. "auth_events": [
  728. initial_state_map[("m.room.create", "")],
  729. rejected_power_levels_event.event_id,
  730. initial_state_map[("m.room.member", bert_user_id)],
  731. initial_state_map[("m.room.member", OTHER_USER)],
  732. ],
  733. "origin_server_ts": next_timestamp,
  734. "depth": next_depth,
  735. "content": {"membership": "leave"},
  736. }
  737. ),
  738. room_version,
  739. )
  740. next_depth += 1
  741. next_timestamp += 100
  742. # The kick event must fail the state-independent auth rules, but pass the
  743. # state-dependent auth rules, so that it has a chance of making it through state
  744. # resolution.
  745. self.get_failure(
  746. check_state_independent_auth_rules(main_store, rejected_kick_event),
  747. AuthError,
  748. )
  749. check_state_dependent_auth_rules(
  750. rejected_kick_event,
  751. [create_event, power_levels_event, other_member_event, bert_member_event],
  752. )
  753. # The kick event must also win over the original member event during state
  754. # resolution.
  755. self.assertEqual(
  756. self.get_success(
  757. _mainline_sort(
  758. self.clock,
  759. room_id,
  760. event_ids=[
  761. bert_member_event.event_id,
  762. rejected_kick_event.event_id,
  763. ],
  764. resolved_power_event_id=power_levels_event.event_id,
  765. event_map={
  766. bert_member_event.event_id: bert_member_event,
  767. rejected_kick_event.event_id: rejected_kick_event,
  768. },
  769. state_res_store=main_store,
  770. )
  771. ),
  772. [bert_member_event.event_id, rejected_kick_event.event_id],
  773. "The rejected kick event will not be applied after bert's join event "
  774. "during state resolution. The test setup is incorrect.",
  775. )
  776. with LoggingContext("send_rejected_kick_event"):
  777. self.get_success(
  778. self.hs.get_federation_event_handler()._process_pulled_event(
  779. self.OTHER_SERVER_NAME, rejected_kick_event, backfilled=False
  780. )
  781. )
  782. self.assertEqual(
  783. self.get_success(
  784. main_store.get_rejection_reason(rejected_kick_event.event_id)
  785. ),
  786. "auth_error",
  787. )
  788. # We need another power levels event which will win over the rejected one during
  789. # state resolution, otherwise we hit other issues where we end up with rejected
  790. # a power levels event during state resolution.
  791. self.reactor.advance(100) # ensure the `origin_server_ts` is larger
  792. new_power_levels_event = self.get_success(
  793. main_store.get_event(
  794. self.helper.send_state(
  795. room_id,
  796. "m.room.power_levels",
  797. {"users": {kermit_user_id: 100, OTHER_USER: 100, bert_user_id: 1}},
  798. tok=kermit_tok,
  799. )["event_id"]
  800. )
  801. )
  802. self.assertEqual(
  803. self.get_success(
  804. _reverse_topological_power_sort(
  805. self.clock,
  806. room_id,
  807. event_ids=[
  808. new_power_levels_event.event_id,
  809. rejected_power_levels_event.event_id,
  810. ],
  811. event_map={},
  812. state_res_store=main_store,
  813. full_conflicted_set=set(),
  814. )
  815. ),
  816. [rejected_power_levels_event.event_id, new_power_levels_event.event_id],
  817. "The power levels events will not have the desired ordering during state "
  818. "resolution. The test setup is incorrect.",
  819. )
  820. # Create a missing event, so that the local homeserver has to do a `/state` or
  821. # `/state_ids` request to pull state from the remote homeserver.
  822. missing_event = make_event_from_dict(
  823. self.add_hashes_and_signatures_from_other_server(
  824. {
  825. "type": "m.room.message",
  826. "room_id": room_id,
  827. "sender": OTHER_USER,
  828. "prev_events": [rejected_kick_event.event_id],
  829. "auth_events": [
  830. initial_state_map[("m.room.create", "")],
  831. initial_state_map[("m.room.power_levels", "")],
  832. initial_state_map[("m.room.member", OTHER_USER)],
  833. ],
  834. "origin_server_ts": next_timestamp,
  835. "depth": next_depth,
  836. "content": {"msgtype": "m.text", "body": "foo"},
  837. }
  838. ),
  839. room_version,
  840. )
  841. next_depth += 1
  842. next_timestamp += 100
  843. # The pulled event has two prev events, one of which is missing. We will make a
  844. # `/state` or `/state_ids` request to the remote homeserver to ask it for the
  845. # state before the missing prev event.
  846. pulled_event = make_event_from_dict(
  847. self.add_hashes_and_signatures_from_other_server(
  848. {
  849. "type": "m.room.message",
  850. "room_id": room_id,
  851. "sender": OTHER_USER,
  852. "prev_events": [
  853. new_power_levels_event.event_id,
  854. missing_event.event_id,
  855. ],
  856. "auth_events": [
  857. initial_state_map[("m.room.create", "")],
  858. new_power_levels_event.event_id,
  859. initial_state_map[("m.room.member", OTHER_USER)],
  860. ],
  861. "origin_server_ts": next_timestamp,
  862. "depth": next_depth,
  863. "content": {"msgtype": "m.text", "body": "bar"},
  864. }
  865. ),
  866. room_version,
  867. )
  868. next_depth += 1
  869. next_timestamp += 100
  870. # Prepare the response for the `/state` or `/state_ids` request.
  871. # The remote server believes bert has been kicked, while the local server does
  872. # not.
  873. state_before_missing_event = self.get_success(
  874. main_store.get_events_as_list(initial_state_map.values())
  875. )
  876. state_before_missing_event = [
  877. event
  878. for event in state_before_missing_event
  879. if event.event_id != bert_member_event.event_id
  880. ]
  881. state_before_missing_event.append(rejected_kick_event)
  882. # We have to bump the clock a bit, to keep the retry logic in
  883. # `FederationClient.get_pdu` happy
  884. self.reactor.advance(60000)
  885. with LoggingContext("send_pulled_event"):
  886. async def get_event(
  887. destination: str, event_id: str, timeout: Optional[int] = None
  888. ) -> JsonDict:
  889. self.assertEqual(destination, self.OTHER_SERVER_NAME)
  890. self.assertEqual(event_id, missing_event.event_id)
  891. return {"pdus": [missing_event.get_pdu_json()]}
  892. async def get_room_state_ids(
  893. destination: str, room_id: str, event_id: str
  894. ) -> JsonDict:
  895. self.assertEqual(destination, self.OTHER_SERVER_NAME)
  896. self.assertEqual(event_id, missing_event.event_id)
  897. return {
  898. "pdu_ids": [event.event_id for event in state_before_missing_event],
  899. "auth_chain_ids": [],
  900. }
  901. async def get_room_state(
  902. room_version: RoomVersion, destination: str, room_id: str, event_id: str
  903. ) -> StateRequestResponse:
  904. self.assertEqual(destination, self.OTHER_SERVER_NAME)
  905. self.assertEqual(event_id, missing_event.event_id)
  906. return StateRequestResponse(
  907. state=state_before_missing_event,
  908. auth_events=[],
  909. )
  910. self.mock_federation_transport_client.get_event.side_effect = get_event
  911. self.mock_federation_transport_client.get_room_state_ids.side_effect = (
  912. get_room_state_ids
  913. )
  914. self.mock_federation_transport_client.get_room_state.side_effect = (
  915. get_room_state
  916. )
  917. self.get_success(
  918. self.hs.get_federation_event_handler()._process_pulled_event(
  919. self.OTHER_SERVER_NAME, pulled_event, backfilled=False
  920. )
  921. )
  922. self.assertIsNone(
  923. self.get_success(
  924. main_store.get_rejection_reason(pulled_event.event_id)
  925. ),
  926. "Pulled event was unexpectedly rejected, likely due to a problem with "
  927. "the test setup.",
  928. )
  929. self.assertEqual(
  930. {pulled_event.event_id},
  931. self.get_success(
  932. main_store.have_events_in_timeline([pulled_event.event_id])
  933. ),
  934. "Pulled event was not persisted, likely due to a problem with the test "
  935. "setup.",
  936. )
  937. # We must not accept rejected events into the room state, so we expect bert
  938. # to not be kicked, even if the remote server believes so.
  939. new_state_map = self.get_success(
  940. main_store.get_partial_current_state_ids(room_id)
  941. )
  942. self.assertEqual(
  943. new_state_map[("m.room.member", bert_user_id)],
  944. bert_member_event.event_id,
  945. "Rejected kick event unexpectedly became part of room state.",
  946. )