1
0

test_user_directory.py 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089
  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.test.proto_helpers import MemoryReactor
  18. import synapse.rest.admin
  19. from synapse.api.constants import UserTypes
  20. from synapse.api.room_versions import RoomVersion, RoomVersions
  21. from synapse.appservice import ApplicationService
  22. from synapse.rest.client import login, register, room, user_directory
  23. from synapse.server import HomeServer
  24. from synapse.storage.roommember import ProfileInfo
  25. from synapse.types import create_requester
  26. from synapse.util import Clock
  27. from tests import unittest
  28. from tests.storage.test_user_directory import GetUserDirectoryTables
  29. from tests.test_utils import make_awaitable
  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. # Re-enables updating the user directory, as that function is needed below.
  50. config["update_user_directory_from_worker"] = None
  51. self.appservice = ApplicationService(
  52. token="i_am_an_app_service",
  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. assert profile is not None
  305. self.assertTrue(profile["display_name"] == display_name)
  306. def test_handle_local_profile_change_with_deactivated_user(self) -> None:
  307. # create user
  308. r_user_id = "@regular:test"
  309. self.get_success(
  310. self.store.register_user(user_id=r_user_id, password_hash=None)
  311. )
  312. # update profile
  313. display_name = "Regular User"
  314. profile_info = ProfileInfo(avatar_url="avatar_url", display_name=display_name)
  315. self.get_success(
  316. self.handler.handle_local_profile_change(r_user_id, profile_info)
  317. )
  318. # profile is in directory
  319. profile = self.get_success(self.store.get_user_in_directory(r_user_id))
  320. assert profile is not None
  321. self.assertTrue(profile["display_name"] == display_name)
  322. # deactivate user
  323. self.get_success(self.store.set_user_deactivated_status(r_user_id, True))
  324. self.get_success(self.handler.handle_local_user_deactivated(r_user_id))
  325. # profile is not in directory
  326. profile = self.get_success(self.store.get_user_in_directory(r_user_id))
  327. self.assertIsNone(profile)
  328. # update profile after deactivation
  329. self.get_success(
  330. self.handler.handle_local_profile_change(r_user_id, profile_info)
  331. )
  332. # profile is furthermore not in directory
  333. profile = self.get_success(self.store.get_user_in_directory(r_user_id))
  334. self.assertIsNone(profile)
  335. def test_handle_local_profile_change_with_appservice_user(self) -> None:
  336. # create user
  337. as_user_id, _ = self.register_appservice_user(
  338. "as_user_alice", self.appservice.token
  339. )
  340. # profile is not in directory
  341. profile = self.get_success(self.store.get_user_in_directory(as_user_id))
  342. self.assertIsNone(profile)
  343. # update profile
  344. profile_info = ProfileInfo(avatar_url="avatar_url", display_name="4L1c3")
  345. self.get_success(
  346. self.handler.handle_local_profile_change(as_user_id, profile_info)
  347. )
  348. # profile is still not in directory
  349. profile = self.get_success(self.store.get_user_in_directory(as_user_id))
  350. self.assertIsNone(profile)
  351. def test_handle_local_profile_change_with_appservice_sender(self) -> None:
  352. # profile is not in directory
  353. profile = self.get_success(
  354. self.store.get_user_in_directory(self.appservice.sender)
  355. )
  356. self.assertIsNone(profile)
  357. # update profile
  358. profile_info = ProfileInfo(avatar_url="avatar_url", display_name="4L1c3")
  359. self.get_success(
  360. self.handler.handle_local_profile_change(
  361. self.appservice.sender, profile_info
  362. )
  363. )
  364. # profile is still not in directory
  365. profile = self.get_success(
  366. self.store.get_user_in_directory(self.appservice.sender)
  367. )
  368. self.assertIsNone(profile)
  369. def test_handle_user_deactivated_support_user(self) -> None:
  370. s_user_id = "@support:test"
  371. self.get_success(
  372. self.store.register_user(
  373. user_id=s_user_id, password_hash=None, user_type=UserTypes.SUPPORT
  374. )
  375. )
  376. mock_remove_from_user_dir = Mock(return_value=make_awaitable(None))
  377. with patch.object(
  378. self.store, "remove_from_user_dir", mock_remove_from_user_dir
  379. ):
  380. self.get_success(self.handler.handle_local_user_deactivated(s_user_id))
  381. # BUG: the correct spelling is assert_not_called, but that makes the test fail
  382. # and it's not clear that this is actually the behaviour we want.
  383. mock_remove_from_user_dir.not_called()
  384. def test_handle_user_deactivated_regular_user(self) -> None:
  385. r_user_id = "@regular:test"
  386. self.get_success(
  387. self.store.register_user(user_id=r_user_id, password_hash=None)
  388. )
  389. mock_remove_from_user_dir = Mock(return_value=make_awaitable(None))
  390. with patch.object(
  391. self.store, "remove_from_user_dir", mock_remove_from_user_dir
  392. ):
  393. self.get_success(self.handler.handle_local_user_deactivated(r_user_id))
  394. mock_remove_from_user_dir.assert_called_once_with(r_user_id)
  395. def test_reactivation_makes_regular_user_searchable(self) -> None:
  396. user = self.register_user("regular", "pass")
  397. user_token = self.login(user, "pass")
  398. admin_user = self.register_user("admin", "pass", admin=True)
  399. admin_token = self.login(admin_user, "pass")
  400. # Ensure the regular user is publicly visible and searchable.
  401. self.helper.create_room_as(user, is_public=True, tok=user_token)
  402. s = self.get_success(self.handler.search_users(admin_user, user, 10))
  403. self.assertEqual(len(s["results"]), 1)
  404. self.assertEqual(s["results"][0]["user_id"], user)
  405. # Deactivate the user and check they're not searchable.
  406. deactivate_handler = self.hs.get_deactivate_account_handler()
  407. self.get_success(
  408. deactivate_handler.deactivate_account(
  409. user, erase_data=False, requester=create_requester(admin_user)
  410. )
  411. )
  412. s = self.get_success(self.handler.search_users(admin_user, user, 10))
  413. self.assertEqual(s["results"], [])
  414. # Reactivate the user
  415. channel = self.make_request(
  416. "PUT",
  417. f"/_synapse/admin/v2/users/{quote(user)}",
  418. access_token=admin_token,
  419. content={"deactivated": False, "password": "pass"},
  420. )
  421. self.assertEqual(channel.code, 200)
  422. user_token = self.login(user, "pass")
  423. self.helper.create_room_as(user, is_public=True, tok=user_token)
  424. # Check they're searchable.
  425. s = self.get_success(self.handler.search_users(admin_user, user, 10))
  426. self.assertEqual(len(s["results"]), 1)
  427. self.assertEqual(s["results"][0]["user_id"], user)
  428. def test_process_join_after_server_leaves_room(self) -> None:
  429. alice = self.register_user("alice", "pass")
  430. alice_token = self.login(alice, "pass")
  431. bob = self.register_user("bob", "pass")
  432. bob_token = self.login(bob, "pass")
  433. # Alice makes two rooms. Bob joins one of them.
  434. room1 = self.helper.create_room_as(alice, tok=alice_token)
  435. room2 = self.helper.create_room_as(alice, tok=alice_token)
  436. self.helper.join(room1, bob, tok=bob_token)
  437. # The user sharing tables should have been updated.
  438. public1 = self.get_success(self.user_dir_helper.get_users_in_public_rooms())
  439. self.assertEqual(set(public1), {(alice, room1), (alice, room2), (bob, room1)})
  440. # Alice leaves room1. The user sharing tables should be updated.
  441. self.helper.leave(room1, alice, tok=alice_token)
  442. public2 = self.get_success(self.user_dir_helper.get_users_in_public_rooms())
  443. self.assertEqual(set(public2), {(alice, room2), (bob, room1)})
  444. # Pause the processing of new events.
  445. dir_handler = self.hs.get_user_directory_handler()
  446. dir_handler.update_user_directory = False
  447. # Bob leaves one room and joins the other.
  448. self.helper.leave(room1, bob, tok=bob_token)
  449. self.helper.join(room2, bob, tok=bob_token)
  450. # Process the leave and join in one go.
  451. dir_handler.update_user_directory = True
  452. dir_handler.notify_new_event()
  453. self.wait_for_background_updates()
  454. # The user sharing tables should have been updated.
  455. public3 = self.get_success(self.user_dir_helper.get_users_in_public_rooms())
  456. self.assertEqual(set(public3), {(alice, room2), (bob, room2)})
  457. def test_per_room_profile_doesnt_alter_directory_entry(self) -> None:
  458. alice = self.register_user("alice", "pass")
  459. alice_token = self.login(alice, "pass")
  460. bob = self.register_user("bob", "pass")
  461. # Alice should have a user directory entry created at registration.
  462. users = self.get_success(self.user_dir_helper.get_profiles_in_user_directory())
  463. self.assertEqual(
  464. users[alice], ProfileInfo(display_name="alice", avatar_url=None)
  465. )
  466. # Alice makes a room for herself.
  467. room = self.helper.create_room_as(alice, is_public=True, tok=alice_token)
  468. # Alice sets a nickname unique to that room.
  469. self.helper.send_state(
  470. room,
  471. "m.room.member",
  472. {
  473. "displayname": "Freddy Mercury",
  474. "membership": "join",
  475. },
  476. alice_token,
  477. state_key=alice,
  478. )
  479. # Alice's display name remains the same in the user directory.
  480. search_result = self.get_success(self.handler.search_users(bob, alice, 10))
  481. self.assertEqual(
  482. search_result["results"],
  483. [{"display_name": "alice", "avatar_url": None, "user_id": alice}],
  484. 0,
  485. )
  486. def test_making_room_public_doesnt_alter_directory_entry(self) -> None:
  487. """Per-room names shouldn't go to the directory when the room becomes public.
  488. This isn't about preventing a leak (the room is now public, so the nickname
  489. is too). It's about preserving the invariant that we only show a user's public
  490. profile in the user directory results.
  491. I made this a Synapse test case rather than a Complement one because
  492. I think this is (strictly speaking) an implementation choice. Synapse
  493. has chosen to only ever use the public profile when responding to a user
  494. directory search. There's no privacy leak here, because making the room
  495. public discloses the per-room name.
  496. The spec doesn't mandate anything about _how_ a user
  497. should appear in a /user_directory/search result. Hypothetical example:
  498. suppose Bob searches for Alice. When representing Alice in a search
  499. result, it's reasonable to use any of Alice's nicknames that Bob is
  500. aware of. Heck, maybe we even want to use lots of them in a combined
  501. displayname like `Alice (aka "ali", "ally", "41iC3")`.
  502. """
  503. # TODO the same should apply when Alice is a remote user.
  504. alice = self.register_user("alice", "pass")
  505. alice_token = self.login(alice, "pass")
  506. bob = self.register_user("bob", "pass")
  507. bob_token = self.login(bob, "pass")
  508. # Alice and Bob are in a private room.
  509. room = self.helper.create_room_as(alice, is_public=False, tok=alice_token)
  510. self.helper.invite(room, src=alice, targ=bob, tok=alice_token)
  511. self.helper.join(room, user=bob, tok=bob_token)
  512. # Alice has a nickname unique to that room.
  513. self.helper.send_state(
  514. room,
  515. "m.room.member",
  516. {
  517. "displayname": "Freddy Mercury",
  518. "membership": "join",
  519. },
  520. alice_token,
  521. state_key=alice,
  522. )
  523. # Check Alice isn't recorded as being in a public room.
  524. public = self.get_success(self.user_dir_helper.get_users_in_public_rooms())
  525. self.assertNotIn((alice, room), public)
  526. # One of them makes the room public.
  527. self.helper.send_state(
  528. room,
  529. "m.room.join_rules",
  530. {"join_rule": "public"},
  531. alice_token,
  532. )
  533. # Check that Alice is now recorded as being in a public room
  534. public = self.get_success(self.user_dir_helper.get_users_in_public_rooms())
  535. self.assertIn((alice, room), public)
  536. # Alice's display name remains the same in the user directory.
  537. search_result = self.get_success(self.handler.search_users(bob, alice, 10))
  538. self.assertEqual(
  539. search_result["results"],
  540. [{"display_name": "alice", "avatar_url": None, "user_id": alice}],
  541. 0,
  542. )
  543. def test_private_room(self) -> None:
  544. """
  545. A user can be searched for only by people that are either in a public
  546. room, or that share a private chat.
  547. """
  548. u1 = self.register_user("user1", "pass")
  549. u1_token = self.login(u1, "pass")
  550. u2 = self.register_user("user2", "pass")
  551. u2_token = self.login(u2, "pass")
  552. u3 = self.register_user("user3", "pass")
  553. # u1 can't see u2 until they share a private room, or u1 is in a public room.
  554. s = self.get_success(self.handler.search_users(u1, "user2", 10))
  555. self.assertEqual(len(s["results"]), 0)
  556. # Get u1 and u2 into a private room.
  557. room = self.helper.create_room_as(u1, is_public=False, tok=u1_token)
  558. self.helper.invite(room, src=u1, targ=u2, tok=u1_token)
  559. self.helper.join(room, user=u2, tok=u2_token)
  560. # Check we have populated the database correctly.
  561. users, public_users, shares_private = self.get_success(
  562. self.user_dir_helper.get_tables()
  563. )
  564. self.assertEqual(users, {u1, u2, u3})
  565. self.assertEqual(shares_private, {(u1, u2, room), (u2, u1, room)})
  566. self.assertEqual(public_users, set())
  567. # We get one search result when searching for user2 by user1.
  568. s = self.get_success(self.handler.search_users(u1, "user2", 10))
  569. self.assertEqual(len(s["results"]), 1)
  570. # We get NO search results when searching for user2 by user3.
  571. s = self.get_success(self.handler.search_users(u3, "user2", 10))
  572. self.assertEqual(len(s["results"]), 0)
  573. # We get NO search results when searching for user3 by user1.
  574. s = self.get_success(self.handler.search_users(u1, "user3", 10))
  575. self.assertEqual(len(s["results"]), 0)
  576. # User 2 then leaves.
  577. self.helper.leave(room, user=u2, tok=u2_token)
  578. # Check this is reflected in the DB.
  579. users, public_users, shares_private = self.get_success(
  580. self.user_dir_helper.get_tables()
  581. )
  582. self.assertEqual(users, {u1, u2, u3})
  583. self.assertEqual(shares_private, set())
  584. self.assertEqual(public_users, set())
  585. # User1 now gets no search results for any of the other users.
  586. s = self.get_success(self.handler.search_users(u1, "user2", 10))
  587. self.assertEqual(len(s["results"]), 0)
  588. s = self.get_success(self.handler.search_users(u1, "user3", 10))
  589. self.assertEqual(len(s["results"]), 0)
  590. def test_joining_private_room_with_excluded_user(self) -> None:
  591. """
  592. When a user excluded from the user directory, E say, joins a private
  593. room, E will not appear in the `users_who_share_private_rooms` table.
  594. When a normal user, U say, joins a private room containing E, then
  595. U will appear in the `users_who_share_private_rooms` table, but E will
  596. not.
  597. """
  598. # Setup a support and two normal users.
  599. alice = self.register_user("alice", "pass")
  600. alice_token = self.login(alice, "pass")
  601. bob = self.register_user("bob", "pass")
  602. bob_token = self.login(bob, "pass")
  603. support = "@support1:test"
  604. self.get_success(
  605. self.store.register_user(
  606. user_id=support, password_hash=None, user_type=UserTypes.SUPPORT
  607. )
  608. )
  609. # Alice makes a room. Inject the support user into the room.
  610. room = self.helper.create_room_as(alice, is_public=False, tok=alice_token)
  611. self.get_success(inject_member_event(self.hs, room, support, "join"))
  612. # Check the DB state. The support user should not be in the directory.
  613. users, in_public, in_private = self.get_success(
  614. self.user_dir_helper.get_tables()
  615. )
  616. self.assertEqual(users, {alice, bob})
  617. self.assertEqual(in_public, set())
  618. self.assertEqual(in_private, set())
  619. # Then invite Bob, who accepts.
  620. self.helper.invite(room, alice, bob, tok=alice_token)
  621. self.helper.join(room, bob, tok=bob_token)
  622. # Check the DB state. The support user should not be in the directory.
  623. users, in_public, in_private = self.get_success(
  624. self.user_dir_helper.get_tables()
  625. )
  626. self.assertEqual(users, {alice, bob})
  627. self.assertEqual(in_public, set())
  628. self.assertEqual(in_private, {(alice, bob, room), (bob, alice, room)})
  629. def test_spam_checker(self) -> None:
  630. """
  631. A user which fails the spam checks will not appear in search results.
  632. """
  633. u1 = self.register_user("user1", "pass")
  634. u1_token = self.login(u1, "pass")
  635. u2 = self.register_user("user2", "pass")
  636. u2_token = self.login(u2, "pass")
  637. # We do not add users to the directory until they join a room.
  638. s = self.get_success(self.handler.search_users(u1, "user2", 10))
  639. self.assertEqual(len(s["results"]), 0)
  640. room = self.helper.create_room_as(u1, is_public=False, tok=u1_token)
  641. self.helper.invite(room, src=u1, targ=u2, tok=u1_token)
  642. self.helper.join(room, user=u2, tok=u2_token)
  643. # Check we have populated the database correctly.
  644. shares_private = self.get_success(
  645. self.user_dir_helper.get_users_who_share_private_rooms()
  646. )
  647. public_users = self.get_success(
  648. self.user_dir_helper.get_users_in_public_rooms()
  649. )
  650. self.assertEqual(shares_private, {(u1, u2, room), (u2, u1, room)})
  651. self.assertEqual(public_users, set())
  652. # We get one search result when searching for user2 by user1.
  653. s = self.get_success(self.handler.search_users(u1, "user2", 10))
  654. self.assertEqual(len(s["results"]), 1)
  655. async def allow_all(user_profile: ProfileInfo) -> bool:
  656. # Allow all users.
  657. return False
  658. # Configure a spam checker that does not filter any users.
  659. spam_checker = self.hs.get_spam_checker()
  660. spam_checker._check_username_for_spam_callbacks = [allow_all]
  661. # The results do not change:
  662. # We get one search result when searching for user2 by user1.
  663. s = self.get_success(self.handler.search_users(u1, "user2", 10))
  664. self.assertEqual(len(s["results"]), 1)
  665. # Configure a spam checker that filters all users.
  666. async def block_all(user_profile: ProfileInfo) -> bool:
  667. # All users are spammy.
  668. return True
  669. spam_checker._check_username_for_spam_callbacks = [block_all]
  670. # User1 now gets no search results for any of the other users.
  671. s = self.get_success(self.handler.search_users(u1, "user2", 10))
  672. self.assertEqual(len(s["results"]), 0)
  673. def test_legacy_spam_checker(self) -> None:
  674. """
  675. A spam checker without the expected method should be ignored.
  676. """
  677. u1 = self.register_user("user1", "pass")
  678. u1_token = self.login(u1, "pass")
  679. u2 = self.register_user("user2", "pass")
  680. u2_token = self.login(u2, "pass")
  681. # We do not add users to the directory until they join a room.
  682. s = self.get_success(self.handler.search_users(u1, "user2", 10))
  683. self.assertEqual(len(s["results"]), 0)
  684. room = self.helper.create_room_as(u1, is_public=False, tok=u1_token)
  685. self.helper.invite(room, src=u1, targ=u2, tok=u1_token)
  686. self.helper.join(room, user=u2, tok=u2_token)
  687. # Check we have populated the database correctly.
  688. shares_private = self.get_success(
  689. self.user_dir_helper.get_users_who_share_private_rooms()
  690. )
  691. public_users = self.get_success(
  692. self.user_dir_helper.get_users_in_public_rooms()
  693. )
  694. self.assertEqual(shares_private, {(u1, u2, room), (u2, u1, room)})
  695. self.assertEqual(public_users, set())
  696. # Configure a spam checker.
  697. spam_checker = self.hs.get_spam_checker()
  698. # The spam checker doesn't need any methods, so create a bare object.
  699. spam_checker.spam_checker = object()
  700. # We get one search result when searching for user2 by user1.
  701. s = self.get_success(self.handler.search_users(u1, "user2", 10))
  702. self.assertEqual(len(s["results"]), 1)
  703. def test_initial_share_all_users(self) -> None:
  704. """
  705. Search all users = True means that a user does not have to share a
  706. private room with the searching user or be in a public room to be search
  707. visible.
  708. """
  709. self.handler.search_all_users = True
  710. self.hs.config.userdirectory.user_directory_search_all_users = True
  711. u1 = self.register_user("user1", "pass")
  712. self.register_user("user2", "pass")
  713. u3 = self.register_user("user3", "pass")
  714. shares_private = self.get_success(
  715. self.user_dir_helper.get_users_who_share_private_rooms()
  716. )
  717. public_users = self.get_success(
  718. self.user_dir_helper.get_users_in_public_rooms()
  719. )
  720. # No users share rooms
  721. self.assertEqual(public_users, set())
  722. self.assertEqual(shares_private, set())
  723. # Despite not sharing a room, search_all_users means we get a search
  724. # result.
  725. s = self.get_success(self.handler.search_users(u1, u3, 10))
  726. self.assertEqual(len(s["results"]), 1)
  727. # We can find the other two users
  728. s = self.get_success(self.handler.search_users(u1, "user", 10))
  729. self.assertEqual(len(s["results"]), 2)
  730. # Registering a user and then searching for them works.
  731. u4 = self.register_user("user4", "pass")
  732. s = self.get_success(self.handler.search_users(u1, u4, 10))
  733. self.assertEqual(len(s["results"]), 1)
  734. @override_config(
  735. {
  736. "user_directory": {
  737. "enabled": True,
  738. "search_all_users": True,
  739. "prefer_local_users": True,
  740. }
  741. }
  742. )
  743. def test_prefer_local_users(self) -> None:
  744. """Tests that local users are shown higher in search results when
  745. user_directory.prefer_local_users is True.
  746. """
  747. # Create a room and few users to test the directory with
  748. searching_user = self.register_user("searcher", "password")
  749. searching_user_tok = self.login("searcher", "password")
  750. room_id = self.helper.create_room_as(
  751. searching_user,
  752. room_version=RoomVersions.V1.identifier,
  753. tok=searching_user_tok,
  754. )
  755. # Create a few local users and join them to the room
  756. local_user_1 = self.register_user("user_xxxxx", "password")
  757. local_user_2 = self.register_user("user_bbbbb", "password")
  758. local_user_3 = self.register_user("user_zzzzz", "password")
  759. self._add_user_to_room(room_id, RoomVersions.V1, local_user_1)
  760. self._add_user_to_room(room_id, RoomVersions.V1, local_user_2)
  761. self._add_user_to_room(room_id, RoomVersions.V1, local_user_3)
  762. # Create a few "remote" users and join them to the room
  763. remote_user_1 = "@user_aaaaa:remote_server"
  764. remote_user_2 = "@user_yyyyy:remote_server"
  765. remote_user_3 = "@user_ccccc:remote_server"
  766. self._add_user_to_room(room_id, RoomVersions.V1, remote_user_1)
  767. self._add_user_to_room(room_id, RoomVersions.V1, remote_user_2)
  768. self._add_user_to_room(room_id, RoomVersions.V1, remote_user_3)
  769. local_users = [local_user_1, local_user_2, local_user_3]
  770. remote_users = [remote_user_1, remote_user_2, remote_user_3]
  771. # The local searching user searches for the term "user", which other users have
  772. # in their user id
  773. results = self.get_success(
  774. self.handler.search_users(searching_user, "user", 20)
  775. )["results"]
  776. received_user_id_ordering = [result["user_id"] for result in results]
  777. # Typically we'd expect Synapse to return users in lexicographical order,
  778. # assuming they have similar User IDs/display names, and profile information.
  779. # Check that the order of returned results using our module is as we expect,
  780. # i.e our local users show up first, despite all users having lexographically mixed
  781. # user IDs.
  782. [self.assertIn(user, local_users) for user in received_user_id_ordering[:3]]
  783. [self.assertIn(user, remote_users) for user in received_user_id_ordering[3:]]
  784. def _add_user_to_room(
  785. self,
  786. room_id: str,
  787. room_version: RoomVersion,
  788. user_id: str,
  789. ) -> None:
  790. # Add a user to the room.
  791. builder = self.event_builder_factory.for_room_version(
  792. room_version,
  793. {
  794. "type": "m.room.member",
  795. "sender": user_id,
  796. "state_key": user_id,
  797. "room_id": room_id,
  798. "content": {"membership": "join"},
  799. },
  800. )
  801. event, context = self.get_success(
  802. self.event_creation_handler.create_new_client_event(builder)
  803. )
  804. self.get_success(
  805. self.hs.get_storage_controllers().persistence.persist_event(event, context)
  806. )
  807. def test_local_user_leaving_room_remains_in_user_directory(self) -> None:
  808. """We've chosen to simplify the user directory's implementation by
  809. always including local users. Ensure this invariant is maintained when
  810. a local user
  811. - leaves a room, and
  812. - leaves the last room they're in which is visible to this server.
  813. This is user-visible if the "search_all_users" config option is on: the
  814. local user who left a room would no longer be searchable if this test fails!
  815. """
  816. alice = self.register_user("alice", "pass")
  817. alice_token = self.login(alice, "pass")
  818. bob = self.register_user("bob", "pass")
  819. bob_token = self.login(bob, "pass")
  820. # Alice makes two public rooms, which Bob joins.
  821. room1 = self.helper.create_room_as(alice, is_public=True, tok=alice_token)
  822. room2 = self.helper.create_room_as(alice, is_public=True, tok=alice_token)
  823. self.helper.join(room1, bob, tok=bob_token)
  824. self.helper.join(room2, bob, tok=bob_token)
  825. # The user directory tables are updated.
  826. users, in_public, in_private = self.get_success(
  827. self.user_dir_helper.get_tables()
  828. )
  829. self.assertEqual(users, {alice, bob})
  830. self.assertEqual(
  831. in_public, {(alice, room1), (alice, room2), (bob, room1), (bob, room2)}
  832. )
  833. self.assertEqual(in_private, set())
  834. # Alice leaves one room. She should still be in the directory.
  835. self.helper.leave(room1, alice, tok=alice_token)
  836. users, in_public, in_private = self.get_success(
  837. self.user_dir_helper.get_tables()
  838. )
  839. self.assertEqual(users, {alice, bob})
  840. self.assertEqual(in_public, {(alice, room2), (bob, room1), (bob, room2)})
  841. self.assertEqual(in_private, set())
  842. # Alice leaves the other. She should still be in the directory.
  843. self.helper.leave(room2, alice, tok=alice_token)
  844. self.wait_for_background_updates()
  845. users, in_public, in_private = self.get_success(
  846. self.user_dir_helper.get_tables()
  847. )
  848. self.assertEqual(users, {alice, bob})
  849. self.assertEqual(in_public, {(bob, room1), (bob, room2)})
  850. self.assertEqual(in_private, set())
  851. def test_ignore_display_names_with_null_codepoints(self) -> None:
  852. MXC_DUMMY = "mxc://dummy"
  853. # Alice creates a public room.
  854. alice = self.register_user("alice", "pass")
  855. # Alice has a user directory entry to start with.
  856. self.assertIn(
  857. alice,
  858. self.get_success(self.user_dir_helper.get_profiles_in_user_directory()),
  859. )
  860. # Alice changes her name to include a null codepoint.
  861. self.get_success(
  862. self.hs.get_user_directory_handler().handle_local_profile_change(
  863. alice,
  864. ProfileInfo(
  865. display_name="abcd\u0000efgh",
  866. avatar_url=MXC_DUMMY,
  867. ),
  868. )
  869. )
  870. # Alice's profile should be updated with the new avatar, but no display name.
  871. self.assertEqual(
  872. self.get_success(self.user_dir_helper.get_profiles_in_user_directory()),
  873. {alice: ProfileInfo(display_name=None, avatar_url=MXC_DUMMY)},
  874. )
  875. class TestUserDirSearchDisabled(unittest.HomeserverTestCase):
  876. servlets = [
  877. user_directory.register_servlets,
  878. room.register_servlets,
  879. login.register_servlets,
  880. synapse.rest.admin.register_servlets_for_client_rest_resource,
  881. ]
  882. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  883. config = self.default_config()
  884. # Re-enables updating the user directory, as that function is needed below. It
  885. # will be force disabled later
  886. config["update_user_directory_from_worker"] = None
  887. hs = self.setup_test_homeserver(config=config)
  888. self.config = hs.config
  889. return hs
  890. def test_disabling_room_list(self) -> None:
  891. self.config.userdirectory.user_directory_search_enabled = True
  892. # Create two users and put them in the same room.
  893. u1 = self.register_user("user1", "pass")
  894. u1_token = self.login(u1, "pass")
  895. u2 = self.register_user("user2", "pass")
  896. u2_token = self.login(u2, "pass")
  897. room = self.helper.create_room_as(u1, tok=u1_token)
  898. self.helper.join(room, user=u2, tok=u2_token)
  899. # Each should see the other when searching the user directory.
  900. channel = self.make_request(
  901. "POST",
  902. b"user_directory/search",
  903. b'{"search_term":"user2"}',
  904. access_token=u1_token,
  905. )
  906. self.assertEqual(200, channel.code, channel.result)
  907. self.assertTrue(len(channel.json_body["results"]) > 0)
  908. # Disable user directory and check search returns nothing
  909. self.config.userdirectory.user_directory_search_enabled = False
  910. channel = self.make_request(
  911. "POST",
  912. b"user_directory/search",
  913. b'{"search_term":"user2"}',
  914. access_token=u1_token,
  915. )
  916. self.assertEqual(200, channel.code, channel.result)
  917. self.assertTrue(len(channel.json_body["results"]) == 0)