1
0

test_user_directory.py 51 KB

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