1
0

test_saml.py 12 KB

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