test_login.py 54 KB

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