1
0

test_directory.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  1. # Copyright 2014-2016 OpenMarket Ltd
  2. # Copyright 2021 Matrix.org Foundation C.I.C.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. from typing import Any, Awaitable, Callable, Dict
  16. from unittest.mock import Mock
  17. from twisted.test.proto_helpers import MemoryReactor
  18. import synapse.api.errors
  19. import synapse.rest.admin
  20. from synapse.api.constants import EventTypes
  21. from synapse.rest.client import directory, login, room
  22. from synapse.server import HomeServer
  23. from synapse.types import JsonDict, RoomAlias, create_requester
  24. from synapse.util import Clock
  25. from tests import unittest
  26. from tests.test_utils import make_awaitable
  27. class DirectoryTestCase(unittest.HomeserverTestCase):
  28. """Tests the directory service."""
  29. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  30. self.mock_federation = Mock()
  31. self.mock_registry = Mock()
  32. self.query_handlers: Dict[str, Callable[[dict], Awaitable[JsonDict]]] = {}
  33. def register_query_handler(
  34. query_type: str, handler: Callable[[dict], Awaitable[JsonDict]]
  35. ) -> None:
  36. self.query_handlers[query_type] = handler
  37. self.mock_registry.register_query_handler = register_query_handler
  38. hs = self.setup_test_homeserver(
  39. federation_client=self.mock_federation,
  40. federation_registry=self.mock_registry,
  41. )
  42. self.handler = hs.get_directory_handler()
  43. self.store = hs.get_datastores().main
  44. self.my_room = RoomAlias.from_string("#my-room:test")
  45. self.your_room = RoomAlias.from_string("#your-room:test")
  46. self.remote_room = RoomAlias.from_string("#another:remote")
  47. return hs
  48. def test_get_local_association(self) -> None:
  49. self.get_success(
  50. self.store.create_room_alias_association(
  51. self.my_room, "!8765qwer:test", ["test"]
  52. )
  53. )
  54. result = self.get_success(self.handler.get_association(self.my_room))
  55. self.assertEqual({"room_id": "!8765qwer:test", "servers": ["test"]}, result)
  56. def test_get_remote_association(self) -> None:
  57. self.mock_federation.make_query.return_value = make_awaitable(
  58. {"room_id": "!8765qwer:test", "servers": ["test", "remote"]}
  59. )
  60. result = self.get_success(self.handler.get_association(self.remote_room))
  61. self.assertEqual(
  62. {"room_id": "!8765qwer:test", "servers": ["test", "remote"]}, result
  63. )
  64. self.mock_federation.make_query.assert_called_with(
  65. destination="remote",
  66. query_type="directory",
  67. args={"room_alias": "#another:remote"},
  68. retry_on_dns_fail=False,
  69. ignore_backoff=True,
  70. )
  71. def test_incoming_fed_query(self) -> None:
  72. self.get_success(
  73. self.store.create_room_alias_association(
  74. self.your_room, "!8765asdf:test", ["test"]
  75. )
  76. )
  77. response = self.get_success(
  78. self.handler.on_directory_query({"room_alias": "#your-room:test"})
  79. )
  80. self.assertEqual({"room_id": "!8765asdf:test", "servers": ["test"]}, response)
  81. class TestCreateAlias(unittest.HomeserverTestCase):
  82. servlets = [
  83. synapse.rest.admin.register_servlets,
  84. login.register_servlets,
  85. room.register_servlets,
  86. directory.register_servlets,
  87. ]
  88. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  89. self.handler = hs.get_directory_handler()
  90. # Create user
  91. self.admin_user = self.register_user("admin", "pass", admin=True)
  92. self.admin_user_tok = self.login("admin", "pass")
  93. # Create a test room
  94. self.room_id = self.helper.create_room_as(
  95. self.admin_user, tok=self.admin_user_tok
  96. )
  97. self.test_alias = "#test:test"
  98. self.room_alias = RoomAlias.from_string(self.test_alias)
  99. # Create a test user.
  100. self.test_user = self.register_user("user", "pass", admin=False)
  101. self.test_user_tok = self.login("user", "pass")
  102. self.helper.join(room=self.room_id, user=self.test_user, tok=self.test_user_tok)
  103. def test_create_alias_joined_room(self) -> None:
  104. """A user can create an alias for a room they're in."""
  105. self.get_success(
  106. self.handler.create_association(
  107. create_requester(self.test_user),
  108. self.room_alias,
  109. self.room_id,
  110. )
  111. )
  112. def test_create_alias_other_room(self) -> None:
  113. """A user cannot create an alias for a room they're NOT in."""
  114. other_room_id = self.helper.create_room_as(
  115. self.admin_user, tok=self.admin_user_tok
  116. )
  117. self.get_failure(
  118. self.handler.create_association(
  119. create_requester(self.test_user),
  120. self.room_alias,
  121. other_room_id,
  122. ),
  123. synapse.api.errors.SynapseError,
  124. )
  125. def test_create_alias_admin(self) -> None:
  126. """An admin can create an alias for a room they're NOT in."""
  127. other_room_id = self.helper.create_room_as(
  128. self.test_user, tok=self.test_user_tok
  129. )
  130. self.get_success(
  131. self.handler.create_association(
  132. create_requester(self.admin_user),
  133. self.room_alias,
  134. other_room_id,
  135. )
  136. )
  137. class TestDeleteAlias(unittest.HomeserverTestCase):
  138. servlets = [
  139. synapse.rest.admin.register_servlets,
  140. login.register_servlets,
  141. room.register_servlets,
  142. directory.register_servlets,
  143. ]
  144. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  145. self.store = hs.get_datastores().main
  146. self.handler = hs.get_directory_handler()
  147. self.state_handler = hs.get_state_handler()
  148. # Create user
  149. self.admin_user = self.register_user("admin", "pass", admin=True)
  150. self.admin_user_tok = self.login("admin", "pass")
  151. # Create a test room
  152. self.room_id = self.helper.create_room_as(
  153. self.admin_user, tok=self.admin_user_tok
  154. )
  155. self.test_alias = "#test:test"
  156. self.room_alias = RoomAlias.from_string(self.test_alias)
  157. # Create a test user.
  158. self.test_user = self.register_user("user", "pass", admin=False)
  159. self.test_user_tok = self.login("user", "pass")
  160. self.helper.join(room=self.room_id, user=self.test_user, tok=self.test_user_tok)
  161. def _create_alias(self, user) -> None:
  162. # Create a new alias to this room.
  163. self.get_success(
  164. self.store.create_room_alias_association(
  165. self.room_alias, self.room_id, ["test"], user
  166. )
  167. )
  168. def test_delete_alias_not_allowed(self) -> None:
  169. """A user that doesn't meet the expected guidelines cannot delete an alias."""
  170. self._create_alias(self.admin_user)
  171. self.get_failure(
  172. self.handler.delete_association(
  173. create_requester(self.test_user), self.room_alias
  174. ),
  175. synapse.api.errors.AuthError,
  176. )
  177. def test_delete_alias_creator(self) -> None:
  178. """An alias creator can delete their own alias."""
  179. # Create an alias from a different user.
  180. self._create_alias(self.test_user)
  181. # Delete the user's alias.
  182. result = self.get_success(
  183. self.handler.delete_association(
  184. create_requester(self.test_user), self.room_alias
  185. )
  186. )
  187. self.assertEqual(self.room_id, result)
  188. # Confirm the alias is gone.
  189. self.get_failure(
  190. self.handler.get_association(self.room_alias),
  191. synapse.api.errors.SynapseError,
  192. )
  193. def test_delete_alias_admin(self) -> None:
  194. """A server admin can delete an alias created by another user."""
  195. # Create an alias from a different user.
  196. self._create_alias(self.test_user)
  197. # Delete the user's alias as the admin.
  198. result = self.get_success(
  199. self.handler.delete_association(
  200. create_requester(self.admin_user), self.room_alias
  201. )
  202. )
  203. self.assertEqual(self.room_id, result)
  204. # Confirm the alias is gone.
  205. self.get_failure(
  206. self.handler.get_association(self.room_alias),
  207. synapse.api.errors.SynapseError,
  208. )
  209. def test_delete_alias_sufficient_power(self) -> None:
  210. """A user with a sufficient power level should be able to delete an alias."""
  211. self._create_alias(self.admin_user)
  212. # Increase the user's power level.
  213. self.helper.send_state(
  214. self.room_id,
  215. "m.room.power_levels",
  216. {"users": {self.test_user: 100}},
  217. tok=self.admin_user_tok,
  218. )
  219. # They can now delete the alias.
  220. result = self.get_success(
  221. self.handler.delete_association(
  222. create_requester(self.test_user), self.room_alias
  223. )
  224. )
  225. self.assertEqual(self.room_id, result)
  226. # Confirm the alias is gone.
  227. self.get_failure(
  228. self.handler.get_association(self.room_alias),
  229. synapse.api.errors.SynapseError,
  230. )
  231. class CanonicalAliasTestCase(unittest.HomeserverTestCase):
  232. """Test modifications of the canonical alias when delete aliases."""
  233. servlets = [
  234. synapse.rest.admin.register_servlets,
  235. login.register_servlets,
  236. room.register_servlets,
  237. directory.register_servlets,
  238. ]
  239. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  240. self.store = hs.get_datastores().main
  241. self.handler = hs.get_directory_handler()
  242. self.state_handler = hs.get_state_handler()
  243. self._storage_controllers = hs.get_storage_controllers()
  244. # Create user
  245. self.admin_user = self.register_user("admin", "pass", admin=True)
  246. self.admin_user_tok = self.login("admin", "pass")
  247. # Create a test room
  248. self.room_id = self.helper.create_room_as(
  249. self.admin_user, tok=self.admin_user_tok
  250. )
  251. self.test_alias = "#test:test"
  252. self.room_alias = self._add_alias(self.test_alias)
  253. def _add_alias(self, alias: str) -> RoomAlias:
  254. """Add an alias to the test room."""
  255. room_alias = RoomAlias.from_string(alias)
  256. # Create a new alias to this room.
  257. self.get_success(
  258. self.store.create_room_alias_association(
  259. room_alias, self.room_id, ["test"], self.admin_user
  260. )
  261. )
  262. return room_alias
  263. def _set_canonical_alias(self, content) -> None:
  264. """Configure the canonical alias state on the room."""
  265. self.helper.send_state(
  266. self.room_id,
  267. "m.room.canonical_alias",
  268. content,
  269. tok=self.admin_user_tok,
  270. )
  271. def _get_canonical_alias(self):
  272. """Get the canonical alias state of the room."""
  273. return self.get_success(
  274. self._storage_controllers.state.get_current_state_event(
  275. self.room_id, EventTypes.CanonicalAlias, ""
  276. )
  277. )
  278. def test_remove_alias(self) -> None:
  279. """Removing an alias that is the canonical alias should remove it there too."""
  280. # Set this new alias as the canonical alias for this room
  281. self._set_canonical_alias(
  282. {"alias": self.test_alias, "alt_aliases": [self.test_alias]}
  283. )
  284. data = self._get_canonical_alias()
  285. self.assertEqual(data["content"]["alias"], self.test_alias)
  286. self.assertEqual(data["content"]["alt_aliases"], [self.test_alias])
  287. # Finally, delete the alias.
  288. self.get_success(
  289. self.handler.delete_association(
  290. create_requester(self.admin_user), self.room_alias
  291. )
  292. )
  293. data = self._get_canonical_alias()
  294. self.assertNotIn("alias", data["content"])
  295. self.assertNotIn("alt_aliases", data["content"])
  296. def test_remove_other_alias(self) -> None:
  297. """Removing an alias listed as in alt_aliases should remove it there too."""
  298. # Create a second alias.
  299. other_test_alias = "#test2:test"
  300. other_room_alias = self._add_alias(other_test_alias)
  301. # Set the alias as the canonical alias for this room.
  302. self._set_canonical_alias(
  303. {
  304. "alias": self.test_alias,
  305. "alt_aliases": [self.test_alias, other_test_alias],
  306. }
  307. )
  308. data = self._get_canonical_alias()
  309. self.assertEqual(data["content"]["alias"], self.test_alias)
  310. self.assertEqual(
  311. data["content"]["alt_aliases"], [self.test_alias, other_test_alias]
  312. )
  313. # Delete the second alias.
  314. self.get_success(
  315. self.handler.delete_association(
  316. create_requester(self.admin_user), other_room_alias
  317. )
  318. )
  319. data = self._get_canonical_alias()
  320. self.assertEqual(data["content"]["alias"], self.test_alias)
  321. self.assertEqual(data["content"]["alt_aliases"], [self.test_alias])
  322. class TestCreateAliasACL(unittest.HomeserverTestCase):
  323. user_id = "@test:test"
  324. servlets = [directory.register_servlets, room.register_servlets]
  325. def default_config(self) -> Dict[str, Any]:
  326. config = super().default_config()
  327. # Add custom alias creation rules to the config.
  328. config["alias_creation_rules"] = [
  329. {"user_id": "*", "alias": "#unofficial_*", "action": "allow"}
  330. ]
  331. return config
  332. def test_denied(self) -> None:
  333. room_id = self.helper.create_room_as(self.user_id)
  334. channel = self.make_request(
  335. "PUT",
  336. b"directory/room/%23test%3Atest",
  337. {"room_id": room_id},
  338. )
  339. self.assertEqual(403, channel.code, channel.result)
  340. def test_allowed(self) -> None:
  341. room_id = self.helper.create_room_as(self.user_id)
  342. channel = self.make_request(
  343. "PUT",
  344. b"directory/room/%23unofficial_test%3Atest",
  345. {"room_id": room_id},
  346. )
  347. self.assertEqual(200, channel.code, channel.result)
  348. def test_denied_during_creation(self) -> None:
  349. """A room alias that is not allowed should be rejected during creation."""
  350. # Invalid room alias.
  351. self.helper.create_room_as(
  352. self.user_id,
  353. expect_code=403,
  354. extra_content={"room_alias_name": "foo"},
  355. )
  356. def test_allowed_during_creation(self) -> None:
  357. """A valid room alias should be allowed during creation."""
  358. room_id = self.helper.create_room_as(
  359. self.user_id,
  360. extra_content={"room_alias_name": "unofficial_test"},
  361. )
  362. channel = self.make_request(
  363. "GET",
  364. b"directory/room/%23unofficial_test%3Atest",
  365. )
  366. self.assertEqual(200, channel.code, channel.result)
  367. self.assertEqual(channel.json_body["room_id"], room_id)
  368. class TestCreatePublishedRoomACL(unittest.HomeserverTestCase):
  369. servlets = [
  370. synapse.rest.admin.register_servlets_for_client_rest_resource,
  371. login.register_servlets,
  372. directory.register_servlets,
  373. room.register_servlets,
  374. ]
  375. hijack_auth = False
  376. data = {"room_alias_name": "unofficial_test"}
  377. allowed_localpart = "allowed"
  378. def default_config(self) -> Dict[str, Any]:
  379. config = super().default_config()
  380. # Add custom room list publication rules to the config.
  381. config["room_list_publication_rules"] = [
  382. {
  383. "user_id": "@" + self.allowed_localpart + "*",
  384. "alias": "#unofficial_*",
  385. "action": "allow",
  386. },
  387. {"user_id": "*", "alias": "*", "action": "deny"},
  388. ]
  389. return config
  390. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  391. self.allowed_user_id = self.register_user(self.allowed_localpart, "pass")
  392. self.allowed_access_token = self.login(self.allowed_localpart, "pass")
  393. self.denied_user_id = self.register_user("denied", "pass")
  394. self.denied_access_token = self.login("denied", "pass")
  395. def test_denied_without_publication_permission(self) -> None:
  396. """
  397. Try to create a room, register an alias for it, and publish it,
  398. as a user without permission to publish rooms.
  399. (This is used as both a standalone test & as a helper function.)
  400. """
  401. self.helper.create_room_as(
  402. self.denied_user_id,
  403. tok=self.denied_access_token,
  404. extra_content=self.data,
  405. is_public=True,
  406. expect_code=403,
  407. )
  408. def test_allowed_when_creating_private_room(self) -> None:
  409. """
  410. Try to create a room, register an alias for it, and NOT publish it,
  411. as a user without permission to publish rooms.
  412. (This is used as both a standalone test & as a helper function.)
  413. """
  414. self.helper.create_room_as(
  415. self.denied_user_id,
  416. tok=self.denied_access_token,
  417. extra_content=self.data,
  418. is_public=False,
  419. expect_code=200,
  420. )
  421. def test_allowed_with_publication_permission(self) -> None:
  422. """
  423. Try to create a room, register an alias for it, and publish it,
  424. as a user WITH permission to publish rooms.
  425. (This is used as both a standalone test & as a helper function.)
  426. """
  427. self.helper.create_room_as(
  428. self.allowed_user_id,
  429. tok=self.allowed_access_token,
  430. extra_content=self.data,
  431. is_public=True,
  432. expect_code=200,
  433. )
  434. def test_denied_publication_with_invalid_alias(self) -> None:
  435. """
  436. Try to create a room, register an alias for it, and publish it,
  437. as a user WITH permission to publish rooms.
  438. """
  439. self.helper.create_room_as(
  440. self.allowed_user_id,
  441. tok=self.allowed_access_token,
  442. extra_content={"room_alias_name": "foo"},
  443. is_public=True,
  444. expect_code=403,
  445. )
  446. def test_can_create_as_private_room_after_rejection(self) -> None:
  447. """
  448. After failing to publish a room with an alias as a user without publish permission,
  449. retry as the same user, but without publishing the room.
  450. This should pass, but used to fail because the alias was registered by the first
  451. request, even though the room creation was denied.
  452. """
  453. self.test_denied_without_publication_permission()
  454. self.test_allowed_when_creating_private_room()
  455. def test_can_create_with_permission_after_rejection(self) -> None:
  456. """
  457. After failing to publish a room with an alias as a user without publish permission,
  458. retry as someone with permission, using the same alias.
  459. This also used to fail because of the alias having been registered by the first
  460. request, leaving it unavailable for any other user's new rooms.
  461. """
  462. self.test_denied_without_publication_permission()
  463. self.test_allowed_with_publication_permission()
  464. class TestRoomListSearchDisabled(unittest.HomeserverTestCase):
  465. user_id = "@test:test"
  466. servlets = [directory.register_servlets, room.register_servlets]
  467. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  468. room_id = self.helper.create_room_as(self.user_id)
  469. channel = self.make_request(
  470. "PUT", b"directory/list/room/%s" % (room_id.encode("ascii"),), b"{}"
  471. )
  472. self.assertEqual(200, channel.code, channel.result)
  473. self.room_list_handler = hs.get_room_list_handler()
  474. self.directory_handler = hs.get_directory_handler()
  475. def test_disabling_room_list(self) -> None:
  476. self.room_list_handler.enable_room_list_search = True
  477. self.directory_handler.enable_room_list_search = True
  478. # Room list is enabled so we should get some results
  479. channel = self.make_request("GET", b"publicRooms")
  480. self.assertEqual(200, channel.code, channel.result)
  481. self.assertTrue(len(channel.json_body["chunk"]) > 0)
  482. self.room_list_handler.enable_room_list_search = False
  483. self.directory_handler.enable_room_list_search = False
  484. # Room list disabled so we should get no results
  485. channel = self.make_request("GET", b"publicRooms")
  486. self.assertEqual(200, channel.code, channel.result)
  487. self.assertTrue(len(channel.json_body["chunk"]) == 0)
  488. # Room list disabled so we shouldn't be allowed to publish rooms
  489. room_id = self.helper.create_room_as(self.user_id)
  490. channel = self.make_request(
  491. "PUT", b"directory/list/room/%s" % (room_id.encode("ascii"),), b"{}"
  492. )
  493. self.assertEqual(403, channel.code, channel.result)