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
fix(ui_sso): resolve highest privilege Entra app role, not first in claim (#36728)
Imran Ismail02dcc4d34704
diff --git a/litellm/proxy/management_endpoints/ui_sso.py b/litellm/proxy/management_endpoints/ui_sso.pyindex 0c8240b3298..613508da22b 100644--- a/litellm/proxy/management_endpoints/ui_sso.py+++ b/litellm/proxy/management_endpoints/ui_sso.py@@ -808,6 +808,15 @@ def normalize_email(email: str | None) -> str | None:return email.lower() if isinstance(email, str) else email+# Ordered highest to lowest privilege+LITELLM_USER_ROLE_HIERARCHY: Final = (+ LitellmUserRoles.PROXY_ADMIN,+ LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY,+ LitellmUserRoles.INTERNAL_USER,+ LitellmUserRoles.INTERNAL_USER_VIEW_ONLY,+)++def determine_role_from_groups(user_groups: list[str],role_mappings: "RoleMappings",@@ -832,19 +841,11 @@ def determine_role_from_groups(# No role mappings configured, return default_rolereturn role_mappings.default_role- # Role hierarchy (highest to lowest)- role_hierarchy: Final = [- LitellmUserRoles.PROXY_ADMIN,- LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY,- LitellmUserRoles.INTERNAL_USER,- LitellmUserRoles.INTERNAL_USER_VIEW_ONLY,- ]-# Convert user_groups to a set for efficient lookupuser_groups_set: Final = set(user_groups) if isinstance(user_groups, list) else set()# Find the highest privilege role the user belongs to- for role in role_hierarchy:+ for role in LITELLM_USER_ROLE_HIERARCHY:if role in role_mappings.roles:role_groups = role_mappings.roles[role]if isinstance(role_groups, list) and user_groups_set.intersection(set(role_groups)):@@ -4236,15 +4237,7 @@ class MicrosoftSSOHandler:verbose_proxy_logger.debug("Extracted app roles from id_token: %s", app_roles)# Combine groups and app roles- user_role: LitellmUserRoles | None = None- if app_roles:- # Check if any app role is a valid LitellmUserRoles- for role_str in app_roles:- role = get_litellm_user_role(role_str)- if role is not None:- user_role = role- verbose_proxy_logger.debug("Found valid LitellmUserRoles '%s' in app_roles", role.value)- break+ user_role: Final = MicrosoftSSOHandler.get_user_role_from_app_roles(app_roles)verbose_proxy_logger.debug("Combined team_ids (groups + app roles): %s", user_team_ids)@@ -4282,6 +4275,27 @@ class MicrosoftSSOHandler:verbose_proxy_logger.debug("Microsoft SSO OpenID Response: %s", openid_response)return openid_response+ @staticmethod+ def get_user_role_from_app_roles(+ app_roles: Sequence[str] | None,+ ) -> LitellmUserRoles | None:+ """+ Resolve the one role LiteLLM stores for a user from their Entra app roles.++ Entra does not guarantee `roles` claim ordering, so a user holding several app+ roles resolves to the highest privilege one rather than whichever the claim+ listed first. Roles the hierarchy does not rank (org_admin, team, customer)+ resolve by name to stay deterministic+ """+ resolved: Final = frozenset(+ role for role in (get_litellm_user_role(role_str) for role_str in app_roles or ()) if role is not None+ )+ if not resolved:+ return None++ ranked: Final = next((role for role in LITELLM_USER_ROLE_HIERARCHY if role in resolved), None)+ return ranked if ranked is not None else min(resolved, key=lambda role: role.value)+@staticmethoddef get_app_roles_from_id_token(id_token: str | None) -> list[str]:"""diff --git a/tests/test_litellm/proxy/management_endpoints/test_entraid_app_roles.py b/tests/test_litellm/proxy/management_endpoints/test_entraid_app_roles.pyindex 2ce36b73de0..0c3fe175b48 100644--- a/tests/test_litellm/proxy/management_endpoints/test_entraid_app_roles.py+++ b/tests/test_litellm/proxy/management_endpoints/test_entraid_app_roles.py@@ -1,91 +1,120 @@import jwt+import pytest-from litellm.proxy.management_endpoints.ui_sso import MicrosoftSSOHandler-from litellm.proxy.management_endpoints.types import get_litellm_user_rolefrom litellm.proxy._types import LitellmUserRoles+from litellm.proxy.management_endpoints.ui_sso import MicrosoftSSOHandler-def test_extracts_proxy_admin_role_from_jwt():- """Ensure supported app roles like 'proxy_admin' are extracted from the id_token."""+def _id_token(**claims) -> str:+ """Build a signed id_token carrying the given claims."""payload = {"sub": "user123",- "email": "[email protected]",- "app_roles": ["proxy_admin"],+ "email": "[email protected]","aud": "litellm-app","iss": "https://login.microsoftonline.com/tenant-id/v2.0","exp": 9999999999,+ **claims,}+ return jwt.encode(payload, "secret", algorithm="HS256")+++def test_extracts_proxy_admin_role_from_jwt():+ """Ensure supported app roles like 'proxy_admin' are extracted from the id_token."""+ token = _id_token(app_roles=["proxy_admin"])- token = jwt.encode(payload, "secret", algorithm="HS256")roles = MicrosoftSSOHandler.get_app_roles_from_id_token(token)assert roles == ["proxy_admin"]-def test_maps_internal_user_role():- """Ensure internal_user role is correctly mapped to LitellmUserRoles."""- payload = {- "sub": "user456",- "email": "[email protected]",- "app_roles": ["internal_user"],- "aud": "litellm-app",- "iss": "https://login.microsoftonline.com/tenant-id/v2.0",- "exp": 9999999999,- }+def test_extracts_app_roles_from_roles_claim():+ """Entra emits app role values in the `roles` claim; both spellings are read."""+ token = _id_token(roles=["internal_user"])- token = jwt.encode(payload, "secret", algorithm="HS256")roles = MicrosoftSSOHandler.get_app_roles_from_id_token(token)- # Map to LitellmUserRoles- chosen = None- for r in roles:- mapped = get_litellm_user_role(r)- if mapped is not None:- chosen = mapped- break-- assert chosen == LitellmUserRoles.INTERNAL_USER+ assert roles == ["internal_user"]+++ "app_roles, expected",+ [+ (["proxy_admin"], LitellmUserRoles.PROXY_ADMIN),+ (["proxy_admin_viewer"], LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY),+ (["internal_user"], LitellmUserRoles.INTERNAL_USER),+ (["internal_user_viewer"], LitellmUserRoles.INTERNAL_USER_VIEW_ONLY),+ # Case-insensitive, matching get_litellm_user_role.+ (["PROXY_ADMIN_VIEWER"], LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY),+ # Roles outside the privilege hierarchy still resolve.+ (["org_admin"], LitellmUserRoles.ORG_ADMIN),+ ],+)+def test_maps_single_app_role(app_roles, expected):+ """A lone app role maps to its LitellmUserRoles equivalent."""+ assert MicrosoftSSOHandler.get_user_role_from_app_roles(app_roles) == expected+++ "app_roles",+ [+ ["internal_user", "proxy_admin_viewer"],+ ["proxy_admin_viewer", "internal_user"],+ ],+)+def test_highest_privilege_role_wins_regardless_of_claim_order(app_roles):+ """+ A user in one group mapped to `internal_user` and another mapped to+ `proxy_admin_viewer` gets the higher privilege role either way.++ Entra does not guarantee the ordering of the `roles` claim, so the resolved+ role must not depend on it.+ """+ assert MicrosoftSSOHandler.get_user_role_from_app_roles(app_roles) == (LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY)+++ "app_roles",+ [+ ["internal_user", "proxy_admin_viewer", "proxy_admin"],+ ["proxy_admin", "proxy_admin_viewer", "internal_user"],+ ["proxy_admin_viewer", "internal_user", "proxy_admin"],+ ],+)+def test_proxy_admin_beats_every_other_role(app_roles):+ """proxy_admin outranks every other role in the hierarchy, in any claim order."""+ assert MicrosoftSSOHandler.get_user_role_from_app_roles(app_roles) == LitellmUserRoles.PROXY_ADMIN+++def test_unrecognised_app_roles_are_ignored():+ """App roles that are not LitellmUserRoles values do not shadow ones that are."""+ app_roles = ["Some.Custom.Role", "msiam_access", "internal_user"]++ assert MicrosoftSSOHandler.get_user_role_from_app_roles(app_roles) == LitellmUserRoles.INTERNAL_USER++[email protected]("app_roles", [None, [], ["msiam_access"], ["User"]])+def test_returns_none_when_no_role_resolves(app_roles):+ """+ Returning None lets the caller keep the user's stored role or apply+ default_internal_user_params, rather than forcing a role.+ """+ assert MicrosoftSSOHandler.get_user_role_from_app_roles(app_roles) is None+++def test_no_role_claim_yields_no_app_roles():+ """An id_token with no role claim produces no app roles, and so no role."""+ token = _id_token()--def test_maps_proxy_admin_viewer_role():- """Ensure proxy_admin_viewer role is correctly mapped."""- payload = {- "sub": "user789",- "email": "[email protected]",- "app_roles": ["proxy_admin_viewer"],- "aud": "litellm-app",- "iss": "https://login.microsoftonline.com/tenant-id/v2.0",- "exp": 9999999999,- }-- token = jwt.encode(payload, "secret", algorithm="HS256")roles = MicrosoftSSOHandler.get_app_roles_from_id_token(token)- chosen = None- for r in roles:- mapped = get_litellm_user_role(r)- if mapped is not None:- chosen = mapped- break-- assert chosen == LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY+ assert roles == []+ assert MicrosoftSSOHandler.get_user_role_from_app_roles(roles) is None-def test_defaults_to_internal_user_viewer_when_no_role():- """Ensure default role is internal_user_viewer when no app role is present."""- payload = {- "sub": "user_no_role",- "email": "[email protected]",- "aud": "litellm-app",- "iss": "https://login.microsoftonline.com/tenant-id/v2.0",- "exp": 9999999999,- }+def test_end_to_end_from_id_token_to_role():+ """The id_token -> role path resolves the highest privilege role."""+ token = _id_token(roles=["internal_user", "proxy_admin_viewer"])- token = jwt.encode(payload, "secret", algorithm="HS256")roles = MicrosoftSSOHandler.get_app_roles_from_id_token(token)- assert roles == []-- # Default role would be internal_user_viewer- default_role = LitellmUserRoles.INTERNAL_USER_VIEW_ONLY- assert default_role.value == "internal_user_viewer"+ assert MicrosoftSSOHandler.get_user_role_from_app_roles(roles) == LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY