Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

fix(scim): parse membership id from filtered PATCH path when value omitted (#34181)

Yassin Kortam8d217a4d5f9f
diff --git a/litellm/proxy/management_endpoints/scim/scim_v2.py b/litellm/proxy/management_endpoints/scim/scim_v2.py
index 525ce9f0e89..90eae5bbb21 100644
--- a/litellm/proxy/management_endpoints/scim/scim_v2.py
+++ b/litellm/proxy/management_endpoints/scim/scim_v2.py
@@ -1353,6 +1353,31 @@ def _extract_group_values(value: Any) -> List[str]:
return group_values
+def _extract_ids_from_path_filter(path: str | None, attribute: str) -> List[str]:
+ """Return ids from a SCIM filtered path like ``members[value eq "id"]``.
+
+ Okta commonly sends membership removals as a filtered path and omits the
+ request body ``value``, so the id lives only inside the ``[value eq "..."]``
+ filter. The ``eq`` operator is matched case-insensitively per the SCIM
+ spec; the id keeps its original case. Per the SCIM filter grammar the
+ compared value must be quoted (single or double), so malformed unquoted
+ filters yield no id. A quoted id may contain escaped quotes and
+ backslashes (``\\"`` and ``\\\\``), which are unescaped before use.
+ ``path`` must be the raw, case-preserving path from the patch op.
+ """
+ if not path:
+ return []
+ match = re.match(
+ rf"""\s*{re.escape(attribute)}\s*\[\s*value\s+eq\s+(['"])((?:\\.|[^\\])*?)\1\s*\]\s*$""",
+ path,
+ flags=re.IGNORECASE,
+ )
+ if not match:
+ return []
+ extracted = re.sub(r"\\(.)", r"\1", match.group(2))
+ return [extracted] if extracted else []
+
+
def _handle_displayname_update(op_type: str, value: Any, update_data: Dict[str, Any]) -> None:
"""Handle displayname updates."""
if op_type == "remove":
@@ -1396,9 +1421,11 @@ def _handle_name_update(path: str, op_type: str, value: Any, scim_metadata: Dict
scim_metadata["familyName"] = str(value)
-def _handle_group_operations(op_type: str, value: Any, teams_set: Set[str]) -> Optional[Set[str]]:
+def _handle_group_operations(op_type: str, value: Any, teams_set: Set[str], path: str | None) -> Set[str] | None:
"""Handle group/team membership operations."""
group_values = _extract_group_values(value)
+ if not group_values and value is None:
+ group_values = _extract_ids_from_path_filter(path, "groups")
if op_type == "replace":
return set(group_values)
elif op_type == "add":
@@ -1511,7 +1538,7 @@ def _apply_patch_ops(
elif _multi_valued_attribute_base(path) in SCIM_MULTI_VALUED_ATTRIBUTE_METADATA_KEYS:
_handle_multi_valued_attribute_update(path, op_type, value, metadata)
elif path.startswith("groups"):
- new_replace_set = _handle_group_operations(op_type, value, teams_set)
+ new_replace_set = _handle_group_operations(op_type, value, teams_set, op.path)
if new_replace_set is not None:
replace_team_set = new_replace_set
else:
@@ -1975,6 +2002,8 @@ async def _process_group_patch_operations(
elif path.startswith("members"):
# Handle member operations
member_values = _extract_group_values(value)
+ if not member_values and value is None:
+ member_values = _extract_ids_from_path_filter(op.path, "members")
# Check the feature flag
scim_upsert_user = await _get_scim_upsert_user_setting()
# Validate all users exist or create them based on feature flag
diff --git a/tests/test_litellm/proxy/management_endpoints/scim/test_scim_patch_user.py b/tests/test_litellm/proxy/management_endpoints/scim/test_scim_patch_user.py
index f8995a6f4da..c3af4208d37 100644
--- a/tests/test_litellm/proxy/management_endpoints/scim/test_scim_patch_user.py
+++ b/tests/test_litellm/proxy/management_endpoints/scim/test_scim_patch_user.py
@@ -465,3 +465,58 @@ def test_apply_patch_ops_filtered_path_raises_400_instead_of_junk_metadata():
)
assert exc_info.value.status_code == 400
+
+
+def test_apply_patch_ops_remove_group_filtered_path_without_value():
+ """Okta removes a user from a team with groups[value eq "..."] and no body
+ value; the team id must be parsed from the filter so the remove takes effect"""
+ user = LiteLLM_UserTable(
+ user_id="user-fp",
+ user_email="[email protected]",
+ teams=["team-1", "team-2"],
+ metadata={},
+ )
+ patch_ops = SCIMPatchOp(
+ Operations=[SCIMPatchOperation(op="remove", path='groups[value eq "team-1"]')]
+ )
+
+ _, final_team_set = _apply_patch_ops(existing_user=user, patch_ops=patch_ops)
+
+ assert final_team_set == {"team-2"}
+
+
+def test_apply_patch_ops_add_group_filtered_path_without_value():
+ """A filtered add path with no body value adds the team id from the filter."""
+ user = LiteLLM_UserTable(
+ user_id="user-fp",
+ user_email="[email protected]",
+ teams=["team-1"],
+ metadata={},
+ )
+ patch_ops = SCIMPatchOp(
+ Operations=[SCIMPatchOperation(op="add", path="groups[value eq 'team-3']")]
+ )
+
+ _, final_team_set = _apply_patch_ops(existing_user=user, patch_ops=patch_ops)
+
+ assert final_team_set == {"team-1", "team-3"}
+
+
+def test_apply_patch_ops_replace_groups_empty_value_does_not_use_path_filter():
+ """A filtered replace with an explicit empty value must not resurrect the
+ filter id; the team set is replaced with the empty value as given."""
+ user = LiteLLM_UserTable(
+ user_id="user-fp",
+ user_email="[email protected]",
+ teams=["team-1", "team-2"],
+ metadata={},
+ )
+ patch_ops = SCIMPatchOp(
+ Operations=[
+ SCIMPatchOperation(op="replace", path='groups[value eq "team-1"]', value=[])
+ ]
+ )
+
+ _, final_team_set = _apply_patch_ops(existing_user=user, patch_ops=patch_ops)
+
+ assert final_team_set == set()
diff --git a/tests/test_litellm/proxy/management_endpoints/scim/test_scim_v2_endpoints.py b/tests/test_litellm/proxy/management_endpoints/scim/test_scim_v2_endpoints.py
index 850b8fc7cfd..7bb74285ac6 100644
--- a/tests/test_litellm/proxy/management_endpoints/scim/test_scim_v2_endpoints.py
+++ b/tests/test_litellm/proxy/management_endpoints/scim/test_scim_v2_endpoints.py
@@ -1,3 +1,4 @@
+import time
from unittest.mock import AsyncMock
import pytest
@@ -17,6 +18,7 @@ from litellm.proxy.management_endpoints.scim.scim_v2 import (
UserProvisionerHelpers,
_apply_group_patch_updates,
_extract_group_member_ids,
+ _extract_ids_from_path_filter,
_handle_team_membership_changes,
_process_group_patch_operations,
_recompute_scim_member_roles,
@@ -3377,3 +3379,143 @@ async def test_patch_group_replace_stays_absolute_against_concurrent_roster(mock
call.kwargs["user_id"] for call in calls if call.kwargs.get("teams_ids_to_add_user_to") == [group_id]
}
assert added_user_ids == set()
+
+
+ "path, attribute, expected",
+ [
+ ('members[value eq "user-1"]', "members", ["user-1"]),
+ ("members[value eq 'user-1']", "members", ["user-1"]),
+ ('members[value EQ "user-1"]', "members", ["user-1"]),
+ ('members[ value eq "user-1" ]', "members", ["user-1"]),
+ ('groups[value eq "team-1"]', "groups", ["team-1"]),
+ ('members[value eq "Mixed-CASE-Id"]', "members", ["Mixed-CASE-Id"]),
+ ('members[value eq "a\\"b"]', "members", ['a"b']),
+ ('members[value eq "a\\\\b"]', "members", ["a\\b"]),
+ ("members[value eq 'a\\'b']", "members", ["a'b"]),
+ ("members", "members", []),
+ ('groups[value eq "team-1"]', "members", []),
+ (None, "members", []),
+ ('members[value eq ""]', "members", []),
+ ("members[value eq user-1]", "members", []),
+ ("members[value eq unintendeduser]", "members", []),
+ ],
+)
+def test_extract_ids_from_path_filter(path, attribute, expected):
+ assert _extract_ids_from_path_filter(path, attribute) == expected
+
+
+def test_extract_ids_from_path_filter_unterminated_is_linear():
+ """A pathological unterminated quoted filter must not trigger super-linear
+ backtracking; it returns no id and completes near-instantly."""
+ pathological = 'members[value eq "' + ("\\" * 200)
+
+ start = time.perf_counter()
+ result = _extract_ids_from_path_filter(pathological, "members")
+ elapsed = time.perf_counter() - start
+
+ assert result == []
+ assert elapsed < 1.0
+
+
+async def test_process_group_patch_remove_filtered_path_without_value(mocker):
+ """Okta sends group membership removals as a filtered path with no request
+ body value; the member id must be parsed out of members[value eq "..."]"""
+ patch_ops = SCIMPatchOp(
+ schemas=["urn:ietf:params:scim:api:messages:2.0:PatchOp"],
+ Operations=[SCIMPatchOperation(op="remove", path='members[value eq "user-1"]')],
+ )
+
+ existing_team = LiteLLM_TeamTable(
+ team_id="team-1",
+ team_alias="Team One",
+ members=[],
+ members_with_roles=[
+ Member(user_id="user-1", role="user"),
+ Member(user_id="user-2", role="user"),
+ ],
+ )
+
+ prisma_client = mocker.MagicMock()
+ prisma_client.db = mocker.MagicMock()
+ prisma_client.db.litellm_usertable = mocker.MagicMock()
+ prisma_client.db.litellm_usertable.find_unique = AsyncMock(
+ return_value=LiteLLM_UserTable(user_id="user-1")
+ )
+
+ _, final_members, _ = await _process_group_patch_operations(
+ patch_ops=patch_ops,
+ existing_team=existing_team,
+ prisma_client=prisma_client,
+ )
+
+ assert final_members == {"user-2"}
+
+
+async def test_process_group_patch_add_filtered_path_without_value(mocker):
+ """A filtered add path with no body value adds the id parsed from the filter."""
+ patch_ops = SCIMPatchOp(
+ schemas=["urn:ietf:params:scim:api:messages:2.0:PatchOp"],
+ Operations=[SCIMPatchOperation(op="add", path='members[value eq "user-3"]')],
+ )
+
+ existing_team = LiteLLM_TeamTable(
+ team_id="team-1",
+ team_alias="Team One",
+ members=[],
+ members_with_roles=[Member(user_id="user-1", role="user")],
+ )
+
+ prisma_client = mocker.MagicMock()
+ prisma_client.db = mocker.MagicMock()
+ prisma_client.db.litellm_usertable = mocker.MagicMock()
+ prisma_client.db.litellm_usertable.find_unique = AsyncMock(
+ return_value=LiteLLM_UserTable(user_id="user-3")
+ )
+
+ _, final_members, _ = await _process_group_patch_operations(
+ patch_ops=patch_ops,
+ existing_team=existing_team,
+ prisma_client=prisma_client,
+ )
+
+ assert final_members == {"user-1", "user-3"}
+
+
+async def test_process_group_patch_replace_empty_value_does_not_use_path_filter(mocker):
+ """An explicit empty replace value must clear membership rather than pull an
+ id from the filtered path, which would retain one member and drop the rest."""
+ patch_ops = SCIMPatchOp(
+ schemas=["urn:ietf:params:scim:api:messages:2.0:PatchOp"],
+ Operations=[
+ SCIMPatchOperation(op="replace", path='members[value eq "user-1"]', value=[])
+ ],
+ )
+
+ existing_team = LiteLLM_TeamTable(
+ team_id="team-1",
+ team_alias="Team One",
+ members=[],
+ members_with_roles=[
+ Member(user_id="user-1", role="user"),
+ Member(user_id="user-2", role="user"),
+ ],
+ )
+
+ prisma_client = mocker.MagicMock()
+ prisma_client.db = mocker.MagicMock()
+ prisma_client.db.litellm_usertable = mocker.MagicMock()
+ prisma_client.db.litellm_usertable.find_unique = AsyncMock(
+ return_value=LiteLLM_UserTable(user_id="user-1")
+ )
+
+ _, final_members, _ = await _process_group_patch_operations(
+ patch_ops=patch_ops,
+ existing_team=existing_team,
+ prisma_client=prisma_client,
+ )
+
+ assert final_members == set()