test_api.py 39 KB

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