test_password_providers.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008
  1. # Copyright 2020 The Matrix.org Foundation C.I.C.
  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. """Tests for the password_auth_provider interface"""
  15. from typing import Any, Type, Union
  16. from unittest.mock import Mock
  17. import synapse
  18. from synapse.api.constants import LoginType
  19. from synapse.api.errors import Codes
  20. from synapse.handlers.auth import load_legacy_password_auth_providers
  21. from synapse.module_api import ModuleApi
  22. from synapse.rest.client import account, devices, login, logout, register
  23. from synapse.types import JsonDict, UserID
  24. from tests import unittest
  25. from tests.server import FakeChannel
  26. from tests.test_utils import make_awaitable
  27. from tests.unittest import override_config
  28. # Login flows we expect to appear in the list after the normal ones.
  29. ADDITIONAL_LOGIN_FLOWS = [
  30. {"type": "m.login.application_service"},
  31. ]
  32. # a mock instance which the dummy auth providers delegate to, so we can see what's going
  33. # on
  34. mock_password_provider = Mock()
  35. class LegacyPasswordOnlyAuthProvider:
  36. """A legacy password_provider which only implements `check_password`."""
  37. @staticmethod
  38. def parse_config(self):
  39. pass
  40. def __init__(self, config, account_handler):
  41. pass
  42. def check_password(self, *args):
  43. return mock_password_provider.check_password(*args)
  44. class LegacyCustomAuthProvider:
  45. """A legacy password_provider which implements a custom login type."""
  46. @staticmethod
  47. def parse_config(self):
  48. pass
  49. def __init__(self, config, account_handler):
  50. pass
  51. def get_supported_login_types(self):
  52. return {"test.login_type": ["test_field"]}
  53. def check_auth(self, *args):
  54. return mock_password_provider.check_auth(*args)
  55. class CustomAuthProvider:
  56. """A module which registers password_auth_provider callbacks for a custom login type."""
  57. @staticmethod
  58. def parse_config(self):
  59. pass
  60. def __init__(self, config, api: ModuleApi):
  61. api.register_password_auth_provider_callbacks(
  62. auth_checkers={("test.login_type", ("test_field",)): self.check_auth}
  63. )
  64. def check_auth(self, *args):
  65. return mock_password_provider.check_auth(*args)
  66. class LegacyPasswordCustomAuthProvider:
  67. """A password_provider which implements password login via `check_auth`, as well
  68. as a custom type."""
  69. @staticmethod
  70. def parse_config(self):
  71. pass
  72. def __init__(self, config, account_handler):
  73. pass
  74. def get_supported_login_types(self):
  75. return {"m.login.password": ["password"], "test.login_type": ["test_field"]}
  76. def check_auth(self, *args):
  77. return mock_password_provider.check_auth(*args)
  78. class PasswordCustomAuthProvider:
  79. """A module which registers password_auth_provider callbacks for a custom login type.
  80. as well as a password login"""
  81. @staticmethod
  82. def parse_config(self):
  83. pass
  84. def __init__(self, config, api: ModuleApi):
  85. api.register_password_auth_provider_callbacks(
  86. auth_checkers={
  87. ("test.login_type", ("test_field",)): self.check_auth,
  88. ("m.login.password", ("password",)): self.check_auth,
  89. }
  90. )
  91. def check_auth(self, *args):
  92. return mock_password_provider.check_auth(*args)
  93. def check_pass(self, *args):
  94. return mock_password_provider.check_password(*args)
  95. def legacy_providers_config(*providers: Type[Any]) -> dict:
  96. """Returns a config dict that will enable the given legacy password auth providers"""
  97. return {
  98. "password_providers": [
  99. {"module": "%s.%s" % (__name__, provider.__qualname__), "config": {}}
  100. for provider in providers
  101. ]
  102. }
  103. def providers_config(*providers: Type[Any]) -> dict:
  104. """Returns a config dict that will enable the given modules"""
  105. return {
  106. "modules": [
  107. {"module": "%s.%s" % (__name__, provider.__qualname__), "config": {}}
  108. for provider in providers
  109. ]
  110. }
  111. class PasswordAuthProviderTests(unittest.HomeserverTestCase):
  112. servlets = [
  113. synapse.rest.admin.register_servlets,
  114. login.register_servlets,
  115. devices.register_servlets,
  116. logout.register_servlets,
  117. register.register_servlets,
  118. account.register_servlets,
  119. ]
  120. CALLBACK_USERNAME = "get_username_for_registration"
  121. CALLBACK_DISPLAYNAME = "get_displayname_for_registration"
  122. def setUp(self):
  123. # we use a global mock device, so make sure we are starting with a clean slate
  124. mock_password_provider.reset_mock()
  125. super().setUp()
  126. def make_homeserver(self, reactor, clock):
  127. hs = self.setup_test_homeserver()
  128. # Load the modules into the homeserver
  129. module_api = hs.get_module_api()
  130. for module, config in hs.config.modules.loaded_modules:
  131. module(config=config, api=module_api)
  132. load_legacy_password_auth_providers(hs)
  133. return hs
  134. @override_config(legacy_providers_config(LegacyPasswordOnlyAuthProvider))
  135. def test_password_only_auth_progiver_login_legacy(self):
  136. self.password_only_auth_provider_login_test_body()
  137. def password_only_auth_provider_login_test_body(self):
  138. # login flows should only have m.login.password
  139. flows = self._get_login_flows()
  140. self.assertEqual(flows, [{"type": "m.login.password"}] + ADDITIONAL_LOGIN_FLOWS)
  141. # check_password must return an awaitable
  142. mock_password_provider.check_password.return_value = make_awaitable(True)
  143. channel = self._send_password_login("u", "p")
  144. self.assertEqual(channel.code, 200, channel.result)
  145. self.assertEqual("@u:test", channel.json_body["user_id"])
  146. mock_password_provider.check_password.assert_called_once_with("@u:test", "p")
  147. mock_password_provider.reset_mock()
  148. # login with mxid should work too
  149. channel = self._send_password_login("@u:bz", "p")
  150. self.assertEqual(channel.code, 200, channel.result)
  151. self.assertEqual("@u:bz", channel.json_body["user_id"])
  152. mock_password_provider.check_password.assert_called_once_with("@u:bz", "p")
  153. mock_password_provider.reset_mock()
  154. # try a weird username / pass. Honestly it's unclear what we *expect* to happen
  155. # in these cases, but at least we can guard against the API changing
  156. # unexpectedly
  157. channel = self._send_password_login(" USER🙂NAME ", " pASS\U0001F622word ")
  158. self.assertEqual(channel.code, 200, channel.result)
  159. self.assertEqual("@ USER🙂NAME :test", channel.json_body["user_id"])
  160. mock_password_provider.check_password.assert_called_once_with(
  161. "@ USER🙂NAME :test", " pASS😢word "
  162. )
  163. @override_config(legacy_providers_config(LegacyPasswordOnlyAuthProvider))
  164. def test_password_only_auth_provider_ui_auth_legacy(self):
  165. self.password_only_auth_provider_ui_auth_test_body()
  166. def password_only_auth_provider_ui_auth_test_body(self):
  167. """UI Auth should delegate correctly to the password provider"""
  168. # create the user, otherwise access doesn't work
  169. module_api = self.hs.get_module_api()
  170. self.get_success(module_api.register_user("u"))
  171. # log in twice, to get two devices
  172. mock_password_provider.check_password.return_value = make_awaitable(True)
  173. tok1 = self.login("u", "p")
  174. self.login("u", "p", device_id="dev2")
  175. mock_password_provider.reset_mock()
  176. # have the auth provider deny the request to start with
  177. mock_password_provider.check_password.return_value = make_awaitable(False)
  178. # make the initial request which returns a 401
  179. session = self._start_delete_device_session(tok1, "dev2")
  180. mock_password_provider.check_password.assert_not_called()
  181. # Make another request providing the UI auth flow.
  182. channel = self._authed_delete_device(tok1, "dev2", session, "u", "p")
  183. self.assertEqual(channel.code, 401) # XXX why not a 403?
  184. self.assertEqual(channel.json_body["errcode"], "M_FORBIDDEN")
  185. mock_password_provider.check_password.assert_called_once_with("@u:test", "p")
  186. mock_password_provider.reset_mock()
  187. # Finally, check the request goes through when we allow it
  188. mock_password_provider.check_password.return_value = make_awaitable(True)
  189. channel = self._authed_delete_device(tok1, "dev2", session, "u", "p")
  190. self.assertEqual(channel.code, 200)
  191. mock_password_provider.check_password.assert_called_once_with("@u:test", "p")
  192. @override_config(legacy_providers_config(LegacyPasswordOnlyAuthProvider))
  193. def test_local_user_fallback_login_legacy(self):
  194. self.local_user_fallback_login_test_body()
  195. def local_user_fallback_login_test_body(self):
  196. """rejected login should fall back to local db"""
  197. self.register_user("localuser", "localpass")
  198. # check_password must return an awaitable
  199. mock_password_provider.check_password.return_value = make_awaitable(False)
  200. channel = self._send_password_login("u", "p")
  201. self.assertEqual(channel.code, 403, channel.result)
  202. channel = self._send_password_login("localuser", "localpass")
  203. self.assertEqual(channel.code, 200, channel.result)
  204. self.assertEqual("@localuser:test", channel.json_body["user_id"])
  205. @override_config(legacy_providers_config(LegacyPasswordOnlyAuthProvider))
  206. def test_local_user_fallback_ui_auth_legacy(self):
  207. self.local_user_fallback_ui_auth_test_body()
  208. def local_user_fallback_ui_auth_test_body(self):
  209. """rejected login should fall back to local db"""
  210. self.register_user("localuser", "localpass")
  211. # have the auth provider deny the request
  212. mock_password_provider.check_password.return_value = make_awaitable(False)
  213. # log in twice, to get two devices
  214. tok1 = self.login("localuser", "localpass")
  215. self.login("localuser", "localpass", device_id="dev2")
  216. mock_password_provider.check_password.reset_mock()
  217. # first delete should give a 401
  218. session = self._start_delete_device_session(tok1, "dev2")
  219. mock_password_provider.check_password.assert_not_called()
  220. # Wrong password
  221. channel = self._authed_delete_device(tok1, "dev2", session, "localuser", "xxx")
  222. self.assertEqual(channel.code, 401) # XXX why not a 403?
  223. self.assertEqual(channel.json_body["errcode"], "M_FORBIDDEN")
  224. mock_password_provider.check_password.assert_called_once_with(
  225. "@localuser:test", "xxx"
  226. )
  227. mock_password_provider.reset_mock()
  228. # Right password
  229. channel = self._authed_delete_device(
  230. tok1, "dev2", session, "localuser", "localpass"
  231. )
  232. self.assertEqual(channel.code, 200)
  233. mock_password_provider.check_password.assert_called_once_with(
  234. "@localuser:test", "localpass"
  235. )
  236. @override_config(
  237. {
  238. **legacy_providers_config(LegacyPasswordOnlyAuthProvider),
  239. "password_config": {"localdb_enabled": False},
  240. }
  241. )
  242. def test_no_local_user_fallback_login_legacy(self):
  243. self.no_local_user_fallback_login_test_body()
  244. def no_local_user_fallback_login_test_body(self):
  245. """localdb_enabled can block login with the local password"""
  246. self.register_user("localuser", "localpass")
  247. # check_password must return an awaitable
  248. mock_password_provider.check_password.return_value = make_awaitable(False)
  249. channel = self._send_password_login("localuser", "localpass")
  250. self.assertEqual(channel.code, 403)
  251. self.assertEqual(channel.json_body["errcode"], "M_FORBIDDEN")
  252. mock_password_provider.check_password.assert_called_once_with(
  253. "@localuser:test", "localpass"
  254. )
  255. @override_config(
  256. {
  257. **legacy_providers_config(LegacyPasswordOnlyAuthProvider),
  258. "password_config": {"localdb_enabled": False},
  259. }
  260. )
  261. def test_no_local_user_fallback_ui_auth_legacy(self):
  262. self.no_local_user_fallback_ui_auth_test_body()
  263. def no_local_user_fallback_ui_auth_test_body(self):
  264. """localdb_enabled can block ui auth with the local password"""
  265. self.register_user("localuser", "localpass")
  266. # allow login via the auth provider
  267. mock_password_provider.check_password.return_value = make_awaitable(True)
  268. # log in twice, to get two devices
  269. tok1 = self.login("localuser", "p")
  270. self.login("localuser", "p", device_id="dev2")
  271. mock_password_provider.check_password.reset_mock()
  272. # first delete should give a 401
  273. channel = self._delete_device(tok1, "dev2")
  274. self.assertEqual(channel.code, 401)
  275. # m.login.password UIA is permitted because the auth provider allows it,
  276. # even though the localdb does not.
  277. self.assertEqual(channel.json_body["flows"], [{"stages": ["m.login.password"]}])
  278. session = channel.json_body["session"]
  279. mock_password_provider.check_password.assert_not_called()
  280. # now try deleting with the local password
  281. mock_password_provider.check_password.return_value = make_awaitable(False)
  282. channel = self._authed_delete_device(
  283. tok1, "dev2", session, "localuser", "localpass"
  284. )
  285. self.assertEqual(channel.code, 401) # XXX why not a 403?
  286. self.assertEqual(channel.json_body["errcode"], "M_FORBIDDEN")
  287. mock_password_provider.check_password.assert_called_once_with(
  288. "@localuser:test", "localpass"
  289. )
  290. @override_config(
  291. {
  292. **legacy_providers_config(LegacyPasswordOnlyAuthProvider),
  293. "password_config": {"enabled": False},
  294. }
  295. )
  296. def test_password_auth_disabled_legacy(self):
  297. self.password_auth_disabled_test_body()
  298. def password_auth_disabled_test_body(self):
  299. """password auth doesn't work if it's disabled across the board"""
  300. # login flows should be empty
  301. flows = self._get_login_flows()
  302. self.assertEqual(flows, ADDITIONAL_LOGIN_FLOWS)
  303. # login shouldn't work and should be rejected with a 400 ("unknown login type")
  304. channel = self._send_password_login("u", "p")
  305. self.assertEqual(channel.code, 400, channel.result)
  306. mock_password_provider.check_password.assert_not_called()
  307. @override_config(legacy_providers_config(LegacyCustomAuthProvider))
  308. def test_custom_auth_provider_login_legacy(self):
  309. self.custom_auth_provider_login_test_body()
  310. @override_config(providers_config(CustomAuthProvider))
  311. def test_custom_auth_provider_login(self):
  312. self.custom_auth_provider_login_test_body()
  313. def custom_auth_provider_login_test_body(self):
  314. # login flows should have the custom flow and m.login.password, since we
  315. # haven't disabled local password lookup.
  316. # (password must come first, because reasons)
  317. flows = self._get_login_flows()
  318. self.assertEqual(
  319. flows,
  320. [{"type": "m.login.password"}, {"type": "test.login_type"}]
  321. + ADDITIONAL_LOGIN_FLOWS,
  322. )
  323. # login with missing param should be rejected
  324. channel = self._send_login("test.login_type", "u")
  325. self.assertEqual(channel.code, 400, channel.result)
  326. mock_password_provider.check_auth.assert_not_called()
  327. mock_password_provider.check_auth.return_value = make_awaitable(
  328. ("@user:bz", None)
  329. )
  330. channel = self._send_login("test.login_type", "u", test_field="y")
  331. self.assertEqual(channel.code, 200, channel.result)
  332. self.assertEqual("@user:bz", channel.json_body["user_id"])
  333. mock_password_provider.check_auth.assert_called_once_with(
  334. "u", "test.login_type", {"test_field": "y"}
  335. )
  336. mock_password_provider.reset_mock()
  337. # try a weird username. Again, it's unclear what we *expect* to happen
  338. # in these cases, but at least we can guard against the API changing
  339. # unexpectedly
  340. mock_password_provider.check_auth.return_value = make_awaitable(
  341. ("@ MALFORMED! :bz", None)
  342. )
  343. channel = self._send_login("test.login_type", " USER🙂NAME ", test_field=" abc ")
  344. self.assertEqual(channel.code, 200, channel.result)
  345. self.assertEqual("@ MALFORMED! :bz", channel.json_body["user_id"])
  346. mock_password_provider.check_auth.assert_called_once_with(
  347. " USER🙂NAME ", "test.login_type", {"test_field": " abc "}
  348. )
  349. @override_config(legacy_providers_config(LegacyCustomAuthProvider))
  350. def test_custom_auth_provider_ui_auth_legacy(self):
  351. self.custom_auth_provider_ui_auth_test_body()
  352. @override_config(providers_config(CustomAuthProvider))
  353. def test_custom_auth_provider_ui_auth(self):
  354. self.custom_auth_provider_ui_auth_test_body()
  355. def custom_auth_provider_ui_auth_test_body(self):
  356. # register the user and log in twice, to get two devices
  357. self.register_user("localuser", "localpass")
  358. tok1 = self.login("localuser", "localpass")
  359. self.login("localuser", "localpass", device_id="dev2")
  360. # make the initial request which returns a 401
  361. channel = self._delete_device(tok1, "dev2")
  362. self.assertEqual(channel.code, 401)
  363. # Ensure that flows are what is expected.
  364. self.assertIn({"stages": ["m.login.password"]}, channel.json_body["flows"])
  365. self.assertIn({"stages": ["test.login_type"]}, channel.json_body["flows"])
  366. session = channel.json_body["session"]
  367. # missing param
  368. body = {
  369. "auth": {
  370. "type": "test.login_type",
  371. "identifier": {"type": "m.id.user", "user": "localuser"},
  372. "session": session,
  373. },
  374. }
  375. channel = self._delete_device(tok1, "dev2", body)
  376. self.assertEqual(channel.code, 400)
  377. # there's a perfectly good M_MISSING_PARAM errcode, but heaven forfend we should
  378. # use it...
  379. self.assertIn("Missing parameters", channel.json_body["error"])
  380. mock_password_provider.check_auth.assert_not_called()
  381. mock_password_provider.reset_mock()
  382. # right params, but authing as the wrong user
  383. mock_password_provider.check_auth.return_value = make_awaitable(
  384. ("@user:bz", None)
  385. )
  386. body["auth"]["test_field"] = "foo"
  387. channel = self._delete_device(tok1, "dev2", body)
  388. self.assertEqual(channel.code, 403)
  389. self.assertEqual(channel.json_body["errcode"], "M_FORBIDDEN")
  390. mock_password_provider.check_auth.assert_called_once_with(
  391. "localuser", "test.login_type", {"test_field": "foo"}
  392. )
  393. mock_password_provider.reset_mock()
  394. # and finally, succeed
  395. mock_password_provider.check_auth.return_value = make_awaitable(
  396. ("@localuser:test", None)
  397. )
  398. channel = self._delete_device(tok1, "dev2", body)
  399. self.assertEqual(channel.code, 200)
  400. mock_password_provider.check_auth.assert_called_once_with(
  401. "localuser", "test.login_type", {"test_field": "foo"}
  402. )
  403. @override_config(legacy_providers_config(LegacyCustomAuthProvider))
  404. def test_custom_auth_provider_callback_legacy(self):
  405. self.custom_auth_provider_callback_test_body()
  406. @override_config(providers_config(CustomAuthProvider))
  407. def test_custom_auth_provider_callback(self):
  408. self.custom_auth_provider_callback_test_body()
  409. def custom_auth_provider_callback_test_body(self):
  410. callback = Mock(return_value=make_awaitable(None))
  411. mock_password_provider.check_auth.return_value = make_awaitable(
  412. ("@user:bz", callback)
  413. )
  414. channel = self._send_login("test.login_type", "u", test_field="y")
  415. self.assertEqual(channel.code, 200, channel.result)
  416. self.assertEqual("@user:bz", channel.json_body["user_id"])
  417. mock_password_provider.check_auth.assert_called_once_with(
  418. "u", "test.login_type", {"test_field": "y"}
  419. )
  420. # check the args to the callback
  421. callback.assert_called_once()
  422. call_args, call_kwargs = callback.call_args
  423. # should be one positional arg
  424. self.assertEqual(len(call_args), 1)
  425. self.assertEqual(call_args[0]["user_id"], "@user:bz")
  426. for p in ["user_id", "access_token", "device_id", "home_server"]:
  427. self.assertIn(p, call_args[0])
  428. @override_config(
  429. {
  430. **legacy_providers_config(LegacyCustomAuthProvider),
  431. "password_config": {"enabled": False},
  432. }
  433. )
  434. def test_custom_auth_password_disabled_legacy(self):
  435. self.custom_auth_password_disabled_test_body()
  436. @override_config(
  437. {**providers_config(CustomAuthProvider), "password_config": {"enabled": False}}
  438. )
  439. def test_custom_auth_password_disabled(self):
  440. self.custom_auth_password_disabled_test_body()
  441. def custom_auth_password_disabled_test_body(self):
  442. """Test login with a custom auth provider where password login is disabled"""
  443. self.register_user("localuser", "localpass")
  444. flows = self._get_login_flows()
  445. self.assertEqual(flows, [{"type": "test.login_type"}] + ADDITIONAL_LOGIN_FLOWS)
  446. # login shouldn't work and should be rejected with a 400 ("unknown login type")
  447. channel = self._send_password_login("localuser", "localpass")
  448. self.assertEqual(channel.code, 400, channel.result)
  449. mock_password_provider.check_auth.assert_not_called()
  450. @override_config(
  451. {
  452. **legacy_providers_config(LegacyCustomAuthProvider),
  453. "password_config": {"enabled": False, "localdb_enabled": False},
  454. }
  455. )
  456. def test_custom_auth_password_disabled_localdb_enabled_legacy(self):
  457. self.custom_auth_password_disabled_localdb_enabled_test_body()
  458. @override_config(
  459. {
  460. **providers_config(CustomAuthProvider),
  461. "password_config": {"enabled": False, "localdb_enabled": False},
  462. }
  463. )
  464. def test_custom_auth_password_disabled_localdb_enabled(self):
  465. self.custom_auth_password_disabled_localdb_enabled_test_body()
  466. def custom_auth_password_disabled_localdb_enabled_test_body(self):
  467. """Check the localdb_enabled == enabled == False
  468. Regression test for https://github.com/matrix-org/synapse/issues/8914: check
  469. that setting *both* `localdb_enabled` *and* `password: enabled` to False doesn't
  470. cause an exception.
  471. """
  472. self.register_user("localuser", "localpass")
  473. flows = self._get_login_flows()
  474. self.assertEqual(flows, [{"type": "test.login_type"}] + ADDITIONAL_LOGIN_FLOWS)
  475. # login shouldn't work and should be rejected with a 400 ("unknown login type")
  476. channel = self._send_password_login("localuser", "localpass")
  477. self.assertEqual(channel.code, 400, channel.result)
  478. mock_password_provider.check_auth.assert_not_called()
  479. @override_config(
  480. {
  481. **legacy_providers_config(LegacyPasswordCustomAuthProvider),
  482. "password_config": {"enabled": False},
  483. }
  484. )
  485. def test_password_custom_auth_password_disabled_login_legacy(self):
  486. self.password_custom_auth_password_disabled_login_test_body()
  487. @override_config(
  488. {
  489. **providers_config(PasswordCustomAuthProvider),
  490. "password_config": {"enabled": False},
  491. }
  492. )
  493. def test_password_custom_auth_password_disabled_login(self):
  494. self.password_custom_auth_password_disabled_login_test_body()
  495. def password_custom_auth_password_disabled_login_test_body(self):
  496. """log in with a custom auth provider which implements password, but password
  497. login is disabled"""
  498. self.register_user("localuser", "localpass")
  499. flows = self._get_login_flows()
  500. self.assertEqual(flows, [{"type": "test.login_type"}] + ADDITIONAL_LOGIN_FLOWS)
  501. # login shouldn't work and should be rejected with a 400 ("unknown login type")
  502. channel = self._send_password_login("localuser", "localpass")
  503. self.assertEqual(channel.code, 400, channel.result)
  504. mock_password_provider.check_auth.assert_not_called()
  505. mock_password_provider.check_password.assert_not_called()
  506. @override_config(
  507. {
  508. **legacy_providers_config(LegacyPasswordCustomAuthProvider),
  509. "password_config": {"enabled": False},
  510. }
  511. )
  512. def test_password_custom_auth_password_disabled_ui_auth_legacy(self):
  513. self.password_custom_auth_password_disabled_ui_auth_test_body()
  514. @override_config(
  515. {
  516. **providers_config(PasswordCustomAuthProvider),
  517. "password_config": {"enabled": False},
  518. }
  519. )
  520. def test_password_custom_auth_password_disabled_ui_auth(self):
  521. self.password_custom_auth_password_disabled_ui_auth_test_body()
  522. def password_custom_auth_password_disabled_ui_auth_test_body(self):
  523. """UI Auth with a custom auth provider which implements password, but password
  524. login is disabled"""
  525. # register the user and log in twice via the test login type to get two devices,
  526. self.register_user("localuser", "localpass")
  527. mock_password_provider.check_auth.return_value = make_awaitable(
  528. ("@localuser:test", None)
  529. )
  530. channel = self._send_login("test.login_type", "localuser", test_field="")
  531. self.assertEqual(channel.code, 200, channel.result)
  532. tok1 = channel.json_body["access_token"]
  533. channel = self._send_login(
  534. "test.login_type", "localuser", test_field="", device_id="dev2"
  535. )
  536. self.assertEqual(channel.code, 200, channel.result)
  537. # make the initial request which returns a 401
  538. channel = self._delete_device(tok1, "dev2")
  539. self.assertEqual(channel.code, 401)
  540. # Ensure that flows are what is expected. In particular, "password" should *not*
  541. # be present.
  542. self.assertIn({"stages": ["test.login_type"]}, channel.json_body["flows"])
  543. session = channel.json_body["session"]
  544. mock_password_provider.reset_mock()
  545. # check that auth with password is rejected
  546. body = {
  547. "auth": {
  548. "type": "m.login.password",
  549. "identifier": {"type": "m.id.user", "user": "localuser"},
  550. "password": "localpass",
  551. "session": session,
  552. },
  553. }
  554. channel = self._delete_device(tok1, "dev2", body)
  555. self.assertEqual(channel.code, 400)
  556. self.assertEqual(
  557. "Password login has been disabled.", channel.json_body["error"]
  558. )
  559. mock_password_provider.check_auth.assert_not_called()
  560. mock_password_provider.check_password.assert_not_called()
  561. mock_password_provider.reset_mock()
  562. # successful auth
  563. body["auth"]["type"] = "test.login_type"
  564. body["auth"]["test_field"] = "x"
  565. channel = self._delete_device(tok1, "dev2", body)
  566. self.assertEqual(channel.code, 200)
  567. mock_password_provider.check_auth.assert_called_once_with(
  568. "localuser", "test.login_type", {"test_field": "x"}
  569. )
  570. mock_password_provider.check_password.assert_not_called()
  571. @override_config(
  572. {
  573. **legacy_providers_config(LegacyCustomAuthProvider),
  574. "password_config": {"localdb_enabled": False},
  575. }
  576. )
  577. def test_custom_auth_no_local_user_fallback_legacy(self):
  578. self.custom_auth_no_local_user_fallback_test_body()
  579. @override_config(
  580. {
  581. **providers_config(CustomAuthProvider),
  582. "password_config": {"localdb_enabled": False},
  583. }
  584. )
  585. def test_custom_auth_no_local_user_fallback(self):
  586. self.custom_auth_no_local_user_fallback_test_body()
  587. def custom_auth_no_local_user_fallback_test_body(self):
  588. """Test login with a custom auth provider where the local db is disabled"""
  589. self.register_user("localuser", "localpass")
  590. flows = self._get_login_flows()
  591. self.assertEqual(flows, [{"type": "test.login_type"}] + ADDITIONAL_LOGIN_FLOWS)
  592. # password login shouldn't work and should be rejected with a 400
  593. # ("unknown login type")
  594. channel = self._send_password_login("localuser", "localpass")
  595. self.assertEqual(channel.code, 400, channel.result)
  596. def test_on_logged_out(self):
  597. """Tests that the on_logged_out callback is called when the user logs out."""
  598. self.register_user("rin", "password")
  599. tok = self.login("rin", "password")
  600. self.called = False
  601. async def on_logged_out(user_id, device_id, access_token):
  602. self.called = True
  603. on_logged_out = Mock(side_effect=on_logged_out)
  604. self.hs.get_password_auth_provider().on_logged_out_callbacks.append(
  605. on_logged_out
  606. )
  607. channel = self.make_request(
  608. "POST",
  609. "/_matrix/client/v3/logout",
  610. {},
  611. access_token=tok,
  612. )
  613. self.assertEqual(channel.code, 200)
  614. on_logged_out.assert_called_once()
  615. self.assertTrue(self.called)
  616. def test_username(self):
  617. """Tests that the get_username_for_registration callback can define the username
  618. of a user when registering.
  619. """
  620. self._setup_get_name_for_registration(
  621. callback_name=self.CALLBACK_USERNAME,
  622. )
  623. username = "rin"
  624. channel = self.make_request(
  625. "POST",
  626. "/register",
  627. {
  628. "username": username,
  629. "password": "bar",
  630. "auth": {"type": LoginType.DUMMY},
  631. },
  632. )
  633. self.assertEqual(channel.code, 200)
  634. # Our callback takes the username and appends "-foo" to it, check that's what we
  635. # have.
  636. mxid = channel.json_body["user_id"]
  637. self.assertEqual(UserID.from_string(mxid).localpart, username + "-foo")
  638. def test_username_uia(self):
  639. """Tests that the get_username_for_registration callback is only called at the
  640. end of the UIA flow.
  641. """
  642. m = self._setup_get_name_for_registration(
  643. callback_name=self.CALLBACK_USERNAME,
  644. )
  645. username = "rin"
  646. res = self._do_uia_assert_mock_not_called(username, m)
  647. mxid = res["user_id"]
  648. self.assertEqual(UserID.from_string(mxid).localpart, username + "-foo")
  649. # Check that the callback has been called.
  650. m.assert_called_once()
  651. # Set some email configuration so the test doesn't fail because of its absence.
  652. @override_config({"email": {"notif_from": "noreply@test"}})
  653. def test_3pid_allowed(self):
  654. """Tests that an is_3pid_allowed_callbacks forbidding a 3PID makes Synapse refuse
  655. to bind the new 3PID, and that one allowing a 3PID makes Synapse accept to bind
  656. the 3PID. Also checks that the module is passed a boolean indicating whether the
  657. user to bind this 3PID to is currently registering.
  658. """
  659. self._test_3pid_allowed("rin", False)
  660. self._test_3pid_allowed("kitay", True)
  661. def test_displayname(self):
  662. """Tests that the get_displayname_for_registration callback can define the
  663. display name of a user when registering.
  664. """
  665. self._setup_get_name_for_registration(
  666. callback_name=self.CALLBACK_DISPLAYNAME,
  667. )
  668. username = "rin"
  669. channel = self.make_request(
  670. "POST",
  671. "/register",
  672. {
  673. "username": username,
  674. "password": "bar",
  675. "auth": {"type": LoginType.DUMMY},
  676. },
  677. )
  678. self.assertEqual(channel.code, 200)
  679. # Our callback takes the username and appends "-foo" to it, check that's what we
  680. # have.
  681. user_id = UserID.from_string(channel.json_body["user_id"])
  682. display_name = self.get_success(
  683. self.hs.get_profile_handler().get_displayname(user_id)
  684. )
  685. self.assertEqual(display_name, username + "-foo")
  686. def test_displayname_uia(self):
  687. """Tests that the get_displayname_for_registration callback is only called at the
  688. end of the UIA flow.
  689. """
  690. m = self._setup_get_name_for_registration(
  691. callback_name=self.CALLBACK_DISPLAYNAME,
  692. )
  693. username = "rin"
  694. res = self._do_uia_assert_mock_not_called(username, m)
  695. user_id = UserID.from_string(res["user_id"])
  696. display_name = self.get_success(
  697. self.hs.get_profile_handler().get_displayname(user_id)
  698. )
  699. self.assertEqual(display_name, username + "-foo")
  700. # Check that the callback has been called.
  701. m.assert_called_once()
  702. def _test_3pid_allowed(self, username: str, registration: bool):
  703. """Tests that the "is_3pid_allowed" module callback is called correctly, using
  704. either /register or /account URLs depending on the arguments.
  705. Args:
  706. username: The username to use for the test.
  707. registration: Whether to test with registration URLs.
  708. """
  709. self.hs.get_identity_handler().send_threepid_validation = Mock(
  710. return_value=make_awaitable(0),
  711. )
  712. m = Mock(return_value=make_awaitable(False))
  713. self.hs.get_password_auth_provider().is_3pid_allowed_callbacks = [m]
  714. self.register_user(username, "password")
  715. tok = self.login(username, "password")
  716. if registration:
  717. url = "/register/email/requestToken"
  718. else:
  719. url = "/account/3pid/email/requestToken"
  720. channel = self.make_request(
  721. "POST",
  722. url,
  723. {
  724. "client_secret": "foo",
  725. "email": "foo@test.com",
  726. "send_attempt": 0,
  727. },
  728. access_token=tok,
  729. )
  730. self.assertEqual(channel.code, 403, channel.result)
  731. self.assertEqual(
  732. channel.json_body["errcode"],
  733. Codes.THREEPID_DENIED,
  734. channel.json_body,
  735. )
  736. m.assert_called_once_with("email", "foo@test.com", registration)
  737. m = Mock(return_value=make_awaitable(True))
  738. self.hs.get_password_auth_provider().is_3pid_allowed_callbacks = [m]
  739. channel = self.make_request(
  740. "POST",
  741. url,
  742. {
  743. "client_secret": "foo",
  744. "email": "bar@test.com",
  745. "send_attempt": 0,
  746. },
  747. access_token=tok,
  748. )
  749. self.assertEqual(channel.code, 200, channel.result)
  750. self.assertIn("sid", channel.json_body)
  751. m.assert_called_once_with("email", "bar@test.com", registration)
  752. def _setup_get_name_for_registration(self, callback_name: str) -> Mock:
  753. """Registers either a get_username_for_registration callback or a
  754. get_displayname_for_registration callback that appends "-foo" to the username the
  755. client is trying to register.
  756. """
  757. async def callback(uia_results, params):
  758. self.assertIn(LoginType.DUMMY, uia_results)
  759. username = params["username"]
  760. return username + "-foo"
  761. m = Mock(side_effect=callback)
  762. password_auth_provider = self.hs.get_password_auth_provider()
  763. getattr(password_auth_provider, callback_name + "_callbacks").append(m)
  764. return m
  765. def _do_uia_assert_mock_not_called(self, username: str, m: Mock) -> JsonDict:
  766. # Initiate the UIA flow.
  767. channel = self.make_request(
  768. "POST",
  769. "register",
  770. {"username": username, "type": "m.login.password", "password": "bar"},
  771. )
  772. self.assertEqual(channel.code, 401)
  773. self.assertIn("session", channel.json_body)
  774. # Check that the callback hasn't been called yet.
  775. m.assert_not_called()
  776. # Finish the UIA flow.
  777. session = channel.json_body["session"]
  778. channel = self.make_request(
  779. "POST",
  780. "register",
  781. {"auth": {"session": session, "type": LoginType.DUMMY}},
  782. )
  783. self.assertEqual(channel.code, 200, channel.json_body)
  784. return channel.json_body
  785. def _get_login_flows(self) -> JsonDict:
  786. channel = self.make_request("GET", "/_matrix/client/r0/login")
  787. self.assertEqual(channel.code, 200, channel.result)
  788. return channel.json_body["flows"]
  789. def _send_password_login(self, user: str, password: str) -> FakeChannel:
  790. return self._send_login(type="m.login.password", user=user, password=password)
  791. def _send_login(self, type, user, **params) -> FakeChannel:
  792. params.update({"identifier": {"type": "m.id.user", "user": user}, "type": type})
  793. channel = self.make_request("POST", "/_matrix/client/r0/login", params)
  794. return channel
  795. def _start_delete_device_session(self, access_token, device_id) -> str:
  796. """Make an initial delete device request, and return the UI Auth session ID"""
  797. channel = self._delete_device(access_token, device_id)
  798. self.assertEqual(channel.code, 401)
  799. # Ensure that flows are what is expected.
  800. self.assertIn({"stages": ["m.login.password"]}, channel.json_body["flows"])
  801. return channel.json_body["session"]
  802. def _authed_delete_device(
  803. self,
  804. access_token: str,
  805. device_id: str,
  806. session: str,
  807. user_id: str,
  808. password: str,
  809. ) -> FakeChannel:
  810. """Make a delete device request, authenticating with the given uid/password"""
  811. return self._delete_device(
  812. access_token,
  813. device_id,
  814. {
  815. "auth": {
  816. "type": "m.login.password",
  817. "identifier": {"type": "m.id.user", "user": user_id},
  818. "password": password,
  819. "session": session,
  820. },
  821. },
  822. )
  823. def _delete_device(
  824. self,
  825. access_token: str,
  826. device: str,
  827. body: Union[JsonDict, bytes] = b"",
  828. ) -> FakeChannel:
  829. """Delete an individual device."""
  830. channel = self.make_request(
  831. "DELETE", "devices/" + device, body, access_token=access_token
  832. )
  833. return channel