Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

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