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.
 
 
 
 
 
 

170 lines
5.5 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. from typing import TYPE_CHECKING, Union
  15. from synapse.events import EventBase
  16. from synapse.events.snapshot import EventContext
  17. from synapse.types import Requester, StateMap
  18. if TYPE_CHECKING:
  19. from synapse.server import HomeServer
  20. class ThirdPartyEventRules:
  21. """Allows server admins to provide a Python module implementing an extra
  22. set of rules to apply when processing events.
  23. This is designed to help admins of closed federations with enforcing custom
  24. behaviours.
  25. """
  26. def __init__(self, hs: "HomeServer"):
  27. self.third_party_rules = None
  28. self.store = hs.get_datastore()
  29. module = None
  30. config = None
  31. if hs.config.third_party_event_rules:
  32. module, config = hs.config.third_party_event_rules
  33. if module is not None:
  34. self.third_party_rules = module(
  35. config=config,
  36. module_api=hs.get_module_api(),
  37. )
  38. async def check_event_allowed(
  39. self, event: EventBase, context: EventContext
  40. ) -> Union[bool, dict]:
  41. """Check if a provided event should be allowed in the given context.
  42. The module can return:
  43. * True: the event is allowed.
  44. * False: the event is not allowed, and should be rejected with M_FORBIDDEN.
  45. * a dict: replacement event data.
  46. Args:
  47. event: The event to be checked.
  48. context: The context of the event.
  49. Returns:
  50. The result from the ThirdPartyRules module, as above
  51. """
  52. if self.third_party_rules is None:
  53. return True
  54. prev_state_ids = await context.get_prev_state_ids()
  55. # Retrieve the state events from the database.
  56. events = await self.store.get_events(prev_state_ids.values())
  57. state_events = {(ev.type, ev.state_key): ev for ev in events.values()}
  58. # Ensure that the event is frozen, to make sure that the module is not tempted
  59. # to try to modify it. Any attempt to modify it at this point will invalidate
  60. # the hashes and signatures.
  61. event.freeze()
  62. return await self.third_party_rules.check_event_allowed(event, state_events)
  63. async def on_create_room(
  64. self, requester: Requester, config: dict, is_requester_admin: bool
  65. ) -> bool:
  66. """Intercept requests to create room to allow, deny or update the
  67. request config.
  68. Args:
  69. requester
  70. config: The creation config from the client.
  71. is_requester_admin: If the requester is an admin
  72. Returns:
  73. Whether room creation is allowed or denied.
  74. """
  75. if self.third_party_rules is None:
  76. return True
  77. return await self.third_party_rules.on_create_room(
  78. requester, config, is_requester_admin
  79. )
  80. async def check_threepid_can_be_invited(
  81. self, medium: str, address: str, room_id: str
  82. ) -> bool:
  83. """Check if a provided 3PID can be invited in the given room.
  84. Args:
  85. medium: The 3PID's medium.
  86. address: The 3PID's address.
  87. room_id: The room we want to invite the threepid to.
  88. Returns:
  89. True if the 3PID can be invited, False if not.
  90. """
  91. if self.third_party_rules is None:
  92. return True
  93. state_events = await self._get_state_map_for_room(room_id)
  94. return await self.third_party_rules.check_threepid_can_be_invited(
  95. medium, address, state_events
  96. )
  97. async def check_visibility_can_be_modified(
  98. self, room_id: str, new_visibility: str
  99. ) -> bool:
  100. """Check if a room is allowed to be published to, or removed from, the public room
  101. list.
  102. Args:
  103. room_id: The ID of the room.
  104. new_visibility: The new visibility state. Either "public" or "private".
  105. Returns:
  106. True if the room's visibility can be modified, False if not.
  107. """
  108. if self.third_party_rules is None:
  109. return True
  110. check_func = getattr(
  111. self.third_party_rules, "check_visibility_can_be_modified", None
  112. )
  113. if not check_func or not callable(check_func):
  114. return True
  115. state_events = await self._get_state_map_for_room(room_id)
  116. return await check_func(room_id, state_events, new_visibility)
  117. async def _get_state_map_for_room(self, room_id: str) -> StateMap[EventBase]:
  118. """Given a room ID, return the state events of that room.
  119. Args:
  120. room_id: The ID of the room.
  121. Returns:
  122. A dict mapping (event type, state key) to state event.
  123. """
  124. state_ids = await self.store.get_filtered_current_state_ids(room_id)
  125. room_state_events = await self.store.get_events(state_ids.values())
  126. state_events = {}
  127. for key, event_id in state_ids.items():
  128. state_events[key] = room_state_events[event_id]
  129. return state_events