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.
 
 
 
 
 
 

1536 lines
59 KiB

  1. # Copyright 2019-2021 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. import time
  15. import urllib.parse
  16. from typing import Any, Collection, Dict, List, Optional, Tuple, Union
  17. from unittest.mock import Mock
  18. from urllib.parse import urlencode
  19. import pymacaroons
  20. from typing_extensions import Literal
  21. from twisted.test.proto_helpers import MemoryReactor
  22. from twisted.web.resource import Resource
  23. import synapse.rest.admin
  24. from synapse.api.constants import ApprovalNoticeMedium, LoginType
  25. from synapse.api.errors import Codes
  26. from synapse.appservice import ApplicationService
  27. from synapse.module_api import ModuleApi
  28. from synapse.rest.client import devices, login, logout, register
  29. from synapse.rest.client.account import WhoamiRestServlet
  30. from synapse.rest.synapse.client import build_synapse_client_resource_tree
  31. from synapse.server import HomeServer
  32. from synapse.types import JsonDict, create_requester
  33. from synapse.util import Clock
  34. from tests import unittest
  35. from tests.handlers.test_oidc import HAS_OIDC
  36. from tests.handlers.test_saml import has_saml2
  37. from tests.rest.client.utils import TEST_OIDC_CONFIG
  38. from tests.server import FakeChannel
  39. from tests.test_utils.html_parsers import TestHtmlParser
  40. from tests.unittest import HomeserverTestCase, override_config, skip_unless
  41. try:
  42. from authlib.jose import JsonWebKey, jwt
  43. HAS_JWT = True
  44. except ImportError:
  45. HAS_JWT = False
  46. # synapse server name: used to populate public_baseurl in some tests
  47. SYNAPSE_SERVER_PUBLIC_HOSTNAME = "synapse"
  48. # public_baseurl for some tests. It uses an http:// scheme because
  49. # FakeChannel.isSecure() returns False, so synapse will see the requested uri as
  50. # http://..., so using http in the public_baseurl stops Synapse trying to redirect to
  51. # https://....
  52. BASE_URL = "http://%s/" % (SYNAPSE_SERVER_PUBLIC_HOSTNAME,)
  53. # CAS server used in some tests
  54. CAS_SERVER = "https://fake.test"
  55. # just enough to tell pysaml2 where to redirect to
  56. SAML_SERVER = "https://test.saml.server/idp/sso"
  57. TEST_SAML_METADATA = """
  58. <md:EntityDescriptor xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata">
  59. <md:IDPSSODescriptor protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol">
  60. <md:SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect" Location="%(SAML_SERVER)s"/>
  61. </md:IDPSSODescriptor>
  62. </md:EntityDescriptor>
  63. """ % {
  64. "SAML_SERVER": SAML_SERVER,
  65. }
  66. LOGIN_URL = b"/_matrix/client/r0/login"
  67. TEST_URL = b"/_matrix/client/r0/account/whoami"
  68. # a (valid) url with some annoying characters in. %3D is =, %26 is &, %2B is +
  69. TEST_CLIENT_REDIRECT_URL = 'https://x?<ab c>&q"+%3D%2B"="fö%26=o"'
  70. # the query params in TEST_CLIENT_REDIRECT_URL
  71. EXPECTED_CLIENT_REDIRECT_URL_PARAMS = [("<ab c>", ""), ('q" =+"', '"fö&=o"')]
  72. # Login flows we expect to appear in the list after the normal ones.
  73. ADDITIONAL_LOGIN_FLOWS = [
  74. {"type": "m.login.application_service"},
  75. ]
  76. class TestSpamChecker:
  77. def __init__(self, config: None, api: ModuleApi):
  78. api.register_spam_checker_callbacks(
  79. check_login_for_spam=self.check_login_for_spam,
  80. )
  81. @staticmethod
  82. def parse_config(config: JsonDict) -> None:
  83. return None
  84. async def check_login_for_spam(
  85. self,
  86. user_id: str,
  87. device_id: Optional[str],
  88. initial_display_name: Optional[str],
  89. request_info: Collection[Tuple[Optional[str], str]],
  90. auth_provider_id: Optional[str] = None,
  91. ) -> Union[
  92. Literal["NOT_SPAM"],
  93. Tuple["synapse.module_api.errors.Codes", JsonDict],
  94. ]:
  95. return "NOT_SPAM"
  96. class DenyAllSpamChecker:
  97. def __init__(self, config: None, api: ModuleApi):
  98. api.register_spam_checker_callbacks(
  99. check_login_for_spam=self.check_login_for_spam,
  100. )
  101. @staticmethod
  102. def parse_config(config: JsonDict) -> None:
  103. return None
  104. async def check_login_for_spam(
  105. self,
  106. user_id: str,
  107. device_id: Optional[str],
  108. initial_display_name: Optional[str],
  109. request_info: Collection[Tuple[Optional[str], str]],
  110. auth_provider_id: Optional[str] = None,
  111. ) -> Union[
  112. Literal["NOT_SPAM"],
  113. Tuple["synapse.module_api.errors.Codes", JsonDict],
  114. ]:
  115. # Return an odd set of values to ensure that they get correctly passed
  116. # to the client.
  117. return Codes.LIMIT_EXCEEDED, {"extra": "value"}
  118. class LoginRestServletTestCase(unittest.HomeserverTestCase):
  119. servlets = [
  120. synapse.rest.admin.register_servlets_for_client_rest_resource,
  121. login.register_servlets,
  122. logout.register_servlets,
  123. devices.register_servlets,
  124. lambda hs, http_server: WhoamiRestServlet(hs).register(http_server),
  125. register.register_servlets,
  126. ]
  127. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  128. self.hs = self.setup_test_homeserver()
  129. self.hs.config.registration.enable_registration = True
  130. self.hs.config.registration.registrations_require_3pid = []
  131. self.hs.config.registration.auto_join_rooms = []
  132. self.hs.config.captcha.enable_registration_captcha = False
  133. return self.hs
  134. @override_config(
  135. {
  136. "rc_login": {
  137. "address": {"per_second": 0.17, "burst_count": 5},
  138. # Prevent the account login ratelimiter from raising first
  139. #
  140. # This is normally covered by the default test homeserver config
  141. # which sets these values to 10000, but as we're overriding the entire
  142. # rc_login dict here, we need to set this manually as well
  143. "account": {"per_second": 10000, "burst_count": 10000},
  144. },
  145. "experimental_features": {"msc4041_enabled": True},
  146. }
  147. )
  148. def test_POST_ratelimiting_per_address(self) -> None:
  149. # Create different users so we're sure not to be bothered by the per-user
  150. # ratelimiter.
  151. for i in range(6):
  152. self.register_user("kermit" + str(i), "monkey")
  153. for i in range(6):
  154. params = {
  155. "type": "m.login.password",
  156. "identifier": {"type": "m.id.user", "user": "kermit" + str(i)},
  157. "password": "monkey",
  158. }
  159. channel = self.make_request(b"POST", LOGIN_URL, params)
  160. if i == 5:
  161. self.assertEqual(channel.code, 429, msg=channel.result)
  162. retry_after_ms = int(channel.json_body["retry_after_ms"])
  163. retry_header = channel.headers.getRawHeaders("Retry-After")
  164. else:
  165. self.assertEqual(channel.code, 200, msg=channel.result)
  166. # Since we're ratelimiting at 1 request/min, retry_after_ms should be lower
  167. # than 1min.
  168. self.assertLess(retry_after_ms, 6000)
  169. assert retry_header
  170. self.assertLessEqual(int(retry_header[0]), 6)
  171. self.reactor.advance(retry_after_ms / 1000.0 + 1.0)
  172. params = {
  173. "type": "m.login.password",
  174. "identifier": {"type": "m.id.user", "user": "kermit" + str(i)},
  175. "password": "monkey",
  176. }
  177. channel = self.make_request(b"POST", LOGIN_URL, params)
  178. self.assertEqual(channel.code, 200, msg=channel.result)
  179. @override_config(
  180. {
  181. "rc_login": {
  182. "account": {"per_second": 0.17, "burst_count": 5},
  183. # Prevent the address login ratelimiter from raising first
  184. #
  185. # This is normally covered by the default test homeserver config
  186. # which sets these values to 10000, but as we're overriding the entire
  187. # rc_login dict here, we need to set this manually as well
  188. "address": {"per_second": 10000, "burst_count": 10000},
  189. },
  190. "experimental_features": {"msc4041_enabled": True},
  191. }
  192. )
  193. def test_POST_ratelimiting_per_account(self) -> None:
  194. self.register_user("kermit", "monkey")
  195. for i in range(6):
  196. params = {
  197. "type": "m.login.password",
  198. "identifier": {"type": "m.id.user", "user": "kermit"},
  199. "password": "monkey",
  200. }
  201. channel = self.make_request(b"POST", LOGIN_URL, params)
  202. if i == 5:
  203. self.assertEqual(channel.code, 429, msg=channel.result)
  204. retry_after_ms = int(channel.json_body["retry_after_ms"])
  205. retry_header = channel.headers.getRawHeaders("Retry-After")
  206. else:
  207. self.assertEqual(channel.code, 200, msg=channel.result)
  208. # Since we're ratelimiting at 1 request/min, retry_after_ms should be lower
  209. # than 1min.
  210. self.assertLess(retry_after_ms, 6000)
  211. assert retry_header
  212. self.assertLessEqual(int(retry_header[0]), 6)
  213. self.reactor.advance(retry_after_ms / 1000.0)
  214. params = {
  215. "type": "m.login.password",
  216. "identifier": {"type": "m.id.user", "user": "kermit"},
  217. "password": "monkey",
  218. }
  219. channel = self.make_request(b"POST", LOGIN_URL, params)
  220. self.assertEqual(channel.code, 200, msg=channel.result)
  221. @override_config(
  222. {
  223. "rc_login": {
  224. # Prevent the address login ratelimiter from raising first
  225. #
  226. # This is normally covered by the default test homeserver config
  227. # which sets these values to 10000, but as we're overriding the entire
  228. # rc_login dict here, we need to set this manually as well
  229. "address": {"per_second": 10000, "burst_count": 10000},
  230. "failed_attempts": {"per_second": 0.17, "burst_count": 5},
  231. },
  232. "experimental_features": {"msc4041_enabled": True},
  233. }
  234. )
  235. def test_POST_ratelimiting_per_account_failed_attempts(self) -> None:
  236. self.register_user("kermit", "monkey")
  237. for i in range(6):
  238. params = {
  239. "type": "m.login.password",
  240. "identifier": {"type": "m.id.user", "user": "kermit"},
  241. "password": "notamonkey",
  242. }
  243. channel = self.make_request(b"POST", LOGIN_URL, params)
  244. if i == 5:
  245. self.assertEqual(channel.code, 429, msg=channel.result)
  246. retry_after_ms = int(channel.json_body["retry_after_ms"])
  247. retry_header = channel.headers.getRawHeaders("Retry-After")
  248. else:
  249. self.assertEqual(channel.code, 403, msg=channel.result)
  250. # Since we're ratelimiting at 1 request/min, retry_after_ms should be lower
  251. # than 1min.
  252. self.assertLess(retry_after_ms, 6000)
  253. assert retry_header
  254. self.assertLessEqual(int(retry_header[0]), 6)
  255. self.reactor.advance(retry_after_ms / 1000.0 + 1.0)
  256. params = {
  257. "type": "m.login.password",
  258. "identifier": {"type": "m.id.user", "user": "kermit"},
  259. "password": "notamonkey",
  260. }
  261. channel = self.make_request(b"POST", LOGIN_URL, params)
  262. self.assertEqual(channel.code, 403, msg=channel.result)
  263. @override_config({"session_lifetime": "24h"})
  264. def test_soft_logout(self) -> None:
  265. self.register_user("kermit", "monkey")
  266. # we shouldn't be able to make requests without an access token
  267. channel = self.make_request(b"GET", TEST_URL)
  268. self.assertEqual(channel.code, 401, msg=channel.result)
  269. self.assertEqual(channel.json_body["errcode"], "M_MISSING_TOKEN")
  270. # log in as normal
  271. params = {
  272. "type": "m.login.password",
  273. "identifier": {"type": "m.id.user", "user": "kermit"},
  274. "password": "monkey",
  275. }
  276. channel = self.make_request(b"POST", LOGIN_URL, params)
  277. self.assertEqual(channel.code, 200, channel.result)
  278. access_token = channel.json_body["access_token"]
  279. device_id = channel.json_body["device_id"]
  280. # we should now be able to make requests with the access token
  281. channel = self.make_request(b"GET", TEST_URL, access_token=access_token)
  282. self.assertEqual(channel.code, 200, channel.result)
  283. # time passes
  284. self.reactor.advance(24 * 3600)
  285. # ... and we should be soft-logouted
  286. channel = self.make_request(b"GET", TEST_URL, access_token=access_token)
  287. self.assertEqual(channel.code, 401, channel.result)
  288. self.assertEqual(channel.json_body["errcode"], "M_UNKNOWN_TOKEN")
  289. self.assertEqual(channel.json_body["soft_logout"], True)
  290. #
  291. # test behaviour after deleting the expired device
  292. #
  293. # we now log in as a different device
  294. access_token_2 = self.login("kermit", "monkey")
  295. # more requests with the expired token should still return a soft-logout
  296. self.reactor.advance(3600)
  297. channel = self.make_request(b"GET", TEST_URL, access_token=access_token)
  298. self.assertEqual(channel.code, 401, channel.result)
  299. self.assertEqual(channel.json_body["errcode"], "M_UNKNOWN_TOKEN")
  300. self.assertEqual(channel.json_body["soft_logout"], True)
  301. # ... but if we delete that device, it will be a proper logout
  302. self._delete_device(access_token_2, "kermit", "monkey", device_id)
  303. channel = self.make_request(b"GET", TEST_URL, access_token=access_token)
  304. self.assertEqual(channel.code, 401, channel.result)
  305. self.assertEqual(channel.json_body["errcode"], "M_UNKNOWN_TOKEN")
  306. self.assertEqual(channel.json_body["soft_logout"], False)
  307. def _delete_device(
  308. self, access_token: str, user_id: str, password: str, device_id: str
  309. ) -> None:
  310. """Perform the UI-Auth to delete a device"""
  311. channel = self.make_request(
  312. b"DELETE", "devices/" + device_id, access_token=access_token
  313. )
  314. self.assertEqual(channel.code, 401, channel.result)
  315. # check it's a UI-Auth fail
  316. self.assertEqual(
  317. set(channel.json_body.keys()),
  318. {"flows", "params", "session"},
  319. channel.result,
  320. )
  321. auth = {
  322. "type": "m.login.password",
  323. # https://github.com/matrix-org/synapse/issues/5665
  324. # "identifier": {"type": "m.id.user", "user": user_id},
  325. "user": user_id,
  326. "password": password,
  327. "session": channel.json_body["session"],
  328. }
  329. channel = self.make_request(
  330. b"DELETE",
  331. "devices/" + device_id,
  332. access_token=access_token,
  333. content={"auth": auth},
  334. )
  335. self.assertEqual(channel.code, 200, channel.result)
  336. @override_config({"session_lifetime": "24h"})
  337. def test_session_can_hard_logout_after_being_soft_logged_out(self) -> None:
  338. self.register_user("kermit", "monkey")
  339. # log in as normal
  340. access_token = self.login("kermit", "monkey")
  341. # we should now be able to make requests with the access token
  342. channel = self.make_request(b"GET", TEST_URL, access_token=access_token)
  343. self.assertEqual(channel.code, 200, channel.result)
  344. # time passes
  345. self.reactor.advance(24 * 3600)
  346. # ... and we should be soft-logouted
  347. channel = self.make_request(b"GET", TEST_URL, access_token=access_token)
  348. self.assertEqual(channel.code, 401, channel.result)
  349. self.assertEqual(channel.json_body["errcode"], "M_UNKNOWN_TOKEN")
  350. self.assertEqual(channel.json_body["soft_logout"], True)
  351. # Now try to hard logout this session
  352. channel = self.make_request(b"POST", "/logout", access_token=access_token)
  353. self.assertEqual(channel.code, 200, msg=channel.result)
  354. @override_config({"session_lifetime": "24h"})
  355. def test_session_can_hard_logout_all_sessions_after_being_soft_logged_out(
  356. self,
  357. ) -> None:
  358. self.register_user("kermit", "monkey")
  359. # log in as normal
  360. access_token = self.login("kermit", "monkey")
  361. # we should now be able to make requests with the access token
  362. channel = self.make_request(b"GET", TEST_URL, access_token=access_token)
  363. self.assertEqual(channel.code, 200, channel.result)
  364. # time passes
  365. self.reactor.advance(24 * 3600)
  366. # ... and we should be soft-logouted
  367. channel = self.make_request(b"GET", TEST_URL, access_token=access_token)
  368. self.assertEqual(channel.code, 401, channel.result)
  369. self.assertEqual(channel.json_body["errcode"], "M_UNKNOWN_TOKEN")
  370. self.assertEqual(channel.json_body["soft_logout"], True)
  371. # Now try to hard log out all of the user's sessions
  372. channel = self.make_request(b"POST", "/logout/all", access_token=access_token)
  373. self.assertEqual(channel.code, 200, msg=channel.result)
  374. def test_login_with_overly_long_device_id_fails(self) -> None:
  375. self.register_user("mickey", "cheese")
  376. # create a device_id longer than 512 characters
  377. device_id = "yolo" * 512
  378. body = {
  379. "type": "m.login.password",
  380. "user": "mickey",
  381. "password": "cheese",
  382. "device_id": device_id,
  383. }
  384. # make a login request with the bad device_id
  385. channel = self.make_request(
  386. "POST",
  387. "/_matrix/client/v3/login",
  388. body,
  389. custom_headers=None,
  390. )
  391. # test that the login fails with the correct error code
  392. self.assertEqual(channel.code, 400)
  393. self.assertEqual(channel.json_body["errcode"], "M_INVALID_PARAM")
  394. @override_config(
  395. {
  396. "experimental_features": {
  397. "msc3866": {
  398. "enabled": True,
  399. "require_approval_for_new_accounts": True,
  400. }
  401. }
  402. }
  403. )
  404. def test_require_approval(self) -> None:
  405. channel = self.make_request(
  406. "POST",
  407. "register",
  408. {
  409. "username": "kermit",
  410. "password": "monkey",
  411. "auth": {"type": LoginType.DUMMY},
  412. },
  413. )
  414. self.assertEqual(403, channel.code, channel.result)
  415. self.assertEqual(Codes.USER_AWAITING_APPROVAL, channel.json_body["errcode"])
  416. self.assertEqual(
  417. ApprovalNoticeMedium.NONE, channel.json_body["approval_notice_medium"]
  418. )
  419. params = {
  420. "type": LoginType.PASSWORD,
  421. "identifier": {"type": "m.id.user", "user": "kermit"},
  422. "password": "monkey",
  423. }
  424. channel = self.make_request("POST", LOGIN_URL, params)
  425. self.assertEqual(403, channel.code, channel.result)
  426. self.assertEqual(Codes.USER_AWAITING_APPROVAL, channel.json_body["errcode"])
  427. self.assertEqual(
  428. ApprovalNoticeMedium.NONE, channel.json_body["approval_notice_medium"]
  429. )
  430. def test_get_login_flows_with_login_via_existing_disabled(self) -> None:
  431. """GET /login should return m.login.token without get_login_token"""
  432. channel = self.make_request("GET", "/_matrix/client/r0/login")
  433. self.assertEqual(channel.code, 200, channel.result)
  434. flows = {flow["type"]: flow for flow in channel.json_body["flows"]}
  435. self.assertNotIn("m.login.token", flows)
  436. @override_config({"login_via_existing_session": {"enabled": True}})
  437. def test_get_login_flows_with_login_via_existing_enabled(self) -> None:
  438. """GET /login should return m.login.token with get_login_token true"""
  439. channel = self.make_request("GET", "/_matrix/client/r0/login")
  440. self.assertEqual(channel.code, 200, channel.result)
  441. self.assertCountEqual(
  442. channel.json_body["flows"],
  443. [
  444. {"type": "m.login.token", "get_login_token": True},
  445. {"type": "m.login.password"},
  446. {"type": "m.login.application_service"},
  447. ],
  448. )
  449. @override_config(
  450. {
  451. "modules": [
  452. {
  453. "module": TestSpamChecker.__module__
  454. + "."
  455. + TestSpamChecker.__qualname__
  456. }
  457. ]
  458. }
  459. )
  460. def test_spam_checker_allow(self) -> None:
  461. """Check that that adding a spam checker doesn't break login."""
  462. self.register_user("kermit", "monkey")
  463. body = {"type": "m.login.password", "user": "kermit", "password": "monkey"}
  464. channel = self.make_request(
  465. "POST",
  466. "/_matrix/client/r0/login",
  467. body,
  468. )
  469. self.assertEqual(channel.code, 200, channel.result)
  470. @override_config(
  471. {
  472. "modules": [
  473. {
  474. "module": DenyAllSpamChecker.__module__
  475. + "."
  476. + DenyAllSpamChecker.__qualname__
  477. }
  478. ]
  479. }
  480. )
  481. def test_spam_checker_deny(self) -> None:
  482. """Check that login"""
  483. self.register_user("kermit", "monkey")
  484. body = {"type": "m.login.password", "user": "kermit", "password": "monkey"}
  485. channel = self.make_request(
  486. "POST",
  487. "/_matrix/client/r0/login",
  488. body,
  489. )
  490. self.assertEqual(channel.code, 403, channel.result)
  491. self.assertLessEqual(
  492. {"errcode": Codes.LIMIT_EXCEEDED, "extra": "value"}.items(),
  493. channel.json_body.items(),
  494. )
  495. @skip_unless(has_saml2 and HAS_OIDC, "Requires SAML2 and OIDC")
  496. class MultiSSOTestCase(unittest.HomeserverTestCase):
  497. """Tests for homeservers with multiple SSO providers enabled"""
  498. servlets = [
  499. login.register_servlets,
  500. ]
  501. def default_config(self) -> Dict[str, Any]:
  502. config = super().default_config()
  503. config["public_baseurl"] = BASE_URL
  504. config["cas_config"] = {
  505. "enabled": True,
  506. "server_url": CAS_SERVER,
  507. "service_url": "https://matrix.goodserver.com:8448",
  508. }
  509. config["saml2_config"] = {
  510. "sp_config": {
  511. "metadata": {"inline": [TEST_SAML_METADATA]},
  512. # use the XMLSecurity backend to avoid relying on xmlsec1
  513. "crypto_backend": "XMLSecurity",
  514. },
  515. }
  516. # default OIDC provider
  517. config["oidc_config"] = TEST_OIDC_CONFIG
  518. # additional OIDC providers
  519. config["oidc_providers"] = [
  520. {
  521. "idp_id": "idp1",
  522. "idp_name": "IDP1",
  523. "discover": False,
  524. "issuer": "https://issuer1",
  525. "client_id": "test-client-id",
  526. "client_secret": "test-client-secret",
  527. "scopes": ["profile"],
  528. "authorization_endpoint": "https://issuer1/auth",
  529. "token_endpoint": "https://issuer1/token",
  530. "userinfo_endpoint": "https://issuer1/userinfo",
  531. "user_mapping_provider": {
  532. "config": {"localpart_template": "{{ user.sub }}"}
  533. },
  534. }
  535. ]
  536. return config
  537. def create_resource_dict(self) -> Dict[str, Resource]:
  538. d = super().create_resource_dict()
  539. d.update(build_synapse_client_resource_tree(self.hs))
  540. return d
  541. def test_get_login_flows(self) -> None:
  542. """GET /login should return password and SSO flows"""
  543. channel = self.make_request("GET", "/_matrix/client/r0/login")
  544. self.assertEqual(channel.code, 200, channel.result)
  545. expected_flow_types = [
  546. "m.login.cas",
  547. "m.login.sso",
  548. "m.login.token",
  549. "m.login.password",
  550. ] + [f["type"] for f in ADDITIONAL_LOGIN_FLOWS]
  551. self.assertCountEqual(
  552. [f["type"] for f in channel.json_body["flows"]], expected_flow_types
  553. )
  554. flows = {flow["type"]: flow for flow in channel.json_body["flows"]}
  555. self.assertCountEqual(
  556. flows["m.login.sso"]["identity_providers"],
  557. [
  558. {"id": "cas", "name": "CAS"},
  559. {"id": "saml", "name": "SAML"},
  560. {"id": "oidc-idp1", "name": "IDP1"},
  561. {"id": "oidc", "name": "OIDC"},
  562. ],
  563. )
  564. def test_multi_sso_redirect(self) -> None:
  565. """/login/sso/redirect should redirect to an identity picker"""
  566. # first hit the redirect url, which should redirect to our idp picker
  567. channel = self._make_sso_redirect_request(None)
  568. self.assertEqual(channel.code, 302, channel.result)
  569. location_headers = channel.headers.getRawHeaders("Location")
  570. assert location_headers
  571. uri = location_headers[0]
  572. # hitting that picker should give us some HTML
  573. channel = self.make_request("GET", uri)
  574. self.assertEqual(channel.code, 200, channel.result)
  575. # parse the form to check it has fields assumed elsewhere in this class
  576. html = channel.result["body"].decode("utf-8")
  577. p = TestHtmlParser()
  578. p.feed(html)
  579. p.close()
  580. # there should be a link for each href
  581. returned_idps: List[str] = []
  582. for link in p.links:
  583. path, query = link.split("?", 1)
  584. self.assertEqual(path, "pick_idp")
  585. params = urllib.parse.parse_qs(query)
  586. self.assertEqual(params["redirectUrl"], [TEST_CLIENT_REDIRECT_URL])
  587. returned_idps.append(params["idp"][0])
  588. self.assertCountEqual(returned_idps, ["cas", "oidc", "oidc-idp1", "saml"])
  589. def test_multi_sso_redirect_to_cas(self) -> None:
  590. """If CAS is chosen, should redirect to the CAS server"""
  591. channel = self.make_request(
  592. "GET",
  593. "/_synapse/client/pick_idp?redirectUrl="
  594. + urllib.parse.quote_plus(TEST_CLIENT_REDIRECT_URL)
  595. + "&idp=cas",
  596. shorthand=False,
  597. )
  598. self.assertEqual(channel.code, 302, channel.result)
  599. location_headers = channel.headers.getRawHeaders("Location")
  600. assert location_headers
  601. cas_uri = location_headers[0]
  602. cas_uri_path, cas_uri_query = cas_uri.split("?", 1)
  603. # it should redirect us to the login page of the cas server
  604. self.assertEqual(cas_uri_path, CAS_SERVER + "/login")
  605. # check that the redirectUrl is correctly encoded in the service param - ie, the
  606. # place that CAS will redirect to
  607. cas_uri_params = urllib.parse.parse_qs(cas_uri_query)
  608. service_uri = cas_uri_params["service"][0]
  609. _, service_uri_query = service_uri.split("?", 1)
  610. service_uri_params = urllib.parse.parse_qs(service_uri_query)
  611. self.assertEqual(service_uri_params["redirectUrl"][0], TEST_CLIENT_REDIRECT_URL)
  612. def test_multi_sso_redirect_to_saml(self) -> None:
  613. """If SAML is chosen, should redirect to the SAML server"""
  614. channel = self.make_request(
  615. "GET",
  616. "/_synapse/client/pick_idp?redirectUrl="
  617. + urllib.parse.quote_plus(TEST_CLIENT_REDIRECT_URL)
  618. + "&idp=saml",
  619. )
  620. self.assertEqual(channel.code, 302, channel.result)
  621. location_headers = channel.headers.getRawHeaders("Location")
  622. assert location_headers
  623. saml_uri = location_headers[0]
  624. saml_uri_path, saml_uri_query = saml_uri.split("?", 1)
  625. # it should redirect us to the login page of the SAML server
  626. self.assertEqual(saml_uri_path, SAML_SERVER)
  627. # the RelayState is used to carry the client redirect url
  628. saml_uri_params = urllib.parse.parse_qs(saml_uri_query)
  629. relay_state_param = saml_uri_params["RelayState"][0]
  630. self.assertEqual(relay_state_param, TEST_CLIENT_REDIRECT_URL)
  631. def test_login_via_oidc(self) -> None:
  632. """If OIDC is chosen, should redirect to the OIDC auth endpoint"""
  633. fake_oidc_server = self.helper.fake_oidc_server()
  634. with fake_oidc_server.patch_homeserver(hs=self.hs):
  635. # pick the default OIDC provider
  636. channel = self.make_request(
  637. "GET",
  638. "/_synapse/client/pick_idp?redirectUrl="
  639. + urllib.parse.quote_plus(TEST_CLIENT_REDIRECT_URL)
  640. + "&idp=oidc",
  641. )
  642. self.assertEqual(channel.code, 302, channel.result)
  643. location_headers = channel.headers.getRawHeaders("Location")
  644. assert location_headers
  645. oidc_uri = location_headers[0]
  646. oidc_uri_path, oidc_uri_query = oidc_uri.split("?", 1)
  647. # it should redirect us to the auth page of the OIDC server
  648. self.assertEqual(oidc_uri_path, fake_oidc_server.authorization_endpoint)
  649. # ... and should have set a cookie including the redirect url
  650. cookie_headers = channel.headers.getRawHeaders("Set-Cookie")
  651. assert cookie_headers
  652. cookies: Dict[str, str] = {}
  653. for h in cookie_headers:
  654. key, value = h.split(";")[0].split("=", maxsplit=1)
  655. cookies[key] = value
  656. oidc_session_cookie = cookies["oidc_session"]
  657. macaroon = pymacaroons.Macaroon.deserialize(oidc_session_cookie)
  658. self.assertEqual(
  659. self._get_value_from_macaroon(macaroon, "client_redirect_url"),
  660. TEST_CLIENT_REDIRECT_URL,
  661. )
  662. channel, _ = self.helper.complete_oidc_auth(
  663. fake_oidc_server, oidc_uri, cookies, {"sub": "user1"}
  664. )
  665. # that should serve a confirmation page
  666. self.assertEqual(channel.code, 200, channel.result)
  667. content_type_headers = channel.headers.getRawHeaders("Content-Type")
  668. assert content_type_headers
  669. self.assertTrue(content_type_headers[-1].startswith("text/html"))
  670. p = TestHtmlParser()
  671. p.feed(channel.text_body)
  672. p.close()
  673. # ... which should contain our redirect link
  674. self.assertEqual(len(p.links), 1)
  675. path, query = p.links[0].split("?", 1)
  676. self.assertEqual(path, "https://x")
  677. # it will have url-encoded the params properly, so we'll have to parse them
  678. params = urllib.parse.parse_qsl(
  679. query, keep_blank_values=True, strict_parsing=True, errors="strict"
  680. )
  681. self.assertEqual(params[0:2], EXPECTED_CLIENT_REDIRECT_URL_PARAMS)
  682. self.assertEqual(params[2][0], "loginToken")
  683. # finally, submit the matrix login token to the login API, which gives us our
  684. # matrix access token, mxid, and device id.
  685. login_token = params[2][1]
  686. chan = self.make_request(
  687. "POST",
  688. "/login",
  689. content={"type": "m.login.token", "token": login_token},
  690. )
  691. self.assertEqual(chan.code, 200, chan.result)
  692. self.assertEqual(chan.json_body["user_id"], "@user1:test")
  693. def test_multi_sso_redirect_to_unknown(self) -> None:
  694. """An unknown IdP should cause a 400"""
  695. channel = self.make_request(
  696. "GET",
  697. "/_synapse/client/pick_idp?redirectUrl=http://x&idp=xyz",
  698. )
  699. self.assertEqual(channel.code, 400, channel.result)
  700. def test_client_idp_redirect_to_unknown(self) -> None:
  701. """If the client tries to pick an unknown IdP, return a 404"""
  702. channel = self._make_sso_redirect_request("xxx")
  703. self.assertEqual(channel.code, 404, channel.result)
  704. self.assertEqual(channel.json_body["errcode"], "M_NOT_FOUND")
  705. def test_client_idp_redirect_to_oidc(self) -> None:
  706. """If the client pick a known IdP, redirect to it"""
  707. fake_oidc_server = self.helper.fake_oidc_server()
  708. with fake_oidc_server.patch_homeserver(hs=self.hs):
  709. channel = self._make_sso_redirect_request("oidc")
  710. self.assertEqual(channel.code, 302, channel.result)
  711. location_headers = channel.headers.getRawHeaders("Location")
  712. assert location_headers
  713. oidc_uri = location_headers[0]
  714. oidc_uri_path, oidc_uri_query = oidc_uri.split("?", 1)
  715. # it should redirect us to the auth page of the OIDC server
  716. self.assertEqual(oidc_uri_path, fake_oidc_server.authorization_endpoint)
  717. def _make_sso_redirect_request(self, idp_prov: Optional[str] = None) -> FakeChannel:
  718. """Send a request to /_matrix/client/r0/login/sso/redirect
  719. ... possibly specifying an IDP provider
  720. """
  721. endpoint = "/_matrix/client/r0/login/sso/redirect"
  722. if idp_prov is not None:
  723. endpoint += "/" + idp_prov
  724. endpoint += "?redirectUrl=" + urllib.parse.quote_plus(TEST_CLIENT_REDIRECT_URL)
  725. return self.make_request(
  726. "GET",
  727. endpoint,
  728. custom_headers=[("Host", SYNAPSE_SERVER_PUBLIC_HOSTNAME)],
  729. )
  730. @staticmethod
  731. def _get_value_from_macaroon(macaroon: pymacaroons.Macaroon, key: str) -> str:
  732. prefix = key + " = "
  733. for caveat in macaroon.caveats:
  734. if caveat.caveat_id.startswith(prefix):
  735. return caveat.caveat_id[len(prefix) :]
  736. raise ValueError("No %s caveat in macaroon" % (key,))
  737. class CASTestCase(unittest.HomeserverTestCase):
  738. servlets = [
  739. login.register_servlets,
  740. ]
  741. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  742. self.base_url = "https://matrix.goodserver.com/"
  743. self.redirect_path = "_synapse/client/login/sso/redirect/confirm"
  744. config = self.default_config()
  745. config["public_baseurl"] = (
  746. config.get("public_baseurl") or "https://matrix.goodserver.com:8448"
  747. )
  748. config["cas_config"] = {
  749. "enabled": True,
  750. "server_url": CAS_SERVER,
  751. }
  752. cas_user_id = "username"
  753. self.user_id = "@%s:test" % cas_user_id
  754. async def get_raw(uri: str, args: Any) -> bytes:
  755. """Return an example response payload from a call to the `/proxyValidate`
  756. endpoint of a CAS server, copied from
  757. https://apereo.github.io/cas/5.0.x/protocol/CAS-Protocol-V2-Specification.html#26-proxyvalidate-cas-20
  758. This needs to be returned by an async function (as opposed to set as the
  759. mock's return value) because the corresponding Synapse code awaits on it.
  760. """
  761. return (
  762. """
  763. <cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'>
  764. <cas:authenticationSuccess>
  765. <cas:user>%s</cas:user>
  766. <cas:proxyGrantingTicket>PGTIOU-84678-8a9d...</cas:proxyGrantingTicket>
  767. <cas:proxies>
  768. <cas:proxy>https://proxy2/pgtUrl</cas:proxy>
  769. <cas:proxy>https://proxy1/pgtUrl</cas:proxy>
  770. </cas:proxies>
  771. </cas:authenticationSuccess>
  772. </cas:serviceResponse>
  773. """
  774. % cas_user_id
  775. ).encode("utf-8")
  776. mocked_http_client = Mock(spec=["get_raw"])
  777. mocked_http_client.get_raw.side_effect = get_raw
  778. self.hs = self.setup_test_homeserver(
  779. config=config,
  780. proxied_http_client=mocked_http_client,
  781. )
  782. return self.hs
  783. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  784. self.deactivate_account_handler = hs.get_deactivate_account_handler()
  785. def test_cas_redirect_confirm(self) -> None:
  786. """Tests that the SSO login flow serves a confirmation page before redirecting a
  787. user to the redirect URL.
  788. """
  789. base_url = "/_matrix/client/r0/login/cas/ticket?redirectUrl"
  790. redirect_url = "https://dodgy-site.com/"
  791. url_parts = list(urllib.parse.urlparse(base_url))
  792. query = dict(urllib.parse.parse_qsl(url_parts[4]))
  793. query.update({"redirectUrl": redirect_url})
  794. query.update({"ticket": "ticket"})
  795. url_parts[4] = urllib.parse.urlencode(query)
  796. cas_ticket_url = urllib.parse.urlunparse(url_parts)
  797. # Get Synapse to call the fake CAS and serve the template.
  798. channel = self.make_request("GET", cas_ticket_url)
  799. # Test that the response is HTML.
  800. self.assertEqual(channel.code, 200, channel.result)
  801. content_type_header_value = ""
  802. for header in channel.result.get("headers", []):
  803. if header[0] == b"Content-Type":
  804. content_type_header_value = header[1].decode("utf8")
  805. self.assertTrue(content_type_header_value.startswith("text/html"))
  806. # Test that the body isn't empty.
  807. self.assertTrue(len(channel.result["body"]) > 0)
  808. # And that it contains our redirect link
  809. self.assertIn(redirect_url, channel.result["body"].decode("UTF-8"))
  810. @override_config(
  811. {
  812. "sso": {
  813. "client_whitelist": [
  814. "https://legit-site.com/",
  815. "https://other-site.com/",
  816. ]
  817. }
  818. }
  819. )
  820. def test_cas_redirect_whitelisted(self) -> None:
  821. """Tests that the SSO login flow serves a redirect to a whitelisted url"""
  822. self._test_redirect("https://legit-site.com/")
  823. @override_config({"public_baseurl": "https://example.com"})
  824. def test_cas_redirect_login_fallback(self) -> None:
  825. self._test_redirect("https://example.com/_matrix/static/client/login")
  826. def _test_redirect(self, redirect_url: str) -> None:
  827. """Tests that the SSO login flow serves a redirect for the given redirect URL."""
  828. cas_ticket_url = (
  829. "/_matrix/client/r0/login/cas/ticket?redirectUrl=%s&ticket=ticket"
  830. % (urllib.parse.quote(redirect_url))
  831. )
  832. # Get Synapse to call the fake CAS and serve the template.
  833. channel = self.make_request("GET", cas_ticket_url)
  834. self.assertEqual(channel.code, 302)
  835. location_headers = channel.headers.getRawHeaders("Location")
  836. assert location_headers
  837. self.assertEqual(location_headers[0][: len(redirect_url)], redirect_url)
  838. @override_config({"sso": {"client_whitelist": ["https://legit-site.com/"]}})
  839. def test_deactivated_user(self) -> None:
  840. """Logging in as a deactivated account should error."""
  841. redirect_url = "https://legit-site.com/"
  842. # First login (to create the user).
  843. self._test_redirect(redirect_url)
  844. # Deactivate the account.
  845. self.get_success(
  846. self.deactivate_account_handler.deactivate_account(
  847. self.user_id, False, create_requester(self.user_id)
  848. )
  849. )
  850. # Request the CAS ticket.
  851. cas_ticket_url = (
  852. "/_matrix/client/r0/login/cas/ticket?redirectUrl=%s&ticket=ticket"
  853. % (urllib.parse.quote(redirect_url))
  854. )
  855. # Get Synapse to call the fake CAS and serve the template.
  856. channel = self.make_request("GET", cas_ticket_url)
  857. # Because the user is deactivated they are served an error template.
  858. self.assertEqual(channel.code, 403)
  859. self.assertIn(b"SSO account deactivated", channel.result["body"])
  860. @skip_unless(HAS_JWT, "requires authlib")
  861. class JWTTestCase(unittest.HomeserverTestCase):
  862. servlets = [
  863. synapse.rest.admin.register_servlets_for_client_rest_resource,
  864. login.register_servlets,
  865. ]
  866. jwt_secret = "secret"
  867. jwt_algorithm = "HS256"
  868. base_config = {
  869. "enabled": True,
  870. "secret": jwt_secret,
  871. "algorithm": jwt_algorithm,
  872. }
  873. def default_config(self) -> Dict[str, Any]:
  874. config = super().default_config()
  875. # If jwt_config has been defined (eg via @override_config), don't replace it.
  876. if config.get("jwt_config") is None:
  877. config["jwt_config"] = self.base_config
  878. return config
  879. def jwt_encode(self, payload: Dict[str, Any], secret: str = jwt_secret) -> str:
  880. header = {"alg": self.jwt_algorithm}
  881. result: bytes = jwt.encode(header, payload, secret)
  882. return result.decode("ascii")
  883. def jwt_login(self, *args: Any) -> FakeChannel:
  884. params = {"type": "org.matrix.login.jwt", "token": self.jwt_encode(*args)}
  885. channel = self.make_request(b"POST", LOGIN_URL, params)
  886. return channel
  887. def test_login_jwt_valid_registered(self) -> None:
  888. self.register_user("kermit", "monkey")
  889. channel = self.jwt_login({"sub": "kermit"})
  890. self.assertEqual(channel.code, 200, msg=channel.result)
  891. self.assertEqual(channel.json_body["user_id"], "@kermit:test")
  892. def test_login_jwt_valid_unregistered(self) -> None:
  893. channel = self.jwt_login({"sub": "frog"})
  894. self.assertEqual(channel.code, 200, msg=channel.result)
  895. self.assertEqual(channel.json_body["user_id"], "@frog:test")
  896. def test_login_jwt_invalid_signature(self) -> None:
  897. channel = self.jwt_login({"sub": "frog"}, "notsecret")
  898. self.assertEqual(channel.code, 403, msg=channel.result)
  899. self.assertEqual(channel.json_body["errcode"], "M_FORBIDDEN")
  900. self.assertEqual(
  901. channel.json_body["error"],
  902. "JWT validation failed: Signature verification failed",
  903. )
  904. def test_login_jwt_expired(self) -> None:
  905. channel = self.jwt_login({"sub": "frog", "exp": 864000})
  906. self.assertEqual(channel.code, 403, msg=channel.result)
  907. self.assertEqual(channel.json_body["errcode"], "M_FORBIDDEN")
  908. self.assertEqual(
  909. channel.json_body["error"],
  910. "JWT validation failed: expired_token: The token is expired",
  911. )
  912. def test_login_jwt_not_before(self) -> None:
  913. now = int(time.time())
  914. channel = self.jwt_login({"sub": "frog", "nbf": now + 3600})
  915. self.assertEqual(channel.code, 403, msg=channel.result)
  916. self.assertEqual(channel.json_body["errcode"], "M_FORBIDDEN")
  917. self.assertEqual(
  918. channel.json_body["error"],
  919. "JWT validation failed: invalid_token: The token is not valid yet",
  920. )
  921. def test_login_no_sub(self) -> None:
  922. channel = self.jwt_login({"username": "root"})
  923. self.assertEqual(channel.code, 403, msg=channel.result)
  924. self.assertEqual(channel.json_body["errcode"], "M_FORBIDDEN")
  925. self.assertEqual(channel.json_body["error"], "Invalid JWT")
  926. @override_config({"jwt_config": {**base_config, "issuer": "test-issuer"}})
  927. def test_login_iss(self) -> None:
  928. """Test validating the issuer claim."""
  929. # A valid issuer.
  930. channel = self.jwt_login({"sub": "kermit", "iss": "test-issuer"})
  931. self.assertEqual(channel.code, 200, msg=channel.result)
  932. self.assertEqual(channel.json_body["user_id"], "@kermit:test")
  933. # An invalid issuer.
  934. channel = self.jwt_login({"sub": "kermit", "iss": "invalid"})
  935. self.assertEqual(channel.code, 403, msg=channel.result)
  936. self.assertEqual(channel.json_body["errcode"], "M_FORBIDDEN")
  937. self.assertEqual(
  938. channel.json_body["error"],
  939. 'JWT validation failed: invalid_claim: Invalid claim "iss"',
  940. )
  941. # Not providing an issuer.
  942. channel = self.jwt_login({"sub": "kermit"})
  943. self.assertEqual(channel.code, 403, msg=channel.result)
  944. self.assertEqual(channel.json_body["errcode"], "M_FORBIDDEN")
  945. self.assertEqual(
  946. channel.json_body["error"],
  947. 'JWT validation failed: missing_claim: Missing "iss" claim',
  948. )
  949. def test_login_iss_no_config(self) -> None:
  950. """Test providing an issuer claim without requiring it in the configuration."""
  951. channel = self.jwt_login({"sub": "kermit", "iss": "invalid"})
  952. self.assertEqual(channel.code, 200, msg=channel.result)
  953. self.assertEqual(channel.json_body["user_id"], "@kermit:test")
  954. @override_config({"jwt_config": {**base_config, "audiences": ["test-audience"]}})
  955. def test_login_aud(self) -> None:
  956. """Test validating the audience claim."""
  957. # A valid audience.
  958. channel = self.jwt_login({"sub": "kermit", "aud": "test-audience"})
  959. self.assertEqual(channel.code, 200, msg=channel.result)
  960. self.assertEqual(channel.json_body["user_id"], "@kermit:test")
  961. # An invalid audience.
  962. channel = self.jwt_login({"sub": "kermit", "aud": "invalid"})
  963. self.assertEqual(channel.code, 403, msg=channel.result)
  964. self.assertEqual(channel.json_body["errcode"], "M_FORBIDDEN")
  965. self.assertEqual(
  966. channel.json_body["error"],
  967. 'JWT validation failed: invalid_claim: Invalid claim "aud"',
  968. )
  969. # Not providing an audience.
  970. channel = self.jwt_login({"sub": "kermit"})
  971. self.assertEqual(channel.code, 403, msg=channel.result)
  972. self.assertEqual(channel.json_body["errcode"], "M_FORBIDDEN")
  973. self.assertEqual(
  974. channel.json_body["error"],
  975. 'JWT validation failed: missing_claim: Missing "aud" claim',
  976. )
  977. def test_login_aud_no_config(self) -> None:
  978. """Test providing an audience without requiring it in the configuration."""
  979. channel = self.jwt_login({"sub": "kermit", "aud": "invalid"})
  980. self.assertEqual(channel.code, 403, msg=channel.result)
  981. self.assertEqual(channel.json_body["errcode"], "M_FORBIDDEN")
  982. self.assertEqual(
  983. channel.json_body["error"],
  984. 'JWT validation failed: invalid_claim: Invalid claim "aud"',
  985. )
  986. def test_login_default_sub(self) -> None:
  987. """Test reading user ID from the default subject claim."""
  988. channel = self.jwt_login({"sub": "kermit"})
  989. self.assertEqual(channel.code, 200, msg=channel.result)
  990. self.assertEqual(channel.json_body["user_id"], "@kermit:test")
  991. @override_config({"jwt_config": {**base_config, "subject_claim": "username"}})
  992. def test_login_custom_sub(self) -> None:
  993. """Test reading user ID from a custom subject claim."""
  994. channel = self.jwt_login({"username": "frog"})
  995. self.assertEqual(channel.code, 200, msg=channel.result)
  996. self.assertEqual(channel.json_body["user_id"], "@frog:test")
  997. def test_login_no_token(self) -> None:
  998. params = {"type": "org.matrix.login.jwt"}
  999. channel = self.make_request(b"POST", LOGIN_URL, params)
  1000. self.assertEqual(channel.code, 403, msg=channel.result)
  1001. self.assertEqual(channel.json_body["errcode"], "M_FORBIDDEN")
  1002. self.assertEqual(channel.json_body["error"], "Token field for JWT is missing")
  1003. def test_deactivated_user(self) -> None:
  1004. """Logging in as a deactivated account should error."""
  1005. user_id = self.register_user("kermit", "monkey")
  1006. self.get_success(
  1007. self.hs.get_deactivate_account_handler().deactivate_account(
  1008. user_id, erase_data=False, requester=create_requester(user_id)
  1009. )
  1010. )
  1011. channel = self.jwt_login({"sub": "kermit"})
  1012. self.assertEqual(channel.code, 403, msg=channel.result)
  1013. self.assertEqual(channel.json_body["errcode"], "M_USER_DEACTIVATED")
  1014. self.assertEqual(
  1015. channel.json_body["error"], "This account has been deactivated"
  1016. )
  1017. # The JWTPubKeyTestCase is a complement to JWTTestCase where we instead use
  1018. # RSS256, with a public key configured in synapse as "jwt_secret", and tokens
  1019. # signed by the private key.
  1020. @skip_unless(HAS_JWT, "requires authlib")
  1021. class JWTPubKeyTestCase(unittest.HomeserverTestCase):
  1022. servlets = [
  1023. login.register_servlets,
  1024. ]
  1025. # This key's pubkey is used as the jwt_secret setting of synapse. Valid
  1026. # tokens are signed by this and validated using the pubkey. It is generated
  1027. # with `openssl genrsa 512` (not a secure way to generate real keys, but
  1028. # good enough for tests!)
  1029. jwt_privatekey = "\n".join(
  1030. [
  1031. "-----BEGIN RSA PRIVATE KEY-----",
  1032. "MIIBPAIBAAJBAM50f1Q5gsdmzifLstzLHb5NhfajiOt7TKO1vSEWdq7u9x8SMFiB",
  1033. "492RM9W/XFoh8WUfL9uL6Now6tPRDsWv3xsCAwEAAQJAUv7OOSOtiU+wzJq82rnk",
  1034. "yR4NHqt7XX8BvkZPM7/+EjBRanmZNSp5kYZzKVaZ/gTOM9+9MwlmhidrUOweKfB/",
  1035. "kQIhAPZwHazbjo7dYlJs7wPQz1vd+aHSEH+3uQKIysebkmm3AiEA1nc6mDdmgiUq",
  1036. "TpIN8A4MBKmfZMWTLq6z05y/qjKyxb0CIQDYJxCwTEenIaEa4PdoJl+qmXFasVDN",
  1037. "ZU0+XtNV7yul0wIhAMI9IhiStIjS2EppBa6RSlk+t1oxh2gUWlIh+YVQfZGRAiEA",
  1038. "tqBR7qLZGJ5CVKxWmNhJZGt1QHoUtOch8t9C4IdOZ2g=",
  1039. "-----END RSA PRIVATE KEY-----",
  1040. ]
  1041. )
  1042. # Generated with `openssl rsa -in foo.key -pubout`, with the the above
  1043. # private key placed in foo.key (jwt_privatekey).
  1044. jwt_pubkey = "\n".join(
  1045. [
  1046. "-----BEGIN PUBLIC KEY-----",
  1047. "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAM50f1Q5gsdmzifLstzLHb5NhfajiOt7",
  1048. "TKO1vSEWdq7u9x8SMFiB492RM9W/XFoh8WUfL9uL6Now6tPRDsWv3xsCAwEAAQ==",
  1049. "-----END PUBLIC KEY-----",
  1050. ]
  1051. )
  1052. # This key is used to sign tokens that shouldn't be accepted by synapse.
  1053. # Generated just like jwt_privatekey.
  1054. bad_privatekey = "\n".join(
  1055. [
  1056. "-----BEGIN RSA PRIVATE KEY-----",
  1057. "MIIBOgIBAAJBAL//SQrKpKbjCCnv/FlasJCv+t3k/MPsZfniJe4DVFhsktF2lwQv",
  1058. "gLjmQD3jBUTz+/FndLSBvr3F4OHtGL9O/osCAwEAAQJAJqH0jZJW7Smzo9ShP02L",
  1059. "R6HRZcLExZuUrWI+5ZSP7TaZ1uwJzGFspDrunqaVoPobndw/8VsP8HFyKtceC7vY",
  1060. "uQIhAPdYInDDSJ8rFKGiy3Ajv5KWISBicjevWHF9dbotmNO9AiEAxrdRJVU+EI9I",
  1061. "eB4qRZpY6n4pnwyP0p8f/A3NBaQPG+cCIFlj08aW/PbxNdqYoBdeBA0xDrXKfmbb",
  1062. "iwYxBkwL0JCtAiBYmsi94sJn09u2Y4zpuCbJeDPKzWkbuwQh+W1fhIWQJQIhAKR0",
  1063. "KydN6cRLvphNQ9c/vBTdlzWxzcSxREpguC7F1J1m",
  1064. "-----END RSA PRIVATE KEY-----",
  1065. ]
  1066. )
  1067. def default_config(self) -> Dict[str, Any]:
  1068. config = super().default_config()
  1069. config["jwt_config"] = {
  1070. "enabled": True,
  1071. "secret": self.jwt_pubkey,
  1072. "algorithm": "RS256",
  1073. }
  1074. return config
  1075. def jwt_encode(self, payload: Dict[str, Any], secret: str = jwt_privatekey) -> str:
  1076. header = {"alg": "RS256"}
  1077. if secret.startswith("-----BEGIN RSA PRIVATE KEY-----"):
  1078. secret = JsonWebKey.import_key(secret, {"kty": "RSA"})
  1079. result: bytes = jwt.encode(header, payload, secret)
  1080. return result.decode("ascii")
  1081. def jwt_login(self, *args: Any) -> FakeChannel:
  1082. params = {"type": "org.matrix.login.jwt", "token": self.jwt_encode(*args)}
  1083. channel = self.make_request(b"POST", LOGIN_URL, params)
  1084. return channel
  1085. def test_login_jwt_valid(self) -> None:
  1086. channel = self.jwt_login({"sub": "kermit"})
  1087. self.assertEqual(channel.code, 200, msg=channel.result)
  1088. self.assertEqual(channel.json_body["user_id"], "@kermit:test")
  1089. def test_login_jwt_invalid_signature(self) -> None:
  1090. channel = self.jwt_login({"sub": "frog"}, self.bad_privatekey)
  1091. self.assertEqual(channel.code, 403, msg=channel.result)
  1092. self.assertEqual(channel.json_body["errcode"], "M_FORBIDDEN")
  1093. self.assertEqual(
  1094. channel.json_body["error"],
  1095. "JWT validation failed: Signature verification failed",
  1096. )
  1097. AS_USER = "as_user_alice"
  1098. class AppserviceLoginRestServletTestCase(unittest.HomeserverTestCase):
  1099. servlets = [
  1100. login.register_servlets,
  1101. register.register_servlets,
  1102. ]
  1103. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  1104. self.hs = self.setup_test_homeserver()
  1105. self.service = ApplicationService(
  1106. id="unique_identifier",
  1107. token="some_token",
  1108. sender="@asbot:example.com",
  1109. namespaces={
  1110. ApplicationService.NS_USERS: [
  1111. {"regex": r"@as_user.*", "exclusive": False}
  1112. ],
  1113. ApplicationService.NS_ROOMS: [],
  1114. ApplicationService.NS_ALIASES: [],
  1115. },
  1116. )
  1117. self.another_service = ApplicationService(
  1118. id="another__identifier",
  1119. token="another_token",
  1120. sender="@as2bot:example.com",
  1121. namespaces={
  1122. ApplicationService.NS_USERS: [
  1123. {"regex": r"@as2_user.*", "exclusive": False}
  1124. ],
  1125. ApplicationService.NS_ROOMS: [],
  1126. ApplicationService.NS_ALIASES: [],
  1127. },
  1128. )
  1129. self.hs.get_datastores().main.services_cache.append(self.service)
  1130. self.hs.get_datastores().main.services_cache.append(self.another_service)
  1131. return self.hs
  1132. def test_login_appservice_user(self) -> None:
  1133. """Test that an appservice user can use /login"""
  1134. self.register_appservice_user(AS_USER, self.service.token)
  1135. params = {
  1136. "type": login.LoginRestServlet.APPSERVICE_TYPE,
  1137. "identifier": {"type": "m.id.user", "user": AS_USER},
  1138. }
  1139. channel = self.make_request(
  1140. b"POST", LOGIN_URL, params, access_token=self.service.token
  1141. )
  1142. self.assertEqual(channel.code, 200, msg=channel.result)
  1143. def test_login_appservice_user_bot(self) -> None:
  1144. """Test that the appservice bot can use /login"""
  1145. self.register_appservice_user(AS_USER, self.service.token)
  1146. params = {
  1147. "type": login.LoginRestServlet.APPSERVICE_TYPE,
  1148. "identifier": {"type": "m.id.user", "user": self.service.sender},
  1149. }
  1150. channel = self.make_request(
  1151. b"POST", LOGIN_URL, params, access_token=self.service.token
  1152. )
  1153. self.assertEqual(channel.code, 200, msg=channel.result)
  1154. def test_login_appservice_wrong_user(self) -> None:
  1155. """Test that non-as users cannot login with the as token"""
  1156. self.register_appservice_user(AS_USER, self.service.token)
  1157. params = {
  1158. "type": login.LoginRestServlet.APPSERVICE_TYPE,
  1159. "identifier": {"type": "m.id.user", "user": "fibble_wibble"},
  1160. }
  1161. channel = self.make_request(
  1162. b"POST", LOGIN_URL, params, access_token=self.service.token
  1163. )
  1164. self.assertEqual(channel.code, 403, msg=channel.result)
  1165. def test_login_appservice_wrong_as(self) -> None:
  1166. """Test that as users cannot login with wrong as token"""
  1167. self.register_appservice_user(AS_USER, self.service.token)
  1168. params = {
  1169. "type": login.LoginRestServlet.APPSERVICE_TYPE,
  1170. "identifier": {"type": "m.id.user", "user": AS_USER},
  1171. }
  1172. channel = self.make_request(
  1173. b"POST", LOGIN_URL, params, access_token=self.another_service.token
  1174. )
  1175. self.assertEqual(channel.code, 403, msg=channel.result)
  1176. def test_login_appservice_no_token(self) -> None:
  1177. """Test that users must provide a token when using the appservice
  1178. login method
  1179. """
  1180. self.register_appservice_user(AS_USER, self.service.token)
  1181. params = {
  1182. "type": login.LoginRestServlet.APPSERVICE_TYPE,
  1183. "identifier": {"type": "m.id.user", "user": AS_USER},
  1184. }
  1185. channel = self.make_request(b"POST", LOGIN_URL, params)
  1186. self.assertEqual(channel.code, 401, msg=channel.result)
  1187. @skip_unless(HAS_OIDC, "requires OIDC")
  1188. class UsernamePickerTestCase(HomeserverTestCase):
  1189. """Tests for the username picker flow of SSO login"""
  1190. servlets = [login.register_servlets]
  1191. def default_config(self) -> Dict[str, Any]:
  1192. config = super().default_config()
  1193. config["public_baseurl"] = BASE_URL
  1194. config["oidc_config"] = {}
  1195. config["oidc_config"].update(TEST_OIDC_CONFIG)
  1196. config["oidc_config"]["user_mapping_provider"] = {
  1197. "config": {"display_name_template": "{{ user.displayname }}"}
  1198. }
  1199. # whitelist this client URI so we redirect straight to it rather than
  1200. # serving a confirmation page
  1201. config["sso"] = {"client_whitelist": ["https://x"]}
  1202. return config
  1203. def create_resource_dict(self) -> Dict[str, Resource]:
  1204. d = super().create_resource_dict()
  1205. d.update(build_synapse_client_resource_tree(self.hs))
  1206. return d
  1207. def test_username_picker(self) -> None:
  1208. """Test the happy path of a username picker flow."""
  1209. fake_oidc_server = self.helper.fake_oidc_server()
  1210. # do the start of the login flow
  1211. channel, _ = self.helper.auth_via_oidc(
  1212. fake_oidc_server,
  1213. {"sub": "tester", "displayname": "Jonny"},
  1214. TEST_CLIENT_REDIRECT_URL,
  1215. )
  1216. # that should redirect to the username picker
  1217. self.assertEqual(channel.code, 302, channel.result)
  1218. location_headers = channel.headers.getRawHeaders("Location")
  1219. assert location_headers
  1220. picker_url = location_headers[0]
  1221. self.assertEqual(picker_url, "/_synapse/client/pick_username/account_details")
  1222. # ... with a username_mapping_session cookie
  1223. cookies: Dict[str, str] = {}
  1224. channel.extract_cookies(cookies)
  1225. self.assertIn("username_mapping_session", cookies)
  1226. session_id = cookies["username_mapping_session"]
  1227. # introspect the sso handler a bit to check that the username mapping session
  1228. # looks ok.
  1229. username_mapping_sessions = self.hs.get_sso_handler()._username_mapping_sessions
  1230. self.assertIn(
  1231. session_id,
  1232. username_mapping_sessions,
  1233. "session id not found in map",
  1234. )
  1235. session = username_mapping_sessions[session_id]
  1236. self.assertEqual(session.remote_user_id, "tester")
  1237. self.assertEqual(session.display_name, "Jonny")
  1238. self.assertEqual(session.client_redirect_url, TEST_CLIENT_REDIRECT_URL)
  1239. # the expiry time should be about 15 minutes away
  1240. expected_expiry = self.clock.time_msec() + (15 * 60 * 1000)
  1241. self.assertApproximates(session.expiry_time_ms, expected_expiry, tolerance=1000)
  1242. # Now, submit a username to the username picker, which should serve a redirect
  1243. # to the completion page
  1244. content = urlencode({b"username": b"bobby"}).encode("utf8")
  1245. chan = self.make_request(
  1246. "POST",
  1247. path=picker_url,
  1248. content=content,
  1249. content_is_form=True,
  1250. custom_headers=[
  1251. ("Cookie", "username_mapping_session=" + session_id),
  1252. # old versions of twisted don't do form-parsing without a valid
  1253. # content-length header.
  1254. ("Content-Length", str(len(content))),
  1255. ],
  1256. )
  1257. self.assertEqual(chan.code, 302, chan.result)
  1258. location_headers = chan.headers.getRawHeaders("Location")
  1259. assert location_headers
  1260. # send a request to the completion page, which should 302 to the client redirectUrl
  1261. chan = self.make_request(
  1262. "GET",
  1263. path=location_headers[0],
  1264. custom_headers=[("Cookie", "username_mapping_session=" + session_id)],
  1265. )
  1266. self.assertEqual(chan.code, 302, chan.result)
  1267. location_headers = chan.headers.getRawHeaders("Location")
  1268. assert location_headers
  1269. # ensure that the returned location matches the requested redirect URL
  1270. path, query = location_headers[0].split("?", 1)
  1271. self.assertEqual(path, "https://x")
  1272. # it will have url-encoded the params properly, so we'll have to parse them
  1273. params = urllib.parse.parse_qsl(
  1274. query, keep_blank_values=True, strict_parsing=True, errors="strict"
  1275. )
  1276. self.assertEqual(params[0:2], EXPECTED_CLIENT_REDIRECT_URL_PARAMS)
  1277. self.assertEqual(params[2][0], "loginToken")
  1278. # fish the login token out of the returned redirect uri
  1279. login_token = params[2][1]
  1280. # finally, submit the matrix login token to the login API, which gives us our
  1281. # matrix access token, mxid, and device id.
  1282. chan = self.make_request(
  1283. "POST",
  1284. "/login",
  1285. content={"type": "m.login.token", "token": login_token},
  1286. )
  1287. self.assertEqual(chan.code, 200, chan.result)
  1288. self.assertEqual(chan.json_body["user_id"], "@bobby:test")