Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
ldap: Support binary attributes as unique_account_id.
Mateusz Mandera198cf5f2532b
diff --git a/docs/production/authentication-methods.md b/docs/production/authentication-methods.mdindex 3c40607471a..8c5e922b251 100644--- a/docs/production/authentication-methods.md+++ b/docs/production/authentication-methods.md@@ -415,6 +415,19 @@ For Active Directory installations, the immutable Security Identifier[`objectSid`](https://ldapwiki.com/wiki/Wiki.jsp?page=Security%20Identifier)is recommended.+Some attributes, including Active Directory's `objectSid`, have binary rather+than textual values. When using such an attribute, you must additionally set+`LDAP_UNIQUE_ACCOUNT_ID_IS_BINARY`:++```python+AUTH_LDAP_USER_ATTR_MAP = {+ # ...+ "unique_account_id": "objectSid",+}++LDAP_UNIQUE_ACCOUNT_ID_IS_BINARY = True+```+:::{note}If a Zulip account is already linked to a differentdiff --git a/zerver/tests/test_auth_backends.py b/zerver/tests/test_auth_backends.pyindex 2e682dac340..dafcea3417c 100644--- a/zerver/tests/test_auth_backends.py+++ b/zerver/tests/test_auth_backends.py@@ -8118,6 +8118,16 @@ class DjangoToLDAPUsernameTests(ZulipTestCase):self.assertTrue(user_profile.is_active)+# A realistic Active Directory objectSid value. Values of such binary attributes+# generally aren't valid utf-8, so django-auth-ldap hands them to us as bytes.+EXAMPLE_OBJECT_SID = bytes.fromhex("010500000000000515000000a065cf7e784b9b5fe77c8770091f0200")+# An objectSid value that happens to be valid utf-8, and thus gets decoded to a str+# by django-auth-ldap before it reaches us. This is a rare, but possible, edge case.+EXAMPLE_UTF8_DECODABLE_OBJECT_SID = bytes.fromhex(+ "0105000000000005150000000102030405060708090a0b0c51040000"+)++class ZulipLDAPTestCase(ZulipTestCase):@overridedef setUp(self) -> None:@@ -8390,6 +8400,31 @@ class TestLDAP(ZulipLDAPTestCase):self.assert_length(external_auth_ids, 1)self.assertEqual(external_auth_ids[0].external_auth_id, "123456789")+ @override_settings(+ AUTHENTICATION_BACKENDS=("zproject.backends.ZulipLDAPAuthBackend",),+ LDAP_EMAIL_ATTR="mail",+ AUTH_LDAP_USER_ATTR_MAP={"full_name": "cn", "unique_account_id": "objectSid"},+ LDAP_UNIQUE_ACCOUNT_ID_IS_BINARY=True,+ )+ def test_external_auth_id_login_with_binary_unique_account_id_attribute(self) -> None:+ """+ Attributes that are the natural choice for unique_account_id in Active Directory,+ such as objectSid, have binary values - which we store hex-encoded.+ """+ hamlet = self.example_user("hamlet")+ self.change_ldap_user_attr("hamlet", "objectSid", EXAMPLE_OBJECT_SID)++ user_profile = self.backend.authenticate(+ request=mock.MagicMock(),+ username=self.ldap_username("hamlet"),+ password=self.ldap_password("hamlet"),+ realm=get_realm("zulip"),+ )+ self.assertEqual(hamlet.id, user_profile.id)++ external_auth_id = ExternalAuthID.objects.get(user=hamlet)+ self.assertEqual(external_auth_id.external_auth_id, EXAMPLE_OBJECT_SID.hex())+@override_settings(AUTHENTICATION_BACKENDS=("zproject.backends.ZulipLDAPAuthBackend",),LDAP_EMAIL_ATTR="mail",@@ -9309,6 +9344,143 @@ class TestZulipLDAPUserPopulator(ZulipLDAPTestCase):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": "objectSid"},+ LDAP_UNIQUE_ACCOUNT_ID_IS_BINARY=True,+ )+ def test_sync_creates_external_auth_id_record_for_binary_attribute(self) -> None:+ hamlet = self.example_user("hamlet")++ self.change_ldap_user_attr("hamlet", "objectSid", EXAMPLE_OBJECT_SID)+ sync_user_from_ldap(hamlet, mock.Mock())+ self.assertEqual(+ ExternalAuthID.objects.get(user=hamlet).external_auth_id, EXAMPLE_OBJECT_SID.hex()+ )++ # A binary value that django-auth-ldap managed to decode to a str has to end up+ # stored in the same way as one that reaches us as bytes.+ ExternalAuthID.objects.filter(user=hamlet).delete()+ self.change_ldap_user_attr("hamlet", "objectSid", EXAMPLE_UTF8_DECODABLE_OBJECT_SID)+ sync_user_from_ldap(hamlet, mock.Mock())+ self.assertEqual(+ ExternalAuthID.objects.get(user=hamlet).external_auth_id,+ EXAMPLE_UTF8_DECODABLE_OBJECT_SID.hex(),+ )++ @override_settings(+ LDAP_EMAIL_ATTR="mail",+ AUTH_LDAP_USER_ATTR_MAP={"full_name": "cn", "unique_account_id": "objectSid"},+ )+ def test_sync_with_binary_unique_account_id_attribute_misconfigured(self) -> None:+ hamlet = self.example_user("hamlet")+ self.change_ldap_user_attr("hamlet", "objectSid", EXAMPLE_OBJECT_SID)++ with (+ self.assertRaises(AssertionError) as e,+ self.assertLogs("django_auth_ldap", level="WARNING"),+ ):+ sync_user_from_ldap(hamlet, mock.Mock())++ self.assertEqual(+ str(e.exception),+ "Attribute objectSid configured as unique_account_id has non-string values. "+ "You might need to set LDAP_UNIQUE_ACCOUNT_ID_IS_BINARY to True.",+ )++ @override_settings(+ LDAP_EMAIL_ATTR="mail",+ AUTH_LDAP_USER_ATTR_MAP={"full_name": "cn", "unique_account_id": "objectSid"},+ LDAP_UNIQUE_ACCOUNT_ID_IS_BINARY=True,+ )+ def test_sync_via_external_auth_id_binary_attribute(self) -> None:+ hamlet = self.example_user("hamlet")+ hamlet_dn = "uid=hamlet,ou=users,dc=zulip,dc=com"+ self.change_ldap_user_attr("hamlet", "objectSid", EXAMPLE_OBJECT_SID)+ ExternalAuthID.objects.create(+ user=hamlet,+ realm=hamlet.realm,+ external_auth_method_name="ldap",+ external_auth_id=EXAMPLE_OBJECT_SID.hex(),+ )+ self.change_ldap_user_attr("hamlet", "mail", "[email protected]")++ # Our fake LDAP directory can't match binary values in a search filter, so we+ # answer the search ourselves - and verify that the filter sent to the LDAP+ # server is the escaped octet form it expects for a binary value.+ logger = logging.getLogger("zulip.sync_ldap_user_data")+ with (+ mock.patch.object(+ self.mock_ldap,+ "search_s",+ return_value=[(hamlet_dn, self.mock_ldap.directory[hamlet_dn])],+ ) as mock_search_s,+ self.assertLogs(logger, level="INFO") as log_output,+ ):+ sync_user_from_ldap(hamlet, logger)++ mock_search_s.assert_called_once_with(+ "ou=users,dc=zulip,dc=com",+ ldap.SCOPE_ONELEVEL,+ r"(objectSid=\01\05\00\00\00\00\00\05\15\00\00\00\a0\65\cf\7e"+ r"\78\4b\9b\5f\e7\7c\87\70\09\1f\02\00)",+ None,+ )++ hamlet.refresh_from_db()+ self.assertEqual(hamlet.delivery_email, "[email protected]")++ self.assertIn(+ f"INFO:zulip.sync_ldap_user_data:Syncing user [email protected] (id={hamlet.id})"+ f" via external auth id. Result DN: {hamlet_dn}",+ log_output.output,+ )+ self.assertIn(+ f"INFO:zulip.sync_ldap_user_data:User {hamlet.id},"+ f" being synced via ExternalAuthId {EXAMPLE_OBJECT_SID.hex()},"+ " 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": "objectSid"},+ LDAP_UNIQUE_ACCOUNT_ID_IS_BINARY=True,+ )+ def test_sync_via_external_auth_id_binary_attribute_with_non_hex_value(self) -> None:+ # An ExternalAuthID record can predate unique_account_id being switched to+ # a binary attribute, in which case its value isn't hex.+ hamlet = self.example_user("hamlet")+ self.change_ldap_user_attr("hamlet", "objectSid", EXAMPLE_OBJECT_SID)+ external_auth_id_obj = ExternalAuthID.objects.create(+ user=hamlet,+ realm=hamlet.realm,+ external_auth_method_name="ldap",+ external_auth_id="uid=hamlet,ou=users,dc=zulip,dc=com",+ )++ logger = logging.getLogger("zulip.sync_ldap_user_data")+ with (+ self.assertLogs(logger, level="WARNING") as log_output,+ self.assertLogs("zulip.auth.ldap", level="WARNING") as ldap_log_output,+ ):+ sync_user_from_ldap(hamlet, logger)++ self.assertIn(+ f"WARNING:zulip.sync_ldap_user_data:ExternalAuthID {external_auth_id_obj.id}"+ f" for user {hamlet.id} is not a valid value of the binary attribute objectSid",+ log_output.output,+ )++ # The user gets synced via their email address instead, which fixes up the record.+ self.assertIn(+ f"WARNING:zulip.auth.ldap:User {hamlet.id} had mismatched ExternalAuthID record. "+ f"Updating uid=hamlet,ou=users,dc=zulip,dc=com => {EXAMPLE_OBJECT_SID.hex()}",+ ldap_log_output.output,+ )+ external_auth_id_obj.refresh_from_db()+ self.assertEqual(external_auth_id_obj.external_auth_id, EXAMPLE_OBJECT_SID.hex())+@override_settings(LDAP_EMAIL_ATTR="mail",AUTH_LDAP_USER_ATTR_MAP={"full_name": "cn", "unique_account_id": "dn"},@@ -9493,6 +9665,24 @@ class TestZulipLDAPUserPopulator(ZulipLDAPTestCase):class TestQueryLDAP(ZulipLDAPTestCase):+ @override_settings(AUTHENTICATION_BACKENDS=("zproject.backends.ZulipLDAPAuthBackend",))+ def test_query_with_binary_unique_account_id(self) -> None:+ self.change_ldap_user_attr("hamlet", "objectSid", EXAMPLE_OBJECT_SID)+ with self.settings(+ AUTH_LDAP_USER_ATTR_MAP={"full_name": "cn", "unique_account_id": "objectSid"},+ LDAP_UNIQUE_ACCOUNT_ID_IS_BINARY=True,+ ):+ values = query_ldap(self.example_email("hamlet"))++ # The unique_account_id is displayed the way it gets stored.+ self.assertEqual(+ values,+ [+ "full_name: King Hamlet",+ f"unique_account_id: {EXAMPLE_OBJECT_SID.hex()}",+ ],+ )+@override_settings(AUTHENTICATION_BACKENDS=("zproject.backends.EmailAuthBackend",))def test_ldap_not_configured(self) -> None:values = query_ldap(self.example_email("hamlet"))diff --git a/zproject/backends.py b/zproject/backends.pyindex 85cf73fd610..8dd90e6ac67 100644--- a/zproject/backends.py+++ b/zproject/backends.py@@ -677,9 +677,9 @@ class ZulipLDAPSearch(_LDAPUser):super().__init__(LDAPBackend(), username="")def do_search(- self, ldap_search: LDAPSearch, kwargs_dict: dict[str, str]+ self, ldap_search: LDAPSearch, kwargs_dict: dict[str, str], escape: bool = True) -> list[tuple[str, dict[str, list[object]]]]:- return ldap_search.execute(self.connection, kwargs_dict)+ return ldap_search.execute(self.connection, kwargs_dict, escape=escape)class LDAPReverseEmailSearch(ZulipLDAPSearch):@@ -736,6 +736,30 @@ def ldap_external_auth_id_sync_enabled() -> bool:return True+def binary_ldap_attr_value_to_hex(value: str | bytes) -> str:+ """+ django-auth-ldap decodes attribute values from utf-8 when it can, and leaves+ them as raw bytes when it can't - so the values of a binary attribute reach us+ as either type, depending on the individual value. Both forms represent the+ underlying bytes losslessly; we convert them to hex, as binary data can't be+ stored in a text field.+ """+ if isinstance(value, str):+ value = value.encode()++ return value.hex()+++def hex_to_escaped_ldap_filter_value(value: str) -> str:+ r"""+ Binary values have to be matched in an ldap search filter as escaped octets,+ e.g. \01\05\00 - see RFC 4515.++ Raises ValueError if the value isn't valid hex.+ """+ return "".join(f"\\{byte:02x}" for byte in bytes.fromhex(value))++class ZulipLDAPSettings(LDAPSettings):NON_SYNCABLE_ATTRS = ["unique_account_id",@@ -1394,7 +1418,15 @@ class ZulipLDAPUser(_LDAPUser):return self.dnexternal_auth_id = self.attrs[attr_name][0]- assert isinstance(external_auth_id, str)+ if settings.LDAP_UNIQUE_ACCOUNT_ID_IS_BINARY:+ return binary_ldap_attr_value_to_hex(external_auth_id)++ if not isinstance(external_auth_id, str):+ raise AssertionError(+ f"Attribute {attr_name} configured as unique_account_id has non-string values. "+ "You might need to set LDAP_UNIQUE_ACCOUNT_ID_IS_BINARY to True."+ )+return external_auth_id# We intentionally want to create a transaction savepoint here. This only@@ -1624,16 +1656,39 @@ def prepare_ldap_user_for_sync_by_external_auth_id(base_dn = ldap_user_search_obj.base_dnscope = ldap_user_search_obj.scope+ escape_filter_value = Trueif 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}+ if settings.LDAP_UNIQUE_ACCOUNT_ID_IS_BINARY:+ # Values of a binary attribute are stored hex-encoded, and have to be+ # matched in the search filter as escaped octets - which django-auth-ldap+ # must therefore not escape again.+ escape_filter_value = False+ try:+ search_value = hex_to_escaped_ldap_filter_value(ldap_external_auth_id)+ except ValueError:+ # This can happen with an ExternalAuthID record created before the+ # unique_account_id attribute was configured as binary. Syncing the user+ # via their email address will fix up the record.+ logger.warning(+ "ExternalAuthID %s for user %s is not a valid value of the binary attribute %s",+ external_auth_id_obj.id,+ user_profile.id,+ attr_name,+ )+ return None+ else:+ search_value = ldap_external_auth_id+ search_kwargs_dict = {"external_auth_id": search_value}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)+ results = ZulipLDAPSearch().do_search(+ LDAPSearch(*ldap_search_args), search_kwargs_dict, escape=escape_filter_value+ )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)@@ -1758,9 +1813,16 @@ def query_ldap(email: str) -> list[str]:ldap_attrs = _LDAPUser(backend, ldap_username).attrsfor django_field, ldap_field in settings.AUTH_LDAP_USER_ATTR_MAP.items():- value = ldap_attrs.get(ldap_field, ["LDAP field not present"])[0]+ if ldap_field not in ldap_attrs:+ values.append(f"{django_field}: LDAP field not present")+ continue++ value = ldap_attrs[ldap_field][0]if django_field == "avatar" and isinstance(value, bytes):value = "(An avatar image file)"+ elif django_field == "unique_account_id" and settings.LDAP_UNIQUE_ACCOUNT_ID_IS_BINARY:+ # Display the value the way it gets stored in the ExternalAuthID record.+ value = binary_ldap_attr_value_to_hex(value)values.append(f"{django_field}: {value}")if settings.LDAP_EMAIL_ATTR is not None:values.append("{}: {}".format("email", ldap_attrs[settings.LDAP_EMAIL_ATTR][0]))diff --git a/zproject/default_settings.py b/zproject/default_settings.pyindex 32573bb1a72..f91eaeb96ef 100644--- a/zproject/default_settings.py+++ b/zproject/default_settings.py@@ -60,6 +60,9 @@ AUTH_LDAP_USERNAME_ATTR: str | None = NoneAUTH_LDAP_USER_ATTR_MAP: dict[str, str] = {"full_name": "cn",}+# Whether the attribute configured as unique_account_id has binary values,+# like Active Directory's objectSid.+LDAP_UNIQUE_ACCOUNT_ID_IS_BINARY = False# Automatically deactivate users not found by the AUTH_LDAP_USER_SEARCH query.LDAP_DEACTIVATE_NON_MATCHING_USERS: bool | None = None# AUTH_LDAP_CONNECTION_OPTIONS: we set ldap.OPT_REFERRALS in settings.py if unset.diff --git a/zproject/prod_settings_template.py b/zproject/prod_settings_template.pyindex 1357afdafcc..8b4235a1e1b 100644--- a/zproject/prod_settings_template.py+++ b/zproject/prod_settings_template.py@@ -285,6 +285,10 @@ AUTH_LDAP_USER_ATTR_MAP = {# "org_membership": "department",}+## Set this if the attribute configured as unique_account_id has binary+## values, such as Active Directory's objectSid.+# LDAP_UNIQUE_ACCOUNT_ID_IS_BINARY = True+## Whether to automatically deactivate users not found in LDAP. If LDAP## is the only authentication method, then this setting defaults to## True. If other authentication methods are enabled, it defaults to