1
0

test_saml.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  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", "saml", request, "redirect_uri", None, new_user=True
  103. )
  104. @override_config({"saml2_config": {"grandfathered_mxid_source_attribute": "mxid"}})
  105. def test_map_saml_response_to_existing_user(self):
  106. """Existing users can log in with SAML account."""
  107. store = self.hs.get_datastore()
  108. self.get_success(
  109. store.register_user(user_id="@test_user:test", password_hash=None)
  110. )
  111. # stub out the auth handler
  112. auth_handler = self.hs.get_auth_handler()
  113. auth_handler.complete_sso_login = simple_async_mock()
  114. # Map a user via SSO.
  115. saml_response = FakeAuthnResponse(
  116. {"uid": "tester", "mxid": ["test_user"], "username": "test_user"}
  117. )
  118. request = _mock_request()
  119. self.get_success(
  120. self.handler._handle_authn_response(request, saml_response, "")
  121. )
  122. # check that the auth handler got called as expected
  123. auth_handler.complete_sso_login.assert_called_once_with(
  124. "@test_user:test", "saml", request, "", None, new_user=False
  125. )
  126. # Subsequent calls should map to the same mxid.
  127. auth_handler.complete_sso_login.reset_mock()
  128. self.get_success(
  129. self.handler._handle_authn_response(request, saml_response, "")
  130. )
  131. auth_handler.complete_sso_login.assert_called_once_with(
  132. "@test_user:test", "saml", request, "", None, new_user=False
  133. )
  134. def test_map_saml_response_to_invalid_localpart(self):
  135. """If the mapping provider generates an invalid localpart it should be rejected."""
  136. # stub out the auth handler
  137. auth_handler = self.hs.get_auth_handler()
  138. auth_handler.complete_sso_login = simple_async_mock()
  139. # mock out the error renderer too
  140. sso_handler = self.hs.get_sso_handler()
  141. sso_handler.render_error = Mock(return_value=None)
  142. saml_response = FakeAuthnResponse({"uid": "test", "username": "föö"})
  143. request = _mock_request()
  144. self.get_success(
  145. self.handler._handle_authn_response(request, saml_response, ""),
  146. )
  147. sso_handler.render_error.assert_called_once_with(
  148. request, "mapping_error", "localpart is invalid: föö"
  149. )
  150. auth_handler.complete_sso_login.assert_not_called()
  151. def test_map_saml_response_to_user_retries(self):
  152. """The mapping provider can retry generating an MXID if the MXID is already in use."""
  153. # stub out the auth handler and error renderer
  154. auth_handler = self.hs.get_auth_handler()
  155. auth_handler.complete_sso_login = simple_async_mock()
  156. sso_handler = self.hs.get_sso_handler()
  157. sso_handler.render_error = Mock(return_value=None)
  158. # register a user to occupy the first-choice MXID
  159. store = self.hs.get_datastore()
  160. self.get_success(
  161. store.register_user(user_id="@test_user:test", password_hash=None)
  162. )
  163. # send the fake SAML response
  164. saml_response = FakeAuthnResponse({"uid": "test", "username": "test_user"})
  165. request = _mock_request()
  166. self.get_success(
  167. self.handler._handle_authn_response(request, saml_response, ""),
  168. )
  169. # test_user is already taken, so test_user1 gets registered instead.
  170. auth_handler.complete_sso_login.assert_called_once_with(
  171. "@test_user1:test", "saml", request, "", None, new_user=True
  172. )
  173. auth_handler.complete_sso_login.reset_mock()
  174. # Register all of the potential mxids for a particular SAML username.
  175. self.get_success(
  176. store.register_user(user_id="@tester:test", password_hash=None)
  177. )
  178. for i in range(1, 3):
  179. self.get_success(
  180. store.register_user(user_id="@tester%d:test" % i, password_hash=None)
  181. )
  182. # Now attempt to map to a username, this will fail since all potential usernames are taken.
  183. saml_response = FakeAuthnResponse({"uid": "tester", "username": "tester"})
  184. self.get_success(
  185. self.handler._handle_authn_response(request, saml_response, ""),
  186. )
  187. sso_handler.render_error.assert_called_once_with(
  188. request,
  189. "mapping_error",
  190. "Unable to generate a Matrix ID from the SSO response",
  191. )
  192. auth_handler.complete_sso_login.assert_not_called()
  193. @override_config(
  194. {
  195. "saml2_config": {
  196. "user_mapping_provider": {
  197. "module": __name__ + ".TestRedirectMappingProvider"
  198. },
  199. }
  200. }
  201. )
  202. def test_map_saml_response_redirect(self):
  203. """Test a mapping provider that raises a RedirectException"""
  204. saml_response = FakeAuthnResponse({"uid": "test", "username": "test_user"})
  205. request = _mock_request()
  206. e = self.get_failure(
  207. self.handler._handle_authn_response(request, saml_response, ""),
  208. RedirectException,
  209. )
  210. self.assertEqual(e.value.location, b"https://custom-saml-redirect/")
  211. @override_config(
  212. {
  213. "saml2_config": {
  214. "attribute_requirements": [
  215. {"attribute": "userGroup", "value": "staff"},
  216. {"attribute": "department", "value": "sales"},
  217. ],
  218. },
  219. }
  220. )
  221. def test_attribute_requirements(self):
  222. """The required attributes must be met from the SAML response."""
  223. # stub out the auth handler
  224. auth_handler = self.hs.get_auth_handler()
  225. auth_handler.complete_sso_login = simple_async_mock()
  226. # The response doesn't have the proper userGroup or department.
  227. saml_response = FakeAuthnResponse({"uid": "test_user", "username": "test_user"})
  228. request = _mock_request()
  229. self.get_success(
  230. self.handler._handle_authn_response(request, saml_response, "redirect_uri")
  231. )
  232. auth_handler.complete_sso_login.assert_not_called()
  233. # The response doesn't have the proper department.
  234. saml_response = FakeAuthnResponse(
  235. {"uid": "test_user", "username": "test_user", "userGroup": ["staff"]}
  236. )
  237. request = _mock_request()
  238. self.get_success(
  239. self.handler._handle_authn_response(request, saml_response, "redirect_uri")
  240. )
  241. auth_handler.complete_sso_login.assert_not_called()
  242. # Add the proper attributes and it should succeed.
  243. saml_response = FakeAuthnResponse(
  244. {
  245. "uid": "test_user",
  246. "username": "test_user",
  247. "userGroup": ["staff", "admin"],
  248. "department": ["sales"],
  249. }
  250. )
  251. request.reset_mock()
  252. self.get_success(
  253. self.handler._handle_authn_response(request, saml_response, "redirect_uri")
  254. )
  255. # check that the auth handler got called as expected
  256. auth_handler.complete_sso_login.assert_called_once_with(
  257. "@test_user:test", "saml", request, "redirect_uri", None, new_user=True
  258. )
  259. def _mock_request():
  260. """Returns a mock which will stand in as a SynapseRequest"""
  261. return Mock(spec=["getClientIP", "getHeader", "_disconnected"])