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.
 
 
 
 
 
 

422 lines
16 KiB

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