test_user_directory.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  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. hostname="test",
  115. id="1234",
  116. namespaces={"users": [{"regex": r"@as_user.*", "exclusive": True}]},
  117. sender="@as:test",
  118. )
  119. mock_load_appservices = Mock(return_value=[self.appservice])
  120. with patch(
  121. "synapse.storage.databases.main.appservice.load_appservices",
  122. mock_load_appservices,
  123. ):
  124. hs = super().make_homeserver(reactor, clock)
  125. return hs
  126. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  127. self.store = hs.get_datastores().main
  128. self.user_dir_helper = GetUserDirectoryTables(self.store)
  129. def _purge_and_rebuild_user_dir(self) -> None:
  130. """Nuke the user directory tables, start the background process to
  131. repopulate them, and wait for the process to complete. This allows us
  132. to inspect the outcome of the background process alone, without any of
  133. the other incremental updates.
  134. """
  135. self.get_success(self.store.update_user_directory_stream_pos(None))
  136. self.get_success(self.store.delete_all_from_user_dir())
  137. shares_private = self.get_success(
  138. self.user_dir_helper.get_users_who_share_private_rooms()
  139. )
  140. public_users = self.get_success(
  141. self.user_dir_helper.get_users_in_public_rooms()
  142. )
  143. # Nothing updated yet
  144. self.assertEqual(shares_private, set())
  145. self.assertEqual(public_users, set())
  146. # Ugh, have to reset this flag
  147. self.store.db_pool.updates._all_done = False
  148. self.get_success(
  149. self.store.db_pool.simple_insert(
  150. "background_updates",
  151. {
  152. "update_name": "populate_user_directory_createtables",
  153. "progress_json": "{}",
  154. },
  155. )
  156. )
  157. self.get_success(
  158. self.store.db_pool.simple_insert(
  159. "background_updates",
  160. {
  161. "update_name": "populate_user_directory_process_rooms",
  162. "progress_json": "{}",
  163. "depends_on": "populate_user_directory_createtables",
  164. },
  165. )
  166. )
  167. self.get_success(
  168. self.store.db_pool.simple_insert(
  169. "background_updates",
  170. {
  171. "update_name": "populate_user_directory_process_users",
  172. "progress_json": "{}",
  173. "depends_on": "populate_user_directory_process_rooms",
  174. },
  175. )
  176. )
  177. self.get_success(
  178. self.store.db_pool.simple_insert(
  179. "background_updates",
  180. {
  181. "update_name": "populate_user_directory_cleanup",
  182. "progress_json": "{}",
  183. "depends_on": "populate_user_directory_process_users",
  184. },
  185. )
  186. )
  187. self.wait_for_background_updates()
  188. def test_initial(self) -> None:
  189. """
  190. The user directory's initial handler correctly updates the search tables.
  191. """
  192. u1 = self.register_user("user1", "pass")
  193. u1_token = self.login(u1, "pass")
  194. u2 = self.register_user("user2", "pass")
  195. u2_token = self.login(u2, "pass")
  196. u3 = self.register_user("user3", "pass")
  197. u3_token = self.login(u3, "pass")
  198. room = self.helper.create_room_as(u1, is_public=True, tok=u1_token)
  199. self.helper.invite(room, src=u1, targ=u2, tok=u1_token)
  200. self.helper.join(room, user=u2, tok=u2_token)
  201. private_room = self.helper.create_room_as(u1, is_public=False, tok=u1_token)
  202. self.helper.invite(private_room, src=u1, targ=u3, tok=u1_token)
  203. self.helper.join(private_room, user=u3, tok=u3_token)
  204. # Do the initial population of the user directory via the background update
  205. self._purge_and_rebuild_user_dir()
  206. users, in_public, in_private = self.get_success(
  207. self.user_dir_helper.get_tables()
  208. )
  209. # User 1 and User 2 are in the same public room
  210. self.assertEqual(in_public, {(u1, room), (u2, room)})
  211. # User 1 and User 3 share private rooms
  212. self.assertEqual(in_private, {(u1, u3, private_room), (u3, u1, private_room)})
  213. # All three should have entries in the directory
  214. self.assertEqual(users, {u1, u2, u3})
  215. # The next four tests (test_population_excludes_*) all set up
  216. # - A normal user included in the user dir
  217. # - A public and private room created by that user
  218. # - A user excluded from the room dir, belonging to both rooms
  219. # They match similar logic in handlers/test_user_directory.py But that tests
  220. # updating the directory; this tests rebuilding it from scratch.
  221. def _create_rooms_and_inject_memberships(
  222. self, creator: str, token: str, joiner: str
  223. ) -> Tuple[str, str]:
  224. """Create a public and private room as a normal user.
  225. Then get the `joiner` into those rooms.
  226. """
  227. public_room = self.helper.create_room_as(
  228. creator,
  229. is_public=True,
  230. # See https://github.com/matrix-org/synapse/issues/10951
  231. extra_content={"visibility": "public"},
  232. tok=token,
  233. )
  234. private_room = self.helper.create_room_as(creator, is_public=False, tok=token)
  235. # HACK: get the user into these rooms
  236. self.get_success(inject_member_event(self.hs, public_room, joiner, "join"))
  237. self.get_success(inject_member_event(self.hs, private_room, joiner, "join"))
  238. return public_room, private_room
  239. def _check_room_sharing_tables(
  240. self, normal_user: str, public_room: str, private_room: str
  241. ) -> None:
  242. # After rebuilding the directory, we should only see the normal user.
  243. users, in_public, in_private = self.get_success(
  244. self.user_dir_helper.get_tables()
  245. )
  246. self.assertEqual(users, {normal_user})
  247. self.assertEqual(in_public, {(normal_user, public_room)})
  248. self.assertEqual(in_private, set())
  249. def test_population_excludes_support_user(self) -> None:
  250. # Create a normal and support user.
  251. user = self.register_user("user", "pass")
  252. token = self.login(user, "pass")
  253. support = "@support1:test"
  254. self.get_success(
  255. self.store.register_user(
  256. user_id=support, password_hash=None, user_type=UserTypes.SUPPORT
  257. )
  258. )
  259. # Join the support user to rooms owned by the normal user.
  260. public, private = self._create_rooms_and_inject_memberships(
  261. user, token, support
  262. )
  263. # Rebuild the directory.
  264. self._purge_and_rebuild_user_dir()
  265. # Check the support user is not in the directory.
  266. self._check_room_sharing_tables(user, public, private)
  267. def test_population_excludes_deactivated_user(self) -> None:
  268. user = self.register_user("naughty", "pass")
  269. admin = self.register_user("admin", "pass", admin=True)
  270. admin_token = self.login(admin, "pass")
  271. # Deactivate the user.
  272. channel = self.make_request(
  273. "PUT",
  274. f"/_synapse/admin/v2/users/{user}",
  275. access_token=admin_token,
  276. content={"deactivated": True},
  277. )
  278. self.assertEqual(channel.code, 200)
  279. self.assertEqual(channel.json_body["deactivated"], True)
  280. # Join the deactivated user to rooms owned by the admin.
  281. # Is this something that could actually happen outside of a test?
  282. public, private = self._create_rooms_and_inject_memberships(
  283. admin, admin_token, user
  284. )
  285. # Rebuild the user dir. The deactivated user should be missing.
  286. self._purge_and_rebuild_user_dir()
  287. self._check_room_sharing_tables(admin, public, private)
  288. def test_population_excludes_appservice_user(self) -> None:
  289. # Register an AS user.
  290. user = self.register_user("user", "pass")
  291. token = self.login(user, "pass")
  292. as_user, _ = self.register_appservice_user(
  293. "as_user_potato", self.appservice.token
  294. )
  295. # Join the AS user to rooms owned by the normal user.
  296. public, private = self._create_rooms_and_inject_memberships(
  297. user, token, as_user
  298. )
  299. # Rebuild the directory.
  300. self._purge_and_rebuild_user_dir()
  301. # Check the AS user is not in the directory.
  302. self._check_room_sharing_tables(user, public, private)
  303. def test_population_excludes_appservice_sender(self) -> None:
  304. user = self.register_user("user", "pass")
  305. token = self.login(user, "pass")
  306. # Join the AS sender to rooms owned by the normal user.
  307. public, private = self._create_rooms_and_inject_memberships(
  308. user, token, self.appservice.sender
  309. )
  310. # Rebuild the directory.
  311. self._purge_and_rebuild_user_dir()
  312. # Check the AS sender is not in the directory.
  313. self._check_room_sharing_tables(user, public, private)
  314. def test_population_conceals_private_nickname(self) -> None:
  315. # Make a private room, and set a nickname within
  316. user = self.register_user("aaaa", "pass")
  317. user_token = self.login(user, "pass")
  318. private_room = self.helper.create_room_as(user, is_public=False, tok=user_token)
  319. self.helper.send_state(
  320. private_room,
  321. EventTypes.Member,
  322. state_key=user,
  323. body={"membership": Membership.JOIN, "displayname": "BBBB"},
  324. tok=user_token,
  325. )
  326. # Rebuild the user directory. Make the rescan of the `users` table a no-op
  327. # so we only see the effect of scanning the `room_memberships` table.
  328. async def mocked_process_users(*args: Any, **kwargs: Any) -> int:
  329. await self.store.db_pool.updates._end_background_update(
  330. "populate_user_directory_process_users"
  331. )
  332. return 1
  333. with mock.patch.dict(
  334. self.store.db_pool.updates._background_update_handlers,
  335. populate_user_directory_process_users=_BackgroundUpdateHandler(
  336. mocked_process_users,
  337. ),
  338. ):
  339. self._purge_and_rebuild_user_dir()
  340. # Local users are ignored by the scan over rooms
  341. users = self.get_success(self.user_dir_helper.get_profiles_in_user_directory())
  342. self.assertEqual(users, {})
  343. # Do a full rebuild including the scan over the `users` table. The local
  344. # user should appear with their profile name.
  345. self._purge_and_rebuild_user_dir()
  346. users = self.get_success(self.user_dir_helper.get_profiles_in_user_directory())
  347. self.assertEqual(
  348. users, {user: ProfileInfo(display_name="aaaa", avatar_url=None)}
  349. )
  350. class UserDirectoryStoreTestCase(HomeserverTestCase):
  351. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  352. self.store = hs.get_datastores().main
  353. # alice and bob are both in !room_id. bobby is not but shares
  354. # a homeserver with alice.
  355. self.get_success(self.store.update_profile_in_user_dir(ALICE, "alice", None))
  356. self.get_success(self.store.update_profile_in_user_dir(BOB, "bob", None))
  357. self.get_success(self.store.update_profile_in_user_dir(BOBBY, "bobby", None))
  358. self.get_success(self.store.update_profile_in_user_dir(BELA, "Bela", None))
  359. self.get_success(self.store.add_users_in_public_rooms("!room:id", (ALICE, BOB)))
  360. def test_search_user_dir(self) -> None:
  361. # normally when alice searches the directory she should just find
  362. # bob because bobby doesn't share a room with her.
  363. r = self.get_success(self.store.search_user_dir(ALICE, "bob", 10))
  364. self.assertFalse(r["limited"])
  365. self.assertEqual(1, len(r["results"]))
  366. self.assertDictEqual(
  367. r["results"][0], {"user_id": BOB, "display_name": "bob", "avatar_url": None}
  368. )
  369. @override_config({"user_directory": {"search_all_users": True}})
  370. def test_search_user_dir_all_users(self) -> None:
  371. r = self.get_success(self.store.search_user_dir(ALICE, "bob", 10))
  372. self.assertFalse(r["limited"])
  373. self.assertEqual(2, len(r["results"]))
  374. self.assertDictEqual(
  375. r["results"][0],
  376. {"user_id": BOB, "display_name": "bob", "avatar_url": None},
  377. )
  378. self.assertDictEqual(
  379. r["results"][1],
  380. {"user_id": BOBBY, "display_name": "bobby", "avatar_url": None},
  381. )
  382. @override_config({"user_directory": {"search_all_users": True}})
  383. def test_search_user_dir_stop_words(self) -> None:
  384. """Tests that a user can look up another user by searching for the start if its
  385. display name even if that name happens to be a common English word that would
  386. usually be ignored in full text searches.
  387. """
  388. r = self.get_success(self.store.search_user_dir(ALICE, "be", 10))
  389. self.assertFalse(r["limited"])
  390. self.assertEqual(1, len(r["results"]))
  391. self.assertDictEqual(
  392. r["results"][0],
  393. {"user_id": BELA, "display_name": "Bela", "avatar_url": None},
  394. )