1
0

test_federation_client.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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. import json
  15. from unittest import mock
  16. import twisted.web.client
  17. from twisted.internet import defer
  18. from twisted.internet.protocol import Protocol
  19. from twisted.python.failure import Failure
  20. from twisted.test.proto_helpers import MemoryReactor
  21. from synapse.api.room_versions import RoomVersions
  22. from synapse.events import EventBase
  23. from synapse.server import HomeServer
  24. from synapse.types import JsonDict
  25. from synapse.util import Clock
  26. from tests.unittest import FederatingHomeserverTestCase
  27. class FederationClientTest(FederatingHomeserverTestCase):
  28. def prepare(self, reactor: MemoryReactor, clock: Clock, homeserver: HomeServer):
  29. super().prepare(reactor, clock, homeserver)
  30. # mock out the Agent used by the federation client, which is easier than
  31. # catching the HTTPS connection and do the TLS stuff.
  32. self._mock_agent = mock.create_autospec(twisted.web.client.Agent, spec_set=True)
  33. homeserver.get_federation_http_client().agent = self._mock_agent
  34. # Move clock up to somewhat realistic time so the PDU destination retry
  35. # works (`now` needs to be larger than `0 + PDU_RETRY_TIME_MS`).
  36. self.reactor.advance(1000000000)
  37. self.creator = f"@creator:{self.OTHER_SERVER_NAME}"
  38. self.test_room_id = "!room_id"
  39. def test_get_room_state(self):
  40. # mock up some events to use in the response.
  41. # In real life, these would have things in `prev_events` and `auth_events`, but that's
  42. # a bit annoying to mock up, and the code under test doesn't care, so we don't bother.
  43. create_event_dict = self.add_hashes_and_signatures_from_other_server(
  44. {
  45. "room_id": self.test_room_id,
  46. "type": "m.room.create",
  47. "state_key": "",
  48. "sender": self.creator,
  49. "content": {"creator": self.creator},
  50. "prev_events": [],
  51. "auth_events": [],
  52. "origin_server_ts": 500,
  53. }
  54. )
  55. member_event_dict = self.add_hashes_and_signatures_from_other_server(
  56. {
  57. "room_id": self.test_room_id,
  58. "type": "m.room.member",
  59. "sender": self.creator,
  60. "state_key": self.creator,
  61. "content": {"membership": "join"},
  62. "prev_events": [],
  63. "auth_events": [],
  64. "origin_server_ts": 600,
  65. }
  66. )
  67. pl_event_dict = self.add_hashes_and_signatures_from_other_server(
  68. {
  69. "room_id": self.test_room_id,
  70. "type": "m.room.power_levels",
  71. "sender": self.creator,
  72. "state_key": "",
  73. "content": {},
  74. "prev_events": [],
  75. "auth_events": [],
  76. "origin_server_ts": 700,
  77. }
  78. )
  79. # mock up the response, and have the agent return it
  80. self._mock_agent.request.side_effect = lambda *args, **kwargs: defer.succeed(
  81. _mock_response(
  82. {
  83. "pdus": [
  84. create_event_dict,
  85. member_event_dict,
  86. pl_event_dict,
  87. ],
  88. "auth_chain": [
  89. create_event_dict,
  90. member_event_dict,
  91. ],
  92. }
  93. )
  94. )
  95. # now fire off the request
  96. state_resp, auth_resp = self.get_success(
  97. self.hs.get_federation_client().get_room_state(
  98. "yet.another.server",
  99. self.test_room_id,
  100. "event_id",
  101. RoomVersions.V9,
  102. )
  103. )
  104. # check the right call got made to the agent
  105. self._mock_agent.request.assert_called_once_with(
  106. b"GET",
  107. b"matrix://yet.another.server/_matrix/federation/v1/state/%21room_id?event_id=event_id",
  108. headers=mock.ANY,
  109. bodyProducer=None,
  110. )
  111. # ... and that the response is correct.
  112. # the auth_resp should be empty because all the events are also in state
  113. self.assertEqual(auth_resp, [])
  114. # all of the events should be returned in state_resp, though not necessarily
  115. # in the same order. We just check the type on the assumption that if the type
  116. # is right, so is the rest of the event.
  117. self.assertCountEqual(
  118. [e.type for e in state_resp],
  119. ["m.room.create", "m.room.member", "m.room.power_levels"],
  120. )
  121. def test_get_pdu_returns_nothing_when_event_does_not_exist(self):
  122. """No event should be returned when the event does not exist"""
  123. remote_pdu = self.get_success(
  124. self.hs.get_federation_client().get_pdu(
  125. ["yet.another.server"],
  126. "event_should_not_exist",
  127. RoomVersions.V9,
  128. )
  129. )
  130. self.assertEqual(remote_pdu, None)
  131. def test_get_pdu(self):
  132. """Test to make sure an event is returned by `get_pdu()`"""
  133. self._get_pdu_once()
  134. def test_get_pdu_event_from_cache_is_pristine(self):
  135. """Test that modifications made to events returned by `get_pdu()`
  136. do not propagate back to to the internal cache (events returned should
  137. be a copy).
  138. """
  139. # Get the PDU in the cache
  140. remote_pdu = self._get_pdu_once()
  141. # Modify the the event reference.
  142. # This change should not make it back to the `_get_pdu_cache`.
  143. remote_pdu.internal_metadata.outlier = True
  144. # Get the event again. This time it should read it from cache.
  145. remote_pdu2 = self.get_success(
  146. self.hs.get_federation_client().get_pdu(
  147. ["yet.another.server"],
  148. remote_pdu.event_id,
  149. RoomVersions.V9,
  150. )
  151. )
  152. # Sanity check that we are working against the same event
  153. self.assertEqual(remote_pdu.event_id, remote_pdu2.event_id)
  154. # Make sure the event does not include modification from earlier
  155. self.assertIsNotNone(remote_pdu2)
  156. self.assertEqual(remote_pdu2.internal_metadata.outlier, False)
  157. def _get_pdu_once(self) -> EventBase:
  158. """Retrieve an event via `get_pdu()` and assert that an event was returned.
  159. Also used to prime the cache for subsequent test logic.
  160. """
  161. message_event_dict = self.add_hashes_and_signatures_from_other_server(
  162. {
  163. "room_id": self.test_room_id,
  164. "type": "m.room.message",
  165. "sender": self.creator,
  166. "state_key": "",
  167. "content": {},
  168. "prev_events": [],
  169. "auth_events": [],
  170. "origin_server_ts": 700,
  171. "depth": 10,
  172. }
  173. )
  174. # mock up the response, and have the agent return it
  175. self._mock_agent.request.side_effect = lambda *args, **kwargs: defer.succeed(
  176. _mock_response(
  177. {
  178. "origin": "yet.another.server",
  179. "origin_server_ts": 900,
  180. "pdus": [
  181. message_event_dict,
  182. ],
  183. }
  184. )
  185. )
  186. remote_pdu = self.get_success(
  187. self.hs.get_federation_client().get_pdu(
  188. ["yet.another.server"],
  189. "event_id",
  190. RoomVersions.V9,
  191. )
  192. )
  193. # check the right call got made to the agent
  194. self._mock_agent.request.assert_called_once_with(
  195. b"GET",
  196. b"matrix://yet.another.server/_matrix/federation/v1/event/event_id",
  197. headers=mock.ANY,
  198. bodyProducer=None,
  199. )
  200. self.assertIsNotNone(remote_pdu)
  201. self.assertEqual(remote_pdu.internal_metadata.outlier, False)
  202. return remote_pdu
  203. def _mock_response(resp: JsonDict):
  204. body = json.dumps(resp).encode("utf-8")
  205. def deliver_body(p: Protocol):
  206. p.dataReceived(body)
  207. p.connectionLost(Failure(twisted.web.client.ResponseDone()))
  208. response = mock.Mock(
  209. code=200,
  210. phrase=b"OK",
  211. headers=twisted.web.client.Headers({"content-Type": ["application/json"]}),
  212. length=len(body),
  213. deliverBody=deliver_body,
  214. )
  215. mock.seal(response)
  216. return response