1
0

test_oidc.py 49 KB

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