1
0

test_saml.py 12 KB

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