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.
 
 
 
 
 
 

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