test_user_directory.py 18 KB

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