test_login.py 51 KB

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