test_directory.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. # Copyright 2019 New Vector Ltd
  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 http import HTTPStatus
  15. from twisted.test.proto_helpers import MemoryReactor
  16. from synapse.appservice import ApplicationService
  17. from synapse.rest import admin
  18. from synapse.rest.client import directory, login, room
  19. from synapse.server import HomeServer
  20. from synapse.types import RoomAlias
  21. from synapse.util import Clock
  22. from synapse.util.stringutils import random_string
  23. from tests import unittest
  24. from tests.unittest import override_config
  25. class DirectoryTestCase(unittest.HomeserverTestCase):
  26. servlets = [
  27. admin.register_servlets_for_client_rest_resource,
  28. directory.register_servlets,
  29. login.register_servlets,
  30. room.register_servlets,
  31. ]
  32. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  33. config = self.default_config()
  34. config["require_membership_for_aliases"] = True
  35. self.hs = self.setup_test_homeserver(config=config)
  36. return self.hs
  37. def prepare(
  38. self, reactor: MemoryReactor, clock: Clock, homeserver: HomeServer
  39. ) -> None:
  40. """Create two local users and access tokens for them.
  41. One of them creates a room."""
  42. self.room_owner = self.register_user("room_owner", "test")
  43. self.room_owner_tok = self.login("room_owner", "test")
  44. self.room_id = self.helper.create_room_as(
  45. self.room_owner, tok=self.room_owner_tok
  46. )
  47. self.user = self.register_user("user", "test")
  48. self.user_tok = self.login("user", "test")
  49. def test_state_event_not_in_room(self) -> None:
  50. self.ensure_user_left_room()
  51. self.set_alias_via_state_event(HTTPStatus.FORBIDDEN)
  52. def test_directory_endpoint_not_in_room(self) -> None:
  53. self.ensure_user_left_room()
  54. self.set_alias_via_directory(HTTPStatus.FORBIDDEN)
  55. def test_state_event_in_room_too_long(self) -> None:
  56. self.ensure_user_joined_room()
  57. self.set_alias_via_state_event(HTTPStatus.BAD_REQUEST, alias_length=256)
  58. def test_directory_in_room_too_long(self) -> None:
  59. self.ensure_user_joined_room()
  60. self.set_alias_via_directory(HTTPStatus.BAD_REQUEST, alias_length=256)
  61. @override_config({"default_room_version": 5})
  62. def test_state_event_user_in_v5_room(self) -> None:
  63. """Test that a regular user can add alias events before room v6"""
  64. self.ensure_user_joined_room()
  65. self.set_alias_via_state_event(HTTPStatus.OK)
  66. @override_config({"default_room_version": 6})
  67. def test_state_event_v6_room(self) -> None:
  68. """Test that a regular user can *not* add alias events from room v6"""
  69. self.ensure_user_joined_room()
  70. self.set_alias_via_state_event(HTTPStatus.FORBIDDEN)
  71. def test_directory_in_room(self) -> None:
  72. self.ensure_user_joined_room()
  73. self.set_alias_via_directory(HTTPStatus.OK)
  74. def test_room_creation_too_long(self) -> None:
  75. url = "/_matrix/client/r0/createRoom"
  76. # We use deliberately a localpart under the length threshold so
  77. # that we can make sure that the check is done on the whole alias.
  78. request_data = {"room_alias_name": random_string(256 - len(self.hs.hostname))}
  79. channel = self.make_request(
  80. "POST", url, request_data, access_token=self.user_tok
  81. )
  82. self.assertEqual(channel.code, HTTPStatus.BAD_REQUEST, channel.result)
  83. def test_room_creation(self) -> None:
  84. url = "/_matrix/client/r0/createRoom"
  85. # Check with an alias of allowed length. There should already be
  86. # a test that ensures it works in test_register.py, but let's be
  87. # as cautious as possible here.
  88. request_data = {"room_alias_name": random_string(5)}
  89. channel = self.make_request(
  90. "POST", url, request_data, access_token=self.user_tok
  91. )
  92. self.assertEqual(channel.code, HTTPStatus.OK, channel.result)
  93. def test_deleting_alias_via_directory(self) -> None:
  94. # Add an alias for the room. We must be joined to do so.
  95. self.ensure_user_joined_room()
  96. alias = self.set_alias_via_directory(HTTPStatus.OK)
  97. # Then try to remove the alias
  98. channel = self.make_request(
  99. "DELETE",
  100. f"/_matrix/client/r0/directory/room/{alias}",
  101. access_token=self.user_tok,
  102. )
  103. self.assertEqual(channel.code, HTTPStatus.OK, channel.result)
  104. def test_deleting_alias_via_directory_appservice(self) -> None:
  105. user_id = "@as:test"
  106. as_token = "i_am_an_app_service"
  107. appservice = ApplicationService(
  108. as_token,
  109. id="1234",
  110. namespaces={"aliases": [{"regex": "#asns-*", "exclusive": True}]},
  111. sender=user_id,
  112. )
  113. self.hs.get_datastores().main.services_cache.append(appservice)
  114. # Add an alias for the room, as the appservice
  115. alias = RoomAlias(f"asns-{random_string(5)}", self.hs.hostname).to_string()
  116. request_data = {"room_id": self.room_id}
  117. channel = self.make_request(
  118. "PUT",
  119. f"/_matrix/client/r0/directory/room/{alias}",
  120. request_data,
  121. access_token=as_token,
  122. )
  123. self.assertEqual(channel.code, HTTPStatus.OK, channel.result)
  124. # Then try to remove the alias, as the appservice
  125. channel = self.make_request(
  126. "DELETE",
  127. f"/_matrix/client/r0/directory/room/{alias}",
  128. access_token=as_token,
  129. )
  130. self.assertEqual(channel.code, HTTPStatus.OK, channel.result)
  131. def test_deleting_nonexistant_alias(self) -> None:
  132. # Check that no alias exists
  133. alias = "#potato:test"
  134. channel = self.make_request(
  135. "GET",
  136. f"/_matrix/client/r0/directory/room/{alias}",
  137. access_token=self.user_tok,
  138. )
  139. self.assertEqual(channel.code, HTTPStatus.NOT_FOUND, channel.result)
  140. self.assertIn("error", channel.json_body, channel.json_body)
  141. self.assertEqual(channel.json_body["errcode"], "M_NOT_FOUND", channel.json_body)
  142. # Then try to remove the alias
  143. channel = self.make_request(
  144. "DELETE",
  145. f"/_matrix/client/r0/directory/room/{alias}",
  146. access_token=self.user_tok,
  147. )
  148. self.assertEqual(channel.code, HTTPStatus.NOT_FOUND, channel.result)
  149. self.assertIn("error", channel.json_body, channel.json_body)
  150. self.assertEqual(channel.json_body["errcode"], "M_NOT_FOUND", channel.json_body)
  151. def set_alias_via_state_event(
  152. self, expected_code: HTTPStatus, alias_length: int = 5
  153. ) -> None:
  154. url = "/_matrix/client/r0/rooms/%s/state/m.room.aliases/%s" % (
  155. self.room_id,
  156. self.hs.hostname,
  157. )
  158. request_data = {"aliases": [self.random_alias(alias_length)]}
  159. channel = self.make_request(
  160. "PUT", url, request_data, access_token=self.user_tok
  161. )
  162. self.assertEqual(channel.code, expected_code, channel.result)
  163. def set_alias_via_directory(
  164. self, expected_code: HTTPStatus, alias_length: int = 5
  165. ) -> str:
  166. alias = self.random_alias(alias_length)
  167. url = "/_matrix/client/r0/directory/room/%s" % alias
  168. request_data = {"room_id": self.room_id}
  169. channel = self.make_request(
  170. "PUT", url, request_data, access_token=self.user_tok
  171. )
  172. self.assertEqual(channel.code, expected_code, channel.result)
  173. return alias
  174. def test_invalid_alias(self) -> None:
  175. alias = "#potato"
  176. channel = self.make_request(
  177. "GET",
  178. f"/_matrix/client/r0/directory/room/{alias}",
  179. access_token=self.user_tok,
  180. )
  181. self.assertEqual(channel.code, HTTPStatus.BAD_REQUEST, channel.result)
  182. self.assertIn("error", channel.json_body, channel.json_body)
  183. self.assertEqual(
  184. channel.json_body["errcode"], "M_INVALID_PARAM", channel.json_body
  185. )
  186. def random_alias(self, length: int) -> str:
  187. return RoomAlias(random_string(length), self.hs.hostname).to_string()
  188. def ensure_user_left_room(self) -> None:
  189. self.ensure_membership("leave")
  190. def ensure_user_joined_room(self) -> None:
  191. self.ensure_membership("join")
  192. def ensure_membership(self, membership: str) -> None:
  193. try:
  194. if membership == "leave":
  195. self.helper.leave(room=self.room_id, user=self.user, tok=self.user_tok)
  196. if membership == "join":
  197. self.helper.join(room=self.room_id, user=self.user, tok=self.user_tok)
  198. except AssertionError:
  199. # We don't care whether the leave request didn't return a 200 (e.g.
  200. # if the user isn't already in the room), because we only want to
  201. # make sure the user isn't in the room.
  202. pass