Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
auth: Implement support for multiple OIDC IdPs.
Mateusz Mandera0b37a8bc6aea
diff --git a/docs/production/authentication-methods.md b/docs/production/authentication-methods.mdindex f377d1f5dda..4ba9c862f46 100644--- a/docs/production/authentication-methods.md+++ b/docs/production/authentication-methods.md@@ -1176,8 +1176,6 @@ If your server was originally installed from a release in thefile. You can find instructions on how to do that in a[separate doc][update-inline-comments].-Note that `SOCIAL_AUTH_OIDC_ENABLED_IDPS` only supports a single IdP currently.-The Return URL to authorize with the provider is`https://yourzulipdomain.example.com/complete/oidc/`.diff --git a/zerver/tests/test_auth_backends.py b/zerver/tests/test_auth_backends.pyindex 8cb93faaaa9..2b9589459cc 100644--- a/zerver/tests/test_auth_backends.py+++ b/zerver/tests/test_auth_backends.py@@ -86,6 +86,7 @@ from zerver.lib.test_helpers import ()from zerver.lib.thumbnail import DEFAULT_AVATAR_SIZE, MEDIUM_AVATAR_SIZE, resize_avatarfrom zerver.lib.types import Validator+from zerver.lib.url_encoding import append_url_query_stringfrom zerver.lib.user_groups import (get_system_user_group_by_name,get_system_user_group_for_user,@@ -841,7 +842,9 @@ class SocialAuthBase(DesktopFlowTestingLib, ZulipTestCase, ABC):params["next"] = nextparams["multiuse_object_key"] = multiuse_object_keyif len(params) > 0:- url += f"?{urlencode(params)}"+ query = urlencode(params)+ url = append_url_query_string(url, query)+if user_agent is not None:headers["HTTP_USER_AGENT"] = user_agent@@ -2568,7 +2571,7 @@ class SAMLAuthBackendTest(SocialAuthBase):result = self.client_get("/accounts/login/social/saml")self.assertEqual(info_log.output[0],- "INFO:root:Attempted to initiate SAML authentication with wrong idp argument: None",+ "INFO:root:Attempted to initiate saml authentication with wrong idp argument: None",)self.assertEqual(result.status_code, 500)self.assert_in_response("Configuration error", result)@@ -3028,7 +3031,7 @@ class SAMLAuthBackendTest(SocialAuthBase):self.assert_in_response("SAML authentication", result)self.assertEqual(info_log.output[0],- "INFO:root:Attempted to initiate SAML authentication with wrong idp argument: None",+ "INFO:root:Attempted to initiate saml authentication with wrong idp argument: None",)with self.assertLogs(level="INFO") as info_log:@@ -3036,7 +3039,7 @@ class SAMLAuthBackendTest(SocialAuthBase):# No such IdP is configured.self.assertEqual(info_log.output[0],- "INFO:root:Attempted to initiate SAML authentication with wrong idp argument: nonexistent_idp",+ "INFO:root:Attempted to initiate saml authentication with wrong idp argument: nonexistent_idp",)self.assertEqual(result.status_code, 500)self.assert_in_response("Configuration error", result)@@ -4242,8 +4245,8 @@ class GenericOpenIdConnectTest(SocialAuthBase):BACKEND_CLASS = GenericOpenIdConnectBackendCLIENT_KEY_SETTING = "SOCIAL_AUTH_TESTOIDC_KEY"CLIENT_SECRET_SETTING = "SOCIAL_AUTH_TESTOIDC_SECRET"- LOGIN_URL = "/accounts/login/social/oidc"- SIGNUP_URL = "/accounts/register/social/oidc"+ LOGIN_URL = "/accounts/login/social/oidc/testoidc"+ SIGNUP_URL = "/accounts/register/social/oidc/testoidc"BASE_OIDC_URL = "https://example.com/api/openid"AUTHORIZATION_URL = f"{BASE_OIDC_URL}/authorize"@@ -4252,23 +4255,19 @@ class GenericOpenIdConnectTest(SocialAuthBase):USER_INFO_URL = f"{BASE_OIDC_URL}/userinfo"AUTH_FINISH_URL = "/complete/oidc/"- @override- def social_auth_test(- self,- *args: Any,- **kwargs: Any,- ) -> "TestHttpResponse":+ def _default_discovery_payload(self, base_oidc_url: str) -> dict[str, Any]:# Example payload of the discovery endpoint (with appropriate values filled# in to match our test setup).# All the attributes below are REQUIRED per OIDC specification:# https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata# or at least required for the `code` flow with userinfo - that this implementation uses.# Other flows are not supported right now.- idp_discovery_endpoint_payload_dict = {- "issuer": self.BASE_OIDC_URL,- "authorization_endpoint": self.AUTHORIZATION_URL,- "token_endpoint": self.ACCESS_TOKEN_URL,- "userinfo_endpoint": self.USER_INFO_URL,+ return {+ "issuer": base_oidc_url,+ "authorization_endpoint": f"{base_oidc_url}/authorize",+ "token_endpoint": f"{base_oidc_url}/token",+ "userinfo_endpoint": f"{base_oidc_url}/userinfo",+ "jwks_uri": f"{base_oidc_url}/jwks.json","response_types_supported": ["code","id_token",@@ -4277,21 +4276,42 @@ class GenericOpenIdConnectTest(SocialAuthBase):"code id_token","code id_token token",],- "jwks_uri": self.JWKS_URL,"id_token_signing_alg_values_supported": ["HS256", "RS256"],"subject_types_supported": ["public"],}- # We need to run the social_auth_test procedure with a mock response set up for the- # OIDC discovery endpoint as that's the first thing requested by the server when a user- # starts trying to authenticate.- with responses.RequestsMock(assert_all_requests_are_fired=False) as requests_mock:+ @contextmanager+ def mock_oidc_discovery(+ self,+ base_oidc_url: str,+ *,+ assert_all_requests_are_fired: bool = False,+ ) -> Iterator[responses.RequestsMock]:+ discovery_url = f"{base_oidc_url}/.well-known/openid-configuration"+ body = json.dumps(self._default_discovery_payload(base_oidc_url))++ with responses.RequestsMock(+ assert_all_requests_are_fired=assert_all_requests_are_fired+ ) as requests_mock:requests_mock.add(- requests_mock.GET,- f"{self.BASE_OIDC_URL}/.well-known/openid-configuration",+ method=responses.GET,+ url=discovery_url,status=200,- body=json.dumps(idp_discovery_endpoint_payload_dict),+ body=body,+ content_type="application/json",)+ yield requests_mock++ @override+ def social_auth_test(+ self,+ *args: Any,+ **kwargs: Any,+ ) -> "TestHttpResponse":+ # We need to run the social_auth_test procedure with a mock response set up for the+ # OIDC discovery endpoint as that's the first thing requested by the server when a user+ # starts trying to authenticate.+ with self.mock_oidc_discovery(self.BASE_OIDC_URL):result = super().social_auth_test(*args, **kwargs)return result@@ -4323,6 +4343,16 @@ class GenericOpenIdConnectTest(SocialAuthBase):json=json.loads(EXAMPLE_JWK),)+ discovery_url = f"{self.BASE_OIDC_URL}/.well-known/openid-configuration"+ body = json.dumps(self._default_discovery_payload(self.BASE_OIDC_URL))+ requests_mock.add(+ method=responses.GET,+ url=discovery_url,+ status=200,+ body=body,+ content_type="application/json",+ )+@overridedef generate_access_token_url_payload(self, account_data_dict: dict[str, str]) -> str:return json.dumps(@@ -4432,30 +4462,137 @@ class GenericOpenIdConnectTest(SocialAuthBase):[f"ERROR:django.request:Internal Server Error: {self.LOGIN_URL}"],)- def test_too_many_idps(self) -> None:- """- Only one IdP is supported for now.- """- account_data_dict = self.get_account_data_dict(email=self.email, name=self.name)-- mock_oidc_setting_dict = copy.deepcopy(settings.SOCIAL_AUTH_OIDC_ENABLED_IDPS)- [idp_config_dict] = mock_oidc_setting_dict.values()- mock_oidc_setting_dict["secondprovider"] = idp_config_dictwith (self.settings(SOCIAL_AUTH_OIDC_ENABLED_IDPS=mock_oidc_setting_dict),self.assertLogs("django.request", level="ERROR") as m,):result = self.social_auth_test(- account_data_dict, subdomain="zulip", next="/user_uploads/image"+ account_data_dict, is_signup=True, subdomain="zulip", next="/user_uploads/image")self.assertEqual(result.status_code, 500)self.assert_in_response("Configuration error", result)self.assert_in_response("OpenID Connect", result)self.assertEqual(- m.output,- [f"ERROR:django.request:Internal Server Error: {self.LOGIN_URL}"],+ m.output, [f"ERROR:django.request:Internal Server Error: {self.SIGNUP_URL}"])+ def test_social_auth_oidc_multiple_idps_configured(self) -> None:+ idps_dict = copy.deepcopy(settings.SOCIAL_AUTH_OIDC_ENABLED_IDPS)+ idps_dict["testoidc2"] = copy.deepcopy(idps_dict["testoidc"])+ idps_dict["testoidc2"]["oidc_url"] = "https://example.com/idp2/api/openid"+ idps_dict["testoidc2"]["display_name"] = "Second Test IdP"+ idps_dict["testoidc2"]["limit_to_subdomains"] = ["zulip"]+ with self.settings(SOCIAL_AUTH_OIDC_ENABLED_IDPS=idps_dict):+ # Go to the login page and check that buttons to log in show up for both IdPs:+ result = self.client_get("/accounts/login/")+ self.assert_in_success_response(["Log in with Test IdP"], result)+ self.assert_in_success_response(["/accounts/login/social/oidc/testoidc"], result)+ self.assert_in_success_response(["Log in with Second Test IdP"], result)+ self.assert_in_success_response(["/accounts/login/social/oidc/testoidc2"], result)++ # Try successful authentication with the regular idp from all previous tests:+ self.test_social_auth_success()++ # Now test with the second idp:+ original_LOGIN_URL = self.LOGIN_URL+ original_SIGNUP_URL = self.SIGNUP_URL+ original_AUTHORIZATION_URL = self.AUTHORIZATION_URL+ original_BASE_OIDC_URL = self.BASE_OIDC_URL+ original_ACCESS_TOKEN_URL = self.ACCESS_TOKEN_URL+ original_JWKS_URL = self.JWKS_URL+ original_USER_INFO_URL = self.USER_INFO_URL+ original_AUTH_FINISH_URL = self.AUTH_FINISH_URL+ self.LOGIN_URL = "/accounts/login/social/oidc/testoidc2"+ self.SIGNUP_URL = "/accounts/register/social/oidc/testoidc2"+ self.BASE_OIDC_URL = idps_dict["testoidc2"]["oidc_url"]+ self.AUTHORIZATION_URL = f"{self.BASE_OIDC_URL}/authorize"+ self.ACCESS_TOKEN_URL = f"{self.BASE_OIDC_URL}/token"+ self.JWKS_URL = f"{self.BASE_OIDC_URL}/jwks"+ self.USER_INFO_URL = f"{self.BASE_OIDC_URL}/userinfo"+ try:+ self.test_social_auth_success()+ finally:+ # Restore original values at the end, regardless of what happens+ # in the block above, to avoid affecting other tests in unpredictable+ # ways.+ self.LOGIN_URL = original_LOGIN_URL+ self.SIGNUP_URL = original_SIGNUP_URL+ self.AUTHORIZATION_URL = original_AUTHORIZATION_URL+ self.BASE_OIDC_URL = original_BASE_OIDC_URL+ self.ACCESS_TOKEN_URL = original_ACCESS_TOKEN_URL+ self.JWKS_URL = original_JWKS_URL+ self.USER_INFO_URL = original_USER_INFO_URL+ self.AUTH_FINISH_URL = original_AUTH_FINISH_URL++ def test_no_idp_parameter(self) -> None:+ with self.assertLogs(self.logger_string, level="INFO") as m:+ result = self.client_get(reverse("social:begin", args=[self.backend.name]))+ self.assert_json_error(result, "Missing idp param")+ self.assertEqual(+ m.output, [self.logger_output("/login/oidc/: Missing idp param.", type="info")]+ )++ def test_social_auth_oidc_idp_limited_to_subdomains_attempt_wrong_realm(self) -> None:+ idps_dict = copy.deepcopy(settings.SOCIAL_AUTH_OIDC_ENABLED_IDPS)+ idps_dict["testoidc"]["limit_to_subdomains"] = ["zulip"]+ with self.settings(SOCIAL_AUTH_OIDC_ENABLED_IDPS=idps_dict):+ account_data_dict = self.get_account_data_dict(email=self.email, name=self.name)+ with self.assertLogs(self.logger_string, level="INFO") as m:+ result = self.social_auth_test(account_data_dict, subdomain="zephyr")+ self.assertEqual(result.status_code, 302)+ self.assertEqual("/login/", result["Location"])+ self.assertEqual(+ m.output,+ [+ self.logger_output(+ "/complete/oidc/: Authentication request with IdP testoidc but this provider is not enabled "+ "for this subdomain zephyr.",+ "info",+ )+ ],+ )++ @override+ def test_social_auth_complete(self) -> None:+ def mock_process_error(backend: BaseOAuth2, data: Mapping[str, object]) -> None:+ raise AuthFailed(backend, "Not found")++ with (+ mock.patch(+ "social_core.backends.oauth.BaseOAuth2.process_error",+ autospec=True,+ side_effect=mock_process_error,+ ),+ self.assertLogs(self.logger_string, level="INFO") as m,+ ):+ result = self.client_get(reverse("social:complete", args=[self.backend.name]))+ self.assertEqual(result.status_code, 302)+ self.assertIn("login", result["Location"])+ self.assertEqual(+ m.output,+ [+ self.logger_output("AuthFailed: Authentication failed: Not found", "info"),+ ],+ )++ with (+ self.assertLogs(self.logger_string, level="WARNING") as m,+ ):+ result = self.client_get(reverse("social:complete", args=[self.backend.name]))+ self.assertEqual(result.status_code, 302)+ self.assertIn("login", result["Location"])+ self.assertEqual(+ m.output,+ [+ self.logger_output("Missing needed parameter state", "warning"),+ ],+ )++ @override+ def test_social_auth_session_fields_cleared_correctly(self) -> None:+ with self.mock_oidc_discovery(self.BASE_OIDC_URL):+ super().test_social_auth_session_fields_cleared_correctly()+@overridedef test_config_error_development(self) -> None:"""@@ -5797,44 +5934,54 @@ class ExternalMethodDictsTests(ZulipTestCase):[string.format("register") for string in expected_button_id_strings], result)- def test_get_external_method_dicts_multiple_saml_idps(self) -> None:- idps_dict = copy.deepcopy(settings.SOCIAL_AUTH_SAML_ENABLED_IDPS)+ def test_get_external_method_dicts_multiple_saml_oidc_idps(self) -> None:+ saml_idps_dict = copy.deepcopy(settings.SOCIAL_AUTH_SAML_ENABLED_IDPS)# Create another IdP config, by copying the original one and changing some details.idps_dict['test_idp'])- idps_dict["test_idp2"] = copy.deepcopy(idps_dict["test_idp"])- idps_dict["test_idp2"]["url"] = "https://idp2.example.com/idp/profile/SAML2/Redirect/SSO"- idps_dict["test_idp2"]["display_name"] = "Second Test IdP"- idps_dict["test_idp2"]["limit_to_subdomains"] = ["zephyr"]+ saml_idps_dict["test_idp2"] = copy.deepcopy(saml_idps_dict["test_idp"])+ saml_idps_dict["test_idp2"]["url"] = (+ "https://idp2.example.com/idp/profile/SAML2/Redirect/SSO"+ )+ saml_idps_dict["test_idp2"]["display_name"] = "Second Test IdP"+ saml_idps_dict["test_idp2"]["limit_to_subdomains"] = ["zephyr"]++ oidc_idps_dict = copy.deepcopy(settings.SOCIAL_AUTH_OIDC_ENABLED_IDPS)+ oidc_idps_dict["testoidc2"] = copy.deepcopy(oidc_idps_dict["testoidc"])+ oidc_idps_dict["testoidc2"]["oidc_url"] = "https://example.com/idp2/api/openid"+ oidc_idps_dict["testoidc2"]["display_name"] = "Second Test IdP"+ oidc_idps_dict["testoidc2"]["limit_to_subdomains"] = ["zephyr"]with self.settings(- SOCIAL_AUTH_SAML_ENABLED_IDPS=idps_dict,+ SOCIAL_AUTH_SAML_ENABLED_IDPS=saml_idps_dict,+ SOCIAL_AUTH_OIDC_ENABLED_IDPS=oidc_idps_dict,AUTHENTICATION_BACKENDS=("zproject.backends.EmailAuthBackend","zproject.backends.GitHubAuthBackend","zproject.backends.SAMLAuthBackend",+ "zproject.backends.GenericOpenIdConnectBackend",),):# Calling get_external_method_dicts without a realm returns all methods configured on the server:external_auth_methods = get_external_method_dicts()- # 1 IdP enabled for all realms + a dict for GitHub auth- self.assert_length(external_auth_methods, 2)+ # 1 IdP enabled for all realms for SAML as well as OIDC + a dict for GitHub auth+ self.assert_length(external_auth_methods, 3)self.assertEqual(- [external_auth_methods[0]["name"], external_auth_methods[1]["name"]],- ["saml:test_idp", "github"],+ {method["name"] for method in external_auth_methods},+ {"saml:test_idp", "oidc:testoidc", "github"},)external_auth_methods = get_external_method_dicts(get_realm("zulip"))- # Only test_idp enabled for the zulip realm, + GitHub auth.- self.assert_length(external_auth_methods, 2)+ # Only test_idp end testoidc nabled for the zulip realm, + GitHub auth.+ self.assert_length(external_auth_methods, 3)self.assertEqual(- [external_auth_methods[0]["name"], external_auth_methods[1]["name"]],- ["saml:test_idp", "github"],+ {method["name"] for method in external_auth_methods},+ {"saml:test_idp", "oidc:testoidc", "github"},)external_auth_methods = get_external_method_dicts(get_realm("zephyr"))# Both idps enabled for the zephyr realm, + GitHub auth.- self.assert_length(external_auth_methods, 3)+ self.assert_length(external_auth_methods, 5)self.assertEqual(- {external_auth_methods[0]["name"], external_auth_methods[1]["name"]},- {"saml:test_idp", "saml:test_idp2"},+ {method["name"] for method in external_auth_methods},+ {"saml:test_idp", "saml:test_idp2", "oidc:testoidc", "oidc:testoidc2", "github"},)diff --git a/zerver/views/auth.py b/zerver/views/auth.pyindex ff585a1ea42..dec1487905c 100644--- a/zerver/views/auth.py+++ b/zerver/views/auth.py@@ -106,6 +106,7 @@ from zproject.backends import (sync_groups_for_prereg_user,validate_otp_params,)+from zproject.settings_types import OIDCIdPConfigDict, SAMLIdPConfigDictif TYPE_CHECKING:from django.http.request import _ImmutableQueryDict@@ -716,23 +717,33 @@ def _start_social_auth_flow(authentication flow (both login and signup)."""extra_url_params: dict[str, str] = {}- if backend == "saml":- if not SAMLAuthBackend.check_config():- return config_error(request, "saml")-- # This backend requires the name of the IdP (from the list of configured ones)+ if backend in ["saml", "oidc"]:+ idps_settings_dict: dict[str, SAMLIdPConfigDict] | dict[str, OIDCIdPConfigDict]+ match backend:+ case "saml":+ if not SAMLAuthBackend.check_config():+ return config_error(request, "saml")+ idps_settings_dict = settings.SOCIAL_AUTH_SAML_ENABLED_IDPS+ case "oidc":+ if not GenericOpenIdConnectBackend.check_config():+ return config_error(request, "oidc")+ idps_settings_dict = settings.SOCIAL_AUTH_OIDC_ENABLED_IDPS+ case _: # nocoverage+ raise AssertionError++ # These backends require the name of the IdP (from the list of configured ones)# to be passed as the parameter.- if not extra_arg or extra_arg not in settings.SOCIAL_AUTH_SAML_ENABLED_IDPS:+ if not extra_arg or extra_arg not in idps_settings_dict:logging.info(- "Attempted to initiate SAML authentication with wrong idp argument: %s", extra_arg+ "Attempted to initiate %s authentication with wrong idp argument: %s",+ backend,+ extra_arg,)- return config_error(request, "saml")+ return config_error(request, backend)extra_url_params = {"idp": extra_arg}if backend == "apple" and not AppleAuthBackend.check_config():return config_error(request, "apple")- if backend == "oidc" and not GenericOpenIdConnectBackend.check_config():- return config_error(request, "oidc")# TODO: Add AzureAD also.if backend in ["github", "google", "gitlab"]:diff --git a/zproject/backends.py b/zproject/backends.pyindex e1b96f3786b..cb71d911284 100644--- a/zproject/backends.py+++ b/zproject/backends.py@@ -3533,19 +3533,20 @@ class GenericOpenIdConnectBackend(SocialAuthMixin, OpenIdConnectAuth):auth_backend_name = "OpenID Connect"sort_order = 100- # Hack: We don't yet support multiple IdPs, but we want this- # module to import if nothing has been configured yet.- settings_dict: OIDCIdPConfigDict- [settings_dict] = settings.SOCIAL_AUTH_OIDC_ENABLED_IDPS.values() or [OIDCIdPConfigDict()]-- display_icon: str | None = settings_dict.get("display_icon", None)- display_name: str = settings_dict.get("display_name", "OIDC")+ REDIS_EXPIRATION_SECONDS = 60 * 15full_name_validated = getattr(settings, "SOCIAL_AUTH_OIDC_FULL_NAME_VALIDATED", False)- # Discovery endpoint for the superclass to read all the appropriate- # configuration from.- OIDC_ENDPOINT = settings_dict.get("oidc_url")+ def __init__(self, *args: Any, **kwargs: Any) -> None:+ self.server_settings_dict: dict[str, OIDCIdPConfigDict] = (+ settings.SOCIAL_AUTH_OIDC_ENABLED_IDPS+ )+ self.idp_name: str | None = None++ self._cached_oidc_config: Any = None+ self._cached_jwks_keys: Any = None++ super().__init__(*args, **kwargs)@overridedef get_key_and_secret(self) -> tuple[str, str]:@@ -3555,15 +3556,170 @@ class GenericOpenIdConnectBackend(SocialAuthMixin, OpenIdConnectAuth):assert isinstance(secret, str)return client_id, secret+ # Discovery endpoint for the superclass to read all the appropriate+ # configuration from.+ @property+ @override+ def OIDC_ENDPOINT(self) -> str: # type: ignore[override] # mypy complains about overriding a writable attr with a @property.+ return self.settings_dict["oidc_url"]++ @property+ def settings_dict(self) -> OIDCIdPConfigDict:+ # This property is the core of the multi-IdP support for this backend.+ # Returns the correct configuration dict based on which IdP is being used+ # for the current authentication attempt.+ idp_name = self.get_idp_name()+ return self.server_settings_dict[idp_name]++ def get_idp_name(self) -> str:+ # This should only be accessed after the idp_name has been set:+ # 1) During auth initiation step: after get_or_create_state() in the auth_url() codepath+ # has set this value.+ # 2) During auth final step at /complete/oidc/: after auth_complete() has fetched, validated+ # and set the value.+ assert self.idp_name is not None+ return self.idp_name++ @override+ def get_or_create_state(self) -> str:+ try:+ idp_name = self.strategy.request_data()["idp"]+ except KeyError:+ # If the above raise KeyError, no idp was specified. This no a valid request+ # to the /login/oidc/ endpoint and it should be impossible for this request+ # to happen with normal usage of the login page - only through the user manually+ # fiddling with the URL.+ self.logger.info("/login/oidc/: Missing idp param.")+ raise JsonableError(_("Missing idp param"))+ self.idp_name = idp_name++ # python-social-auth's implementation first checks if there already is an+ # oidc_state stored in the session and if so, reuses it.+ # We want to avoid issues with reuse of a state value across different+ # IdPs, so we just generate a fresh state token at auth initiation.+ state = self.state_token()+ self.strategy.session_set("oidc_state", state)++ params_to_relay = self.standard_relay_params+ request_data = self.strategy.request_data().dict()+ data_to_relay = {key: request_data[key] for key in params_to_relay if key in request_data}+ data_to_relay["idp"] = idp_name++ # Associate the important data, especially the IdP which is being used, with the state token+ # to ensure we have the right set of values for this auth session.+ # This is more robust than relying on storing variables in request.session.+ self.put_data_in_redis(state, data_to_relay)++ return state++ @override+ def oidc_config(self) -> dict[Any, Any]:+ # Overridden from superclass to remove class-level caching, which is incompatible+ # with our multi-IdP support implementation.+ # TODO: We should add our own caching, to avoid unnecessary requests on every+ # auth attempt.+ # A simple instance-level caching is necessary to avoid making a new request every time+ # a property from /openid-configuration needs to be ready (which can be multiple times during+ # the processing of a single authentication attempt).+ if self._cached_oidc_config is None:+ self._cached_oidc_config = self.get_json(+ self.oidc_endpoint() + "/.well-known/openid-configuration"+ )++ return self._cached_oidc_config++ @override+ def get_jwks_keys(self) -> Any: # nocoverage+ # Overridden from superclass to remove class-level caching, which is incompatible+ # with our multi-IdP support implementation.+ if self._cached_jwks_keys is None:+ self._cached_jwks_keys = self.get_remote_jwks_keys()+ return self._cached_jwks_keys+@classmethod- def check_config(cls) -> bool:- if len(settings.SOCIAL_AUTH_OIDC_ENABLED_IDPS.keys()) != 1:- # Only one IdP supported for now.- return False+ def put_data_in_redis(cls, state: str, data_to_relay: dict[str, Any]) -> str:+ return put_dict_in_redis(+ redis_client,+ "oidc_state_{token}",+ data_to_store=data_to_relay,+ expiration_seconds=cls.REDIS_EXPIRATION_SECONDS,+ token=state,+ )++ @classmethod+ def get_data_from_redis(cls, state: str) -> dict[str, Any] | None:+ data = get_dict_from_redis(+ redis_client, key_format="oidc_state_{token}", key=f"oidc_state_{state}"+ )+ return data++ @override+ def auth_complete(self, *args: Any, **kwargs: Any) -> HttpResponse | None:+ """+ Overridden in order to support multiple IdPs being enabled on the server.+ Needs to safely determine:+ 1) Which IdP is handling this authentication attempt+ 2) Which subdomain we're logging into+ 3) Validate that the IdP is allowed for authentication users for this subdomain.+ """+ with social_auth_exception_guard(self.logger) as abort_flag:+ self.process_error(self.data)+ state = self.validate_state()+ if abort_flag.aborted:+ return None+ assert state++ relayed_params = self.get_data_from_redis(state)+ assert relayed_params is not None+ for param in self.standard_relay_params:+ relayed_value = relayed_params.get(param)+ session_value = self.strategy.session_get(param)+ # A hardening measure. These params are automatically saved in the+ # user's Zulip session by python-social-auth when auth is initiated.+ # More robustly, we associate these values with the "state" token+ # generated for this OIDC authentication attempt and store that in+ # redis.+ # It's this latter storage that we want to rely on for fetching+ # these values here in auth_complete, after the user has been+ # redirected back to us from the IdP. However, if all is right,+ # then the values in the session should match what we retrieve from+ # redis.+ assert relayed_value == session_value++ idp_name = relayed_params["idp"]+ assert idp_name+ subdomain = relayed_params["subdomain"]+ assert subdomain is not None+ idp_valid = self.validate_idp_for_subdomain(idp_name, subdomain)+ if not idp_valid:+ error_msg = (+ "/complete/oidc/: Authentication request with IdP %s but this provider is not"+ " enabled for this subdomain %s."+ )+ self.logger.info(error_msg, idp_name, subdomain)+ return None+ self.idp_name = idp_name++ # We've identified the IdP and ensured it's allowed for the target subdomain.+ # Now we can hand off the rest of the auth flow to the superclass' implementation.+ return super().auth_complete(*args, **kwargs)++ @classmethod+ def check_config(cls) -> bool:mandatory_config_keys = ["oidc_url", "client_id", "secret"]- [idp_config_dict] = settings.SOCIAL_AUTH_OIDC_ENABLED_IDPS.values()- if not all(idp_config_dict.get(key) for key in mandatory_config_keys):+ for idp_config_dict in settings.SOCIAL_AUTH_OIDC_ENABLED_IDPS.values():+ if not all(idp_config_dict.get(key) for key in mandatory_config_keys):+ return False++ return True++ @classmethod+ def validate_idp_for_subdomain(cls, idp_name: str, subdomain: str) -> bool:+ idp_dict = settings.SOCIAL_AUTH_OIDC_ENABLED_IDPS.get(idp_name)+ if idp_dict is None:+ raise AssertionError(f"IdP: {idp_name} not found")+ if "limit_to_subdomains" in idp_dict and subdomain not in idp_dict["limit_to_subdomains"]:return Falsereturn True@@ -3571,15 +3727,24 @@ class GenericOpenIdConnectBackend(SocialAuthMixin, OpenIdConnectAuth):@classmethod@overridedef dict_representation(cls, realm: Realm | None = None) -> list[ExternalAuthMethodDictT]:- return [- dict(- name=f"oidc:{cls.name}",- display_name=cls.display_name,- display_icon=cls.display_icon,- login_url=reverse("login-social", args=(cls.name,)),- signup_url=reverse("signup-social", args=(cls.name,)),+ result: list[ExternalAuthMethodDictT] = []+ for idp_name, idp_dict in settings.SOCIAL_AUTH_OIDC_ENABLED_IDPS.items():+ if realm and not cls.validate_idp_for_subdomain(idp_name, realm.subdomain):+ continue+ if realm is None and "limit_to_subdomains" in idp_dict:+ # If queried without a realm, only return IdPs that can be used on all realms.+ continue++ auth_dict: ExternalAuthMethodDictT = dict(+ name=f"oidc:{idp_name}",+ display_name=idp_dict.get("display_name", cls.auth_backend_name),+ display_icon=idp_dict.get("display_icon", cls.display_icon),+ login_url=reverse("login-social", args=("oidc", idp_name)),+ signup_url=reverse("signup-social", args=("oidc", idp_name)),)- ]+ result.append(auth_dict)++ return result@overridedef should_auto_signup(self) -> bool:diff --git a/zproject/prod_settings_template.py b/zproject/prod_settings_template.pyindex c38a537f0f1..038b73e7dc3 100644--- a/zproject/prod_settings_template.py+++ b/zproject/prod_settings_template.py@@ -397,6 +397,10 @@ SOCIAL_AUTH_OIDC_ENABLED_IDPS: dict[str, Any] = {## reads the secret with the specified name from zulip-secrets.conf."client_id": "<your client id>","secret": get_secret("social_auth_oidc_secret"),+ ## If you want this IdP to only be enabled for authentication+ ## to certain subdomains, uncomment and edit the setting below.+ # "limit_to_subdomains": ["subdomain1", "subdomain2"],+ #### Determines whether "Log in with OIDC" will automatically## register a new account if one does not already exist. By## default, Zulip asks the user whether they want to create andiff --git a/zproject/settings_types.py b/zproject/settings_types.pyindex d448c24a4ce..5430268be48 100644--- a/zproject/settings_types.py+++ b/zproject/settings_types.py@@ -35,6 +35,7 @@ class OIDCIdPConfigDict(TypedDict, total=False):client_id: strsecret: str | Noneauto_signup: bool+ limit_to_subdomains: list[str]class SCIMConfigDict(TypedDict, total=False):