test_api.py 39 KB

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