diff --git a/dejacode/ldap_config.py b/dejacode/ldap_config.py new file mode 100644 index 00000000..5793be51 --- /dev/null +++ b/dejacode/ldap_config.py @@ -0,0 +1,54 @@ +# +# Copyright (c) nexB Inc. and others. All rights reserved. +# DejaCode is a trademark of nexB Inc. +# SPDX-License-Identifier: AGPL-3.0-only +# See https://github.com/aboutcode-org/dejacode for support or download. +# See https://aboutcode.org for more information about AboutCode FOSS projects. +# + +import json + +from django.core.exceptions import ImproperlyConfigured + +import ldap +from django_auth_ldap.config import LDAPSearch +from django_auth_ldap.config import LDAPSearchUnion + + +def get_user_search(index, search_definition): + """Return an ``LDAPSearch`` from one ``AUTH_LDAP_USER_SEARCHES`` entry.""" + entry_name = f"AUTH_LDAP_USER_SEARCHES[{index}]" + + if not isinstance(search_definition, dict): + raise ImproperlyConfigured(f"{entry_name} must be a JSON object") + + base_dn = search_definition.get("base") + filterstr = search_definition.get("filter") + + has_base_and_filter = all(isinstance(value, str) and value for value in (base_dn, filterstr)) + if not has_base_and_filter: + raise ImproperlyConfigured( + f"{entry_name} must define 'base' and 'filter' as non-empty strings" + ) + + if "%(user)s" not in filterstr: + raise ImproperlyConfigured(f"{entry_name} 'filter' must include the %(user)s placeholder") + + return LDAPSearch(base_dn, ldap.SCOPE_SUBTREE, filterstr) + + +def build_user_search_union(user_searches): + """Return an ``LDAPSearchUnion`` from the ``AUTH_LDAP_USER_SEARCHES`` JSON string.""" + try: + search_definitions = json.loads(user_searches) + except json.JSONDecodeError as error: + raise ImproperlyConfigured(f"Invalid JSON in AUTH_LDAP_USER_SEARCHES: {error}") from error + + if not isinstance(search_definitions, list) or not search_definitions: + raise ImproperlyConfigured("AUTH_LDAP_USER_SEARCHES must be a non-empty JSON list") + + searches = [ + get_user_search(index, search_definition) + for index, search_definition in enumerate(search_definitions) + ] + return LDAPSearchUnion(*searches) diff --git a/dejacode/settings.py b/dejacode/settings.py index c9bc11d9..fc8abda2 100644 --- a/dejacode/settings.py +++ b/dejacode/settings.py @@ -18,6 +18,8 @@ from django_auth_ldap.config import GroupOfNamesType from django_auth_ldap.config import LDAPSearch +from dejacode.ldap_config import build_user_search_union + # The home directory of the dejacode user that owns the installation. PROJECT_DIR = environ.Path(__file__) - 1 ROOT_DIR = PROJECT_DIR - 1 @@ -783,6 +785,14 @@ def get_fake_redis_connection(config, use_strict_redis): AUTH_LDAP_USER_SEARCH = LDAPSearch(AUTH_LDAP_USER_DN, ldap.SCOPE_SUBTREE, AUTH_LDAP_USER_FILTERSTR) +# Optional: search users in several locations of the LDAP directory. +# A JSON list with one entry per location: a "base" DN and a "filter" including %(user)s. +# When set, AUTH_LDAP_USER_DN and AUTH_LDAP_USER_FILTERSTR are ignored. +# AUTH_LDAP_USER_SEARCHES=[{"base": "ou=staff,dc=example,dc=com", "filter": "(uid=%(user)s)"}, ...] +AUTH_LDAP_USER_SEARCHES = env.str("AUTH_LDAP_USER_SEARCHES", default="") +if AUTH_LDAP_USER_SEARCHES: + AUTH_LDAP_USER_SEARCH = build_user_search_union(AUTH_LDAP_USER_SEARCHES) + # When AUTH_LDAP_AUTOCREATE_USER is True (default), a new DejaCode user will be # created in the database with the minimum permission (a read-only user). # Enabling this setting also requires a valid dataspace name for the diff --git a/dje/tests/test_ldap.py b/dje/tests/test_ldap.py index f0234ec4..ccb00786 100644 --- a/dje/tests/test_ldap.py +++ b/dje/tests/test_ldap.py @@ -43,6 +43,7 @@ from guardian.shortcuts import assign_perm from ldap.ldapobject import SimpleLDAPObject +from dejacode.ldap_config import build_user_search_union from dje.ldap_backend import DejaCodeLDAPBackend from dje.models import Dataspace from dje.models import DataspaceConfiguration @@ -176,6 +177,18 @@ def test_ldap_authentication_populate_user(self): self.assertEqual(user.last_name, "Smith") self.assertEqual(user.email, "bob@test.com") + @override_settings( + AUTH_LDAP_USER_DN_TEMPLATE=None, + AUTH_LDAP_USER_SEARCH=build_user_search_union( + '[{"base": "ou=groups,o=test", "filter": "(uid=%(user)s)"},' + ' {"base": "ou=people,o=test", "filter": "(uid=%(user)s)"}]' + ), + ) + def test_ldap_authentication_user_search_union(self): + user = authenticate(username="bob", password="secret") + self.assertEqual("bob", user.username) + self.assertEqual("bob@test.com", user.email) + def test_ldap_group_active_properly_setup_and_searchable(self): conn = self.ldap_object_class(self.server.ldap_uri) results = conn.search_s("ou=groups,o=test", ldap.SCOPE_ONELEVEL, "(cn=active)") diff --git a/dje/tests/test_ldap_config.py b/dje/tests/test_ldap_config.py new file mode 100644 index 00000000..a6c80a9f --- /dev/null +++ b/dje/tests/test_ldap_config.py @@ -0,0 +1,93 @@ +# +# Copyright (c) nexB Inc. and others. All rights reserved. +# DejaCode is a trademark of nexB Inc. +# SPDX-License-Identifier: AGPL-3.0-only +# See https://github.com/aboutcode-org/dejacode for support or download. +# See https://aboutcode.org for more information about AboutCode FOSS projects. +# + +from django.core.exceptions import ImproperlyConfigured +from django.test import SimpleTestCase + +import ldap +from django_auth_ldap.config import LDAPSearch +from django_auth_ldap.config import LDAPSearchUnion + +from dejacode.ldap_config import build_user_search_union +from dejacode.ldap_config import get_user_search + + +class LDAPConfigTestCase(SimpleTestCase): + def test_ldap_config_get_user_search(self): + search_definition = {"base": "ou=users,dc=example,dc=com", "filter": "(uid=%(user)s)"} + user_search = get_user_search(0, search_definition) + self.assertIsInstance(user_search, LDAPSearch) + self.assertEqual("ou=users,dc=example,dc=com", user_search.base_dn) + self.assertEqual(ldap.SCOPE_SUBTREE, user_search.scope) + self.assertEqual("(uid=%(user)s)", user_search.filterstr) + + def test_ldap_config_get_user_search_not_an_object(self): + expected_message = "AUTH_LDAP_USER_SEARCHES[2] must be a JSON object" + with self.assertRaisesMessage(ImproperlyConfigured, expected_message): + get_user_search(2, "ou=users,dc=example,dc=com") + + def test_ldap_config_get_user_search_invalid_base_or_filter(self): + invalid_definitions = [ + {"filter": "(uid=%(user)s)"}, + {"base": "ou=users,dc=example,dc=com"}, + {"base": "", "filter": "(uid=%(user)s)"}, + {"base": ["ou=users,dc=example,dc=com"], "filter": "(uid=%(user)s)"}, + {"base": "ou=users,dc=example,dc=com", "filter": 123}, + ] + expected_message = ( + "AUTH_LDAP_USER_SEARCHES[0] must define 'base' and 'filter' as non-empty strings" + ) + for search_definition in invalid_definitions: + with self.subTest(search_definition=search_definition): + with self.assertRaisesMessage(ImproperlyConfigured, expected_message): + get_user_search(0, search_definition) + + def test_ldap_config_get_user_search_filter_without_user_placeholder(self): + search_definition = {"base": "ou=users,dc=example,dc=com", "filter": "(objectClass=person)"} + expected_message = ( + "AUTH_LDAP_USER_SEARCHES[0] 'filter' must include the %(user)s placeholder" + ) + with self.assertRaisesMessage(ImproperlyConfigured, expected_message): + get_user_search(0, search_definition) + + def test_ldap_config_build_user_search_union(self): + user_searches = ( + '[{"base": "ou=users,dc=example,dc=com", "filter": "(uid=%(user)s)"},' + ' {"base": "ou=staff,dc=example,dc=com", "filter": "(cn=%(user)s)"}]' + ) + user_search_union = build_user_search_union(user_searches) + self.assertIsInstance(user_search_union, LDAPSearchUnion) + search_values = [ + (search.base_dn, search.filterstr) for search in user_search_union.searches + ] + expected = [ + ("ou=users,dc=example,dc=com", "(uid=%(user)s)"), + ("ou=staff,dc=example,dc=com", "(cn=%(user)s)"), + ] + self.assertEqual(expected, search_values) + + def test_ldap_config_build_user_search_union_invalid_json(self): + expected_message = "Invalid JSON in AUTH_LDAP_USER_SEARCHES" + with self.assertRaisesMessage(ImproperlyConfigured, expected_message): + build_user_search_union("{not json") + + def test_ldap_config_build_user_search_union_not_a_non_empty_list(self): + expected_message = "AUTH_LDAP_USER_SEARCHES must be a non-empty JSON list" + for user_searches in ["[]", '{"base": "ou=users,dc=example,dc=com"}', '"text"']: + with self.subTest(user_searches=user_searches): + with self.assertRaisesMessage(ImproperlyConfigured, expected_message): + build_user_search_union(user_searches) + + def test_ldap_config_build_user_search_union_invalid_entry_index(self): + user_searches = ( + '[{"base": "ou=users,dc=example,dc=com", "filter": "(uid=%(user)s)"},' + ' {"base": "ou=staff,dc=example,dc=com"}]' + ) + expected_message = "AUTH_LDAP_USER_SEARCHES[1] must define 'base' and 'filter'" + with self.assertRaisesMessage(ImproperlyConfigured, expected_message): + build_user_search_union(user_searches) diff --git a/docs/application-settings.rst b/docs/application-settings.rst index d7e1903f..eefe47ba 100644 --- a/docs/application-settings.rst +++ b/docs/application-settings.rst @@ -383,6 +383,30 @@ It must return exactly one result for authentication to succeed. AUTH_LDAP_USER_DN="ou=users,dc=example,dc=com" AUTH_LDAP_USER_FILTERSTR="(uid=%(user)s)" +USER_SEARCHES +------------- + +When users are stored in several locations of the LDAP directory, for example in +different organizational units, use ``AUTH_LDAP_USER_SEARCHES`` instead of +``USER_DN``. + +The value is a JSON list with one entry per location: + +- ``base``: the distinguished name of the location. +- ``filter``: the filter to find the user, including the ``%(user)s`` placeholder. + +The following example searches users in both ``employees`` and ``contractors``: + +.. code-block:: python + + AUTH_LDAP_USER_SEARCHES=[{"base": "ou=employees,dc=example,dc=com", "filter": "(uid=%(user)s)"}, {"base": "ou=contractors,dc=example,dc=com", "filter": "(uid=%(user)s)"}] + +All locations are searched, and the username must match exactly one user across +them for authentication to succeed. +When set, ``AUTH_LDAP_USER_DN`` and ``AUTH_LDAP_USER_FILTERSTR`` are ignored. + +.. note:: The value must be written on a single line. + AUTOCREATE_USER ---------------