test_third_party_rules.py 39 KB

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