Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
saml: Support full_name sync upon login.
Mateusz Mandera1a1fb1d22667
diff --git a/docs/production/authentication-methods.md b/docs/production/authentication-methods.mdindex 3d301c28b09..d02807dc806 100644--- a/docs/production/authentication-methods.md+++ b/docs/production/authentication-methods.md@@ -805,7 +805,7 @@ their metadata might feel reasonable.Specifically, Zulip supports synchronizing[group memberships][user-groups-help-center], the [user-role][user-role-help-center] and [custom profile+role][user-role-help-center], the user's full name, and [custom profilefields][custom-profile-fields] from the SAML provider.In order to use this functionality, configure `SOCIAL_AUTH_SYNC_ATTRS_DICT` indiff --git a/zerver/tests/test_auth_backends.py b/zerver/tests/test_auth_backends.pyindex 3c2c41387dd..a3a2db0e6c2 100644--- a/zerver/tests/test_auth_backends.py+++ b/zerver/tests/test_auth_backends.py@@ -3448,6 +3448,63 @@ class SAMLAuthBackendTest(SocialAuthBase):).valueself.assertEqual(phone_field_value, expected_value)+ def test_social_auth_full_name_sync(self) -> None:+ sync_attrs_dict = {"zulip": {"saml": {"full_name": True}}}+ new_name = "Updated Name"++ with self.settings(SOCIAL_AUTH_SYNC_ATTRS_DICT=sync_attrs_dict):+ account_data_dict = self.get_account_data_dict(email=self.email, name=new_name)+ with self.assertLogs(self.logger_string, level="INFO"):+ result = self.social_auth_test(+ account_data_dict,+ subdomain="zulip",+ )+ data = load_subdomain_token(result)+ self.assertEqual(data["email"], self.email)+ self.assertEqual(result.status_code, 302)+ self.user_profile.refresh_from_db()+ self.assertEqual(self.user_profile.full_name, new_name)++ # Without full_name sync configured, the name should not be updated.+ with self.settings(SOCIAL_AUTH_SYNC_ATTRS_DICT={}):+ account_data_dict = self.get_account_data_dict(email=self.email, name="Another Name")+ result = self.social_auth_test(+ account_data_dict,+ subdomain="zulip",+ )+ data = load_subdomain_token(result)+ self.assertEqual(data["email"], self.email)+ self.assertEqual(result.status_code, 302)+ self.user_profile.refresh_from_db()+ self.assertEqual(self.user_profile.full_name, new_name)++ # Name with invalid characters should be rejected with a warning.+ with (+ self.settings(SOCIAL_AUTH_SYNC_ATTRS_DICT=sync_attrs_dict),+ self.assertLogs(self.logger_string, level="WARNING") as m,+ ):+ account_data_dict = self.get_account_data_dict(email=self.email, name="Invalid* Name")+ result = self.social_auth_test(+ account_data_dict,+ subdomain="zulip",+ )+ # Logging in succeeds.+ data = load_subdomain_token(result)+ self.assertEqual(data["email"], self.email)+ self.assertEqual(result.status_code, 302)+ self.user_profile.refresh_from_db()+ # The name doesn't get synced however, and we log a warning.+ self.assertEqual(self.user_profile.full_name, new_name)+ self.assertEqual(+ m.output,+ [+ self.logger_output(+ f"Failed to sync full_name for user {self.user_profile.id}: Invalid characters in name!",+ type="warning",+ )+ ],+ )+def test_social_auth_group_sync(self) -> None:realm = get_realm("zulip")hamlet = self.example_user("hamlet")diff --git a/zproject/backends.py b/zproject/backends.pyindex 89eb6e4ec11..ce1cc7558d9 100644--- a/zproject/backends.py+++ b/zproject/backends.py@@ -81,7 +81,11 @@ from zerver.actions.user_groups import (bulk_remove_members_from_user_groups,check_add_user_group_core,)-from zerver.actions.user_settings import do_change_user_delivery_email, do_regenerate_api_key+from zerver.actions.user_settings import (+ do_change_full_name,+ do_change_user_delivery_email,+ do_regenerate_api_key,+)from zerver.actions.users import do_change_user_role, do_deactivate_userfrom zerver.lib.avatar import avatar_url, is_avatar_newfrom zerver.lib.avatar_hash import user_avatar_content_hash@@ -2175,7 +2179,11 @@ def process_social_auth_group_sync_info(def social_auth_sync_user_attributes(- realm: Realm, user_profile: UserProfile | None, extra_attrs: dict[str, Any], backend: Any+ realm: Realm,+ user_profile: UserProfile | None,+ full_name: str | None,+ extra_attrs: dict[str, Any],+ backend: Any,) -> SocialAuthSyncNewUserInfo | None:"""Syncs user attributes based on the SOCIAL_AUTH_SYNC_ATTRS_DICT setting.@@ -2183,7 +2191,11 @@ def social_auth_sync_user_attributes(1. Syncing the role. This is plumbed through to user creation, so can beused to immediately create new users with their role set based on an attributeprovided by the IdP.- 2. Syncing custom attributes. This isn't supported for user creation,+ 2. Syncing the full_name. This uses the standard name data already+ extracted during authentication. We only have to worry about syncing+ existing users upon login; new signups already get their name from+ the IdP via the regular registration flow plumbing.+ 3. Syncing custom attributes. This isn't supported for user creation,so they'll only be synced during the user's next login, not duringsignup."""@@ -2200,14 +2212,16 @@ def social_auth_sync_user_attributes(attrs_config = attrs_by_backend.get(backend.name, {})profile_field_name_to_attr_name = cast(- dict[str, str], {key: value for key, value in attrs_config.items() if key != "groups"}+ dict[str, str],+ {key: value for key, value in attrs_config.items() if key not in ("groups", "full_name")},)group_sync_config = process_social_auth_group_sync_info(backend, realm, user_profile, attrs_config, extra_attrs)should_sync_user_attrs = extra_attrs and profile_field_name_to_attr_name- if not (should_sync_user_attrs or group_sync_config is not None):+ should_sync_full_name = (attrs_config.get("full_name", False) is True) and full_name+ if not (should_sync_user_attrs or should_sync_full_name or group_sync_config is not None):return Noneuser_id = None@@ -2267,6 +2281,23 @@ def social_auth_sync_user_attributes("Set role %s for user %s", UserProfile.ROLE_ID_TO_API_NAME[new_role], user_profile.id)+ if should_sync_full_name:+ assert full_name is not None+ if full_name != user_profile.full_name:+ try:+ validated_full_name = check_full_name(+ full_name_raw=full_name, user_profile=user_profile, realm=user_profile.realm+ )+ except JsonableError as e:+ backend.logger.warning(+ "Failed to sync full_name for user %s: %s", user_profile.id, e.msg+ )+ else:+ do_change_full_name(+ user_profile, validated_full_name, acting_user=None, notify=True+ )+ backend.logger.info("Set new full_name for user %s", user_profile.id)+try:sync_user_profile_custom_fields(user_profile, custom_profile_field_name_to_value, backend.logger@@ -2557,7 +2588,7 @@ def social_auth_finish(extra_attrs = return_data.get("extra_attrs", {})social_auth_sync_new_user_info = social_auth_sync_user_attributes(- realm, user_profile, extra_attrs, backend+ realm, user_profile, full_name, extra_attrs, backend)if user_profile:diff --git a/zproject/default_settings.py b/zproject/default_settings.pyindex 952a2b70d6f..3b323df83cd 100644--- a/zproject/default_settings.py+++ b/zproject/default_settings.py@@ -116,7 +116,9 @@ SOCIAL_AUTH_APPLE_EMAIL_AS_USERNAME = TrueSOCIAL_AUTH_OIDC_ENABLED_IDPS: dict[str, OIDCIdPConfigDict] = {}SOCIAL_AUTH_OIDC_FULL_NAME_VALIDATED = False-SOCIAL_AUTH_SYNC_ATTRS_DICT: dict[str, dict[str, dict[str, str | list[str | tuple[str, str]]]]] = {}+SOCIAL_AUTH_SYNC_ATTRS_DICT: dict[+ str, dict[str, dict[str, str | bool | list[str | tuple[str, str]]]]+] = {}# Other authSSO_APPEND_DOMAIN: str | None = Nonediff --git a/zproject/prod_settings_template.py b/zproject/prod_settings_template.pyindex 22e15751027..f5ddf50045b 100644--- a/zproject/prod_settings_template.py+++ b/zproject/prod_settings_template.py@@ -579,7 +579,10 @@ SOCIAL_AUTH_SAML_SUPPORT_CONTACT = {# SOCIAL_AUTH_SYNC_ATTRS_DICT = {# "example_org": {# "saml": {-# # role is currently the only supported major attribute.+# # No extra_attrs are required to enable syncing names, which will use+# # the standard SAML name attributes.+# "full_name": True,+# # role is the other supported major attribute.# "role": "zulip_role",# # Specify custom profile fields with a custom__ prefix for the# # Zulip field name.