test_oidc.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2020 Quentin Gliech
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import json
  16. from urllib.parse import parse_qs, urlparse
  17. from mock import Mock, patch
  18. import attr
  19. import pymacaroons
  20. from twisted.internet import defer
  21. from twisted.python.failure import Failure
  22. from twisted.web._newclient import ResponseDone
  23. from synapse.handlers.oidc_handler import (
  24. MappingException,
  25. OidcError,
  26. OidcHandler,
  27. OidcMappingProvider,
  28. )
  29. from synapse.types import UserID
  30. from tests.unittest import HomeserverTestCase, override_config
  31. @attr.s
  32. class FakeResponse:
  33. code = attr.ib()
  34. body = attr.ib()
  35. phrase = attr.ib()
  36. def deliverBody(self, protocol):
  37. protocol.dataReceived(self.body)
  38. protocol.connectionLost(Failure(ResponseDone()))
  39. # These are a few constants that are used as config parameters in the tests.
  40. ISSUER = "https://issuer/"
  41. CLIENT_ID = "test-client-id"
  42. CLIENT_SECRET = "test-client-secret"
  43. BASE_URL = "https://synapse/"
  44. CALLBACK_URL = BASE_URL + "_synapse/oidc/callback"
  45. SCOPES = ["openid"]
  46. AUTHORIZATION_ENDPOINT = ISSUER + "authorize"
  47. TOKEN_ENDPOINT = ISSUER + "token"
  48. USERINFO_ENDPOINT = ISSUER + "userinfo"
  49. WELL_KNOWN = ISSUER + ".well-known/openid-configuration"
  50. JWKS_URI = ISSUER + ".well-known/jwks.json"
  51. # config for common cases
  52. COMMON_CONFIG = {
  53. "discover": False,
  54. "authorization_endpoint": AUTHORIZATION_ENDPOINT,
  55. "token_endpoint": TOKEN_ENDPOINT,
  56. "jwks_uri": JWKS_URI,
  57. }
  58. # The cookie name and path don't really matter, just that it has to be coherent
  59. # between the callback & redirect handlers.
  60. COOKIE_NAME = b"oidc_session"
  61. COOKIE_PATH = "/_synapse/oidc"
  62. MockedMappingProvider = Mock(OidcMappingProvider)
  63. def simple_async_mock(return_value=None, raises=None):
  64. # AsyncMock is not available in python3.5, this mimics part of its behaviour
  65. async def cb(*args, **kwargs):
  66. if raises:
  67. raise raises
  68. return return_value
  69. return Mock(side_effect=cb)
  70. async def get_json(url):
  71. # Mock get_json calls to handle jwks & oidc discovery endpoints
  72. if url == WELL_KNOWN:
  73. # Minimal discovery document, as defined in OpenID.Discovery
  74. # https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata
  75. return {
  76. "issuer": ISSUER,
  77. "authorization_endpoint": AUTHORIZATION_ENDPOINT,
  78. "token_endpoint": TOKEN_ENDPOINT,
  79. "jwks_uri": JWKS_URI,
  80. "userinfo_endpoint": USERINFO_ENDPOINT,
  81. "response_types_supported": ["code"],
  82. "subject_types_supported": ["public"],
  83. "id_token_signing_alg_values_supported": ["RS256"],
  84. }
  85. elif url == JWKS_URI:
  86. return {"keys": []}
  87. class OidcHandlerTestCase(HomeserverTestCase):
  88. def make_homeserver(self, reactor, clock):
  89. self.http_client = Mock(spec=["get_json"])
  90. self.http_client.get_json.side_effect = get_json
  91. self.http_client.user_agent = "Synapse Test"
  92. config = self.default_config()
  93. config["public_baseurl"] = BASE_URL
  94. oidc_config = config.get("oidc_config", {})
  95. oidc_config["enabled"] = True
  96. oidc_config["client_id"] = CLIENT_ID
  97. oidc_config["client_secret"] = CLIENT_SECRET
  98. oidc_config["issuer"] = ISSUER
  99. oidc_config["scopes"] = SCOPES
  100. oidc_config["user_mapping_provider"] = {
  101. "module": __name__ + ".MockedMappingProvider"
  102. }
  103. config["oidc_config"] = oidc_config
  104. hs = self.setup_test_homeserver(
  105. http_client=self.http_client,
  106. proxied_http_client=self.http_client,
  107. config=config,
  108. )
  109. self.handler = OidcHandler(hs)
  110. return hs
  111. def metadata_edit(self, values):
  112. return patch.dict(self.handler._provider_metadata, values)
  113. def assertRenderedError(self, error, error_description=None):
  114. args = self.handler._render_error.call_args[0]
  115. self.assertEqual(args[1], error)
  116. if error_description is not None:
  117. self.assertEqual(args[2], error_description)
  118. # Reset the render_error mock
  119. self.handler._render_error.reset_mock()
  120. def test_config(self):
  121. """Basic config correctly sets up the callback URL and client auth correctly."""
  122. self.assertEqual(self.handler._callback_url, CALLBACK_URL)
  123. self.assertEqual(self.handler._client_auth.client_id, CLIENT_ID)
  124. self.assertEqual(self.handler._client_auth.client_secret, CLIENT_SECRET)
  125. @override_config({"oidc_config": {"discover": True}})
  126. @defer.inlineCallbacks
  127. def test_discovery(self):
  128. """The handler should discover the endpoints from OIDC discovery document."""
  129. # This would throw if some metadata were invalid
  130. metadata = yield defer.ensureDeferred(self.handler.load_metadata())
  131. self.http_client.get_json.assert_called_once_with(WELL_KNOWN)
  132. self.assertEqual(metadata.issuer, ISSUER)
  133. self.assertEqual(metadata.authorization_endpoint, AUTHORIZATION_ENDPOINT)
  134. self.assertEqual(metadata.token_endpoint, TOKEN_ENDPOINT)
  135. self.assertEqual(metadata.jwks_uri, JWKS_URI)
  136. # FIXME: it seems like authlib does not have that defined in its metadata models
  137. # self.assertEqual(metadata.userinfo_endpoint, USERINFO_ENDPOINT)
  138. # subsequent calls should be cached
  139. self.http_client.reset_mock()
  140. yield defer.ensureDeferred(self.handler.load_metadata())
  141. self.http_client.get_json.assert_not_called()
  142. @override_config({"oidc_config": COMMON_CONFIG})
  143. @defer.inlineCallbacks
  144. def test_no_discovery(self):
  145. """When discovery is disabled, it should not try to load from discovery document."""
  146. yield defer.ensureDeferred(self.handler.load_metadata())
  147. self.http_client.get_json.assert_not_called()
  148. @override_config({"oidc_config": COMMON_CONFIG})
  149. @defer.inlineCallbacks
  150. def test_load_jwks(self):
  151. """JWKS loading is done once (then cached) if used."""
  152. jwks = yield defer.ensureDeferred(self.handler.load_jwks())
  153. self.http_client.get_json.assert_called_once_with(JWKS_URI)
  154. self.assertEqual(jwks, {"keys": []})
  155. # subsequent calls should be cached…
  156. self.http_client.reset_mock()
  157. yield defer.ensureDeferred(self.handler.load_jwks())
  158. self.http_client.get_json.assert_not_called()
  159. # …unless forced
  160. self.http_client.reset_mock()
  161. yield defer.ensureDeferred(self.handler.load_jwks(force=True))
  162. self.http_client.get_json.assert_called_once_with(JWKS_URI)
  163. # Throw if the JWKS uri is missing
  164. with self.metadata_edit({"jwks_uri": None}):
  165. with self.assertRaises(RuntimeError):
  166. yield defer.ensureDeferred(self.handler.load_jwks(force=True))
  167. # Return empty key set if JWKS are not used
  168. self.handler._scopes = [] # not asking the openid scope
  169. self.http_client.get_json.reset_mock()
  170. jwks = yield defer.ensureDeferred(self.handler.load_jwks(force=True))
  171. self.http_client.get_json.assert_not_called()
  172. self.assertEqual(jwks, {"keys": []})
  173. @override_config({"oidc_config": COMMON_CONFIG})
  174. def test_validate_config(self):
  175. """Provider metadatas are extensively validated."""
  176. h = self.handler
  177. # Default test config does not throw
  178. h._validate_metadata()
  179. with self.metadata_edit({"issuer": None}):
  180. self.assertRaisesRegex(ValueError, "issuer", h._validate_metadata)
  181. with self.metadata_edit({"issuer": "http://insecure/"}):
  182. self.assertRaisesRegex(ValueError, "issuer", h._validate_metadata)
  183. with self.metadata_edit({"issuer": "https://invalid/?because=query"}):
  184. self.assertRaisesRegex(ValueError, "issuer", h._validate_metadata)
  185. with self.metadata_edit({"authorization_endpoint": None}):
  186. self.assertRaisesRegex(
  187. ValueError, "authorization_endpoint", h._validate_metadata
  188. )
  189. with self.metadata_edit({"authorization_endpoint": "http://insecure/auth"}):
  190. self.assertRaisesRegex(
  191. ValueError, "authorization_endpoint", h._validate_metadata
  192. )
  193. with self.metadata_edit({"token_endpoint": None}):
  194. self.assertRaisesRegex(ValueError, "token_endpoint", h._validate_metadata)
  195. with self.metadata_edit({"token_endpoint": "http://insecure/token"}):
  196. self.assertRaisesRegex(ValueError, "token_endpoint", h._validate_metadata)
  197. with self.metadata_edit({"jwks_uri": None}):
  198. self.assertRaisesRegex(ValueError, "jwks_uri", h._validate_metadata)
  199. with self.metadata_edit({"jwks_uri": "http://insecure/jwks.json"}):
  200. self.assertRaisesRegex(ValueError, "jwks_uri", h._validate_metadata)
  201. with self.metadata_edit({"response_types_supported": ["id_token"]}):
  202. self.assertRaisesRegex(
  203. ValueError, "response_types_supported", h._validate_metadata
  204. )
  205. with self.metadata_edit(
  206. {"token_endpoint_auth_methods_supported": ["client_secret_basic"]}
  207. ):
  208. # should not throw, as client_secret_basic is the default auth method
  209. h._validate_metadata()
  210. with self.metadata_edit(
  211. {"token_endpoint_auth_methods_supported": ["client_secret_post"]}
  212. ):
  213. self.assertRaisesRegex(
  214. ValueError,
  215. "token_endpoint_auth_methods_supported",
  216. h._validate_metadata,
  217. )
  218. # Tests for configs that the userinfo endpoint
  219. self.assertFalse(h._uses_userinfo)
  220. h._scopes = [] # do not request the openid scope
  221. self.assertTrue(h._uses_userinfo)
  222. self.assertRaisesRegex(ValueError, "userinfo_endpoint", h._validate_metadata)
  223. with self.metadata_edit(
  224. {"userinfo_endpoint": USERINFO_ENDPOINT, "jwks_uri": None}
  225. ):
  226. # Shouldn't raise with a valid userinfo, even without
  227. h._validate_metadata()
  228. @override_config({"oidc_config": {"skip_verification": True}})
  229. def test_skip_verification(self):
  230. """Provider metadata validation can be disabled by config."""
  231. with self.metadata_edit({"issuer": "http://insecure"}):
  232. # This should not throw
  233. self.handler._validate_metadata()
  234. @defer.inlineCallbacks
  235. def test_redirect_request(self):
  236. """The redirect request has the right arguments & generates a valid session cookie."""
  237. req = Mock(spec=["addCookie"])
  238. url = yield defer.ensureDeferred(
  239. self.handler.handle_redirect_request(req, b"http://client/redirect")
  240. )
  241. url = urlparse(url)
  242. auth_endpoint = urlparse(AUTHORIZATION_ENDPOINT)
  243. self.assertEqual(url.scheme, auth_endpoint.scheme)
  244. self.assertEqual(url.netloc, auth_endpoint.netloc)
  245. self.assertEqual(url.path, auth_endpoint.path)
  246. params = parse_qs(url.query)
  247. self.assertEqual(params["redirect_uri"], [CALLBACK_URL])
  248. self.assertEqual(params["response_type"], ["code"])
  249. self.assertEqual(params["scope"], [" ".join(SCOPES)])
  250. self.assertEqual(params["client_id"], [CLIENT_ID])
  251. self.assertEqual(len(params["state"]), 1)
  252. self.assertEqual(len(params["nonce"]), 1)
  253. # Check what is in the cookie
  254. # note: python3.5 mock does not have the .called_once() method
  255. calls = req.addCookie.call_args_list
  256. self.assertEqual(len(calls), 1) # called once
  257. # For some reason, call.args does not work with python3.5
  258. args = calls[0][0]
  259. kwargs = calls[0][1]
  260. self.assertEqual(args[0], COOKIE_NAME)
  261. self.assertEqual(kwargs["path"], COOKIE_PATH)
  262. cookie = args[1]
  263. macaroon = pymacaroons.Macaroon.deserialize(cookie)
  264. state = self.handler._get_value_from_macaroon(macaroon, "state")
  265. nonce = self.handler._get_value_from_macaroon(macaroon, "nonce")
  266. redirect = self.handler._get_value_from_macaroon(
  267. macaroon, "client_redirect_url"
  268. )
  269. self.assertEqual(params["state"], [state])
  270. self.assertEqual(params["nonce"], [nonce])
  271. self.assertEqual(redirect, "http://client/redirect")
  272. @defer.inlineCallbacks
  273. def test_callback_error(self):
  274. """Errors from the provider returned in the callback are displayed."""
  275. self.handler._render_error = Mock()
  276. request = Mock(args={})
  277. request.args[b"error"] = [b"invalid_client"]
  278. yield defer.ensureDeferred(self.handler.handle_oidc_callback(request))
  279. self.assertRenderedError("invalid_client", "")
  280. request.args[b"error_description"] = [b"some description"]
  281. yield defer.ensureDeferred(self.handler.handle_oidc_callback(request))
  282. self.assertRenderedError("invalid_client", "some description")
  283. @defer.inlineCallbacks
  284. def test_callback(self):
  285. """Code callback works and display errors if something went wrong.
  286. A lot of scenarios are tested here:
  287. - when the callback works, with userinfo from ID token
  288. - when the user mapping fails
  289. - when ID token verification fails
  290. - when the callback works, with userinfo fetched from the userinfo endpoint
  291. - when the userinfo fetching fails
  292. - when the code exchange fails
  293. """
  294. token = {
  295. "type": "bearer",
  296. "id_token": "id_token",
  297. "access_token": "access_token",
  298. }
  299. userinfo = {
  300. "sub": "foo",
  301. "preferred_username": "bar",
  302. }
  303. user_id = UserID("foo", "domain.org")
  304. self.handler._render_error = Mock(return_value=None)
  305. self.handler._exchange_code = simple_async_mock(return_value=token)
  306. self.handler._parse_id_token = simple_async_mock(return_value=userinfo)
  307. self.handler._fetch_userinfo = simple_async_mock(return_value=userinfo)
  308. self.handler._map_userinfo_to_user = simple_async_mock(return_value=user_id)
  309. self.handler._auth_handler.complete_sso_login = simple_async_mock()
  310. request = Mock(spec=["args", "getCookie", "addCookie"])
  311. code = "code"
  312. state = "state"
  313. nonce = "nonce"
  314. client_redirect_url = "http://client/redirect"
  315. session = self.handler._generate_oidc_session_token(
  316. state=state,
  317. nonce=nonce,
  318. client_redirect_url=client_redirect_url,
  319. ui_auth_session_id=None,
  320. )
  321. request.getCookie.return_value = session
  322. request.args = {}
  323. request.args[b"code"] = [code.encode("utf-8")]
  324. request.args[b"state"] = [state.encode("utf-8")]
  325. yield defer.ensureDeferred(self.handler.handle_oidc_callback(request))
  326. self.handler._auth_handler.complete_sso_login.assert_called_once_with(
  327. user_id, request, client_redirect_url,
  328. )
  329. self.handler._exchange_code.assert_called_once_with(code)
  330. self.handler._parse_id_token.assert_called_once_with(token, nonce=nonce)
  331. self.handler._map_userinfo_to_user.assert_called_once_with(userinfo, token)
  332. self.handler._fetch_userinfo.assert_not_called()
  333. self.handler._render_error.assert_not_called()
  334. # Handle mapping errors
  335. self.handler._map_userinfo_to_user = simple_async_mock(
  336. raises=MappingException()
  337. )
  338. yield defer.ensureDeferred(self.handler.handle_oidc_callback(request))
  339. self.assertRenderedError("mapping_error")
  340. self.handler._map_userinfo_to_user = simple_async_mock(return_value=user_id)
  341. # Handle ID token errors
  342. self.handler._parse_id_token = simple_async_mock(raises=Exception())
  343. yield defer.ensureDeferred(self.handler.handle_oidc_callback(request))
  344. self.assertRenderedError("invalid_token")
  345. self.handler._auth_handler.complete_sso_login.reset_mock()
  346. self.handler._exchange_code.reset_mock()
  347. self.handler._parse_id_token.reset_mock()
  348. self.handler._map_userinfo_to_user.reset_mock()
  349. self.handler._fetch_userinfo.reset_mock()
  350. # With userinfo fetching
  351. self.handler._scopes = [] # do not ask the "openid" scope
  352. yield defer.ensureDeferred(self.handler.handle_oidc_callback(request))
  353. self.handler._auth_handler.complete_sso_login.assert_called_once_with(
  354. user_id, request, client_redirect_url,
  355. )
  356. self.handler._exchange_code.assert_called_once_with(code)
  357. self.handler._parse_id_token.assert_not_called()
  358. self.handler._map_userinfo_to_user.assert_called_once_with(userinfo, token)
  359. self.handler._fetch_userinfo.assert_called_once_with(token)
  360. self.handler._render_error.assert_not_called()
  361. # Handle userinfo fetching error
  362. self.handler._fetch_userinfo = simple_async_mock(raises=Exception())
  363. yield defer.ensureDeferred(self.handler.handle_oidc_callback(request))
  364. self.assertRenderedError("fetch_error")
  365. # Handle code exchange failure
  366. self.handler._exchange_code = simple_async_mock(
  367. raises=OidcError("invalid_request")
  368. )
  369. yield defer.ensureDeferred(self.handler.handle_oidc_callback(request))
  370. self.assertRenderedError("invalid_request")
  371. @defer.inlineCallbacks
  372. def test_callback_session(self):
  373. """The callback verifies the session presence and validity"""
  374. self.handler._render_error = Mock(return_value=None)
  375. request = Mock(spec=["args", "getCookie", "addCookie"])
  376. # Missing cookie
  377. request.args = {}
  378. request.getCookie.return_value = None
  379. yield defer.ensureDeferred(self.handler.handle_oidc_callback(request))
  380. self.assertRenderedError("missing_session", "No session cookie found")
  381. # Missing session parameter
  382. request.args = {}
  383. request.getCookie.return_value = "session"
  384. yield defer.ensureDeferred(self.handler.handle_oidc_callback(request))
  385. self.assertRenderedError("invalid_request", "State parameter is missing")
  386. # Invalid cookie
  387. request.args = {}
  388. request.args[b"state"] = [b"state"]
  389. request.getCookie.return_value = "session"
  390. yield defer.ensureDeferred(self.handler.handle_oidc_callback(request))
  391. self.assertRenderedError("invalid_session")
  392. # Mismatching session
  393. session = self.handler._generate_oidc_session_token(
  394. state="state",
  395. nonce="nonce",
  396. client_redirect_url="http://client/redirect",
  397. ui_auth_session_id=None,
  398. )
  399. request.args = {}
  400. request.args[b"state"] = [b"mismatching state"]
  401. request.getCookie.return_value = session
  402. yield defer.ensureDeferred(self.handler.handle_oidc_callback(request))
  403. self.assertRenderedError("mismatching_session")
  404. # Valid session
  405. request.args = {}
  406. request.args[b"state"] = [b"state"]
  407. request.getCookie.return_value = session
  408. yield defer.ensureDeferred(self.handler.handle_oidc_callback(request))
  409. self.assertRenderedError("invalid_request")
  410. @override_config({"oidc_config": {"client_auth_method": "client_secret_post"}})
  411. @defer.inlineCallbacks
  412. def test_exchange_code(self):
  413. """Code exchange behaves correctly and handles various error scenarios."""
  414. token = {"type": "bearer"}
  415. token_json = json.dumps(token).encode("utf-8")
  416. self.http_client.request = simple_async_mock(
  417. return_value=FakeResponse(code=200, phrase=b"OK", body=token_json)
  418. )
  419. code = "code"
  420. ret = yield defer.ensureDeferred(self.handler._exchange_code(code))
  421. kwargs = self.http_client.request.call_args[1]
  422. self.assertEqual(ret, token)
  423. self.assertEqual(kwargs["method"], "POST")
  424. self.assertEqual(kwargs["uri"], TOKEN_ENDPOINT)
  425. args = parse_qs(kwargs["data"].decode("utf-8"))
  426. self.assertEqual(args["grant_type"], ["authorization_code"])
  427. self.assertEqual(args["code"], [code])
  428. self.assertEqual(args["client_id"], [CLIENT_ID])
  429. self.assertEqual(args["client_secret"], [CLIENT_SECRET])
  430. self.assertEqual(args["redirect_uri"], [CALLBACK_URL])
  431. # Test error handling
  432. self.http_client.request = simple_async_mock(
  433. return_value=FakeResponse(
  434. code=400,
  435. phrase=b"Bad Request",
  436. body=b'{"error": "foo", "error_description": "bar"}',
  437. )
  438. )
  439. with self.assertRaises(OidcError) as exc:
  440. yield defer.ensureDeferred(self.handler._exchange_code(code))
  441. self.assertEqual(exc.exception.error, "foo")
  442. self.assertEqual(exc.exception.error_description, "bar")
  443. # Internal server error with no JSON body
  444. self.http_client.request = simple_async_mock(
  445. return_value=FakeResponse(
  446. code=500, phrase=b"Internal Server Error", body=b"Not JSON",
  447. )
  448. )
  449. with self.assertRaises(OidcError) as exc:
  450. yield defer.ensureDeferred(self.handler._exchange_code(code))
  451. self.assertEqual(exc.exception.error, "server_error")
  452. # Internal server error with JSON body
  453. self.http_client.request = simple_async_mock(
  454. return_value=FakeResponse(
  455. code=500,
  456. phrase=b"Internal Server Error",
  457. body=b'{"error": "internal_server_error"}',
  458. )
  459. )
  460. with self.assertRaises(OidcError) as exc:
  461. yield defer.ensureDeferred(self.handler._exchange_code(code))
  462. self.assertEqual(exc.exception.error, "internal_server_error")
  463. # 4xx error without "error" field
  464. self.http_client.request = simple_async_mock(
  465. return_value=FakeResponse(code=400, phrase=b"Bad request", body=b"{}",)
  466. )
  467. with self.assertRaises(OidcError) as exc:
  468. yield defer.ensureDeferred(self.handler._exchange_code(code))
  469. self.assertEqual(exc.exception.error, "server_error")
  470. # 2xx error with "error" field
  471. self.http_client.request = simple_async_mock(
  472. return_value=FakeResponse(
  473. code=200, phrase=b"OK", body=b'{"error": "some_error"}',
  474. )
  475. )
  476. with self.assertRaises(OidcError) as exc:
  477. yield defer.ensureDeferred(self.handler._exchange_code(code))
  478. self.assertEqual(exc.exception.error, "some_error")