test_third_party_rules.py 39 KB

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