test_api.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934
  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.api.errors import NotFoundError
  18. from synapse.events import EventBase
  19. from synapse.federation.units import Transaction
  20. from synapse.handlers.presence import UserPresenceState
  21. from synapse.handlers.push_rules import InvalidRuleException
  22. from synapse.rest import admin
  23. from synapse.rest.client import login, notifications, presence, profile, room
  24. from synapse.types import create_requester
  25. from tests.events.test_presence_router import send_presence_update, sync_presence
  26. from tests.replication._base import BaseMultiWorkerStreamTestCase
  27. from tests.test_utils import simple_async_mock
  28. from tests.test_utils.event_injection import inject_member_event
  29. from tests.unittest import HomeserverTestCase, override_config
  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_update_room_membership_remote_join(self):
  456. """Test that the module API can join a remote room."""
  457. # Necessary to fake a remote join.
  458. fake_stream_id = 1
  459. mocked_remote_join = simple_async_mock(
  460. return_value=("fake-event-id", fake_stream_id)
  461. )
  462. self.hs.get_room_member_handler()._remote_join = mocked_remote_join
  463. fake_remote_host = f"{self.module_api.server_name}-remote"
  464. # Given that the join is to be faked, we expect the relevant join event not to
  465. # be persisted and the module API method to raise that.
  466. self.get_failure(
  467. defer.ensureDeferred(
  468. self.module_api.update_room_membership(
  469. sender=f"@user:{self.module_api.server_name}",
  470. target=f"@user:{self.module_api.server_name}",
  471. room_id=f"!nonexistent:{fake_remote_host}",
  472. new_membership="join",
  473. remote_room_hosts=[fake_remote_host],
  474. )
  475. ),
  476. NotFoundError,
  477. )
  478. # Check that a remote join was attempted.
  479. self.assertEqual(mocked_remote_join.call_count, 1)
  480. def test_get_room_state(self):
  481. """Tests that a module can retrieve the state of a room through the module API."""
  482. user_id = self.register_user("peter", "hackme")
  483. tok = self.login("peter", "hackme")
  484. # Create a room and send some custom state in it.
  485. room_id = self.helper.create_room_as(tok=tok)
  486. self.helper.send_state(room_id, "org.matrix.test", {}, tok=tok)
  487. # Check that the module API can successfully fetch state for the room.
  488. state = self.get_success(
  489. defer.ensureDeferred(self.module_api.get_room_state(room_id))
  490. )
  491. # Check that a few standard events are in the returned state.
  492. self.assertIn((EventTypes.Create, ""), state)
  493. self.assertIn((EventTypes.Member, user_id), state)
  494. # Check that our custom state event is in the returned state.
  495. self.assertEqual(state[("org.matrix.test", "")].sender, user_id)
  496. self.assertEqual(state[("org.matrix.test", "")].state_key, "")
  497. self.assertEqual(state[("org.matrix.test", "")].content, {})
  498. def test_set_push_rules_action(self) -> None:
  499. """Test that a module can change the actions of an existing push rule for a user."""
  500. # Create a room with 2 users in it. Push rules must not match if the user is the
  501. # event's sender, so we need one user to send messages and one user to receive
  502. # notifications.
  503. user_id = self.register_user("user", "password")
  504. tok = self.login("user", "password")
  505. room_id = self.helper.create_room_as(user_id, is_public=True, tok=tok)
  506. user_id2 = self.register_user("user2", "password")
  507. tok2 = self.login("user2", "password")
  508. self.helper.join(room_id, user_id2, tok=tok2)
  509. # Register a 3rd user and join them to the room, so that we don't accidentally
  510. # trigger 1:1 push rules.
  511. user_id3 = self.register_user("user3", "password")
  512. tok3 = self.login("user3", "password")
  513. self.helper.join(room_id, user_id3, tok=tok3)
  514. # Send a message as the second user and check that it notifies.
  515. res = self.helper.send(room_id=room_id, body="here's a message", tok=tok2)
  516. event_id = res["event_id"]
  517. channel = self.make_request(
  518. "GET",
  519. "/notifications",
  520. access_token=tok,
  521. )
  522. self.assertEqual(channel.code, 200, channel.result)
  523. self.assertEqual(len(channel.json_body["notifications"]), 1, channel.json_body)
  524. self.assertEqual(
  525. channel.json_body["notifications"][0]["event"]["event_id"],
  526. event_id,
  527. channel.json_body,
  528. )
  529. # Change the .m.rule.message actions to not notify on new messages.
  530. self.get_success(
  531. defer.ensureDeferred(
  532. self.module_api.set_push_rule_action(
  533. user_id=user_id,
  534. scope="global",
  535. kind="underride",
  536. rule_id=".m.rule.message",
  537. actions=["dont_notify"],
  538. )
  539. )
  540. )
  541. # Send another message as the second user and check that the number of
  542. # notifications didn't change.
  543. self.helper.send(room_id=room_id, body="here's another message", tok=tok2)
  544. channel = self.make_request(
  545. "GET",
  546. "/notifications?from=",
  547. access_token=tok,
  548. )
  549. self.assertEqual(channel.code, 200, channel.result)
  550. self.assertEqual(len(channel.json_body["notifications"]), 1, channel.json_body)
  551. def test_check_push_rules_actions(self) -> None:
  552. """Test that modules can check whether a list of push rules actions are spec
  553. compliant.
  554. """
  555. with self.assertRaises(InvalidRuleException):
  556. self.module_api.check_push_rule_actions(["foo"])
  557. with self.assertRaises(InvalidRuleException):
  558. self.module_api.check_push_rule_actions({"foo": "bar"})
  559. self.module_api.check_push_rule_actions(["notify"])
  560. self.module_api.check_push_rule_actions(
  561. [{"set_tweak": "sound", "value": "default"}]
  562. )
  563. def test_lookup_room_alias(self) -> None:
  564. """Test that modules can resolve a room alias to a room ID."""
  565. password = "password"
  566. user_id = self.register_user("user", password)
  567. access_token = self.login(user_id, password)
  568. room_alias = "my-alias"
  569. reference_room_id = self.helper.create_room_as(
  570. tok=access_token, extra_content={"room_alias_name": room_alias}
  571. )
  572. self.assertIsNotNone(reference_room_id)
  573. (room_id, _) = self.get_success(
  574. self.module_api.lookup_room_alias(
  575. f"#{room_alias}:{self.module_api.server_name}"
  576. )
  577. )
  578. self.assertEqual(room_id, reference_room_id)
  579. def test_create_room(self) -> None:
  580. """Test that modules can create a room."""
  581. # First test user validation (i.e. user is local).
  582. self.get_failure(
  583. self.module_api.create_room(
  584. user_id=f"@user:{self.module_api.server_name}abc",
  585. config={},
  586. ratelimit=False,
  587. ),
  588. RuntimeError,
  589. )
  590. # Now do the happy path.
  591. user_id = self.register_user("user", "password")
  592. access_token = self.login(user_id, "password")
  593. room_id, room_alias = self.get_success(
  594. self.module_api.create_room(
  595. user_id=user_id, config={"room_alias_name": "foo-bar"}, ratelimit=False
  596. )
  597. )
  598. # Check room creator.
  599. channel = self.make_request(
  600. "GET",
  601. f"/_matrix/client/v3/rooms/{room_id}/state/m.room.create",
  602. access_token=access_token,
  603. )
  604. self.assertEqual(channel.code, 200, channel.result)
  605. self.assertEqual(channel.json_body["creator"], user_id)
  606. # Check room alias.
  607. self.assertEquals(room_alias, f"#foo-bar:{self.module_api.server_name}")
  608. # Let's try a room with no alias.
  609. room_id, room_alias = self.get_success(
  610. self.module_api.create_room(user_id=user_id, config={}, ratelimit=False)
  611. )
  612. # Check room creator.
  613. channel = self.make_request(
  614. "GET",
  615. f"/_matrix/client/v3/rooms/{room_id}/state/m.room.create",
  616. access_token=access_token,
  617. )
  618. self.assertEqual(channel.code, 200, channel.result)
  619. self.assertEqual(channel.json_body["creator"], user_id)
  620. # Check room alias.
  621. self.assertIsNone(room_alias)
  622. class ModuleApiWorkerTestCase(BaseMultiWorkerStreamTestCase):
  623. """For testing ModuleApi functionality in a multi-worker setup"""
  624. servlets = [
  625. admin.register_servlets,
  626. login.register_servlets,
  627. room.register_servlets,
  628. presence.register_servlets,
  629. ]
  630. def default_config(self):
  631. conf = super().default_config()
  632. conf["stream_writers"] = {"presence": ["presence_writer"]}
  633. conf["instance_map"] = {
  634. "presence_writer": {"host": "testserv", "port": 1001},
  635. }
  636. return conf
  637. def prepare(self, reactor, clock, homeserver):
  638. self.module_api = homeserver.get_module_api()
  639. self.sync_handler = homeserver.get_sync_handler()
  640. def test_send_local_online_presence_to_workers(self):
  641. # Test sending local online presence to users from a worker process
  642. _test_sending_local_online_presence_to_local_user(self, test_with_workers=True)
  643. def _test_sending_local_online_presence_to_local_user(
  644. test_case: HomeserverTestCase, test_with_workers: bool = False
  645. ):
  646. """Tests that send_local_presence_to_users sends local online presence to local users.
  647. This simultaneously tests two different usecases:
  648. * Testing that this method works when either called from a worker or the main process.
  649. - We test this by calling this method from both a TestCase that runs in monolith mode, and one that
  650. runs with a main and generic_worker.
  651. * Testing that multiple devices syncing simultaneously will all receive a snapshot of local,
  652. online presence - but only once per device.
  653. Args:
  654. test_with_workers: If True, this method will call ModuleApi.send_local_online_presence_to on a
  655. worker process. The test users will still sync with the main process. The purpose of testing
  656. with a worker is to check whether a Synapse module running on a worker can inform other workers/
  657. the main process that they should include additional presence when a user next syncs.
  658. """
  659. if test_with_workers:
  660. # Create a worker process to make module_api calls against
  661. worker_hs = test_case.make_worker_hs(
  662. "synapse.app.generic_worker", {"worker_name": "presence_writer"}
  663. )
  664. # Create a user who will send presence updates
  665. test_case.presence_receiver_id = test_case.register_user(
  666. "presence_receiver1", "monkey"
  667. )
  668. test_case.presence_receiver_tok = test_case.login("presence_receiver1", "monkey")
  669. # And another user that will send presence updates out
  670. test_case.presence_sender_id = test_case.register_user("presence_sender2", "monkey")
  671. test_case.presence_sender_tok = test_case.login("presence_sender2", "monkey")
  672. # Put them in a room together so they will receive each other's presence updates
  673. room_id = test_case.helper.create_room_as(
  674. test_case.presence_receiver_id,
  675. tok=test_case.presence_receiver_tok,
  676. )
  677. test_case.helper.join(
  678. room_id, test_case.presence_sender_id, tok=test_case.presence_sender_tok
  679. )
  680. # Presence sender comes online
  681. send_presence_update(
  682. test_case,
  683. test_case.presence_sender_id,
  684. test_case.presence_sender_tok,
  685. "online",
  686. "I'm online!",
  687. )
  688. # Presence receiver should have received it
  689. presence_updates, sync_token = sync_presence(
  690. test_case, test_case.presence_receiver_id
  691. )
  692. test_case.assertEqual(len(presence_updates), 1)
  693. presence_update: UserPresenceState = presence_updates[0]
  694. test_case.assertEqual(presence_update.user_id, test_case.presence_sender_id)
  695. test_case.assertEqual(presence_update.state, "online")
  696. if test_with_workers:
  697. # Replicate the current sync presence token from the main process to the worker process.
  698. # We need to do this so that the worker process knows the current presence stream ID to
  699. # insert into the database when we call ModuleApi.send_local_online_presence_to.
  700. test_case.replicate()
  701. # Syncing again should result in no presence updates
  702. presence_updates, sync_token = sync_presence(
  703. test_case, test_case.presence_receiver_id, sync_token
  704. )
  705. test_case.assertEqual(len(presence_updates), 0)
  706. # We do an (initial) sync with a second "device" now, getting a new sync token.
  707. # We'll use this in a moment.
  708. _, sync_token_second_device = sync_presence(
  709. test_case, test_case.presence_receiver_id
  710. )
  711. # Determine on which process (main or worker) to call ModuleApi.send_local_online_presence_to on
  712. if test_with_workers:
  713. module_api_to_use = worker_hs.get_module_api()
  714. else:
  715. module_api_to_use = test_case.module_api
  716. # Trigger sending local online presence. We expect this information
  717. # to be saved to the database where all processes can access it.
  718. # Note that we're syncing via the master.
  719. d = module_api_to_use.send_local_online_presence_to(
  720. [
  721. test_case.presence_receiver_id,
  722. ]
  723. )
  724. d = defer.ensureDeferred(d)
  725. if test_with_workers:
  726. # In order for the required presence_set_state replication request to occur between the
  727. # worker and main process, we need to pump the reactor. Otherwise, the coordinator that
  728. # reads the request on the main process won't do so, and the request will time out.
  729. while not d.called:
  730. test_case.reactor.advance(0.1)
  731. test_case.get_success(d)
  732. # The presence receiver should have received online presence again.
  733. presence_updates, sync_token = sync_presence(
  734. test_case, test_case.presence_receiver_id, sync_token
  735. )
  736. test_case.assertEqual(len(presence_updates), 1)
  737. presence_update: UserPresenceState = presence_updates[0]
  738. test_case.assertEqual(presence_update.user_id, test_case.presence_sender_id)
  739. test_case.assertEqual(presence_update.state, "online")
  740. # We attempt to sync with the second sync token we received above - just to check that
  741. # multiple syncing devices will each receive the necessary online presence.
  742. presence_updates, sync_token_second_device = sync_presence(
  743. test_case, test_case.presence_receiver_id, sync_token_second_device
  744. )
  745. test_case.assertEqual(len(presence_updates), 1)
  746. presence_update: UserPresenceState = presence_updates[0]
  747. test_case.assertEqual(presence_update.user_id, test_case.presence_sender_id)
  748. test_case.assertEqual(presence_update.state, "online")
  749. # However, if we now sync with either "device", we won't receive another burst of online presence
  750. # until the API is called again sometime in the future
  751. presence_updates, sync_token = sync_presence(
  752. test_case, test_case.presence_receiver_id, sync_token
  753. )
  754. # Now we check that we don't receive *offline* updates using ModuleApi.send_local_online_presence_to.
  755. # Presence sender goes offline
  756. send_presence_update(
  757. test_case,
  758. test_case.presence_sender_id,
  759. test_case.presence_sender_tok,
  760. "offline",
  761. "I slink back into the darkness.",
  762. )
  763. # Presence receiver should have received the updated, offline state
  764. presence_updates, sync_token = sync_presence(
  765. test_case, test_case.presence_receiver_id, sync_token
  766. )
  767. test_case.assertEqual(len(presence_updates), 1)
  768. # Now trigger sending local online presence.
  769. d = module_api_to_use.send_local_online_presence_to(
  770. [
  771. test_case.presence_receiver_id,
  772. ]
  773. )
  774. d = defer.ensureDeferred(d)
  775. if test_with_workers:
  776. # In order for the required presence_set_state replication request to occur between the
  777. # worker and main process, we need to pump the reactor. Otherwise, the coordinator that
  778. # reads the request on the main process won't do so, and the request will time out.
  779. while not d.called:
  780. test_case.reactor.advance(0.1)
  781. test_case.get_success(d)
  782. # Presence receiver should *not* have received offline state
  783. presence_updates, sync_token = sync_presence(
  784. test_case, test_case.presence_receiver_id, sync_token
  785. )
  786. test_case.assertEqual(len(presence_updates), 0)