test_register.py 31 KB

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