login.py 24 KB

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