test_register.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2015, 2016 OpenMarket Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. from mock import Mock
  16. from twisted.internet import defer
  17. from synapse.api.constants import UserTypes
  18. from synapse.api.errors import Codes, ResourceLimitError, SynapseError
  19. from synapse.handlers.register import RegistrationHandler
  20. from synapse.types import RoomAlias, UserID, create_requester
  21. from .. import unittest
  22. class RegistrationHandlers(object):
  23. def __init__(self, hs):
  24. self.registration_handler = RegistrationHandler(hs)
  25. class RegistrationTestCase(unittest.HomeserverTestCase):
  26. """ Tests the RegistrationHandler. """
  27. def make_homeserver(self, reactor, clock):
  28. hs_config = self.default_config()
  29. # some of the tests rely on us having a user consent version
  30. hs_config["user_consent"] = {
  31. "version": "test_consent_version",
  32. "template_dir": ".",
  33. }
  34. hs_config["max_mau_value"] = 50
  35. hs_config["limit_usage_by_mau"] = True
  36. hs = self.setup_test_homeserver(config=hs_config)
  37. return hs
  38. def prepare(self, reactor, clock, hs):
  39. self.mock_distributor = Mock()
  40. self.mock_distributor.declare("registered_user")
  41. self.mock_captcha_client = Mock()
  42. self.macaroon_generator = Mock(
  43. generate_access_token=Mock(return_value="secret")
  44. )
  45. self.hs.get_macaroon_generator = Mock(return_value=self.macaroon_generator)
  46. self.handler = self.hs.get_registration_handler()
  47. self.store = self.hs.get_datastore()
  48. self.lots_of_users = 100
  49. self.small_number_of_users = 1
  50. self.requester = create_requester("@requester:test")
  51. def test_user_is_created_and_logged_in_if_doesnt_exist(self):
  52. frank = UserID.from_string("@frank:test")
  53. user_id = frank.to_string()
  54. requester = create_requester(user_id)
  55. result_user_id, result_token = self.get_success(
  56. self.get_or_create_user(requester, frank.localpart, "Frankie")
  57. )
  58. self.assertEquals(result_user_id, user_id)
  59. self.assertTrue(result_token is not None)
  60. self.assertEquals(result_token, "secret")
  61. def test_if_user_exists(self):
  62. store = self.hs.get_datastore()
  63. frank = UserID.from_string("@frank:test")
  64. self.get_success(
  65. store.register_user(user_id=frank.to_string(), password_hash=None)
  66. )
  67. local_part = frank.localpart
  68. user_id = frank.to_string()
  69. requester = create_requester(user_id)
  70. result_user_id, result_token = self.get_success(
  71. self.get_or_create_user(requester, local_part, None)
  72. )
  73. self.assertEquals(result_user_id, user_id)
  74. self.assertTrue(result_token is not None)
  75. def test_mau_limits_when_disabled(self):
  76. self.hs.config.limit_usage_by_mau = False
  77. # Ensure does not throw exception
  78. self.get_success(self.get_or_create_user(self.requester, "a", "display_name"))
  79. def test_get_or_create_user_mau_not_blocked(self):
  80. self.hs.config.limit_usage_by_mau = True
  81. self.store.count_monthly_users = Mock(
  82. return_value=defer.succeed(self.hs.config.max_mau_value - 1)
  83. )
  84. # Ensure does not throw exception
  85. self.get_success(self.get_or_create_user(self.requester, "c", "User"))
  86. def test_get_or_create_user_mau_blocked(self):
  87. self.hs.config.limit_usage_by_mau = True
  88. self.store.get_monthly_active_count = Mock(
  89. return_value=defer.succeed(self.lots_of_users)
  90. )
  91. self.get_failure(
  92. self.get_or_create_user(self.requester, "b", "display_name"),
  93. ResourceLimitError,
  94. )
  95. self.store.get_monthly_active_count = Mock(
  96. return_value=defer.succeed(self.hs.config.max_mau_value)
  97. )
  98. self.get_failure(
  99. self.get_or_create_user(self.requester, "b", "display_name"),
  100. ResourceLimitError,
  101. )
  102. def test_register_mau_blocked(self):
  103. self.hs.config.limit_usage_by_mau = True
  104. self.store.get_monthly_active_count = Mock(
  105. return_value=defer.succeed(self.lots_of_users)
  106. )
  107. self.get_failure(
  108. self.handler.register_user(localpart="local_part"), ResourceLimitError
  109. )
  110. self.store.get_monthly_active_count = Mock(
  111. return_value=defer.succeed(self.hs.config.max_mau_value)
  112. )
  113. self.get_failure(
  114. self.handler.register_user(localpart="local_part"), ResourceLimitError
  115. )
  116. def test_auto_create_auto_join_rooms(self):
  117. room_alias_str = "#room:test"
  118. self.hs.config.auto_join_rooms = [room_alias_str]
  119. user_id = self.get_success(self.handler.register_user(localpart="jeff"))
  120. rooms = self.get_success(self.store.get_rooms_for_user(user_id))
  121. directory_handler = self.hs.get_handlers().directory_handler
  122. room_alias = RoomAlias.from_string(room_alias_str)
  123. room_id = self.get_success(directory_handler.get_association(room_alias))
  124. self.assertTrue(room_id["room_id"] in rooms)
  125. self.assertEqual(len(rooms), 1)
  126. def test_auto_create_auto_join_rooms_with_no_rooms(self):
  127. self.hs.config.auto_join_rooms = []
  128. frank = UserID.from_string("@frank:test")
  129. user_id = self.get_success(self.handler.register_user(frank.localpart))
  130. self.assertEqual(user_id, frank.to_string())
  131. rooms = self.get_success(self.store.get_rooms_for_user(user_id))
  132. self.assertEqual(len(rooms), 0)
  133. def test_auto_create_auto_join_where_room_is_another_domain(self):
  134. self.hs.config.auto_join_rooms = ["#room:another"]
  135. frank = UserID.from_string("@frank:test")
  136. user_id = self.get_success(self.handler.register_user(frank.localpart))
  137. self.assertEqual(user_id, frank.to_string())
  138. rooms = self.get_success(self.store.get_rooms_for_user(user_id))
  139. self.assertEqual(len(rooms), 0)
  140. def test_auto_create_auto_join_where_auto_create_is_false(self):
  141. self.hs.config.autocreate_auto_join_rooms = False
  142. room_alias_str = "#room:test"
  143. self.hs.config.auto_join_rooms = [room_alias_str]
  144. user_id = self.get_success(self.handler.register_user(localpart="jeff"))
  145. rooms = self.get_success(self.store.get_rooms_for_user(user_id))
  146. self.assertEqual(len(rooms), 0)
  147. def test_auto_create_auto_join_rooms_when_user_is_not_a_real_user(self):
  148. room_alias_str = "#room:test"
  149. self.hs.config.auto_join_rooms = [room_alias_str]
  150. self.store.is_real_user = Mock(return_value=defer.succeed(False))
  151. user_id = self.get_success(self.handler.register_user(localpart="support"))
  152. rooms = self.get_success(self.store.get_rooms_for_user(user_id))
  153. self.assertEqual(len(rooms), 0)
  154. directory_handler = self.hs.get_handlers().directory_handler
  155. room_alias = RoomAlias.from_string(room_alias_str)
  156. self.get_failure(directory_handler.get_association(room_alias), SynapseError)
  157. def test_auto_create_auto_join_rooms_when_user_is_the_first_real_user(self):
  158. room_alias_str = "#room:test"
  159. self.hs.config.auto_join_rooms = [room_alias_str]
  160. self.store.count_real_users = Mock(return_value=defer.succeed(1))
  161. self.store.is_real_user = Mock(return_value=defer.succeed(True))
  162. user_id = self.get_success(self.handler.register_user(localpart="real"))
  163. rooms = self.get_success(self.store.get_rooms_for_user(user_id))
  164. directory_handler = self.hs.get_handlers().directory_handler
  165. room_alias = RoomAlias.from_string(room_alias_str)
  166. room_id = self.get_success(directory_handler.get_association(room_alias))
  167. self.assertTrue(room_id["room_id"] in rooms)
  168. self.assertEqual(len(rooms), 1)
  169. def test_auto_create_auto_join_rooms_when_user_is_not_the_first_real_user(self):
  170. room_alias_str = "#room:test"
  171. self.hs.config.auto_join_rooms = [room_alias_str]
  172. self.store.count_real_users = Mock(return_value=defer.succeed(2))
  173. self.store.is_real_user = Mock(return_value=defer.succeed(True))
  174. user_id = self.get_success(self.handler.register_user(localpart="real"))
  175. rooms = self.get_success(self.store.get_rooms_for_user(user_id))
  176. self.assertEqual(len(rooms), 0)
  177. def test_auto_create_auto_join_where_no_consent(self):
  178. """Test to ensure that the first user is not auto-joined to a room if
  179. they have not given general consent.
  180. """
  181. # Given:-
  182. # * a user must give consent,
  183. # * they have not given that consent
  184. # * The server is configured to auto-join to a room
  185. # (and autocreate if necessary)
  186. event_creation_handler = self.hs.get_event_creation_handler()
  187. # (Messing with the internals of event_creation_handler is fragile
  188. # but can't see a better way to do this. One option could be to subclass
  189. # the test with custom config.)
  190. event_creation_handler._block_events_without_consent_error = "Error"
  191. event_creation_handler._consent_uri_builder = Mock()
  192. room_alias_str = "#room:test"
  193. self.hs.config.auto_join_rooms = [room_alias_str]
  194. # When:-
  195. # * the user is registered and post consent actions are called
  196. user_id = self.get_success(self.handler.register_user(localpart="jeff"))
  197. self.get_success(self.handler.post_consent_actions(user_id))
  198. # Then:-
  199. # * Ensure that they have not been joined to the room
  200. rooms = self.get_success(self.store.get_rooms_for_user(user_id))
  201. self.assertEqual(len(rooms), 0)
  202. def test_register_support_user(self):
  203. user_id = self.get_success(
  204. self.handler.register_user(localpart="user", user_type=UserTypes.SUPPORT)
  205. )
  206. d = self.store.is_support_user(user_id)
  207. self.assertTrue(self.get_success(d))
  208. def test_register_not_support_user(self):
  209. user_id = self.get_success(self.handler.register_user(localpart="user"))
  210. d = self.store.is_support_user(user_id)
  211. self.assertFalse(self.get_success(d))
  212. def test_invalid_user_id_length(self):
  213. invalid_user_id = "x" * 256
  214. self.get_failure(
  215. self.handler.register_user(localpart=invalid_user_id), SynapseError
  216. )
  217. async def get_or_create_user(
  218. self, requester, localpart, displayname, password_hash=None
  219. ):
  220. """Creates a new user if the user does not exist,
  221. else revokes all previous access tokens and generates a new one.
  222. XXX: this used to be in the main codebase, but was only used by this file,
  223. so got moved here. TODO: get rid of it, probably
  224. Args:
  225. localpart : The local part of the user ID to register. If None,
  226. one will be randomly generated.
  227. Returns:
  228. A tuple of (user_id, access_token).
  229. """
  230. if localpart is None:
  231. raise SynapseError(400, "Request must include user id")
  232. await self.hs.get_auth().check_auth_blocking()
  233. need_register = True
  234. try:
  235. await self.handler.check_username(localpart)
  236. except SynapseError as e:
  237. if e.errcode == Codes.USER_IN_USE:
  238. need_register = False
  239. else:
  240. raise
  241. user = UserID(localpart, self.hs.hostname)
  242. user_id = user.to_string()
  243. token = self.macaroon_generator.generate_access_token(user_id)
  244. if need_register:
  245. await self.handler.register_with_store(
  246. user_id=user_id,
  247. password_hash=password_hash,
  248. create_profile_with_displayname=user.localpart,
  249. )
  250. else:
  251. await self.hs.get_auth_handler().delete_access_tokens_for_user(user_id)
  252. await self.store.add_access_token_to_user(
  253. user_id=user_id, token=token, device_id=None, valid_until_ms=None
  254. )
  255. if displayname is not None:
  256. # logger.info("setting user display name: %s -> %s", user_id, displayname)
  257. await self.hs.get_profile_handler().set_displayname(
  258. user, requester, displayname, by_admin=True
  259. )
  260. return user_id, token