test_oidc.py 52 KB

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