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.
 
 
 
 
 
 

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