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.

scim: Add support for syncing custom profile fields.

Tim Abbottec56a6762985
diff --git a/docs/production/scim.md b/docs/production/scim.md
index a6de7e22b9b..44c29786fce 100644
--- a/docs/production/scim.md
+++ b/docs/production/scim.md
@@ -61,7 +61,7 @@ The Zulip server-side configuration is straightforward:
Example configuration with the additional option:
- ```
+ ```python
SCIM_CONFIG = {
"subdomain": {
"bearer_token": "<secret token>",
@@ -71,3 +71,33 @@ The Zulip server-side configuration is straightforward:
}
}
```
+
+- To sync custom profile fields from the SCIM IdP, add
+ `"custom_profile_field_map"` to your client's config dict. This is a
+ dictionary mapping Zulip custom profile field names to SCIM
+ attribute names. A custom profile field is represented for this feature
+ by its user-facing name in lowercase with spaces replaced by underscores
+ (e.g., "Phone number" is represented by `phone_number`).
+
+ Example configuration with custom profile field syncing:
+
+ ```python
+ SCIM_CONFIG = {
+ "subdomain": {
+ "bearer_token": "<secret token>",
+ "scim_client_name": "okta",
+ "name_formatted_included": False,
+ "custom_profile_field_map": {
+ # Phone number
+ "phone_number": "phoneNumber",
+ # Birthday
+ "birthday": "birthday",
+ },
+ }
+ }
+ ```
+
+ With this configuration, when the SCIM IdP sends a `phoneNumber`
+ attribute in a User request, its value will be synced to the "Phone
+ number" custom profile field in Zulip. The custom profile fields
+ referenced must already exist in the Zulip organization settings.
diff --git a/zerver/lib/scim.py b/zerver/lib/scim.py
index 9625e5475e3..99282315196 100644
--- a/zerver/lib/scim.py
+++ b/zerver/lib/scim.py
@@ -14,6 +14,7 @@ from django_scim.adapters import SCIMGroup, SCIMUser
from scim2_filter_parser.attr_paths import AttrPath
from zerver.actions.create_user import do_create_user, do_reactivate_user
+from zerver.actions.custom_profile_fields import do_update_user_custom_profile_data_if_changed
from zerver.actions.user_groups import (
bulk_add_members_to_user_groups,
bulk_remove_members_from_user_groups,
@@ -34,12 +35,17 @@ from zerver.lib.user_groups import (
get_user_group_direct_member_ids,
)
from zerver.models import Realm, UserProfile
+from zerver.models.custom_profile_fields import (
+ CustomProfileFieldValue,
+ custom_profile_fields_for_realm,
+)
from zerver.models.groups import NamedUserGroup, SystemGroups
from zerver.models.realms import (
DisposableEmailError,
DomainNotAllowedForRealmError,
EmailContainsPlusError,
)
+from zproject.backends import SyncUserError, validate_custom_profile_field_data
class ZulipSCIMUser(SCIMUser):
@@ -75,6 +81,7 @@ class ZulipSCIMUser(SCIMUser):
self._full_name_new_value: str | None = None
self._role_new_value: int | None = None
self._password_set_to: str | None = None
+ self._custom_profile_field_data: dict[str, str] | None = None
def is_new_user(self) -> bool:
return not bool(self.obj.id)
@@ -118,7 +125,7 @@ class ZulipSCIMUser(SCIMUser):
"familyName": last_name,
}
- return {
+ d = {
"schemas": [scim_constants.SchemaURI.USER],
"id": str(self.obj.id),
"userName": self.obj.delivery_email,
@@ -134,6 +141,25 @@ class ZulipSCIMUser(SCIMUser):
"meta": self.meta,
}
+ custom_profile_field_map = self.config.get("custom_profile_field_map", {})
+ if custom_profile_field_map:
+ fields = custom_profile_fields_for_realm(self.obj.realm_id)
+ field_id_to_var_name = {}
+ for field in fields:
+ var_name = "_".join(field.name.lower().split(" "))
+ if var_name in custom_profile_field_map:
+ field_id_to_var_name[field.id] = var_name
+
+ values = CustomProfileFieldValue.objects.filter(
+ user_profile=self.obj, field_id__in=field_id_to_var_name.keys()
+ )
+ for field_value in values:
+ var_name = field_id_to_var_name[field_value.field_id]
+ scim_attr = custom_profile_field_map[var_name]
+ d[scim_attr] = field_value.value
+
+ return d
+
def from_dict(self, d: dict[str, Any]) -> None:
"""Consume a dictionary conforming to the SCIM User Schema. The
dictionary was originally submitted as JSON by the client in
@@ -192,6 +218,17 @@ class ZulipSCIMUser(SCIMUser):
assert isinstance(role_name, str)
self.change_role(role_name)
+ custom_profile_field_map = self.config.get("custom_profile_field_map", {})
+ if custom_profile_field_map:
+ custom_field_data: dict[str, str] = {}
+ for var_name, scim_attr in custom_profile_field_map.items():
+ value = d.get(scim_attr)
+ if value is not None:
+ assert isinstance(value, str)
+ custom_field_data[var_name] = value
+ if custom_field_data:
+ self._custom_profile_field_data = custom_field_data
+
def change_delivery_email(self, new_value: str) -> None:
# Note that the email_allowed_for_realm check that usually
# appears adjacent to validate_email is present in save().
@@ -255,7 +292,17 @@ class ZulipSCIMUser(SCIMUser):
assert isinstance(val, str)
self.change_role(val)
else:
- raise scim_exceptions.NotImplementedError("Not Implemented")
+ custom_profile_field_map = self.config.get("custom_profile_field_map", {})
+ scim_attr_to_var_name = {v: k for k, v in custom_profile_field_map.items()}
+ attr_name = attr_path.first_path[0]
+ if attr_name in scim_attr_to_var_name:
+ assert isinstance(val, str)
+ var_name = scim_attr_to_var_name[attr_name]
+ if self._custom_profile_field_data is None:
+ self._custom_profile_field_data = {}
+ self._custom_profile_field_data[var_name] = val
+ else:
+ raise scim_exceptions.NotImplementedError("Not Implemented")
self.save()
@@ -273,6 +320,7 @@ class ZulipSCIMUser(SCIMUser):
full_name_new_value = getattr(self, "_full_name_new_value", None)
role_new_value = getattr(self, "_role_new_value", None)
password = getattr(self, "_password_set_to", None)
+ custom_profile_field_data = getattr(self, "_custom_profile_field_data", None)
# Clean up the internal "pending change" state, now that we've
# fetched the values:
@@ -281,6 +329,7 @@ class ZulipSCIMUser(SCIMUser):
self._full_name_new_value = None
self._password_set_to = None
self._role_new_value = None
+ self._custom_profile_field_data = None
if email_new_value is not None:
try:
@@ -306,6 +355,18 @@ class ZulipSCIMUser(SCIMUser):
except ValidationError as e:
raise ConflictError("Email address already in use: " + str(e))
+ # Validate custom profile field data early, before any
+ # mutations, so that errors are caught before creating or
+ # partially updating users.
+ custom_profile_data = None
+ if custom_profile_field_data:
+ try:
+ custom_profile_data = validate_custom_profile_field_data(
+ realm.id, custom_profile_field_data
+ )
+ except SyncUserError as e:
+ raise scim_exceptions.BadRequestError(str(e))
+
if self.is_new_user():
assert email_new_value is not None
assert full_name_new_value is not None
@@ -326,6 +387,10 @@ class ZulipSCIMUser(SCIMUser):
add_initial_stream_subscriptions=add_initial_stream_subscriptions,
acting_user=None,
)
+ if custom_profile_data:
+ do_update_user_custom_profile_data_if_changed(
+ self.obj, custom_profile_data, None, notify=True
+ )
return
# TODO: The below operations should ideally be executed in a single
@@ -348,6 +413,11 @@ class ZulipSCIMUser(SCIMUser):
elif is_active_new_value is not None and not is_active_new_value:
do_deactivate_user(self.obj, acting_user=None)
+ if custom_profile_data:
+ do_update_user_custom_profile_data_if_changed(
+ self.obj, custom_profile_data, None, notify=True
+ )
+
def delete(self) -> None:
"""
This is consistent with Okta SCIM - users don't get DELETEd, they're deactivated
diff --git a/zerver/tests/test_scim.py b/zerver/tests/test_scim.py
index 97c25001a58..b2d52367d84 100644
--- a/zerver/tests/test_scim.py
+++ b/zerver/tests/test_scim.py
@@ -13,6 +13,7 @@ from zerver.lib.stream_subscription import get_subscribed_stream_ids_for_user
from zerver.lib.test_classes import ZulipTestCase
from zerver.lib.user_groups import get_user_group_direct_member_ids
from zerver.models import UserProfile
+from zerver.models.custom_profile_fields import CustomProfileField, CustomProfileFieldValue
from zerver.models.groups import NamedUserGroup
from zerver.models.realms import get_realm
@@ -33,8 +34,12 @@ class SCIMTestCase(ZulipTestCase):
def scim_headers(self) -> SCIMHeadersDict:
return {"HTTP_AUTHORIZATION": f"Bearer {settings.SCIM_CONFIG['zulip']['bearer_token']}"}
- def generate_user_schema(self, user_profile: UserProfile) -> dict[str, Any]:
- return {
+ def generate_user_schema(
+ self,
+ user_profile: UserProfile,
+ expected_custom_profile_fields: dict[str, str] | None = None,
+ ) -> dict[str, Any]:
+ d: dict[str, Any] = {
"schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
"id": str(user_profile.id),
"userName": user_profile.delivery_email,
@@ -49,6 +54,9 @@ class SCIMTestCase(ZulipTestCase):
"location": f"http://zulip.testserver/scim/v2/Users/{user_profile.id}",
},
}
+ if expected_custom_profile_fields is not None:
+ d.update(expected_custom_profile_fields)
+ return d
def assert_uniqueness_error(self, result: "TestHttpResponse", extra_message: str) -> None:
self.assertEqual(result.status_code, 409)
@@ -69,6 +77,13 @@ class SCIMTestCase(ZulipTestCase):
with self.settings(SCIM_CONFIG=config_dict):
yield
+ @contextmanager
+ def mock_custom_profile_field_map(self, field_map: dict[str, str]) -> Iterator[None]:
+ config_dict = copy.deepcopy(settings.SCIM_CONFIG)
+ config_dict["zulip"]["custom_profile_field_map"] = field_map
+ with self.settings(SCIM_CONFIG=config_dict):
+ yield
+
class TestNonSCIMAPIAccess(SCIMTestCase):
def test_scim_client_cant_access_different_apis(self) -> None:
@@ -825,6 +840,268 @@ class TestSCIMUser(SCIMTestCase):
)
self.assertEqual(result.status_code, 200)
+ def test_post_with_custom_profile_fields(self) -> None:
+ field_map = {"phone_number": "phoneNumber", "birthday": "birthday"}
+ payload = {
+ "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
+ "userName": "[email protected]",
+ "name": {"formatted": "New User"},
+ "active": True,
+ "phoneNumber": "123456789",
+ "birthday": "2000-01-01",
+ }
+
+ with self.mock_custom_profile_field_map(field_map):
+ result = self.client_post(
+ "/scim/v2/Users", payload, content_type="application/json", **self.scim_headers()
+ )
+ self.assertEqual(result.status_code, 201)
+ output_data = orjson.loads(result.content)
+
+ new_user = UserProfile.objects.get(delivery_email="[email protected]")
+
+ phone_field = CustomProfileField.objects.get(realm=new_user.realm, name="Phone number")
+ phone_value = CustomProfileFieldValue.objects.get(user_profile=new_user, field=phone_field)
+ self.assertEqual(phone_value.value, "123456789")
+
+ birthday_field = CustomProfileField.objects.get(realm=new_user.realm, name="Birthday")
+ birthday_value = CustomProfileFieldValue.objects.get(
+ user_profile=new_user, field=birthday_field
+ )
+ self.assertEqual(birthday_value.value, "2000-01-01")
+
+ expected_response_schema = self.generate_user_schema(
+ new_user,
+ expected_custom_profile_fields={"phoneNumber": "123456789", "birthday": "2000-01-01"},
+ )
+ self.assertEqual(output_data, expected_response_schema)
+
+ def test_put_with_custom_profile_fields(self) -> None:
+ hamlet = self.example_user("hamlet")
+ field_map = {"phone_number": "phoneNumber"}
+ 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": "987654321",
+ }
+
+ with self.mock_custom_profile_field_map(field_map):
+ result = self.json_put(f"/scim/v2/Users/{hamlet.id}", payload, **self.scim_headers())
+ self.assertEqual(result.status_code, 200)
+
+ output_data = orjson.loads(result.content)
+ expected_response_schema = self.generate_user_schema(
+ hamlet, expected_custom_profile_fields={"phoneNumber": "987654321"}
+ )
+ self.assertEqual(output_data, expected_response_schema)
+
+ 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, "987654321")
+
+ def test_patch_custom_profile_fields(self) -> None:
+ hamlet = self.example_user("hamlet")
+ field_map = {"phone_number": "phoneNumber"}
+
+ # First, test PATCH with a path specified.
+ payload = {
+ "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"],
+ "Operations": [
+ {"op": "replace", "path": "phoneNumber", "value": "111222333"},
+ ],
+ }
+
+ with self.mock_custom_profile_field_map(field_map):
+ result = self.json_patch(f"/scim/v2/Users/{hamlet.id}", payload, **self.scim_headers())
+ self.assertEqual(result.status_code, 200)
+
+ output_data = orjson.loads(result.content)
+ expected_response_schema = self.generate_user_schema(
+ hamlet, expected_custom_profile_fields={"phoneNumber": "111222333"}
+ )
+ self.assertEqual(output_data, expected_response_schema)
+
+ 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, "111222333")
+
+ # Now test the other PATCH form, without path, specifying
+ # the attribute to modify in the value dict.
+ payload = {
+ "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"],
+ "Operations": [
+ {"op": "replace", "value": {"phoneNumber": "444555666"}},
+ ],
+ }
+
+ with self.mock_custom_profile_field_map(field_map):
+ result = self.json_patch(f"/scim/v2/Users/{hamlet.id}", payload, **self.scim_headers())
+ self.assertEqual(result.status_code, 200)
+
+ output_data = orjson.loads(result.content)
+ expected_response_schema = self.generate_user_schema(
+ hamlet, expected_custom_profile_fields={"phoneNumber": "444555666"}
+ )
+ self.assertEqual(output_data, expected_response_schema)
+
+ phone_value.refresh_from_db()
+ self.assertEqual(phone_value.value, "444555666")
+
+ def test_get_with_custom_profile_fields(self) -> None:
+ hamlet = self.example_user("hamlet")
+ field_map = {"phone_number": "phoneNumber"}
+
+ phone_field = CustomProfileField.objects.get(realm=hamlet.realm, name="Phone number")
+ CustomProfileFieldValue.objects.update_or_create(
+ user_profile=hamlet,
+ field=phone_field,
+ defaults={"value": "gettest123"},
+ )
+
+ with self.mock_custom_profile_field_map(field_map):
+ result = self.client_get(f"/scim/v2/Users/{hamlet.id}", {}, **self.scim_headers())
+ self.assertEqual(result.status_code, 200)
+ output_data = orjson.loads(result.content)
+
+ # The response should include the standard schema plus the custom field.
+ expected_response_schema = self.generate_user_schema(
+ hamlet, expected_custom_profile_fields={"phoneNumber": "gettest123"}
+ )
+ self.assertEqual(output_data, expected_response_schema)
+
+ def test_custom_profile_field_invalid_data(self) -> None:
+ field_map = {"birthday": "birthday"}
+
+ # Test with an existing user (PUT): an invalid date string for a date field.
+ hamlet = self.example_user("hamlet")
+ 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,
+ "birthday": "not-a-date",
+ }
+
+ with self.mock_custom_profile_field_map(field_map):
+ result = self.json_put(f"/scim/v2/Users/{hamlet.id}", payload, **self.scim_headers())
+ self.assertEqual(
+ orjson.loads(result.content),
+ {
+ "schemas": ["urn:ietf:params:scim:api:messages:2.0:Error"],
+ "detail": "Invalid data for birthday field: Birthday is not a date",
+ "status": 400,
+ },
+ )
+
+ # Test the new user creation codepath (POST) with same invalid data.
+ # The request should fail validation and thus no user will be created.
+ original_user_count = UserProfile.objects.count()
+ payload = {
+ "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
+ "userName": "[email protected]",
+ "name": {"formatted": "New User"},
+ "active": True,
+ "birthday": "not-a-date",
+ }
+
+ with self.mock_custom_profile_field_map(field_map):
+ result = self.client_post(
+ "/scim/v2/Users", payload, content_type="application/json", **self.scim_headers()
+ )
+ self.assertEqual(
+ orjson.loads(result.content),
+ {
+ "schemas": ["urn:ietf:params:scim:api:messages:2.0:Error"],
+ "detail": "Invalid data for birthday field: Birthday is not a date",
+ "status": 400,
+ },
+ )
+ self.assertEqual(UserProfile.objects.count(), original_user_count)
+
+ 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"}
+
+ hamlet = self.example_user("hamlet")
+ 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,
+ "someAttr": "somevalue",
+ }
+
+ with self.mock_custom_profile_field_map(field_map):
+ result = self.json_put(f"/scim/v2/Users/{hamlet.id}", payload, **self.scim_headers())
+ self.assertEqual(
+ orjson.loads(result.content),
+ {
+ "schemas": ["urn:ietf:params:scim:api:messages:2.0:Error"],
+ "detail": "Custom profile field with name nonexistent_field not found.",
+ "status": 400,
+ },
+ )
+
+ # Test with a new user (POST). Early validation should reject
+ # the request before creating the user.
+ original_user_count = UserProfile.objects.count()
+ payload = {
+ "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
+ "userName": "[email protected]",
+ "name": {"formatted": "New User"},
+ "active": True,
+ "someAttr": "somevalue",
+ }
+
+ with self.mock_custom_profile_field_map(field_map):
+ result = self.client_post(
+ "/scim/v2/Users", payload, content_type="application/json", **self.scim_headers()
+ )
+ self.assertEqual(
+ orjson.loads(result.content),
+ {
+ "schemas": ["urn:ietf:params:scim:api:messages:2.0:Error"],
+ "detail": "Custom profile field with name nonexistent_field not found.",
+ "status": 400,
+ },
+ )
+ self.assertEqual(UserProfile.objects.count(), original_user_count)
+
+ def test_no_custom_profile_field_map_ignores_extra_attrs(self) -> None:
+ """
+ When custom_profile_field_map is not configured, extra attributes
+ in the SCIM payload are silently ignored.
+ """
+ payload = {
+ "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],
+ "userName": "[email protected]",
+ "name": {"formatted": "New User"},
+ "active": True,
+ "phoneNumber": "123456789",
+ }
+
+ result = self.client_post(
+ "/scim/v2/Users", payload, content_type="application/json", **self.scim_headers()
+ )
+ self.assertEqual(result.status_code, 201)
+ output_data = orjson.loads(result.content)
+
+ new_user = UserProfile.objects.get(delivery_email="[email protected]")
+ phone_field = CustomProfileField.objects.get(realm=new_user.realm, name="Phone number")
+ self.assertFalse(
+ CustomProfileFieldValue.objects.filter(
+ user_profile=new_user, field=phone_field
+ ).exists()
+ )
+
+ expected_response_schema = self.generate_user_schema(new_user)
+ self.assertEqual(output_data, expected_response_schema)
+
class TestSCIMGroup(SCIMTestCase):
"""
diff --git a/zproject/backends.py b/zproject/backends.py
index 96753ff4b16..9dd0c6cdeca 100644
--- a/zproject/backends.py
+++ b/zproject/backends.py
@@ -1747,11 +1747,14 @@ class SyncUserError(Exception):
pass
-def sync_user_profile_custom_fields(
- user_profile: UserProfile, custom_field_name_to_value: dict[str, Any]
-) -> None:
+def validate_custom_profile_field_data(
+ realm_id: int, custom_field_name_to_value: dict[str, Any]
+) -> list[ProfileDataElementUpdateDict]:
+ """Validate custom profile field var names and values, returning the
+ validated profile data list. Raises SyncUserError if a var name
+ doesn't match any field or a value fails validation."""
fields_by_var_name: dict[str, CustomProfileField] = {}
- custom_profile_fields = custom_profile_fields_for_realm(user_profile.realm.id)
+ custom_profile_fields = custom_profile_fields_for_realm(realm_id)
for field in custom_profile_fields:
var_name = "_".join(field.name.lower().split(" "))
fields_by_var_name[var_name] = field
@@ -1763,7 +1766,7 @@ def sync_user_profile_custom_fields(
except KeyError:
raise SyncUserError(f"Custom profile field with name {var_name} not found.")
try:
- validate_user_custom_profile_field(user_profile.realm.id, field, value)
+ validate_user_custom_profile_field(realm_id, field, value)
except ValidationError as error:
raise SyncUserError(f"Invalid data for {var_name} field: {error.message}")
profile_data.append(
@@ -1772,6 +1775,15 @@ def sync_user_profile_custom_fields(
"value": value,
}
)
+ return profile_data
+
+
+def sync_user_profile_custom_fields(
+ user_profile: UserProfile, custom_field_name_to_value: dict[str, Any]
+) -> None:
+ profile_data = validate_custom_profile_field_data(
+ user_profile.realm_id, custom_field_name_to_value
+ )
do_update_user_custom_profile_data_if_changed(user_profile, profile_data, None, notify=True)
diff --git a/zproject/settings_types.py b/zproject/settings_types.py
index 5430268be48..07747d861fd 100644
--- a/zproject/settings_types.py
+++ b/zproject/settings_types.py
@@ -43,3 +43,4 @@ class SCIMConfigDict(TypedDict, total=False):
scim_client_name: str
name_formatted_included: bool
create_guests_without_streams: bool
+ custom_profile_field_map: dict[str, str]