Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
oidc: Support ExternalAuthID-based user lookup.
Mateusz Mandera27fb56ace901
diff --git a/docs/production/authentication-methods.md b/docs/production/authentication-methods.mdindex fd86946d0e6..890be39286a 100644--- a/docs/production/authentication-methods.md+++ b/docs/production/authentication-methods.md@@ -1175,6 +1175,28 @@ login](#synchronizing-data-during-login) for details. To synchronizeuser data continuously rather than only at login, consider [SCIMprovisioning](./scim.md) instead, if your provider offers it.+### Synchronizing email addresses with OIDC++Zulip 13.0+ supports automatically handling changes in email address+for OIDC-authenticated users. To enable this, set+`"enable_external_auth_id_auth": True` in your IdP configuration dict+in `SOCIAL_AUTH_OIDC_ENABLED_IDPS`. When this is enabled, users are+identified by the standard OIDC `sub` claim (a permanent, unique+identifier) together with the `iss` (issuer) rather than by email+address, and Zulip will update user email upon login if the email+changes.++:::{note}++The first time a user logs in with OIDC, the `sub` claim is linked to+their Zulip account. After a change in their email address at the IdP,+Zulip will update the linked account's email address the next time the+user logs in. If another Zulip user already has the new email address,+the email will not be updated, a warning will be logged and the+administrator should resolve the conflict manually.++:::+### Microsoft Entra ID (OIDC)Microsoft Entra ID (AzureAD) can be configured as an OIDC provider.diff --git a/zerver/tests/test_auth_backends.py b/zerver/tests/test_auth_backends.pyindex 325e1ccdf56..2bcf6119545 100644--- a/zerver/tests/test_auth_backends.py+++ b/zerver/tests/test_auth_backends.py@@ -5074,17 +5074,29 @@ class GenericOpenIdConnectTest(SocialAuthBaseWithSyncAttrTest):return result@override- def social_auth_test_finish(self, *args: Any, **kwargs: Any) -> "TestHttpResponse":+ def social_auth_test_finish(+ self,+ result: "TestHttpResponse",+ account_data_dict: dict[str, str],+ *args: Any,+ **kwargs: Any,+ ) -> "TestHttpResponse":# Trying to generate a (access_token, id_token) pair here in tests that would# successfully pass validation by validate_and_return_id_token is impractical# and unnecessary (see python-social-auth implementation of the method for# how the validation works).- # We can simply mock the method to make it succeed and return an empty dict, because- # the return value is not used for anything.+ # We can simply mock the method to make it succeed and return just the+ # claims that are used: iss for ExternalAuthID lookup, and sub, which+ # python-social-auth requires to match the sub from the UserInfo endpoint.with mock.patch.object(- GenericOpenIdConnectBackend, "validate_and_return_id_token", return_value={}+ GenericOpenIdConnectBackend,+ "validate_and_return_id_token",+ return_value={+ "iss": account_data_dict.get("iss", self.BASE_OIDC_URL),+ "sub": account_data_dict["sub"],+ },):- return super().social_auth_test_finish(*args, **kwargs)+ return super().social_auth_test_finish(result, account_data_dict, *args, **kwargs)@overridedef register_extra_endpoints(@@ -5132,6 +5144,7 @@ class GenericOpenIdConnectTest(SocialAuthBaseWithSyncAttrTest):family_name = Nonereturn dict(+ sub="123-test-sub",email=email,name=name,nickname="somenickname",@@ -5494,6 +5507,180 @@ class GenericOpenIdConnectTest(SocialAuthBaseWithSyncAttrTest):"""return+ def test_external_auth_id_oidc_login(self) -> None:+ """+ Test that OIDC login creates an ExternalAuthID record on first login,+ and uses it for subsequent logins even if the email changes at the IdP.+ """+ hamlet = self.example_user("hamlet")++ idps_config_dict = copy.deepcopy(settings.SOCIAL_AUTH_OIDC_ENABLED_IDPS)+ idps_config_dict["testoidc"]["enable_external_auth_id_auth"] = True+ sub_value = "testsub"+ expected_method_name = f"oidc:<testoidc>:<{self.BASE_OIDC_URL}>"++ # First login: no ExternalAuthID exists yet. One should be created.+ self.assertEqual(ExternalAuthID.objects.filter(user=hamlet).count(), 0)+ account_data_dict = self.get_account_data_dict(email=self.email, name=self.name)+ account_data_dict["sub"] = sub_value+ with (+ self.settings(SOCIAL_AUTH_OIDC_ENABLED_IDPS=idps_config_dict),+ self.assertLogs(self.logger_string, level="INFO"),+ ):+ result = self.social_auth_test(+ account_data_dict,+ subdomain="zulip",+ )+ self.assertEqual(result.status_code, 302)+ data = load_subdomain_token(result)+ self.assertEqual(data["email"], hamlet.delivery_email)++ external_auth_ids = list(ExternalAuthID.objects.filter(user=hamlet))+ self.assert_length(external_auth_ids, 1)+ self.assertEqual(external_auth_ids[0].external_auth_method_name, expected_method_name)+ self.assertEqual(external_auth_ids[0].external_auth_id, sub_value)++ # Login with a new email, but same sub value - user should be found by ExternalAuthID+ # and the email should be synced.+ new_email = "[email protected]"+ new_account_data_dict = self.get_account_data_dict(email=new_email, name=self.name)+ new_account_data_dict["sub"] = sub_value+ with (+ self.settings(SOCIAL_AUTH_OIDC_ENABLED_IDPS=idps_config_dict),+ self.assertLogs(self.logger_string, level="INFO") as m,+ ):+ result = self.social_auth_test(+ new_account_data_dict,+ subdomain="zulip",+ )+ self.assertEqual(result.status_code, 302)+ data = load_subdomain_token(result)+ self.assertEqual(data["email"], new_email)+ hamlet.refresh_from_db()+ self.assertEqual(hamlet.delivery_email, new_email)++ self.assertIn("has mismatched email. Syncing:", m.output[0])++ # The same sub from a different issuer isn't matched to the existing+ # ExternalAuthID. The user is found by email and linked to the new issuer.+ new_account_data_dict["iss"] = "https://other-issuer.example.com"+ with (+ self.settings(SOCIAL_AUTH_OIDC_ENABLED_IDPS=idps_config_dict),+ self.assertLogs(self.logger_string, level="INFO"),+ ):+ result = self.social_auth_test(+ new_account_data_dict,+ subdomain="zulip",+ )+ data = load_subdomain_token(result)+ self.assertEqual(data["email"], new_email)+ self.assertEqual(+ set(+ ExternalAuthID.objects.filter(user=hamlet).values_list(+ "external_auth_method_name", "external_auth_id"+ )+ ),+ {+ (expected_method_name, sub_value),+ ("oidc:<testoidc>:<https://other-issuer.example.com>", sub_value),+ },+ )++ def test_external_auth_id_oidc_email_conflict(self) -> None:+ """+ Test that email is NOT synced when another user already has the target email.+ """++ hamlet = self.example_user("hamlet")+ othello = self.example_user("othello")++ idps_config_dict = copy.deepcopy(settings.SOCIAL_AUTH_OIDC_ENABLED_IDPS)+ idps_config_dict["testoidc"]["enable_external_auth_id_auth"] = True+ sub_value = "testsub"+ expected_method_name = f"oidc:<testoidc>:<{self.BASE_OIDC_URL}>"++ account_data_dict = self.get_account_data_dict(email=self.email, name=self.name)+ account_data_dict["sub"] = sub_value+ with (+ self.settings(SOCIAL_AUTH_OIDC_ENABLED_IDPS=idps_config_dict),+ self.assertLogs(self.logger_string, level="INFO"),+ ):+ result = self.social_auth_test(+ account_data_dict,+ subdomain="zulip",+ )+ self.assertEqual(result.status_code, 302)+ data = load_subdomain_token(result)+ self.assertEqual(data["email"], hamlet.delivery_email)++ external_auth_ids = list(ExternalAuthID.objects.filter(user=hamlet))+ self.assert_length(external_auth_ids, 1)+ self.assertEqual(external_auth_ids[0].external_auth_method_name, expected_method_name)+ self.assertEqual(external_auth_ids[0].external_auth_id, sub_value)++ # Try to login with othello's email but hamlet's sub - authentication should find hamlet+ # by ExternalAuthID but NOT sync the email since othello already has it.+ othello_email = othello.delivery_email+ conflict_data = self.get_account_data_dict(email=othello_email, name=self.name)+ conflict_data["sub"] = sub_value+ with (+ self.settings(SOCIAL_AUTH_OIDC_ENABLED_IDPS=idps_config_dict),+ self.assertLogs(self.logger_string, level="INFO") as m,+ ):+ result = self.social_auth_test(+ conflict_data,+ subdomain="zulip",+ )+ self.assertEqual(result.status_code, 302)+ data = load_subdomain_token(result)+ self.assertEqual(data["email"], hamlet.delivery_email)++ hamlet.refresh_from_db()+ # Email should NOT have changed.+ self.assertEqual(hamlet.delivery_email, self.email)+ self.assertIn(+ f"Can't sync email for user {hamlet.id}: "+ f"another user exists with target email {othello_email}",+ m.output[1],+ )++ @override_settings(TERMS_OF_SERVICE_VERSION=None)+ def test_external_auth_id_oidc_registration(self) -> None:+ email = "[email protected]"+ name = "New User"+ subdomain = "zulip"+ realm = get_realm("zulip")+ idps_config_dict = copy.deepcopy(settings.SOCIAL_AUTH_OIDC_ENABLED_IDPS)+ idps_config_dict["testoidc"]["enable_external_auth_id_auth"] = True+ sub_value = "newuser_sub"++ account_data_dict = self.get_account_data_dict(email=email, name=name)+ account_data_dict["sub"] = sub_value+ with self.settings(SOCIAL_AUTH_OIDC_ENABLED_IDPS=idps_config_dict):+ result = self.social_auth_test(+ account_data_dict,+ subdomain=subdomain,+ is_signup=True,+ )+ self.stage_two_of_registration(+ result,+ realm,+ subdomain,+ email,+ name,+ name,+ self.BACKEND_CLASS.full_name_validated,+ )+ user_profile = get_user_by_delivery_email(email, realm)+ self.assertTrue(user_profile.is_active)+ external_auth_ids = list(ExternalAuthID.objects.filter(user=user_profile))+ self.assert_length(external_auth_ids, 1)+ self.assertEqual(+ external_auth_ids[0].external_auth_method_name,+ f"oidc:<testoidc>:<{self.BASE_OIDC_URL}>",+ )+ self.assertEqual(external_auth_ids[0].external_auth_id, sub_value)+class GitHubAuthBackendTest(SocialAuthBase):BACKEND_CLASS = GitHubAuthBackenddiff --git a/zproject/backends.py b/zproject/backends.pyindex 50c5d30b4df..8132ef4a5b5 100644--- a/zproject/backends.py+++ b/zproject/backends.py@@ -4191,6 +4191,46 @@ class GenericOpenIdConnectBackend(SocialAuthMixin, OpenIdConnectAuth):assert isinstance(secret, str)return client_id, secret+ @override+ def get_authenticated_user(+ self,+ email: str,+ realm: Realm,+ return_data: dict[str, Any],+ **kwargs: Any,+ ) -> UserProfile | None:+ idp_name = self.get_idp_name()++ if not self.settings_dict.get("enable_external_auth_id_auth", False):+ return common_get_active_user(email, realm, return_data)++ sub = self.get_user_id(kwargs["details"], kwargs["response"])+ assert sub++ # self.id_token is declared as None in the base class, but is set by request_access_token.+ id_token = cast(dict[str, Any] | None, self.id_token)+ assert id_token is not None+ iss = id_token["iss"]+ # The sub value is supposed to be unique, but only within the specific issuer. Theoretically,+ # the same sub value can correspond to two different users for two different issuers. This could+ # cause very bad bugs if a server administrator changes the underlying issuer in the OIDC config+ # without changing the idp_name.+ # We prevent this by including the iss value in the ExternalAuthID entries.+ external_auth_method_name = f"oidc:<{idp_name}>:<{iss}>"+ user_profile = get_and_sync_user_profile_by_external_auth_id(+ external_auth_method_name=external_auth_method_name,+ external_auth_id=sub,+ email=email,+ realm=realm,+ return_data=return_data,+ logger=self.logger,+ )+ return_data["external_auth_id_dict_for_registration"] = {+ "external_auth_method_name": external_auth_method_name,+ "external_auth_id": sub,+ }+ return user_profile+# Discovery endpoint for the superclass to read all the appropriate# configuration from.@propertydiff --git a/zproject/prod_settings_template.py b/zproject/prod_settings_template.pyindex ebe0ca6fd34..1e766a6cea4 100644--- a/zproject/prod_settings_template.py+++ b/zproject/prod_settings_template.py@@ -449,6 +449,13 @@ SOCIAL_AUTH_OIDC_ENABLED_IDPS: dict[str, Any] = {## These attributes will be available for synchronizing user## profile fields in SOCIAL_AUTH_SYNC_ATTRS_DICT.# "extra_attrs": ["title", "mobilePhone", "zulip_role"],+ ##+ ## When enabled, users are identified by their permanent OIDC+ ## "sub" claim rather than by email. This allows Zulip to+ ## automatically update users' email addresses when they+ ## change at the IdP. See:+ ## https://zulip.readthedocs.io/en/latest/production/authentication-methods.html#synchronizing-email-addresses-with-oidc+ # "enable_external_auth_id_auth": True,},## Example: Microsoft Entra ID (AzureAD) OIDC configuration.## This is the recommended approach for Entra ID SSO on self-hosted servers.diff --git a/zproject/settings_types.py b/zproject/settings_types.pyindex e1b8dda28a5..663da728eb1 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+ enable_external_auth_id_auth: boollimit_to_subdomains: list[str]extra_attrs: list[str]