oidc_handler.py 39 KB

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