From 6e18d784319c5273db15e2212a97d6f7c0d00f53 Mon Sep 17 00:00:00 2001 From: ryan-crabbe-berri Date: Tue, 4 Aug 2026 15:27:52 -0700 Subject: [PATCH 1/3] fix(proxy): apply key_alias/key_hash filters to all /key/list visibility branches The filters previously lived only in the own-keys OR branch, so a team admin's admin-team branch matched every team key and the Key Alias filter in the Virtual Keys UI appeared broken. Both filters are now global AND conditions alongside team_id/project_id/access_group_id/agent_id, narrowing every visibility branch while leaving unfiltered visibility unchanged. --- .../key_management_endpoints.py | 52 +++---- ruff-strict-budget.json | 2 +- .../test_key_management_endpoints.py | 131 ++++++++++++++---- type-discipline-budget.json | 2 +- ui/litellm-dashboard/src/lib/http/schema.d.ts | 2 +- 5 files changed, 133 insertions(+), 56 deletions(-) diff --git a/litellm/proxy/management_endpoints/key_management_endpoints.py b/litellm/proxy/management_endpoints/key_management_endpoints.py index f37bc6da23e2..318e904d9fc4 100644 --- a/litellm/proxy/management_endpoints/key_management_endpoints.py +++ b/litellm/proxy/management_endpoints/key_management_endpoints.py @@ -5703,20 +5703,10 @@ def _build_key_filter_conditions( } else: user_condition["user_id"] = user_id - if key_alias and isinstance(key_alias, str): - if use_substring_matching: - user_condition["key_alias"] = { - "contains": key_alias, - "mode": "insensitive", - } - else: - user_condition["key_alias"] = key_alias if exclude_team_id and isinstance(exclude_team_id, str): user_condition["team_id"] = {"not": exclude_team_id} if organization_id and isinstance(organization_id, str): user_condition["organization_id"] = organization_id - if key_hash and isinstance(key_hash, str): - user_condition["token"] = key_hash if user_condition: or_conditions.append(user_condition) @@ -5772,21 +5762,33 @@ def _build_key_filter_conditions( elif len(or_conditions) == 1: where.update(or_conditions[0]) - # Apply team_id, project_id and access_group_id as global AND filters so they - # narrow results across all visibility conditions (own keys, team keys, etc.) - if team_id and isinstance(team_id, str): - where = {"AND": [where, {"team_id": team_id}]} - if project_id: - where = {"AND": [where, {"project_id": project_id}]} - if access_group_id: - where = {"AND": [where, {"access_group_ids": {"hasSome": [access_group_id]}}]} - if agent_id and isinstance(agent_id, str): - where = {"AND": [where, {"agent_id": agent_id}]} - if expires_filter is not None and expires_filter in VALID_EXPIRES_FILTER_VALUES: - where = {"AND": [where, _build_expires_where_clause(expires_filter, datetime.now(timezone.utc))]} - - verbose_proxy_logger.debug("Filter conditions: %s", where) - return where + # Apply key_alias, key_hash, team_id, project_id and access_group_id as global + # AND filters so they narrow results across all visibility conditions + # (own keys, admin team keys, member service accounts, created_by keys) + global_filters: tuple[dict[str, Any], ...] = ( + *( + ( + {"key_alias": {"contains": key_alias, "mode": "insensitive"}} + if use_substring_matching + else {"key_alias": key_alias}, + ) + if key_alias and isinstance(key_alias, str) + else () + ), + *(({"token": key_hash},) if key_hash and isinstance(key_hash, str) else ()), + *(({"team_id": team_id},) if team_id and isinstance(team_id, str) else ()), + *(({"project_id": project_id},) if project_id else ()), + *(({"access_group_ids": {"hasSome": [access_group_id]}},) if access_group_id else ()), + *(({"agent_id": agent_id},) if agent_id and isinstance(agent_id, str) else ()), + *( + (_build_expires_where_clause(expires_filter, datetime.now(timezone.utc)),) + if expires_filter is not None and expires_filter in VALID_EXPIRES_FILTER_VALUES + else () + ), + ) + combined_where = {"AND": [where, *global_filters]} if global_filters else where + verbose_proxy_logger.debug("Filter conditions: %s", combined_where) + return combined_where async def _list_key_helper( diff --git a/ruff-strict-budget.json b/ruff-strict-budget.json index 96428267a451..5d41835b9dce 100644 --- a/ruff-strict-budget.json +++ b/ruff-strict-budget.json @@ -81,7 +81,7 @@ "limit": 4 }, "C901": { - "limit": 311 + "limit": 310 }, "D419": { "limit": 9 diff --git a/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py index 867ef759fb31..db6bd34e9779 100644 --- a/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py +++ b/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py @@ -141,11 +141,25 @@ async def test_list_keys_include_created_by_keys(): where_condition = mock_find_many.call_args.kwargs["where"] print(f"where_condition with include_created_by_keys=True: {where_condition}") - # Verify the structure contains AND with OR conditions - assert "AND" in where_condition - assert "OR" in where_condition["AND"][1] + def _flatten_and(node): + if set(node.keys()) == {"AND"}: + return [c for child in node["AND"] for c in _flatten_and(child)] + return [node] - or_conditions = where_condition["AND"][1]["OR"] + def _find_visibility_or(node): + return next( + c["OR"] + for c in _flatten_and(node) + if "OR" in c and any("user_id" in branch or "created_by" in branch for branch in c["OR"]) + ) + + conditions = _flatten_and(where_condition) + # key_alias/key_hash are global AND filters (LIT-3243) so they narrow + # every visibility branch, not just the own-keys branch + assert {"key_alias": test_key_alias} in conditions + assert {"token": test_key_hash} in conditions + + or_conditions = _find_visibility_or(where_condition) # Should have 2 OR conditions: user's own keys and created_by keys assert len(or_conditions) == 2 @@ -163,11 +177,12 @@ async def test_list_keys_include_created_by_keys(): assert user_condition is not None, "User condition should be present" assert created_by_condition is not None, "Created by condition should be present" - # Verify user condition has all the filters + # Verify user condition scopes visibility; key_alias/token must NOT be + # confined to this branch (that was the LIT-3243 bug) assert user_condition["user_id"] == test_user_id assert user_condition["organization_id"] == test_org_id - assert user_condition["key_alias"] == test_key_alias - assert user_condition["token"] == test_key_hash + assert "key_alias" not in user_condition + assert "token" not in user_condition # Verify created_by condition only has the created_by filter (no other filters applied) # This is the current behavior - created_by keys don't inherit other filters @@ -218,7 +233,7 @@ async def test_list_keys_include_created_by_keys(): where_condition_with_exclude = mock_find_many.call_args.kwargs["where"] print(f"where_condition with exclude_team_id: {where_condition_with_exclude}") - or_conditions_with_exclude = where_condition_with_exclude["AND"][1]["OR"] + or_conditions_with_exclude = _find_visibility_or(where_condition_with_exclude) # Find the user condition and created_by condition user_condition_with_exclude = None @@ -6444,6 +6459,75 @@ def test_build_key_filter_conditions_agent_id_narrows_visibility(): assert "agent_id" not in json.dumps(where_without) +def test_build_key_filter_conditions_key_alias_narrows_team_admin_visibility(): + """ + LIT-3243: key_alias sat only in the own-keys OR branch, so a team admin's + admin-team branch matched every team key and the filter was a no-op. It + must be a top-level AND so it narrows every visibility branch. + """ + from litellm.proxy.management_endpoints.key_management_endpoints import ( + _build_key_filter_conditions, + ) + + where = _build_key_filter_conditions( + user_id="team-admin-user", + team_id=None, + organization_id=None, + key_alias="member-key-alias", + key_hash=None, + exclude_team_id=None, + admin_team_ids=["team-a"], + member_team_ids=["team-a"], + include_created_by_keys=False, + ) + + assert where.get("AND"), f"expected top-level AND, got: {where}" + assert {"key_alias": "member-key-alias"} in where["AND"], f"key_alias not ANDed: {where}" + assert json.dumps({"team_id": {"in": ["team-a"]}}) in json.dumps(where) + + where_substring = _build_key_filter_conditions( + user_id="team-admin-user", + team_id=None, + organization_id=None, + key_alias="member-key", + key_hash=None, + exclude_team_id=None, + admin_team_ids=["team-a"], + member_team_ids=["team-a"], + include_created_by_keys=False, + use_substring_matching=True, + ) + assert {"key_alias": {"contains": "member-key", "mode": "insensitive"}} in where_substring["AND"], ( + f"substring key_alias not ANDed: {where_substring}" + ) + + +def test_build_key_filter_conditions_key_hash_narrows_team_admin_visibility(): + """ + Same class as LIT-3243: key_hash must AND across all visibility branches + instead of sitting in the own-keys branch where the admin-team branch + bypasses it. + """ + from litellm.proxy.management_endpoints.key_management_endpoints import ( + _build_key_filter_conditions, + ) + + where = _build_key_filter_conditions( + user_id="team-admin-user", + team_id=None, + organization_id=None, + key_alias=None, + key_hash="hashed-token-123", + exclude_team_id=None, + admin_team_ids=["team-a"], + member_team_ids=["team-a"], + include_created_by_keys=False, + ) + + assert where.get("AND"), f"expected top-level AND, got: {where}" + assert {"token": "hashed-token-123"} in where["AND"], f"key_hash not ANDed: {where}" + + @pytest.mark.asyncio async def test_generate_key_negative_max_budget(): """ @@ -8877,21 +8961,11 @@ async def test_build_key_filter_project_id_and_access_group_id(): access_group_id=access_group_id, ) - # After project_id: {"AND": [visibility_where, {"project_id": ...}]} - # After access_group_id: {"AND": [above, {"access_group_ids": ...}]} + # Both filters sit in the top-level AND alongside the visibility where assert "AND" in where outer_and = where["AND"] - assert len(outer_and) == 2 - - # The access_group_ids filter is the outermost AND - access_group_filter = outer_and[1] - assert access_group_filter == {"access_group_ids": {"hasSome": [access_group_id]}} - - # The project_id filter is nested one level in - inner = outer_and[0] - assert "AND" in inner - inner_and = inner["AND"] - assert {"project_id": project_id} in inner_and + assert {"project_id": project_id} in outer_and + assert {"access_group_ids": {"hasSome": [access_group_id]}} in outer_and @pytest.mark.asyncio @@ -8953,9 +9027,10 @@ async def test_build_key_filter_admin_substring_matching(): use_substring_matching=True, ) - # Single OR condition is flattened into the top-level where dict - assert where["user_id"] == {"contains": user_id, "mode": "insensitive"} - assert where["key_alias"] == {"contains": key_alias, "mode": "insensitive"} + # user_id lives in the flattened own-keys condition; key_alias is a + # global AND filter (LIT-3243) + assert where["AND"][0]["user_id"] == {"contains": user_id, "mode": "insensitive"} + assert {"key_alias": {"contains": key_alias, "mode": "insensitive"}} in where["AND"] @pytest.mark.asyncio @@ -8985,10 +9060,10 @@ async def test_build_key_filter_non_admin_exact_matching(): use_substring_matching=False, ) - # Single OR condition is flattened into the top-level where dict - # Exact match — no contains/insensitive wrapping - assert where["user_id"] == user_id - assert where["key_alias"] == key_alias + # Exact match — no contains/insensitive wrapping; key_alias is a global + # AND filter (LIT-3243) + assert where["AND"][0]["user_id"] == user_id + assert {"key_alias": key_alias} in where["AND"] @pytest.mark.asyncio diff --git a/type-discipline-budget.json b/type-discipline-budget.json index 9976be98522e..42b6a9196dab 100644 --- a/type-discipline-budget.json +++ b/type-discipline-budget.json @@ -3,7 +3,7 @@ "limit": 23350 }, "LIT002": { - "limit": 27239 + "limit": 27234 }, "LIT003": { "limit": 292 diff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.ts index 9133bfb5cf4f..fd2155701c20 100644 --- a/ui/litellm-dashboard/src/lib/http/schema.d.ts +++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts @@ -23744,7 +23744,7 @@ export interface components { * @description Default role assigned to new users created * @default internal_user_viewer */ - user_role: ("proxy_admin" | "proxy_admin_viewer" | "internal_user" | "internal_user_viewer") | null; + user_role: ("internal_user" | "internal_user_viewer" | "proxy_admin" | "proxy_admin_viewer") | null; }; /** * DefaultTeamSSOParams From eb8914805e69ee0ceef33f96f77715733d963e00 Mon Sep 17 00:00:00 2001 From: ryan-crabbe-berri Date: Tue, 4 Aug 2026 15:42:12 -0700 Subject: [PATCH 2/3] chore: drop new explanatory comments flagged by review --- .../management_endpoints/key_management_endpoints.py | 5 ++--- .../test_key_management_endpoints.py | 10 +--------- 2 files changed, 3 insertions(+), 12 deletions(-) diff --git a/litellm/proxy/management_endpoints/key_management_endpoints.py b/litellm/proxy/management_endpoints/key_management_endpoints.py index 318e904d9fc4..d627f24c31d3 100644 --- a/litellm/proxy/management_endpoints/key_management_endpoints.py +++ b/litellm/proxy/management_endpoints/key_management_endpoints.py @@ -5762,9 +5762,8 @@ def _build_key_filter_conditions( elif len(or_conditions) == 1: where.update(or_conditions[0]) - # Apply key_alias, key_hash, team_id, project_id and access_group_id as global - # AND filters so they narrow results across all visibility conditions - # (own keys, admin team keys, member service accounts, created_by keys) + # Apply team_id, project_id and access_group_id as global AND filters so they + # narrow results across all visibility conditions (own keys, team keys, etc.) global_filters: tuple[dict[str, Any], ...] = ( *( ( diff --git a/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py index db6bd34e9779..cf9aa4771127 100644 --- a/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py +++ b/tests/test_litellm/proxy/management_endpoints/test_key_management_endpoints.py @@ -154,8 +154,6 @@ def _find_visibility_or(node): ) conditions = _flatten_and(where_condition) - # key_alias/key_hash are global AND filters (LIT-3243) so they narrow - # every visibility branch, not just the own-keys branch assert {"key_alias": test_key_alias} in conditions assert {"token": test_key_hash} in conditions @@ -177,8 +175,6 @@ def _find_visibility_or(node): assert user_condition is not None, "User condition should be present" assert created_by_condition is not None, "Created by condition should be present" - # Verify user condition scopes visibility; key_alias/token must NOT be - # confined to this branch (that was the LIT-3243 bug) assert user_condition["user_id"] == test_user_id assert user_condition["organization_id"] == test_org_id assert "key_alias" not in user_condition @@ -8961,7 +8957,6 @@ async def test_build_key_filter_project_id_and_access_group_id(): access_group_id=access_group_id, ) - # Both filters sit in the top-level AND alongside the visibility where assert "AND" in where outer_and = where["AND"] assert {"project_id": project_id} in outer_and @@ -9027,8 +9022,6 @@ async def test_build_key_filter_admin_substring_matching(): use_substring_matching=True, ) - # user_id lives in the flattened own-keys condition; key_alias is a - # global AND filter (LIT-3243) assert where["AND"][0]["user_id"] == {"contains": user_id, "mode": "insensitive"} assert {"key_alias": {"contains": key_alias, "mode": "insensitive"}} in where["AND"] @@ -9060,8 +9053,7 @@ async def test_build_key_filter_non_admin_exact_matching(): use_substring_matching=False, ) - # Exact match — no contains/insensitive wrapping; key_alias is a global - # AND filter (LIT-3243) + # Exact match — no contains/insensitive wrapping assert where["AND"][0]["user_id"] == user_id assert {"key_alias": key_alias} in where["AND"] From 87c738699d9a87e2c8457a99d3c82ec80c620af0 Mon Sep 17 00:00:00 2001 From: ryan-crabbe-berri Date: Tue, 4 Aug 2026 15:55:13 -0700 Subject: [PATCH 3/3] chore: restore schema.d.ts to base enum order --- ui/litellm-dashboard/src/lib/http/schema.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.ts index fd2155701c20..9133bfb5cf4f 100644 --- a/ui/litellm-dashboard/src/lib/http/schema.d.ts +++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts @@ -23744,7 +23744,7 @@ export interface components { * @description Default role assigned to new users created * @default internal_user_viewer */ - user_role: ("internal_user" | "internal_user_viewer" | "proxy_admin" | "proxy_admin_viewer") | null; + user_role: ("proxy_admin" | "proxy_admin_viewer" | "internal_user" | "internal_user_viewer") | null; }; /** * DefaultTeamSSOParams