test_login.py 53 KB

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