You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1056 lines
44 KiB

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