test_third_party_rules.py 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058
  1. # Copyright 2019 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. import threading
  15. from typing import TYPE_CHECKING, Any, Dict, Optional, Tuple, Union
  16. from unittest.mock import Mock
  17. from twisted.test.proto_helpers import MemoryReactor
  18. from synapse.api.constants import EventTypes, LoginType, Membership
  19. from synapse.api.errors import SynapseError
  20. from synapse.api.room_versions import RoomVersion
  21. from synapse.config.homeserver import HomeServerConfig
  22. from synapse.events import EventBase
  23. from synapse.events.third_party_rules import load_legacy_third_party_event_rules
  24. from synapse.rest import admin
  25. from synapse.rest.client import account, login, profile, room
  26. from synapse.server import HomeServer
  27. from synapse.types import JsonDict, Requester, StateMap
  28. from synapse.util import Clock
  29. from synapse.util.frozenutils import unfreeze
  30. from tests import unittest
  31. from tests.test_utils import make_awaitable
  32. if TYPE_CHECKING:
  33. from synapse.module_api import ModuleApi
  34. thread_local = threading.local()
  35. class LegacyThirdPartyRulesTestModule:
  36. def __init__(self, config: Dict, module_api: "ModuleApi") -> None:
  37. # keep a record of the "current" rules module, so that the test can patch
  38. # it if desired.
  39. thread_local.rules_module = self
  40. self.module_api = module_api
  41. async def on_create_room(
  42. self, requester: Requester, config: dict, is_requester_admin: bool
  43. ) -> bool:
  44. return True
  45. async def check_event_allowed(
  46. self, event: EventBase, state: StateMap[EventBase]
  47. ) -> Union[bool, dict]:
  48. return True
  49. @staticmethod
  50. def parse_config(config: Dict[str, Any]) -> Dict[str, Any]:
  51. return config
  52. class LegacyDenyNewRooms(LegacyThirdPartyRulesTestModule):
  53. def __init__(self, config: Dict, module_api: "ModuleApi") -> None:
  54. super().__init__(config, module_api)
  55. async def on_create_room(
  56. self, requester: Requester, config: dict, is_requester_admin: bool
  57. ) -> bool:
  58. return False
  59. class LegacyChangeEvents(LegacyThirdPartyRulesTestModule):
  60. def __init__(self, config: Dict, module_api: "ModuleApi") -> None:
  61. super().__init__(config, module_api)
  62. async def check_event_allowed(
  63. self, event: EventBase, state: StateMap[EventBase]
  64. ) -> JsonDict:
  65. d = event.get_dict()
  66. content = unfreeze(event.content)
  67. content["foo"] = "bar"
  68. d["content"] = content
  69. return d
  70. class ThirdPartyRulesTestCase(unittest.FederatingHomeserverTestCase):
  71. servlets = [
  72. admin.register_servlets,
  73. login.register_servlets,
  74. room.register_servlets,
  75. profile.register_servlets,
  76. account.register_servlets,
  77. ]
  78. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  79. hs = self.setup_test_homeserver()
  80. load_legacy_third_party_event_rules(hs)
  81. # We're not going to be properly signing events as our remote homeserver is fake,
  82. # therefore disable event signature checks.
  83. # Note that these checks are not relevant to this test case.
  84. # Have this homeserver auto-approve all event signature checking.
  85. async def approve_all_signature_checking(
  86. _: RoomVersion, pdu: EventBase
  87. ) -> EventBase:
  88. return pdu
  89. hs.get_federation_server()._check_sigs_and_hash = approve_all_signature_checking # type: ignore[assignment]
  90. # Have this homeserver skip event auth checks. This is necessary due to
  91. # event auth checks ensuring that events were signed by the sender's homeserver.
  92. async def _check_event_auth(origin: Any, event: Any, context: Any) -> None:
  93. pass
  94. hs.get_federation_event_handler()._check_event_auth = _check_event_auth # type: ignore[assignment]
  95. return hs
  96. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  97. super().prepare(reactor, clock, hs)
  98. # Create some users and a room to play with during the tests
  99. self.user_id = self.register_user("kermit", "monkey")
  100. self.invitee = self.register_user("invitee", "hackme")
  101. self.tok = self.login("kermit", "monkey")
  102. # Some tests might prevent room creation on purpose.
  103. try:
  104. self.room_id = self.helper.create_room_as(self.user_id, tok=self.tok)
  105. except Exception:
  106. pass
  107. def test_third_party_rules(self) -> None:
  108. """Tests that a forbidden event is forbidden from being sent, but an allowed one
  109. can be sent.
  110. """
  111. # patch the rules module with a Mock which will return False for some event
  112. # types
  113. async def check(
  114. ev: EventBase, state: StateMap[EventBase]
  115. ) -> Tuple[bool, Optional[JsonDict]]:
  116. return ev.type != "foo.bar.forbidden", None
  117. callback = Mock(spec=[], side_effect=check)
  118. self.hs.get_third_party_event_rules()._check_event_allowed_callbacks = [
  119. callback
  120. ]
  121. channel = self.make_request(
  122. "PUT",
  123. "/_matrix/client/r0/rooms/%s/send/foo.bar.allowed/1" % self.room_id,
  124. {},
  125. access_token=self.tok,
  126. )
  127. self.assertEqual(channel.code, 200, channel.result)
  128. callback.assert_called_once()
  129. # there should be various state events in the state arg: do some basic checks
  130. state_arg = callback.call_args[0][1]
  131. for k in (("m.room.create", ""), ("m.room.member", self.user_id)):
  132. self.assertIn(k, state_arg)
  133. ev = state_arg[k]
  134. self.assertEqual(ev.type, k[0])
  135. self.assertEqual(ev.state_key, k[1])
  136. channel = self.make_request(
  137. "PUT",
  138. "/_matrix/client/r0/rooms/%s/send/foo.bar.forbidden/2" % self.room_id,
  139. {},
  140. access_token=self.tok,
  141. )
  142. self.assertEqual(channel.code, 403, channel.result)
  143. def test_third_party_rules_workaround_synapse_errors_pass_through(self) -> None:
  144. """
  145. Tests that the workaround introduced by https://github.com/matrix-org/synapse/pull/11042
  146. is functional: that SynapseErrors are passed through from check_event_allowed
  147. and bubble up to the web resource.
  148. NEW MODULES SHOULD NOT MAKE USE OF THIS WORKAROUND!
  149. This is a temporary workaround!
  150. """
  151. class NastyHackException(SynapseError):
  152. def error_dict(self, config: Optional[HomeServerConfig]) -> JsonDict:
  153. """
  154. This overrides SynapseError's `error_dict` to nastily inject
  155. JSON into the error response.
  156. """
  157. result = super().error_dict(config)
  158. result["nasty"] = "very"
  159. return result
  160. # add a callback that will raise our hacky exception
  161. async def check(
  162. ev: EventBase, state: StateMap[EventBase]
  163. ) -> Tuple[bool, Optional[JsonDict]]:
  164. raise NastyHackException(429, "message")
  165. self.hs.get_third_party_event_rules()._check_event_allowed_callbacks = [check]
  166. # Make a request
  167. channel = self.make_request(
  168. "PUT",
  169. "/_matrix/client/r0/rooms/%s/send/foo.bar.forbidden/2" % self.room_id,
  170. {},
  171. access_token=self.tok,
  172. )
  173. # Check the error code
  174. self.assertEqual(channel.code, 429, channel.result)
  175. # Check the JSON body has had the `nasty` key injected
  176. self.assertEqual(
  177. channel.json_body,
  178. {"errcode": "M_UNKNOWN", "error": "message", "nasty": "very"},
  179. )
  180. def test_cannot_modify_event(self) -> None:
  181. """cannot accidentally modify an event before it is persisted"""
  182. # first patch the event checker so that it will try to modify the event
  183. async def check(
  184. ev: EventBase, state: StateMap[EventBase]
  185. ) -> Tuple[bool, Optional[JsonDict]]:
  186. ev.content = {"x": "y"}
  187. return True, None
  188. self.hs.get_third_party_event_rules()._check_event_allowed_callbacks = [check]
  189. # now send the event
  190. channel = self.make_request(
  191. "PUT",
  192. "/_matrix/client/r0/rooms/%s/send/modifyme/1" % self.room_id,
  193. {"x": "x"},
  194. access_token=self.tok,
  195. )
  196. # Because check_event_allowed raises an exception, it leads to a
  197. # 500 Internal Server Error
  198. self.assertEqual(channel.code, 500, channel.result)
  199. def test_modify_event(self) -> None:
  200. """The module can return a modified version of the event"""
  201. # first patch the event checker so that it will modify the event
  202. async def check(
  203. ev: EventBase, state: StateMap[EventBase]
  204. ) -> Tuple[bool, Optional[JsonDict]]:
  205. d = ev.get_dict()
  206. d["content"] = {"x": "y"}
  207. return True, d
  208. self.hs.get_third_party_event_rules()._check_event_allowed_callbacks = [check]
  209. # now send the event
  210. channel = self.make_request(
  211. "PUT",
  212. "/_matrix/client/r0/rooms/%s/send/modifyme/1" % self.room_id,
  213. {"x": "x"},
  214. access_token=self.tok,
  215. )
  216. self.assertEqual(channel.code, 200, channel.result)
  217. event_id = channel.json_body["event_id"]
  218. # ... and check that it got modified
  219. channel = self.make_request(
  220. "GET",
  221. "/_matrix/client/r0/rooms/%s/event/%s" % (self.room_id, event_id),
  222. access_token=self.tok,
  223. )
  224. self.assertEqual(channel.code, 200, channel.result)
  225. ev = channel.json_body
  226. self.assertEqual(ev["content"]["x"], "y")
  227. def test_message_edit(self) -> None:
  228. """Ensure that the module doesn't cause issues with edited messages."""
  229. # first patch the event checker so that it will modify the event
  230. async def check(
  231. ev: EventBase, state: StateMap[EventBase]
  232. ) -> Tuple[bool, Optional[JsonDict]]:
  233. d = ev.get_dict()
  234. d["content"] = {
  235. "msgtype": "m.text",
  236. "body": d["content"]["body"].upper(),
  237. }
  238. return True, d
  239. self.hs.get_third_party_event_rules()._check_event_allowed_callbacks = [check]
  240. # Send an event, then edit it.
  241. channel = self.make_request(
  242. "PUT",
  243. "/_matrix/client/r0/rooms/%s/send/modifyme/1" % self.room_id,
  244. {
  245. "msgtype": "m.text",
  246. "body": "Original body",
  247. },
  248. access_token=self.tok,
  249. )
  250. self.assertEqual(channel.code, 200, channel.result)
  251. orig_event_id = channel.json_body["event_id"]
  252. channel = self.make_request(
  253. "PUT",
  254. "/_matrix/client/r0/rooms/%s/send/m.room.message/2" % self.room_id,
  255. {
  256. "m.new_content": {"msgtype": "m.text", "body": "Edited body"},
  257. "m.relates_to": {
  258. "rel_type": "m.replace",
  259. "event_id": orig_event_id,
  260. },
  261. "msgtype": "m.text",
  262. "body": "Edited body",
  263. },
  264. access_token=self.tok,
  265. )
  266. self.assertEqual(channel.code, 200, channel.result)
  267. edited_event_id = channel.json_body["event_id"]
  268. # ... and check that they both got modified
  269. channel = self.make_request(
  270. "GET",
  271. "/_matrix/client/r0/rooms/%s/event/%s" % (self.room_id, orig_event_id),
  272. access_token=self.tok,
  273. )
  274. self.assertEqual(channel.code, 200, channel.result)
  275. ev = channel.json_body
  276. self.assertEqual(ev["content"]["body"], "ORIGINAL BODY")
  277. channel = self.make_request(
  278. "GET",
  279. "/_matrix/client/r0/rooms/%s/event/%s" % (self.room_id, edited_event_id),
  280. access_token=self.tok,
  281. )
  282. self.assertEqual(channel.code, 200, channel.result)
  283. ev = channel.json_body
  284. self.assertEqual(ev["content"]["body"], "EDITED BODY")
  285. def test_send_event(self) -> None:
  286. """Tests that a module can send an event into a room via the module api"""
  287. content = {
  288. "msgtype": "m.text",
  289. "body": "Hello!",
  290. }
  291. event_dict = {
  292. "room_id": self.room_id,
  293. "type": "m.room.message",
  294. "content": content,
  295. "sender": self.user_id,
  296. }
  297. event: EventBase = self.get_success(
  298. self.hs.get_module_api().create_and_send_event_into_room(event_dict)
  299. )
  300. self.assertEqual(event.sender, self.user_id)
  301. self.assertEqual(event.room_id, self.room_id)
  302. self.assertEqual(event.type, "m.room.message")
  303. self.assertEqual(event.content, content)
  304. @unittest.override_config(
  305. {
  306. "third_party_event_rules": {
  307. "module": __name__ + ".LegacyChangeEvents",
  308. "config": {},
  309. }
  310. }
  311. )
  312. def test_legacy_check_event_allowed(self) -> None:
  313. """Tests that the wrapper for legacy check_event_allowed callbacks works
  314. correctly.
  315. """
  316. channel = self.make_request(
  317. "PUT",
  318. "/_matrix/client/r0/rooms/%s/send/m.room.message/1" % self.room_id,
  319. {
  320. "msgtype": "m.text",
  321. "body": "Original body",
  322. },
  323. access_token=self.tok,
  324. )
  325. self.assertEqual(channel.code, 200, channel.result)
  326. event_id = channel.json_body["event_id"]
  327. channel = self.make_request(
  328. "GET",
  329. "/_matrix/client/r0/rooms/%s/event/%s" % (self.room_id, event_id),
  330. access_token=self.tok,
  331. )
  332. self.assertEqual(channel.code, 200, channel.result)
  333. self.assertIn("foo", channel.json_body["content"].keys())
  334. self.assertEqual(channel.json_body["content"]["foo"], "bar")
  335. @unittest.override_config(
  336. {
  337. "third_party_event_rules": {
  338. "module": __name__ + ".LegacyDenyNewRooms",
  339. "config": {},
  340. }
  341. }
  342. )
  343. def test_legacy_on_create_room(self) -> None:
  344. """Tests that the wrapper for legacy on_create_room callbacks works
  345. correctly.
  346. """
  347. self.helper.create_room_as(self.user_id, tok=self.tok, expect_code=403)
  348. def test_sent_event_end_up_in_room_state(self) -> None:
  349. """Tests that a state event sent by a module while processing another state event
  350. doesn't get dropped from the state of the room. This is to guard against a bug
  351. where Synapse has been observed doing so, see https://github.com/matrix-org/synapse/issues/10830
  352. """
  353. event_type = "org.matrix.test_state"
  354. # This content will be updated later on, and since we actually use a reference on
  355. # the dict it does the right thing. It's a bit hacky but a handy way of making
  356. # sure the state actually gets updated.
  357. event_content = {"i": -1}
  358. api = self.hs.get_module_api()
  359. # Define a callback that sends a custom event on power levels update.
  360. async def test_fn(
  361. event: EventBase, state_events: StateMap[EventBase]
  362. ) -> Tuple[bool, Optional[JsonDict]]:
  363. if event.is_state() and event.type == EventTypes.PowerLevels:
  364. await api.create_and_send_event_into_room(
  365. {
  366. "room_id": event.room_id,
  367. "sender": event.sender,
  368. "type": event_type,
  369. "content": event_content,
  370. "state_key": "",
  371. }
  372. )
  373. return True, None
  374. self.hs.get_third_party_event_rules()._check_event_allowed_callbacks = [test_fn]
  375. # Sometimes the bug might not happen the first time the event type is added
  376. # to the state but might happen when an event updates the state of the room for
  377. # that type, so we test updating the state several times.
  378. for i in range(5):
  379. # Update the content of the custom state event to be sent by the callback.
  380. event_content["i"] = i
  381. # Update the room's power levels with a different value each time so Synapse
  382. # doesn't consider an update redundant.
  383. self._update_power_levels(event_default=i)
  384. # Check that the new event made it to the room's state.
  385. channel = self.make_request(
  386. method="GET",
  387. path="/rooms/" + self.room_id + "/state/" + event_type,
  388. access_token=self.tok,
  389. )
  390. self.assertEqual(channel.code, 200)
  391. self.assertEqual(channel.json_body["i"], i)
  392. def test_on_new_event(self) -> None:
  393. """Test that the on_new_event callback is called on new events"""
  394. on_new_event = Mock(make_awaitable(None))
  395. self.hs.get_third_party_event_rules()._on_new_event_callbacks.append(
  396. on_new_event
  397. )
  398. # Send a message event to the room and check that the callback is called.
  399. self.helper.send(room_id=self.room_id, tok=self.tok)
  400. self.assertEqual(on_new_event.call_count, 1)
  401. # Check that the callback is also called on membership updates.
  402. self.helper.invite(
  403. room=self.room_id,
  404. src=self.user_id,
  405. targ=self.invitee,
  406. tok=self.tok,
  407. )
  408. self.assertEqual(on_new_event.call_count, 2)
  409. args, _ = on_new_event.call_args
  410. self.assertEqual(args[0].membership, Membership.INVITE)
  411. self.assertEqual(args[0].state_key, self.invitee)
  412. # Check that the invitee's membership is correct in the state that's passed down
  413. # to the callback.
  414. self.assertEqual(
  415. args[1][(EventTypes.Member, self.invitee)].membership,
  416. Membership.INVITE,
  417. )
  418. # Send an event over federation and check that the callback is also called.
  419. self._send_event_over_federation()
  420. self.assertEqual(on_new_event.call_count, 3)
  421. def _send_event_over_federation(self) -> None:
  422. """Send a dummy event over federation and check that the request succeeds."""
  423. body = {
  424. "pdus": [
  425. {
  426. "sender": self.user_id,
  427. "type": EventTypes.Message,
  428. "state_key": "",
  429. "content": {"body": "hello world", "msgtype": "m.text"},
  430. "room_id": self.room_id,
  431. "depth": 0,
  432. "origin_server_ts": self.clock.time_msec(),
  433. "prev_events": [],
  434. "auth_events": [],
  435. "signatures": {},
  436. "unsigned": {},
  437. }
  438. ],
  439. }
  440. channel = self.make_signed_federation_request(
  441. method="PUT",
  442. path="/_matrix/federation/v1/send/1",
  443. content=body,
  444. )
  445. self.assertEqual(channel.code, 200, channel.result)
  446. def _update_power_levels(self, event_default: int = 0) -> None:
  447. """Updates the room's power levels.
  448. Args:
  449. event_default: Value to use for 'events_default'.
  450. """
  451. self.helper.send_state(
  452. room_id=self.room_id,
  453. event_type=EventTypes.PowerLevels,
  454. body={
  455. "ban": 50,
  456. "events": {
  457. "m.room.avatar": 50,
  458. "m.room.canonical_alias": 50,
  459. "m.room.encryption": 100,
  460. "m.room.history_visibility": 100,
  461. "m.room.name": 50,
  462. "m.room.power_levels": 100,
  463. "m.room.server_acl": 100,
  464. "m.room.tombstone": 100,
  465. },
  466. "events_default": event_default,
  467. "invite": 0,
  468. "kick": 50,
  469. "redact": 50,
  470. "state_default": 50,
  471. "users": {self.user_id: 100},
  472. "users_default": 0,
  473. },
  474. tok=self.tok,
  475. )
  476. def test_on_profile_update(self) -> None:
  477. """Tests that the on_profile_update module callback is correctly called on
  478. profile updates.
  479. """
  480. displayname = "Foo"
  481. avatar_url = "mxc://matrix.org/oWQDvfewxmlRaRCkVbfetyEo"
  482. # Register a mock callback.
  483. m = Mock(return_value=make_awaitable(None))
  484. self.hs.get_third_party_event_rules()._on_profile_update_callbacks.append(m)
  485. # Change the display name.
  486. channel = self.make_request(
  487. "PUT",
  488. "/_matrix/client/v3/profile/%s/displayname" % self.user_id,
  489. {"displayname": displayname},
  490. access_token=self.tok,
  491. )
  492. self.assertEqual(channel.code, 200, channel.json_body)
  493. # Check that the callback has been called once for our user.
  494. m.assert_called_once()
  495. args = m.call_args[0]
  496. self.assertEqual(args[0], self.user_id)
  497. # Test that by_admin is False.
  498. self.assertFalse(args[2])
  499. # Test that deactivation is False.
  500. self.assertFalse(args[3])
  501. # Check that we've got the right profile data.
  502. profile_info = args[1]
  503. self.assertEqual(profile_info.display_name, displayname)
  504. self.assertIsNone(profile_info.avatar_url)
  505. # Change the avatar.
  506. channel = self.make_request(
  507. "PUT",
  508. "/_matrix/client/v3/profile/%s/avatar_url" % self.user_id,
  509. {"avatar_url": avatar_url},
  510. access_token=self.tok,
  511. )
  512. self.assertEqual(channel.code, 200, channel.json_body)
  513. # Check that the callback has been called once for our user.
  514. self.assertEqual(m.call_count, 2)
  515. args = m.call_args[0]
  516. self.assertEqual(args[0], self.user_id)
  517. # Test that by_admin is False.
  518. self.assertFalse(args[2])
  519. # Test that deactivation is False.
  520. self.assertFalse(args[3])
  521. # Check that we've got the right profile data.
  522. profile_info = args[1]
  523. self.assertEqual(profile_info.display_name, displayname)
  524. self.assertEqual(profile_info.avatar_url, avatar_url)
  525. def test_on_profile_update_admin(self) -> None:
  526. """Tests that the on_profile_update module callback is correctly called on
  527. profile updates triggered by a server admin.
  528. """
  529. displayname = "Foo"
  530. avatar_url = "mxc://matrix.org/oWQDvfewxmlRaRCkVbfetyEo"
  531. # Register a mock callback.
  532. m = Mock(return_value=make_awaitable(None))
  533. self.hs.get_third_party_event_rules()._on_profile_update_callbacks.append(m)
  534. # Register an admin user.
  535. self.register_user("admin", "password", admin=True)
  536. admin_tok = self.login("admin", "password")
  537. # Change a user's profile.
  538. channel = self.make_request(
  539. "PUT",
  540. "/_synapse/admin/v2/users/%s" % self.user_id,
  541. {"displayname": displayname, "avatar_url": avatar_url},
  542. access_token=admin_tok,
  543. )
  544. self.assertEqual(channel.code, 200, channel.json_body)
  545. # Check that the callback has been called twice (since we update the display name
  546. # and avatar separately).
  547. self.assertEqual(m.call_count, 2)
  548. # Get the arguments for the last call and check it's about the right user.
  549. args = m.call_args[0]
  550. self.assertEqual(args[0], self.user_id)
  551. # Check that by_admin is True.
  552. self.assertTrue(args[2])
  553. # Test that deactivation is False.
  554. self.assertFalse(args[3])
  555. # Check that we've got the right profile data.
  556. profile_info = args[1]
  557. self.assertEqual(profile_info.display_name, displayname)
  558. self.assertEqual(profile_info.avatar_url, avatar_url)
  559. def test_on_user_deactivation_status_changed(self) -> None:
  560. """Tests that the on_user_deactivation_status_changed module callback is called
  561. correctly when processing a user's deactivation.
  562. """
  563. # Register a mocked callback.
  564. deactivation_mock = Mock(return_value=make_awaitable(None))
  565. third_party_rules = self.hs.get_third_party_event_rules()
  566. third_party_rules._on_user_deactivation_status_changed_callbacks.append(
  567. deactivation_mock,
  568. )
  569. # Also register a mocked callback for profile updates, to check that the
  570. # deactivation code calls it in a way that let modules know the user is being
  571. # deactivated.
  572. profile_mock = Mock(return_value=make_awaitable(None))
  573. self.hs.get_third_party_event_rules()._on_profile_update_callbacks.append(
  574. profile_mock,
  575. )
  576. # Register a user that we'll deactivate.
  577. user_id = self.register_user("altan", "password")
  578. tok = self.login("altan", "password")
  579. # Deactivate that user.
  580. channel = self.make_request(
  581. "POST",
  582. "/_matrix/client/v3/account/deactivate",
  583. {
  584. "auth": {
  585. "type": LoginType.PASSWORD,
  586. "password": "password",
  587. "identifier": {
  588. "type": "m.id.user",
  589. "user": user_id,
  590. },
  591. },
  592. "erase": True,
  593. },
  594. access_token=tok,
  595. )
  596. self.assertEqual(channel.code, 200, channel.json_body)
  597. # Check that the mock was called once.
  598. deactivation_mock.assert_called_once()
  599. args = deactivation_mock.call_args[0]
  600. # Check that the mock was called with the right user ID, and with a True
  601. # deactivated flag and a False by_admin flag.
  602. self.assertEqual(args[0], user_id)
  603. self.assertTrue(args[1])
  604. self.assertFalse(args[2])
  605. # Check that the profile update callback was called twice (once for the display
  606. # name and once for the avatar URL), and that the "deactivation" boolean is true.
  607. self.assertEqual(profile_mock.call_count, 2)
  608. args = profile_mock.call_args[0]
  609. self.assertTrue(args[3])
  610. def test_on_user_deactivation_status_changed_admin(self) -> None:
  611. """Tests that the on_user_deactivation_status_changed module callback is called
  612. correctly when processing a user's deactivation triggered by a server admin as
  613. well as a reactivation.
  614. """
  615. # Register a mock callback.
  616. m = Mock(return_value=make_awaitable(None))
  617. third_party_rules = self.hs.get_third_party_event_rules()
  618. third_party_rules._on_user_deactivation_status_changed_callbacks.append(m)
  619. # Register an admin user.
  620. self.register_user("admin", "password", admin=True)
  621. admin_tok = self.login("admin", "password")
  622. # Register a user that we'll deactivate.
  623. user_id = self.register_user("altan", "password")
  624. # Deactivate the user.
  625. channel = self.make_request(
  626. "PUT",
  627. "/_synapse/admin/v2/users/%s" % user_id,
  628. {"deactivated": True},
  629. access_token=admin_tok,
  630. )
  631. self.assertEqual(channel.code, 200, channel.json_body)
  632. # Check that the mock was called once.
  633. m.assert_called_once()
  634. args = m.call_args[0]
  635. # Check that the mock was called with the right user ID, and with True deactivated
  636. # and by_admin flags.
  637. self.assertEqual(args[0], user_id)
  638. self.assertTrue(args[1])
  639. self.assertTrue(args[2])
  640. # Reactivate the user.
  641. channel = self.make_request(
  642. "PUT",
  643. "/_synapse/admin/v2/users/%s" % user_id,
  644. {"deactivated": False, "password": "hackme"},
  645. access_token=admin_tok,
  646. )
  647. self.assertEqual(channel.code, 200, channel.json_body)
  648. # Check that the mock was called once.
  649. self.assertEqual(m.call_count, 2)
  650. args = m.call_args[0]
  651. # Check that the mock was called with the right user ID, and with a False
  652. # deactivated flag and a True by_admin flag.
  653. self.assertEqual(args[0], user_id)
  654. self.assertFalse(args[1])
  655. self.assertTrue(args[2])
  656. def test_check_can_deactivate_user(self) -> None:
  657. """Tests that the on_user_deactivation_status_changed module callback is called
  658. correctly when processing a user's deactivation.
  659. """
  660. # Register a mocked callback.
  661. deactivation_mock = Mock(return_value=make_awaitable(False))
  662. third_party_rules = self.hs.get_third_party_event_rules()
  663. third_party_rules._check_can_deactivate_user_callbacks.append(
  664. deactivation_mock,
  665. )
  666. # Register a user that we'll deactivate.
  667. user_id = self.register_user("altan", "password")
  668. tok = self.login("altan", "password")
  669. # Deactivate that user.
  670. channel = self.make_request(
  671. "POST",
  672. "/_matrix/client/v3/account/deactivate",
  673. {
  674. "auth": {
  675. "type": LoginType.PASSWORD,
  676. "password": "password",
  677. "identifier": {
  678. "type": "m.id.user",
  679. "user": user_id,
  680. },
  681. },
  682. "erase": True,
  683. },
  684. access_token=tok,
  685. )
  686. # Check that the deactivation was blocked
  687. self.assertEqual(channel.code, 403, channel.json_body)
  688. # Check that the mock was called once.
  689. deactivation_mock.assert_called_once()
  690. args = deactivation_mock.call_args[0]
  691. # Check that the mock was called with the right user ID
  692. self.assertEqual(args[0], user_id)
  693. # Check that the request was not made by an admin
  694. self.assertEqual(args[1], False)
  695. def test_check_can_deactivate_user_admin(self) -> None:
  696. """Tests that the on_user_deactivation_status_changed module callback is called
  697. correctly when processing a user's deactivation triggered by a server admin.
  698. """
  699. # Register a mocked callback.
  700. deactivation_mock = Mock(return_value=make_awaitable(False))
  701. third_party_rules = self.hs.get_third_party_event_rules()
  702. third_party_rules._check_can_deactivate_user_callbacks.append(
  703. deactivation_mock,
  704. )
  705. # Register an admin user.
  706. self.register_user("admin", "password", admin=True)
  707. admin_tok = self.login("admin", "password")
  708. # Register a user that we'll deactivate.
  709. user_id = self.register_user("altan", "password")
  710. # Deactivate the user.
  711. channel = self.make_request(
  712. "PUT",
  713. "/_synapse/admin/v2/users/%s" % user_id,
  714. {"deactivated": True},
  715. access_token=admin_tok,
  716. )
  717. # Check that the deactivation was blocked
  718. self.assertEqual(channel.code, 403, channel.json_body)
  719. # Check that the mock was called once.
  720. deactivation_mock.assert_called_once()
  721. args = deactivation_mock.call_args[0]
  722. # Check that the mock was called with the right user ID
  723. self.assertEqual(args[0], user_id)
  724. # Check that the mock was made by an admin
  725. self.assertEqual(args[1], True)
  726. def test_check_can_shutdown_room(self) -> None:
  727. """Tests that the check_can_shutdown_room module callback is called
  728. correctly when processing an admin's shutdown room request.
  729. """
  730. # Register a mocked callback.
  731. shutdown_mock = Mock(return_value=make_awaitable(False))
  732. third_party_rules = self.hs.get_third_party_event_rules()
  733. third_party_rules._check_can_shutdown_room_callbacks.append(
  734. shutdown_mock,
  735. )
  736. # Register an admin user.
  737. admin_user_id = self.register_user("admin", "password", admin=True)
  738. admin_tok = self.login("admin", "password")
  739. # Shutdown the room.
  740. channel = self.make_request(
  741. "DELETE",
  742. "/_synapse/admin/v2/rooms/%s" % self.room_id,
  743. {},
  744. access_token=admin_tok,
  745. )
  746. # Check that the shutdown was blocked
  747. self.assertEqual(channel.code, 403, channel.json_body)
  748. # Check that the mock was called once.
  749. shutdown_mock.assert_called_once()
  750. args = shutdown_mock.call_args[0]
  751. # Check that the mock was called with the right user ID
  752. self.assertEqual(args[0], admin_user_id)
  753. # Check that the mock was called with the right room ID
  754. self.assertEqual(args[1], self.room_id)
  755. def test_on_threepid_bind(self) -> None:
  756. """Tests that the on_threepid_bind module callback is called correctly after
  757. associating a 3PID to an account.
  758. """
  759. # Register a mocked callback.
  760. threepid_bind_mock = Mock(return_value=make_awaitable(None))
  761. third_party_rules = self.hs.get_third_party_event_rules()
  762. third_party_rules._on_threepid_bind_callbacks.append(threepid_bind_mock)
  763. # Register an admin user.
  764. self.register_user("admin", "password", admin=True)
  765. admin_tok = self.login("admin", "password")
  766. # Also register a normal user we can modify.
  767. user_id = self.register_user("user", "password")
  768. # Add a 3PID to the user.
  769. channel = self.make_request(
  770. "PUT",
  771. "/_synapse/admin/v2/users/%s" % user_id,
  772. {
  773. "threepids": [
  774. {
  775. "medium": "email",
  776. "address": "foo@example.com",
  777. },
  778. ],
  779. },
  780. access_token=admin_tok,
  781. )
  782. # Check that the shutdown was blocked
  783. self.assertEqual(channel.code, 200, channel.json_body)
  784. # Check that the mock was called once.
  785. threepid_bind_mock.assert_called_once()
  786. args = threepid_bind_mock.call_args[0]
  787. # Check that the mock was called with the right parameters
  788. self.assertEqual(args, (user_id, "email", "foo@example.com"))
  789. def test_on_add_and_remove_user_third_party_identifier(self) -> None:
  790. """Tests that the on_add_user_third_party_identifier and
  791. on_remove_user_third_party_identifier module callbacks are called
  792. just before associating and removing a 3PID to/from an account.
  793. """
  794. # Pretend to be a Synapse module and register both callbacks as mocks.
  795. on_add_user_third_party_identifier_callback_mock = Mock(
  796. return_value=make_awaitable(None)
  797. )
  798. on_remove_user_third_party_identifier_callback_mock = Mock(
  799. return_value=make_awaitable(None)
  800. )
  801. third_party_rules = self.hs.get_third_party_event_rules()
  802. third_party_rules.register_third_party_rules_callbacks(
  803. on_add_user_third_party_identifier=on_add_user_third_party_identifier_callback_mock,
  804. on_remove_user_third_party_identifier=on_remove_user_third_party_identifier_callback_mock,
  805. )
  806. # Register an admin user.
  807. self.register_user("admin", "password", admin=True)
  808. admin_tok = self.login("admin", "password")
  809. # Also register a normal user we can modify.
  810. user_id = self.register_user("user", "password")
  811. # Add a 3PID to the user.
  812. channel = self.make_request(
  813. "PUT",
  814. "/_synapse/admin/v2/users/%s" % user_id,
  815. {
  816. "threepids": [
  817. {
  818. "medium": "email",
  819. "address": "foo@example.com",
  820. },
  821. ],
  822. },
  823. access_token=admin_tok,
  824. )
  825. # Check that the mocked add callback was called with the appropriate
  826. # 3PID details.
  827. self.assertEqual(channel.code, 200, channel.json_body)
  828. on_add_user_third_party_identifier_callback_mock.assert_called_once()
  829. args = on_add_user_third_party_identifier_callback_mock.call_args[0]
  830. self.assertEqual(args, (user_id, "email", "foo@example.com"))
  831. # Now remove the 3PID from the user
  832. channel = self.make_request(
  833. "PUT",
  834. "/_synapse/admin/v2/users/%s" % user_id,
  835. {
  836. "threepids": [],
  837. },
  838. access_token=admin_tok,
  839. )
  840. # Check that the mocked remove callback was called with the appropriate
  841. # 3PID details.
  842. self.assertEqual(channel.code, 200, channel.json_body)
  843. on_remove_user_third_party_identifier_callback_mock.assert_called_once()
  844. args = on_remove_user_third_party_identifier_callback_mock.call_args[0]
  845. self.assertEqual(args, (user_id, "email", "foo@example.com"))
  846. def test_on_remove_user_third_party_identifier_is_called_on_deactivate(
  847. self,
  848. ) -> None:
  849. """Tests that the on_remove_user_third_party_identifier module callback is called
  850. when a user is deactivated and their third-party ID associations are deleted.
  851. """
  852. # Pretend to be a Synapse module and register both callbacks as mocks.
  853. on_remove_user_third_party_identifier_callback_mock = Mock(
  854. return_value=make_awaitable(None)
  855. )
  856. third_party_rules = self.hs.get_third_party_event_rules()
  857. third_party_rules.register_third_party_rules_callbacks(
  858. on_remove_user_third_party_identifier=on_remove_user_third_party_identifier_callback_mock,
  859. )
  860. # Register an admin user.
  861. self.register_user("admin", "password", admin=True)
  862. admin_tok = self.login("admin", "password")
  863. # Also register a normal user we can modify.
  864. user_id = self.register_user("user", "password")
  865. # Add a 3PID to the user.
  866. channel = self.make_request(
  867. "PUT",
  868. "/_synapse/admin/v2/users/%s" % user_id,
  869. {
  870. "threepids": [
  871. {
  872. "medium": "email",
  873. "address": "foo@example.com",
  874. },
  875. ],
  876. },
  877. access_token=admin_tok,
  878. )
  879. self.assertEqual(channel.code, 200, channel.json_body)
  880. # Check that the mock was not called on the act of adding a third-party ID.
  881. on_remove_user_third_party_identifier_callback_mock.assert_not_called()
  882. # Now deactivate the user.
  883. channel = self.make_request(
  884. "PUT",
  885. "/_synapse/admin/v2/users/%s" % user_id,
  886. {
  887. "deactivated": True,
  888. },
  889. access_token=admin_tok,
  890. )
  891. # Check that the mocked remove callback was called with the appropriate
  892. # 3PID details.
  893. self.assertEqual(channel.code, 200, channel.json_body)
  894. on_remove_user_third_party_identifier_callback_mock.assert_called_once()
  895. args = on_remove_user_third_party_identifier_callback_mock.call_args[0]
  896. self.assertEqual(args, (user_id, "email", "foo@example.com"))