Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
ldap: Support ExternalAuthID in the sync_ldap_user_data system.
Mateusz Mandera7788ce98e9f8
diff --git a/docs/overview/changelog.md b/docs/overview/changelog.mdindex ca03066711e..3e54078f9a4 100644--- a/docs/overview/changelog.md+++ b/docs/overview/changelog.md@@ -304,6 +304,12 @@ _Released 2026-04-26_synced but don't exist in the Zulip organization. Starting in 12.0,such groups will be created automatically when syncing the groupsfor a user who should be a member of that group.+- The `AUTH_LDAP_USERNAME_ATTR` setting is now required for all LDAP+ configurations. It was previously optional when using `LDAP_APPEND_DOMAIN`+ (configuration (B) in our LDAP setup documentation). It should be set to the+ name of the LDAP attribute that holds the username in `AUTH_LDAP_USER_SEARCH`+ results (for example, `uid` or `sAMAccountName`). Configurations which+ already had this set correctly don't need to take any action on this item.- The [`GET /api/v1/users/{user_id_or_email}/presence`](https://zulip.com/api/get-user-presence)API endpoint now returns presence data in the modern format, inaddition to the legacy format that it has always returned. Customdiff --git a/docs/production/authentication-methods.md b/docs/production/authentication-methods.mdindex d02807dc806..dc870420e9a 100644--- a/docs/production/authentication-methods.md+++ b/docs/production/authentication-methods.md@@ -210,6 +210,8 @@ In either configuration, you will need to do the following:- Set `AUTH_LDAP_USER_SEARCH` to query by LDAP username- Set `LDAP_APPEND_DOMAIN = "example.com"`.+ - Set `AUTH_LDAP_USERNAME_ATTR` to the name of the LDAP+ attribute for the user's LDAP username in that search result.(C) Using LDAP usernames as Zulip usernames, with email addressestaken from some other attribute in LDAP (for example, `mail`):@@ -403,17 +405,6 @@ For Active Directory installations, the immutable Security Identifier[`objectSid`](https://ldapwiki.com/wiki/Wiki.jsp?page=Security%20Identifier)is recommended.-:::{note}--While most LDAP data is synced in `sync_ldap_user_data`, email address-synchronization is only checked on login. The first time a user logs-in with `unique_account_id` enabled, the unique ID will be linked with-their Zulip account. After a change in their LDAP email address, Zulip-will update the linked Zulip account's Zulip email address the next-time the user logs in.--:::-#### Manually handling LDAP email changesIf you don't have `unique_account_id` enabled, when a user's emaildiff --git a/zerver/tests/test_auth_backends.py b/zerver/tests/test_auth_backends.pyindex a3a2db0e6c2..37876c2c134 100644--- a/zerver/tests/test_auth_backends.py+++ b/zerver/tests/test_auth_backends.py@@ -1,6 +1,7 @@import base64import copyimport json+import loggingimport osimport reimport secrets@@ -7674,7 +7675,7 @@ class TestLDAP(ZulipLDAPTestCase):self.assertEqual(user_profile.delivery_email, "[email protected]")self.assertEqual(ExternalAuthID.objects.filter(user=hamlet).count(), 1)self.assertIn(- f"INFO:zulip.auth.ldap:User {hamlet.id}, logged in via ExternalAuthId uid=hamlet,ou=users,dc=zulip,dc=com, has mismatched email. Syncing: [email protected] => [email protected]",+ f"INFO:zulip.auth.ldap:User {hamlet.id}, being synced via ExternalAuthId uid=hamlet,ou=users,dc=zulip,dc=com, has mismatched email. Syncing: [email protected] => [email protected]",mock_log.output,)@@ -7717,7 +7718,7 @@ class TestLDAP(ZulipLDAPTestCase):self.assertEqual(user_profile.delivery_email, "[email protected]")self.assertEqual(ExternalAuthID.objects.filter(user=hamlet).count(), 1)self.assertIn(- f"INFO:zulip.auth.ldap:User {hamlet.id}, logged in via ExternalAuthId uid=hamlet,ou=users,dc=zulip,dc=com, has mismatched email. Syncing: [email protected] => [email protected]",+ f"INFO:zulip.auth.ldap:User {hamlet.id}, being synced via ExternalAuthId uid=hamlet,ou=users,dc=zulip,dc=com, has mismatched email. Syncing: [email protected] => [email protected]",mock_log.output,)@@ -8646,6 +8647,225 @@ class TestZulipLDAPUserPopulator(ZulipLDAPTestCase):],)+ def test_sync_creates_external_auth_id_record(self) -> None:+ hamlet = self.example_user("hamlet")+ realm = hamlet.realm+ self.assertEqual(ExternalAuthID.objects.filter(user=hamlet).count(), 0)++ with self.settings(+ LDAP_EMAIL_ATTR="mail",+ AUTH_LDAP_USER_ATTR_MAP={"full_name": "cn", "unique_account_id": "dn"},+ ):+ sync_user_from_ldap(hamlet, mock.Mock())++ external_auth_ids = list(ExternalAuthID.objects.filter(user=hamlet))+ self.assert_length(external_auth_ids, 1)+ self.assertEqual(external_auth_ids[0].realm_id, realm.id)+ self.assertEqual(external_auth_ids[0].external_auth_method_name, "ldap")+ self.assertEqual(+ external_auth_ids[0].external_auth_id, "uid=hamlet,ou=users,dc=zulip,dc=com"+ )++ ExternalAuthID.objects.filter(user=hamlet).delete()++ # Now test a configuration with a different attribute as unique_account_id.+ with self.settings(+ LDAP_EMAIL_ATTR="mail",+ AUTH_LDAP_USER_ATTR_MAP={"full_name": "cn", "unique_account_id": "homePhone"},+ ):+ sync_user_from_ldap(hamlet, mock.Mock())++ external_auth_ids = list(ExternalAuthID.objects.filter(user=hamlet))+ self.assert_length(external_auth_ids, 1)+ self.assertEqual(external_auth_ids[0].external_auth_id, "123456789")++ # If unique_account_id is not configured, no ExternalAuthID should be created.+ ExternalAuthID.objects.filter(user=hamlet).delete()+ self.perform_ldap_sync(hamlet)+ self.assertEqual(ExternalAuthID.objects.filter(user=hamlet).count(), 0)++ @override_settings(+ LDAP_EMAIL_ATTR="mail",+ AUTH_LDAP_USER_ATTR_MAP={"full_name": "cn", "unique_account_id": "dn"},+ )+ def test_sync_via_external_auth_id_end_to_end(self) -> None:+ hamlet = self.example_user("hamlet")+ realm = get_realm("zulip")++ # Initial sync will happen via email, due to no pre-existing ExternalAuthID+ # record.+ self.assert_length(ExternalAuthID.objects.filter(user=hamlet), 0)+ sync_user_from_ldap(hamlet, mock.Mock())+ external_auth_ids = list(ExternalAuthID.objects.filter(user=hamlet))+ self.assert_length(external_auth_ids, 1)+ self.assertEqual(external_auth_ids[0].realm_id, realm.id)+ self.assertEqual(external_auth_ids[0].external_auth_method_name, "ldap")+ self.assertEqual(+ external_auth_ids[0].external_auth_id, "uid=hamlet,ou=users,dc=zulip,dc=com"+ )++ # Next we test a sync that will just update the name, no email change happens yet.+ self.change_ldap_user_attr("hamlet", "cn", "New Name")+ sync_user_from_ldap(hamlet, mock.Mock())+ hamlet.refresh_from_db()+ self.assertEqual(hamlet.delivery_email, "[email protected]")+ self.assertEqual(hamlet.full_name, "New Name")+ self.assert_length(ExternalAuthID.objects.filter(user=hamlet), 1)++ # Now sync with an email change involved. Hamlet's delivery_email should get updated.+ self.change_ldap_user_attr("hamlet", "mail", "[email protected]")+ self.change_ldap_user_attr("hamlet", "cn", "New Name2")++ logger = logging.getLogger("zulip.sync_ldap_user_data")+ with self.assertLogs(logger, level="INFO") as log_output:+ sync_user_from_ldap(hamlet, logger)++ hamlet.refresh_from_db()+ self.assertEqual(hamlet.delivery_email, "[email protected]")+ self.assertEqual(hamlet.full_name, "New Name2")++ # Verify the ExternalAuthID path was used and the email was synced.+ self.assertIn(+ f"INFO:zulip.sync_ldap_user_data:Syncing user [email protected] (id={hamlet.id})"+ " via external auth id. Result DN: uid=hamlet,ou=users,dc=zulip,dc=com",+ log_output.output,+ )+ self.assertIn(+ f"INFO:zulip.sync_ldap_user_data:User {hamlet.id},"+ " being synced via ExternalAuthId uid=hamlet,ou=users,dc=zulip,dc=com,"+ " has mismatched email. Syncing: [email protected] => [email protected]",+ log_output.output,+ )++ @override_settings(+ LDAP_EMAIL_ATTR="mail",+ AUTH_LDAP_USER_ATTR_MAP={"full_name": "cn", "unique_account_id": "dn"},+ )+ def test_sync_via_external_auth_id_email_capitalization_change(self) -> None:+ hamlet = self.example_user("hamlet")+ ExternalAuthID.objects.create(+ user=hamlet,+ realm=hamlet.realm,+ external_auth_method_name="ldap",+ external_auth_id="uid=hamlet,ou=users,dc=zulip,dc=com",+ )++ self.change_ldap_user_attr("hamlet", "mail", "[email protected]")+ mock_logger = mock.Mock()+ sync_user_from_ldap(hamlet, mock_logger)++ hamlet.refresh_from_db()+ self.assertEqual(hamlet.delivery_email, "[email protected]")++ @override_settings(+ LDAP_EMAIL_ATTR="mail",+ AUTH_LDAP_USER_ATTR_MAP={"full_name": "cn", "unique_account_id": "dn"},+ )+ def test_sync_via_external_auth_id_email_conflict(self) -> None:+ hamlet = self.example_user("hamlet")+ cordelia = self.example_user("cordelia")+ ExternalAuthID.objects.create(+ user=hamlet,+ realm=hamlet.realm,+ external_auth_method_name="ldap",+ external_auth_id="uid=hamlet,ou=users,dc=zulip,dc=com",+ )++ # Change hamlet's LDAP email to cordelia's email to cause conflict+ # when syncing attempts to update hamlet's delivery_email.+ self.change_ldap_user_attr("hamlet", "mail", cordelia.delivery_email)+ with self.assertRaises(PopulateUserLDAPError):+ sync_user_from_ldap(hamlet, mock.Mock())++ # hamlet's email should not have changed, and cordelia should be unaffected.+ hamlet.refresh_from_db()+ cordelia.refresh_from_db()+ self.assertEqual(hamlet.delivery_email, "[email protected]")+ self.assertEqual(cordelia.full_name, "Cordelia, Lear's daughter")+ self.assertEqual(cordelia.delivery_email, "[email protected]")++ @override_settings(+ LDAP_EMAIL_ATTR="mail",+ AUTH_LDAP_USER_ATTR_MAP={"full_name": "cn", "unique_account_id": "homePhone"},+ )+ def test_sync_external_auth_id_stale_value(self) -> None:+ hamlet = self.example_user("hamlet")+ # Create ExternalAuthID with a stale value that doesn't match LDAP.+ ExternalAuthID.objects.create(+ user=hamlet,+ realm=hamlet.realm,+ external_auth_method_name="ldap",+ external_auth_id="old_value",+ )++ # The stale ExternalAuthID doesn't have a match in LDAP, so the sync+ # falls back to email-based lookup and then resolves the ExternalAuthID+ # issue.+ with self.assertLogs("zulip.auth.ldap", level="WARNING") as log_output:+ sync_user_from_ldap(hamlet, mock.Mock())++ external_auth_id_obj = ExternalAuthID.objects.get(user=hamlet)+ self.assertEqual(external_auth_id_obj.external_auth_id, "123456789")+ self.assertIn(+ f"WARNING:zulip.auth.ldap:User {hamlet.id} had mismatched ExternalAuthID record. "+ "Updating old_value => 123456789",+ log_output.output,+ )++ def test_sync_via_external_auth_id_deleted_ldap_user(self) -> None:+ hamlet = self.example_user("hamlet")+ hamlet_dn = "uid=hamlet,ou=users,dc=zulip,dc=com"+ hamlet_ldap_entry = self.mock_ldap.directory[hamlet_dn]++ # Test a DN-based lookup for a user whose record has been deleted from LDAP.+ # Since the LDAP record can't be found, neither by ExternalAuthID nor email,+ # no sync can happen beyond deactivating the user for having no matching+ # LDAP record; if that configuration is enabled.+ ExternalAuthID.objects.create(+ user=hamlet,+ realm=hamlet.realm,+ external_auth_method_name="ldap",+ external_auth_id=hamlet_dn,+ )+ del self.mock_ldap.directory[hamlet_dn]++ with self.settings(+ LDAP_EMAIL_ATTR="mail",+ AUTH_LDAP_USER_ATTR_MAP={"full_name": "cn", "unique_account_id": "dn"},+ LDAP_DEACTIVATE_NON_MATCHING_USERS=True,+ AUTHENTICATION_BACKENDS=("zproject.backends.ZulipLDAPAuthBackend",),+ ):+ sync_user_from_ldap(hamlet, mock.Mock())++ hamlet.refresh_from_db()+ self.assertFalse(hamlet.is_active)++ # Restore the initial state.+ do_reactivate_user(hamlet, acting_user=None)+ self.mock_ldap.directory[hamlet_dn] = hamlet_ldap_entry+ ExternalAuthID.objects.filter(user=hamlet).delete()++ # Now test the same scenario as above, but with a different attribute than DN+ # configured as the unique_account_id.+ ExternalAuthID.objects.create(+ user=hamlet,+ realm=hamlet.realm,+ external_auth_method_name="ldap",+ external_auth_id=hamlet_ldap_entry["homePhone"],+ )+ del self.mock_ldap.directory[hamlet_dn]++ with self.settings(+ LDAP_EMAIL_ATTR="mail",+ AUTH_LDAP_USER_ATTR_MAP={"full_name": "cn", "unique_account_id": "homePhone"},+ LDAP_DEACTIVATE_NON_MATCHING_USERS=True,+ AUTHENTICATION_BACKENDS=("zproject.backends.ZulipLDAPAuthBackend",),+ ):+ sync_user_from_ldap(hamlet, mock.Mock())++ hamlet.refresh_from_db()+ self.assertFalse(hamlet.is_active)+class TestQueryLDAP(ZulipLDAPTestCase):@override_settings(AUTHENTICATION_BACKENDS=("zproject.backends.EmailAuthBackend",))diff --git a/zproject/backends.py b/zproject/backends.pyindex ce1cc7558d9..aa1f25c9b5d 100644--- a/zproject/backends.py+++ b/zproject/backends.py@@ -22,6 +22,7 @@ from dataclasses import dataclassfrom email.headerregistry import Addressfrom typing import TYPE_CHECKING, Any, TypedDict, TypeVar, cast+import ldapimport magicimport orjsonfrom decorator import decorator@@ -38,7 +39,7 @@ from django.shortcuts import renderfrom django.urls import reversefrom django.utils.translation import gettext as _from django_auth_ldap.backend import LDAPBackend, _LDAPUser, _LDAPUserGroups, ldap_error-from django_auth_ldap.config import LDAPSettings+from django_auth_ldap.config import LDAPSearch, LDAPSettingsfrom lxml.etree import XMLSyntaxErrorfrom onelogin.saml2 import compat as onelogin_saml2_compatfrom onelogin.saml2.auth import OneLogin_Saml2_Auth@@ -101,6 +102,7 @@ from zerver.lib.subdomains import get_subdomainfrom zerver.lib.types import ProfileDataElementUpdateDictfrom 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_field+from zerver.lib.utils import assert_is_not_nonefrom zerver.lib.validator import LONG_STRING_MAX_LENGTH, SHORT_STRING_MAX_LENGTHfrom zerver.models import (CustomProfileField,@@ -597,9 +599,10 @@ def is_valid_email(email: str) -> bool:def check_ldap_config() -> None:+ assert settings.AUTH_LDAP_USERNAME_ATTRif not settings.LDAP_APPEND_DOMAIN:# Email search needs to be configured in this case.- assert settings.AUTH_LDAP_USERNAME_ATTR and settings.AUTH_LDAP_REVERSE_EMAIL_SEARCH+ assert settings.AUTH_LDAP_REVERSE_EMAIL_SEARCH# These two are alternatives approaches to deactivating users based on an ldap attribute# and thus don't make sense to have enabled together.@@ -652,7 +655,7 @@ def email_belongs_to_ldap(realm: Realm, email: str) -> bool:ldap_logger = logging.getLogger("zulip.ldap")-class LDAPReverseEmailSearch(_LDAPUser):+class ZulipLDAPSearch(_LDAPUser):"""This class is a workaround - we want to usedjango-auth-ldap to query the ldap directory for@@ -673,12 +676,19 @@ class LDAPReverseEmailSearch(_LDAPUser):# for only making a search query, so we pass an empty string.super().__init__(LDAPBackend(), username="")+ def do_search(+ self, ldap_search: LDAPSearch, kwargs_dict: dict[str, str]+ ) -> list[tuple[str, dict[str, list[object]]]]:+ return ldap_search.execute(self.connection, kwargs_dict)+++class LDAPReverseEmailSearch(ZulipLDAPSearch):def search_for_users(self, email: str) -> list[_LDAPUser]:search = settings.AUTH_LDAP_REVERSE_EMAIL_SEARCH- USERNAME_ATTR = settings.AUTH_LDAP_USERNAME_ATTR+ USERNAME_ATTR = assert_is_not_none(settings.AUTH_LDAP_USERNAME_ATTR)assert search is not None- results = search.execute(self.connection, {"email": email})+ results = self.do_search(search, {"email": email})ldap_users = []for result in results:@@ -810,44 +820,7 @@ def get_and_sync_user_profile_by_external_auth_id(# We need to ensure the email address of the Zulip account remains synced with what's# in the external auth directory. That's the point of external_auth_id-based authentication.- if user_profile.delivery_email != email:- # We intentionally do a case-sensitive comparison, despite emails in Zulip being- # case-insensitive in auth contexts. We want to support the case of sync tweaking just- # capitalization of the email address.- logger.info(- "User %s, logged in via ExternalAuthId %s, has mismatched email. Syncing: %s => %s",- user_profile.id,- external_auth_id,- user_profile.delivery_email,- email,- )- if is_cross_realm_bot_email(email):- # Cross-realm bot emails are reserved for system bots; we- # must never let an external auth directory sync a regular- # user's delivery_email onto one, since is_cross_realm_bot_email- # is used as an authorization shortcut in several places.- logger.warning(- "Can't sync email for user %s: %s is reserved for system bots",- user_profile.id,- email,- )- elif (- UserProfile.objects.filter(realm=realm, delivery_email__iexact=email)- # The EXISTS query has a somewhat strange shape because we need- # to again consider the edge case where we might be simply- # updating capitalization of the email for the user. In such a- # situation, a "conflict" on (realm, delivery_email__iexact) is- # not an actual conflict.- .exclude(id=user_profile.id)- .exists()- ):- logger.warning(- "Can't sync email for user %s: another user exists with target email %s",- user_profile.id,- email,- )- else:- do_change_user_delivery_email(user_profile, email, acting_user=None)+ sync_delivery_email_if_needed(user_profile, email, external_auth_id, logger)return user_profile@@ -1153,6 +1126,33 @@ class ZulipLDAPAuthBackendBase(ZulipAuthMixin, LDAPBackend):except Exception as e:raise ZulipLDAPError(str(e)) from e+ def sync_external_auth_id_from_ldap(+ self, user_profile: UserProfile, ldap_user: "ZulipLDAPUser"+ ) -> None:+ if not ldap_external_auth_id_sync_enabled():+ return++ ldap_external_auth_id = ldap_user.get_external_auth_id()+ external_auth_id_obj, created = ExternalAuthID.objects.get_or_create(+ external_auth_method_name=self.name,+ user=user_profile,+ defaults={+ "external_auth_id": ldap_external_auth_id,+ "realm": user_profile.realm,+ },+ )+ if created or external_auth_id_obj.external_auth_id == ldap_external_auth_id:+ return++ self.logger.warning(+ "User %s had mismatched ExternalAuthID record. Updating %s => %s",+ user_profile.id,+ external_auth_id_obj.external_auth_id,+ ldap_external_auth_id,+ )+ external_auth_id_obj.external_auth_id = ldap_external_auth_id+ external_auth_id_obj.save(update_fields=["external_auth_id"])+class ZulipLDAPAuthBackend(ZulipLDAPAuthBackendBase):REALM_IS_NONE_ERROR = 1@@ -1493,6 +1493,7 @@ class ZulipLDAPUserPopulator(ZulipLDAPAuthBackendBase):self.sync_full_name_from_ldap(user, ldap_user)self.sync_custom_profile_fields_from_ldap(user, ldap_user)self.sync_groups_from_ldap(user, ldap_user)+ self.sync_external_auth_id_from_ldap(user, ldap_user)return (user, built)@@ -1515,22 +1516,189 @@ def catch_ldap_error(signal: Signal, **kwargs: Any) -> None:raise PopulateUserLDAPError(type(kwargs["exception"]).__name__)+def sync_delivery_email_if_needed(+ user_profile: UserProfile,+ email: str,+ external_auth_id: str,+ logger: logging.Logger,+ exception_on_conflict: type[Exception] | None = None,+) -> None:+ if user_profile.delivery_email == email:+ # We intentionally do a case-sensitive comparison, despite emails in Zulip being+ # case-insensitive in auth contexts. We want to support the case of sync tweaking just+ # capitalization of the email address.+ return++ logger.info(+ "User %s, being synced via ExternalAuthId %s, has mismatched email. Syncing: %s => %s",+ user_profile.id,+ external_auth_id,+ user_profile.delivery_email,+ email,+ )++ if is_cross_realm_bot_email(email):+ # Cross-realm bot emails are reserved for system bots; we+ # must never let an external auth directory sync a regular+ # user's delivery_email onto one, since is_cross_realm_bot_email+ # is used as an authorization shortcut in several places.+ msg = f"Can't sync email for user {user_profile.id}: {email} is reserved for system bots"+ if exception_on_conflict is not None: # nocoverage+ raise exception_on_conflict(msg)+ else:+ logger.warning(msg)+ elif (+ UserProfile.objects.filter(realm=user_profile.realm, delivery_email__iexact=email)+ # The EXISTS query has a somewhat strange shape because we need+ # to again consider the edge case where we might be simply+ # updating capitalization of the email for the user. In such a+ # situation, a "conflict" on (realm, delivery_email__iexact) is+ # not an actual conflict.+ .exclude(id=user_profile.id)+ .exists()+ ):+ msg = f"Can't sync email for user {user_profile.id}: another user exists with target email {email}"+ if exception_on_conflict is not None:+ raise exception_on_conflict(msg)+ else:+ logger.warning(msg)+ else:+ do_change_user_delivery_email(user_profile, email, acting_user=None)+++def prepare_ldap_user_for_sync_by_external_auth_id(+ backend: ZulipLDAPUserPopulator, user_profile: UserProfile, logger: logging.Logger+) -> ZulipLDAPUser | None:+ """+ The purpose of this function is to take a UserProfile meant for syncing with LDAP,+ and if it is connected to an LDAP user entry via a ExternalAuthID record, follow+ that connection to fetch the associated LDAP user.+ This allows the UserProfile to be linked to its associated LDAP user even if there's+ a mismatch in the email - most commonly caused by an update to the user's email in the+ LDAP directory.+ If such a mismatch is detected, the UserProfile's email is synced to the LDAP value+ in order to facilitate the rest of the sync codepath being able to successfully do+ its job.+ """+ try:+ external_auth_id_obj = ExternalAuthID.objects.get(+ user=user_profile,+ external_auth_method_name=ZulipLDAPAuthBackendBase.name,+ )+ except ExternalAuthID.DoesNotExist:+ # This UserProfile doesn't have any records connecting it to an LDAP user entry.+ # We can't do anything here.+ return None++ ldap_external_auth_id = external_auth_id_obj.external_auth_id++ attr_name = settings.AUTH_LDAP_USER_ATTR_MAP.get("unique_account_id")+ assert attr_name is not None++ dn_as_external_auth_id = attr_name.lower() == "dn"++ # We have an external_auth_id value, which should allow us to find the matching LDAP+ # user. We need to prepare the appropriate LDAP search query.+ ldap_user_search_obj = assert_is_not_none(settings.AUTH_LDAP_USER_SEARCH)+ base_dn = ldap_user_search_obj.base_dn+ scope = ldap_user_search_obj.scope++ if not dn_as_external_auth_id:+ ldap_search_args = (base_dn, scope, f"({attr_name}=%(external_auth_id)s)")+ search_kwargs_dict = {"external_auth_id": ldap_external_auth_id}+ else:+ # Searching by the DN has a different structure than by a normal attribute.+ ldap_search_args = (ldap_external_auth_id, ldap.SCOPE_BASE, "(objectClass=*)")+ search_kwargs_dict = {}++ try:+ results = ZulipLDAPSearch().do_search(LDAPSearch(*ldap_search_args), search_kwargs_dict)+ except ldap.NO_SUCH_OBJECT:+ # This can happen when doing a DN-based lookup when the matching LDAP entry doesn't exist.+ # In the ldap protocol, SCOPE_BASE lookup returns an error (rather than just empty results)+ # if the target isn't found.+ return None+ results_dns = [result[0] for result in results]+ if not results:+ return None+ elif len(results) > 1:+ raise AssertionError(+ f"LDAPSearch{ldap_search_args} returned multiple results: "+ f"result DNs: {results_dns}. "+ "The search MUST be unique."+ )++ assert len(results) == 1+ user_dn, user_attrs = results[0]++ # We need to return a correct ZulipLDAPUser entry to the caller. To initialize+ # an instance of this class, we need to read the username of the target LDAP+ # user.+ USERNAME_ATTR = assert_is_not_none(settings.AUTH_LDAP_USERNAME_ATTR)+ username = user_attrs[USERNAME_ATTR][0]+ assert isinstance(username, str)++ ldap_user = ZulipLDAPUser(backend, username, realm=user_profile.realm)+ # We've already fetched the user's data, so we can set it on the relevant internal+ # fields of _LDAPUser to avoid django-auth-ldap doing an unnecessary re-fetch.+ ldap_user._user_dn = user_dn+ ldap_user._user_attrs = user_attrs++ email = backend.user_email_from_ldapuser(username, ldap_user)++ # If we detect that the email in LDAP has changed relative to what's on the UserProfile,+ # we need to update it - so that the rest of the sync job, which relies+ # on the email as user identifier, can succeed.+ sync_delivery_email_if_needed(+ user_profile,+ email,+ ldap_external_auth_id,+ logger,+ # If we cannot sync a fundamental attribute like delivery_email, then sync should just+ # straight-up fail.+ # Ignoring the failure to sync the email would also mean that if later in the codepath,+ # we try to get_user_by_delivery_email using the email value from the LDAP record,+ # the incorrect user would be fetched. That's a recipe for very buggy and confusing+ # sync behavior, so let's avoid it entirely.+ exception_on_conflict=PopulateUserLDAPError,+ )++ return ldap_user++def sync_user_from_ldap(user_profile: UserProfile, logger: logging.Logger) -> bool:backend = ZulipLDAPUserPopulator()- try:- ldap_username = backend.django_to_ldap_username(user_profile.delivery_email)- except NoMatchingLDAPUserError:- if (- settings.ONLY_LDAP- if settings.LDAP_DEACTIVATE_NON_MATCHING_USERS is None- else settings.LDAP_DEACTIVATE_NON_MATCHING_USERS- ):- do_deactivate_user(user_profile, acting_user=None)- logger.info("Deactivated non-matching user: %s", user_profile.delivery_email)- return True- elif user_profile.is_active:- logger.warning("Did not find %s in LDAP.", user_profile.delivery_email)- return False+ ldap_user = None+ if ldap_external_auth_id_sync_enabled():+ # If we can fetch the LDAP user data based on the ExternalAuthID connection, then that's the best case.+ # This allows us to find the LDAP user even if its email value has changed.+ ldap_user = prepare_ldap_user_for_sync_by_external_auth_id(backend, user_profile, logger)+ if ldap_user is not None:+ logger.info(+ "Syncing user %s (id=%s) via external auth id. Result DN: %s",+ user_profile.delivery_email,+ user_profile.id,+ ldap_user.dn,+ )++ if ldap_user is None:+ try:+ ldap_username = backend.django_to_ldap_username(user_profile.delivery_email)+ except NoMatchingLDAPUserError:+ if (+ settings.ONLY_LDAP+ if settings.LDAP_DEACTIVATE_NON_MATCHING_USERS is None+ else settings.LDAP_DEACTIVATE_NON_MATCHING_USERS+ ):+ do_deactivate_user(user_profile, acting_user=None)+ logger.info("Deactivated non-matching user: %s", user_profile.delivery_email)+ return True+ elif user_profile.is_active:+ logger.warning("Did not find %s in LDAP.", user_profile.delivery_email)+ return False+ ldap_user = ZulipLDAPUser(backend, ldap_username, realm=user_profile.realm)++ assert ldap_user is not None# What one would expect to see like to do here is just a call to# `backend.populate_user`, which in turn just creates the@@ -1547,7 +1715,7 @@ def sync_user_from_ldap(user_profile: UserProfile, logger: logging.Logger) -> bo## Ideally, we'd contribute changes to `django-auth-ldap` upstream# making this flow possible in a more directly supported fashion.- updated_user = ZulipLDAPUser(backend, ldap_username, realm=user_profile.realm).populate_user()+ updated_user = ldap_user.populate_user()if updated_user:logger.info("Updated %s.", user_profile.delivery_email)return Truediff --git a/zproject/prod_settings_template.py b/zproject/prod_settings_template.pyindex f5ddf50045b..385dcabca34 100644--- a/zproject/prod_settings_template.py+++ b/zproject/prod_settings_template.py@@ -228,6 +228,10 @@ AUTH_LDAP_USER_SEARCH = LDAPSearch("ou=users,dc=example,dc=com", ldap.SCOPE_SUBTREE, "(uid=%(user)s)")+## AUTH_LDAP_USERNAME_ATTR should be the Zulip username attribute+## (defined in AUTH_LDAP_USER_SEARCH).+# AUTH_LDAP_USERNAME_ATTR = "uid"+## Configuration to look up a user's LDAP data given their email address## (for Zulip reverse mapping). If users log in as e.g. "sam" when## their email address is "[email protected]", set LDAP_APPEND_DOMAIN to@@ -242,15 +246,11 @@ AUTH_LDAP_USER_SEARCH = LDAPSearch(# LDAP_EMAIL_ATTR = None## AUTH_LDAP_REVERSE_EMAIL_SEARCH works like AUTH_LDAP_USER_SEARCH and-## should query an LDAP user given their email address. It and-## AUTH_LDAP_USERNAME_ATTR are required when LDAP_APPEND_DOMAIN is None.+## should query an LDAP user given their email address. It is required+## when LDAP_APPEND_DOMAIN is None.# AUTH_LDAP_REVERSE_EMAIL_SEARCH = LDAPSearch("ou=users,dc=example,dc=com",# ldap.SCOPE_SUBTREE, "(email=%(email)s)")-## AUTH_LDAP_USERNAME_ATTR should be the Zulip username attribute-## (defined in AUTH_LDAP_USER_SEARCH).-# AUTH_LDAP_USERNAME_ATTR = "uid"-## This map defines how to populate attributes of a Zulip user from LDAP.#### The format is `zulip_name: ldap_name`; each entry maps a Zulip