test_oidc.py 46 KB

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