test_user_directory.py 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057
  1. # Copyright 2018 New Vector
  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 Tuple
  15. from unittest.mock import Mock, patch
  16. from urllib.parse import quote
  17. from twisted.internet import defer
  18. from twisted.test.proto_helpers import MemoryReactor
  19. import synapse.rest.admin
  20. from synapse.api.constants import UserTypes
  21. from synapse.api.room_versions import RoomVersion, RoomVersions
  22. from synapse.appservice import ApplicationService
  23. from synapse.rest.client import login, register, room, user_directory
  24. from synapse.server import HomeServer
  25. from synapse.storage.roommember import ProfileInfo
  26. from synapse.types import create_requester
  27. from synapse.util import Clock
  28. from tests import unittest
  29. from tests.storage.test_user_directory import GetUserDirectoryTables
  30. from tests.test_utils.event_injection import inject_member_event
  31. from tests.unittest import override_config
  32. class UserDirectoryTestCase(unittest.HomeserverTestCase):
  33. """Tests the UserDirectoryHandler.
  34. We're broadly testing two kinds of things here.
  35. 1. Check that we correctly update the user directory in response
  36. to events (e.g. join a room, leave a room, change name, make public)
  37. 2. Check that the search logic behaves as expected.
  38. The background process that rebuilds the user directory is tested in
  39. tests/storage/test_user_directory.py.
  40. """
  41. servlets = [
  42. login.register_servlets,
  43. synapse.rest.admin.register_servlets,
  44. register.register_servlets,
  45. room.register_servlets,
  46. ]
  47. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  48. config = self.default_config()
  49. config["update_user_directory"] = True
  50. self.appservice = ApplicationService(
  51. token="i_am_an_app_service",
  52. hostname="test",
  53. id="1234",
  54. namespaces={"users": [{"regex": r"@as_user.*", "exclusive": True}]},
  55. # Note: this user does not match the regex above, so that tests
  56. # can distinguish the sender from the AS user.
  57. sender="@as_main:test",
  58. )
  59. mock_load_appservices = Mock(return_value=[self.appservice])
  60. with patch(
  61. "synapse.storage.databases.main.appservice.load_appservices",
  62. mock_load_appservices,
  63. ):
  64. hs = self.setup_test_homeserver(config=config)
  65. return hs
  66. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  67. self.store = hs.get_datastores().main
  68. self.handler = hs.get_user_directory_handler()
  69. self.event_builder_factory = self.hs.get_event_builder_factory()
  70. self.event_creation_handler = self.hs.get_event_creation_handler()
  71. self.user_dir_helper = GetUserDirectoryTables(self.store)
  72. def test_normal_user_pair(self) -> None:
  73. """Sanity check that the room-sharing tables are updated correctly."""
  74. alice = self.register_user("alice", "pass")
  75. alice_token = self.login(alice, "pass")
  76. bob = self.register_user("bob", "pass")
  77. bob_token = self.login(bob, "pass")
  78. public = self.helper.create_room_as(
  79. alice,
  80. is_public=True,
  81. extra_content={"visibility": "public"},
  82. tok=alice_token,
  83. )
  84. private = self.helper.create_room_as(alice, is_public=False, tok=alice_token)
  85. self.helper.invite(private, alice, bob, tok=alice_token)
  86. self.helper.join(public, bob, tok=bob_token)
  87. self.helper.join(private, bob, tok=bob_token)
  88. # Alice also makes a second public room but no-one else joins
  89. public2 = self.helper.create_room_as(
  90. alice,
  91. is_public=True,
  92. extra_content={"visibility": "public"},
  93. tok=alice_token,
  94. )
  95. # The user directory should reflect the room memberships above.
  96. users, in_public, in_private = self.get_success(
  97. self.user_dir_helper.get_tables()
  98. )
  99. self.assertEqual(users, {alice, bob})
  100. self.assertEqual(in_public, {(alice, public), (bob, public), (alice, public2)})
  101. self.assertEqual(
  102. in_private,
  103. {(alice, bob, private), (bob, alice, private)},
  104. )
  105. # The next four tests (test_excludes_*) all setup
  106. # - A normal user included in the user dir
  107. # - A public and private room created by that user
  108. # - A user excluded from the room dir, belonging to both rooms
  109. # They match similar logic in storage/test_user_directory. But that tests
  110. # rebuilding the directory; this tests updating it incrementally.
  111. def test_excludes_support_user(self) -> None:
  112. alice = self.register_user("alice", "pass")
  113. alice_token = self.login(alice, "pass")
  114. support = "@support1:test"
  115. self.get_success(
  116. self.store.register_user(
  117. user_id=support, password_hash=None, user_type=UserTypes.SUPPORT
  118. )
  119. )
  120. public, private = self._create_rooms_and_inject_memberships(
  121. alice, alice_token, support
  122. )
  123. self._check_only_one_user_in_directory(alice, public)
  124. def test_excludes_deactivated_user(self) -> None:
  125. admin = self.register_user("admin", "pass", admin=True)
  126. admin_token = self.login(admin, "pass")
  127. user = self.register_user("naughty", "pass")
  128. # Deactivate the user.
  129. channel = self.make_request(
  130. "PUT",
  131. f"/_synapse/admin/v2/users/{user}",
  132. access_token=admin_token,
  133. content={"deactivated": True},
  134. )
  135. self.assertEqual(channel.code, 200)
  136. self.assertEqual(channel.json_body["deactivated"], True)
  137. # Join the deactivated user to rooms owned by the admin.
  138. # Is this something that could actually happen outside of a test?
  139. public, private = self._create_rooms_and_inject_memberships(
  140. admin, admin_token, user
  141. )
  142. self._check_only_one_user_in_directory(admin, public)
  143. def test_excludes_appservices_user(self) -> None:
  144. # Register an AS user.
  145. user = self.register_user("user", "pass")
  146. token = self.login(user, "pass")
  147. as_user, _ = self.register_appservice_user(
  148. "as_user_potato", self.appservice.token
  149. )
  150. # Join the AS user to rooms owned by the normal user.
  151. public, private = self._create_rooms_and_inject_memberships(
  152. user, token, as_user
  153. )
  154. self._check_only_one_user_in_directory(user, public)
  155. def test_excludes_appservice_sender(self) -> None:
  156. user = self.register_user("user", "pass")
  157. token = self.login(user, "pass")
  158. room = self.helper.create_room_as(user, is_public=True, tok=token)
  159. self.helper.join(room, self.appservice.sender, tok=self.appservice.token)
  160. self._check_only_one_user_in_directory(user, room)
  161. def test_user_not_in_users_table(self) -> None:
  162. """Unclear how it happens, but on matrix.org we've seen join events
  163. for users who aren't in the users table. Test that we don't fall over
  164. when processing such a user.
  165. """
  166. user1 = self.register_user("user1", "pass")
  167. token1 = self.login(user1, "pass")
  168. room = self.helper.create_room_as(user1, is_public=True, tok=token1)
  169. # Inject a join event for a user who doesn't exist
  170. self.get_success(inject_member_event(self.hs, room, "@not-a-user:test", "join"))
  171. # Another new user registers and joins the room
  172. user2 = self.register_user("user2", "pass")
  173. token2 = self.login(user2, "pass")
  174. self.helper.join(room, user2, tok=token2)
  175. # The dodgy event should not have stopped us from processing user2's join.
  176. in_public = self.get_success(self.user_dir_helper.get_users_in_public_rooms())
  177. self.assertEqual(set(in_public), {(user1, room), (user2, room)})
  178. def test_excludes_users_when_making_room_public(self) -> None:
  179. # Create a regular user and a support user.
  180. alice = self.register_user("alice", "pass")
  181. alice_token = self.login(alice, "pass")
  182. support = "@support1:test"
  183. self.get_success(
  184. self.store.register_user(
  185. user_id=support, password_hash=None, user_type=UserTypes.SUPPORT
  186. )
  187. )
  188. # Make a public and private room containing Alice and the support user
  189. public, initially_private = self._create_rooms_and_inject_memberships(
  190. alice, alice_token, support
  191. )
  192. self._check_only_one_user_in_directory(alice, public)
  193. # Alice makes the private room public.
  194. self.helper.send_state(
  195. initially_private,
  196. "m.room.join_rules",
  197. {"join_rule": "public"},
  198. tok=alice_token,
  199. )
  200. users, in_public, in_private = self.get_success(
  201. self.user_dir_helper.get_tables()
  202. )
  203. self.assertEqual(users, {alice})
  204. self.assertEqual(in_public, {(alice, public), (alice, initially_private)})
  205. self.assertEqual(in_private, set())
  206. def test_switching_from_private_to_public_to_private(self) -> None:
  207. """Check we update the room sharing tables when switching a room
  208. from private to public, then back again to private."""
  209. # Alice and Bob share a private room.
  210. alice = self.register_user("alice", "pass")
  211. alice_token = self.login(alice, "pass")
  212. bob = self.register_user("bob", "pass")
  213. bob_token = self.login(bob, "pass")
  214. room = self.helper.create_room_as(alice, is_public=False, tok=alice_token)
  215. self.helper.invite(room, alice, bob, tok=alice_token)
  216. self.helper.join(room, bob, tok=bob_token)
  217. # The user directory should reflect this.
  218. def check_user_dir_for_private_room() -> None:
  219. users, in_public, in_private = self.get_success(
  220. self.user_dir_helper.get_tables()
  221. )
  222. self.assertEqual(users, {alice, bob})
  223. self.assertEqual(in_public, set())
  224. self.assertEqual(in_private, {(alice, bob, room), (bob, alice, room)})
  225. check_user_dir_for_private_room()
  226. # Alice makes the room public.
  227. self.helper.send_state(
  228. room,
  229. "m.room.join_rules",
  230. {"join_rule": "public"},
  231. tok=alice_token,
  232. )
  233. # The user directory should be updated accordingly
  234. users, in_public, in_private = self.get_success(
  235. self.user_dir_helper.get_tables()
  236. )
  237. self.assertEqual(users, {alice, bob})
  238. self.assertEqual(in_public, {(alice, room), (bob, room)})
  239. self.assertEqual(in_private, set())
  240. # Alice makes the room private.
  241. self.helper.send_state(
  242. room,
  243. "m.room.join_rules",
  244. {"join_rule": "invite"},
  245. tok=alice_token,
  246. )
  247. # The user directory should be updated accordingly
  248. check_user_dir_for_private_room()
  249. def _create_rooms_and_inject_memberships(
  250. self, creator: str, token: str, joiner: str
  251. ) -> Tuple[str, str]:
  252. """Create a public and private room as a normal user.
  253. Then get the `joiner` into those rooms.
  254. """
  255. # TODO: Duplicates the same-named method in UserDirectoryInitialPopulationTest.
  256. public_room = self.helper.create_room_as(
  257. creator,
  258. is_public=True,
  259. # See https://github.com/matrix-org/synapse/issues/10951
  260. extra_content={"visibility": "public"},
  261. tok=token,
  262. )
  263. private_room = self.helper.create_room_as(creator, is_public=False, tok=token)
  264. # HACK: get the user into these rooms
  265. self.get_success(inject_member_event(self.hs, public_room, joiner, "join"))
  266. self.get_success(inject_member_event(self.hs, private_room, joiner, "join"))
  267. return public_room, private_room
  268. def _check_only_one_user_in_directory(self, user: str, public: str) -> None:
  269. """Check that the user directory DB tables show that:
  270. - only one user is in the user directory
  271. - they belong to exactly one public room
  272. - they don't share a private room with anyone.
  273. """
  274. users, in_public, in_private = self.get_success(
  275. self.user_dir_helper.get_tables()
  276. )
  277. self.assertEqual(users, {user})
  278. self.assertEqual(in_public, {(user, public)})
  279. self.assertEqual(in_private, set())
  280. def test_handle_local_profile_change_with_support_user(self) -> None:
  281. support_user_id = "@support:test"
  282. self.get_success(
  283. self.store.register_user(
  284. user_id=support_user_id, password_hash=None, user_type=UserTypes.SUPPORT
  285. )
  286. )
  287. regular_user_id = "@regular:test"
  288. self.get_success(
  289. self.store.register_user(user_id=regular_user_id, password_hash=None)
  290. )
  291. self.get_success(
  292. self.handler.handle_local_profile_change(
  293. support_user_id, ProfileInfo("I love support me", None)
  294. )
  295. )
  296. profile = self.get_success(self.store.get_user_in_directory(support_user_id))
  297. self.assertIsNone(profile)
  298. display_name = "display_name"
  299. profile_info = ProfileInfo(avatar_url="avatar_url", display_name=display_name)
  300. self.get_success(
  301. self.handler.handle_local_profile_change(regular_user_id, profile_info)
  302. )
  303. profile = self.get_success(self.store.get_user_in_directory(regular_user_id))
  304. self.assertTrue(profile["display_name"] == display_name)
  305. def test_handle_local_profile_change_with_deactivated_user(self) -> None:
  306. # create user
  307. r_user_id = "@regular:test"
  308. self.get_success(
  309. self.store.register_user(user_id=r_user_id, password_hash=None)
  310. )
  311. # update profile
  312. display_name = "Regular User"
  313. profile_info = ProfileInfo(avatar_url="avatar_url", display_name=display_name)
  314. self.get_success(
  315. self.handler.handle_local_profile_change(r_user_id, profile_info)
  316. )
  317. # profile is in directory
  318. profile = self.get_success(self.store.get_user_in_directory(r_user_id))
  319. self.assertTrue(profile["display_name"] == display_name)
  320. # deactivate user
  321. self.get_success(self.store.set_user_deactivated_status(r_user_id, True))
  322. self.get_success(self.handler.handle_local_user_deactivated(r_user_id))
  323. # profile is not in directory
  324. profile = self.get_success(self.store.get_user_in_directory(r_user_id))
  325. self.assertIsNone(profile)
  326. # update profile after deactivation
  327. self.get_success(
  328. self.handler.handle_local_profile_change(r_user_id, profile_info)
  329. )
  330. # profile is furthermore not in directory
  331. profile = self.get_success(self.store.get_user_in_directory(r_user_id))
  332. self.assertIsNone(profile)
  333. def test_handle_local_profile_change_with_appservice_user(self) -> None:
  334. # create user
  335. as_user_id, _ = self.register_appservice_user(
  336. "as_user_alice", self.appservice.token
  337. )
  338. # profile is not in directory
  339. profile = self.get_success(self.store.get_user_in_directory(as_user_id))
  340. self.assertIsNone(profile)
  341. # update profile
  342. profile_info = ProfileInfo(avatar_url="avatar_url", display_name="4L1c3")
  343. self.get_success(
  344. self.handler.handle_local_profile_change(as_user_id, profile_info)
  345. )
  346. # profile is still not in directory
  347. profile = self.get_success(self.store.get_user_in_directory(as_user_id))
  348. self.assertIsNone(profile)
  349. def test_handle_local_profile_change_with_appservice_sender(self) -> None:
  350. # profile is not in directory
  351. profile = self.get_success(
  352. self.store.get_user_in_directory(self.appservice.sender)
  353. )
  354. self.assertIsNone(profile)
  355. # update profile
  356. profile_info = ProfileInfo(avatar_url="avatar_url", display_name="4L1c3")
  357. self.get_success(
  358. self.handler.handle_local_profile_change(
  359. self.appservice.sender, profile_info
  360. )
  361. )
  362. # profile is still not in directory
  363. profile = self.get_success(
  364. self.store.get_user_in_directory(self.appservice.sender)
  365. )
  366. self.assertIsNone(profile)
  367. def test_handle_user_deactivated_support_user(self) -> None:
  368. s_user_id = "@support:test"
  369. self.get_success(
  370. self.store.register_user(
  371. user_id=s_user_id, password_hash=None, user_type=UserTypes.SUPPORT
  372. )
  373. )
  374. mock_remove_from_user_dir = Mock(return_value=defer.succeed(None))
  375. with patch.object(
  376. self.store, "remove_from_user_dir", mock_remove_from_user_dir
  377. ):
  378. self.get_success(self.handler.handle_local_user_deactivated(s_user_id))
  379. # BUG: the correct spelling is assert_not_called, but that makes the test fail
  380. # and it's not clear that this is actually the behaviour we want.
  381. mock_remove_from_user_dir.not_called()
  382. def test_handle_user_deactivated_regular_user(self) -> None:
  383. r_user_id = "@regular:test"
  384. self.get_success(
  385. self.store.register_user(user_id=r_user_id, password_hash=None)
  386. )
  387. mock_remove_from_user_dir = Mock(return_value=defer.succeed(None))
  388. with patch.object(
  389. self.store, "remove_from_user_dir", mock_remove_from_user_dir
  390. ):
  391. self.get_success(self.handler.handle_local_user_deactivated(r_user_id))
  392. mock_remove_from_user_dir.assert_called_once_with(r_user_id)
  393. def test_reactivation_makes_regular_user_searchable(self) -> None:
  394. user = self.register_user("regular", "pass")
  395. user_token = self.login(user, "pass")
  396. admin_user = self.register_user("admin", "pass", admin=True)
  397. admin_token = self.login(admin_user, "pass")
  398. # Ensure the regular user is publicly visible and searchable.
  399. self.helper.create_room_as(user, is_public=True, tok=user_token)
  400. s = self.get_success(self.handler.search_users(admin_user, user, 10))
  401. self.assertEqual(len(s["results"]), 1)
  402. self.assertEqual(s["results"][0]["user_id"], user)
  403. # Deactivate the user and check they're not searchable.
  404. deactivate_handler = self.hs.get_deactivate_account_handler()
  405. self.get_success(
  406. deactivate_handler.deactivate_account(
  407. user, erase_data=False, requester=create_requester(admin_user)
  408. )
  409. )
  410. s = self.get_success(self.handler.search_users(admin_user, user, 10))
  411. self.assertEqual(s["results"], [])
  412. # Reactivate the user
  413. channel = self.make_request(
  414. "PUT",
  415. f"/_synapse/admin/v2/users/{quote(user)}",
  416. access_token=admin_token,
  417. content={"deactivated": False, "password": "pass"},
  418. )
  419. self.assertEqual(channel.code, 200)
  420. user_token = self.login(user, "pass")
  421. self.helper.create_room_as(user, is_public=True, tok=user_token)
  422. # Check they're searchable.
  423. s = self.get_success(self.handler.search_users(admin_user, user, 10))
  424. self.assertEqual(len(s["results"]), 1)
  425. self.assertEqual(s["results"][0]["user_id"], user)
  426. def test_process_join_after_server_leaves_room(self) -> None:
  427. alice = self.register_user("alice", "pass")
  428. alice_token = self.login(alice, "pass")
  429. bob = self.register_user("bob", "pass")
  430. bob_token = self.login(bob, "pass")
  431. # Alice makes two rooms. Bob joins one of them.
  432. room1 = self.helper.create_room_as(alice, tok=alice_token)
  433. room2 = self.helper.create_room_as(alice, tok=alice_token)
  434. self.helper.join(room1, bob, tok=bob_token)
  435. # The user sharing tables should have been updated.
  436. public1 = self.get_success(self.user_dir_helper.get_users_in_public_rooms())
  437. self.assertEqual(set(public1), {(alice, room1), (alice, room2), (bob, room1)})
  438. # Alice leaves room1. The user sharing tables should be updated.
  439. self.helper.leave(room1, alice, tok=alice_token)
  440. public2 = self.get_success(self.user_dir_helper.get_users_in_public_rooms())
  441. self.assertEqual(set(public2), {(alice, room2), (bob, room1)})
  442. # Pause the processing of new events.
  443. dir_handler = self.hs.get_user_directory_handler()
  444. dir_handler.update_user_directory = False
  445. # Bob leaves one room and joins the other.
  446. self.helper.leave(room1, bob, tok=bob_token)
  447. self.helper.join(room2, bob, tok=bob_token)
  448. # Process the leave and join in one go.
  449. dir_handler.update_user_directory = True
  450. dir_handler.notify_new_event()
  451. self.wait_for_background_updates()
  452. # The user sharing tables should have been updated.
  453. public3 = self.get_success(self.user_dir_helper.get_users_in_public_rooms())
  454. self.assertEqual(set(public3), {(alice, room2), (bob, room2)})
  455. def test_per_room_profile_doesnt_alter_directory_entry(self) -> None:
  456. alice = self.register_user("alice", "pass")
  457. alice_token = self.login(alice, "pass")
  458. bob = self.register_user("bob", "pass")
  459. # Alice should have a user directory entry created at registration.
  460. users = self.get_success(self.user_dir_helper.get_profiles_in_user_directory())
  461. self.assertEqual(
  462. users[alice], ProfileInfo(display_name="alice", avatar_url=None)
  463. )
  464. # Alice makes a room for herself.
  465. room = self.helper.create_room_as(alice, is_public=True, tok=alice_token)
  466. # Alice sets a nickname unique to that room.
  467. self.helper.send_state(
  468. room,
  469. "m.room.member",
  470. {
  471. "displayname": "Freddy Mercury",
  472. "membership": "join",
  473. },
  474. alice_token,
  475. state_key=alice,
  476. )
  477. # Alice's display name remains the same in the user directory.
  478. search_result = self.get_success(self.handler.search_users(bob, alice, 10))
  479. self.assertEqual(
  480. search_result["results"],
  481. [{"display_name": "alice", "avatar_url": None, "user_id": alice}],
  482. 0,
  483. )
  484. def test_making_room_public_doesnt_alter_directory_entry(self) -> None:
  485. """Per-room names shouldn't go to the directory when the room becomes public.
  486. This isn't about preventing a leak (the room is now public, so the nickname
  487. is too). It's about preserving the invariant that we only show a user's public
  488. profile in the user directory results.
  489. I made this a Synapse test case rather than a Complement one because
  490. I think this is (strictly speaking) an implementation choice. Synapse
  491. has chosen to only ever use the public profile when responding to a user
  492. directory search. There's no privacy leak here, because making the room
  493. public discloses the per-room name.
  494. The spec doesn't mandate anything about _how_ a user
  495. should appear in a /user_directory/search result. Hypothetical example:
  496. suppose Bob searches for Alice. When representing Alice in a search
  497. result, it's reasonable to use any of Alice's nicknames that Bob is
  498. aware of. Heck, maybe we even want to use lots of them in a combined
  499. displayname like `Alice (aka "ali", "ally", "41iC3")`.
  500. """
  501. # TODO the same should apply when Alice is a remote user.
  502. alice = self.register_user("alice", "pass")
  503. alice_token = self.login(alice, "pass")
  504. bob = self.register_user("bob", "pass")
  505. bob_token = self.login(bob, "pass")
  506. # Alice and Bob are in a private room.
  507. room = self.helper.create_room_as(alice, is_public=False, tok=alice_token)
  508. self.helper.invite(room, src=alice, targ=bob, tok=alice_token)
  509. self.helper.join(room, user=bob, tok=bob_token)
  510. # Alice has a nickname unique to that room.
  511. self.helper.send_state(
  512. room,
  513. "m.room.member",
  514. {
  515. "displayname": "Freddy Mercury",
  516. "membership": "join",
  517. },
  518. alice_token,
  519. state_key=alice,
  520. )
  521. # Check Alice isn't recorded as being in a public room.
  522. public = self.get_success(self.user_dir_helper.get_users_in_public_rooms())
  523. self.assertNotIn((alice, room), public)
  524. # One of them makes the room public.
  525. self.helper.send_state(
  526. room,
  527. "m.room.join_rules",
  528. {"join_rule": "public"},
  529. alice_token,
  530. )
  531. # Check that Alice is now recorded as being in a public room
  532. public = self.get_success(self.user_dir_helper.get_users_in_public_rooms())
  533. self.assertIn((alice, room), public)
  534. # Alice's display name remains the same in the user directory.
  535. search_result = self.get_success(self.handler.search_users(bob, alice, 10))
  536. self.assertEqual(
  537. search_result["results"],
  538. [{"display_name": "alice", "avatar_url": None, "user_id": alice}],
  539. 0,
  540. )
  541. def test_private_room(self) -> None:
  542. """
  543. A user can be searched for only by people that are either in a public
  544. room, or that share a private chat.
  545. """
  546. u1 = self.register_user("user1", "pass")
  547. u1_token = self.login(u1, "pass")
  548. u2 = self.register_user("user2", "pass")
  549. u2_token = self.login(u2, "pass")
  550. u3 = self.register_user("user3", "pass")
  551. # u1 can't see u2 until they share a private room, or u1 is in a public room.
  552. s = self.get_success(self.handler.search_users(u1, "user2", 10))
  553. self.assertEqual(len(s["results"]), 0)
  554. # Get u1 and u2 into a private room.
  555. room = self.helper.create_room_as(u1, is_public=False, tok=u1_token)
  556. self.helper.invite(room, src=u1, targ=u2, tok=u1_token)
  557. self.helper.join(room, user=u2, tok=u2_token)
  558. # Check we have populated the database correctly.
  559. users, public_users, shares_private = self.get_success(
  560. self.user_dir_helper.get_tables()
  561. )
  562. self.assertEqual(users, {u1, u2, u3})
  563. self.assertEqual(shares_private, {(u1, u2, room), (u2, u1, room)})
  564. self.assertEqual(public_users, set())
  565. # We get one search result when searching for user2 by user1.
  566. s = self.get_success(self.handler.search_users(u1, "user2", 10))
  567. self.assertEqual(len(s["results"]), 1)
  568. # We get NO search results when searching for user2 by user3.
  569. s = self.get_success(self.handler.search_users(u3, "user2", 10))
  570. self.assertEqual(len(s["results"]), 0)
  571. # We get NO search results when searching for user3 by user1.
  572. s = self.get_success(self.handler.search_users(u1, "user3", 10))
  573. self.assertEqual(len(s["results"]), 0)
  574. # User 2 then leaves.
  575. self.helper.leave(room, user=u2, tok=u2_token)
  576. # Check this is reflected in the DB.
  577. users, public_users, shares_private = self.get_success(
  578. self.user_dir_helper.get_tables()
  579. )
  580. self.assertEqual(users, {u1, u2, u3})
  581. self.assertEqual(shares_private, set())
  582. self.assertEqual(public_users, set())
  583. # User1 now gets no search results for any of the other users.
  584. s = self.get_success(self.handler.search_users(u1, "user2", 10))
  585. self.assertEqual(len(s["results"]), 0)
  586. s = self.get_success(self.handler.search_users(u1, "user3", 10))
  587. self.assertEqual(len(s["results"]), 0)
  588. def test_joining_private_room_with_excluded_user(self) -> None:
  589. """
  590. When a user excluded from the user directory, E say, joins a private
  591. room, E will not appear in the `users_who_share_private_rooms` table.
  592. When a normal user, U say, joins a private room containing E, then
  593. U will appear in the `users_who_share_private_rooms` table, but E will
  594. not.
  595. """
  596. # Setup a support and two normal users.
  597. alice = self.register_user("alice", "pass")
  598. alice_token = self.login(alice, "pass")
  599. bob = self.register_user("bob", "pass")
  600. bob_token = self.login(bob, "pass")
  601. support = "@support1:test"
  602. self.get_success(
  603. self.store.register_user(
  604. user_id=support, password_hash=None, user_type=UserTypes.SUPPORT
  605. )
  606. )
  607. # Alice makes a room. Inject the support user into the room.
  608. room = self.helper.create_room_as(alice, is_public=False, tok=alice_token)
  609. self.get_success(inject_member_event(self.hs, room, support, "join"))
  610. # Check the DB state. The support user should not be in the directory.
  611. users, in_public, in_private = self.get_success(
  612. self.user_dir_helper.get_tables()
  613. )
  614. self.assertEqual(users, {alice, bob})
  615. self.assertEqual(in_public, set())
  616. self.assertEqual(in_private, set())
  617. # Then invite Bob, who accepts.
  618. self.helper.invite(room, alice, bob, tok=alice_token)
  619. self.helper.join(room, bob, tok=bob_token)
  620. # Check the DB state. The support user should not be in the directory.
  621. users, in_public, in_private = self.get_success(
  622. self.user_dir_helper.get_tables()
  623. )
  624. self.assertEqual(users, {alice, bob})
  625. self.assertEqual(in_public, set())
  626. self.assertEqual(in_private, {(alice, bob, room), (bob, alice, room)})
  627. def test_spam_checker(self) -> None:
  628. """
  629. A user which fails the spam checks will not appear in search results.
  630. """
  631. u1 = self.register_user("user1", "pass")
  632. u1_token = self.login(u1, "pass")
  633. u2 = self.register_user("user2", "pass")
  634. u2_token = self.login(u2, "pass")
  635. # We do not add users to the directory until they join a room.
  636. s = self.get_success(self.handler.search_users(u1, "user2", 10))
  637. self.assertEqual(len(s["results"]), 0)
  638. room = self.helper.create_room_as(u1, is_public=False, tok=u1_token)
  639. self.helper.invite(room, src=u1, targ=u2, tok=u1_token)
  640. self.helper.join(room, user=u2, tok=u2_token)
  641. # Check we have populated the database correctly.
  642. shares_private = self.get_success(
  643. self.user_dir_helper.get_users_who_share_private_rooms()
  644. )
  645. public_users = self.get_success(
  646. self.user_dir_helper.get_users_in_public_rooms()
  647. )
  648. self.assertEqual(shares_private, {(u1, u2, room), (u2, u1, room)})
  649. self.assertEqual(public_users, set())
  650. # We get one search result when searching for user2 by user1.
  651. s = self.get_success(self.handler.search_users(u1, "user2", 10))
  652. self.assertEqual(len(s["results"]), 1)
  653. async def allow_all(user_profile: ProfileInfo) -> bool:
  654. # Allow all users.
  655. return False
  656. # Configure a spam checker that does not filter any users.
  657. spam_checker = self.hs.get_spam_checker()
  658. spam_checker._check_username_for_spam_callbacks = [allow_all]
  659. # The results do not change:
  660. # We get one search result when searching for user2 by user1.
  661. s = self.get_success(self.handler.search_users(u1, "user2", 10))
  662. self.assertEqual(len(s["results"]), 1)
  663. # Configure a spam checker that filters all users.
  664. async def block_all(user_profile: ProfileInfo) -> bool:
  665. # All users are spammy.
  666. return True
  667. spam_checker._check_username_for_spam_callbacks = [block_all]
  668. # User1 now gets no search results for any of the other users.
  669. s = self.get_success(self.handler.search_users(u1, "user2", 10))
  670. self.assertEqual(len(s["results"]), 0)
  671. def test_legacy_spam_checker(self) -> None:
  672. """
  673. A spam checker without the expected method should be ignored.
  674. """
  675. u1 = self.register_user("user1", "pass")
  676. u1_token = self.login(u1, "pass")
  677. u2 = self.register_user("user2", "pass")
  678. u2_token = self.login(u2, "pass")
  679. # We do not add users to the directory until they join a room.
  680. s = self.get_success(self.handler.search_users(u1, "user2", 10))
  681. self.assertEqual(len(s["results"]), 0)
  682. room = self.helper.create_room_as(u1, is_public=False, tok=u1_token)
  683. self.helper.invite(room, src=u1, targ=u2, tok=u1_token)
  684. self.helper.join(room, user=u2, tok=u2_token)
  685. # Check we have populated the database correctly.
  686. shares_private = self.get_success(
  687. self.user_dir_helper.get_users_who_share_private_rooms()
  688. )
  689. public_users = self.get_success(
  690. self.user_dir_helper.get_users_in_public_rooms()
  691. )
  692. self.assertEqual(shares_private, {(u1, u2, room), (u2, u1, room)})
  693. self.assertEqual(public_users, set())
  694. # Configure a spam checker.
  695. spam_checker = self.hs.get_spam_checker()
  696. # The spam checker doesn't need any methods, so create a bare object.
  697. spam_checker.spam_checker = object()
  698. # We get one search result when searching for user2 by user1.
  699. s = self.get_success(self.handler.search_users(u1, "user2", 10))
  700. self.assertEqual(len(s["results"]), 1)
  701. def test_initial_share_all_users(self) -> None:
  702. """
  703. Search all users = True means that a user does not have to share a
  704. private room with the searching user or be in a public room to be search
  705. visible.
  706. """
  707. self.handler.search_all_users = True
  708. self.hs.config.userdirectory.user_directory_search_all_users = True
  709. u1 = self.register_user("user1", "pass")
  710. self.register_user("user2", "pass")
  711. u3 = self.register_user("user3", "pass")
  712. shares_private = self.get_success(
  713. self.user_dir_helper.get_users_who_share_private_rooms()
  714. )
  715. public_users = self.get_success(
  716. self.user_dir_helper.get_users_in_public_rooms()
  717. )
  718. # No users share rooms
  719. self.assertEqual(public_users, set())
  720. self.assertEqual(shares_private, set())
  721. # Despite not sharing a room, search_all_users means we get a search
  722. # result.
  723. s = self.get_success(self.handler.search_users(u1, u3, 10))
  724. self.assertEqual(len(s["results"]), 1)
  725. # We can find the other two users
  726. s = self.get_success(self.handler.search_users(u1, "user", 10))
  727. self.assertEqual(len(s["results"]), 2)
  728. # Registering a user and then searching for them works.
  729. u4 = self.register_user("user4", "pass")
  730. s = self.get_success(self.handler.search_users(u1, u4, 10))
  731. self.assertEqual(len(s["results"]), 1)
  732. @override_config(
  733. {
  734. "user_directory": {
  735. "enabled": True,
  736. "search_all_users": True,
  737. "prefer_local_users": True,
  738. }
  739. }
  740. )
  741. def test_prefer_local_users(self) -> None:
  742. """Tests that local users are shown higher in search results when
  743. user_directory.prefer_local_users is True.
  744. """
  745. # Create a room and few users to test the directory with
  746. searching_user = self.register_user("searcher", "password")
  747. searching_user_tok = self.login("searcher", "password")
  748. room_id = self.helper.create_room_as(
  749. searching_user,
  750. room_version=RoomVersions.V1.identifier,
  751. tok=searching_user_tok,
  752. )
  753. # Create a few local users and join them to the room
  754. local_user_1 = self.register_user("user_xxxxx", "password")
  755. local_user_2 = self.register_user("user_bbbbb", "password")
  756. local_user_3 = self.register_user("user_zzzzz", "password")
  757. self._add_user_to_room(room_id, RoomVersions.V1, local_user_1)
  758. self._add_user_to_room(room_id, RoomVersions.V1, local_user_2)
  759. self._add_user_to_room(room_id, RoomVersions.V1, local_user_3)
  760. # Create a few "remote" users and join them to the room
  761. remote_user_1 = "@user_aaaaa:remote_server"
  762. remote_user_2 = "@user_yyyyy:remote_server"
  763. remote_user_3 = "@user_ccccc:remote_server"
  764. self._add_user_to_room(room_id, RoomVersions.V1, remote_user_1)
  765. self._add_user_to_room(room_id, RoomVersions.V1, remote_user_2)
  766. self._add_user_to_room(room_id, RoomVersions.V1, remote_user_3)
  767. local_users = [local_user_1, local_user_2, local_user_3]
  768. remote_users = [remote_user_1, remote_user_2, remote_user_3]
  769. # The local searching user searches for the term "user", which other users have
  770. # in their user id
  771. results = self.get_success(
  772. self.handler.search_users(searching_user, "user", 20)
  773. )["results"]
  774. received_user_id_ordering = [result["user_id"] for result in results]
  775. # Typically we'd expect Synapse to return users in lexicographical order,
  776. # assuming they have similar User IDs/display names, and profile information.
  777. # Check that the order of returned results using our module is as we expect,
  778. # i.e our local users show up first, despite all users having lexographically mixed
  779. # user IDs.
  780. [self.assertIn(user, local_users) for user in received_user_id_ordering[:3]]
  781. [self.assertIn(user, remote_users) for user in received_user_id_ordering[3:]]
  782. def _add_user_to_room(
  783. self,
  784. room_id: str,
  785. room_version: RoomVersion,
  786. user_id: str,
  787. ) -> None:
  788. # Add a user to the room.
  789. builder = self.event_builder_factory.for_room_version(
  790. room_version,
  791. {
  792. "type": "m.room.member",
  793. "sender": user_id,
  794. "state_key": user_id,
  795. "room_id": room_id,
  796. "content": {"membership": "join"},
  797. },
  798. )
  799. event, context = self.get_success(
  800. self.event_creation_handler.create_new_client_event(builder)
  801. )
  802. self.get_success(
  803. self.hs.get_storage().persistence.persist_event(event, context)
  804. )
  805. def test_local_user_leaving_room_remains_in_user_directory(self) -> None:
  806. """We've chosen to simplify the user directory's implementation by
  807. always including local users. Ensure this invariant is maintained when
  808. a local user
  809. - leaves a room, and
  810. - leaves the last room they're in which is visible to this server.
  811. This is user-visible if the "search_all_users" config option is on: the
  812. local user who left a room would no longer be searchable if this test fails!
  813. """
  814. alice = self.register_user("alice", "pass")
  815. alice_token = self.login(alice, "pass")
  816. bob = self.register_user("bob", "pass")
  817. bob_token = self.login(bob, "pass")
  818. # Alice makes two public rooms, which Bob joins.
  819. room1 = self.helper.create_room_as(alice, is_public=True, tok=alice_token)
  820. room2 = self.helper.create_room_as(alice, is_public=True, tok=alice_token)
  821. self.helper.join(room1, bob, tok=bob_token)
  822. self.helper.join(room2, bob, tok=bob_token)
  823. # The user directory tables are updated.
  824. users, in_public, in_private = self.get_success(
  825. self.user_dir_helper.get_tables()
  826. )
  827. self.assertEqual(users, {alice, bob})
  828. self.assertEqual(
  829. in_public, {(alice, room1), (alice, room2), (bob, room1), (bob, room2)}
  830. )
  831. self.assertEqual(in_private, set())
  832. # Alice leaves one room. She should still be in the directory.
  833. self.helper.leave(room1, alice, tok=alice_token)
  834. users, in_public, in_private = self.get_success(
  835. self.user_dir_helper.get_tables()
  836. )
  837. self.assertEqual(users, {alice, bob})
  838. self.assertEqual(in_public, {(alice, room2), (bob, room1), (bob, room2)})
  839. self.assertEqual(in_private, set())
  840. # Alice leaves the other. She should still be in the directory.
  841. self.helper.leave(room2, alice, tok=alice_token)
  842. self.wait_for_background_updates()
  843. users, in_public, in_private = self.get_success(
  844. self.user_dir_helper.get_tables()
  845. )
  846. self.assertEqual(users, {alice, bob})
  847. self.assertEqual(in_public, {(bob, room1), (bob, room2)})
  848. self.assertEqual(in_private, set())
  849. class TestUserDirSearchDisabled(unittest.HomeserverTestCase):
  850. servlets = [
  851. user_directory.register_servlets,
  852. room.register_servlets,
  853. login.register_servlets,
  854. synapse.rest.admin.register_servlets_for_client_rest_resource,
  855. ]
  856. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  857. config = self.default_config()
  858. config["update_user_directory"] = True
  859. hs = self.setup_test_homeserver(config=config)
  860. self.config = hs.config
  861. return hs
  862. def test_disabling_room_list(self) -> None:
  863. self.config.userdirectory.user_directory_search_enabled = True
  864. # Create two users and put them in the same room.
  865. u1 = self.register_user("user1", "pass")
  866. u1_token = self.login(u1, "pass")
  867. u2 = self.register_user("user2", "pass")
  868. u2_token = self.login(u2, "pass")
  869. room = self.helper.create_room_as(u1, tok=u1_token)
  870. self.helper.join(room, user=u2, tok=u2_token)
  871. # Each should see the other when searching the user directory.
  872. channel = self.make_request(
  873. "POST",
  874. b"user_directory/search",
  875. b'{"search_term":"user2"}',
  876. access_token=u1_token,
  877. )
  878. self.assertEqual(200, channel.code, channel.result)
  879. self.assertTrue(len(channel.json_body["results"]) > 0)
  880. # Disable user directory and check search returns nothing
  881. self.config.userdirectory.user_directory_search_enabled = False
  882. channel = self.make_request(
  883. "POST",
  884. b"user_directory/search",
  885. b'{"search_term":"user2"}',
  886. access_token=u1_token,
  887. )
  888. self.assertEqual(200, channel.code, channel.result)
  889. self.assertTrue(len(channel.json_body["results"]) == 0)