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.
 
 
 
 
 
 

516 lines
20 KiB

  1. # Copyright 2018-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. import re
  15. from typing import Any, Dict, Set, Tuple
  16. from unittest import mock
  17. from unittest.mock import Mock, patch
  18. from twisted.test.proto_helpers import MemoryReactor
  19. from synapse.api.constants import EventTypes, Membership, UserTypes
  20. from synapse.appservice import ApplicationService
  21. from synapse.rest import admin
  22. from synapse.rest.client import login, register, room
  23. from synapse.server import HomeServer
  24. from synapse.storage import DataStore
  25. from synapse.storage.background_updates import _BackgroundUpdateHandler
  26. from synapse.storage.roommember import ProfileInfo
  27. from synapse.util import Clock
  28. from tests.server import ThreadedMemoryReactorClock
  29. from tests.test_utils.event_injection import inject_member_event
  30. from tests.unittest import HomeserverTestCase, override_config
  31. try:
  32. import icu
  33. except ImportError:
  34. icu = None # type: ignore
  35. ALICE = "@alice:a"
  36. BOB = "@bob:b"
  37. BOBBY = "@bobby:a"
  38. # The localpart isn't 'Bela' on purpose so we can test looking up display names.
  39. BELA = "@somenickname:a"
  40. class GetUserDirectoryTables:
  41. """Helper functions that we want to reuse in tests/handlers/test_user_directory.py"""
  42. def __init__(self, store: DataStore):
  43. self.store = store
  44. async def get_users_in_public_rooms(self) -> Set[Tuple[str, str]]:
  45. """Fetch the entire `users_in_public_rooms` table.
  46. Returns a list of tuples (user_id, room_id) where room_id is public and
  47. contains the user with the given id.
  48. """
  49. r = await self.store.db_pool.simple_select_list(
  50. "users_in_public_rooms", None, ("user_id", "room_id")
  51. )
  52. retval = set()
  53. for i in r:
  54. retval.add((i["user_id"], i["room_id"]))
  55. return retval
  56. async def get_users_who_share_private_rooms(self) -> Set[Tuple[str, str, str]]:
  57. """Fetch the entire `users_who_share_private_rooms` table.
  58. Returns a set of tuples (user_id, other_user_id, room_id) corresponding
  59. to the rows of `users_who_share_private_rooms`.
  60. """
  61. rows = await self.store.db_pool.simple_select_list(
  62. "users_who_share_private_rooms",
  63. None,
  64. ["user_id", "other_user_id", "room_id"],
  65. )
  66. rv = set()
  67. for row in rows:
  68. rv.add((row["user_id"], row["other_user_id"], row["room_id"]))
  69. return rv
  70. async def get_users_in_user_directory(self) -> Set[str]:
  71. """Fetch the set of users in the `user_directory` table.
  72. This is useful when checking we've correctly excluded users from the directory.
  73. """
  74. result = await self.store.db_pool.simple_select_list(
  75. "user_directory",
  76. None,
  77. ["user_id"],
  78. )
  79. return {row["user_id"] for row in result}
  80. async def get_profiles_in_user_directory(self) -> Dict[str, ProfileInfo]:
  81. """Fetch users and their profiles from the `user_directory` table.
  82. This is useful when we want to inspect display names and avatars.
  83. It's almost the entire contents of the `user_directory` table: the only
  84. thing missing is an unused room_id column.
  85. """
  86. rows = await self.store.db_pool.simple_select_list(
  87. "user_directory",
  88. None,
  89. ("user_id", "display_name", "avatar_url"),
  90. )
  91. return {
  92. row["user_id"]: ProfileInfo(
  93. display_name=row["display_name"], avatar_url=row["avatar_url"]
  94. )
  95. for row in rows
  96. }
  97. async def get_tables(
  98. self,
  99. ) -> Tuple[Set[str], Set[Tuple[str, str]], Set[Tuple[str, str, str]]]:
  100. """Multiple tests want to inspect these tables, so expose them together."""
  101. return (
  102. await self.get_users_in_user_directory(),
  103. await self.get_users_in_public_rooms(),
  104. await self.get_users_who_share_private_rooms(),
  105. )
  106. class UserDirectoryInitialPopulationTestcase(HomeserverTestCase):
  107. """Ensure that rebuilding the directory writes the correct data to the DB.
  108. See also tests/handlers/test_user_directory.py for similar checks. They
  109. test the incremental updates, rather than the big rebuild.
  110. """
  111. servlets = [
  112. login.register_servlets,
  113. admin.register_servlets,
  114. room.register_servlets,
  115. register.register_servlets,
  116. ]
  117. def make_homeserver(
  118. self, reactor: ThreadedMemoryReactorClock, clock: Clock
  119. ) -> HomeServer:
  120. self.appservice = ApplicationService(
  121. token="i_am_an_app_service",
  122. id="1234",
  123. namespaces={"users": [{"regex": r"@as_user.*", "exclusive": True}]},
  124. sender="@as:test",
  125. )
  126. mock_load_appservices = Mock(return_value=[self.appservice])
  127. with patch(
  128. "synapse.storage.databases.main.appservice.load_appservices",
  129. mock_load_appservices,
  130. ):
  131. hs = super().make_homeserver(reactor, clock)
  132. return hs
  133. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  134. self.store = hs.get_datastores().main
  135. self.user_dir_helper = GetUserDirectoryTables(self.store)
  136. def _purge_and_rebuild_user_dir(self) -> None:
  137. """Nuke the user directory tables, start the background process to
  138. repopulate them, and wait for the process to complete. This allows us
  139. to inspect the outcome of the background process alone, without any of
  140. the other incremental updates.
  141. """
  142. self.get_success(self.store.update_user_directory_stream_pos(None))
  143. self.get_success(self.store.delete_all_from_user_dir())
  144. shares_private = self.get_success(
  145. self.user_dir_helper.get_users_who_share_private_rooms()
  146. )
  147. public_users = self.get_success(
  148. self.user_dir_helper.get_users_in_public_rooms()
  149. )
  150. # Nothing updated yet
  151. self.assertEqual(shares_private, set())
  152. self.assertEqual(public_users, set())
  153. # Ugh, have to reset this flag
  154. self.store.db_pool.updates._all_done = False
  155. self.get_success(
  156. self.store.db_pool.simple_insert(
  157. "background_updates",
  158. {
  159. "update_name": "populate_user_directory_createtables",
  160. "progress_json": "{}",
  161. },
  162. )
  163. )
  164. self.get_success(
  165. self.store.db_pool.simple_insert(
  166. "background_updates",
  167. {
  168. "update_name": "populate_user_directory_process_rooms",
  169. "progress_json": "{}",
  170. "depends_on": "populate_user_directory_createtables",
  171. },
  172. )
  173. )
  174. self.get_success(
  175. self.store.db_pool.simple_insert(
  176. "background_updates",
  177. {
  178. "update_name": "populate_user_directory_process_users",
  179. "progress_json": "{}",
  180. "depends_on": "populate_user_directory_process_rooms",
  181. },
  182. )
  183. )
  184. self.get_success(
  185. self.store.db_pool.simple_insert(
  186. "background_updates",
  187. {
  188. "update_name": "populate_user_directory_cleanup",
  189. "progress_json": "{}",
  190. "depends_on": "populate_user_directory_process_users",
  191. },
  192. )
  193. )
  194. self.wait_for_background_updates()
  195. def test_initial(self) -> None:
  196. """
  197. The user directory's initial handler correctly updates the search tables.
  198. """
  199. u1 = self.register_user("user1", "pass")
  200. u1_token = self.login(u1, "pass")
  201. u2 = self.register_user("user2", "pass")
  202. u2_token = self.login(u2, "pass")
  203. u3 = self.register_user("user3", "pass")
  204. u3_token = self.login(u3, "pass")
  205. room = self.helper.create_room_as(u1, is_public=True, tok=u1_token)
  206. self.helper.invite(room, src=u1, targ=u2, tok=u1_token)
  207. self.helper.join(room, user=u2, tok=u2_token)
  208. private_room = self.helper.create_room_as(u1, is_public=False, tok=u1_token)
  209. self.helper.invite(private_room, src=u1, targ=u3, tok=u1_token)
  210. self.helper.join(private_room, user=u3, tok=u3_token)
  211. # Do the initial population of the user directory via the background update
  212. self._purge_and_rebuild_user_dir()
  213. users, in_public, in_private = self.get_success(
  214. self.user_dir_helper.get_tables()
  215. )
  216. # User 1 and User 2 are in the same public room
  217. self.assertEqual(in_public, {(u1, room), (u2, room)})
  218. # User 1 and User 3 share private rooms
  219. self.assertEqual(in_private, {(u1, u3, private_room), (u3, u1, private_room)})
  220. # All three should have entries in the directory
  221. self.assertEqual(users, {u1, u2, u3})
  222. # The next four tests (test_population_excludes_*) all set up
  223. # - A normal user included in the user dir
  224. # - A public and private room created by that user
  225. # - A user excluded from the room dir, belonging to both rooms
  226. # They match similar logic in handlers/test_user_directory.py But that tests
  227. # updating the directory; this tests rebuilding it from scratch.
  228. def _create_rooms_and_inject_memberships(
  229. self, creator: str, token: str, joiner: str
  230. ) -> Tuple[str, str]:
  231. """Create a public and private room as a normal user.
  232. Then get the `joiner` into those rooms.
  233. """
  234. public_room = self.helper.create_room_as(
  235. creator,
  236. is_public=True,
  237. # See https://github.com/matrix-org/synapse/issues/10951
  238. extra_content={"visibility": "public"},
  239. tok=token,
  240. )
  241. private_room = self.helper.create_room_as(creator, is_public=False, tok=token)
  242. # HACK: get the user into these rooms
  243. self.get_success(inject_member_event(self.hs, public_room, joiner, "join"))
  244. self.get_success(inject_member_event(self.hs, private_room, joiner, "join"))
  245. return public_room, private_room
  246. def _check_room_sharing_tables(
  247. self, normal_user: str, public_room: str, private_room: str
  248. ) -> None:
  249. # After rebuilding the directory, we should only see the normal user.
  250. users, in_public, in_private = self.get_success(
  251. self.user_dir_helper.get_tables()
  252. )
  253. self.assertEqual(users, {normal_user})
  254. self.assertEqual(in_public, {(normal_user, public_room)})
  255. self.assertEqual(in_private, set())
  256. def test_population_excludes_support_user(self) -> None:
  257. # Create a normal and support user.
  258. user = self.register_user("user", "pass")
  259. token = self.login(user, "pass")
  260. support = "@support1:test"
  261. self.get_success(
  262. self.store.register_user(
  263. user_id=support, password_hash=None, user_type=UserTypes.SUPPORT
  264. )
  265. )
  266. # Join the support user to rooms owned by the normal user.
  267. public, private = self._create_rooms_and_inject_memberships(
  268. user, token, support
  269. )
  270. # Rebuild the directory.
  271. self._purge_and_rebuild_user_dir()
  272. # Check the support user is not in the directory.
  273. self._check_room_sharing_tables(user, public, private)
  274. def test_population_excludes_deactivated_user(self) -> None:
  275. user = self.register_user("naughty", "pass")
  276. admin = self.register_user("admin", "pass", admin=True)
  277. admin_token = self.login(admin, "pass")
  278. # Deactivate the user.
  279. channel = self.make_request(
  280. "PUT",
  281. f"/_synapse/admin/v2/users/{user}",
  282. access_token=admin_token,
  283. content={"deactivated": True},
  284. )
  285. self.assertEqual(channel.code, 200)
  286. self.assertEqual(channel.json_body["deactivated"], True)
  287. # Join the deactivated user to rooms owned by the admin.
  288. # Is this something that could actually happen outside of a test?
  289. public, private = self._create_rooms_and_inject_memberships(
  290. admin, admin_token, user
  291. )
  292. # Rebuild the user dir. The deactivated user should be missing.
  293. self._purge_and_rebuild_user_dir()
  294. self._check_room_sharing_tables(admin, public, private)
  295. def test_population_excludes_appservice_user(self) -> None:
  296. # Register an AS user.
  297. user = self.register_user("user", "pass")
  298. token = self.login(user, "pass")
  299. as_user, _ = self.register_appservice_user(
  300. "as_user_potato", self.appservice.token
  301. )
  302. # Join the AS user to rooms owned by the normal user.
  303. public, private = self._create_rooms_and_inject_memberships(
  304. user, token, as_user
  305. )
  306. # Rebuild the directory.
  307. self._purge_and_rebuild_user_dir()
  308. # Check the AS user is not in the directory.
  309. self._check_room_sharing_tables(user, public, private)
  310. def test_population_excludes_appservice_sender(self) -> None:
  311. user = self.register_user("user", "pass")
  312. token = self.login(user, "pass")
  313. # Join the AS sender to rooms owned by the normal user.
  314. public, private = self._create_rooms_and_inject_memberships(
  315. user, token, self.appservice.sender
  316. )
  317. # Rebuild the directory.
  318. self._purge_and_rebuild_user_dir()
  319. # Check the AS sender is not in the directory.
  320. self._check_room_sharing_tables(user, public, private)
  321. def test_population_conceals_private_nickname(self) -> None:
  322. # Make a private room, and set a nickname within
  323. user = self.register_user("aaaa", "pass")
  324. user_token = self.login(user, "pass")
  325. private_room = self.helper.create_room_as(user, is_public=False, tok=user_token)
  326. self.helper.send_state(
  327. private_room,
  328. EventTypes.Member,
  329. state_key=user,
  330. body={"membership": Membership.JOIN, "displayname": "BBBB"},
  331. tok=user_token,
  332. )
  333. # Rebuild the user directory. Make the rescan of the `users` table a no-op
  334. # so we only see the effect of scanning the `room_memberships` table.
  335. async def mocked_process_users(*args: Any, **kwargs: Any) -> int:
  336. await self.store.db_pool.updates._end_background_update(
  337. "populate_user_directory_process_users"
  338. )
  339. return 1
  340. with mock.patch.dict(
  341. self.store.db_pool.updates._background_update_handlers,
  342. populate_user_directory_process_users=_BackgroundUpdateHandler(
  343. mocked_process_users,
  344. ),
  345. ):
  346. self._purge_and_rebuild_user_dir()
  347. # Local users are ignored by the scan over rooms
  348. users = self.get_success(self.user_dir_helper.get_profiles_in_user_directory())
  349. self.assertEqual(users, {})
  350. # Do a full rebuild including the scan over the `users` table. The local
  351. # user should appear with their profile name.
  352. self._purge_and_rebuild_user_dir()
  353. users = self.get_success(self.user_dir_helper.get_profiles_in_user_directory())
  354. self.assertEqual(
  355. users, {user: ProfileInfo(display_name="aaaa", avatar_url=None)}
  356. )
  357. class UserDirectoryStoreTestCase(HomeserverTestCase):
  358. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  359. self.store = hs.get_datastores().main
  360. # alice and bob are both in !room_id. bobby is not but shares
  361. # a homeserver with alice.
  362. self.get_success(self.store.update_profile_in_user_dir(ALICE, "alice", None))
  363. self.get_success(self.store.update_profile_in_user_dir(BOB, "bob", None))
  364. self.get_success(self.store.update_profile_in_user_dir(BOBBY, "bobby", None))
  365. self.get_success(self.store.update_profile_in_user_dir(BELA, "Bela", None))
  366. self.get_success(self.store.add_users_in_public_rooms("!room:id", (ALICE, BOB)))
  367. def test_search_user_dir(self) -> None:
  368. # normally when alice searches the directory she should just find
  369. # bob because bobby doesn't share a room with her.
  370. r = self.get_success(self.store.search_user_dir(ALICE, "bob", 10))
  371. self.assertFalse(r["limited"])
  372. self.assertEqual(1, len(r["results"]))
  373. self.assertDictEqual(
  374. r["results"][0], {"user_id": BOB, "display_name": "bob", "avatar_url": None}
  375. )
  376. @override_config({"user_directory": {"search_all_users": True}})
  377. def test_search_user_dir_all_users(self) -> None:
  378. r = self.get_success(self.store.search_user_dir(ALICE, "bob", 10))
  379. self.assertFalse(r["limited"])
  380. self.assertEqual(2, len(r["results"]))
  381. self.assertDictEqual(
  382. r["results"][0],
  383. {"user_id": BOB, "display_name": "bob", "avatar_url": None},
  384. )
  385. self.assertDictEqual(
  386. r["results"][1],
  387. {"user_id": BOBBY, "display_name": "bobby", "avatar_url": None},
  388. )
  389. @override_config({"user_directory": {"search_all_users": True}})
  390. def test_search_user_limit_correct(self) -> None:
  391. r = self.get_success(self.store.search_user_dir(ALICE, "bob", 1))
  392. self.assertTrue(r["limited"])
  393. self.assertEqual(1, len(r["results"]))
  394. @override_config({"user_directory": {"search_all_users": True}})
  395. def test_search_user_dir_stop_words(self) -> None:
  396. """Tests that a user can look up another user by searching for the start if its
  397. display name even if that name happens to be a common English word that would
  398. usually be ignored in full text searches.
  399. """
  400. r = self.get_success(self.store.search_user_dir(ALICE, "be", 10))
  401. self.assertFalse(r["limited"])
  402. self.assertEqual(1, len(r["results"]))
  403. self.assertDictEqual(
  404. r["results"][0],
  405. {"user_id": BELA, "display_name": "Bela", "avatar_url": None},
  406. )
  407. class UserDirectoryICUTestCase(HomeserverTestCase):
  408. if not icu:
  409. skip = "Requires PyICU"
  410. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  411. self.store = hs.get_datastores().main
  412. self.user_dir_helper = GetUserDirectoryTables(self.store)
  413. def test_icu_word_boundary(self) -> None:
  414. """Tests that we correctly detect word boundaries when ICU (International
  415. Components for Unicode) support is available.
  416. """
  417. display_name = "Gáo"
  418. # This word is not broken down correctly by Python's regular expressions,
  419. # likely because á is actually a lowercase a followed by a U+0301 combining
  420. # acute accent. This is specifically something that ICU support fixes.
  421. matches = re.findall(r"([\w\-]+)", display_name, re.UNICODE)
  422. self.assertEqual(len(matches), 2)
  423. self.get_success(
  424. self.store.update_profile_in_user_dir(ALICE, display_name, None)
  425. )
  426. self.get_success(self.store.add_users_in_public_rooms("!room:id", (ALICE,)))
  427. # Check that searching for this user yields the correct result.
  428. r = self.get_success(self.store.search_user_dir(BOB, display_name, 10))
  429. self.assertFalse(r["limited"])
  430. self.assertEqual(len(r["results"]), 1)
  431. self.assertDictEqual(
  432. r["results"][0],
  433. {"user_id": ALICE, "display_name": display_name, "avatar_url": None},
  434. )