test_federation_client.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. # Copyright 2022 Matrix.org Federation 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. import twisted.web.client
  16. from twisted.internet import defer
  17. from twisted.test.proto_helpers import MemoryReactor
  18. from synapse.api.room_versions import RoomVersions
  19. from synapse.events import EventBase
  20. from synapse.rest import admin
  21. from synapse.rest.client import login, room
  22. from synapse.server import HomeServer
  23. from synapse.util import Clock
  24. from tests.test_utils import FakeResponse, event_injection
  25. from tests.unittest import FederatingHomeserverTestCase
  26. class FederationClientTest(FederatingHomeserverTestCase):
  27. servlets = [
  28. admin.register_servlets,
  29. room.register_servlets,
  30. login.register_servlets,
  31. ]
  32. def prepare(
  33. self, reactor: MemoryReactor, clock: Clock, homeserver: HomeServer
  34. ) -> None:
  35. super().prepare(reactor, clock, homeserver)
  36. # mock out the Agent used by the federation client, which is easier than
  37. # catching the HTTPS connection and do the TLS stuff.
  38. self._mock_agent = mock.create_autospec(twisted.web.client.Agent, spec_set=True)
  39. homeserver.get_federation_http_client().agent = self._mock_agent
  40. # Move clock up to somewhat realistic time so the PDU destination retry
  41. # works (`now` needs to be larger than `0 + PDU_RETRY_TIME_MS`).
  42. self.reactor.advance(1000000000)
  43. self.creator = f"@creator:{self.OTHER_SERVER_NAME}"
  44. self.test_room_id = "!room_id"
  45. def test_get_room_state(self) -> None:
  46. # mock up some events to use in the response.
  47. # In real life, these would have things in `prev_events` and `auth_events`, but that's
  48. # a bit annoying to mock up, and the code under test doesn't care, so we don't bother.
  49. create_event_dict = self.add_hashes_and_signatures_from_other_server(
  50. {
  51. "room_id": self.test_room_id,
  52. "type": "m.room.create",
  53. "state_key": "",
  54. "sender": self.creator,
  55. "content": {"creator": self.creator},
  56. "prev_events": [],
  57. "auth_events": [],
  58. "origin_server_ts": 500,
  59. }
  60. )
  61. member_event_dict = self.add_hashes_and_signatures_from_other_server(
  62. {
  63. "room_id": self.test_room_id,
  64. "type": "m.room.member",
  65. "sender": self.creator,
  66. "state_key": self.creator,
  67. "content": {"membership": "join"},
  68. "prev_events": [],
  69. "auth_events": [],
  70. "origin_server_ts": 600,
  71. }
  72. )
  73. pl_event_dict = self.add_hashes_and_signatures_from_other_server(
  74. {
  75. "room_id": self.test_room_id,
  76. "type": "m.room.power_levels",
  77. "sender": self.creator,
  78. "state_key": "",
  79. "content": {},
  80. "prev_events": [],
  81. "auth_events": [],
  82. "origin_server_ts": 700,
  83. }
  84. )
  85. # mock up the response, and have the agent return it
  86. self._mock_agent.request.side_effect = lambda *args, **kwargs: defer.succeed(
  87. FakeResponse.json(
  88. payload={
  89. "pdus": [
  90. create_event_dict,
  91. member_event_dict,
  92. pl_event_dict,
  93. ],
  94. "auth_chain": [
  95. create_event_dict,
  96. member_event_dict,
  97. ],
  98. }
  99. )
  100. )
  101. # now fire off the request
  102. state_resp, auth_resp = self.get_success(
  103. self.hs.get_federation_client().get_room_state(
  104. "yet.another.server",
  105. self.test_room_id,
  106. "event_id",
  107. RoomVersions.V9,
  108. )
  109. )
  110. # check the right call got made to the agent
  111. self._mock_agent.request.assert_called_once_with(
  112. b"GET",
  113. b"matrix://yet.another.server/_matrix/federation/v1/state/%21room_id?event_id=event_id",
  114. headers=mock.ANY,
  115. bodyProducer=None,
  116. )
  117. # ... and that the response is correct.
  118. # the auth_resp should be empty because all the events are also in state
  119. self.assertEqual(auth_resp, [])
  120. # all of the events should be returned in state_resp, though not necessarily
  121. # in the same order. We just check the type on the assumption that if the type
  122. # is right, so is the rest of the event.
  123. self.assertCountEqual(
  124. [e.type for e in state_resp],
  125. ["m.room.create", "m.room.member", "m.room.power_levels"],
  126. )
  127. def test_get_pdu_returns_nothing_when_event_does_not_exist(self) -> None:
  128. """No event should be returned when the event does not exist"""
  129. pulled_pdu_info = self.get_success(
  130. self.hs.get_federation_client().get_pdu(
  131. ["yet.another.server"],
  132. "event_should_not_exist",
  133. RoomVersions.V9,
  134. )
  135. )
  136. self.assertEqual(pulled_pdu_info, None)
  137. def test_get_pdu(self) -> None:
  138. """Test to make sure an event is returned by `get_pdu()`"""
  139. self._get_pdu_once()
  140. def test_get_pdu_event_from_cache_is_pristine(self) -> None:
  141. """Test that modifications made to events returned by `get_pdu()`
  142. do not propagate back to to the internal cache (events returned should
  143. be a copy).
  144. """
  145. # Get the PDU in the cache
  146. remote_pdu = self._get_pdu_once()
  147. # Modify the the event reference.
  148. # This change should not make it back to the `_get_pdu_cache`.
  149. remote_pdu.internal_metadata.outlier = True
  150. # Get the event again. This time it should read it from cache.
  151. pulled_pdu_info2 = self.get_success(
  152. self.hs.get_federation_client().get_pdu(
  153. ["yet.another.server"],
  154. remote_pdu.event_id,
  155. RoomVersions.V9,
  156. )
  157. )
  158. assert pulled_pdu_info2 is not None
  159. remote_pdu2 = pulled_pdu_info2.pdu
  160. # Sanity check that we are working against the same event
  161. self.assertEqual(remote_pdu.event_id, remote_pdu2.event_id)
  162. # Make sure the event does not include modification from earlier
  163. self.assertIsNotNone(remote_pdu2)
  164. self.assertEqual(remote_pdu2.internal_metadata.outlier, False)
  165. def _get_pdu_once(self) -> EventBase:
  166. """Retrieve an event via `get_pdu()` and assert that an event was returned.
  167. Also used to prime the cache for subsequent test logic.
  168. """
  169. message_event_dict = self.add_hashes_and_signatures_from_other_server(
  170. {
  171. "room_id": self.test_room_id,
  172. "type": "m.room.message",
  173. "sender": self.creator,
  174. "state_key": "",
  175. "content": {},
  176. "prev_events": [],
  177. "auth_events": [],
  178. "origin_server_ts": 700,
  179. "depth": 10,
  180. }
  181. )
  182. # mock up the response, and have the agent return it
  183. self._mock_agent.request.side_effect = lambda *args, **kwargs: defer.succeed(
  184. FakeResponse.json(
  185. payload={
  186. "origin": "yet.another.server",
  187. "origin_server_ts": 900,
  188. "pdus": [
  189. message_event_dict,
  190. ],
  191. }
  192. )
  193. )
  194. pulled_pdu_info = self.get_success(
  195. self.hs.get_federation_client().get_pdu(
  196. ["yet.another.server"],
  197. "event_id",
  198. RoomVersions.V9,
  199. )
  200. )
  201. assert pulled_pdu_info is not None
  202. remote_pdu = pulled_pdu_info.pdu
  203. # check the right call got made to the agent
  204. self._mock_agent.request.assert_called_once_with(
  205. b"GET",
  206. b"matrix://yet.another.server/_matrix/federation/v1/event/event_id",
  207. headers=mock.ANY,
  208. bodyProducer=None,
  209. )
  210. self.assertIsNotNone(remote_pdu)
  211. self.assertEqual(remote_pdu.internal_metadata.outlier, False)
  212. return remote_pdu
  213. def test_backfill_invalid_signature_records_failed_pull_attempts(
  214. self,
  215. ) -> None:
  216. """
  217. Test to make sure that events from /backfill with invalid signatures get
  218. recorded as failed pull attempts.
  219. """
  220. OTHER_USER = f"@user:{self.OTHER_SERVER_NAME}"
  221. main_store = self.hs.get_datastores().main
  222. # Create the room
  223. user_id = self.register_user("kermit", "test")
  224. tok = self.login("kermit", "test")
  225. room_id = self.helper.create_room_as(room_creator=user_id, tok=tok)
  226. # We purposely don't run `add_hashes_and_signatures_from_other_server`
  227. # over this because we want the signature check to fail.
  228. pulled_event, _ = self.get_success(
  229. event_injection.create_event(
  230. self.hs,
  231. room_id=room_id,
  232. sender=OTHER_USER,
  233. type="test_event_type",
  234. content={"body": "garply"},
  235. )
  236. )
  237. # We expect an outbound request to /backfill, so stub that out
  238. self._mock_agent.request.side_effect = lambda *args, **kwargs: defer.succeed(
  239. FakeResponse.json(
  240. payload={
  241. "origin": "yet.another.server",
  242. "origin_server_ts": 900,
  243. # Mimic the other server returning our new `pulled_event`
  244. "pdus": [pulled_event.get_pdu_json()],
  245. }
  246. )
  247. )
  248. self.get_success(
  249. self.hs.get_federation_client().backfill(
  250. # We use "yet.another.server" instead of
  251. # `self.OTHER_SERVER_NAME` because we want to see the behavior
  252. # from `_check_sigs_and_hash_and_fetch_one` where it tries to
  253. # fetch the PDU again from the origin server if the signature
  254. # fails. Just want to make sure that the failure is counted from
  255. # both code paths.
  256. dest="yet.another.server",
  257. room_id=room_id,
  258. limit=1,
  259. extremities=[pulled_event.event_id],
  260. ),
  261. )
  262. # Make sure our failed pull attempt was recorded
  263. backfill_num_attempts = self.get_success(
  264. main_store.db_pool.simple_select_one_onecol(
  265. table="event_failed_pull_attempts",
  266. keyvalues={"event_id": pulled_event.event_id},
  267. retcol="num_attempts",
  268. )
  269. )
  270. # This is 2 because it failed once from `self.OTHER_SERVER_NAME` and the
  271. # other from "yet.another.server"
  272. self.assertEqual(backfill_num_attempts, 2)