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.
 
 
 
 
 
 

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