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]

fix(keys): support explicit project detachment

Yuneng Jiangb571193c5dcf
diff --git a/litellm/proxy/_lazy_openapi_snapshot.json b/litellm/proxy/_lazy_openapi_snapshot.json
index cb7a18cd107..fe0bda5ddb9 100644
--- a/litellm/proxy/_lazy_openapi_snapshot.json
+++ b/litellm/proxy/_lazy_openapi_snapshot.json
@@ -18914,7 +18914,7 @@
}
}
},
- "description": "\n Unified rate-limit error.\n\n Every rate-limit condition surfaced by litellm \u2014 whether it originated from\n an upstream LLM provider, a vendor batch endpoint, or one of litellm's own\n proxy-side limiters (parallel-requests, dynamic-rate, batch-rate, budget,\n max-iterations, etc.) \u2014 is raised as an instance of this class.\n\n The :attr:`category` attribute lets callers distinguish the source. See\n :class:`RateLimitErrorCategory` for the available values.\n "
+ "description": "\nUnified rate-limit error.\n\nEvery rate-limit condition surfaced by litellm \u2014 whether it originated from\nan upstream LLM provider, a vendor batch endpoint, or one of litellm's own\nproxy-side limiters (parallel-requests, dynamic-rate, batch-rate, budget,\nmax-iterations, etc.) \u2014 is raised as an instance of this class.\n\nThe :attr:`category` attribute lets callers distinguish the source. See\n:class:`RateLimitErrorCategory` for the available values.\n"
},
"500": {
"content": {
diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.py
index 3d22923c0a8..273a14368cf 100644
--- a/litellm/proxy/_types.py
+++ b/litellm/proxy/_types.py
@@ -1302,6 +1302,11 @@ class UpdateKeyRequest(KeyRequestBase):
rotation_interval: str | None = None
organization_id: str | None = None
+ project_id: str | None = Field(
+ default=None,
+ description="Omit to retain the project, or send null to detach. Assigning a different project is not supported.",
+ )
+
@model_validator(mode="before")
@classmethod
def drop_blank_team_id(cls, values: object) -> object:
diff --git a/litellm/proxy/hooks/key_management_event_hooks.py b/litellm/proxy/hooks/key_management_event_hooks.py
index cdaa6d5a81c..8c86f354295 100644
--- a/litellm/proxy/hooks/key_management_event_hooks.py
+++ b/litellm/proxy/hooks/key_management_event_hooks.py
@@ -108,7 +108,10 @@ class KeyManagementEventHooks:
from litellm.proxy.proxy_server import litellm_proxy_admin_name
if is_audit_logging_enabled():
- _updated_values: Final = json.dumps(data.json(exclude_none=True), default=str)
+ updated_fields: Final = data.model_dump(exclude_none=True)
+ if "project_id" in data.model_fields_set:
+ updated_fields["project_id"] = data.project_id
+ _updated_values: Final = json.dumps(updated_fields, default=str)
_before_value = existing_key_row.json(exclude_none=True)
_before_value = json.dumps(_before_value, default=str)
diff --git a/litellm/proxy/management_endpoints/key_management_endpoints.py b/litellm/proxy/management_endpoints/key_management_endpoints.py
index db4467dda5b..1fe174763c4 100644
--- a/litellm/proxy/management_endpoints/key_management_endpoints.py
+++ b/litellm/proxy/management_endpoints/key_management_endpoints.py
@@ -2718,6 +2718,12 @@ async def _validate_update_key_data(
user_api_key_dict=user_api_key_dict,
)
+ if data.project_id is not None and data.project_id != existing_key_row.project_id:
+ raise HTTPException(
+ status_code=400, detail="Project reassignment is not supported. Use null to detach the key."
+ )
+ is_project_change: Final = "project_id" in data.model_fields_set and data.project_id != existing_key_row.project_id
+
common_key_access_checks(
user_api_key_dict=user_api_key_dict,
data=data,
@@ -2810,7 +2816,9 @@ async def _validate_update_key_data(
# non-budget change means the caller was authorized — skip the redundant
# _check_key_admin_access that would otherwise require team/org admin status.
_key_is_team_key: Final = getattr(existing_key_row, "team_id", None) is not None
- can_skip_admin_check: Final = (caller_is_creator or _key_is_team_key) and not _is_budget_change
+ can_skip_admin_check: Final = (caller_is_creator or _key_is_team_key) and not (
+ _is_budget_change or is_project_change
+ )
if (not _is_proxy_admin) and not can_skip_admin_check:
hashed_key: Final = existing_key_row.token
await _check_key_admin_access(
@@ -2853,7 +2861,9 @@ async def _validate_update_key_data(
)
# Validate key against project limits if project_id is being set
- _project_id_to_check: Final = getattr(data, "project_id", None) or getattr(existing_key_row, "project_id", None)
+ _project_id_to_check: Final = (
+ data.project_id if "project_id" in data.model_fields_set else existing_key_row.project_id
+ )
if _project_id_to_check is not None and (data.models is not None or data.max_budget is not None):
await _check_project_key_limits(
project_id=_project_id_to_check,
@@ -2962,6 +2972,7 @@ async def update_key_fn(
- user_id: Optional[str] - User ID associated with key
- team_id: Optional[str] - Team ID associated with key
- agent_id: Optional[str] - The agent id associated with the key.
+ - project_id: Optional[str] - Omit to retain the project, or send null to detach. A different project ID is rejected.
- organization_id: Optional[str] - The organization id of the key.
- budget_id: Optional[str] - The budget id associated with the key. Created by calling `/budget/new`.
- models: Optional[list] - Model_name's a user is allowed to call
diff --git a/tests/e2e/management/test_key_management_e2e.py b/tests/e2e/management/test_key_management_e2e.py
index 8b7d5f0eb6f..585fcd676b2 100644
--- a/tests/e2e/management/test_key_management_e2e.py
+++ b/tests/e2e/management/test_key_management_e2e.py
@@ -13,7 +13,7 @@ from __future__ import annotations
import time
from collections.abc import Callable
-from typing import Literal
+from typing import Final, Literal
import pytest
@@ -21,7 +21,7 @@ from e2e_config import unique_marker
from e2e_http import NoBody, StreamingResponse, unwrap
from lifecycle import ResourceManager
from management_client import ManagementClient
-from models import KeyDeleteBody, KeyGenerateBody, KeyUpdateBody
+from models import CLEAR, ChatResponse, KeyDeleteBody, KeyGenerateBody, KeyInfo, KeyUpdateBody, LiteLLMParamsBody, OrgNewBody, TeamNewBody
from pydantic import BaseModel
pytestmark = pytest.mark.e2e
@@ -131,7 +131,80 @@ def _unblock(client: ManagementClient, key: str) -> None:
)
+class ProjectIdentity(BaseModel):
+ project_id: str
+
+
+class ProjectCreateBody(BaseModel):
+ team_id: str
+ project_alias: str
+ models: list[str]
+
+
+class ProjectBlockBody(ProjectIdentity):
+ blocked: bool
+
+
class TestKeyManagementRoutes:
+ @pytest.mark.covers("mgmt.key.update.persists")
+ def test_project_detachment_preserves_key_scope_and_refreshes_auth(
+ self, client: ManagementClient, resources: ResourceManager
+ ) -> None:
+ name: Final = f"e2e-detach-{unique_marker()}"
+ model_id: Final = client.proxy.create_model(
+ name, LiteLLMParamsBody(model="openai/synthetic-detachment", api_key="synthetic", mock_response="orbit")
+ )
+ resources.defer(lambda: client.proxy.delete_model(model_id))
+ org_id: Final = client.create_org(OrgNewBody(organization_alias=name, models=[name]))
+ resources.defer(lambda: client.delete_org(org_id))
+ team_id: Final = client.create_team(TeamNewBody(team_alias=name, organization_id=org_id, models=[name]))
+ resources.defer(lambda: client.delete_team(team_id))
+ project: Final = unwrap(client.proxy.transport.post(
+ "/project/new", headers=client.proxy.transport.master,
+ json=ProjectCreateBody(team_id=team_id, project_alias=name, models=[name]),
+ response_type=ProjectIdentity,
+ ))
+ resources.defer(lambda: unwrap(client.proxy.transport.post(
+ "/project/delete", headers=client.proxy.transport.master, json=project, response_type=NoBody,
+ )))
+ key: Final = _generate_key(client, resources, KeyGenerateBody(
+ key_alias=name, team_id=team_id, organization_id=org_id, project_id=project.project_id,
+ models=[name], max_budget=5, tpm_limit=12345, rpm_limit=97,
+ ))
+ initial: Final = client.chat_status(key, name, "project attached")
+ assert initial.ok, initial.body
+ _ = unwrap(client.update_key(KeyUpdateBody(key=key, key_alias=f"{name}-saved")))
+ assert client.proxy.key_info(key).project_id == project.project_id
+ _ = unwrap(client.update_key(KeyUpdateBody(key=key, project_id=project.project_id)))
+ rejected: Final = client.proxy.transport.send(
+ "/key/update", headers=client.proxy.transport.master,
+ json=KeyUpdateBody(key=key, project_id=f"{name}-different"),
+ )
+ assert rejected.status_code == 400 and "reassignment" in rejected.body
+ assert client.proxy.key_info(key).project_id == project.project_id
+ _ = unwrap(client.proxy.transport.post(
+ "/project/update", headers=client.proxy.transport.master,
+ json=ProjectBlockBody(project_id=project.project_id, blocked=True), response_type=NoBody,
+ ))
+ blocked: Final = client.chat_status(key, name, "project blocked")
+ assert not blocked.ok and "is blocked" in blocked.body
+ detached: Final = unwrap(client.proxy.transport.post(
+ "/key/update", headers=client.proxy.transport.master,
+ json=KeyUpdateBody(key=key, project_id=CLEAR), response_type=KeyInfo,
+ ))
+ assert detached.project_id is None
+ saved: Final = client.proxy.key_info(key)
+ assert (saved.project_id, saved.team_id, saved.organization_id) == (None, team_id, org_id)
+ assert (saved.models, saved.max_budget, saved.tpm_limit, saved.rpm_limit) == ([name], 5, 12345, 97)
+ allowed: Final = client.chat_status(key, name, "project detached")
+ assert allowed.ok, allowed.body
+ message: Final = ChatResponse.model_validate_json(allowed.body).choices[0].message
+ assert message is not None and message.content == "orbit"
+ _ = unwrap(client.update_key(KeyUpdateBody(key=key, project_id=CLEAR)))
+ assert client.proxy.key_info(key).project_id is None
+ denied: Final = client.chat_status(key, f"{name}-outside", "outside key scope")
+ assert denied.status_code in (401, 403), denied.body
+
@pytest.mark.covers("mgmt.key.info.persists")
def test_info_reflects_the_fields_the_key_was_created_with(
self, client: ManagementClient, resources: ResourceManager
diff --git a/tests/e2e/models.py b/tests/e2e/models.py
index f362d4cc6e5..3cab0334dea 100644
--- a/tests/e2e/models.py
+++ b/tests/e2e/models.py
@@ -76,6 +76,7 @@ class KeyGenerateBody(BaseModel):
budget_duration: str | None = None
user_id: str | None = None
team_id: str | None = None
+ project_id: str | None = None
organization_id: str | None = None
budget_id: str | None = None
key_alias: str | None = None
@@ -139,6 +140,8 @@ class KeyInfo(BaseModel):
models: list[str] = []
tpm_limit: int | None = None
rpm_limit: int | None = None
+ project_id: str | None = None
+ organization_id: str | None = None
team_id: str | None = None
blocked: bool | None = None
spend: float | None = None
@@ -1057,6 +1060,7 @@ class KeyUpdateBody(BaseModel):
clears `budget_reset_at` with it), and `metadata` replaces the stored metadata wholesale."""
key: str
+ project_id: str | Cleared | None = None
models: list[str] | None = None
key_alias: str | None = None
tpm_limit: int | None = None
diff --git a/tests/test_litellm/proxy/hooks/test_key_management_event_hooks.py b/tests/test_litellm/proxy/hooks/test_key_management_event_hooks.py
index 860fb762450..bdadf1657e9 100644
--- a/tests/test_litellm/proxy/hooks/test_key_management_event_hooks.py
+++ b/tests/test_litellm/proxy/hooks/test_key_management_event_hooks.py
@@ -5,6 +5,7 @@ Validates that email and secret manager operations are independent and non-block
"""
import asyncio
+import json
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
@@ -475,7 +476,7 @@ class TestRotateVirtualKeyInSecretManager:
class TestKeyUpdatedAuditLogObjectId:
"""Tests that /key/update audit logs never store the raw virtual key (issue #31620)."""
- async def _run_updated_hook_and_capture_audit_log(self, request_key: str):
+ async def _run_updated_hook_and_capture_audit_log(self, request_key: str, detach_project: bool = False):
import asyncio
from litellm.proxy._types import (
@@ -493,8 +494,13 @@ class TestKeyUpdatedAuditLogObjectId:
existing_key_row = LiteLLM_VerificationToken(
token=hash_token("sk-raw-test-key-31620"),
key_name="sk-...1620",
+ project_id="project-orbit",
)
+ data = UpdateKeyRequest(key=request_key, max_budget=2000.0)
+ if detach_project:
+ data.project_id = None
+
with (
patch("litellm.store_audit_logs", True),
patch(
@@ -503,7 +509,7 @@ class TestKeyUpdatedAuditLogObjectId:
),
):
await KeyManagementEventHooks.async_key_updated_hook(
- data=UpdateKeyRequest(key=request_key, max_budget=2000.0),
+ data=data,
existing_key_row=existing_key_row,
response=MagicMock(),
user_api_key_dict=UserAPIKeyAuth(api_key="sk-admin-key", user_id="admin"),
@@ -530,13 +536,20 @@ class TestKeyUpdatedAuditLogObjectId:
assert raw_key not in str(audit_row.updated_values)
assert raw_key not in str(audit_row.before_value)
+ @pytest.mark.parametrize("detach_project", [False, True])
@pytest.mark.asyncio
- async def test_update_audit_log_passes_through_hashed_key(self):
+ async def test_update_audit_log_passes_through_hashed_key(self, detach_project: bool):
"""An already-hashed token sent to /key/update is stored unchanged."""
from litellm.proxy.utils import hash_token
hashed_key = hash_token("sk-raw-test-key-31620")
- audit_row = await self._run_updated_hook_and_capture_audit_log(request_key=hashed_key)
+ audit_row = await self._run_updated_hook_and_capture_audit_log(request_key=hashed_key, detach_project=detach_project)
assert audit_row.object_id == hashed_key
+ updated_values = json.loads(audit_row.updated_values)
+ assert ("project_id" in updated_values) is detach_project
+ if detach_project:
+ assert updated_values["project_id"] == "None"
+ assert json.loads(audit_row.before_value)["project_id"] == "project-orbit"
+ assert updated_values["max_budget"] == 2000.0
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 65cc23ea67f..0d3434942c0 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
@@ -1,3 +1,4 @@
+from typing import Final
import json
from datetime import datetime, timedelta, timezone
@@ -18129,3 +18130,58 @@ def test_key_generation_check_blank_team_id_uses_personal_permissions(monkeypatc
)
is True
)
+
+
+async def test_project_detachment_preserves_omission_and_other_key_fields():
+ existing: Final = LiteLLM_VerificationToken(
+ token="project-detach-token", project_id="project-orbit", team_id="team-orbit",
+ organization_id="org-orbit", models=["model-orbit"], max_budget=5, rpm_limit=97,
+ )
+ omitted: Final = await prepare_key_update_data(
+ data=UpdateKeyRequest(key=existing.token, key_alias="renamed"), existing_key_row=existing,
+ )
+ assert "project_id" not in omitted
+ cleared: Final = await prepare_key_update_data(
+ data=UpdateKeyRequest(key=existing.token, project_id=None), existing_key_row=existing,
+ )
+ assert cleared == {"project_id": None, "metadata": {}}
+ assert existing.project_id == "project-orbit"
+
+
[email protected]("project_id", [None, "project-orbit", "project-other", ""])
+async def test_project_detachment_uses_effective_project_for_validation(project_id: str | None):
+ existing: Final = LiteLLM_VerificationToken(token="project-detach-token", project_id="project-orbit")
+ cache: Final = await _cache_with_project("project-orbit", ["model-orbit"])
+ data: Final = UpdateKeyRequest(key=existing.token, project_id=project_id, models=["model-other"])
+ if project_id is None:
+ await _validate_update_key_data(
+ data, existing, UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN),
+ None, False, MagicMock(), cache,
+ )
+ else:
+ with pytest.raises(HTTPException) as exc:
+ await _validate_update_key_data(
+ data, existing, UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN),
+ None, False, MagicMock(), cache,
+ )
+ assert exc.value.status_code == 400
+ assert ("not in project's allowed models" if project_id == "project-orbit" else "reassignment") in str(exc.value.detail)
+
+
+async def test_key_creator_cannot_detach_project_without_admin_access():
+ existing: Final = LiteLLM_VerificationToken(
+ token="project-detach-token", project_id="project-orbit", user_id="user-orbit", created_by="user-orbit",
+ )
+ database: Final = MagicMock()
+ database.db.litellm_verificationtoken.find_unique = AsyncMock(return_value=existing)
+ with pytest.raises(HTTPException) as exc:
+ await _validate_update_key_data(
+ UpdateKeyRequest(key=existing.token, project_id=None), existing,
+ UserAPIKeyAuth(user_id="user-orbit", user_role=LitellmUserRoles.INTERNAL_USER),
+ None, False, database, UserApiKeyCache(),
+ )
+ assert exc.value.status_code == 403
+ assert "Only proxy admins, team admins, or org admins" in str(exc.value.detail)
diff --git a/ui/litellm-dashboard/src/components/templates/KeyProjectField.tsx b/ui/litellm-dashboard/src/components/templates/KeyProjectField.tsx
new file mode 100644
index 00000000000..4c523b0ae01
--- /dev/null
+++ b/ui/litellm-dashboard/src/components/templates/KeyProjectField.tsx
@@ -0,0 +1,58 @@
+import type { Organization, Team } from "@/components/networking";
+import { isOrgAdminForAnyOrg, isProxyAdminRole } from "@/utils/roles";
+import { useId } from "react";
+import { useProjects } from "@/app/(dashboard)/hooks/projects/useProjects";
+import { Button } from "@/components/ui/button";
+import { Field, FieldLabel } from "@/components/ui/field";
+import { Input } from "@/components/ui/input";
+
+type KeyProjectFieldProps = {
+ projectId: string | null | undefined;
+ canDetach: boolean;
+ pending: boolean;
+ disabled: boolean;
+ onToggle: () => void;
+};
+
+export function KeyProjectField({ projectId, canDetach, pending, disabled, onToggle }: KeyProjectFieldProps) {
+ const id = useId();
+ const { data: projects } = useProjects();
+ const alias = projects?.find((project) => project.project_id === projectId)?.project_alias;
+ const display = alias ? `${alias} (${projectId})` : projectId;
+ return (
+ <Field>
+ <FieldLabel htmlFor={id}>Project</FieldLabel>
+ <Input id={id} value={display ?? ""} disabled readOnly />
+ {canDetach && (
+ <>
+ {pending && (
+ <p className="text-sm text-muted-foreground">
+ The project will be removed when you save. Team, organization, and key limits will stay the same.
+ </p>
+ )}
+ <Button type="button" variant="outline" disabled={disabled} onClick={onToggle}>
+ {pending ? "Keep project" : "Detach from project"}
+ </Button>
+ </>
+ )}
+ </Field>
+ );
+}
+
+type ProjectKeyTeam = Pick<Team, "organization_id" | "members_with_roles"> & {
+ team_member_permissions?: string[] | null;
+};
+
+export function canDetachKeyProject(
+ team: ProjectKeyTeam | undefined,
+ organizations: Organization[] | undefined,
+ userID: string | null,
+ userRole: string | null,
+): boolean {
+ if (isProxyAdminRole(userRole ?? "")) return true;
+ const member = team?.members_with_roles?.find((candidate) => candidate.user_id === userID);
+ if (member?.role === "admin") return true;
+ const canUpdateKey = member != null && team?.team_member_permissions?.includes("/key/update");
+ const keyOrganizations = organizations?.filter((org) => org.organization_id === team?.organization_id);
+ return Boolean(canUpdateKey && isOrgAdminForAnyOrg(keyOrganizations, userID));
+}
diff --git a/ui/litellm-dashboard/src/components/templates/keyEditFormValues.ts b/ui/litellm-dashboard/src/components/templates/keyEditFormValues.ts
index fec8e749143..233b58b48ab 100644
--- a/ui/litellm-dashboard/src/components/templates/keyEditFormValues.ts
+++ b/ui/litellm-dashboard/src/components/templates/keyEditFormValues.ts
@@ -49,6 +49,7 @@ export interface KeyEditFormValues {
skills?: string[];
organization_id?: string | null;
team_id?: string | null;
+ project_id?: string | null;
logging_settings?: unknown[];
metadata?: string;
duration?: string | null;
@@ -106,6 +107,7 @@ export const toKeyEditFormValues = (keyData: KeyResponse): KeyEditFormValues =>
skills: keyData.object_permission?.skills || [],
organization_id: keyData.organization_id,
team_id: keyData.team_id,
+ project_id: keyData.project_id,
logging_settings: extractLoggingSettings(keyData.metadata),
metadata: formatMetadataForDisplay(stripTagsFromMetadata(keyData.metadata)),
duration: (keyData as { duration?: string }).duration ?? "",
@@ -153,6 +155,7 @@ export const keyEditFormSchema = z.object({
skills: z.custom<string[] | undefined>(),
organization_id: z.custom<string | null | undefined>(),
team_id: z.custom<string | null | undefined>(),
+ project_id: z.string().nullable().optional(),
logging_settings: z.custom<unknown[] | undefined>(),
metadata: z.custom<string | undefined>(),
duration: z.custom<string | null | undefined>(),
diff --git a/ui/litellm-dashboard/src/components/templates/key_edit_view.integration.test.tsx b/ui/litellm-dashboard/src/components/templates/key_edit_view.integration.test.tsx
index 7c2226f0369..cbe17b67865 100644
--- a/ui/litellm-dashboard/src/components/templates/key_edit_view.integration.test.tsx
+++ b/ui/litellm-dashboard/src/components/templates/key_edit_view.integration.test.tsx
@@ -1,12 +1,13 @@
import { fireEvent, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { beforeEach, describe, expect, it, vi } from "vitest";
-import { chooseSelectOption, renderWithProviders } from "../../../tests/test-utils";
+import { chooseSelectOption, renderWithProviders, testQueryClient } from "../../../tests/test-utils";
import { KeyResponse } from "../key_team_helpers/key_list";
import { MODEL_MAX_BUDGET_PREMIUM_HINT } from "../key_team_helpers/ModelMaxBudgetEditor";
import {
getPassThroughEndpointsCall,
getPoliciesList,
+ getUiSettings,
getPromptsList,
modelAvailableCall,
vectorStoreListCall,
@@ -22,6 +23,7 @@ vi.mock("../networking", async () => {
const actual = await vi.importActual("../networking");
return {
...actual,
+ getUiSettings: vi.fn().mockResolvedValue({ values: { enable_projects_ui: false } }),
getPromptsList: vi.fn().mockResolvedValue({
prompts: [{ prompt_id: "prompt-1" }, { prompt_id: "prompt-2" }],
}),
@@ -88,7 +90,11 @@ vi.mock("../common_components/RouterSettingsAccordion", async () => {
vi.mock("@/app/(dashboard)/hooks/organizations/useOrganizations", () => ({
useOrganizations: vi.fn().mockReturnValue({
data: [
- { organization_id: "org-1", organization_alias: "Engineering" },
+ {
+ organization_id: "org-1",
+ organization_alias: "Engineering",
+ members: [{ user_id: "user-orbit", user_role: "org_admin" }],
+ },
{ organization_id: "org-2", organization_alias: "Sales" },
],
isLoading: false,
@@ -366,6 +372,8 @@ describe("KeyEditView", () => {
beforeEach(() => {
vi.clearAllMocks();
can.mockReturnValue(true);
+ vi.mocked(getUiSettings).mockResolvedValue({ values: { enable_projects_ui: false } });
+ testQueryClient.removeQueries({ queryKey: ["uiSettings"] });
});
describe("policy and prompt fields", () => {
@@ -1512,7 +1520,61 @@ describe("KeyEditView", () => {
});
});
- it("keeps project key relationships locked and omits unsupported project updates", async () => {
+ it("should save an explicit project detach while keeping parents locked until the saved key changes", async () => {
+ vi.mocked(getUiSettings).mockResolvedValue({ values: { enable_projects_ui: true } });
+ const onSubmit = vi.fn().mockResolvedValue(undefined);
+ const onCancel = vi.fn();
+ const key = { ...MOCK_KEY_DATA, organization_id: "org-1", team_id: "group-maple", project_id: "project-orbit" };
+ const team = {
+ team_id: "group-maple",
+ organization_id: "org-1",
+ members_with_roles: [] as { user_id: string; role: string }[],
+ team_member_permissions: [] as string[],
+ };
+ const renderEditor = (keyData: KeyResponse = key, role = "Admin", editorTeam = team) => (
+ <KeyEditView
+ keyData={keyData}
+ teams={[editorTeam]}
+ onCancel={onCancel}
+ onSubmit={onSubmit}
+ accessToken=""
+ userID="user-orbit"
+ userRole={role}
+ premiumUser={false}
+ />
+ );
+ const view = renderWithProviders(renderEditor());
+ await userEvent.click(await screen.findByRole("button", { name: "Detach from project" }));
+ expect(screen.getByRole("combobox", { name: "Organization" })).toBeDisabled();
+ expect(screen.getByRole("combobox", { name: "Team ID" })).toBeDisabled();
+ await userEvent.click(screen.getByRole("button", { name: "Cancel" }));
+ expect(onCancel).toHaveBeenCalledOnce();
+ expect(onSubmit).not.toHaveBeenCalled();
+ view.rerender(renderEditor({ ...key }));
+ await userEvent.click(await screen.findByRole("button", { name: "Detach from project" }));
+ await userEvent.click(screen.getByRole("button", { name: /save changes/i }));
+ const expectedDetach = { project_id: null, organization_id: "org-1", team_id: "group-maple", models: key.models };
+ await waitFor(() => expect(onSubmit).toHaveBeenCalledWith(expect.objectContaining(expectedDetach)));
+ expect(screen.getByRole("combobox", { name: "Team ID" })).toBeDisabled();
+ view.rerender(renderEditor({ ...key, project_id: null }));
+ expect(screen.getByRole("combobox", { name: "Team ID" })).toBeEnabled();
+ expect(screen.queryByRole("button", { name: "Detach from project" })).not.toBeInTheDocument();
+ view.rerender(renderEditor(key, "Internal User"));
+ expect(screen.queryByRole("button", { name: "Detach from project" })).not.toBeInTheDocument();
+ view.rerender(renderEditor(key, "Org Admin"));
+ expect(screen.queryByRole("button", { name: "Detach from project" })).not.toBeInTheDocument();
+ const memberTeam = { ...team, members_with_roles: [{ user_id: "user-orbit", role: "user" }] };
+ view.rerender(renderEditor(key, "Org Admin", memberTeam));
+ expect(screen.queryByRole("button", { name: "Detach from project" })).not.toBeInTheDocument();
+ const permittedTeam = { ...memberTeam, team_member_permissions: ["/key/update"] };
+ view.rerender(renderEditor(key, "Org Admin", permittedTeam));
+ expect(await screen.findByRole("button", { name: "Detach from project" })).toBeInTheDocument();
+ const adminTeam = { ...team, members_with_roles: [{ user_id: "user-orbit", role: "admin" }] };
+ view.rerender(renderEditor(key, "Internal User", adminTeam));
+ expect(await screen.findByRole("button", { name: "Detach from project" })).toBeInTheDocument();
+ });
+
+ it("keeps project key relationships locked and omits project updates when the project UI is disabled", async () => {
const onSubmit = vi.fn().mockResolvedValue(undefined);
renderWithProviders(
<KeyEditView
diff --git a/ui/litellm-dashboard/src/components/templates/key_edit_view.tsx b/ui/litellm-dashboard/src/components/templates/key_edit_view.tsx
index f0d63f9671d..d327db21a9e 100644
--- a/ui/litellm-dashboard/src/components/templates/key_edit_view.tsx
+++ b/ui/litellm-dashboard/src/components/templates/key_edit_view.tsx
@@ -1,6 +1,6 @@
+import { canDetachKeyProject, KeyProjectField } from "./KeyProjectField";
import GuardrailSelector from "@/components/guardrails/GuardrailSelector";
import { useOrganizations } from "@/app/(dashboard)/hooks/organizations/useOrganizations";
-import { useProjects } from "@/app/(dashboard)/hooks/projects/useProjects";
import { useUISettings } from "@/app/(dashboard)/hooks/uiSettings/useUISettings";
import PolicySelector from "@/components/policies/PolicySelector";
import { Button } from "@/components/ui/button";
@@ -119,17 +119,12 @@ export function KeyEditView({
const modelBudget = useModelMaxBudgetField(keyData.token, keyData.model_max_budget);
const routerSettingsRef = useRef<RouterSettingsAccordionRef>(null);
const keyTypeFieldId = React.useId();
- const projectFieldId = React.useId();
const { data: organizations, isLoading: isOrganizationsLoading } = useOrganizations();
- const { data: projects } = useProjects();
const { data: uiSettingsData } = useUISettings();
const enableProjectsUI = Boolean(uiSettingsData?.values?.enable_projects_ui);
const hasProject = Boolean(keyData.project_id);
- const projectDisplay = (() => {
- if (!keyData.project_id) return null;
- const project = projects?.find((p) => p.project_id === keyData.project_id);
- return project?.project_alias ? `${project.project_alias} (${keyData.project_id})` : keyData.project_id;
- })();
+ const detachProject = hasProject && form.watch("project_id") === null;
+ const canDetachProject = canDetachKeyProject(team, organizations, userID, userRole);
const allowedRoutesValue = form.watch("allowed_routes");
const selectedModels = (form.watch("models") as string[] | undefined) ?? [];
@@ -296,7 +291,12 @@ export function KeyEditView({
values.router_settings = routerSettings;
}
- await onSubmit(withNormalizedEstimates(values));
+ await onSubmit(
+ withNormalizedEstimates({
+ ...values,
+ ...(detachProject && enableProjectsUI && canDetachProject ? { project_id: null } : {}),
+ }),
+ );
} finally {
setIsKeySaving(false);
}
@@ -813,10 +813,13 @@ export function KeyEditView({
</FormField>
{enableProjectsUI && hasProject && (
- <Field>
- <FieldLabel htmlFor={projectFieldId}>Project</FieldLabel>
- <Input id={projectFieldId} value={projectDisplay ?? ""} disabled readOnly />
- </Field>
+ <KeyProjectField
+ projectId={keyData.project_id}
+ canDetach={canDetachProject}
+ pending={detachProject}
+ disabled={isKeySaving}
+ onToggle={() => form.setValue("project_id", detachProject ? keyData.project_id : null)}
+ />
)}
<Field>
diff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.ts
index 7ed8df6815d..9e844b992b2 100644
--- a/ui/litellm-dashboard/src/lib/http/schema.d.ts
+++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts
@@ -8089,6 +8089,7 @@ export interface paths {
* - user_id: Optional[str] - User ID associated with key
* - team_id: Optional[str] - Team ID associated with key
* - agent_id: Optional[str] - The agent id associated with the key.
+ * - project_id: Optional[str] - Omit to retain the project, or send null to detach. A different project ID is rejected.
* - organization_id: Optional[str] - The organization id of the key.
* - budget_id: Optional[str] - The budget id associated with the key. Created by calling `/budget/new`.
* - models: Optional[list] - Model_name's a user is allowed to call
@@ -37991,6 +37992,11 @@ export interface components {
} | null;
/** Policies */
policies?: string[] | null;
+ /**
+ * Project Id
+ * @description Omit to retain the project, or send null to detach. Assigning a different project is not supported.
+ */
+ project_id?: string | null;
/** Prompts */
prompts?: string[] | null;
/** Rotation Interval */