sso.py 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263
  1. # Copyright 2020 The Matrix.org Foundation C.I.C.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import abc
  15. import hashlib
  16. import io
  17. import logging
  18. from typing import (
  19. TYPE_CHECKING,
  20. Any,
  21. Awaitable,
  22. Callable,
  23. Dict,
  24. Iterable,
  25. List,
  26. Mapping,
  27. Optional,
  28. Set,
  29. )
  30. from urllib.parse import urlencode
  31. import attr
  32. from typing_extensions import NoReturn, Protocol
  33. from twisted.web.iweb import IRequest
  34. from twisted.web.server import Request
  35. from synapse.api.constants import LoginType
  36. from synapse.api.errors import Codes, NotFoundError, RedirectException, SynapseError
  37. from synapse.config.sso import SsoAttributeRequirement
  38. from synapse.handlers.device import DeviceHandler
  39. from synapse.handlers.register import init_counters_for_auth_provider
  40. from synapse.handlers.ui_auth import UIAuthSessionDataConstants
  41. from synapse.http import get_request_user_agent
  42. from synapse.http.server import respond_with_html, respond_with_redirect
  43. from synapse.http.site import SynapseRequest
  44. from synapse.types import (
  45. JsonDict,
  46. StrCollection,
  47. UserID,
  48. contains_invalid_mxid_characters,
  49. create_requester,
  50. )
  51. from synapse.util.async_helpers import Linearizer
  52. from synapse.util.stringutils import random_string
  53. if TYPE_CHECKING:
  54. from synapse.server import HomeServer
  55. logger = logging.getLogger(__name__)
  56. class MappingException(Exception):
  57. """Used to catch errors when mapping an SSO response to user attributes.
  58. Note that the msg that is raised is shown to end-users.
  59. """
  60. class SsoIdentityProvider(Protocol):
  61. """Abstract base class to be implemented by SSO Identity Providers
  62. An Identity Provider, or IdP, is an external HTTP service which authenticates a user
  63. to say whether they should be allowed to log in, or perform a given action.
  64. Synapse supports various implementations of IdPs, including OpenID Connect, SAML,
  65. and CAS.
  66. The main entry point is `handle_redirect_request`, which should return a URI to
  67. redirect the user's browser to the IdP's authentication page.
  68. Each IdP should be registered with the SsoHandler via
  69. `hs.get_sso_handler().register_identity_provider()`, so that requests to
  70. `/_matrix/client/r0/login/sso/redirect` can be correctly dispatched.
  71. """
  72. @property
  73. @abc.abstractmethod
  74. def idp_id(self) -> str:
  75. """A unique identifier for this SSO provider
  76. Eg, "saml", "cas", "github"
  77. """
  78. @property
  79. @abc.abstractmethod
  80. def idp_name(self) -> str:
  81. """User-facing name for this provider"""
  82. @property
  83. def idp_icon(self) -> Optional[str]:
  84. """Optional MXC URI for user-facing icon"""
  85. return None
  86. @property
  87. def idp_brand(self) -> Optional[str]:
  88. """Optional branding identifier"""
  89. return None
  90. @abc.abstractmethod
  91. async def handle_redirect_request(
  92. self,
  93. request: SynapseRequest,
  94. client_redirect_url: Optional[bytes],
  95. ui_auth_session_id: Optional[str] = None,
  96. ) -> str:
  97. """Handle an incoming request to /login/sso/redirect
  98. Args:
  99. request: the incoming HTTP request
  100. client_redirect_url: the URL that we should redirect the
  101. client to after login (or None for UI Auth).
  102. ui_auth_session_id: The session ID of the ongoing UI Auth (or
  103. None if this is a login).
  104. Returns:
  105. URL to redirect to
  106. """
  107. raise NotImplementedError()
  108. @attr.s(auto_attribs=True)
  109. class UserAttributes:
  110. # NB: This struct is documented in docs/sso_mapping_providers.md so that users can
  111. # populate it with data from their own mapping providers.
  112. # the localpart of the mxid that the mapper has assigned to the user.
  113. # if `None`, the mapper has not picked a userid, and the user should be prompted to
  114. # enter one.
  115. localpart: Optional[str]
  116. confirm_localpart: bool = False
  117. display_name: Optional[str] = None
  118. picture: Optional[str] = None
  119. # mypy thinks these are incompatible for some reason.
  120. emails: StrCollection = attr.Factory(list) # type: ignore[assignment]
  121. @attr.s(slots=True, auto_attribs=True)
  122. class UsernameMappingSession:
  123. """Data we track about SSO sessions"""
  124. # A unique identifier for this SSO provider, e.g. "oidc" or "saml".
  125. auth_provider_id: str
  126. # An optional session ID from the IdP.
  127. auth_provider_session_id: Optional[str]
  128. # user ID on the IdP server
  129. remote_user_id: str
  130. # attributes returned by the ID mapper
  131. display_name: Optional[str]
  132. emails: StrCollection
  133. # An optional dictionary of extra attributes to be provided to the client in the
  134. # login response.
  135. extra_login_attributes: Optional[JsonDict]
  136. # where to redirect the client back to
  137. client_redirect_url: str
  138. # expiry time for the session, in milliseconds
  139. expiry_time_ms: int
  140. # choices made by the user
  141. chosen_localpart: Optional[str] = None
  142. use_display_name: bool = True
  143. emails_to_use: StrCollection = ()
  144. terms_accepted_version: Optional[str] = None
  145. # the HTTP cookie used to track the mapping session id
  146. USERNAME_MAPPING_SESSION_COOKIE_NAME = b"username_mapping_session"
  147. class SsoHandler:
  148. # The number of attempts to ask the mapping provider for when generating an MXID.
  149. _MAP_USERNAME_RETRIES = 1000
  150. # the time a UsernameMappingSession remains valid for
  151. _MAPPING_SESSION_VALIDITY_PERIOD_MS = 15 * 60 * 1000
  152. def __init__(self, hs: "HomeServer"):
  153. self._clock = hs.get_clock()
  154. self._store = hs.get_datastores().main
  155. self._server_name = hs.hostname
  156. self._registration_handler = hs.get_registration_handler()
  157. self._auth_handler = hs.get_auth_handler()
  158. self._device_handler = hs.get_device_handler()
  159. self._error_template = hs.config.sso.sso_error_template
  160. self._bad_user_template = hs.config.sso.sso_auth_bad_user_template
  161. self._profile_handler = hs.get_profile_handler()
  162. self._media_repo = (
  163. hs.get_media_repository() if hs.config.media.can_load_media_repo else None
  164. )
  165. self._http_client = hs.get_proxied_blacklisted_http_client()
  166. # The following template is shown after a successful user interactive
  167. # authentication session. It tells the user they can close the window.
  168. self._sso_auth_success_template = hs.config.sso.sso_auth_success_template
  169. self._sso_update_profile_information = (
  170. hs.config.sso.sso_update_profile_information
  171. )
  172. # a lock on the mappings
  173. self._mapping_lock = Linearizer(name="sso_user_mapping", clock=hs.get_clock())
  174. # a map from session id to session data
  175. self._username_mapping_sessions: Dict[str, UsernameMappingSession] = {}
  176. # map from idp_id to SsoIdentityProvider
  177. self._identity_providers: Dict[str, SsoIdentityProvider] = {}
  178. self._consent_at_registration = hs.config.consent.user_consent_at_registration
  179. def register_identity_provider(self, p: SsoIdentityProvider) -> None:
  180. p_id = p.idp_id
  181. assert p_id not in self._identity_providers
  182. self._identity_providers[p_id] = p
  183. init_counters_for_auth_provider(p_id)
  184. def get_identity_providers(self) -> Mapping[str, SsoIdentityProvider]:
  185. """Get the configured identity providers"""
  186. return self._identity_providers
  187. async def get_identity_providers_for_user(
  188. self, user_id: str
  189. ) -> Mapping[str, SsoIdentityProvider]:
  190. """Get the SsoIdentityProviders which a user has used
  191. Given a user id, get the identity providers that that user has used to log in
  192. with in the past (and thus could use to re-identify themselves for UI Auth).
  193. Args:
  194. user_id: MXID of user to look up
  195. Raises:
  196. a map of idp_id to SsoIdentityProvider
  197. """
  198. external_ids = await self._store.get_external_ids_by_user(user_id)
  199. valid_idps = {}
  200. for idp_id, _ in external_ids:
  201. idp = self._identity_providers.get(idp_id)
  202. if not idp:
  203. logger.warning(
  204. "User %r has an SSO mapping for IdP %r, but this is no longer "
  205. "configured.",
  206. user_id,
  207. idp_id,
  208. )
  209. else:
  210. valid_idps[idp_id] = idp
  211. return valid_idps
  212. def render_error(
  213. self,
  214. request: Request,
  215. error: str,
  216. error_description: Optional[str] = None,
  217. code: int = 400,
  218. ) -> None:
  219. """Renders the error template and responds with it.
  220. This is used to show errors to the user. The template of this page can
  221. be found under `synapse/res/templates/sso_error.html`.
  222. Args:
  223. request: The incoming request from the browser.
  224. We'll respond with an HTML page describing the error.
  225. error: A technical identifier for this error.
  226. error_description: A human-readable description of the error.
  227. code: The integer error code (an HTTP response code)
  228. """
  229. html = self._error_template.render(
  230. error=error, error_description=error_description
  231. )
  232. respond_with_html(request, code, html)
  233. async def handle_redirect_request(
  234. self,
  235. request: SynapseRequest,
  236. client_redirect_url: bytes,
  237. idp_id: Optional[str],
  238. ) -> str:
  239. """Handle a request to /login/sso/redirect
  240. Args:
  241. request: incoming HTTP request
  242. client_redirect_url: the URL that we should redirect the
  243. client to after login.
  244. idp_id: optional identity provider chosen by the client
  245. Returns:
  246. the URI to redirect to
  247. """
  248. if not self._identity_providers:
  249. raise SynapseError(
  250. 400, "Homeserver not configured for SSO.", errcode=Codes.UNRECOGNIZED
  251. )
  252. # if the client chose an IdP, use that
  253. idp: Optional[SsoIdentityProvider] = None
  254. if idp_id:
  255. idp = self._identity_providers.get(idp_id)
  256. if not idp:
  257. raise NotFoundError("Unknown identity provider")
  258. # if we only have one auth provider, redirect to it directly
  259. elif len(self._identity_providers) == 1:
  260. idp = next(iter(self._identity_providers.values()))
  261. if idp:
  262. return await idp.handle_redirect_request(request, client_redirect_url)
  263. # otherwise, redirect to the IDP picker
  264. return "/_synapse/client/pick_idp?" + urlencode(
  265. (("redirectUrl", client_redirect_url),)
  266. )
  267. async def get_sso_user_by_remote_user_id(
  268. self, auth_provider_id: str, remote_user_id: str
  269. ) -> Optional[str]:
  270. """
  271. Maps the user ID of a remote IdP to a mxid for a previously seen user.
  272. If the user has not been seen yet, this will return None.
  273. Args:
  274. auth_provider_id: A unique identifier for this SSO provider, e.g.
  275. "oidc" or "saml".
  276. remote_user_id: The user ID according to the remote IdP. This might
  277. be an e-mail address, a GUID, or some other form. It must be
  278. unique and immutable.
  279. Returns:
  280. The mxid of a previously seen user.
  281. """
  282. logger.debug(
  283. "Looking for existing mapping for user %s:%s",
  284. auth_provider_id,
  285. remote_user_id,
  286. )
  287. # Check if we already have a mapping for this user.
  288. previously_registered_user_id = await self._store.get_user_by_external_id(
  289. auth_provider_id,
  290. remote_user_id,
  291. )
  292. # A match was found, return the user ID.
  293. if previously_registered_user_id is not None:
  294. logger.info(
  295. "Found existing mapping for IdP '%s' and remote_user_id '%s': %s",
  296. auth_provider_id,
  297. remote_user_id,
  298. previously_registered_user_id,
  299. )
  300. return previously_registered_user_id
  301. # No match.
  302. return None
  303. async def complete_sso_login_request(
  304. self,
  305. auth_provider_id: str,
  306. remote_user_id: str,
  307. request: SynapseRequest,
  308. client_redirect_url: str,
  309. sso_to_matrix_id_mapper: Callable[[int], Awaitable[UserAttributes]],
  310. grandfather_existing_users: Callable[[], Awaitable[Optional[str]]],
  311. extra_login_attributes: Optional[JsonDict] = None,
  312. auth_provider_session_id: Optional[str] = None,
  313. ) -> None:
  314. """
  315. Given an SSO ID, retrieve the user ID for it and possibly register the user.
  316. This first checks if the SSO ID has previously been linked to a matrix ID,
  317. if it has that matrix ID is returned regardless of the current mapping
  318. logic.
  319. If a callable is provided for grandfathering users, it is called and can
  320. potentially return a matrix ID to use. If it does, the SSO ID is linked to
  321. this matrix ID for subsequent calls.
  322. The mapping function is called (potentially multiple times) to generate
  323. a localpart for the user.
  324. If an unused localpart is generated, the user is registered from the
  325. given user-agent and IP address and the SSO ID is linked to this matrix
  326. ID for subsequent calls.
  327. Finally, we generate a redirect to the supplied redirect uri, with a login token
  328. Args:
  329. auth_provider_id: A unique identifier for this SSO provider, e.g.
  330. "oidc" or "saml".
  331. remote_user_id: The unique identifier from the SSO provider.
  332. request: The request to respond to
  333. client_redirect_url: The redirect URL passed in by the client.
  334. sso_to_matrix_id_mapper: A callable to generate the user attributes.
  335. The only parameter is an integer which represents the amount of
  336. times the returned mxid localpart mapping has failed.
  337. It is expected that the mapper can raise two exceptions, which
  338. will get passed through to the caller:
  339. MappingException if there was a problem mapping the response
  340. to the user.
  341. RedirectException to redirect to an additional page (e.g.
  342. to prompt the user for more information).
  343. grandfather_existing_users: A callable which can return an previously
  344. existing matrix ID. The SSO ID is then linked to the returned
  345. matrix ID.
  346. extra_login_attributes: An optional dictionary of extra
  347. attributes to be provided to the client in the login response.
  348. auth_provider_session_id: An optional session ID from the IdP.
  349. Raises:
  350. MappingException if there was a problem mapping the response to a user.
  351. RedirectException: if the mapping provider needs to redirect the user
  352. to an additional page. (e.g. to prompt for more information)
  353. """
  354. new_user = False
  355. # grab a lock while we try to find a mapping for this user. This seems...
  356. # optimistic, especially for implementations that end up redirecting to
  357. # interstitial pages.
  358. async with self._mapping_lock.queue(auth_provider_id):
  359. # first of all, check if we already have a mapping for this user
  360. user_id = await self.get_sso_user_by_remote_user_id(
  361. auth_provider_id,
  362. remote_user_id,
  363. )
  364. # Check for grandfathering of users.
  365. if not user_id:
  366. user_id = await grandfather_existing_users()
  367. if user_id:
  368. # Future logins should also match this user ID.
  369. await self._store.record_user_external_id(
  370. auth_provider_id, remote_user_id, user_id
  371. )
  372. # Otherwise, generate a new user.
  373. if not user_id:
  374. attributes = await self._call_attribute_mapper(sso_to_matrix_id_mapper)
  375. next_step_url = self._get_url_for_next_new_user_step(
  376. attributes=attributes
  377. )
  378. if next_step_url:
  379. await self._redirect_to_next_new_user_step(
  380. auth_provider_id,
  381. remote_user_id,
  382. attributes,
  383. client_redirect_url,
  384. next_step_url,
  385. extra_login_attributes,
  386. auth_provider_session_id,
  387. )
  388. user_id = await self._register_mapped_user(
  389. attributes,
  390. auth_provider_id,
  391. remote_user_id,
  392. get_request_user_agent(request),
  393. request.getClientAddress().host,
  394. )
  395. new_user = True
  396. elif self._sso_update_profile_information:
  397. attributes = await self._call_attribute_mapper(sso_to_matrix_id_mapper)
  398. if attributes.display_name:
  399. user_id_obj = UserID.from_string(user_id)
  400. profile_display_name = await self._profile_handler.get_displayname(
  401. user_id_obj
  402. )
  403. if profile_display_name != attributes.display_name:
  404. requester = create_requester(
  405. user_id,
  406. authenticated_entity=user_id,
  407. )
  408. await self._profile_handler.set_displayname(
  409. user_id_obj, requester, attributes.display_name, True
  410. )
  411. if attributes.picture:
  412. await self.set_avatar(user_id, attributes.picture)
  413. await self._auth_handler.complete_sso_login(
  414. user_id,
  415. auth_provider_id,
  416. request,
  417. client_redirect_url,
  418. extra_login_attributes,
  419. new_user=new_user,
  420. auth_provider_session_id=auth_provider_session_id,
  421. )
  422. async def _call_attribute_mapper(
  423. self,
  424. sso_to_matrix_id_mapper: Callable[[int], Awaitable[UserAttributes]],
  425. ) -> UserAttributes:
  426. """Call the attribute mapper function in a loop, until we get a unique userid"""
  427. for i in range(self._MAP_USERNAME_RETRIES):
  428. try:
  429. attributes = await sso_to_matrix_id_mapper(i)
  430. except (RedirectException, MappingException):
  431. # Mapping providers are allowed to issue a redirect (e.g. to ask
  432. # the user for more information) and can issue a mapping exception
  433. # if a name cannot be generated.
  434. raise
  435. except Exception as e:
  436. # Any other exception is unexpected.
  437. raise MappingException(
  438. "Could not extract user attributes from SSO response."
  439. ) from e
  440. logger.debug(
  441. "Retrieved user attributes from user mapping provider: %r (attempt %d)",
  442. attributes,
  443. i,
  444. )
  445. if not attributes.localpart:
  446. # the mapper has not picked a localpart
  447. return attributes
  448. # Check if this mxid already exists
  449. user_id = UserID(attributes.localpart, self._server_name).to_string()
  450. if not await self._store.get_users_by_id_case_insensitive(user_id):
  451. # This mxid is free
  452. break
  453. else:
  454. # Unable to generate a username in 1000 iterations
  455. # Break and return error to the user
  456. raise MappingException(
  457. "Unable to generate a Matrix ID from the SSO response"
  458. )
  459. return attributes
  460. def _get_url_for_next_new_user_step(
  461. self,
  462. attributes: Optional[UserAttributes] = None,
  463. session: Optional[UsernameMappingSession] = None,
  464. ) -> bytes:
  465. """Returns the URL to redirect to for the next step of new user registration
  466. Given attributes from the user mapping provider or a UsernameMappingSession,
  467. returns the URL to redirect to for the next step of the registration flow.
  468. Args:
  469. attributes: the user attributes returned by the user mapping provider,
  470. from before a UsernameMappingSession has begun.
  471. session: an active UsernameMappingSession, possibly with some of its
  472. attributes chosen by the user.
  473. Returns:
  474. The URL to redirect to, or an empty value if no redirect is necessary
  475. """
  476. # Must provide either attributes or session, not both
  477. assert (attributes is not None) != (session is not None)
  478. if (
  479. attributes
  480. and (attributes.localpart is None or attributes.confirm_localpart is True)
  481. ) or (session and session.chosen_localpart is None):
  482. return b"/_synapse/client/pick_username/account_details"
  483. elif self._consent_at_registration and not (
  484. session and session.terms_accepted_version
  485. ):
  486. return b"/_synapse/client/new_user_consent"
  487. else:
  488. return b"/_synapse/client/sso_register" if session else b""
  489. async def _redirect_to_next_new_user_step(
  490. self,
  491. auth_provider_id: str,
  492. remote_user_id: str,
  493. attributes: UserAttributes,
  494. client_redirect_url: str,
  495. next_step_url: bytes,
  496. extra_login_attributes: Optional[JsonDict],
  497. auth_provider_session_id: Optional[str],
  498. ) -> NoReturn:
  499. """Creates a UsernameMappingSession and redirects the browser
  500. Called if the user mapping provider doesn't return complete information for a new user.
  501. Raises a RedirectException which redirects the browser to a specified URL.
  502. Args:
  503. auth_provider_id: A unique identifier for this SSO provider, e.g.
  504. "oidc" or "saml".
  505. remote_user_id: The unique identifier from the SSO provider.
  506. attributes: the user attributes returned by the user mapping provider.
  507. client_redirect_url: The redirect URL passed in by the client, which we
  508. will eventually redirect back to.
  509. next_step_url: The URL to redirect to for the next step of the new user flow.
  510. extra_login_attributes: An optional dictionary of extra
  511. attributes to be provided to the client in the login response.
  512. auth_provider_session_id: An optional session ID from the IdP.
  513. Raises:
  514. RedirectException
  515. """
  516. # TODO: If needed, allow using/looking up an existing session here.
  517. session_id = random_string(16)
  518. now = self._clock.time_msec()
  519. session = UsernameMappingSession(
  520. auth_provider_id=auth_provider_id,
  521. auth_provider_session_id=auth_provider_session_id,
  522. remote_user_id=remote_user_id,
  523. display_name=attributes.display_name,
  524. emails=attributes.emails,
  525. client_redirect_url=client_redirect_url,
  526. expiry_time_ms=now + self._MAPPING_SESSION_VALIDITY_PERIOD_MS,
  527. extra_login_attributes=extra_login_attributes,
  528. # Treat the localpart returned by the user mapping provider as though
  529. # it was chosen by the user. If it's None, it must be chosen eventually.
  530. chosen_localpart=attributes.localpart,
  531. # TODO: Consider letting the user mapping provider specify defaults for
  532. # other user-chosen attributes.
  533. )
  534. self._username_mapping_sessions[session_id] = session
  535. logger.info("Recorded registration session id %s", session_id)
  536. # Set the cookie and redirect to the next step
  537. e = RedirectException(next_step_url)
  538. e.cookies.append(
  539. b"%s=%s; path=/"
  540. % (USERNAME_MAPPING_SESSION_COOKIE_NAME, session_id.encode("ascii"))
  541. )
  542. raise e
  543. async def _register_mapped_user(
  544. self,
  545. attributes: UserAttributes,
  546. auth_provider_id: str,
  547. remote_user_id: str,
  548. user_agent: str,
  549. ip_address: str,
  550. ) -> str:
  551. """Register a new SSO user.
  552. This is called once we have successfully mapped the remote user id onto a local
  553. user id, one way or another.
  554. Args:
  555. attributes: user attributes returned by the user mapping provider,
  556. including a non-empty localpart.
  557. auth_provider_id: A unique identifier for this SSO provider, e.g.
  558. "oidc" or "saml".
  559. remote_user_id: The unique identifier from the SSO provider.
  560. user_agent: The user-agent in the HTTP request (used for potential
  561. shadow-banning.)
  562. ip_address: The IP address of the requester (used for potential
  563. shadow-banning.)
  564. Raises:
  565. a MappingException if the localpart is invalid.
  566. a SynapseError with code 400 and errcode Codes.USER_IN_USE if the localpart
  567. is already taken.
  568. """
  569. # Since the localpart is provided via a potentially untrusted module,
  570. # ensure the MXID is valid before registering.
  571. if not attributes.localpart or contains_invalid_mxid_characters(
  572. attributes.localpart
  573. ):
  574. raise MappingException("localpart is invalid: %s" % (attributes.localpart,))
  575. logger.debug("Mapped SSO user to local part %s", attributes.localpart)
  576. registered_user_id = await self._registration_handler.register_user(
  577. localpart=attributes.localpart,
  578. default_display_name=attributes.display_name,
  579. bind_emails=attributes.emails,
  580. user_agent_ips=[(user_agent, ip_address)],
  581. auth_provider_id=auth_provider_id,
  582. )
  583. await self._store.record_user_external_id(
  584. auth_provider_id, remote_user_id, registered_user_id
  585. )
  586. # Set avatar, if available
  587. if attributes.picture:
  588. await self.set_avatar(registered_user_id, attributes.picture)
  589. return registered_user_id
  590. async def set_avatar(self, user_id: str, picture_https_url: str) -> bool:
  591. """Set avatar of the user.
  592. This downloads the image file from the URL provided, stores that in
  593. the media repository and then sets the avatar on the user's profile.
  594. It can detect if the same image is being saved again and bails early by storing
  595. the hash of the file in the `upload_name` of the avatar image.
  596. Currently, it only supports server configurations which run the media repository
  597. within the same process.
  598. It silently fails and logs a warning by raising an exception and catching it
  599. internally if:
  600. * it is unable to fetch the image itself (non 200 status code) or
  601. * the image supplied is bigger than max allowed size or
  602. * the image type is not one of the allowed image types.
  603. Args:
  604. user_id: matrix user ID in the form @localpart:domain as a string.
  605. picture_https_url: HTTPS url for the picture image file.
  606. Returns: `True` if the user's avatar has been successfully set to the image at
  607. `picture_https_url`.
  608. """
  609. if self._media_repo is None:
  610. logger.info(
  611. "failed to set user avatar because out-of-process media repositories "
  612. "are not supported yet "
  613. )
  614. return False
  615. try:
  616. uid = UserID.from_string(user_id)
  617. def is_allowed_mime_type(content_type: str) -> bool:
  618. if (
  619. self._profile_handler.allowed_avatar_mimetypes
  620. and content_type
  621. not in self._profile_handler.allowed_avatar_mimetypes
  622. ):
  623. return False
  624. return True
  625. # download picture, enforcing size limit & mime type check
  626. picture = io.BytesIO()
  627. content_length, headers, uri, code = await self._http_client.get_file(
  628. url=picture_https_url,
  629. output_stream=picture,
  630. max_size=self._profile_handler.max_avatar_size,
  631. is_allowed_content_type=is_allowed_mime_type,
  632. )
  633. if code != 200:
  634. raise Exception(
  635. "GET request to download sso avatar image returned {}".format(code)
  636. )
  637. # upload name includes hash of the image file's content so that we can
  638. # easily check if it requires an update or not, the next time user logs in
  639. upload_name = "sso_avatar_" + hashlib.sha256(picture.read()).hexdigest()
  640. # bail if user already has the same avatar
  641. profile = await self._profile_handler.get_profile(user_id)
  642. if profile["avatar_url"] is not None:
  643. server_name = profile["avatar_url"].split("/")[-2]
  644. media_id = profile["avatar_url"].split("/")[-1]
  645. if server_name == self._server_name:
  646. media = await self._media_repo.store.get_local_media(media_id)
  647. if media is not None and upload_name == media["upload_name"]:
  648. logger.info("skipping saving the user avatar")
  649. return True
  650. # store it in media repository
  651. avatar_mxc_url = await self._media_repo.create_content(
  652. media_type=headers[b"Content-Type"][0].decode("utf-8"),
  653. upload_name=upload_name,
  654. content=picture,
  655. content_length=content_length,
  656. auth_user=uid,
  657. )
  658. # save it as user avatar
  659. await self._profile_handler.set_avatar_url(
  660. uid,
  661. create_requester(uid),
  662. str(avatar_mxc_url),
  663. )
  664. logger.info("successfully saved the user avatar")
  665. return True
  666. except Exception:
  667. logger.warning("failed to save the user avatar")
  668. return False
  669. async def complete_sso_ui_auth_request(
  670. self,
  671. auth_provider_id: str,
  672. remote_user_id: str,
  673. ui_auth_session_id: str,
  674. request: Request,
  675. ) -> None:
  676. """
  677. Given an SSO ID, retrieve the user ID for it and complete UIA.
  678. Note that this requires that the user is mapped in the "user_external_ids"
  679. table. This will be the case if they have ever logged in via SAML or OIDC in
  680. recentish synapse versions, but may not be for older users.
  681. Args:
  682. auth_provider_id: A unique identifier for this SSO provider, e.g.
  683. "oidc" or "saml".
  684. remote_user_id: The unique identifier from the SSO provider.
  685. ui_auth_session_id: The ID of the user-interactive auth session.
  686. request: The request to complete.
  687. """
  688. user_id = await self.get_sso_user_by_remote_user_id(
  689. auth_provider_id,
  690. remote_user_id,
  691. )
  692. user_id_to_verify: str = await self._auth_handler.get_session_data(
  693. ui_auth_session_id, UIAuthSessionDataConstants.REQUEST_USER_ID
  694. )
  695. if not user_id:
  696. logger.warning(
  697. "Remote user %s/%s has not previously logged in here: UIA will fail",
  698. auth_provider_id,
  699. remote_user_id,
  700. )
  701. elif user_id != user_id_to_verify:
  702. logger.warning(
  703. "Remote user %s/%s mapped onto incorrect user %s: UIA will fail",
  704. auth_provider_id,
  705. remote_user_id,
  706. user_id,
  707. )
  708. else:
  709. # success!
  710. # Mark the stage of the authentication as successful.
  711. await self._store.mark_ui_auth_stage_complete(
  712. ui_auth_session_id, LoginType.SSO, user_id
  713. )
  714. # Render the HTML confirmation page and return.
  715. html = self._sso_auth_success_template
  716. respond_with_html(request, 200, html)
  717. return
  718. # the user_id didn't match: mark the stage of the authentication as unsuccessful
  719. await self._store.mark_ui_auth_stage_complete(
  720. ui_auth_session_id, LoginType.SSO, ""
  721. )
  722. # render an error page.
  723. html = self._bad_user_template.render(
  724. server_name=self._server_name,
  725. user_id_to_verify=user_id_to_verify,
  726. )
  727. respond_with_html(request, 200, html)
  728. def get_mapping_session(self, session_id: str) -> UsernameMappingSession:
  729. """Look up the given username mapping session
  730. If it is not found, raises a SynapseError with an http code of 400
  731. Args:
  732. session_id: session to look up
  733. Returns:
  734. active mapping session
  735. Raises:
  736. SynapseError if the session is not found/has expired
  737. """
  738. self._expire_old_sessions()
  739. session = self._username_mapping_sessions.get(session_id)
  740. if session:
  741. return session
  742. logger.info("Couldn't find session id %s", session_id)
  743. raise SynapseError(400, "unknown session")
  744. async def check_username_availability(
  745. self,
  746. localpart: str,
  747. session_id: str,
  748. ) -> bool:
  749. """Handle an "is username available" callback check
  750. Args:
  751. localpart: desired localpart
  752. session_id: the session id for the username picker
  753. Returns:
  754. True if the username is available
  755. Raises:
  756. SynapseError if the localpart is invalid or the session is unknown
  757. """
  758. # make sure that there is a valid mapping session, to stop people dictionary-
  759. # scanning for accounts
  760. self.get_mapping_session(session_id)
  761. logger.info(
  762. "[session %s] Checking for availability of username %s",
  763. session_id,
  764. localpart,
  765. )
  766. if contains_invalid_mxid_characters(localpart):
  767. raise SynapseError(400, "localpart is invalid: %s" % (localpart,))
  768. user_id = UserID(localpart, self._server_name).to_string()
  769. user_infos = await self._store.get_users_by_id_case_insensitive(user_id)
  770. logger.info("[session %s] users: %s", session_id, user_infos)
  771. return not user_infos
  772. async def handle_submit_username_request(
  773. self,
  774. request: SynapseRequest,
  775. session_id: str,
  776. localpart: str,
  777. use_display_name: bool,
  778. emails_to_use: Iterable[str],
  779. ) -> None:
  780. """Handle a request to the username-picker 'submit' endpoint
  781. Will serve an HTTP response to the request.
  782. Args:
  783. request: HTTP request
  784. localpart: localpart requested by the user
  785. session_id: ID of the username mapping session, extracted from a cookie
  786. use_display_name: whether the user wants to use the suggested display name
  787. emails_to_use: emails that the user would like to use
  788. """
  789. try:
  790. session = self.get_mapping_session(session_id)
  791. except SynapseError as e:
  792. self.render_error(request, "bad_session", e.msg, code=e.code)
  793. return
  794. # update the session with the user's choices
  795. session.chosen_localpart = localpart
  796. session.use_display_name = use_display_name
  797. emails_from_idp = set(session.emails)
  798. filtered_emails: Set[str] = set()
  799. # we iterate through the list rather than just building a set conjunction, so
  800. # that we can log attempts to use unknown addresses
  801. for email in emails_to_use:
  802. if email in emails_from_idp:
  803. filtered_emails.add(email)
  804. else:
  805. logger.warning(
  806. "[session %s] ignoring user request to use unknown email address %r",
  807. session_id,
  808. email,
  809. )
  810. session.emails_to_use = filtered_emails
  811. respond_with_redirect(
  812. request, self._get_url_for_next_new_user_step(session=session)
  813. )
  814. async def handle_terms_accepted(
  815. self, request: SynapseRequest, session_id: str, terms_version: str
  816. ) -> None:
  817. """Handle a request to the new-user 'consent' endpoint
  818. Will serve an HTTP response to the request.
  819. Args:
  820. request: HTTP request
  821. session_id: ID of the username mapping session, extracted from a cookie
  822. terms_version: the version of the terms which the user viewed and consented
  823. to
  824. """
  825. logger.info(
  826. "[session %s] User consented to terms version %s",
  827. session_id,
  828. terms_version,
  829. )
  830. try:
  831. session = self.get_mapping_session(session_id)
  832. except SynapseError as e:
  833. self.render_error(request, "bad_session", e.msg, code=e.code)
  834. return
  835. session.terms_accepted_version = terms_version
  836. respond_with_redirect(
  837. request, self._get_url_for_next_new_user_step(session=session)
  838. )
  839. async def register_sso_user(self, request: Request, session_id: str) -> None:
  840. """Called once we have all the info we need to register a new user.
  841. Does so and serves an HTTP response
  842. Args:
  843. request: HTTP request
  844. session_id: ID of the username mapping session, extracted from a cookie
  845. """
  846. try:
  847. session = self.get_mapping_session(session_id)
  848. except SynapseError as e:
  849. self.render_error(request, "bad_session", e.msg, code=e.code)
  850. return
  851. logger.info(
  852. "[session %s] Registering localpart %s",
  853. session_id,
  854. session.chosen_localpart,
  855. )
  856. attributes = UserAttributes(
  857. localpart=session.chosen_localpart,
  858. emails=session.emails_to_use,
  859. )
  860. if session.use_display_name:
  861. attributes.display_name = session.display_name
  862. # the following will raise a 400 error if the username has been taken in the
  863. # meantime.
  864. user_id = await self._register_mapped_user(
  865. attributes,
  866. session.auth_provider_id,
  867. session.remote_user_id,
  868. get_request_user_agent(request),
  869. request.getClientAddress().host,
  870. )
  871. logger.info(
  872. "[session %s] Registered userid %s with attributes %s",
  873. session_id,
  874. user_id,
  875. attributes,
  876. )
  877. # delete the mapping session and the cookie
  878. del self._username_mapping_sessions[session_id]
  879. # delete the cookie
  880. request.addCookie(
  881. USERNAME_MAPPING_SESSION_COOKIE_NAME,
  882. b"",
  883. expires=b"Thu, 01 Jan 1970 00:00:00 GMT",
  884. path=b"/",
  885. )
  886. auth_result = {}
  887. if session.terms_accepted_version:
  888. # TODO: make this less awful.
  889. auth_result[LoginType.TERMS] = True
  890. await self._registration_handler.post_registration_actions(
  891. user_id, auth_result, access_token=None
  892. )
  893. await self._auth_handler.complete_sso_login(
  894. user_id,
  895. session.auth_provider_id,
  896. request,
  897. session.client_redirect_url,
  898. session.extra_login_attributes,
  899. new_user=True,
  900. auth_provider_session_id=session.auth_provider_session_id,
  901. )
  902. def _expire_old_sessions(self) -> None:
  903. to_expire = []
  904. now = int(self._clock.time_msec())
  905. for session_id, session in self._username_mapping_sessions.items():
  906. if session.expiry_time_ms <= now:
  907. to_expire.append(session_id)
  908. for session_id in to_expire:
  909. logger.info("Expiring mapping session %s", session_id)
  910. del self._username_mapping_sessions[session_id]
  911. def check_required_attributes(
  912. self,
  913. request: SynapseRequest,
  914. attributes: Mapping[str, List[Any]],
  915. attribute_requirements: Iterable[SsoAttributeRequirement],
  916. ) -> bool:
  917. """
  918. Confirm that the required attributes were present in the SSO response.
  919. If all requirements are met, this will return True.
  920. If any requirement is not met, then the request will be finalized by
  921. showing an error page to the user and False will be returned.
  922. Args:
  923. request: The request to (potentially) respond to.
  924. attributes: The attributes from the SSO IdP.
  925. attribute_requirements: The requirements that attributes must meet.
  926. Returns:
  927. True if all requirements are met, False if any attribute fails to
  928. meet the requirement.
  929. """
  930. # Ensure that the attributes of the logged in user meet the required
  931. # attributes.
  932. for requirement in attribute_requirements:
  933. if not _check_attribute_requirement(attributes, requirement):
  934. self.render_error(
  935. request, "unauthorised", "You are not authorised to log in here."
  936. )
  937. return False
  938. return True
  939. async def revoke_sessions_for_provider_session_id(
  940. self,
  941. auth_provider_id: str,
  942. auth_provider_session_id: str,
  943. expected_user_id: Optional[str] = None,
  944. ) -> None:
  945. """Revoke any devices and in-flight logins tied to a provider session.
  946. Can only be called from the main process.
  947. Args:
  948. auth_provider_id: A unique identifier for this SSO provider, e.g.
  949. "oidc" or "saml".
  950. auth_provider_session_id: The session ID from the provider to logout
  951. expected_user_id: The user we're expecting to logout. If set, it will ignore
  952. sessions belonging to other users and log an error.
  953. """
  954. # It is expected that this is the main process.
  955. assert isinstance(
  956. self._device_handler, DeviceHandler
  957. ), "revoking SSO sessions can only be called on the main process"
  958. # Invalidate any running user-mapping sessions
  959. to_delete = []
  960. for session_id, session in self._username_mapping_sessions.items():
  961. if (
  962. session.auth_provider_id == auth_provider_id
  963. and session.auth_provider_session_id == auth_provider_session_id
  964. ):
  965. to_delete.append(session_id)
  966. for session_id in to_delete:
  967. logger.info("Revoking mapping session %s", session_id)
  968. del self._username_mapping_sessions[session_id]
  969. # Invalidate any in-flight login tokens
  970. await self._store.invalidate_login_tokens_by_session_id(
  971. auth_provider_id=auth_provider_id,
  972. auth_provider_session_id=auth_provider_session_id,
  973. )
  974. # Fetch any device(s) in the store associated with the session ID.
  975. devices = await self._store.get_devices_by_auth_provider_session_id(
  976. auth_provider_id=auth_provider_id,
  977. auth_provider_session_id=auth_provider_session_id,
  978. )
  979. # We have no guarantee that all the devices of that session are for the same
  980. # `user_id`. Hence, we have to iterate over the list of devices and log them out
  981. # one by one.
  982. for device in devices:
  983. user_id = device["user_id"]
  984. device_id = device["device_id"]
  985. # If the user_id associated with that device/session is not the one we got
  986. # out of the `sub` claim, skip that device and show log an error.
  987. if expected_user_id is not None and user_id != expected_user_id:
  988. logger.error(
  989. "Received a logout notification from SSO provider "
  990. f"{auth_provider_id!r} for the user {expected_user_id!r}, but with "
  991. f"a session ID ({auth_provider_session_id!r}) which belongs to "
  992. f"{user_id!r}. This may happen when the SSO provider user mapper "
  993. "uses something else than the standard attribute as mapping ID. "
  994. "For OIDC providers, set `backchannel_logout_ignore_sub` to `true` "
  995. "in the provider config if that is the case."
  996. )
  997. continue
  998. logger.info(
  999. "Logging out %r (device %r) via SSO (%r) logout notification (session %r).",
  1000. user_id,
  1001. device_id,
  1002. auth_provider_id,
  1003. auth_provider_session_id,
  1004. )
  1005. await self._device_handler.delete_devices(user_id, [device_id])
  1006. def get_username_mapping_session_cookie_from_request(request: IRequest) -> str:
  1007. """Extract the session ID from the cookie
  1008. Raises a SynapseError if the cookie isn't found
  1009. """
  1010. session_id = request.getCookie(USERNAME_MAPPING_SESSION_COOKIE_NAME)
  1011. if not session_id:
  1012. raise SynapseError(code=400, msg="missing session_id")
  1013. return session_id.decode("ascii", errors="replace")
  1014. def _check_attribute_requirement(
  1015. attributes: Mapping[str, List[Any]], req: SsoAttributeRequirement
  1016. ) -> bool:
  1017. """Check if SSO attributes meet the proper requirements.
  1018. Args:
  1019. attributes: A mapping of attributes to an iterable of one or more values.
  1020. requirement: The configured requirement to check.
  1021. Returns:
  1022. True if the required attribute was found and had a proper value.
  1023. """
  1024. if req.attribute not in attributes:
  1025. logger.info("SSO attribute missing: %s", req.attribute)
  1026. return False
  1027. # If the requirement is None, the attribute existing is enough.
  1028. if req.value is None:
  1029. return True
  1030. values = attributes[req.attribute]
  1031. if req.value in values:
  1032. return True
  1033. logger.info(
  1034. "SSO attribute %s did not match required value '%s' (was '%s')",
  1035. req.attribute,
  1036. req.value,
  1037. values,
  1038. )
  1039. return False