1
0

test_register.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783
  1. # Copyright 2015, 2016 OpenMarket Ltd
  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 unittest.mock import Mock
  15. from synapse.api.auth import Auth
  16. from synapse.api.constants import UserTypes
  17. from synapse.api.errors import (
  18. CodeMessageException,
  19. Codes,
  20. ResourceLimitError,
  21. SynapseError,
  22. )
  23. from synapse.events.spamcheck import load_legacy_spam_checkers
  24. from synapse.spam_checker_api import RegistrationBehaviour
  25. from synapse.types import RoomAlias, RoomID, UserID, create_requester
  26. from tests.test_utils import make_awaitable
  27. from tests.unittest import override_config
  28. from tests.utils import mock_getRawHeaders
  29. from .. import unittest
  30. class TestSpamChecker:
  31. def __init__(self, config, api):
  32. api.register_spam_checker_callbacks(
  33. check_registration_for_spam=self.check_registration_for_spam,
  34. )
  35. @staticmethod
  36. def parse_config(config):
  37. return config
  38. async def check_registration_for_spam(
  39. self,
  40. email_threepid,
  41. username,
  42. request_info,
  43. auth_provider_id,
  44. ):
  45. pass
  46. class DenyAll(TestSpamChecker):
  47. async def check_registration_for_spam(
  48. self,
  49. email_threepid,
  50. username,
  51. request_info,
  52. auth_provider_id,
  53. ):
  54. return RegistrationBehaviour.DENY
  55. class BanAll(TestSpamChecker):
  56. async def check_registration_for_spam(
  57. self,
  58. email_threepid,
  59. username,
  60. request_info,
  61. auth_provider_id,
  62. ):
  63. return RegistrationBehaviour.SHADOW_BAN
  64. class BanBadIdPUser(TestSpamChecker):
  65. async def check_registration_for_spam(
  66. self, email_threepid, username, request_info, auth_provider_id=None
  67. ):
  68. # Reject any user coming from CAS and whose username contains profanity
  69. if auth_provider_id == "cas" and "flimflob" in username:
  70. return RegistrationBehaviour.DENY
  71. return RegistrationBehaviour.ALLOW
  72. class TestLegacyRegistrationSpamChecker:
  73. def __init__(self, config, api):
  74. pass
  75. async def check_registration_for_spam(
  76. self,
  77. email_threepid,
  78. username,
  79. request_info,
  80. ):
  81. pass
  82. class LegacyAllowAll(TestLegacyRegistrationSpamChecker):
  83. async def check_registration_for_spam(
  84. self,
  85. email_threepid,
  86. username,
  87. request_info,
  88. ):
  89. return RegistrationBehaviour.ALLOW
  90. class LegacyDenyAll(TestLegacyRegistrationSpamChecker):
  91. async def check_registration_for_spam(
  92. self,
  93. email_threepid,
  94. username,
  95. request_info,
  96. ):
  97. return RegistrationBehaviour.DENY
  98. class RegistrationTestCase(unittest.HomeserverTestCase):
  99. """Tests the RegistrationHandler."""
  100. def make_homeserver(self, reactor, clock):
  101. hs_config = self.default_config()
  102. # some of the tests rely on us having a user consent version
  103. hs_config.setdefault("user_consent", {}).update(
  104. {
  105. "version": "test_consent_version",
  106. "template_dir": ".",
  107. }
  108. )
  109. hs_config["max_mau_value"] = 50
  110. hs_config["limit_usage_by_mau"] = True
  111. # Don't attempt to reach out over federation.
  112. self.mock_federation_client = Mock()
  113. self.mock_federation_client.make_query.side_effect = CodeMessageException(
  114. 500, ""
  115. )
  116. hs = self.setup_test_homeserver(
  117. config=hs_config, federation_client=self.mock_federation_client
  118. )
  119. load_legacy_spam_checkers(hs)
  120. module_api = hs.get_module_api()
  121. for module, config in hs.config.modules.loaded_modules:
  122. module(config=config, api=module_api)
  123. return hs
  124. def prepare(self, reactor, clock, hs):
  125. self.handler = self.hs.get_registration_handler()
  126. self.store = self.hs.get_datastore()
  127. self.lots_of_users = 100
  128. self.small_number_of_users = 1
  129. self.requester = create_requester("@requester:test")
  130. def test_user_is_created_and_logged_in_if_doesnt_exist(self):
  131. frank = UserID.from_string("@frank:test")
  132. user_id = frank.to_string()
  133. requester = create_requester(user_id)
  134. result_user_id, result_token = self.get_success(
  135. self.get_or_create_user(requester, frank.localpart, "Frankie")
  136. )
  137. self.assertEquals(result_user_id, user_id)
  138. self.assertIsInstance(result_token, str)
  139. self.assertGreater(len(result_token), 20)
  140. def test_if_user_exists(self):
  141. store = self.hs.get_datastore()
  142. frank = UserID.from_string("@frank:test")
  143. self.get_success(
  144. store.register_user(user_id=frank.to_string(), password_hash=None)
  145. )
  146. local_part = frank.localpart
  147. user_id = frank.to_string()
  148. requester = create_requester(user_id)
  149. result_user_id, result_token = self.get_success(
  150. self.get_or_create_user(requester, local_part, None)
  151. )
  152. self.assertEquals(result_user_id, user_id)
  153. self.assertTrue(result_token is not None)
  154. @override_config({"limit_usage_by_mau": False})
  155. def test_mau_limits_when_disabled(self):
  156. # Ensure does not throw exception
  157. self.get_success(self.get_or_create_user(self.requester, "a", "display_name"))
  158. @override_config({"limit_usage_by_mau": True})
  159. def test_get_or_create_user_mau_not_blocked(self):
  160. self.store.count_monthly_users = Mock(
  161. return_value=make_awaitable(self.hs.config.server.max_mau_value - 1)
  162. )
  163. # Ensure does not throw exception
  164. self.get_success(self.get_or_create_user(self.requester, "c", "User"))
  165. @override_config({"limit_usage_by_mau": True})
  166. def test_get_or_create_user_mau_blocked(self):
  167. self.store.get_monthly_active_count = Mock(
  168. return_value=make_awaitable(self.lots_of_users)
  169. )
  170. self.get_failure(
  171. self.get_or_create_user(self.requester, "b", "display_name"),
  172. ResourceLimitError,
  173. )
  174. self.store.get_monthly_active_count = Mock(
  175. return_value=make_awaitable(self.hs.config.server.max_mau_value)
  176. )
  177. self.get_failure(
  178. self.get_or_create_user(self.requester, "b", "display_name"),
  179. ResourceLimitError,
  180. )
  181. @override_config({"limit_usage_by_mau": True})
  182. def test_register_mau_blocked(self):
  183. self.store.get_monthly_active_count = Mock(
  184. return_value=make_awaitable(self.lots_of_users)
  185. )
  186. self.get_failure(
  187. self.handler.register_user(localpart="local_part"), ResourceLimitError
  188. )
  189. self.store.get_monthly_active_count = Mock(
  190. return_value=make_awaitable(self.hs.config.server.max_mau_value)
  191. )
  192. self.get_failure(
  193. self.handler.register_user(localpart="local_part"), ResourceLimitError
  194. )
  195. @override_config(
  196. {"auto_join_rooms": ["#room:test"], "auto_join_rooms_for_guests": False}
  197. )
  198. def test_auto_join_rooms_for_guests(self):
  199. user_id = self.get_success(
  200. self.handler.register_user(localpart="jeff", make_guest=True),
  201. )
  202. rooms = self.get_success(self.store.get_rooms_for_user(user_id))
  203. self.assertEqual(len(rooms), 0)
  204. @override_config({"auto_join_rooms": ["#room:test"]})
  205. def test_auto_create_auto_join_rooms(self):
  206. room_alias_str = "#room:test"
  207. user_id = self.get_success(self.handler.register_user(localpart="jeff"))
  208. rooms = self.get_success(self.store.get_rooms_for_user(user_id))
  209. directory_handler = self.hs.get_directory_handler()
  210. room_alias = RoomAlias.from_string(room_alias_str)
  211. room_id = self.get_success(directory_handler.get_association(room_alias))
  212. self.assertTrue(room_id["room_id"] in rooms)
  213. self.assertEqual(len(rooms), 1)
  214. @override_config({"auto_join_rooms": []})
  215. def test_auto_create_auto_join_rooms_with_no_rooms(self):
  216. frank = UserID.from_string("@frank:test")
  217. user_id = self.get_success(self.handler.register_user(frank.localpart))
  218. self.assertEqual(user_id, frank.to_string())
  219. rooms = self.get_success(self.store.get_rooms_for_user(user_id))
  220. self.assertEqual(len(rooms), 0)
  221. @override_config({"auto_join_rooms": ["#room:another"]})
  222. def test_auto_create_auto_join_where_room_is_another_domain(self):
  223. frank = UserID.from_string("@frank:test")
  224. user_id = self.get_success(self.handler.register_user(frank.localpart))
  225. self.assertEqual(user_id, frank.to_string())
  226. rooms = self.get_success(self.store.get_rooms_for_user(user_id))
  227. self.assertEqual(len(rooms), 0)
  228. @override_config(
  229. {"auto_join_rooms": ["#room:test"], "autocreate_auto_join_rooms": False}
  230. )
  231. def test_auto_create_auto_join_where_auto_create_is_false(self):
  232. user_id = self.get_success(self.handler.register_user(localpart="jeff"))
  233. rooms = self.get_success(self.store.get_rooms_for_user(user_id))
  234. self.assertEqual(len(rooms), 0)
  235. @override_config({"auto_join_rooms": ["#room:test"]})
  236. def test_auto_create_auto_join_rooms_when_user_is_not_a_real_user(self):
  237. room_alias_str = "#room:test"
  238. self.store.is_real_user = Mock(return_value=make_awaitable(False))
  239. user_id = self.get_success(self.handler.register_user(localpart="support"))
  240. rooms = self.get_success(self.store.get_rooms_for_user(user_id))
  241. self.assertEqual(len(rooms), 0)
  242. directory_handler = self.hs.get_directory_handler()
  243. room_alias = RoomAlias.from_string(room_alias_str)
  244. self.get_failure(directory_handler.get_association(room_alias), SynapseError)
  245. @override_config({"auto_join_rooms": ["#room:test"]})
  246. def test_auto_create_auto_join_rooms_when_user_is_the_first_real_user(self):
  247. room_alias_str = "#room:test"
  248. self.store.count_real_users = Mock(return_value=make_awaitable(1))
  249. self.store.is_real_user = Mock(return_value=make_awaitable(True))
  250. user_id = self.get_success(self.handler.register_user(localpart="real"))
  251. rooms = self.get_success(self.store.get_rooms_for_user(user_id))
  252. directory_handler = self.hs.get_directory_handler()
  253. room_alias = RoomAlias.from_string(room_alias_str)
  254. room_id = self.get_success(directory_handler.get_association(room_alias))
  255. self.assertTrue(room_id["room_id"] in rooms)
  256. self.assertEqual(len(rooms), 1)
  257. @override_config({"auto_join_rooms": ["#room:test"]})
  258. def test_auto_create_auto_join_rooms_when_user_is_not_the_first_real_user(self):
  259. self.store.count_real_users = Mock(return_value=make_awaitable(2))
  260. self.store.is_real_user = Mock(return_value=make_awaitable(True))
  261. user_id = self.get_success(self.handler.register_user(localpart="real"))
  262. rooms = self.get_success(self.store.get_rooms_for_user(user_id))
  263. self.assertEqual(len(rooms), 0)
  264. @override_config(
  265. {
  266. "auto_join_rooms": ["#room:test"],
  267. "autocreate_auto_join_rooms_federated": False,
  268. }
  269. )
  270. def test_auto_create_auto_join_rooms_federated(self):
  271. """
  272. Auto-created rooms that are private require an invite to go to the user
  273. (instead of directly joining it).
  274. """
  275. room_alias_str = "#room:test"
  276. user_id = self.get_success(self.handler.register_user(localpart="jeff"))
  277. # Ensure the room was created.
  278. directory_handler = self.hs.get_directory_handler()
  279. room_alias = RoomAlias.from_string(room_alias_str)
  280. room_id = self.get_success(directory_handler.get_association(room_alias))
  281. # Ensure the room is properly not federated.
  282. room = self.get_success(self.store.get_room_with_stats(room_id["room_id"]))
  283. self.assertFalse(room["federatable"])
  284. self.assertFalse(room["public"])
  285. self.assertEqual(room["join_rules"], "public")
  286. self.assertIsNone(room["guest_access"])
  287. # The user should be in the room.
  288. rooms = self.get_success(self.store.get_rooms_for_user(user_id))
  289. self.assertIn(room_id["room_id"], rooms)
  290. @override_config(
  291. {"auto_join_rooms": ["#room:test"], "auto_join_mxid_localpart": "support"}
  292. )
  293. def test_auto_join_mxid_localpart(self):
  294. """
  295. Ensure the user still needs up in the room created by a different user.
  296. """
  297. # Ensure the support user exists.
  298. inviter = "@support:test"
  299. room_alias_str = "#room:test"
  300. user_id = self.get_success(self.handler.register_user(localpart="jeff"))
  301. # Ensure the room was created.
  302. directory_handler = self.hs.get_directory_handler()
  303. room_alias = RoomAlias.from_string(room_alias_str)
  304. room_id = self.get_success(directory_handler.get_association(room_alias))
  305. # Ensure the room is properly a public room.
  306. room = self.get_success(self.store.get_room_with_stats(room_id["room_id"]))
  307. self.assertEqual(room["join_rules"], "public")
  308. # Both users should be in the room.
  309. rooms = self.get_success(self.store.get_rooms_for_user(inviter))
  310. self.assertIn(room_id["room_id"], rooms)
  311. rooms = self.get_success(self.store.get_rooms_for_user(user_id))
  312. self.assertIn(room_id["room_id"], rooms)
  313. # Register a second user, which should also end up in the room.
  314. user_id = self.get_success(self.handler.register_user(localpart="bob"))
  315. rooms = self.get_success(self.store.get_rooms_for_user(user_id))
  316. self.assertIn(room_id["room_id"], rooms)
  317. @override_config(
  318. {
  319. "auto_join_rooms": ["#room:test"],
  320. "autocreate_auto_join_room_preset": "private_chat",
  321. "auto_join_mxid_localpart": "support",
  322. }
  323. )
  324. def test_auto_create_auto_join_room_preset(self):
  325. """
  326. Auto-created rooms that are private require an invite to go to the user
  327. (instead of directly joining it).
  328. """
  329. # Ensure the support user exists.
  330. inviter = "@support:test"
  331. room_alias_str = "#room:test"
  332. user_id = self.get_success(self.handler.register_user(localpart="jeff"))
  333. # Ensure the room was created.
  334. directory_handler = self.hs.get_directory_handler()
  335. room_alias = RoomAlias.from_string(room_alias_str)
  336. room_id = self.get_success(directory_handler.get_association(room_alias))
  337. # Ensure the room is properly a private room.
  338. room = self.get_success(self.store.get_room_with_stats(room_id["room_id"]))
  339. self.assertFalse(room["public"])
  340. self.assertEqual(room["join_rules"], "invite")
  341. self.assertEqual(room["guest_access"], "can_join")
  342. # Both users should be in the room.
  343. rooms = self.get_success(self.store.get_rooms_for_user(inviter))
  344. self.assertIn(room_id["room_id"], rooms)
  345. rooms = self.get_success(self.store.get_rooms_for_user(user_id))
  346. self.assertIn(room_id["room_id"], rooms)
  347. # Register a second user, which should also end up in the room.
  348. user_id = self.get_success(self.handler.register_user(localpart="bob"))
  349. rooms = self.get_success(self.store.get_rooms_for_user(user_id))
  350. self.assertIn(room_id["room_id"], rooms)
  351. @override_config(
  352. {
  353. "auto_join_rooms": ["#room:test"],
  354. "autocreate_auto_join_room_preset": "private_chat",
  355. "auto_join_mxid_localpart": "support",
  356. }
  357. )
  358. def test_auto_create_auto_join_room_preset_guest(self):
  359. """
  360. Auto-created rooms that are private require an invite to go to the user
  361. (instead of directly joining it).
  362. This should also work for guests.
  363. """
  364. inviter = "@support:test"
  365. room_alias_str = "#room:test"
  366. user_id = self.get_success(
  367. self.handler.register_user(localpart="jeff", make_guest=True)
  368. )
  369. # Ensure the room was created.
  370. directory_handler = self.hs.get_directory_handler()
  371. room_alias = RoomAlias.from_string(room_alias_str)
  372. room_id = self.get_success(directory_handler.get_association(room_alias))
  373. # Ensure the room is properly a private room.
  374. room = self.get_success(self.store.get_room_with_stats(room_id["room_id"]))
  375. self.assertFalse(room["public"])
  376. self.assertEqual(room["join_rules"], "invite")
  377. self.assertEqual(room["guest_access"], "can_join")
  378. # Both users should be in the room.
  379. rooms = self.get_success(self.store.get_rooms_for_user(inviter))
  380. self.assertIn(room_id["room_id"], rooms)
  381. rooms = self.get_success(self.store.get_rooms_for_user(user_id))
  382. self.assertIn(room_id["room_id"], rooms)
  383. @override_config(
  384. {
  385. "auto_join_rooms": ["#room:test"],
  386. "autocreate_auto_join_room_preset": "private_chat",
  387. "auto_join_mxid_localpart": "support",
  388. }
  389. )
  390. def test_auto_create_auto_join_room_preset_invalid_permissions(self):
  391. """
  392. Auto-created rooms that are private require an invite, check that
  393. registration doesn't completely break if the inviter doesn't have proper
  394. permissions.
  395. """
  396. inviter = "@support:test"
  397. # Register an initial user to create the room and such (essentially this
  398. # is a subset of test_auto_create_auto_join_room_preset).
  399. room_alias_str = "#room:test"
  400. user_id = self.get_success(self.handler.register_user(localpart="jeff"))
  401. # Ensure the room was created.
  402. directory_handler = self.hs.get_directory_handler()
  403. room_alias = RoomAlias.from_string(room_alias_str)
  404. room_id = self.get_success(directory_handler.get_association(room_alias))
  405. # Ensure the room exists.
  406. self.get_success(self.store.get_room_with_stats(room_id["room_id"]))
  407. # Both users should be in the room.
  408. rooms = self.get_success(self.store.get_rooms_for_user(inviter))
  409. self.assertIn(room_id["room_id"], rooms)
  410. rooms = self.get_success(self.store.get_rooms_for_user(user_id))
  411. self.assertIn(room_id["room_id"], rooms)
  412. # Lower the permissions of the inviter.
  413. event_creation_handler = self.hs.get_event_creation_handler()
  414. requester = create_requester(inviter)
  415. event, context = self.get_success(
  416. event_creation_handler.create_event(
  417. requester,
  418. {
  419. "type": "m.room.power_levels",
  420. "state_key": "",
  421. "room_id": room_id["room_id"],
  422. "content": {"invite": 100, "users": {inviter: 0}},
  423. "sender": inviter,
  424. },
  425. )
  426. )
  427. self.get_success(
  428. event_creation_handler.handle_new_client_event(requester, event, context)
  429. )
  430. # Register a second user, which won't be be in the room (or even have an invite)
  431. # since the inviter no longer has the proper permissions.
  432. user_id = self.get_success(self.handler.register_user(localpart="bob"))
  433. # This user should not be in any rooms.
  434. rooms = self.get_success(self.store.get_rooms_for_user(user_id))
  435. invited_rooms = self.get_success(
  436. self.store.get_invited_rooms_for_local_user(user_id)
  437. )
  438. self.assertEqual(rooms, set())
  439. self.assertEqual(invited_rooms, [])
  440. @override_config(
  441. {
  442. "user_consent": {
  443. "block_events_error": "Error",
  444. "require_at_registration": True,
  445. },
  446. "form_secret": "53cr3t",
  447. "public_baseurl": "http://test",
  448. "auto_join_rooms": ["#room:test"],
  449. },
  450. )
  451. def test_auto_create_auto_join_where_no_consent(self):
  452. """Test to ensure that the first user is not auto-joined to a room if
  453. they have not given general consent.
  454. """
  455. # Given:-
  456. # * a user must give consent,
  457. # * they have not given that consent
  458. # * The server is configured to auto-join to a room
  459. # (and autocreate if necessary)
  460. # When:-
  461. # * the user is registered
  462. user_id = self.get_success(self.handler.register_user(localpart="jeff"))
  463. # Then:-
  464. # * Ensure that they have not been joined to the room
  465. rooms = self.get_success(self.store.get_rooms_for_user(user_id))
  466. self.assertEqual(len(rooms), 0)
  467. # The user provides consent; ensure they are now in the rooms.
  468. self.get_success(self.handler.post_consent_actions(user_id))
  469. rooms = self.get_success(self.store.get_rooms_for_user(user_id))
  470. self.assertEqual(len(rooms), 1)
  471. def test_register_support_user(self):
  472. user_id = self.get_success(
  473. self.handler.register_user(localpart="user", user_type=UserTypes.SUPPORT)
  474. )
  475. d = self.store.is_support_user(user_id)
  476. self.assertTrue(self.get_success(d))
  477. def test_register_not_support_user(self):
  478. user_id = self.get_success(self.handler.register_user(localpart="user"))
  479. d = self.store.is_support_user(user_id)
  480. self.assertFalse(self.get_success(d))
  481. def test_invalid_user_id_length(self):
  482. invalid_user_id = "x" * 256
  483. self.get_failure(
  484. self.handler.register_user(localpart=invalid_user_id), SynapseError
  485. )
  486. @override_config(
  487. {
  488. "modules": [
  489. {
  490. "module": TestSpamChecker.__module__ + ".DenyAll",
  491. }
  492. ]
  493. }
  494. )
  495. def test_spam_checker_deny(self):
  496. """A spam checker can deny registration, which results in an error."""
  497. self.get_failure(self.handler.register_user(localpart="user"), SynapseError)
  498. @override_config(
  499. {
  500. "spam_checker": [
  501. {
  502. "module": TestSpamChecker.__module__ + ".LegacyAllowAll",
  503. }
  504. ]
  505. }
  506. )
  507. def test_spam_checker_legacy_allow(self):
  508. """Tests that a legacy spam checker implementing the legacy 3-arg version of the
  509. check_registration_for_spam callback is correctly called.
  510. In this test and the following one we test both success and failure to make sure
  511. any failure comes from the spam checker (and not something else failing in the
  512. call stack) and any success comes from the spam checker (and not because a
  513. misconfiguration prevented it from being loaded).
  514. """
  515. self.get_success(self.handler.register_user(localpart="user"))
  516. @override_config(
  517. {
  518. "spam_checker": [
  519. {
  520. "module": TestSpamChecker.__module__ + ".LegacyDenyAll",
  521. }
  522. ]
  523. }
  524. )
  525. def test_spam_checker_legacy_deny(self):
  526. """Tests that a legacy spam checker implementing the legacy 3-arg version of the
  527. check_registration_for_spam callback is correctly called.
  528. In this test and the previous one we test both success and failure to make sure
  529. any failure comes from the spam checker (and not something else failing in the
  530. call stack) and any success comes from the spam checker (and not because a
  531. misconfiguration prevented it from being loaded).
  532. """
  533. self.get_failure(self.handler.register_user(localpart="user"), SynapseError)
  534. @override_config(
  535. {
  536. "modules": [
  537. {
  538. "module": TestSpamChecker.__module__ + ".BanAll",
  539. }
  540. ]
  541. }
  542. )
  543. def test_spam_checker_shadow_ban(self):
  544. """A spam checker can choose to shadow-ban a user, which allows registration to succeed."""
  545. user_id = self.get_success(self.handler.register_user(localpart="user"))
  546. # Get an access token.
  547. token = "testtok"
  548. self.get_success(
  549. self.store.add_access_token_to_user(
  550. user_id=user_id, token=token, device_id=None, valid_until_ms=None
  551. )
  552. )
  553. # Ensure the user was marked as shadow-banned.
  554. request = Mock(args={})
  555. request.args[b"access_token"] = [token.encode("ascii")]
  556. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  557. auth = Auth(self.hs)
  558. requester = self.get_success(auth.get_user_by_req(request))
  559. self.assertTrue(requester.shadow_banned)
  560. @override_config(
  561. {
  562. "modules": [
  563. {
  564. "module": TestSpamChecker.__module__ + ".BanBadIdPUser",
  565. }
  566. ]
  567. }
  568. )
  569. def test_spam_checker_receives_sso_type(self):
  570. """Test rejecting registration based on SSO type"""
  571. f = self.get_failure(
  572. self.handler.register_user(localpart="bobflimflob", auth_provider_id="cas"),
  573. SynapseError,
  574. )
  575. exception = f.value
  576. # We return 429 from the spam checker for denied registrations
  577. self.assertIsInstance(exception, SynapseError)
  578. self.assertEqual(exception.code, 429)
  579. # Check the same username can register using SAML
  580. self.get_success(
  581. self.handler.register_user(localpart="bobflimflob", auth_provider_id="saml")
  582. )
  583. async def get_or_create_user(
  584. self, requester, localpart, displayname, password_hash=None
  585. ):
  586. """Creates a new user if the user does not exist,
  587. else revokes all previous access tokens and generates a new one.
  588. XXX: this used to be in the main codebase, but was only used by this file,
  589. so got moved here. TODO: get rid of it, probably
  590. Args:
  591. localpart : The local part of the user ID to register. If None,
  592. one will be randomly generated.
  593. Returns:
  594. A tuple of (user_id, access_token).
  595. """
  596. if localpart is None:
  597. raise SynapseError(400, "Request must include user id")
  598. await self.hs.get_auth().check_auth_blocking()
  599. need_register = True
  600. try:
  601. await self.handler.check_username(localpart)
  602. except SynapseError as e:
  603. if e.errcode == Codes.USER_IN_USE:
  604. need_register = False
  605. else:
  606. raise
  607. user = UserID(localpart, self.hs.hostname)
  608. user_id = user.to_string()
  609. token = self.hs.get_auth_handler().generate_access_token(user)
  610. if need_register:
  611. await self.handler.register_with_store(
  612. user_id=user_id,
  613. password_hash=password_hash,
  614. create_profile_with_displayname=user.localpart,
  615. )
  616. else:
  617. await self.hs.get_auth_handler().delete_access_tokens_for_user(user_id)
  618. await self.store.add_access_token_to_user(
  619. user_id=user_id, token=token, device_id=None, valid_until_ms=None
  620. )
  621. if displayname is not None:
  622. # logger.info("setting user display name: %s -> %s", user_id, displayname)
  623. await self.hs.get_profile_handler().set_displayname(
  624. user, requester, displayname, by_admin=True
  625. )
  626. return user_id, token
  627. class RemoteAutoJoinTestCase(unittest.HomeserverTestCase):
  628. """Tests auto-join on remote rooms."""
  629. def make_homeserver(self, reactor, clock):
  630. self.room_id = "!roomid:remotetest"
  631. async def update_membership(*args, **kwargs):
  632. pass
  633. async def lookup_room_alias(*args, **kwargs):
  634. return RoomID.from_string(self.room_id), ["remotetest"]
  635. self.room_member_handler = Mock(spec=["update_membership", "lookup_room_alias"])
  636. self.room_member_handler.update_membership.side_effect = update_membership
  637. self.room_member_handler.lookup_room_alias.side_effect = lookup_room_alias
  638. hs = self.setup_test_homeserver(room_member_handler=self.room_member_handler)
  639. return hs
  640. def prepare(self, reactor, clock, hs):
  641. self.handler = self.hs.get_registration_handler()
  642. self.store = self.hs.get_datastore()
  643. @override_config({"auto_join_rooms": ["#room:remotetest"]})
  644. def test_auto_create_auto_join_remote_room(self):
  645. """Tests that we don't attempt to create remote rooms, and that we don't attempt
  646. to invite ourselves to rooms we're not in."""
  647. # Register a first user; this should call _create_and_join_rooms
  648. self.get_success(self.handler.register_user(localpart="jeff"))
  649. _, kwargs = self.room_member_handler.update_membership.call_args
  650. self.assertEqual(kwargs["room_id"], self.room_id)
  651. self.assertEqual(kwargs["action"], "join")
  652. self.assertEqual(kwargs["remote_room_hosts"], ["remotetest"])
  653. # Register a second user; this should call _join_rooms
  654. self.get_success(self.handler.register_user(localpart="jeff2"))
  655. _, kwargs = self.room_member_handler.update_membership.call_args
  656. self.assertEqual(kwargs["room_id"], self.room_id)
  657. self.assertEqual(kwargs["action"], "join")
  658. self.assertEqual(kwargs["remote_room_hosts"], ["remotetest"])