test_user_directory.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  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), {(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 test_spam_checker(self):
  123. """
  124. A user which fails to the spam checks will not appear in search results.
  125. """
  126. u1 = self.register_user("user1", "pass")
  127. u1_token = self.login(u1, "pass")
  128. u2 = self.register_user("user2", "pass")
  129. u2_token = self.login(u2, "pass")
  130. # We do not add users to the directory until they join a room.
  131. s = self.get_success(self.handler.search_users(u1, "user2", 10))
  132. self.assertEqual(len(s["results"]), 0)
  133. room = self.helper.create_room_as(u1, is_public=False, tok=u1_token)
  134. self.helper.invite(room, src=u1, targ=u2, tok=u1_token)
  135. self.helper.join(room, user=u2, tok=u2_token)
  136. # Check we have populated the database correctly.
  137. shares_private = self.get_users_who_share_private_rooms()
  138. public_users = self.get_users_in_public_rooms()
  139. self.assertEqual(
  140. self._compress_shared(shares_private), {(u1, u2, room), (u2, u1, room)}
  141. )
  142. self.assertEqual(public_users, [])
  143. # We get one search result when searching for user2 by user1.
  144. s = self.get_success(self.handler.search_users(u1, "user2", 10))
  145. self.assertEqual(len(s["results"]), 1)
  146. # Configure a spam checker that does not filter any users.
  147. spam_checker = self.hs.get_spam_checker()
  148. class AllowAll(object):
  149. def check_username_for_spam(self, user_profile):
  150. # Allow all users.
  151. return False
  152. spam_checker.spam_checkers = [AllowAll()]
  153. # The results do not change:
  154. # We get one search result when searching for user2 by user1.
  155. s = self.get_success(self.handler.search_users(u1, "user2", 10))
  156. self.assertEqual(len(s["results"]), 1)
  157. # Configure a spam checker that filters all users.
  158. class BlockAll(object):
  159. def check_username_for_spam(self, user_profile):
  160. # All users are spammy.
  161. return True
  162. spam_checker.spam_checkers = [BlockAll()]
  163. # User1 now gets no search results for any of the other users.
  164. s = self.get_success(self.handler.search_users(u1, "user2", 10))
  165. self.assertEqual(len(s["results"]), 0)
  166. def test_legacy_spam_checker(self):
  167. """
  168. A spam checker without the expected method should be ignored.
  169. """
  170. u1 = self.register_user("user1", "pass")
  171. u1_token = self.login(u1, "pass")
  172. u2 = self.register_user("user2", "pass")
  173. u2_token = self.login(u2, "pass")
  174. # We do not add users to the directory until they join a room.
  175. s = self.get_success(self.handler.search_users(u1, "user2", 10))
  176. self.assertEqual(len(s["results"]), 0)
  177. room = self.helper.create_room_as(u1, is_public=False, tok=u1_token)
  178. self.helper.invite(room, src=u1, targ=u2, tok=u1_token)
  179. self.helper.join(room, user=u2, tok=u2_token)
  180. # Check we have populated the database correctly.
  181. shares_private = self.get_users_who_share_private_rooms()
  182. public_users = self.get_users_in_public_rooms()
  183. self.assertEqual(
  184. self._compress_shared(shares_private), {(u1, u2, room), (u2, u1, room)}
  185. )
  186. self.assertEqual(public_users, [])
  187. # Configure a spam checker.
  188. spam_checker = self.hs.get_spam_checker()
  189. # The spam checker doesn't need any methods, so create a bare object.
  190. spam_checker.spam_checker = object()
  191. # We get one search result when searching for user2 by user1.
  192. s = self.get_success(self.handler.search_users(u1, "user2", 10))
  193. self.assertEqual(len(s["results"]), 1)
  194. def _compress_shared(self, shared):
  195. """
  196. Compress a list of users who share rooms dicts to a list of tuples.
  197. """
  198. r = set()
  199. for i in shared:
  200. r.add((i["user_id"], i["other_user_id"], i["room_id"]))
  201. return r
  202. def get_users_in_public_rooms(self):
  203. r = self.get_success(
  204. self.store.db.simple_select_list(
  205. "users_in_public_rooms", None, ("user_id", "room_id")
  206. )
  207. )
  208. retval = []
  209. for i in r:
  210. retval.append((i["user_id"], i["room_id"]))
  211. return retval
  212. def get_users_who_share_private_rooms(self):
  213. return self.get_success(
  214. self.store.db.simple_select_list(
  215. "users_who_share_private_rooms",
  216. None,
  217. ["user_id", "other_user_id", "room_id"],
  218. )
  219. )
  220. def _add_background_updates(self):
  221. """
  222. Add the background updates we need to run.
  223. """
  224. # Ugh, have to reset this flag
  225. self.store.db.updates._all_done = False
  226. self.get_success(
  227. self.store.db.simple_insert(
  228. "background_updates",
  229. {
  230. "update_name": "populate_user_directory_createtables",
  231. "progress_json": "{}",
  232. },
  233. )
  234. )
  235. self.get_success(
  236. self.store.db.simple_insert(
  237. "background_updates",
  238. {
  239. "update_name": "populate_user_directory_process_rooms",
  240. "progress_json": "{}",
  241. "depends_on": "populate_user_directory_createtables",
  242. },
  243. )
  244. )
  245. self.get_success(
  246. self.store.db.simple_insert(
  247. "background_updates",
  248. {
  249. "update_name": "populate_user_directory_process_users",
  250. "progress_json": "{}",
  251. "depends_on": "populate_user_directory_process_rooms",
  252. },
  253. )
  254. )
  255. self.get_success(
  256. self.store.db.simple_insert(
  257. "background_updates",
  258. {
  259. "update_name": "populate_user_directory_cleanup",
  260. "progress_json": "{}",
  261. "depends_on": "populate_user_directory_process_users",
  262. },
  263. )
  264. )
  265. def test_initial(self):
  266. """
  267. The user directory's initial handler correctly updates the search tables.
  268. """
  269. u1 = self.register_user("user1", "pass")
  270. u1_token = self.login(u1, "pass")
  271. u2 = self.register_user("user2", "pass")
  272. u2_token = self.login(u2, "pass")
  273. u3 = self.register_user("user3", "pass")
  274. u3_token = self.login(u3, "pass")
  275. room = self.helper.create_room_as(u1, is_public=True, tok=u1_token)
  276. self.helper.invite(room, src=u1, targ=u2, tok=u1_token)
  277. self.helper.join(room, user=u2, tok=u2_token)
  278. private_room = self.helper.create_room_as(u1, is_public=False, tok=u1_token)
  279. self.helper.invite(private_room, src=u1, targ=u3, tok=u1_token)
  280. self.helper.join(private_room, user=u3, tok=u3_token)
  281. self.get_success(self.store.update_user_directory_stream_pos(None))
  282. self.get_success(self.store.delete_all_from_user_dir())
  283. shares_private = self.get_users_who_share_private_rooms()
  284. public_users = self.get_users_in_public_rooms()
  285. # Nothing updated yet
  286. self.assertEqual(shares_private, [])
  287. self.assertEqual(public_users, [])
  288. # Do the initial population of the user directory via the background update
  289. self._add_background_updates()
  290. while not self.get_success(
  291. self.store.db.updates.has_completed_background_updates()
  292. ):
  293. self.get_success(
  294. self.store.db.updates.do_next_background_update(100), by=0.1
  295. )
  296. shares_private = self.get_users_who_share_private_rooms()
  297. public_users = self.get_users_in_public_rooms()
  298. # User 1 and User 2 are in the same public room
  299. self.assertEqual(set(public_users), {(u1, room), (u2, room)})
  300. # User 1 and User 3 share private rooms
  301. self.assertEqual(
  302. self._compress_shared(shares_private),
  303. {(u1, u3, private_room), (u3, u1, private_room)},
  304. )
  305. def test_initial_share_all_users(self):
  306. """
  307. Search all users = True means that a user does not have to share a
  308. private room with the searching user or be in a public room to be search
  309. visible.
  310. """
  311. self.handler.search_all_users = True
  312. self.hs.config.user_directory_search_all_users = True
  313. u1 = self.register_user("user1", "pass")
  314. self.register_user("user2", "pass")
  315. u3 = self.register_user("user3", "pass")
  316. # Wipe the user dir
  317. self.get_success(self.store.update_user_directory_stream_pos(None))
  318. self.get_success(self.store.delete_all_from_user_dir())
  319. # Do the initial population of the user directory via the background update
  320. self._add_background_updates()
  321. while not self.get_success(
  322. self.store.db.updates.has_completed_background_updates()
  323. ):
  324. self.get_success(
  325. self.store.db.updates.do_next_background_update(100), by=0.1
  326. )
  327. shares_private = self.get_users_who_share_private_rooms()
  328. public_users = self.get_users_in_public_rooms()
  329. # No users share rooms
  330. self.assertEqual(public_users, [])
  331. self.assertEqual(self._compress_shared(shares_private), set())
  332. # Despite not sharing a room, search_all_users means we get a search
  333. # result.
  334. s = self.get_success(self.handler.search_users(u1, u3, 10))
  335. self.assertEqual(len(s["results"]), 1)
  336. # We can find the other two users
  337. s = self.get_success(self.handler.search_users(u1, "user", 10))
  338. self.assertEqual(len(s["results"]), 2)
  339. # Registering a user and then searching for them works.
  340. u4 = self.register_user("user4", "pass")
  341. s = self.get_success(self.handler.search_users(u1, u4, 10))
  342. self.assertEqual(len(s["results"]), 1)
  343. class TestUserDirSearchDisabled(unittest.HomeserverTestCase):
  344. user_id = "@test:test"
  345. servlets = [
  346. user_directory.register_servlets,
  347. room.register_servlets,
  348. login.register_servlets,
  349. synapse.rest.admin.register_servlets_for_client_rest_resource,
  350. ]
  351. def make_homeserver(self, reactor, clock):
  352. config = self.default_config()
  353. config["update_user_directory"] = True
  354. hs = self.setup_test_homeserver(config=config)
  355. self.config = hs.config
  356. return hs
  357. def test_disabling_room_list(self):
  358. self.config.user_directory_search_enabled = True
  359. # First we create a room with another user so that user dir is non-empty
  360. # for our user
  361. self.helper.create_room_as(self.user_id)
  362. u2 = self.register_user("user2", "pass")
  363. room = self.helper.create_room_as(self.user_id)
  364. self.helper.join(room, user=u2)
  365. # Assert user directory is not empty
  366. request, channel = self.make_request(
  367. "POST", b"user_directory/search", b'{"search_term":"user2"}'
  368. )
  369. self.render(request)
  370. self.assertEquals(200, channel.code, channel.result)
  371. self.assertTrue(len(channel.json_body["results"]) > 0)
  372. # Disable user directory and check search returns nothing
  373. self.config.user_directory_search_enabled = False
  374. request, channel = self.make_request(
  375. "POST", b"user_directory/search", b'{"search_term":"user2"}'
  376. )
  377. self.render(request)
  378. self.assertEquals(200, channel.code, channel.result)
  379. self.assertTrue(len(channel.json_body["results"]) == 0)