1
0

test_saml.py 13 KB

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