experimental.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. # Copyright 2021 The Matrix.org Foundation C.I.C.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import enum
  15. from typing import TYPE_CHECKING, Any, Optional
  16. import attr
  17. import attr.validators
  18. from synapse.api.room_versions import KNOWN_ROOM_VERSIONS, RoomVersions
  19. from synapse.config import ConfigError
  20. from synapse.config._base import Config, RootConfig
  21. from synapse.types import JsonDict
  22. # Determine whether authlib is installed.
  23. try:
  24. import authlib # noqa: F401
  25. HAS_AUTHLIB = True
  26. except ImportError:
  27. HAS_AUTHLIB = False
  28. if TYPE_CHECKING:
  29. # Only import this if we're type checking, as it might not be installed at runtime.
  30. from authlib.jose.rfc7517 import JsonWebKey
  31. class ClientAuthMethod(enum.Enum):
  32. """List of supported client auth methods."""
  33. CLIENT_SECRET_POST = "client_secret_post"
  34. CLIENT_SECRET_BASIC = "client_secret_basic"
  35. CLIENT_SECRET_JWT = "client_secret_jwt"
  36. PRIVATE_KEY_JWT = "private_key_jwt"
  37. def _parse_jwks(jwks: Optional[JsonDict]) -> Optional["JsonWebKey"]:
  38. """A helper function to parse a JWK dict into a JsonWebKey."""
  39. if jwks is None:
  40. return None
  41. from authlib.jose.rfc7517 import JsonWebKey
  42. return JsonWebKey.import_key(jwks)
  43. @attr.s(slots=True, frozen=True)
  44. class MSC3861:
  45. """Configuration for MSC3861: Matrix architecture change to delegate authentication via OIDC"""
  46. enabled: bool = attr.ib(default=False, validator=attr.validators.instance_of(bool))
  47. """Whether to enable MSC3861 auth delegation."""
  48. @enabled.validator
  49. def _check_enabled(self, attribute: attr.Attribute, value: bool) -> None:
  50. # Only allow enabling MSC3861 if authlib is installed
  51. if value and not HAS_AUTHLIB:
  52. raise ConfigError(
  53. "MSC3861 is enabled but authlib is not installed. "
  54. "Please install authlib to use MSC3861.",
  55. ("experimental", "msc3861", "enabled"),
  56. )
  57. issuer: str = attr.ib(default="", validator=attr.validators.instance_of(str))
  58. """The URL of the OIDC Provider."""
  59. issuer_metadata: Optional[JsonDict] = attr.ib(default=None)
  60. """The issuer metadata to use, otherwise discovered from /.well-known/openid-configuration as per MSC2965."""
  61. client_id: str = attr.ib(
  62. default="",
  63. validator=attr.validators.instance_of(str),
  64. )
  65. """The client ID to use when calling the introspection endpoint."""
  66. client_auth_method: ClientAuthMethod = attr.ib(
  67. default=ClientAuthMethod.CLIENT_SECRET_POST, converter=ClientAuthMethod
  68. )
  69. """The auth method used when calling the introspection endpoint."""
  70. client_secret: Optional[str] = attr.ib(
  71. default=None,
  72. validator=attr.validators.optional(attr.validators.instance_of(str)),
  73. )
  74. """
  75. The client secret to use when calling the introspection endpoint,
  76. when using any of the client_secret_* client auth methods.
  77. """
  78. jwk: Optional["JsonWebKey"] = attr.ib(default=None, converter=_parse_jwks)
  79. """
  80. The JWKS to use when calling the introspection endpoint,
  81. when using the private_key_jwt client auth method.
  82. """
  83. @client_auth_method.validator
  84. def _check_client_auth_method(
  85. self, attribute: attr.Attribute, value: ClientAuthMethod
  86. ) -> None:
  87. # Check that the right client credentials are provided for the client auth method.
  88. if not self.enabled:
  89. return
  90. if value == ClientAuthMethod.PRIVATE_KEY_JWT and self.jwk is None:
  91. raise ConfigError(
  92. "A JWKS must be provided when using the private_key_jwt client auth method",
  93. ("experimental", "msc3861", "client_auth_method"),
  94. )
  95. if (
  96. value
  97. in (
  98. ClientAuthMethod.CLIENT_SECRET_POST,
  99. ClientAuthMethod.CLIENT_SECRET_BASIC,
  100. ClientAuthMethod.CLIENT_SECRET_JWT,
  101. )
  102. and self.client_secret is None
  103. ):
  104. raise ConfigError(
  105. f"A client secret must be provided when using the {value} client auth method",
  106. ("experimental", "msc3861", "client_auth_method"),
  107. )
  108. account_management_url: Optional[str] = attr.ib(
  109. default=None,
  110. validator=attr.validators.optional(attr.validators.instance_of(str)),
  111. )
  112. """The URL of the My Account page on the OIDC Provider as per MSC2965."""
  113. admin_token: Optional[str] = attr.ib(
  114. default=None,
  115. validator=attr.validators.optional(attr.validators.instance_of(str)),
  116. )
  117. """
  118. A token that should be considered as an admin token.
  119. This is used by the OIDC provider, to make admin calls to Synapse.
  120. """
  121. def check_config_conflicts(self, root: RootConfig) -> None:
  122. """Checks for any configuration conflicts with other parts of Synapse.
  123. Raises:
  124. ConfigError: If there are any configuration conflicts.
  125. """
  126. if not self.enabled:
  127. return
  128. if (
  129. root.auth.password_enabled_for_reauth
  130. or root.auth.password_enabled_for_login
  131. ):
  132. raise ConfigError(
  133. "Password auth cannot be enabled when OAuth delegation is enabled",
  134. ("password_config", "enabled"),
  135. )
  136. if root.registration.enable_registration:
  137. raise ConfigError(
  138. "Registration cannot be enabled when OAuth delegation is enabled",
  139. ("enable_registration",),
  140. )
  141. if (
  142. root.oidc.oidc_enabled
  143. or root.saml2.saml2_enabled
  144. or root.cas.cas_enabled
  145. or root.jwt.jwt_enabled
  146. ):
  147. raise ConfigError("SSO cannot be enabled when OAuth delegation is enabled")
  148. if bool(root.authproviders.password_providers):
  149. raise ConfigError(
  150. "Password auth providers cannot be enabled when OAuth delegation is enabled"
  151. )
  152. if root.captcha.enable_registration_captcha:
  153. raise ConfigError(
  154. "CAPTCHA cannot be enabled when OAuth delegation is enabled",
  155. ("captcha", "enable_registration_captcha"),
  156. )
  157. if root.auth.login_via_existing_enabled:
  158. raise ConfigError(
  159. "Login via existing session cannot be enabled when OAuth delegation is enabled",
  160. ("login_via_existing_session", "enabled"),
  161. )
  162. if root.registration.refresh_token_lifetime:
  163. raise ConfigError(
  164. "refresh_token_lifetime cannot be set when OAuth delegation is enabled",
  165. ("refresh_token_lifetime",),
  166. )
  167. if root.registration.nonrefreshable_access_token_lifetime:
  168. raise ConfigError(
  169. "nonrefreshable_access_token_lifetime cannot be set when OAuth delegation is enabled",
  170. ("nonrefreshable_access_token_lifetime",),
  171. )
  172. if root.registration.session_lifetime:
  173. raise ConfigError(
  174. "session_lifetime cannot be set when OAuth delegation is enabled",
  175. ("session_lifetime",),
  176. )
  177. @attr.s(auto_attribs=True, frozen=True, slots=True)
  178. class MSC3866Config:
  179. """Configuration for MSC3866 (mandating approval for new users)"""
  180. # Whether the base support for the approval process is enabled. This includes the
  181. # ability for administrators to check and update the approval of users, even if no
  182. # approval is currently required.
  183. enabled: bool = False
  184. # Whether to require that new users are approved by an admin before their account
  185. # can be used. Note that this setting is ignored if 'enabled' is false.
  186. require_approval_for_new_accounts: bool = False
  187. class ExperimentalConfig(Config):
  188. """Config section for enabling experimental features"""
  189. section = "experimental"
  190. def read_config(self, config: JsonDict, **kwargs: Any) -> None:
  191. experimental = config.get("experimental_features") or {}
  192. # MSC3026 (busy presence state)
  193. self.msc3026_enabled: bool = experimental.get("msc3026_enabled", False)
  194. # MSC2697 (device dehydration)
  195. # Enabled by default since this option was added after adding the feature.
  196. # It is not recommended that both MSC2697 and MSC3814 both be enabled at
  197. # once.
  198. self.msc2697_enabled: bool = experimental.get("msc2697_enabled", True)
  199. # MSC3814 (dehydrated devices with SSSS)
  200. # This is an alternative method to achieve the same goals as MSC2697.
  201. # It is not recommended that both MSC2697 and MSC3814 both be enabled at
  202. # once.
  203. self.msc3814_enabled: bool = experimental.get("msc3814_enabled", False)
  204. if self.msc2697_enabled and self.msc3814_enabled:
  205. raise ConfigError(
  206. "MSC2697 and MSC3814 should not both be enabled.",
  207. (
  208. "experimental_features",
  209. "msc3814_enabled",
  210. ),
  211. )
  212. # MSC3244 (room version capabilities)
  213. self.msc3244_enabled: bool = experimental.get("msc3244_enabled", True)
  214. # MSC3266 (room summary api)
  215. self.msc3266_enabled: bool = experimental.get("msc3266_enabled", False)
  216. # MSC2409 (this setting only relates to optionally sending to-device messages).
  217. # Presence, typing and read receipt EDUs are already sent to application services that
  218. # have opted in to receive them. If enabled, this adds to-device messages to that list.
  219. self.msc2409_to_device_messages_enabled: bool = experimental.get(
  220. "msc2409_to_device_messages_enabled", False
  221. )
  222. # The portion of MSC3202 which is related to device masquerading.
  223. self.msc3202_device_masquerading_enabled: bool = experimental.get(
  224. "msc3202_device_masquerading", False
  225. )
  226. # The portion of MSC3202 related to transaction extensions:
  227. # sending device list changes, one-time key counts and fallback key
  228. # usage to application services.
  229. self.msc3202_transaction_extensions: bool = experimental.get(
  230. "msc3202_transaction_extensions", False
  231. )
  232. # MSC3983: Proxying OTK claim requests to exclusive ASes.
  233. self.msc3983_appservice_otk_claims: bool = experimental.get(
  234. "msc3983_appservice_otk_claims", False
  235. )
  236. # MSC3984: Proxying key queries to exclusive ASes.
  237. self.msc3984_appservice_key_query: bool = experimental.get(
  238. "msc3984_appservice_key_query", False
  239. )
  240. # MSC3720 (Account status endpoint)
  241. self.msc3720_enabled: bool = experimental.get("msc3720_enabled", False)
  242. # MSC2654: Unread counts
  243. #
  244. # Note that enabling this will result in an incorrect unread count for
  245. # previously calculated push actions.
  246. self.msc2654_enabled: bool = experimental.get("msc2654_enabled", False)
  247. # MSC2815 (allow room moderators to view redacted event content)
  248. self.msc2815_enabled: bool = experimental.get("msc2815_enabled", False)
  249. # MSC3391: Removing account data.
  250. self.msc3391_enabled = experimental.get("msc3391_enabled", False)
  251. # MSC3773: Thread notifications
  252. self.msc3773_enabled: bool = experimental.get("msc3773_enabled", False)
  253. # MSC3664: Pushrules to match on related events
  254. self.msc3664_enabled: bool = experimental.get("msc3664_enabled", False)
  255. # MSC3848: Introduce errcodes for specific event sending failures
  256. self.msc3848_enabled: bool = experimental.get("msc3848_enabled", False)
  257. # MSC3852: Expose last seen user agent field on /_matrix/client/v3/devices.
  258. self.msc3852_enabled: bool = experimental.get("msc3852_enabled", False)
  259. # MSC3866: M_USER_AWAITING_APPROVAL error code
  260. raw_msc3866_config = experimental.get("msc3866", {})
  261. self.msc3866 = MSC3866Config(**raw_msc3866_config)
  262. # MSC3881: Remotely toggle push notifications for another client
  263. self.msc3881_enabled: bool = experimental.get("msc3881_enabled", False)
  264. # MSC3874: Filtering /messages with rel_types / not_rel_types.
  265. self.msc3874_enabled: bool = experimental.get("msc3874_enabled", False)
  266. # MSC3886: Simple client rendezvous capability
  267. self.msc3886_endpoint: Optional[str] = experimental.get(
  268. "msc3886_endpoint", None
  269. )
  270. # MSC3890: Remotely silence local notifications
  271. # Note: This option requires "experimental_features.msc3391_enabled" to be
  272. # set to "true", in order to communicate account data deletions to clients.
  273. self.msc3890_enabled: bool = experimental.get("msc3890_enabled", False)
  274. if self.msc3890_enabled and not self.msc3391_enabled:
  275. raise ConfigError(
  276. "Option 'experimental_features.msc3391' must be set to 'true' to "
  277. "enable 'experimental_features.msc3890'. MSC3391 functionality is "
  278. "required to communicate account data deletions to clients."
  279. )
  280. # MSC3381: Polls.
  281. # In practice, supporting polls in Synapse only requires an implementation of
  282. # MSC3930: Push rules for MSC3391 polls; which is what this option enables.
  283. self.msc3381_polls_enabled: bool = experimental.get(
  284. "msc3381_polls_enabled", False
  285. )
  286. # MSC3912: Relation-based redactions.
  287. self.msc3912_enabled: bool = experimental.get("msc3912_enabled", False)
  288. # MSC1767 and friends: Extensible Events
  289. self.msc1767_enabled: bool = experimental.get("msc1767_enabled", False)
  290. if self.msc1767_enabled:
  291. # Enable room version (and thus applicable push rules from MSC3931/3932)
  292. version_id = RoomVersions.MSC1767v10.identifier
  293. KNOWN_ROOM_VERSIONS[version_id] = RoomVersions.MSC1767v10
  294. # MSC3391: Removing account data.
  295. self.msc3391_enabled = experimental.get("msc3391_enabled", False)
  296. # MSC3959: Do not generate notifications for edits.
  297. self.msc3958_supress_edit_notifs = experimental.get(
  298. "msc3958_supress_edit_notifs", False
  299. )
  300. # MSC3967: Do not require UIA when first uploading cross signing keys
  301. self.msc3967_enabled = experimental.get("msc3967_enabled", False)
  302. # MSC3981: Recurse relations
  303. self.msc3981_recurse_relations = experimental.get(
  304. "msc3981_recurse_relations", False
  305. )
  306. # MSC3861: Matrix architecture change to delegate authentication via OIDC
  307. try:
  308. self.msc3861 = MSC3861(**experimental.get("msc3861", {}))
  309. except ValueError as exc:
  310. raise ConfigError(
  311. "Invalid MSC3861 configuration", ("experimental", "msc3861")
  312. ) from exc
  313. # Check that none of the other config options conflict with MSC3861 when enabled
  314. self.msc3861.check_config_conflicts(self.root)
  315. # MSC4010: Do not allow setting m.push_rules account data.
  316. self.msc4010_push_rules_account_data = experimental.get(
  317. "msc4010_push_rules_account_data", False
  318. )