test_api.py 37 KB

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