test_api.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. # Copyright 2020 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 unittest.mock import Mock
  15. from twisted.internet import defer
  16. from synapse.api.constants import EduTypes
  17. from synapse.events import EventBase
  18. from synapse.federation.units import Transaction
  19. from synapse.handlers.presence import UserPresenceState
  20. from synapse.rest import admin
  21. from synapse.rest.client import login, presence, room
  22. from synapse.types import create_requester
  23. from tests.events.test_presence_router import send_presence_update, sync_presence
  24. from tests.replication._base import BaseMultiWorkerStreamTestCase
  25. from tests.test_utils.event_injection import inject_member_event
  26. from tests.unittest import HomeserverTestCase, override_config
  27. from tests.utils import USE_POSTGRES_FOR_TESTS
  28. class ModuleApiTestCase(HomeserverTestCase):
  29. servlets = [
  30. admin.register_servlets,
  31. login.register_servlets,
  32. room.register_servlets,
  33. presence.register_servlets,
  34. ]
  35. def prepare(self, reactor, clock, homeserver):
  36. self.store = homeserver.get_datastore()
  37. self.module_api = homeserver.get_module_api()
  38. self.event_creation_handler = homeserver.get_event_creation_handler()
  39. self.sync_handler = homeserver.get_sync_handler()
  40. def make_homeserver(self, reactor, clock):
  41. return self.setup_test_homeserver(
  42. federation_transport_client=Mock(spec=["send_transaction"]),
  43. )
  44. def test_can_register_user(self):
  45. """Tests that an external module can register a user"""
  46. # Register a new user
  47. user_id, access_token = self.get_success(
  48. self.module_api.register(
  49. "bob", displayname="Bobberino", emails=["bob@bobinator.bob"]
  50. )
  51. )
  52. # Check that the new user exists with all provided attributes
  53. self.assertEqual(user_id, "@bob:test")
  54. self.assertTrue(access_token)
  55. self.assertTrue(self.get_success(self.store.get_user_by_id(user_id)))
  56. # Check that the email was assigned
  57. emails = self.get_success(self.store.user_get_threepids(user_id))
  58. self.assertEqual(len(emails), 1)
  59. email = emails[0]
  60. self.assertEqual(email["medium"], "email")
  61. self.assertEqual(email["address"], "bob@bobinator.bob")
  62. # Should these be 0?
  63. self.assertEqual(email["validated_at"], 0)
  64. self.assertEqual(email["added_at"], 0)
  65. # Check that the displayname was assigned
  66. displayname = self.get_success(self.store.get_profile_displayname("bob"))
  67. self.assertEqual(displayname, "Bobberino")
  68. def test_get_userinfo_by_id(self):
  69. user_id = self.register_user("alice", "1234")
  70. found_user = self.get_success(self.module_api.get_userinfo_by_id(user_id))
  71. self.assertEqual(found_user.user_id.to_string(), user_id)
  72. self.assertIdentical(found_user.is_admin, False)
  73. def test_get_userinfo_by_id__no_user_found(self):
  74. found_user = self.get_success(self.module_api.get_userinfo_by_id("@alice:test"))
  75. self.assertIsNone(found_user)
  76. def test_sending_events_into_room(self):
  77. """Tests that a module can send events into a room"""
  78. # Mock out create_and_send_nonmember_event to check whether events are being sent
  79. self.event_creation_handler.create_and_send_nonmember_event = Mock(
  80. spec=[],
  81. side_effect=self.event_creation_handler.create_and_send_nonmember_event,
  82. )
  83. # Create a user and room to play with
  84. user_id = self.register_user("summer", "monkey")
  85. tok = self.login("summer", "monkey")
  86. room_id = self.helper.create_room_as(user_id, tok=tok)
  87. # Create and send a non-state event
  88. content = {"body": "I am a puppet", "msgtype": "m.text"}
  89. event_dict = {
  90. "room_id": room_id,
  91. "type": "m.room.message",
  92. "content": content,
  93. "sender": user_id,
  94. }
  95. event: EventBase = self.get_success(
  96. self.module_api.create_and_send_event_into_room(event_dict)
  97. )
  98. self.assertEqual(event.sender, user_id)
  99. self.assertEqual(event.type, "m.room.message")
  100. self.assertEqual(event.room_id, room_id)
  101. self.assertFalse(hasattr(event, "state_key"))
  102. self.assertDictEqual(event.content, content)
  103. expected_requester = create_requester(
  104. user_id, authenticated_entity=self.hs.hostname
  105. )
  106. # Check that the event was sent
  107. self.event_creation_handler.create_and_send_nonmember_event.assert_called_with(
  108. expected_requester,
  109. event_dict,
  110. ratelimit=False,
  111. ignore_shadow_ban=True,
  112. )
  113. # Create and send a state event
  114. content = {
  115. "events_default": 0,
  116. "users": {user_id: 100},
  117. "state_default": 50,
  118. "users_default": 0,
  119. "events": {"test.event.type": 25},
  120. }
  121. event_dict = {
  122. "room_id": room_id,
  123. "type": "m.room.power_levels",
  124. "content": content,
  125. "sender": user_id,
  126. "state_key": "",
  127. }
  128. event: EventBase = self.get_success(
  129. self.module_api.create_and_send_event_into_room(event_dict)
  130. )
  131. self.assertEqual(event.sender, user_id)
  132. self.assertEqual(event.type, "m.room.power_levels")
  133. self.assertEqual(event.room_id, room_id)
  134. self.assertEqual(event.state_key, "")
  135. self.assertDictEqual(event.content, content)
  136. # Check that the event was sent
  137. self.event_creation_handler.create_and_send_nonmember_event.assert_called_with(
  138. expected_requester,
  139. {
  140. "type": "m.room.power_levels",
  141. "content": content,
  142. "room_id": room_id,
  143. "sender": user_id,
  144. "state_key": "",
  145. },
  146. ratelimit=False,
  147. ignore_shadow_ban=True,
  148. )
  149. # Check that we can't send membership events
  150. content = {
  151. "membership": "leave",
  152. }
  153. event_dict = {
  154. "room_id": room_id,
  155. "type": "m.room.member",
  156. "content": content,
  157. "sender": user_id,
  158. "state_key": user_id,
  159. }
  160. self.get_failure(
  161. self.module_api.create_and_send_event_into_room(event_dict), Exception
  162. )
  163. def test_public_rooms(self):
  164. """Tests that a room can be added and removed from the public rooms list,
  165. as well as have its public rooms directory state queried.
  166. """
  167. # Create a user and room to play with
  168. user_id = self.register_user("kermit", "monkey")
  169. tok = self.login("kermit", "monkey")
  170. room_id = self.helper.create_room_as(user_id, tok=tok)
  171. # The room should not currently be in the public rooms directory
  172. is_in_public_rooms = self.get_success(
  173. self.module_api.public_room_list_manager.room_is_in_public_room_list(
  174. room_id
  175. )
  176. )
  177. self.assertFalse(is_in_public_rooms)
  178. # Let's try adding it to the public rooms directory
  179. self.get_success(
  180. self.module_api.public_room_list_manager.add_room_to_public_room_list(
  181. room_id
  182. )
  183. )
  184. # And checking whether it's in there...
  185. is_in_public_rooms = self.get_success(
  186. self.module_api.public_room_list_manager.room_is_in_public_room_list(
  187. room_id
  188. )
  189. )
  190. self.assertTrue(is_in_public_rooms)
  191. # Let's remove it again
  192. self.get_success(
  193. self.module_api.public_room_list_manager.remove_room_from_public_room_list(
  194. room_id
  195. )
  196. )
  197. # Should be gone
  198. is_in_public_rooms = self.get_success(
  199. self.module_api.public_room_list_manager.room_is_in_public_room_list(
  200. room_id
  201. )
  202. )
  203. self.assertFalse(is_in_public_rooms)
  204. def test_send_local_online_presence_to(self):
  205. # Test sending local online presence to users from the main process
  206. _test_sending_local_online_presence_to_local_user(self, test_with_workers=False)
  207. @override_config({"send_federation": True})
  208. def test_send_local_online_presence_to_federation(self):
  209. """Tests that send_local_presence_to_users sends local online presence to remote users."""
  210. # Create a user who will send presence updates
  211. self.presence_sender_id = self.register_user("presence_sender1", "monkey")
  212. self.presence_sender_tok = self.login("presence_sender1", "monkey")
  213. # And a room they're a part of
  214. room_id = self.helper.create_room_as(
  215. self.presence_sender_id,
  216. tok=self.presence_sender_tok,
  217. )
  218. # Mark them as online
  219. send_presence_update(
  220. self,
  221. self.presence_sender_id,
  222. self.presence_sender_tok,
  223. "online",
  224. "I'm online!",
  225. )
  226. # Make up a remote user to send presence to
  227. remote_user_id = "@far_away_person:island"
  228. # Create a join membership event for the remote user into the room.
  229. # This allows presence information to flow from one user to the other.
  230. self.get_success(
  231. inject_member_event(
  232. self.hs,
  233. room_id,
  234. sender=remote_user_id,
  235. target=remote_user_id,
  236. membership="join",
  237. )
  238. )
  239. # The remote user would have received the existing room members' presence
  240. # when they joined the room.
  241. #
  242. # Thus we reset the mock, and try sending online local user
  243. # presence again
  244. self.hs.get_federation_transport_client().send_transaction.reset_mock()
  245. # Broadcast local user online presence
  246. self.get_success(
  247. self.module_api.send_local_online_presence_to([remote_user_id])
  248. )
  249. # Check that a presence update was sent as part of a federation transaction
  250. found_update = False
  251. calls = (
  252. self.hs.get_federation_transport_client().send_transaction.call_args_list
  253. )
  254. for call in calls:
  255. call_args = call[0]
  256. federation_transaction: Transaction = call_args[0]
  257. # Get the sent EDUs in this transaction
  258. edus = federation_transaction.get_dict()["edus"]
  259. for edu in edus:
  260. # Make sure we're only checking presence-type EDUs
  261. if edu["edu_type"] != EduTypes.Presence:
  262. continue
  263. # EDUs can contain multiple presence updates
  264. for presence_update in edu["content"]["push"]:
  265. if presence_update["user_id"] == self.presence_sender_id:
  266. found_update = True
  267. self.assertTrue(found_update)
  268. class ModuleApiWorkerTestCase(BaseMultiWorkerStreamTestCase):
  269. """For testing ModuleApi functionality in a multi-worker setup"""
  270. # Testing stream ID replication from the main to worker processes requires postgres
  271. # (due to needing `MultiWriterIdGenerator`).
  272. if not USE_POSTGRES_FOR_TESTS:
  273. skip = "Requires Postgres"
  274. servlets = [
  275. admin.register_servlets,
  276. login.register_servlets,
  277. room.register_servlets,
  278. presence.register_servlets,
  279. ]
  280. def default_config(self):
  281. conf = super().default_config()
  282. conf["redis"] = {"enabled": "true"}
  283. conf["stream_writers"] = {"presence": ["presence_writer"]}
  284. conf["instance_map"] = {
  285. "presence_writer": {"host": "testserv", "port": 1001},
  286. }
  287. return conf
  288. def prepare(self, reactor, clock, homeserver):
  289. self.module_api = homeserver.get_module_api()
  290. self.sync_handler = homeserver.get_sync_handler()
  291. def test_send_local_online_presence_to_workers(self):
  292. # Test sending local online presence to users from a worker process
  293. _test_sending_local_online_presence_to_local_user(self, test_with_workers=True)
  294. def _test_sending_local_online_presence_to_local_user(
  295. test_case: HomeserverTestCase, test_with_workers: bool = False
  296. ):
  297. """Tests that send_local_presence_to_users sends local online presence to local users.
  298. This simultaneously tests two different usecases:
  299. * Testing that this method works when either called from a worker or the main process.
  300. - We test this by calling this method from both a TestCase that runs in monolith mode, and one that
  301. runs with a main and generic_worker.
  302. * Testing that multiple devices syncing simultaneously will all receive a snapshot of local,
  303. online presence - but only once per device.
  304. Args:
  305. test_with_workers: If True, this method will call ModuleApi.send_local_online_presence_to on a
  306. worker process. The test users will still sync with the main process. The purpose of testing
  307. with a worker is to check whether a Synapse module running on a worker can inform other workers/
  308. the main process that they should include additional presence when a user next syncs.
  309. """
  310. if test_with_workers:
  311. # Create a worker process to make module_api calls against
  312. worker_hs = test_case.make_worker_hs(
  313. "synapse.app.generic_worker", {"worker_name": "presence_writer"}
  314. )
  315. # Create a user who will send presence updates
  316. test_case.presence_receiver_id = test_case.register_user(
  317. "presence_receiver1", "monkey"
  318. )
  319. test_case.presence_receiver_tok = test_case.login("presence_receiver1", "monkey")
  320. # And another user that will send presence updates out
  321. test_case.presence_sender_id = test_case.register_user("presence_sender2", "monkey")
  322. test_case.presence_sender_tok = test_case.login("presence_sender2", "monkey")
  323. # Put them in a room together so they will receive each other's presence updates
  324. room_id = test_case.helper.create_room_as(
  325. test_case.presence_receiver_id,
  326. tok=test_case.presence_receiver_tok,
  327. )
  328. test_case.helper.join(
  329. room_id, test_case.presence_sender_id, tok=test_case.presence_sender_tok
  330. )
  331. # Presence sender comes online
  332. send_presence_update(
  333. test_case,
  334. test_case.presence_sender_id,
  335. test_case.presence_sender_tok,
  336. "online",
  337. "I'm online!",
  338. )
  339. # Presence receiver should have received it
  340. presence_updates, sync_token = sync_presence(
  341. test_case, test_case.presence_receiver_id
  342. )
  343. test_case.assertEqual(len(presence_updates), 1)
  344. presence_update: UserPresenceState = presence_updates[0]
  345. test_case.assertEqual(presence_update.user_id, test_case.presence_sender_id)
  346. test_case.assertEqual(presence_update.state, "online")
  347. if test_with_workers:
  348. # Replicate the current sync presence token from the main process to the worker process.
  349. # We need to do this so that the worker process knows the current presence stream ID to
  350. # insert into the database when we call ModuleApi.send_local_online_presence_to.
  351. test_case.replicate()
  352. # Syncing again should result in no presence updates
  353. presence_updates, sync_token = sync_presence(
  354. test_case, test_case.presence_receiver_id, sync_token
  355. )
  356. test_case.assertEqual(len(presence_updates), 0)
  357. # We do an (initial) sync with a second "device" now, getting a new sync token.
  358. # We'll use this in a moment.
  359. _, sync_token_second_device = sync_presence(
  360. test_case, test_case.presence_receiver_id
  361. )
  362. # Determine on which process (main or worker) to call ModuleApi.send_local_online_presence_to on
  363. if test_with_workers:
  364. module_api_to_use = worker_hs.get_module_api()
  365. else:
  366. module_api_to_use = test_case.module_api
  367. # Trigger sending local online presence. We expect this information
  368. # to be saved to the database where all processes can access it.
  369. # Note that we're syncing via the master.
  370. d = module_api_to_use.send_local_online_presence_to(
  371. [
  372. test_case.presence_receiver_id,
  373. ]
  374. )
  375. d = defer.ensureDeferred(d)
  376. if test_with_workers:
  377. # In order for the required presence_set_state replication request to occur between the
  378. # worker and main process, we need to pump the reactor. Otherwise, the coordinator that
  379. # reads the request on the main process won't do so, and the request will time out.
  380. while not d.called:
  381. test_case.reactor.advance(0.1)
  382. test_case.get_success(d)
  383. # The presence receiver should have received online presence again.
  384. presence_updates, sync_token = sync_presence(
  385. test_case, test_case.presence_receiver_id, sync_token
  386. )
  387. test_case.assertEqual(len(presence_updates), 1)
  388. presence_update: UserPresenceState = presence_updates[0]
  389. test_case.assertEqual(presence_update.user_id, test_case.presence_sender_id)
  390. test_case.assertEqual(presence_update.state, "online")
  391. # We attempt to sync with the second sync token we received above - just to check that
  392. # multiple syncing devices will each receive the necessary online presence.
  393. presence_updates, sync_token_second_device = sync_presence(
  394. test_case, test_case.presence_receiver_id, sync_token_second_device
  395. )
  396. test_case.assertEqual(len(presence_updates), 1)
  397. presence_update: UserPresenceState = presence_updates[0]
  398. test_case.assertEqual(presence_update.user_id, test_case.presence_sender_id)
  399. test_case.assertEqual(presence_update.state, "online")
  400. # However, if we now sync with either "device", we won't receive another burst of online presence
  401. # until the API is called again sometime in the future
  402. presence_updates, sync_token = sync_presence(
  403. test_case, test_case.presence_receiver_id, sync_token
  404. )
  405. # Now we check that we don't receive *offline* updates using ModuleApi.send_local_online_presence_to.
  406. # Presence sender goes offline
  407. send_presence_update(
  408. test_case,
  409. test_case.presence_sender_id,
  410. test_case.presence_sender_tok,
  411. "offline",
  412. "I slink back into the darkness.",
  413. )
  414. # Presence receiver should have received the updated, offline state
  415. presence_updates, sync_token = sync_presence(
  416. test_case, test_case.presence_receiver_id, sync_token
  417. )
  418. test_case.assertEqual(len(presence_updates), 1)
  419. # Now trigger sending local online presence.
  420. d = module_api_to_use.send_local_online_presence_to(
  421. [
  422. test_case.presence_receiver_id,
  423. ]
  424. )
  425. d = defer.ensureDeferred(d)
  426. if test_with_workers:
  427. # In order for the required presence_set_state replication request to occur between the
  428. # worker and main process, we need to pump the reactor. Otherwise, the coordinator that
  429. # reads the request on the main process won't do so, and the request will time out.
  430. while not d.called:
  431. test_case.reactor.advance(0.1)
  432. test_case.get_success(d)
  433. # Presence receiver should *not* have received offline state
  434. presence_updates, sync_token = sync_presence(
  435. test_case, test_case.presence_receiver_id, sync_token
  436. )
  437. test_case.assertEqual(len(presence_updates), 0)