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.
 
 
 
 
 
 

1954 lines
70 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. Collection,
  22. Dict,
  23. Generator,
  24. Iterable,
  25. List,
  26. Mapping,
  27. Optional,
  28. Tuple,
  29. TypeVar,
  30. Union,
  31. )
  32. import attr
  33. import jinja2
  34. from typing_extensions import Concatenate, ParamSpec
  35. from twisted.internet import defer
  36. from twisted.internet.interfaces import IDelayedCall
  37. from twisted.web.resource import Resource
  38. from synapse.api import errors
  39. from synapse.api.errors import SynapseError
  40. from synapse.api.presence import UserPresenceState
  41. from synapse.config import ConfigError
  42. from synapse.events import EventBase
  43. from synapse.events.presence_router import (
  44. GET_INTERESTED_USERS_CALLBACK,
  45. GET_USERS_FOR_STATES_CALLBACK,
  46. PresenceRouter,
  47. )
  48. from synapse.events.utils import ADD_EXTRA_FIELDS_TO_UNSIGNED_CLIENT_EVENT_CALLBACK
  49. from synapse.handlers.account_data import ON_ACCOUNT_DATA_UPDATED_CALLBACK
  50. from synapse.handlers.auth import (
  51. CHECK_3PID_AUTH_CALLBACK,
  52. CHECK_AUTH_CALLBACK,
  53. GET_DISPLAYNAME_FOR_REGISTRATION_CALLBACK,
  54. GET_USERNAME_FOR_REGISTRATION_CALLBACK,
  55. IS_3PID_ALLOWED_CALLBACK,
  56. ON_LOGGED_OUT_CALLBACK,
  57. AuthHandler,
  58. )
  59. from synapse.handlers.device import DeviceHandler
  60. from synapse.handlers.push_rules import RuleSpec, check_actions
  61. from synapse.http.client import SimpleHttpClient
  62. from synapse.http.server import (
  63. DirectServeHtmlResource,
  64. DirectServeJsonResource,
  65. respond_with_html,
  66. )
  67. from synapse.http.servlet import parse_json_object_from_request
  68. from synapse.http.site import SynapseRequest
  69. from synapse.logging.context import (
  70. defer_to_thread,
  71. make_deferred_yieldable,
  72. run_in_background,
  73. )
  74. from synapse.metrics.background_process_metrics import run_as_background_process
  75. from synapse.module_api.callbacks.account_validity_callbacks import (
  76. IS_USER_EXPIRED_CALLBACK,
  77. ON_LEGACY_ADMIN_REQUEST,
  78. ON_LEGACY_RENEW_CALLBACK,
  79. ON_LEGACY_SEND_MAIL_CALLBACK,
  80. ON_USER_LOGIN_CALLBACK,
  81. ON_USER_REGISTRATION_CALLBACK,
  82. )
  83. from synapse.module_api.callbacks.spamchecker_callbacks import (
  84. CHECK_EVENT_FOR_SPAM_CALLBACK,
  85. CHECK_LOGIN_FOR_SPAM_CALLBACK,
  86. CHECK_MEDIA_FILE_FOR_SPAM_CALLBACK,
  87. CHECK_REGISTRATION_FOR_SPAM_CALLBACK,
  88. CHECK_USERNAME_FOR_SPAM_CALLBACK,
  89. SHOULD_DROP_FEDERATED_EVENT_CALLBACK,
  90. USER_MAY_CREATE_ROOM_ALIAS_CALLBACK,
  91. USER_MAY_CREATE_ROOM_CALLBACK,
  92. USER_MAY_INVITE_CALLBACK,
  93. USER_MAY_JOIN_ROOM_CALLBACK,
  94. USER_MAY_PUBLISH_ROOM_CALLBACK,
  95. USER_MAY_SEND_3PID_INVITE_CALLBACK,
  96. SpamCheckerModuleApiCallbacks,
  97. )
  98. from synapse.module_api.callbacks.third_party_event_rules_callbacks import (
  99. CHECK_CAN_DEACTIVATE_USER_CALLBACK,
  100. CHECK_CAN_SHUTDOWN_ROOM_CALLBACK,
  101. CHECK_EVENT_ALLOWED_CALLBACK,
  102. CHECK_THREEPID_CAN_BE_INVITED_CALLBACK,
  103. CHECK_VISIBILITY_CAN_BE_MODIFIED_CALLBACK,
  104. ON_ADD_USER_THIRD_PARTY_IDENTIFIER_CALLBACK,
  105. ON_CREATE_ROOM_CALLBACK,
  106. ON_NEW_EVENT_CALLBACK,
  107. ON_PROFILE_UPDATE_CALLBACK,
  108. ON_REMOVE_USER_THIRD_PARTY_IDENTIFIER_CALLBACK,
  109. ON_THREEPID_BIND_CALLBACK,
  110. ON_USER_DEACTIVATION_STATUS_CHANGED_CALLBACK,
  111. )
  112. from synapse.push.httppusher import HttpPusher
  113. from synapse.rest.client.login import LoginResponse
  114. from synapse.storage import DataStore
  115. from synapse.storage.background_updates import (
  116. DEFAULT_BATCH_SIZE_CALLBACK,
  117. MIN_BATCH_SIZE_CALLBACK,
  118. ON_UPDATE_CALLBACK,
  119. )
  120. from synapse.storage.database import DatabasePool, LoggingTransaction
  121. from synapse.storage.databases.main.roommember import ProfileInfo
  122. from synapse.types import (
  123. DomainSpecificString,
  124. JsonDict,
  125. JsonMapping,
  126. Requester,
  127. RoomAlias,
  128. RoomID,
  129. StateMap,
  130. UserID,
  131. UserInfo,
  132. UserProfile,
  133. create_requester,
  134. )
  135. from synapse.types.state import StateFilter
  136. from synapse.util import Clock
  137. from synapse.util.async_helpers import maybe_awaitable
  138. from synapse.util.caches.descriptors import CachedFunction, cached as _cached
  139. from synapse.util.frozenutils import freeze
  140. if TYPE_CHECKING:
  141. from synapse.app.generic_worker import GenericWorkerStore
  142. from synapse.server import HomeServer
  143. T = TypeVar("T")
  144. P = ParamSpec("P")
  145. F = TypeVar("F", bound=Callable[..., Any])
  146. """
  147. This package defines the 'stable' API which can be used by extension modules which
  148. are loaded into Synapse.
  149. """
  150. PRESENCE_ALL_USERS = PresenceRouter.ALL_USERS
  151. NOT_SPAM = SpamCheckerModuleApiCallbacks.NOT_SPAM
  152. __all__ = [
  153. "errors",
  154. "make_deferred_yieldable",
  155. "parse_json_object_from_request",
  156. "respond_with_html",
  157. "run_in_background",
  158. "run_as_background_process",
  159. "cached",
  160. "NOT_SPAM",
  161. "UserID",
  162. "DatabasePool",
  163. "LoggingTransaction",
  164. "DirectServeHtmlResource",
  165. "DirectServeJsonResource",
  166. "ModuleApi",
  167. "PRESENCE_ALL_USERS",
  168. "LoginResponse",
  169. "JsonDict",
  170. "JsonMapping",
  171. "EventBase",
  172. "StateMap",
  173. "ProfileInfo",
  174. "RoomAlias",
  175. "UserProfile",
  176. ]
  177. logger = logging.getLogger(__name__)
  178. @attr.s(auto_attribs=True)
  179. class UserIpAndAgent:
  180. """
  181. An IP address and user agent used by a user to connect to this homeserver.
  182. """
  183. ip: str
  184. user_agent: str
  185. # The time at which this user agent/ip was last seen.
  186. last_seen: int
  187. def cached(
  188. *,
  189. max_entries: int = 1000,
  190. num_args: Optional[int] = None,
  191. uncached_args: Optional[Collection[str]] = None,
  192. ) -> Callable[[F], CachedFunction[F]]:
  193. """Returns a decorator that applies a memoizing cache around the function. This
  194. decorator behaves similarly to functools.lru_cache.
  195. Example:
  196. @cached()
  197. def foo('a', 'b'):
  198. ...
  199. Added in Synapse v1.74.0.
  200. Args:
  201. max_entries: The maximum number of entries in the cache. If the cache is full
  202. and a new entry is added, the least recently accessed entry will be evicted
  203. from the cache.
  204. num_args: The number of positional arguments (excluding `self`) to use as cache
  205. keys. Defaults to all named args of the function.
  206. uncached_args: A list of argument names to not use as the cache key. (`self` is
  207. always ignored.) Cannot be used with num_args.
  208. Returns:
  209. A decorator that applies a memoizing cache around the function.
  210. """
  211. return _cached(
  212. max_entries=max_entries,
  213. num_args=num_args,
  214. uncached_args=uncached_args,
  215. )
  216. class ModuleApi:
  217. """A proxy object that gets passed to various plugin modules so they
  218. can register new users etc if necessary.
  219. """
  220. def __init__(self, hs: "HomeServer", auth_handler: AuthHandler) -> None:
  221. self._hs = hs
  222. # TODO: Fix this type hint once the types for the data stores have been ironed
  223. # out.
  224. self._store: Union[DataStore, "GenericWorkerStore"] = hs.get_datastores().main
  225. self._storage_controllers = hs.get_storage_controllers()
  226. self._auth = hs.get_auth()
  227. self._auth_handler = auth_handler
  228. self._server_name = hs.hostname
  229. self._presence_stream = hs.get_event_sources().sources.presence
  230. self._state = hs.get_state_handler()
  231. self._clock: Clock = hs.get_clock()
  232. self._registration_handler = hs.get_registration_handler()
  233. self._send_email_handler = hs.get_send_email_handler()
  234. self._push_rules_handler = hs.get_push_rules_handler()
  235. self._pusherpool = hs.get_pusherpool()
  236. self._device_handler = hs.get_device_handler()
  237. self.custom_template_dir = hs.config.server.custom_template_directory
  238. self._callbacks = hs.get_module_api_callbacks()
  239. self.msc3861_oauth_delegation_enabled = hs.config.experimental.msc3861.enabled
  240. self._event_serializer = hs.get_event_client_serializer()
  241. try:
  242. app_name = self._hs.config.email.email_app_name
  243. self._from_string = self._hs.config.email.email_notif_from % {
  244. "app": app_name
  245. }
  246. except (KeyError, TypeError):
  247. # If substitution failed (which can happen if the string contains
  248. # placeholders other than just "app", or if the type of the placeholder is
  249. # not a string), fall back to the bare strings.
  250. self._from_string = self._hs.config.email.email_notif_from
  251. self._raw_from = email.utils.parseaddr(self._from_string)[1]
  252. # We expose these as properties below in order to attach a helpful docstring.
  253. self._http_client: SimpleHttpClient = hs.get_simple_http_client()
  254. self._public_room_list_manager = PublicRoomListManager(hs)
  255. self._account_data_manager = AccountDataManager(hs)
  256. self._password_auth_provider = hs.get_password_auth_provider()
  257. self._presence_router = hs.get_presence_router()
  258. self._account_data_handler = hs.get_account_data_handler()
  259. #################################################################################
  260. # The following methods should only be called during the module's initialisation.
  261. def register_spam_checker_callbacks(
  262. self,
  263. *,
  264. check_event_for_spam: Optional[CHECK_EVENT_FOR_SPAM_CALLBACK] = None,
  265. should_drop_federated_event: Optional[
  266. SHOULD_DROP_FEDERATED_EVENT_CALLBACK
  267. ] = None,
  268. user_may_join_room: Optional[USER_MAY_JOIN_ROOM_CALLBACK] = None,
  269. user_may_invite: Optional[USER_MAY_INVITE_CALLBACK] = None,
  270. user_may_send_3pid_invite: Optional[USER_MAY_SEND_3PID_INVITE_CALLBACK] = None,
  271. user_may_create_room: Optional[USER_MAY_CREATE_ROOM_CALLBACK] = None,
  272. user_may_create_room_alias: Optional[
  273. USER_MAY_CREATE_ROOM_ALIAS_CALLBACK
  274. ] = None,
  275. user_may_publish_room: Optional[USER_MAY_PUBLISH_ROOM_CALLBACK] = None,
  276. check_username_for_spam: Optional[CHECK_USERNAME_FOR_SPAM_CALLBACK] = None,
  277. check_registration_for_spam: Optional[
  278. CHECK_REGISTRATION_FOR_SPAM_CALLBACK
  279. ] = None,
  280. check_media_file_for_spam: Optional[CHECK_MEDIA_FILE_FOR_SPAM_CALLBACK] = None,
  281. check_login_for_spam: Optional[CHECK_LOGIN_FOR_SPAM_CALLBACK] = None,
  282. ) -> None:
  283. """Registers callbacks for spam checking capabilities.
  284. Added in Synapse v1.37.0.
  285. """
  286. return self._callbacks.spam_checker.register_callbacks(
  287. check_event_for_spam=check_event_for_spam,
  288. should_drop_federated_event=should_drop_federated_event,
  289. user_may_join_room=user_may_join_room,
  290. user_may_invite=user_may_invite,
  291. user_may_send_3pid_invite=user_may_send_3pid_invite,
  292. user_may_create_room=user_may_create_room,
  293. user_may_create_room_alias=user_may_create_room_alias,
  294. user_may_publish_room=user_may_publish_room,
  295. check_username_for_spam=check_username_for_spam,
  296. check_registration_for_spam=check_registration_for_spam,
  297. check_media_file_for_spam=check_media_file_for_spam,
  298. check_login_for_spam=check_login_for_spam,
  299. )
  300. def register_account_validity_callbacks(
  301. self,
  302. *,
  303. is_user_expired: Optional[IS_USER_EXPIRED_CALLBACK] = None,
  304. on_user_registration: Optional[ON_USER_REGISTRATION_CALLBACK] = None,
  305. on_user_login: Optional[ON_USER_LOGIN_CALLBACK] = None,
  306. on_legacy_send_mail: Optional[ON_LEGACY_SEND_MAIL_CALLBACK] = None,
  307. on_legacy_renew: Optional[ON_LEGACY_RENEW_CALLBACK] = None,
  308. on_legacy_admin_request: Optional[ON_LEGACY_ADMIN_REQUEST] = None,
  309. ) -> None:
  310. """Registers callbacks for account validity capabilities.
  311. Added in Synapse v1.39.0.
  312. """
  313. return self._callbacks.account_validity.register_callbacks(
  314. is_user_expired=is_user_expired,
  315. on_user_registration=on_user_registration,
  316. on_user_login=on_user_login,
  317. on_legacy_send_mail=on_legacy_send_mail,
  318. on_legacy_renew=on_legacy_renew,
  319. on_legacy_admin_request=on_legacy_admin_request,
  320. )
  321. def register_third_party_rules_callbacks(
  322. self,
  323. *,
  324. check_event_allowed: Optional[CHECK_EVENT_ALLOWED_CALLBACK] = None,
  325. on_create_room: Optional[ON_CREATE_ROOM_CALLBACK] = None,
  326. check_threepid_can_be_invited: Optional[
  327. CHECK_THREEPID_CAN_BE_INVITED_CALLBACK
  328. ] = None,
  329. check_visibility_can_be_modified: Optional[
  330. CHECK_VISIBILITY_CAN_BE_MODIFIED_CALLBACK
  331. ] = None,
  332. on_new_event: Optional[ON_NEW_EVENT_CALLBACK] = None,
  333. check_can_shutdown_room: Optional[CHECK_CAN_SHUTDOWN_ROOM_CALLBACK] = None,
  334. check_can_deactivate_user: Optional[CHECK_CAN_DEACTIVATE_USER_CALLBACK] = None,
  335. on_profile_update: Optional[ON_PROFILE_UPDATE_CALLBACK] = None,
  336. on_user_deactivation_status_changed: Optional[
  337. ON_USER_DEACTIVATION_STATUS_CHANGED_CALLBACK
  338. ] = None,
  339. on_threepid_bind: Optional[ON_THREEPID_BIND_CALLBACK] = None,
  340. on_add_user_third_party_identifier: Optional[
  341. ON_ADD_USER_THIRD_PARTY_IDENTIFIER_CALLBACK
  342. ] = None,
  343. on_remove_user_third_party_identifier: Optional[
  344. ON_REMOVE_USER_THIRD_PARTY_IDENTIFIER_CALLBACK
  345. ] = None,
  346. ) -> None:
  347. """Registers callbacks for third party event rules capabilities.
  348. Added in Synapse v1.39.0.
  349. """
  350. return self._callbacks.third_party_event_rules.register_third_party_rules_callbacks(
  351. check_event_allowed=check_event_allowed,
  352. on_create_room=on_create_room,
  353. check_threepid_can_be_invited=check_threepid_can_be_invited,
  354. check_visibility_can_be_modified=check_visibility_can_be_modified,
  355. on_new_event=on_new_event,
  356. check_can_shutdown_room=check_can_shutdown_room,
  357. check_can_deactivate_user=check_can_deactivate_user,
  358. on_profile_update=on_profile_update,
  359. on_user_deactivation_status_changed=on_user_deactivation_status_changed,
  360. on_threepid_bind=on_threepid_bind,
  361. on_add_user_third_party_identifier=on_add_user_third_party_identifier,
  362. on_remove_user_third_party_identifier=on_remove_user_third_party_identifier,
  363. )
  364. def register_presence_router_callbacks(
  365. self,
  366. *,
  367. get_users_for_states: Optional[GET_USERS_FOR_STATES_CALLBACK] = None,
  368. get_interested_users: Optional[GET_INTERESTED_USERS_CALLBACK] = None,
  369. ) -> None:
  370. """Registers callbacks for presence router capabilities.
  371. Added in Synapse v1.42.0.
  372. """
  373. return self._presence_router.register_presence_router_callbacks(
  374. get_users_for_states=get_users_for_states,
  375. get_interested_users=get_interested_users,
  376. )
  377. def register_password_auth_provider_callbacks(
  378. self,
  379. *,
  380. check_3pid_auth: Optional[CHECK_3PID_AUTH_CALLBACK] = None,
  381. on_logged_out: Optional[ON_LOGGED_OUT_CALLBACK] = None,
  382. auth_checkers: Optional[
  383. Dict[Tuple[str, Tuple[str, ...]], CHECK_AUTH_CALLBACK]
  384. ] = None,
  385. is_3pid_allowed: Optional[IS_3PID_ALLOWED_CALLBACK] = None,
  386. get_username_for_registration: Optional[
  387. GET_USERNAME_FOR_REGISTRATION_CALLBACK
  388. ] = None,
  389. get_displayname_for_registration: Optional[
  390. GET_DISPLAYNAME_FOR_REGISTRATION_CALLBACK
  391. ] = None,
  392. ) -> None:
  393. """Registers callbacks for password auth provider capabilities.
  394. Added in Synapse v1.46.0.
  395. """
  396. if self.msc3861_oauth_delegation_enabled:
  397. raise ConfigError(
  398. "Cannot use password auth provider callbacks when OAuth delegation is enabled"
  399. )
  400. return self._password_auth_provider.register_password_auth_provider_callbacks(
  401. check_3pid_auth=check_3pid_auth,
  402. on_logged_out=on_logged_out,
  403. is_3pid_allowed=is_3pid_allowed,
  404. auth_checkers=auth_checkers,
  405. get_username_for_registration=get_username_for_registration,
  406. get_displayname_for_registration=get_displayname_for_registration,
  407. )
  408. def register_background_update_controller_callbacks(
  409. self,
  410. *,
  411. on_update: ON_UPDATE_CALLBACK,
  412. default_batch_size: Optional[DEFAULT_BATCH_SIZE_CALLBACK] = None,
  413. min_batch_size: Optional[MIN_BATCH_SIZE_CALLBACK] = None,
  414. ) -> None:
  415. """Registers background update controller callbacks.
  416. Added in Synapse v1.49.0.
  417. """
  418. for db in self._hs.get_datastores().databases:
  419. db.updates.register_update_controller_callbacks(
  420. on_update=on_update,
  421. default_batch_size=default_batch_size,
  422. min_batch_size=min_batch_size,
  423. )
  424. def register_account_data_callbacks(
  425. self,
  426. *,
  427. on_account_data_updated: Optional[ON_ACCOUNT_DATA_UPDATED_CALLBACK] = None,
  428. ) -> None:
  429. """Registers account data callbacks.
  430. Added in Synapse 1.57.0.
  431. """
  432. return self._account_data_handler.register_module_callbacks(
  433. on_account_data_updated=on_account_data_updated,
  434. )
  435. def register_web_resource(self, path: str, resource: Resource) -> None:
  436. """Registers a web resource to be served at the given path.
  437. This function should be called during initialisation of the module.
  438. If multiple modules register a resource for the same path, the module that
  439. appears the highest in the configuration file takes priority.
  440. Added in Synapse v1.37.0.
  441. Args:
  442. path: The path to register the resource for.
  443. resource: The resource to attach to this path.
  444. """
  445. self._hs.register_module_web_resource(path, resource)
  446. def register_add_extra_fields_to_unsigned_client_event_callbacks(
  447. self,
  448. *,
  449. add_field_to_unsigned_callback: Optional[
  450. ADD_EXTRA_FIELDS_TO_UNSIGNED_CLIENT_EVENT_CALLBACK
  451. ] = None,
  452. ) -> None:
  453. """Registers a callback that can be used to add fields to the unsigned
  454. section of events.
  455. The callback is called every time an event is sent down to a client.
  456. Added in Synapse 1.96.0
  457. """
  458. if add_field_to_unsigned_callback is not None:
  459. self._event_serializer.register_add_extra_fields_to_unsigned_client_event_callback(
  460. add_field_to_unsigned_callback
  461. )
  462. #########################################################################
  463. # The following methods can be called by the module at any point in time.
  464. @property
  465. def http_client(self) -> SimpleHttpClient:
  466. """Allows making outbound HTTP requests to remote resources.
  467. An instance of synapse.http.client.SimpleHttpClient
  468. Added in Synapse v1.22.0.
  469. """
  470. return self._http_client
  471. @property
  472. def public_room_list_manager(self) -> "PublicRoomListManager":
  473. """Allows adding to, removing from and checking the status of rooms in the
  474. public room list.
  475. An instance of synapse.module_api.PublicRoomListManager
  476. Added in Synapse v1.22.0.
  477. """
  478. return self._public_room_list_manager
  479. @property
  480. def account_data_manager(self) -> "AccountDataManager":
  481. """Allows reading and modifying users' account data.
  482. Added in Synapse v1.57.0.
  483. """
  484. return self._account_data_manager
  485. @property
  486. def public_baseurl(self) -> str:
  487. """The configured public base URL for this homeserver.
  488. Added in Synapse v1.39.0.
  489. """
  490. return self._hs.config.server.public_baseurl
  491. @property
  492. def email_app_name(self) -> str:
  493. """The application name configured in the homeserver's configuration.
  494. Added in Synapse v1.39.0.
  495. """
  496. return self._hs.config.email.email_app_name
  497. @property
  498. def server_name(self) -> str:
  499. """The server name for the local homeserver.
  500. Added in Synapse v1.53.0.
  501. """
  502. return self._server_name
  503. @property
  504. def worker_name(self) -> Optional[str]:
  505. """The name of the worker this specific instance is running as per the
  506. "worker_name" configuration setting, or None if it's the main process.
  507. Added in Synapse v1.53.0.
  508. """
  509. return self._hs.config.worker.worker_name
  510. @property
  511. def worker_app(self) -> Optional[str]:
  512. """The name of the worker app this specific instance is running as per the
  513. "worker_app" configuration setting, or None if it's the main process.
  514. Added in Synapse v1.53.0.
  515. """
  516. return self._hs.config.worker.worker_app
  517. async def get_userinfo_by_id(self, user_id: str) -> Optional[UserInfo]:
  518. """Get user info by user_id
  519. Added in Synapse v1.41.0.
  520. Args:
  521. user_id: Fully qualified user id.
  522. Returns:
  523. UserInfo object if a user was found, otherwise None
  524. """
  525. return await self._store.get_user_by_id(user_id)
  526. async def get_user_by_req(
  527. self,
  528. req: SynapseRequest,
  529. allow_guest: bool = False,
  530. allow_expired: bool = False,
  531. ) -> Requester:
  532. """Check the access_token provided for a request
  533. Added in Synapse v1.39.0.
  534. Args:
  535. req: Incoming HTTP request
  536. allow_guest: True if guest users should be allowed. If this
  537. is False, and the access token is for a guest user, an
  538. AuthError will be thrown
  539. allow_expired: True if expired users should be allowed. If this
  540. is False, and the access token is for an expired user, an
  541. AuthError will be thrown
  542. Returns:
  543. The requester for this request
  544. Raises:
  545. InvalidClientCredentialsError: if no user by that token exists,
  546. or the token is invalid.
  547. """
  548. return await self._auth.get_user_by_req(
  549. req,
  550. allow_guest,
  551. allow_expired=allow_expired,
  552. )
  553. async def is_user_admin(self, user_id: str) -> bool:
  554. """Checks if a user is a server admin.
  555. Added in Synapse v1.39.0.
  556. Args:
  557. user_id: The Matrix ID of the user to check.
  558. Returns:
  559. True if the user is a server admin, False otherwise.
  560. """
  561. return await self._store.is_server_admin(UserID.from_string(user_id))
  562. async def set_user_admin(self, user_id: str, admin: bool) -> None:
  563. """Sets if a user is a server admin.
  564. Added in Synapse v1.56.0.
  565. Args:
  566. user_id: The Matrix ID of the user to set admin status for.
  567. admin: True iff the user is to be a server admin, false otherwise.
  568. """
  569. await self._store.set_server_admin(UserID.from_string(user_id), admin)
  570. def get_qualified_user_id(self, username: str) -> str:
  571. """Qualify a user id, if necessary
  572. Takes a user id provided by the user and adds the @ and :domain to
  573. qualify it, if necessary
  574. Added in Synapse v0.25.0.
  575. Args:
  576. username: provided user id
  577. Returns:
  578. qualified @user:id
  579. """
  580. if username.startswith("@"):
  581. return username
  582. return UserID(username, self._hs.hostname).to_string()
  583. async def get_profile_for_user(self, localpart: str) -> ProfileInfo:
  584. """Look up the profile info for the user with the given localpart.
  585. Added in Synapse v1.39.0.
  586. Args:
  587. localpart: The localpart to look up profile information for.
  588. Returns:
  589. The profile information (i.e. display name and avatar URL).
  590. """
  591. server_name = self._hs.hostname
  592. user_id = UserID.from_string(f"@{localpart}:{server_name}")
  593. return await self._store.get_profileinfo(user_id)
  594. async def get_threepids_for_user(self, user_id: str) -> List[Dict[str, str]]:
  595. """Look up the threepids (email addresses and phone numbers) associated with the
  596. given Matrix user ID.
  597. Added in Synapse v1.39.0.
  598. Args:
  599. user_id: The Matrix user ID to look up threepids for.
  600. Returns:
  601. A list of threepids, each threepid being represented by a dictionary
  602. containing a "medium" key which value is "email" for email addresses and
  603. "msisdn" for phone numbers, and an "address" key which value is the
  604. threepid's address.
  605. """
  606. return [attr.asdict(t) for t in await self._store.user_get_threepids(user_id)]
  607. def check_user_exists(self, user_id: str) -> "defer.Deferred[Optional[str]]":
  608. """Check if user exists.
  609. Added in Synapse v0.25.0.
  610. Args:
  611. user_id: Complete @user:id
  612. Returns:
  613. Canonical (case-corrected) user_id, or None
  614. if the user is not registered.
  615. """
  616. return defer.ensureDeferred(self._auth_handler.check_user_exists(user_id))
  617. @defer.inlineCallbacks
  618. def register(
  619. self,
  620. localpart: str,
  621. displayname: Optional[str] = None,
  622. emails: Optional[List[str]] = None,
  623. ) -> Generator["defer.Deferred[Any]", Any, Tuple[str, str]]:
  624. """Registers a new user with given localpart and optional displayname, emails.
  625. Also returns an access token for the new user.
  626. Deprecated: avoid this, as it generates a new device with no way to
  627. return that device to the user. Prefer separate calls to register_user and
  628. register_device.
  629. Added in Synapse v0.25.0.
  630. Args:
  631. localpart: The localpart of the new user.
  632. displayname: The displayname of the new user.
  633. emails: Emails to bind to the new user.
  634. Returns:
  635. a 2-tuple of (user_id, access_token)
  636. """
  637. logger.warning(
  638. "Using deprecated ModuleApi.register which creates a dummy user device."
  639. )
  640. user_id = yield self.register_user(localpart, displayname, emails or [])
  641. _, access_token, _, _ = yield self.register_device(user_id)
  642. return user_id, access_token
  643. def register_user(
  644. self,
  645. localpart: str,
  646. displayname: Optional[str] = None,
  647. emails: Optional[List[str]] = None,
  648. admin: bool = False,
  649. ) -> "defer.Deferred[str]":
  650. """Registers a new user with given localpart and optional displayname, emails.
  651. Added in Synapse v1.2.0.
  652. Changed in Synapse v1.56.0: add 'admin' argument to register the user as admin.
  653. Args:
  654. localpart: The localpart of the new user.
  655. displayname: The displayname of the new user.
  656. emails: Emails to bind to the new user.
  657. admin: True if the user should be registered as a server admin.
  658. Raises:
  659. SynapseError if there is an error performing the registration. Check the
  660. 'errcode' property for more information on the reason for failure
  661. Returns:
  662. user_id
  663. """
  664. return defer.ensureDeferred(
  665. self._hs.get_registration_handler().register_user(
  666. localpart=localpart,
  667. default_display_name=displayname,
  668. bind_emails=emails or [],
  669. admin=admin,
  670. )
  671. )
  672. def register_device(
  673. self,
  674. user_id: str,
  675. device_id: Optional[str] = None,
  676. initial_display_name: Optional[str] = None,
  677. ) -> "defer.Deferred[Tuple[str, str, Optional[int], Optional[str]]]":
  678. """Register a device for a user and generate an access token.
  679. Added in Synapse v1.2.0.
  680. Args:
  681. user_id: full canonical @user:id
  682. device_id: The device ID to check, or None to generate
  683. a new one.
  684. initial_display_name: An optional display name for the
  685. device.
  686. Returns:
  687. Tuple of device ID, access token, access token expiration time and refresh token
  688. """
  689. return defer.ensureDeferred(
  690. self._hs.get_registration_handler().register_device(
  691. user_id=user_id,
  692. device_id=device_id,
  693. initial_display_name=initial_display_name,
  694. )
  695. )
  696. def record_user_external_id(
  697. self, auth_provider_id: str, remote_user_id: str, registered_user_id: str
  698. ) -> defer.Deferred:
  699. """Record a mapping between an external user id from a single sign-on provider
  700. and a mxid.
  701. Added in Synapse v1.9.0.
  702. Args:
  703. auth_provider: identifier for the remote auth provider, see `sso` and
  704. `oidc_providers` in the homeserver configuration.
  705. Note that no error is raised if the provided value is not in the
  706. homeserver configuration.
  707. external_id: id on that system
  708. user_id: complete mxid that it is mapped to
  709. """
  710. return defer.ensureDeferred(
  711. self._store.record_user_external_id(
  712. auth_provider_id, remote_user_id, registered_user_id
  713. )
  714. )
  715. async def create_login_token(
  716. self,
  717. user_id: str,
  718. duration_in_ms: int = (2 * 60 * 1000),
  719. auth_provider_id: Optional[str] = None,
  720. auth_provider_session_id: Optional[str] = None,
  721. ) -> str:
  722. """Create a login token suitable for m.login.token authentication
  723. Added in Synapse v1.69.0.
  724. Args:
  725. user_id: gives the ID of the user that the token is for
  726. duration_in_ms: the time that the token will be valid for
  727. auth_provider_id: the ID of the SSO IdP that the user used to authenticate
  728. to get this token, if any. This is encoded in the token so that
  729. /login can report stats on number of successful logins by IdP.
  730. auth_provider_session_id: The session ID got during login from the SSO IdP,
  731. if any.
  732. """
  733. return await self._hs.get_auth_handler().create_login_token_for_user_id(
  734. user_id,
  735. duration_in_ms,
  736. auth_provider_id,
  737. auth_provider_session_id,
  738. )
  739. @defer.inlineCallbacks
  740. def invalidate_access_token(
  741. self, access_token: str
  742. ) -> Generator["defer.Deferred[Any]", Any, None]:
  743. """Invalidate an access token for a user
  744. Can only be called from the main process.
  745. Added in Synapse v0.25.0.
  746. Args:
  747. access_token: access token
  748. Returns:
  749. twisted.internet.defer.Deferred - resolves once the access token
  750. has been removed.
  751. Raises:
  752. synapse.api.errors.AuthError: the access token is invalid
  753. """
  754. assert isinstance(
  755. self._device_handler, DeviceHandler
  756. ), "invalidate_access_token can only be called on the main process"
  757. # see if the access token corresponds to a device
  758. user_info = yield defer.ensureDeferred(
  759. self._auth.get_user_by_access_token(access_token)
  760. )
  761. device_id = user_info.get("device_id")
  762. user_id = user_info["user"].to_string()
  763. if device_id:
  764. # delete the device, which will also delete its access tokens
  765. yield defer.ensureDeferred(
  766. self._device_handler.delete_devices(user_id, [device_id])
  767. )
  768. else:
  769. # no associated device. Just delete the access token.
  770. yield defer.ensureDeferred(
  771. self._auth_handler.delete_access_token(access_token)
  772. )
  773. def run_db_interaction(
  774. self,
  775. desc: str,
  776. func: Callable[Concatenate[LoggingTransaction, P], T],
  777. *args: P.args,
  778. **kwargs: P.kwargs,
  779. ) -> "defer.Deferred[T]":
  780. """Run a function with a database connection
  781. Added in Synapse v0.25.0.
  782. Args:
  783. desc: description for the transaction, for metrics etc
  784. func: function to be run. Passed a database cursor object
  785. as well as *args and **kwargs
  786. *args: positional args to be passed to func
  787. **kwargs: named args to be passed to func
  788. Returns:
  789. Result of func
  790. """
  791. # type-ignore: See https://github.com/python/mypy/issues/8862
  792. return defer.ensureDeferred(
  793. self._store.db_pool.runInteraction(desc, func, *args, **kwargs) # type: ignore[arg-type]
  794. )
  795. def register_cached_function(self, cached_func: CachedFunction) -> None:
  796. """Register a cached function that should be invalidated across workers.
  797. Invalidation local to a worker can be done directly using `cached_func.invalidate`,
  798. however invalidation that needs to go to other workers needs to call `invalidate_cache`
  799. on the module API instead.
  800. Added in Synapse v1.69.0.
  801. Args:
  802. cached_function: The cached function that will be registered to receive invalidation
  803. locally and from other workers.
  804. """
  805. self._store.register_external_cached_function(
  806. f"{cached_func.__module__}.{cached_func.__name__}", cached_func
  807. )
  808. async def invalidate_cache(
  809. self, cached_func: CachedFunction, keys: Tuple[Any, ...]
  810. ) -> None:
  811. """Invalidate a cache entry of a cached function across workers. The cached function
  812. needs to be registered on all workers first with `register_cached_function`.
  813. Added in Synapse v1.69.0.
  814. Args:
  815. cached_function: The cached function that needs an invalidation
  816. keys: keys of the entry to invalidate, usually matching the arguments of the
  817. cached function.
  818. """
  819. cached_func.invalidate(keys)
  820. await self._store.send_invalidation_to_replication(
  821. f"{cached_func.__module__}.{cached_func.__name__}",
  822. keys,
  823. )
  824. async def complete_sso_login_async(
  825. self,
  826. registered_user_id: str,
  827. request: SynapseRequest,
  828. client_redirect_url: str,
  829. new_user: bool = False,
  830. auth_provider_id: str = "<unknown>",
  831. ) -> None:
  832. """Complete a SSO login by redirecting the user to a page to confirm whether they
  833. want their access token sent to `client_redirect_url`, or redirect them to that
  834. URL with a token directly if the URL matches with one of the whitelisted clients.
  835. Added in Synapse v1.13.0.
  836. Args:
  837. registered_user_id: The MXID that has been registered as a previous step of
  838. of this SSO login.
  839. request: The request to respond to.
  840. client_redirect_url: The URL to which to offer to redirect the user (or to
  841. redirect them directly if whitelisted).
  842. new_user: set to true to use wording for the consent appropriate to a user
  843. who has just registered.
  844. auth_provider_id: the ID of the SSO IdP which was used to log in. This
  845. is used to track counts of sucessful logins by IdP.
  846. """
  847. await self._auth_handler.complete_sso_login(
  848. registered_user_id,
  849. auth_provider_id,
  850. request,
  851. client_redirect_url,
  852. new_user=new_user,
  853. )
  854. @defer.inlineCallbacks
  855. def get_state_events_in_room(
  856. self, room_id: str, types: Iterable[Tuple[str, Optional[str]]]
  857. ) -> Generator[defer.Deferred, Any, Iterable[EventBase]]:
  858. """Gets current state events for the given room.
  859. (This is exposed for compatibility with the old SpamCheckerApi. We should
  860. probably deprecate it and replace it with an async method in a subclass.)
  861. Added in Synapse v1.22.0.
  862. Args:
  863. room_id: The room ID to get state events in.
  864. types: The event type and state key (using None
  865. to represent 'any') of the room state to acquire.
  866. Returns:
  867. The filtered state events in the room.
  868. """
  869. state_ids = yield defer.ensureDeferred(
  870. self._storage_controllers.state.get_current_state_ids(
  871. room_id=room_id, state_filter=StateFilter.from_types(types)
  872. )
  873. )
  874. state = yield defer.ensureDeferred(self._store.get_events(state_ids.values()))
  875. return state.values()
  876. async def update_room_membership(
  877. self,
  878. sender: str,
  879. target: str,
  880. room_id: str,
  881. new_membership: str,
  882. content: Optional[JsonDict] = None,
  883. remote_room_hosts: Optional[List[str]] = None,
  884. ) -> EventBase:
  885. """Updates the membership of a user to the given value.
  886. Added in Synapse v1.46.0.
  887. Changed in Synapse v1.65.0: Added the 'remote_room_hosts' parameter.
  888. Args:
  889. sender: The user performing the membership change. Must be a user local to
  890. this homeserver.
  891. target: The user whose membership is changing. This is often the same value
  892. as `sender`, but it might differ in some cases (e.g. when kicking a user,
  893. the `sender` is the user performing the kick and the `target` is the user
  894. being kicked).
  895. room_id: The room in which to change the membership.
  896. new_membership: The new membership state of `target` after this operation. See
  897. https://spec.matrix.org/unstable/client-server-api/#mroommember for the
  898. list of allowed values.
  899. content: Additional values to include in the resulting event's content.
  900. remote_room_hosts: Remote servers to use for remote joins/knocks/etc.
  901. Returns:
  902. The newly created membership event.
  903. Raises:
  904. RuntimeError if the `sender` isn't a local user.
  905. ShadowBanError if a shadow-banned requester attempts to send an invite.
  906. SynapseError if the module attempts to send a membership event that isn't
  907. allowed, either by the server's configuration (e.g. trying to set a
  908. per-room display name that's too long) or by the validation rules around
  909. membership updates (e.g. the `membership` value is invalid).
  910. """
  911. if not self.is_mine(sender):
  912. raise RuntimeError(
  913. "Tried to send an event as a user that isn't local to this homeserver",
  914. )
  915. requester = create_requester(sender)
  916. target_user_id = UserID.from_string(target)
  917. if content is None:
  918. content = {}
  919. # Set the profile if not already done by the module.
  920. if "avatar_url" not in content or "displayname" not in content:
  921. try:
  922. # Try to fetch the user's profile.
  923. profile = await self._hs.get_profile_handler().get_profile(
  924. target_user_id.to_string(),
  925. )
  926. except SynapseError as e:
  927. # If the profile couldn't be found, use default values.
  928. profile = {
  929. "displayname": target_user_id.localpart,
  930. "avatar_url": None,
  931. }
  932. if e.code != 404:
  933. # If the error isn't 404, it means we tried to fetch the profile over
  934. # federation but the remote server responded with a non-standard
  935. # status code.
  936. logger.error(
  937. "Got non-404 error status when fetching profile for %s",
  938. target_user_id.to_string(),
  939. )
  940. # Set the profile where it needs to be set.
  941. if "avatar_url" not in content:
  942. content["avatar_url"] = profile["avatar_url"]
  943. if "displayname" not in content:
  944. content["displayname"] = profile["displayname"]
  945. event_id, _ = await self._hs.get_room_member_handler().update_membership(
  946. requester=requester,
  947. target=target_user_id,
  948. room_id=room_id,
  949. action=new_membership,
  950. content=content,
  951. remote_room_hosts=remote_room_hosts,
  952. )
  953. # Try to retrieve the resulting event.
  954. event = await self._hs.get_datastores().main.get_event(event_id)
  955. return event
  956. async def create_and_send_event_into_room(self, event_dict: JsonDict) -> EventBase:
  957. """Create and send an event into a room.
  958. Membership events are not supported by this method. To update a user's membership
  959. in a room, please use the `update_room_membership` method instead.
  960. Added in Synapse v1.22.0.
  961. Args:
  962. event_dict: A dictionary representing the event to send.
  963. Required keys are `type`, `room_id`, `sender` and `content`.
  964. Returns:
  965. The event that was sent. If state event deduplication happened, then
  966. the previous, duplicate event instead.
  967. Raises:
  968. SynapseError if the event was not allowed.
  969. """
  970. # Create a requester object
  971. requester = create_requester(
  972. event_dict["sender"], authenticated_entity=self._server_name
  973. )
  974. # Create and send the event
  975. (
  976. event,
  977. _,
  978. ) = await self._hs.get_event_creation_handler().create_and_send_nonmember_event(
  979. requester,
  980. event_dict,
  981. ratelimit=False,
  982. ignore_shadow_ban=True,
  983. )
  984. return event
  985. async def send_local_online_presence_to(self, users: Iterable[str]) -> None:
  986. """
  987. Forces the equivalent of a presence initial_sync for a set of local or remote
  988. users. The users will receive presence for all currently online users that they
  989. are considered interested in.
  990. Updates to remote users will be sent immediately, whereas local users will receive
  991. them on their next sync attempt.
  992. Note that this method can only be run on the process that is configured to write to the
  993. presence stream. By default this is the main process.
  994. Added in Synapse v1.32.0.
  995. """
  996. if self._hs._instance_name not in self._hs.config.worker.writers.presence:
  997. raise Exception(
  998. "send_local_online_presence_to can only be run "
  999. "on the process that is configured to write to the "
  1000. "presence stream (by default this is the main process)",
  1001. )
  1002. local_users = set()
  1003. remote_users = set()
  1004. for user in users:
  1005. if self._hs.is_mine_id(user):
  1006. local_users.add(user)
  1007. else:
  1008. remote_users.add(user)
  1009. # We pull out the presence handler here to break a cyclic
  1010. # dependency between the presence router and module API.
  1011. presence_handler = self._hs.get_presence_handler()
  1012. if local_users:
  1013. # Force a presence initial_sync for these users next time they sync.
  1014. await presence_handler.send_full_presence_to_users(local_users)
  1015. for user in remote_users:
  1016. # Retrieve presence state for currently online users that this user
  1017. # is considered interested in.
  1018. presence_events, _ = await self._presence_stream.get_new_events(
  1019. UserID.from_string(user), from_key=None, include_offline=False
  1020. )
  1021. # Send to remote destinations.
  1022. destination = UserID.from_string(user).domain
  1023. await presence_handler.get_federation_queue().send_presence_to_destinations(
  1024. presence_events, [destination]
  1025. )
  1026. async def set_presence_for_users(
  1027. self, users: Mapping[str, Tuple[str, Optional[str]]]
  1028. ) -> None:
  1029. """
  1030. Update the internal presence state of users.
  1031. This can be used for either local or remote users.
  1032. Note that this method can only be run on the process that is configured to write to the
  1033. presence stream. By default, this is the main process.
  1034. Added in Synapse v1.96.0.
  1035. """
  1036. # We pull out the presence handler here to break a cyclic
  1037. # dependency between the presence router and module API.
  1038. presence_handler = self._hs.get_presence_handler()
  1039. from synapse.handlers.presence import PresenceHandler
  1040. assert isinstance(presence_handler, PresenceHandler)
  1041. states = await presence_handler.current_state_for_users(users.keys())
  1042. for user_id, (state, status_msg) in users.items():
  1043. prev_state = states.setdefault(user_id, UserPresenceState.default(user_id))
  1044. states[user_id] = prev_state.copy_and_replace(
  1045. state=state, status_msg=status_msg
  1046. )
  1047. await presence_handler._update_states(states.values(), force_notify=True)
  1048. def looping_background_call(
  1049. self,
  1050. f: Callable,
  1051. msec: float,
  1052. *args: object,
  1053. desc: Optional[str] = None,
  1054. run_on_all_instances: bool = False,
  1055. **kwargs: object,
  1056. ) -> None:
  1057. """Wraps a function as a background process and calls it repeatedly.
  1058. NOTE: Will only run on the instance that is configured to run
  1059. background processes (which is the main process by default), unless
  1060. `run_on_all_workers` is set.
  1061. Waits `msec` initially before calling `f` for the first time.
  1062. Added in Synapse v1.39.0.
  1063. Args:
  1064. f: The function to call repeatedly. f can be either synchronous or
  1065. asynchronous, and must follow Synapse's logcontext rules.
  1066. More info about logcontexts is available at
  1067. https://matrix-org.github.io/synapse/latest/log_contexts.html
  1068. msec: How long to wait between calls in milliseconds.
  1069. *args: Positional arguments to pass to function.
  1070. desc: The background task's description. Default to the function's name.
  1071. run_on_all_instances: Whether to run this on all instances, rather
  1072. than just the instance configured to run background tasks.
  1073. **kwargs: Key arguments to pass to function.
  1074. """
  1075. if desc is None:
  1076. desc = f.__name__
  1077. if self._hs.config.worker.run_background_tasks or run_on_all_instances:
  1078. self._clock.looping_call(
  1079. run_as_background_process,
  1080. msec,
  1081. desc,
  1082. lambda: maybe_awaitable(f(*args, **kwargs)),
  1083. )
  1084. else:
  1085. logger.warning(
  1086. "Not running looping call %s as the configuration forbids it",
  1087. f,
  1088. )
  1089. def should_run_background_tasks(self) -> bool:
  1090. """
  1091. Return true if and only if the current worker is configured to run
  1092. background tasks.
  1093. There should only be one worker configured to run background tasks, so
  1094. this is helpful when you need to only run a task on one worker but don't
  1095. have any other good way to choose which one.
  1096. Added in Synapse v1.89.0.
  1097. """
  1098. return self._hs.config.worker.run_background_tasks
  1099. def delayed_background_call(
  1100. self,
  1101. msec: float,
  1102. f: Callable,
  1103. *args: object,
  1104. desc: Optional[str] = None,
  1105. **kwargs: object,
  1106. ) -> IDelayedCall:
  1107. """Wraps a function as a background process and calls it in a given number of milliseconds.
  1108. The scheduled call is not persistent: if the current Synapse instance is
  1109. restarted before the call is made, the call will not be made.
  1110. Added in Synapse v1.90.0.
  1111. Args:
  1112. msec: How long to wait before calling, in milliseconds.
  1113. f: The function to call once. f can be either synchronous or
  1114. asynchronous, and must follow Synapse's logcontext rules.
  1115. More info about logcontexts is available at
  1116. https://matrix-org.github.io/synapse/latest/log_contexts.html
  1117. *args: Positional arguments to pass to function.
  1118. desc: The background task's description. Default to the function's name.
  1119. **kwargs: Keyword arguments to pass to function.
  1120. Returns:
  1121. IDelayedCall handle from twisted, which allows to cancel the delayed call if desired.
  1122. """
  1123. if desc is None:
  1124. desc = f.__name__
  1125. return self._clock.call_later(
  1126. # convert ms to seconds as needed by call_later.
  1127. msec * 0.001,
  1128. run_as_background_process,
  1129. desc,
  1130. lambda: maybe_awaitable(f(*args, **kwargs)),
  1131. )
  1132. async def sleep(self, seconds: float) -> None:
  1133. """Sleeps for the given number of seconds.
  1134. Added in Synapse v1.49.0.
  1135. """
  1136. await self._clock.sleep(seconds)
  1137. async def send_http_push_notification(
  1138. self,
  1139. user_id: str,
  1140. device_id: Optional[str],
  1141. content: JsonDict,
  1142. tweaks: Optional[JsonMapping] = None,
  1143. default_payload: Optional[JsonMapping] = None,
  1144. ) -> Dict[str, bool]:
  1145. """Send an HTTP push notification that is forwarded to the registered push gateway
  1146. for the specified user/device.
  1147. Added in Synapse v1.82.0.
  1148. Args:
  1149. user_id: The user ID to send the push notification to.
  1150. device_id: The device ID of the device where to send the push notification. If `None`,
  1151. the notification will be sent to all registered HTTP pushers of the user.
  1152. content: A dict of values that will be put in the `notification` field of the push
  1153. (cf Push Gateway spec). `devices` field will be overrided if included.
  1154. tweaks: A dict of `tweaks` that will be inserted in the `devices` section, cf spec.
  1155. default_payload: default payload to add in `devices[0].data.default_payload`.
  1156. This will be merged (and override if some matching values already exist there)
  1157. with existing `default_payload`.
  1158. Returns:
  1159. a dict reprensenting the status of the push per device ID
  1160. """
  1161. status = {}
  1162. if user_id in self._pusherpool.pushers:
  1163. for p in self._pusherpool.pushers[user_id].values():
  1164. if isinstance(p, HttpPusher) and (
  1165. not device_id or p.device_id == device_id
  1166. ):
  1167. res = await p.dispatch_push(content, tweaks, default_payload)
  1168. # Check if the push was successful and no pushers were rejected.
  1169. sent = res is not False and not res
  1170. # This is mainly to accomodate mypy
  1171. # device_id should never be empty after the `set_device_id_for_pushers`
  1172. # background job has been properly run.
  1173. if p.device_id:
  1174. status[p.device_id] = sent
  1175. return status
  1176. async def send_mail(
  1177. self,
  1178. recipient: str,
  1179. subject: str,
  1180. html: str,
  1181. text: str,
  1182. ) -> None:
  1183. """Send an email on behalf of the homeserver.
  1184. Added in Synapse v1.39.0.
  1185. Args:
  1186. recipient: The email address for the recipient.
  1187. subject: The email's subject.
  1188. html: The email's HTML content.
  1189. text: The email's text content.
  1190. """
  1191. await self._send_email_handler.send_email(
  1192. email_address=recipient,
  1193. subject=subject,
  1194. app_name=self.email_app_name,
  1195. html=html,
  1196. text=text,
  1197. )
  1198. def read_templates(
  1199. self,
  1200. filenames: List[str],
  1201. custom_template_directory: Optional[str] = None,
  1202. ) -> List[jinja2.Template]:
  1203. """Read and load the content of the template files at the given location.
  1204. By default, Synapse will look for these templates in its configured template
  1205. directory, but another directory to search in can be provided.
  1206. Added in Synapse v1.39.0.
  1207. Args:
  1208. filenames: The name of the template files to look for.
  1209. custom_template_directory: An additional directory to look for the files in.
  1210. Returns:
  1211. A list containing the loaded templates, with the orders matching the one of
  1212. the filenames parameter.
  1213. """
  1214. return self._hs.config.server.read_templates(
  1215. filenames,
  1216. (td for td in (self.custom_template_dir, custom_template_directory) if td),
  1217. )
  1218. def is_mine(self, id: Union[str, DomainSpecificString]) -> bool:
  1219. """
  1220. Checks whether an ID (user id, room, ...) comes from this homeserver.
  1221. Added in Synapse v1.44.0.
  1222. Args:
  1223. id: any Matrix id (e.g. user id, room id, ...), either as a raw id,
  1224. e.g. string "@user:example.com" or as a parsed UserID, RoomID, ...
  1225. Returns:
  1226. True if id comes from this homeserver, False otherwise.
  1227. """
  1228. if isinstance(id, DomainSpecificString):
  1229. return self._hs.is_mine(id)
  1230. else:
  1231. return self._hs.is_mine_id(id)
  1232. async def get_user_ip_and_agents(
  1233. self, user_id: str, since_ts: int = 0
  1234. ) -> List[UserIpAndAgent]:
  1235. """
  1236. Return the list of user IPs and agents for a user.
  1237. Added in Synapse v1.44.0.
  1238. Args:
  1239. user_id: the id of a user, local or remote
  1240. since_ts: a timestamp in seconds since the epoch,
  1241. or the epoch itself if not specified.
  1242. Returns:
  1243. The list of all UserIpAndAgent that the user has
  1244. used to connect to this homeserver since `since_ts`.
  1245. If the user is remote, this list is empty.
  1246. """
  1247. # Don't hit the db if this is not a local user.
  1248. is_mine = False
  1249. try:
  1250. # Let's be defensive against ill-formed strings.
  1251. if self.is_mine(user_id):
  1252. is_mine = True
  1253. except Exception:
  1254. pass
  1255. if is_mine:
  1256. raw_data = await self._store.get_user_ip_and_agents(
  1257. UserID.from_string(user_id), since_ts
  1258. )
  1259. # Sanitize some of the data. We don't want to return tokens.
  1260. return [
  1261. UserIpAndAgent(
  1262. ip=data["ip"],
  1263. user_agent=data["user_agent"],
  1264. last_seen=data["last_seen"],
  1265. )
  1266. for data in raw_data
  1267. ]
  1268. else:
  1269. return []
  1270. async def get_room_state(
  1271. self,
  1272. room_id: str,
  1273. event_filter: Optional[Iterable[Tuple[str, Optional[str]]]] = None,
  1274. ) -> StateMap[EventBase]:
  1275. """Returns the current state of the given room.
  1276. The events are returned as a mapping, in which the key for each event is a tuple
  1277. which first element is the event's type and the second one is its state key.
  1278. Added in Synapse v1.47.0
  1279. Args:
  1280. room_id: The ID of the room to get state from.
  1281. event_filter: A filter to apply when retrieving events. None if no filter
  1282. should be applied. If provided, must be an iterable of tuples. A tuple's
  1283. first element is the event type and the second is the state key, or is
  1284. None if the state key should not be filtered on.
  1285. An example of a filter is:
  1286. [
  1287. ("m.room.member", "@alice:example.com"), # Member event for @alice:example.com
  1288. ("org.matrix.some_event", ""), # State event of type "org.matrix.some_event"
  1289. # with an empty string as its state key
  1290. ("org.matrix.some_other_event", None), # State events of type "org.matrix.some_other_event"
  1291. # regardless of their state key
  1292. ]
  1293. """
  1294. state_filter = None
  1295. if event_filter:
  1296. # If a filter was provided, turn it into a StateFilter and retrieve a filtered
  1297. # view of the state.
  1298. state_filter = StateFilter.from_types(event_filter)
  1299. state_ids = await self._storage_controllers.state.get_current_state_ids(
  1300. room_id,
  1301. state_filter,
  1302. )
  1303. state_events = await self._store.get_events(state_ids.values())
  1304. return {key: state_events[event_id] for key, event_id in state_ids.items()}
  1305. async def defer_to_thread(
  1306. self,
  1307. f: Callable[P, T],
  1308. *args: P.args,
  1309. **kwargs: P.kwargs,
  1310. ) -> T:
  1311. """Runs the given function in a separate thread from Synapse's thread pool.
  1312. Added in Synapse v1.49.0.
  1313. Args:
  1314. f: The function to run.
  1315. args: The function's arguments.
  1316. kwargs: The function's keyword arguments.
  1317. Returns:
  1318. The return value of the function once ran in a thread.
  1319. """
  1320. return await defer_to_thread(self._hs.get_reactor(), f, *args, **kwargs)
  1321. async def check_username(self, username: str) -> None:
  1322. """Checks if the provided username uses the grammar defined in the Matrix
  1323. specification, and is already being used by an existing user.
  1324. Added in Synapse v1.52.0.
  1325. Args:
  1326. username: The username to check. This is the local part of the user's full
  1327. Matrix user ID, i.e. it's "alice" if the full user ID is "@alice:foo.com".
  1328. Raises:
  1329. SynapseError with the errcode "M_USER_IN_USE" if the username is already in
  1330. use.
  1331. """
  1332. await self._registration_handler.check_username(username)
  1333. async def store_remote_3pid_association(
  1334. self, user_id: str, medium: str, address: str, id_server: str
  1335. ) -> None:
  1336. """Stores an existing association between a user ID and a third-party identifier.
  1337. The association must already exist on the remote identity server.
  1338. Added in Synapse v1.56.0.
  1339. Args:
  1340. user_id: The user ID that's been associated with the 3PID.
  1341. medium: The medium of the 3PID (current supported values are "msisdn" and
  1342. "email").
  1343. address: The address of the 3PID.
  1344. id_server: The identity server the 3PID association has been registered on.
  1345. This should only be the domain (or IP address, optionally with the port
  1346. number) for the identity server. This will be used to reach out to the
  1347. identity server using HTTPS (unless specified otherwise by Synapse's
  1348. configuration) when attempting to unbind the third-party identifier.
  1349. """
  1350. await self._store.add_user_bound_threepid(user_id, medium, address, id_server)
  1351. def check_push_rule_actions(
  1352. self, actions: List[Union[str, Dict[str, str]]]
  1353. ) -> None:
  1354. """Checks if the given push rule actions are valid according to the Matrix
  1355. specification.
  1356. See https://spec.matrix.org/v1.2/client-server-api/#actions for the list of valid
  1357. actions.
  1358. Added in Synapse v1.58.0.
  1359. Args:
  1360. actions: the actions to check.
  1361. Raises:
  1362. synapse.module_api.errors.InvalidRuleException if the actions are invalid.
  1363. """
  1364. check_actions(actions)
  1365. async def set_push_rule_action(
  1366. self,
  1367. user_id: str,
  1368. scope: str,
  1369. kind: str,
  1370. rule_id: str,
  1371. actions: List[Union[str, Dict[str, str]]],
  1372. ) -> None:
  1373. """Changes the actions of an existing push rule for the given user.
  1374. See https://spec.matrix.org/v1.2/client-server-api/#push-rules for more
  1375. information about push rules and their syntax.
  1376. Can only be called on the main process.
  1377. Added in Synapse v1.58.0.
  1378. Args:
  1379. user_id: the user for which to change the push rule's actions.
  1380. scope: the push rule's scope, currently only "global" is allowed.
  1381. kind: the push rule's kind.
  1382. rule_id: the push rule's identifier.
  1383. actions: the actions to run when the rule's conditions match.
  1384. Raises:
  1385. RuntimeError if this method is called on a worker or `scope` is invalid.
  1386. synapse.module_api.errors.RuleNotFoundException if the rule being modified
  1387. can't be found.
  1388. synapse.module_api.errors.InvalidRuleException if the actions are invalid.
  1389. """
  1390. if self.worker_app is not None:
  1391. raise RuntimeError("module tried to change push rule actions on a worker")
  1392. if scope != "global":
  1393. raise RuntimeError(
  1394. "invalid scope %s, only 'global' is currently allowed" % scope
  1395. )
  1396. spec = RuleSpec(scope, kind, rule_id, "actions")
  1397. await self._push_rules_handler.set_rule_attr(
  1398. user_id, spec, {"actions": actions}
  1399. )
  1400. async def get_monthly_active_users_by_service(
  1401. self, start_timestamp: Optional[int] = None, end_timestamp: Optional[int] = None
  1402. ) -> List[Tuple[str, str]]:
  1403. """Generates list of monthly active users and their services.
  1404. Please see corresponding storage docstring for more details.
  1405. Added in Synapse v1.61.0.
  1406. Arguments:
  1407. start_timestamp: If specified, only include users that were first active
  1408. at or after this point
  1409. end_timestamp: If specified, only include users that were first active
  1410. at or before this point
  1411. Returns:
  1412. A list of tuples (appservice_id, user_id)
  1413. """
  1414. return await self._store.get_monthly_active_users_by_service(
  1415. start_timestamp, end_timestamp
  1416. )
  1417. async def get_canonical_room_alias(self, room_id: RoomID) -> Optional[RoomAlias]:
  1418. """
  1419. Retrieve the given room's current canonical alias.
  1420. A room may declare an alias as "canonical", meaning that it is the
  1421. preferred alias to use when referring to the room. This function
  1422. retrieves that alias from the room's state.
  1423. Added in Synapse v1.86.0.
  1424. Args:
  1425. room_id: The Room ID to find the alias of.
  1426. Returns:
  1427. None if the room ID does not exist, or if the room exists but has no canonical alias.
  1428. Otherwise, the parsed room alias.
  1429. """
  1430. room_alias_str = (
  1431. await self._storage_controllers.state.get_canonical_alias_for_room(
  1432. room_id.to_string()
  1433. )
  1434. )
  1435. if room_alias_str:
  1436. return RoomAlias.from_string(room_alias_str)
  1437. return None
  1438. async def lookup_room_alias(self, room_alias: str) -> Tuple[str, List[str]]:
  1439. """
  1440. Get the room ID associated with a room alias.
  1441. Added in Synapse v1.65.0.
  1442. Args:
  1443. room_alias: The alias to look up.
  1444. Returns:
  1445. A tuple of:
  1446. The room ID (str).
  1447. Hosts likely to be participating in the room ([str]).
  1448. Raises:
  1449. SynapseError if room alias is invalid or could not be found.
  1450. """
  1451. alias = RoomAlias.from_string(room_alias)
  1452. (room_id, hosts) = await self._hs.get_room_member_handler().lookup_room_alias(
  1453. alias
  1454. )
  1455. return room_id.to_string(), hosts
  1456. async def create_room(
  1457. self,
  1458. user_id: str,
  1459. config: JsonDict,
  1460. ratelimit: bool = True,
  1461. creator_join_profile: Optional[JsonDict] = None,
  1462. ) -> Tuple[str, Optional[str]]:
  1463. """Creates a new room.
  1464. Added in Synapse v1.65.0.
  1465. Args:
  1466. user_id:
  1467. The user who requested the room creation.
  1468. config : A dict of configuration options. See "Request body" of:
  1469. https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3createroom
  1470. ratelimit: set to False to disable the rate limiter for this specific operation.
  1471. creator_join_profile:
  1472. Set to override the displayname and avatar for the creating
  1473. user in this room. If unset, displayname and avatar will be
  1474. derived from the user's profile. If set, should contain the
  1475. values to go in the body of the 'join' event (typically
  1476. `avatar_url` and/or `displayname`.
  1477. Returns:
  1478. A tuple containing: 1) the room ID (str), 2) if an alias was requested,
  1479. the room alias (str), otherwise None if no alias was requested.
  1480. Raises:
  1481. ResourceLimitError if server is blocked to some resource being
  1482. exceeded.
  1483. RuntimeError if the user_id does not refer to a local user.
  1484. SynapseError if the user_id is invalid, room ID couldn't be stored, or
  1485. something went horribly wrong.
  1486. """
  1487. if not self.is_mine(user_id):
  1488. raise RuntimeError(
  1489. "Tried to create a room as a user that isn't local to this homeserver",
  1490. )
  1491. requester = create_requester(user_id)
  1492. room_id, room_alias, _ = await self._hs.get_room_creation_handler().create_room(
  1493. requester=requester,
  1494. config=config,
  1495. ratelimit=ratelimit,
  1496. creator_join_profile=creator_join_profile,
  1497. )
  1498. room_alias_str = room_alias.to_string() if room_alias else None
  1499. return room_id, room_alias_str
  1500. async def delete_room(self, room_id: str) -> None:
  1501. """
  1502. Schedules the deletion of a room from Synapse's database.
  1503. If the room is already being deleted, this method does nothing.
  1504. This method does not wait for the room to be deleted.
  1505. Added in Synapse v1.89.0.
  1506. """
  1507. # Future extensions to this method might want to e.g. allow use of `force_purge`.
  1508. # TODO In the future we should make sure this is persistent.
  1509. await self._hs.get_pagination_handler().start_shutdown_and_purge_room(
  1510. room_id,
  1511. {
  1512. "new_room_user_id": None,
  1513. "new_room_name": None,
  1514. "message": None,
  1515. "requester_user_id": None,
  1516. "block": False,
  1517. "purge": True,
  1518. "force_purge": False,
  1519. },
  1520. )
  1521. async def set_displayname(
  1522. self,
  1523. user_id: UserID,
  1524. new_displayname: str,
  1525. deactivation: bool = False,
  1526. ) -> None:
  1527. """Sets a user's display name.
  1528. Added in Synapse v1.76.0.
  1529. Args:
  1530. user_id:
  1531. The user whose display name is to be changed.
  1532. new_displayname:
  1533. The new display name to give the user.
  1534. deactivation:
  1535. Whether this change was made while deactivating the user.
  1536. """
  1537. requester = create_requester(user_id)
  1538. await self._hs.get_profile_handler().set_displayname(
  1539. target_user=user_id,
  1540. requester=requester,
  1541. new_displayname=new_displayname,
  1542. by_admin=True,
  1543. deactivation=deactivation,
  1544. )
  1545. class PublicRoomListManager:
  1546. """Contains methods for adding to, removing from and querying whether a room
  1547. is in the public room list.
  1548. """
  1549. def __init__(self, hs: "HomeServer"):
  1550. self._store = hs.get_datastores().main
  1551. async def room_is_in_public_room_list(self, room_id: str) -> bool:
  1552. """Checks whether a room is in the public room list.
  1553. Added in Synapse v1.22.0.
  1554. Args:
  1555. room_id: The ID of the room.
  1556. Returns:
  1557. Whether the room is in the public room list. Returns False if the room does
  1558. not exist.
  1559. """
  1560. room = await self._store.get_room(room_id)
  1561. if not room:
  1562. return False
  1563. # The first item is whether the room is public.
  1564. return room[0]
  1565. async def add_room_to_public_room_list(self, room_id: str) -> None:
  1566. """Publishes a room to the public room list.
  1567. Added in Synapse v1.22.0.
  1568. Args:
  1569. room_id: The ID of the room.
  1570. """
  1571. await self._store.set_room_is_public(room_id, True)
  1572. async def remove_room_from_public_room_list(self, room_id: str) -> None:
  1573. """Removes a room from the public room list.
  1574. Added in Synapse v1.22.0.
  1575. Args:
  1576. room_id: The ID of the room.
  1577. """
  1578. await self._store.set_room_is_public(room_id, False)
  1579. class AccountDataManager:
  1580. """
  1581. Allows modules to manage account data.
  1582. """
  1583. def __init__(self, hs: "HomeServer") -> None:
  1584. self._hs = hs
  1585. self._store = hs.get_datastores().main
  1586. self._handler = hs.get_account_data_handler()
  1587. def _validate_user_id(self, user_id: str) -> None:
  1588. """
  1589. Validates a user ID is valid and local.
  1590. Private method to be used in other account data methods.
  1591. """
  1592. user = UserID.from_string(user_id)
  1593. if not self._hs.is_mine(user):
  1594. raise ValueError(
  1595. f"{user_id} is not local to this homeserver; can't access account data for remote users."
  1596. )
  1597. async def get_global(self, user_id: str, data_type: str) -> Optional[JsonMapping]:
  1598. """
  1599. Gets some global account data, of a specified type, for the specified user.
  1600. The provided user ID must be a valid user ID of a local user.
  1601. Added in Synapse v1.57.0.
  1602. """
  1603. self._validate_user_id(user_id)
  1604. data = await self._store.get_global_account_data_by_type_for_user(
  1605. user_id, data_type
  1606. )
  1607. # We clone and freeze to prevent the module accidentally mutating the
  1608. # dict that lives in the cache, as that could introduce nasty bugs.
  1609. return freeze(data)
  1610. async def put_global(
  1611. self, user_id: str, data_type: str, new_data: JsonDict
  1612. ) -> None:
  1613. """
  1614. Puts some global account data, of a specified type, for the specified user.
  1615. The provided user ID must be a valid user ID of a local user.
  1616. Please note that this will overwrite existing the account data of that type
  1617. for that user!
  1618. Added in Synapse v1.57.0.
  1619. """
  1620. self._validate_user_id(user_id)
  1621. if not isinstance(data_type, str):
  1622. raise TypeError(f"data_type must be a str; got {type(data_type).__name__}")
  1623. if not isinstance(new_data, dict):
  1624. raise TypeError(f"new_data must be a dict; got {type(new_data).__name__}")
  1625. # Ensure the user exists, so we don't just write to users that aren't there.
  1626. if await self._store.get_user_by_id(user_id) is None:
  1627. raise ValueError(f"User {user_id} does not exist on this server.")
  1628. await self._handler.add_account_data_for_user(user_id, data_type, new_data)