test_register.py 31 KB

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