test_third_party_rules.py 34 KB

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