test_saml.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  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. from typing import Any, Dict, Optional, Set, Tuple
  15. from unittest.mock import AsyncMock, Mock
  16. import attr
  17. from twisted.test.proto_helpers import MemoryReactor
  18. from synapse.api.errors import RedirectException
  19. from synapse.module_api import ModuleApi
  20. from synapse.server import HomeServer
  21. from synapse.types import JsonDict
  22. from synapse.util import Clock
  23. from tests.unittest import HomeserverTestCase, override_config
  24. # Check if we have the dependencies to run the tests.
  25. try:
  26. import saml2.config
  27. import saml2.response
  28. from saml2.sigver import SigverError
  29. has_saml2 = True
  30. # pysaml2 can be installed and imported, but might not be able to find xmlsec1.
  31. config = saml2.config.SPConfig()
  32. try:
  33. config.load({"metadata": {}})
  34. has_xmlsec1 = True
  35. except SigverError:
  36. has_xmlsec1 = False
  37. except ImportError:
  38. has_saml2 = False
  39. has_xmlsec1 = False
  40. # These are a few constants that are used as config parameters in the tests.
  41. BASE_URL = "https://synapse/"
  42. @attr.s
  43. class FakeAuthnResponse:
  44. ava = attr.ib(type=dict)
  45. assertions = attr.ib(type=list, factory=list)
  46. in_response_to = attr.ib(type=Optional[str], default=None)
  47. class TestMappingProvider:
  48. def __init__(self, config: None, module: ModuleApi):
  49. pass
  50. @staticmethod
  51. def parse_config(config: JsonDict) -> None:
  52. return None
  53. @staticmethod
  54. def get_saml_attributes(config: None) -> Tuple[Set[str], Set[str]]:
  55. return {"uid"}, {"displayName"}
  56. def get_remote_user_id(
  57. self, saml_response: "saml2.response.AuthnResponse", client_redirect_url: str
  58. ) -> str:
  59. return saml_response.ava["uid"]
  60. def saml_response_to_user_attributes(
  61. self,
  62. saml_response: "saml2.response.AuthnResponse",
  63. failures: int,
  64. client_redirect_url: str,
  65. ) -> dict:
  66. localpart = saml_response.ava["username"] + (str(failures) if failures else "")
  67. return {"mxid_localpart": localpart, "displayname": None}
  68. class TestRedirectMappingProvider(TestMappingProvider):
  69. def saml_response_to_user_attributes(
  70. self,
  71. saml_response: "saml2.response.AuthnResponse",
  72. failures: int,
  73. client_redirect_url: str,
  74. ) -> dict:
  75. raise RedirectException(b"https://custom-saml-redirect/")
  76. class SamlHandlerTestCase(HomeserverTestCase):
  77. def default_config(self) -> Dict[str, Any]:
  78. config = super().default_config()
  79. config["public_baseurl"] = BASE_URL
  80. saml_config: Dict[str, Any] = {
  81. "sp_config": {"metadata": {}},
  82. # Disable grandfathering.
  83. "grandfathered_mxid_source_attribute": None,
  84. "user_mapping_provider": {"module": __name__ + ".TestMappingProvider"},
  85. }
  86. # Update this config with what's in the default config so that
  87. # override_config works as expected.
  88. saml_config.update(config.get("saml2_config", {}))
  89. config["saml2_config"] = saml_config
  90. return config
  91. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  92. hs = self.setup_test_homeserver()
  93. self.handler = hs.get_saml_handler()
  94. # Reduce the number of attempts when generating MXIDs.
  95. sso_handler = hs.get_sso_handler()
  96. sso_handler._MAP_USERNAME_RETRIES = 3
  97. return hs
  98. if not has_saml2:
  99. skip = "Requires pysaml2"
  100. elif not has_xmlsec1:
  101. skip = "Requires xmlsec1"
  102. def test_map_saml_response_to_user(self) -> None:
  103. """Ensure that mapping the SAML response returned from a provider to an MXID works properly."""
  104. # stub out the auth handler
  105. auth_handler = self.hs.get_auth_handler()
  106. auth_handler.complete_sso_login = AsyncMock() # type: ignore[method-assign]
  107. # send a mocked-up SAML response to the callback
  108. saml_response = FakeAuthnResponse({"uid": "test_user", "username": "test_user"})
  109. request = _mock_request()
  110. self.get_success(
  111. self.handler._handle_authn_response(request, saml_response, "redirect_uri")
  112. )
  113. # check that the auth handler got called as expected
  114. auth_handler.complete_sso_login.assert_called_once_with(
  115. "@test_user:test",
  116. "saml",
  117. request,
  118. "redirect_uri",
  119. None,
  120. new_user=True,
  121. auth_provider_session_id=None,
  122. )
  123. @override_config({"saml2_config": {"grandfathered_mxid_source_attribute": "mxid"}})
  124. def test_map_saml_response_to_existing_user(self) -> None:
  125. """Existing users can log in with SAML account."""
  126. store = self.hs.get_datastores().main
  127. self.get_success(
  128. store.register_user(user_id="@test_user:test", password_hash=None)
  129. )
  130. # stub out the auth handler
  131. auth_handler = self.hs.get_auth_handler()
  132. auth_handler.complete_sso_login = AsyncMock() # type: ignore[method-assign]
  133. # Map a user via SSO.
  134. saml_response = FakeAuthnResponse(
  135. {"uid": "tester", "mxid": ["test_user"], "username": "test_user"}
  136. )
  137. request = _mock_request()
  138. self.get_success(
  139. self.handler._handle_authn_response(request, saml_response, "")
  140. )
  141. # check that the auth handler got called as expected
  142. auth_handler.complete_sso_login.assert_called_once_with(
  143. "@test_user:test",
  144. "saml",
  145. request,
  146. "",
  147. None,
  148. new_user=False,
  149. auth_provider_session_id=None,
  150. )
  151. # Subsequent calls should map to the same mxid.
  152. auth_handler.complete_sso_login.reset_mock()
  153. self.get_success(
  154. self.handler._handle_authn_response(request, saml_response, "")
  155. )
  156. auth_handler.complete_sso_login.assert_called_once_with(
  157. "@test_user:test",
  158. "saml",
  159. request,
  160. "",
  161. None,
  162. new_user=False,
  163. auth_provider_session_id=None,
  164. )
  165. def test_map_saml_response_to_invalid_localpart(self) -> None:
  166. """If the mapping provider generates an invalid localpart it should be rejected."""
  167. # stub out the auth handler
  168. auth_handler = self.hs.get_auth_handler()
  169. auth_handler.complete_sso_login = AsyncMock() # type: ignore[method-assign]
  170. # mock out the error renderer too
  171. sso_handler = self.hs.get_sso_handler()
  172. sso_handler.render_error = Mock(return_value=None) # type: ignore[method-assign]
  173. saml_response = FakeAuthnResponse({"uid": "test", "username": "föö"})
  174. request = _mock_request()
  175. self.get_success(
  176. self.handler._handle_authn_response(request, saml_response, ""),
  177. )
  178. sso_handler.render_error.assert_called_once_with(
  179. request, "mapping_error", "localpart is invalid: föö"
  180. )
  181. auth_handler.complete_sso_login.assert_not_called()
  182. def test_map_saml_response_to_user_retries(self) -> None:
  183. """The mapping provider can retry generating an MXID if the MXID is already in use."""
  184. # stub out the auth handler and error renderer
  185. auth_handler = self.hs.get_auth_handler()
  186. auth_handler.complete_sso_login = AsyncMock() # type: ignore[method-assign]
  187. sso_handler = self.hs.get_sso_handler()
  188. sso_handler.render_error = Mock(return_value=None) # type: ignore[method-assign]
  189. # register a user to occupy the first-choice MXID
  190. store = self.hs.get_datastores().main
  191. self.get_success(
  192. store.register_user(user_id="@test_user:test", password_hash=None)
  193. )
  194. # send the fake SAML response
  195. saml_response = FakeAuthnResponse({"uid": "test", "username": "test_user"})
  196. request = _mock_request()
  197. self.get_success(
  198. self.handler._handle_authn_response(request, saml_response, ""),
  199. )
  200. # test_user is already taken, so test_user1 gets registered instead.
  201. auth_handler.complete_sso_login.assert_called_once_with(
  202. "@test_user1:test",
  203. "saml",
  204. request,
  205. "",
  206. None,
  207. new_user=True,
  208. auth_provider_session_id=None,
  209. )
  210. auth_handler.complete_sso_login.reset_mock()
  211. # Register all of the potential mxids for a particular SAML username.
  212. self.get_success(
  213. store.register_user(user_id="@tester:test", password_hash=None)
  214. )
  215. for i in range(1, 3):
  216. self.get_success(
  217. store.register_user(user_id="@tester%d:test" % i, password_hash=None)
  218. )
  219. # Now attempt to map to a username, this will fail since all potential usernames are taken.
  220. saml_response = FakeAuthnResponse({"uid": "tester", "username": "tester"})
  221. self.get_success(
  222. self.handler._handle_authn_response(request, saml_response, ""),
  223. )
  224. sso_handler.render_error.assert_called_once_with(
  225. request,
  226. "mapping_error",
  227. "Unable to generate a Matrix ID from the SSO response",
  228. )
  229. auth_handler.complete_sso_login.assert_not_called()
  230. @override_config(
  231. {
  232. "saml2_config": {
  233. "user_mapping_provider": {
  234. "module": __name__ + ".TestRedirectMappingProvider"
  235. },
  236. }
  237. }
  238. )
  239. def test_map_saml_response_redirect(self) -> None:
  240. """Test a mapping provider that raises a RedirectException"""
  241. saml_response = FakeAuthnResponse({"uid": "test", "username": "test_user"})
  242. request = _mock_request()
  243. e = self.get_failure(
  244. self.handler._handle_authn_response(request, saml_response, ""),
  245. RedirectException,
  246. )
  247. self.assertEqual(e.value.location, b"https://custom-saml-redirect/")
  248. @override_config(
  249. {
  250. "saml2_config": {
  251. "attribute_requirements": [
  252. {"attribute": "userGroup", "value": "staff"},
  253. {"attribute": "department", "value": "sales"},
  254. ],
  255. },
  256. }
  257. )
  258. def test_attribute_requirements(self) -> None:
  259. """The required attributes must be met from the SAML response."""
  260. # stub out the auth handler
  261. auth_handler = self.hs.get_auth_handler()
  262. auth_handler.complete_sso_login = AsyncMock() # type: ignore[method-assign]
  263. # The response doesn't have the proper userGroup or department.
  264. saml_response = FakeAuthnResponse({"uid": "test_user", "username": "test_user"})
  265. request = _mock_request()
  266. self.get_success(
  267. self.handler._handle_authn_response(request, saml_response, "redirect_uri")
  268. )
  269. auth_handler.complete_sso_login.assert_not_called()
  270. # The response doesn't have the proper department.
  271. saml_response = FakeAuthnResponse(
  272. {"uid": "test_user", "username": "test_user", "userGroup": ["staff"]}
  273. )
  274. request = _mock_request()
  275. self.get_success(
  276. self.handler._handle_authn_response(request, saml_response, "redirect_uri")
  277. )
  278. auth_handler.complete_sso_login.assert_not_called()
  279. # Add the proper attributes and it should succeed.
  280. saml_response = FakeAuthnResponse(
  281. {
  282. "uid": "test_user",
  283. "username": "test_user",
  284. "userGroup": ["staff", "admin"],
  285. "department": ["sales"],
  286. }
  287. )
  288. request.reset_mock()
  289. self.get_success(
  290. self.handler._handle_authn_response(request, saml_response, "redirect_uri")
  291. )
  292. # check that the auth handler got called as expected
  293. auth_handler.complete_sso_login.assert_called_once_with(
  294. "@test_user:test",
  295. "saml",
  296. request,
  297. "redirect_uri",
  298. None,
  299. new_user=True,
  300. auth_provider_session_id=None,
  301. )
  302. def _mock_request() -> Mock:
  303. """Returns a mock which will stand in as a SynapseRequest"""
  304. mock = Mock(
  305. spec=[
  306. "finish",
  307. "getClientAddress",
  308. "getHeader",
  309. "setHeader",
  310. "setResponseCode",
  311. "write",
  312. ]
  313. )
  314. # `_disconnected` musn't be another `Mock`, otherwise it will be truthy.
  315. mock._disconnected = False
  316. return mock