You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1279 lines
47 KiB

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