You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

611 lines
21 KiB

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