You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1003 lines
39 KiB

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