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.
 
 
 
 
 
 

985 line
34 KiB

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