test_register.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  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("test")
  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_support_user_exists(self):
  148. room_alias_str = "#room:test"
  149. self.hs.config.auto_join_rooms = [room_alias_str]
  150. self.store.is_support_user = Mock(return_value=True)
  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_where_no_consent(self):
  158. """Test to ensure that the first user is not auto-joined to a room if
  159. they have not given general consent.
  160. """
  161. # Given:-
  162. # * a user must give consent,
  163. # * they have not given that consent
  164. # * The server is configured to auto-join to a room
  165. # (and autocreate if necessary)
  166. event_creation_handler = self.hs.get_event_creation_handler()
  167. # (Messing with the internals of event_creation_handler is fragile
  168. # but can't see a better way to do this. One option could be to subclass
  169. # the test with custom config.)
  170. event_creation_handler._block_events_without_consent_error = "Error"
  171. event_creation_handler._consent_uri_builder = Mock()
  172. room_alias_str = "#room:test"
  173. self.hs.config.auto_join_rooms = [room_alias_str]
  174. # When:-
  175. # * the user is registered and post consent actions are called
  176. user_id = self.get_success(self.handler.register_user(localpart="jeff"))
  177. self.get_success(self.handler.post_consent_actions(user_id))
  178. # Then:-
  179. # * Ensure that they have not been joined to the room
  180. rooms = self.get_success(self.store.get_rooms_for_user(user_id))
  181. self.assertEqual(len(rooms), 0)
  182. def test_register_support_user(self):
  183. user_id = self.get_success(
  184. self.handler.register_user(localpart="user", user_type=UserTypes.SUPPORT)
  185. )
  186. d = self.store.is_support_user(user_id)
  187. self.assertTrue(self.get_success(d))
  188. def test_register_not_support_user(self):
  189. user_id = self.get_success(self.handler.register_user(localpart="user"))
  190. d = self.store.is_support_user(user_id)
  191. self.assertFalse(self.get_success(d))
  192. def test_invalid_user_id_length(self):
  193. invalid_user_id = "x" * 256
  194. self.get_failure(
  195. self.handler.register_user(localpart=invalid_user_id), SynapseError
  196. )
  197. @defer.inlineCallbacks
  198. def get_or_create_user(self, requester, localpart, displayname, password_hash=None):
  199. """Creates a new user if the user does not exist,
  200. else revokes all previous access tokens and generates a new one.
  201. XXX: this used to be in the main codebase, but was only used by this file,
  202. so got moved here. TODO: get rid of it, probably
  203. Args:
  204. localpart : The local part of the user ID to register. If None,
  205. one will be randomly generated.
  206. Returns:
  207. A tuple of (user_id, access_token).
  208. Raises:
  209. RegistrationError if there was a problem registering.
  210. """
  211. if localpart is None:
  212. raise SynapseError(400, "Request must include user id")
  213. yield self.hs.get_auth().check_auth_blocking()
  214. need_register = True
  215. try:
  216. yield self.handler.check_username(localpart)
  217. except SynapseError as e:
  218. if e.errcode == Codes.USER_IN_USE:
  219. need_register = False
  220. else:
  221. raise
  222. user = UserID(localpart, self.hs.hostname)
  223. user_id = user.to_string()
  224. token = self.macaroon_generator.generate_access_token(user_id)
  225. if need_register:
  226. yield self.handler.register_with_store(
  227. user_id=user_id,
  228. password_hash=password_hash,
  229. create_profile_with_displayname=user.localpart,
  230. )
  231. else:
  232. yield self.hs.get_auth_handler().delete_access_tokens_for_user(user_id)
  233. yield self.store.add_access_token_to_user(
  234. user_id=user_id, token=token, device_id=None, valid_until_ms=None
  235. )
  236. if displayname is not None:
  237. # logger.info("setting user display name: %s -> %s", user_id, displayname)
  238. yield self.hs.get_profile_handler().set_displayname(
  239. user, requester, displayname, by_admin=True
  240. )
  241. return (user_id, token)