test_third_party_rules.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933
  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.result["code"], b"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.result["code"], b"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.result["code"], b"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.result["code"], b"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.result["code"], b"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.result["code"], b"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.result["code"], b"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.result["code"], b"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.result["code"], b"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.result["code"], b"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.result["code"], b"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"))