cas.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. # Copyright 2020 The Matrix.org Foundation C.I.C.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import logging
  15. import urllib.parse
  16. from typing import TYPE_CHECKING, Dict, List, Optional
  17. from xml.etree import ElementTree as ET
  18. import attr
  19. from twisted.web.client import PartialDownloadError
  20. from synapse.api.errors import HttpResponseException
  21. from synapse.handlers.sso import MappingException, UserAttributes
  22. from synapse.http.site import SynapseRequest
  23. from synapse.types import UserID, map_username_to_mxid_localpart
  24. if TYPE_CHECKING:
  25. from synapse.server import HomeServer
  26. logger = logging.getLogger(__name__)
  27. class CasError(Exception):
  28. """Used to catch errors when validating the CAS ticket."""
  29. def __init__(self, error: str, error_description: Optional[str] = None):
  30. self.error = error
  31. self.error_description = error_description
  32. def __str__(self) -> str:
  33. if self.error_description:
  34. return f"{self.error}: {self.error_description}"
  35. return self.error
  36. @attr.s(slots=True, frozen=True, auto_attribs=True)
  37. class CasResponse:
  38. username: str
  39. attributes: Dict[str, List[Optional[str]]]
  40. class CasHandler:
  41. """
  42. Utility class for to handle the response from a CAS SSO service.
  43. Args:
  44. hs
  45. """
  46. def __init__(self, hs: "HomeServer"):
  47. self.hs = hs
  48. self._hostname = hs.hostname
  49. self._store = hs.get_datastores().main
  50. self._auth_handler = hs.get_auth_handler()
  51. self._registration_handler = hs.get_registration_handler()
  52. self._cas_server_url = hs.config.cas.cas_server_url
  53. self._cas_service_url = hs.config.cas.cas_service_url
  54. self._cas_displayname_attribute = hs.config.cas.cas_displayname_attribute
  55. self._cas_required_attributes = hs.config.cas.cas_required_attributes
  56. self._http_client = hs.get_proxied_http_client()
  57. # identifier for the external_ids table
  58. self.idp_id = "cas"
  59. # user-facing name of this auth provider
  60. self.idp_name = "CAS"
  61. # we do not currently support brands/icons for CAS auth, but this is required by
  62. # the SsoIdentityProvider protocol type.
  63. self.idp_icon = None
  64. self.idp_brand = None
  65. self._sso_handler = hs.get_sso_handler()
  66. self._sso_handler.register_identity_provider(self)
  67. def _build_service_param(self, args: Dict[str, str]) -> str:
  68. """
  69. Generates a value to use as the "service" parameter when redirecting or
  70. querying the CAS service.
  71. Args:
  72. args: Additional arguments to include in the final redirect URL.
  73. Returns:
  74. The URL to use as a "service" parameter.
  75. """
  76. return "%s?%s" % (
  77. self._cas_service_url,
  78. urllib.parse.urlencode(args),
  79. )
  80. async def _validate_ticket(
  81. self, ticket: str, service_args: Dict[str, str]
  82. ) -> CasResponse:
  83. """
  84. Validate a CAS ticket with the server, and return the parsed the response.
  85. Args:
  86. ticket: The CAS ticket from the client.
  87. service_args: Additional arguments to include in the service URL.
  88. Should be the same as those passed to `handle_redirect_request`.
  89. Raises:
  90. CasError: If there's an error parsing the CAS response.
  91. Returns:
  92. The parsed CAS response.
  93. """
  94. uri = self._cas_server_url + "/proxyValidate"
  95. args = {
  96. "ticket": ticket,
  97. "service": self._build_service_param(service_args),
  98. }
  99. try:
  100. body = await self._http_client.get_raw(uri, args)
  101. except PartialDownloadError as pde:
  102. # Twisted raises this error if the connection is closed,
  103. # even if that's being used old-http style to signal end-of-data
  104. # Assertion is for mypy's benefit. Error.response is Optional[bytes],
  105. # but a PartialDownloadError should always have a non-None response.
  106. assert pde.response is not None
  107. body = pde.response
  108. except HttpResponseException as e:
  109. description = (
  110. 'Authorization server responded with a "{status}" error '
  111. "while exchanging the authorization code."
  112. ).format(status=e.code)
  113. raise CasError("server_error", description) from e
  114. return self._parse_cas_response(body)
  115. def _parse_cas_response(self, cas_response_body: bytes) -> CasResponse:
  116. """
  117. Retrieve the user and other parameters from the CAS response.
  118. Args:
  119. cas_response_body: The response from the CAS query.
  120. Raises:
  121. CasError: If there's an error parsing the CAS response.
  122. Returns:
  123. The parsed CAS response.
  124. """
  125. # Ensure the response is valid.
  126. root = ET.fromstring(cas_response_body)
  127. if not root.tag.endswith("serviceResponse"):
  128. raise CasError(
  129. "missing_service_response",
  130. "root of CAS response is not serviceResponse",
  131. )
  132. success = root[0].tag.endswith("authenticationSuccess")
  133. if not success:
  134. raise CasError("unsucessful_response", "Unsuccessful CAS response")
  135. # Iterate through the nodes and pull out the user and any extra attributes.
  136. user = None
  137. attributes: Dict[str, List[Optional[str]]] = {}
  138. for child in root[0]:
  139. if child.tag.endswith("user"):
  140. user = child.text
  141. if child.tag.endswith("attributes"):
  142. for attribute in child:
  143. # ElementTree library expands the namespace in
  144. # attribute tags to the full URL of the namespace.
  145. # We don't care about namespace here and it will always
  146. # be encased in curly braces, so we remove them.
  147. tag = attribute.tag
  148. if "}" in tag:
  149. tag = tag.split("}")[1]
  150. attributes.setdefault(tag, []).append(attribute.text)
  151. # Ensure a user was found.
  152. if user is None:
  153. raise CasError("no_user", "CAS response does not contain user")
  154. return CasResponse(user, attributes)
  155. async def handle_redirect_request(
  156. self,
  157. request: SynapseRequest,
  158. client_redirect_url: Optional[bytes],
  159. ui_auth_session_id: Optional[str] = None,
  160. ) -> str:
  161. """Generates a URL for the CAS server where the client should be redirected.
  162. Args:
  163. request: the incoming HTTP request
  164. client_redirect_url: the URL that we should redirect the
  165. client to after login (or None for UI Auth).
  166. ui_auth_session_id: The session ID of the ongoing UI Auth (or
  167. None if this is a login).
  168. Returns:
  169. URL to redirect to
  170. """
  171. if ui_auth_session_id:
  172. service_args = {"session": ui_auth_session_id}
  173. else:
  174. assert client_redirect_url
  175. service_args = {"redirectUrl": client_redirect_url.decode("utf8")}
  176. args = urllib.parse.urlencode(
  177. {"service": self._build_service_param(service_args)}
  178. )
  179. return "%s/login?%s" % (self._cas_server_url, args)
  180. async def handle_ticket(
  181. self,
  182. request: SynapseRequest,
  183. ticket: str,
  184. client_redirect_url: Optional[str],
  185. session: Optional[str],
  186. ) -> None:
  187. """
  188. Called once the user has successfully authenticated with the SSO.
  189. Validates a CAS ticket sent by the client and completes the auth process.
  190. If the user interactive authentication session is provided, marks the
  191. UI Auth session as complete, then returns an HTML page notifying the
  192. user they are done.
  193. Otherwise, this registers the user if necessary, and then returns a
  194. redirect (with a login token) to the client.
  195. Args:
  196. request: the incoming request from the browser. We'll
  197. respond to it with a redirect or an HTML page.
  198. ticket: The CAS ticket provided by the client.
  199. client_redirect_url: the redirectUrl parameter from the `/cas/ticket` HTTP request, if given.
  200. This should be the same as the redirectUrl from the original `/login/sso/redirect` request.
  201. session: The session parameter from the `/cas/ticket` HTTP request, if given.
  202. This should be the UI Auth session id.
  203. """
  204. args = {}
  205. if client_redirect_url:
  206. args["redirectUrl"] = client_redirect_url
  207. if session:
  208. args["session"] = session
  209. try:
  210. cas_response = await self._validate_ticket(ticket, args)
  211. except CasError as e:
  212. logger.exception("Could not validate ticket")
  213. self._sso_handler.render_error(request, e.error, e.error_description, 401)
  214. return
  215. await self._handle_cas_response(
  216. request, cas_response, client_redirect_url, session
  217. )
  218. async def _handle_cas_response(
  219. self,
  220. request: SynapseRequest,
  221. cas_response: CasResponse,
  222. client_redirect_url: Optional[str],
  223. session: Optional[str],
  224. ) -> None:
  225. """Handle a CAS response to a ticket request.
  226. Assumes that the response has been validated. Maps the user onto an MXID,
  227. registering them if necessary, and returns a response to the browser.
  228. Args:
  229. request: the incoming request from the browser. We'll respond to it with an
  230. HTML page or a redirect
  231. cas_response: The parsed CAS response.
  232. client_redirect_url: the redirectUrl parameter from the `/cas/ticket` HTTP request, if given.
  233. This should be the same as the redirectUrl from the original `/login/sso/redirect` request.
  234. session: The session parameter from the `/cas/ticket` HTTP request, if given.
  235. This should be the UI Auth session id.
  236. """
  237. # first check if we're doing a UIA
  238. if session:
  239. return await self._sso_handler.complete_sso_ui_auth_request(
  240. self.idp_id,
  241. cas_response.username,
  242. session,
  243. request,
  244. )
  245. # otherwise, we're handling a login request.
  246. # Ensure that the attributes of the logged in user meet the required
  247. # attributes.
  248. if not self._sso_handler.check_required_attributes(
  249. request, cas_response.attributes, self._cas_required_attributes
  250. ):
  251. return
  252. # Call the mapper to register/login the user
  253. # If this not a UI auth request than there must be a redirect URL.
  254. assert client_redirect_url is not None
  255. try:
  256. await self._complete_cas_login(cas_response, request, client_redirect_url)
  257. except MappingException as e:
  258. logger.exception("Could not map user")
  259. self._sso_handler.render_error(request, "mapping_error", str(e))
  260. async def _complete_cas_login(
  261. self,
  262. cas_response: CasResponse,
  263. request: SynapseRequest,
  264. client_redirect_url: str,
  265. ) -> None:
  266. """
  267. Given a CAS response, complete the login flow
  268. Retrieves the remote user ID, registers the user if necessary, and serves
  269. a redirect back to the client with a login-token.
  270. Args:
  271. cas_response: The parsed CAS response.
  272. request: The request to respond to
  273. client_redirect_url: The redirect URL passed in by the client.
  274. Raises:
  275. MappingException if there was a problem mapping the response to a user.
  276. RedirectException: some mapping providers may raise this if they need
  277. to redirect to an interstitial page.
  278. """
  279. # Note that CAS does not support a mapping provider, so the logic is hard-coded.
  280. localpart = map_username_to_mxid_localpart(cas_response.username)
  281. async def cas_response_to_user_attributes(failures: int) -> UserAttributes:
  282. """
  283. Map from CAS attributes to user attributes.
  284. """
  285. # Due to the grandfathering logic matching any previously registered
  286. # mxids it isn't expected for there to be any failures.
  287. if failures:
  288. raise RuntimeError("CAS is not expected to de-duplicate Matrix IDs")
  289. # Arbitrarily use the first attribute found.
  290. display_name = cas_response.attributes.get(
  291. self._cas_displayname_attribute, [None]
  292. )[0]
  293. return UserAttributes(localpart=localpart, display_name=display_name)
  294. async def grandfather_existing_users() -> Optional[str]:
  295. # Since CAS did not always use the user_external_ids table, always
  296. # to attempt to map to existing users.
  297. user_id = UserID(localpart, self._hostname).to_string()
  298. logger.debug(
  299. "Looking for existing account based on mapped %s",
  300. user_id,
  301. )
  302. users = await self._store.get_users_by_id_case_insensitive(user_id)
  303. if users:
  304. registered_user_id = list(users.keys())[0]
  305. logger.info("Grandfathering mapping to %s", registered_user_id)
  306. return registered_user_id
  307. return None
  308. await self._sso_handler.complete_sso_login_request(
  309. self.idp_id,
  310. cas_response.username,
  311. request,
  312. client_redirect_url,
  313. cas_response_to_user_attributes,
  314. grandfather_existing_users,
  315. )