__init__.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2017 New Vector Ltd
  3. # Copyright 2020 The Matrix.org Foundation C.I.C.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import logging
  17. from typing import TYPE_CHECKING, Iterable, Optional, Tuple
  18. from twisted.internet import defer
  19. from synapse.events import EventBase
  20. from synapse.http.client import SimpleHttpClient
  21. from synapse.http.site import SynapseRequest
  22. from synapse.logging.context import make_deferred_yieldable, run_in_background
  23. from synapse.storage.state import StateFilter
  24. from synapse.types import JsonDict, UserID, create_requester
  25. if TYPE_CHECKING:
  26. from synapse.server import HomeServer
  27. """
  28. This package defines the 'stable' API which can be used by extension modules which
  29. are loaded into Synapse.
  30. """
  31. __all__ = ["errors", "make_deferred_yieldable", "run_in_background", "ModuleApi"]
  32. logger = logging.getLogger(__name__)
  33. class ModuleApi:
  34. """A proxy object that gets passed to various plugin modules so they
  35. can register new users etc if necessary.
  36. """
  37. def __init__(self, hs, auth_handler):
  38. self._hs = hs
  39. self._store = hs.get_datastore()
  40. self._auth = hs.get_auth()
  41. self._auth_handler = auth_handler
  42. self._server_name = hs.hostname
  43. # We expose these as properties below in order to attach a helpful docstring.
  44. self._http_client = hs.get_simple_http_client() # type: SimpleHttpClient
  45. self._public_room_list_manager = PublicRoomListManager(hs)
  46. @property
  47. def http_client(self):
  48. """Allows making outbound HTTP requests to remote resources.
  49. An instance of synapse.http.client.SimpleHttpClient
  50. """
  51. return self._http_client
  52. @property
  53. def public_room_list_manager(self):
  54. """Allows adding to, removing from and checking the status of rooms in the
  55. public room list.
  56. An instance of synapse.module_api.PublicRoomListManager
  57. """
  58. return self._public_room_list_manager
  59. def get_user_by_req(self, req, allow_guest=False):
  60. """Check the access_token provided for a request
  61. Args:
  62. req (twisted.web.server.Request): Incoming HTTP request
  63. allow_guest (bool): True if guest users should be allowed. If this
  64. is False, and the access token is for a guest user, an
  65. AuthError will be thrown
  66. Returns:
  67. twisted.internet.defer.Deferred[synapse.types.Requester]:
  68. the requester for this request
  69. Raises:
  70. synapse.api.errors.AuthError: if no user by that token exists,
  71. or the token is invalid.
  72. """
  73. return self._auth.get_user_by_req(req, allow_guest)
  74. def get_qualified_user_id(self, username):
  75. """Qualify a user id, if necessary
  76. Takes a user id provided by the user and adds the @ and :domain to
  77. qualify it, if necessary
  78. Args:
  79. username (str): provided user id
  80. Returns:
  81. str: qualified @user:id
  82. """
  83. if username.startswith("@"):
  84. return username
  85. return UserID(username, self._hs.hostname).to_string()
  86. def check_user_exists(self, user_id):
  87. """Check if user exists.
  88. Args:
  89. user_id (str): Complete @user:id
  90. Returns:
  91. Deferred[str|None]: Canonical (case-corrected) user_id, or None
  92. if the user is not registered.
  93. """
  94. return defer.ensureDeferred(self._auth_handler.check_user_exists(user_id))
  95. @defer.inlineCallbacks
  96. def register(self, localpart, displayname=None, emails=[]):
  97. """Registers a new user with given localpart and optional displayname, emails.
  98. Also returns an access token for the new user.
  99. Deprecated: avoid this, as it generates a new device with no way to
  100. return that device to the user. Prefer separate calls to register_user and
  101. register_device.
  102. Args:
  103. localpart (str): The localpart of the new user.
  104. displayname (str|None): The displayname of the new user.
  105. emails (List[str]): Emails to bind to the new user.
  106. Returns:
  107. Deferred[tuple[str, str]]: a 2-tuple of (user_id, access_token)
  108. """
  109. logger.warning(
  110. "Using deprecated ModuleApi.register which creates a dummy user device."
  111. )
  112. user_id = yield self.register_user(localpart, displayname, emails)
  113. _, access_token = yield self.register_device(user_id)
  114. return user_id, access_token
  115. def register_user(self, localpart, displayname=None, emails=[]):
  116. """Registers a new user with given localpart and optional displayname, emails.
  117. Args:
  118. localpart (str): The localpart of the new user.
  119. displayname (str|None): The displayname of the new user.
  120. emails (List[str]): Emails to bind to the new user.
  121. Raises:
  122. SynapseError if there is an error performing the registration. Check the
  123. 'errcode' property for more information on the reason for failure
  124. Returns:
  125. defer.Deferred[str]: user_id
  126. """
  127. return defer.ensureDeferred(
  128. self._hs.get_registration_handler().register_user(
  129. localpart=localpart,
  130. default_display_name=displayname,
  131. bind_emails=emails,
  132. )
  133. )
  134. def register_device(self, user_id, device_id=None, initial_display_name=None):
  135. """Register a device for a user and generate an access token.
  136. Args:
  137. user_id (str): full canonical @user:id
  138. device_id (str|None): The device ID to check, or None to generate
  139. a new one.
  140. initial_display_name (str|None): An optional display name for the
  141. device.
  142. Returns:
  143. defer.Deferred[tuple[str, str]]: Tuple of device ID and access token
  144. """
  145. return defer.ensureDeferred(
  146. self._hs.get_registration_handler().register_device(
  147. user_id=user_id,
  148. device_id=device_id,
  149. initial_display_name=initial_display_name,
  150. )
  151. )
  152. def record_user_external_id(
  153. self, auth_provider_id: str, remote_user_id: str, registered_user_id: str
  154. ) -> defer.Deferred:
  155. """Record a mapping from an external user id to a mxid
  156. Args:
  157. auth_provider: identifier for the remote auth provider
  158. external_id: id on that system
  159. user_id: complete mxid that it is mapped to
  160. """
  161. return defer.ensureDeferred(
  162. self._store.record_user_external_id(
  163. auth_provider_id, remote_user_id, registered_user_id
  164. )
  165. )
  166. def generate_short_term_login_token(
  167. self, user_id: str, duration_in_ms: int = (2 * 60 * 1000)
  168. ) -> str:
  169. """Generate a login token suitable for m.login.token authentication"""
  170. return self._hs.get_macaroon_generator().generate_short_term_login_token(
  171. user_id, duration_in_ms
  172. )
  173. @defer.inlineCallbacks
  174. def invalidate_access_token(self, access_token):
  175. """Invalidate an access token for a user
  176. Args:
  177. access_token(str): access token
  178. Returns:
  179. twisted.internet.defer.Deferred - resolves once the access token
  180. has been removed.
  181. Raises:
  182. synapse.api.errors.AuthError: the access token is invalid
  183. """
  184. # see if the access token corresponds to a device
  185. user_info = yield defer.ensureDeferred(
  186. self._auth.get_user_by_access_token(access_token)
  187. )
  188. device_id = user_info.get("device_id")
  189. user_id = user_info["user"].to_string()
  190. if device_id:
  191. # delete the device, which will also delete its access tokens
  192. yield defer.ensureDeferred(
  193. self._hs.get_device_handler().delete_device(user_id, device_id)
  194. )
  195. else:
  196. # no associated device. Just delete the access token.
  197. yield defer.ensureDeferred(
  198. self._auth_handler.delete_access_token(access_token)
  199. )
  200. def run_db_interaction(self, desc, func, *args, **kwargs):
  201. """Run a function with a database connection
  202. Args:
  203. desc (str): description for the transaction, for metrics etc
  204. func (func): function to be run. Passed a database cursor object
  205. as well as *args and **kwargs
  206. *args: positional args to be passed to func
  207. **kwargs: named args to be passed to func
  208. Returns:
  209. Deferred[object]: result of func
  210. """
  211. return defer.ensureDeferred(
  212. self._store.db_pool.runInteraction(desc, func, *args, **kwargs)
  213. )
  214. def complete_sso_login(
  215. self, registered_user_id: str, request: SynapseRequest, client_redirect_url: str
  216. ):
  217. """Complete a SSO login by redirecting the user to a page to confirm whether they
  218. want their access token sent to `client_redirect_url`, or redirect them to that
  219. URL with a token directly if the URL matches with one of the whitelisted clients.
  220. This is deprecated in favor of complete_sso_login_async.
  221. Args:
  222. registered_user_id: The MXID that has been registered as a previous step of
  223. of this SSO login.
  224. request: The request to respond to.
  225. client_redirect_url: The URL to which to offer to redirect the user (or to
  226. redirect them directly if whitelisted).
  227. """
  228. self._auth_handler._complete_sso_login(
  229. registered_user_id,
  230. request,
  231. client_redirect_url,
  232. )
  233. async def complete_sso_login_async(
  234. self,
  235. registered_user_id: str,
  236. request: SynapseRequest,
  237. client_redirect_url: str,
  238. new_user: bool = False,
  239. ):
  240. """Complete a SSO login by redirecting the user to a page to confirm whether they
  241. want their access token sent to `client_redirect_url`, or redirect them to that
  242. URL with a token directly if the URL matches with one of the whitelisted clients.
  243. Args:
  244. registered_user_id: The MXID that has been registered as a previous step of
  245. of this SSO login.
  246. request: The request to respond to.
  247. client_redirect_url: The URL to which to offer to redirect the user (or to
  248. redirect them directly if whitelisted).
  249. new_user: set to true to use wording for the consent appropriate to a user
  250. who has just registered.
  251. """
  252. await self._auth_handler.complete_sso_login(
  253. registered_user_id, request, client_redirect_url, new_user=new_user
  254. )
  255. @defer.inlineCallbacks
  256. def get_state_events_in_room(
  257. self, room_id: str, types: Iterable[Tuple[str, Optional[str]]]
  258. ) -> defer.Deferred:
  259. """Gets current state events for the given room.
  260. (This is exposed for compatibility with the old SpamCheckerApi. We should
  261. probably deprecate it and replace it with an async method in a subclass.)
  262. Args:
  263. room_id: The room ID to get state events in.
  264. types: The event type and state key (using None
  265. to represent 'any') of the room state to acquire.
  266. Returns:
  267. twisted.internet.defer.Deferred[list(synapse.events.FrozenEvent)]:
  268. The filtered state events in the room.
  269. """
  270. state_ids = yield defer.ensureDeferred(
  271. self._store.get_filtered_current_state_ids(
  272. room_id=room_id, state_filter=StateFilter.from_types(types)
  273. )
  274. )
  275. state = yield defer.ensureDeferred(self._store.get_events(state_ids.values()))
  276. return state.values()
  277. async def create_and_send_event_into_room(self, event_dict: JsonDict) -> EventBase:
  278. """Create and send an event into a room. Membership events are currently not supported.
  279. Args:
  280. event_dict: A dictionary representing the event to send.
  281. Required keys are `type`, `room_id`, `sender` and `content`.
  282. Returns:
  283. The event that was sent. If state event deduplication happened, then
  284. the previous, duplicate event instead.
  285. Raises:
  286. SynapseError if the event was not allowed.
  287. """
  288. # Create a requester object
  289. requester = create_requester(
  290. event_dict["sender"], authenticated_entity=self._server_name
  291. )
  292. # Create and send the event
  293. (
  294. event,
  295. _,
  296. ) = await self._hs.get_event_creation_handler().create_and_send_nonmember_event(
  297. requester,
  298. event_dict,
  299. ratelimit=False,
  300. ignore_shadow_ban=True,
  301. )
  302. return event
  303. class PublicRoomListManager:
  304. """Contains methods for adding to, removing from and querying whether a room
  305. is in the public room list.
  306. """
  307. def __init__(self, hs: "HomeServer"):
  308. self._store = hs.get_datastore()
  309. async def room_is_in_public_room_list(self, room_id: str) -> bool:
  310. """Checks whether a room is in the public room list.
  311. Args:
  312. room_id: The ID of the room.
  313. Returns:
  314. Whether the room is in the public room list. Returns False if the room does
  315. not exist.
  316. """
  317. room = await self._store.get_room(room_id)
  318. if not room:
  319. return False
  320. return room.get("is_public", False)
  321. async def add_room_to_public_room_list(self, room_id: str) -> None:
  322. """Publishes a room to the public room list.
  323. Args:
  324. room_id: The ID of the room.
  325. """
  326. await self._store.set_room_is_public(room_id, True)
  327. async def remove_room_from_public_room_list(self, room_id: str) -> None:
  328. """Removes a room from the public room list.
  329. Args:
  330. room_id: The ID of the room.
  331. """
  332. await self._store.set_room_is_public(room_id, False)