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
add a new feature fix to expose the team alias when authenticating th… (#17725)
saisurya237f3ead2c153a4
diff --git a/.github/workflows/test-linting.yml b/.github/workflows/test-linting.ymlindex 9638c00e453..35ebffeada3 100644--- a/.github/workflows/test-linting.yml+++ b/.github/workflows/test-linting.yml@@ -30,6 +30,7 @@ jobs:- name: Install dependenciesrun: |+ poetry lockpoetry install --with devpoetry run pip install openai==1.100.1diff --git a/.github/workflows/test-litellm.yml b/.github/workflows/test-litellm.ymlindex c7de07aec62..a38a29491ef 100644--- a/.github/workflows/test-litellm.yml+++ b/.github/workflows/test-litellm.yml@@ -27,6 +27,7 @@ jobs:- name: Install dependenciesrun: |+ poetry lockpoetry install --with dev,proxy-dev --extras "proxy semantic-router"poetry run pip install "pytest-retry==1.6.3"poetry run pip install pytest-xdistdiff --git a/.github/workflows/test-mcp.yml b/.github/workflows/test-mcp.ymlindex 2da6980951a..64363c6f96d 100644--- a/.github/workflows/test-mcp.yml+++ b/.github/workflows/test-mcp.yml@@ -27,6 +27,7 @@ jobs:- name: Install dependenciesrun: |+ poetry lockpoetry install --with dev,proxy-dev --extras "proxy semantic-router"poetry run pip install "pytest==7.3.1"poetry run pip install "pytest-retry==1.6.3"diff --git a/litellm/proxy/client/cli/commands/auth.py b/litellm/proxy/client/cli/commands/auth.pyindex 49cbbed4b59..bdc8d56d1c3 100644--- a/litellm/proxy/client/cli/commands/auth.py+++ b/litellm/proxy/client/cli/commands/auth.py@@ -20,60 +20,66 @@ def get_token_file_path() -> str:config_dir.mkdir(exist_ok=True)return str(config_dir / "token.json")+def save_token(token_data: Dict[str, Any]) -> None:"""Save token data to file"""token_file = get_token_file_path()- with open(token_file, 'w') as f:+ with open(token_file, "w") as f:json.dump(token_data, f, indent=2)# Set file permissions to be readable only by owneros.chmod(token_file, 0o600)+def load_token() -> Optional[Dict[str, Any]]:"""Load token data from file"""token_file = get_token_file_path()if not os.path.exists(token_file):return None-+try:- with open(token_file, 'r') as f:+ with open(token_file, "r") as f:return json.load(f)except (json.JSONDecodeError, IOError):return None+def clear_token() -> None:"""Clear stored token"""token_file = get_token_file_path()if os.path.exists(token_file):os.remove(token_file)+def get_stored_api_key() -> Optional[str]:"""Get the stored API key from token file"""# Use the SDK-level utilityfrom litellm.litellm_core_utils.cli_token_utils import get_litellm_gateway_api_key+return get_litellm_gateway_api_key()+# Team selection utilitiesdef display_teams_table(teams: List[Dict[str, Any]]) -> None:"""Display teams in a formatted table"""console = Console()-+if not teams:console.print("❌ No teams found for your user.")return-+table = Table(title="Available Teams")table.add_column("Index", style="cyan", no_wrap=True)table.add_column("Team Alias", style="magenta")table.add_column("Team ID", style="green")table.add_column("Models", style="yellow")table.add_column("Max Budget", style="blue")-+for i, team in enumerate(teams):team_alias = team.get("team_alias") or "N/A"team_id = team.get("team_id", "N/A")models = team.get("models", [])max_budget = team.get("max_budget")-+# Format models listif models:if len(models) > 3:@@ -82,61 +88,57 @@ def display_teams_table(teams: List[Dict[str, Any]]) -> None:models_str = ", ".join(models)else:models_str = "All models"-+# Format budgetbudget_str = f"${max_budget}" if max_budget else "Unlimited"-- table.add_row(- str(i + 1),- team_alias,- team_id,- models_str,- budget_str- )-++ table.add_row(str(i + 1), team_alias, team_id, models_str, budget_str)+console.print(table)def get_key_input():"""Get a single key input from the user (cross-platform)"""try:- if sys.platform == 'win32':+ if sys.platform == "win32":import msvcrt+key = msvcrt.getch()- if key == b'\xe0': # Arrow keys on Windows+ if key == b"\xe0": # Arrow keys on Windowskey = msvcrt.getch()- if key == b'H': # Up arrow- return 'up'- elif key == b'P': # Down arrow- return 'down'- elif key == b'\r': # Enter key- return 'enter'- elif key == b'\x1b': # Escape key- return 'escape'- elif key == b'q':- return 'quit'+ if key == b"H": # Up arrow+ return "up"+ elif key == b"P": # Down arrow+ return "down"+ elif key == b"\r": # Enter key+ return "enter"+ elif key == b"\x1b": # Escape key+ return "escape"+ elif key == b"q":+ return "quit"return Noneelse:import termiosimport tty+fd = sys.stdin.fileno()old_settings = termios.tcgetattr(fd)try:tty.setraw(sys.stdin.fileno())key = sys.stdin.read(1)-- if key == '\x1b': # Escape sequence++ if key == "\x1b": # Escape sequencekey += sys.stdin.read(2)- if key == '\x1b[A': # Up arrow- return 'up'- elif key == '\x1b[B': # Down arrow- return 'down'- elif key == '\x1b': # Just escape- return 'escape'- elif key == '\r' or key == '\n': # Enter key- return 'enter'- elif key == 'q':- return 'quit'+ if key == "\x1b[A": # Up arrow+ return "up"+ elif key == "\x1b[B": # Down arrow+ return "down"+ elif key == "\x1b": # Just escape+ return "escape"+ elif key == "\r" or key == "\n": # Enter key+ return "enter"+ elif key == "q":+ return "quit"return Nonefinally:termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)@@ -145,21 +147,23 @@ def get_key_input():return None-def display_interactive_team_selection(teams: List[Dict[str, Any]], selected_index: int = 0) -> None:+def display_interactive_team_selection(+ teams: List[Dict[str, Any]], selected_index: int = 0+) -> None:"""Display teams with one highlighted for selection"""console = Console()-+# Clear the screen using Rich's methodconsole.clear()-+console.print("🎯 Select a Team (Use ↑↓ arrows, Enter to select, 'q' to skip):\n")-+for i, team in enumerate(teams):team_alias = team.get("team_alias") or "N/A"team_id = team.get("team_id", "N/A")models = team.get("models", [])max_budget = team.get("max_budget")-+# Format models listif models:if len(models) > 3:@@ -168,10 +172,10 @@ def display_interactive_team_selection(teams: List[Dict[str, Any]], selected_indmodels_str = ", ".join(models)else:models_str = "All models"-+# Format budgetbudget_str = f"${max_budget}" if max_budget else "Unlimited"-+# Highlight the selected itemif i == selected_index:console.print(f"➤ [bold cyan]{team_alias}[/bold cyan] ({team_id})")@@ -187,32 +191,34 @@ def prompt_team_selection(teams: List[Dict[str, Any]]) -> Optional[Dict[str, Any"""Interactive team selection with arrow keys"""if not teams:return None-+selected_index = 0-+try:# Check if we can use interactive modeif not sys.stdin.isatty():# Fallback to simple selection for non-interactive environmentsreturn prompt_team_selection_fallback(teams)-+while True:display_interactive_team_selection(teams, selected_index)-+key = get_key_input()-- if key == 'up':++ if key == "up":selected_index = (selected_index - 1) % len(teams)- elif key == 'down':+ elif key == "down":selected_index = (selected_index + 1) % len(teams)- elif key == 'enter':+ elif key == "enter":selected_team = teams[selected_index]# Clear screen and show selectionconsole = Console()console.clear()- click.echo(f"✅ Selected team: {selected_team.get('team_alias', 'N/A')} ({selected_team.get('team_id')})")+ click.echo(+ f"✅ Selected team: {selected_team.get('team_alias', 'N/A')} ({selected_team.get('team_id')})"+ )return selected_team- elif key == 'quit' or key == 'escape':+ elif key == "quit" or key == "escape":# Clear screenconsole = Console()console.clear()@@ -221,7 +227,7 @@ def prompt_team_selection(teams: List[Dict[str, Any]]) -> Optional[Dict[str, Anyelif key is None:# If we can't get key input, fall back to simple selectionreturn prompt_team_selection_fallback(teams)-+except KeyboardInterrupt:console = Console()console.clear()@@ -232,28 +238,34 @@ def prompt_team_selection(teams: List[Dict[str, Any]]) -> Optional[Dict[str, Anyreturn prompt_team_selection_fallback(teams)-def prompt_team_selection_fallback(teams: List[Dict[str, Any]]) -> Optional[Dict[str, Any]]:+def prompt_team_selection_fallback(+ teams: List[Dict[str, Any]]+) -> Optional[Dict[str, Any]]:"""Fallback team selection for non-interactive environments"""if not teams:return None-+while True:try:choice = click.prompt("\nSelect a team by entering the index number (or 'skip' to continue without a team)",- type=str+ type=str,).strip()-- if choice.lower() == 'skip':++ if choice.lower() == "skip":return None-+index = int(choice) - 1if 0 <= index < len(teams):selected_team = teams[index]- click.echo(f"\n✅ Selected team: {selected_team.get('team_alias', 'N/A')} ({selected_team.get('team_id')})")+ click.echo(+ f"\n✅ Selected team: {selected_team.get('team_alias', 'N/A')} ({selected_team.get('team_id')})"+ )return selected_teamelse:- click.echo(f"❌ Invalid selection. Please enter a number between 1 and {len(teams)}")+ click.echo(+ f"❌ Invalid selection. Please enter a number between 1 and {len(teams)}"+ )except ValueError:click.echo("❌ Invalid input. Please enter a number or 'skip'")except KeyboardInterrupt:@@ -263,19 +275,18 @@ def prompt_team_selection_fallback(teams: List[Dict[str, Any]]) -> Optional[Dict# Polling-based authentication - no local server needed-def _poll_for_authentication(- base_url: str, key_id: str-) -> Optional[dict]:++def _poll_for_authentication(base_url: str, key_id: str) -> Optional[dict]:"""Poll the server for authentication completion and handle team selection.-+Returns:Dictionary with authentication data if successful, None otherwise"""poll_url = f"{base_url}/sso/cli/poll/{key_id}"timeout = 300 # 5 minute timeoutpoll_interval = 2 # Poll every 2 seconds-+for attempt in range(timeout // poll_interval):try:response = requests.get(poll_url, timeout=10)@@ -284,25 +295,54 @@ def _poll_for_authentication(if data.get("status") == "ready":# Check if we need team selection firstif data.get("requires_team_selection"):- # Server returned teams list without JWT - need to select team+ # Server returned teams list without JWT - need to select team.+ # Newer servers may also return "team_details" containing+ # objects with both team_id and team_alias. We prefer those+ # for display, but continue to support the legacy list of+ # team IDs for backwards compatibility.teams = data.get("teams", [])+ team_details = data.get("team_details")user_id = data.get("user_id")-- if teams and len(teams) > 1:++ # Build a normalized list of team objects that always have+ # "team_id" and optionally "team_alias".+ normalized_teams: List[Dict[str, Any]] = []+ if isinstance(team_details, list) and team_details:+ for item in team_details:+ if isinstance(item, dict):+ team_id = item.get("team_id") or item.get("id")+ if team_id is None:+ continue+ normalized_teams.append(+ {+ "team_id": team_id,+ "team_alias": item.get("team_alias"),+ }+ )+ elif isinstance(teams, list):+ for t in teams:+ normalized_teams.append(+ {+ "team_id": str(t),+ "team_alias": None,+ }+ )++ if normalized_teams and len(normalized_teams) > 1:# User has multiple teams - let them selectjwt_with_team = _handle_team_selection_during_polling(base_url=base_url,key_id=key_id,- teams=teams+ teams=normalized_teams,)-+# Use the team-specific JWT if selection succeededif jwt_with_team:return {"api_key": jwt_with_team,"user_id": user_id,"teams": teams,- "team_id": None # Set by server in JWT+ "team_id": None, # Set by server in JWT}else:# Selection failed or was skipped - poll again without team_id@@ -318,17 +358,17 @@ def _poll_for_authentication(user_id = data.get("user_id")teams = data.get("teams", [])team_id = data.get("team_id")-+# Show which team was assignedif team_id and len(teams) == 1:click.echo(f"\n✅ Automatically assigned to team: {team_id}")-+if api_key:return {"api_key": api_key,"user_id": user_id,"teams": teams,- "team_id": team_id+ "team_id": team_id,}elif data.get("status") == "pending":# Still pending@@ -336,83 +376,51 @@ def _poll_for_authentication(click.echo("Still waiting for authentication...")else:click.echo(f"Polling error: HTTP {response.status_code}")-+except requests.RequestException as e:if attempt % 10 == 0:click.echo(f"Connection error (will retry): {e}")-+time.sleep(poll_interval)-+# Timeout reachedreturn Nonedef _handle_team_selection_during_polling(- base_url: str, key_id: str, teams: List[str]+ base_url: str, key_id: str, teams: List[Dict[str, Any]]) -> Optional[str]:"""Handle team selection and re-poll with selected team_id.-+Args:teams: List of team IDs (strings)-+Returns:The JWT token with the selected team, or None if selection was skipped"""if not teams:- click.echo("ℹ️ No teams found. You can create or join teams using the web interface.")+ click.echo(+ "ℹ️ No teams found. You can create or join teams using the web interface."+ )return None-- click.echo("\n" + "="*60)++ click.echo("\n" + "=" * 60)click.echo("📋 Select a team for your CLI session...")-- # Display teams as simple list since we only have IDs- console = Console()- table = Table(title="Available Teams")- table.add_column("Index", style="cyan", no_wrap=True)- table.add_column("Team ID", style="green")-- for i, team in enumerate(teams):- table.add_row(str(i + 1), team)-- console.print(table)-- # Simple selection- team_id: Optional[str] = None- while True:- try:- choice = click.prompt(- "\nSelect a team by entering the index number (or 'skip' to use first team)",- type=str- ).strip()-- if choice.lower() == 'skip':- team_id = teams[0] if teams else None- break-- index = int(choice) - 1- if 0 <= index < len(teams):- team_id = teams[index]- break- else:- click.echo(f"❌ Invalid selection. Please enter a number between 1 and {len(teams)}")- except ValueError:- click.echo("❌ Invalid input. Please enter a number or 'skip'")- except KeyboardInterrupt:- click.echo("\n❌ Team selection cancelled.")- return None-++ team_id = _render_and_prompt_for_team_selection(teams)+if not team_id:click.echo("ℹ️ No team selected.")return None-+click.echo(f"\n🔄 Generating JWT for team: {team_id}")-+# Re-poll with team_id to get JWT with correct teamtry:poll_url = f"{base_url}/sso/cli/poll/{key_id}?team_id={team_id}"response = requests.get(poll_url, timeout=10)-+if response.status_code == 200:data = response.json()if data.get("status") == "ready":@@ -420,15 +428,70 @@ def _handle_team_selection_during_polling(if jwt_token:click.echo(f"✅ Successfully generated JWT for team: {team_id}")return jwt_token-+click.echo(f"❌ Failed to get JWT with team. Status: {response.status_code}")return None-+except Exception as e:click.echo(f"❌ Error getting JWT with team: {e}")return None+def _render_and_prompt_for_team_selection(teams: List[Dict[str, Any]]) -> Optional[str]:+ """Render teams table and prompt user for a team selection.++ Returns the selected team_id as a string, or None if selection was+ cancelled or skipped without any teams available.+ """+ # Display teams as a simple list, but prefer showing aliases where+ # available while still keeping the underlying IDs intact.+ console = Console()+ table = Table(title="Available Teams")+ table.add_column("Index", style="cyan", no_wrap=True)+ table.add_column("Team Name", style="magenta")+ table.add_column("Team ID", style="green")++ for i, team in enumerate(teams):+ team_id = str(team.get("team_id"))+ team_alias = team.get("team_alias") or team_id+ table.add_row(str(i + 1), team_alias, team_id)++ console.print(table)++ # Simple selection+ while True:+ try:+ choice = click.prompt(+ "\nSelect a team by entering the index number (or 'skip' to use first team)",+ type=str,+ ).strip()++ if choice.lower() == "skip":+ # Default to the first team's ID if the user skips an+ # explicit selection.+ if teams:+ first_team = teams[0]+ return str(first_team.get("team_id"))+ return None++ index = int(choice) - 1+ if 0 <= index < len(teams):+ selected_team = teams[index]+ team_id = str(selected_team.get("team_id"))+ team_alias = selected_team.get("team_alias") or team_id+ click.echo(f"\n✅ Selected team: {team_alias} ({team_id})")+ return team_id++ click.echo(+ f"❌ Invalid selection. Please enter a number between 1 and {len(teams)}"+ )+ except ValueError:+ click.echo("❌ Invalid input. Please enter a number or 'skip'")+ except KeyboardInterrupt:+ click.echo("\n❌ Team selection cancelled.")+ return None++@click.command(name="login")@click.pass_contextdef login(ctx: click.Context):@@ -436,63 +499,65 @@ def login(ctx: click.Context):from litellm._uuid import uuidfrom litellm.constants import LITELLM_CLI_SOURCE_IDENTIFIERfrom litellm.proxy.client.cli.interface import show_commands-+base_url = ctx.obj["base_url"]-+# Check if we have an existing key to regenerateexisting_key = get_stored_api_key()-+# Generate unique key ID for this login sessionkey_id = f"sk-{str(uuid.uuid4())}"-+try:# Construct SSO login URL with CLI source and pre-generated keysso_url = f"{base_url}/sso/key/generate?source={LITELLM_CLI_SOURCE_IDENTIFIER}&key={key_id}"-+# If we have an existing key, include it as a parameter to the login endpoint# The server will encode it in the OAuth state parameter for the SSO flowif existing_key:sso_url += f"&existing_key={existing_key}"-+click.echo(f"Opening browser to: {sso_url}")click.echo("Please complete the SSO authentication in your browser...")click.echo(f"Session ID: {key_id}")-+# Open browserwebbrowser.open(sso_url)-+# Poll for authentication completionclick.echo("Waiting for authentication...")-+auth_result = _poll_for_authentication(base_url=base_url, key_id=key_id)-+if auth_result:api_key = auth_result["api_key"]user_id = auth_result["user_id"]-+# Save token data (simplified for CLI - we just need the key)- save_token({- 'key': api_key,- 'user_id': user_id or 'cli-user',- 'user_email': 'unknown',- 'user_role': 'cli',- 'auth_header_name': 'Authorization',- 'jwt_token': '',- 'timestamp': time.time()- })-+ save_token(+ {+ "key": api_key,+ "user_id": user_id or "cli-user",+ "user_email": "unknown",+ "user_role": "cli",+ "auth_header_name": "Authorization",+ "jwt_token": "",+ "timestamp": time.time(),+ }+ )+click.echo("\n✅ Login successful!")click.echo(f"JWT Token: {api_key[:20]}...")click.echo("You can now use the CLI without specifying --api-key")-+# Show available commands after successful login- click.echo("\n" + "="*60)+ click.echo("\n" + "=" * 60)show_commands()returnelse:click.echo("❌ Authentication timed out. Please try again.")return-+except KeyboardInterrupt:click.echo("\n❌ Authentication cancelled by user.")return@@ -500,36 +565,39 @@ def login(ctx: click.Context):click.echo(f"❌ Authentication failed: {e}")return+@click.command(name="logout")def logout():"""Logout and clear stored authentication"""clear_token()click.echo("✅ Logged out successfully. Authentication token cleared.")+@click.command(name="whoami")def whoami():"""Show current authentication status"""token_data = load_token()-+if not token_data:click.echo("❌ Not authenticated. Run 'litellm-proxy login' to authenticate.")return-+click.echo("✅ Authenticated")click.echo(f"User Email: {token_data.get('user_email', 'Unknown')}")click.echo(f"User ID: {token_data.get('user_id', 'Unknown')}")click.echo(f"User Role: {token_data.get('user_role', 'Unknown')}")-+# Check if token is still valid (basic timestamp check)- timestamp = token_data.get('timestamp', 0)+ timestamp = token_data.get("timestamp", 0)age_hours = (time.time() - timestamp) / 3600click.echo(f"Token age: {age_hours:.1f} hours")-+if age_hours > 24:click.echo("⚠️ Warning: Token is more than 24 hours old and may have expired.")+# Export functions for use by other CLI commands-__all__ = ['login', 'logout', 'whoami', 'prompt_team_selection']+__all__ = ["login", "logout", "whoami", "prompt_team_selection"]# Export individual commands instead of grouping them-# login, logout, and whoami will be added as top-level commands\ No newline at end of file+# login, logout, and whoami will be added as top-level commandsdiff --git a/litellm/proxy/management_endpoints/ui_sso.py b/litellm/proxy/management_endpoints/ui_sso.pyindex c8f58713cda..fea797d9cc6 100644--- a/litellm/proxy/management_endpoints/ui_sso.py+++ b/litellm/proxy/management_endpoints/ui_sso.py@@ -558,6 +558,7 @@ async def get_user_info_from_db(return None+def _should_use_role_from_sso_response(sso_role: Optional[str]) -> bool:"""returns true if SSO upsert should use the 'role' defined on the SSO response"""if sso_role is None:@@ -621,15 +622,21 @@ def apply_user_info_values_to_sso_user_defined_values(# This ensures SSO is the authoritative source for user rolessso_role = user_defined_values.get("user_role")db_role = user_info.user_role if user_info else None-+if _should_use_role_from_sso_response(sso_role):# SSO provided a valid role, keep it and log that we're using it- verbose_proxy_logger.info(f"Using SSO role: {sso_role} (DB role was: {db_role})")+ verbose_proxy_logger.info(+ f"Using SSO role: {sso_role} (DB role was: {db_role})"+ )else:# SSO didn't provide a valid role, fall back to DB role or defaultif user_info is None or user_info.user_role is None:- user_defined_values["user_role"] = LitellmUserRoles.INTERNAL_USER_VIEW_ONLY.value- verbose_proxy_logger.debug("No SSO or DB role found, using default: INTERNAL_USER_VIEW_ONLY")+ user_defined_values[+ "user_role"+ ] = LitellmUserRoles.INTERNAL_USER_VIEW_ONLY.value+ verbose_proxy_logger.debug(+ "No SSO or DB role found, using default: INTERNAL_USER_VIEW_ONLY"+ )else:user_defined_values["user_role"] = user_info.user_roleverbose_proxy_logger.debug(f"Using DB role: {user_info.user_role}")@@ -837,12 +844,39 @@ async def cli_sso_callback(if hasattr(user_info, "teams") and user_info.teams:teams = user_info.teams if isinstance(user_info.teams, list) else []+ # Also fetch team aliases for a better CLI UX. We keep the original+ # "teams" list of IDs for backwards compatibility and add an+ # optional "team_details" field containing objects with both+ # team_id and team_alias.+ team_details: List[Dict[str, Any]] = []+ try:+ if teams:+ prisma_teams = await prisma_client.db.litellm_teamtable.find_many(+ where={"team_id": {"in": teams}}+ )+ for team_row in prisma_teams:+ team_dict = team_row.model_dump()+ team_details.append(+ {+ "team_id": team_dict.get("team_id"),+ "team_alias": team_dict.get("team_alias"),+ }+ )+ except Exception as e:+ # If anything goes wrong here, fall back gracefully without+ # impacting the SSO flow.+ verbose_proxy_logger.error(+ f"Error fetching team details for CLI SSO session: {e}"+ )+session_data = {"user_id": user_info.user_id,"user_role": user_info.user_role,"models": user_info.models if hasattr(user_info, "models") else [],"user_email": parsed_openid_result.get("user_email"),"teams": teams,+ # Optional rich metadata for clients that want nicer display+ "team_details": team_details,}cache_key = f"{CLI_SSO_SESSION_CACHE_KEY_PREFIX}:{key}"@@ -873,11 +907,11 @@ async def cli_sso_callback(async def cli_poll_key(key_id: str, team_id: Optional[str] = None):"""CLI polling endpoint - retrieves session from cache and generates JWT.-+Flow:1. First poll (no team_id): Returns teams list without generating JWT2. Second poll (with team_id): Generates JWT with selected team and deletes session-+Args:key_id: The session key IDteam_id: Optional team ID to assign to the JWT. If provided, must be one of user's teams.@@ -896,25 +930,38 @@ async def cli_poll_key(key_id: str, team_id: Optional[str] = None):if session_data:user_teams = session_data.get("teams", [])+ user_team_details = session_data.get("team_details")user_id = session_data["user_id"]-+verbose_proxy_logger.info(f"CLI poll: user={user_id}, team_id={team_id}, user_teams={user_teams}, num_teams={len(user_teams)}")-+# If no team_id provided and user has teams, return teams list for selection- # Don't generate JWT yet - let CLI select a team first+ # Don't generate JWT yet - let CLI select a team first. For newer+ # clients we return rich team details (id + alias); older clients+ # can continue to rely on the simple "teams" list.if team_id is None and len(user_teams) > 1:verbose_proxy_logger.info(f"Returning teams list for user {user_id} to select from: {user_teams}")+ # Best-effort construction of team_details if it wasn't+ # already cached for some reason.+ team_details_response: Optional[List[Dict[str, Any]]] = None+ if isinstance(user_team_details, list) and user_team_details:+ team_details_response = user_team_details+ elif user_teams:+ team_details_response = [+ {"team_id": t, "team_alias": None} for t in user_teams+ ]return {"status": "ready","user_id": user_id,"teams": user_teams,+ "team_details": team_details_response,"requires_team_selection": True,}-+# Validate team_id if providedif team_id is not None:if team_id not in user_teams:@@ -952,6 +999,9 @@ async def cli_poll_key(key_id: str, team_id: Optional[str] = None):"user_id": user_id,"team_id": team_id,"teams": user_teams,+ # Echo back any team details we have so clients can+ # present nicer information if needed.+ "team_details": user_team_details,}else:return {"status": "pending"}@@ -996,9 +1046,9 @@ async def insert_sso_user(if user_defined_values.get("max_budget") is None:user_defined_values["max_budget"] = litellm.max_internal_user_budgetif user_defined_values.get("budget_duration") is None:- user_defined_values["budget_duration"] = (- litellm.internal_user_budget_duration- )+ user_defined_values[+ "budget_duration"+ ] = litellm.internal_user_budget_durationif user_defined_values["user_role"] is None:user_defined_values["user_role"] = LitellmUserRoles.INTERNAL_USER_VIEW_ONLY@@ -1217,11 +1267,12 @@ class SSOAuthenticationHandler:# or a cryptographicly signed state that we can verify stateless# For simplification we are using a static state, this is not perfect but some# SSO providers do not allow stateless verification- redirect_params, code_verifier = (- SSOAuthenticationHandler._get_generic_sso_redirect_params(- state=state,- generic_authorization_endpoint=generic_authorization_endpoint,- )+ (+ redirect_params,+ code_verifier,+ ) = SSOAuthenticationHandler._get_generic_sso_redirect_params(+ state=state,+ generic_authorization_endpoint=generic_authorization_endpoint,)# Separate PKCE params from state params (fastapi-sso doesn't accept code_challenge)@@ -1238,7 +1289,6 @@ class SSOAuthenticationHandler:# If PKCE is enabled, add PKCE parameters to the redirect URLif code_verifier and "state" in redirect_params:-# Store code_verifier in cache (10 min TTL)cache_key = f"pkce_verifier:{redirect_params['state']}"user_api_key_cache.set_cache(@@ -1318,9 +1368,10 @@ class SSOAuthenticationHandler:# Set GENERIC_CLIENT_USE_PKCE=true to enable PKCE for enhanced OAuth securityuse_pkce = os.getenv("GENERIC_CLIENT_USE_PKCE", "false").lower() == "true"if use_pkce:- code_verifier, code_challenge = (- SSOAuthenticationHandler.generate_pkce_params()- )+ (+ code_verifier,+ code_challenge,+ ) = SSOAuthenticationHandler.generate_pkce_params()redirect_params["code_challenge"] = code_challengeredirect_params["code_challenge_method"] = "S256"verbose_proxy_logger.debug(@@ -1610,8 +1661,14 @@ class SSOAuthenticationHandler:_user_role = getattr(result, "user_role", None)if _user_role is not None:# Convert enum to string if needed- user_role = _user_role.value if isinstance(_user_role, LitellmUserRoles) else _user_role- verbose_proxy_logger.debug(f"Extracted user_role from SSO result: {user_role}")+ user_role = (+ _user_role.value+ if isinstance(_user_role, LitellmUserRoles)+ else _user_role+ )+ verbose_proxy_logger.debug(+ f"Extracted user_role from SSO result: {user_role}"+ )# generic client id - override with custom attribute name if specifiedif generic_client_id is not None and result is not None:@@ -1984,9 +2041,9 @@ class MicrosoftSSOHandler:# if user is trying to get the raw sso response for debugging, return the raw sso responseif return_raw_sso_response:- original_msft_result[MicrosoftSSOHandler.GRAPH_API_RESPONSE_KEY] = (- user_team_ids- )+ original_msft_result[+ MicrosoftSSOHandler.GRAPH_API_RESPONSE_KEY+ ] = user_team_idsoriginal_msft_result["app_roles"] = app_rolesreturn original_msft_result or {}@@ -2103,9 +2160,9 @@ class MicrosoftSSOHandler:# Fetch user membership from Microsoft Graph APIall_group_ids = []- next_link: Optional[str] = (- MicrosoftSSOHandler.graph_api_user_groups_endpoint- )+ next_link: Optional[+ str+ ] = MicrosoftSSOHandler.graph_api_user_groups_endpointauth_headers = {"Authorization": f"Bearer {access_token}"}page_count = 0diff --git a/poetry.lock b/poetry.lockindex fdfa86a9935..dea637fa14b 100644--- a/poetry.lock+++ b/poetry.lock@@ -1,4 +1,4 @@-# This file is automatically @generated by Poetry 2.2.0 and should not be changed by hand.+# This file is automatically @generated by Poetry 2.2.1 and should not be changed by hand.[[package]]name = "aiofiles"@@ -3089,15 +3089,15 @@ files = [[[package]]name = "litellm-proxy-extras"-version = "0.4.11"+version = "0.4.12"description = "Additional files for the LiteLLM Proxy. Reduces the size of the main litellm package."optional = truepython-versions = "!=2.7.*,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*,!=3.7.*,>=3.8"groups = ["main"]markers = "extra == \"proxy\""files = [- {file = "litellm_proxy_extras-0.4.11-py3-none-any.whl", hash = "sha256:ef63f497e46b2ed856c6e94802357b34ffcf29bef77c9993081fb355bba2f1e4"},- {file = "litellm_proxy_extras-0.4.11.tar.gz", hash = "sha256:847b630827b0980d9a4505ae124f1a56902e4b4e1e6fdd90f831614b5a87447e"},+ {file = "litellm_proxy_extras-0.4.12-py3-none-any.whl", hash = "sha256:3ac2b5ba05d60d41bceab8f140cff5cd292220a48a6079fd8f89cb12fd664051"},+ {file = "litellm_proxy_extras-0.4.12.tar.gz", hash = "sha256:2d7eab8c0f0daa27a2cc774b648ed48eb3321f65fb34b270f4580820f75ce3d8"},][[package]]@@ -7989,4 +7989,4 @@ utils = ["numpydoc"][metadata]lock-version = "2.1"python-versions = ">=3.9,<4.0"-content-hash = "60d89f77574f1ef4107a944b78e59988fa9e4e2400143b4ade3b8fbd436cb65c"+content-hash = "fec0ac9f9222e9952c6244bf874fac20201ac1e14e435d3201611ab4f882c4d7"diff --git a/tests/test_litellm/proxy/client/cli/test_auth_commands.py b/tests/test_litellm/proxy/client/cli/test_auth_commands.pyindex 6e374cea47f..fa0fc5d0e6a 100644--- a/tests/test_litellm/proxy/client/cli/test_auth_commands.py+++ b/tests/test_litellm/proxy/client/cli/test_auth_commands.py@@ -459,7 +459,13 @@ class TestCLIKeyRegenerationFlow:"status": "ready","requires_team_selection": True,"user_id": "test-user-456",- "teams": ["team-alpha", "team-beta", "team-gamma"]+ "teams": ["team-alpha", "team-beta", "team-gamma"],+ # New richer response with team details including aliases+ "team_details": [+ {"team_id": "team-alpha", "team_alias": "Alpha Team"},+ {"team_id": "team-beta", "team_alias": "Beta Team"},+ {"team_id": "team-gamma", "team_alias": "Gamma Team"},+ ],}# Mock second response after team selection - JWT with selected team@@ -486,6 +492,8 @@ class TestCLIKeyRegenerationFlow:assert result.exit_code == 0assert "✅ Login successful!" in result.outputassert "team-beta" in result.output+ # Ensure we surface the human-readable team alias to the user+ assert "Beta Team" in result.output# Verify browser was openedmock_browser.assert_called_once()