test_register.py 29 KB

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