test_user_directory.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  1. # Copyright 2018-2021 The Matrix.org Foundation C.I.C.
  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. import re
  15. from typing import Any, Dict, Set, Tuple
  16. from unittest import mock
  17. from unittest.mock import Mock, patch
  18. from twisted.test.proto_helpers import MemoryReactor
  19. from synapse.api.constants import EventTypes, Membership, UserTypes
  20. from synapse.appservice import ApplicationService
  21. from synapse.rest import admin
  22. from synapse.rest.client import login, register, room
  23. from synapse.server import HomeServer
  24. from synapse.storage import DataStore
  25. from synapse.storage.background_updates import _BackgroundUpdateHandler
  26. from synapse.storage.databases.main import user_directory
  27. from synapse.storage.databases.main.user_directory import (
  28. _parse_words_with_icu,
  29. _parse_words_with_regex,
  30. )
  31. from synapse.storage.roommember import ProfileInfo
  32. from synapse.util import Clock
  33. from tests.server import ThreadedMemoryReactorClock
  34. from tests.test_utils.event_injection import inject_member_event
  35. from tests.unittest import HomeserverTestCase, override_config
  36. try:
  37. import icu
  38. except ImportError:
  39. icu = None # type: ignore
  40. ALICE = "@alice:a"
  41. BOB = "@bob:b"
  42. BOBBY = "@bobby:a"
  43. # The localpart isn't 'Bela' on purpose so we can test looking up display names.
  44. BELA = "@somenickname:example.org"
  45. class GetUserDirectoryTables:
  46. """Helper functions that we want to reuse in tests/handlers/test_user_directory.py"""
  47. def __init__(self, store: DataStore):
  48. self.store = store
  49. async def get_users_in_public_rooms(self) -> Set[Tuple[str, str]]:
  50. """Fetch the entire `users_in_public_rooms` table.
  51. Returns a list of tuples (user_id, room_id) where room_id is public and
  52. contains the user with the given id.
  53. """
  54. r = await self.store.db_pool.simple_select_list(
  55. "users_in_public_rooms", None, ("user_id", "room_id")
  56. )
  57. retval = set()
  58. for i in r:
  59. retval.add((i["user_id"], i["room_id"]))
  60. return retval
  61. async def get_users_who_share_private_rooms(self) -> Set[Tuple[str, str, str]]:
  62. """Fetch the entire `users_who_share_private_rooms` table.
  63. Returns a set of tuples (user_id, other_user_id, room_id) corresponding
  64. to the rows of `users_who_share_private_rooms`.
  65. """
  66. rows = await self.store.db_pool.simple_select_list(
  67. "users_who_share_private_rooms",
  68. None,
  69. ["user_id", "other_user_id", "room_id"],
  70. )
  71. rv = set()
  72. for row in rows:
  73. rv.add((row["user_id"], row["other_user_id"], row["room_id"]))
  74. return rv
  75. async def get_users_in_user_directory(self) -> Set[str]:
  76. """Fetch the set of users in the `user_directory` table.
  77. This is useful when checking we've correctly excluded users from the directory.
  78. """
  79. result = await self.store.db_pool.simple_select_list(
  80. "user_directory",
  81. None,
  82. ["user_id"],
  83. )
  84. return {row["user_id"] for row in result}
  85. async def get_profiles_in_user_directory(self) -> Dict[str, ProfileInfo]:
  86. """Fetch users and their profiles from the `user_directory` table.
  87. This is useful when we want to inspect display names and avatars.
  88. It's almost the entire contents of the `user_directory` table: the only
  89. thing missing is an unused room_id column.
  90. """
  91. rows = await self.store.db_pool.simple_select_list(
  92. "user_directory",
  93. None,
  94. ("user_id", "display_name", "avatar_url"),
  95. )
  96. return {
  97. row["user_id"]: ProfileInfo(
  98. display_name=row["display_name"], avatar_url=row["avatar_url"]
  99. )
  100. for row in rows
  101. }
  102. async def get_tables(
  103. self,
  104. ) -> Tuple[Set[str], Set[Tuple[str, str]], Set[Tuple[str, str, str]]]:
  105. """Multiple tests want to inspect these tables, so expose them together."""
  106. return (
  107. await self.get_users_in_user_directory(),
  108. await self.get_users_in_public_rooms(),
  109. await self.get_users_who_share_private_rooms(),
  110. )
  111. class UserDirectoryInitialPopulationTestcase(HomeserverTestCase):
  112. """Ensure that rebuilding the directory writes the correct data to the DB.
  113. See also tests/handlers/test_user_directory.py for similar checks. They
  114. test the incremental updates, rather than the big rebuild.
  115. """
  116. servlets = [
  117. login.register_servlets,
  118. admin.register_servlets,
  119. room.register_servlets,
  120. register.register_servlets,
  121. ]
  122. def make_homeserver(
  123. self, reactor: ThreadedMemoryReactorClock, clock: Clock
  124. ) -> HomeServer:
  125. self.appservice = ApplicationService(
  126. token="i_am_an_app_service",
  127. id="1234",
  128. namespaces={"users": [{"regex": r"@as_user.*", "exclusive": True}]},
  129. sender="@as:test",
  130. )
  131. mock_load_appservices = Mock(return_value=[self.appservice])
  132. with patch(
  133. "synapse.storage.databases.main.appservice.load_appservices",
  134. mock_load_appservices,
  135. ):
  136. hs = super().make_homeserver(reactor, clock)
  137. return hs
  138. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  139. self.store = hs.get_datastores().main
  140. self.user_dir_helper = GetUserDirectoryTables(self.store)
  141. def _purge_and_rebuild_user_dir(self) -> None:
  142. """Nuke the user directory tables, start the background process to
  143. repopulate them, and wait for the process to complete. This allows us
  144. to inspect the outcome of the background process alone, without any of
  145. the other incremental updates.
  146. """
  147. self.get_success(self.store.update_user_directory_stream_pos(None))
  148. self.get_success(self.store.delete_all_from_user_dir())
  149. shares_private = self.get_success(
  150. self.user_dir_helper.get_users_who_share_private_rooms()
  151. )
  152. public_users = self.get_success(
  153. self.user_dir_helper.get_users_in_public_rooms()
  154. )
  155. # Nothing updated yet
  156. self.assertEqual(shares_private, set())
  157. self.assertEqual(public_users, set())
  158. # Ugh, have to reset this flag
  159. self.store.db_pool.updates._all_done = False
  160. self.get_success(
  161. self.store.db_pool.simple_insert(
  162. "background_updates",
  163. {
  164. "update_name": "populate_user_directory_createtables",
  165. "progress_json": "{}",
  166. },
  167. )
  168. )
  169. self.get_success(
  170. self.store.db_pool.simple_insert(
  171. "background_updates",
  172. {
  173. "update_name": "populate_user_directory_process_rooms",
  174. "progress_json": "{}",
  175. "depends_on": "populate_user_directory_createtables",
  176. },
  177. )
  178. )
  179. self.get_success(
  180. self.store.db_pool.simple_insert(
  181. "background_updates",
  182. {
  183. "update_name": "populate_user_directory_process_users",
  184. "progress_json": "{}",
  185. "depends_on": "populate_user_directory_process_rooms",
  186. },
  187. )
  188. )
  189. self.get_success(
  190. self.store.db_pool.simple_insert(
  191. "background_updates",
  192. {
  193. "update_name": "populate_user_directory_cleanup",
  194. "progress_json": "{}",
  195. "depends_on": "populate_user_directory_process_users",
  196. },
  197. )
  198. )
  199. self.wait_for_background_updates()
  200. def test_initial(self) -> None:
  201. """
  202. The user directory's initial handler correctly updates the search tables.
  203. """
  204. u1 = self.register_user("user1", "pass")
  205. u1_token = self.login(u1, "pass")
  206. u2 = self.register_user("user2", "pass")
  207. u2_token = self.login(u2, "pass")
  208. u3 = self.register_user("user3", "pass")
  209. u3_token = self.login(u3, "pass")
  210. room = self.helper.create_room_as(u1, is_public=True, tok=u1_token)
  211. self.helper.invite(room, src=u1, targ=u2, tok=u1_token)
  212. self.helper.join(room, user=u2, tok=u2_token)
  213. private_room = self.helper.create_room_as(u1, is_public=False, tok=u1_token)
  214. self.helper.invite(private_room, src=u1, targ=u3, tok=u1_token)
  215. self.helper.join(private_room, user=u3, tok=u3_token)
  216. # Do the initial population of the user directory via the background update
  217. self._purge_and_rebuild_user_dir()
  218. users, in_public, in_private = self.get_success(
  219. self.user_dir_helper.get_tables()
  220. )
  221. # User 1 and User 2 are in the same public room
  222. self.assertEqual(in_public, {(u1, room), (u2, room)})
  223. # User 1 and User 3 share private rooms
  224. self.assertEqual(in_private, {(u1, u3, private_room), (u3, u1, private_room)})
  225. # All three should have entries in the directory
  226. self.assertEqual(users, {u1, u2, u3})
  227. # The next four tests (test_population_excludes_*) all set up
  228. # - A normal user included in the user dir
  229. # - A public and private room created by that user
  230. # - A user excluded from the room dir, belonging to both rooms
  231. # They match similar logic in handlers/test_user_directory.py But that tests
  232. # updating the directory; this tests rebuilding it from scratch.
  233. def _create_rooms_and_inject_memberships(
  234. self, creator: str, token: str, joiner: str
  235. ) -> Tuple[str, str]:
  236. """Create a public and private room as a normal user.
  237. Then get the `joiner` into those rooms.
  238. """
  239. public_room = self.helper.create_room_as(
  240. creator,
  241. is_public=True,
  242. # See https://github.com/matrix-org/synapse/issues/10951
  243. extra_content={"visibility": "public"},
  244. tok=token,
  245. )
  246. private_room = self.helper.create_room_as(creator, is_public=False, tok=token)
  247. # HACK: get the user into these rooms
  248. self.get_success(inject_member_event(self.hs, public_room, joiner, "join"))
  249. self.get_success(inject_member_event(self.hs, private_room, joiner, "join"))
  250. return public_room, private_room
  251. def _check_room_sharing_tables(
  252. self, normal_user: str, public_room: str, private_room: str
  253. ) -> None:
  254. # After rebuilding the directory, we should only see the normal user.
  255. users, in_public, in_private = self.get_success(
  256. self.user_dir_helper.get_tables()
  257. )
  258. self.assertEqual(users, {normal_user})
  259. self.assertEqual(in_public, {(normal_user, public_room)})
  260. self.assertEqual(in_private, set())
  261. def test_population_excludes_support_user(self) -> None:
  262. # Create a normal and support user.
  263. user = self.register_user("user", "pass")
  264. token = self.login(user, "pass")
  265. support = "@support1:test"
  266. self.get_success(
  267. self.store.register_user(
  268. user_id=support, password_hash=None, user_type=UserTypes.SUPPORT
  269. )
  270. )
  271. # Join the support user to rooms owned by the normal user.
  272. public, private = self._create_rooms_and_inject_memberships(
  273. user, token, support
  274. )
  275. # Rebuild the directory.
  276. self._purge_and_rebuild_user_dir()
  277. # Check the support user is not in the directory.
  278. self._check_room_sharing_tables(user, public, private)
  279. def test_population_excludes_deactivated_user(self) -> None:
  280. user = self.register_user("naughty", "pass")
  281. admin = self.register_user("admin", "pass", admin=True)
  282. admin_token = self.login(admin, "pass")
  283. # Deactivate the user.
  284. channel = self.make_request(
  285. "PUT",
  286. f"/_synapse/admin/v2/users/{user}",
  287. access_token=admin_token,
  288. content={"deactivated": True},
  289. )
  290. self.assertEqual(channel.code, 200)
  291. self.assertEqual(channel.json_body["deactivated"], True)
  292. # Join the deactivated user to rooms owned by the admin.
  293. # Is this something that could actually happen outside of a test?
  294. public, private = self._create_rooms_and_inject_memberships(
  295. admin, admin_token, user
  296. )
  297. # Rebuild the user dir. The deactivated user should be missing.
  298. self._purge_and_rebuild_user_dir()
  299. self._check_room_sharing_tables(admin, public, private)
  300. def test_population_excludes_appservice_user(self) -> None:
  301. # Register an AS user.
  302. user = self.register_user("user", "pass")
  303. token = self.login(user, "pass")
  304. as_user, _ = self.register_appservice_user(
  305. "as_user_potato", self.appservice.token
  306. )
  307. # Join the AS user to rooms owned by the normal user.
  308. public, private = self._create_rooms_and_inject_memberships(
  309. user, token, as_user
  310. )
  311. # Rebuild the directory.
  312. self._purge_and_rebuild_user_dir()
  313. # Check the AS user is not in the directory.
  314. self._check_room_sharing_tables(user, public, private)
  315. def test_population_excludes_appservice_sender(self) -> None:
  316. user = self.register_user("user", "pass")
  317. token = self.login(user, "pass")
  318. # Join the AS sender to rooms owned by the normal user.
  319. public, private = self._create_rooms_and_inject_memberships(
  320. user, token, self.appservice.sender
  321. )
  322. # Rebuild the directory.
  323. self._purge_and_rebuild_user_dir()
  324. # Check the AS sender is not in the directory.
  325. self._check_room_sharing_tables(user, public, private)
  326. def test_population_conceals_private_nickname(self) -> None:
  327. # Make a private room, and set a nickname within
  328. user = self.register_user("aaaa", "pass")
  329. user_token = self.login(user, "pass")
  330. private_room = self.helper.create_room_as(user, is_public=False, tok=user_token)
  331. self.helper.send_state(
  332. private_room,
  333. EventTypes.Member,
  334. state_key=user,
  335. body={"membership": Membership.JOIN, "displayname": "BBBB"},
  336. tok=user_token,
  337. )
  338. # Rebuild the user directory. Make the rescan of the `users` table a no-op
  339. # so we only see the effect of scanning the `room_memberships` table.
  340. async def mocked_process_users(*args: Any, **kwargs: Any) -> int:
  341. await self.store.db_pool.updates._end_background_update(
  342. "populate_user_directory_process_users"
  343. )
  344. return 1
  345. with mock.patch.dict(
  346. self.store.db_pool.updates._background_update_handlers,
  347. populate_user_directory_process_users=_BackgroundUpdateHandler(
  348. mocked_process_users,
  349. ),
  350. ):
  351. self._purge_and_rebuild_user_dir()
  352. # Local users are ignored by the scan over rooms
  353. users = self.get_success(self.user_dir_helper.get_profiles_in_user_directory())
  354. self.assertEqual(users, {})
  355. # Do a full rebuild including the scan over the `users` table. The local
  356. # user should appear with their profile name.
  357. self._purge_and_rebuild_user_dir()
  358. users = self.get_success(self.user_dir_helper.get_profiles_in_user_directory())
  359. self.assertEqual(
  360. users, {user: ProfileInfo(display_name="aaaa", avatar_url=None)}
  361. )
  362. class UserDirectoryStoreTestCase(HomeserverTestCase):
  363. use_icu = False
  364. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  365. self.store = hs.get_datastores().main
  366. # alice and bob are both in !room_id. bobby is not but shares
  367. # a homeserver with alice.
  368. self.get_success(self.store.update_profile_in_user_dir(ALICE, "alice", None))
  369. self.get_success(self.store.update_profile_in_user_dir(BOB, "bob", None))
  370. self.get_success(self.store.update_profile_in_user_dir(BOBBY, "bobby", None))
  371. self.get_success(self.store.update_profile_in_user_dir(BELA, "Bela", None))
  372. self.get_success(self.store.add_users_in_public_rooms("!room:id", (ALICE, BOB)))
  373. self._restore_use_icu = user_directory.USE_ICU
  374. user_directory.USE_ICU = self.use_icu
  375. def tearDown(self) -> None:
  376. user_directory.USE_ICU = self._restore_use_icu
  377. def test_search_user_dir(self) -> None:
  378. # normally when alice searches the directory she should just find
  379. # bob because bobby doesn't share a room with her.
  380. r = self.get_success(self.store.search_user_dir(ALICE, "bob", 10))
  381. self.assertFalse(r["limited"])
  382. self.assertEqual(1, len(r["results"]))
  383. self.assertDictEqual(
  384. r["results"][0], {"user_id": BOB, "display_name": "bob", "avatar_url": None}
  385. )
  386. @override_config({"user_directory": {"search_all_users": True}})
  387. def test_search_user_dir_all_users(self) -> None:
  388. r = self.get_success(self.store.search_user_dir(ALICE, "bob", 10))
  389. self.assertFalse(r["limited"])
  390. self.assertEqual(2, len(r["results"]))
  391. self.assertDictEqual(
  392. r["results"][0],
  393. {"user_id": BOB, "display_name": "bob", "avatar_url": None},
  394. )
  395. self.assertDictEqual(
  396. r["results"][1],
  397. {"user_id": BOBBY, "display_name": "bobby", "avatar_url": None},
  398. )
  399. @override_config({"user_directory": {"search_all_users": True}})
  400. def test_search_user_limit_correct(self) -> None:
  401. r = self.get_success(self.store.search_user_dir(ALICE, "bob", 1))
  402. self.assertTrue(r["limited"])
  403. self.assertEqual(1, len(r["results"]))
  404. @override_config({"user_directory": {"search_all_users": True}})
  405. def test_search_user_dir_stop_words(self) -> None:
  406. """Tests that a user can look up another user by searching for the start if its
  407. display name even if that name happens to be a common English word that would
  408. usually be ignored in full text searches.
  409. """
  410. r = self.get_success(self.store.search_user_dir(ALICE, "be", 10))
  411. self.assertFalse(r["limited"])
  412. self.assertEqual(1, len(r["results"]))
  413. self.assertDictEqual(
  414. r["results"][0],
  415. {"user_id": BELA, "display_name": "Bela", "avatar_url": None},
  416. )
  417. @override_config({"user_directory": {"search_all_users": True}})
  418. def test_search_user_dir_start_of_user_id(self) -> None:
  419. """Tests that a user can look up another user by searching for the start
  420. of their user ID.
  421. """
  422. r = self.get_success(self.store.search_user_dir(ALICE, "somenickname:exa", 10))
  423. self.assertFalse(r["limited"])
  424. self.assertEqual(1, len(r["results"]))
  425. self.assertDictEqual(
  426. r["results"][0],
  427. {"user_id": BELA, "display_name": "Bela", "avatar_url": None},
  428. )
  429. @override_config({"user_directory": {"search_all_users": True}})
  430. def test_search_user_dir_ascii_case_insensitivity(self) -> None:
  431. """Tests that a user can look up another user by searching for their name in a
  432. different case.
  433. """
  434. CHARLIE = "@someuser:example.org"
  435. self.get_success(
  436. self.store.update_profile_in_user_dir(CHARLIE, "Charlie", None)
  437. )
  438. r = self.get_success(self.store.search_user_dir(ALICE, "cHARLIE", 10))
  439. self.assertFalse(r["limited"])
  440. self.assertEqual(1, len(r["results"]))
  441. self.assertDictEqual(
  442. r["results"][0],
  443. {"user_id": CHARLIE, "display_name": "Charlie", "avatar_url": None},
  444. )
  445. @override_config({"user_directory": {"search_all_users": True}})
  446. def test_search_user_dir_unicode_case_insensitivity(self) -> None:
  447. """Tests that a user can look up another user by searching for their name in a
  448. different case.
  449. """
  450. IVAN = "@someuser:example.org"
  451. self.get_success(self.store.update_profile_in_user_dir(IVAN, "Иван", None))
  452. r = self.get_success(self.store.search_user_dir(ALICE, "иВАН", 10))
  453. self.assertFalse(r["limited"])
  454. self.assertEqual(1, len(r["results"]))
  455. self.assertDictEqual(
  456. r["results"][0],
  457. {"user_id": IVAN, "display_name": "Иван", "avatar_url": None},
  458. )
  459. @override_config({"user_directory": {"search_all_users": True}})
  460. def test_search_user_dir_dotted_dotless_i_case_insensitivity(self) -> None:
  461. """Tests that a user can look up another user by searching for their name in a
  462. different case, when their name contains dotted or dotless "i"s.
  463. Some languages have dotted and dotless versions of "i", which are considered to
  464. be different letters: i <-> İ, ı <-> I. To make things difficult, they reuse the
  465. ASCII "i" and "I" code points, despite having different lowercase / uppercase
  466. forms.
  467. """
  468. USER = "@someuser:example.org"
  469. expected_matches = [
  470. # (search_term, display_name)
  471. # A search for "i" should match "İ".
  472. ("iiiii", "İİİİİ"),
  473. # A search for "I" should match "ı".
  474. ("IIIII", "ııııı"),
  475. # A search for "ı" should match "I".
  476. ("ııııı", "IIIII"),
  477. # A search for "İ" should match "i".
  478. ("İİİİİ", "iiiii"),
  479. ]
  480. for search_term, display_name in expected_matches:
  481. self.get_success(
  482. self.store.update_profile_in_user_dir(USER, display_name, None)
  483. )
  484. r = self.get_success(self.store.search_user_dir(ALICE, search_term, 10))
  485. self.assertFalse(r["limited"])
  486. self.assertEqual(
  487. 1,
  488. len(r["results"]),
  489. f"searching for {search_term!r} did not match {display_name!r}",
  490. )
  491. self.assertDictEqual(
  492. r["results"][0],
  493. {"user_id": USER, "display_name": display_name, "avatar_url": None},
  494. )
  495. # We don't test for negative matches, to allow implementations that consider all
  496. # the i variants to be the same.
  497. test_search_user_dir_dotted_dotless_i_case_insensitivity.skip = "not supported" # type: ignore
  498. @override_config({"user_directory": {"search_all_users": True}})
  499. def test_search_user_dir_unicode_normalization(self) -> None:
  500. """Tests that a user can look up another user by searching for their name with
  501. either composed or decomposed accents.
  502. """
  503. AMELIE = "@someuser:example.org"
  504. expected_matches = [
  505. # (search_term, display_name)
  506. ("Ame\u0301lie", "Amélie"),
  507. ("Amélie", "Ame\u0301lie"),
  508. ]
  509. for search_term, display_name in expected_matches:
  510. self.get_success(
  511. self.store.update_profile_in_user_dir(AMELIE, display_name, None)
  512. )
  513. r = self.get_success(self.store.search_user_dir(ALICE, search_term, 10))
  514. self.assertFalse(r["limited"])
  515. self.assertEqual(
  516. 1,
  517. len(r["results"]),
  518. f"searching for {search_term!r} did not match {display_name!r}",
  519. )
  520. self.assertDictEqual(
  521. r["results"][0],
  522. {"user_id": AMELIE, "display_name": display_name, "avatar_url": None},
  523. )
  524. @override_config({"user_directory": {"search_all_users": True}})
  525. def test_search_user_dir_accent_insensitivity(self) -> None:
  526. """Tests that a user can look up another user by searching for their name
  527. without any accents.
  528. """
  529. AMELIE = "@someuser:example.org"
  530. self.get_success(self.store.update_profile_in_user_dir(AMELIE, "Amélie", None))
  531. r = self.get_success(self.store.search_user_dir(ALICE, "amelie", 10))
  532. self.assertFalse(r["limited"])
  533. self.assertEqual(1, len(r["results"]))
  534. self.assertDictEqual(
  535. r["results"][0],
  536. {"user_id": AMELIE, "display_name": "Amélie", "avatar_url": None},
  537. )
  538. # It may be desirable for "é"s in search terms to not match plain "e"s and we
  539. # really don't want "é"s in search terms to match "e"s with different accents.
  540. # But we don't test for this to allow implementations that consider all
  541. # "e"-lookalikes to be the same.
  542. test_search_user_dir_accent_insensitivity.skip = "not supported yet" # type: ignore
  543. class UserDirectoryStoreTestCaseWithIcu(UserDirectoryStoreTestCase):
  544. use_icu = True
  545. if not icu:
  546. skip = "Requires PyICU"
  547. class UserDirectoryICUTestCase(HomeserverTestCase):
  548. if not icu:
  549. skip = "Requires PyICU"
  550. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  551. self.store = hs.get_datastores().main
  552. self.user_dir_helper = GetUserDirectoryTables(self.store)
  553. def test_icu_word_boundary(self) -> None:
  554. """Tests that we correctly detect word boundaries when ICU (International
  555. Components for Unicode) support is available.
  556. """
  557. display_name = "Gáo"
  558. # This word is not broken down correctly by Python's regular expressions,
  559. # likely because á is actually a lowercase a followed by a U+0301 combining
  560. # acute accent. This is specifically something that ICU support fixes.
  561. matches = re.findall(r"([\w\-]+)", display_name, re.UNICODE)
  562. self.assertEqual(len(matches), 2)
  563. self.get_success(
  564. self.store.update_profile_in_user_dir(ALICE, display_name, None)
  565. )
  566. self.get_success(self.store.add_users_in_public_rooms("!room:id", (ALICE,)))
  567. # Check that searching for this user yields the correct result.
  568. r = self.get_success(self.store.search_user_dir(BOB, display_name, 10))
  569. self.assertFalse(r["limited"])
  570. self.assertEqual(len(r["results"]), 1)
  571. self.assertDictEqual(
  572. r["results"][0],
  573. {"user_id": ALICE, "display_name": display_name, "avatar_url": None},
  574. )
  575. def test_icu_word_boundary_punctuation(self) -> None:
  576. """
  577. Tests the behaviour of punctuation with the ICU tokeniser.
  578. Seems to depend on underlying version of ICU.
  579. """
  580. # Note: either tokenisation is fine, because Postgres actually splits
  581. # words itself afterwards.
  582. self.assertIn(
  583. _parse_words_with_icu("lazy'fox jumped:over the.dog"),
  584. (
  585. # ICU 66 on Ubuntu 20.04
  586. ["lazy'fox", "jumped", "over", "the", "dog"],
  587. # ICU 70 on Ubuntu 22.04
  588. ["lazy'fox", "jumped:over", "the.dog"],
  589. # pyicu 2.10.2 on Alpine edge / macOS
  590. ["lazy'fox", "jumped", "over", "the.dog"],
  591. ),
  592. )
  593. def test_regex_word_boundary_punctuation(self) -> None:
  594. """
  595. Tests the behaviour of punctuation with the non-ICU tokeniser
  596. """
  597. self.assertEqual(
  598. _parse_words_with_regex("lazy'fox jumped:over the.dog"),
  599. ["lazy", "fox", "jumped", "over", "the", "dog"],
  600. )