test_api.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842
  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, EventTypes
  17. from synapse.events import EventBase
  18. from synapse.federation.units import Transaction
  19. from synapse.handlers.presence import UserPresenceState
  20. from synapse.handlers.push_rules import InvalidRuleException
  21. from synapse.rest import admin
  22. from synapse.rest.client import login, notifications, presence, profile, room
  23. from synapse.types import create_requester
  24. from tests.events.test_presence_router import send_presence_update, sync_presence
  25. from tests.replication._base import BaseMultiWorkerStreamTestCase
  26. from tests.test_utils import simple_async_mock
  27. from tests.test_utils.event_injection import inject_member_event
  28. from tests.unittest import HomeserverTestCase, override_config
  29. from tests.utils import USE_POSTGRES_FOR_TESTS
  30. class ModuleApiTestCase(HomeserverTestCase):
  31. servlets = [
  32. admin.register_servlets,
  33. login.register_servlets,
  34. room.register_servlets,
  35. presence.register_servlets,
  36. profile.register_servlets,
  37. notifications.register_servlets,
  38. ]
  39. def prepare(self, reactor, clock, homeserver):
  40. self.store = homeserver.get_datastores().main
  41. self.module_api = homeserver.get_module_api()
  42. self.event_creation_handler = homeserver.get_event_creation_handler()
  43. self.sync_handler = homeserver.get_sync_handler()
  44. self.auth_handler = homeserver.get_auth_handler()
  45. def make_homeserver(self, reactor, clock):
  46. # Mock out the calls over federation.
  47. fed_transport_client = Mock(spec=["send_transaction"])
  48. fed_transport_client.send_transaction = simple_async_mock({})
  49. return self.setup_test_homeserver(
  50. federation_transport_client=fed_transport_client,
  51. )
  52. def test_can_register_user(self):
  53. """Tests that an external module can register a user"""
  54. # Register a new user
  55. user_id, access_token = self.get_success(
  56. self.module_api.register(
  57. "bob", displayname="Bobberino", emails=["bob@bobinator.bob"]
  58. )
  59. )
  60. # Check that the new user exists with all provided attributes
  61. self.assertEqual(user_id, "@bob:test")
  62. self.assertTrue(access_token)
  63. self.assertTrue(self.get_success(self.store.get_user_by_id(user_id)))
  64. # Check that the email was assigned
  65. emails = self.get_success(self.store.user_get_threepids(user_id))
  66. self.assertEqual(len(emails), 1)
  67. email = emails[0]
  68. self.assertEqual(email["medium"], "email")
  69. self.assertEqual(email["address"], "bob@bobinator.bob")
  70. # Should these be 0?
  71. self.assertEqual(email["validated_at"], 0)
  72. self.assertEqual(email["added_at"], 0)
  73. # Check that the displayname was assigned
  74. displayname = self.get_success(self.store.get_profile_displayname("bob"))
  75. self.assertEqual(displayname, "Bobberino")
  76. def test_can_register_admin_user(self):
  77. user_id = self.register_user(
  78. "bob_module_admin", "1234", displayname="Bobberino Admin", admin=True
  79. )
  80. found_user = self.get_success(self.module_api.get_userinfo_by_id(user_id))
  81. self.assertEqual(found_user.user_id.to_string(), user_id)
  82. self.assertIdentical(found_user.is_admin, True)
  83. def test_can_set_admin(self):
  84. user_id = self.register_user(
  85. "alice_wants_admin",
  86. "1234",
  87. displayname="Alice Powerhungry",
  88. admin=False,
  89. )
  90. self.get_success(self.module_api.set_user_admin(user_id, True))
  91. found_user = self.get_success(self.module_api.get_userinfo_by_id(user_id))
  92. self.assertEqual(found_user.user_id.to_string(), user_id)
  93. self.assertIdentical(found_user.is_admin, True)
  94. def test_get_userinfo_by_id(self):
  95. user_id = self.register_user("alice", "1234")
  96. found_user = self.get_success(self.module_api.get_userinfo_by_id(user_id))
  97. self.assertEqual(found_user.user_id.to_string(), user_id)
  98. self.assertIdentical(found_user.is_admin, False)
  99. def test_get_userinfo_by_id__no_user_found(self):
  100. found_user = self.get_success(self.module_api.get_userinfo_by_id("@alice:test"))
  101. self.assertIsNone(found_user)
  102. def test_get_user_ip_and_agents(self):
  103. user_id = self.register_user("test_get_user_ip_and_agents_user", "1234")
  104. # Initially, we should have no ip/agent for our user.
  105. info = self.get_success(self.module_api.get_user_ip_and_agents(user_id))
  106. self.assertEqual(info, [])
  107. # Insert a first ip, agent. We should be able to retrieve it.
  108. self.get_success(
  109. self.store.insert_client_ip(
  110. user_id, "access_token", "ip_1", "user_agent_1", "device_1", None
  111. )
  112. )
  113. info = self.get_success(self.module_api.get_user_ip_and_agents(user_id))
  114. self.assertEqual(len(info), 1)
  115. last_seen_1 = info[0].last_seen
  116. # Insert a second ip, agent at a later date. We should be able to retrieve it.
  117. last_seen_2 = last_seen_1 + 10000
  118. self.get_success(
  119. self.store.insert_client_ip(
  120. user_id, "access_token", "ip_2", "user_agent_2", "device_2", last_seen_2
  121. )
  122. )
  123. info = self.get_success(self.module_api.get_user_ip_and_agents(user_id))
  124. self.assertEqual(len(info), 2)
  125. ip_1_seen = False
  126. ip_2_seen = False
  127. for i in info:
  128. if i.ip == "ip_1":
  129. ip_1_seen = True
  130. self.assertEqual(i.user_agent, "user_agent_1")
  131. self.assertEqual(i.last_seen, last_seen_1)
  132. elif i.ip == "ip_2":
  133. ip_2_seen = True
  134. self.assertEqual(i.user_agent, "user_agent_2")
  135. self.assertEqual(i.last_seen, last_seen_2)
  136. self.assertTrue(ip_1_seen)
  137. self.assertTrue(ip_2_seen)
  138. # If we fetch from a midpoint between last_seen_1 and last_seen_2,
  139. # we should only find the second ip, agent.
  140. info = self.get_success(
  141. self.module_api.get_user_ip_and_agents(
  142. user_id, (last_seen_1 + last_seen_2) / 2
  143. )
  144. )
  145. self.assertEqual(len(info), 1)
  146. self.assertEqual(info[0].ip, "ip_2")
  147. self.assertEqual(info[0].user_agent, "user_agent_2")
  148. self.assertEqual(info[0].last_seen, last_seen_2)
  149. # If we fetch from a point later than last_seen_2, we shouldn't
  150. # find anything.
  151. info = self.get_success(
  152. self.module_api.get_user_ip_and_agents(user_id, last_seen_2 + 10000)
  153. )
  154. self.assertEqual(info, [])
  155. def test_get_user_ip_and_agents__no_user_found(self):
  156. info = self.get_success(
  157. self.module_api.get_user_ip_and_agents(
  158. "@test_get_user_ip_and_agents_user_nonexistent:example.com"
  159. )
  160. )
  161. self.assertEqual(info, [])
  162. def test_sending_events_into_room(self):
  163. """Tests that a module can send events into a room"""
  164. # Mock out create_and_send_nonmember_event to check whether events are being sent
  165. self.event_creation_handler.create_and_send_nonmember_event = Mock(
  166. spec=[],
  167. side_effect=self.event_creation_handler.create_and_send_nonmember_event,
  168. )
  169. # Create a user and room to play with
  170. user_id = self.register_user("summer", "monkey")
  171. tok = self.login("summer", "monkey")
  172. room_id = self.helper.create_room_as(user_id, tok=tok)
  173. # Create and send a non-state event
  174. content = {"body": "I am a puppet", "msgtype": "m.text"}
  175. event_dict = {
  176. "room_id": room_id,
  177. "type": "m.room.message",
  178. "content": content,
  179. "sender": user_id,
  180. }
  181. event: EventBase = self.get_success(
  182. self.module_api.create_and_send_event_into_room(event_dict)
  183. )
  184. self.assertEqual(event.sender, user_id)
  185. self.assertEqual(event.type, "m.room.message")
  186. self.assertEqual(event.room_id, room_id)
  187. self.assertFalse(hasattr(event, "state_key"))
  188. self.assertDictEqual(event.content, content)
  189. expected_requester = create_requester(
  190. user_id, authenticated_entity=self.hs.hostname
  191. )
  192. # Check that the event was sent
  193. self.event_creation_handler.create_and_send_nonmember_event.assert_called_with(
  194. expected_requester,
  195. event_dict,
  196. ratelimit=False,
  197. ignore_shadow_ban=True,
  198. )
  199. # Create and send a state event
  200. content = {
  201. "events_default": 0,
  202. "users": {user_id: 100},
  203. "state_default": 50,
  204. "users_default": 0,
  205. "events": {"test.event.type": 25},
  206. }
  207. event_dict = {
  208. "room_id": room_id,
  209. "type": "m.room.power_levels",
  210. "content": content,
  211. "sender": user_id,
  212. "state_key": "",
  213. }
  214. event: EventBase = self.get_success(
  215. self.module_api.create_and_send_event_into_room(event_dict)
  216. )
  217. self.assertEqual(event.sender, user_id)
  218. self.assertEqual(event.type, "m.room.power_levels")
  219. self.assertEqual(event.room_id, room_id)
  220. self.assertEqual(event.state_key, "")
  221. self.assertDictEqual(event.content, content)
  222. # Check that the event was sent
  223. self.event_creation_handler.create_and_send_nonmember_event.assert_called_with(
  224. expected_requester,
  225. {
  226. "type": "m.room.power_levels",
  227. "content": content,
  228. "room_id": room_id,
  229. "sender": user_id,
  230. "state_key": "",
  231. },
  232. ratelimit=False,
  233. ignore_shadow_ban=True,
  234. )
  235. # Check that we can't send membership events
  236. content = {
  237. "membership": "leave",
  238. }
  239. event_dict = {
  240. "room_id": room_id,
  241. "type": "m.room.member",
  242. "content": content,
  243. "sender": user_id,
  244. "state_key": user_id,
  245. }
  246. self.get_failure(
  247. self.module_api.create_and_send_event_into_room(event_dict), Exception
  248. )
  249. def test_public_rooms(self):
  250. """Tests that a room can be added and removed from the public rooms list,
  251. as well as have its public rooms directory state queried.
  252. """
  253. # Create a user and room to play with
  254. user_id = self.register_user("kermit", "monkey")
  255. tok = self.login("kermit", "monkey")
  256. room_id = self.helper.create_room_as(user_id, tok=tok, is_public=False)
  257. # The room should not currently be in the public rooms directory
  258. is_in_public_rooms = self.get_success(
  259. self.module_api.public_room_list_manager.room_is_in_public_room_list(
  260. room_id
  261. )
  262. )
  263. self.assertFalse(is_in_public_rooms)
  264. # Let's try adding it to the public rooms directory
  265. self.get_success(
  266. self.module_api.public_room_list_manager.add_room_to_public_room_list(
  267. room_id
  268. )
  269. )
  270. # And checking whether it's in there...
  271. is_in_public_rooms = self.get_success(
  272. self.module_api.public_room_list_manager.room_is_in_public_room_list(
  273. room_id
  274. )
  275. )
  276. self.assertTrue(is_in_public_rooms)
  277. # Let's remove it again
  278. self.get_success(
  279. self.module_api.public_room_list_manager.remove_room_from_public_room_list(
  280. room_id
  281. )
  282. )
  283. # Should be gone
  284. is_in_public_rooms = self.get_success(
  285. self.module_api.public_room_list_manager.room_is_in_public_room_list(
  286. room_id
  287. )
  288. )
  289. self.assertFalse(is_in_public_rooms)
  290. def test_send_local_online_presence_to(self):
  291. # Test sending local online presence to users from the main process
  292. _test_sending_local_online_presence_to_local_user(self, test_with_workers=False)
  293. @override_config({"send_federation": True})
  294. def test_send_local_online_presence_to_federation(self):
  295. """Tests that send_local_presence_to_users sends local online presence to remote users."""
  296. # Create a user who will send presence updates
  297. self.presence_sender_id = self.register_user("presence_sender1", "monkey")
  298. self.presence_sender_tok = self.login("presence_sender1", "monkey")
  299. # And a room they're a part of
  300. room_id = self.helper.create_room_as(
  301. self.presence_sender_id,
  302. tok=self.presence_sender_tok,
  303. )
  304. # Mark them as online
  305. send_presence_update(
  306. self,
  307. self.presence_sender_id,
  308. self.presence_sender_tok,
  309. "online",
  310. "I'm online!",
  311. )
  312. # Make up a remote user to send presence to
  313. remote_user_id = "@far_away_person:island"
  314. # Create a join membership event for the remote user into the room.
  315. # This allows presence information to flow from one user to the other.
  316. self.get_success(
  317. inject_member_event(
  318. self.hs,
  319. room_id,
  320. sender=remote_user_id,
  321. target=remote_user_id,
  322. membership="join",
  323. )
  324. )
  325. # The remote user would have received the existing room members' presence
  326. # when they joined the room.
  327. #
  328. # Thus we reset the mock, and try sending online local user
  329. # presence again
  330. self.hs.get_federation_transport_client().send_transaction.reset_mock()
  331. # Broadcast local user online presence
  332. self.get_success(
  333. self.module_api.send_local_online_presence_to([remote_user_id])
  334. )
  335. # Check that a presence update was sent as part of a federation transaction
  336. found_update = False
  337. calls = (
  338. self.hs.get_federation_transport_client().send_transaction.call_args_list
  339. )
  340. for call in calls:
  341. call_args = call[0]
  342. federation_transaction: Transaction = call_args[0]
  343. # Get the sent EDUs in this transaction
  344. edus = federation_transaction.get_dict()["edus"]
  345. for edu in edus:
  346. # Make sure we're only checking presence-type EDUs
  347. if edu["edu_type"] != EduTypes.PRESENCE:
  348. continue
  349. # EDUs can contain multiple presence updates
  350. for presence_update in edu["content"]["push"]:
  351. if presence_update["user_id"] == self.presence_sender_id:
  352. found_update = True
  353. self.assertTrue(found_update)
  354. def test_update_membership(self):
  355. """Tests that the module API can update the membership of a user in a room."""
  356. peter = self.register_user("peter", "hackme")
  357. lesley = self.register_user("lesley", "hackme")
  358. tok = self.login("peter", "hackme")
  359. lesley_tok = self.login("lesley", "hackme")
  360. # Make peter create a public room.
  361. room_id = self.helper.create_room_as(
  362. room_creator=peter, is_public=True, tok=tok
  363. )
  364. # Set a profile for lesley.
  365. channel = self.make_request(
  366. method="PUT",
  367. path="/_matrix/client/r0/profile/%s/displayname" % lesley,
  368. content={"displayname": "Lesley May"},
  369. access_token=lesley_tok,
  370. )
  371. self.assertEqual(channel.code, 200, channel.result)
  372. channel = self.make_request(
  373. method="PUT",
  374. path="/_matrix/client/r0/profile/%s/avatar_url" % lesley,
  375. content={"avatar_url": "some_url"},
  376. access_token=lesley_tok,
  377. )
  378. self.assertEqual(channel.code, 200, channel.result)
  379. # Make Peter invite Lesley to the room.
  380. self.get_success(
  381. defer.ensureDeferred(
  382. self.module_api.update_room_membership(peter, lesley, room_id, "invite")
  383. )
  384. )
  385. res = self.helper.get_state(
  386. room_id=room_id,
  387. event_type="m.room.member",
  388. state_key=lesley,
  389. tok=tok,
  390. )
  391. # Check the membership is correct.
  392. self.assertEqual(res["membership"], "invite")
  393. # Also check that the profile was correctly filled out, and that it's not
  394. # Peter's.
  395. self.assertEqual(res["displayname"], "Lesley May")
  396. self.assertEqual(res["avatar_url"], "some_url")
  397. # Make lesley join it.
  398. self.get_success(
  399. defer.ensureDeferred(
  400. self.module_api.update_room_membership(lesley, lesley, room_id, "join")
  401. )
  402. )
  403. # Check that the membership of lesley in the room is "join".
  404. res = self.helper.get_state(
  405. room_id=room_id,
  406. event_type="m.room.member",
  407. state_key=lesley,
  408. tok=tok,
  409. )
  410. self.assertEqual(res["membership"], "join")
  411. # Also check that the profile was correctly filled out.
  412. self.assertEqual(res["displayname"], "Lesley May")
  413. self.assertEqual(res["avatar_url"], "some_url")
  414. # Make peter kick lesley from the room.
  415. self.get_success(
  416. defer.ensureDeferred(
  417. self.module_api.update_room_membership(peter, lesley, room_id, "leave")
  418. )
  419. )
  420. # Check that the membership of lesley in the room is "leave".
  421. res = self.helper.get_state(
  422. room_id=room_id,
  423. event_type="m.room.member",
  424. state_key=lesley,
  425. tok=tok,
  426. )
  427. self.assertEqual(res["membership"], "leave")
  428. # Try to send a membership update from a non-local user and check that it fails.
  429. d = defer.ensureDeferred(
  430. self.module_api.update_room_membership(
  431. "@nicolas:otherserver.com",
  432. lesley,
  433. room_id,
  434. "invite",
  435. )
  436. )
  437. self.get_failure(d, RuntimeError)
  438. # Check that inviting a user that doesn't have a profile falls back to using a
  439. # default (localpart + no avatar) profile.
  440. simone = "@simone:" + self.hs.config.server.server_name
  441. self.get_success(
  442. defer.ensureDeferred(
  443. self.module_api.update_room_membership(peter, simone, room_id, "invite")
  444. )
  445. )
  446. res = self.helper.get_state(
  447. room_id=room_id,
  448. event_type="m.room.member",
  449. state_key=simone,
  450. tok=tok,
  451. )
  452. self.assertEqual(res["membership"], "invite")
  453. self.assertEqual(res["displayname"], "simone")
  454. self.assertIsNone(res["avatar_url"])
  455. def test_get_room_state(self):
  456. """Tests that a module can retrieve the state of a room through the module API."""
  457. user_id = self.register_user("peter", "hackme")
  458. tok = self.login("peter", "hackme")
  459. # Create a room and send some custom state in it.
  460. room_id = self.helper.create_room_as(tok=tok)
  461. self.helper.send_state(room_id, "org.matrix.test", {}, tok=tok)
  462. # Check that the module API can successfully fetch state for the room.
  463. state = self.get_success(
  464. defer.ensureDeferred(self.module_api.get_room_state(room_id))
  465. )
  466. # Check that a few standard events are in the returned state.
  467. self.assertIn((EventTypes.Create, ""), state)
  468. self.assertIn((EventTypes.Member, user_id), state)
  469. # Check that our custom state event is in the returned state.
  470. self.assertEqual(state[("org.matrix.test", "")].sender, user_id)
  471. self.assertEqual(state[("org.matrix.test", "")].state_key, "")
  472. self.assertEqual(state[("org.matrix.test", "")].content, {})
  473. def test_set_push_rules_action(self) -> None:
  474. """Test that a module can change the actions of an existing push rule for a user."""
  475. # Create a room with 2 users in it. Push rules must not match if the user is the
  476. # event's sender, so we need one user to send messages and one user to receive
  477. # notifications.
  478. user_id = self.register_user("user", "password")
  479. tok = self.login("user", "password")
  480. room_id = self.helper.create_room_as(user_id, is_public=True, tok=tok)
  481. user_id2 = self.register_user("user2", "password")
  482. tok2 = self.login("user2", "password")
  483. self.helper.join(room_id, user_id2, tok=tok2)
  484. # Register a 3rd user and join them to the room, so that we don't accidentally
  485. # trigger 1:1 push rules.
  486. user_id3 = self.register_user("user3", "password")
  487. tok3 = self.login("user3", "password")
  488. self.helper.join(room_id, user_id3, tok=tok3)
  489. # Send a message as the second user and check that it notifies.
  490. res = self.helper.send(room_id=room_id, body="here's a message", tok=tok2)
  491. event_id = res["event_id"]
  492. channel = self.make_request(
  493. "GET",
  494. "/notifications",
  495. access_token=tok,
  496. )
  497. self.assertEqual(channel.code, 200, channel.result)
  498. self.assertEqual(len(channel.json_body["notifications"]), 1, channel.json_body)
  499. self.assertEqual(
  500. channel.json_body["notifications"][0]["event"]["event_id"],
  501. event_id,
  502. channel.json_body,
  503. )
  504. # Change the .m.rule.message actions to not notify on new messages.
  505. self.get_success(
  506. defer.ensureDeferred(
  507. self.module_api.set_push_rule_action(
  508. user_id=user_id,
  509. scope="global",
  510. kind="underride",
  511. rule_id=".m.rule.message",
  512. actions=["dont_notify"],
  513. )
  514. )
  515. )
  516. # Send another message as the second user and check that the number of
  517. # notifications didn't change.
  518. self.helper.send(room_id=room_id, body="here's another message", tok=tok2)
  519. channel = self.make_request(
  520. "GET",
  521. "/notifications?from=",
  522. access_token=tok,
  523. )
  524. self.assertEqual(channel.code, 200, channel.result)
  525. self.assertEqual(len(channel.json_body["notifications"]), 1, channel.json_body)
  526. def test_check_push_rules_actions(self) -> None:
  527. """Test that modules can check whether a list of push rules actions are spec
  528. compliant.
  529. """
  530. with self.assertRaises(InvalidRuleException):
  531. self.module_api.check_push_rule_actions(["foo"])
  532. with self.assertRaises(InvalidRuleException):
  533. self.module_api.check_push_rule_actions({"foo": "bar"})
  534. self.module_api.check_push_rule_actions(["notify"])
  535. self.module_api.check_push_rule_actions(
  536. [{"set_tweak": "sound", "value": "default"}]
  537. )
  538. class ModuleApiWorkerTestCase(BaseMultiWorkerStreamTestCase):
  539. """For testing ModuleApi functionality in a multi-worker setup"""
  540. # Testing stream ID replication from the main to worker processes requires postgres
  541. # (due to needing `MultiWriterIdGenerator`).
  542. if not USE_POSTGRES_FOR_TESTS:
  543. skip = "Requires Postgres"
  544. servlets = [
  545. admin.register_servlets,
  546. login.register_servlets,
  547. room.register_servlets,
  548. presence.register_servlets,
  549. ]
  550. def default_config(self):
  551. conf = super().default_config()
  552. conf["redis"] = {"enabled": "true"}
  553. conf["stream_writers"] = {"presence": ["presence_writer"]}
  554. conf["instance_map"] = {
  555. "presence_writer": {"host": "testserv", "port": 1001},
  556. }
  557. return conf
  558. def prepare(self, reactor, clock, homeserver):
  559. self.module_api = homeserver.get_module_api()
  560. self.sync_handler = homeserver.get_sync_handler()
  561. def test_send_local_online_presence_to_workers(self):
  562. # Test sending local online presence to users from a worker process
  563. _test_sending_local_online_presence_to_local_user(self, test_with_workers=True)
  564. def _test_sending_local_online_presence_to_local_user(
  565. test_case: HomeserverTestCase, test_with_workers: bool = False
  566. ):
  567. """Tests that send_local_presence_to_users sends local online presence to local users.
  568. This simultaneously tests two different usecases:
  569. * Testing that this method works when either called from a worker or the main process.
  570. - We test this by calling this method from both a TestCase that runs in monolith mode, and one that
  571. runs with a main and generic_worker.
  572. * Testing that multiple devices syncing simultaneously will all receive a snapshot of local,
  573. online presence - but only once per device.
  574. Args:
  575. test_with_workers: If True, this method will call ModuleApi.send_local_online_presence_to on a
  576. worker process. The test users will still sync with the main process. The purpose of testing
  577. with a worker is to check whether a Synapse module running on a worker can inform other workers/
  578. the main process that they should include additional presence when a user next syncs.
  579. """
  580. if test_with_workers:
  581. # Create a worker process to make module_api calls against
  582. worker_hs = test_case.make_worker_hs(
  583. "synapse.app.generic_worker", {"worker_name": "presence_writer"}
  584. )
  585. # Create a user who will send presence updates
  586. test_case.presence_receiver_id = test_case.register_user(
  587. "presence_receiver1", "monkey"
  588. )
  589. test_case.presence_receiver_tok = test_case.login("presence_receiver1", "monkey")
  590. # And another user that will send presence updates out
  591. test_case.presence_sender_id = test_case.register_user("presence_sender2", "monkey")
  592. test_case.presence_sender_tok = test_case.login("presence_sender2", "monkey")
  593. # Put them in a room together so they will receive each other's presence updates
  594. room_id = test_case.helper.create_room_as(
  595. test_case.presence_receiver_id,
  596. tok=test_case.presence_receiver_tok,
  597. )
  598. test_case.helper.join(
  599. room_id, test_case.presence_sender_id, tok=test_case.presence_sender_tok
  600. )
  601. # Presence sender comes online
  602. send_presence_update(
  603. test_case,
  604. test_case.presence_sender_id,
  605. test_case.presence_sender_tok,
  606. "online",
  607. "I'm online!",
  608. )
  609. # Presence receiver should have received it
  610. presence_updates, sync_token = sync_presence(
  611. test_case, test_case.presence_receiver_id
  612. )
  613. test_case.assertEqual(len(presence_updates), 1)
  614. presence_update: UserPresenceState = presence_updates[0]
  615. test_case.assertEqual(presence_update.user_id, test_case.presence_sender_id)
  616. test_case.assertEqual(presence_update.state, "online")
  617. if test_with_workers:
  618. # Replicate the current sync presence token from the main process to the worker process.
  619. # We need to do this so that the worker process knows the current presence stream ID to
  620. # insert into the database when we call ModuleApi.send_local_online_presence_to.
  621. test_case.replicate()
  622. # Syncing again should result in no presence updates
  623. presence_updates, sync_token = sync_presence(
  624. test_case, test_case.presence_receiver_id, sync_token
  625. )
  626. test_case.assertEqual(len(presence_updates), 0)
  627. # We do an (initial) sync with a second "device" now, getting a new sync token.
  628. # We'll use this in a moment.
  629. _, sync_token_second_device = sync_presence(
  630. test_case, test_case.presence_receiver_id
  631. )
  632. # Determine on which process (main or worker) to call ModuleApi.send_local_online_presence_to on
  633. if test_with_workers:
  634. module_api_to_use = worker_hs.get_module_api()
  635. else:
  636. module_api_to_use = test_case.module_api
  637. # Trigger sending local online presence. We expect this information
  638. # to be saved to the database where all processes can access it.
  639. # Note that we're syncing via the master.
  640. d = module_api_to_use.send_local_online_presence_to(
  641. [
  642. test_case.presence_receiver_id,
  643. ]
  644. )
  645. d = defer.ensureDeferred(d)
  646. if test_with_workers:
  647. # In order for the required presence_set_state replication request to occur between the
  648. # worker and main process, we need to pump the reactor. Otherwise, the coordinator that
  649. # reads the request on the main process won't do so, and the request will time out.
  650. while not d.called:
  651. test_case.reactor.advance(0.1)
  652. test_case.get_success(d)
  653. # The presence receiver should have received online presence again.
  654. presence_updates, sync_token = sync_presence(
  655. test_case, test_case.presence_receiver_id, sync_token
  656. )
  657. test_case.assertEqual(len(presence_updates), 1)
  658. presence_update: UserPresenceState = presence_updates[0]
  659. test_case.assertEqual(presence_update.user_id, test_case.presence_sender_id)
  660. test_case.assertEqual(presence_update.state, "online")
  661. # We attempt to sync with the second sync token we received above - just to check that
  662. # multiple syncing devices will each receive the necessary online presence.
  663. presence_updates, sync_token_second_device = sync_presence(
  664. test_case, test_case.presence_receiver_id, sync_token_second_device
  665. )
  666. test_case.assertEqual(len(presence_updates), 1)
  667. presence_update: UserPresenceState = presence_updates[0]
  668. test_case.assertEqual(presence_update.user_id, test_case.presence_sender_id)
  669. test_case.assertEqual(presence_update.state, "online")
  670. # However, if we now sync with either "device", we won't receive another burst of online presence
  671. # until the API is called again sometime in the future
  672. presence_updates, sync_token = sync_presence(
  673. test_case, test_case.presence_receiver_id, sync_token
  674. )
  675. # Now we check that we don't receive *offline* updates using ModuleApi.send_local_online_presence_to.
  676. # Presence sender goes offline
  677. send_presence_update(
  678. test_case,
  679. test_case.presence_sender_id,
  680. test_case.presence_sender_tok,
  681. "offline",
  682. "I slink back into the darkness.",
  683. )
  684. # Presence receiver should have received the updated, offline state
  685. presence_updates, sync_token = sync_presence(
  686. test_case, test_case.presence_receiver_id, sync_token
  687. )
  688. test_case.assertEqual(len(presence_updates), 1)
  689. # Now trigger sending local online presence.
  690. d = module_api_to_use.send_local_online_presence_to(
  691. [
  692. test_case.presence_receiver_id,
  693. ]
  694. )
  695. d = defer.ensureDeferred(d)
  696. if test_with_workers:
  697. # In order for the required presence_set_state replication request to occur between the
  698. # worker and main process, we need to pump the reactor. Otherwise, the coordinator that
  699. # reads the request on the main process won't do so, and the request will time out.
  700. while not d.called:
  701. test_case.reactor.advance(0.1)
  702. test_case.get_success(d)
  703. # Presence receiver should *not* have received offline state
  704. presence_updates, sync_token = sync_presence(
  705. test_case, test_case.presence_receiver_id, sync_token
  706. )
  707. test_case.assertEqual(len(presence_updates), 0)