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]

chore(proxy): block explicit-null user_id in ownership rebind guard

user8f3056c9c901
diff --git a/litellm/proxy/management_endpoints/key_management_endpoints.py b/litellm/proxy/management_endpoints/key_management_endpoints.py
index 1e7c4fce9ef..30655746cbb 100644
--- a/litellm/proxy/management_endpoints/key_management_endpoints.py
+++ b/litellm/proxy/management_endpoints/key_management_endpoints.py
@@ -483,10 +483,17 @@ def _validate_caller_can_change_key_ownership(
return
if data is None:
return
- incoming_user_id = getattr(data, "user_id", None)
- if incoming_user_id is None:
+ # Distinguish "user_id omitted" from "user_id explicitly set to None".
+ # Both leave ``getattr(data, 'user_id', None)`` at None, but only the
+ # explicit-null variant survives ``model_dump(exclude_unset=True)`` in
+ # ``prepare_key_update_data`` and writes NULL to the token row —
+ # detaching the key from its user and bypassing the user-row
+ # role check on subsequent requests.
+ fields_set = getattr(data, "model_fields_set", None) or set()
+ if "user_id" not in fields_set:
return
- if incoming_user_id == "":
+ incoming_user_id = getattr(data, "user_id", None)
+ if incoming_user_id is None or incoming_user_id == "":
raise HTTPException(
status_code=403,
detail="Non-admin users cannot remove the user_id from a key.",
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 b40079be8a7..ae3741c5e2a 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
@@ -10647,10 +10647,18 @@ def _patch_regenerate_side_effects():
("default_user_id", 403, "not allowed to rebind the key"),
# Empty-string removal: companion guard.
("", 403, "remove the user_id"),
+ # Explicit null: same effect as empty-string removal — survives
+ # model_dump(exclude_unset=True) and writes NULL to the token row.
+ (None, 403, "remove the user_id"),
# No-op rebind (caller sends their own user_id): must succeed.
("user-1", None, None),
],
- ids=["rebind_blocked", "empty_blocked", "same_user_id_allowed"],
+ ids=[
+ "rebind_blocked",
+ "empty_blocked",
+ "explicit_null_blocked",
+ "same_user_id_allowed",
+ ],
)
async def test_regenerate_user_id_rebind_guard(
incoming_user_id, expected_status, expected_substring