test_user_directory.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2018 New Vector
  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 mock import Mock
  16. import synapse.rest.admin
  17. from synapse.api.constants import UserTypes
  18. from synapse.rest.client.v1 import login, room
  19. from synapse.rest.client.v2_alpha import user_directory
  20. from synapse.storage.roommember import ProfileInfo
  21. from tests import unittest
  22. class UserDirectoryTestCase(unittest.HomeserverTestCase):
  23. """
  24. Tests the UserDirectoryHandler.
  25. """
  26. servlets = [
  27. login.register_servlets,
  28. synapse.rest.admin.register_servlets_for_client_rest_resource,
  29. room.register_servlets,
  30. ]
  31. def make_homeserver(self, reactor, clock):
  32. config = self.default_config()
  33. config["update_user_directory"] = True
  34. return self.setup_test_homeserver(config=config)
  35. def prepare(self, reactor, clock, hs):
  36. self.store = hs.get_datastore()
  37. self.handler = hs.get_user_directory_handler()
  38. def test_handle_local_profile_change_with_support_user(self):
  39. support_user_id = "@support:test"
  40. self.get_success(
  41. self.store.register_user(
  42. user_id=support_user_id, password_hash=None, user_type=UserTypes.SUPPORT
  43. )
  44. )
  45. self.get_success(
  46. self.handler.handle_local_profile_change(support_user_id, None)
  47. )
  48. profile = self.get_success(self.store.get_user_in_directory(support_user_id))
  49. self.assertTrue(profile is None)
  50. display_name = "display_name"
  51. profile_info = ProfileInfo(avatar_url="avatar_url", display_name=display_name)
  52. regular_user_id = "@regular:test"
  53. self.get_success(
  54. self.handler.handle_local_profile_change(regular_user_id, profile_info)
  55. )
  56. profile = self.get_success(self.store.get_user_in_directory(regular_user_id))
  57. self.assertTrue(profile["display_name"] == display_name)
  58. def test_handle_user_deactivated_support_user(self):
  59. s_user_id = "@support:test"
  60. self.get_success(
  61. self.store.register_user(
  62. user_id=s_user_id, password_hash=None, user_type=UserTypes.SUPPORT
  63. )
  64. )
  65. self.store.remove_from_user_dir = Mock()
  66. self.store.remove_from_user_in_public_room = Mock()
  67. self.get_success(self.handler.handle_user_deactivated(s_user_id))
  68. self.store.remove_from_user_dir.not_called()
  69. self.store.remove_from_user_in_public_room.not_called()
  70. def test_handle_user_deactivated_regular_user(self):
  71. r_user_id = "@regular:test"
  72. self.get_success(
  73. self.store.register_user(user_id=r_user_id, password_hash=None)
  74. )
  75. self.store.remove_from_user_dir = Mock()
  76. self.get_success(self.handler.handle_user_deactivated(r_user_id))
  77. self.store.remove_from_user_dir.called_once_with(r_user_id)
  78. def test_private_room(self):
  79. """
  80. A user can be searched for only by people that are either in a public
  81. room, or that share a private chat.
  82. """
  83. u1 = self.register_user("user1", "pass")
  84. u1_token = self.login(u1, "pass")
  85. u2 = self.register_user("user2", "pass")
  86. u2_token = self.login(u2, "pass")
  87. u3 = self.register_user("user3", "pass")
  88. # We do not add users to the directory until they join a room.
  89. s = self.get_success(self.handler.search_users(u1, "user2", 10))
  90. self.assertEqual(len(s["results"]), 0)
  91. room = self.helper.create_room_as(u1, is_public=False, tok=u1_token)
  92. self.helper.invite(room, src=u1, targ=u2, tok=u1_token)
  93. self.helper.join(room, user=u2, tok=u2_token)
  94. # Check we have populated the database correctly.
  95. shares_private = self.get_users_who_share_private_rooms()
  96. public_users = self.get_users_in_public_rooms()
  97. self.assertEqual(
  98. self._compress_shared(shares_private), set([(u1, u2, room), (u2, u1, room)])
  99. )
  100. self.assertEqual(public_users, [])
  101. # We get one search result when searching for user2 by user1.
  102. s = self.get_success(self.handler.search_users(u1, "user2", 10))
  103. self.assertEqual(len(s["results"]), 1)
  104. # We get NO search results when searching for user2 by user3.
  105. s = self.get_success(self.handler.search_users(u3, "user2", 10))
  106. self.assertEqual(len(s["results"]), 0)
  107. # We get NO search results when searching for user3 by user1.
  108. s = self.get_success(self.handler.search_users(u1, "user3", 10))
  109. self.assertEqual(len(s["results"]), 0)
  110. # User 2 then leaves.
  111. self.helper.leave(room, user=u2, tok=u2_token)
  112. # Check we have removed the values.
  113. shares_private = self.get_users_who_share_private_rooms()
  114. public_users = self.get_users_in_public_rooms()
  115. self.assertEqual(self._compress_shared(shares_private), set())
  116. self.assertEqual(public_users, [])
  117. # User1 now gets no search results for any of the other users.
  118. s = self.get_success(self.handler.search_users(u1, "user2", 10))
  119. self.assertEqual(len(s["results"]), 0)
  120. s = self.get_success(self.handler.search_users(u1, "user3", 10))
  121. self.assertEqual(len(s["results"]), 0)
  122. def _compress_shared(self, shared):
  123. """
  124. Compress a list of users who share rooms dicts to a list of tuples.
  125. """
  126. r = set()
  127. for i in shared:
  128. r.add((i["user_id"], i["other_user_id"], i["room_id"]))
  129. return r
  130. def get_users_in_public_rooms(self):
  131. r = self.get_success(
  132. self.store.db.simple_select_list(
  133. "users_in_public_rooms", None, ("user_id", "room_id")
  134. )
  135. )
  136. retval = []
  137. for i in r:
  138. retval.append((i["user_id"], i["room_id"]))
  139. return retval
  140. def get_users_who_share_private_rooms(self):
  141. return self.get_success(
  142. self.store.db.simple_select_list(
  143. "users_who_share_private_rooms",
  144. None,
  145. ["user_id", "other_user_id", "room_id"],
  146. )
  147. )
  148. def _add_background_updates(self):
  149. """
  150. Add the background updates we need to run.
  151. """
  152. # Ugh, have to reset this flag
  153. self.store.db.updates._all_done = False
  154. self.get_success(
  155. self.store.db.simple_insert(
  156. "background_updates",
  157. {
  158. "update_name": "populate_user_directory_createtables",
  159. "progress_json": "{}",
  160. },
  161. )
  162. )
  163. self.get_success(
  164. self.store.db.simple_insert(
  165. "background_updates",
  166. {
  167. "update_name": "populate_user_directory_process_rooms",
  168. "progress_json": "{}",
  169. "depends_on": "populate_user_directory_createtables",
  170. },
  171. )
  172. )
  173. self.get_success(
  174. self.store.db.simple_insert(
  175. "background_updates",
  176. {
  177. "update_name": "populate_user_directory_process_users",
  178. "progress_json": "{}",
  179. "depends_on": "populate_user_directory_process_rooms",
  180. },
  181. )
  182. )
  183. self.get_success(
  184. self.store.db.simple_insert(
  185. "background_updates",
  186. {
  187. "update_name": "populate_user_directory_cleanup",
  188. "progress_json": "{}",
  189. "depends_on": "populate_user_directory_process_users",
  190. },
  191. )
  192. )
  193. def test_initial(self):
  194. """
  195. The user directory's initial handler correctly updates the search tables.
  196. """
  197. u1 = self.register_user("user1", "pass")
  198. u1_token = self.login(u1, "pass")
  199. u2 = self.register_user("user2", "pass")
  200. u2_token = self.login(u2, "pass")
  201. u3 = self.register_user("user3", "pass")
  202. u3_token = self.login(u3, "pass")
  203. room = self.helper.create_room_as(u1, is_public=True, tok=u1_token)
  204. self.helper.invite(room, src=u1, targ=u2, tok=u1_token)
  205. self.helper.join(room, user=u2, tok=u2_token)
  206. private_room = self.helper.create_room_as(u1, is_public=False, tok=u1_token)
  207. self.helper.invite(private_room, src=u1, targ=u3, tok=u1_token)
  208. self.helper.join(private_room, user=u3, tok=u3_token)
  209. self.get_success(self.store.update_user_directory_stream_pos(None))
  210. self.get_success(self.store.delete_all_from_user_dir())
  211. shares_private = self.get_users_who_share_private_rooms()
  212. public_users = self.get_users_in_public_rooms()
  213. # Nothing updated yet
  214. self.assertEqual(shares_private, [])
  215. self.assertEqual(public_users, [])
  216. # Do the initial population of the user directory via the background update
  217. self._add_background_updates()
  218. while not self.get_success(
  219. self.store.db.updates.has_completed_background_updates()
  220. ):
  221. self.get_success(
  222. self.store.db.updates.do_next_background_update(100), by=0.1
  223. )
  224. shares_private = self.get_users_who_share_private_rooms()
  225. public_users = self.get_users_in_public_rooms()
  226. # User 1 and User 2 are in the same public room
  227. self.assertEqual(set(public_users), set([(u1, room), (u2, room)]))
  228. # User 1 and User 3 share private rooms
  229. self.assertEqual(
  230. self._compress_shared(shares_private),
  231. set([(u1, u3, private_room), (u3, u1, private_room)]),
  232. )
  233. def test_initial_share_all_users(self):
  234. """
  235. Search all users = True means that a user does not have to share a
  236. private room with the searching user or be in a public room to be search
  237. visible.
  238. """
  239. self.handler.search_all_users = True
  240. self.hs.config.user_directory_search_all_users = True
  241. u1 = self.register_user("user1", "pass")
  242. self.register_user("user2", "pass")
  243. u3 = self.register_user("user3", "pass")
  244. # Wipe the user dir
  245. self.get_success(self.store.update_user_directory_stream_pos(None))
  246. self.get_success(self.store.delete_all_from_user_dir())
  247. # Do the initial population of the user directory via the background update
  248. self._add_background_updates()
  249. while not self.get_success(
  250. self.store.db.updates.has_completed_background_updates()
  251. ):
  252. self.get_success(
  253. self.store.db.updates.do_next_background_update(100), by=0.1
  254. )
  255. shares_private = self.get_users_who_share_private_rooms()
  256. public_users = self.get_users_in_public_rooms()
  257. # No users share rooms
  258. self.assertEqual(public_users, [])
  259. self.assertEqual(self._compress_shared(shares_private), set([]))
  260. # Despite not sharing a room, search_all_users means we get a search
  261. # result.
  262. s = self.get_success(self.handler.search_users(u1, u3, 10))
  263. self.assertEqual(len(s["results"]), 1)
  264. # We can find the other two users
  265. s = self.get_success(self.handler.search_users(u1, "user", 10))
  266. self.assertEqual(len(s["results"]), 2)
  267. # Registering a user and then searching for them works.
  268. u4 = self.register_user("user4", "pass")
  269. s = self.get_success(self.handler.search_users(u1, u4, 10))
  270. self.assertEqual(len(s["results"]), 1)
  271. class TestUserDirSearchDisabled(unittest.HomeserverTestCase):
  272. user_id = "@test:test"
  273. servlets = [
  274. user_directory.register_servlets,
  275. room.register_servlets,
  276. login.register_servlets,
  277. synapse.rest.admin.register_servlets_for_client_rest_resource,
  278. ]
  279. def make_homeserver(self, reactor, clock):
  280. config = self.default_config()
  281. config["update_user_directory"] = True
  282. hs = self.setup_test_homeserver(config=config)
  283. self.config = hs.config
  284. return hs
  285. def test_disabling_room_list(self):
  286. self.config.user_directory_search_enabled = True
  287. # First we create a room with another user so that user dir is non-empty
  288. # for our user
  289. self.helper.create_room_as(self.user_id)
  290. u2 = self.register_user("user2", "pass")
  291. room = self.helper.create_room_as(self.user_id)
  292. self.helper.join(room, user=u2)
  293. # Assert user directory is not empty
  294. request, channel = self.make_request(
  295. "POST", b"user_directory/search", b'{"search_term":"user2"}'
  296. )
  297. self.render(request)
  298. self.assertEquals(200, channel.code, channel.result)
  299. self.assertTrue(len(channel.json_body["results"]) > 0)
  300. # Disable user directory and check search returns nothing
  301. self.config.user_directory_search_enabled = False
  302. request, channel = self.make_request(
  303. "POST", b"user_directory/search", b'{"search_term":"user2"}'
  304. )
  305. self.render(request)
  306. self.assertEquals(200, channel.code, channel.result)
  307. self.assertTrue(len(channel.json_body["results"]) == 0)