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.
 
 
 
 
 
 

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