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.
 
 
 
 
 
 

734 lines
27 KiB

  1. # Copyright 2014-2021 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 logging
  15. import re
  16. from typing import (
  17. TYPE_CHECKING,
  18. Any,
  19. Awaitable,
  20. Callable,
  21. Dict,
  22. List,
  23. Optional,
  24. Tuple,
  25. Union,
  26. )
  27. from typing_extensions import TypedDict
  28. from synapse.api.constants import ApprovalNoticeMedium
  29. from synapse.api.errors import (
  30. Codes,
  31. InvalidClientTokenError,
  32. LoginError,
  33. NotApprovedError,
  34. SynapseError,
  35. UserDeactivatedError,
  36. )
  37. from synapse.api.ratelimiting import Ratelimiter
  38. from synapse.api.urls import CLIENT_API_PREFIX
  39. from synapse.appservice import ApplicationService
  40. from synapse.handlers.sso import SsoIdentityProvider
  41. from synapse.http import get_request_uri
  42. from synapse.http.server import HttpServer, finish_request
  43. from synapse.http.servlet import (
  44. RestServlet,
  45. assert_params_in_dict,
  46. parse_bytes_from_args,
  47. parse_json_object_from_request,
  48. parse_string,
  49. )
  50. from synapse.http.site import RequestInfo, SynapseRequest
  51. from synapse.rest.client._base import client_patterns
  52. from synapse.rest.well_known import WellKnownBuilder
  53. from synapse.types import JsonDict, UserID
  54. if TYPE_CHECKING:
  55. from synapse.server import HomeServer
  56. logger = logging.getLogger(__name__)
  57. class LoginResponse(TypedDict, total=False):
  58. user_id: str
  59. access_token: Optional[str]
  60. home_server: str
  61. expires_in_ms: Optional[int]
  62. refresh_token: Optional[str]
  63. device_id: Optional[str]
  64. well_known: Optional[Dict[str, Any]]
  65. class LoginRestServlet(RestServlet):
  66. PATTERNS = client_patterns("/login$", v1=True)
  67. CATEGORY = "Registration/login requests"
  68. CAS_TYPE = "m.login.cas"
  69. SSO_TYPE = "m.login.sso"
  70. TOKEN_TYPE = "m.login.token"
  71. JWT_TYPE = "org.matrix.login.jwt"
  72. APPSERVICE_TYPE = "m.login.application_service"
  73. REFRESH_TOKEN_PARAM = "refresh_token"
  74. def __init__(self, hs: "HomeServer"):
  75. super().__init__()
  76. self.hs = hs
  77. self._main_store = hs.get_datastores().main
  78. # JWT configuration variables.
  79. self.jwt_enabled = hs.config.jwt.jwt_enabled
  80. # SSO configuration.
  81. self.saml2_enabled = hs.config.saml2.saml2_enabled
  82. self.cas_enabled = hs.config.cas.cas_enabled
  83. self.oidc_enabled = hs.config.oidc.oidc_enabled
  84. self._refresh_tokens_enabled = (
  85. hs.config.registration.refreshable_access_token_lifetime is not None
  86. )
  87. # Whether we need to check if the user has been approved or not.
  88. self._require_approval = (
  89. hs.config.experimental.msc3866.enabled
  90. and hs.config.experimental.msc3866.require_approval_for_new_accounts
  91. )
  92. # Whether get login token is enabled.
  93. self._get_login_token_enabled = hs.config.auth.login_via_existing_enabled
  94. self.auth = hs.get_auth()
  95. self.clock = hs.get_clock()
  96. self.auth_handler = self.hs.get_auth_handler()
  97. self.registration_handler = hs.get_registration_handler()
  98. self._sso_handler = hs.get_sso_handler()
  99. self._spam_checker = hs.get_module_api_callbacks().spam_checker
  100. self._account_validity_handler = hs.get_account_validity_handler()
  101. self._well_known_builder = WellKnownBuilder(hs)
  102. self._address_ratelimiter = Ratelimiter(
  103. store=self._main_store,
  104. clock=hs.get_clock(),
  105. cfg=self.hs.config.ratelimiting.rc_login_address,
  106. )
  107. self._account_ratelimiter = Ratelimiter(
  108. store=self._main_store,
  109. clock=hs.get_clock(),
  110. cfg=self.hs.config.ratelimiting.rc_login_account,
  111. )
  112. # ensure the CAS/SAML/OIDC handlers are loaded on this worker instance.
  113. # The reason for this is to ensure that the auth_provider_ids are registered
  114. # with SsoHandler, which in turn ensures that the login/registration prometheus
  115. # counters are initialised for the auth_provider_ids.
  116. _load_sso_handlers(hs)
  117. def on_GET(self, request: SynapseRequest) -> Tuple[int, JsonDict]:
  118. flows: List[JsonDict] = []
  119. if self.jwt_enabled:
  120. flows.append({"type": LoginRestServlet.JWT_TYPE})
  121. if self.cas_enabled:
  122. # we advertise CAS for backwards compat, though MSC1721 renamed it
  123. # to SSO.
  124. flows.append({"type": LoginRestServlet.CAS_TYPE})
  125. # The login token flow requires m.login.token to be advertised.
  126. support_login_token_flow = self._get_login_token_enabled
  127. if self.cas_enabled or self.saml2_enabled or self.oidc_enabled:
  128. flows.append(
  129. {
  130. "type": LoginRestServlet.SSO_TYPE,
  131. "identity_providers": [
  132. _get_auth_flow_dict_for_idp(idp)
  133. for idp in self._sso_handler.get_identity_providers().values()
  134. ],
  135. }
  136. )
  137. # SSO requires a login token to be generated, so we need to advertise that flow
  138. support_login_token_flow = True
  139. # While it's valid for us to advertise this login type generally,
  140. # synapse currently only gives out these tokens as part of the
  141. # SSO login flow or as part of login via an existing session.
  142. #
  143. # Generally we don't want to advertise login flows that clients
  144. # don't know how to implement, since they (currently) will always
  145. # fall back to the fallback API if they don't understand one of the
  146. # login flow types returned.
  147. if support_login_token_flow:
  148. tokenTypeFlow: Dict[str, Any] = {"type": LoginRestServlet.TOKEN_TYPE}
  149. # If the login token flow is enabled advertise the get_login_token flag.
  150. if self._get_login_token_enabled:
  151. tokenTypeFlow["get_login_token"] = True
  152. flows.append(tokenTypeFlow)
  153. flows.extend({"type": t} for t in self.auth_handler.get_supported_login_types())
  154. flows.append({"type": LoginRestServlet.APPSERVICE_TYPE})
  155. return 200, {"flows": flows}
  156. async def on_POST(self, request: SynapseRequest) -> Tuple[int, LoginResponse]:
  157. login_submission = parse_json_object_from_request(request)
  158. # Check to see if the client requested a refresh token.
  159. client_requested_refresh_token = login_submission.get(
  160. LoginRestServlet.REFRESH_TOKEN_PARAM, False
  161. )
  162. if not isinstance(client_requested_refresh_token, bool):
  163. raise SynapseError(400, "`refresh_token` should be true or false.")
  164. should_issue_refresh_token = (
  165. self._refresh_tokens_enabled and client_requested_refresh_token
  166. )
  167. request_info = request.request_info()
  168. try:
  169. if login_submission["type"] == LoginRestServlet.APPSERVICE_TYPE:
  170. requester = await self.auth.get_user_by_req(request)
  171. appservice = requester.app_service
  172. if appservice is None:
  173. raise InvalidClientTokenError(
  174. "This login method is only valid for application services"
  175. )
  176. if appservice.is_rate_limited():
  177. await self._address_ratelimiter.ratelimit(
  178. None, request.getClientAddress().host
  179. )
  180. result = await self._do_appservice_login(
  181. login_submission,
  182. appservice,
  183. should_issue_refresh_token=should_issue_refresh_token,
  184. request_info=request_info,
  185. )
  186. elif (
  187. self.jwt_enabled
  188. and login_submission["type"] == LoginRestServlet.JWT_TYPE
  189. ):
  190. await self._address_ratelimiter.ratelimit(
  191. None, request.getClientAddress().host
  192. )
  193. result = await self._do_jwt_login(
  194. login_submission,
  195. should_issue_refresh_token=should_issue_refresh_token,
  196. request_info=request_info,
  197. )
  198. elif login_submission["type"] == LoginRestServlet.TOKEN_TYPE:
  199. await self._address_ratelimiter.ratelimit(
  200. None, request.getClientAddress().host
  201. )
  202. result = await self._do_token_login(
  203. login_submission,
  204. should_issue_refresh_token=should_issue_refresh_token,
  205. request_info=request_info,
  206. )
  207. else:
  208. await self._address_ratelimiter.ratelimit(
  209. None, request.getClientAddress().host
  210. )
  211. result = await self._do_other_login(
  212. login_submission,
  213. should_issue_refresh_token=should_issue_refresh_token,
  214. request_info=request_info,
  215. )
  216. except KeyError:
  217. raise SynapseError(400, "Missing JSON keys.")
  218. if self._require_approval:
  219. approved = await self.auth_handler.is_user_approved(result["user_id"])
  220. if not approved:
  221. raise NotApprovedError(
  222. msg="This account is pending approval by a server administrator.",
  223. approval_notice_medium=ApprovalNoticeMedium.NONE,
  224. )
  225. well_known_data = self._well_known_builder.get_well_known()
  226. if well_known_data:
  227. result["well_known"] = well_known_data
  228. return 200, result
  229. async def _do_appservice_login(
  230. self,
  231. login_submission: JsonDict,
  232. appservice: ApplicationService,
  233. should_issue_refresh_token: bool = False,
  234. *,
  235. request_info: RequestInfo,
  236. ) -> LoginResponse:
  237. identifier = login_submission.get("identifier")
  238. logger.info("Got appservice login request with identifier: %r", identifier)
  239. if not isinstance(identifier, dict):
  240. raise SynapseError(
  241. 400, "Invalid identifier in login submission", Codes.INVALID_PARAM
  242. )
  243. # this login flow only supports identifiers of type "m.id.user".
  244. if identifier.get("type") != "m.id.user":
  245. raise SynapseError(
  246. 400, "Unknown login identifier type", Codes.INVALID_PARAM
  247. )
  248. user = identifier.get("user")
  249. if not isinstance(user, str):
  250. raise SynapseError(400, "Invalid user in identifier", Codes.INVALID_PARAM)
  251. if user.startswith("@"):
  252. qualified_user_id = user
  253. else:
  254. qualified_user_id = UserID(user, self.hs.hostname).to_string()
  255. if not appservice.is_interested_in_user(qualified_user_id):
  256. raise LoginError(403, "Invalid access_token", errcode=Codes.FORBIDDEN)
  257. return await self._complete_login(
  258. qualified_user_id,
  259. login_submission,
  260. ratelimit=appservice.is_rate_limited(),
  261. should_issue_refresh_token=should_issue_refresh_token,
  262. # The user represented by an appservice's configured sender_localpart
  263. # is not actually created in Synapse.
  264. should_check_deactivated=qualified_user_id != appservice.sender,
  265. request_info=request_info,
  266. )
  267. async def _do_other_login(
  268. self,
  269. login_submission: JsonDict,
  270. should_issue_refresh_token: bool = False,
  271. *,
  272. request_info: RequestInfo,
  273. ) -> LoginResponse:
  274. """Handle non-token/saml/jwt logins
  275. Args:
  276. login_submission:
  277. should_issue_refresh_token: True if this login should issue
  278. a refresh token alongside the access token.
  279. Returns:
  280. HTTP response
  281. """
  282. # Log the request we got, but only certain fields to minimise the chance of
  283. # logging someone's password (even if they accidentally put it in the wrong
  284. # field)
  285. logger.info(
  286. "Got login request with identifier: %r, medium: %r, address: %r, user: %r",
  287. login_submission.get("identifier"),
  288. login_submission.get("medium"),
  289. login_submission.get("address"),
  290. login_submission.get("user"),
  291. )
  292. canonical_user_id, callback = await self.auth_handler.validate_login(
  293. login_submission, ratelimit=True
  294. )
  295. result = await self._complete_login(
  296. canonical_user_id,
  297. login_submission,
  298. callback,
  299. should_issue_refresh_token=should_issue_refresh_token,
  300. request_info=request_info,
  301. )
  302. return result
  303. async def _complete_login(
  304. self,
  305. user_id: str,
  306. login_submission: JsonDict,
  307. callback: Optional[Callable[[LoginResponse], Awaitable[None]]] = None,
  308. create_non_existent_users: bool = False,
  309. ratelimit: bool = True,
  310. auth_provider_id: Optional[str] = None,
  311. should_issue_refresh_token: bool = False,
  312. auth_provider_session_id: Optional[str] = None,
  313. should_check_deactivated: bool = True,
  314. *,
  315. request_info: RequestInfo,
  316. ) -> LoginResponse:
  317. """Called when we've successfully authed the user and now need to
  318. actually login them in (e.g. create devices). This gets called on
  319. all successful logins.
  320. Applies the ratelimiting for successful login attempts against an
  321. account.
  322. Args:
  323. user_id: ID of the user to register.
  324. login_submission: Dictionary of login information.
  325. callback: Callback function to run after login.
  326. create_non_existent_users: Whether to create the user if they don't
  327. exist. Defaults to False.
  328. ratelimit: Whether to ratelimit the login request.
  329. auth_provider_id: The SSO IdP the user used, if any.
  330. should_issue_refresh_token: True if this login should issue
  331. a refresh token alongside the access token.
  332. auth_provider_session_id: The session ID got during login from the SSO IdP.
  333. should_check_deactivated: True if the user should be checked for
  334. deactivation status before logging in.
  335. This exists purely for appservice's configured sender_localpart
  336. which doesn't have an associated user in the database.
  337. request_info: The user agent/IP address of the user.
  338. Returns:
  339. Dictionary of account information after successful login.
  340. """
  341. # Before we actually log them in we check if they've already logged in
  342. # too often. This happens here rather than before as we don't
  343. # necessarily know the user before now.
  344. if ratelimit:
  345. await self._account_ratelimiter.ratelimit(None, user_id.lower())
  346. if create_non_existent_users:
  347. canonical_uid = await self.auth_handler.check_user_exists(user_id)
  348. if not canonical_uid:
  349. canonical_uid = await self.registration_handler.register_user(
  350. localpart=UserID.from_string(user_id).localpart
  351. )
  352. user_id = canonical_uid
  353. # If the account has been deactivated, do not proceed with the login.
  354. if should_check_deactivated:
  355. deactivated = await self._main_store.get_user_deactivated_status(user_id)
  356. if deactivated:
  357. raise UserDeactivatedError("This account has been deactivated")
  358. device_id = login_submission.get("device_id")
  359. # If device_id is present, check that device_id is not longer than a reasonable 512 characters
  360. if device_id and len(device_id) > 512:
  361. raise LoginError(
  362. 400,
  363. "device_id cannot be longer than 512 characters.",
  364. errcode=Codes.INVALID_PARAM,
  365. )
  366. if self._require_approval:
  367. approved = await self.auth_handler.is_user_approved(user_id)
  368. if not approved:
  369. # If the user isn't approved (and needs to be) we won't allow them to
  370. # actually log in, so we don't want to create a device/access token.
  371. return LoginResponse(
  372. user_id=user_id,
  373. home_server=self.hs.hostname,
  374. )
  375. initial_display_name = login_submission.get("initial_device_display_name")
  376. spam_check = await self._spam_checker.check_login_for_spam(
  377. user_id,
  378. device_id=device_id,
  379. initial_display_name=initial_display_name,
  380. request_info=[(request_info.user_agent, request_info.ip)],
  381. auth_provider_id=auth_provider_id,
  382. )
  383. if spam_check != self._spam_checker.NOT_SPAM:
  384. logger.info("Blocking login due to spam checker")
  385. raise SynapseError(
  386. 403,
  387. msg="Login was blocked by the server",
  388. errcode=spam_check[0],
  389. additional_fields=spam_check[1],
  390. )
  391. (
  392. device_id,
  393. access_token,
  394. valid_until_ms,
  395. refresh_token,
  396. ) = await self.registration_handler.register_device(
  397. user_id,
  398. device_id,
  399. initial_display_name,
  400. auth_provider_id=auth_provider_id,
  401. should_issue_refresh_token=should_issue_refresh_token,
  402. auth_provider_session_id=auth_provider_session_id,
  403. )
  404. result = LoginResponse(
  405. user_id=user_id,
  406. access_token=access_token,
  407. home_server=self.hs.hostname,
  408. device_id=device_id,
  409. )
  410. # execute the callback
  411. await self._account_validity_handler.on_user_login(
  412. user_id,
  413. auth_provider_type=login_submission.get("type"),
  414. auth_provider_id=auth_provider_id,
  415. )
  416. if valid_until_ms is not None:
  417. expires_in_ms = valid_until_ms - self.clock.time_msec()
  418. result["expires_in_ms"] = expires_in_ms
  419. if refresh_token is not None:
  420. result["refresh_token"] = refresh_token
  421. if callback is not None:
  422. await callback(result)
  423. return result
  424. async def _do_token_login(
  425. self,
  426. login_submission: JsonDict,
  427. should_issue_refresh_token: bool = False,
  428. *,
  429. request_info: RequestInfo,
  430. ) -> LoginResponse:
  431. """
  432. Handle token login.
  433. Args:
  434. login_submission: The JSON request body.
  435. should_issue_refresh_token: True if this login should issue
  436. a refresh token alongside the access token.
  437. Returns:
  438. The body of the JSON response.
  439. """
  440. token = login_submission["token"]
  441. res = await self.auth_handler.consume_login_token(token)
  442. return await self._complete_login(
  443. res.user_id,
  444. login_submission,
  445. self.auth_handler._sso_login_callback,
  446. auth_provider_id=res.auth_provider_id,
  447. should_issue_refresh_token=should_issue_refresh_token,
  448. auth_provider_session_id=res.auth_provider_session_id,
  449. request_info=request_info,
  450. )
  451. async def _do_jwt_login(
  452. self,
  453. login_submission: JsonDict,
  454. should_issue_refresh_token: bool = False,
  455. *,
  456. request_info: RequestInfo,
  457. ) -> LoginResponse:
  458. """
  459. Handle the custom JWT login.
  460. Args:
  461. login_submission: The JSON request body.
  462. should_issue_refresh_token: True if this login should issue
  463. a refresh token alongside the access token.
  464. Returns:
  465. The body of the JSON response.
  466. """
  467. user_id = self.hs.get_jwt_handler().validate_login(login_submission)
  468. return await self._complete_login(
  469. user_id,
  470. login_submission,
  471. create_non_existent_users=True,
  472. should_issue_refresh_token=should_issue_refresh_token,
  473. request_info=request_info,
  474. )
  475. def _get_auth_flow_dict_for_idp(idp: SsoIdentityProvider) -> JsonDict:
  476. """Return an entry for the login flow dict
  477. Returns an entry suitable for inclusion in "identity_providers" in the
  478. response to GET /_matrix/client/r0/login
  479. Args:
  480. idp: the identity provider to describe
  481. """
  482. e: JsonDict = {"id": idp.idp_id, "name": idp.idp_name}
  483. if idp.idp_icon:
  484. e["icon"] = idp.idp_icon
  485. if idp.idp_brand:
  486. e["brand"] = idp.idp_brand
  487. return e
  488. class RefreshTokenServlet(RestServlet):
  489. PATTERNS = client_patterns("/refresh$")
  490. CATEGORY = "Registration/login requests"
  491. def __init__(self, hs: "HomeServer"):
  492. self._auth_handler = hs.get_auth_handler()
  493. self._clock = hs.get_clock()
  494. self.refreshable_access_token_lifetime = (
  495. hs.config.registration.refreshable_access_token_lifetime
  496. )
  497. self.refresh_token_lifetime = hs.config.registration.refresh_token_lifetime
  498. async def on_POST(self, request: SynapseRequest) -> Tuple[int, JsonDict]:
  499. refresh_submission = parse_json_object_from_request(request)
  500. assert_params_in_dict(refresh_submission, ["refresh_token"])
  501. token = refresh_submission["refresh_token"]
  502. if not isinstance(token, str):
  503. raise SynapseError(400, "Invalid param: refresh_token", Codes.INVALID_PARAM)
  504. now = self._clock.time_msec()
  505. access_valid_until_ms = None
  506. if self.refreshable_access_token_lifetime is not None:
  507. access_valid_until_ms = now + self.refreshable_access_token_lifetime
  508. refresh_valid_until_ms = None
  509. if self.refresh_token_lifetime is not None:
  510. refresh_valid_until_ms = now + self.refresh_token_lifetime
  511. (
  512. access_token,
  513. refresh_token,
  514. actual_access_token_expiry,
  515. ) = await self._auth_handler.refresh_token(
  516. token, access_valid_until_ms, refresh_valid_until_ms
  517. )
  518. response: Dict[str, Union[str, int]] = {
  519. "access_token": access_token,
  520. "refresh_token": refresh_token,
  521. }
  522. # expires_in_ms is only present if the token expires
  523. if actual_access_token_expiry is not None:
  524. response["expires_in_ms"] = actual_access_token_expiry - now
  525. return 200, response
  526. class SsoRedirectServlet(RestServlet):
  527. PATTERNS = list(client_patterns("/login/(cas|sso)/redirect$", v1=True)) + [
  528. re.compile(
  529. "^"
  530. + CLIENT_API_PREFIX
  531. + "/(r0|v3)/login/sso/redirect/(?P<idp_id>[A-Za-z0-9_.~-]+)$"
  532. )
  533. ]
  534. CATEGORY = "SSO requests needed for all SSO providers"
  535. def __init__(self, hs: "HomeServer"):
  536. # make sure that the relevant handlers are instantiated, so that they
  537. # register themselves with the main SSOHandler.
  538. _load_sso_handlers(hs)
  539. self._sso_handler = hs.get_sso_handler()
  540. self._public_baseurl = hs.config.server.public_baseurl
  541. async def on_GET(
  542. self, request: SynapseRequest, idp_id: Optional[str] = None
  543. ) -> None:
  544. if not self._public_baseurl:
  545. raise SynapseError(400, "SSO requires a valid public_baseurl")
  546. # if this isn't the expected hostname, redirect to the right one, so that we
  547. # get our cookies back.
  548. requested_uri = get_request_uri(request)
  549. baseurl_bytes = self._public_baseurl.encode("utf-8")
  550. if not requested_uri.startswith(baseurl_bytes):
  551. # swap out the incorrect base URL for the right one.
  552. #
  553. # The idea here is to redirect from
  554. # https://foo.bar/whatever/_matrix/...
  555. # to
  556. # https://public.baseurl/_matrix/...
  557. #
  558. i = requested_uri.index(b"/_matrix")
  559. new_uri = baseurl_bytes[:-1] + requested_uri[i:]
  560. logger.info(
  561. "Requested URI %s is not canonical: redirecting to %s",
  562. requested_uri.decode("utf-8", errors="replace"),
  563. new_uri.decode("utf-8", errors="replace"),
  564. )
  565. request.redirect(new_uri)
  566. finish_request(request)
  567. return
  568. args: Dict[bytes, List[bytes]] = request.args # type: ignore
  569. client_redirect_url = parse_bytes_from_args(args, "redirectUrl", required=True)
  570. sso_url = await self._sso_handler.handle_redirect_request(
  571. request,
  572. client_redirect_url,
  573. idp_id,
  574. )
  575. logger.info("Redirecting to %s", sso_url)
  576. request.redirect(sso_url)
  577. finish_request(request)
  578. class CasTicketServlet(RestServlet):
  579. PATTERNS = client_patterns("/login/cas/ticket", v1=True)
  580. def __init__(self, hs: "HomeServer"):
  581. super().__init__()
  582. self._cas_handler = hs.get_cas_handler()
  583. async def on_GET(self, request: SynapseRequest) -> None:
  584. client_redirect_url = parse_string(request, "redirectUrl")
  585. ticket = parse_string(request, "ticket", required=True)
  586. # Maybe get a session ID (if this ticket is from user interactive
  587. # authentication).
  588. session = parse_string(request, "session")
  589. # Either client_redirect_url or session must be provided.
  590. if not client_redirect_url and not session:
  591. message = "Missing string query parameter redirectUrl or session"
  592. raise SynapseError(400, message, errcode=Codes.MISSING_PARAM)
  593. await self._cas_handler.handle_ticket(
  594. request, ticket, client_redirect_url, session
  595. )
  596. def register_servlets(hs: "HomeServer", http_server: HttpServer) -> None:
  597. if hs.config.experimental.msc3861.enabled:
  598. return
  599. LoginRestServlet(hs).register(http_server)
  600. if (
  601. hs.config.worker.worker_app is None
  602. and hs.config.registration.refreshable_access_token_lifetime is not None
  603. ):
  604. RefreshTokenServlet(hs).register(http_server)
  605. if (
  606. hs.config.cas.cas_enabled
  607. or hs.config.saml2.saml2_enabled
  608. or hs.config.oidc.oidc_enabled
  609. ):
  610. SsoRedirectServlet(hs).register(http_server)
  611. if hs.config.cas.cas_enabled:
  612. CasTicketServlet(hs).register(http_server)
  613. def _load_sso_handlers(hs: "HomeServer") -> None:
  614. """Ensure that the SSO handlers are loaded, if they are enabled by configuration.
  615. This is mostly useful to ensure that the CAS/SAML/OIDC handlers register themselves
  616. with the main SsoHandler.
  617. It's safe to call this multiple times.
  618. """
  619. if hs.config.cas.cas_enabled:
  620. hs.get_cas_handler()
  621. if hs.config.saml2.saml2_enabled:
  622. hs.get_saml_handler()
  623. if hs.config.oidc.oidc_enabled:
  624. hs.get_oidc_handler()