test_api.py 39 KB

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