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

427 Zeilen
16 KiB

  1. # Copyright 2020 Quentin Gliech
  2. # Copyright 2020-2021 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. from collections import Counter
  16. from typing import Any, Collection, Iterable, List, Mapping, Optional, Tuple, Type
  17. import attr
  18. from synapse.config._util import validate_config
  19. from synapse.config.sso import SsoAttributeRequirement
  20. from synapse.types import JsonDict
  21. from synapse.util.module_loader import load_module
  22. from synapse.util.stringutils import parse_and_validate_mxc_uri
  23. from ..util.check_dependencies import check_requirements
  24. from ._base import Config, ConfigError, read_file
  25. DEFAULT_USER_MAPPING_PROVIDER = "synapse.handlers.oidc.JinjaOidcMappingProvider"
  26. # The module that JinjaOidcMappingProvider is in was renamed, we want to
  27. # transparently handle both the same.
  28. LEGACY_USER_MAPPING_PROVIDER = "synapse.handlers.oidc_handler.JinjaOidcMappingProvider"
  29. class OIDCConfig(Config):
  30. section = "oidc"
  31. def read_config(self, config: JsonDict, **kwargs: Any) -> None:
  32. self.oidc_providers = tuple(_parse_oidc_provider_configs(config))
  33. if not self.oidc_providers:
  34. return
  35. check_requirements("oidc")
  36. # check we don't have any duplicate idp_ids now. (The SSO handler will also
  37. # check for duplicates when the REST listeners get registered, but that happens
  38. # after synapse has forked so doesn't give nice errors.)
  39. c = Counter([i.idp_id for i in self.oidc_providers])
  40. for idp_id, count in c.items():
  41. if count > 1:
  42. raise ConfigError(
  43. "Multiple OIDC providers have the idp_id %r." % idp_id
  44. )
  45. public_baseurl = self.root.server.public_baseurl
  46. self.oidc_callback_url = public_baseurl + "_synapse/client/oidc/callback"
  47. @property
  48. def oidc_enabled(self) -> bool:
  49. # OIDC is enabled if we have a provider
  50. return bool(self.oidc_providers)
  51. # jsonschema definition of the configuration settings for an oidc identity provider
  52. OIDC_PROVIDER_CONFIG_SCHEMA = {
  53. "type": "object",
  54. "required": ["issuer", "client_id"],
  55. "properties": {
  56. "idp_id": {
  57. "type": "string",
  58. "minLength": 1,
  59. # MSC2858 allows a maxlen of 255, but we prefix with "oidc-"
  60. "maxLength": 250,
  61. "pattern": "^[A-Za-z0-9._~-]+$",
  62. },
  63. "idp_name": {"type": "string"},
  64. "idp_icon": {"type": "string"},
  65. "idp_brand": {
  66. "type": "string",
  67. "minLength": 1,
  68. "maxLength": 255,
  69. "pattern": "^[a-z][a-z0-9_.-]*$",
  70. },
  71. "discover": {"type": "boolean"},
  72. "issuer": {"type": "string"},
  73. "client_id": {"type": "string"},
  74. "client_secret": {"type": "string"},
  75. "client_secret_jwt_key": {
  76. "type": "object",
  77. "required": ["jwt_header"],
  78. "oneOf": [
  79. {"required": ["key"]},
  80. {"required": ["key_file"]},
  81. ],
  82. "properties": {
  83. "key": {"type": "string"},
  84. "key_file": {"type": "string"},
  85. "jwt_header": {
  86. "type": "object",
  87. "required": ["alg"],
  88. "properties": {
  89. "alg": {"type": "string"},
  90. },
  91. "additionalProperties": {"type": "string"},
  92. },
  93. "jwt_payload": {
  94. "type": "object",
  95. "additionalProperties": {"type": "string"},
  96. },
  97. },
  98. },
  99. "client_auth_method": {
  100. "type": "string",
  101. # the following list is the same as the keys of
  102. # authlib.oauth2.auth.ClientAuth.DEFAULT_AUTH_METHODS. We inline it
  103. # to avoid importing authlib here.
  104. "enum": ["client_secret_basic", "client_secret_post", "none"],
  105. },
  106. "pkce_method": {"type": "string", "enum": ["auto", "always", "never"]},
  107. "scopes": {"type": "array", "items": {"type": "string"}},
  108. "authorization_endpoint": {"type": "string"},
  109. "token_endpoint": {"type": "string"},
  110. "userinfo_endpoint": {"type": "string"},
  111. "jwks_uri": {"type": "string"},
  112. "skip_verification": {"type": "boolean"},
  113. "backchannel_logout_enabled": {"type": "boolean"},
  114. "backchannel_logout_ignore_sub": {"type": "boolean"},
  115. "user_profile_method": {
  116. "type": "string",
  117. "enum": ["auto", "userinfo_endpoint"],
  118. },
  119. "allow_existing_users": {"type": "boolean"},
  120. "user_mapping_provider": {"type": ["object", "null"]},
  121. "attribute_requirements": {
  122. "type": "array",
  123. "items": SsoAttributeRequirement.JSON_SCHEMA,
  124. },
  125. "enable_registration": {"type": "boolean"},
  126. },
  127. }
  128. # the same as OIDC_PROVIDER_CONFIG_SCHEMA, but with compulsory idp_id and idp_name
  129. OIDC_PROVIDER_CONFIG_WITH_ID_SCHEMA = {
  130. "allOf": [OIDC_PROVIDER_CONFIG_SCHEMA, {"required": ["idp_id", "idp_name"]}]
  131. }
  132. # the `oidc_providers` list can either be None (as it is in the default config), or
  133. # a list of provider configs, each of which requires an explicit ID and name.
  134. OIDC_PROVIDER_LIST_SCHEMA = {
  135. "oneOf": [
  136. {"type": "null"},
  137. {"type": "array", "items": OIDC_PROVIDER_CONFIG_WITH_ID_SCHEMA},
  138. ]
  139. }
  140. # the `oidc_config` setting can either be None (which it used to be in the default
  141. # config), or an object. If an object, it is ignored unless it has an "enabled: True"
  142. # property.
  143. #
  144. # It's *possible* to represent this with jsonschema, but the resultant errors aren't
  145. # particularly clear, so we just check for either an object or a null here, and do
  146. # additional checks in the code.
  147. OIDC_CONFIG_SCHEMA = {"oneOf": [{"type": "null"}, {"type": "object"}]}
  148. # the top-level schema can contain an "oidc_config" and/or an "oidc_providers".
  149. MAIN_CONFIG_SCHEMA = {
  150. "type": "object",
  151. "properties": {
  152. "oidc_config": OIDC_CONFIG_SCHEMA,
  153. "oidc_providers": OIDC_PROVIDER_LIST_SCHEMA,
  154. },
  155. }
  156. def _parse_oidc_provider_configs(config: JsonDict) -> Iterable["OidcProviderConfig"]:
  157. """extract and parse the OIDC provider configs from the config dict
  158. The configuration may contain either a single `oidc_config` object with an
  159. `enabled: True` property, or a list of provider configurations under
  160. `oidc_providers`, *or both*.
  161. Returns a generator which yields the OidcProviderConfig objects
  162. """
  163. validate_config(MAIN_CONFIG_SCHEMA, config, ())
  164. for i, p in enumerate(config.get("oidc_providers") or []):
  165. yield _parse_oidc_config_dict(p, ("oidc_providers", "<item %i>" % (i,)))
  166. # for backwards-compatibility, it is also possible to provide a single "oidc_config"
  167. # object with an "enabled: True" property.
  168. oidc_config = config.get("oidc_config")
  169. if oidc_config and oidc_config.get("enabled", False):
  170. # MAIN_CONFIG_SCHEMA checks that `oidc_config` is an object, but not that
  171. # it matches OIDC_PROVIDER_CONFIG_SCHEMA (see the comments on OIDC_CONFIG_SCHEMA
  172. # above), so now we need to validate it.
  173. validate_config(OIDC_PROVIDER_CONFIG_SCHEMA, oidc_config, ("oidc_config",))
  174. yield _parse_oidc_config_dict(oidc_config, ("oidc_config",))
  175. def _parse_oidc_config_dict(
  176. oidc_config: JsonDict, config_path: Tuple[str, ...]
  177. ) -> "OidcProviderConfig":
  178. """Take the configuration dict and parse it into an OidcProviderConfig
  179. Raises:
  180. ConfigError if the configuration is malformed.
  181. """
  182. ump_config = oidc_config.get("user_mapping_provider", {})
  183. ump_config.setdefault("module", DEFAULT_USER_MAPPING_PROVIDER)
  184. if ump_config.get("module") == LEGACY_USER_MAPPING_PROVIDER:
  185. ump_config["module"] = DEFAULT_USER_MAPPING_PROVIDER
  186. ump_config.setdefault("config", {})
  187. (
  188. user_mapping_provider_class,
  189. user_mapping_provider_config,
  190. ) = load_module(ump_config, config_path + ("user_mapping_provider",))
  191. # Ensure loaded user mapping module has defined all necessary methods
  192. required_methods = [
  193. "get_remote_user_id",
  194. "map_user_attributes",
  195. ]
  196. missing_methods = [
  197. method
  198. for method in required_methods
  199. if not hasattr(user_mapping_provider_class, method)
  200. ]
  201. if missing_methods:
  202. raise ConfigError(
  203. "Class %s is missing required "
  204. "methods: %s"
  205. % (
  206. user_mapping_provider_class,
  207. ", ".join(missing_methods),
  208. ),
  209. config_path + ("user_mapping_provider", "module"),
  210. )
  211. idp_id = oidc_config.get("idp_id", "oidc")
  212. # prefix the given IDP with a prefix specific to the SSO mechanism, to avoid
  213. # clashes with other mechs (such as SAML, CAS).
  214. #
  215. # We allow "oidc" as an exception so that people migrating from old-style
  216. # "oidc_config" format (which has long used "oidc" as its idp_id) can migrate to
  217. # a new-style "oidc_providers" entry without changing the idp_id for their provider
  218. # (and thereby invalidating their user_external_ids data).
  219. if idp_id != "oidc":
  220. idp_id = "oidc-" + idp_id
  221. # MSC2858 also specifies that the idp_icon must be a valid MXC uri
  222. idp_icon = oidc_config.get("idp_icon")
  223. if idp_icon is not None:
  224. try:
  225. parse_and_validate_mxc_uri(idp_icon)
  226. except ValueError as e:
  227. raise ConfigError(
  228. "idp_icon must be a valid MXC URI", config_path + ("idp_icon",)
  229. ) from e
  230. client_secret_jwt_key_config = oidc_config.get("client_secret_jwt_key")
  231. client_secret_jwt_key: Optional[OidcProviderClientSecretJwtKey] = None
  232. if client_secret_jwt_key_config is not None:
  233. keyfile = client_secret_jwt_key_config.get("key_file")
  234. if keyfile:
  235. key = read_file(keyfile, config_path + ("client_secret_jwt_key",))
  236. else:
  237. key = client_secret_jwt_key_config["key"]
  238. client_secret_jwt_key = OidcProviderClientSecretJwtKey(
  239. key=key,
  240. jwt_header=client_secret_jwt_key_config["jwt_header"],
  241. jwt_payload=client_secret_jwt_key_config.get("jwt_payload", {}),
  242. )
  243. # parse attribute_requirements from config (list of dicts) into a list of SsoAttributeRequirement
  244. attribute_requirements = [
  245. SsoAttributeRequirement(**x)
  246. for x in oidc_config.get("attribute_requirements", [])
  247. ]
  248. # Read from either `client_secret_path` or `client_secret`. If both exist, error.
  249. client_secret = oidc_config.get("client_secret")
  250. client_secret_path = oidc_config.get("client_secret_path")
  251. if client_secret_path is not None:
  252. if client_secret is None:
  253. client_secret = read_file(
  254. client_secret_path, config_path + ("client_secret_path",)
  255. ).rstrip("\n")
  256. else:
  257. raise ConfigError(
  258. "Cannot specify both client_secret and client_secret_path",
  259. config_path + ("client_secret",),
  260. )
  261. return OidcProviderConfig(
  262. idp_id=idp_id,
  263. idp_name=oidc_config.get("idp_name", "OIDC"),
  264. idp_icon=idp_icon,
  265. idp_brand=oidc_config.get("idp_brand"),
  266. discover=oidc_config.get("discover", True),
  267. issuer=oidc_config["issuer"],
  268. client_id=oidc_config["client_id"],
  269. client_secret=client_secret,
  270. client_secret_jwt_key=client_secret_jwt_key,
  271. client_auth_method=oidc_config.get("client_auth_method", "client_secret_basic"),
  272. pkce_method=oidc_config.get("pkce_method", "auto"),
  273. scopes=oidc_config.get("scopes", ["openid"]),
  274. authorization_endpoint=oidc_config.get("authorization_endpoint"),
  275. token_endpoint=oidc_config.get("token_endpoint"),
  276. userinfo_endpoint=oidc_config.get("userinfo_endpoint"),
  277. jwks_uri=oidc_config.get("jwks_uri"),
  278. backchannel_logout_enabled=oidc_config.get("backchannel_logout_enabled", False),
  279. backchannel_logout_ignore_sub=oidc_config.get(
  280. "backchannel_logout_ignore_sub", False
  281. ),
  282. skip_verification=oidc_config.get("skip_verification", False),
  283. user_profile_method=oidc_config.get("user_profile_method", "auto"),
  284. allow_existing_users=oidc_config.get("allow_existing_users", False),
  285. user_mapping_provider_class=user_mapping_provider_class,
  286. user_mapping_provider_config=user_mapping_provider_config,
  287. attribute_requirements=attribute_requirements,
  288. enable_registration=oidc_config.get("enable_registration", True),
  289. )
  290. @attr.s(slots=True, frozen=True, auto_attribs=True)
  291. class OidcProviderClientSecretJwtKey:
  292. # a pem-encoded signing key
  293. key: str
  294. # properties to include in the JWT header
  295. jwt_header: Mapping[str, str]
  296. # properties to include in the JWT payload.
  297. jwt_payload: Mapping[str, str]
  298. @attr.s(slots=True, frozen=True, auto_attribs=True)
  299. class OidcProviderConfig:
  300. # a unique identifier for this identity provider. Used in the 'user_external_ids'
  301. # table, as well as the query/path parameter used in the login protocol.
  302. idp_id: str
  303. # user-facing name for this identity provider.
  304. idp_name: str
  305. # Optional MXC URI for icon for this IdP.
  306. idp_icon: Optional[str]
  307. # Optional brand identifier for this IdP.
  308. idp_brand: Optional[str]
  309. # whether the OIDC discovery mechanism is used to discover endpoints
  310. discover: bool
  311. # the OIDC issuer. Used to validate tokens and (if discovery is enabled) to
  312. # discover the provider's endpoints.
  313. issuer: str
  314. # oauth2 client id to use
  315. client_id: str
  316. # oauth2 client secret to use. if `None`, use client_secret_jwt_key to generate
  317. # a secret.
  318. client_secret: Optional[str]
  319. # key to use to construct a JWT to use as a client secret. May be `None` if
  320. # `client_secret` is set.
  321. client_secret_jwt_key: Optional[OidcProviderClientSecretJwtKey]
  322. # auth method to use when exchanging the token.
  323. # Valid values are 'client_secret_basic', 'client_secret_post' and
  324. # 'none'.
  325. client_auth_method: str
  326. # Whether to enable PKCE when exchanging the authorization & token.
  327. # Valid values are 'auto', 'always', and 'never'.
  328. pkce_method: str
  329. # list of scopes to request
  330. scopes: Collection[str]
  331. # the oauth2 authorization endpoint. Required if discovery is disabled.
  332. authorization_endpoint: Optional[str]
  333. # the oauth2 token endpoint. Required if discovery is disabled.
  334. token_endpoint: Optional[str]
  335. # the OIDC userinfo endpoint. Required if discovery is disabled and the
  336. # "openid" scope is not requested.
  337. userinfo_endpoint: Optional[str]
  338. # URI where to fetch the JWKS. Required if discovery is disabled and the
  339. # "openid" scope is used.
  340. jwks_uri: Optional[str]
  341. # Whether Synapse should react to backchannel logouts
  342. backchannel_logout_enabled: bool
  343. # Whether Synapse should ignore the `sub` claim in backchannel logouts or not.
  344. backchannel_logout_ignore_sub: bool
  345. # Whether to skip metadata verification
  346. skip_verification: bool
  347. # Whether to fetch the user profile from the userinfo endpoint. Valid
  348. # values are: "auto" or "userinfo_endpoint".
  349. user_profile_method: str
  350. # whether to allow a user logging in via OIDC to match a pre-existing account
  351. # instead of failing
  352. allow_existing_users: bool
  353. # the class of the user mapping provider
  354. user_mapping_provider_class: Type
  355. # the config of the user mapping provider
  356. user_mapping_provider_config: Any
  357. # required attributes to require in userinfo to allow login/registration
  358. attribute_requirements: List[SsoAttributeRequirement]
  359. # Whether automatic registrations are enabled in the ODIC flow. Defaults to True
  360. enable_registration: bool