test_presence_router.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. # Copyright 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. from typing import Dict, Iterable, List, Optional, Set, Tuple, Union
  15. from unittest.mock import Mock
  16. import attr
  17. from synapse.api.constants import EduTypes
  18. from synapse.events.presence_router import PresenceRouter, load_legacy_presence_router
  19. from synapse.federation.units import Transaction
  20. from synapse.handlers.presence import UserPresenceState
  21. from synapse.module_api import ModuleApi
  22. from synapse.rest import admin
  23. from synapse.rest.client import login, presence, room
  24. from synapse.types import JsonDict, StreamToken, create_requester
  25. from tests.handlers.test_sync import generate_sync_config
  26. from tests.test_utils import simple_async_mock
  27. from tests.unittest import FederatingHomeserverTestCase, TestCase, override_config
  28. @attr.s
  29. class PresenceRouterTestConfig:
  30. users_who_should_receive_all_presence = attr.ib(type=List[str], default=[])
  31. class LegacyPresenceRouterTestModule:
  32. def __init__(self, config: PresenceRouterTestConfig, module_api: ModuleApi):
  33. self._config = config
  34. self._module_api = module_api
  35. async def get_users_for_states(
  36. self, state_updates: Iterable[UserPresenceState]
  37. ) -> Dict[str, Set[UserPresenceState]]:
  38. users_to_state = {
  39. user_id: set(state_updates)
  40. for user_id in self._config.users_who_should_receive_all_presence
  41. }
  42. return users_to_state
  43. async def get_interested_users(
  44. self, user_id: str
  45. ) -> Union[Set[str], PresenceRouter.ALL_USERS]:
  46. if user_id in self._config.users_who_should_receive_all_presence:
  47. return PresenceRouter.ALL_USERS
  48. return set()
  49. @staticmethod
  50. def parse_config(config_dict: dict) -> PresenceRouterTestConfig:
  51. """Parse a configuration dictionary from the homeserver config, do
  52. some validation and return a typed PresenceRouterConfig.
  53. Args:
  54. config_dict: The configuration dictionary.
  55. Returns:
  56. A validated config object.
  57. """
  58. # Initialise a typed config object
  59. config = PresenceRouterTestConfig()
  60. config.users_who_should_receive_all_presence = config_dict.get(
  61. "users_who_should_receive_all_presence"
  62. )
  63. return config
  64. class PresenceRouterTestModule:
  65. def __init__(self, config: PresenceRouterTestConfig, api: ModuleApi):
  66. self._config = config
  67. self._module_api = api
  68. api.register_presence_router_callbacks(
  69. get_users_for_states=self.get_users_for_states,
  70. get_interested_users=self.get_interested_users,
  71. )
  72. async def get_users_for_states(
  73. self, state_updates: Iterable[UserPresenceState]
  74. ) -> Dict[str, Set[UserPresenceState]]:
  75. users_to_state = {
  76. user_id: set(state_updates)
  77. for user_id in self._config.users_who_should_receive_all_presence
  78. }
  79. return users_to_state
  80. async def get_interested_users(
  81. self, user_id: str
  82. ) -> Union[Set[str], PresenceRouter.ALL_USERS]:
  83. if user_id in self._config.users_who_should_receive_all_presence:
  84. return PresenceRouter.ALL_USERS
  85. return set()
  86. @staticmethod
  87. def parse_config(config_dict: dict) -> PresenceRouterTestConfig:
  88. """Parse a configuration dictionary from the homeserver config, do
  89. some validation and return a typed PresenceRouterConfig.
  90. Args:
  91. config_dict: The configuration dictionary.
  92. Returns:
  93. A validated config object.
  94. """
  95. # Initialise a typed config object
  96. config = PresenceRouterTestConfig()
  97. config.users_who_should_receive_all_presence = config_dict.get(
  98. "users_who_should_receive_all_presence"
  99. )
  100. return config
  101. class PresenceRouterTestCase(FederatingHomeserverTestCase):
  102. """
  103. Test cases using a custom PresenceRouter
  104. By default in test cases, federation sending is disabled. This class re-enables it
  105. for the main process by setting `federation_sender_instances` to None.
  106. """
  107. servlets = [
  108. admin.register_servlets,
  109. login.register_servlets,
  110. room.register_servlets,
  111. presence.register_servlets,
  112. ]
  113. def make_homeserver(self, reactor, clock):
  114. # Mock out the calls over federation.
  115. fed_transport_client = Mock(spec=["send_transaction"])
  116. fed_transport_client.send_transaction = simple_async_mock({})
  117. hs = self.setup_test_homeserver(
  118. federation_transport_client=fed_transport_client,
  119. )
  120. load_legacy_presence_router(hs)
  121. return hs
  122. def prepare(self, reactor, clock, homeserver):
  123. self.sync_handler = self.hs.get_sync_handler()
  124. self.module_api = homeserver.get_module_api()
  125. def default_config(self) -> JsonDict:
  126. config = super().default_config()
  127. config["federation_sender_instances"] = None
  128. return config
  129. @override_config(
  130. {
  131. "presence": {
  132. "presence_router": {
  133. "module": __name__ + ".LegacyPresenceRouterTestModule",
  134. "config": {
  135. "users_who_should_receive_all_presence": [
  136. "@presence_gobbler:test",
  137. ]
  138. },
  139. }
  140. },
  141. }
  142. )
  143. def test_receiving_all_presence_legacy(self):
  144. self.receiving_all_presence_test_body()
  145. @override_config(
  146. {
  147. "modules": [
  148. {
  149. "module": __name__ + ".PresenceRouterTestModule",
  150. "config": {
  151. "users_who_should_receive_all_presence": [
  152. "@presence_gobbler:test",
  153. ]
  154. },
  155. },
  156. ],
  157. }
  158. )
  159. def test_receiving_all_presence(self):
  160. self.receiving_all_presence_test_body()
  161. def receiving_all_presence_test_body(self):
  162. """Test that a user that does not share a room with another other can receive
  163. presence for them, due to presence routing.
  164. """
  165. # Create a user who should receive all presence of others
  166. self.presence_receiving_user_id = self.register_user(
  167. "presence_gobbler", "monkey"
  168. )
  169. self.presence_receiving_user_tok = self.login("presence_gobbler", "monkey")
  170. # And two users who should not have any special routing
  171. self.other_user_one_id = self.register_user("other_user_one", "monkey")
  172. self.other_user_one_tok = self.login("other_user_one", "monkey")
  173. self.other_user_two_id = self.register_user("other_user_two", "monkey")
  174. self.other_user_two_tok = self.login("other_user_two", "monkey")
  175. # Put the other two users in a room with each other
  176. room_id = self.helper.create_room_as(
  177. self.other_user_one_id, tok=self.other_user_one_tok
  178. )
  179. self.helper.invite(
  180. room_id,
  181. self.other_user_one_id,
  182. self.other_user_two_id,
  183. tok=self.other_user_one_tok,
  184. )
  185. self.helper.join(room_id, self.other_user_two_id, tok=self.other_user_two_tok)
  186. # User one sends some presence
  187. send_presence_update(
  188. self,
  189. self.other_user_one_id,
  190. self.other_user_one_tok,
  191. "online",
  192. "boop",
  193. )
  194. # Check that the presence receiving user gets user one's presence when syncing
  195. presence_updates, sync_token = sync_presence(
  196. self, self.presence_receiving_user_id
  197. )
  198. self.assertEqual(len(presence_updates), 1)
  199. presence_update: UserPresenceState = presence_updates[0]
  200. self.assertEqual(presence_update.user_id, self.other_user_one_id)
  201. self.assertEqual(presence_update.state, "online")
  202. self.assertEqual(presence_update.status_msg, "boop")
  203. # Have all three users send presence
  204. send_presence_update(
  205. self,
  206. self.other_user_one_id,
  207. self.other_user_one_tok,
  208. "online",
  209. "user_one",
  210. )
  211. send_presence_update(
  212. self,
  213. self.other_user_two_id,
  214. self.other_user_two_tok,
  215. "online",
  216. "user_two",
  217. )
  218. send_presence_update(
  219. self,
  220. self.presence_receiving_user_id,
  221. self.presence_receiving_user_tok,
  222. "online",
  223. "presence_gobbler",
  224. )
  225. # Check that the presence receiving user gets everyone's presence
  226. presence_updates, _ = sync_presence(
  227. self, self.presence_receiving_user_id, sync_token
  228. )
  229. self.assertEqual(len(presence_updates), 3)
  230. # But that User One only get itself and User Two's presence
  231. presence_updates, _ = sync_presence(self, self.other_user_one_id)
  232. self.assertEqual(len(presence_updates), 2)
  233. found = False
  234. for update in presence_updates:
  235. if update.user_id == self.other_user_two_id:
  236. self.assertEqual(update.state, "online")
  237. self.assertEqual(update.status_msg, "user_two")
  238. found = True
  239. self.assertTrue(found)
  240. @override_config(
  241. {
  242. "presence": {
  243. "presence_router": {
  244. "module": __name__ + ".LegacyPresenceRouterTestModule",
  245. "config": {
  246. "users_who_should_receive_all_presence": [
  247. "@presence_gobbler1:test",
  248. "@presence_gobbler2:test",
  249. "@far_away_person:island",
  250. ]
  251. },
  252. }
  253. },
  254. }
  255. )
  256. def test_send_local_online_presence_to_with_module_legacy(self):
  257. self.send_local_online_presence_to_with_module_test_body()
  258. @override_config(
  259. {
  260. "modules": [
  261. {
  262. "module": __name__ + ".PresenceRouterTestModule",
  263. "config": {
  264. "users_who_should_receive_all_presence": [
  265. "@presence_gobbler1:test",
  266. "@presence_gobbler2:test",
  267. "@far_away_person:island",
  268. ]
  269. },
  270. },
  271. ],
  272. }
  273. )
  274. def test_send_local_online_presence_to_with_module(self):
  275. self.send_local_online_presence_to_with_module_test_body()
  276. def send_local_online_presence_to_with_module_test_body(self):
  277. """Tests that send_local_presence_to_users sends local online presence to a set
  278. of specified local and remote users, with a custom PresenceRouter module enabled.
  279. """
  280. # Create a user who will send presence updates
  281. self.other_user_id = self.register_user("other_user", "monkey")
  282. self.other_user_tok = self.login("other_user", "monkey")
  283. # And another two users that will also send out presence updates, as well as receive
  284. # theirs and everyone else's
  285. self.presence_receiving_user_one_id = self.register_user(
  286. "presence_gobbler1", "monkey"
  287. )
  288. self.presence_receiving_user_one_tok = self.login("presence_gobbler1", "monkey")
  289. self.presence_receiving_user_two_id = self.register_user(
  290. "presence_gobbler2", "monkey"
  291. )
  292. self.presence_receiving_user_two_tok = self.login("presence_gobbler2", "monkey")
  293. # Have all three users send some presence updates
  294. send_presence_update(
  295. self,
  296. self.other_user_id,
  297. self.other_user_tok,
  298. "online",
  299. "I'm online!",
  300. )
  301. send_presence_update(
  302. self,
  303. self.presence_receiving_user_one_id,
  304. self.presence_receiving_user_one_tok,
  305. "online",
  306. "I'm also online!",
  307. )
  308. send_presence_update(
  309. self,
  310. self.presence_receiving_user_two_id,
  311. self.presence_receiving_user_two_tok,
  312. "unavailable",
  313. "I'm in a meeting!",
  314. )
  315. # Mark each presence-receiving user for receiving all user presence
  316. self.get_success(
  317. self.module_api.send_local_online_presence_to(
  318. [
  319. self.presence_receiving_user_one_id,
  320. self.presence_receiving_user_two_id,
  321. ]
  322. )
  323. )
  324. # Perform a sync for each user
  325. # The other user should only receive their own presence
  326. presence_updates, _ = sync_presence(self, self.other_user_id)
  327. self.assertEqual(len(presence_updates), 1)
  328. presence_update: UserPresenceState = presence_updates[0]
  329. self.assertEqual(presence_update.user_id, self.other_user_id)
  330. self.assertEqual(presence_update.state, "online")
  331. self.assertEqual(presence_update.status_msg, "I'm online!")
  332. # Whereas both presence receiving users should receive everyone's presence updates
  333. presence_updates, _ = sync_presence(self, self.presence_receiving_user_one_id)
  334. self.assertEqual(len(presence_updates), 3)
  335. presence_updates, _ = sync_presence(self, self.presence_receiving_user_two_id)
  336. self.assertEqual(len(presence_updates), 3)
  337. # We stagger sending of presence, so we need to wait a bit for them to
  338. # get sent out.
  339. self.reactor.advance(60)
  340. # Test that sending to a remote user works
  341. remote_user_id = "@far_away_person:island"
  342. # Note that due to the remote user being in our module's
  343. # users_who_should_receive_all_presence config, they would have
  344. # received user presence updates already.
  345. #
  346. # Thus we reset the mock, and try sending all online local user
  347. # presence again
  348. self.hs.get_federation_transport_client().send_transaction.reset_mock()
  349. # Broadcast local user online presence
  350. self.get_success(
  351. self.module_api.send_local_online_presence_to([remote_user_id])
  352. )
  353. # We stagger sending of presence, so we need to wait a bit for them to
  354. # get sent out.
  355. self.reactor.advance(60)
  356. # Check that the expected presence updates were sent
  357. # We explicitly compare using sets as we expect that calling
  358. # module_api.send_local_online_presence_to will create a presence
  359. # update that is a duplicate of the specified user's current presence.
  360. # These are sent to clients and will be picked up below, thus we use a
  361. # set to deduplicate. We're just interested that non-offline updates were
  362. # sent out for each user ID.
  363. expected_users = {
  364. self.other_user_id,
  365. self.presence_receiving_user_one_id,
  366. self.presence_receiving_user_two_id,
  367. }
  368. found_users = set()
  369. calls = (
  370. self.hs.get_federation_transport_client().send_transaction.call_args_list
  371. )
  372. for call in calls:
  373. call_args = call[0]
  374. federation_transaction: Transaction = call_args[0]
  375. # Get the sent EDUs in this transaction
  376. edus = federation_transaction.get_dict()["edus"]
  377. for edu in edus:
  378. # Make sure we're only checking presence-type EDUs
  379. if edu["edu_type"] != EduTypes.PRESENCE:
  380. continue
  381. # EDUs can contain multiple presence updates
  382. for presence_update in edu["content"]["push"]:
  383. # Check for presence updates that contain the user IDs we're after
  384. found_users.add(presence_update["user_id"])
  385. # Ensure that no offline states are being sent out
  386. self.assertNotEqual(presence_update["presence"], "offline")
  387. self.assertEqual(found_users, expected_users)
  388. def send_presence_update(
  389. testcase: TestCase,
  390. user_id: str,
  391. access_token: str,
  392. presence_state: str,
  393. status_message: Optional[str] = None,
  394. ) -> JsonDict:
  395. # Build the presence body
  396. body = {"presence": presence_state}
  397. if status_message:
  398. body["status_msg"] = status_message
  399. # Update the user's presence state
  400. channel = testcase.make_request(
  401. "PUT", "/presence/%s/status" % (user_id,), body, access_token=access_token
  402. )
  403. testcase.assertEqual(channel.code, 200)
  404. return channel.json_body
  405. def sync_presence(
  406. testcase: TestCase,
  407. user_id: str,
  408. since_token: Optional[StreamToken] = None,
  409. ) -> Tuple[List[UserPresenceState], StreamToken]:
  410. """Perform a sync request for the given user and return the user presence updates
  411. they've received, as well as the next_batch token.
  412. This method assumes testcase.sync_handler points to the homeserver's sync handler.
  413. Args:
  414. testcase: The testcase that is currently being run.
  415. user_id: The ID of the user to generate a sync response for.
  416. since_token: An optional token to indicate from at what point to sync from.
  417. Returns:
  418. A tuple containing a list of presence updates, and the sync response's
  419. next_batch token.
  420. """
  421. requester = create_requester(user_id)
  422. sync_config = generate_sync_config(requester.user.to_string())
  423. sync_result = testcase.get_success(
  424. testcase.sync_handler.wait_for_sync_for_user(
  425. requester, sync_config, since_token
  426. )
  427. )
  428. return sync_result.presence, sync_result.next_batch