fix(proxy): ensure default admin user exists and report accurate FK error in user invitation (#41176)

This commit is contained in:
DYNOSuprovo 2026-09-15 20:06:37 +05:30
parent c8114ba41f
commit 77d85df869
2 changed files with 114 additions and 5 deletions

View file

@ -23,6 +23,27 @@ async def create_invitation_for_user(
detail={"error": CommonProxyErrors.db_not_connected_error.value},
)
creator_id = user_api_key_dict.user_id or litellm_proxy_admin_name
# If the invitation is being created under the default admin user (e.g. master key auth
# without prior Admin UI login), ensure the admin user row exists to prevent FK violation.
if creator_id == litellm_proxy_admin_name:
try:
from litellm.repositories.user_repository import UserRepository
await UserRepository(prisma_client).table.upsert(
where={"user_id": litellm_proxy_admin_name},
data={
"create": {
"user_id": litellm_proxy_admin_name,
"user_role": "proxy_admin",
},
"update": {},
},
)
except Exception: # noqa: S110, BLE001
pass
current_time: Final = litellm.utils.get_utc_datetime()
expires_at: Final = current_time + timedelta(days=7)
@ -32,18 +53,29 @@ async def create_invitation_for_user(
"user_id": data.user_id,
"created_at": current_time,
"expires_at": expires_at,
"created_by": user_api_key_dict.user_id or litellm_proxy_admin_name,
"created_by": creator_id,
"updated_at": current_time,
"updated_by": user_api_key_dict.user_id or litellm_proxy_admin_name,
"updated_by": creator_id,
}
)
return response
except Exception as e:
if "Foreign key constraint failed on the field" in str(e):
except Exception as e: # noqa: BLE001
err_str = str(e)
if "Foreign key constraint failed on the field" in err_str:
if "created_by" in err_str or "CreatedBy" in err_str:
raise HTTPException(
status_code=400,
detail={"error": f"Creator user '{creator_id}' does not exist in 'LiteLLM_UserTable'."},
)
elif "updated_by" in err_str or "UpdatedBy" in err_str:
raise HTTPException(
status_code=400,
detail={"error": f"Updater user '{creator_id}' does not exist in 'LiteLLM_UserTable'."},
)
raise HTTPException(
status_code=400,
detail={
"error": "User id does not exist in 'LiteLLM_UserTable'. Fix this by creating user via `/user/new`."
},
)
raise HTTPException(status_code=500, detail={"error": str(e)})
raise HTTPException(status_code=500, detail={"error": err_str})

View file

@ -385,3 +385,80 @@ def test_invitation_delete_db_not_connected_400(client, auth_as, monkeypatch):
assert response.status_code == 400
err_text = str(response.json())
assert "No connected db" in err_text or "db" in err_text.lower()
@pytest.mark.asyncio
async def test_create_invitation_for_user_upserts_default_admin(monkeypatch):
"""When user_api_key_dict.user_id is None, ensures default_user_id is upserted."""
from litellm.proxy import proxy_server as ps
from litellm.proxy._types import InvitationNew, UserAPIKeyAuth
from litellm.proxy.management_helpers.user_invitation import create_invitation_for_user
mock_prisma = MagicMock()
mock_upsert = AsyncMock()
mock_prisma.db.litellm_usertable.upsert = mock_upsert
mock_create = AsyncMock(return_value=_make_invitation(created_by="default_user_id"))
mock_prisma.db.litellm_invitationlink.create = mock_create
monkeypatch.setattr(ps, "prisma_client", mock_prisma)
monkeypatch.setattr(ps, "litellm_proxy_admin_name", "default_user_id")
res = await create_invitation_for_user(
data=InvitationNew(user_id="user-target"),
user_api_key_dict=UserAPIKeyAuth(user_id=None),
)
assert res.created_by == "default_user_id"
mock_upsert.assert_awaited_once()
@pytest.mark.asyncio
async def test_create_invitation_for_user_created_by_fk_error(monkeypatch):
"""When created_by FK fails, error message clearly identifies creator user."""
from fastapi import HTTPException
from litellm.proxy import proxy_server as ps
from litellm.proxy._types import InvitationNew, UserAPIKeyAuth
from litellm.proxy.management_helpers.user_invitation import create_invitation_for_user
mock_prisma = MagicMock()
mock_prisma.db.litellm_usertable.upsert = AsyncMock()
mock_prisma.db.litellm_invitationlink.create = AsyncMock(
side_effect=Exception("Foreign key constraint failed on the field: `LiteLLM_InvitationLink_created_by_fkey`")
)
monkeypatch.setattr(ps, "prisma_client", mock_prisma)
with pytest.raises(HTTPException) as exc_info:
await create_invitation_for_user(
data=InvitationNew(user_id="user-target"),
user_api_key_dict=UserAPIKeyAuth(user_id="custom-admin-id"),
)
assert exc_info.value.status_code == 400
assert "Creator user 'custom-admin-id' does not exist" in str(exc_info.value.detail)
@pytest.mark.asyncio
async def test_create_invitation_for_user_target_user_fk_error(monkeypatch):
"""When user_id FK fails, existing helpful error message is returned."""
from fastapi import HTTPException
from litellm.proxy import proxy_server as ps
from litellm.proxy._types import InvitationNew, UserAPIKeyAuth
from litellm.proxy.management_helpers.user_invitation import create_invitation_for_user
mock_prisma = MagicMock()
mock_prisma.db.litellm_usertable.upsert = AsyncMock()
mock_prisma.db.litellm_invitationlink.create = AsyncMock(
side_effect=Exception("Foreign key constraint failed on the field: `LiteLLM_InvitationLink_user_id_fkey`")
)
monkeypatch.setattr(ps, "prisma_client", mock_prisma)
with pytest.raises(HTTPException) as exc_info:
await create_invitation_for_user(
data=InvitationNew(user_id="user-target"),
user_api_key_dict=UserAPIKeyAuth(user_id="admin-id"),
)
assert exc_info.value.status_code == 400
assert "User id does not exist in 'LiteLLM_UserTable'" in str(exc_info.value.detail)