test_upgrade_room.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  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. self.assertIsNotNone(tombstone_event)
  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. # Retrieve the room's current power levels.
  172. power_levels = self.helper.get_state(
  173. self.room_id,
  174. "m.room.power_levels",
  175. tok=self.creator_token,
  176. )
  177. # Set creator's power level to the string "100" instead of the integer `100`.
  178. power_levels["users"][self.creator] = "100"
  179. # Synapse refuses to accept new stringy power level events. Bypass this by
  180. # neutering the validation.
  181. with patch("synapse.events.validator.jsonschema.validate"):
  182. # Note: https://github.com/matrix-org/matrix-spec/issues/853 plans to forbid
  183. # string power levels in new rooms. For this test to have a clean
  184. # conscience, we ought to ensure it's upgrading from a sufficiently old
  185. # version of room.
  186. self.helper.send_state(
  187. self.room_id,
  188. "m.room.power_levels",
  189. body=power_levels,
  190. tok=self.creator_token,
  191. )
  192. # Upgrade the room. Check the homeserver reports success.
  193. channel = self._upgrade_room()
  194. self.assertEqual(200, channel.code, channel.result)
  195. # Extract the new room ID.
  196. new_room_id = channel.json_body["replacement_room"]
  197. # Fetch the new room's power level event.
  198. new_power_levels = self.helper.get_state(
  199. new_room_id,
  200. "m.room.power_levels",
  201. tok=self.creator_token,
  202. )
  203. # We should now have an integer power level.
  204. self.assertEqual(new_power_levels["users"][self.creator], 100, new_power_levels)
  205. def test_space(self) -> None:
  206. """Test upgrading a space."""
  207. # Create a space.
  208. space_id = self.helper.create_room_as(
  209. self.creator,
  210. tok=self.creator_token,
  211. extra_content={
  212. "creation_content": {EventContentFields.ROOM_TYPE: RoomTypes.SPACE}
  213. },
  214. )
  215. # Add the room as a child room.
  216. self.helper.send_state(
  217. space_id,
  218. event_type=EventTypes.SpaceChild,
  219. body={"via": [self.hs.hostname]},
  220. tok=self.creator_token,
  221. state_key=self.room_id,
  222. )
  223. # Also add a room that was removed.
  224. old_room_id = "!notaroom:" + self.hs.hostname
  225. self.helper.send_state(
  226. space_id,
  227. event_type=EventTypes.SpaceChild,
  228. body={},
  229. tok=self.creator_token,
  230. state_key=old_room_id,
  231. )
  232. # Upgrade the room!
  233. channel = self._upgrade_room(room_id=space_id)
  234. self.assertEqual(200, channel.code, channel.result)
  235. self.assertIn("replacement_room", channel.json_body)
  236. new_space_id = channel.json_body["replacement_room"]
  237. state_ids = self.get_success(
  238. self.store.get_partial_current_state_ids(new_space_id)
  239. )
  240. # Ensure the new room is still a space.
  241. create_event = self.get_success(
  242. self.store.get_event(state_ids[(EventTypes.Create, "")])
  243. )
  244. self.assertEqual(
  245. create_event.content.get(EventContentFields.ROOM_TYPE), RoomTypes.SPACE
  246. )
  247. # The child link should have been copied over.
  248. self.assertIn((EventTypes.SpaceChild, self.room_id), state_ids)
  249. # The child that was removed should not be copied over.
  250. self.assertNotIn((EventTypes.SpaceChild, old_room_id), state_ids)
  251. def test_custom_room_type(self) -> None:
  252. """Test upgrading a room that has a custom room type set."""
  253. test_room_type = "com.example.my_custom_room_type"
  254. # Create a room with a custom room type.
  255. room_id = self.helper.create_room_as(
  256. self.creator,
  257. tok=self.creator_token,
  258. extra_content={
  259. "creation_content": {EventContentFields.ROOM_TYPE: test_room_type}
  260. },
  261. )
  262. # Upgrade the room!
  263. channel = self._upgrade_room(room_id=room_id)
  264. self.assertEqual(200, channel.code, channel.result)
  265. self.assertIn("replacement_room", channel.json_body)
  266. new_room_id = channel.json_body["replacement_room"]
  267. state_ids = self.get_success(
  268. self.store.get_partial_current_state_ids(new_room_id)
  269. )
  270. # Ensure the new room is the same type as the old room.
  271. create_event = self.get_success(
  272. self.store.get_event(state_ids[(EventTypes.Create, "")])
  273. )
  274. self.assertEqual(
  275. create_event.content.get(EventContentFields.ROOM_TYPE), test_room_type
  276. )
  277. def test_second_upgrade_from_same_user(self) -> None:
  278. """A second room upgrade from the same user is deduplicated."""
  279. channel1 = self._upgrade_room()
  280. self.assertEqual(200, channel1.code, channel1.result)
  281. channel2 = self._upgrade_room(expire_cache=False)
  282. self.assertEqual(200, channel2.code, channel2.result)
  283. self.assertEqual(
  284. channel1.json_body["replacement_room"],
  285. channel2.json_body["replacement_room"],
  286. )
  287. def test_second_upgrade_after_delay(self) -> None:
  288. """A second room upgrade is not deduplicated after some time has passed."""
  289. channel1 = self._upgrade_room()
  290. self.assertEqual(200, channel1.code, channel1.result)
  291. channel2 = self._upgrade_room(expire_cache=True)
  292. self.assertEqual(200, channel2.code, channel2.result)
  293. self.assertNotEqual(
  294. channel1.json_body["replacement_room"],
  295. channel2.json_body["replacement_room"],
  296. )
  297. def test_second_upgrade_from_different_user(self) -> None:
  298. """A second room upgrade from a different user is blocked."""
  299. channel = self._upgrade_room()
  300. self.assertEqual(200, channel.code, channel.result)
  301. channel = self._upgrade_room(self.other_token, expire_cache=False)
  302. self.assertEqual(400, channel.code, channel.result)
  303. def test_first_upgrade_does_not_block_second(self) -> None:
  304. """A second room upgrade is not blocked when a previous upgrade attempt was not
  305. allowed.
  306. """
  307. channel = self._upgrade_room(self.other_token)
  308. self.assertEqual(403, channel.code, channel.result)
  309. channel = self._upgrade_room(expire_cache=False)
  310. self.assertEqual(200, channel.code, channel.result)