cas.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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. body = pde.response
  105. except HttpResponseException as e:
  106. description = (
  107. 'Authorization server responded with a "{status}" error '
  108. "while exchanging the authorization code."
  109. ).format(status=e.code)
  110. raise CasError("server_error", description) from e
  111. return self._parse_cas_response(body)
  112. def _parse_cas_response(self, cas_response_body: bytes) -> CasResponse:
  113. """
  114. Retrieve the user and other parameters from the CAS response.
  115. Args:
  116. cas_response_body: The response from the CAS query.
  117. Raises:
  118. CasError: If there's an error parsing the CAS response.
  119. Returns:
  120. The parsed CAS response.
  121. """
  122. # Ensure the response is valid.
  123. root = ET.fromstring(cas_response_body)
  124. if not root.tag.endswith("serviceResponse"):
  125. raise CasError(
  126. "missing_service_response",
  127. "root of CAS response is not serviceResponse",
  128. )
  129. success = root[0].tag.endswith("authenticationSuccess")
  130. if not success:
  131. raise CasError("unsucessful_response", "Unsuccessful CAS response")
  132. # Iterate through the nodes and pull out the user and any extra attributes.
  133. user = None
  134. attributes: Dict[str, List[Optional[str]]] = {}
  135. for child in root[0]:
  136. if child.tag.endswith("user"):
  137. user = child.text
  138. if child.tag.endswith("attributes"):
  139. for attribute in child:
  140. # ElementTree library expands the namespace in
  141. # attribute tags to the full URL of the namespace.
  142. # We don't care about namespace here and it will always
  143. # be encased in curly braces, so we remove them.
  144. tag = attribute.tag
  145. if "}" in tag:
  146. tag = tag.split("}")[1]
  147. attributes.setdefault(tag, []).append(attribute.text)
  148. # Ensure a user was found.
  149. if user is None:
  150. raise CasError("no_user", "CAS response does not contain user")
  151. return CasResponse(user, attributes)
  152. async def handle_redirect_request(
  153. self,
  154. request: SynapseRequest,
  155. client_redirect_url: Optional[bytes],
  156. ui_auth_session_id: Optional[str] = None,
  157. ) -> str:
  158. """Generates a URL for the CAS server where the client should be redirected.
  159. Args:
  160. request: the incoming HTTP request
  161. client_redirect_url: the URL that we should redirect the
  162. client to after login (or None for UI Auth).
  163. ui_auth_session_id: The session ID of the ongoing UI Auth (or
  164. None if this is a login).
  165. Returns:
  166. URL to redirect to
  167. """
  168. if ui_auth_session_id:
  169. service_args = {"session": ui_auth_session_id}
  170. else:
  171. assert client_redirect_url
  172. service_args = {"redirectUrl": client_redirect_url.decode("utf8")}
  173. args = urllib.parse.urlencode(
  174. {"service": self._build_service_param(service_args)}
  175. )
  176. return "%s/login?%s" % (self._cas_server_url, args)
  177. async def handle_ticket(
  178. self,
  179. request: SynapseRequest,
  180. ticket: str,
  181. client_redirect_url: Optional[str],
  182. session: Optional[str],
  183. ) -> None:
  184. """
  185. Called once the user has successfully authenticated with the SSO.
  186. Validates a CAS ticket sent by the client and completes the auth process.
  187. If the user interactive authentication session is provided, marks the
  188. UI Auth session as complete, then returns an HTML page notifying the
  189. user they are done.
  190. Otherwise, this registers the user if necessary, and then returns a
  191. redirect (with a login token) to the client.
  192. Args:
  193. request: the incoming request from the browser. We'll
  194. respond to it with a redirect or an HTML page.
  195. ticket: The CAS ticket provided by the client.
  196. client_redirect_url: the redirectUrl parameter from the `/cas/ticket` HTTP request, if given.
  197. This should be the same as the redirectUrl from the original `/login/sso/redirect` request.
  198. session: The session parameter from the `/cas/ticket` HTTP request, if given.
  199. This should be the UI Auth session id.
  200. """
  201. args = {}
  202. if client_redirect_url:
  203. args["redirectUrl"] = client_redirect_url
  204. if session:
  205. args["session"] = session
  206. try:
  207. cas_response = await self._validate_ticket(ticket, args)
  208. except CasError as e:
  209. logger.exception("Could not validate ticket")
  210. self._sso_handler.render_error(request, e.error, e.error_description, 401)
  211. return
  212. await self._handle_cas_response(
  213. request, cas_response, client_redirect_url, session
  214. )
  215. async def _handle_cas_response(
  216. self,
  217. request: SynapseRequest,
  218. cas_response: CasResponse,
  219. client_redirect_url: Optional[str],
  220. session: Optional[str],
  221. ) -> None:
  222. """Handle a CAS response to a ticket request.
  223. Assumes that the response has been validated. Maps the user onto an MXID,
  224. registering them if necessary, and returns a response to the browser.
  225. Args:
  226. request: the incoming request from the browser. We'll respond to it with an
  227. HTML page or a redirect
  228. cas_response: The parsed CAS response.
  229. client_redirect_url: the redirectUrl parameter from the `/cas/ticket` HTTP request, if given.
  230. This should be the same as the redirectUrl from the original `/login/sso/redirect` request.
  231. session: The session parameter from the `/cas/ticket` HTTP request, if given.
  232. This should be the UI Auth session id.
  233. """
  234. # first check if we're doing a UIA
  235. if session:
  236. return await self._sso_handler.complete_sso_ui_auth_request(
  237. self.idp_id,
  238. cas_response.username,
  239. session,
  240. request,
  241. )
  242. # otherwise, we're handling a login request.
  243. # Ensure that the attributes of the logged in user meet the required
  244. # attributes.
  245. if not self._sso_handler.check_required_attributes(
  246. request, cas_response.attributes, self._cas_required_attributes
  247. ):
  248. return
  249. # Call the mapper to register/login the user
  250. # If this not a UI auth request than there must be a redirect URL.
  251. assert client_redirect_url is not None
  252. try:
  253. await self._complete_cas_login(cas_response, request, client_redirect_url)
  254. except MappingException as e:
  255. logger.exception("Could not map user")
  256. self._sso_handler.render_error(request, "mapping_error", str(e))
  257. async def _complete_cas_login(
  258. self,
  259. cas_response: CasResponse,
  260. request: SynapseRequest,
  261. client_redirect_url: str,
  262. ) -> None:
  263. """
  264. Given a CAS response, complete the login flow
  265. Retrieves the remote user ID, registers the user if necessary, and serves
  266. a redirect back to the client with a login-token.
  267. Args:
  268. cas_response: The parsed CAS response.
  269. request: The request to respond to
  270. client_redirect_url: The redirect URL passed in by the client.
  271. Raises:
  272. MappingException if there was a problem mapping the response to a user.
  273. RedirectException: some mapping providers may raise this if they need
  274. to redirect to an interstitial page.
  275. """
  276. # Note that CAS does not support a mapping provider, so the logic is hard-coded.
  277. localpart = map_username_to_mxid_localpart(cas_response.username)
  278. async def cas_response_to_user_attributes(failures: int) -> UserAttributes:
  279. """
  280. Map from CAS attributes to user attributes.
  281. """
  282. # Due to the grandfathering logic matching any previously registered
  283. # mxids it isn't expected for there to be any failures.
  284. if failures:
  285. raise RuntimeError("CAS is not expected to de-duplicate Matrix IDs")
  286. # Arbitrarily use the first attribute found.
  287. display_name = cas_response.attributes.get(
  288. self._cas_displayname_attribute, [None]
  289. )[0]
  290. return UserAttributes(localpart=localpart, display_name=display_name)
  291. async def grandfather_existing_users() -> Optional[str]:
  292. # Since CAS did not always use the user_external_ids table, always
  293. # to attempt to map to existing users.
  294. user_id = UserID(localpart, self._hostname).to_string()
  295. logger.debug(
  296. "Looking for existing account based on mapped %s",
  297. user_id,
  298. )
  299. users = await self._store.get_users_by_id_case_insensitive(user_id)
  300. if users:
  301. registered_user_id = list(users.keys())[0]
  302. logger.info("Grandfathering mapping to %s", registered_user_id)
  303. return registered_user_id
  304. return None
  305. await self._sso_handler.complete_sso_login_request(
  306. self.idp_id,
  307. cas_response.username,
  308. request,
  309. client_redirect_url,
  310. cas_response_to_user_attributes,
  311. grandfather_existing_users,
  312. )