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.
 
 
 
 
 
 

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