oidc.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  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. "scopes": {"type": "array", "items": {"type": "string"}},
  107. "authorization_endpoint": {"type": "string"},
  108. "token_endpoint": {"type": "string"},
  109. "userinfo_endpoint": {"type": "string"},
  110. "jwks_uri": {"type": "string"},
  111. "skip_verification": {"type": "boolean"},
  112. "backchannel_logout_enabled": {"type": "boolean"},
  113. "backchannel_logout_ignore_sub": {"type": "boolean"},
  114. "user_profile_method": {
  115. "type": "string",
  116. "enum": ["auto", "userinfo_endpoint"],
  117. },
  118. "allow_existing_users": {"type": "boolean"},
  119. "user_mapping_provider": {"type": ["object", "null"]},
  120. "attribute_requirements": {
  121. "type": "array",
  122. "items": SsoAttributeRequirement.JSON_SCHEMA,
  123. },
  124. },
  125. }
  126. # the same as OIDC_PROVIDER_CONFIG_SCHEMA, but with compulsory idp_id and idp_name
  127. OIDC_PROVIDER_CONFIG_WITH_ID_SCHEMA = {
  128. "allOf": [OIDC_PROVIDER_CONFIG_SCHEMA, {"required": ["idp_id", "idp_name"]}]
  129. }
  130. # the `oidc_providers` list can either be None (as it is in the default config), or
  131. # a list of provider configs, each of which requires an explicit ID and name.
  132. OIDC_PROVIDER_LIST_SCHEMA = {
  133. "oneOf": [
  134. {"type": "null"},
  135. {"type": "array", "items": OIDC_PROVIDER_CONFIG_WITH_ID_SCHEMA},
  136. ]
  137. }
  138. # the `oidc_config` setting can either be None (which it used to be in the default
  139. # config), or an object. If an object, it is ignored unless it has an "enabled: True"
  140. # property.
  141. #
  142. # It's *possible* to represent this with jsonschema, but the resultant errors aren't
  143. # particularly clear, so we just check for either an object or a null here, and do
  144. # additional checks in the code.
  145. OIDC_CONFIG_SCHEMA = {"oneOf": [{"type": "null"}, {"type": "object"}]}
  146. # the top-level schema can contain an "oidc_config" and/or an "oidc_providers".
  147. MAIN_CONFIG_SCHEMA = {
  148. "type": "object",
  149. "properties": {
  150. "oidc_config": OIDC_CONFIG_SCHEMA,
  151. "oidc_providers": OIDC_PROVIDER_LIST_SCHEMA,
  152. },
  153. }
  154. def _parse_oidc_provider_configs(config: JsonDict) -> Iterable["OidcProviderConfig"]:
  155. """extract and parse the OIDC provider configs from the config dict
  156. The configuration may contain either a single `oidc_config` object with an
  157. `enabled: True` property, or a list of provider configurations under
  158. `oidc_providers`, *or both*.
  159. Returns a generator which yields the OidcProviderConfig objects
  160. """
  161. validate_config(MAIN_CONFIG_SCHEMA, config, ())
  162. for i, p in enumerate(config.get("oidc_providers") or []):
  163. yield _parse_oidc_config_dict(p, ("oidc_providers", "<item %i>" % (i,)))
  164. # for backwards-compatibility, it is also possible to provide a single "oidc_config"
  165. # object with an "enabled: True" property.
  166. oidc_config = config.get("oidc_config")
  167. if oidc_config and oidc_config.get("enabled", False):
  168. # MAIN_CONFIG_SCHEMA checks that `oidc_config` is an object, but not that
  169. # it matches OIDC_PROVIDER_CONFIG_SCHEMA (see the comments on OIDC_CONFIG_SCHEMA
  170. # above), so now we need to validate it.
  171. validate_config(OIDC_PROVIDER_CONFIG_SCHEMA, oidc_config, ("oidc_config",))
  172. yield _parse_oidc_config_dict(oidc_config, ("oidc_config",))
  173. def _parse_oidc_config_dict(
  174. oidc_config: JsonDict, config_path: Tuple[str, ...]
  175. ) -> "OidcProviderConfig":
  176. """Take the configuration dict and parse it into an OidcProviderConfig
  177. Raises:
  178. ConfigError if the configuration is malformed.
  179. """
  180. ump_config = oidc_config.get("user_mapping_provider", {})
  181. ump_config.setdefault("module", DEFAULT_USER_MAPPING_PROVIDER)
  182. if ump_config.get("module") == LEGACY_USER_MAPPING_PROVIDER:
  183. ump_config["module"] = DEFAULT_USER_MAPPING_PROVIDER
  184. ump_config.setdefault("config", {})
  185. (
  186. user_mapping_provider_class,
  187. user_mapping_provider_config,
  188. ) = load_module(ump_config, config_path + ("user_mapping_provider",))
  189. # Ensure loaded user mapping module has defined all necessary methods
  190. required_methods = [
  191. "get_remote_user_id",
  192. "map_user_attributes",
  193. ]
  194. missing_methods = [
  195. method
  196. for method in required_methods
  197. if not hasattr(user_mapping_provider_class, method)
  198. ]
  199. if missing_methods:
  200. raise ConfigError(
  201. "Class %s is missing required "
  202. "methods: %s"
  203. % (
  204. user_mapping_provider_class,
  205. ", ".join(missing_methods),
  206. ),
  207. config_path + ("user_mapping_provider", "module"),
  208. )
  209. idp_id = oidc_config.get("idp_id", "oidc")
  210. # prefix the given IDP with a prefix specific to the SSO mechanism, to avoid
  211. # clashes with other mechs (such as SAML, CAS).
  212. #
  213. # We allow "oidc" as an exception so that people migrating from old-style
  214. # "oidc_config" format (which has long used "oidc" as its idp_id) can migrate to
  215. # a new-style "oidc_providers" entry without changing the idp_id for their provider
  216. # (and thereby invalidating their user_external_ids data).
  217. if idp_id != "oidc":
  218. idp_id = "oidc-" + idp_id
  219. # MSC2858 also specifies that the idp_icon must be a valid MXC uri
  220. idp_icon = oidc_config.get("idp_icon")
  221. if idp_icon is not None:
  222. try:
  223. parse_and_validate_mxc_uri(idp_icon)
  224. except ValueError as e:
  225. raise ConfigError(
  226. "idp_icon must be a valid MXC URI", config_path + ("idp_icon",)
  227. ) from e
  228. client_secret_jwt_key_config = oidc_config.get("client_secret_jwt_key")
  229. client_secret_jwt_key: Optional[OidcProviderClientSecretJwtKey] = None
  230. if client_secret_jwt_key_config is not None:
  231. keyfile = client_secret_jwt_key_config.get("key_file")
  232. if keyfile:
  233. key = read_file(keyfile, config_path + ("client_secret_jwt_key",))
  234. else:
  235. key = client_secret_jwt_key_config["key"]
  236. client_secret_jwt_key = OidcProviderClientSecretJwtKey(
  237. key=key,
  238. jwt_header=client_secret_jwt_key_config["jwt_header"],
  239. jwt_payload=client_secret_jwt_key_config.get("jwt_payload", {}),
  240. )
  241. # parse attribute_requirements from config (list of dicts) into a list of SsoAttributeRequirement
  242. attribute_requirements = [
  243. SsoAttributeRequirement(**x)
  244. for x in oidc_config.get("attribute_requirements", [])
  245. ]
  246. return OidcProviderConfig(
  247. idp_id=idp_id,
  248. idp_name=oidc_config.get("idp_name", "OIDC"),
  249. idp_icon=idp_icon,
  250. idp_brand=oidc_config.get("idp_brand"),
  251. discover=oidc_config.get("discover", True),
  252. issuer=oidc_config["issuer"],
  253. client_id=oidc_config["client_id"],
  254. client_secret=oidc_config.get("client_secret"),
  255. client_secret_jwt_key=client_secret_jwt_key,
  256. client_auth_method=oidc_config.get("client_auth_method", "client_secret_basic"),
  257. scopes=oidc_config.get("scopes", ["openid"]),
  258. authorization_endpoint=oidc_config.get("authorization_endpoint"),
  259. token_endpoint=oidc_config.get("token_endpoint"),
  260. userinfo_endpoint=oidc_config.get("userinfo_endpoint"),
  261. jwks_uri=oidc_config.get("jwks_uri"),
  262. backchannel_logout_enabled=oidc_config.get("backchannel_logout_enabled", False),
  263. backchannel_logout_ignore_sub=oidc_config.get(
  264. "backchannel_logout_ignore_sub", False
  265. ),
  266. skip_verification=oidc_config.get("skip_verification", False),
  267. user_profile_method=oidc_config.get("user_profile_method", "auto"),
  268. allow_existing_users=oidc_config.get("allow_existing_users", False),
  269. user_mapping_provider_class=user_mapping_provider_class,
  270. user_mapping_provider_config=user_mapping_provider_config,
  271. attribute_requirements=attribute_requirements,
  272. )
  273. @attr.s(slots=True, frozen=True, auto_attribs=True)
  274. class OidcProviderClientSecretJwtKey:
  275. # a pem-encoded signing key
  276. key: str
  277. # properties to include in the JWT header
  278. jwt_header: Mapping[str, str]
  279. # properties to include in the JWT payload.
  280. jwt_payload: Mapping[str, str]
  281. @attr.s(slots=True, frozen=True, auto_attribs=True)
  282. class OidcProviderConfig:
  283. # a unique identifier for this identity provider. Used in the 'user_external_ids'
  284. # table, as well as the query/path parameter used in the login protocol.
  285. idp_id: str
  286. # user-facing name for this identity provider.
  287. idp_name: str
  288. # Optional MXC URI for icon for this IdP.
  289. idp_icon: Optional[str]
  290. # Optional brand identifier for this IdP.
  291. idp_brand: Optional[str]
  292. # whether the OIDC discovery mechanism is used to discover endpoints
  293. discover: bool
  294. # the OIDC issuer. Used to validate tokens and (if discovery is enabled) to
  295. # discover the provider's endpoints.
  296. issuer: str
  297. # oauth2 client id to use
  298. client_id: str
  299. # oauth2 client secret to use. if `None`, use client_secret_jwt_key to generate
  300. # a secret.
  301. client_secret: Optional[str]
  302. # key to use to construct a JWT to use as a client secret. May be `None` if
  303. # `client_secret` is set.
  304. client_secret_jwt_key: Optional[OidcProviderClientSecretJwtKey]
  305. # auth method to use when exchanging the token.
  306. # Valid values are 'client_secret_basic', 'client_secret_post' and
  307. # 'none'.
  308. client_auth_method: str
  309. # list of scopes to request
  310. scopes: Collection[str]
  311. # the oauth2 authorization endpoint. Required if discovery is disabled.
  312. authorization_endpoint: Optional[str]
  313. # the oauth2 token endpoint. Required if discovery is disabled.
  314. token_endpoint: Optional[str]
  315. # the OIDC userinfo endpoint. Required if discovery is disabled and the
  316. # "openid" scope is not requested.
  317. userinfo_endpoint: Optional[str]
  318. # URI where to fetch the JWKS. Required if discovery is disabled and the
  319. # "openid" scope is used.
  320. jwks_uri: Optional[str]
  321. # Whether Synapse should react to backchannel logouts
  322. backchannel_logout_enabled: bool
  323. # Whether Synapse should ignore the `sub` claim in backchannel logouts or not.
  324. backchannel_logout_ignore_sub: bool
  325. # Whether to skip metadata verification
  326. skip_verification: bool
  327. # Whether to fetch the user profile from the userinfo endpoint. Valid
  328. # values are: "auto" or "userinfo_endpoint".
  329. user_profile_method: str
  330. # whether to allow a user logging in via OIDC to match a pre-existing account
  331. # instead of failing
  332. allow_existing_users: bool
  333. # the class of the user mapping provider
  334. user_mapping_provider_class: Type
  335. # the config of the user mapping provider
  336. user_mapping_provider_config: Any
  337. # required attributes to require in userinfo to allow login/registration
  338. attribute_requirements: List[SsoAttributeRequirement]