test_login.py 52 KB

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