Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

auth: Fix 500 on login with a new ExternalAuthID for a linked account.

Mateusz Mandera835c0b70e1f0
diff --git a/docs/production/authentication-methods.md b/docs/production/authentication-methods.md
index 890be39286a..3c40607471a 100644
--- a/docs/production/authentication-methods.md
+++ b/docs/production/authentication-methods.md
@@ -415,6 +415,27 @@ For Active Directory installations, the immutable Security Identifier
[`objectSid`](https://ldapwiki.com/wiki/Wiki.jsp?page=Security%20Identifier)
is recommended.
+:::{note}
+
+If a Zulip account is already linked to a different
+`unique_account_id` than the one in LDAP for the same email address,
+Zulip will refuse the login and log a warning, since the email address
+may have been reassigned to a different person. This can happen when
+a user's LDAP account is deleted and recreated, if `unique_account_id`
+is an attribute like `objectSid` that is assigned anew to each
+account.
+
+`manage.py sync_ldap_user_data`, as an explicit tool for syncing
+Zulip with LDAP, handles this case differently. When it finds a Zulip
+account linked to a different `unique_account_id` than the LDAP
+account with the same email address, it logs a warning and relinks
+the Zulip account to the new LDAP account. Running it is thus how to
+let such a user log in again. If you run it in a [regular cron
+job](#synchronizing-data), as recommended, this happens automatically
+on its next run.
+
+:::
+
#### Manually handling LDAP email changes
If you don't have `unique_account_id` enabled, when a user's email
@@ -838,6 +859,13 @@ user logs in. If another Zulip user already has the new email address,
the email will not be updated, a warning will be logged and the
administrator should resolve the conflict manually.
+If a Zulip account is already linked to a different permanent ID
+than the one the IdP sends for the same email address (for example,
+because the user's account at the IdP was deleted and recreated),
+Zulip will refuse the login and log a warning, since the email
+address may have been reassigned to a different person. The
+administrator should resolve the conflict manually.
+
:::
### SCIM
@@ -1195,6 +1223,16 @@ user logs in. If another Zulip user already has the new email address,
the email will not be updated, a warning will be logged and the
administrator should resolve the conflict manually.
+If a Zulip account is already linked to a different `sub` than the
+one the IdP sends for the same email address, Zulip will refuse the
+login and log a warning, since the email address may have been
+reassigned to a different person. The administrator should resolve
+the conflict manually. This can happen when the user's account at the
+IdP was deleted and recreated. With Microsoft Entra ID, it can also
+happen for all users if the Zulip application is registered again with
+a new client ID, since Entra ID issues a different `sub` for each
+application.
+
:::
### Microsoft Entra ID (OIDC)
diff --git a/zerver/tests/test_auth_backends.py b/zerver/tests/test_auth_backends.py
index 2bcf6119545..c8dec4c62ec 100644
--- a/zerver/tests/test_auth_backends.py
+++ b/zerver/tests/test_auth_backends.py
@@ -5644,6 +5644,57 @@ class GenericOpenIdConnectTest(SocialAuthBaseWithSyncAttrTest):
m.output[1],
)
+ def test_external_auth_id_oidc_account_linked_to_different_sub(self) -> None:
+ """
+ Test that login is refused when the account with the matching email is
+ already linked to a different sub, rather than relinking the account.
+ """
+ hamlet = self.example_user("hamlet")
+ realm = hamlet.realm
+
+ idps_config_dict = copy.deepcopy(settings.SOCIAL_AUTH_OIDC_ENABLED_IDPS)
+ idps_config_dict["testoidc"]["enable_external_auth_id_auth"] = True
+
+ account_data_dict = self.get_account_data_dict(email=self.email, name=self.name)
+ account_data_dict["sub"] = "original_sub"
+ with (
+ self.settings(SOCIAL_AUTH_OIDC_ENABLED_IDPS=idps_config_dict),
+ 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"], hamlet.delivery_email)
+
+ account_data_dict["sub"] = "new_sub"
+ with (
+ self.settings(SOCIAL_AUTH_OIDC_ENABLED_IDPS=idps_config_dict),
+ self.assertLogs(self.logger_string, level="WARNING") as m,
+ ):
+ result = self.social_auth_test(
+ account_data_dict,
+ subdomain="zulip",
+ )
+ self.assertEqual(result.status_code, 302)
+ self.assertEqual(result["Location"], realm.url + "/login/")
+ self.assertEqual(
+ m.output,
+ [
+ self.logger_output(
+ f"Can't log in user {hamlet.id} via ExternalAuthID new_sub: "
+ "account is already linked to ExternalAuthID original_sub",
+ "warning",
+ )
+ ],
+ )
+
+ external_auth_ids = list(ExternalAuthID.objects.filter(realm=realm))
+ self.assert_length(external_auth_ids, 1)
+ self.assertEqual(external_auth_ids[0].user, hamlet)
+ self.assertEqual(external_auth_ids[0].external_auth_id, "original_sub")
+
@override_settings(TERMS_OF_SERVICE_VERSION=None)
def test_external_auth_id_oidc_registration(self) -> None:
@@ -8312,6 +8363,28 @@ class TestLDAP(ZulipLDAPTestCase):
self.assertEqual(new_external_auth_id.external_auth_method_name, "ldap")
self.assertEqual(new_external_auth_id.external_auth_id, "123456789")
+ # The account is recreated in LDAP with the same email but a new
+ # unique_account_id. The login is refused rather than relinking
+ # the Zulip account to the new LDAP account.
+ self.change_ldap_user_attr(username, "homePhone", "987654321")
+ with self.assertLogs("zulip.auth.ldap", level="WARNING") as mock_log:
+ user_profile = self.backend.authenticate(
+ request=mock.MagicMock(),
+ username=username,
+ password=self.ldap_password("hamlet"),
+ realm=get_realm("zulip"),
+ )
+ self.assertIsNone(user_profile)
+ self.assertEqual(
+ mock_log.output,
+ [
+ f"WARNING:zulip.auth.ldap:Can't log in user {hamlet.id} via ExternalAuthID 987654321: account is already linked to ExternalAuthID 123456789"
+ ],
+ )
+ 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")
+
@override_settings(
AUTHENTICATION_BACKENDS=("zproject.backends.ZulipLDAPAuthBackend",),
LDAP_EMAIL_ATTR="mail",
diff --git a/zproject/backends.py b/zproject/backends.py
index 8132ef4a5b5..85cf73fd610 100644
--- a/zproject/backends.py
+++ b/zproject/backends.py
@@ -797,15 +797,34 @@ def get_and_sync_user_profile_by_external_auth_id(
).user
except ExternalAuthID.DoesNotExist:
user_profile = common_get_active_user(email, realm, return_data)
- if user_profile is not None:
- # If we found an account with the matching email, but no ExternalAuthID, then this account hasn't
- # yet had its external_auth_id stored - we need to do this now.
- ExternalAuthID.objects.create(
- external_auth_method_name=external_auth_method_name,
- external_auth_id=external_auth_id,
- realm=realm,
- user=user_profile,
+ if user_profile is None:
+ return None
+
+ existing_external_auth_id = ExternalAuthID.objects.filter(
+ user=user_profile, external_auth_method_name=external_auth_method_name
+ ).first()
+ if existing_external_auth_id is not None:
+ # The account with the matching email is already linked to a different
+ # external_auth_id. This can mean the account was recreated in the external
+ # auth directory, but it can also mean the email address was reassigned
+ # to a different person there, so we can't safely relink the account.
+ logger.warning(
+ "Can't log in user %s via ExternalAuthID %s: account is already linked to ExternalAuthID %s",
+ user_profile.id,
+ external_auth_id,
+ existing_external_auth_id.external_auth_id,
)
+ return_data["external_auth_id_conflict"] = True
+ return None
+
+ # If we found an account with the matching email, but no ExternalAuthID, then this account hasn't
+ # yet had its external_auth_id stored - we need to do this now.
+ ExternalAuthID.objects.create(
+ external_auth_method_name=external_auth_method_name,
+ external_auth_id=external_auth_id,
+ realm=realm,
+ user=user_profile,
+ )
return user_profile
assert user_profile is not None
@@ -1265,6 +1284,8 @@ class ZulipLDAPAuthBackend(ZulipLDAPAuthBackendBase):
raise ZulipLDAPError("Realm has been deactivated")
if return_data.get("inactive_user"):
raise ZulipLDAPError("User has been deactivated")
+ if return_data.get("external_auth_id_conflict"):
+ raise ZulipLDAPError("User is already linked to a different ExternalAuthID")
# An invalid_subdomain `return_data` value here is ignored,
# since that just means we're trying to create an account in a
# second realm on the server (`ldap_auth_enabled(realm)` would
@@ -2693,6 +2714,7 @@ def social_auth_finish(
invalid_email = return_data.get("invalid_email")
auth_failed_reason = return_data.get("social_auth_failed_reason")
email_not_associated = return_data.get("email_not_associated")
+ external_auth_id_conflict = return_data.get("external_auth_id_conflict")
if invalid_realm:
# User has passed an invalid subdomain param - this shouldn't happen in the normal flow,
@@ -2702,7 +2724,13 @@ def social_auth_finish(
return HttpResponseRedirect(reverse("find_account"))
realm = Realm.objects.get(id=return_data["realm_id"])
- if auth_backend_disabled or inactive_realm or no_verified_email or email_not_associated:
+ if (
+ auth_backend_disabled
+ or inactive_realm
+ or no_verified_email
+ or email_not_associated
+ or external_auth_id_conflict
+ ):
# Redirect to login page. We can't send to registration
# workflow with these errors. We will redirect to login page.
return redirect_to_login(realm)