test_user_directory.py 20 KB

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