test_oidc.py 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314
  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 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._token_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. from synapse.handlers.oidc import OidcSessionData
  1086. handler = hs.get_oidc_handler()
  1087. provider = handler._providers["oidc"]
  1088. provider._exchange_code = simple_async_mock(return_value={"id_token": ""}) # type: ignore[assignment]
  1089. provider._parse_id_token = simple_async_mock(return_value=userinfo) # type: ignore[assignment]
  1090. provider._fetch_userinfo = simple_async_mock(return_value=userinfo) # type: ignore[assignment]
  1091. state = "state"
  1092. session = handler._token_generator.generate_oidc_session_token(
  1093. state=state,
  1094. session_data=OidcSessionData(
  1095. idp_id="oidc",
  1096. nonce="nonce",
  1097. client_redirect_url=client_redirect_url,
  1098. ui_auth_session_id="",
  1099. ),
  1100. )
  1101. request = _build_callback_request("code", state, session)
  1102. await handler.handle_oidc_callback(request)
  1103. def _build_callback_request(
  1104. code: str,
  1105. state: str,
  1106. session: str,
  1107. ip_address: str = "10.0.0.1",
  1108. ):
  1109. """Builds a fake SynapseRequest to mock the browser callback
  1110. Returns a Mock object which looks like the SynapseRequest we get from a browser
  1111. after SSO (before we return to the client)
  1112. Args:
  1113. code: the authorization code which would have been returned by the OIDC
  1114. provider
  1115. state: the "state" param which would have been passed around in the
  1116. query param. Should be the same as was embedded in the session in
  1117. _build_oidc_session.
  1118. session: the "session" which would have been passed around in the cookie.
  1119. ip_address: the IP address to pretend the request came from
  1120. """
  1121. request = Mock(
  1122. spec=[
  1123. "args",
  1124. "getCookie",
  1125. "cookies",
  1126. "requestHeaders",
  1127. "getClientAddress",
  1128. "getHeader",
  1129. ]
  1130. )
  1131. request.cookies = []
  1132. request.getCookie.return_value = session
  1133. request.args = {}
  1134. request.args[b"code"] = [code.encode("utf-8")]
  1135. request.args[b"state"] = [state.encode("utf-8")]
  1136. request.getClientAddress.return_value.host = ip_address
  1137. return request