test_oidc.py 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307
  1. # Copyright 2020 Quentin Gliech
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import json
  15. import os
  16. from unittest.mock import ANY, Mock, patch
  17. from urllib.parse import parse_qs, urlparse
  18. import pymacaroons
  19. from synapse.handlers.sso import MappingException
  20. from synapse.server import HomeServer
  21. from synapse.types import UserID
  22. from synapse.util.macaroons import get_value_from_macaroon
  23. from tests.test_utils import FakeResponse, get_awaitable_result, simple_async_mock
  24. from tests.unittest import HomeserverTestCase, override_config
  25. try:
  26. import authlib # noqa: F401
  27. HAS_OIDC = True
  28. except ImportError:
  29. HAS_OIDC = False
  30. # These are a few constants that are used as config parameters in the tests.
  31. ISSUER = "https://issuer/"
  32. CLIENT_ID = "test-client-id"
  33. CLIENT_SECRET = "test-client-secret"
  34. BASE_URL = "https://synapse/"
  35. CALLBACK_URL = BASE_URL + "_synapse/client/oidc/callback"
  36. SCOPES = ["openid"]
  37. AUTHORIZATION_ENDPOINT = ISSUER + "authorize"
  38. TOKEN_ENDPOINT = ISSUER + "token"
  39. USERINFO_ENDPOINT = ISSUER + "userinfo"
  40. WELL_KNOWN = ISSUER + ".well-known/openid-configuration"
  41. JWKS_URI = ISSUER + ".well-known/jwks.json"
  42. # config for common cases
  43. DEFAULT_CONFIG = {
  44. "enabled": True,
  45. "client_id": CLIENT_ID,
  46. "client_secret": CLIENT_SECRET,
  47. "issuer": ISSUER,
  48. "scopes": SCOPES,
  49. "user_mapping_provider": {"module": __name__ + ".TestMappingProvider"},
  50. }
  51. # extends the default config with explicit OAuth2 endpoints instead of using discovery
  52. EXPLICIT_ENDPOINT_CONFIG = {
  53. **DEFAULT_CONFIG,
  54. "discover": False,
  55. "authorization_endpoint": AUTHORIZATION_ENDPOINT,
  56. "token_endpoint": TOKEN_ENDPOINT,
  57. "jwks_uri": JWKS_URI,
  58. }
  59. class TestMappingProvider:
  60. @staticmethod
  61. def parse_config(config):
  62. return
  63. def __init__(self, config):
  64. pass
  65. def get_remote_user_id(self, userinfo):
  66. return userinfo["sub"]
  67. async def map_user_attributes(self, userinfo, token):
  68. return {"localpart": userinfo["username"], "display_name": None}
  69. # Do not include get_extra_attributes to test backwards compatibility paths.
  70. class TestMappingProviderExtra(TestMappingProvider):
  71. async def get_extra_attributes(self, userinfo, token):
  72. return {"phone": userinfo["phone"]}
  73. class TestMappingProviderFailures(TestMappingProvider):
  74. async def map_user_attributes(self, userinfo, token, failures):
  75. return {
  76. "localpart": userinfo["username"] + (str(failures) if failures else ""),
  77. "display_name": None,
  78. }
  79. async def get_json(url):
  80. # Mock get_json calls to handle jwks & oidc discovery endpoints
  81. if url == WELL_KNOWN:
  82. # Minimal discovery document, as defined in OpenID.Discovery
  83. # https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata
  84. return {
  85. "issuer": ISSUER,
  86. "authorization_endpoint": AUTHORIZATION_ENDPOINT,
  87. "token_endpoint": TOKEN_ENDPOINT,
  88. "jwks_uri": JWKS_URI,
  89. "userinfo_endpoint": USERINFO_ENDPOINT,
  90. "response_types_supported": ["code"],
  91. "subject_types_supported": ["public"],
  92. "id_token_signing_alg_values_supported": ["RS256"],
  93. }
  94. elif url == JWKS_URI:
  95. return {"keys": []}
  96. def _key_file_path() -> str:
  97. """path to a file containing the private half of a test key"""
  98. # this key was generated with:
  99. # openssl ecparam -name prime256v1 -genkey -noout |
  100. # openssl pkcs8 -topk8 -nocrypt -out oidc_test_key.p8
  101. #
  102. # we use PKCS8 rather than SEC-1 (which is what openssl ecparam spits out), because
  103. # that's what Apple use, and we want to be sure that we work with Apple's keys.
  104. #
  105. # (For the record: both PKCS8 and SEC-1 specify (different) ways of representing
  106. # keys using ASN.1. Both are then typically formatted using PEM, which says: use the
  107. # base64-encoded DER encoding of ASN.1, with headers and footers. But we don't
  108. # really need to care about any of that.)
  109. return os.path.join(os.path.dirname(__file__), "oidc_test_key.p8")
  110. def _public_key_file_path() -> str:
  111. """path to a file containing the public half of a test key"""
  112. # this was generated with:
  113. # openssl ec -in oidc_test_key.p8 -pubout -out oidc_test_key.pub.pem
  114. #
  115. # See above about where oidc_test_key.p8 came from
  116. return os.path.join(os.path.dirname(__file__), "oidc_test_key.pub.pem")
  117. class OidcHandlerTestCase(HomeserverTestCase):
  118. if not HAS_OIDC:
  119. skip = "requires OIDC"
  120. def default_config(self):
  121. config = super().default_config()
  122. config["public_baseurl"] = BASE_URL
  123. return config
  124. def make_homeserver(self, reactor, clock):
  125. self.http_client = Mock(spec=["get_json"])
  126. self.http_client.get_json.side_effect = get_json
  127. self.http_client.user_agent = b"Synapse Test"
  128. hs = self.setup_test_homeserver(proxied_http_client=self.http_client)
  129. self.handler = hs.get_oidc_handler()
  130. self.provider = self.handler._providers["oidc"]
  131. sso_handler = hs.get_sso_handler()
  132. # Mock the render error method.
  133. self.render_error = Mock(return_value=None)
  134. sso_handler.render_error = self.render_error
  135. # Reduce the number of attempts when generating MXIDs.
  136. sso_handler._MAP_USERNAME_RETRIES = 3
  137. return hs
  138. def metadata_edit(self, values):
  139. """Modify the result that will be returned by the well-known query"""
  140. async def patched_get_json(uri):
  141. res = await get_json(uri)
  142. if uri == WELL_KNOWN:
  143. res.update(values)
  144. return res
  145. return patch.object(self.http_client, "get_json", patched_get_json)
  146. def assertRenderedError(self, error, error_description=None):
  147. self.render_error.assert_called_once()
  148. args = self.render_error.call_args[0]
  149. self.assertEqual(args[1], error)
  150. if error_description is not None:
  151. self.assertEqual(args[2], error_description)
  152. # Reset the render_error mock
  153. self.render_error.reset_mock()
  154. return args
  155. @override_config({"oidc_config": DEFAULT_CONFIG})
  156. def test_config(self):
  157. """Basic config correctly sets up the callback URL and client auth correctly."""
  158. self.assertEqual(self.provider._callback_url, CALLBACK_URL)
  159. self.assertEqual(self.provider._client_auth.client_id, CLIENT_ID)
  160. self.assertEqual(self.provider._client_auth.client_secret, CLIENT_SECRET)
  161. @override_config({"oidc_config": {**DEFAULT_CONFIG, "discover": True}})
  162. def test_discovery(self):
  163. """The handler should discover the endpoints from OIDC discovery document."""
  164. # This would throw if some metadata were invalid
  165. metadata = self.get_success(self.provider.load_metadata())
  166. self.http_client.get_json.assert_called_once_with(WELL_KNOWN)
  167. self.assertEqual(metadata.issuer, ISSUER)
  168. self.assertEqual(metadata.authorization_endpoint, AUTHORIZATION_ENDPOINT)
  169. self.assertEqual(metadata.token_endpoint, TOKEN_ENDPOINT)
  170. self.assertEqual(metadata.jwks_uri, JWKS_URI)
  171. # FIXME: it seems like authlib does not have that defined in its metadata models
  172. # self.assertEqual(metadata.userinfo_endpoint, USERINFO_ENDPOINT)
  173. # subsequent calls should be cached
  174. self.http_client.reset_mock()
  175. self.get_success(self.provider.load_metadata())
  176. self.http_client.get_json.assert_not_called()
  177. @override_config({"oidc_config": EXPLICIT_ENDPOINT_CONFIG})
  178. def test_no_discovery(self):
  179. """When discovery is disabled, it should not try to load from discovery document."""
  180. self.get_success(self.provider.load_metadata())
  181. self.http_client.get_json.assert_not_called()
  182. @override_config({"oidc_config": EXPLICIT_ENDPOINT_CONFIG})
  183. def test_load_jwks(self):
  184. """JWKS loading is done once (then cached) if used."""
  185. jwks = self.get_success(self.provider.load_jwks())
  186. self.http_client.get_json.assert_called_once_with(JWKS_URI)
  187. self.assertEqual(jwks, {"keys": []})
  188. # subsequent calls should be cached…
  189. self.http_client.reset_mock()
  190. self.get_success(self.provider.load_jwks())
  191. self.http_client.get_json.assert_not_called()
  192. # …unless forced
  193. self.http_client.reset_mock()
  194. self.get_success(self.provider.load_jwks(force=True))
  195. self.http_client.get_json.assert_called_once_with(JWKS_URI)
  196. # Throw if the JWKS uri is missing
  197. original = self.provider.load_metadata
  198. async def patched_load_metadata():
  199. m = (await original()).copy()
  200. m.update({"jwks_uri": None})
  201. return m
  202. with patch.object(self.provider, "load_metadata", patched_load_metadata):
  203. self.get_failure(self.provider.load_jwks(force=True), RuntimeError)
  204. @override_config({"oidc_config": DEFAULT_CONFIG})
  205. def test_validate_config(self):
  206. """Provider metadatas are extensively validated."""
  207. h = self.provider
  208. def force_load_metadata():
  209. async def force_load():
  210. return await h.load_metadata(force=True)
  211. return get_awaitable_result(force_load())
  212. # Default test config does not throw
  213. force_load_metadata()
  214. with self.metadata_edit({"issuer": None}):
  215. self.assertRaisesRegex(ValueError, "issuer", force_load_metadata)
  216. with self.metadata_edit({"issuer": "http://insecure/"}):
  217. self.assertRaisesRegex(ValueError, "issuer", force_load_metadata)
  218. with self.metadata_edit({"issuer": "https://invalid/?because=query"}):
  219. self.assertRaisesRegex(ValueError, "issuer", force_load_metadata)
  220. with self.metadata_edit({"authorization_endpoint": None}):
  221. self.assertRaisesRegex(
  222. ValueError, "authorization_endpoint", force_load_metadata
  223. )
  224. with self.metadata_edit({"authorization_endpoint": "http://insecure/auth"}):
  225. self.assertRaisesRegex(
  226. ValueError, "authorization_endpoint", force_load_metadata
  227. )
  228. with self.metadata_edit({"token_endpoint": None}):
  229. self.assertRaisesRegex(ValueError, "token_endpoint", force_load_metadata)
  230. with self.metadata_edit({"token_endpoint": "http://insecure/token"}):
  231. self.assertRaisesRegex(ValueError, "token_endpoint", force_load_metadata)
  232. with self.metadata_edit({"jwks_uri": None}):
  233. self.assertRaisesRegex(ValueError, "jwks_uri", force_load_metadata)
  234. with self.metadata_edit({"jwks_uri": "http://insecure/jwks.json"}):
  235. self.assertRaisesRegex(ValueError, "jwks_uri", force_load_metadata)
  236. with self.metadata_edit({"response_types_supported": ["id_token"]}):
  237. self.assertRaisesRegex(
  238. ValueError, "response_types_supported", force_load_metadata
  239. )
  240. with self.metadata_edit(
  241. {"token_endpoint_auth_methods_supported": ["client_secret_basic"]}
  242. ):
  243. # should not throw, as client_secret_basic is the default auth method
  244. force_load_metadata()
  245. with self.metadata_edit(
  246. {"token_endpoint_auth_methods_supported": ["client_secret_post"]}
  247. ):
  248. self.assertRaisesRegex(
  249. ValueError,
  250. "token_endpoint_auth_methods_supported",
  251. force_load_metadata,
  252. )
  253. # Tests for configs that require the userinfo endpoint
  254. self.assertFalse(h._uses_userinfo)
  255. self.assertEqual(h._user_profile_method, "auto")
  256. h._user_profile_method = "userinfo_endpoint"
  257. self.assertTrue(h._uses_userinfo)
  258. # Revert the profile method and do not request the "openid" scope: this should
  259. # mean that we check for a userinfo endpoint
  260. h._user_profile_method = "auto"
  261. h._scopes = []
  262. self.assertTrue(h._uses_userinfo)
  263. with self.metadata_edit({"userinfo_endpoint": None}):
  264. self.assertRaisesRegex(ValueError, "userinfo_endpoint", force_load_metadata)
  265. with self.metadata_edit({"jwks_uri": None}):
  266. # Shouldn't raise with a valid userinfo, even without jwks
  267. force_load_metadata()
  268. @override_config({"oidc_config": {**DEFAULT_CONFIG, "skip_verification": True}})
  269. def test_skip_verification(self):
  270. """Provider metadata validation can be disabled by config."""
  271. with self.metadata_edit({"issuer": "http://insecure"}):
  272. # This should not throw
  273. get_awaitable_result(self.provider.load_metadata())
  274. @override_config({"oidc_config": DEFAULT_CONFIG})
  275. def test_redirect_request(self):
  276. """The redirect request has the right arguments & generates a valid session cookie."""
  277. req = Mock(spec=["cookies"])
  278. req.cookies = []
  279. url = self.get_success(
  280. self.provider.handle_redirect_request(req, b"http://client/redirect")
  281. )
  282. url = urlparse(url)
  283. auth_endpoint = urlparse(AUTHORIZATION_ENDPOINT)
  284. self.assertEqual(url.scheme, auth_endpoint.scheme)
  285. self.assertEqual(url.netloc, auth_endpoint.netloc)
  286. self.assertEqual(url.path, auth_endpoint.path)
  287. params = parse_qs(url.query)
  288. self.assertEqual(params["redirect_uri"], [CALLBACK_URL])
  289. self.assertEqual(params["response_type"], ["code"])
  290. self.assertEqual(params["scope"], [" ".join(SCOPES)])
  291. self.assertEqual(params["client_id"], [CLIENT_ID])
  292. self.assertEqual(len(params["state"]), 1)
  293. self.assertEqual(len(params["nonce"]), 1)
  294. # Check what is in the cookies
  295. self.assertEqual(len(req.cookies), 2) # two cookies
  296. cookie_header = req.cookies[0]
  297. # The cookie name and path don't really matter, just that it has to be coherent
  298. # between the callback & redirect handlers.
  299. parts = [p.strip() for p in cookie_header.split(b";")]
  300. self.assertIn(b"Path=/_synapse/client/oidc", parts)
  301. name, cookie = parts[0].split(b"=")
  302. self.assertEqual(name, b"oidc_session")
  303. macaroon = pymacaroons.Macaroon.deserialize(cookie)
  304. state = get_value_from_macaroon(macaroon, "state")
  305. nonce = get_value_from_macaroon(macaroon, "nonce")
  306. redirect = get_value_from_macaroon(macaroon, "client_redirect_url")
  307. self.assertEqual(params["state"], [state])
  308. self.assertEqual(params["nonce"], [nonce])
  309. self.assertEqual(redirect, "http://client/redirect")
  310. @override_config({"oidc_config": DEFAULT_CONFIG})
  311. def test_callback_error(self):
  312. """Errors from the provider returned in the callback are displayed."""
  313. request = Mock(args={})
  314. request.args[b"error"] = [b"invalid_client"]
  315. self.get_success(self.handler.handle_oidc_callback(request))
  316. self.assertRenderedError("invalid_client", "")
  317. request.args[b"error_description"] = [b"some description"]
  318. self.get_success(self.handler.handle_oidc_callback(request))
  319. self.assertRenderedError("invalid_client", "some description")
  320. @override_config({"oidc_config": DEFAULT_CONFIG})
  321. def test_callback(self):
  322. """Code callback works and display errors if something went wrong.
  323. A lot of scenarios are tested here:
  324. - when the callback works, with userinfo from ID token
  325. - when the user mapping fails
  326. - when ID token verification fails
  327. - when the callback works, with userinfo fetched from the userinfo endpoint
  328. - when the userinfo fetching fails
  329. - when the code exchange fails
  330. """
  331. # ensure that we are correctly testing the fallback when "get_extra_attributes"
  332. # is not implemented.
  333. mapping_provider = self.provider._user_mapping_provider
  334. with self.assertRaises(AttributeError):
  335. _ = mapping_provider.get_extra_attributes
  336. token = {
  337. "type": "bearer",
  338. "id_token": "id_token",
  339. "access_token": "access_token",
  340. }
  341. username = "bar"
  342. userinfo = {
  343. "sub": "foo",
  344. "username": username,
  345. }
  346. expected_user_id = "@%s:%s" % (username, self.hs.hostname)
  347. self.provider._exchange_code = simple_async_mock(return_value=token)
  348. self.provider._parse_id_token = simple_async_mock(return_value=userinfo)
  349. self.provider._fetch_userinfo = simple_async_mock(return_value=userinfo)
  350. auth_handler = self.hs.get_auth_handler()
  351. auth_handler.complete_sso_login = simple_async_mock()
  352. code = "code"
  353. state = "state"
  354. nonce = "nonce"
  355. client_redirect_url = "http://client/redirect"
  356. ip_address = "10.0.0.1"
  357. session = self._generate_oidc_session_token(state, nonce, client_redirect_url)
  358. request = _build_callback_request(code, state, session, ip_address=ip_address)
  359. self.get_success(self.handler.handle_oidc_callback(request))
  360. auth_handler.complete_sso_login.assert_called_once_with(
  361. expected_user_id,
  362. "oidc",
  363. request,
  364. client_redirect_url,
  365. None,
  366. new_user=True,
  367. auth_provider_session_id=None,
  368. )
  369. self.provider._exchange_code.assert_called_once_with(code)
  370. self.provider._parse_id_token.assert_called_once_with(token, nonce=nonce)
  371. self.provider._fetch_userinfo.assert_not_called()
  372. self.render_error.assert_not_called()
  373. # Handle mapping errors
  374. with patch.object(
  375. self.provider,
  376. "_remote_id_from_userinfo",
  377. new=Mock(side_effect=MappingException()),
  378. ):
  379. self.get_success(self.handler.handle_oidc_callback(request))
  380. self.assertRenderedError("mapping_error")
  381. # Handle ID token errors
  382. self.provider._parse_id_token = simple_async_mock(raises=Exception())
  383. self.get_success(self.handler.handle_oidc_callback(request))
  384. self.assertRenderedError("invalid_token")
  385. auth_handler.complete_sso_login.reset_mock()
  386. self.provider._exchange_code.reset_mock()
  387. self.provider._parse_id_token.reset_mock()
  388. self.provider._fetch_userinfo.reset_mock()
  389. # With userinfo fetching
  390. self.provider._user_profile_method = "userinfo_endpoint"
  391. token = {
  392. "type": "bearer",
  393. "access_token": "access_token",
  394. }
  395. self.provider._exchange_code = simple_async_mock(return_value=token)
  396. self.get_success(self.handler.handle_oidc_callback(request))
  397. auth_handler.complete_sso_login.assert_called_once_with(
  398. expected_user_id,
  399. "oidc",
  400. request,
  401. client_redirect_url,
  402. None,
  403. new_user=False,
  404. auth_provider_session_id=None,
  405. )
  406. self.provider._exchange_code.assert_called_once_with(code)
  407. self.provider._parse_id_token.assert_not_called()
  408. self.provider._fetch_userinfo.assert_called_once_with(token)
  409. self.render_error.assert_not_called()
  410. # With an ID token, userinfo fetching and sid in the ID token
  411. self.provider._user_profile_method = "userinfo_endpoint"
  412. token = {
  413. "type": "bearer",
  414. "access_token": "access_token",
  415. "id_token": "id_token",
  416. }
  417. id_token = {
  418. "sid": "abcdefgh",
  419. }
  420. self.provider._parse_id_token = simple_async_mock(return_value=id_token)
  421. self.provider._exchange_code = simple_async_mock(return_value=token)
  422. auth_handler.complete_sso_login.reset_mock()
  423. self.provider._fetch_userinfo.reset_mock()
  424. self.get_success(self.handler.handle_oidc_callback(request))
  425. auth_handler.complete_sso_login.assert_called_once_with(
  426. expected_user_id,
  427. "oidc",
  428. request,
  429. client_redirect_url,
  430. None,
  431. new_user=False,
  432. auth_provider_session_id=id_token["sid"],
  433. )
  434. self.provider._exchange_code.assert_called_once_with(code)
  435. self.provider._parse_id_token.assert_called_once_with(token, nonce=nonce)
  436. self.provider._fetch_userinfo.assert_called_once_with(token)
  437. self.render_error.assert_not_called()
  438. # Handle userinfo fetching error
  439. self.provider._fetch_userinfo = simple_async_mock(raises=Exception())
  440. self.get_success(self.handler.handle_oidc_callback(request))
  441. self.assertRenderedError("fetch_error")
  442. # Handle code exchange failure
  443. from synapse.handlers.oidc import OidcError
  444. self.provider._exchange_code = simple_async_mock(
  445. raises=OidcError("invalid_request")
  446. )
  447. self.get_success(self.handler.handle_oidc_callback(request))
  448. self.assertRenderedError("invalid_request")
  449. @override_config({"oidc_config": DEFAULT_CONFIG})
  450. def test_callback_session(self):
  451. """The callback verifies the session presence and validity"""
  452. request = Mock(spec=["args", "getCookie", "cookies"])
  453. # Missing cookie
  454. request.args = {}
  455. request.getCookie.return_value = None
  456. self.get_success(self.handler.handle_oidc_callback(request))
  457. self.assertRenderedError("missing_session", "No session cookie found")
  458. # Missing session parameter
  459. request.args = {}
  460. request.getCookie.return_value = "session"
  461. self.get_success(self.handler.handle_oidc_callback(request))
  462. self.assertRenderedError("invalid_request", "State parameter is missing")
  463. # Invalid cookie
  464. request.args = {}
  465. request.args[b"state"] = [b"state"]
  466. request.getCookie.return_value = "session"
  467. self.get_success(self.handler.handle_oidc_callback(request))
  468. self.assertRenderedError("invalid_session")
  469. # Mismatching session
  470. session = self._generate_oidc_session_token(
  471. state="state",
  472. nonce="nonce",
  473. client_redirect_url="http://client/redirect",
  474. )
  475. request.args = {}
  476. request.args[b"state"] = [b"mismatching state"]
  477. request.getCookie.return_value = session
  478. self.get_success(self.handler.handle_oidc_callback(request))
  479. self.assertRenderedError("mismatching_session")
  480. # Valid session
  481. request.args = {}
  482. request.args[b"state"] = [b"state"]
  483. request.getCookie.return_value = session
  484. self.get_success(self.handler.handle_oidc_callback(request))
  485. self.assertRenderedError("invalid_request")
  486. @override_config(
  487. {"oidc_config": {**DEFAULT_CONFIG, "client_auth_method": "client_secret_post"}}
  488. )
  489. def test_exchange_code(self):
  490. """Code exchange behaves correctly and handles various error scenarios."""
  491. token = {"type": "bearer"}
  492. token_json = json.dumps(token).encode("utf-8")
  493. self.http_client.request = simple_async_mock(
  494. return_value=FakeResponse(code=200, phrase=b"OK", body=token_json)
  495. )
  496. code = "code"
  497. ret = self.get_success(self.provider._exchange_code(code))
  498. kwargs = self.http_client.request.call_args[1]
  499. self.assertEqual(ret, token)
  500. self.assertEqual(kwargs["method"], "POST")
  501. self.assertEqual(kwargs["uri"], TOKEN_ENDPOINT)
  502. args = parse_qs(kwargs["data"].decode("utf-8"))
  503. self.assertEqual(args["grant_type"], ["authorization_code"])
  504. self.assertEqual(args["code"], [code])
  505. self.assertEqual(args["client_id"], [CLIENT_ID])
  506. self.assertEqual(args["client_secret"], [CLIENT_SECRET])
  507. self.assertEqual(args["redirect_uri"], [CALLBACK_URL])
  508. # Test error handling
  509. self.http_client.request = simple_async_mock(
  510. return_value=FakeResponse(
  511. code=400,
  512. phrase=b"Bad Request",
  513. body=b'{"error": "foo", "error_description": "bar"}',
  514. )
  515. )
  516. from synapse.handlers.oidc import OidcError
  517. exc = self.get_failure(self.provider._exchange_code(code), OidcError)
  518. self.assertEqual(exc.value.error, "foo")
  519. self.assertEqual(exc.value.error_description, "bar")
  520. # Internal server error with no JSON body
  521. self.http_client.request = simple_async_mock(
  522. return_value=FakeResponse(
  523. code=500,
  524. phrase=b"Internal Server Error",
  525. body=b"Not JSON",
  526. )
  527. )
  528. exc = self.get_failure(self.provider._exchange_code(code), OidcError)
  529. self.assertEqual(exc.value.error, "server_error")
  530. # Internal server error with JSON body
  531. self.http_client.request = simple_async_mock(
  532. return_value=FakeResponse(
  533. code=500,
  534. phrase=b"Internal Server Error",
  535. body=b'{"error": "internal_server_error"}',
  536. )
  537. )
  538. exc = self.get_failure(self.provider._exchange_code(code), OidcError)
  539. self.assertEqual(exc.value.error, "internal_server_error")
  540. # 4xx error without "error" field
  541. self.http_client.request = simple_async_mock(
  542. return_value=FakeResponse(
  543. code=400,
  544. phrase=b"Bad request",
  545. body=b"{}",
  546. )
  547. )
  548. exc = self.get_failure(self.provider._exchange_code(code), OidcError)
  549. self.assertEqual(exc.value.error, "server_error")
  550. # 2xx error with "error" field
  551. self.http_client.request = simple_async_mock(
  552. return_value=FakeResponse(
  553. code=200,
  554. phrase=b"OK",
  555. body=b'{"error": "some_error"}',
  556. )
  557. )
  558. exc = self.get_failure(self.provider._exchange_code(code), OidcError)
  559. self.assertEqual(exc.value.error, "some_error")
  560. @override_config(
  561. {
  562. "oidc_config": {
  563. "enabled": True,
  564. "client_id": CLIENT_ID,
  565. "issuer": ISSUER,
  566. "client_auth_method": "client_secret_post",
  567. "client_secret_jwt_key": {
  568. "key_file": _key_file_path(),
  569. "jwt_header": {"alg": "ES256", "kid": "ABC789"},
  570. "jwt_payload": {"iss": "DEFGHI"},
  571. },
  572. }
  573. }
  574. )
  575. def test_exchange_code_jwt_key(self):
  576. """Test that code exchange works with a JWK client secret."""
  577. from authlib.jose import jwt
  578. token = {"type": "bearer"}
  579. self.http_client.request = simple_async_mock(
  580. return_value=FakeResponse(
  581. code=200, phrase=b"OK", body=json.dumps(token).encode("utf-8")
  582. )
  583. )
  584. code = "code"
  585. # advance the clock a bit before we start, so we aren't working with zero
  586. # timestamps.
  587. self.reactor.advance(1000)
  588. start_time = self.reactor.seconds()
  589. ret = self.get_success(self.provider._exchange_code(code))
  590. self.assertEqual(ret, token)
  591. # the request should have hit the token endpoint
  592. kwargs = self.http_client.request.call_args[1]
  593. self.assertEqual(kwargs["method"], "POST")
  594. self.assertEqual(kwargs["uri"], TOKEN_ENDPOINT)
  595. # the client secret provided to the should be a jwt which can be checked with
  596. # the public key
  597. args = parse_qs(kwargs["data"].decode("utf-8"))
  598. secret = args["client_secret"][0]
  599. with open(_public_key_file_path()) as f:
  600. key = f.read()
  601. claims = jwt.decode(secret, key)
  602. self.assertEqual(claims.header["kid"], "ABC789")
  603. self.assertEqual(claims["aud"], ISSUER)
  604. self.assertEqual(claims["iss"], "DEFGHI")
  605. self.assertEqual(claims["sub"], CLIENT_ID)
  606. self.assertEqual(claims["iat"], start_time)
  607. self.assertGreater(claims["exp"], start_time)
  608. # check the rest of the POSTed data
  609. self.assertEqual(args["grant_type"], ["authorization_code"])
  610. self.assertEqual(args["code"], [code])
  611. self.assertEqual(args["client_id"], [CLIENT_ID])
  612. self.assertEqual(args["redirect_uri"], [CALLBACK_URL])
  613. @override_config(
  614. {
  615. "oidc_config": {
  616. "enabled": True,
  617. "client_id": CLIENT_ID,
  618. "issuer": ISSUER,
  619. "client_auth_method": "none",
  620. }
  621. }
  622. )
  623. def test_exchange_code_no_auth(self):
  624. """Test that code exchange works with no client secret."""
  625. token = {"type": "bearer"}
  626. self.http_client.request = simple_async_mock(
  627. return_value=FakeResponse(
  628. code=200, phrase=b"OK", body=json.dumps(token).encode("utf-8")
  629. )
  630. )
  631. code = "code"
  632. ret = self.get_success(self.provider._exchange_code(code))
  633. self.assertEqual(ret, token)
  634. # the request should have hit the token endpoint
  635. kwargs = self.http_client.request.call_args[1]
  636. self.assertEqual(kwargs["method"], "POST")
  637. self.assertEqual(kwargs["uri"], TOKEN_ENDPOINT)
  638. # check the POSTed data
  639. args = parse_qs(kwargs["data"].decode("utf-8"))
  640. self.assertEqual(args["grant_type"], ["authorization_code"])
  641. self.assertEqual(args["code"], [code])
  642. self.assertEqual(args["client_id"], [CLIENT_ID])
  643. self.assertEqual(args["redirect_uri"], [CALLBACK_URL])
  644. @override_config(
  645. {
  646. "oidc_config": {
  647. **DEFAULT_CONFIG,
  648. "user_mapping_provider": {
  649. "module": __name__ + ".TestMappingProviderExtra"
  650. },
  651. }
  652. }
  653. )
  654. def test_extra_attributes(self):
  655. """
  656. Login while using a mapping provider that implements get_extra_attributes.
  657. """
  658. token = {
  659. "type": "bearer",
  660. "id_token": "id_token",
  661. "access_token": "access_token",
  662. }
  663. userinfo = {
  664. "sub": "foo",
  665. "username": "foo",
  666. "phone": "1234567",
  667. }
  668. self.provider._exchange_code = simple_async_mock(return_value=token)
  669. self.provider._parse_id_token = simple_async_mock(return_value=userinfo)
  670. auth_handler = self.hs.get_auth_handler()
  671. auth_handler.complete_sso_login = simple_async_mock()
  672. state = "state"
  673. client_redirect_url = "http://client/redirect"
  674. session = self._generate_oidc_session_token(
  675. state=state,
  676. nonce="nonce",
  677. client_redirect_url=client_redirect_url,
  678. )
  679. request = _build_callback_request("code", state, session)
  680. self.get_success(self.handler.handle_oidc_callback(request))
  681. auth_handler.complete_sso_login.assert_called_once_with(
  682. "@foo:test",
  683. "oidc",
  684. request,
  685. client_redirect_url,
  686. {"phone": "1234567"},
  687. new_user=True,
  688. auth_provider_session_id=None,
  689. )
  690. @override_config({"oidc_config": DEFAULT_CONFIG})
  691. def test_map_userinfo_to_user(self):
  692. """Ensure that mapping the userinfo returned from a provider to an MXID works properly."""
  693. auth_handler = self.hs.get_auth_handler()
  694. auth_handler.complete_sso_login = simple_async_mock()
  695. userinfo = {
  696. "sub": "test_user",
  697. "username": "test_user",
  698. }
  699. self.get_success(_make_callback_with_userinfo(self.hs, userinfo))
  700. auth_handler.complete_sso_login.assert_called_once_with(
  701. "@test_user:test",
  702. "oidc",
  703. ANY,
  704. ANY,
  705. None,
  706. new_user=True,
  707. auth_provider_session_id=None,
  708. )
  709. auth_handler.complete_sso_login.reset_mock()
  710. # Some providers return an integer ID.
  711. userinfo = {
  712. "sub": 1234,
  713. "username": "test_user_2",
  714. }
  715. self.get_success(_make_callback_with_userinfo(self.hs, userinfo))
  716. auth_handler.complete_sso_login.assert_called_once_with(
  717. "@test_user_2:test",
  718. "oidc",
  719. ANY,
  720. ANY,
  721. None,
  722. new_user=True,
  723. auth_provider_session_id=None,
  724. )
  725. auth_handler.complete_sso_login.reset_mock()
  726. # Test if the mxid is already taken
  727. store = self.hs.get_datastores().main
  728. user3 = UserID.from_string("@test_user_3:test")
  729. self.get_success(
  730. store.register_user(user_id=user3.to_string(), password_hash=None)
  731. )
  732. userinfo = {"sub": "test3", "username": "test_user_3"}
  733. self.get_success(_make_callback_with_userinfo(self.hs, userinfo))
  734. auth_handler.complete_sso_login.assert_not_called()
  735. self.assertRenderedError(
  736. "mapping_error",
  737. "Mapping provider does not support de-duplicating Matrix IDs",
  738. )
  739. @override_config({"oidc_config": {**DEFAULT_CONFIG, "allow_existing_users": True}})
  740. def test_map_userinfo_to_existing_user(self):
  741. """Existing users can log in with OpenID Connect when allow_existing_users is True."""
  742. store = self.hs.get_datastores().main
  743. user = UserID.from_string("@test_user:test")
  744. self.get_success(
  745. store.register_user(user_id=user.to_string(), password_hash=None)
  746. )
  747. auth_handler = self.hs.get_auth_handler()
  748. auth_handler.complete_sso_login = simple_async_mock()
  749. # Map a user via SSO.
  750. userinfo = {
  751. "sub": "test",
  752. "username": "test_user",
  753. }
  754. self.get_success(_make_callback_with_userinfo(self.hs, userinfo))
  755. auth_handler.complete_sso_login.assert_called_once_with(
  756. user.to_string(),
  757. "oidc",
  758. ANY,
  759. ANY,
  760. None,
  761. new_user=False,
  762. auth_provider_session_id=None,
  763. )
  764. auth_handler.complete_sso_login.reset_mock()
  765. # Subsequent calls should map to the same mxid.
  766. self.get_success(_make_callback_with_userinfo(self.hs, userinfo))
  767. auth_handler.complete_sso_login.assert_called_once_with(
  768. user.to_string(),
  769. "oidc",
  770. ANY,
  771. ANY,
  772. None,
  773. new_user=False,
  774. auth_provider_session_id=None,
  775. )
  776. auth_handler.complete_sso_login.reset_mock()
  777. # Note that a second SSO user can be mapped to the same Matrix ID. (This
  778. # requires a unique sub, but something that maps to the same matrix ID,
  779. # in this case we'll just use the same username. A more realistic example
  780. # would be subs which are email addresses, and mapping from the localpart
  781. # of the email, e.g. bob@foo.com and bob@bar.com -> @bob:test.)
  782. userinfo = {
  783. "sub": "test1",
  784. "username": "test_user",
  785. }
  786. self.get_success(_make_callback_with_userinfo(self.hs, userinfo))
  787. auth_handler.complete_sso_login.assert_called_once_with(
  788. user.to_string(),
  789. "oidc",
  790. ANY,
  791. ANY,
  792. None,
  793. new_user=False,
  794. auth_provider_session_id=None,
  795. )
  796. auth_handler.complete_sso_login.reset_mock()
  797. # Register some non-exact matching cases.
  798. user2 = UserID.from_string("@TEST_user_2:test")
  799. self.get_success(
  800. store.register_user(user_id=user2.to_string(), password_hash=None)
  801. )
  802. user2_caps = UserID.from_string("@test_USER_2:test")
  803. self.get_success(
  804. store.register_user(user_id=user2_caps.to_string(), password_hash=None)
  805. )
  806. # Attempting to login without matching a name exactly is an error.
  807. userinfo = {
  808. "sub": "test2",
  809. "username": "TEST_USER_2",
  810. }
  811. self.get_success(_make_callback_with_userinfo(self.hs, userinfo))
  812. auth_handler.complete_sso_login.assert_not_called()
  813. args = self.assertRenderedError("mapping_error")
  814. self.assertTrue(
  815. args[2].startswith(
  816. "Attempted to login as '@TEST_USER_2:test' but it matches more than one user inexactly:"
  817. )
  818. )
  819. # Logging in when matching a name exactly should work.
  820. user2 = UserID.from_string("@TEST_USER_2:test")
  821. self.get_success(
  822. store.register_user(user_id=user2.to_string(), password_hash=None)
  823. )
  824. self.get_success(_make_callback_with_userinfo(self.hs, userinfo))
  825. auth_handler.complete_sso_login.assert_called_once_with(
  826. "@TEST_USER_2:test",
  827. "oidc",
  828. ANY,
  829. ANY,
  830. None,
  831. new_user=False,
  832. auth_provider_session_id=None,
  833. )
  834. @override_config({"oidc_config": DEFAULT_CONFIG})
  835. def test_map_userinfo_to_invalid_localpart(self):
  836. """If the mapping provider generates an invalid localpart it should be rejected."""
  837. self.get_success(
  838. _make_callback_with_userinfo(self.hs, {"sub": "test2", "username": "föö"})
  839. )
  840. self.assertRenderedError("mapping_error", "localpart is invalid: föö")
  841. @override_config(
  842. {
  843. "oidc_config": {
  844. **DEFAULT_CONFIG,
  845. "user_mapping_provider": {
  846. "module": __name__ + ".TestMappingProviderFailures"
  847. },
  848. }
  849. }
  850. )
  851. def test_map_userinfo_to_user_retries(self):
  852. """The mapping provider can retry generating an MXID if the MXID is already in use."""
  853. auth_handler = self.hs.get_auth_handler()
  854. auth_handler.complete_sso_login = simple_async_mock()
  855. store = self.hs.get_datastores().main
  856. self.get_success(
  857. store.register_user(user_id="@test_user:test", password_hash=None)
  858. )
  859. userinfo = {
  860. "sub": "test",
  861. "username": "test_user",
  862. }
  863. self.get_success(_make_callback_with_userinfo(self.hs, userinfo))
  864. # test_user is already taken, so test_user1 gets registered instead.
  865. auth_handler.complete_sso_login.assert_called_once_with(
  866. "@test_user1:test",
  867. "oidc",
  868. ANY,
  869. ANY,
  870. None,
  871. new_user=True,
  872. auth_provider_session_id=None,
  873. )
  874. auth_handler.complete_sso_login.reset_mock()
  875. # Register all of the potential mxids for a particular OIDC username.
  876. self.get_success(
  877. store.register_user(user_id="@tester:test", password_hash=None)
  878. )
  879. for i in range(1, 3):
  880. self.get_success(
  881. store.register_user(user_id="@tester%d:test" % i, password_hash=None)
  882. )
  883. # Now attempt to map to a username, this will fail since all potential usernames are taken.
  884. userinfo = {
  885. "sub": "tester",
  886. "username": "tester",
  887. }
  888. self.get_success(_make_callback_with_userinfo(self.hs, userinfo))
  889. auth_handler.complete_sso_login.assert_not_called()
  890. self.assertRenderedError(
  891. "mapping_error", "Unable to generate a Matrix ID from the SSO response"
  892. )
  893. @override_config({"oidc_config": DEFAULT_CONFIG})
  894. def test_empty_localpart(self):
  895. """Attempts to map onto an empty localpart should be rejected."""
  896. userinfo = {
  897. "sub": "tester",
  898. "username": "",
  899. }
  900. self.get_success(_make_callback_with_userinfo(self.hs, userinfo))
  901. self.assertRenderedError("mapping_error", "localpart is invalid: ")
  902. @override_config(
  903. {
  904. "oidc_config": {
  905. **DEFAULT_CONFIG,
  906. "user_mapping_provider": {
  907. "config": {"localpart_template": "{{ user.username }}"}
  908. },
  909. }
  910. }
  911. )
  912. def test_null_localpart(self):
  913. """Mapping onto a null localpart via an empty OIDC attribute should be rejected"""
  914. userinfo = {
  915. "sub": "tester",
  916. "username": None,
  917. }
  918. self.get_success(_make_callback_with_userinfo(self.hs, userinfo))
  919. self.assertRenderedError("mapping_error", "localpart is invalid: ")
  920. @override_config(
  921. {
  922. "oidc_config": {
  923. **DEFAULT_CONFIG,
  924. "attribute_requirements": [{"attribute": "test", "value": "foobar"}],
  925. }
  926. }
  927. )
  928. def test_attribute_requirements(self):
  929. """The required attributes must be met from the OIDC userinfo response."""
  930. auth_handler = self.hs.get_auth_handler()
  931. auth_handler.complete_sso_login = simple_async_mock()
  932. # userinfo lacking "test": "foobar" attribute should fail.
  933. userinfo = {
  934. "sub": "tester",
  935. "username": "tester",
  936. }
  937. self.get_success(_make_callback_with_userinfo(self.hs, userinfo))
  938. auth_handler.complete_sso_login.assert_not_called()
  939. # userinfo with "test": "foobar" attribute should succeed.
  940. userinfo = {
  941. "sub": "tester",
  942. "username": "tester",
  943. "test": "foobar",
  944. }
  945. self.get_success(_make_callback_with_userinfo(self.hs, userinfo))
  946. # check that the auth handler got called as expected
  947. auth_handler.complete_sso_login.assert_called_once_with(
  948. "@tester:test",
  949. "oidc",
  950. ANY,
  951. ANY,
  952. None,
  953. new_user=True,
  954. auth_provider_session_id=None,
  955. )
  956. @override_config(
  957. {
  958. "oidc_config": {
  959. **DEFAULT_CONFIG,
  960. "attribute_requirements": [{"attribute": "test", "value": "foobar"}],
  961. }
  962. }
  963. )
  964. def test_attribute_requirements_contains(self):
  965. """Test that auth succeeds if userinfo attribute CONTAINS required value"""
  966. auth_handler = self.hs.get_auth_handler()
  967. auth_handler.complete_sso_login = simple_async_mock()
  968. # userinfo with "test": ["foobar", "foo", "bar"] attribute should succeed.
  969. userinfo = {
  970. "sub": "tester",
  971. "username": "tester",
  972. "test": ["foobar", "foo", "bar"],
  973. }
  974. self.get_success(_make_callback_with_userinfo(self.hs, userinfo))
  975. # check that the auth handler got called as expected
  976. auth_handler.complete_sso_login.assert_called_once_with(
  977. "@tester:test",
  978. "oidc",
  979. ANY,
  980. ANY,
  981. None,
  982. new_user=True,
  983. auth_provider_session_id=None,
  984. )
  985. @override_config(
  986. {
  987. "oidc_config": {
  988. **DEFAULT_CONFIG,
  989. "attribute_requirements": [{"attribute": "test", "value": "foobar"}],
  990. }
  991. }
  992. )
  993. def test_attribute_requirements_mismatch(self):
  994. """
  995. Test that auth fails if attributes exist but don't match,
  996. or are non-string values.
  997. """
  998. auth_handler = self.hs.get_auth_handler()
  999. auth_handler.complete_sso_login = simple_async_mock()
  1000. # userinfo with "test": "not_foobar" attribute should fail
  1001. userinfo = {
  1002. "sub": "tester",
  1003. "username": "tester",
  1004. "test": "not_foobar",
  1005. }
  1006. self.get_success(_make_callback_with_userinfo(self.hs, userinfo))
  1007. auth_handler.complete_sso_login.assert_not_called()
  1008. # userinfo with "test": ["foo", "bar"] attribute should fail
  1009. userinfo = {
  1010. "sub": "tester",
  1011. "username": "tester",
  1012. "test": ["foo", "bar"],
  1013. }
  1014. self.get_success(_make_callback_with_userinfo(self.hs, userinfo))
  1015. auth_handler.complete_sso_login.assert_not_called()
  1016. # userinfo with "test": False attribute should fail
  1017. # this is largely just to ensure we don't crash here
  1018. userinfo = {
  1019. "sub": "tester",
  1020. "username": "tester",
  1021. "test": False,
  1022. }
  1023. self.get_success(_make_callback_with_userinfo(self.hs, userinfo))
  1024. auth_handler.complete_sso_login.assert_not_called()
  1025. # userinfo with "test": None attribute should fail
  1026. # a value of None breaks the OIDC spec, but it's important to not crash here
  1027. userinfo = {
  1028. "sub": "tester",
  1029. "username": "tester",
  1030. "test": None,
  1031. }
  1032. self.get_success(_make_callback_with_userinfo(self.hs, userinfo))
  1033. auth_handler.complete_sso_login.assert_not_called()
  1034. # userinfo with "test": 1 attribute should fail
  1035. # this is largely just to ensure we don't crash here
  1036. userinfo = {
  1037. "sub": "tester",
  1038. "username": "tester",
  1039. "test": 1,
  1040. }
  1041. self.get_success(_make_callback_with_userinfo(self.hs, userinfo))
  1042. auth_handler.complete_sso_login.assert_not_called()
  1043. # userinfo with "test": 3.14 attribute should fail
  1044. # this is largely just to ensure we don't crash here
  1045. userinfo = {
  1046. "sub": "tester",
  1047. "username": "tester",
  1048. "test": 3.14,
  1049. }
  1050. self.get_success(_make_callback_with_userinfo(self.hs, userinfo))
  1051. auth_handler.complete_sso_login.assert_not_called()
  1052. def _generate_oidc_session_token(
  1053. self,
  1054. state: str,
  1055. nonce: str,
  1056. client_redirect_url: str,
  1057. ui_auth_session_id: str = "",
  1058. ) -> str:
  1059. from synapse.handlers.oidc import OidcSessionData
  1060. return self.handler._token_generator.generate_oidc_session_token(
  1061. state=state,
  1062. session_data=OidcSessionData(
  1063. idp_id="oidc",
  1064. nonce=nonce,
  1065. client_redirect_url=client_redirect_url,
  1066. ui_auth_session_id=ui_auth_session_id,
  1067. ),
  1068. )
  1069. async def _make_callback_with_userinfo(
  1070. hs: HomeServer, userinfo: dict, client_redirect_url: str = "http://client/redirect"
  1071. ) -> None:
  1072. """Mock up an OIDC callback with the given userinfo dict
  1073. We'll pull out the OIDC handler from the homeserver, stub out a couple of methods,
  1074. and poke in the userinfo dict as if it were the response to an OIDC userinfo call.
  1075. Args:
  1076. hs: the HomeServer impl to send the callback to.
  1077. userinfo: the OIDC userinfo dict
  1078. client_redirect_url: the URL to redirect to on success.
  1079. """
  1080. from synapse.handlers.oidc import OidcSessionData
  1081. handler = hs.get_oidc_handler()
  1082. provider = handler._providers["oidc"]
  1083. provider._exchange_code = simple_async_mock(return_value={"id_token": ""})
  1084. provider._parse_id_token = simple_async_mock(return_value=userinfo)
  1085. provider._fetch_userinfo = simple_async_mock(return_value=userinfo)
  1086. state = "state"
  1087. session = handler._token_generator.generate_oidc_session_token(
  1088. state=state,
  1089. session_data=OidcSessionData(
  1090. idp_id="oidc",
  1091. nonce="nonce",
  1092. client_redirect_url=client_redirect_url,
  1093. ui_auth_session_id="",
  1094. ),
  1095. )
  1096. request = _build_callback_request("code", state, session)
  1097. await handler.handle_oidc_callback(request)
  1098. def _build_callback_request(
  1099. code: str,
  1100. state: str,
  1101. session: str,
  1102. ip_address: str = "10.0.0.1",
  1103. ):
  1104. """Builds a fake SynapseRequest to mock the browser callback
  1105. Returns a Mock object which looks like the SynapseRequest we get from a browser
  1106. after SSO (before we return to the client)
  1107. Args:
  1108. code: the authorization code which would have been returned by the OIDC
  1109. provider
  1110. state: the "state" param which would have been passed around in the
  1111. query param. Should be the same as was embedded in the session in
  1112. _build_oidc_session.
  1113. session: the "session" which would have been passed around in the cookie.
  1114. ip_address: the IP address to pretend the request came from
  1115. """
  1116. request = Mock(
  1117. spec=[
  1118. "args",
  1119. "getCookie",
  1120. "cookies",
  1121. "requestHeaders",
  1122. "getClientIP",
  1123. "getHeader",
  1124. ]
  1125. )
  1126. request.cookies = []
  1127. request.getCookie.return_value = session
  1128. request.args = {}
  1129. request.args[b"code"] = [code.encode("utf-8")]
  1130. request.args[b"state"] = [state.encode("utf-8")]
  1131. request.getClientIP.return_value = ip_address
  1132. return request