Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

refactor(scim): reduce SCIM user PATCH handler complexity (#90840)

posthog[bot]2f7ebfeb94b7
diff --git a/ee/api/scim/test/test_users_api.py b/ee/api/scim/test/test_users_api.py
index f8342ca14747..a806fc43e7e8 100644
--- a/ee/api/scim/test/test_users_api.py
+++ b/ee/api/scim/test/test_users_api.py
@@ -323,7 +323,15 @@ class TestSCIMUsersAPI(APILicensedTest):
assert "groups" in data
assert any(g.get("display") == "Engineers" for g in data["groups"])
- def test_deactivate_user(self):
+ @parameterized.expand(
+ [
+ ("replace_without_path", {"op": "replace", "value": {"active": False}}),
+ ("replace_with_path", {"op": "replace", "path": "active", "value": False}),
+ ("add_with_path", {"op": "add", "path": "active", "value": False}),
+ ("remove_with_path", {"op": "remove", "path": "active", "value": False}),
+ ]
+ )
+ def test_deactivate_user(self, _name: str, operation: dict):
user = User.objects.create_user(
email="[email protected]", password=None, first_name="Test", is_email_verified=True
)
@@ -341,7 +349,7 @@ class TestSCIMUsersAPI(APILicensedTest):
patch_data = {
"schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"],
- "Operations": [{"op": "replace", "value": {"active": False}}],
+ "Operations": [operation],
}
response = self.client.patch(
@@ -830,6 +838,67 @@ class TestSCIMUsersAPI(APILicensedTest):
user.refresh_from_db()
assert user.email == "[email protected]"
+ @parameterized.expand([("replace",), ("add",)])
+ def test_patch_user_name_updates_scim_record(self, op: str):
+ user = User.objects.create_user(
+ email="[email protected]", password=None, first_name="Test", is_email_verified=True
+ )
+ OrganizationMembership.objects.create(
+ user=user, organization=self.organization, level=OrganizationMembership.Level.MEMBER
+ )
+ SCIMProvisionedUser.objects.create(
+ user=user,
+ identity_provider_config=self.config,
+ username="[email protected]",
+ identity_provider=SCIMProvisionedUser.IdentityProvider.OKTA,
+ active=True,
+ )
+
+ patch_data = {
+ "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"],
+ "Operations": [{"op": op, "path": "userName", "value": "[email protected]"}],
+ }
+
+ response = self.client.patch(
+ f"/scim/v2/{self.config.scim_slug}/Users/{user.id}", data=patch_data, content_type="application/scim+json"
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["userName"] == "[email protected]"
+ scim_user = SCIMProvisionedUser.objects.get(user=user, identity_provider_config=self.config)
+ assert scim_user.username == "[email protected]"
+ # The upsert must not reset which provider owns the record
+ assert scim_user.identity_provider == SCIMProvisionedUser.IdentityProvider.OKTA
+
+ @parameterized.expand(
+ [
+ ("unmapped_attribute", "nickName", "Nick"),
+ ("unmapped_sub_attribute", "name.middleName", "Middle"),
+ ]
+ )
+ def test_patch_ignores_attributes_we_do_not_support(self, _name: str, path: str, value: str):
+ # Identity providers send attributes we do not store. Rejecting them fails the whole sync.
+ user = User.objects.create_user(
+ email="[email protected]", password=None, first_name="Test", last_name="User", is_email_verified=True
+ )
+ OrganizationMembership.objects.create(
+ user=user, organization=self.organization, level=OrganizationMembership.Level.MEMBER
+ )
+
+ patch_data = {
+ "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"],
+ "Operations": [{"op": "replace", "path": path, "value": value}],
+ }
+
+ response = self.client.patch(
+ f"/scim/v2/{self.config.scim_slug}/Users/{user.id}", data=patch_data, content_type="application/scim+json"
+ )
+
+ assert response.status_code == status.HTTP_200_OK
+ user.refresh_from_db()
+ assert user.first_name == "Test"
+ assert user.last_name == "User"
+
def test_patch_remove_user_family_name_with_simple_path(self):
user = User.objects.create_user(
diff --git a/ee/api/scim/user.py b/ee/api/scim/user.py
index 572e4daf78e6..773d2f0e61dc 100644
--- a/ee/api/scim/user.py
+++ b/ee/api/scim/user.py
@@ -293,142 +293,124 @@ class PostHogSCIMUser(SCIMUser):
SCIMProvisionedUser.objects.for_config(self._config).filter(user=self.obj).delete()
- def handle_replace(self, path: AttrPath, value: Union[str, list, dict], operation: dict) -> None:
+ def _activate(self) -> None:
+ """Give the user back their organization membership and mark the SCIM record active."""
+ OrganizationMembership.objects.get_or_create(
+ user=self.obj,
+ organization=self._config.organization,
+ defaults={"level": OrganizationMembership.Level.MEMBER},
+ )
+ SCIMProvisionedUser.objects.upsert(
+ user=self.obj,
+ config=self._config,
+ defaults={
+ "active": True,
+ "username": self.user_name,
+ "identity_provider": self.identity_provider,
+ },
+ )
+
+ def _set_username(self, username: str) -> None:
+ SCIMProvisionedUser.objects.upsert(
+ user=self.obj,
+ config=self._config,
+ defaults={
+ "username": username,
+ "active": True,
+ "identity_provider": self.identity_provider,
+ },
+ )
+
+ def _apply_name(self, sub_attr: Optional[str], value: Union[str, list, dict]) -> None:
+ if sub_attr == "givenName" and isinstance(value, str):
+ self.obj.first_name = value
+ elif sub_attr == "familyName" and isinstance(value, str):
+ self.obj.last_name = value
+ elif isinstance(value, dict):
+ if "givenName" in value:
+ self.obj.first_name = value["givenName"]
+ if "familyName" in value:
+ self.obj.last_name = value["familyName"]
+
+ def _clear_name(self, sub_attr: Optional[str]) -> None:
+ if sub_attr == "givenName":
+ self.obj.first_name = ""
+ elif sub_attr == "familyName":
+ self.obj.last_name = ""
+ elif not sub_attr:
+ self.obj.first_name = ""
+ self.obj.last_name = ""
+
+ @classmethod
+ def _email_from_operation(cls, path: AttrPath, value: Union[str, list, dict]) -> Optional[str]:
+ """Read the target email out of a PATCH value, which is a bare string for a filtered path."""
+ if path.is_complex and isinstance(value, str):
+ return value
+ if isinstance(value, list):
+ return cls._extract_email_from_value(value)
+ return None
+
+ def _apply_email(self, email: str) -> None:
+ if User.objects.filter(email__iexact=email).exclude(id=self.obj.id).exists():
+ raise ValueError("Email belongs to another user")
+ _validate_email_domain_is_verified(email, self._config.organization)
+ # Org must also own the current email domain to prevent cross-tenant account takeover
+ _validate_email_domain_is_verified(self.obj.email, self._config.organization)
+ self.obj.email = email
+
+ def _write_attribute(self, path: AttrPath, value: Union[str, list, dict]) -> bool:
"""
- Handle SCIM PATCH replace operations (called by django-scim2 handle_operations).
+ Write one SCIM attribute. Returns True when the User row still needs a save.
- Each attribute update comes as a separate call with its specific path and value.
- Supports complex paths like 'emails[type eq "work"].value' via scim2-filter-parser.
+ Unknown attributes are ignored, because the SCIM spec lets a provider support a subset.
"""
first_path = path.first_path
attr_name = first_path.attr_name
- sub_attr = first_path.sub_attr
- with transaction.atomic():
- if attr_name == "active":
- if not value:
- self.deactivate()
- return
- else:
- OrganizationMembership.objects.get_or_create(
- user=self.obj,
- organization=self._config.organization,
- defaults={"level": OrganizationMembership.Level.MEMBER},
- )
-
- SCIMProvisionedUser.objects.upsert(
- user=self.obj,
- config=self._config,
- defaults={
- "active": True,
- "username": self.user_name,
- "identity_provider": self.identity_provider,
- },
- )
+ if attr_name == "active":
+ if value:
+ self._activate()
+ else:
+ self.deactivate()
+ return False
- elif attr_name == "name":
- if sub_attr == "givenName" and isinstance(value, str):
- self.obj.first_name = value
- elif sub_attr == "familyName" and isinstance(value, str):
- self.obj.last_name = value
- elif isinstance(value, dict):
- if "givenName" in value:
- self.obj.first_name = value["givenName"]
- if "familyName" in value:
- self.obj.last_name = value["familyName"]
+ if attr_name == "name":
+ self._apply_name(first_path.sub_attr, value)
+ return True
- elif attr_name == "emails":
- email = None
- if path.is_complex and isinstance(value, str):
- email = value
- elif isinstance(value, list):
- email = self._extract_email_from_value(value)
-
- if email:
- if User.objects.filter(email__iexact=email).exclude(id=self.obj.id).exists():
- raise ValueError("Email belongs to another user")
- _validate_email_domain_is_verified(email, self._config.organization)
- # Org must also own the current email domain to prevent cross-tenant account takeover
- _validate_email_domain_is_verified(self.obj.email, self._config.organization)
- self.obj.email = email
-
- elif attr_name == "userName" and isinstance(value, str):
- SCIMProvisionedUser.objects.upsert(
- user=self.obj,
- config=self._config,
- defaults={
- "username": value,
- "active": True,
- "identity_provider": self.identity_provider,
- },
- )
+ if attr_name == "emails":
+ email = self._email_from_operation(path, value)
+ if not email:
+ return False
+ self._apply_email(email)
+ return True
- self.obj.save()
+ if attr_name == "userName" and isinstance(value, str):
+ self._set_username(value)
- def handle_add(self, path: AttrPath, value: Union[str, list, dict], operation: dict) -> None:
- """
- Handle SCIM PATCH add operations (called by django-scim2 handle_operations).
- """
- first_path = path.first_path
- attr_name = first_path.attr_name
- sub_attr = first_path.sub_attr
+ return False
+ def _handle_write(self, path: AttrPath, value: Union[str, list, dict]) -> None:
with transaction.atomic():
- if attr_name == "active" and value:
- OrganizationMembership.objects.get_or_create(
- user=self.obj,
- organization=self._config.organization,
- defaults={"level": OrganizationMembership.Level.MEMBER},
- )
+ if self._write_attribute(path, value):
+ self.obj.save()
- SCIMProvisionedUser.objects.upsert(
- user=self.obj,
- config=self._config,
- defaults={
- "active": True,
- "username": self.user_name,
- "identity_provider": self.identity_provider,
- },
- )
+ def handle_replace(self, path: AttrPath, value: Union[str, list, dict], operation: dict) -> None:
+ """
+ Handle SCIM PATCH replace operations (called by django-scim2 handle_operations).
- elif attr_name == "name":
- if sub_attr == "givenName" and isinstance(value, str):
- self.obj.first_name = value
- elif sub_attr == "familyName" and isinstance(value, str):
- self.obj.last_name = value
- elif isinstance(value, dict):
- if "givenName" in value:
- self.obj.first_name = value["givenName"]
- if "familyName" in value:
- self.obj.last_name = value["familyName"]
- self.obj.save()
+ Each attribute update comes as a separate call with its specific path and value.
+ Supports complex paths like 'emails[type eq "work"].value' via scim2-filter-parser.
+ """
+ self._handle_write(path, value)
- elif attr_name == "emails":
- email = None
- if path.is_complex and isinstance(value, str):
- email = value
- elif isinstance(value, list):
- email = self._extract_email_from_value(value)
-
- if email:
- if User.objects.filter(email__iexact=email).exclude(id=self.obj.id).exists():
- raise ValueError("Email belongs to another user")
- _validate_email_domain_is_verified(email, self._config.organization)
- # Org must also own the current email domain to prevent cross-tenant account takeover
- _validate_email_domain_is_verified(self.obj.email, self._config.organization)
- self.obj.email = email
- self.obj.save()
-
- elif attr_name == "userName" and isinstance(value, str):
- SCIMProvisionedUser.objects.upsert(
- user=self.obj,
- config=self._config,
- defaults={
- "username": value,
- "active": True,
- "identity_provider": self.identity_provider,
- },
- )
+ def handle_add(self, path: AttrPath, value: Union[str, list, dict], operation: dict) -> None:
+ """
+ Handle SCIM PATCH add operations (called by django-scim2 handle_operations).
+
+ A SCIM single-valued attribute has one slot, so an add on one behaves as a replace.
+ """
+ self._handle_write(path, value)
def handle_remove(self, path: AttrPath, value: Union[str, list, dict], operation: dict) -> None:
"""
@@ -436,21 +418,13 @@ class PostHogSCIMUser(SCIMUser):
"""
first_path = path.first_path
attr_name = first_path.attr_name
- sub_attr = first_path.sub_attr
with transaction.atomic():
if attr_name == "active":
self.deactivate()
- return
elif attr_name == "name":
- if sub_attr == "givenName":
- self.obj.first_name = ""
- elif sub_attr == "familyName":
- self.obj.last_name = ""
- elif not sub_attr:
- self.obj.first_name = ""
- self.obj.last_name = ""
+ self._clear_name(first_path.sub_attr)
self.obj.save()
elif attr_name == "emails":