test_saml.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  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. import attr
  15. from synapse.api.errors import RedirectException
  16. from synapse.handlers.sso import MappingException
  17. from tests.unittest import HomeserverTestCase, override_config
  18. # These are a few constants that are used as config parameters in the tests.
  19. BASE_URL = "https://synapse/"
  20. @attr.s
  21. class FakeAuthnResponse:
  22. ava = attr.ib(type=dict)
  23. class TestMappingProvider:
  24. def __init__(self, config, module):
  25. pass
  26. @staticmethod
  27. def parse_config(config):
  28. return
  29. @staticmethod
  30. def get_saml_attributes(config):
  31. return {"uid"}, {"displayName"}
  32. def get_remote_user_id(self, saml_response, client_redirect_url):
  33. return saml_response.ava["uid"]
  34. def saml_response_to_user_attributes(
  35. self, saml_response, failures, client_redirect_url
  36. ):
  37. localpart = saml_response.ava["username"] + (str(failures) if failures else "")
  38. return {"mxid_localpart": localpart, "displayname": None}
  39. class TestRedirectMappingProvider(TestMappingProvider):
  40. def saml_response_to_user_attributes(
  41. self, saml_response, failures, client_redirect_url
  42. ):
  43. raise RedirectException(b"https://custom-saml-redirect/")
  44. class SamlHandlerTestCase(HomeserverTestCase):
  45. def default_config(self):
  46. config = super().default_config()
  47. config["public_baseurl"] = BASE_URL
  48. saml_config = {
  49. "sp_config": {"metadata": {}},
  50. # Disable grandfathering.
  51. "grandfathered_mxid_source_attribute": None,
  52. "user_mapping_provider": {"module": __name__ + ".TestMappingProvider"},
  53. }
  54. # Update this config with what's in the default config so that
  55. # override_config works as expected.
  56. saml_config.update(config.get("saml2_config", {}))
  57. config["saml2_config"] = saml_config
  58. return config
  59. def make_homeserver(self, reactor, clock):
  60. hs = self.setup_test_homeserver()
  61. self.handler = hs.get_saml_handler()
  62. # Reduce the number of attempts when generating MXIDs.
  63. sso_handler = hs.get_sso_handler()
  64. sso_handler._MAP_USERNAME_RETRIES = 3
  65. return hs
  66. def test_map_saml_response_to_user(self):
  67. """Ensure that mapping the SAML response returned from a provider to an MXID works properly."""
  68. saml_response = FakeAuthnResponse({"uid": "test_user", "username": "test_user"})
  69. # The redirect_url doesn't matter with the default user mapping provider.
  70. redirect_url = ""
  71. mxid = self.get_success(
  72. self.handler._map_saml_response_to_user(
  73. saml_response, redirect_url, "user-agent", "10.10.10.10"
  74. )
  75. )
  76. self.assertEqual(mxid, "@test_user:test")
  77. @override_config({"saml2_config": {"grandfathered_mxid_source_attribute": "mxid"}})
  78. def test_map_saml_response_to_existing_user(self):
  79. """Existing users can log in with SAML account."""
  80. store = self.hs.get_datastore()
  81. self.get_success(
  82. store.register_user(user_id="@test_user:test", password_hash=None)
  83. )
  84. # Map a user via SSO.
  85. saml_response = FakeAuthnResponse(
  86. {"uid": "tester", "mxid": ["test_user"], "username": "test_user"}
  87. )
  88. redirect_url = ""
  89. mxid = self.get_success(
  90. self.handler._map_saml_response_to_user(
  91. saml_response, redirect_url, "user-agent", "10.10.10.10"
  92. )
  93. )
  94. self.assertEqual(mxid, "@test_user:test")
  95. # Subsequent calls should map to the same mxid.
  96. mxid = self.get_success(
  97. self.handler._map_saml_response_to_user(
  98. saml_response, redirect_url, "user-agent", "10.10.10.10"
  99. )
  100. )
  101. self.assertEqual(mxid, "@test_user:test")
  102. def test_map_saml_response_to_invalid_localpart(self):
  103. """If the mapping provider generates an invalid localpart it should be rejected."""
  104. saml_response = FakeAuthnResponse({"uid": "test", "username": "föö"})
  105. redirect_url = ""
  106. e = self.get_failure(
  107. self.handler._map_saml_response_to_user(
  108. saml_response, redirect_url, "user-agent", "10.10.10.10"
  109. ),
  110. MappingException,
  111. )
  112. self.assertEqual(str(e.value), "localpart is invalid: föö")
  113. def test_map_saml_response_to_user_retries(self):
  114. """The mapping provider can retry generating an MXID if the MXID is already in use."""
  115. store = self.hs.get_datastore()
  116. self.get_success(
  117. store.register_user(user_id="@test_user:test", password_hash=None)
  118. )
  119. saml_response = FakeAuthnResponse({"uid": "test", "username": "test_user"})
  120. redirect_url = ""
  121. mxid = self.get_success(
  122. self.handler._map_saml_response_to_user(
  123. saml_response, redirect_url, "user-agent", "10.10.10.10"
  124. )
  125. )
  126. # test_user is already taken, so test_user1 gets registered instead.
  127. self.assertEqual(mxid, "@test_user1:test")
  128. # Register all of the potential mxids for a particular SAML username.
  129. self.get_success(
  130. store.register_user(user_id="@tester:test", password_hash=None)
  131. )
  132. for i in range(1, 3):
  133. self.get_success(
  134. store.register_user(user_id="@tester%d:test" % i, password_hash=None)
  135. )
  136. # Now attempt to map to a username, this will fail since all potential usernames are taken.
  137. saml_response = FakeAuthnResponse({"uid": "tester", "username": "tester"})
  138. e = self.get_failure(
  139. self.handler._map_saml_response_to_user(
  140. saml_response, redirect_url, "user-agent", "10.10.10.10"
  141. ),
  142. MappingException,
  143. )
  144. self.assertEqual(
  145. str(e.value), "Unable to generate a Matrix ID from the SSO response"
  146. )
  147. @override_config(
  148. {
  149. "saml2_config": {
  150. "user_mapping_provider": {
  151. "module": __name__ + ".TestRedirectMappingProvider"
  152. },
  153. }
  154. }
  155. )
  156. def test_map_saml_response_redirect(self):
  157. saml_response = FakeAuthnResponse({"uid": "test", "username": "test_user"})
  158. redirect_url = ""
  159. e = self.get_failure(
  160. self.handler._map_saml_response_to_user(
  161. saml_response, redirect_url, "user-agent", "10.10.10.10"
  162. ),
  163. RedirectException,
  164. )
  165. self.assertEqual(e.value.location, b"https://custom-saml-redirect/")