test_password_providers.py 38 KB

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