You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

598 lines
24 KiB

  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 logging
  15. from typing import TYPE_CHECKING, Any, Awaitable, Callable, List, Optional, Tuple
  16. from twisted.internet.defer import CancelledError
  17. from synapse.api.errors import ModuleFailedException, SynapseError
  18. from synapse.events import EventBase
  19. from synapse.events.snapshot import UnpersistedEventContextBase
  20. from synapse.storage.roommember import ProfileInfo
  21. from synapse.types import Requester, StateMap
  22. from synapse.util.async_helpers import delay_cancellation, maybe_awaitable
  23. if TYPE_CHECKING:
  24. from synapse.server import HomeServer
  25. logger = logging.getLogger(__name__)
  26. CHECK_EVENT_ALLOWED_CALLBACK = Callable[
  27. [EventBase, StateMap[EventBase]], Awaitable[Tuple[bool, Optional[dict]]]
  28. ]
  29. ON_CREATE_ROOM_CALLBACK = Callable[[Requester, dict, bool], Awaitable]
  30. CHECK_THREEPID_CAN_BE_INVITED_CALLBACK = Callable[
  31. [str, str, StateMap[EventBase]], Awaitable[bool]
  32. ]
  33. CHECK_VISIBILITY_CAN_BE_MODIFIED_CALLBACK = Callable[
  34. [str, StateMap[EventBase], str], Awaitable[bool]
  35. ]
  36. ON_NEW_EVENT_CALLBACK = Callable[[EventBase, StateMap[EventBase]], Awaitable]
  37. CHECK_CAN_SHUTDOWN_ROOM_CALLBACK = Callable[[Optional[str], str], Awaitable[bool]]
  38. CHECK_CAN_DEACTIVATE_USER_CALLBACK = Callable[[str, bool], Awaitable[bool]]
  39. ON_PROFILE_UPDATE_CALLBACK = Callable[[str, ProfileInfo, bool, bool], Awaitable]
  40. ON_USER_DEACTIVATION_STATUS_CHANGED_CALLBACK = Callable[[str, bool, bool], Awaitable]
  41. ON_THREEPID_BIND_CALLBACK = Callable[[str, str, str], Awaitable]
  42. ON_ADD_USER_THIRD_PARTY_IDENTIFIER_CALLBACK = Callable[[str, str, str], Awaitable]
  43. ON_REMOVE_USER_THIRD_PARTY_IDENTIFIER_CALLBACK = Callable[[str, str, str], Awaitable]
  44. def load_legacy_third_party_event_rules(hs: "HomeServer") -> None:
  45. """Wrapper that loads a third party event rules module configured using the old
  46. configuration, and registers the hooks they implement.
  47. """
  48. if hs.config.thirdpartyrules.third_party_event_rules is None:
  49. return
  50. module, config = hs.config.thirdpartyrules.third_party_event_rules
  51. api = hs.get_module_api()
  52. third_party_rules = module(config=config, module_api=api)
  53. # The known hooks. If a module implements a method which name appears in this set,
  54. # we'll want to register it.
  55. third_party_event_rules_methods = {
  56. "check_event_allowed",
  57. "on_create_room",
  58. "check_threepid_can_be_invited",
  59. "check_visibility_can_be_modified",
  60. }
  61. def async_wrapper(f: Optional[Callable]) -> Optional[Callable[..., Awaitable]]:
  62. # f might be None if the callback isn't implemented by the module. In this
  63. # case we don't want to register a callback at all so we return None.
  64. if f is None:
  65. return None
  66. # We return a separate wrapper for these methods because, in order to wrap them
  67. # correctly, we need to await its result. Therefore it doesn't make a lot of
  68. # sense to make it go through the run() wrapper.
  69. if f.__name__ == "check_event_allowed":
  70. # We need to wrap check_event_allowed because its old form would return either
  71. # a boolean or a dict, but now we want to return the dict separately from the
  72. # boolean.
  73. async def wrap_check_event_allowed(
  74. event: EventBase,
  75. state_events: StateMap[EventBase],
  76. ) -> Tuple[bool, Optional[dict]]:
  77. # Assertion required because mypy can't prove we won't change
  78. # `f` back to `None`. See
  79. # https://mypy.readthedocs.io/en/latest/common_issues.html#narrowing-and-inner-functions
  80. assert f is not None
  81. res = await f(event, state_events)
  82. if isinstance(res, dict):
  83. return True, res
  84. else:
  85. return res, None
  86. return wrap_check_event_allowed
  87. if f.__name__ == "on_create_room":
  88. # We need to wrap on_create_room because its old form would return a boolean
  89. # if the room creation is denied, but now we just want it to raise an
  90. # exception.
  91. async def wrap_on_create_room(
  92. requester: Requester, config: dict, is_requester_admin: bool
  93. ) -> None:
  94. # Assertion required because mypy can't prove we won't change
  95. # `f` back to `None`. See
  96. # https://mypy.readthedocs.io/en/latest/common_issues.html#narrowing-and-inner-functions
  97. assert f is not None
  98. res = await f(requester, config, is_requester_admin)
  99. if res is False:
  100. raise SynapseError(
  101. 403,
  102. "Room creation forbidden with these parameters",
  103. )
  104. return wrap_on_create_room
  105. def run(*args: Any, **kwargs: Any) -> Awaitable:
  106. # Assertion required because mypy can't prove we won't change `f`
  107. # back to `None`. See
  108. # https://mypy.readthedocs.io/en/latest/common_issues.html#narrowing-and-inner-functions
  109. assert f is not None
  110. return maybe_awaitable(f(*args, **kwargs))
  111. return run
  112. # Register the hooks through the module API.
  113. hooks = {
  114. hook: async_wrapper(getattr(third_party_rules, hook, None))
  115. for hook in third_party_event_rules_methods
  116. }
  117. api.register_third_party_rules_callbacks(**hooks)
  118. class ThirdPartyEventRulesModuleApiCallbacks:
  119. """Allows server admins to provide a Python module implementing an extra
  120. set of rules to apply when processing events.
  121. This is designed to help admins of closed federations with enforcing custom
  122. behaviours.
  123. """
  124. def __init__(self, hs: "HomeServer"):
  125. self.store = hs.get_datastores().main
  126. self._storage_controllers = hs.get_storage_controllers()
  127. self._check_event_allowed_callbacks: List[CHECK_EVENT_ALLOWED_CALLBACK] = []
  128. self._on_create_room_callbacks: List[ON_CREATE_ROOM_CALLBACK] = []
  129. self._check_threepid_can_be_invited_callbacks: List[
  130. CHECK_THREEPID_CAN_BE_INVITED_CALLBACK
  131. ] = []
  132. self._check_visibility_can_be_modified_callbacks: List[
  133. CHECK_VISIBILITY_CAN_BE_MODIFIED_CALLBACK
  134. ] = []
  135. self._on_new_event_callbacks: List[ON_NEW_EVENT_CALLBACK] = []
  136. self._check_can_shutdown_room_callbacks: List[
  137. CHECK_CAN_SHUTDOWN_ROOM_CALLBACK
  138. ] = []
  139. self._check_can_deactivate_user_callbacks: List[
  140. CHECK_CAN_DEACTIVATE_USER_CALLBACK
  141. ] = []
  142. self._on_profile_update_callbacks: List[ON_PROFILE_UPDATE_CALLBACK] = []
  143. self._on_user_deactivation_status_changed_callbacks: List[
  144. ON_USER_DEACTIVATION_STATUS_CHANGED_CALLBACK
  145. ] = []
  146. self._on_threepid_bind_callbacks: List[ON_THREEPID_BIND_CALLBACK] = []
  147. self._on_add_user_third_party_identifier_callbacks: List[
  148. ON_ADD_USER_THIRD_PARTY_IDENTIFIER_CALLBACK
  149. ] = []
  150. self._on_remove_user_third_party_identifier_callbacks: List[
  151. ON_REMOVE_USER_THIRD_PARTY_IDENTIFIER_CALLBACK
  152. ] = []
  153. def register_third_party_rules_callbacks(
  154. self,
  155. check_event_allowed: Optional[CHECK_EVENT_ALLOWED_CALLBACK] = None,
  156. on_create_room: Optional[ON_CREATE_ROOM_CALLBACK] = None,
  157. check_threepid_can_be_invited: Optional[
  158. CHECK_THREEPID_CAN_BE_INVITED_CALLBACK
  159. ] = None,
  160. check_visibility_can_be_modified: Optional[
  161. CHECK_VISIBILITY_CAN_BE_MODIFIED_CALLBACK
  162. ] = None,
  163. on_new_event: Optional[ON_NEW_EVENT_CALLBACK] = None,
  164. check_can_shutdown_room: Optional[CHECK_CAN_SHUTDOWN_ROOM_CALLBACK] = None,
  165. check_can_deactivate_user: Optional[CHECK_CAN_DEACTIVATE_USER_CALLBACK] = None,
  166. on_profile_update: Optional[ON_PROFILE_UPDATE_CALLBACK] = None,
  167. on_user_deactivation_status_changed: Optional[
  168. ON_USER_DEACTIVATION_STATUS_CHANGED_CALLBACK
  169. ] = None,
  170. on_threepid_bind: Optional[ON_THREEPID_BIND_CALLBACK] = None,
  171. on_add_user_third_party_identifier: Optional[
  172. ON_ADD_USER_THIRD_PARTY_IDENTIFIER_CALLBACK
  173. ] = None,
  174. on_remove_user_third_party_identifier: Optional[
  175. ON_REMOVE_USER_THIRD_PARTY_IDENTIFIER_CALLBACK
  176. ] = None,
  177. ) -> None:
  178. """Register callbacks from modules for each hook."""
  179. if check_event_allowed is not None:
  180. self._check_event_allowed_callbacks.append(check_event_allowed)
  181. if on_create_room is not None:
  182. self._on_create_room_callbacks.append(on_create_room)
  183. if check_threepid_can_be_invited is not None:
  184. self._check_threepid_can_be_invited_callbacks.append(
  185. check_threepid_can_be_invited,
  186. )
  187. if check_visibility_can_be_modified is not None:
  188. self._check_visibility_can_be_modified_callbacks.append(
  189. check_visibility_can_be_modified,
  190. )
  191. if on_new_event is not None:
  192. self._on_new_event_callbacks.append(on_new_event)
  193. if check_can_shutdown_room is not None:
  194. self._check_can_shutdown_room_callbacks.append(check_can_shutdown_room)
  195. if check_can_deactivate_user is not None:
  196. self._check_can_deactivate_user_callbacks.append(check_can_deactivate_user)
  197. if on_profile_update is not None:
  198. self._on_profile_update_callbacks.append(on_profile_update)
  199. if on_user_deactivation_status_changed is not None:
  200. self._on_user_deactivation_status_changed_callbacks.append(
  201. on_user_deactivation_status_changed,
  202. )
  203. if on_threepid_bind is not None:
  204. self._on_threepid_bind_callbacks.append(on_threepid_bind)
  205. if on_add_user_third_party_identifier is not None:
  206. self._on_add_user_third_party_identifier_callbacks.append(
  207. on_add_user_third_party_identifier
  208. )
  209. if on_remove_user_third_party_identifier is not None:
  210. self._on_remove_user_third_party_identifier_callbacks.append(
  211. on_remove_user_third_party_identifier
  212. )
  213. async def check_event_allowed(
  214. self,
  215. event: EventBase,
  216. context: UnpersistedEventContextBase,
  217. ) -> Tuple[bool, Optional[dict]]:
  218. """Check if a provided event should be allowed in the given context.
  219. The module can return:
  220. * True: the event is allowed.
  221. * False: the event is not allowed, and should be rejected with M_FORBIDDEN.
  222. If the event is allowed, the module can also return a dictionary to use as a
  223. replacement for the event.
  224. Args:
  225. event: The event to be checked.
  226. context: The context of the event.
  227. Returns:
  228. The result from the ThirdPartyRules module, as above.
  229. """
  230. # Bail out early without hitting the store if we don't have any callbacks to run.
  231. if len(self._check_event_allowed_callbacks) == 0:
  232. return True, None
  233. prev_state_ids = await context.get_prev_state_ids()
  234. # Retrieve the state events from the database.
  235. events = await self.store.get_events(prev_state_ids.values())
  236. state_events = {(ev.type, ev.state_key): ev for ev in events.values()}
  237. # Ensure that the event is frozen, to make sure that the module is not tempted
  238. # to try to modify it. Any attempt to modify it at this point will invalidate
  239. # the hashes and signatures.
  240. event.freeze()
  241. for callback in self._check_event_allowed_callbacks:
  242. try:
  243. res, replacement_data = await delay_cancellation(
  244. callback(event, state_events)
  245. )
  246. except CancelledError:
  247. raise
  248. except SynapseError as e:
  249. # FIXME: Being able to throw SynapseErrors is relied upon by
  250. # some modules. PR https://github.com/matrix-org/synapse/pull/10386
  251. # accidentally broke this ability.
  252. # That said, we aren't keen on exposing this implementation detail
  253. # to modules and we should one day have a proper way to do what
  254. # is wanted.
  255. # This module callback needs a rework so that hacks such as
  256. # this one are not necessary.
  257. raise e
  258. except Exception:
  259. raise ModuleFailedException(
  260. "Failed to run `check_event_allowed` module API callback"
  261. )
  262. # Return if the event shouldn't be allowed or if the module came up with a
  263. # replacement dict for the event.
  264. if res is False:
  265. return res, None
  266. elif isinstance(replacement_data, dict):
  267. return True, replacement_data
  268. return True, None
  269. async def on_create_room(
  270. self, requester: Requester, config: dict, is_requester_admin: bool
  271. ) -> None:
  272. """Intercept requests to create room to maybe deny it (via an exception) or
  273. update the request config.
  274. Args:
  275. requester
  276. config: The creation config from the client.
  277. is_requester_admin: If the requester is an admin
  278. """
  279. for callback in self._on_create_room_callbacks:
  280. try:
  281. await callback(requester, config, is_requester_admin)
  282. except Exception as e:
  283. # Don't silence the errors raised by this callback since we expect it to
  284. # raise an exception to deny the creation of the room; instead make sure
  285. # it's a SynapseError we can send to clients.
  286. if not isinstance(e, SynapseError):
  287. e = SynapseError(
  288. 403, "Room creation forbidden with these parameters"
  289. )
  290. raise e
  291. async def check_threepid_can_be_invited(
  292. self, medium: str, address: str, room_id: str
  293. ) -> bool:
  294. """Check if a provided 3PID can be invited in the given room.
  295. Args:
  296. medium: The 3PID's medium.
  297. address: The 3PID's address.
  298. room_id: The room we want to invite the threepid to.
  299. Returns:
  300. True if the 3PID can be invited, False if not.
  301. """
  302. # Bail out early without hitting the store if we don't have any callbacks to run.
  303. if len(self._check_threepid_can_be_invited_callbacks) == 0:
  304. return True
  305. state_events = await self._get_state_map_for_room(room_id)
  306. for callback in self._check_threepid_can_be_invited_callbacks:
  307. try:
  308. threepid_can_be_invited = await delay_cancellation(
  309. callback(medium, address, state_events)
  310. )
  311. if threepid_can_be_invited is False:
  312. return False
  313. except CancelledError:
  314. raise
  315. except Exception as e:
  316. logger.warning("Failed to run module API callback %s: %s", callback, e)
  317. return True
  318. async def check_visibility_can_be_modified(
  319. self, room_id: str, new_visibility: str
  320. ) -> bool:
  321. """Check if a room is allowed to be published to, or removed from, the public room
  322. list.
  323. Args:
  324. room_id: The ID of the room.
  325. new_visibility: The new visibility state. Either "public" or "private".
  326. Returns:
  327. True if the room's visibility can be modified, False if not.
  328. """
  329. # Bail out early without hitting the store if we don't have any callback
  330. if len(self._check_visibility_can_be_modified_callbacks) == 0:
  331. return True
  332. state_events = await self._get_state_map_for_room(room_id)
  333. for callback in self._check_visibility_can_be_modified_callbacks:
  334. try:
  335. visibility_can_be_modified = await delay_cancellation(
  336. callback(room_id, state_events, new_visibility)
  337. )
  338. if visibility_can_be_modified is False:
  339. return False
  340. except CancelledError:
  341. raise
  342. except Exception as e:
  343. logger.warning("Failed to run module API callback %s: %s", callback, e)
  344. return True
  345. async def on_new_event(self, event_id: str) -> None:
  346. """Let modules act on events after they've been sent (e.g. auto-accepting
  347. invites, etc.)
  348. Args:
  349. event_id: The ID of the event.
  350. """
  351. # Bail out early without hitting the store if we don't have any callbacks
  352. if len(self._on_new_event_callbacks) == 0:
  353. return
  354. event = await self.store.get_event(event_id)
  355. state_events = await self._get_state_map_for_room(event.room_id)
  356. for callback in self._on_new_event_callbacks:
  357. try:
  358. await callback(event, state_events)
  359. except Exception as e:
  360. logger.exception(
  361. "Failed to run module API callback %s: %s", callback, e
  362. )
  363. async def check_can_shutdown_room(
  364. self, user_id: Optional[str], room_id: str
  365. ) -> bool:
  366. """Intercept requests to shutdown a room. If `False` is returned, the
  367. room must not be shut down.
  368. Args:
  369. user_id: The ID of the user requesting the shutdown.
  370. If no user ID is supplied, then the room is being shut down through
  371. some mechanism other than a user's request, e.g. through a module's
  372. request.
  373. room_id: The ID of the room.
  374. """
  375. for callback in self._check_can_shutdown_room_callbacks:
  376. try:
  377. can_shutdown_room = await delay_cancellation(callback(user_id, room_id))
  378. if can_shutdown_room is False:
  379. return False
  380. except CancelledError:
  381. raise
  382. except Exception as e:
  383. logger.exception(
  384. "Failed to run module API callback %s: %s", callback, e
  385. )
  386. return True
  387. async def check_can_deactivate_user(
  388. self,
  389. user_id: str,
  390. by_admin: bool,
  391. ) -> bool:
  392. """Intercept requests to deactivate a user. If `False` is returned, the
  393. user should not be deactivated.
  394. Args:
  395. requester
  396. user_id: The ID of the room.
  397. """
  398. for callback in self._check_can_deactivate_user_callbacks:
  399. try:
  400. can_deactivate_user = await delay_cancellation(
  401. callback(user_id, by_admin)
  402. )
  403. if can_deactivate_user is False:
  404. return False
  405. except CancelledError:
  406. raise
  407. except Exception as e:
  408. logger.exception(
  409. "Failed to run module API callback %s: %s", callback, e
  410. )
  411. return True
  412. async def _get_state_map_for_room(self, room_id: str) -> StateMap[EventBase]:
  413. """Given a room ID, return the state events of that room.
  414. Args:
  415. room_id: The ID of the room.
  416. Returns:
  417. A dict mapping (event type, state key) to state event.
  418. """
  419. return await self._storage_controllers.state.get_current_state(room_id)
  420. async def on_profile_update(
  421. self, user_id: str, new_profile: ProfileInfo, by_admin: bool, deactivation: bool
  422. ) -> None:
  423. """Called after the global profile of a user has been updated. Does not include
  424. per-room profile changes.
  425. Args:
  426. user_id: The user whose profile was changed.
  427. new_profile: The updated profile for the user.
  428. by_admin: Whether the profile update was performed by a server admin.
  429. deactivation: Whether this change was made while deactivating the user.
  430. """
  431. for callback in self._on_profile_update_callbacks:
  432. try:
  433. await callback(user_id, new_profile, by_admin, deactivation)
  434. except Exception as e:
  435. logger.exception(
  436. "Failed to run module API callback %s: %s", callback, e
  437. )
  438. async def on_user_deactivation_status_changed(
  439. self, user_id: str, deactivated: bool, by_admin: bool
  440. ) -> None:
  441. """Called after a user has been deactivated or reactivated.
  442. Args:
  443. user_id: The deactivated user.
  444. deactivated: Whether the user is now deactivated.
  445. by_admin: Whether the deactivation was performed by a server admin.
  446. """
  447. for callback in self._on_user_deactivation_status_changed_callbacks:
  448. try:
  449. await callback(user_id, deactivated, by_admin)
  450. except Exception as e:
  451. logger.exception(
  452. "Failed to run module API callback %s: %s", callback, e
  453. )
  454. async def on_threepid_bind(self, user_id: str, medium: str, address: str) -> None:
  455. """Called after a threepid association has been verified and stored.
  456. Note that this callback is called when an association is created on the
  457. local homeserver, not when it's created on an identity server (and then kept track
  458. of so that it can be unbound on the same IS later on).
  459. THIS MODULE CALLBACK METHOD HAS BEEN DEPRECATED. Please use the
  460. `on_add_user_third_party_identifier` callback method instead.
  461. Args:
  462. user_id: the user being associated with the threepid.
  463. medium: the threepid's medium.
  464. address: the threepid's address.
  465. """
  466. for callback in self._on_threepid_bind_callbacks:
  467. try:
  468. await callback(user_id, medium, address)
  469. except Exception as e:
  470. logger.exception(
  471. "Failed to run module API callback %s: %s", callback, e
  472. )
  473. async def on_add_user_third_party_identifier(
  474. self, user_id: str, medium: str, address: str
  475. ) -> None:
  476. """Called when an association between a user's Matrix ID and a third-party ID
  477. (email, phone number) has successfully been registered on the homeserver.
  478. Args:
  479. user_id: The User ID included in the association.
  480. medium: The medium of the third-party ID (email, msisdn).
  481. address: The address of the third-party ID (i.e. an email address).
  482. """
  483. for callback in self._on_add_user_third_party_identifier_callbacks:
  484. try:
  485. await callback(user_id, medium, address)
  486. except Exception as e:
  487. logger.exception(
  488. "Failed to run module API callback %s: %s", callback, e
  489. )
  490. async def on_remove_user_third_party_identifier(
  491. self, user_id: str, medium: str, address: str
  492. ) -> None:
  493. """Called when an association between a user's Matrix ID and a third-party ID
  494. (email, phone number) has been successfully removed on the homeserver.
  495. This is called *after* any known bindings on identity servers for this
  496. association have been removed.
  497. Args:
  498. user_id: The User ID included in the removed association.
  499. medium: The medium of the third-party ID (email, msisdn).
  500. address: The address of the third-party ID (i.e. an email address).
  501. """
  502. for callback in self._on_remove_user_third_party_identifier_callbacks:
  503. try:
  504. await callback(user_id, medium, address)
  505. except Exception as e:
  506. logger.exception(
  507. "Failed to run module API callback %s: %s", callback, e
  508. )