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: refactoring + testing
Krrish Dholakia7694e9f6a9cf
diff --git a/litellm/proxy/management_endpoints/ui_sso.py b/litellm/proxy/management_endpoints/ui_sso.pyindex 1900cb15753..e6fdcef2805 100644--- a/litellm/proxy/management_endpoints/ui_sso.py+++ b/litellm/proxy/management_endpoints/ui_sso.py@@ -76,6 +76,42 @@ else:router = APIRouter()+def process_sso_jwt_access_token(+ access_token_str: Optional[str],+ sso_jwt_handler: Optional[JWTHandler],+ result: Union[OpenID, dict, None],+) -> None:+ """+ Process SSO JWT access token and extract team IDs if available.++ This function decodes the JWT access token and extracts team IDs using the+ sso_jwt_handler, then sets the team_ids attribute on the result object.++ Args:+ access_token_str: The JWT access token string+ sso_jwt_handler: SSO-specific JWT handler for team ID extraction+ result: The SSO result object to update with team IDs+ """+ if access_token_str and sso_jwt_handler and result:+ import jwt++ access_token_payload = jwt.decode(+ access_token_str, options={"verify_signature": False}+ )++ # Handle both dict and object result types+ if isinstance(result, dict):+ result_team_ids: Optional[List[str]] = result.get("team_ids", [])+ if not result_team_ids:+ team_ids = sso_jwt_handler.get_team_ids_from_jwt(access_token_payload)+ result["team_ids"] = team_ids+ else:+ result_team_ids = getattr(result, "team_ids", []) if result else []+ if not result_team_ids:+ team_ids = sso_jwt_handler.get_team_ids_from_jwt(access_token_payload)+ setattr(result, "team_ids", team_ids)++@router.get("/sso/key/generate", tags=["experimental"], include_in_schema=False)async def google_login(request: Request, source: Optional[str] = None, key: Optional[str] = None@@ -343,19 +379,7 @@ async def get_generic_sso_response()access_token_str: Optional[str] = generic_sso.access_token- if access_token_str and sso_jwt_handler:- import jwt-- access_token_payload = jwt.decode(- access_token_str, options={"verify_signature": False}- )-- result_team_ids: Optional[List[str]] = (- getattr(result, "team_ids", []) if result else []- )- if not result_team_ids:- team_ids = sso_jwt_handler.get_team_ids_from_jwt(access_token_payload)- setattr(result, "team_ids", team_ids)+ process_sso_jwt_access_token(access_token_str, sso_jwt_handler, result)except Exception as e:verbose_proxy_logger.exception(diff --git a/tests/test_litellm/proxy/management_endpoints/test_ui_sso.py b/tests/test_litellm/proxy/management_endpoints/test_ui_sso.pyindex 53cd5a31aff..d72e9f7caa5 100644--- a/tests/test_litellm/proxy/management_endpoints/test_ui_sso.py+++ b/tests/test_litellm/proxy/management_endpoints/test_ui_sso.py@@ -1246,3 +1246,302 @@ class TestCustomUISSO:assert result == mock_redirect_responseassert result.status_code == 303++class TestProcessSSOJWTAccessToken:+ """Test the process_sso_jwt_access_token helper function"""++ @pytest.fixture+ def mock_jwt_handler(self):+ """Create a mock JWT handler for testing"""+ mock_handler = MagicMock(spec=JWTHandler)+ mock_handler.get_team_ids_from_jwt.return_value = ["team1", "team2", "team3"]+ return mock_handler++ @pytest.fixture+ def sample_jwt_token(self):+ """Create a sample JWT token string"""+ return "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"++ @pytest.fixture+ def sample_jwt_payload(self):+ """Create a sample JWT payload"""+ return {+ "sub": "1234567890",+ "name": "John Doe",+ "iat": 1516239022,+ "groups": ["team1", "team2", "team3"]+ }++ 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,+ )++ # Create a result object without team_ids+ result = CustomOpenID(+ id="test_user",+ email="[email protected]",+ first_name="Test",+ last_name="User",+ display_name="Test User",+ provider="generic",+ team_ids=[]+ )++ with patch("jwt.decode", return_value=sample_jwt_payload) as mock_jwt_decode:+ # Act+ process_sso_jwt_access_token(+ access_token_str=sample_jwt_token,+ sso_jwt_handler=mock_jwt_handler,+ result=result+ )++ # Assert+ # Verify JWT was decoded correctly+ 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)++ # Verify team IDs were set on the result object+ assert result.team_ids == ["team1", "team2", "team3"]++ 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,+ )++ # Create a result object with existing team_ids+ existing_team_ids = ["existing_team1", "existing_team2"]+ result = CustomOpenID(+ id="test_user",+ email="[email protected]",+ first_name="Test",+ last_name="User",+ display_name="Test User",+ provider="generic",+ team_ids=existing_team_ids+ )++ with patch("jwt.decode") as mock_jwt_decode:+ # Act+ process_sso_jwt_access_token(+ access_token_str=sample_jwt_token,+ sso_jwt_handler=mock_jwt_handler,+ result=result+ )++ # Assert+ # JWT should still be decoded+ mock_jwt_decode.assert_called_once()++ # But team IDs should NOT be extracted since they already exist+ mock_jwt_handler.get_team_ids_from_jwt.assert_not_called()++ # Existing team IDs should remain unchanged+ assert 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):+ """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"+ }++ with patch("jwt.decode", return_value=sample_jwt_payload) as mock_jwt_decode:+ # Act+ process_sso_jwt_access_token(+ access_token_str=sample_jwt_token,+ sso_jwt_handler=mock_jwt_handler,+ result=result+ )++ # Assert+ mock_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)++ # Verify team_ids was added to the dict as a key+ assert "team_ids" in result+ assert 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):+ """Test that existing team IDs in dictionary are not overwritten"""+ from litellm.proxy.management_endpoints.ui_sso import (+ process_sso_jwt_access_token,+ )++ # Create a dictionary result with existing team_ids+ existing_team_ids = ["dict_team1", "dict_team2"]+ result = {+ "id": "test_user",+ "email": "[email protected]",+ "name": "Test User",+ "team_ids": existing_team_ids+ }++ with patch("jwt.decode") as mock_jwt_decode:+ # Act+ process_sso_jwt_access_token(+ access_token_str=sample_jwt_token,+ sso_jwt_handler=mock_jwt_handler,+ result=result+ )++ # Assert+ # JWT should still be decoded+ mock_jwt_decode.assert_called_once()++ # But team IDs should NOT be extracted since they already exist+ mock_jwt_handler.get_team_ids_from_jwt.assert_not_called()++ # Existing team IDs should remain unchanged+ assert result["team_ids"] == existing_team_ids++ def test_process_sso_jwt_access_token_no_access_token(self, mock_jwt_handler):+ """Test that nothing happens when access token is None or empty"""+ from litellm.proxy.management_endpoints.ui_sso import (+ process_sso_jwt_access_token,+ )++ result = CustomOpenID(+ id="test_user",+ email="[email protected]",+ team_ids=[]+ )++ # Test with None access token+ with patch("jwt.decode") as mock_jwt_decode:+ process_sso_jwt_access_token(+ access_token_str=None,+ sso_jwt_handler=mock_jwt_handler,+ result=result+ )++ # Assert nothing was processed+ mock_jwt_decode.assert_not_called()+ mock_jwt_handler.get_team_ids_from_jwt.assert_not_called()+ assert result.team_ids == []++ # Test with empty string access token+ with patch("jwt.decode") as mock_jwt_decode:+ process_sso_jwt_access_token(+ access_token_str="",+ sso_jwt_handler=mock_jwt_handler,+ result=result+ )++ # Assert nothing was processed+ mock_jwt_decode.assert_not_called()+ mock_jwt_handler.get_team_ids_from_jwt.assert_not_called()+ assert result.team_ids == []++ def test_process_sso_jwt_access_token_no_sso_jwt_handler(self, sample_jwt_token):+ """Test that nothing happens when sso_jwt_handler is None"""+ from litellm.proxy.management_endpoints.ui_sso import (+ process_sso_jwt_access_token,+ )++ result = CustomOpenID(+ id="test_user",+ email="[email protected]",+ team_ids=[]+ )++ with patch("jwt.decode") as mock_jwt_decode:+ # Act+ process_sso_jwt_access_token(+ access_token_str=sample_jwt_token,+ sso_jwt_handler=None,+ result=result+ )++ # Assert nothing was processed+ mock_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):+ """Test that nothing happens when result is None"""+ from litellm.proxy.management_endpoints.ui_sso import (+ process_sso_jwt_access_token,+ )++ with patch("jwt.decode") as mock_jwt_decode:+ # Act+ process_sso_jwt_access_token(+ access_token_str=sample_jwt_token,+ sso_jwt_handler=mock_jwt_handler,+ result=None+ )++ # Assert nothing was processed+ mock_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):+ """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=[]+ )++ with patch("jwt.decode", side_effect=Exception("JWT decode error")) as mock_jwt_decode:+ # Act & Assert+ with 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+ )++ # Verify JWT decode was attempted+ mock_jwt_decode.assert_called_once()+ # But team extraction should not have been called+ mock_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):+ """Test processing when JWT handler returns empty team IDs"""+ from litellm.proxy.management_endpoints.ui_sso import (+ process_sso_jwt_access_token,+ )++ # Configure mock to return empty team IDs+ mock_jwt_handler.get_team_ids_from_jwt.return_value = []++ result = CustomOpenID(+ id="test_user",+ email="[email protected]",+ team_ids=[]+ )++ with patch("jwt.decode", return_value=sample_jwt_payload) as mock_jwt_decode:+ # Act+ process_sso_jwt_access_token(+ access_token_str=sample_jwt_token,+ sso_jwt_handler=mock_jwt_handler,+ result=result+ )++ # Assert+ mock_jwt_decode.assert_called_once()+ mock_jwt_handler.get_team_ids_from_jwt.assert_called_once_with(sample_jwt_payload)++ # Even empty team IDs should be set+ assert result.team_ids == []+