test_password_providers.py 38 KB

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