1
0

test_directory.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  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. # Create user
  244. self.admin_user = self.register_user("admin", "pass", admin=True)
  245. self.admin_user_tok = self.login("admin", "pass")
  246. # Create a test room
  247. self.room_id = self.helper.create_room_as(
  248. self.admin_user, tok=self.admin_user_tok
  249. )
  250. self.test_alias = "#test:test"
  251. self.room_alias = self._add_alias(self.test_alias)
  252. def _add_alias(self, alias: str) -> RoomAlias:
  253. """Add an alias to the test room."""
  254. room_alias = RoomAlias.from_string(alias)
  255. # Create a new alias to this room.
  256. self.get_success(
  257. self.store.create_room_alias_association(
  258. room_alias, self.room_id, ["test"], self.admin_user
  259. )
  260. )
  261. return room_alias
  262. def _set_canonical_alias(self, content) -> None:
  263. """Configure the canonical alias state on the room."""
  264. self.helper.send_state(
  265. self.room_id,
  266. "m.room.canonical_alias",
  267. content,
  268. tok=self.admin_user_tok,
  269. )
  270. def _get_canonical_alias(self):
  271. """Get the canonical alias state of the room."""
  272. return self.get_success(
  273. self.state_handler.get_current_state(
  274. self.room_id, EventTypes.CanonicalAlias, ""
  275. )
  276. )
  277. def test_remove_alias(self) -> None:
  278. """Removing an alias that is the canonical alias should remove it there too."""
  279. # Set this new alias as the canonical alias for this room
  280. self._set_canonical_alias(
  281. {"alias": self.test_alias, "alt_aliases": [self.test_alias]}
  282. )
  283. data = self._get_canonical_alias()
  284. self.assertEqual(data["content"]["alias"], self.test_alias)
  285. self.assertEqual(data["content"]["alt_aliases"], [self.test_alias])
  286. # Finally, delete the alias.
  287. self.get_success(
  288. self.handler.delete_association(
  289. create_requester(self.admin_user), self.room_alias
  290. )
  291. )
  292. data = self._get_canonical_alias()
  293. self.assertNotIn("alias", data["content"])
  294. self.assertNotIn("alt_aliases", data["content"])
  295. def test_remove_other_alias(self) -> None:
  296. """Removing an alias listed as in alt_aliases should remove it there too."""
  297. # Create a second alias.
  298. other_test_alias = "#test2:test"
  299. other_room_alias = self._add_alias(other_test_alias)
  300. # Set the alias as the canonical alias for this room.
  301. self._set_canonical_alias(
  302. {
  303. "alias": self.test_alias,
  304. "alt_aliases": [self.test_alias, other_test_alias],
  305. }
  306. )
  307. data = self._get_canonical_alias()
  308. self.assertEqual(data["content"]["alias"], self.test_alias)
  309. self.assertEqual(
  310. data["content"]["alt_aliases"], [self.test_alias, other_test_alias]
  311. )
  312. # Delete the second alias.
  313. self.get_success(
  314. self.handler.delete_association(
  315. create_requester(self.admin_user), other_room_alias
  316. )
  317. )
  318. data = self._get_canonical_alias()
  319. self.assertEqual(data["content"]["alias"], self.test_alias)
  320. self.assertEqual(data["content"]["alt_aliases"], [self.test_alias])
  321. class TestCreateAliasACL(unittest.HomeserverTestCase):
  322. user_id = "@test:test"
  323. servlets = [directory.register_servlets, room.register_servlets]
  324. def default_config(self) -> Dict[str, Any]:
  325. config = super().default_config()
  326. # Add custom alias creation rules to the config.
  327. config["alias_creation_rules"] = [
  328. {"user_id": "*", "alias": "#unofficial_*", "action": "allow"}
  329. ]
  330. return config
  331. def test_denied(self) -> None:
  332. room_id = self.helper.create_room_as(self.user_id)
  333. channel = self.make_request(
  334. "PUT",
  335. b"directory/room/%23test%3Atest",
  336. {"room_id": room_id},
  337. )
  338. self.assertEqual(403, channel.code, channel.result)
  339. def test_allowed(self) -> None:
  340. room_id = self.helper.create_room_as(self.user_id)
  341. channel = self.make_request(
  342. "PUT",
  343. b"directory/room/%23unofficial_test%3Atest",
  344. {"room_id": room_id},
  345. )
  346. self.assertEqual(200, channel.code, channel.result)
  347. def test_denied_during_creation(self) -> None:
  348. """A room alias that is not allowed should be rejected during creation."""
  349. # Invalid room alias.
  350. self.helper.create_room_as(
  351. self.user_id,
  352. expect_code=403,
  353. extra_content={"room_alias_name": "foo"},
  354. )
  355. def test_allowed_during_creation(self) -> None:
  356. """A valid room alias should be allowed during creation."""
  357. room_id = self.helper.create_room_as(
  358. self.user_id,
  359. extra_content={"room_alias_name": "unofficial_test"},
  360. )
  361. channel = self.make_request(
  362. "GET",
  363. b"directory/room/%23unofficial_test%3Atest",
  364. )
  365. self.assertEqual(200, channel.code, channel.result)
  366. self.assertEqual(channel.json_body["room_id"], room_id)
  367. class TestCreatePublishedRoomACL(unittest.HomeserverTestCase):
  368. servlets = [
  369. synapse.rest.admin.register_servlets_for_client_rest_resource,
  370. login.register_servlets,
  371. directory.register_servlets,
  372. room.register_servlets,
  373. ]
  374. hijack_auth = False
  375. data = {"room_alias_name": "unofficial_test"}
  376. allowed_localpart = "allowed"
  377. def default_config(self) -> Dict[str, Any]:
  378. config = super().default_config()
  379. # Add custom room list publication rules to the config.
  380. config["room_list_publication_rules"] = [
  381. {
  382. "user_id": "@" + self.allowed_localpart + "*",
  383. "alias": "#unofficial_*",
  384. "action": "allow",
  385. },
  386. {"user_id": "*", "alias": "*", "action": "deny"},
  387. ]
  388. return config
  389. def prepare(
  390. self, reactor: MemoryReactor, clock: Clock, hs: HomeServer
  391. ) -> HomeServer:
  392. self.allowed_user_id = self.register_user(self.allowed_localpart, "pass")
  393. self.allowed_access_token = self.login(self.allowed_localpart, "pass")
  394. self.denied_user_id = self.register_user("denied", "pass")
  395. self.denied_access_token = self.login("denied", "pass")
  396. return hs
  397. def test_denied_without_publication_permission(self) -> None:
  398. """
  399. Try to create a room, register an alias for it, and publish it,
  400. as a user without permission to publish rooms.
  401. (This is used as both a standalone test & as a helper function.)
  402. """
  403. self.helper.create_room_as(
  404. self.denied_user_id,
  405. tok=self.denied_access_token,
  406. extra_content=self.data,
  407. is_public=True,
  408. expect_code=403,
  409. )
  410. def test_allowed_when_creating_private_room(self) -> None:
  411. """
  412. Try to create a room, register an alias for it, and NOT publish it,
  413. as a user without permission to publish rooms.
  414. (This is used as both a standalone test & as a helper function.)
  415. """
  416. self.helper.create_room_as(
  417. self.denied_user_id,
  418. tok=self.denied_access_token,
  419. extra_content=self.data,
  420. is_public=False,
  421. expect_code=200,
  422. )
  423. def test_allowed_with_publication_permission(self) -> None:
  424. """
  425. Try to create a room, register an alias for it, and publish it,
  426. as a user WITH permission to publish rooms.
  427. (This is used as both a standalone test & as a helper function.)
  428. """
  429. self.helper.create_room_as(
  430. self.allowed_user_id,
  431. tok=self.allowed_access_token,
  432. extra_content=self.data,
  433. is_public=True,
  434. expect_code=200,
  435. )
  436. def test_denied_publication_with_invalid_alias(self) -> None:
  437. """
  438. Try to create a room, register an alias for it, and publish it,
  439. as a user WITH permission to publish rooms.
  440. """
  441. self.helper.create_room_as(
  442. self.allowed_user_id,
  443. tok=self.allowed_access_token,
  444. extra_content={"room_alias_name": "foo"},
  445. is_public=True,
  446. expect_code=403,
  447. )
  448. def test_can_create_as_private_room_after_rejection(self) -> None:
  449. """
  450. After failing to publish a room with an alias as a user without publish permission,
  451. retry as the same user, but without publishing the room.
  452. This should pass, but used to fail because the alias was registered by the first
  453. request, even though the room creation was denied.
  454. """
  455. self.test_denied_without_publication_permission()
  456. self.test_allowed_when_creating_private_room()
  457. def test_can_create_with_permission_after_rejection(self) -> None:
  458. """
  459. After failing to publish a room with an alias as a user without publish permission,
  460. retry as someone with permission, using the same alias.
  461. This also used to fail because of the alias having been registered by the first
  462. request, leaving it unavailable for any other user's new rooms.
  463. """
  464. self.test_denied_without_publication_permission()
  465. self.test_allowed_with_publication_permission()
  466. class TestRoomListSearchDisabled(unittest.HomeserverTestCase):
  467. user_id = "@test:test"
  468. servlets = [directory.register_servlets, room.register_servlets]
  469. def prepare(
  470. self, reactor: MemoryReactor, clock: Clock, hs: HomeServer
  471. ) -> HomeServer:
  472. room_id = self.helper.create_room_as(self.user_id)
  473. channel = self.make_request(
  474. "PUT", b"directory/list/room/%s" % (room_id.encode("ascii"),), b"{}"
  475. )
  476. self.assertEqual(200, channel.code, channel.result)
  477. self.room_list_handler = hs.get_room_list_handler()
  478. self.directory_handler = hs.get_directory_handler()
  479. return hs
  480. def test_disabling_room_list(self) -> None:
  481. self.room_list_handler.enable_room_list_search = True
  482. self.directory_handler.enable_room_list_search = True
  483. # Room list is enabled so we should get some results
  484. channel = self.make_request("GET", b"publicRooms")
  485. self.assertEqual(200, channel.code, channel.result)
  486. self.assertTrue(len(channel.json_body["chunk"]) > 0)
  487. self.room_list_handler.enable_room_list_search = False
  488. self.directory_handler.enable_room_list_search = False
  489. # Room list disabled so we should get no results
  490. channel = self.make_request("GET", b"publicRooms")
  491. self.assertEqual(200, channel.code, channel.result)
  492. self.assertTrue(len(channel.json_body["chunk"]) == 0)
  493. # Room list disabled so we shouldn't be allowed to publish rooms
  494. room_id = self.helper.create_room_as(self.user_id)
  495. channel = self.make_request(
  496. "PUT", b"directory/list/room/%s" % (room_id.encode("ascii"),), b"{}"
  497. )
  498. self.assertEqual(403, channel.code, channel.result)