test_password_providers.py 38 KB

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