Skip to content

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]

Add Kubernetes ServiceAccount JWT authentication support (#18055)

Lukas de Boeredc8413f1e51
diff --git a/docs/my-website/docs/proxy/token_auth.md b/docs/my-website/docs/proxy/token_auth.md
index fe928a596cf..78cd144d56d 100644
--- a/docs/my-website/docs/proxy/token_auth.md
+++ b/docs/my-website/docs/proxy/token_auth.md
@@ -114,6 +114,189 @@ Set `JWT_PUBLIC_KEY_URL` in your environment to a comma-separated list of URLs f
export JWT_PUBLIC_KEY_URL="https://demo.duendesoftware.com/.well-known/openid-configuration/jwks,https://accounts.google.com/.well-known/openid-configuration/jwks"
```
+### Kubernetes ServiceAccount Authentication
+
+Use Kubernetes ServiceAccount tokens to authenticate workloads running in your cluster. This is useful when you want pods to authenticate to LiteLLM using their native Kubernetes identity.
+
+#### Prerequisites
+
+1. Your Kubernetes cluster must have ServiceAccount token projection enabled (default in Kubernetes 1.20+)
+2. Your cluster's OIDC issuer must be accessible (for EKS, GKE, AKS this is automatic)
+
+#### Step 1: Configure the OIDC Discovery URL
+
+Set `JWT_PUBLIC_KEY_URL` to your cluster's OIDC discovery endpoint:
+
+<Tabs>
+<TabItem value="eks" label="Amazon EKS">
+
+```bash
+# Get your EKS OIDC issuer URL
+aws eks describe-cluster --name <cluster-name> --query "cluster.identity.oidc.issuer" --output text
+
+# Set the JWKS URL (append /keys to the issuer URL)
+export JWT_PUBLIC_KEY_URL="https://oidc.eks.<region>.amazonaws.com/id/<id>/keys"
+```
+
+</TabItem>
+<TabItem value="gke" label="Google GKE">
+
+```bash
+# GKE uses Google's OIDC provider
+export JWT_PUBLIC_KEY_URL="https://container.googleapis.com/v1/projects/<project>/locations/<location>/clusters/<cluster>/jwks"
+```
+
+</TabItem>
+<TabItem value="aks" label="Azure AKS">
+
+```bash
+# Get your AKS OIDC issuer URL
+az aks show --name <cluster-name> --resource-group <resource-group> --query "oidcIssuerProfile.issuerUrl" -o tsv
+
+# Set the JWKS URL
+export JWT_PUBLIC_KEY_URL="<issuer-url>/openid/v1/jwks"
+```
+
+</TabItem>
+<TabItem value="self-managed" label="Self-Managed">
+
+```bash
+# For self-managed clusters, check your API server's --service-account-issuer flag
+# The JWKS endpoint is typically at:
+export JWT_PUBLIC_KEY_URL="https://<api-server>/openid/v1/jwks"
+```
+
+</TabItem>
+</Tabs>
+
+#### Step 2: Configure LiteLLM
+
+Configure LiteLLM to extract identity information from Kubernetes ServiceAccount tokens:
+
+```yaml
+general_settings:
+ enable_jwt_auth: True
+ litellm_jwtauth:
+ # Use namespace as team identifier (resolves via team_alias in DB)
+ team_alias_jwt_field: "kubernetes\.io.namespace"
+```
+
+#### Step 3: Create ServiceAccount and Configure Pod
+
+Create a ServiceAccount with an associated secret and configure your pod to use the token:
+
+```yaml
+apiVersion: v1
+kind: ServiceAccount
+metadata:
+ name: my-llm-client
+ namespace: my-app
+---
+apiVersion: v1
+kind: Secret
+metadata:
+ name: my-llm-client-token
+ namespace: my-app
+ annotations:
+ kubernetes.io/service-account.name: my-llm-client
+type: kubernetes.io/service-account-token
+---
+apiVersion: v1
+kind: Pod
+metadata:
+ name: llm-client-pod
+ namespace: my-app
+spec:
+ serviceAccountName: my-llm-client
+ containers:
+ - name: app
+ image: my-app:latest
+ env:
+ - name: LITELLM_TOKEN
+ valueFrom:
+ secretKeyRef:
+ name: my-llm-client-token
+ key: token
+```
+
+Set the expected audience in LiteLLM:
+
+```bash
+export JWT_AUDIENCE="https://kubernetes.default.svc"
+```
+
+#### Step 4: Create Team for Namespace
+
+Create a team in LiteLLM that matches the namespace (using `team_alias`):
+
+```bash
+curl -X POST 'http://0.0.0.0:4000/team/new' \
+-H 'Authorization: Bearer <PROXY_MASTER_KEY>' \
+-H 'Content-Type: application/json' \
+-d '{
+ "team_alias": "my-app",
+ "team_id": "my-app",
+ "models": ["gpt-4", "claude-sonnet-4-20250514"]
+}'
+```
+
+#### Step 5: Use the Token
+
+From within the pod, the token is available in the `LITELLM_TOKEN` environment variable:
+
+```bash
+# Make a request to LiteLLM using the env var
+curl -X POST 'http://0.0.0.0:4000/v1/chat/completions' \
+-H 'Content-Type: application/json' \
+-H "Authorization: Bearer $LITELLM_TOKEN" \
+-d '{
+ "model": "gpt-4",
+ "messages": [{"role": "user", "content": "Hello!"}]
+}'
+```
+
+#### Example: ServiceAccount Token Structure
+
+A Kubernetes ServiceAccount token looks like this:
+
+```json
+{
+ "aud": ["litellm-proxy"],
+ "exp": 1234567890,
+ "iat": 1234567890,
+ "iss": "https://oidc.eks.us-west-2.amazonaws.com/id/EXAMPLE",
+ "kubernetes.io": {
+ "namespace": "my-app",
+ "pod": {
+ "name": "llm-client-pod",
+ "uid": "pod-uid"
+ },
+ "serviceaccount": {
+ "name": "my-llm-client",
+ "uid": "sa-uid"
+ }
+ },
+ "nbf": 1234567890,
+ "sub": "system:serviceaccount:my-app:my-llm-client"
+}
+```
+
+#### Advanced: Map Namespace to Team Using Name Resolution
+
+Use the `team_alias_jwt_field` to automatically resolve namespaces to teams:
+
+```yaml
+general_settings:
+ enable_jwt_auth: True
+ litellm_jwtauth:
+ user_id_jwt_field: "sub"
+ # Map the namespace to team_alias in the database
+ team_alias_jwt_field: "kubernetes\.io.namespace"
+ user_id_upsert: true
+```
+
+This way, pods in namespace `production` automatically get associated with the team that has `team_alias: production`.
+
### Set Accepted JWT Scope Names
Change the string in JWT 'scopes', that litellm evaluates to see if a user has admin access.
@@ -183,6 +366,62 @@ litellm_jwtauth:
Now litellm will automatically update the spend for the user/team/org in the db for each call.
+### Resolve by Name (Alias) Instead of ID
+
+Sometimes your JWT token contains human-readable names instead of database IDs. LiteLLM can resolve these names to IDs by looking them up in the database.
+
+**Use Case:** Your IDP provides team/org names in the JWT, but LiteLLM needs the actual database IDs for spend tracking and access control.
+
+```yaml
+general_settings:
+ master_key: sk-1234
+ enable_jwt_auth: True
+ litellm_jwtauth:
+ # Name-based fields (resolved via database lookup)
+ team_alias_jwt_field: "team_alias" # Resolves team by team_alias in DB
+ org_alias_jwt_field: "org_alias" # Resolves org by organization_alias in DB
+```
+
+**Expected JWT:**
+
+```json
+{
+ "sub": "user-123",
+ "team_alias": "engineering-team",
+ "org_alias": "acme-corp"
+}
+```
+
+**How It Works:**
+
+1. LiteLLM extracts the name from the configured JWT field
+2. Looks up the entity in the database by its alias field:
+ - Teams: `team_alias` column in `LiteLLM_TeamTable`
+ - Organizations: `organization_alias` column in `LiteLLM_OrganizationTable`
+3. Uses the resolved ID for spend tracking and access control
+
+**Precedence:** ID fields always take precedence over name fields. If both `team_id_jwt_field` and `team_alias_jwt_field` are configured and both values exist in the JWT, the ID will be used.
+
+```yaml
+# Example: ID takes precedence
+litellm_jwtauth:
+ team_id_jwt_field: "team_id" # Used if present in JWT
+ team_alias_jwt_field: "team_alias" # Fallback if team_id not present
+```
+
+**Nested Fields:** Name fields also support dot notation for nested claims:
+
+```yaml
+litellm_jwtauth:
+ team_alias_jwt_field: "organization.team.name"
+ org_alias_jwt_field: "company.name"
+```
+
+**Important Notes:**
+- The entity (team/org) must already exist in the database with the matching alias
+- Aliases should be unique - if multiple entities share the same alias, an error will be returned
+- Name resolution adds a database lookup, so using IDs directly is slightly more performant
+
### JWT Scopes
Here's what scopes on JWT-Auth tokens look like
diff --git a/litellm/litellm_core_utils/dot_notation_indexing.py b/litellm/litellm_core_utils/dot_notation_indexing.py
index 6e293a4cb77..1e835004e94 100644
--- a/litellm/litellm_core_utils/dot_notation_indexing.py
+++ b/litellm/litellm_core_utils/dot_notation_indexing.py
@@ -9,6 +9,7 @@ Custom implementation with zero external dependencies.
Supported syntax:
- "field" - top-level field
- "parent.child" - nested field
+- "parent\\.with\\.dots.child" - keys containing dots (escape with backslash)
- "array[*]" - all array elements (wildcard)
- "array[0]" - specific array element (index)
- "array[*].field" - field in all array elements
@@ -47,6 +48,9 @@ def get_nested_value(
'value'
>>> get_nested_value(data, "a.b.d", "default")
'default'
+ >>> data = {"kubernetes.io": {"namespace": "default"}}
+ >>> get_nested_value(data, "kubernetes\\.io.namespace")
+ 'default'
"""
if not key_path:
return default
@@ -58,8 +62,11 @@ def get_nested_value(
else key_path
)
- # Split the key path into parts
- parts = key_path.split(".")
+ # Split the key path into parts, respecting escaped dots (\.)
+ # Use a temporary placeholder, split on unescaped dots, then restore
+ placeholder = "\x00"
+ parts = key_path.replace("\\.", placeholder).split(".")
+ parts = [p.replace(placeholder, ".") for p in parts]
# Traverse through the dictionary
current: Any = data
diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.py
index a94b4d4a077..77f9290cdca 100644
--- a/litellm/proxy/_types.py
+++ b/litellm/proxy/_types.py
@@ -3561,8 +3561,16 @@ class LiteLLM_JWTAuth(LiteLLMPydanticObjectBase):
default=None,
description="If no team_id given, default permissions/spend-tracking to this team.s",
)
+ team_alias_jwt_field: Optional[str] = Field(
+ default=None,
+ description="The field in the JWT token that stores the team name/alias. Will be resolved to team_id via database lookup.",
+ )
org_id_jwt_field: Optional[str] = None
+ org_alias_jwt_field: Optional[str] = Field(
+ default=None,
+ description="The field in the JWT token that stores the organization name/alias. Will be resolved to org_id via database lookup.",
+ )
user_id_jwt_field: Optional[str] = None
user_email_jwt_field: Optional[str] = None
user_allowed_email_domain: Optional[str] = None
diff --git a/litellm/proxy/auth/auth_checks.py b/litellm/proxy/auth/auth_checks.py
index e2e90abeb1b..de4973ecc69 100644
--- a/litellm/proxy/auth/auth_checks.py
+++ b/litellm/proxy/auth/auth_checks.py
@@ -1372,6 +1372,195 @@ async def get_team_object(
)
+@log_db_metrics
+async def get_team_object_by_alias(
+ team_alias: str,
+ prisma_client: Optional[PrismaClient],
+ user_api_key_cache: DualCache,
+ parent_otel_span: Optional["Span"] = None,
+ proxy_logging_obj: Optional[ProxyLogging] = None,
+) -> LiteLLM_TeamTableCachedObj:
+ """
+ Look up a team by its team_alias (name) in the database.
+
+ Args:
+ team_alias: The team name/alias to look up
+ prisma_client: Database client
+ user_api_key_cache: Cache for storing results
+ parent_otel_span: Optional OpenTelemetry span
+ proxy_logging_obj: Optional proxy logging object
+
+ Returns:
+ LiteLLM_TeamTableCachedObj: The team object if found
+
+ Raises:
+ HTTPException: If team doesn't exist or multiple teams have the same alias
+ """
+ if prisma_client is None:
+ raise Exception(
+ "No DB Connected. See - https://docs.litellm.ai/docs/proxy/virtual_keys"
+ )
+
+ # Check cache first (keyed by alias)
+ cache_key = "team_alias:{}".format(team_alias)
+
+ cached_team_obj = await _get_team_object_from_cache(
+ key=cache_key,
+ proxy_logging_obj=proxy_logging_obj,
+ user_api_key_cache=user_api_key_cache,
+ parent_otel_span=parent_otel_span,
+ )
+
+ if cached_team_obj is not None:
+ return cached_team_obj
+
+ # Query database by team_alias
+ try:
+ teams = await prisma_client.db.litellm_teamtable.find_many(
+ where={"team_alias": team_alias}
+ )
+
+ if not teams:
+ raise HTTPException(
+ status_code=404,
+ detail={
+ "error": f"Team with alias '{team_alias}' doesn't exist in db. Create team via `/team/new` call."
+ },
+ )
+
+ if len(teams) > 1:
+ raise HTTPException(
+ status_code=400,
+ detail={
+ "error": f"Multiple teams found with alias '{team_alias}'. Please use team_id_jwt_field instead or ensure team aliases are unique."
+ },
+ )
+
+ team = teams[0]
+ team_obj = LiteLLM_TeamTableCachedObj(**team.model_dump())
+
+ # Cache the result by both alias and team_id
+ await user_api_key_cache.async_set_cache(
+ key=cache_key,
+ value=team_obj,
+ ttl=DEFAULT_IN_MEMORY_TTL,
+ )
+ # Also cache by team_id for consistency
+ team_id_cache_key = "team_id:{}".format(team_obj.team_id)
+ await user_api_key_cache.async_set_cache(
+ key=team_id_cache_key,
+ value=team_obj,
+ ttl=DEFAULT_IN_MEMORY_TTL,
+ )
+
+ return team_obj
+
+ except HTTPException:
+ raise
+ except Exception as e:
+ verbose_proxy_logger.exception(
+ "Error looking up team by alias: %s", team_alias
+ )
+ raise HTTPException(
+ status_code=500,
+ detail={
+ "error": f"Error looking up team by alias '{team_alias}': {str(e)}"
+ },
+ )
+
+
+@log_db_metrics
+async def get_org_object_by_alias(
+ org_alias: str,
+ prisma_client: Optional[PrismaClient],
+ user_api_key_cache: DualCache,
+ parent_otel_span: Optional["Span"] = None,
+ proxy_logging_obj: Optional[ProxyLogging] = None,
+) -> Optional[LiteLLM_OrganizationTable]:
+ """
+ Look up an organization by its organization_alias in the database.
+
+ Args:
+ org_alias: The organization name/alias to look up
+ prisma_client: Database client
+ user_api_key_cache: Cache for storing results
+ parent_otel_span: Optional OpenTelemetry span
+ proxy_logging_obj: Optional proxy logging object
+
+ Returns:
+ LiteLLM_OrganizationTable if found, None otherwise
+
+ Raises:
+ HTTPException: If organization not found or multiple orgs have the same alias
+ """
+ if prisma_client is None:
+ raise Exception(
+ "No DB Connected. See - https://docs.litellm.ai/docs/proxy/virtual_keys"
+ )
+
+ # Check cache first (keyed by alias)
+ cache_key = "org_alias:{}".format(org_alias)
+ cached_org_obj = await user_api_key_cache.async_get_cache(key=cache_key)
+ if cached_org_obj is not None:
+ if isinstance(cached_org_obj, dict):
+ return LiteLLM_OrganizationTable(**cached_org_obj)
+ elif isinstance(cached_org_obj, LiteLLM_OrganizationTable):
+ return cached_org_obj
+
+ # Query database by organization_alias
+ try:
+ orgs = await prisma_client.db.litellm_organizationtable.find_many(
+ where={"organization_alias": org_alias}
+ )
+
+ if not orgs:
+ raise HTTPException(
+ status_code=404,
+ detail={
+ "error": f"Organization with alias '{org_alias}' doesn't exist in db. Create organization via `/organization/new` call."
+ },
+ )
+
+ if len(orgs) > 1:
+ raise HTTPException(
+ status_code=400,
+ detail={
+ "error": f"Multiple organizations found with alias '{org_alias}'. Please use org_id_jwt_field instead or ensure organization aliases are unique."
+ },
+ )
+
+ org = orgs[0]
+ org_obj = LiteLLM_OrganizationTable(**org.model_dump())
+
+ # Cache the result
+ await user_api_key_cache.async_set_cache(
+ key=cache_key,
+ value=org_obj.model_dump(),
+ ttl=DEFAULT_IN_MEMORY_TTL,
+ )
+ # Also cache by org_id for consistency
+ await user_api_key_cache.async_set_cache(
+ key="org_id:{}".format(org_obj.organization_id),
+ value=org_obj.model_dump(),
+ ttl=DEFAULT_IN_MEMORY_TTL,
+ )
+
+ return org_obj
+
+ except HTTPException:
+ raise
+ except Exception as e:
+ verbose_proxy_logger.exception(
+ "Error looking up organization by alias: %s", org_alias
+ )
+ raise HTTPException(
+ status_code=500,
+ detail={
+ "error": f"Error looking up organization by alias '{org_alias}': {str(e)}"
+ },
+ )
+
+
class ExperimentalUIJWTToken:
@staticmethod
def get_experimental_ui_login_jwt_auth_token(user_info: LiteLLM_UserTable) -> str:
diff --git a/litellm/proxy/auth/handle_jwt.py b/litellm/proxy/auth/handle_jwt.py
index 17ff0de9f7b..33667b5d8d9 100644
--- a/litellm/proxy/auth/handle_jwt.py
+++ b/litellm/proxy/auth/handle_jwt.py
@@ -48,10 +48,12 @@ from .auth_checks import (
get_actual_routes,
get_end_user_object,
get_org_object,
+ get_org_object_by_alias,
get_role_based_models,
get_role_based_routes,
get_team_membership,
get_team_object,
+ get_team_object_by_alias,
get_user_object,
)
@@ -194,10 +196,13 @@ class JWTHandler:
def is_required_team_id(self) -> bool:
"""
Returns:
- - True: if 'team_id_jwt_field' is set
- - False: if not
+ - True: if 'team_id_jwt_field' or 'team_alias_jwt_field' is set
+ - False: if neither is set
"""
- if self.litellm_jwtauth.team_id_jwt_field is None:
+ if (
+ self.litellm_jwtauth.team_id_jwt_field is None
+ and self.litellm_jwtauth.team_alias_jwt_field is None
+ ):
return False
return True
@@ -240,6 +245,31 @@ class JWTHandler:
team_id = default_value
return team_id
+ def get_team_alias(self, token: dict, default_value: Optional[str]) -> Optional[str]:
+ """
+ Extract team name/alias from JWT token using the configured team_alias_jwt_field.
+
+ Args:
+ token: The decoded JWT token dictionary
+ default_value: Default value to return if field not found
+
+ Returns:
+ The team alias from the token, or default_value if not found
+ """
+ try:
+ if self.litellm_jwtauth.team_alias_jwt_field is not None:
+ team_alias = get_nested_value(
+ data=token,
+ key_path=self.litellm_jwtauth.team_alias_jwt_field,
+ default=default_value,
+ )
+ return team_alias
+ else:
+ team_alias = None
+ except KeyError:
+ team_alias = default_value
+ return team_alias
+
def is_upsert_user_id(self, valid_user_email: Optional[bool] = None) -> bool:
"""
Returns:
@@ -383,6 +413,31 @@ class JWTHandler:
org_id = default_value
return org_id
+ def get_org_alias(self, token: dict, default_value: Optional[str]) -> Optional[str]:
+ """
+ Extract organization name/alias from JWT token using the configured org_alias_jwt_field.
+
+ Args:
+ token: The decoded JWT token dictionary
+ default_value: Default value to return if field not found
+
+ Returns:
+ The organization alias from the token, or default_value if not found
+ """
+ try:
+ if self.litellm_jwtauth.org_alias_jwt_field is not None:
+ org_alias = get_nested_value(
+ data=token,
+ key_path=self.litellm_jwtauth.org_alias_jwt_field,
+ default=default_value,
+ )
+ return org_alias
+ else:
+ org_alias = None
+ except KeyError:
+ org_alias = default_value
+ return org_alias
+
def get_scopes(self, token: dict) -> List[str]:
try:
if isinstance(token["scope"], str):
@@ -813,18 +868,14 @@ class JWTAuthManager:
parent_otel_span: Optional[Span],
proxy_logging_obj: ProxyLogging,
) -> Tuple[Optional[str], Optional[LiteLLM_TeamTable]]:
- """Find and validate specific team ID"""
+ """Find and validate specific team ID from team_id_jwt_field or team_alias_jwt_field"""
individual_team_id = jwt_handler.get_team_id(
token=jwt_valid_token, default_value=None
)
- if not individual_team_id and jwt_handler.is_required_team_id() is True:
- raise Exception(
- f"No team id found in token. Checked team_id field '{jwt_handler.litellm_jwtauth.team_id_jwt_field}'"
- )
-
- ## VALIDATE TEAM OBJECT ###
team_object: Optional[LiteLLM_TeamTable] = None
+
+ # First try to get team by team_id
if individual_team_id:
team_object = await get_team_object(
team_id=individual_team_id,
@@ -834,6 +885,37 @@ class JWTAuthManager:
proxy_logging_obj=proxy_logging_obj,
team_id_upsert=jwt_handler.litellm_jwtauth.team_id_upsert,
)
+ return individual_team_id, team_object
+
+ # If no team_id found, try to resolve via team_alias_jwt_field
+ team_alias = jwt_handler.get_team_alias(
+ token=jwt_valid_token, default_value=None
+ )
+ if team_alias:
+ verbose_proxy_logger.info(
+ f"JWT Auth: Resolving team by alias: '{team_alias}'"
+ )
+ team_object = await get_team_object_by_alias(
+ team_alias=team_alias,
+ prisma_client=prisma_client,
+ user_api_key_cache=user_api_key_cache,
+ parent_otel_span=parent_otel_span,
+ proxy_logging_obj=proxy_logging_obj,
+ )
+ if team_object:
+ individual_team_id = team_object.team_id
+ verbose_proxy_logger.info(
+ f"JWT Auth: Resolved team_alias='{team_alias}' to team_id='{individual_team_id}'"
+ )
+ return individual_team_id, team_object
+
+ # Check if team is required but not found
+ if jwt_handler.is_required_team_id() is True:
+ team_id_field = jwt_handler.litellm_jwtauth.team_id_jwt_field
+ team_alias_field = jwt_handler.litellm_jwtauth.team_alias_jwt_field
+ raise Exception(
+ f"No team found in token. Checked team_id field '{team_id_field}' and team_alias field '{team_alias_field}'"
+ )
return individual_team_id, team_object
@@ -942,13 +1024,16 @@ class JWTAuthManager:
parent_otel_span: Optional[Span],
proxy_logging_obj: ProxyLogging,
route: str,
+ org_alias: Optional[str] = None,
) -> Tuple[
Optional[LiteLLM_UserTable],
Optional[LiteLLM_OrganizationTable],
- Optional[LiteLLM_EndUserTable],
+ Optional[LiteLLM_EndUserTable],
Optional[LiteLLM_TeamMembership],
]:
- """Get user, org, and end user objects"""
+ """Get user, org, and end user objects. Also resolves org aliases to IDs if configured."""
+
+ # Get org object - first try by ID, then by alias
org_object: Optional[LiteLLM_OrganizationTable] = None
if org_id:
org_object = (
@@ -962,6 +1047,21 @@ class JWTAuthManager:
if org_id
else None
)
+ elif org_alias:
+ verbose_proxy_logger.info(
+ f"JWT Auth: Resolving org by alias: '{org_alias}'"
+ )
+ org_object = await get_org_object_by_alias(
+ org_alias=org_alias,
+ prisma_client=prisma_client,
+ user_api_key_cache=user_api_key_cache,
+ parent_otel_span=parent_otel_span,
+ proxy_logging_obj=proxy_logging_obj,
+ )
+ if org_object:
+ verbose_proxy_logger.info(
+ f"JWT Auth: Resolved org_alias='{org_alias}' to org_id='{org_object.organization_id}'"
+ )
user_object: Optional[LiteLLM_UserTable] = None
if user_id:
@@ -1304,6 +1404,8 @@ class JWTAuthManager:
parent_otel_span=parent_otel_span,
proxy_logging_obj=proxy_logging_obj,
)
+ # Extract alias fields for resolution (if configured)
+ org_alias = jwt_handler.get_org_alias(token=jwt_valid_token, default_value=None)
# Get other objects
user_object, org_object, end_user_object, team_membership_object = (
@@ -1320,9 +1422,13 @@ class JWTAuthManager:
parent_otel_span=parent_otel_span,
proxy_logging_obj=proxy_logging_obj,
route=route,
+ org_alias=org_alias,
)
)
+ # Derive org_id from org_object if resolved by alias
+ resolved_org_id = org_object.organization_id if org_object else org_id
+
await JWTAuthManager.sync_user_role_and_teams(
jwt_handler=jwt_handler,
jwt_valid_token=jwt_valid_token,
@@ -1345,10 +1451,9 @@ class JWTAuthManager:
)
# check if user is proxy admin
- if user_object and user_object.user_role == LitellmUserRoles.PROXY_ADMIN:
- is_proxy_admin = True
- else:
- is_proxy_admin = False
+ is_proxy_admin = bool(
+ user_object and user_object.user_role == LitellmUserRoles.PROXY_ADMIN
+ )
return JWTAuthBuilderResult(
is_proxy_admin=is_proxy_admin,
@@ -1356,7 +1461,7 @@ class JWTAuthManager:
team_object=team_object,
user_id=user_id,
user_object=user_object,
- org_id=org_id,
+ org_id=resolved_org_id, # Use resolved org_id (from alias lookup if applicable)
org_object=org_object,
end_user_id=end_user_id,
end_user_object=end_user_object,
diff --git a/litellm/proxy/auth/user_api_key_auth.py b/litellm/proxy/auth/user_api_key_auth.py
index 495d4db304c..9b53d9a3a80 100644
--- a/litellm/proxy/auth/user_api_key_auth.py
+++ b/litellm/proxy/auth/user_api_key_auth.py
@@ -551,6 +551,9 @@ async def _user_api_key_auth_builder( # noqa: PLR0915
valid_token = UserAPIKeyAuth(
api_key=None,
team_id=team_id,
+ team_alias=(
+ team_object.team_alias if team_object is not None else None
+ ),
team_tpm_limit=(
team_object.tpm_limit if team_object is not None else None
),
diff --git a/tests/test_litellm/litellm_core_utils/test_dot_notation_indexing.py b/tests/test_litellm/litellm_core_utils/test_dot_notation_indexing.py
new file mode 100644
index 00000000000..6940a5ea7a5
--- /dev/null
+++ b/tests/test_litellm/litellm_core_utils/test_dot_notation_indexing.py
@@ -0,0 +1,138 @@
+"""
+Tests for litellm.litellm_core_utils.dot_notation_indexing module.
+"""
+
+import pytest
+
+from litellm.litellm_core_utils.dot_notation_indexing import (
+ get_nested_value,
+ delete_nested_value,
+)
+
+
+class TestGetNestedValue:
+ """Tests for get_nested_value function."""
+
+ def test_simple_key(self):
+ """Test accessing a simple top-level key."""
+ data = {"name": "test"}
+ assert get_nested_value(data, "name") == "test"
+
+ def test_nested_key(self):
+ """Test accessing nested keys with dot notation."""
+ data = {"a": {"b": {"c": "value"}}}
+ assert get_nested_value(data, "a.b.c") == "value"
+
+ def test_missing_key_returns_default(self):
+ """Test that missing keys return the default value."""
+ data = {"a": {"b": "value"}}
+ assert get_nested_value(data, "a.b", "default") == "value"
+ assert get_nested_value(data, "a.c", "default") == "default"
+ assert get_nested_value(data, "x.y.z") is None
+
+ def test_empty_key_path(self):
+ """Test that empty key path returns default."""
+ data = {"a": "value"}
+ assert get_nested_value(data, "") is None
+ assert get_nested_value(data, "", "default") == "default"
+
+ def test_metadata_prefix_removal(self):
+ """Test that metadata. prefix is properly removed."""
+ data = {"user": {"email": "[email protected]"}}
+ assert get_nested_value(data, "metadata.user.email") == "[email protected]"
+
+ def test_escaped_dot_in_key(self):
+ """Test accessing keys that contain dots using escape sequence."""
+ data = {"kubernetes.io": {"namespace": "default"}}
+ assert get_nested_value(data, "kubernetes\\.io.namespace") == "default"
+
+ def test_escaped_dot_nested(self):
+ """Test multiple levels with escaped dots."""
+ data = {
+ "kubernetes.io": {
+ "pod.info": {
+ "name": "my-pod"
+ }
+ }
+ }
+ assert get_nested_value(data, "kubernetes\\.io.pod\\.info.name") == "my-pod"
+
+ def test_kubernetes_jwt_example(self):
+ """Test with a realistic Kubernetes JWT structure."""
+ jwt_token = {
+ "aud": ["https://kubernetes.default.svc"],
+ "exp": "1234567890",
+ "iat": "123456789",
+ "iss": "https://oidc.eks.region.amazonaws.com/id/randomstring",
+ "jti": "randomstring",
+ "kubernetes.io": {
+ "namespace": "namespace",
+ "node": {
+ "name": "node-name",
+ "uid": "node-uid"
+ },
+ "pod": {
+ "name": "pod-name",
+ "uid": "pod-uid"
+ },
+ "serviceaccount": {
+ "name": "serviceaccount-name",
+ "uid": "serviceaccount-uid"
+ },
+ "warnafter": 1234567880
+ },
+ "nbf": 123456789,
+ "sub": "system:serviceaccount:namespace:serviceaccount-name"
+ }
+
+ # Test accessing kubernetes.io.namespace
+ assert get_nested_value(jwt_token, "kubernetes\\.io.namespace") == "namespace"
+
+ # Test accessing nested values within kubernetes.io
+ assert get_nested_value(jwt_token, "kubernetes\\.io.pod.name") == "pod-name"
+ assert get_nested_value(jwt_token, "kubernetes\\.io.serviceaccount.name") == "serviceaccount-name"
+
+ # Test accessing regular keys still works
+ assert get_nested_value(jwt_token, "sub") == "system:serviceaccount:namespace:serviceaccount-name"
+
+ def test_mixed_escaped_and_regular_dots(self):
+ """Test path with both escaped dots (in keys) and regular dots (separators)."""
+ data = {
+ "config.v1": {
+ "settings": {
+ "feature.enabled": True
+ }
+ }
+ }
+ assert get_nested_value(data, "config\\.v1.settings.feature\\.enabled") is True
+
+
+class TestDeleteNestedValue:
+ """Tests for delete_nested_value function."""
+
+ def test_delete_simple_key(self):
+ """Test deleting a simple top-level key."""
+ data = {"a": 1, "b": 2}
+ result = delete_nested_value(data, "a")
+ assert result == {"b": 2}
+ # Original should be unchanged
+ assert data == {"a": 1, "b": 2}
+
+ def test_delete_nested_key(self):
+ """Test deleting a nested key."""
+ data = {"a": {"b": {"c": 1, "d": 2}}}
+ result = delete_nested_value(data, "a.b.c")
+ assert result == {"a": {"b": {"d": 2}}}
+
+ def test_delete_array_wildcard(self):
+ """Test deleting a field from all array elements."""
+ data = {"tools": [{"name": "t1", "secret": "s1"}, {"name": "t2", "secret": "s2"}]}
+ result = delete_nested_value(data, "tools[*].secret")
+ assert result == {"tools": [{"name": "t1"}, {"name": "t2"}]}
+
+ def test_delete_array_index(self):
+ """Test deleting a field from a specific array element."""
+ data = {"items": [{"a": 1, "b": 2}, {"a": 3, "b": 4}]}
+ result = delete_nested_value(data, "items[0].b")
+ assert result == {"items": [{"a": 1}, {"a": 3, "b": 4}]}
+
diff --git a/tests/test_litellm/proxy/auth/test_handle_jwt.py b/tests/test_litellm/proxy/auth/test_handle_jwt.py
index 8ecbaced21e..b56d13bb932 100644
--- a/tests/test_litellm/proxy/auth/test_handle_jwt.py
+++ b/tests/test_litellm/proxy/auth/test_handle_jwt.py
@@ -1146,4 +1146,343 @@ async def test_auth_builder_uses_team_from_header_e2e():
)
assert result["team_id"] == "team-2"
- assert result["team_object"] == team_object
\ No newline at end of file
+ assert result["team_object"] == team_object
+
+
+async def test_get_team_alias_with_nested_fields():
+ """
+ Test get_team_alias() method with nested JWT fields
+ """
+ from litellm.proxy._types import LiteLLM_JWTAuth
+ from litellm.proxy.auth.handle_jwt import JWTHandler
+
+ jwt_handler = JWTHandler()
+
+ # Test token with nested team name
+ nested_token = {
+ "organization": {
+ "team": {
+ "name": "engineering-team"
+ }
+ },
+ "team_name": "flat-team"
+ }
+
+ # Test nested access
+ jwt_handler.litellm_jwtauth = LiteLLM_JWTAuth(team_alias_jwt_field="organization.team.name")
+ assert jwt_handler.get_team_alias(nested_token, None) == "engineering-team"
+
+ # Test flat access (backward compatibility)
+ jwt_handler.litellm_jwtauth = LiteLLM_JWTAuth(team_alias_jwt_field="team_name")
+ assert jwt_handler.get_team_alias(nested_token, None) == "flat-team"
+
+ # Test missing field returns default
+ jwt_handler.litellm_jwtauth = LiteLLM_JWTAuth(team_alias_jwt_field="nonexistent.field")
+ assert jwt_handler.get_team_alias(nested_token, "default-team") == "default-team"
+
+ # Test with team_alias_jwt_field not configured
+ jwt_handler.litellm_jwtauth = LiteLLM_JWTAuth() # team_alias_jwt_field is None
+ assert jwt_handler.get_team_alias(nested_token, "default") is None
+
+
+async def test_is_required_team_id_with_team_alias_field():
+ """
+ Test that is_required_team_id() returns True when team_alias_jwt_field is set
+ """
+ from litellm.proxy._types import LiteLLM_JWTAuth
+ from litellm.proxy.auth.handle_jwt import JWTHandler
+
+ jwt_handler = JWTHandler()
+
+ # Neither field set - should return False
+ jwt_handler.litellm_jwtauth = LiteLLM_JWTAuth()
+ assert jwt_handler.is_required_team_id() is False
+
+ # Only team_id_jwt_field set - should return True
+ jwt_handler.litellm_jwtauth = LiteLLM_JWTAuth(team_id_jwt_field="team_id")
+ assert jwt_handler.is_required_team_id() is True
+
+ # Only team_alias_jwt_field set - should return True
+ jwt_handler.litellm_jwtauth = LiteLLM_JWTAuth(team_alias_jwt_field="team_name")
+ assert jwt_handler.is_required_team_id() is True
+
+ # Both fields set - should return True
+ jwt_handler.litellm_jwtauth = LiteLLM_JWTAuth(
+ team_id_jwt_field="team_id",
+ team_alias_jwt_field="team_name"
+ )
+ assert jwt_handler.is_required_team_id() is True
+
+
+async def test_find_and_validate_specific_team_id_with_team_alias():
+ """
+ Test that find_and_validate_specific_team_id resolves team by name when team_id is not found
+ """
+ from unittest.mock import MagicMock
+
+ from litellm.caching import DualCache
+ from litellm.proxy._types import LiteLLM_JWTAuth, LiteLLM_TeamTable
+ from litellm.proxy.auth.handle_jwt import JWTAuthManager, JWTHandler
+ from litellm.proxy.utils import ProxyLogging
+
+ jwt_handler = JWTHandler()
+ user_api_key_cache = DualCache()
+ proxy_logging_obj = ProxyLogging(user_api_key_cache=user_api_key_cache)
+
+ jwt_handler.update_environment(
+ prisma_client=None,
+ user_api_key_cache=user_api_key_cache,
+ litellm_jwtauth=LiteLLM_JWTAuth(
+ team_alias_jwt_field="team_alias"
+ ),
+ )
+
+ # Token with team name (no team_id)
+ jwt_token = {
+ "sub": "user-1",
+ "team_alias": "my-team"
+ }
+
+ # Mock team object returned by get_team_object_by_alias
+ team_object = LiteLLM_TeamTable(team_id="resolved-team-id", team_alias="my-team")
+
+ with patch(
+ "litellm.proxy.auth.handle_jwt.get_team_object_by_alias",
+ new_callable=AsyncMock
+ ) as mock_get_by_alias:
+ mock_get_by_alias.return_value = team_object
+
+ team_id, result_team = await JWTAuthManager.find_and_validate_specific_team_id(
+ jwt_handler=jwt_handler,
+ jwt_valid_token=jwt_token,
+ prisma_client=None,
+ user_api_key_cache=user_api_key_cache,
+ parent_otel_span=None,
+ proxy_logging_obj=proxy_logging_obj,
+ )
+
+ # Should have resolved team_id from team name
+ assert team_id == "resolved-team-id"
+ assert result_team == team_object
+ mock_get_by_alias.assert_called_once_with(
+ team_alias="my-team",
+ prisma_client=None,
+ user_api_key_cache=user_api_key_cache,
+ parent_otel_span=None,
+ proxy_logging_obj=proxy_logging_obj,
+ )
+
+
+async def test_find_and_validate_team_id_takes_precedence_over_name():
+ """
+ Test that team_id_jwt_field takes precedence over team_alias_jwt_field
+ """
+ from unittest.mock import MagicMock
+
+ from litellm.caching import DualCache
+ from litellm.proxy._types import LiteLLM_JWTAuth, LiteLLM_TeamTable
+ from litellm.proxy.auth.handle_jwt import JWTAuthManager, JWTHandler
+ from litellm.proxy.utils import ProxyLogging
+
+ jwt_handler = JWTHandler()
+ user_api_key_cache = DualCache()
+ proxy_logging_obj = ProxyLogging(user_api_key_cache=user_api_key_cache)
+
+ jwt_handler.update_environment(
+ prisma_client=None,
+ user_api_key_cache=user_api_key_cache,
+ litellm_jwtauth=LiteLLM_JWTAuth(
+ team_id_jwt_field="team_id",
+ team_alias_jwt_field="team_alias"
+ ),
+ )
+
+ # Token with both team_id and team name
+ jwt_token = {
+ "sub": "user-1",
+ "team_id": "direct-team-id",
+ "team_alias": "my-team"
+ }
+
+ # Mock team object returned by get_team_object (by ID)
+ team_object = LiteLLM_TeamTable(team_id="direct-team-id")
+
+ with patch(
+ "litellm.proxy.auth.handle_jwt.get_team_object",
+ new_callable=AsyncMock
+ ) as mock_get_by_id, patch(
+ "litellm.proxy.auth.handle_jwt.get_team_object_by_alias",
+ new_callable=AsyncMock
+ ) as mock_get_by_alias:
+ mock_get_by_id.return_value = team_object
+
+ team_id, result_team = await JWTAuthManager.find_and_validate_specific_team_id(
+ jwt_handler=jwt_handler,
+ jwt_valid_token=jwt_token,
+ prisma_client=None,
+ user_api_key_cache=user_api_key_cache,
+ parent_otel_span=None,
+ proxy_logging_obj=proxy_logging_obj,
+ )
+
+ # Should use team_id directly, not resolve by name
+ assert team_id == "direct-team-id"
+ assert result_team == team_object
+ mock_get_by_id.assert_called_once()
+ mock_get_by_alias.assert_not_called()
+
+
+async def test_find_and_validate_raises_when_required_team_not_found():
+ """
+ Test that an exception is raised when team is required but neither team_id nor team_name is found
+ """
+ from litellm.caching import DualCache
+ from litellm.proxy._types import LiteLLM_JWTAuth
+ from litellm.proxy.auth.handle_jwt import JWTAuthManager, JWTHandler
+ from litellm.proxy.utils import ProxyLogging
+
+ jwt_handler = JWTHandler()
+ user_api_key_cache = DualCache()
+ proxy_logging_obj = ProxyLogging(user_api_key_cache=user_api_key_cache)
+
+ jwt_handler.update_environment(
+ prisma_client=None,
+ user_api_key_cache=user_api_key_cache,
+ litellm_jwtauth=LiteLLM_JWTAuth(
+ team_alias_jwt_field="team_alias" # Required, but not in token
+ ),
+ )
+
+ # Token without team info
+ jwt_token = {
+ "sub": "user-1"
+ }
+
+ with pytest.raises(Exception) as exc_info:
+ await JWTAuthManager.find_and_validate_specific_team_id(
+ jwt_handler=jwt_handler,
+ jwt_valid_token=jwt_token,
+ prisma_client=None,
+ user_api_key_cache=user_api_key_cache,
+ parent_otel_span=None,
+ proxy_logging_obj=proxy_logging_obj,
+ )
+
+ assert "No team found in token" in str(exc_info.value)
+ assert "team_alias field 'team_alias'" in str(exc_info.value)
+
+
+async def test_get_org_alias_with_nested_fields():
+ """
+ Test get_org_alias() method with nested JWT fields
+ """
+ from litellm.proxy._types import LiteLLM_JWTAuth
+ from litellm.proxy.auth.handle_jwt import JWTHandler
+
+ jwt_handler = JWTHandler()
+
+ # Test token with nested org name
+ nested_token = {
+ "company": {
+ "organization": {
+ "name": "acme-corp"
+ }
+ },
+ "org_name": "flat-org"
+ }
+
+ # Test nested access
+ jwt_handler.litellm_jwtauth = LiteLLM_JWTAuth(org_alias_jwt_field="company.organization.name")
+ assert jwt_handler.get_org_alias(nested_token, None) == "acme-corp"
+
+ # Test flat access
+ jwt_handler.litellm_jwtauth = LiteLLM_JWTAuth(org_alias_jwt_field="org_name")
+ assert jwt_handler.get_org_alias(nested_token, None) == "flat-org"
+
+ # Test missing field returns default
+ jwt_handler.litellm_jwtauth = LiteLLM_JWTAuth(org_alias_jwt_field="nonexistent.field")
+ assert jwt_handler.get_org_alias(nested_token, "default-org") == "default-org"
+
+ # Test with org_alias_jwt_field not configured
+ jwt_handler.litellm_jwtauth = LiteLLM_JWTAuth()
+ assert jwt_handler.get_org_alias(nested_token, "default") is None
+
+
+async def test_get_objects_resolves_org_by_name():
+ """
+ Test that get_objects resolves organization by name when org_id is not provided
+ """
+ from litellm.caching import DualCache
+ from litellm.proxy._types import LiteLLM_JWTAuth, LiteLLM_OrganizationTable
+ from litellm.proxy.auth.handle_jwt import JWTAuthManager, JWTHandler
+ from litellm.proxy.utils import ProxyLogging
+
+ jwt_handler = JWTHandler()
+ user_api_key_cache = DualCache()
+ proxy_logging_obj = ProxyLogging(user_api_key_cache=user_api_key_cache)
+
+ jwt_handler.update_environment(
+ prisma_client=None,
+ user_api_key_cache=user_api_key_cache,
+ litellm_jwtauth=LiteLLM_JWTAuth(
+ org_alias_jwt_field="org_alias"
+ ),
+ )
+
+ # Mock org object returned by get_org_object_by_alias
+ org_object = LiteLLM_OrganizationTable(
+ organization_id="resolved-org-id",
+ organization_alias="my-org",
+ budget_id="budget-1",
+ created_by="admin",
+ updated_by="admin",
+ models=[]
+ )
+
+ with patch(
+ "litellm.proxy.auth.handle_jwt.get_org_object_by_alias",
+ new_callable=AsyncMock
+ ) as mock_get_by_alias:
+ mock_get_by_alias.return_value = org_object
+
+ (
+ result_user_obj,
+ result_org_obj,
+ result_end_user_obj,
+ result_team_membership,
+ ) = await JWTAuthManager.get_objects(
+ user_id=None,
+ user_email=None,
+ org_id=None, # No org_id provided
+ end_user_id=None,
+ team_id=None,
+ valid_user_email=None,
+ jwt_handler=jwt_handler,
+ prisma_client=None,
+ user_api_key_cache=user_api_key_cache,
+ parent_otel_span=None,
+ proxy_logging_obj=proxy_logging_obj,
+ route="/chat/completions",
+ org_alias="my-org",
+ )
+
+ # Should resolve org by alias - org_id can be derived from org_object.organization_id
+ assert result_org_obj == org_object
+ assert result_org_obj.organization_id == "resolved-org-id"
+ mock_get_by_alias.assert_called_once_with(
+ org_alias="my-org",
+ prisma_client=None,
+ user_api_key_cache=user_api_key_cache,
+ parent_otel_span=None,
+ proxy_logging_obj=proxy_logging_obj,
+ )
+
+
+