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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
test: add unit testing
Krrish Dholakiae43c3b9b88f7
diff --git a/tests/test_litellm/proxy/management_endpoints/test_ui_sso.py b/tests/test_litellm/proxy/management_endpoints/test_ui_sso.pyindex 941517db120..bdc0852b151 100644--- a/tests/test_litellm/proxy/management_endpoints/test_ui_sso.py+++ b/tests/test_litellm/proxy/management_endpoints/test_ui_sso.py@@ -99,7 +99,9 @@ def test_microsoft_sso_handler_with_empty_response():# Test with None response# Act- result = MicrosoftSSOHandler.openid_from_response(response=None, team_ids=[], user_role=None)+ result = MicrosoftSSOHandler.openid_from_response(+ response=None, team_ids=[], user_role=None+ )# Assertassert isinstance(result, CustomOpenID)@@ -789,11 +791,11 @@ class TestCLISSOCallbackFunction:"not-sk-key","sk", # too short]-+for invalid_key in invalid_keys:# This should fail validation before any database operations# We can test this by checking if the key starts with 'sk-'- if not invalid_key or not invalid_key.startswith('sk-'):+ if not invalid_key or not invalid_key.startswith("sk-"):# This would trigger the validation errorassert True # Validation works as expected@@ -806,14 +808,14 @@ class TestCLIPollingFunction:# Test key format validation logicinvalid_keys = ["invalid-key",- "not-sk-key",+ "not-sk-key","","sk", # too short]-+for invalid_key in invalid_keys:# Validation logic: key must start with 'sk-'- if not invalid_key.startswith('sk-'):+ if not invalid_key.startswith("sk-"):# This would trigger the validation error in the actual functionassert True # Validation works as expected@@ -827,7 +829,7 @@ class TestAuthCallbackRouting:# Test CLI state detection logiccli_state = f"{LITELLM_CLI_SESSION_TOKEN_PREFIX}:sk-test123"-+# This mimics the logic in auth_callbackif cli_state and cli_state.startswith(f"{LITELLM_CLI_SESSION_TOKEN_PREFIX}:"):# Extract the key ID from the state@@ -839,18 +841,20 @@ class TestAuthCallbackRouting:def test_non_cli_state_routing(self):"""Test that non-CLI states don't trigger CLI routing"""from litellm.constants import LITELLM_CLI_SESSION_TOKEN_PREFIX-+non_cli_states = ["regular_oauth_state",- "some_random_string",+ "some_random_string",None,"",- "not_session_token:something"+ "not_session_token:something",]-+for state in non_cli_states:# This mimics the routing logic in auth_callback- should_route_to_cli = state and state.startswith(f"{LITELLM_CLI_SESSION_TOKEN_PREFIX}:")+ should_route_to_cli = state and state.startswith(+ f"{LITELLM_CLI_SESSION_TOKEN_PREFIX}:"+ )assert not should_route_to_cli, f"State '{state}' should not route to CLI"@@ -864,9 +868,9 @@ class TestGoogleLoginCLIIntegration:# Test the CLI state generation logic used in google_loginsource = "litellm-cli"key = "sk-test123"-+cli_state = SSOAuthenticationHandler._get_cli_state(source=source, key=key)-+assert cli_state is not Noneassert cli_state.startswith("litellm-session-token:")assert "sk-test123" in cli_state@@ -882,10 +886,12 @@ class TestGoogleLoginCLIIntegration:(None, "sk-test123"),("wrong-source", "sk-test123"),]-+for source, key in test_cases:cli_state = SSOAuthenticationHandler._get_cli_state(source=source, key=key)- assert cli_state is None, f"CLI state should not be generated for source='{source}', key='{key}'"+ assert (+ cli_state is None+ ), f"CLI state should not be generated for source='{source}', key='{key}'"class TestSSOHandlerIntegration:@@ -896,13 +902,24 @@ class TestSSOHandlerIntegration:from litellm.proxy.management_endpoints.ui_sso import SSOAuthenticationHandler# Test that SSO handler is used when client IDs are provided- assert SSOAuthenticationHandler.should_use_sso_handler(google_client_id="test") is True- assert SSOAuthenticationHandler.should_use_sso_handler(microsoft_client_id="test") is True- assert SSOAuthenticationHandler.should_use_sso_handler(generic_client_id="test") is True-+ assert (+ SSOAuthenticationHandler.should_use_sso_handler(google_client_id="test")+ is True+ )+ assert (+ SSOAuthenticationHandler.should_use_sso_handler(microsoft_client_id="test")+ is True+ )+ assert (+ SSOAuthenticationHandler.should_use_sso_handler(generic_client_id="test")+ is True+ )+# Test that SSO handler is not used when no client IDs are providedassert SSOAuthenticationHandler.should_use_sso_handler() is False- assert SSOAuthenticationHandler.should_use_sso_handler(None, None, None) is False+ assert (+ SSOAuthenticationHandler.should_use_sso_handler(None, None, None) is False+ )def test_get_redirect_url_for_sso(self):"""Test the redirect URL generation for SSO"""@@ -911,13 +928,12 @@ class TestSSOHandlerIntegration:# Mock request objectmock_request = MagicMock()mock_request.base_url = "https://test.litellm.ai/"-+# Test redirect URL generationredirect_url = SSOAuthenticationHandler.get_redirect_url_for_sso(- request=mock_request,- sso_callback_route="sso/callback"+ request=mock_request, sso_callback_route="sso/callback")-+assert redirect_url.startswith("https://test.litellm.ai")assert "sso/callback" in redirect_url@@ -928,21 +944,25 @@ class TestUISSO_FunctionsExistence:def test_cli_sso_callback_exists(self):"""Test that cli_sso_callback function exists"""from litellm.proxy.management_endpoints.ui_sso import cli_sso_callback+assert callable(cli_sso_callback)def test_cli_poll_key_exists(self):"""Test that cli_poll_key function exists"""from litellm.proxy.management_endpoints.ui_sso import cli_poll_key+assert callable(cli_poll_key)def test_auth_callback_exists(self):"""Test that auth_callback function exists"""from litellm.proxy.management_endpoints.ui_sso import auth_callback+assert callable(auth_callback)def test_google_login_exists(self):"""Test that google_login function exists"""from litellm.proxy.management_endpoints.ui_sso import google_login+assert callable(google_login)def test_sso_authentication_handler_exists(self):@@ -951,9 +971,9 @@ class TestUISSO_FunctionsExistence:# Check that the class existsassert SSOAuthenticationHandler is not None-+# Check that the new _get_cli_state method exists- assert hasattr(SSOAuthenticationHandler, '_get_cli_state')+ assert hasattr(SSOAuthenticationHandler, "_get_cli_state")assert callable(SSOAuthenticationHandler._get_cli_state)@@ -963,9 +983,11 @@ class TestSSOStateHandling:def test_get_cli_state_valid(self):"""Test generating CLI state with valid parameters"""from litellm.proxy.management_endpoints.ui_sso import SSOAuthenticationHandler-- state = SSOAuthenticationHandler._get_cli_state(source="litellm-cli", key="sk-test123")-++ state = SSOAuthenticationHandler._get_cli_state(+ source="litellm-cli", key="sk-test123"+ )+assert state is not Noneassert state.startswith("litellm-session-token:")assert "sk-test123" in state@@ -973,37 +995,39 @@ class TestSSOStateHandling:def test_get_cli_state_invalid_source(self):"""Test generating CLI state with invalid source"""from litellm.proxy.management_endpoints.ui_sso import SSOAuthenticationHandler-- state = SSOAuthenticationHandler._get_cli_state(source="invalid_source", key="sk-test123")-++ state = SSOAuthenticationHandler._get_cli_state(+ source="invalid_source", key="sk-test123"+ )+assert state is Nonedef test_get_cli_state_no_key(self):"""Test generating CLI state without key"""from litellm.proxy.management_endpoints.ui_sso import SSOAuthenticationHandler-+state = SSOAuthenticationHandler._get_cli_state(source="litellm-cli", key=None)-+assert state is Nonedef test_get_cli_state_no_source(self):"""Test generating CLI state without source"""from litellm.proxy.management_endpoints.ui_sso import SSOAuthenticationHandler-+state = SSOAuthenticationHandler._get_cli_state(source=None, key="sk-test123")-+assert state is Nonedef test_get_cli_state_with_existing_key(self):"""Test generating CLI state with existing_key embedded in state parameter"""from litellm.proxy.management_endpoints.ui_sso import SSOAuthenticationHandler-+state = SSOAuthenticationHandler._get_cli_state(- source="litellm-cli",+ source="litellm-cli",key="sk-new-key-123",- existing_key="sk-existing-key-456"+ existing_key="sk-existing-key-456",)-+assert state is not Noneassert state.startswith("litellm-session-token:")assert "sk-new-key-123" in state@@ -1014,13 +1038,11 @@ class TestSSOStateHandling:def test_get_cli_state_without_existing_key(self):"""Test generating CLI state without existing_key"""from litellm.proxy.management_endpoints.ui_sso import SSOAuthenticationHandler-+state = SSOAuthenticationHandler._get_cli_state(- source="litellm-cli",- key="sk-new-key-789",- existing_key=None+ source="litellm-cli", key="sk-new-key-789", existing_key=None)-+assert state is not Noneassert state.startswith("litellm-session-token:")assert "sk-new-key-789" in state@@ -1039,7 +1061,7 @@ class TestStateRouting:# Test CLI state formatcli_state = f"{LITELLM_CLI_SESSION_TOKEN_PREFIX}:sk-test123"assert cli_state.startswith(f"{LITELLM_CLI_SESSION_TOKEN_PREFIX}:")-+# Test extraction of key from statekey_id = cli_state.split(":", 1)[1]assert key_id == "sk-test123"@@ -1049,13 +1071,15 @@ class TestStateRouting:from litellm.constants import LITELLM_CLI_SESSION_TOKEN_PREFIX# State format: {PREFIX}:{key}:{existing_key}- cli_state = f"{LITELLM_CLI_SESSION_TOKEN_PREFIX}:sk-new-key-456:sk-existing-key-789"-+ cli_state = (+ f"{LITELLM_CLI_SESSION_TOKEN_PREFIX}:sk-new-key-456:sk-existing-key-789"+ )+# Parse as done in auth_callbackstate_parts = cli_state.split(":", 2) # Split into max 3 partskey_id = state_parts[1] if len(state_parts) > 1 else Noneexisting_key = state_parts[2] if len(state_parts) > 2 else None-+assert key_id == "sk-new-key-456"assert existing_key == "sk-existing-key-789"@@ -1065,12 +1089,12 @@ class TestStateRouting:# State format: {PREFIX}:{key}cli_state = f"{LITELLM_CLI_SESSION_TOKEN_PREFIX}:sk-new-key-999"-+# Parse as done in auth_callbackstate_parts = cli_state.split(":", 2) # Split into max 3 partskey_id = state_parts[1] if len(state_parts) > 1 else Noneexisting_key = state_parts[2] if len(state_parts) > 2 else None-+assert key_id == "sk-new-key-999"assert existing_key is None@@ -1084,9 +1108,9 @@ class TestStateRouting:"some_random_string",None,"",- "not_session_token:something"+ "not_session_token:something",]-+for state in test_states:if state:assert not state.startswith(f"{LITELLM_CLI_SESSION_TOKEN_PREFIX}:")@@ -1105,10 +1129,10 @@ class TestHTMLIntegration:# Test that function exists and is callableassert callable(render_cli_sso_success_page)-+# Test that it returns expected typehtml = render_cli_sso_success_page()-+assert isinstance(html, str)assert len(html) > 0@@ -1125,11 +1149,19 @@ class TestCustomUISSO:# Mock requestmock_request = MagicMock()mock_request.base_url = "https://test.example.com/"-+# Mock user_custom_ui_sso_sign_in_handler to exist but make enterprise import failwith patch("litellm.proxy.proxy_server.premium_user", True):- with patch("litellm.proxy.proxy_server.user_custom_ui_sso_sign_in_handler", MagicMock()):- with patch.dict('sys.modules', {'enterprise.litellm_enterprise.proxy.auth.custom_sso_handler': None}):+ with patch(+ "litellm.proxy.proxy_server.user_custom_ui_sso_sign_in_handler",+ MagicMock(),+ ):+ with patch.dict(+ "sys.modules",+ {+ "enterprise.litellm_enterprise.proxy.auth.custom_sso_handler": None+ },+ ):# Temporarily mock the google_login function call to test the import error pathasync def mock_google_login():# This mimics the relevant part of google_login that would trigger the import error@@ -1137,13 +1169,19 @@ class TestCustomUISSO:from enterprise.litellm_enterprise.proxy.auth.custom_sso_handler import (EnterpriseCustomSSOHandler,)+return "success"except ImportError:- raise ValueError("Enterprise features are not available. Custom UI SSO sign-in requires LiteLLM Enterprise.")-+ raise ValueError(+ "Enterprise features are not available. Custom UI SSO sign-in requires LiteLLM Enterprise."+ )+# Test that the ValueError is raised with the correct messageimport pytest- with pytest.raises(ValueError, match="Enterprise features are not available"):++ with pytest.raises(+ ValueError, match="Enterprise features are not available"+ ):asyncio.run(mock_google_login())@pytest.mark.asyncio@@ -1195,8 +1233,10 @@ class TestCustomUISSO:return_value=mock_redirect_response,) as mock_get_redirect:# Act- result = await EnterpriseCustomSSOHandler.handle_custom_ui_sso_sign_in(- request=mock_request+ result = (+ await EnterpriseCustomSSOHandler.handle_custom_ui_sso_sign_in(+ request=mock_request+ ))# Assert@@ -1241,12 +1281,14 @@ class TestCustomUISSO:async def handle_custom_ui_sso_sign_in(self, request: Request) -> OpenID:self.method_called = Trueself.received_request = request-+# Parse headers like the actual implementation wouldrequest_headers_dict = dict(request.headers)return OpenID(id=request_headers_dict.get("x-litellm-user-id", "default_user"),- email=request_headers_dict.get("x-litellm-user-email", "[email protected]"),+ email=request_headers_dict.get(+ "x-litellm-user-email", "[email protected]"+ ),first_name="Custom",last_name="Handler",display_name="Custom Handler Test",@@ -1260,7 +1302,7 @@ class TestCustomUISSO:# Mock request with custom headersmock_request = MagicMock(spec=Request)mock_request.headers = {- "x-litellm-user-id": "custom_test_user_456",+ "x-litellm-user-id": "custom_test_user_456","x-litellm-user-email": "[email protected]","x-forwarded-for": "10.0.0.1",}@@ -1281,8 +1323,10 @@ class TestCustomUISSO:return_value=mock_redirect_response,) as mock_get_redirect:# Act- result = await EnterpriseCustomSSOHandler.handle_custom_ui_sso_sign_in(- request=mock_request+ result = (+ await EnterpriseCustomSSOHandler.handle_custom_ui_sso_sign_in(+ request=mock_request+ ))# Assert that our custom handler was executed@@ -1292,7 +1336,7 @@ class TestCustomUISSO:# Verify the redirect response was called with the OpenID from our custom handlermock_get_redirect.assert_called_once()call_args = mock_get_redirect.call_args.kwargs-+# Verify the OpenID object has the expected values from our custom handleropenid_result = call_args["result"]assert openid_result.id == "custom_test_user_456"@@ -1323,25 +1367,30 @@ class TestCLIKeyRegenerationFlow:# Mock requestmock_request = MagicMock(spec=Request)-+# Test dataexisting_key = "sk-existing-key-123"new_key = "sk-new-key-456"-+# Mock the regenerate helper function- with patch("litellm.proxy.management_endpoints.ui_sso._regenerate_cli_key") as mock_regenerate, \- patch("litellm.proxy.proxy_server.prisma_client", MagicMock()), \- patch("litellm.proxy.common_utils.html_forms.cli_sso_success.render_cli_sso_success_page", return_value="<html>Success</html>"):-+ with patch(+ "litellm.proxy.management_endpoints.ui_sso._regenerate_cli_key"+ ) as mock_regenerate, patch(+ "litellm.proxy.proxy_server.prisma_client", MagicMock()+ ), patch(+ "litellm.proxy.common_utils.html_forms.cli_sso_success.render_cli_sso_success_page",+ return_value="<html>Success</html>",+ ):+# Actresult = await cli_sso_callback(- request=mock_request,- key=new_key,- existing_key=existing_key+ request=mock_request, key=new_key, existing_key=existing_key)-+# Assert- mock_regenerate.assert_called_once_with(existing_key=existing_key, new_key=new_key, user_id=None)+ mock_regenerate.assert_called_once_with(+ existing_key=existing_key, new_key=new_key, user_id=None+ )assert result.status_code == 200assert "Success" in result.body.decode()@@ -1352,22 +1401,25 @@ class TestCLIKeyRegenerationFlow:# Mock requestmock_request = MagicMock(spec=Request)-+# Test datanew_key = "sk-new-key-789"-+# Mock the create helper function- with patch("litellm.proxy.management_endpoints.ui_sso._create_new_cli_key") as mock_create, \- patch("litellm.proxy.proxy_server.prisma_client", MagicMock()), \- patch("litellm.proxy.common_utils.html_forms.cli_sso_success.render_cli_sso_success_page", return_value="<html>Success</html>"):-+ with patch(+ "litellm.proxy.management_endpoints.ui_sso._create_new_cli_key"+ ) as mock_create, patch(+ "litellm.proxy.proxy_server.prisma_client", MagicMock()+ ), patch(+ "litellm.proxy.common_utils.html_forms.cli_sso_success.render_cli_sso_success_page",+ return_value="<html>Success</html>",+ ):+# Actresult = await cli_sso_callback(- request=mock_request,- key=new_key,- existing_key=None+ request=mock_request, key=new_key, existing_key=None)-+# Assertmock_create.assert_called_once_with(key=new_key, user_id=None)assert result.status_code == 200@@ -1381,32 +1433,42 @@ class TestCLIKeyRegenerationFlow:# Mock request (no query params needed - existing_key is in state)mock_request = MagicMock(spec=Request)-+# CLI state with existing_key embedded: {PREFIX}:{key}:{existing_key}cli_state = f"{LITELLM_CLI_SESSION_TOKEN_PREFIX}:sk-new-session-key-456:sk-existing-cli-key-123"-+# Mock the CLI callback and required proxy server componentsmock_result = {"user_id": "test-user", "email": "[email protected]"}-- with patch("litellm.proxy.management_endpoints.ui_sso.cli_sso_callback") as mock_cli_callback, \- patch("litellm.proxy.proxy_server.prisma_client", MagicMock()), \- patch("litellm.proxy.proxy_server.master_key", "test-master-key"), \- patch("litellm.proxy.proxy_server.general_settings", {}), \- patch("litellm.proxy.proxy_server.jwt_handler", MagicMock()), \- patch("litellm.proxy.proxy_server.user_api_key_cache", MagicMock()), \- patch.dict(os.environ, {"GOOGLE_CLIENT_ID": "test-google-id"}, clear=True), \- patch("litellm.proxy.management_endpoints.ui_sso.GoogleSSOHandler.get_google_callback_response", return_value=mock_result):++ with patch(+ "litellm.proxy.management_endpoints.ui_sso.cli_sso_callback"+ ) as mock_cli_callback, patch(+ "litellm.proxy.proxy_server.prisma_client", MagicMock()+ ), patch(+ "litellm.proxy.proxy_server.master_key", "test-master-key"+ ), patch(+ "litellm.proxy.proxy_server.general_settings", {}+ ), patch(+ "litellm.proxy.proxy_server.jwt_handler", MagicMock()+ ), patch(+ "litellm.proxy.proxy_server.user_api_key_cache", MagicMock()+ ), patch.dict(+ os.environ, {"GOOGLE_CLIENT_ID": "test-google-id"}, clear=True+ ), patch(+ "litellm.proxy.management_endpoints.ui_sso.GoogleSSOHandler.get_google_callback_response",+ return_value=mock_result,+ ):mock_cli_callback.return_value = MagicMock()-+# Actawait auth_callback(request=mock_request, state=cli_state)-+# Assert - existing_key should be extracted from state parametermock_cli_callback.assert_called_once_with(request=mock_request,key="sk-new-session-key-456",existing_key="sk-existing-cli-key-123",- result=mock_result+ result=mock_result,)def test_get_redirect_url_does_not_include_existing_key_in_url(self):@@ -1416,15 +1478,17 @@ class TestCLIKeyRegenerationFlow:# Mock requestmock_request = MagicMock()mock_request.base_url = "https://test.litellm.ai/"-- with patch("litellm.proxy.utils.get_custom_url", return_value="https://test.litellm.ai"):++ with patch(+ "litellm.proxy.utils.get_custom_url", return_value="https://test.litellm.ai"+ ):# Test with existing_key - should NOT be in URLredirect_url = SSOAuthenticationHandler.get_redirect_url_for_sso(request=mock_request,sso_callback_route="sso/callback",- existing_key="sk-existing-123"+ existing_key="sk-existing-123",)-+# existing_key should NOT be in the URLassert "https://test.litellm.ai/sso/callback" == redirect_urlassert "existing_key" not in redirect_url@@ -1436,44 +1500,181 @@ class TestCLIKeyRegenerationFlow:# Mock requestmock_request = MagicMock()mock_request.base_url = "https://test.litellm.ai/"-- with patch("litellm.proxy.utils.get_custom_url", return_value="https://test.litellm.ai"):++ with patch(+ "litellm.proxy.utils.get_custom_url", return_value="https://test.litellm.ai"+ ):# Test without existing_keyredirect_url = SSOAuthenticationHandler.get_redirect_url_for_sso(- request=mock_request,- sso_callback_route="sso/callback"+ request=mock_request, sso_callback_route="sso/callback")-+assert "https://test.litellm.ai/sso/callback" == redirect_url@pytest.mark.asyncioasync def test_cli_sso_callback_regenerate_vs_create_flow(self):"""Test CLI SSO callback calls regenerate_key_fn when existing_key provided, generate_key_helper_fn when not"""from litellm.proxy.management_endpoints.ui_sso import cli_sso_callback-+mock_request = MagicMock(spec=Request)-- with patch("litellm.proxy.management_endpoints.key_management_endpoints.regenerate_key_fn") as mock_regenerate, \- patch("litellm.proxy.management_endpoints.key_management_endpoints.generate_key_helper_fn") as mock_generate, \- patch("litellm.proxy._types.UserAPIKeyAuth.get_litellm_cli_user_api_key_auth"), \- patch("litellm.proxy.proxy_server.prisma_client", MagicMock()), \- patch("litellm.proxy.common_utils.html_forms.cli_sso_success.render_cli_sso_success_page", return_value="<html>Success</html>"):-++ with patch(+ "litellm.proxy.management_endpoints.key_management_endpoints.regenerate_key_fn"+ ) as mock_regenerate, patch(+ "litellm.proxy.management_endpoints.key_management_endpoints.generate_key_helper_fn"+ ) as mock_generate, patch(+ "litellm.proxy._types.UserAPIKeyAuth.get_litellm_cli_user_api_key_auth"+ ), patch(+ "litellm.proxy.proxy_server.prisma_client", MagicMock()+ ), patch(+ "litellm.proxy.common_utils.html_forms.cli_sso_success.render_cli_sso_success_page",+ return_value="<html>Success</html>",+ ):+# Test regeneration path- await cli_sso_callback(mock_request, key="sk-new-123", existing_key="sk-existing-456")+ await cli_sso_callback(+ mock_request, key="sk-new-123", existing_key="sk-existing-456"+ )mock_regenerate.assert_called_once()mock_generate.assert_not_called()-+# Reset mocksmock_regenerate.reset_mock()mock_generate.reset_mock()-+# Test creation pathawait cli_sso_callback(mock_request, key="sk-new-789", existing_key=None)mock_regenerate.assert_not_called()mock_generate.assert_called_once()+class TestGetAppRolesFromIdToken:+ """Test the get_app_roles_from_id_token method"""++ def test_roles_picked_when_app_roles_not_exists(self):+ """Test that 'roles' is picked when 'app_roles' doesn't exist"""+ import jwt++ # Create a token with only 'roles' claim+ token_payload = {+ "sub": "user123",+ "email": "[email protected]",+ "roles": ["Admin", "User", "Developer"],+ }++ # Create a mock JWT token+ mock_token = "mock.jwt.token"++ with patch("jwt.decode", return_value=token_payload) as mock_jwt_decode:+ # Act+ result = MicrosoftSSOHandler.get_app_roles_from_id_token(mock_token)++ # Assert+ assert result == ["Admin", "User", "Developer"]+ mock_jwt_decode.assert_called_once_with(+ mock_token, options={"verify_signature": False}+ )++ def test_app_roles_picked_when_both_exist(self):+ """Test that 'app_roles' takes precedence when both 'app_roles' and 'roles' exist"""+ import jwt++ # Create a token with both 'app_roles' and 'roles' claims+ token_payload = {+ "sub": "user123",+ "email": "[email protected]",+ "app_roles": ["AppAdmin", "AppUser"],+ "roles": ["RoleAdmin", "RoleUser"],+ }++ mock_token = "mock.jwt.token"++ with patch("jwt.decode", return_value=token_payload):+ # Act+ result = MicrosoftSSOHandler.get_app_roles_from_id_token(mock_token)++ # Assert - app_roles should be picked, not roles+ assert result == ["AppAdmin", "AppUser"]++ def test_roles_picked_when_app_roles_is_empty(self):+ """Test that 'roles' is picked when 'app_roles' exists but is empty"""+ import jwt++ # Create a token with empty 'app_roles' and populated 'roles'+ token_payload = {+ "sub": "user123",+ "email": "[email protected]",+ "app_roles": [],+ "roles": ["Admin", "User"],+ }++ mock_token = "mock.jwt.token"++ with patch("jwt.decode", return_value=token_payload):+ # Act+ result = MicrosoftSSOHandler.get_app_roles_from_id_token(mock_token)++ # Assert - roles should be picked since app_roles is empty+ assert result == ["Admin", "User"]++ def test_empty_list_when_neither_exists(self):+ """Test that empty list is returned when neither 'app_roles' nor 'roles' exist"""+ import jwt++ # Create a token without roles claims+ token_payload = {"sub": "user123", "email": "[email protected]"}++ mock_token = "mock.jwt.token"++ with patch("jwt.decode", return_value=token_payload):+ # Act+ result = MicrosoftSSOHandler.get_app_roles_from_id_token(mock_token)++ # Assert+ assert result == []++ def test_empty_list_when_no_token_provided(self):+ """Test that empty list is returned when no token is provided"""+ # Act+ result = MicrosoftSSOHandler.get_app_roles_from_id_token(None)++ # Assert+ assert result == []++ def test_empty_list_when_roles_not_a_list(self):+ """Test that empty list is returned when roles is not a list"""+ import jwt++ # Create a token with non-list roles+ token_payload = {+ "sub": "user123",+ "email": "[email protected]",+ "roles": "Admin", # String instead of list+ }++ mock_token = "mock.jwt.token"++ with patch("jwt.decode", return_value=token_payload):+ # Act+ result = MicrosoftSSOHandler.get_app_roles_from_id_token(mock_token)++ # Assert+ assert result == []++ def test_error_handling_on_jwt_decode_exception(self):+ """Test that exceptions during JWT decode are handled gracefully"""+ import jwt++ mock_token = "invalid.jwt.token"++ with patch("jwt.decode", side_effect=Exception("Invalid token")):+ # Act+ result = MicrosoftSSOHandler.get_app_roles_from_id_token(mock_token)++ # Assert - should return empty list on error+ assert result == []++class TestProcessSSOJWTAccessToken:"""Test the process_sso_jwt_access_token helper function"""@@ -1496,10 +1697,12 @@ class TestProcessSSOJWTAccessToken:"sub": "1234567890","name": "John Doe","iat": 1516239022,- "groups": ["team1", "team2", "team3"]+ "groups": ["team1", "team2", "team3"],}- def test_process_sso_jwt_access_token_with_valid_token(self, mock_jwt_handler, sample_jwt_token, sample_jwt_payload):+ def test_process_sso_jwt_access_token_with_valid_token(+ self, mock_jwt_handler, sample_jwt_token, sample_jwt_payload+ ):"""Test processing a valid JWT access token with team extraction"""from litellm.proxy.management_endpoints.ui_sso import (process_sso_jwt_access_token,@@ -1513,7 +1716,7 @@ class TestProcessSSOJWTAccessToken:last_name="User",display_name="Test User",provider="generic",- team_ids=[]+ team_ids=[],)with patch("jwt.decode", return_value=sample_jwt_payload) as mock_jwt_decode:@@ -1521,7 +1724,7 @@ class TestProcessSSOJWTAccessToken:process_sso_jwt_access_token(access_token_str=sample_jwt_token,sso_jwt_handler=mock_jwt_handler,- result=result+ result=result,)# Assert@@ -1529,14 +1732,18 @@ class TestProcessSSOJWTAccessToken:mock_jwt_decode.assert_called_once_with(sample_jwt_token, options={"verify_signature": False})-+# Verify team IDs were extracted from JWT- mock_jwt_handler.get_team_ids_from_jwt.assert_called_once_with(sample_jwt_payload)-+ mock_jwt_handler.get_team_ids_from_jwt.assert_called_once_with(+ sample_jwt_payload+ )+# Verify team IDs were set on the result objectassert result.team_ids == ["team1", "team2", "team3"]- def test_process_sso_jwt_access_token_with_existing_team_ids(self, mock_jwt_handler, sample_jwt_token):+ def test_process_sso_jwt_access_token_with_existing_team_ids(+ self, mock_jwt_handler, sample_jwt_token+ ):"""Test that existing team IDs are not overwritten"""from litellm.proxy.management_endpoints.ui_sso import (process_sso_jwt_access_token,@@ -1551,7 +1758,7 @@ class TestProcessSSOJWTAccessToken:last_name="User",display_name="Test User",provider="generic",- team_ids=existing_team_ids+ team_ids=existing_team_ids,)with patch("jwt.decode") as mock_jwt_decode:@@ -1559,51 +1766,53 @@ class TestProcessSSOJWTAccessToken:process_sso_jwt_access_token(access_token_str=sample_jwt_token,sso_jwt_handler=mock_jwt_handler,- result=result+ result=result,)# Assert# JWT should still be decodedmock_jwt_decode.assert_called_once()-+# But team IDs should NOT be extracted since they already existmock_jwt_handler.get_team_ids_from_jwt.assert_not_called()-+# Existing team IDs should remain unchangedassert result.team_ids == existing_team_ids- def test_process_sso_jwt_access_token_with_dict_result(self, mock_jwt_handler, sample_jwt_token, sample_jwt_payload):+ def test_process_sso_jwt_access_token_with_dict_result(+ self, mock_jwt_handler, sample_jwt_token, sample_jwt_payload+ ):"""Test processing with a dictionary result object"""from litellm.proxy.management_endpoints.ui_sso import (process_sso_jwt_access_token,)# Create a dictionary result without team_ids- result = {- "id": "test_user",- "email": "[email protected]",- "name": "Test User"- }+ result = {"id": "test_user", "email": "[email protected]", "name": "Test User"}with patch("jwt.decode", return_value=sample_jwt_payload) as mock_jwt_decode:# Actprocess_sso_jwt_access_token(access_token_str=sample_jwt_token,sso_jwt_handler=mock_jwt_handler,- result=result+ result=result,)# Assertmock_jwt_decode.assert_called_once_with(sample_jwt_token, options={"verify_signature": False})- mock_jwt_handler.get_team_ids_from_jwt.assert_called_once_with(sample_jwt_payload)-+ mock_jwt_handler.get_team_ids_from_jwt.assert_called_once_with(+ sample_jwt_payload+ )+# Verify team_ids was added to the dict as a keyassert "team_ids" in resultassert result["team_ids"] == ["team1", "team2", "team3"]- def test_process_sso_jwt_access_token_with_dict_existing_team_ids(self, mock_jwt_handler, sample_jwt_token):+ def test_process_sso_jwt_access_token_with_dict_existing_team_ids(+ self, mock_jwt_handler, sample_jwt_token+ ):"""Test that existing team IDs in dictionary are not overwritten"""from litellm.proxy.management_endpoints.ui_sso import (process_sso_jwt_access_token,@@ -1615,7 +1824,7 @@ class TestProcessSSOJWTAccessToken:"id": "test_user","email": "[email protected]","name": "Test User",- "team_ids": existing_team_ids+ "team_ids": existing_team_ids,}with patch("jwt.decode") as mock_jwt_decode:@@ -1623,16 +1832,16 @@ class TestProcessSSOJWTAccessToken:process_sso_jwt_access_token(access_token_str=sample_jwt_token,sso_jwt_handler=mock_jwt_handler,- result=result+ result=result,)# Assert# JWT should still be decodedmock_jwt_decode.assert_called_once()-+# But team IDs should NOT be extracted since they already existmock_jwt_handler.get_team_ids_from_jwt.assert_not_called()-+# Existing team IDs should remain unchangedassert result["team_ids"] == existing_team_ids@@ -1642,20 +1851,14 @@ class TestProcessSSOJWTAccessToken:process_sso_jwt_access_token,)- result = CustomOpenID(- id="test_user",- email="[email protected]",- team_ids=[]- )+ result = CustomOpenID(id="test_user", email="[email protected]", team_ids=[])# Test with None access tokenwith patch("jwt.decode") as mock_jwt_decode:process_sso_jwt_access_token(- access_token_str=None,- sso_jwt_handler=mock_jwt_handler,- result=result+ access_token_str=None, sso_jwt_handler=mock_jwt_handler, result=result)-+# Assert nothing was processedmock_jwt_decode.assert_not_called()mock_jwt_handler.get_team_ids_from_jwt.assert_not_called()@@ -1664,11 +1867,9 @@ class TestProcessSSOJWTAccessToken:# Test with empty string access tokenwith patch("jwt.decode") as mock_jwt_decode:process_sso_jwt_access_token(- access_token_str="",- sso_jwt_handler=mock_jwt_handler,- result=result+ access_token_str="", sso_jwt_handler=mock_jwt_handler, result=result)-+# Assert nothing was processedmock_jwt_decode.assert_not_called()mock_jwt_handler.get_team_ids_from_jwt.assert_not_called()@@ -1680,25 +1881,21 @@ class TestProcessSSOJWTAccessToken:process_sso_jwt_access_token,)- result = CustomOpenID(- id="test_user",- email="[email protected]",- team_ids=[]- )+ result = CustomOpenID(id="test_user", email="[email protected]", team_ids=[])with patch("jwt.decode") as mock_jwt_decode:# Actprocess_sso_jwt_access_token(- access_token_str=sample_jwt_token,- sso_jwt_handler=None,- result=result+ access_token_str=sample_jwt_token, sso_jwt_handler=None, result=result)# Assert nothing was processedmock_jwt_decode.assert_not_called()assert result.team_ids == []- def test_process_sso_jwt_access_token_no_result(self, mock_jwt_handler, sample_jwt_token):+ def test_process_sso_jwt_access_token_no_result(+ self, mock_jwt_handler, sample_jwt_token+ ):"""Test that nothing happens when result is None"""from litellm.proxy.management_endpoints.ui_sso import (process_sso_jwt_access_token,@@ -1709,32 +1906,32 @@ class TestProcessSSOJWTAccessToken:process_sso_jwt_access_token(access_token_str=sample_jwt_token,sso_jwt_handler=mock_jwt_handler,- result=None+ result=None,)# Assert nothing was processedmock_jwt_decode.assert_not_called()mock_jwt_handler.get_team_ids_from_jwt.assert_not_called()- def test_process_sso_jwt_access_token_jwt_decode_exception(self, mock_jwt_handler, sample_jwt_token):+ def test_process_sso_jwt_access_token_jwt_decode_exception(+ self, mock_jwt_handler, sample_jwt_token+ ):"""Test that JWT decode exceptions are not caught (should propagate up)"""from litellm.proxy.management_endpoints.ui_sso import (process_sso_jwt_access_token,)- result = CustomOpenID(- id="test_user",- email="[email protected]",- team_ids=[]- )+ result = CustomOpenID(id="test_user", email="[email protected]", team_ids=[])- with patch("jwt.decode", side_effect=Exception("JWT decode error")) as mock_jwt_decode:+ with patch(+ "jwt.decode", side_effect=Exception("JWT decode error")+ ) as mock_jwt_decode:# Act & Assertwith pytest.raises(Exception, match="JWT decode error"):process_sso_jwt_access_token(access_token_str=sample_jwt_token,sso_jwt_handler=mock_jwt_handler,- result=result+ result=result,)# Verify JWT decode was attempted@@ -1742,7 +1939,9 @@ class TestProcessSSOJWTAccessToken:# But team extraction should not have been calledmock_jwt_handler.get_team_ids_from_jwt.assert_not_called()- def test_process_sso_jwt_access_token_empty_team_ids_from_jwt(self, mock_jwt_handler, sample_jwt_token, sample_jwt_payload):+ def test_process_sso_jwt_access_token_empty_team_ids_from_jwt(+ self, mock_jwt_handler, sample_jwt_token, sample_jwt_payload+ ):"""Test processing when JWT handler returns empty team IDs"""from litellm.proxy.management_endpoints.ui_sso import (process_sso_jwt_access_token,@@ -1751,24 +1950,21 @@ class TestProcessSSOJWTAccessToken:# Configure mock to return empty team IDsmock_jwt_handler.get_team_ids_from_jwt.return_value = []- result = CustomOpenID(- id="test_user",- email="[email protected]",- team_ids=[]- )+ result = CustomOpenID(id="test_user", email="[email protected]", team_ids=[])with patch("jwt.decode", return_value=sample_jwt_payload) as mock_jwt_decode:# Actprocess_sso_jwt_access_token(access_token_str=sample_jwt_token,sso_jwt_handler=mock_jwt_handler,- result=result+ result=result,)# Assertmock_jwt_decode.assert_called_once()- mock_jwt_handler.get_team_ids_from_jwt.assert_called_once_with(sample_jwt_payload)-+ mock_jwt_handler.get_team_ids_from_jwt.assert_called_once_with(+ sample_jwt_payload+ )+# Even empty team IDs should be setassert result.team_ids == []-