test_knocking.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. # Copyright 2020 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 collections import OrderedDict
  15. from typing import Dict, List
  16. from synapse.api.constants import EventTypes, JoinRules, Membership
  17. from synapse.api.room_versions import RoomVersions
  18. from synapse.events import builder
  19. from synapse.rest import admin
  20. from synapse.rest.client import login, room
  21. from synapse.server import HomeServer
  22. from synapse.types import RoomAlias
  23. from tests.test_utils import event_injection
  24. from tests.unittest import FederatingHomeserverTestCase, TestCase, override_config
  25. class KnockingStrippedStateEventHelperMixin(TestCase):
  26. def send_example_state_events_to_room(
  27. self,
  28. hs: "HomeServer",
  29. room_id: str,
  30. sender: str,
  31. ) -> OrderedDict:
  32. """Adds some state to a room. State events are those that should be sent to a knocking
  33. user after they knock on the room, as well as some state that *shouldn't* be sent
  34. to the knocking user.
  35. Args:
  36. hs: The homeserver of the sender.
  37. room_id: The ID of the room to send state into.
  38. sender: The ID of the user to send state as. Must be in the room.
  39. Returns:
  40. The OrderedDict of event types and content that a user is expected to see
  41. after knocking on a room.
  42. """
  43. # To set a canonical alias, we'll need to point an alias at the room first.
  44. canonical_alias = "#fancy_alias:test"
  45. self.get_success(
  46. self.store.create_room_alias_association(
  47. RoomAlias.from_string(canonical_alias), room_id, ["test"]
  48. )
  49. )
  50. # Send some state that we *don't* expect to be given to knocking users
  51. self.get_success(
  52. event_injection.inject_event(
  53. hs,
  54. room_version=RoomVersions.V7.identifier,
  55. room_id=room_id,
  56. sender=sender,
  57. type="com.example.secret",
  58. state_key="",
  59. content={"secret": "password"},
  60. )
  61. )
  62. # We use an OrderedDict here to ensure that the knock membership appears last.
  63. # Note that order only matters when sending stripped state to clients, not federated
  64. # homeservers.
  65. room_state = OrderedDict(
  66. [
  67. # We need to set the room's join rules to allow knocking
  68. (
  69. EventTypes.JoinRules,
  70. {"content": {"join_rule": JoinRules.KNOCK}, "state_key": ""},
  71. ),
  72. # Below are state events that are to be stripped and sent to clients
  73. (
  74. EventTypes.Name,
  75. {"content": {"name": "A cool room"}, "state_key": ""},
  76. ),
  77. (
  78. EventTypes.RoomAvatar,
  79. {
  80. "content": {
  81. "info": {
  82. "h": 398,
  83. "mimetype": "image/jpeg",
  84. "size": 31037,
  85. "w": 394,
  86. },
  87. "url": "mxc://example.org/JWEIFJgwEIhweiWJE",
  88. },
  89. "state_key": "",
  90. },
  91. ),
  92. (
  93. EventTypes.RoomEncryption,
  94. {"content": {"algorithm": "m.megolm.v1.aes-sha2"}, "state_key": ""},
  95. ),
  96. (
  97. EventTypes.CanonicalAlias,
  98. {
  99. "content": {"alias": canonical_alias, "alt_aliases": []},
  100. "state_key": "",
  101. },
  102. ),
  103. ]
  104. )
  105. for event_type, event_dict in room_state.items():
  106. event_content = event_dict["content"]
  107. state_key = event_dict["state_key"]
  108. self.get_success(
  109. event_injection.inject_event(
  110. hs,
  111. room_version=RoomVersions.V7.identifier,
  112. room_id=room_id,
  113. sender=sender,
  114. type=event_type,
  115. state_key=state_key,
  116. content=event_content,
  117. )
  118. )
  119. # Finally, we expect to see the m.room.create event of the room as part of the
  120. # stripped state. We don't need to inject this event though.
  121. room_state[EventTypes.Create] = {
  122. "content": {
  123. "creator": sender,
  124. "room_version": RoomVersions.V7.identifier,
  125. },
  126. "state_key": "",
  127. }
  128. return room_state
  129. def check_knock_room_state_against_room_state(
  130. self,
  131. knock_room_state: List[Dict],
  132. expected_room_state: Dict,
  133. ) -> None:
  134. """Test a list of stripped room state events received over federation against a
  135. dict of expected state events.
  136. Args:
  137. knock_room_state: The list of room state that was received over federation.
  138. expected_room_state: A dict containing the room state we expect to see in
  139. `knock_room_state`.
  140. """
  141. for event in knock_room_state:
  142. event_type = event["type"]
  143. # Check that this event type is one of those that we expected.
  144. # Note: This will also check that no excess state was included
  145. self.assertIn(event_type, expected_room_state)
  146. # Check the state content matches
  147. self.assertEquals(
  148. expected_room_state[event_type]["content"], event["content"]
  149. )
  150. # Check the state key is correct
  151. self.assertEqual(
  152. expected_room_state[event_type]["state_key"], event["state_key"]
  153. )
  154. # Ensure the event has been stripped
  155. self.assertNotIn("signatures", event)
  156. # Pop once we've found and processed a state event
  157. expected_room_state.pop(event_type)
  158. # Check that all expected state events were accounted for
  159. self.assertEqual(len(expected_room_state), 0)
  160. class FederationKnockingTestCase(
  161. FederatingHomeserverTestCase, KnockingStrippedStateEventHelperMixin
  162. ):
  163. servlets = [
  164. admin.register_servlets,
  165. room.register_servlets,
  166. login.register_servlets,
  167. ]
  168. def prepare(self, reactor, clock, homeserver):
  169. self.store = homeserver.get_datastore()
  170. # We're not going to be properly signing events as our remote homeserver is fake,
  171. # therefore disable event signature checks.
  172. # Note that these checks are not relevant to this test case.
  173. # Have this homeserver auto-approve all event signature checking.
  174. async def approve_all_signature_checking(_, pdu):
  175. return pdu
  176. homeserver.get_federation_server()._check_sigs_and_hash = (
  177. approve_all_signature_checking
  178. )
  179. # Have this homeserver skip event auth checks. This is necessary due to
  180. # event auth checks ensuring that events were signed by the sender's homeserver.
  181. async def _check_event_auth(origin, event, context, *args, **kwargs):
  182. return context
  183. homeserver.get_federation_handler()._check_event_auth = _check_event_auth
  184. return super().prepare(reactor, clock, homeserver)
  185. @override_config({"experimental_features": {"msc2403_enabled": True}})
  186. def test_room_state_returned_when_knocking(self):
  187. """
  188. Tests that specific, stripped state events from a room are returned after
  189. a remote homeserver successfully knocks on a local room.
  190. """
  191. user_id = self.register_user("u1", "you the one")
  192. user_token = self.login("u1", "you the one")
  193. fake_knocking_user_id = "@user:other.example.com"
  194. # Create a room with a room version that includes knocking
  195. room_id = self.helper.create_room_as(
  196. "u1",
  197. is_public=False,
  198. room_version=RoomVersions.V7.identifier,
  199. tok=user_token,
  200. )
  201. # Update the join rules and add additional state to the room to check for later
  202. expected_room_state = self.send_example_state_events_to_room(
  203. self.hs, room_id, user_id
  204. )
  205. channel = self.make_request(
  206. "GET",
  207. "/_matrix/federation/v1/make_knock/%s/%s?ver=%s"
  208. % (
  209. room_id,
  210. fake_knocking_user_id,
  211. # Inform the remote that we support the room version of the room we're
  212. # knocking on
  213. RoomVersions.V7.identifier,
  214. ),
  215. )
  216. self.assertEquals(200, channel.code, channel.result)
  217. # Note: We don't expect the knock membership event to be sent over federation as
  218. # part of the stripped room state, as the knocking homeserver already has that
  219. # event. It is only done for clients during /sync
  220. # Extract the generated knock event json
  221. knock_event = channel.json_body["event"]
  222. # Check that the event has things we expect in it
  223. self.assertEquals(knock_event["room_id"], room_id)
  224. self.assertEquals(knock_event["sender"], fake_knocking_user_id)
  225. self.assertEquals(knock_event["state_key"], fake_knocking_user_id)
  226. self.assertEquals(knock_event["type"], EventTypes.Member)
  227. self.assertEquals(knock_event["content"]["membership"], Membership.KNOCK)
  228. # Turn the event json dict into a proper event.
  229. # We won't sign it properly, but that's OK as we stub out event auth in `prepare`
  230. signed_knock_event = builder.create_local_event_from_event_dict(
  231. self.clock,
  232. self.hs.hostname,
  233. self.hs.signing_key,
  234. room_version=RoomVersions.V7,
  235. event_dict=knock_event,
  236. )
  237. # Convert our proper event back to json dict format
  238. signed_knock_event_json = signed_knock_event.get_pdu_json(
  239. self.clock.time_msec()
  240. )
  241. # Send the signed knock event into the room
  242. channel = self.make_request(
  243. "PUT",
  244. "/_matrix/federation/v1/send_knock/%s/%s"
  245. % (room_id, signed_knock_event.event_id),
  246. signed_knock_event_json,
  247. )
  248. self.assertEquals(200, channel.code, channel.result)
  249. # Check that we got the stripped room state in return
  250. room_state_events = channel.json_body["knock_state_events"]
  251. # Validate the stripped room state events
  252. self.check_knock_room_state_against_room_state(
  253. room_state_events, expected_room_state
  254. )