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.

sync: Truncate simple text custom profile field values when too long.

Mateusz Mandera8b58d8aded8d
diff --git a/zerver/lib/scim.py b/zerver/lib/scim.py
index 99282315196..a80320dc0da 100644
--- a/zerver/lib/scim.py
+++ b/zerver/lib/scim.py
@@ -1,3 +1,4 @@
+import logging
import re
from collections.abc import Callable
from typing import Any
@@ -45,7 +46,9 @@ from zerver.models.realms import (
DomainNotAllowedForRealmError,
EmailContainsPlusError,
)
-from zproject.backends import SyncUserError, validate_custom_profile_field_data
+from zproject.backends import SyncUserError, validate_custom_profile_field_data_for_sync
+
+logger = logging.getLogger(__name__)
class ZulipSCIMUser(SCIMUser):
@@ -361,8 +364,11 @@ class ZulipSCIMUser(SCIMUser):
custom_profile_data = None
if custom_profile_field_data:
try:
- custom_profile_data = validate_custom_profile_field_data(
- realm.id, custom_profile_field_data
+ custom_profile_data = validate_custom_profile_field_data_for_sync(
+ realm.id,
+ custom_profile_field_data,
+ logger,
+ None if self.is_new_user() else self.obj.id,
)
except SyncUserError as e:
raise scim_exceptions.BadRequestError(str(e))
diff --git a/zerver/lib/validator.py b/zerver/lib/validator.py
index ee747d31ad0..7050ec34e5a 100644
--- a/zerver/lib/validator.py
+++ b/zerver/lib/validator.py
@@ -74,8 +74,11 @@ def check_string_in(possible_values: Container[str]) -> Validator[str]:
return validator
+SHORT_STRING_MAX_LENGTH = 50
+
+
def check_short_string(var_name: str, val: object) -> str:
- return check_capped_string(50)(var_name, val)
+ return check_capped_string(SHORT_STRING_MAX_LENGTH)(var_name, val)
def check_capped_string(max_length: int) -> Validator[str]:
@@ -109,8 +112,11 @@ def check_string_fixed_length(length: int) -> Validator[str]:
return validator
+LONG_STRING_MAX_LENGTH = 500
+
+
def check_long_string(var_name: str, val: object) -> str:
- return check_capped_string(500)(var_name, val)
+ return check_capped_string(LONG_STRING_MAX_LENGTH)(var_name, val)
def check_date(var_name: str, val: object) -> str:
diff --git a/zerver/tests/test_auth_backends.py b/zerver/tests/test_auth_backends.py
index c660c51a69d..df93b6e59cd 100644
--- a/zerver/tests/test_auth_backends.py
+++ b/zerver/tests/test_auth_backends.py
@@ -3415,6 +3415,36 @@ class SAMLAuthBackendTest(SocialAuthBase):
self.user_profile.refresh_from_db()
self.assertEqual(self.user_profile.role, UserProfile.ROLE_REALM_OWNER)
+ # Verify that values for text fields are truncated if they're too long.
+ long_value = "x" * 60
+ expected_value = "x" * 49 + "…"
+ with (
+ self.settings(
+ SOCIAL_AUTH_SAML_ENABLED_IDPS=idps_dict,
+ SOCIAL_AUTH_SYNC_ATTRS_DICT=sync_custom_attrs_dict,
+ ),
+ self.assertLogs(self.logger_string, level="WARNING") as m,
+ ):
+ 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(mobilePhone=[long_value]),
+ )
+ data = load_subdomain_token(result)
+ self.assertEqual(data["email"], self.email)
+ self.assertIn(
+ self.logger_output(
+ f"Truncated value for custom profile field phone_number of user {self.user_profile.id} to 50 characters.",
+ type="warning",
+ ),
+ m.output,
+ )
+ phone_field_value = CustomProfileFieldValue.objects.get(
+ user_profile=self.user_profile, field=phone_field
+ ).value
+ self.assertEqual(phone_field_value, expected_value)
+
def test_social_auth_group_sync(self) -> None:
realm = get_realm("zulip")
hamlet = self.example_user("hamlet")
@@ -8353,6 +8383,31 @@ class TestZulipLDAPUserPopulator(ZulipLDAPTestCase):
debug_log.output,
)
+ def test_update_custom_profile_field_truncation(self) -> None:
+ long_value = "x" * 60
+ expected_value = "x" * 49 + "…"
+ self.change_ldap_user_attr("hamlet", "homePhone", long_value)
+
+ with (
+ self.settings(
+ AUTH_LDAP_USER_ATTR_MAP={
+ "full_name": "cn",
+ "custom_profile_field__phone_number": "homePhone",
+ }
+ ),
+ self.assertLogs("zulip.ldap", "WARNING") as log_output,
+ ):
+ self.perform_ldap_sync(self.example_user("hamlet"))
+
+ hamlet = self.example_user("hamlet")
+ phone_field = CustomProfileField.objects.get(realm=hamlet.realm, name="Phone number")
+ phone_value = CustomProfileFieldValue.objects.get(user_profile=hamlet, field=phone_field)
+ self.assertEqual(phone_value.value, expected_value)
+ self.assertIn(
+ f"WARNING:zulip.ldap:Truncated value for custom profile field phone_number of user {hamlet.id} to 50 characters.",
+ log_output.output,
+ )
+
def test_update_custom_profile_field_no_mapping(self) -> None:
hamlet = self.example_user("hamlet")
no_op_field = CustomProfileField.objects.get(realm=hamlet.realm, name="Phone number")
diff --git a/zerver/tests/test_scim.py b/zerver/tests/test_scim.py
index b2d52367d84..09a80ba4cfb 100644
--- a/zerver/tests/test_scim.py
+++ b/zerver/tests/test_scim.py
@@ -1022,6 +1022,47 @@ class TestSCIMUser(SCIMTestCase):
)
self.assertEqual(UserProfile.objects.count(), original_user_count)
+ def test_custom_profile_field_value_truncation(self) -> None:
+ hamlet = self.example_user("hamlet")
+ field_map = {"phone_number": "phoneNumber", "biography": "biography"}
+ long_short_value = "x" * 60
+ expected_short_value = "x" * 49 + "…"
+ long_long_value = "y" * 510
+ expected_long_value = "y" * 499 + "…"
+ payload = {
+ "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
+ "id": hamlet.id,
+ "userName": hamlet.delivery_email,
+ "name": {"formatted": hamlet.full_name},
+ "active": True,
+ "phoneNumber": long_short_value,
+ "biography": long_long_value,
+ }
+
+ with (
+ self.mock_custom_profile_field_map(field_map),
+ self.assertLogs("zerver.lib.scim", level="WARNING") as log_output,
+ ):
+ result = self.json_put(f"/scim/v2/Users/{hamlet.id}", payload, **self.scim_headers())
+ self.assertEqual(result.status_code, 200)
+ self.assertEqual(
+ log_output.output,
+ [
+ f"WARNING:zerver.lib.scim:Truncated value for custom profile field phone_number of user {hamlet.id} to 50 characters.",
+ f"WARNING:zerver.lib.scim:Truncated value for custom profile field biography of user {hamlet.id} to 500 characters.",
+ ],
+ )
+
+ phone_field = CustomProfileField.objects.get(realm=hamlet.realm, name="Phone number")
+ phone_value = CustomProfileFieldValue.objects.get(user_profile=hamlet, field=phone_field)
+ self.assertEqual(phone_value.value, expected_short_value)
+
+ biography_field = CustomProfileField.objects.get(realm=hamlet.realm, name="Biography")
+ biography_value = CustomProfileFieldValue.objects.get(
+ user_profile=hamlet, field=biography_field
+ )
+ self.assertEqual(biography_value.value, expected_long_value)
+
def test_custom_profile_field_nonexistent_field(self) -> None:
# Map a SCIM attribute to a var_name that doesn't match any custom profile field.
field_map = {"nonexistent_field": "someAttr"}
diff --git a/zproject/backends.py b/zproject/backends.py
index ec5e3c3f358..3d928fec927 100644
--- a/zproject/backends.py
+++ b/zproject/backends.py
@@ -96,6 +96,7 @@ from zerver.lib.subdomains import get_subdomain
from zerver.lib.types import ProfileDataElementUpdateDict
from zerver.lib.user_groups import check_user_group_name, get_role_based_system_groups_dict
from zerver.lib.users import check_full_name, validate_user_custom_profile_field
+from zerver.lib.validator import LONG_STRING_MAX_LENGTH, SHORT_STRING_MAX_LENGTH
from zerver.models import (
CustomProfileField,
NamedUserGroup,
@@ -1099,7 +1100,7 @@ class ZulipLDAPAuthBackendBase(ZulipAuthMixin, LDAPBackend):
values_by_var_name[var_name] = value
try:
- sync_user_profile_custom_fields(user_profile, values_by_var_name)
+ sync_user_profile_custom_fields(user_profile, values_by_var_name, ldap_logger)
except SyncUserError as e:
raise ZulipLDAPError(str(e)) from e
@@ -1747,8 +1748,18 @@ class SyncUserError(Exception):
pass
-def validate_custom_profile_field_data(
- realm_id: int, custom_field_name_to_value: dict[str, Any]
+def truncate_custom_profile_field_text_for_sync(value: str, length: int) -> str:
+ assert len(value) > length
+ return value[: length - 1] + "…"
+
+
+def validate_custom_profile_field_data_for_sync(
+ realm_id: int,
+ custom_field_name_to_value: dict[str, Any],
+ logger: logging.Logger,
+ # This can be called during new user creation (in SCIM codepaths),
+ # so user ID might not be available.
+ user_id: int | None,
) -> list[ProfileDataElementUpdateDict]:
"""Validate custom profile field var names and values, returning the
validated profile data list. Raises SyncUserError if a var name
@@ -1765,6 +1776,26 @@ def validate_custom_profile_field_data(
field = fields_by_var_name[var_name]
except KeyError:
raise SyncUserError(f"Custom profile field with name {var_name} not found.")
+
+ # For TEXT type fields we can provide a reasonable truncation behavior to allow
+ # a mostly-successful sync instead of failing with an error.
+ text_field_max_length = {
+ CustomProfileField.SHORT_TEXT: SHORT_STRING_MAX_LENGTH,
+ CustomProfileField.LONG_TEXT: LONG_STRING_MAX_LENGTH,
+ }.get(field.field_type)
+ if (
+ isinstance(value, str)
+ and text_field_max_length is not None
+ and len(value) > text_field_max_length
+ ):
+ value = truncate_custom_profile_field_text_for_sync(value, text_field_max_length)
+ logger.warning(
+ "Truncated value for custom profile field %s of user %s to %d characters.",
+ var_name,
+ user_id,
+ text_field_max_length,
+ )
+
try:
validate_user_custom_profile_field(realm_id, field, value)
except ValidationError as error:
@@ -1779,10 +1810,12 @@ def validate_custom_profile_field_data(
def sync_user_profile_custom_fields(
- user_profile: UserProfile, custom_field_name_to_value: dict[str, Any]
+ user_profile: UserProfile,
+ custom_field_name_to_value: dict[str, Any],
+ logger: logging.Logger,
) -> None:
- profile_data = validate_custom_profile_field_data(
- user_profile.realm_id, custom_field_name_to_value
+ profile_data = validate_custom_profile_field_data_for_sync(
+ user_profile.realm_id, custom_field_name_to_value, logger, user_profile.id
)
do_update_user_custom_profile_data_if_changed(user_profile, profile_data, None, notify=True)
@@ -2215,7 +2248,9 @@ def social_auth_sync_user_attributes(
)
try:
- sync_user_profile_custom_fields(user_profile, custom_profile_field_name_to_value)
+ sync_user_profile_custom_fields(
+ user_profile, custom_profile_field_name_to_value, backend.logger
+ )
except SyncUserError as e:
backend.logger.warning(
"Exception while syncing custom profile fields for user %s: %s",