test_login.py 53 KB

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