test_user_directory.py 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288
  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 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, make_awaitable
  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["display_name"] == 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.assertTrue(profile["display_name"] == 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. s_user_id = "@support:test"
  382. self.get_success(
  383. self.store.register_user(
  384. user_id=s_user_id, password_hash=None, user_type=UserTypes.SUPPORT
  385. )
  386. )
  387. mock_remove_from_user_dir = Mock(return_value=make_awaitable(None))
  388. with patch.object(
  389. self.store, "remove_from_user_dir", mock_remove_from_user_dir
  390. ):
  391. self.get_success(self.handler.handle_local_user_deactivated(s_user_id))
  392. # BUG: the correct spelling is assert_not_called, but that makes the test fail
  393. # and it's not clear that this is actually the behaviour we want.
  394. mock_remove_from_user_dir.not_called()
  395. def test_handle_user_deactivated_regular_user(self) -> None:
  396. r_user_id = "@regular:test"
  397. self.get_success(
  398. self.store.register_user(user_id=r_user_id, password_hash=None)
  399. )
  400. mock_remove_from_user_dir = Mock(return_value=make_awaitable(None))
  401. with patch.object(
  402. self.store, "remove_from_user_dir", mock_remove_from_user_dir
  403. ):
  404. self.get_success(self.handler.handle_local_user_deactivated(r_user_id))
  405. mock_remove_from_user_dir.assert_called_once_with(r_user_id)
  406. def test_reactivation_makes_regular_user_searchable(self) -> None:
  407. user = self.register_user("regular", "pass")
  408. user_token = self.login(user, "pass")
  409. admin_user = self.register_user("admin", "pass", admin=True)
  410. admin_token = self.login(admin_user, "pass")
  411. # Ensure the regular user is publicly visible and searchable.
  412. self.helper.create_room_as(user, is_public=True, tok=user_token)
  413. s = self.get_success(self.handler.search_users(admin_user, user, 10))
  414. self.assertEqual(len(s["results"]), 1)
  415. self.assertEqual(s["results"][0]["user_id"], user)
  416. # Deactivate the user and check they're not searchable.
  417. deactivate_handler = self.hs.get_deactivate_account_handler()
  418. self.get_success(
  419. deactivate_handler.deactivate_account(
  420. user, erase_data=False, requester=create_requester(admin_user)
  421. )
  422. )
  423. s = self.get_success(self.handler.search_users(admin_user, user, 10))
  424. self.assertEqual(s["results"], [])
  425. # Reactivate the user
  426. channel = self.make_request(
  427. "PUT",
  428. f"/_synapse/admin/v2/users/{quote(user)}",
  429. access_token=admin_token,
  430. content={"deactivated": False, "password": "pass"},
  431. )
  432. self.assertEqual(channel.code, 200)
  433. user_token = self.login(user, "pass")
  434. self.helper.create_room_as(user, is_public=True, tok=user_token)
  435. # Check they're searchable.
  436. s = self.get_success(self.handler.search_users(admin_user, user, 10))
  437. self.assertEqual(len(s["results"]), 1)
  438. self.assertEqual(s["results"][0]["user_id"], user)
  439. def test_process_join_after_server_leaves_room(self) -> None:
  440. alice = self.register_user("alice", "pass")
  441. alice_token = self.login(alice, "pass")
  442. bob = self.register_user("bob", "pass")
  443. bob_token = self.login(bob, "pass")
  444. # Alice makes two rooms. Bob joins one of them.
  445. room1 = self.helper.create_room_as(alice, tok=alice_token)
  446. room2 = self.helper.create_room_as(alice, tok=alice_token)
  447. self.helper.join(room1, bob, tok=bob_token)
  448. # The user sharing tables should have been updated.
  449. public1 = self.get_success(self.user_dir_helper.get_users_in_public_rooms())
  450. self.assertEqual(set(public1), {(alice, room1), (alice, room2), (bob, room1)})
  451. # Alice leaves room1. The user sharing tables should be updated.
  452. self.helper.leave(room1, alice, tok=alice_token)
  453. public2 = self.get_success(self.user_dir_helper.get_users_in_public_rooms())
  454. self.assertEqual(set(public2), {(alice, room2), (bob, room1)})
  455. # Pause the processing of new events.
  456. dir_handler = self.hs.get_user_directory_handler()
  457. dir_handler.update_user_directory = False
  458. # Bob leaves one room and joins the other.
  459. self.helper.leave(room1, bob, tok=bob_token)
  460. self.helper.join(room2, bob, tok=bob_token)
  461. # Process the leave and join in one go.
  462. dir_handler.update_user_directory = True
  463. dir_handler.notify_new_event()
  464. self.wait_for_background_updates()
  465. # The user sharing tables should have been updated.
  466. public3 = self.get_success(self.user_dir_helper.get_users_in_public_rooms())
  467. self.assertEqual(set(public3), {(alice, room2), (bob, room2)})
  468. def test_per_room_profile_doesnt_alter_directory_entry(self) -> None:
  469. alice = self.register_user("alice", "pass")
  470. alice_token = self.login(alice, "pass")
  471. bob = self.register_user("bob", "pass")
  472. # Alice should have a user directory entry created at registration.
  473. users = self.get_success(self.user_dir_helper.get_profiles_in_user_directory())
  474. self.assertEqual(
  475. users[alice], ProfileInfo(display_name="alice", avatar_url=None)
  476. )
  477. # Alice makes a room for herself.
  478. room = self.helper.create_room_as(alice, is_public=True, tok=alice_token)
  479. # Alice sets a nickname unique to that room.
  480. self.helper.send_state(
  481. room,
  482. "m.room.member",
  483. {
  484. "displayname": "Freddy Mercury",
  485. "membership": "join",
  486. },
  487. alice_token,
  488. state_key=alice,
  489. )
  490. # Alice's display name remains the same in the user directory.
  491. search_result = self.get_success(self.handler.search_users(bob, alice, 10))
  492. self.assertEqual(
  493. search_result["results"],
  494. [{"display_name": "alice", "avatar_url": None, "user_id": alice}],
  495. 0,
  496. )
  497. def test_making_room_public_doesnt_alter_directory_entry(self) -> None:
  498. """Per-room names shouldn't go to the directory when the room becomes public.
  499. This isn't about preventing a leak (the room is now public, so the nickname
  500. is too). It's about preserving the invariant that we only show a user's public
  501. profile in the user directory results.
  502. I made this a Synapse test case rather than a Complement one because
  503. I think this is (strictly speaking) an implementation choice. Synapse
  504. has chosen to only ever use the public profile when responding to a user
  505. directory search. There's no privacy leak here, because making the room
  506. public discloses the per-room name.
  507. The spec doesn't mandate anything about _how_ a user
  508. should appear in a /user_directory/search result. Hypothetical example:
  509. suppose Bob searches for Alice. When representing Alice in a search
  510. result, it's reasonable to use any of Alice's nicknames that Bob is
  511. aware of. Heck, maybe we even want to use lots of them in a combined
  512. displayname like `Alice (aka "ali", "ally", "41iC3")`.
  513. """
  514. # TODO the same should apply when Alice is a remote user.
  515. alice = self.register_user("alice", "pass")
  516. alice_token = self.login(alice, "pass")
  517. bob = self.register_user("bob", "pass")
  518. bob_token = self.login(bob, "pass")
  519. # Alice and Bob are in a private room.
  520. room = self.helper.create_room_as(alice, is_public=False, tok=alice_token)
  521. self.helper.invite(room, src=alice, targ=bob, tok=alice_token)
  522. self.helper.join(room, user=bob, tok=bob_token)
  523. # Alice has a nickname unique to that room.
  524. self.helper.send_state(
  525. room,
  526. "m.room.member",
  527. {
  528. "displayname": "Freddy Mercury",
  529. "membership": "join",
  530. },
  531. alice_token,
  532. state_key=alice,
  533. )
  534. # Check Alice isn't recorded as being in a public room.
  535. public = self.get_success(self.user_dir_helper.get_users_in_public_rooms())
  536. self.assertNotIn((alice, room), public)
  537. # One of them makes the room public.
  538. self.helper.send_state(
  539. room,
  540. "m.room.join_rules",
  541. {"join_rule": "public"},
  542. alice_token,
  543. )
  544. # Check that Alice is now recorded as being in a public room
  545. public = self.get_success(self.user_dir_helper.get_users_in_public_rooms())
  546. self.assertIn((alice, room), public)
  547. # Alice's display name remains the same in the user directory.
  548. search_result = self.get_success(self.handler.search_users(bob, alice, 10))
  549. self.assertEqual(
  550. search_result["results"],
  551. [{"display_name": "alice", "avatar_url": None, "user_id": alice}],
  552. 0,
  553. )
  554. def test_private_room(self) -> None:
  555. """
  556. A user can be searched for only by people that are either in a public
  557. room, or that share a private chat.
  558. """
  559. u1 = self.register_user("user1", "pass")
  560. u1_token = self.login(u1, "pass")
  561. u2 = self.register_user("user2", "pass")
  562. u2_token = self.login(u2, "pass")
  563. u3 = self.register_user("user3", "pass")
  564. # u1 can't see u2 until they share a private room, or u1 is in a public room.
  565. s = self.get_success(self.handler.search_users(u1, "user2", 10))
  566. self.assertEqual(len(s["results"]), 0)
  567. # Get u1 and u2 into a private room.
  568. room = self.helper.create_room_as(u1, is_public=False, tok=u1_token)
  569. self.helper.invite(room, src=u1, targ=u2, tok=u1_token)
  570. self.helper.join(room, user=u2, tok=u2_token)
  571. # Check we have populated the database correctly.
  572. users, public_users, shares_private = self.get_success(
  573. self.user_dir_helper.get_tables()
  574. )
  575. self.assertEqual(users, {u1, u2, u3})
  576. self.assertEqual(shares_private, {(u1, u2, room), (u2, u1, room)})
  577. self.assertEqual(public_users, set())
  578. # We get one search result when searching for user2 by user1.
  579. s = self.get_success(self.handler.search_users(u1, "user2", 10))
  580. self.assertEqual(len(s["results"]), 1)
  581. # We get NO search results when searching for user2 by user3.
  582. s = self.get_success(self.handler.search_users(u3, "user2", 10))
  583. self.assertEqual(len(s["results"]), 0)
  584. # We get NO search results when searching for user3 by user1.
  585. s = self.get_success(self.handler.search_users(u1, "user3", 10))
  586. self.assertEqual(len(s["results"]), 0)
  587. # User 2 then leaves.
  588. self.helper.leave(room, user=u2, tok=u2_token)
  589. # Check this is reflected in the DB.
  590. users, public_users, shares_private = self.get_success(
  591. self.user_dir_helper.get_tables()
  592. )
  593. self.assertEqual(users, {u1, u2, u3})
  594. self.assertEqual(shares_private, set())
  595. self.assertEqual(public_users, set())
  596. # User1 now gets no search results for any of the other users.
  597. s = self.get_success(self.handler.search_users(u1, "user2", 10))
  598. self.assertEqual(len(s["results"]), 0)
  599. s = self.get_success(self.handler.search_users(u1, "user3", 10))
  600. self.assertEqual(len(s["results"]), 0)
  601. def test_joining_private_room_with_excluded_user(self) -> None:
  602. """
  603. When a user excluded from the user directory, E say, joins a private
  604. room, E will not appear in the `users_who_share_private_rooms` table.
  605. When a normal user, U say, joins a private room containing E, then
  606. U will appear in the `users_who_share_private_rooms` table, but E will
  607. not.
  608. """
  609. # Setup a support and two normal users.
  610. alice = self.register_user("alice", "pass")
  611. alice_token = self.login(alice, "pass")
  612. bob = self.register_user("bob", "pass")
  613. bob_token = self.login(bob, "pass")
  614. support = "@support1:test"
  615. self.get_success(
  616. self.store.register_user(
  617. user_id=support, password_hash=None, user_type=UserTypes.SUPPORT
  618. )
  619. )
  620. # Alice makes a room. Inject the support user into the room.
  621. room = self.helper.create_room_as(alice, is_public=False, tok=alice_token)
  622. self.get_success(inject_member_event(self.hs, room, support, "join"))
  623. # Check the DB state. The support user should not be in the directory.
  624. users, in_public, in_private = self.get_success(
  625. self.user_dir_helper.get_tables()
  626. )
  627. self.assertEqual(users, {alice, bob})
  628. self.assertEqual(in_public, set())
  629. self.assertEqual(in_private, set())
  630. # Then invite Bob, who accepts.
  631. self.helper.invite(room, alice, bob, tok=alice_token)
  632. self.helper.join(room, bob, tok=bob_token)
  633. # Check the DB state. The support user should not be in the directory.
  634. users, in_public, in_private = self.get_success(
  635. self.user_dir_helper.get_tables()
  636. )
  637. self.assertEqual(users, {alice, bob})
  638. self.assertEqual(in_public, set())
  639. self.assertEqual(in_private, {(alice, bob, room), (bob, alice, room)})
  640. def test_spam_checker(self) -> None:
  641. """
  642. A user which fails the spam checks will not appear in search results.
  643. """
  644. u1 = self.register_user("user1", "pass")
  645. u1_token = self.login(u1, "pass")
  646. u2 = self.register_user("user2", "pass")
  647. u2_token = self.login(u2, "pass")
  648. # We do not add users to the directory until they join a room.
  649. s = self.get_success(self.handler.search_users(u1, "user2", 10))
  650. self.assertEqual(len(s["results"]), 0)
  651. room = self.helper.create_room_as(u1, is_public=False, tok=u1_token)
  652. self.helper.invite(room, src=u1, targ=u2, tok=u1_token)
  653. self.helper.join(room, user=u2, tok=u2_token)
  654. # Check we have populated the database correctly.
  655. shares_private = self.get_success(
  656. self.user_dir_helper.get_users_who_share_private_rooms()
  657. )
  658. public_users = self.get_success(
  659. self.user_dir_helper.get_users_in_public_rooms()
  660. )
  661. self.assertEqual(shares_private, {(u1, u2, room), (u2, u1, room)})
  662. self.assertEqual(public_users, set())
  663. # We get one search result when searching for user2 by user1.
  664. s = self.get_success(self.handler.search_users(u1, "user2", 10))
  665. self.assertEqual(len(s["results"]), 1)
  666. async def allow_all(user_profile: UserProfile) -> bool:
  667. # Allow all users.
  668. return False
  669. # Configure a spam checker that does not filter any users.
  670. spam_checker = self.hs.get_spam_checker()
  671. spam_checker._check_username_for_spam_callbacks = [allow_all]
  672. # The results do not change:
  673. # We get one search result when searching for user2 by user1.
  674. s = self.get_success(self.handler.search_users(u1, "user2", 10))
  675. self.assertEqual(len(s["results"]), 1)
  676. # Configure a spam checker that filters all users.
  677. async def block_all(user_profile: UserProfile) -> bool:
  678. # All users are spammy.
  679. return True
  680. spam_checker._check_username_for_spam_callbacks = [block_all]
  681. # User1 now gets no search results for any of the other users.
  682. s = self.get_success(self.handler.search_users(u1, "user2", 10))
  683. self.assertEqual(len(s["results"]), 0)
  684. @override_config(
  685. {
  686. "spam_checker": {
  687. "module": "tests.handlers.test_user_directory.UselessSpamChecker"
  688. }
  689. }
  690. )
  691. def test_legacy_spam_checker(self) -> None:
  692. """
  693. A spam checker without the expected method should be ignored.
  694. """
  695. u1 = self.register_user("user1", "pass")
  696. u1_token = self.login(u1, "pass")
  697. u2 = self.register_user("user2", "pass")
  698. u2_token = self.login(u2, "pass")
  699. # We do not add users to the directory until they join a room.
  700. s = self.get_success(self.handler.search_users(u1, "user2", 10))
  701. self.assertEqual(len(s["results"]), 0)
  702. room = self.helper.create_room_as(u1, is_public=False, tok=u1_token)
  703. self.helper.invite(room, src=u1, targ=u2, tok=u1_token)
  704. self.helper.join(room, user=u2, tok=u2_token)
  705. # Check we have populated the database correctly.
  706. shares_private = self.get_success(
  707. self.user_dir_helper.get_users_who_share_private_rooms()
  708. )
  709. public_users = self.get_success(
  710. self.user_dir_helper.get_users_in_public_rooms()
  711. )
  712. self.assertEqual(shares_private, {(u1, u2, room), (u2, u1, room)})
  713. self.assertEqual(public_users, set())
  714. # We get one search result when searching for user2 by user1.
  715. s = self.get_success(self.handler.search_users(u1, "user2", 10))
  716. self.assertEqual(len(s["results"]), 1)
  717. def test_initial_share_all_users(self) -> None:
  718. """
  719. Search all users = True means that a user does not have to share a
  720. private room with the searching user or be in a public room to be search
  721. visible.
  722. """
  723. self.handler.search_all_users = True
  724. self.hs.config.userdirectory.user_directory_search_all_users = True
  725. u1 = self.register_user("user1", "pass")
  726. self.register_user("user2", "pass")
  727. u3 = self.register_user("user3", "pass")
  728. shares_private = self.get_success(
  729. self.user_dir_helper.get_users_who_share_private_rooms()
  730. )
  731. public_users = self.get_success(
  732. self.user_dir_helper.get_users_in_public_rooms()
  733. )
  734. # No users share rooms
  735. self.assertEqual(public_users, set())
  736. self.assertEqual(shares_private, set())
  737. # Despite not sharing a room, search_all_users means we get a search
  738. # result.
  739. s = self.get_success(self.handler.search_users(u1, u3, 10))
  740. self.assertEqual(len(s["results"]), 1)
  741. # We can find the other two users
  742. s = self.get_success(self.handler.search_users(u1, "user", 10))
  743. self.assertEqual(len(s["results"]), 2)
  744. # Registering a user and then searching for them works.
  745. u4 = self.register_user("user4", "pass")
  746. s = self.get_success(self.handler.search_users(u1, u4, 10))
  747. self.assertEqual(len(s["results"]), 1)
  748. @override_config(
  749. {
  750. "user_directory": {
  751. "enabled": True,
  752. "search_all_users": True,
  753. "prefer_local_users": True,
  754. }
  755. }
  756. )
  757. def test_prefer_local_users(self) -> None:
  758. """Tests that local users are shown higher in search results when
  759. user_directory.prefer_local_users is True.
  760. """
  761. # Create a room and few users to test the directory with
  762. searching_user = self.register_user("searcher", "password")
  763. searching_user_tok = self.login("searcher", "password")
  764. room_id = self.helper.create_room_as(
  765. searching_user,
  766. room_version=RoomVersions.V1.identifier,
  767. tok=searching_user_tok,
  768. )
  769. # Create a few local users and join them to the room
  770. local_user_1 = self.register_user("user_xxxxx", "password")
  771. local_user_2 = self.register_user("user_bbbbb", "password")
  772. local_user_3 = self.register_user("user_zzzzz", "password")
  773. self._add_user_to_room(room_id, RoomVersions.V1, local_user_1)
  774. self._add_user_to_room(room_id, RoomVersions.V1, local_user_2)
  775. self._add_user_to_room(room_id, RoomVersions.V1, local_user_3)
  776. # Create a few "remote" users and join them to the room
  777. remote_user_1 = "@user_aaaaa:remote_server"
  778. remote_user_2 = "@user_yyyyy:remote_server"
  779. remote_user_3 = "@user_ccccc:remote_server"
  780. self._add_user_to_room(room_id, RoomVersions.V1, remote_user_1)
  781. self._add_user_to_room(room_id, RoomVersions.V1, remote_user_2)
  782. self._add_user_to_room(room_id, RoomVersions.V1, remote_user_3)
  783. local_users = [local_user_1, local_user_2, local_user_3]
  784. remote_users = [remote_user_1, remote_user_2, remote_user_3]
  785. # The local searching user searches for the term "user", which other users have
  786. # in their user id
  787. results = self.get_success(
  788. self.handler.search_users(searching_user, "user", 20)
  789. )["results"]
  790. received_user_id_ordering = [result["user_id"] for result in results]
  791. # Typically we'd expect Synapse to return users in lexicographical order,
  792. # assuming they have similar User IDs/display names, and profile information.
  793. # Check that the order of returned results using our module is as we expect,
  794. # i.e our local users show up first, despite all users having lexographically mixed
  795. # user IDs.
  796. [self.assertIn(user, local_users) for user in received_user_id_ordering[:3]]
  797. [self.assertIn(user, remote_users) for user in received_user_id_ordering[3:]]
  798. def _add_user_to_room(
  799. self,
  800. room_id: str,
  801. room_version: RoomVersion,
  802. user_id: str,
  803. ) -> None:
  804. # Add a user to the room.
  805. builder = self.event_builder_factory.for_room_version(
  806. room_version,
  807. {
  808. "type": "m.room.member",
  809. "sender": user_id,
  810. "state_key": user_id,
  811. "room_id": room_id,
  812. "content": {"membership": "join"},
  813. },
  814. )
  815. event, unpersisted_context = self.get_success(
  816. self.event_creation_handler.create_new_client_event(builder)
  817. )
  818. context = self.get_success(unpersisted_context.persist(event))
  819. persistence = self.hs.get_storage_controllers().persistence
  820. assert persistence is not None
  821. self.get_success(persistence.persist_event(event, context))
  822. def test_local_user_leaving_room_remains_in_user_directory(self) -> None:
  823. """We've chosen to simplify the user directory's implementation by
  824. always including local users. Ensure this invariant is maintained when
  825. a local user
  826. - leaves a room, and
  827. - leaves the last room they're in which is visible to this server.
  828. This is user-visible if the "search_all_users" config option is on: the
  829. local user who left a room would no longer be searchable if this test fails!
  830. """
  831. alice = self.register_user("alice", "pass")
  832. alice_token = self.login(alice, "pass")
  833. bob = self.register_user("bob", "pass")
  834. bob_token = self.login(bob, "pass")
  835. # Alice makes two public rooms, which Bob joins.
  836. room1 = self.helper.create_room_as(alice, is_public=True, tok=alice_token)
  837. room2 = self.helper.create_room_as(alice, is_public=True, tok=alice_token)
  838. self.helper.join(room1, bob, tok=bob_token)
  839. self.helper.join(room2, bob, tok=bob_token)
  840. # The user directory tables are updated.
  841. users, in_public, in_private = self.get_success(
  842. self.user_dir_helper.get_tables()
  843. )
  844. self.assertEqual(users, {alice, bob})
  845. self.assertEqual(
  846. in_public, {(alice, room1), (alice, room2), (bob, room1), (bob, room2)}
  847. )
  848. self.assertEqual(in_private, set())
  849. # Alice leaves one room. She should still be in the directory.
  850. self.helper.leave(room1, alice, tok=alice_token)
  851. users, in_public, in_private = self.get_success(
  852. self.user_dir_helper.get_tables()
  853. )
  854. self.assertEqual(users, {alice, bob})
  855. self.assertEqual(in_public, {(alice, room2), (bob, room1), (bob, room2)})
  856. self.assertEqual(in_private, set())
  857. # Alice leaves the other. She should still be in the directory.
  858. self.helper.leave(room2, alice, tok=alice_token)
  859. self.wait_for_background_updates()
  860. users, in_public, in_private = self.get_success(
  861. self.user_dir_helper.get_tables()
  862. )
  863. self.assertEqual(users, {alice, bob})
  864. self.assertEqual(in_public, {(bob, room1), (bob, room2)})
  865. self.assertEqual(in_private, set())
  866. def test_ignore_display_names_with_null_codepoints(self) -> None:
  867. MXC_DUMMY = "mxc://dummy"
  868. # Alice creates a public room.
  869. alice = self.register_user("alice", "pass")
  870. # Alice has a user directory entry to start with.
  871. self.assertIn(
  872. alice,
  873. self.get_success(self.user_dir_helper.get_profiles_in_user_directory()),
  874. )
  875. # Alice changes her name to include a null codepoint.
  876. self.get_success(
  877. self.hs.get_user_directory_handler().handle_local_profile_change(
  878. alice,
  879. ProfileInfo(
  880. display_name="abcd\u0000efgh",
  881. avatar_url=MXC_DUMMY,
  882. ),
  883. )
  884. )
  885. # Alice's profile should be updated with the new avatar, but no display name.
  886. self.assertEqual(
  887. self.get_success(self.user_dir_helper.get_profiles_in_user_directory()),
  888. {alice: ProfileInfo(display_name=None, avatar_url=MXC_DUMMY)},
  889. )
  890. class TestUserDirSearchDisabled(unittest.HomeserverTestCase):
  891. servlets = [
  892. user_directory.register_servlets,
  893. room.register_servlets,
  894. login.register_servlets,
  895. synapse.rest.admin.register_servlets_for_client_rest_resource,
  896. ]
  897. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  898. config = self.default_config()
  899. # Re-enables updating the user directory, as that function is needed below. It
  900. # will be force disabled later
  901. config["update_user_directory_from_worker"] = None
  902. hs = self.setup_test_homeserver(config=config)
  903. self.config = hs.config
  904. return hs
  905. def test_disabling_room_list(self) -> None:
  906. self.config.userdirectory.user_directory_search_enabled = True
  907. # Create two users and put them in the same room.
  908. u1 = self.register_user("user1", "pass")
  909. u1_token = self.login(u1, "pass")
  910. u2 = self.register_user("user2", "pass")
  911. u2_token = self.login(u2, "pass")
  912. room = self.helper.create_room_as(u1, tok=u1_token)
  913. self.helper.join(room, user=u2, tok=u2_token)
  914. # Each should see the other when searching the user directory.
  915. channel = self.make_request(
  916. "POST",
  917. b"user_directory/search",
  918. b'{"search_term":"user2"}',
  919. access_token=u1_token,
  920. )
  921. self.assertEqual(200, channel.code, channel.result)
  922. self.assertTrue(len(channel.json_body["results"]) > 0)
  923. # Disable user directory and check search returns nothing
  924. self.config.userdirectory.user_directory_search_enabled = False
  925. channel = self.make_request(
  926. "POST",
  927. b"user_directory/search",
  928. b'{"search_term":"user2"}',
  929. access_token=u1_token,
  930. )
  931. self.assertEqual(200, channel.code, channel.result)
  932. self.assertTrue(len(channel.json_body["results"]) == 0)
  933. class UserDirectoryRemoteProfileTestCase(unittest.HomeserverTestCase):
  934. servlets = [
  935. login.register_servlets,
  936. synapse.rest.admin.register_servlets,
  937. register.register_servlets,
  938. room.register_servlets,
  939. ]
  940. def default_config(self) -> JsonDict:
  941. config = super().default_config()
  942. # Re-enables updating the user directory, as that functionality is needed below.
  943. config["update_user_directory_from_worker"] = None
  944. return config
  945. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  946. self.store = hs.get_datastores().main
  947. self.alice = self.register_user("alice", "alice123")
  948. self.alice_tok = self.login("alice", "alice123")
  949. self.user_dir_helper = GetUserDirectoryTables(self.store)
  950. self.user_dir_handler = hs.get_user_directory_handler()
  951. self.profile_handler = hs.get_profile_handler()
  952. # Cancel the startup call: in the steady-state case we can't rely on it anyway.
  953. assert self.user_dir_handler._refresh_remote_profiles_call_later is not None
  954. self.user_dir_handler._refresh_remote_profiles_call_later.cancel()
  955. def test_public_rooms_have_profiles_collected(self) -> None:
  956. """
  957. In a public room, member state events are treated as reflecting the user's
  958. real profile and they are accepted.
  959. (The main motivation for accepting this is to prevent having to query
  960. *every* single profile change over federation.)
  961. """
  962. room_id = self.helper.create_room_as(
  963. self.alice, is_public=True, tok=self.alice_tok
  964. )
  965. self.get_success(
  966. event_injection.inject_member_event(
  967. self.hs,
  968. room_id,
  969. "@bruce:remote",
  970. "join",
  971. "@bruce:remote",
  972. extra_content={
  973. "displayname": "Bruce!",
  974. "avatar_url": "mxc://remote/123",
  975. },
  976. )
  977. )
  978. # Sending this event makes the streams move forward after the injection...
  979. self.helper.send(room_id, "Test", tok=self.alice_tok)
  980. self.pump(0.1)
  981. profiles = self.get_success(
  982. self.user_dir_helper.get_profiles_in_user_directory()
  983. )
  984. self.assertEqual(
  985. profiles.get("@bruce:remote"),
  986. ProfileInfo(display_name="Bruce!", avatar_url="mxc://remote/123"),
  987. )
  988. def test_private_rooms_do_not_have_profiles_collected(self) -> None:
  989. """
  990. In a private room, member state events are not pulled out and used to populate
  991. the user directory.
  992. """
  993. room_id = self.helper.create_room_as(
  994. self.alice, is_public=False, tok=self.alice_tok
  995. )
  996. self.get_success(
  997. event_injection.inject_member_event(
  998. self.hs,
  999. room_id,
  1000. "@bruce:remote",
  1001. "join",
  1002. "@bruce:remote",
  1003. extra_content={
  1004. "displayname": "super-duper bruce",
  1005. "avatar_url": "mxc://remote/456",
  1006. },
  1007. )
  1008. )
  1009. # Sending this event makes the streams move forward after the injection...
  1010. self.helper.send(room_id, "Test", tok=self.alice_tok)
  1011. self.pump(0.1)
  1012. profiles = self.get_success(
  1013. self.user_dir_helper.get_profiles_in_user_directory()
  1014. )
  1015. self.assertNotIn("@bruce:remote", profiles)
  1016. def test_private_rooms_have_profiles_requested(self) -> None:
  1017. """
  1018. When a name changes in a private room, the homeserver instead requests
  1019. the user's global profile over federation.
  1020. """
  1021. async def get_remote_profile(
  1022. user_id: str, ignore_backoff: bool = True
  1023. ) -> JsonDict:
  1024. if user_id == "@bruce:remote":
  1025. return {
  1026. "displayname": "Sir Bruce Bruceson",
  1027. "avatar_url": "mxc://remote/789",
  1028. }
  1029. else:
  1030. raise ValueError(f"unable to fetch {user_id}")
  1031. with patch.object(self.profile_handler, "get_profile", get_remote_profile):
  1032. # Continue from the earlier test...
  1033. self.test_private_rooms_do_not_have_profiles_collected()
  1034. # Advance by a minute
  1035. self.reactor.advance(61.0)
  1036. profiles = self.get_success(
  1037. self.user_dir_helper.get_profiles_in_user_directory()
  1038. )
  1039. self.assertEqual(
  1040. profiles.get("@bruce:remote"),
  1041. ProfileInfo(
  1042. display_name="Sir Bruce Bruceson", avatar_url="mxc://remote/789"
  1043. ),
  1044. )
  1045. def test_profile_requests_are_retried(self) -> None:
  1046. """
  1047. When we fail to fetch the user's profile over federation,
  1048. we try again later.
  1049. """
  1050. has_failed_once = False
  1051. async def get_remote_profile(
  1052. user_id: str, ignore_backoff: bool = True
  1053. ) -> JsonDict:
  1054. nonlocal has_failed_once
  1055. if user_id == "@bruce:remote":
  1056. if not has_failed_once:
  1057. has_failed_once = True
  1058. raise SynapseError(502, "temporary network problem")
  1059. return {
  1060. "displayname": "Sir Bruce Bruceson",
  1061. "avatar_url": "mxc://remote/789",
  1062. }
  1063. else:
  1064. raise ValueError(f"unable to fetch {user_id}")
  1065. with patch.object(self.profile_handler, "get_profile", get_remote_profile):
  1066. # Continue from the earlier test...
  1067. self.test_private_rooms_do_not_have_profiles_collected()
  1068. # Advance by a minute
  1069. self.reactor.advance(61.0)
  1070. # The request has already failed once
  1071. self.assertTrue(has_failed_once)
  1072. # The profile has yet to be updated.
  1073. profiles = self.get_success(
  1074. self.user_dir_helper.get_profiles_in_user_directory()
  1075. )
  1076. self.assertNotIn(
  1077. "@bruce:remote",
  1078. profiles,
  1079. )
  1080. # Advance by five minutes, after the backoff has finished
  1081. self.reactor.advance(301.0)
  1082. # The profile should have been updated now
  1083. profiles = self.get_success(
  1084. self.user_dir_helper.get_profiles_in_user_directory()
  1085. )
  1086. self.assertEqual(
  1087. profiles.get("@bruce:remote"),
  1088. ProfileInfo(
  1089. display_name="Sir Bruce Bruceson", avatar_url="mxc://remote/789"
  1090. ),
  1091. )