Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.
 
 
 
 
 
 

733 Zeilen
26 KiB

  1. # Copyright 2017 New Vector Ltd
  2. # Copyright 2020 The Matrix.org Foundation C.I.C.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import email.utils
  16. import logging
  17. from typing import (
  18. TYPE_CHECKING,
  19. Any,
  20. Callable,
  21. Dict,
  22. Generator,
  23. Iterable,
  24. List,
  25. Optional,
  26. Tuple,
  27. )
  28. import jinja2
  29. from twisted.internet import defer
  30. from twisted.web.resource import IResource
  31. from synapse.events import EventBase
  32. from synapse.http.client import SimpleHttpClient
  33. from synapse.http.server import (
  34. DirectServeHtmlResource,
  35. DirectServeJsonResource,
  36. respond_with_html,
  37. )
  38. from synapse.http.servlet import parse_json_object_from_request
  39. from synapse.http.site import SynapseRequest
  40. from synapse.logging.context import make_deferred_yieldable, run_in_background
  41. from synapse.metrics.background_process_metrics import run_as_background_process
  42. from synapse.storage.database import DatabasePool, LoggingTransaction
  43. from synapse.storage.databases.main.roommember import ProfileInfo
  44. from synapse.storage.state import StateFilter
  45. from synapse.types import JsonDict, Requester, UserID, UserInfo, create_requester
  46. from synapse.util import Clock
  47. from synapse.util.caches.descriptors import cached
  48. if TYPE_CHECKING:
  49. from synapse.server import HomeServer
  50. """
  51. This package defines the 'stable' API which can be used by extension modules which
  52. are loaded into Synapse.
  53. """
  54. __all__ = [
  55. "errors",
  56. "make_deferred_yieldable",
  57. "parse_json_object_from_request",
  58. "respond_with_html",
  59. "run_in_background",
  60. "cached",
  61. "UserID",
  62. "DatabasePool",
  63. "LoggingTransaction",
  64. "DirectServeHtmlResource",
  65. "DirectServeJsonResource",
  66. "ModuleApi",
  67. ]
  68. logger = logging.getLogger(__name__)
  69. class ModuleApi:
  70. """A proxy object that gets passed to various plugin modules so they
  71. can register new users etc if necessary.
  72. """
  73. def __init__(self, hs: "HomeServer", auth_handler):
  74. self._hs = hs
  75. self._store = hs.get_datastore()
  76. self._auth = hs.get_auth()
  77. self._auth_handler = auth_handler
  78. self._server_name = hs.hostname
  79. self._presence_stream = hs.get_event_sources().sources["presence"]
  80. self._state = hs.get_state_handler()
  81. self._clock: Clock = hs.get_clock()
  82. self._send_email_handler = hs.get_send_email_handler()
  83. self.custom_template_dir = hs.config.server.custom_template_directory
  84. try:
  85. app_name = self._hs.config.email_app_name
  86. self._from_string = self._hs.config.email_notif_from % {"app": app_name}
  87. except (KeyError, TypeError):
  88. # If substitution failed (which can happen if the string contains
  89. # placeholders other than just "app", or if the type of the placeholder is
  90. # not a string), fall back to the bare strings.
  91. self._from_string = self._hs.config.email_notif_from
  92. self._raw_from = email.utils.parseaddr(self._from_string)[1]
  93. # We expose these as properties below in order to attach a helpful docstring.
  94. self._http_client: SimpleHttpClient = hs.get_simple_http_client()
  95. self._public_room_list_manager = PublicRoomListManager(hs)
  96. self._spam_checker = hs.get_spam_checker()
  97. self._account_validity_handler = hs.get_account_validity_handler()
  98. self._third_party_event_rules = hs.get_third_party_event_rules()
  99. #################################################################################
  100. # The following methods should only be called during the module's initialisation.
  101. @property
  102. def register_spam_checker_callbacks(self):
  103. """Registers callbacks for spam checking capabilities."""
  104. return self._spam_checker.register_callbacks
  105. @property
  106. def register_account_validity_callbacks(self):
  107. """Registers callbacks for account validity capabilities."""
  108. return self._account_validity_handler.register_account_validity_callbacks
  109. @property
  110. def register_third_party_rules_callbacks(self):
  111. """Registers callbacks for third party event rules capabilities."""
  112. return self._third_party_event_rules.register_third_party_rules_callbacks
  113. def register_web_resource(self, path: str, resource: IResource):
  114. """Registers a web resource to be served at the given path.
  115. This function should be called during initialisation of the module.
  116. If multiple modules register a resource for the same path, the module that
  117. appears the highest in the configuration file takes priority.
  118. Args:
  119. path: The path to register the resource for.
  120. resource: The resource to attach to this path.
  121. """
  122. self._hs.register_module_web_resource(path, resource)
  123. #########################################################################
  124. # The following methods can be called by the module at any point in time.
  125. @property
  126. def http_client(self):
  127. """Allows making outbound HTTP requests to remote resources.
  128. An instance of synapse.http.client.SimpleHttpClient
  129. """
  130. return self._http_client
  131. @property
  132. def public_room_list_manager(self):
  133. """Allows adding to, removing from and checking the status of rooms in the
  134. public room list.
  135. An instance of synapse.module_api.PublicRoomListManager
  136. """
  137. return self._public_room_list_manager
  138. @property
  139. def public_baseurl(self) -> str:
  140. """The configured public base URL for this homeserver."""
  141. return self._hs.config.public_baseurl
  142. @property
  143. def email_app_name(self) -> str:
  144. """The application name configured in the homeserver's configuration."""
  145. return self._hs.config.email.email_app_name
  146. async def get_userinfo_by_id(self, user_id: str) -> Optional[UserInfo]:
  147. """Get user info by user_id
  148. Args:
  149. user_id: Fully qualified user id.
  150. Returns:
  151. UserInfo object if a user was found, otherwise None
  152. """
  153. return await self._store.get_userinfo_by_id(user_id)
  154. async def get_user_by_req(
  155. self,
  156. req: SynapseRequest,
  157. allow_guest: bool = False,
  158. allow_expired: bool = False,
  159. ) -> Requester:
  160. """Check the access_token provided for a request
  161. Args:
  162. req: Incoming HTTP request
  163. allow_guest: True if guest users should be allowed. If this
  164. is False, and the access token is for a guest user, an
  165. AuthError will be thrown
  166. allow_expired: True if expired users should be allowed. If this
  167. is False, and the access token is for an expired user, an
  168. AuthError will be thrown
  169. Returns:
  170. The requester for this request
  171. Raises:
  172. InvalidClientCredentialsError: if no user by that token exists,
  173. or the token is invalid.
  174. """
  175. return await self._auth.get_user_by_req(
  176. req,
  177. allow_guest,
  178. allow_expired=allow_expired,
  179. )
  180. async def is_user_admin(self, user_id: str) -> bool:
  181. """Checks if a user is a server admin.
  182. Args:
  183. user_id: The Matrix ID of the user to check.
  184. Returns:
  185. True if the user is a server admin, False otherwise.
  186. """
  187. return await self._store.is_server_admin(UserID.from_string(user_id))
  188. def get_qualified_user_id(self, username):
  189. """Qualify a user id, if necessary
  190. Takes a user id provided by the user and adds the @ and :domain to
  191. qualify it, if necessary
  192. Args:
  193. username (str): provided user id
  194. Returns:
  195. str: qualified @user:id
  196. """
  197. if username.startswith("@"):
  198. return username
  199. return UserID(username, self._hs.hostname).to_string()
  200. async def get_profile_for_user(self, localpart: str) -> ProfileInfo:
  201. """Look up the profile info for the user with the given localpart.
  202. Args:
  203. localpart: The localpart to look up profile information for.
  204. Returns:
  205. The profile information (i.e. display name and avatar URL).
  206. """
  207. return await self._store.get_profileinfo(localpart)
  208. async def get_threepids_for_user(self, user_id: str) -> List[Dict[str, str]]:
  209. """Look up the threepids (email addresses and phone numbers) associated with the
  210. given Matrix user ID.
  211. Args:
  212. user_id: The Matrix user ID to look up threepids for.
  213. Returns:
  214. A list of threepids, each threepid being represented by a dictionary
  215. containing a "medium" key which value is "email" for email addresses and
  216. "msisdn" for phone numbers, and an "address" key which value is the
  217. threepid's address.
  218. """
  219. return await self._store.user_get_threepids(user_id)
  220. def check_user_exists(self, user_id):
  221. """Check if user exists.
  222. Args:
  223. user_id (str): Complete @user:id
  224. Returns:
  225. Deferred[str|None]: Canonical (case-corrected) user_id, or None
  226. if the user is not registered.
  227. """
  228. return defer.ensureDeferred(self._auth_handler.check_user_exists(user_id))
  229. @defer.inlineCallbacks
  230. def register(self, localpart, displayname=None, emails: Optional[List[str]] = None):
  231. """Registers a new user with given localpart and optional displayname, emails.
  232. Also returns an access token for the new user.
  233. Deprecated: avoid this, as it generates a new device with no way to
  234. return that device to the user. Prefer separate calls to register_user and
  235. register_device.
  236. Args:
  237. localpart (str): The localpart of the new user.
  238. displayname (str|None): The displayname of the new user.
  239. emails (List[str]): Emails to bind to the new user.
  240. Returns:
  241. Deferred[tuple[str, str]]: a 2-tuple of (user_id, access_token)
  242. """
  243. logger.warning(
  244. "Using deprecated ModuleApi.register which creates a dummy user device."
  245. )
  246. user_id = yield self.register_user(localpart, displayname, emails or [])
  247. _, access_token, _, _ = yield self.register_device(user_id)
  248. return user_id, access_token
  249. def register_user(
  250. self, localpart, displayname=None, emails: Optional[List[str]] = None
  251. ):
  252. """Registers a new user with given localpart and optional displayname, emails.
  253. Args:
  254. localpart (str): The localpart of the new user.
  255. displayname (str|None): The displayname of the new user.
  256. emails (List[str]): Emails to bind to the new user.
  257. Raises:
  258. SynapseError if there is an error performing the registration. Check the
  259. 'errcode' property for more information on the reason for failure
  260. Returns:
  261. defer.Deferred[str]: user_id
  262. """
  263. return defer.ensureDeferred(
  264. self._hs.get_registration_handler().register_user(
  265. localpart=localpart,
  266. default_display_name=displayname,
  267. bind_emails=emails or [],
  268. )
  269. )
  270. def register_device(self, user_id, device_id=None, initial_display_name=None):
  271. """Register a device for a user and generate an access token.
  272. Args:
  273. user_id (str): full canonical @user:id
  274. device_id (str|None): The device ID to check, or None to generate
  275. a new one.
  276. initial_display_name (str|None): An optional display name for the
  277. device.
  278. Returns:
  279. defer.Deferred[tuple[str, str]]: Tuple of device ID and access token
  280. """
  281. return defer.ensureDeferred(
  282. self._hs.get_registration_handler().register_device(
  283. user_id=user_id,
  284. device_id=device_id,
  285. initial_display_name=initial_display_name,
  286. )
  287. )
  288. def record_user_external_id(
  289. self, auth_provider_id: str, remote_user_id: str, registered_user_id: str
  290. ) -> defer.Deferred:
  291. """Record a mapping from an external user id to a mxid
  292. Args:
  293. auth_provider: identifier for the remote auth provider
  294. external_id: id on that system
  295. user_id: complete mxid that it is mapped to
  296. """
  297. return defer.ensureDeferred(
  298. self._store.record_user_external_id(
  299. auth_provider_id, remote_user_id, registered_user_id
  300. )
  301. )
  302. def generate_short_term_login_token(
  303. self,
  304. user_id: str,
  305. duration_in_ms: int = (2 * 60 * 1000),
  306. auth_provider_id: str = "",
  307. ) -> str:
  308. """Generate a login token suitable for m.login.token authentication
  309. Args:
  310. user_id: gives the ID of the user that the token is for
  311. duration_in_ms: the time that the token will be valid for
  312. auth_provider_id: the ID of the SSO IdP that the user used to authenticate
  313. to get this token, if any. This is encoded in the token so that
  314. /login can report stats on number of successful logins by IdP.
  315. """
  316. return self._hs.get_macaroon_generator().generate_short_term_login_token(
  317. user_id,
  318. auth_provider_id,
  319. duration_in_ms,
  320. )
  321. @defer.inlineCallbacks
  322. def invalidate_access_token(self, access_token):
  323. """Invalidate an access token for a user
  324. Args:
  325. access_token(str): access token
  326. Returns:
  327. twisted.internet.defer.Deferred - resolves once the access token
  328. has been removed.
  329. Raises:
  330. synapse.api.errors.AuthError: the access token is invalid
  331. """
  332. # see if the access token corresponds to a device
  333. user_info = yield defer.ensureDeferred(
  334. self._auth.get_user_by_access_token(access_token)
  335. )
  336. device_id = user_info.get("device_id")
  337. user_id = user_info["user"].to_string()
  338. if device_id:
  339. # delete the device, which will also delete its access tokens
  340. yield defer.ensureDeferred(
  341. self._hs.get_device_handler().delete_device(user_id, device_id)
  342. )
  343. else:
  344. # no associated device. Just delete the access token.
  345. yield defer.ensureDeferred(
  346. self._auth_handler.delete_access_token(access_token)
  347. )
  348. def run_db_interaction(self, desc, func, *args, **kwargs):
  349. """Run a function with a database connection
  350. Args:
  351. desc (str): description for the transaction, for metrics etc
  352. func (func): function to be run. Passed a database cursor object
  353. as well as *args and **kwargs
  354. *args: positional args to be passed to func
  355. **kwargs: named args to be passed to func
  356. Returns:
  357. Deferred[object]: result of func
  358. """
  359. return defer.ensureDeferred(
  360. self._store.db_pool.runInteraction(desc, func, *args, **kwargs)
  361. )
  362. def complete_sso_login(
  363. self, registered_user_id: str, request: SynapseRequest, client_redirect_url: str
  364. ):
  365. """Complete a SSO login by redirecting the user to a page to confirm whether they
  366. want their access token sent to `client_redirect_url`, or redirect them to that
  367. URL with a token directly if the URL matches with one of the whitelisted clients.
  368. This is deprecated in favor of complete_sso_login_async.
  369. Args:
  370. registered_user_id: The MXID that has been registered as a previous step of
  371. of this SSO login.
  372. request: The request to respond to.
  373. client_redirect_url: The URL to which to offer to redirect the user (or to
  374. redirect them directly if whitelisted).
  375. """
  376. self._auth_handler._complete_sso_login(
  377. registered_user_id,
  378. "<unknown>",
  379. request,
  380. client_redirect_url,
  381. )
  382. async def complete_sso_login_async(
  383. self,
  384. registered_user_id: str,
  385. request: SynapseRequest,
  386. client_redirect_url: str,
  387. new_user: bool = False,
  388. auth_provider_id: str = "<unknown>",
  389. ):
  390. """Complete a SSO login by redirecting the user to a page to confirm whether they
  391. want their access token sent to `client_redirect_url`, or redirect them to that
  392. URL with a token directly if the URL matches with one of the whitelisted clients.
  393. Args:
  394. registered_user_id: The MXID that has been registered as a previous step of
  395. of this SSO login.
  396. request: The request to respond to.
  397. client_redirect_url: The URL to which to offer to redirect the user (or to
  398. redirect them directly if whitelisted).
  399. new_user: set to true to use wording for the consent appropriate to a user
  400. who has just registered.
  401. auth_provider_id: the ID of the SSO IdP which was used to log in. This
  402. is used to track counts of sucessful logins by IdP.
  403. """
  404. await self._auth_handler.complete_sso_login(
  405. registered_user_id,
  406. auth_provider_id,
  407. request,
  408. client_redirect_url,
  409. new_user=new_user,
  410. )
  411. @defer.inlineCallbacks
  412. def get_state_events_in_room(
  413. self, room_id: str, types: Iterable[Tuple[str, Optional[str]]]
  414. ) -> Generator[defer.Deferred, Any, Iterable[EventBase]]:
  415. """Gets current state events for the given room.
  416. (This is exposed for compatibility with the old SpamCheckerApi. We should
  417. probably deprecate it and replace it with an async method in a subclass.)
  418. Args:
  419. room_id: The room ID to get state events in.
  420. types: The event type and state key (using None
  421. to represent 'any') of the room state to acquire.
  422. Returns:
  423. twisted.internet.defer.Deferred[list(synapse.events.FrozenEvent)]:
  424. The filtered state events in the room.
  425. """
  426. state_ids = yield defer.ensureDeferred(
  427. self._store.get_filtered_current_state_ids(
  428. room_id=room_id, state_filter=StateFilter.from_types(types)
  429. )
  430. )
  431. state = yield defer.ensureDeferred(self._store.get_events(state_ids.values()))
  432. return state.values()
  433. async def create_and_send_event_into_room(self, event_dict: JsonDict) -> EventBase:
  434. """Create and send an event into a room. Membership events are currently not supported.
  435. Args:
  436. event_dict: A dictionary representing the event to send.
  437. Required keys are `type`, `room_id`, `sender` and `content`.
  438. Returns:
  439. The event that was sent. If state event deduplication happened, then
  440. the previous, duplicate event instead.
  441. Raises:
  442. SynapseError if the event was not allowed.
  443. """
  444. # Create a requester object
  445. requester = create_requester(
  446. event_dict["sender"], authenticated_entity=self._server_name
  447. )
  448. # Create and send the event
  449. (
  450. event,
  451. _,
  452. ) = await self._hs.get_event_creation_handler().create_and_send_nonmember_event(
  453. requester,
  454. event_dict,
  455. ratelimit=False,
  456. ignore_shadow_ban=True,
  457. )
  458. return event
  459. async def send_local_online_presence_to(self, users: Iterable[str]) -> None:
  460. """
  461. Forces the equivalent of a presence initial_sync for a set of local or remote
  462. users. The users will receive presence for all currently online users that they
  463. are considered interested in.
  464. Updates to remote users will be sent immediately, whereas local users will receive
  465. them on their next sync attempt.
  466. Note that this method can only be run on the process that is configured to write to the
  467. presence stream. By default this is the main process.
  468. """
  469. if self._hs._instance_name not in self._hs.config.worker.writers.presence:
  470. raise Exception(
  471. "send_local_online_presence_to can only be run "
  472. "on the process that is configured to write to the "
  473. "presence stream (by default this is the main process)",
  474. )
  475. local_users = set()
  476. remote_users = set()
  477. for user in users:
  478. if self._hs.is_mine_id(user):
  479. local_users.add(user)
  480. else:
  481. remote_users.add(user)
  482. # We pull out the presence handler here to break a cyclic
  483. # dependency between the presence router and module API.
  484. presence_handler = self._hs.get_presence_handler()
  485. if local_users:
  486. # Force a presence initial_sync for these users next time they sync.
  487. await presence_handler.send_full_presence_to_users(local_users)
  488. for user in remote_users:
  489. # Retrieve presence state for currently online users that this user
  490. # is considered interested in.
  491. presence_events, _ = await self._presence_stream.get_new_events(
  492. UserID.from_string(user), from_key=None, include_offline=False
  493. )
  494. # Send to remote destinations.
  495. destination = UserID.from_string(user).domain
  496. presence_handler.get_federation_queue().send_presence_to_destinations(
  497. presence_events, destination
  498. )
  499. def looping_background_call(
  500. self,
  501. f: Callable,
  502. msec: float,
  503. *args,
  504. desc: Optional[str] = None,
  505. run_on_all_instances: bool = False,
  506. **kwargs,
  507. ):
  508. """Wraps a function as a background process and calls it repeatedly.
  509. NOTE: Will only run on the instance that is configured to run
  510. background processes (which is the main process by default), unless
  511. `run_on_all_workers` is set.
  512. Waits `msec` initially before calling `f` for the first time.
  513. Args:
  514. f: The function to call repeatedly. f can be either synchronous or
  515. asynchronous, and must follow Synapse's logcontext rules.
  516. More info about logcontexts is available at
  517. https://matrix-org.github.io/synapse/latest/log_contexts.html
  518. msec: How long to wait between calls in milliseconds.
  519. *args: Positional arguments to pass to function.
  520. desc: The background task's description. Default to the function's name.
  521. run_on_all_instances: Whether to run this on all instances, rather
  522. than just the instance configured to run background tasks.
  523. **kwargs: Key arguments to pass to function.
  524. """
  525. if desc is None:
  526. desc = f.__name__
  527. if self._hs.config.run_background_tasks or run_on_all_instances:
  528. self._clock.looping_call(
  529. run_as_background_process,
  530. msec,
  531. desc,
  532. f,
  533. *args,
  534. **kwargs,
  535. )
  536. else:
  537. logger.warning(
  538. "Not running looping call %s as the configuration forbids it",
  539. f,
  540. )
  541. async def send_mail(
  542. self,
  543. recipient: str,
  544. subject: str,
  545. html: str,
  546. text: str,
  547. ):
  548. """Send an email on behalf of the homeserver.
  549. Args:
  550. recipient: The email address for the recipient.
  551. subject: The email's subject.
  552. html: The email's HTML content.
  553. text: The email's text content.
  554. """
  555. await self._send_email_handler.send_email(
  556. email_address=recipient,
  557. subject=subject,
  558. app_name=self.email_app_name,
  559. html=html,
  560. text=text,
  561. )
  562. def read_templates(
  563. self,
  564. filenames: List[str],
  565. custom_template_directory: Optional[str] = None,
  566. ) -> List[jinja2.Template]:
  567. """Read and load the content of the template files at the given location.
  568. By default, Synapse will look for these templates in its configured template
  569. directory, but another directory to search in can be provided.
  570. Args:
  571. filenames: The name of the template files to look for.
  572. custom_template_directory: An additional directory to look for the files in.
  573. Returns:
  574. A list containing the loaded templates, with the orders matching the one of
  575. the filenames parameter.
  576. """
  577. return self._hs.config.read_templates(
  578. filenames,
  579. (td for td in (self.custom_template_dir, custom_template_directory) if td),
  580. )
  581. class PublicRoomListManager:
  582. """Contains methods for adding to, removing from and querying whether a room
  583. is in the public room list.
  584. """
  585. def __init__(self, hs: "HomeServer"):
  586. self._store = hs.get_datastore()
  587. async def room_is_in_public_room_list(self, room_id: str) -> bool:
  588. """Checks whether a room is in the public room list.
  589. Args:
  590. room_id: The ID of the room.
  591. Returns:
  592. Whether the room is in the public room list. Returns False if the room does
  593. not exist.
  594. """
  595. room = await self._store.get_room(room_id)
  596. if not room:
  597. return False
  598. return room.get("is_public", False)
  599. async def add_room_to_public_room_list(self, room_id: str) -> None:
  600. """Publishes a room to the public room list.
  601. Args:
  602. room_id: The ID of the room.
  603. """
  604. await self._store.set_room_is_public(room_id, True)
  605. async def remove_room_from_public_room_list(self, room_id: str) -> None:
  606. """Removes a room from the public room list.
  607. Args:
  608. room_id: The ID of the room.
  609. """
  610. await self._store.set_room_is_public(room_id, False)