test_upgrade_room.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. # Copyright 2021 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.mock import patch
  16. from twisted.test.proto_helpers import MemoryReactor
  17. from synapse.api.constants import EventContentFields, EventTypes, RoomTypes
  18. from synapse.config.server import DEFAULT_ROOM_VERSION
  19. from synapse.rest import admin
  20. from synapse.rest.client import login, room, room_upgrade_rest_servlet
  21. from synapse.server import HomeServer
  22. from synapse.util import Clock
  23. from tests import unittest
  24. from tests.server import FakeChannel
  25. class UpgradeRoomTest(unittest.HomeserverTestCase):
  26. servlets = [
  27. admin.register_servlets,
  28. login.register_servlets,
  29. room.register_servlets,
  30. room_upgrade_rest_servlet.register_servlets,
  31. ]
  32. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  33. self.store = hs.get_datastores().main
  34. self.creator = self.register_user("creator", "pass")
  35. self.creator_token = self.login(self.creator, "pass")
  36. self.other = self.register_user("user", "pass")
  37. self.other_token = self.login(self.other, "pass")
  38. self.room_id = self.helper.create_room_as(self.creator, tok=self.creator_token)
  39. self.helper.join(self.room_id, self.other, tok=self.other_token)
  40. def _upgrade_room(
  41. self,
  42. token: Optional[str] = None,
  43. room_id: Optional[str] = None,
  44. expire_cache: bool = True,
  45. ) -> FakeChannel:
  46. if expire_cache:
  47. # We don't want a cached response.
  48. self.reactor.advance(5 * 60 + 1)
  49. if room_id is None:
  50. room_id = self.room_id
  51. return self.make_request(
  52. "POST",
  53. f"/_matrix/client/r0/rooms/{room_id}/upgrade",
  54. # This will upgrade a room to the same version, but that's fine.
  55. content={"new_version": DEFAULT_ROOM_VERSION},
  56. access_token=token or self.creator_token,
  57. )
  58. def test_upgrade(self) -> None:
  59. """
  60. Upgrading a room should work fine.
  61. """
  62. channel = self._upgrade_room()
  63. self.assertEqual(200, channel.code, channel.result)
  64. self.assertIn("replacement_room", channel.json_body)
  65. new_room_id = channel.json_body["replacement_room"]
  66. # Check that the tombstone event points to the new room.
  67. tombstone_event = self.get_success(
  68. self.hs.get_storage_controllers().state.get_current_state_event(
  69. self.room_id, EventTypes.Tombstone, ""
  70. )
  71. )
  72. assert tombstone_event is not None
  73. self.assertEqual(new_room_id, tombstone_event.content["replacement_room"])
  74. # Check that the new room exists.
  75. room = self.get_success(self.store.get_room(new_room_id))
  76. self.assertIsNotNone(room)
  77. def test_never_in_room(self) -> None:
  78. """
  79. A user who has never been in the room cannot upgrade the room.
  80. """
  81. # The user isn't in the room.
  82. roomless = self.register_user("roomless", "pass")
  83. roomless_token = self.login(roomless, "pass")
  84. channel = self._upgrade_room(roomless_token)
  85. self.assertEqual(403, channel.code, channel.result)
  86. def test_left_room(self) -> None:
  87. """
  88. A user who is no longer in the room cannot upgrade the room.
  89. """
  90. # Remove the user from the room.
  91. self.helper.leave(self.room_id, self.creator, tok=self.creator_token)
  92. channel = self._upgrade_room(self.creator_token)
  93. self.assertEqual(403, channel.code, channel.result)
  94. def test_power_levels(self) -> None:
  95. """
  96. Another user can upgrade the room if their power level is increased.
  97. """
  98. # The other user doesn't have the proper power level.
  99. channel = self._upgrade_room(self.other_token)
  100. self.assertEqual(403, channel.code, channel.result)
  101. # Increase the power levels so that this user can upgrade.
  102. power_levels = self.helper.get_state(
  103. self.room_id,
  104. "m.room.power_levels",
  105. tok=self.creator_token,
  106. )
  107. power_levels["users"][self.other] = 100
  108. self.helper.send_state(
  109. self.room_id,
  110. "m.room.power_levels",
  111. body=power_levels,
  112. tok=self.creator_token,
  113. )
  114. # The upgrade should succeed!
  115. channel = self._upgrade_room(self.other_token)
  116. self.assertEqual(200, channel.code, channel.result)
  117. def test_power_levels_user_default(self) -> None:
  118. """
  119. Another user can upgrade the room if the default power level for users is increased.
  120. """
  121. # The other user doesn't have the proper power level.
  122. channel = self._upgrade_room(self.other_token)
  123. self.assertEqual(403, channel.code, channel.result)
  124. # Increase the power levels so that this user can upgrade.
  125. power_levels = self.helper.get_state(
  126. self.room_id,
  127. "m.room.power_levels",
  128. tok=self.creator_token,
  129. )
  130. power_levels["users_default"] = 100
  131. self.helper.send_state(
  132. self.room_id,
  133. "m.room.power_levels",
  134. body=power_levels,
  135. tok=self.creator_token,
  136. )
  137. # The upgrade should succeed!
  138. channel = self._upgrade_room(self.other_token)
  139. self.assertEqual(200, channel.code, channel.result)
  140. def test_power_levels_tombstone(self) -> None:
  141. """
  142. Another user can upgrade the room if they can send the tombstone event.
  143. """
  144. # The other user doesn't have the proper power level.
  145. channel = self._upgrade_room(self.other_token)
  146. self.assertEqual(403, channel.code, channel.result)
  147. # Increase the power levels so that this user can upgrade.
  148. power_levels = self.helper.get_state(
  149. self.room_id,
  150. "m.room.power_levels",
  151. tok=self.creator_token,
  152. )
  153. power_levels["events"]["m.room.tombstone"] = 0
  154. self.helper.send_state(
  155. self.room_id,
  156. "m.room.power_levels",
  157. body=power_levels,
  158. tok=self.creator_token,
  159. )
  160. # The upgrade should succeed!
  161. channel = self._upgrade_room(self.other_token)
  162. self.assertEqual(200, channel.code, channel.result)
  163. power_levels = self.helper.get_state(
  164. self.room_id,
  165. "m.room.power_levels",
  166. tok=self.creator_token,
  167. )
  168. self.assertNotIn(self.other, power_levels["users"])
  169. def test_stringy_power_levels(self) -> None:
  170. """The room upgrade converts stringy power levels to proper integers."""
  171. # Create a room on room version < 10.
  172. room_id = self.helper.create_room_as(
  173. self.creator, tok=self.creator_token, room_version="9"
  174. )
  175. self.helper.join(room_id, self.other, tok=self.other_token)
  176. # Retrieve the room's current power levels.
  177. power_levels = self.helper.get_state(
  178. room_id,
  179. "m.room.power_levels",
  180. tok=self.creator_token,
  181. )
  182. # Set creator's power level to the string "100" instead of the integer `100`.
  183. power_levels["users"][self.creator] = "100"
  184. # Synapse refuses to accept new stringy power level events. Bypass this by
  185. # neutering the validation.
  186. with patch("synapse.events.validator.jsonschema.validate"):
  187. # Note: https://github.com/matrix-org/matrix-spec/issues/853 plans to forbid
  188. # string power levels in new rooms. For this test to have a clean
  189. # conscience, we ought to ensure it's upgrading from a sufficiently old
  190. # version of room.
  191. self.helper.send_state(
  192. room_id,
  193. "m.room.power_levels",
  194. body=power_levels,
  195. tok=self.creator_token,
  196. )
  197. # Upgrade the room. Check the homeserver reports success.
  198. channel = self._upgrade_room(room_id=room_id)
  199. self.assertEqual(200, channel.code, channel.result)
  200. # Extract the new room ID.
  201. new_room_id = channel.json_body["replacement_room"]
  202. # Fetch the new room's power level event.
  203. new_power_levels = self.helper.get_state(
  204. new_room_id,
  205. "m.room.power_levels",
  206. tok=self.creator_token,
  207. )
  208. # We should now have an integer power level.
  209. self.assertEqual(new_power_levels["users"][self.creator], 100, new_power_levels)
  210. def test_space(self) -> None:
  211. """Test upgrading a space."""
  212. # Create a space.
  213. space_id = self.helper.create_room_as(
  214. self.creator,
  215. tok=self.creator_token,
  216. extra_content={
  217. "creation_content": {EventContentFields.ROOM_TYPE: RoomTypes.SPACE}
  218. },
  219. )
  220. # Add the room as a child room.
  221. self.helper.send_state(
  222. space_id,
  223. event_type=EventTypes.SpaceChild,
  224. body={"via": [self.hs.hostname]},
  225. tok=self.creator_token,
  226. state_key=self.room_id,
  227. )
  228. # Also add a room that was removed.
  229. old_room_id = "!notaroom:" + self.hs.hostname
  230. self.helper.send_state(
  231. space_id,
  232. event_type=EventTypes.SpaceChild,
  233. body={},
  234. tok=self.creator_token,
  235. state_key=old_room_id,
  236. )
  237. # Upgrade the room!
  238. channel = self._upgrade_room(room_id=space_id)
  239. self.assertEqual(200, channel.code, channel.result)
  240. self.assertIn("replacement_room", channel.json_body)
  241. new_space_id = channel.json_body["replacement_room"]
  242. state_ids = self.get_success(
  243. self.store.get_partial_current_state_ids(new_space_id)
  244. )
  245. # Ensure the new room is still a space.
  246. create_event = self.get_success(
  247. self.store.get_event(state_ids[(EventTypes.Create, "")])
  248. )
  249. self.assertEqual(
  250. create_event.content.get(EventContentFields.ROOM_TYPE), RoomTypes.SPACE
  251. )
  252. # The child link should have been copied over.
  253. self.assertIn((EventTypes.SpaceChild, self.room_id), state_ids)
  254. # The child that was removed should not be copied over.
  255. self.assertNotIn((EventTypes.SpaceChild, old_room_id), state_ids)
  256. def test_custom_room_type(self) -> None:
  257. """Test upgrading a room that has a custom room type set."""
  258. test_room_type = "com.example.my_custom_room_type"
  259. # Create a room with a custom room type.
  260. room_id = self.helper.create_room_as(
  261. self.creator,
  262. tok=self.creator_token,
  263. extra_content={
  264. "creation_content": {EventContentFields.ROOM_TYPE: test_room_type}
  265. },
  266. )
  267. # Upgrade the room!
  268. channel = self._upgrade_room(room_id=room_id)
  269. self.assertEqual(200, channel.code, channel.result)
  270. self.assertIn("replacement_room", channel.json_body)
  271. new_room_id = channel.json_body["replacement_room"]
  272. state_ids = self.get_success(
  273. self.store.get_partial_current_state_ids(new_room_id)
  274. )
  275. # Ensure the new room is the same type as the old room.
  276. create_event = self.get_success(
  277. self.store.get_event(state_ids[(EventTypes.Create, "")])
  278. )
  279. self.assertEqual(
  280. create_event.content.get(EventContentFields.ROOM_TYPE), test_room_type
  281. )
  282. def test_second_upgrade_from_same_user(self) -> None:
  283. """A second room upgrade from the same user is deduplicated."""
  284. channel1 = self._upgrade_room()
  285. self.assertEqual(200, channel1.code, channel1.result)
  286. channel2 = self._upgrade_room(expire_cache=False)
  287. self.assertEqual(200, channel2.code, channel2.result)
  288. self.assertEqual(
  289. channel1.json_body["replacement_room"],
  290. channel2.json_body["replacement_room"],
  291. )
  292. def test_second_upgrade_after_delay(self) -> None:
  293. """A second room upgrade is not deduplicated after some time has passed."""
  294. channel1 = self._upgrade_room()
  295. self.assertEqual(200, channel1.code, channel1.result)
  296. channel2 = self._upgrade_room(expire_cache=True)
  297. self.assertEqual(200, channel2.code, channel2.result)
  298. self.assertNotEqual(
  299. channel1.json_body["replacement_room"],
  300. channel2.json_body["replacement_room"],
  301. )
  302. def test_second_upgrade_from_different_user(self) -> None:
  303. """A second room upgrade from a different user is blocked."""
  304. channel = self._upgrade_room()
  305. self.assertEqual(200, channel.code, channel.result)
  306. channel = self._upgrade_room(self.other_token, expire_cache=False)
  307. self.assertEqual(400, channel.code, channel.result)
  308. def test_first_upgrade_does_not_block_second(self) -> None:
  309. """A second room upgrade is not blocked when a previous upgrade attempt was not
  310. allowed.
  311. """
  312. channel = self._upgrade_room(self.other_token)
  313. self.assertEqual(403, channel.code, channel.result)
  314. channel = self._upgrade_room(expire_cache=False)
  315. self.assertEqual(200, channel.code, channel.result)