diff --git a/litellm/proxy/management_endpoints/scim/scim_v2.py b/litellm/proxy/management_endpoints/scim/scim_v2.py index 66c2e54f5c6..d16873d8801 100644 --- a/litellm/proxy/management_endpoints/scim/scim_v2.py +++ b/litellm/proxy/management_endpoints/scim/scim_v2.py @@ -1181,6 +1181,41 @@ async def _handle_team_membership_changes( ) +async def _sync_requested_teams( + prisma_client: PrismaClient, + user_id: str, + record_teams: Sequence[str], + requested_teams: Sequence[str], +) -> tuple[str, ...]: + """Write the roster change and return the teams to persist, leaving out groups that have no team row. + + A group the IdP pushed before LiteLLM has a team for it must not hold back the rest of the + request, since that same request may be the one that deactivates the user. + """ + changed: Final = frozenset(record_teams) ^ frozenset(requested_teams) + rows: Final = await find_many_in( + _table(TeamRepository(prisma_client, use_writer=True)), + "team_id", + changed, + chunk_size=SCIM_GROUP_MEMBER_LOOKUP_BATCH_SIZE, + ) + teamless: Final = changed - frozenset(team.team_id for team in rows) + if teamless: + verbose_proxy_logger.warning( + "SCIM: ignoring groups with no LiteLLM team for user %s: %s", + sanitize_for_log(user_id), + sanitize_for_log(sorted(teamless)), + ) + + teams_to_keep: Final = tuple(team for team in requested_teams if team not in teamless) + await _handle_team_membership_changes( + user_id=user_id, + existing_teams=[team for team in record_teams if team not in teamless], + new_teams=list(teams_to_keep), + ) + return teams_to_keep + + SCIM_BLOCKED_METADATA_KEY: Final = "scim_blocked" @@ -1957,17 +1992,18 @@ async def update_user( if user_data["teams"] else existing_user.teams ) - await _handle_team_membership_changes( + synced_teams: Final = await _sync_requested_teams( + prisma_client=prisma_client, user_id=user_id, - existing_teams=existing_user.teams, - new_teams=target_teams, + record_teams=existing_user.teams, + requested_teams=target_teams, ) update_data: Final = { "user_email": user_data["user_email"], "user_alias": user_data["user_alias"], "sso_user_id": user_data["sso_user_id"], - "teams": target_teams, + "teams": list(synced_teams), "metadata": safe_dumps(metadata), } @@ -2607,12 +2643,9 @@ def _apply_patch_ops( record_teams: Final = tuple(existing_user.teams or []) group_ops: Final = tuple(op for op in patch_ops.Operations if _is_group_path(op.path)) - last_replace: Final = next((op for op in reversed(group_ops) if op.op == "replace"), None) final_teams: Final = _keep_record_team_order( record_teams, - _apply_group_operation(record_teams, last_replace) - if last_replace is not None - else reduce(_apply_group_operation, group_ops, record_teams), + reduce(_apply_group_operation, group_ops, record_teams), ) final_metadata: Final = ( { @@ -2785,19 +2818,19 @@ async def patch_user( patched_metadata: Final = update_data.get("metadata") new_active: Final = _scim_active_value(patched_metadata if isinstance(patched_metadata, Mapping) else None) - # Handle team membership changes - await _handle_team_membership_changes( + synced_teams: Final = await _sync_requested_teams( + prisma_client=prisma_client, user_id=user_id, - existing_teams=existing_user.teams or [], - new_teams=list(final_teams), + record_teams=existing_user.teams or [], + requested_teams=final_teams, ) - update_data["teams"] = list(final_teams) + update_data["teams"] = list(synced_teams) admin_group: Final = await _get_scim_admin_group() if admin_group is not None: update_data["user_role"] = _resolve_scim_user_role( - await _scim_groups_from_team_ids(prisma_client, list(final_teams)), + await _scim_groups_from_team_ids(prisma_client, list(synced_teams)), admin_group, _default_scim_user_role(), ) diff --git a/tests/integration/management/test_scim_user_lifecycle.py b/tests/integration/management/test_scim_user_lifecycle.py index 18cb66b3d8b..cbb94aeffe6 100644 --- a/tests/integration/management/test_scim_user_lifecycle.py +++ b/tests/integration/management/test_scim_user_lifecycle.py @@ -13,6 +13,7 @@ SCIM_HEADERS: Final = {"Content-Type": "application/scim+json"} SCIM_CORE_USER_SCHEMA: Final = "urn:ietf:params:scim:schemas:core:2.0:User" SCIM_ENTERPRISE_USER_SCHEMA: Final = "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User" SCIM_LIST_RESPONSE_SCHEMA: Final = "urn:ietf:params:scim:api:messages:2.0:ListResponse" +SCIM_PATCH_OP_SCHEMA: Final = "urn:ietf:params:scim:api:messages:2.0:PatchOp" class ScimResponseModel(BaseModel): @@ -463,6 +464,84 @@ def test_profile_put_without_groups_keeps_memberships_and_a_new_groups_list_move _assert_serving(gateway, model_b, key_b) +def test_a_group_with_no_team_does_not_hold_back_a_deactivation(gateway: Gateway) -> None: + with gateway.scenario() as scenario: + model: Final = scenario.model() + team: Final = scenario.team(models=[model]) + team_info: Final = object_value(gateway.get("/team/info", {"team_id": team})["team_info"]) + expected_group: Final = ScimGroupRef(value=team, display=string_value(team_info["team_alias"]), type="direct") + no_such_team: Final = f"no-such-team-{uuid.uuid4().hex}" + user_name: Final = f"scim-leaver-{uuid.uuid4().hex}@example.com" + profile: Final[dict[str, JsonValue]] = { + "schemas": [SCIM_CORE_USER_SCHEMA], + "userName": user_name, + "name": {"givenName": "Group", "familyName": "Leaver"}, + "emails": [{"value": user_name, "primary": True, "type": "work"}], + "active": True, + } + created: Final = _scim_request(gateway, "POST", "/scim/v2/Users", profile) + scenario.cleanups.callback(_delete_user_if_present, gateway, user_name) + assert created.status_code == 201, created.text + key: Final = _key_with_cleanup(scenario, user_id=user_name, models=[model]) + _assert_serving(gateway, model, key) + + deactivated: Final = _scim_request( + gateway, + "PATCH", + f"/scim/v2/Users/{user_name}", + { + "schemas": [SCIM_PATCH_OP_SCHEMA], + "Operations": [ + {"op": "replace", "path": "active", "value": False}, + {"op": "replace", "path": "groups", "value": [{"value": no_such_team}]}, + {"op": "add", "path": "groups", "value": [{"value": team}]}, + ], + }, + ) + + assert deactivated.status_code == 200, deactivated.text + readback: Final = _scim_request(gateway, "GET", f"/scim/v2/Users/{user_name}") + assert readback.status_code == 200, readback.text + readback_user: Final = ScimUserResponse.model_validate(readback.json()) + assert readback_user.active is False, readback.text + assert readback_user.groups == [expected_group], readback.text + assert _has_team_member(gateway, team, user_name), _team_members(gateway, team) + assert read_rows('SELECT teams FROM "LiteLLM_UserTable" WHERE user_id = %s', (user_name,)) == [ + {"teams": [team]} + ], readback.text + blocked: Final = gateway.request( + "POST", + "/v1/chat/completions", + {"model": model, "messages": [{"role": "user", "content": "SCIM deactivated user"}]}, + key=key, + ) + assert blocked.status_code == 401, blocked.text + + reactivated: Final = _scim_request( + gateway, + "PUT", + f"/scim/v2/Users/{user_name}", + {**profile, "groups": [{"value": team}, {"value": no_such_team}]}, + ) + assert reactivated.status_code == 200, reactivated.text + reactivated_user: Final = ScimUserResponse.model_validate(reactivated.json()) + assert reactivated_user.active is True, reactivated.text + assert reactivated_user.groups == [expected_group], reactivated.text + _assert_serving(gateway, model, key) + + deactivated_by_put: Final = _scim_request( + gateway, + "PUT", + f"/scim/v2/Users/{user_name}", + {**profile, "active": False, "groups": [{"value": no_such_team}]}, + ) + assert deactivated_by_put.status_code == 200, deactivated_by_put.text + deactivated_user: Final = ScimUserResponse.model_validate(deactivated_by_put.json()) + assert deactivated_user.active is False, deactivated_by_put.text + assert deactivated_user.groups == [], deactivated_by_put.text + assert not _has_team_member(gateway, team, user_name), _team_members(gateway, team) + + def test_scim_create_persists_external_id_as_the_sso_user_id(gateway: Gateway) -> None: pytest.skip( "BUG: POST /scim/v2/Users drops externalId, so the 201 resource and GET readback return externalId null and " diff --git a/tests/unit/proxy/management_endpoints/scim/test_scim_patch_user.py b/tests/unit/proxy/management_endpoints/scim/test_scim_patch_user.py index 1901e0efd4b..df11160dcce 100644 --- a/tests/unit/proxy/management_endpoints/scim/test_scim_patch_user.py +++ b/tests/unit/proxy/management_endpoints/scim/test_scim_patch_user.py @@ -1,4 +1,5 @@ -from collections.abc import Mapping +import logging +from collections.abc import Mapping, Sequence from typing import Final from unittest.mock import AsyncMock, MagicMock, patch @@ -6,8 +7,8 @@ import pytest from fastapi import HTTPException from pydantic import TypeAdapter -from litellm.proxy._types import LiteLLM_UserTable -from litellm.proxy.management_endpoints.scim.scim_v2 import _apply_patch_ops, patch_user +from litellm.proxy._types import LiteLLM_UserTable, LitellmUserRoles +from litellm.proxy.management_endpoints.scim.scim_v2 import _apply_patch_ops, _sync_requested_teams, patch_user from litellm.types.proxy.management_endpoints.scim_v2 import ( SCIM_ENTERPRISE_METADATA_KEY, SCIM_ENTERPRISE_USER_SCHEMA, @@ -111,9 +112,11 @@ async def test_patch_user_manages_group_memberships(): mock_client = MagicMock() mock_db = MagicMock() mock_client.db = mock_db + mock_client.writer_db = mock_client.db mock_db.litellm_usertable.find_unique = AsyncMock(return_value=mock_user) mock_db.litellm_usertable.update = AsyncMock(side_effect=mock_update) mock_db.litellm_teamtable.find_unique = AsyncMock(return_value=None) + mock_db.litellm_teamtable.find_many = AsyncMock(return_value=_team_rows(("new-team", "old-team"))) # Mock the transformation function to return a proper SCIMUser mock_scim_user = SCIMUser( @@ -577,8 +580,8 @@ def test_apply_patch_ops_replace_groups_empty_value_does_not_use_path_filter(): SCIMPatchOperation(op="add", path="groups", value=[{"value": "team-mu"}]), SCIMPatchOperation(op="remove", path='groups[value eq "team-delta"]'), ], - ("team-delta", "team-omega", "team-beta"), - id="a_replace_wins_over_later_group_ops", + ("team-omega", "team-beta", "team-mu"), + id="group_ops_after_a_replace_apply_in_order", ), pytest.param( [ @@ -605,6 +608,252 @@ def test_apply_patch_ops_keeps_team_order_so_the_first_team_stays_first( assert final_teams == expected_teams +def _team_rows(team_ids: Sequence[str]) -> list[MagicMock]: + return [MagicMock(team_id=team_id) for team_id in team_ids] + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "record_teams,requested_teams,teams_with_rows,expected_teams,expected_added,expected_removed", + [ + pytest.param( + [], + ["team-real", "team-gone"], + ["team-real"], + ("team-real",), + ["team-real"], + [], + id="an_add_with_no_team_row_is_left_out_and_the_real_team_is_written", + ), + pytest.param( + ["team-real", "team-gone"], + ["team-real"], + ["team-real"], + ("team-real",), + None, + None, + id="a_remove_with_no_team_row_makes_no_roster_write_and_is_dropped_from_the_record", + ), + pytest.param( + ["team-real"], + ["team-real", "team-gone"], + [], + ("team-real",), + None, + None, + id="an_add_with_no_team_row_makes_no_roster_write_and_keeps_the_record_teams", + ), + ], +) +async def test_sync_requested_teams_leaves_out_groups_with_no_team_row( + record_teams: list[str], + requested_teams: list[str], + teams_with_rows: list[str], + expected_teams: tuple[str, ...], + expected_added: list[str] | None, + expected_removed: list[str] | None, +): + mock_client: Final = MagicMock() + mock_client.writer_db = mock_client.db + mock_client.db.litellm_teamtable.find_many = AsyncMock(return_value=_team_rows(teams_with_rows)) + mock_patch_team_membership: Final = AsyncMock() + + with patch( + "litellm.proxy.management_endpoints.scim.scim_v2.patch_team_membership", + mock_patch_team_membership, + ): + teams: Final = await _sync_requested_teams( + prisma_client=mock_client, + user_id="user-groups", + record_teams=record_teams, + requested_teams=requested_teams, + ) + + assert teams == expected_teams + if expected_added is None: + mock_patch_team_membership.assert_not_called() + return + write: Final = mock_patch_team_membership.call_args.kwargs + assert write["teams_ids_to_add_user_to"] == expected_added + assert write["teams_ids_to_remove_user_from"] == expected_removed + + +@pytest.mark.asyncio +async def test_sync_requested_teams_reads_no_team_rows_when_the_groups_did_not_change(): + mock_client: Final = MagicMock() + mock_client.writer_db = mock_client.db + mock_client.db.litellm_teamtable.find_many = AsyncMock(return_value=[]) + + teams: Final = await _sync_requested_teams( + prisma_client=mock_client, + user_id="user-groups", + record_teams=["team-real"], + requested_teams=["team-real"], + ) + + assert teams == ("team-real",) + mock_client.db.litellm_teamtable.find_many.assert_not_called() + + +@pytest.mark.asyncio +async def test_sync_requested_teams_adds_a_team_the_read_replica_has_not_seen_yet(): + mock_client: Final = MagicMock() + mock_client.db.litellm_teamtable.find_many = AsyncMock(return_value=[]) + mock_client.writer_db.litellm_teamtable.find_many = AsyncMock(return_value=_team_rows(["team-new"])) + mock_patch_team_membership: Final = AsyncMock() + + with patch( + "litellm.proxy.management_endpoints.scim.scim_v2.patch_team_membership", + mock_patch_team_membership, + ): + teams: Final = await _sync_requested_teams( + prisma_client=mock_client, + user_id="user-groups", + record_teams=[], + requested_teams=["team-new"], + ) + + assert teams == ("team-new",) + assert mock_patch_team_membership.call_args.kwargs["teams_ids_to_add_user_to"] == ["team-new"] + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("teams_with_rows", "expected_warnings"), + [ + pytest.param(["team-real"], 1, id="a_group_with_no_team_row_is_named_in_one_warning"), + pytest.param(["team-real", "team-new"], 0, id="no_warning_when_every_group_has_a_team_row"), + ], +) +async def test_sync_requested_teams_warns_only_about_groups_it_left_out( + teams_with_rows: list[str], + expected_warnings: int, + caplog: pytest.LogCaptureFixture, +): + mock_client: Final = MagicMock() + mock_client.writer_db = mock_client.db + mock_client.db.litellm_teamtable.find_many = AsyncMock(return_value=_team_rows(teams_with_rows)) + + with ( + patch("litellm.proxy.management_endpoints.scim.scim_v2.patch_team_membership", AsyncMock()), + caplog.at_level(logging.WARNING, logger="LiteLLM Proxy"), + ): + await _sync_requested_teams( + prisma_client=mock_client, + user_id="user-groups", + record_teams=[], + requested_teams=["team-real", "team-new"], + ) + + warnings: Final = [record.getMessage() for record in caplog.records if record.levelno == logging.WARNING] + assert len(warnings) == expected_warnings + assert all("team-new" in warning and "team-real" not in warning for warning in warnings) + + +@pytest.mark.asyncio +async def test_sync_requested_teams_warning_stays_on_one_line_when_the_user_id_holds_line_breaks( + caplog: pytest.LogCaptureFixture, +): + mock_client: Final = MagicMock() + mock_client.writer_db = mock_client.db + mock_client.db.litellm_teamtable.find_many = AsyncMock(return_value=[]) + + with ( + patch("litellm.proxy.management_endpoints.scim.scim_v2.patch_team_membership", AsyncMock()), + caplog.at_level(logging.WARNING, logger="LiteLLM Proxy"), + ): + await _sync_requested_teams( + prisma_client=mock_client, + user_id="user-groups\r\nCRITICAL forged line", + record_teams=[], + requested_teams=["team-new"], + ) + + warnings: Final = [record.getMessage() for record in caplog.records if record.levelno == logging.WARNING] + assert len(warnings) == 1 + assert "\n" not in warnings[0] and "\r" not in warnings[0] + assert "user-groupsCRITICAL forged line" in warnings[0] + + +@pytest.mark.asyncio +async def test_patch_user_ignores_a_group_with_no_team_named_like_the_scim_admin_group(): + mock_user: Final = LiteLLM_UserTable( + user_id="not-an-admin", + user_email="not-an-admin@example.com", + teams=[], + metadata={}, + ) + mock_client: Final = MagicMock() + mock_client.writer_db = mock_client.db + mock_client.db.litellm_usertable.find_unique = AsyncMock(return_value=mock_user) + mock_client.db.litellm_usertable.update = AsyncMock(return_value=mock_user) + mock_client.db.litellm_teamtable.find_many = AsyncMock(return_value=[]) + mock_client.db.litellm_teamtable.find_unique = AsyncMock(return_value=None) + patch_ops: Final = SCIMPatchOp( + Operations=[SCIMPatchOperation(op="add", path="groups", value=[{"value": "litellm-admins"}])] + ) + + with ( + patch("litellm.proxy.proxy_server.prisma_client", mock_client), + patch("litellm.proxy.proxy_server.proxy_config") as mock_proxy_config, + patch("litellm.default_internal_user_params", None), + ): + mock_proxy_config.get_config = AsyncMock( + return_value={"litellm_settings": {"scim_admin_group": "litellm-admins"}} + ) + await patch_user(user_id="not-an-admin", patch_ops=patch_ops) + + update_data: Final = mock_client.db.litellm_usertable.update.call_args.kwargs["data"] + assert update_data["user_role"] == LitellmUserRoles.INTERNAL_USER_VIEW_ONLY + assert update_data["teams"] == [] + + +@pytest.mark.asyncio +async def test_patch_user_deactivates_and_blocks_keys_when_a_group_has_no_team(): + mock_user: Final = LiteLLM_UserTable( + user_id="user-leaver", + user_email="leaver@example.com", + teams=[], + metadata={}, + ) + mock_client: Final = MagicMock() + mock_db: Final = MagicMock() + mock_client.db = mock_db + mock_client.writer_db = mock_client.db + mock_db.litellm_usertable.find_unique = AsyncMock(return_value=mock_user) + + async def mock_update(*, where: Mapping[str, object], data: Mapping[str, object]) -> LiteLLM_UserTable: + assert where == {"user_id": "user-leaver"} + return mock_user + + mock_db.litellm_usertable.update = AsyncMock(side_effect=mock_update) + mock_db.litellm_teamtable.find_many = AsyncMock(return_value=[]) + mock_block_keys: Final = AsyncMock(return_value=1) + mock_patch_team_membership: Final = AsyncMock() + patch_ops: Final = SCIMPatchOp( + Operations=[ + SCIMPatchOperation(op="replace", path="active", value=False), + SCIMPatchOperation(op="add", path="groups", value=[{"value": "no-such-team"}]), + ] + ) + + with ( + patch("litellm.proxy.proxy_server.prisma_client", mock_client), + patch("litellm.proxy.proxy_server.proxy_config") as mock_proxy_config, + patch("litellm.proxy.management_endpoints.scim.scim_v2._set_user_keys_blocked", mock_block_keys), + patch("litellm.proxy.management_endpoints.scim.scim_v2.patch_team_membership", mock_patch_team_membership), + ): + mock_proxy_config.get_config = AsyncMock(return_value={}) + await patch_user(user_id="user-leaver", patch_ops=patch_ops) + + update_data: Final = mock_db.litellm_usertable.update.call_args.kwargs["data"] + metadata: Final = TypeAdapter(dict[str, object]).validate_json(update_data["metadata"]) + assert metadata["scim_active"] is False + assert update_data["teams"] == [] + mock_patch_team_membership.assert_not_called() + mock_block_keys.assert_awaited_once_with(user_id="user-leaver", blocked=True) + + @pytest.mark.asyncio async def test_patch_user_pathless_enterprise_extension_merges_existing_metadata(): mock_user: Final = _user_with_metadata({SCIM_ENTERPRISE_METADATA_KEY: {"employeeNumber": "42"}}) diff --git a/tests/unit/proxy/management_endpoints/scim/test_scim_v2_endpoints.py b/tests/unit/proxy/management_endpoints/scim/test_scim_v2_endpoints.py index 94e0f91ecd1..dfd30b3699f 100644 --- a/tests/unit/proxy/management_endpoints/scim/test_scim_v2_endpoints.py +++ b/tests/unit/proxy/management_endpoints/scim/test_scim_v2_endpoints.py @@ -94,6 +94,10 @@ def _created_team(team_id: str | None) -> dict[str, object]: return LiteLLM_TeamTable(team_id=team_id, members_with_roles=[]).model_dump() +async def _every_team_exists(*, where: Mapping[str, Mapping[str, Sequence[str]]]) -> list[MagicMock]: + return [MagicMock(team_id=team_id) for team_id in where["team_id"]["in"]] + + def _stub_roster_sync(mocker: MockerFixture, team: LiteLLM_TeamTable | None = None) -> AsyncMock: """Stand in for the bulk roster write: apply the plan to ``team`` (else to the row the prisma mock answers for the group, else to an empty roster) and report the diff, so an @@ -1426,8 +1430,10 @@ async def test_update_user_success(mocker): # Mock prisma client mock_prisma_client = mocker.MagicMock() mock_prisma_client.db = mocker.MagicMock() + mock_prisma_client.writer_db = mock_prisma_client.db mock_prisma_client.db.litellm_usertable = mocker.MagicMock() mock_prisma_client.db.litellm_usertable.update = AsyncMock(return_value=updated_user) + mock_prisma_client.db.litellm_teamtable.find_many = AsyncMock(side_effect=_every_team_exists) # Mock dependencies mocker.patch( @@ -1530,6 +1536,68 @@ async def test_update_user_put_with_valueless_entitlements_deactivates_user(scim set_keys_blocked_mock.assert_awaited_once_with(user_id="suspend-me", blocked=True) +@pytest.mark.asyncio +async def test_update_user_put_deactivates_and_blocks_keys_when_a_group_has_no_team( + mocker: MockerFixture, scim_test_client: AsyncClient +) -> None: + existing_user: Final = mocker.MagicMock() + existing_user.teams = [] + existing_user.metadata = {} + + mock_prisma_client: Final = mocker.MagicMock() + mock_prisma_client.writer_db = mock_prisma_client.db + mock_prisma_client.db.litellm_usertable.update = AsyncMock( + return_value={"user_id": "leaver", "user_email": "leaver@example.com", "teams": [], "metadata": "{}"} + ) + mock_prisma_client.db.litellm_teamtable.find_many = AsyncMock(return_value=[]) + mock_patch_team_membership: Final = mocker.patch( # test-quality-ok: endpoint collaborators are module-level, not injectable + "litellm.proxy.management_endpoints.scim.scim_v2.patch_team_membership", + AsyncMock(), + ) + mocker.patch( # test-quality-ok: endpoint collaborators are module-level, not injectable + "litellm.proxy.management_endpoints.scim.scim_v2._get_prisma_client_or_raise_exception", + AsyncMock(return_value=mock_prisma_client), + ) + mocker.patch( # test-quality-ok: endpoint collaborators are module-level, not injectable + "litellm.proxy.management_endpoints.scim.scim_v2._check_user_exists", + AsyncMock(return_value=existing_user), + ) + set_keys_blocked_mock: Final = mocker.patch( # test-quality-ok: endpoint collaborators are module-level, not injectable + "litellm.proxy.management_endpoints.scim.scim_v2._set_user_keys_blocked", + AsyncMock(return_value=1), + ) + mocker.patch( # test-quality-ok: endpoint collaborators are module-level, not injectable + "litellm.proxy.management_endpoints.scim.scim_v2.ScimTransformations.transform_litellm_user_to_scim_user", + AsyncMock( + return_value=SCIMUser( + schemas=["urn:ietf:params:scim:schemas:core:2.0:User"], + id="leaver", + userName="leaver", + active=False, + ) + ), + ) + + async with scim_test_client as client: + response = await client.put( + "/scim/v2/Users/leaver", + json={ + "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"], + "userName": "leaver", + "emails": [{"value": "leaver@example.com", "primary": True}], + "groups": [{"value": "no-such-team"}], + "active": False, + }, + ) + + assert response.status_code == 200, response.text + update_data: Final = mock_prisma_client.db.litellm_usertable.update.call_args.kwargs["data"] + assert json.loads(update_data["metadata"])["scim_active"] is False + assert update_data["teams"] == [] + mock_patch_team_membership.assert_not_called() + set_keys_blocked_mock.assert_awaited_once_with(user_id="leaver", blocked=True) + + @pytest.mark.asyncio @pytest.mark.parametrize("groups", [None, []], ids=["groups-omitted", "groups-empty"]) async def test_update_user_without_groups_preserves_memberships_and_role(mocker, monkeypatch, groups): @@ -1618,7 +1686,9 @@ async def test_update_user_put_keeps_the_record_order_of_teams_the_user_already_ ], ) mock_prisma_client: Final = mocker.MagicMock() + mock_prisma_client.writer_db = mock_prisma_client.db mock_prisma_client.db.litellm_usertable.update = AsyncMock(return_value={"user_id": "order-user"}) + mock_prisma_client.db.litellm_teamtable.find_many = AsyncMock(side_effect=_every_team_exists) mocker.patch( # test-quality-ok: update_user's collaborators are module-level, not injectable "litellm.proxy.management_endpoints.scim.scim_v2._get_prisma_client_or_raise_exception", AsyncMock(return_value=mock_prisma_client), @@ -1703,8 +1773,10 @@ async def test_patch_user_success(mocker): # Mock prisma client mock_prisma_client = mocker.MagicMock() mock_prisma_client.db = mocker.MagicMock() + mock_prisma_client.writer_db = mock_prisma_client.db mock_prisma_client.db.litellm_usertable = mocker.MagicMock() mock_prisma_client.db.litellm_usertable.update = AsyncMock(return_value=updated_user) + mock_prisma_client.db.litellm_teamtable.find_many = AsyncMock(side_effect=_every_team_exists) # Mock dependencies mocker.patch( @@ -2704,8 +2776,10 @@ async def test_update_user_demotes_admin_when_removed_from_scim_admin_group(mock mock_prisma_client = mocker.MagicMock() mock_prisma_client.db = mocker.MagicMock() + mock_prisma_client.writer_db = mock_prisma_client.db mock_prisma_client.db.litellm_usertable = mocker.MagicMock() mock_prisma_client.db.litellm_usertable.update = AsyncMock(return_value=updated_user) + mock_prisma_client.db.litellm_teamtable.find_many = AsyncMock(side_effect=_every_team_exists) mocker.patch( "litellm.proxy.management_endpoints.scim.scim_v2._get_prisma_client_or_raise_exception", @@ -2789,6 +2863,54 @@ async def test_update_user_does_not_force_role_when_scim_admin_group_unset(mocke assert "user_role" not in call_args[1]["data"] +@pytest.mark.asyncio +async def test_update_user_keeps_the_admin_role_from_a_group_with_no_team_named_like_the_scim_admin_group( + mocker: MockerFixture, monkeypatch: pytest.MonkeyPatch +) -> None: + from litellm.proxy.proxy_server import proxy_config + + async def mock_get_config() -> dict[str, dict[str, str]]: + return {"litellm_settings": {"scim_admin_group": "litellm-admins"}} + + monkeypatch.setattr(proxy_config, "get_config", mock_get_config) + monkeypatch.setattr("litellm.default_internal_user_params", None, raising=False) + + existing_user: Final = mocker.MagicMock() + existing_user.teams = [] + existing_user.metadata = {} + scim_user: Final = SCIMUser( + schemas=["urn:ietf:params:scim:schemas:core:2.0:User"], + userName="an-admin", + emails=[SCIMUserEmail(value="an-admin@example.com")], + groups=[SCIMUserGroup(value="no-such-team", display="litellm-admins")], + ) + + mock_prisma_client: Final = mocker.MagicMock() + mock_prisma_client.writer_db = mock_prisma_client.db + mock_prisma_client.db.litellm_usertable.update = AsyncMock( + return_value={"user_id": "an-admin", "teams": [], "metadata": "{}"} + ) + mock_prisma_client.db.litellm_teamtable.find_many = AsyncMock(return_value=[]) + mocker.patch( # test-quality-ok: endpoint collaborators are module-level, not injectable + "litellm.proxy.management_endpoints.scim.scim_v2._get_prisma_client_or_raise_exception", + AsyncMock(return_value=mock_prisma_client), + ) + mocker.patch( # test-quality-ok: endpoint collaborators are module-level, not injectable + "litellm.proxy.management_endpoints.scim.scim_v2._check_user_exists", + AsyncMock(return_value=existing_user), + ) + mocker.patch( # test-quality-ok: endpoint collaborators are module-level, not injectable + "litellm.proxy.management_endpoints.scim.scim_v2.ScimTransformations.transform_litellm_user_to_scim_user", + AsyncMock(return_value=scim_user), + ) + + await update_user(user_id="an-admin", user=scim_user) + + update_data: Final = mock_prisma_client.db.litellm_usertable.update.call_args.kwargs["data"] + assert update_data["user_role"] == LitellmUserRoles.PROXY_ADMIN + assert update_data["teams"] == [] + + @pytest.mark.asyncio async def test_update_user_demotes_when_default_params_lack_user_role(mocker, monkeypatch): """Regression: default_internal_user_params set without a user_role key must @@ -2823,8 +2945,10 @@ async def test_update_user_demotes_when_default_params_lack_user_role(mocker, mo mock_prisma_client = mocker.MagicMock() mock_prisma_client.db = mocker.MagicMock() + mock_prisma_client.writer_db = mock_prisma_client.db mock_prisma_client.db.litellm_usertable = mocker.MagicMock() mock_prisma_client.db.litellm_usertable.update = AsyncMock(return_value=updated_user) + mock_prisma_client.db.litellm_teamtable.find_many = AsyncMock(side_effect=_every_team_exists) mocker.patch( "litellm.proxy.management_endpoints.scim.scim_v2._get_prisma_client_or_raise_exception", @@ -2882,10 +3006,12 @@ async def test_patch_user_demotes_admin_when_removed_from_scim_admin_group(mocke mock_prisma_client = mocker.MagicMock() mock_prisma_client.db = mocker.MagicMock() + mock_prisma_client.writer_db = mock_prisma_client.db mock_prisma_client.db.litellm_usertable = mocker.MagicMock() mock_prisma_client.db.litellm_usertable.update = AsyncMock(return_value=updated_user) mock_prisma_client.db.litellm_teamtable = mocker.MagicMock() mock_prisma_client.db.litellm_teamtable.find_unique = AsyncMock(return_value=engineering_team) + mock_prisma_client.db.litellm_teamtable.find_many = AsyncMock(side_effect=_every_team_exists) mocker.patch( "litellm.proxy.management_endpoints.scim.scim_v2._get_prisma_client_or_raise_exception", @@ -2949,10 +3075,12 @@ async def test_patch_user_grants_admin_by_team_display_name(mocker, monkeypatch) mock_prisma_client = mocker.MagicMock() mock_prisma_client.db = mocker.MagicMock() + mock_prisma_client.writer_db = mock_prisma_client.db mock_prisma_client.db.litellm_usertable = mocker.MagicMock() mock_prisma_client.db.litellm_usertable.update = AsyncMock(return_value=updated_user) mock_prisma_client.db.litellm_teamtable = mocker.MagicMock() mock_prisma_client.db.litellm_teamtable.find_unique = AsyncMock(return_value=admin_team) + mock_prisma_client.db.litellm_teamtable.find_many = AsyncMock(side_effect=_every_team_exists) mocker.patch( "litellm.proxy.management_endpoints.scim.scim_v2._get_prisma_client_or_raise_exception", @@ -6175,8 +6303,10 @@ async def test_update_user_roster_add_failure_propagates_and_skips_teams_write(m mock_prisma_client = mocker.MagicMock() mock_prisma_client.db = mocker.MagicMock() + mock_prisma_client.writer_db = mock_prisma_client.db mock_prisma_client.db.litellm_usertable = mocker.MagicMock() mock_prisma_client.db.litellm_usertable.update = AsyncMock() + mock_prisma_client.db.litellm_teamtable.find_many = AsyncMock(side_effect=_every_team_exists) mocker.patch( "litellm.proxy.management_endpoints.scim.scim_v2._get_prisma_client_or_raise_exception",