1
0

test_api.py 35 KB

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