您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 
 
 

1047 行
38 KiB

  1. # -*- coding: utf-8 -*-
  2. # Copyright 2020 Quentin Gliech
  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. import json
  16. import logging
  17. from typing import TYPE_CHECKING, Dict, Generic, List, Optional, Tuple, TypeVar
  18. from urllib.parse import urlencode
  19. import attr
  20. import pymacaroons
  21. from authlib.common.security import generate_token
  22. from authlib.jose import JsonWebToken
  23. from authlib.oauth2.auth import ClientAuth
  24. from authlib.oauth2.rfc6749.parameters import prepare_grant_uri
  25. from authlib.oidc.core import CodeIDToken, ImplicitIDToken, UserInfo
  26. from authlib.oidc.discovery import OpenIDProviderMetadata, get_well_known_url
  27. from jinja2 import Environment, Template
  28. from pymacaroons.exceptions import (
  29. MacaroonDeserializationException,
  30. MacaroonInvalidSignatureException,
  31. )
  32. from typing_extensions import TypedDict
  33. from twisted.web.client import readBody
  34. from synapse.config import ConfigError
  35. from synapse.http.server import respond_with_html
  36. from synapse.http.site import SynapseRequest
  37. from synapse.logging.context import make_deferred_yieldable
  38. from synapse.push.mailer import load_jinja2_templates
  39. from synapse.types import UserID, map_username_to_mxid_localpart
  40. if TYPE_CHECKING:
  41. from synapse.server import HomeServer
  42. logger = logging.getLogger(__name__)
  43. SESSION_COOKIE_NAME = b"oidc_session"
  44. #: A token exchanged from the token endpoint, as per RFC6749 sec 5.1. and
  45. #: OpenID.Core sec 3.1.3.3.
  46. Token = TypedDict(
  47. "Token",
  48. {
  49. "access_token": str,
  50. "token_type": str,
  51. "id_token": Optional[str],
  52. "refresh_token": Optional[str],
  53. "expires_in": int,
  54. "scope": Optional[str],
  55. },
  56. )
  57. #: A JWK, as per RFC7517 sec 4. The type could be more precise than that, but
  58. #: there is no real point of doing this in our case.
  59. JWK = Dict[str, str]
  60. #: A JWK Set, as per RFC7517 sec 5.
  61. JWKS = TypedDict("JWKS", {"keys": List[JWK]})
  62. class OidcError(Exception):
  63. """Used to catch errors when calling the token_endpoint
  64. """
  65. def __init__(self, error, error_description=None):
  66. self.error = error
  67. self.error_description = error_description
  68. def __str__(self):
  69. if self.error_description:
  70. return "{}: {}".format(self.error, self.error_description)
  71. return self.error
  72. class MappingException(Exception):
  73. """Used to catch errors when mapping the UserInfo object
  74. """
  75. class OidcHandler:
  76. """Handles requests related to the OpenID Connect login flow.
  77. """
  78. def __init__(self, hs: "HomeServer"):
  79. self._callback_url = hs.config.oidc_callback_url # type: str
  80. self._scopes = hs.config.oidc_scopes # type: List[str]
  81. self._client_auth = ClientAuth(
  82. hs.config.oidc_client_id,
  83. hs.config.oidc_client_secret,
  84. hs.config.oidc_client_auth_method,
  85. ) # type: ClientAuth
  86. self._client_auth_method = hs.config.oidc_client_auth_method # type: str
  87. self._provider_metadata = OpenIDProviderMetadata(
  88. issuer=hs.config.oidc_issuer,
  89. authorization_endpoint=hs.config.oidc_authorization_endpoint,
  90. token_endpoint=hs.config.oidc_token_endpoint,
  91. userinfo_endpoint=hs.config.oidc_userinfo_endpoint,
  92. jwks_uri=hs.config.oidc_jwks_uri,
  93. ) # type: OpenIDProviderMetadata
  94. self._provider_needs_discovery = hs.config.oidc_discover # type: bool
  95. self._user_mapping_provider = hs.config.oidc_user_mapping_provider_class(
  96. hs.config.oidc_user_mapping_provider_config
  97. ) # type: OidcMappingProvider
  98. self._skip_verification = hs.config.oidc_skip_verification # type: bool
  99. self._http_client = hs.get_proxied_http_client()
  100. self._auth_handler = hs.get_auth_handler()
  101. self._registration_handler = hs.get_registration_handler()
  102. self._datastore = hs.get_datastore()
  103. self._clock = hs.get_clock()
  104. self._hostname = hs.hostname # type: str
  105. self._server_name = hs.config.server_name # type: str
  106. self._macaroon_secret_key = hs.config.macaroon_secret_key
  107. self._error_template = load_jinja2_templates(
  108. hs.config.sso_template_dir, ["sso_error.html"]
  109. )[0]
  110. # identifier for the external_ids table
  111. self._auth_provider_id = "oidc"
  112. def _render_error(
  113. self, request, error: str, error_description: Optional[str] = None
  114. ) -> None:
  115. """Renders the error template and respond with it.
  116. This is used to show errors to the user. The template of this page can
  117. be found under ``synapse/res/templates/sso_error.html``.
  118. Args:
  119. request: The incoming request from the browser.
  120. We'll respond with an HTML page describing the error.
  121. error: A technical identifier for this error. Those include
  122. well-known OAuth2/OIDC error types like invalid_request or
  123. access_denied.
  124. error_description: A human-readable description of the error.
  125. """
  126. html = self._error_template.render(
  127. error=error, error_description=error_description
  128. )
  129. respond_with_html(request, 400, html)
  130. def _validate_metadata(self):
  131. """Verifies the provider metadata.
  132. This checks the validity of the currently loaded provider. Not
  133. everything is checked, only:
  134. - ``issuer``
  135. - ``authorization_endpoint``
  136. - ``token_endpoint``
  137. - ``response_types_supported`` (checks if "code" is in it)
  138. - ``jwks_uri``
  139. Raises:
  140. ValueError: if something in the provider is not valid
  141. """
  142. # Skip verification to allow non-compliant providers (e.g. issuers not running on a secure origin)
  143. if self._skip_verification is True:
  144. return
  145. m = self._provider_metadata
  146. m.validate_issuer()
  147. m.validate_authorization_endpoint()
  148. m.validate_token_endpoint()
  149. if m.get("token_endpoint_auth_methods_supported") is not None:
  150. m.validate_token_endpoint_auth_methods_supported()
  151. if (
  152. self._client_auth_method
  153. not in m["token_endpoint_auth_methods_supported"]
  154. ):
  155. raise ValueError(
  156. '"{auth_method}" not in "token_endpoint_auth_methods_supported" ({supported!r})'.format(
  157. auth_method=self._client_auth_method,
  158. supported=m["token_endpoint_auth_methods_supported"],
  159. )
  160. )
  161. if m.get("response_types_supported") is not None:
  162. m.validate_response_types_supported()
  163. if "code" not in m["response_types_supported"]:
  164. raise ValueError(
  165. '"code" not in "response_types_supported" (%r)'
  166. % (m["response_types_supported"],)
  167. )
  168. # If the openid scope was not requested, we need a userinfo endpoint to fetch user infos
  169. if self._uses_userinfo:
  170. if m.get("userinfo_endpoint") is None:
  171. raise ValueError(
  172. 'provider has no "userinfo_endpoint", even though it is required because the "openid" scope is not requested'
  173. )
  174. else:
  175. # If we're not using userinfo, we need a valid jwks to validate the ID token
  176. if m.get("jwks") is None:
  177. if m.get("jwks_uri") is not None:
  178. m.validate_jwks_uri()
  179. else:
  180. raise ValueError('"jwks_uri" must be set')
  181. @property
  182. def _uses_userinfo(self) -> bool:
  183. """Returns True if the ``userinfo_endpoint`` should be used.
  184. This is based on the requested scopes: if the scopes include
  185. ``openid``, the provider should give use an ID token containing the
  186. user informations. If not, we should fetch them using the
  187. ``access_token`` with the ``userinfo_endpoint``.
  188. """
  189. # Maybe that should be user-configurable and not inferred?
  190. return "openid" not in self._scopes
  191. async def load_metadata(self) -> OpenIDProviderMetadata:
  192. """Load and validate the provider metadata.
  193. The values metadatas are discovered if ``oidc_config.discovery`` is
  194. ``True`` and then cached.
  195. Raises:
  196. ValueError: if something in the provider is not valid
  197. Returns:
  198. The provider's metadata.
  199. """
  200. # If we are using the OpenID Discovery documents, it needs to be loaded once
  201. # FIXME: should there be a lock here?
  202. if self._provider_needs_discovery:
  203. url = get_well_known_url(self._provider_metadata["issuer"], external=True)
  204. metadata_response = await self._http_client.get_json(url)
  205. # TODO: maybe update the other way around to let user override some values?
  206. self._provider_metadata.update(metadata_response)
  207. self._provider_needs_discovery = False
  208. self._validate_metadata()
  209. return self._provider_metadata
  210. async def load_jwks(self, force: bool = False) -> JWKS:
  211. """Load the JSON Web Key Set used to sign ID tokens.
  212. If we're not using the ``userinfo_endpoint``, user infos are extracted
  213. from the ID token, which is a JWT signed by keys given by the provider.
  214. The keys are then cached.
  215. Args:
  216. force: Force reloading the keys.
  217. Returns:
  218. The key set
  219. Looks like this::
  220. {
  221. 'keys': [
  222. {
  223. 'kid': 'abcdef',
  224. 'kty': 'RSA',
  225. 'alg': 'RS256',
  226. 'use': 'sig',
  227. 'e': 'XXXX',
  228. 'n': 'XXXX',
  229. }
  230. ]
  231. }
  232. """
  233. if self._uses_userinfo:
  234. # We're not using jwt signing, return an empty jwk set
  235. return {"keys": []}
  236. # First check if the JWKS are loaded in the provider metadata.
  237. # It can happen either if the provider gives its JWKS in the discovery
  238. # document directly or if it was already loaded once.
  239. metadata = await self.load_metadata()
  240. jwk_set = metadata.get("jwks")
  241. if jwk_set is not None and not force:
  242. return jwk_set
  243. # Loading the JWKS using the `jwks_uri` metadata
  244. uri = metadata.get("jwks_uri")
  245. if not uri:
  246. raise RuntimeError('Missing "jwks_uri" in metadata')
  247. jwk_set = await self._http_client.get_json(uri)
  248. # Caching the JWKS in the provider's metadata
  249. self._provider_metadata["jwks"] = jwk_set
  250. return jwk_set
  251. async def _exchange_code(self, code: str) -> Token:
  252. """Exchange an authorization code for a token.
  253. This calls the ``token_endpoint`` with the authorization code we
  254. received in the callback to exchange it for a token. The call uses the
  255. ``ClientAuth`` to authenticate with the client with its ID and secret.
  256. See:
  257. https://tools.ietf.org/html/rfc6749#section-3.2
  258. https://openid.net/specs/openid-connect-core-1_0.html#TokenEndpoint
  259. Args:
  260. code: The authorization code we got from the callback.
  261. Returns:
  262. A dict containing various tokens.
  263. May look like this::
  264. {
  265. 'token_type': 'bearer',
  266. 'access_token': 'abcdef',
  267. 'expires_in': 3599,
  268. 'id_token': 'ghijkl',
  269. 'refresh_token': 'mnopqr',
  270. }
  271. Raises:
  272. OidcError: when the ``token_endpoint`` returned an error.
  273. """
  274. metadata = await self.load_metadata()
  275. token_endpoint = metadata.get("token_endpoint")
  276. headers = {
  277. "Content-Type": "application/x-www-form-urlencoded",
  278. "User-Agent": self._http_client.user_agent,
  279. "Accept": "application/json",
  280. }
  281. args = {
  282. "grant_type": "authorization_code",
  283. "code": code,
  284. "redirect_uri": self._callback_url,
  285. }
  286. body = urlencode(args, True)
  287. # Fill the body/headers with credentials
  288. uri, headers, body = self._client_auth.prepare(
  289. method="POST", uri=token_endpoint, headers=headers, body=body
  290. )
  291. headers = {k: [v] for (k, v) in headers.items()}
  292. # Do the actual request
  293. # We're not using the SimpleHttpClient util methods as we don't want to
  294. # check the HTTP status code and we do the body encoding ourself.
  295. response = await self._http_client.request(
  296. method="POST", uri=uri, data=body.encode("utf-8"), headers=headers,
  297. )
  298. # This is used in multiple error messages below
  299. status = "{code} {phrase}".format(
  300. code=response.code, phrase=response.phrase.decode("utf-8")
  301. )
  302. resp_body = await make_deferred_yieldable(readBody(response))
  303. if response.code >= 500:
  304. # In case of a server error, we should first try to decode the body
  305. # and check for an error field. If not, we respond with a generic
  306. # error message.
  307. try:
  308. resp = json.loads(resp_body.decode("utf-8"))
  309. error = resp["error"]
  310. description = resp.get("error_description", error)
  311. except (ValueError, KeyError):
  312. # Catch ValueError for the JSON decoding and KeyError for the "error" field
  313. error = "server_error"
  314. description = (
  315. (
  316. 'Authorization server responded with a "{status}" error '
  317. "while exchanging the authorization code."
  318. ).format(status=status),
  319. )
  320. raise OidcError(error, description)
  321. # Since it is a not a 5xx code, body should be a valid JSON. It will
  322. # raise if not.
  323. resp = json.loads(resp_body.decode("utf-8"))
  324. if "error" in resp:
  325. error = resp["error"]
  326. # In case the authorization server responded with an error field,
  327. # it should be a 4xx code. If not, warn about it but don't do
  328. # anything special and report the original error message.
  329. if response.code < 400:
  330. logger.debug(
  331. "Invalid response from the authorization server: "
  332. 'responded with a "{status}" '
  333. "but body has an error field: {error!r}".format(
  334. status=status, error=resp["error"]
  335. )
  336. )
  337. description = resp.get("error_description", error)
  338. raise OidcError(error, description)
  339. # Now, this should not be an error. According to RFC6749 sec 5.1, it
  340. # should be a 200 code. We're a bit more flexible than that, and will
  341. # only throw on a 4xx code.
  342. if response.code >= 400:
  343. description = (
  344. 'Authorization server responded with a "{status}" error '
  345. 'but did not include an "error" field in its response.'.format(
  346. status=status
  347. )
  348. )
  349. logger.warning(description)
  350. # Body was still valid JSON. Might be useful to log it for debugging.
  351. logger.warning("Code exchange response: {resp!r}".format(resp=resp))
  352. raise OidcError("server_error", description)
  353. return resp
  354. async def _fetch_userinfo(self, token: Token) -> UserInfo:
  355. """Fetch user informations from the ``userinfo_endpoint``.
  356. Args:
  357. token: the token given by the ``token_endpoint``.
  358. Must include an ``access_token`` field.
  359. Returns:
  360. UserInfo: an object representing the user.
  361. """
  362. metadata = await self.load_metadata()
  363. resp = await self._http_client.get_json(
  364. metadata["userinfo_endpoint"],
  365. headers={"Authorization": ["Bearer {}".format(token["access_token"])]},
  366. )
  367. return UserInfo(resp)
  368. async def _parse_id_token(self, token: Token, nonce: str) -> UserInfo:
  369. """Return an instance of UserInfo from token's ``id_token``.
  370. Args:
  371. token: the token given by the ``token_endpoint``.
  372. Must include an ``id_token`` field.
  373. nonce: the nonce value originally sent in the initial authorization
  374. request. This value should match the one inside the token.
  375. Returns:
  376. An object representing the user.
  377. """
  378. metadata = await self.load_metadata()
  379. claims_params = {
  380. "nonce": nonce,
  381. "client_id": self._client_auth.client_id,
  382. }
  383. if "access_token" in token:
  384. # If we got an `access_token`, there should be an `at_hash` claim
  385. # in the `id_token` that we can check against.
  386. claims_params["access_token"] = token["access_token"]
  387. claims_cls = CodeIDToken
  388. else:
  389. claims_cls = ImplicitIDToken
  390. alg_values = metadata.get("id_token_signing_alg_values_supported", ["RS256"])
  391. jwt = JsonWebToken(alg_values)
  392. claim_options = {"iss": {"values": [metadata["issuer"]]}}
  393. # Try to decode the keys in cache first, then retry by forcing the keys
  394. # to be reloaded
  395. jwk_set = await self.load_jwks()
  396. try:
  397. claims = jwt.decode(
  398. token["id_token"],
  399. key=jwk_set,
  400. claims_cls=claims_cls,
  401. claims_options=claim_options,
  402. claims_params=claims_params,
  403. )
  404. except ValueError:
  405. logger.info("Reloading JWKS after decode error")
  406. jwk_set = await self.load_jwks(force=True) # try reloading the jwks
  407. claims = jwt.decode(
  408. token["id_token"],
  409. key=jwk_set,
  410. claims_cls=claims_cls,
  411. claims_options=claim_options,
  412. claims_params=claims_params,
  413. )
  414. claims.validate(leeway=120) # allows 2 min of clock skew
  415. return UserInfo(claims)
  416. async def handle_redirect_request(
  417. self,
  418. request: SynapseRequest,
  419. client_redirect_url: bytes,
  420. ui_auth_session_id: Optional[str] = None,
  421. ) -> str:
  422. """Handle an incoming request to /login/sso/redirect
  423. It returns a redirect to the authorization endpoint with a few
  424. parameters:
  425. - ``client_id``: the client ID set in ``oidc_config.client_id``
  426. - ``response_type``: ``code``
  427. - ``redirect_uri``: the callback URL ; ``{base url}/_synapse/oidc/callback``
  428. - ``scope``: the list of scopes set in ``oidc_config.scopes``
  429. - ``state``: a random string
  430. - ``nonce``: a random string
  431. In addition generating a redirect URL, we are setting a cookie with
  432. a signed macaroon token containing the state, the nonce and the
  433. client_redirect_url params. Those are then checked when the client
  434. comes back from the provider.
  435. Args:
  436. request: the incoming request from the browser.
  437. We'll respond to it with a redirect and a cookie.
  438. client_redirect_url: the URL that we should redirect the client to
  439. when everything is done
  440. ui_auth_session_id: The session ID of the ongoing UI Auth (or
  441. None if this is a login).
  442. Returns:
  443. The redirect URL to the authorization endpoint.
  444. """
  445. state = generate_token()
  446. nonce = generate_token()
  447. cookie = self._generate_oidc_session_token(
  448. state=state,
  449. nonce=nonce,
  450. client_redirect_url=client_redirect_url.decode(),
  451. ui_auth_session_id=ui_auth_session_id,
  452. )
  453. request.addCookie(
  454. SESSION_COOKIE_NAME,
  455. cookie,
  456. path="/_synapse/oidc",
  457. max_age="3600",
  458. httpOnly=True,
  459. sameSite="lax",
  460. )
  461. metadata = await self.load_metadata()
  462. authorization_endpoint = metadata.get("authorization_endpoint")
  463. return prepare_grant_uri(
  464. authorization_endpoint,
  465. client_id=self._client_auth.client_id,
  466. response_type="code",
  467. redirect_uri=self._callback_url,
  468. scope=self._scopes,
  469. state=state,
  470. nonce=nonce,
  471. )
  472. async def handle_oidc_callback(self, request: SynapseRequest) -> None:
  473. """Handle an incoming request to /_synapse/oidc/callback
  474. Since we might want to display OIDC-related errors in a user-friendly
  475. way, we don't raise SynapseError from here. Instead, we call
  476. ``self._render_error`` which displays an HTML page for the error.
  477. Most of the OpenID Connect logic happens here:
  478. - first, we check if there was any error returned by the provider and
  479. display it
  480. - then we fetch the session cookie, decode and verify it
  481. - the ``state`` query parameter should match with the one stored in the
  482. session cookie
  483. - once we known this session is legit, exchange the code with the
  484. provider using the ``token_endpoint`` (see ``_exchange_code``)
  485. - once we have the token, use it to either extract the UserInfo from
  486. the ``id_token`` (``_parse_id_token``), or use the ``access_token``
  487. to fetch UserInfo from the ``userinfo_endpoint``
  488. (``_fetch_userinfo``)
  489. - map those UserInfo to a Matrix user (``_map_userinfo_to_user``) and
  490. finish the login
  491. Args:
  492. request: the incoming request from the browser.
  493. """
  494. # The provider might redirect with an error.
  495. # In that case, just display it as-is.
  496. if b"error" in request.args:
  497. # error response from the auth server. see:
  498. # https://tools.ietf.org/html/rfc6749#section-4.1.2.1
  499. # https://openid.net/specs/openid-connect-core-1_0.html#AuthError
  500. error = request.args[b"error"][0].decode()
  501. description = request.args.get(b"error_description", [b""])[0].decode()
  502. # Most of the errors returned by the provider could be due by
  503. # either the provider misbehaving or Synapse being misconfigured.
  504. # The only exception of that is "access_denied", where the user
  505. # probably cancelled the login flow. In other cases, log those errors.
  506. if error != "access_denied":
  507. logger.error("Error from the OIDC provider: %s %s", error, description)
  508. self._render_error(request, error, description)
  509. return
  510. # otherwise, it is presumably a successful response. see:
  511. # https://tools.ietf.org/html/rfc6749#section-4.1.2
  512. # Fetch the session cookie
  513. session = request.getCookie(SESSION_COOKIE_NAME) # type: Optional[bytes]
  514. if session is None:
  515. logger.info("No session cookie found")
  516. self._render_error(request, "missing_session", "No session cookie found")
  517. return
  518. # Remove the cookie. There is a good chance that if the callback failed
  519. # once, it will fail next time and the code will already be exchanged.
  520. # Removing it early avoids spamming the provider with token requests.
  521. request.addCookie(
  522. SESSION_COOKIE_NAME,
  523. b"",
  524. path="/_synapse/oidc",
  525. expires="Thu, Jan 01 1970 00:00:00 UTC",
  526. httpOnly=True,
  527. sameSite="lax",
  528. )
  529. # Check for the state query parameter
  530. if b"state" not in request.args:
  531. logger.info("State parameter is missing")
  532. self._render_error(request, "invalid_request", "State parameter is missing")
  533. return
  534. state = request.args[b"state"][0].decode()
  535. # Deserialize the session token and verify it.
  536. try:
  537. (
  538. nonce,
  539. client_redirect_url,
  540. ui_auth_session_id,
  541. ) = self._verify_oidc_session_token(session, state)
  542. except MacaroonDeserializationException as e:
  543. logger.exception("Invalid session")
  544. self._render_error(request, "invalid_session", str(e))
  545. return
  546. except MacaroonInvalidSignatureException as e:
  547. logger.exception("Could not verify session")
  548. self._render_error(request, "mismatching_session", str(e))
  549. return
  550. # Exchange the code with the provider
  551. if b"code" not in request.args:
  552. logger.info("Code parameter is missing")
  553. self._render_error(request, "invalid_request", "Code parameter is missing")
  554. return
  555. logger.debug("Exchanging code")
  556. code = request.args[b"code"][0].decode()
  557. try:
  558. token = await self._exchange_code(code)
  559. except OidcError as e:
  560. logger.exception("Could not exchange code")
  561. self._render_error(request, e.error, e.error_description)
  562. return
  563. logger.debug("Successfully obtained OAuth2 access token")
  564. # Now that we have a token, get the userinfo, either by decoding the
  565. # `id_token` or by fetching the `userinfo_endpoint`.
  566. if self._uses_userinfo:
  567. logger.debug("Fetching userinfo")
  568. try:
  569. userinfo = await self._fetch_userinfo(token)
  570. except Exception as e:
  571. logger.exception("Could not fetch userinfo")
  572. self._render_error(request, "fetch_error", str(e))
  573. return
  574. else:
  575. logger.debug("Extracting userinfo from id_token")
  576. try:
  577. userinfo = await self._parse_id_token(token, nonce=nonce)
  578. except Exception as e:
  579. logger.exception("Invalid id_token")
  580. self._render_error(request, "invalid_token", str(e))
  581. return
  582. # Call the mapper to register/login the user
  583. try:
  584. user_id = await self._map_userinfo_to_user(userinfo, token)
  585. except MappingException as e:
  586. logger.exception("Could not map user")
  587. self._render_error(request, "mapping_error", str(e))
  588. return
  589. # and finally complete the login
  590. if ui_auth_session_id:
  591. await self._auth_handler.complete_sso_ui_auth(
  592. user_id, ui_auth_session_id, request
  593. )
  594. else:
  595. await self._auth_handler.complete_sso_login(
  596. user_id, request, client_redirect_url
  597. )
  598. def _generate_oidc_session_token(
  599. self,
  600. state: str,
  601. nonce: str,
  602. client_redirect_url: str,
  603. ui_auth_session_id: Optional[str],
  604. duration_in_ms: int = (60 * 60 * 1000),
  605. ) -> str:
  606. """Generates a signed token storing data about an OIDC session.
  607. When Synapse initiates an authorization flow, it creates a random state
  608. and a random nonce. Those parameters are given to the provider and
  609. should be verified when the client comes back from the provider.
  610. It is also used to store the client_redirect_url, which is used to
  611. complete the SSO login flow.
  612. Args:
  613. state: The ``state`` parameter passed to the OIDC provider.
  614. nonce: The ``nonce`` parameter passed to the OIDC provider.
  615. client_redirect_url: The URL the client gave when it initiated the
  616. flow.
  617. ui_auth_session_id: The session ID of the ongoing UI Auth (or
  618. None if this is a login).
  619. duration_in_ms: An optional duration for the token in milliseconds.
  620. Defaults to an hour.
  621. Returns:
  622. A signed macaroon token with the session informations.
  623. """
  624. macaroon = pymacaroons.Macaroon(
  625. location=self._server_name, identifier="key", key=self._macaroon_secret_key,
  626. )
  627. macaroon.add_first_party_caveat("gen = 1")
  628. macaroon.add_first_party_caveat("type = session")
  629. macaroon.add_first_party_caveat("state = %s" % (state,))
  630. macaroon.add_first_party_caveat("nonce = %s" % (nonce,))
  631. macaroon.add_first_party_caveat(
  632. "client_redirect_url = %s" % (client_redirect_url,)
  633. )
  634. if ui_auth_session_id:
  635. macaroon.add_first_party_caveat(
  636. "ui_auth_session_id = %s" % (ui_auth_session_id,)
  637. )
  638. now = self._clock.time_msec()
  639. expiry = now + duration_in_ms
  640. macaroon.add_first_party_caveat("time < %d" % (expiry,))
  641. return macaroon.serialize()
  642. def _verify_oidc_session_token(
  643. self, session: bytes, state: str
  644. ) -> Tuple[str, str, Optional[str]]:
  645. """Verifies and extract an OIDC session token.
  646. This verifies that a given session token was issued by this homeserver
  647. and extract the nonce and client_redirect_url caveats.
  648. Args:
  649. session: The session token to verify
  650. state: The state the OIDC provider gave back
  651. Returns:
  652. The nonce, client_redirect_url, and ui_auth_session_id for this session
  653. """
  654. macaroon = pymacaroons.Macaroon.deserialize(session)
  655. v = pymacaroons.Verifier()
  656. v.satisfy_exact("gen = 1")
  657. v.satisfy_exact("type = session")
  658. v.satisfy_exact("state = %s" % (state,))
  659. v.satisfy_general(lambda c: c.startswith("nonce = "))
  660. v.satisfy_general(lambda c: c.startswith("client_redirect_url = "))
  661. # Sometimes there's a UI auth session ID, it seems to be OK to attempt
  662. # to always satisfy this.
  663. v.satisfy_general(lambda c: c.startswith("ui_auth_session_id = "))
  664. v.satisfy_general(self._verify_expiry)
  665. v.verify(macaroon, self._macaroon_secret_key)
  666. # Extract the `nonce`, `client_redirect_url`, and maybe the
  667. # `ui_auth_session_id` from the token.
  668. nonce = self._get_value_from_macaroon(macaroon, "nonce")
  669. client_redirect_url = self._get_value_from_macaroon(
  670. macaroon, "client_redirect_url"
  671. )
  672. try:
  673. ui_auth_session_id = self._get_value_from_macaroon(
  674. macaroon, "ui_auth_session_id"
  675. ) # type: Optional[str]
  676. except ValueError:
  677. ui_auth_session_id = None
  678. return nonce, client_redirect_url, ui_auth_session_id
  679. def _get_value_from_macaroon(self, macaroon: pymacaroons.Macaroon, key: str) -> str:
  680. """Extracts a caveat value from a macaroon token.
  681. Args:
  682. macaroon: the token
  683. key: the key of the caveat to extract
  684. Returns:
  685. The extracted value
  686. Raises:
  687. Exception: if the caveat was not in the macaroon
  688. """
  689. prefix = key + " = "
  690. for caveat in macaroon.caveats:
  691. if caveat.caveat_id.startswith(prefix):
  692. return caveat.caveat_id[len(prefix) :]
  693. raise ValueError("No %s caveat in macaroon" % (key,))
  694. def _verify_expiry(self, caveat: str) -> bool:
  695. prefix = "time < "
  696. if not caveat.startswith(prefix):
  697. return False
  698. expiry = int(caveat[len(prefix) :])
  699. now = self._clock.time_msec()
  700. return now < expiry
  701. async def _map_userinfo_to_user(self, userinfo: UserInfo, token: Token) -> str:
  702. """Maps a UserInfo object to a mxid.
  703. UserInfo should have a claim that uniquely identifies users. This claim
  704. is usually `sub`, but can be configured with `oidc_config.subject_claim`.
  705. It is then used as an `external_id`.
  706. If we don't find the user that way, we should register the user,
  707. mapping the localpart and the display name from the UserInfo.
  708. If a user already exists with the mxid we've mapped, raise an exception.
  709. Args:
  710. userinfo: an object representing the user
  711. token: a dict with the tokens obtained from the provider
  712. Raises:
  713. MappingException: if there was an error while mapping some properties
  714. Returns:
  715. The mxid of the user
  716. """
  717. try:
  718. remote_user_id = self._user_mapping_provider.get_remote_user_id(userinfo)
  719. except Exception as e:
  720. raise MappingException(
  721. "Failed to extract subject from OIDC response: %s" % (e,)
  722. )
  723. logger.info(
  724. "Looking for existing mapping for user %s:%s",
  725. self._auth_provider_id,
  726. remote_user_id,
  727. )
  728. registered_user_id = await self._datastore.get_user_by_external_id(
  729. self._auth_provider_id, remote_user_id,
  730. )
  731. if registered_user_id is not None:
  732. logger.info("Found existing mapping %s", registered_user_id)
  733. return registered_user_id
  734. try:
  735. attributes = await self._user_mapping_provider.map_user_attributes(
  736. userinfo, token
  737. )
  738. except Exception as e:
  739. raise MappingException(
  740. "Could not extract user attributes from OIDC response: " + str(e)
  741. )
  742. logger.debug(
  743. "Retrieved user attributes from user mapping provider: %r", attributes
  744. )
  745. if not attributes["localpart"]:
  746. raise MappingException("localpart is empty")
  747. localpart = map_username_to_mxid_localpart(attributes["localpart"])
  748. user_id = UserID(localpart, self._hostname)
  749. if await self._datastore.get_users_by_id_case_insensitive(user_id.to_string()):
  750. # This mxid is taken
  751. raise MappingException(
  752. "mxid '{}' is already taken".format(user_id.to_string())
  753. )
  754. # It's the first time this user is logging in and the mapped mxid was
  755. # not taken, register the user
  756. registered_user_id = await self._registration_handler.register_user(
  757. localpart=localpart, default_display_name=attributes["display_name"],
  758. )
  759. await self._datastore.record_user_external_id(
  760. self._auth_provider_id, remote_user_id, registered_user_id,
  761. )
  762. return registered_user_id
  763. UserAttribute = TypedDict(
  764. "UserAttribute", {"localpart": str, "display_name": Optional[str]}
  765. )
  766. C = TypeVar("C")
  767. class OidcMappingProvider(Generic[C]):
  768. """A mapping provider maps a UserInfo object to user attributes.
  769. It should provide the API described by this class.
  770. """
  771. def __init__(self, config: C):
  772. """
  773. Args:
  774. config: A custom config object from this module, parsed by ``parse_config()``
  775. """
  776. @staticmethod
  777. def parse_config(config: dict) -> C:
  778. """Parse the dict provided by the homeserver's config
  779. Args:
  780. config: A dictionary containing configuration options for this provider
  781. Returns:
  782. A custom config object for this module
  783. """
  784. raise NotImplementedError()
  785. def get_remote_user_id(self, userinfo: UserInfo) -> str:
  786. """Get a unique user ID for this user.
  787. Usually, in an OIDC-compliant scenario, it should be the ``sub`` claim from the UserInfo object.
  788. Args:
  789. userinfo: An object representing the user given by the OIDC provider
  790. Returns:
  791. A unique user ID
  792. """
  793. raise NotImplementedError()
  794. async def map_user_attributes(
  795. self, userinfo: UserInfo, token: Token
  796. ) -> UserAttribute:
  797. """Map a ``UserInfo`` objects into user attributes.
  798. Args:
  799. userinfo: An object representing the user given by the OIDC provider
  800. token: A dict with the tokens returned by the provider
  801. Returns:
  802. A dict containing the ``localpart`` and (optionally) the ``display_name``
  803. """
  804. raise NotImplementedError()
  805. # Used to clear out "None" values in templates
  806. def jinja_finalize(thing):
  807. return thing if thing is not None else ""
  808. env = Environment(finalize=jinja_finalize)
  809. @attr.s
  810. class JinjaOidcMappingConfig:
  811. subject_claim = attr.ib() # type: str
  812. localpart_template = attr.ib() # type: Template
  813. display_name_template = attr.ib() # type: Optional[Template]
  814. class JinjaOidcMappingProvider(OidcMappingProvider[JinjaOidcMappingConfig]):
  815. """An implementation of a mapping provider based on Jinja templates.
  816. This is the default mapping provider.
  817. """
  818. def __init__(self, config: JinjaOidcMappingConfig):
  819. self._config = config
  820. @staticmethod
  821. def parse_config(config: dict) -> JinjaOidcMappingConfig:
  822. subject_claim = config.get("subject_claim", "sub")
  823. if "localpart_template" not in config:
  824. raise ConfigError(
  825. "missing key: oidc_config.user_mapping_provider.config.localpart_template"
  826. )
  827. try:
  828. localpart_template = env.from_string(config["localpart_template"])
  829. except Exception as e:
  830. raise ConfigError(
  831. "invalid jinja template for oidc_config.user_mapping_provider.config.localpart_template: %r"
  832. % (e,)
  833. )
  834. display_name_template = None # type: Optional[Template]
  835. if "display_name_template" in config:
  836. try:
  837. display_name_template = env.from_string(config["display_name_template"])
  838. except Exception as e:
  839. raise ConfigError(
  840. "invalid jinja template for oidc_config.user_mapping_provider.config.display_name_template: %r"
  841. % (e,)
  842. )
  843. return JinjaOidcMappingConfig(
  844. subject_claim=subject_claim,
  845. localpart_template=localpart_template,
  846. display_name_template=display_name_template,
  847. )
  848. def get_remote_user_id(self, userinfo: UserInfo) -> str:
  849. return userinfo[self._config.subject_claim]
  850. async def map_user_attributes(
  851. self, userinfo: UserInfo, token: Token
  852. ) -> UserAttribute:
  853. localpart = self._config.localpart_template.render(user=userinfo).strip()
  854. display_name = None # type: Optional[str]
  855. if self._config.display_name_template is not None:
  856. display_name = self._config.display_name_template.render(
  857. user=userinfo
  858. ).strip()
  859. if display_name == "":
  860. display_name = None
  861. return UserAttribute(localpart=localpart, display_name=display_name)