Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
saml: During group sync, create missing groups on the fly.
Mateusz Manderabed61d61aa5e
diff --git a/docs/production/authentication-methods.md b/docs/production/authentication-methods.mdindex 4ba9c862f46..7f69854e90b 100644--- a/docs/production/authentication-methods.md+++ b/docs/production/authentication-methods.md@@ -858,7 +858,9 @@ using SAML, groups are synced as follows:is managed entirely in Zulip.1. Otherwise, if the group appears in `zulip_groups` in the`SAMLResponse`, the user is added to that group (if not already a- member).+ member). If the group doesn't yet exist in Zulip, it will be created.+ Memberships of groups created in this way will only be editable by+ organization owners.1. Otherwise, the user is removed from that group (if currently amember).diff --git a/zerver/tests/test_auth_backends.py b/zerver/tests/test_auth_backends.pyindex af446a88a79..65150013741 100644--- a/zerver/tests/test_auth_backends.py+++ b/zerver/tests/test_auth_backends.py@@ -3421,12 +3421,20 @@ class SAMLAuthBackendTest(SocialAuthBase):hamlet = self.example_user("hamlet")testgroup1 = create_user_group_in_database("testgroup1", [], realm, acting_user=hamlet)testgroup2 = create_user_group_in_database("testgroup2", [], realm, acting_user=hamlet)+ # Sanity assert. We'll use this group name to verify that groups get created on demand by group sync.+ assert not NamedUserGroup.objects.filter(+ name="newtestgroup", realm_for_sharding=realm+ ).exists()sync_custom_attrs_dict = {"zulip": {"saml": {"role": "zulip_role",- "groups": ["testgroup1", ("samlgroup2", "testgroup2")],+ "groups": [+ "testgroup1",+ ("samlgroup2", "testgroup2"),+ ("samlgroup3", "newtestgroup"),+ ],}}}@@ -3441,7 +3449,9 @@ class SAMLAuthBackendTest(SocialAuthBase):result = self.social_auth_test(account_data_dict,subdomain="zulip",- extra_attributes=dict(zulip_groups=["testgroup1", "samlgroup2"]),+ extra_attributes=dict(+ zulip_groups=["testgroup1", "samlgroup2", "samlgroup3", "samlgroup99"]+ ),)data = load_subdomain_token(result)self.assertEqual(data["email"], self.email)@@ -3461,10 +3471,34 @@ class SAMLAuthBackendTest(SocialAuthBase):direct_member_only=True,))++ # newtestgroup exists now. It was created because the zulip_groups attribute implied the user should+ # be a member of the group.+ new_test_group = NamedUserGroup.objects.get(name="newtestgroup", realm_for_sharding=realm)+ self.assertTrue(+ is_user_in_group(+ new_test_group.id,+ hamlet,+ direct_member_only=True,+ )+ )+ # samlgroup99 is not listed in the configuration, so doesn't get created, despite being passed in+ # the zulip_groups attribute.+ self.assertFalse(+ NamedUserGroup.objects.filter(name="samlgroup99", realm_for_sharding=realm).exists()+ )+# Verify the expected log line revealing the internal details of the incoming groups -> Zulip groups translation.self.assertIn(self.logger_output(- f"social_auth_sync_user_attributes:<user:{hamlet.id}>: received group names: ['samlgroup2', 'testgroup1']|intended Zulip groups: ['testgroup1', 'testgroup2']. group mapping used: {{'testgroup1': 'testgroup1', 'samlgroup2': 'testgroup2'}}",+ f"social_auth_sync_user_attributes:<user:{hamlet.id}>: received group names: ['samlgroup2', 'samlgroup3', 'samlgroup99', 'testgroup1']|intended Zulip groups: ['newtestgroup', 'testgroup1', 'testgroup2']. group mapping used: {{'testgroup1': 'testgroup1', 'samlgroup2': 'testgroup2', 'samlgroup3': 'newtestgroup'}}",+ type="info",+ ),+ mock_log.output,+ )+ self.assertIn(+ self.logger_output(+ f"User {hamlet.id} should be added to groups ['newtestgroup'], but they don't exist. Creating them first.",type="info",),mock_log.output,@@ -3497,6 +3531,13 @@ class SAMLAuthBackendTest(SocialAuthBase):direct_member_only=True,))+ self.assertFalse(+ is_user_in_group(+ new_test_group.id,+ hamlet,+ direct_member_only=True,+ )+ )with self.settings(SOCIAL_AUTH_SYNC_ATTRS_DICT=sync_custom_attrs_dict,@@ -3525,6 +3566,13 @@ class SAMLAuthBackendTest(SocialAuthBase):direct_member_only=True,))+ self.assertFalse(+ is_user_in_group(+ new_test_group.id,+ hamlet,+ direct_member_only=True,+ )+ )bulk_add_members_to_user_groups([testgroup1, testgroup2], [hamlet.id], acting_user=None)@@ -3587,6 +3635,13 @@ class SAMLAuthBackendTest(SocialAuthBase):direct_member_only=True,))+ self.assertFalse(+ is_user_in_group(+ new_test_group.id,+ hamlet,+ direct_member_only=True,+ )+ )def test_social_auth_group_sync_sync_all_groups_mode(self) -> None:realm = get_realm("zulip")@@ -3597,6 +3652,10 @@ class SAMLAuthBackendTest(SocialAuthBase):hamletcharacters_group = NamedUserGroup.objects.get(name="hamletcharacters", realm_for_sharding=realm)+ # Sanity assert. We'll use this group name to verify that groups get created on demand by group sync.+ assert not NamedUserGroup.objects.filter(+ name="newtestgroup", realm_for_sharding=realm+ ).exists()sync_custom_attrs_dict = {"zulip": {@@ -3613,12 +3672,21 @@ class SAMLAuthBackendTest(SocialAuthBase):SOCIAL_AUTH_SYNC_ATTRS_DICT=sync_custom_attrs_dict,),self.assertLogs(self.logger_string) as mock_log,+ self.assertLogs("", level="WARNING") as mock_root_logger,):account_data_dict = self.get_account_data_dict(email=self.email, name=self.name)result = self.social_auth_test(account_data_dict,subdomain="zulip",- extra_attributes=dict(zulip_groups=["testgroup1", "testgroup2"]),+ extra_attributes=dict(+ zulip_groups=[+ "testgroup1",+ "testgroup2",+ "newtestgroup",+ # Not a valid group name. We will want to verify it gets logged and ignored.+ "@@@@",+ ]+ ),)data = load_subdomain_token(result)self.assertEqual(data["email"], self.email)@@ -3645,14 +3713,37 @@ class SAMLAuthBackendTest(SocialAuthBase):direct_member_only=True,))++ # newtestgroup exists now. It was created because the zulip_groups attribute implied the user should+ # be a member of the group.+ new_test_group = NamedUserGroup.objects.get(name="newtestgroup", realm_for_sharding=realm)+ self.assertTrue(+ is_user_in_group(+ new_test_group.id,+ hamlet,+ direct_member_only=True,+ )+ )+# Verify the expected log line revealing the internal details of the incoming groups -> Zulip groups translation.self.assertIn(self.logger_output(- f"social_auth_sync_user_attributes:<user:{hamlet.id}>: received group names: ['testgroup1', 'testgroup2']|intended Zulip groups: ['testgroup1', 'testgroup2']. group mapping used: {{'hamletcharacters': 'hamletcharacters', 'testgroup1': 'testgroup1', 'testgroup2': 'testgroup2'}}",+ f"social_auth_sync_user_attributes:<user:{hamlet.id}>: received group names: ['@@@@', 'newtestgroup', 'testgroup1', 'testgroup2']|intended Zulip groups: ['@@@@', 'newtestgroup', 'testgroup1', 'testgroup2']. group mapping used: {{'hamletcharacters': 'hamletcharacters', 'testgroup1': 'testgroup1', 'testgroup2': 'testgroup2', 'newtestgroup': 'newtestgroup', '@@@@': '@@@@'}}",type="info",),mock_log.output,)+ self.assertIn(+ self.logger_output(+ f"User {hamlet.id} should be added to groups ['@@@@', 'newtestgroup'], but they don't exist. Creating them first.",+ type="info",+ ),+ mock_log.output,+ )+ self.assertEqual(+ mock_root_logger.output[0],+ "WARNING:root:ensure_missing_groups: received invalid groups names: ['@@@@']",+ )@override_settings(TERMS_OF_SERVICE_VERSION=None)def test_social_auth_create_user_with_synced_role_and_groups(self) -> None:@@ -3669,11 +3760,20 @@ class SAMLAuthBackendTest(SocialAuthBase):testgroup1 = create_user_group_in_database("testgroup1", [], realm, acting_user=desdemona)testgroup2 = create_user_group_in_database("testgroup2", [], realm, acting_user=desdemona)+ # Sanity assert. We'll use this group name to verify that groups get created on demand by group sync.+ assert not NamedUserGroup.objects.filter(+ name="newtestgroup", realm_for_sharding=realm+ ).exists()+sync_custom_attrs_dict = {"zulip": {"saml": {"role": "zulip_role",- "groups": ["testgroup1", ("samlgroup2", "testgroup2")],+ "groups": [+ "testgroup1",+ ("samlgroup2", "testgroup2"),+ ("samlgroup3", "newtestgroup"),+ ],}}}@@ -3693,7 +3793,7 @@ class SAMLAuthBackendTest(SocialAuthBase):mobilePhone=["123412341234"],birthday=["2021-01-01"],zulip_role=["owner"],- zulip_groups=["testgroup1"],+ zulip_groups=["testgroup1", "samlgroup3", "samlgroup99"],),)@@ -3718,10 +3818,26 @@ class SAMLAuthBackendTest(SocialAuthBase):))+ # newtestgroup exists now. It was created because the zulip_groups attribute implied the user should+ # be a member of the group.+ new_test_group = NamedUserGroup.objects.get(name="newtestgroup", realm_for_sharding=realm)+ self.assertTrue(+ is_user_in_group(+ new_test_group.id,+ user_profile,+ direct_member_only=True,+ )+ )+ # samlgroup99 is not listed in the configuration, so doesn't get created, despite being passed in+ # the zulip_groups attribute.+ self.assertFalse(+ NamedUserGroup.objects.filter(name="samlgroup99", realm_for_sharding=realm).exists()+ )+self.assertEqual(mock_logger.output[0],self.logger_output(- "social_auth_sync_user_attributes:<new user signup>: received group names: ['testgroup1']|intended Zulip groups: ['testgroup1']. group mapping used: {'testgroup1': 'testgroup1', 'samlgroup2': 'testgroup2'}",+ "social_auth_sync_user_attributes:<new user signup>: received group names: ['samlgroup3', 'samlgroup99', 'testgroup1']|intended Zulip groups: ['newtestgroup', 'testgroup1']. group mapping used: {'testgroup1': 'testgroup1', 'samlgroup2': 'testgroup2', 'samlgroup3': 'newtestgroup'}",type="info",),)@@ -3733,9 +3849,13 @@ class SAMLAuthBackendTest(SocialAuthBase):prereg_user = PreregistrationUser.objects.last()assert prereg_user is not Noneself.assertEqual(- f"INFO:root:Synced user groups for PreregistrationUser {prereg_user.id} in {realm.id}: "- '{"testgroup1": true, "testgroup2": false}. Final groups set: {\'testgroup1\'}',mock_root_logger.output[0],+ f"INFO:root:PreregistrationUser {prereg_user.id} should be added to groups ['newtestgroup'], but they don't exist. Creating them first.",+ )+ self.assertEqual(+ f"INFO:root:Synced user groups for PreregistrationUser {prereg_user.id} in {realm.id}: "+ '{"newtestgroup": true, "testgroup1": true, "testgroup2": false}. Final groups set: [\'newtestgroup\', \'testgroup1\']',+ mock_root_logger.output[1],)@override_settings(TERMS_OF_SERVICE_VERSION=None)@@ -3816,7 +3936,7 @@ class SAMLAuthBackendTest(SocialAuthBase):assert prereg_user is not Noneself.assertEqual(f"INFO:root:Synced user groups for PreregistrationUser {prereg_user.id} in {realm.id}: "- '{"testgroup1": true, "testgroup2": false}. Final groups set: {\'testgroup1\'}',+ '{"testgroup1": true, "testgroup2": false}. Final groups set: [\'testgroup1\']',mock_root_logger.output[0],)diff --git a/zerver/views/auth.py b/zerver/views/auth.pyindex cbdf171a0d2..80bd96b947a 100644--- a/zerver/views/auth.py+++ b/zerver/views/auth.py@@ -320,7 +320,9 @@ def maybe_send_to_registration(if user_groups or group_memberships_sync_map:prereg_user.groups.set(user_groups or [])if group_memberships_sync_map:- sync_groups_for_prereg_user(prereg_user, group_memberships_sync_map)+ sync_groups_for_prereg_user(+ prereg_user, group_memberships_sync_map, create_missing_groups=True+ )if include_realm_default_subscriptions is not None:prereg_user.include_realm_default_subscriptions = include_realm_default_subscriptionsdiff --git a/zproject/backends.py b/zproject/backends.pyindex 4e3bdd56392..73fd2fbbf92 100644--- a/zproject/backends.py+++ b/zproject/backends.py@@ -75,6 +75,8 @@ from zerver.actions.custom_profile_fields import do_update_user_custom_profile_dfrom zerver.actions.user_groups import (bulk_add_members_to_user_groups,bulk_remove_members_from_user_groups,+ create_user_group_in_database,+ do_send_create_user_group_event,)from zerver.actions.user_settings import do_change_user_delivery_email, do_regenerate_api_keyfrom zerver.actions.users import do_change_user_role, do_deactivate_user@@ -90,6 +92,7 @@ from zerver.lib.request import RequestNotesfrom zerver.lib.sessions import delete_user_sessionsfrom zerver.lib.subdomains import get_subdomainfrom zerver.lib.types import ProfileDataElementUpdateDict+from zerver.lib.user_groups import check_user_group_name, get_role_based_system_groups_dictfrom zerver.lib.users import check_full_name, validate_user_custom_profile_fieldfrom zerver.models import (CustomProfileField,@@ -1028,6 +1031,10 @@ class ZulipLDAPAuthBackendBase(ZulipAuthMixin, LDAPBackend):intended_group_names=intended_group_names,user_profile=user_profile,logger=ldap_logger,+ # We don't want to sneakily change LDAP behavior in this commit, we we pass+ # create_missing_group=False to maintain original behavior of ldap group sync.+ # TODO: Change this to True in a follow-up commit. Backport with False to 11.x.+ create_missing_groups=False,)except Exception as e:raise ZulipLDAPError(str(e)) from e@@ -1808,7 +1815,9 @@ def redirect_deactivated_user_to_login(realm: Realm, email: str) -> HttpResponse@transaction.atomic(savepoint=False)def sync_groups_for_prereg_user(- prereg_user: PreregistrationUser, group_memberships_sync_map: dict[str, bool]+ prereg_user: PreregistrationUser,+ group_memberships_sync_map: dict[str, bool],+ create_missing_groups: bool,) -> None:assert prereg_user.realm is not Nonerealm = prereg_user.realm@@ -1825,6 +1834,17 @@ def sync_groups_for_prereg_user(realm_for_sharding=realm, name__in=group_names_to_ensure_member))+ if create_missing_groups and len(groups_to_ensure_member) < len(group_names_to_ensure_member):+ missing_group_names = set(group_names_to_ensure_member) - {+ group.name for group in groups_to_ensure_member+ }+ logging.info(+ "PreregistrationUser %s should be added to groups %s, but they don't exist. Creating them first.",+ prereg_user.id,+ sorted(missing_group_names),+ )+ groups_to_ensure_member += ensure_missing_groups(missing_group_names, realm)+groups_to_ensure_not_member = list(NamedUserGroup.objects.filter(realm_for_sharding=realm, name__in=group_names_to_ensure_not_member@@ -1842,7 +1862,7 @@ def sync_groups_for_prereg_user(prereg_user.id,realm.id,stringified_dict,- final_group_names,+ sorted(final_group_names),)@@ -1851,6 +1871,7 @@ def sync_groups(intended_group_names: set[str],user_profile: UserProfile,logger: logging.Logger,+ create_missing_groups: bool = True,) -> None:"""Ensure that for this user:@@ -1858,6 +1879,9 @@ def sync_groups(- They are not in any NamedUserGroup in all_group_names minus intended_names.The idea is that intended_group_names is the set of names of groups to whichthe user should belong, within the universe specified by all_group_names.++ If create_missing_groups is enabled, if a user is meant to be added to a group+ which doesn't yet exist, we create it. Otherwise, such groups are ignored."""for system_group_name in SystemGroups.GROUP_DISPLAY_NAME_MAP:# system groups are not allowed to be synced.@@ -1889,6 +1913,16 @@ def sync_groups(if to_add:logger.debug("Adding user %s to groups %s", user_id, to_add)add_groups = list(NamedUserGroup.objects.filter(name__in=to_add, realm_for_sharding=realm))++ if create_missing_groups and len(add_groups) < len(to_add):+ missing_group_names = to_add - {group.name for group in add_groups}+ logger.info(+ "User %s should be added to groups %s, but they don't exist. Creating them first.",+ user_id,+ sorted(missing_group_names),+ )+ add_groups += ensure_missing_groups(missing_group_names, realm)+bulk_add_members_to_user_groups(add_groups, [user_id], acting_user=None)if to_remove:@@ -1901,6 +1935,38 @@ def sync_groups(logger.debug("Finished group sync for user %s", user_id)[email protected](savepoint=False)+def ensure_missing_groups(missing_group_names: set[str], realm: Realm) -> list[NamedUserGroup]:+ system_groups_name_dict = get_role_based_system_groups_dict(realm)+ group_owners = system_groups_name_dict[SystemGroups.OWNERS].usergroup_ptr+ group_settings_map = dict(+ can_add_members_group=group_owners,+ can_manage_group=group_owners,+ )+ valid_groups_names: set[str] = set()+ for group_name in missing_group_names:+ try:+ check_user_group_name(group_name)+ except JsonableError:+ continue+ valid_groups_names.add(group_name)+ if valid_groups_names != missing_group_names:+ logging.warning(+ "ensure_missing_groups: received invalid groups names: %s",+ sorted(missing_group_names - valid_groups_names),+ )++ created_groups = []+ for group_name in valid_groups_names:+ user_group = create_user_group_in_database(+ group_name, [], realm, acting_user=None, group_settings_map=group_settings_map+ )+ do_send_create_user_group_event(user_group, member_ids=[])+ created_groups.append(user_group)++ return created_groups++@dataclassclass SocialAuthSyncNewUserInfo:role: int | None@@ -1920,6 +1986,14 @@ def process_social_auth_group_sync_info(attrs_config: dict[str, Any],extra_attrs: dict[str, Any],) -> SocialAuthGroupInfo | None:+ # pop zulip_groups from extra_attrs, so that only user attribute sync+ # values remain there.+ # zulip_groups being absent should be treated as if no group memberships+ # are desired. That's because Okta doesn't send the SAML attribute at all+ # if the user has no group memberships. Thus we treat this absence as+ # an empty list.+ all_received_group_names = extra_attrs.pop("zulip_groups", [])+external_group_name_to_zulip_group_name: dict[str, str] = {}groups_config = cast(str | list[str | tuple[str, str]], attrs_config.get("groups", []))match groups_config:@@ -1945,8 +2019,14 @@ def process_social_auth_group_sync_info(all_realm_groups = NamedUserGroup.objects.filter(realm=realm, deactivated=False, is_system_group=False)- for group in all_realm_groups:- external_group_name_to_zulip_group_name[group.name] = group.name+ external_group_name_to_zulip_group_name = (+ {g.name: g.name for g in all_realm_groups}+ # If a group name is included in the user's zulip_groups, in sync-all-groups mode+ # we want the user to be added to it - even if the group doesn't yet exist in Zulip.+ # Thus, any such group should be recorded here, to be plumbed through further down the+ # group sync codepath where it will be created on the fly and the user added to it.+ | {n: n for n in all_received_group_names}+ )case str(): # nocoverageraise AssertionError(f'unsupported groups config string: {groups_config}; expected "*"')@@ -1955,13 +2035,6 @@ def process_social_auth_group_sync_info(syncable_group_names = set(external_group_name_to_zulip_group_name.values())- # pop zulip_groups from extra_attrs, so that only user attribute sync- # values remain there.- # zulip_groups being absent should be treated as if no group memberships- # are desired. That's because Okta doesn't send the SAML attribute at all- # if the user has no group memberships. Thus we treat this absence as- # an empty list.- all_received_group_names = extra_attrs.pop("zulip_groups", [])external_group_names = [namefor name in all_received_group_names@@ -2107,6 +2180,7 @@ def social_auth_sync_user_attributes(intended_group_names=group_sync_config.intended_group_names,user_profile=user_profile,logger=backend.logger,+ create_missing_groups=True,)return None